Annotation of gforth/doc/gforth.ds, revision 1.112
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.29 crook 14: @comment .. would be useful to have a word that identified all deferred words
15: @comment should semantics stuff in intro be moved to another section
16:
1.66 anton 17: @c POSTPONE, COMPILE, [COMPILE], LITERAL should have their own section
1.28 crook 18:
1.1 anton 19: @comment %**start of header (This is for running Texinfo on a region.)
20: @setfilename gforth.info
21: @settitle Gforth Manual
1.108 anton 22: @dircategory Software development
1.1 anton 23: @direntry
24: * Gforth: (gforth). A fast interpreter for the Forth language.
25: @end direntry
1.49 anton 26: @c The Texinfo manual also recommends doing this, but for Gforth it may
27: @c not make much sense
28: @c @dircategory Individual utilities
29: @c @direntry
30: @c * Gforth: (gforth)Invoking Gforth. gforth, gforth-fast, gforthmi
31: @c @end direntry
32:
1.1 anton 33: @comment @setchapternewpage odd
1.29 crook 34: @comment TODO this gets left in by HTML converter
1.12 anton 35: @macro progstyle {}
36: Programming style note:
1.3 anton 37: @end macro
1.48 anton 38:
39: @macro assignment {}
40: @table @i
41: @item Assignment:
42: @end macro
43: @macro endassignment {}
44: @end table
45: @end macro
46:
1.1 anton 47: @comment %**end of header (This is for running Texinfo on a region.)
48:
1.29 crook 49:
50: @comment ----------------------------------------------------------
51: @comment macros for beautifying glossary entries
52: @comment if these are used, need to strip them out for HTML converter
53: @comment else they get repeated verbatim in HTML output.
54: @comment .. not working yet.
55:
56: @macro GLOSS-START {}
57: @iftex
58: @ninerm
59: @end iftex
60: @end macro
61:
62: @macro GLOSS-END {}
63: @iftex
64: @rm
65: @end iftex
66: @end macro
67:
68: @comment ----------------------------------------------------------
69:
70:
1.10 anton 71: @include version.texi
72:
1.49 anton 73: @ifnottex
1.11 anton 74: This file documents Gforth @value{VERSION}
1.1 anton 75:
1.108 anton 76: Copyright @copyright{} 1995, 1996, 1997, 1998, 2000, 2003 Free Software Foundation, Inc.
1.1 anton 77:
78: Permission is granted to make and distribute verbatim copies of
79: this manual provided the copyright notice and this permission notice
80: are preserved on all copies.
81:
82: @ignore
83: Permission is granted to process this file through TeX and print the
84: results, provided the printed document carries a copying permission
85: notice identical to this one except for the removal of this paragraph
86: (this paragraph not being relevant to the printed manual).
87:
88: @end ignore
89: Permission is granted to copy and distribute modified versions of this
90: manual under the conditions for verbatim copying, provided also that the
91: sections entitled "Distribution" and "General Public License" are
92: included exactly as in the original, and provided that the entire
93: resulting derived work is distributed under the terms of a permission
94: notice identical to this one.
95:
96: Permission is granted to copy and distribute translations of this manual
97: into another language, under the above conditions for modified versions,
98: except that the sections entitled "Distribution" and "General Public
99: License" may be included in a translation approved by the author instead
100: of in the original English.
1.49 anton 101: @end ifnottex
1.1 anton 102:
103: @finalout
104: @titlepage
105: @sp 10
106: @center @titlefont{Gforth Manual}
107: @sp 2
1.11 anton 108: @center for version @value{VERSION}
1.1 anton 109: @sp 2
1.34 anton 110: @center Neal Crook
1.1 anton 111: @center Anton Ertl
1.6 pazsan 112: @center Bernd Paysan
1.5 anton 113: @center Jens Wilke
1.1 anton 114: @sp 3
115:
116: @comment The following two commands start the copyright page.
117: @page
118: @vskip 0pt plus 1filll
1.108 anton 119: Copyright @copyright{} 1995, 1996, 1997, 1998, 2000, 2003 Free Software Foundation, Inc.
1.1 anton 120:
121: @comment !! Published by ... or You can get a copy of this manual ...
122:
123: Permission is granted to make and distribute verbatim copies of
124: this manual provided the copyright notice and this permission notice
125: are preserved on all copies.
126:
127: Permission is granted to copy and distribute modified versions of this
128: manual under the conditions for verbatim copying, provided also that the
129: sections entitled "Distribution" and "General Public License" are
130: included exactly as in the original, and provided that the entire
131: resulting derived work is distributed under the terms of a permission
132: notice identical to this one.
133:
134: Permission is granted to copy and distribute translations of this manual
135: into another language, under the above conditions for modified versions,
136: except that the sections entitled "Distribution" and "General Public
137: License" may be included in a translation approved by the author instead
138: of in the original English.
139: @end titlepage
140:
141: @node Top, License, (dir), (dir)
1.49 anton 142: @ifnottex
1.1 anton 143: Gforth is a free implementation of ANS Forth available on many
1.11 anton 144: personal machines. This manual corresponds to version @value{VERSION}.
1.49 anton 145: @end ifnottex
1.1 anton 146:
147: @menu
1.21 crook 148: * License:: The GPL
1.26 crook 149: * Goals:: About the Gforth Project
1.29 crook 150: * Gforth Environment:: Starting (and exiting) Gforth
1.48 anton 151: * Tutorial:: Hands-on Forth Tutorial
1.21 crook 152: * Introduction:: An introduction to ANS Forth
1.1 anton 153: * Words:: Forth words available in Gforth
1.24 anton 154: * Error messages:: How to interpret them
1.1 anton 155: * Tools:: Programming tools
156: * ANS conformance:: Implementation-defined options etc.
1.65 anton 157: * Standard vs Extensions:: Should I use extensions?
1.1 anton 158: * Model:: The abstract machine of Gforth
159: * Integrating Gforth:: Forth as scripting language for applications
160: * Emacs and Gforth:: The Gforth Mode
161: * Image Files:: @code{.fi} files contain compiled code
162: * Engine:: The inner interpreter and the primitives
1.24 anton 163: * Binding to System Library::
1.13 pazsan 164: * Cross Compiler:: The Cross Compiler
1.1 anton 165: * Bugs:: How to report them
166: * Origin:: Authors and ancestors of Gforth
1.21 crook 167: * Forth-related information:: Books and places to look on the WWW
1.1 anton 168: * Word Index:: An item for each Forth word
169: * Concept Index:: A menu covering many topics
1.12 anton 170:
1.91 anton 171: @detailmenu
172: --- The Detailed Node Listing ---
1.12 anton 173:
1.29 crook 174: Gforth Environment
175:
1.32 anton 176: * Invoking Gforth:: Getting in
177: * Leaving Gforth:: Getting out
178: * Command-line editing::
1.48 anton 179: * Environment variables:: that affect how Gforth starts up
1.32 anton 180: * Gforth Files:: What gets installed and where
1.112 ! anton 181: * Gforth in pipes::
1.48 anton 182: * Startup speed:: When 35ms is not fast enough ...
183:
184: Forth Tutorial
185:
186: * Starting Gforth Tutorial::
187: * Syntax Tutorial::
188: * Crash Course Tutorial::
189: * Stack Tutorial::
190: * Arithmetics Tutorial::
191: * Stack Manipulation Tutorial::
192: * Using files for Forth code Tutorial::
193: * Comments Tutorial::
194: * Colon Definitions Tutorial::
195: * Decompilation Tutorial::
196: * Stack-Effect Comments Tutorial::
197: * Types Tutorial::
198: * Factoring Tutorial::
199: * Designing the stack effect Tutorial::
200: * Local Variables Tutorial::
201: * Conditional execution Tutorial::
202: * Flags and Comparisons Tutorial::
203: * General Loops Tutorial::
204: * Counted loops Tutorial::
205: * Recursion Tutorial::
206: * Leaving definitions or loops Tutorial::
207: * Return Stack Tutorial::
208: * Memory Tutorial::
209: * Characters and Strings Tutorial::
210: * Alignment Tutorial::
1.87 anton 211: * Files Tutorial::
1.48 anton 212: * Interpretation and Compilation Semantics and Immediacy Tutorial::
213: * Execution Tokens Tutorial::
214: * Exceptions Tutorial::
215: * Defining Words Tutorial::
216: * Arrays and Records Tutorial::
217: * POSTPONE Tutorial::
218: * Literal Tutorial::
219: * Advanced macros Tutorial::
220: * Compilation Tokens Tutorial::
221: * Wordlists and Search Order Tutorial::
1.29 crook 222:
1.24 anton 223: An Introduction to ANS Forth
224:
1.67 anton 225: * Introducing the Text Interpreter::
226: * Stacks and Postfix notation::
227: * Your first definition::
228: * How does that work?::
229: * Forth is written in Forth::
230: * Review - elements of a Forth system::
231: * Where to go next::
232: * Exercises::
1.24 anton 233:
1.12 anton 234: Forth Words
235:
236: * Notation::
1.65 anton 237: * Case insensitivity::
238: * Comments::
239: * Boolean Flags::
1.12 anton 240: * Arithmetic::
241: * Stack Manipulation::
242: * Memory::
243: * Control Structures::
244: * Defining Words::
1.65 anton 245: * Interpretation and Compilation Semantics::
1.47 crook 246: * Tokens for Words::
1.81 anton 247: * Compiling words::
1.65 anton 248: * The Text Interpreter::
1.111 anton 249: * The Input Stream::
1.65 anton 250: * Word Lists::
251: * Environmental Queries::
1.12 anton 252: * Files::
253: * Blocks::
254: * Other I/O::
1.78 anton 255: * Locals::
256: * Structures::
257: * Object-oriented Forth::
1.12 anton 258: * Programming Tools::
259: * Assembler and Code Words::
260: * Threading Words::
1.65 anton 261: * Passing Commands to the OS::
262: * Keeping track of Time::
263: * Miscellaneous Words::
1.12 anton 264:
265: Arithmetic
266:
267: * Single precision::
1.67 anton 268: * Double precision:: Double-cell integer arithmetic
1.12 anton 269: * Bitwise operations::
1.67 anton 270: * Numeric comparison::
1.32 anton 271: * Mixed precision:: Operations with single and double-cell integers
1.12 anton 272: * Floating Point::
273:
274: Stack Manipulation
275:
276: * Data stack::
277: * Floating point stack::
278: * Return stack::
279: * Locals stack::
280: * Stack pointer manipulation::
281:
282: Memory
283:
1.32 anton 284: * Memory model::
285: * Dictionary allocation::
286: * Heap Allocation::
287: * Memory Access::
288: * Address arithmetic::
289: * Memory Blocks::
1.12 anton 290:
291: Control Structures
292:
1.41 anton 293: * Selection:: IF ... ELSE ... ENDIF
294: * Simple Loops:: BEGIN ...
1.32 anton 295: * Counted Loops:: DO
1.67 anton 296: * Arbitrary control structures::
297: * Calls and returns::
1.12 anton 298: * Exception Handling::
299:
300: Defining Words
301:
1.67 anton 302: * CREATE::
1.44 crook 303: * Variables:: Variables and user variables
1.67 anton 304: * Constants::
1.44 crook 305: * Values:: Initialised variables
1.67 anton 306: * Colon Definitions::
1.44 crook 307: * Anonymous Definitions:: Definitions without names
1.71 anton 308: * Supplying names:: Passing definition names as strings
1.67 anton 309: * User-defined Defining Words::
1.44 crook 310: * Deferred words:: Allow forward references
1.67 anton 311: * Aliases::
1.47 crook 312:
1.63 anton 313: User-defined Defining Words
314:
315: * CREATE..DOES> applications::
316: * CREATE..DOES> details::
317: * Advanced does> usage example::
1.91 anton 318: * @code{Const-does>}::
1.63 anton 319:
1.47 crook 320: Interpretation and Compilation Semantics
321:
1.67 anton 322: * Combined words::
1.12 anton 323:
1.71 anton 324: Tokens for Words
325:
326: * Execution token:: represents execution/interpretation semantics
327: * Compilation token:: represents compilation semantics
328: * Name token:: represents named words
329:
1.82 anton 330: Compiling words
331:
332: * Literals:: Compiling data values
333: * Macros:: Compiling words
334:
1.21 crook 335: The Text Interpreter
336:
1.67 anton 337: * Input Sources::
338: * Number Conversion::
339: * Interpret/Compile states::
340: * Interpreter Directives::
1.21 crook 341:
1.26 crook 342: Word Lists
343:
1.75 anton 344: * Vocabularies::
1.67 anton 345: * Why use word lists?::
1.75 anton 346: * Word list example::
1.26 crook 347:
348: Files
349:
1.48 anton 350: * Forth source files::
351: * General files::
352: * Search Paths::
353:
354: Search Paths
355:
1.75 anton 356: * Source Search Paths::
1.26 crook 357: * General Search Paths::
358:
359: Other I/O
360:
1.32 anton 361: * Simple numeric output:: Predefined formats
362: * Formatted numeric output:: Formatted (pictured) output
363: * String Formats:: How Forth stores strings in memory
1.67 anton 364: * Displaying characters and strings:: Other stuff
1.32 anton 365: * Input:: Input
1.112 ! anton 366: * Pipes:: How to create your own pipes
1.26 crook 367:
368: Locals
369:
370: * Gforth locals::
371: * ANS Forth locals::
372:
373: Gforth locals
374:
375: * Where are locals visible by name?::
376: * How long do locals live?::
1.78 anton 377: * Locals programming style::
378: * Locals implementation::
1.26 crook 379:
1.12 anton 380: Structures
381:
382: * Why explicit structure support?::
383: * Structure Usage::
384: * Structure Naming Convention::
385: * Structure Implementation::
386: * Structure Glossary::
387:
388: Object-oriented Forth
389:
1.48 anton 390: * Why object-oriented programming?::
391: * Object-Oriented Terminology::
392: * Objects::
393: * OOF::
394: * Mini-OOF::
1.23 crook 395: * Comparison with other object models::
1.12 anton 396:
1.24 anton 397: The @file{objects.fs} model
1.12 anton 398:
399: * Properties of the Objects model::
400: * Basic Objects Usage::
1.41 anton 401: * The Objects base class::
1.12 anton 402: * Creating objects::
403: * Object-Oriented Programming Style::
404: * Class Binding::
405: * Method conveniences::
406: * Classes and Scoping::
1.41 anton 407: * Dividing classes::
1.12 anton 408: * Object Interfaces::
409: * Objects Implementation::
410: * Objects Glossary::
411:
1.24 anton 412: The @file{oof.fs} model
1.12 anton 413:
1.67 anton 414: * Properties of the OOF model::
415: * Basic OOF Usage::
416: * The OOF base class::
417: * Class Declaration::
418: * Class Implementation::
1.12 anton 419:
1.24 anton 420: The @file{mini-oof.fs} model
1.23 crook 421:
1.48 anton 422: * Basic Mini-OOF Usage::
423: * Mini-OOF Example::
424: * Mini-OOF Implementation::
1.23 crook 425:
1.78 anton 426: Programming Tools
427:
428: * Examining::
429: * Forgetting words::
430: * Debugging:: Simple and quick.
431: * Assertions:: Making your programs self-checking.
432: * Singlestep Debugger:: Executing your program word by word.
433:
434: Assembler and Code Words
435:
436: * Code and ;code::
437: * Common Assembler:: Assembler Syntax
438: * Common Disassembler::
439: * 386 Assembler:: Deviations and special cases
440: * Alpha Assembler:: Deviations and special cases
441: * MIPS assembler:: Deviations and special cases
442: * Other assemblers:: How to write them
443:
1.12 anton 444: Tools
445:
446: * ANS Report:: Report the words used, sorted by wordset.
447:
448: ANS conformance
449:
450: * The Core Words::
451: * The optional Block word set::
452: * The optional Double Number word set::
453: * The optional Exception word set::
454: * The optional Facility word set::
455: * The optional File-Access word set::
456: * The optional Floating-Point word set::
457: * The optional Locals word set::
458: * The optional Memory-Allocation word set::
459: * The optional Programming-Tools word set::
460: * The optional Search-Order word set::
461:
462: The Core Words
463:
464: * core-idef:: Implementation Defined Options
465: * core-ambcond:: Ambiguous Conditions
466: * core-other:: Other System Documentation
467:
468: The optional Block word set
469:
470: * block-idef:: Implementation Defined Options
471: * block-ambcond:: Ambiguous Conditions
472: * block-other:: Other System Documentation
473:
474: The optional Double Number word set
475:
476: * double-ambcond:: Ambiguous Conditions
477:
478: The optional Exception word set
479:
480: * exception-idef:: Implementation Defined Options
481:
482: The optional Facility word set
483:
484: * facility-idef:: Implementation Defined Options
485: * facility-ambcond:: Ambiguous Conditions
486:
487: The optional File-Access word set
488:
489: * file-idef:: Implementation Defined Options
490: * file-ambcond:: Ambiguous Conditions
491:
492: The optional Floating-Point word set
493:
494: * floating-idef:: Implementation Defined Options
495: * floating-ambcond:: Ambiguous Conditions
496:
497: The optional Locals word set
498:
499: * locals-idef:: Implementation Defined Options
500: * locals-ambcond:: Ambiguous Conditions
501:
502: The optional Memory-Allocation word set
503:
504: * memory-idef:: Implementation Defined Options
505:
506: The optional Programming-Tools word set
507:
508: * programming-idef:: Implementation Defined Options
509: * programming-ambcond:: Ambiguous Conditions
510:
511: The optional Search-Order word set
512:
513: * search-idef:: Implementation Defined Options
514: * search-ambcond:: Ambiguous Conditions
515:
1.109 anton 516: Emacs and Gforth
517:
518: * Installing gforth.el:: Making Emacs aware of Forth.
519: * Emacs Tags:: Viewing the source of a word in Emacs.
520: * Hilighting:: Making Forth code look prettier.
521: * Auto-Indentation:: Customizing auto-indentation.
522: * Blocks Files:: Reading and writing blocks files.
523:
1.12 anton 524: Image Files
525:
1.24 anton 526: * Image Licensing Issues:: Distribution terms for images.
527: * Image File Background:: Why have image files?
1.67 anton 528: * Non-Relocatable Image Files:: don't always work.
1.24 anton 529: * Data-Relocatable Image Files:: are better.
1.67 anton 530: * Fully Relocatable Image Files:: better yet.
1.24 anton 531: * Stack and Dictionary Sizes:: Setting the default sizes for an image.
1.32 anton 532: * Running Image Files:: @code{gforth -i @i{file}} or @i{file}.
1.24 anton 533: * Modifying the Startup Sequence:: and turnkey applications.
1.12 anton 534:
535: Fully Relocatable Image Files
536:
1.27 crook 537: * gforthmi:: The normal way
1.12 anton 538: * cross.fs:: The hard way
539:
540: Engine
541:
542: * Portability::
543: * Threading::
544: * Primitives::
545: * Performance::
546:
547: Threading
548:
549: * Scheduling::
550: * Direct or Indirect Threaded?::
1.109 anton 551: * Dynamic Superinstructions::
1.12 anton 552: * DOES>::
553:
554: Primitives
555:
556: * Automatic Generation::
557: * TOS Optimization::
558: * Produced code::
1.13 pazsan 559:
560: Cross Compiler
561:
1.67 anton 562: * Using the Cross Compiler::
563: * How the Cross Compiler Works::
1.13 pazsan 564:
1.24 anton 565: @end detailmenu
1.1 anton 566: @end menu
567:
1.26 crook 568: @node License, Goals, Top, Top
1.1 anton 569: @unnumbered GNU GENERAL PUBLIC LICENSE
570: @center Version 2, June 1991
571:
572: @display
573: Copyright @copyright{} 1989, 1991 Free Software Foundation, Inc.
1.88 anton 574: 59 Temple Place, Suite 330, Boston, MA 02111, USA
1.1 anton 575:
576: Everyone is permitted to copy and distribute verbatim copies
577: of this license document, but changing it is not allowed.
578: @end display
579:
580: @unnumberedsec Preamble
581:
582: The licenses for most software are designed to take away your
583: freedom to share and change it. By contrast, the GNU General Public
584: License is intended to guarantee your freedom to share and change free
585: software---to make sure the software is free for all its users. This
586: General Public License applies to most of the Free Software
587: Foundation's software and to any other program whose authors commit to
588: using it. (Some other Free Software Foundation software is covered by
589: the GNU Library General Public License instead.) You can apply it to
590: your programs, too.
591:
592: When we speak of free software, we are referring to freedom, not
593: price. Our General Public Licenses are designed to make sure that you
594: have the freedom to distribute copies of free software (and charge for
595: this service if you wish), that you receive source code or can get it
596: if you want it, that you can change the software or use pieces of it
597: in new free programs; and that you know you can do these things.
598:
599: To protect your rights, we need to make restrictions that forbid
600: anyone to deny you these rights or to ask you to surrender the rights.
601: These restrictions translate to certain responsibilities for you if you
602: distribute copies of the software, or if you modify it.
603:
604: For example, if you distribute copies of such a program, whether
605: gratis or for a fee, you must give the recipients all the rights that
606: you have. You must make sure that they, too, receive or can get the
607: source code. And you must show them these terms so they know their
608: rights.
609:
610: We protect your rights with two steps: (1) copyright the software, and
611: (2) offer you this license which gives you legal permission to copy,
612: distribute and/or modify the software.
613:
614: Also, for each author's protection and ours, we want to make certain
615: that everyone understands that there is no warranty for this free
616: software. If the software is modified by someone else and passed on, we
617: want its recipients to know that what they have is not the original, so
618: that any problems introduced by others will not reflect on the original
619: authors' reputations.
620:
621: Finally, any free program is threatened constantly by software
622: patents. We wish to avoid the danger that redistributors of a free
623: program will individually obtain patent licenses, in effect making the
624: program proprietary. To prevent this, we have made it clear that any
625: patent must be licensed for everyone's free use or not licensed at all.
626:
627: The precise terms and conditions for copying, distribution and
628: modification follow.
629:
630: @iftex
631: @unnumberedsec TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
632: @end iftex
1.49 anton 633: @ifnottex
1.1 anton 634: @center TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
1.49 anton 635: @end ifnottex
1.1 anton 636:
637: @enumerate 0
638: @item
639: This License applies to any program or other work which contains
640: a notice placed by the copyright holder saying it may be distributed
641: under the terms of this General Public License. The ``Program'', below,
642: refers to any such program or work, and a ``work based on the Program''
643: means either the Program or any derivative work under copyright law:
644: that is to say, a work containing the Program or a portion of it,
645: either verbatim or with modifications and/or translated into another
646: language. (Hereinafter, translation is included without limitation in
647: the term ``modification''.) Each licensee is addressed as ``you''.
648:
649: Activities other than copying, distribution and modification are not
650: covered by this License; they are outside its scope. The act of
651: running the Program is not restricted, and the output from the Program
652: is covered only if its contents constitute a work based on the
653: Program (independent of having been made by running the Program).
654: Whether that is true depends on what the Program does.
655:
656: @item
657: You may copy and distribute verbatim copies of the Program's
658: source code as you receive it, in any medium, provided that you
659: conspicuously and appropriately publish on each copy an appropriate
660: copyright notice and disclaimer of warranty; keep intact all the
661: notices that refer to this License and to the absence of any warranty;
662: and give any other recipients of the Program a copy of this License
663: along with the Program.
664:
665: You may charge a fee for the physical act of transferring a copy, and
666: you may at your option offer warranty protection in exchange for a fee.
667:
668: @item
669: You may modify your copy or copies of the Program or any portion
670: of it, thus forming a work based on the Program, and copy and
671: distribute such modifications or work under the terms of Section 1
672: above, provided that you also meet all of these conditions:
673:
674: @enumerate a
675: @item
676: You must cause the modified files to carry prominent notices
677: stating that you changed the files and the date of any change.
678:
679: @item
680: You must cause any work that you distribute or publish, that in
681: whole or in part contains or is derived from the Program or any
682: part thereof, to be licensed as a whole at no charge to all third
683: parties under the terms of this License.
684:
685: @item
686: If the modified program normally reads commands interactively
687: when run, you must cause it, when started running for such
688: interactive use in the most ordinary way, to print or display an
689: announcement including an appropriate copyright notice and a
690: notice that there is no warranty (or else, saying that you provide
691: a warranty) and that users may redistribute the program under
692: these conditions, and telling the user how to view a copy of this
693: License. (Exception: if the Program itself is interactive but
694: does not normally print such an announcement, your work based on
695: the Program is not required to print an announcement.)
696: @end enumerate
697:
698: These requirements apply to the modified work as a whole. If
699: identifiable sections of that work are not derived from the Program,
700: and can be reasonably considered independent and separate works in
701: themselves, then this License, and its terms, do not apply to those
702: sections when you distribute them as separate works. But when you
703: distribute the same sections as part of a whole which is a work based
704: on the Program, the distribution of the whole must be on the terms of
705: this License, whose permissions for other licensees extend to the
706: entire whole, and thus to each and every part regardless of who wrote it.
707:
708: Thus, it is not the intent of this section to claim rights or contest
709: your rights to work written entirely by you; rather, the intent is to
710: exercise the right to control the distribution of derivative or
711: collective works based on the Program.
712:
713: In addition, mere aggregation of another work not based on the Program
714: with the Program (or with a work based on the Program) on a volume of
715: a storage or distribution medium does not bring the other work under
716: the scope of this License.
717:
718: @item
719: You may copy and distribute the Program (or a work based on it,
720: under Section 2) in object code or executable form under the terms of
721: Sections 1 and 2 above provided that you also do one of the following:
722:
723: @enumerate a
724: @item
725: Accompany it with the complete corresponding machine-readable
726: source code, which must be distributed under the terms of Sections
727: 1 and 2 above on a medium customarily used for software interchange; or,
728:
729: @item
730: Accompany it with a written offer, valid for at least three
731: years, to give any third party, for a charge no more than your
732: cost of physically performing source distribution, a complete
733: machine-readable copy of the corresponding source code, to be
734: distributed under the terms of Sections 1 and 2 above on a medium
735: customarily used for software interchange; or,
736:
737: @item
738: Accompany it with the information you received as to the offer
739: to distribute corresponding source code. (This alternative is
740: allowed only for noncommercial distribution and only if you
741: received the program in object code or executable form with such
742: an offer, in accord with Subsection b above.)
743: @end enumerate
744:
745: The source code for a work means the preferred form of the work for
746: making modifications to it. For an executable work, complete source
747: code means all the source code for all modules it contains, plus any
748: associated interface definition files, plus the scripts used to
749: control compilation and installation of the executable. However, as a
750: special exception, the source code distributed need not include
751: anything that is normally distributed (in either source or binary
752: form) with the major components (compiler, kernel, and so on) of the
753: operating system on which the executable runs, unless that component
754: itself accompanies the executable.
755:
756: If distribution of executable or object code is made by offering
757: access to copy from a designated place, then offering equivalent
758: access to copy the source code from the same place counts as
759: distribution of the source code, even though third parties are not
760: compelled to copy the source along with the object code.
761:
762: @item
763: You may not copy, modify, sublicense, or distribute the Program
764: except as expressly provided under this License. Any attempt
765: otherwise to copy, modify, sublicense or distribute the Program is
766: void, and will automatically terminate your rights under this License.
767: However, parties who have received copies, or rights, from you under
768: this License will not have their licenses terminated so long as such
769: parties remain in full compliance.
770:
771: @item
772: You are not required to accept this License, since you have not
773: signed it. However, nothing else grants you permission to modify or
774: distribute the Program or its derivative works. These actions are
775: prohibited by law if you do not accept this License. Therefore, by
776: modifying or distributing the Program (or any work based on the
777: Program), you indicate your acceptance of this License to do so, and
778: all its terms and conditions for copying, distributing or modifying
779: the Program or works based on it.
780:
781: @item
782: Each time you redistribute the Program (or any work based on the
783: Program), the recipient automatically receives a license from the
784: original licensor to copy, distribute or modify the Program subject to
785: these terms and conditions. You may not impose any further
786: restrictions on the recipients' exercise of the rights granted herein.
787: You are not responsible for enforcing compliance by third parties to
788: this License.
789:
790: @item
791: If, as a consequence of a court judgment or allegation of patent
792: infringement or for any other reason (not limited to patent issues),
793: conditions are imposed on you (whether by court order, agreement or
794: otherwise) that contradict the conditions of this License, they do not
795: excuse you from the conditions of this License. If you cannot
796: distribute so as to satisfy simultaneously your obligations under this
797: License and any other pertinent obligations, then as a consequence you
798: may not distribute the Program at all. For example, if a patent
799: license would not permit royalty-free redistribution of the Program by
800: all those who receive copies directly or indirectly through you, then
801: the only way you could satisfy both it and this License would be to
802: refrain entirely from distribution of the Program.
803:
804: If any portion of this section is held invalid or unenforceable under
805: any particular circumstance, the balance of the section is intended to
806: apply and the section as a whole is intended to apply in other
807: circumstances.
808:
809: It is not the purpose of this section to induce you to infringe any
810: patents or other property right claims or to contest validity of any
811: such claims; this section has the sole purpose of protecting the
812: integrity of the free software distribution system, which is
813: implemented by public license practices. Many people have made
814: generous contributions to the wide range of software distributed
815: through that system in reliance on consistent application of that
816: system; it is up to the author/donor to decide if he or she is willing
817: to distribute software through any other system and a licensee cannot
818: impose that choice.
819:
820: This section is intended to make thoroughly clear what is believed to
821: be a consequence of the rest of this License.
822:
823: @item
824: If the distribution and/or use of the Program is restricted in
825: certain countries either by patents or by copyrighted interfaces, the
826: original copyright holder who places the Program under this License
827: may add an explicit geographical distribution limitation excluding
828: those countries, so that distribution is permitted only in or among
829: countries not thus excluded. In such case, this License incorporates
830: the limitation as if written in the body of this License.
831:
832: @item
833: The Free Software Foundation may publish revised and/or new versions
834: of the General Public License from time to time. Such new versions will
835: be similar in spirit to the present version, but may differ in detail to
836: address new problems or concerns.
837:
838: Each version is given a distinguishing version number. If the Program
839: specifies a version number of this License which applies to it and ``any
840: later version'', you have the option of following the terms and conditions
841: either of that version or of any later version published by the Free
842: Software Foundation. If the Program does not specify a version number of
843: this License, you may choose any version ever published by the Free Software
844: Foundation.
845:
846: @item
847: If you wish to incorporate parts of the Program into other free
848: programs whose distribution conditions are different, write to the author
849: to ask for permission. For software which is copyrighted by the Free
850: Software Foundation, write to the Free Software Foundation; we sometimes
851: make exceptions for this. Our decision will be guided by the two goals
852: of preserving the free status of all derivatives of our free software and
853: of promoting the sharing and reuse of software generally.
854:
855: @iftex
856: @heading NO WARRANTY
857: @end iftex
1.49 anton 858: @ifnottex
1.1 anton 859: @center NO WARRANTY
1.49 anton 860: @end ifnottex
1.1 anton 861:
862: @item
863: BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
864: FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
865: OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
866: PROVIDE THE PROGRAM ``AS IS'' WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
867: OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
868: MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
869: TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
870: PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
871: REPAIR OR CORRECTION.
872:
873: @item
874: IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
875: WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
876: REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
877: INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
878: OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
879: TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
880: YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
881: PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
882: POSSIBILITY OF SUCH DAMAGES.
883: @end enumerate
884:
885: @iftex
886: @heading END OF TERMS AND CONDITIONS
887: @end iftex
1.49 anton 888: @ifnottex
1.1 anton 889: @center END OF TERMS AND CONDITIONS
1.49 anton 890: @end ifnottex
1.1 anton 891:
892: @page
893: @unnumberedsec How to Apply These Terms to Your New Programs
894:
895: If you develop a new program, and you want it to be of the greatest
896: possible use to the public, the best way to achieve this is to make it
897: free software which everyone can redistribute and change under these terms.
898:
899: To do so, attach the following notices to the program. It is safest
900: to attach them to the start of each source file to most effectively
901: convey the exclusion of warranty; and each file should have at least
902: the ``copyright'' line and a pointer to where the full notice is found.
903:
904: @smallexample
905: @var{one line to give the program's name and a brief idea of what it does.}
906: Copyright (C) 19@var{yy} @var{name of author}
907:
908: This program is free software; you can redistribute it and/or modify
909: it under the terms of the GNU General Public License as published by
910: the Free Software Foundation; either version 2 of the License, or
911: (at your option) any later version.
912:
913: This program is distributed in the hope that it will be useful,
914: but WITHOUT ANY WARRANTY; without even the implied warranty of
915: MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
916: GNU General Public License for more details.
917:
918: You should have received a copy of the GNU General Public License
919: along with this program; if not, write to the Free Software
1.88 anton 920: Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
1.1 anton 921: @end smallexample
922:
923: Also add information on how to contact you by electronic and paper mail.
924:
925: If the program is interactive, make it output a short notice like this
926: when it starts in an interactive mode:
927:
928: @smallexample
929: Gnomovision version 69, Copyright (C) 19@var{yy} @var{name of author}
930: Gnomovision comes with ABSOLUTELY NO WARRANTY; for details
931: type `show w'.
932: This is free software, and you are welcome to redistribute it
933: under certain conditions; type `show c' for details.
934: @end smallexample
935:
936: The hypothetical commands @samp{show w} and @samp{show c} should show
937: the appropriate parts of the General Public License. Of course, the
938: commands you use may be called something other than @samp{show w} and
939: @samp{show c}; they could even be mouse-clicks or menu items---whatever
940: suits your program.
941:
942: You should also get your employer (if you work as a programmer) or your
943: school, if any, to sign a ``copyright disclaimer'' for the program, if
944: necessary. Here is a sample; alter the names:
945:
946: @smallexample
947: Yoyodyne, Inc., hereby disclaims all copyright interest in the program
948: `Gnomovision' (which makes passes at compilers) written by James Hacker.
949:
950: @var{signature of Ty Coon}, 1 April 1989
951: Ty Coon, President of Vice
952: @end smallexample
953:
954: This General Public License does not permit incorporating your program into
955: proprietary programs. If your program is a subroutine library, you may
956: consider it more useful to permit linking proprietary applications with the
957: library. If this is what you want to do, use the GNU Library General
958: Public License instead of this License.
959:
960: @iftex
961: @unnumbered Preface
962: @cindex Preface
1.21 crook 963: This manual documents Gforth. Some introductory material is provided for
964: readers who are unfamiliar with Forth or who are migrating to Gforth
965: from other Forth compilers. However, this manual is primarily a
966: reference manual.
1.1 anton 967: @end iftex
968:
1.28 crook 969: @comment TODO much more blurb here.
1.26 crook 970:
971: @c ******************************************************************
1.29 crook 972: @node Goals, Gforth Environment, License, Top
1.26 crook 973: @comment node-name, next, previous, up
974: @chapter Goals of Gforth
975: @cindex goals of the Gforth project
976: The goal of the Gforth Project is to develop a standard model for
977: ANS Forth. This can be split into several subgoals:
978:
979: @itemize @bullet
980: @item
981: Gforth should conform to the ANS Forth Standard.
982: @item
983: It should be a model, i.e. it should define all the
984: implementation-dependent things.
985: @item
986: It should become standard, i.e. widely accepted and used. This goal
987: is the most difficult one.
988: @end itemize
989:
990: To achieve these goals Gforth should be
991: @itemize @bullet
992: @item
993: Similar to previous models (fig-Forth, F83)
994: @item
995: Powerful. It should provide for all the things that are considered
996: necessary today and even some that are not yet considered necessary.
997: @item
998: Efficient. It should not get the reputation of being exceptionally
999: slow.
1000: @item
1001: Free.
1002: @item
1003: Available on many machines/easy to port.
1004: @end itemize
1005:
1006: Have we achieved these goals? Gforth conforms to the ANS Forth
1007: standard. It may be considered a model, but we have not yet documented
1008: which parts of the model are stable and which parts we are likely to
1009: change. It certainly has not yet become a de facto standard, but it
1010: appears to be quite popular. It has some similarities to and some
1011: differences from previous models. It has some powerful features, but not
1012: yet everything that we envisioned. We certainly have achieved our
1.65 anton 1013: execution speed goals (@pxref{Performance})@footnote{However, in 1998
1014: the bar was raised when the major commercial Forth vendors switched to
1015: native code compilers.}. It is free and available on many machines.
1.29 crook 1016:
1.26 crook 1017: @c ******************************************************************
1.48 anton 1018: @node Gforth Environment, Tutorial, Goals, Top
1.29 crook 1019: @chapter Gforth Environment
1020: @cindex Gforth environment
1.21 crook 1021:
1.45 crook 1022: Note: ultimately, the Gforth man page will be auto-generated from the
1.29 crook 1023: material in this chapter.
1.21 crook 1024:
1025: @menu
1.29 crook 1026: * Invoking Gforth:: Getting in
1027: * Leaving Gforth:: Getting out
1028: * Command-line editing::
1.48 anton 1029: * Environment variables:: that affect how Gforth starts up
1.29 crook 1030: * Gforth Files:: What gets installed and where
1.112 ! anton 1031: * Gforth in pipes::
1.48 anton 1032: * Startup speed:: When 35ms is not fast enough ...
1.21 crook 1033: @end menu
1034:
1.49 anton 1035: For related information about the creation of images see @ref{Image Files}.
1.29 crook 1036:
1.21 crook 1037: @comment ----------------------------------------------
1.48 anton 1038: @node Invoking Gforth, Leaving Gforth, Gforth Environment, Gforth Environment
1.29 crook 1039: @section Invoking Gforth
1040: @cindex invoking Gforth
1041: @cindex running Gforth
1042: @cindex command-line options
1043: @cindex options on the command line
1044: @cindex flags on the command line
1.21 crook 1045:
1.30 anton 1046: Gforth is made up of two parts; an executable ``engine'' (named
1.109 anton 1047: @command{gforth} or @command{gforth-fast}) and an image file. To start it, you
1.30 anton 1048: will usually just say @code{gforth} -- this automatically loads the
1049: default image file @file{gforth.fi}. In many other cases the default
1050: Gforth image will be invoked like this:
1.21 crook 1051: @example
1.30 anton 1052: gforth [file | -e forth-code] ...
1.21 crook 1053: @end example
1.29 crook 1054: @noindent
1055: This interprets the contents of the files and the Forth code in the order they
1056: are given.
1.21 crook 1057:
1.109 anton 1058: In addition to the @command{gforth} engine, there is also an engine
1059: called @command{gforth-fast}, which is faster, but gives less
1060: informative error messages (@pxref{Error messages}) and may catch some
1061: stack underflows later or not at all. You should use it for debugged,
1062: performance-critical programs.
1063:
1064: Moreover, there is an engine called @command{gforth-itc}, which is
1065: useful in some backwards-compatibility situations (@pxref{Direct or
1066: Indirect Threaded?}).
1.30 anton 1067:
1.29 crook 1068: In general, the command line looks like this:
1.21 crook 1069:
1070: @example
1.30 anton 1071: gforth[-fast] [engine options] [image options]
1.21 crook 1072: @end example
1073:
1.30 anton 1074: The engine options must come before the rest of the command
1.29 crook 1075: line. They are:
1.26 crook 1076:
1.29 crook 1077: @table @code
1078: @cindex -i, command-line option
1079: @cindex --image-file, command-line option
1080: @item --image-file @i{file}
1081: @itemx -i @i{file}
1082: Loads the Forth image @i{file} instead of the default
1083: @file{gforth.fi} (@pxref{Image Files}).
1.21 crook 1084:
1.39 anton 1085: @cindex --appl-image, command-line option
1086: @item --appl-image @i{file}
1087: Loads the image @i{file} and leaves all further command-line arguments
1.65 anton 1088: to the image (instead of processing them as engine options). This is
1089: useful for building executable application images on Unix, built with
1.39 anton 1090: @code{gforthmi --application ...}.
1091:
1.29 crook 1092: @cindex --path, command-line option
1093: @cindex -p, command-line option
1094: @item --path @i{path}
1095: @itemx -p @i{path}
1096: Uses @i{path} for searching the image file and Forth source code files
1097: instead of the default in the environment variable @code{GFORTHPATH} or
1098: the path specified at installation time (e.g.,
1099: @file{/usr/local/share/gforth/0.2.0:.}). A path is given as a list of
1100: directories, separated by @samp{:} (on Unix) or @samp{;} (on other OSs).
1.21 crook 1101:
1.29 crook 1102: @cindex --dictionary-size, command-line option
1103: @cindex -m, command-line option
1104: @cindex @i{size} parameters for command-line options
1105: @cindex size of the dictionary and the stacks
1106: @item --dictionary-size @i{size}
1107: @itemx -m @i{size}
1108: Allocate @i{size} space for the Forth dictionary space instead of
1109: using the default specified in the image (typically 256K). The
1110: @i{size} specification for this and subsequent options consists of
1111: an integer and a unit (e.g.,
1112: @code{4M}). The unit can be one of @code{b} (bytes), @code{e} (element
1113: size, in this case Cells), @code{k} (kilobytes), @code{M} (Megabytes),
1114: @code{G} (Gigabytes), and @code{T} (Terabytes). If no unit is specified,
1115: @code{e} is used.
1.21 crook 1116:
1.29 crook 1117: @cindex --data-stack-size, command-line option
1118: @cindex -d, command-line option
1119: @item --data-stack-size @i{size}
1120: @itemx -d @i{size}
1121: Allocate @i{size} space for the data stack instead of using the
1122: default specified in the image (typically 16K).
1.21 crook 1123:
1.29 crook 1124: @cindex --return-stack-size, command-line option
1125: @cindex -r, command-line option
1126: @item --return-stack-size @i{size}
1127: @itemx -r @i{size}
1128: Allocate @i{size} space for the return stack instead of using the
1129: default specified in the image (typically 15K).
1.21 crook 1130:
1.29 crook 1131: @cindex --fp-stack-size, command-line option
1132: @cindex -f, command-line option
1133: @item --fp-stack-size @i{size}
1134: @itemx -f @i{size}
1135: Allocate @i{size} space for the floating point stack instead of
1136: using the default specified in the image (typically 15.5K). In this case
1137: the unit specifier @code{e} refers to floating point numbers.
1.21 crook 1138:
1.48 anton 1139: @cindex --locals-stack-size, command-line option
1140: @cindex -l, command-line option
1141: @item --locals-stack-size @i{size}
1142: @itemx -l @i{size}
1143: Allocate @i{size} space for the locals stack instead of using the
1144: default specified in the image (typically 14.5K).
1145:
1146: @cindex -h, command-line option
1147: @cindex --help, command-line option
1148: @item --help
1149: @itemx -h
1150: Print a message about the command-line options
1151:
1152: @cindex -v, command-line option
1153: @cindex --version, command-line option
1154: @item --version
1155: @itemx -v
1156: Print version and exit
1157:
1158: @cindex --debug, command-line option
1159: @item --debug
1160: Print some information useful for debugging on startup.
1161:
1162: @cindex --offset-image, command-line option
1163: @item --offset-image
1164: Start the dictionary at a slightly different position than would be used
1165: otherwise (useful for creating data-relocatable images,
1166: @pxref{Data-Relocatable Image Files}).
1167:
1168: @cindex --no-offset-im, command-line option
1169: @item --no-offset-im
1170: Start the dictionary at the normal position.
1171:
1172: @cindex --clear-dictionary, command-line option
1173: @item --clear-dictionary
1174: Initialize all bytes in the dictionary to 0 before loading the image
1175: (@pxref{Data-Relocatable Image Files}).
1176:
1177: @cindex --die-on-signal, command-line-option
1178: @item --die-on-signal
1179: Normally Gforth handles most signals (e.g., the user interrupt SIGINT,
1180: or the segmentation violation SIGSEGV) by translating it into a Forth
1181: @code{THROW}. With this option, Gforth exits if it receives such a
1182: signal. This option is useful when the engine and/or the image might be
1183: severely broken (such that it causes another signal before recovering
1184: from the first); this option avoids endless loops in such cases.
1.109 anton 1185:
1186: @item --no-dynamic
1187: @item --dynamic
1188: Disable or enable dynamic superinstructions with replication
1189: (@pxref{Dynamic Superinstructions}).
1190:
1191: @item --no-super
1.110 anton 1192: Disable dynamic superinstructions, use just dynamic replication; this is
1193: useful if you want to patch threaded code (@pxref{Dynamic
1194: Superinstructions}).
1.109 anton 1195:
1.48 anton 1196: @end table
1197:
1198: @cindex loading files at startup
1199: @cindex executing code on startup
1200: @cindex batch processing with Gforth
1201: As explained above, the image-specific command-line arguments for the
1202: default image @file{gforth.fi} consist of a sequence of filenames and
1203: @code{-e @var{forth-code}} options that are interpreted in the sequence
1204: in which they are given. The @code{-e @var{forth-code}} or
1205: @code{--evaluate @var{forth-code}} option evaluates the Forth
1206: code. This option takes only one argument; if you want to evaluate more
1207: Forth words, you have to quote them or use @code{-e} several times. To exit
1208: after processing the command line (instead of entering interactive mode)
1209: append @code{-e bye} to the command line.
1210:
1211: @cindex versions, invoking other versions of Gforth
1212: If you have several versions of Gforth installed, @code{gforth} will
1213: invoke the version that was installed last. @code{gforth-@i{version}}
1214: invokes a specific version. If your environment contains the variable
1215: @code{GFORTHPATH}, you may want to override it by using the
1216: @code{--path} option.
1217:
1218: Not yet implemented:
1219: On startup the system first executes the system initialization file
1220: (unless the option @code{--no-init-file} is given; note that the system
1221: resulting from using this option may not be ANS Forth conformant). Then
1222: the user initialization file @file{.gforth.fs} is executed, unless the
1.62 crook 1223: option @code{--no-rc} is given; this file is searched for in @file{.},
1.48 anton 1224: then in @file{~}, then in the normal path (see above).
1225:
1226:
1227:
1228: @comment ----------------------------------------------
1229: @node Leaving Gforth, Command-line editing, Invoking Gforth, Gforth Environment
1230: @section Leaving Gforth
1231: @cindex Gforth - leaving
1232: @cindex leaving Gforth
1233:
1234: You can leave Gforth by typing @code{bye} or @kbd{Ctrl-d} (at the start
1235: of a line) or (if you invoked Gforth with the @code{--die-on-signal}
1236: option) @kbd{Ctrl-c}. When you leave Gforth, all of your definitions and
1.49 anton 1237: data are discarded. For ways of saving the state of the system before
1238: leaving Gforth see @ref{Image Files}.
1.48 anton 1239:
1240: doc-bye
1241:
1242:
1243: @comment ----------------------------------------------
1.65 anton 1244: @node Command-line editing, Environment variables, Leaving Gforth, Gforth Environment
1.48 anton 1245: @section Command-line editing
1246: @cindex command-line editing
1247:
1248: Gforth maintains a history file that records every line that you type to
1249: the text interpreter. This file is preserved between sessions, and is
1250: used to provide a command-line recall facility; if you type @kbd{Ctrl-P}
1251: repeatedly you can recall successively older commands from this (or
1252: previous) session(s). The full list of command-line editing facilities is:
1253:
1254: @itemize @bullet
1255: @item
1256: @kbd{Ctrl-p} (``previous'') (or up-arrow) to recall successively older
1257: commands from the history buffer.
1258: @item
1259: @kbd{Ctrl-n} (``next'') (or down-arrow) to recall successively newer commands
1260: from the history buffer.
1261: @item
1262: @kbd{Ctrl-f} (or right-arrow) to move the cursor right, non-destructively.
1263: @item
1264: @kbd{Ctrl-b} (or left-arrow) to move the cursor left, non-destructively.
1265: @item
1266: @kbd{Ctrl-h} (backspace) to delete the character to the left of the cursor,
1267: closing up the line.
1268: @item
1269: @kbd{Ctrl-k} to delete (``kill'') from the cursor to the end of the line.
1270: @item
1271: @kbd{Ctrl-a} to move the cursor to the start of the line.
1272: @item
1273: @kbd{Ctrl-e} to move the cursor to the end of the line.
1274: @item
1275: @key{RET} (@kbd{Ctrl-m}) or @key{LFD} (@kbd{Ctrl-j}) to submit the current
1276: line.
1277: @item
1278: @key{TAB} to step through all possible full-word completions of the word
1279: currently being typed.
1280: @item
1.65 anton 1281: @kbd{Ctrl-d} on an empty line line to terminate Gforth (gracefully,
1282: using @code{bye}).
1283: @item
1284: @kbd{Ctrl-x} (or @code{Ctrl-d} on a non-empty line) to delete the
1285: character under the cursor.
1.48 anton 1286: @end itemize
1287:
1288: When editing, displayable characters are inserted to the left of the
1289: cursor position; the line is always in ``insert'' (as opposed to
1290: ``overstrike'') mode.
1291:
1292: @cindex history file
1293: @cindex @file{.gforth-history}
1294: On Unix systems, the history file is @file{~/.gforth-history} by
1295: default@footnote{i.e. it is stored in the user's home directory.}. You
1296: can find out the name and location of your history file using:
1297:
1298: @example
1299: history-file type \ Unix-class systems
1300:
1301: history-file type \ Other systems
1302: history-dir type
1303: @end example
1304:
1305: If you enter long definitions by hand, you can use a text editor to
1306: paste them out of the history file into a Forth source file for reuse at
1307: a later time.
1308:
1309: Gforth never trims the size of the history file, so you should do this
1310: periodically, if necessary.
1311:
1312: @comment this is all defined in history.fs
1313: @comment NAC TODO the ctrl-D behaviour can either do a bye or a beep.. how is that option
1314: @comment chosen?
1315:
1316:
1317: @comment ----------------------------------------------
1.65 anton 1318: @node Environment variables, Gforth Files, Command-line editing, Gforth Environment
1.48 anton 1319: @section Environment variables
1320: @cindex environment variables
1321:
1322: Gforth uses these environment variables:
1323:
1324: @itemize @bullet
1325: @item
1326: @cindex @code{GFORTHHIST} -- environment variable
1327: @code{GFORTHHIST} -- (Unix systems only) specifies the directory in which to
1328: open/create the history file, @file{.gforth-history}. Default:
1329: @code{$HOME}.
1330:
1331: @item
1332: @cindex @code{GFORTHPATH} -- environment variable
1333: @code{GFORTHPATH} -- specifies the path used when searching for the gforth image file and
1334: for Forth source-code files.
1335:
1336: @item
1337: @cindex @code{GFORTH} -- environment variable
1.49 anton 1338: @code{GFORTH} -- used by @file{gforthmi}, @xref{gforthmi}.
1.48 anton 1339:
1340: @item
1341: @cindex @code{GFORTHD} -- environment variable
1.62 crook 1342: @code{GFORTHD} -- used by @file{gforthmi}, @xref{gforthmi}.
1.48 anton 1343:
1344: @item
1345: @cindex @code{TMP}, @code{TEMP} - environment variable
1346: @code{TMP}, @code{TEMP} - (non-Unix systems only) used as a potential
1347: location for the history file.
1348: @end itemize
1349:
1350: @comment also POSIXELY_CORRECT LINES COLUMNS HOME but no interest in
1351: @comment mentioning these.
1352:
1353: All the Gforth environment variables default to sensible values if they
1354: are not set.
1355:
1356:
1357: @comment ----------------------------------------------
1.112 ! anton 1358: @node Gforth Files, Gforth in pipes, Environment variables, Gforth Environment
1.48 anton 1359: @section Gforth files
1360: @cindex Gforth files
1361:
1362: When you install Gforth on a Unix system, it installs files in these
1363: locations by default:
1364:
1365: @itemize @bullet
1366: @item
1367: @file{/usr/local/bin/gforth}
1368: @item
1369: @file{/usr/local/bin/gforthmi}
1370: @item
1371: @file{/usr/local/man/man1/gforth.1} - man page.
1372: @item
1373: @file{/usr/local/info} - the Info version of this manual.
1374: @item
1375: @file{/usr/local/lib/gforth/<version>/...} - Gforth @file{.fi} files.
1376: @item
1377: @file{/usr/local/share/gforth/<version>/TAGS} - Emacs TAGS file.
1378: @item
1379: @file{/usr/local/share/gforth/<version>/...} - Gforth source files.
1380: @item
1381: @file{.../emacs/site-lisp/gforth.el} - Emacs gforth mode.
1382: @end itemize
1383:
1384: You can select different places for installation by using
1385: @code{configure} options (listed with @code{configure --help}).
1386:
1387: @comment ----------------------------------------------
1.112 ! anton 1388: @node Gforth in pipes, Startup speed, Gforth Files, Gforth Environment
! 1389: @section Gforth in pipes
! 1390: @cindex pipes, Gforth as part of
! 1391:
! 1392: Gforth can be used in pipes created elsewhere (described here). It can
! 1393: also create pipes on its own (@pxref{Pipes}).
! 1394:
! 1395: @cindex input from pipes
! 1396: If you pipe into Gforth, your program should read with @code{read-file}
! 1397: or @code{read-line} from @code{stdin} (@pxref{General files}).
! 1398: @code{Key} does not recognize the end of input. Words like
! 1399: @code{accept} echo the input and are therefore usually not useful for
! 1400: reading from a pipe. You have to invoke the Forth program with an OS
! 1401: command-line option, as you have no chance to use the Forth command line
! 1402: (the text interpreter would try to interpret the pipe input).
! 1403:
! 1404: @cindex output in pipes
! 1405: You can output to a pipe with @code{type}, @code{emit}, @code{cr} etc.
! 1406:
! 1407: @cindex silent exiting from Gforth
! 1408: When you write to a pipe that has been closed at the other end, Gforth
! 1409: receives a SIGPIPE signal (``pipe broken''). Gforth translates this
! 1410: into the exception @code{broken-pipe-error}. If your application does
! 1411: not catch that exception, the system catches it and exits, usually
! 1412: silently (unless you were working on the Forth command line; then it
! 1413: prints an error message and exits). This is usually the desired
! 1414: behaviour.
! 1415:
! 1416: If you do not like this behaviour, you have to catch the exception
! 1417: yourself, and react to it.
! 1418:
! 1419: Here's an example of an invocation of Gforth that is usable in a pipe:
! 1420:
! 1421: @example
! 1422: gforth -e ": foo begin pad dup 10 stdin read-file throw dup while \
! 1423: type repeat ; foo bye"
! 1424: @end example
! 1425:
! 1426: This example just copies the input verbatim to the output. A very
! 1427: simple pipe containing this example looks like this:
! 1428:
! 1429: @example
! 1430: cat startup.fs |
! 1431: gforth -e ": foo begin pad dup 80 stdin read-file throw dup while \
! 1432: type repeat ; foo bye"|
! 1433: head
! 1434: @end example
! 1435:
! 1436: @cindex stderr and pipes
! 1437: Pipes involving Gforth's @code{stderr} output do not work.
! 1438:
! 1439: @comment ----------------------------------------------
! 1440: @node Startup speed, , Gforth in pipes, Gforth Environment
1.48 anton 1441: @section Startup speed
1442: @cindex Startup speed
1443: @cindex speed, startup
1444:
1445: If Gforth is used for CGI scripts or in shell scripts, its startup
1446: speed may become a problem. On a 300MHz 21064a under Linux-2.2.13 with
1447: glibc-2.0.7, @code{gforth -e bye} takes about 24.6ms user and 11.3ms
1448: system time.
1449:
1450: If startup speed is a problem, you may consider the following ways to
1451: improve it; or you may consider ways to reduce the number of startups
1.62 crook 1452: (for example, by using Fast-CGI).
1.48 anton 1453:
1.112 ! anton 1454: An easy step that influences Gforth startup speed is the use of the
! 1455: @option{--no-dynamic} option; this decreases image loading speed, but
! 1456: increases compile-time and run-time.
! 1457:
! 1458: Another step to improve startup speed is to statically link Gforth, by
1.48 anton 1459: building it with @code{XLDFLAGS=-static}. This requires more memory for
1460: the code and will therefore slow down the first invocation, but
1461: subsequent invocations avoid the dynamic linking overhead. Another
1462: disadvantage is that Gforth won't profit from library upgrades. As a
1463: result, @code{gforth-static -e bye} takes about 17.1ms user and
1464: 8.2ms system time.
1465:
1466: The next step to improve startup speed is to use a non-relocatable image
1.65 anton 1467: (@pxref{Non-Relocatable Image Files}). You can create this image with
1.48 anton 1468: @code{gforth -e "savesystem gforthnr.fi bye"} and later use it with
1469: @code{gforth -i gforthnr.fi ...}. This avoids the relocation overhead
1470: and a part of the copy-on-write overhead. The disadvantage is that the
1.62 crook 1471: non-relocatable image does not work if the OS gives Gforth a different
1.48 anton 1472: address for the dictionary, for whatever reason; so you better provide a
1473: fallback on a relocatable image. @code{gforth-static -i gforthnr.fi -e
1474: bye} takes about 15.3ms user and 7.5ms system time.
1475:
1476: The final step is to disable dictionary hashing in Gforth. Gforth
1477: builds the hash table on startup, which takes much of the startup
1478: overhead. You can do this by commenting out the @code{include hash.fs}
1479: in @file{startup.fs} and everything that requires @file{hash.fs} (at the
1480: moment @file{table.fs} and @file{ekey.fs}) and then doing @code{make}.
1481: The disadvantages are that functionality like @code{table} and
1482: @code{ekey} is missing and that text interpretation (e.g., compiling)
1483: now takes much longer. So, you should only use this method if there is
1484: no significant text interpretation to perform (the script should be
1.62 crook 1485: compiled into the image, amongst other things). @code{gforth-static -i
1.48 anton 1486: gforthnrnh.fi -e bye} takes about 2.1ms user and 6.1ms system time.
1487:
1488: @c ******************************************************************
1489: @node Tutorial, Introduction, Gforth Environment, Top
1490: @chapter Forth Tutorial
1491: @cindex Tutorial
1492: @cindex Forth Tutorial
1493:
1.67 anton 1494: @c Topics from nac's Introduction that could be mentioned:
1495: @c press <ret> after each line
1496: @c Prompt
1497: @c numbers vs. words in dictionary on text interpretation
1498: @c what happens on redefinition
1499: @c parsing words (in particular, defining words)
1500:
1.83 anton 1501: The difference of this chapter from the Introduction
1502: (@pxref{Introduction}) is that this tutorial is more fast-paced, should
1503: be used while sitting in front of a computer, and covers much more
1504: material, but does not explain how the Forth system works.
1505:
1.62 crook 1506: This tutorial can be used with any ANS-compliant Forth; any
1507: Gforth-specific features are marked as such and you can skip them if you
1508: work with another Forth. This tutorial does not explain all features of
1509: Forth, just enough to get you started and give you some ideas about the
1510: facilities available in Forth. Read the rest of the manual and the
1511: standard when you are through this.
1.48 anton 1512:
1513: The intended way to use this tutorial is that you work through it while
1514: sitting in front of the console, take a look at the examples and predict
1515: what they will do, then try them out; if the outcome is not as expected,
1516: find out why (e.g., by trying out variations of the example), so you
1517: understand what's going on. There are also some assignments that you
1518: should solve.
1519:
1520: This tutorial assumes that you have programmed before and know what,
1521: e.g., a loop is.
1522:
1523: @c !! explain compat library
1524:
1525: @menu
1526: * Starting Gforth Tutorial::
1527: * Syntax Tutorial::
1528: * Crash Course Tutorial::
1529: * Stack Tutorial::
1530: * Arithmetics Tutorial::
1531: * Stack Manipulation Tutorial::
1532: * Using files for Forth code Tutorial::
1533: * Comments Tutorial::
1534: * Colon Definitions Tutorial::
1535: * Decompilation Tutorial::
1536: * Stack-Effect Comments Tutorial::
1537: * Types Tutorial::
1538: * Factoring Tutorial::
1539: * Designing the stack effect Tutorial::
1540: * Local Variables Tutorial::
1541: * Conditional execution Tutorial::
1542: * Flags and Comparisons Tutorial::
1543: * General Loops Tutorial::
1544: * Counted loops Tutorial::
1545: * Recursion Tutorial::
1546: * Leaving definitions or loops Tutorial::
1547: * Return Stack Tutorial::
1548: * Memory Tutorial::
1549: * Characters and Strings Tutorial::
1550: * Alignment Tutorial::
1.87 anton 1551: * Files Tutorial::
1.48 anton 1552: * Interpretation and Compilation Semantics and Immediacy Tutorial::
1553: * Execution Tokens Tutorial::
1554: * Exceptions Tutorial::
1555: * Defining Words Tutorial::
1556: * Arrays and Records Tutorial::
1557: * POSTPONE Tutorial::
1558: * Literal Tutorial::
1559: * Advanced macros Tutorial::
1560: * Compilation Tokens Tutorial::
1561: * Wordlists and Search Order Tutorial::
1562: @end menu
1563:
1564: @node Starting Gforth Tutorial, Syntax Tutorial, Tutorial, Tutorial
1565: @section Starting Gforth
1.66 anton 1566: @cindex starting Gforth tutorial
1.48 anton 1567: You can start Gforth by typing its name:
1568:
1569: @example
1570: gforth
1571: @end example
1572:
1573: That puts you into interactive mode; you can leave Gforth by typing
1574: @code{bye}. While in Gforth, you can edit the command line and access
1575: the command line history with cursor keys, similar to bash.
1576:
1577:
1578: @node Syntax Tutorial, Crash Course Tutorial, Starting Gforth Tutorial, Tutorial
1579: @section Syntax
1.66 anton 1580: @cindex syntax tutorial
1.48 anton 1581:
1582: A @dfn{word} is a sequence of arbitrary characters (expcept white
1583: space). Words are separated by white space. E.g., each of the
1584: following lines contains exactly one word:
1585:
1586: @example
1587: word
1588: !@@#$%^&*()
1589: 1234567890
1590: 5!a
1591: @end example
1592:
1593: A frequent beginner's error is to leave away necessary white space,
1594: resulting in an error like @samp{Undefined word}; so if you see such an
1595: error, check if you have put spaces wherever necessary.
1596:
1597: @example
1598: ." hello, world" \ correct
1599: ."hello, world" \ gives an "Undefined word" error
1600: @end example
1601:
1.65 anton 1602: Gforth and most other Forth systems ignore differences in case (they are
1.48 anton 1603: case-insensitive), i.e., @samp{word} is the same as @samp{Word}. If
1604: your system is case-sensitive, you may have to type all the examples
1605: given here in upper case.
1606:
1607:
1608: @node Crash Course Tutorial, Stack Tutorial, Syntax Tutorial, Tutorial
1609: @section Crash Course
1610:
1611: Type
1612:
1613: @example
1614: 0 0 !
1615: here execute
1616: ' catch >body 20 erase abort
1617: ' (quit) >body 20 erase
1618: @end example
1619:
1620: The last two examples are guaranteed to destroy parts of Gforth (and
1621: most other systems), so you better leave Gforth afterwards (if it has
1622: not finished by itself). On some systems you may have to kill gforth
1623: from outside (e.g., in Unix with @code{kill}).
1624:
1625: Now that you know how to produce crashes (and that there's not much to
1626: them), let's learn how to produce meaningful programs.
1627:
1628:
1629: @node Stack Tutorial, Arithmetics Tutorial, Crash Course Tutorial, Tutorial
1630: @section Stack
1.66 anton 1631: @cindex stack tutorial
1.48 anton 1632:
1633: The most obvious feature of Forth is the stack. When you type in a
1634: number, it is pushed on the stack. You can display the content of the
1635: stack with @code{.s}.
1636:
1637: @example
1638: 1 2 .s
1639: 3 .s
1640: @end example
1641:
1642: @code{.s} displays the top-of-stack to the right, i.e., the numbers
1643: appear in @code{.s} output as they appeared in the input.
1644:
1645: You can print the top of stack element with @code{.}.
1646:
1647: @example
1648: 1 2 3 . . .
1649: @end example
1650:
1651: In general, words consume their stack arguments (@code{.s} is an
1652: exception).
1653:
1654: @assignment
1655: What does the stack contain after @code{5 6 7 .}?
1656: @endassignment
1657:
1658:
1659: @node Arithmetics Tutorial, Stack Manipulation Tutorial, Stack Tutorial, Tutorial
1660: @section Arithmetics
1.66 anton 1661: @cindex arithmetics tutorial
1.48 anton 1662:
1663: The words @code{+}, @code{-}, @code{*}, @code{/}, and @code{mod} always
1664: operate on the top two stack items:
1665:
1666: @example
1.67 anton 1667: 2 2 .s
1668: + .s
1669: .
1.48 anton 1670: 2 1 - .
1671: 7 3 mod .
1672: @end example
1673:
1674: The operands of @code{-}, @code{/}, and @code{mod} are in the same order
1675: as in the corresponding infix expression (this is generally the case in
1676: Forth).
1677:
1678: Parentheses are superfluous (and not available), because the order of
1679: the words unambiguously determines the order of evaluation and the
1680: operands:
1681:
1682: @example
1683: 3 4 + 5 * .
1684: 3 4 5 * + .
1685: @end example
1686:
1687: @assignment
1688: What are the infix expressions corresponding to the Forth code above?
1689: Write @code{6-7*8+9} in Forth notation@footnote{This notation is also
1690: known as Postfix or RPN (Reverse Polish Notation).}.
1691: @endassignment
1692:
1693: To change the sign, use @code{negate}:
1694:
1695: @example
1696: 2 negate .
1697: @end example
1698:
1699: @assignment
1700: Convert -(-3)*4-5 to Forth.
1701: @endassignment
1702:
1703: @code{/mod} performs both @code{/} and @code{mod}.
1704:
1705: @example
1706: 7 3 /mod . .
1707: @end example
1708:
1.66 anton 1709: Reference: @ref{Arithmetic}.
1710:
1711:
1.48 anton 1712: @node Stack Manipulation Tutorial, Using files for Forth code Tutorial, Arithmetics Tutorial, Tutorial
1713: @section Stack Manipulation
1.66 anton 1714: @cindex stack manipulation tutorial
1.48 anton 1715:
1716: Stack manipulation words rearrange the data on the stack.
1717:
1718: @example
1719: 1 .s drop .s
1720: 1 .s dup .s drop drop .s
1721: 1 2 .s over .s drop drop drop
1722: 1 2 .s swap .s drop drop
1723: 1 2 3 .s rot .s drop drop drop
1724: @end example
1725:
1726: These are the most important stack manipulation words. There are also
1727: variants that manipulate twice as many stack items:
1728:
1729: @example
1730: 1 2 3 4 .s 2swap .s 2drop 2drop
1731: @end example
1732:
1733: Two more stack manipulation words are:
1734:
1735: @example
1736: 1 2 .s nip .s drop
1737: 1 2 .s tuck .s 2drop drop
1738: @end example
1739:
1740: @assignment
1741: Replace @code{nip} and @code{tuck} with combinations of other stack
1742: manipulation words.
1743:
1744: @example
1745: Given: How do you get:
1746: 1 2 3 3 2 1
1747: 1 2 3 1 2 3 2
1748: 1 2 3 1 2 3 3
1749: 1 2 3 1 3 3
1750: 1 2 3 2 1 3
1751: 1 2 3 4 4 3 2 1
1752: 1 2 3 1 2 3 1 2 3
1753: 1 2 3 4 1 2 3 4 1 2
1754: 1 2 3
1755: 1 2 3 1 2 3 4
1756: 1 2 3 1 3
1757: @end example
1758: @endassignment
1759:
1760: @example
1761: 5 dup * .
1762: @end example
1763:
1764: @assignment
1765: Write 17^3 and 17^4 in Forth, without writing @code{17} more than once.
1766: Write a piece of Forth code that expects two numbers on the stack
1767: (@var{a} and @var{b}, with @var{b} on top) and computes
1768: @code{(a-b)(a+1)}.
1769: @endassignment
1770:
1.66 anton 1771: Reference: @ref{Stack Manipulation}.
1772:
1773:
1.48 anton 1774: @node Using files for Forth code Tutorial, Comments Tutorial, Stack Manipulation Tutorial, Tutorial
1775: @section Using files for Forth code
1.66 anton 1776: @cindex loading Forth code, tutorial
1777: @cindex files containing Forth code, tutorial
1.48 anton 1778:
1779: While working at the Forth command line is convenient for one-line
1780: examples and short one-off code, you probably want to store your source
1781: code in files for convenient editing and persistence. You can use your
1782: favourite editor (Gforth includes Emacs support, @pxref{Emacs and
1.102 anton 1783: Gforth}) to create @var{file.fs} and use
1.48 anton 1784:
1785: @example
1.102 anton 1786: s" @var{file.fs}" included
1.48 anton 1787: @end example
1788:
1789: to load it into your Forth system. The file name extension I use for
1790: Forth files is @samp{.fs}.
1791:
1792: You can easily start Gforth with some files loaded like this:
1793:
1794: @example
1.102 anton 1795: gforth @var{file1.fs} @var{file2.fs}
1.48 anton 1796: @end example
1797:
1798: If an error occurs during loading these files, Gforth terminates,
1799: whereas an error during @code{INCLUDED} within Gforth usually gives you
1800: a Gforth command line. Starting the Forth system every time gives you a
1801: clean start every time, without interference from the results of earlier
1802: tries.
1803:
1804: I often put all the tests in a file, then load the code and run the
1805: tests with
1806:
1807: @example
1.102 anton 1808: gforth @var{code.fs} @var{tests.fs} -e bye
1.48 anton 1809: @end example
1810:
1811: (often by performing this command with @kbd{C-x C-e} in Emacs). The
1812: @code{-e bye} ensures that Gforth terminates afterwards so that I can
1813: restart this command without ado.
1814:
1815: The advantage of this approach is that the tests can be repeated easily
1816: every time the program ist changed, making it easy to catch bugs
1817: introduced by the change.
1818:
1.66 anton 1819: Reference: @ref{Forth source files}.
1820:
1.48 anton 1821:
1822: @node Comments Tutorial, Colon Definitions Tutorial, Using files for Forth code Tutorial, Tutorial
1823: @section Comments
1.66 anton 1824: @cindex comments tutorial
1.48 anton 1825:
1826: @example
1827: \ That's a comment; it ends at the end of the line
1828: ( Another comment; it ends here: ) .s
1829: @end example
1830:
1831: @code{\} and @code{(} are ordinary Forth words and therefore have to be
1832: separated with white space from the following text.
1833:
1834: @example
1835: \This gives an "Undefined word" error
1836: @end example
1837:
1838: The first @code{)} ends a comment started with @code{(}, so you cannot
1839: nest @code{(}-comments; and you cannot comment out text containing a
1840: @code{)} with @code{( ... )}@footnote{therefore it's a good idea to
1841: avoid @code{)} in word names.}.
1842:
1843: I use @code{\}-comments for descriptive text and for commenting out code
1844: of one or more line; I use @code{(}-comments for describing the stack
1845: effect, the stack contents, or for commenting out sub-line pieces of
1846: code.
1847:
1848: The Emacs mode @file{gforth.el} (@pxref{Emacs and Gforth}) supports
1849: these uses by commenting out a region with @kbd{C-x \}, uncommenting a
1850: region with @kbd{C-u C-x \}, and filling a @code{\}-commented region
1851: with @kbd{M-q}.
1852:
1.66 anton 1853: Reference: @ref{Comments}.
1854:
1.48 anton 1855:
1856: @node Colon Definitions Tutorial, Decompilation Tutorial, Comments Tutorial, Tutorial
1857: @section Colon Definitions
1.66 anton 1858: @cindex colon definitions, tutorial
1859: @cindex definitions, tutorial
1860: @cindex procedures, tutorial
1861: @cindex functions, tutorial
1.48 anton 1862:
1863: are similar to procedures and functions in other programming languages.
1864:
1865: @example
1866: : squared ( n -- n^2 )
1867: dup * ;
1868: 5 squared .
1869: 7 squared .
1870: @end example
1871:
1872: @code{:} starts the colon definition; its name is @code{squared}. The
1873: following comment describes its stack effect. The words @code{dup *}
1874: are not executed, but compiled into the definition. @code{;} ends the
1875: colon definition.
1876:
1877: The newly-defined word can be used like any other word, including using
1878: it in other definitions:
1879:
1880: @example
1881: : cubed ( n -- n^3 )
1882: dup squared * ;
1883: -5 cubed .
1884: : fourth-power ( n -- n^4 )
1885: squared squared ;
1886: 3 fourth-power .
1887: @end example
1888:
1889: @assignment
1890: Write colon definitions for @code{nip}, @code{tuck}, @code{negate}, and
1891: @code{/mod} in terms of other Forth words, and check if they work (hint:
1892: test your tests on the originals first). Don't let the
1893: @samp{redefined}-Messages spook you, they are just warnings.
1894: @endassignment
1895:
1.66 anton 1896: Reference: @ref{Colon Definitions}.
1897:
1.48 anton 1898:
1899: @node Decompilation Tutorial, Stack-Effect Comments Tutorial, Colon Definitions Tutorial, Tutorial
1900: @section Decompilation
1.66 anton 1901: @cindex decompilation tutorial
1902: @cindex see tutorial
1.48 anton 1903:
1904: You can decompile colon definitions with @code{see}:
1905:
1906: @example
1907: see squared
1908: see cubed
1909: @end example
1910:
1911: In Gforth @code{see} shows you a reconstruction of the source code from
1912: the executable code. Informations that were present in the source, but
1913: not in the executable code, are lost (e.g., comments).
1914:
1.65 anton 1915: You can also decompile the predefined words:
1916:
1917: @example
1918: see .
1919: see +
1920: @end example
1921:
1922:
1.48 anton 1923: @node Stack-Effect Comments Tutorial, Types Tutorial, Decompilation Tutorial, Tutorial
1924: @section Stack-Effect Comments
1.66 anton 1925: @cindex stack-effect comments, tutorial
1926: @cindex --, tutorial
1.48 anton 1927: By convention the comment after the name of a definition describes the
1928: stack effect: The part in from of the @samp{--} describes the state of
1929: the stack before the execution of the definition, i.e., the parameters
1930: that are passed into the colon definition; the part behind the @samp{--}
1931: is the state of the stack after the execution of the definition, i.e.,
1932: the results of the definition. The stack comment only shows the top
1933: stack items that the definition accesses and/or changes.
1934:
1935: You should put a correct stack effect on every definition, even if it is
1936: just @code{( -- )}. You should also add some descriptive comment to
1937: more complicated words (I usually do this in the lines following
1938: @code{:}). If you don't do this, your code becomes unreadable (because
1939: you have to work through every definition before you can undertsand
1940: any).
1941:
1942: @assignment
1943: The stack effect of @code{swap} can be written like this: @code{x1 x2 --
1944: x2 x1}. Describe the stack effect of @code{-}, @code{drop}, @code{dup},
1945: @code{over}, @code{rot}, @code{nip}, and @code{tuck}. Hint: When you
1.65 anton 1946: are done, you can compare your stack effects to those in this manual
1.48 anton 1947: (@pxref{Word Index}).
1948: @endassignment
1949:
1950: Sometimes programmers put comments at various places in colon
1951: definitions that describe the contents of the stack at that place (stack
1952: comments); i.e., they are like the first part of a stack-effect
1953: comment. E.g.,
1954:
1955: @example
1956: : cubed ( n -- n^3 )
1957: dup squared ( n n^2 ) * ;
1958: @end example
1959:
1960: In this case the stack comment is pretty superfluous, because the word
1961: is simple enough. If you think it would be a good idea to add such a
1962: comment to increase readability, you should also consider factoring the
1963: word into several simpler words (@pxref{Factoring Tutorial,,
1.60 anton 1964: Factoring}), which typically eliminates the need for the stack comment;
1.48 anton 1965: however, if you decide not to refactor it, then having such a comment is
1966: better than not having it.
1967:
1968: The names of the stack items in stack-effect and stack comments in the
1969: standard, in this manual, and in many programs specify the type through
1970: a type prefix, similar to Fortran and Hungarian notation. The most
1971: frequent prefixes are:
1972:
1973: @table @code
1974: @item n
1975: signed integer
1976: @item u
1977: unsigned integer
1978: @item c
1979: character
1980: @item f
1981: Boolean flags, i.e. @code{false} or @code{true}.
1982: @item a-addr,a-
1983: Cell-aligned address
1984: @item c-addr,c-
1985: Char-aligned address (note that a Char may have two bytes in Windows NT)
1986: @item xt
1987: Execution token, same size as Cell
1988: @item w,x
1989: Cell, can contain an integer or an address. It usually takes 32, 64 or
1990: 16 bits (depending on your platform and Forth system). A cell is more
1991: commonly known as machine word, but the term @emph{word} already means
1992: something different in Forth.
1993: @item d
1994: signed double-cell integer
1995: @item ud
1996: unsigned double-cell integer
1997: @item r
1998: Float (on the FP stack)
1999: @end table
2000:
2001: You can find a more complete list in @ref{Notation}.
2002:
2003: @assignment
2004: Write stack-effect comments for all definitions you have written up to
2005: now.
2006: @endassignment
2007:
2008:
2009: @node Types Tutorial, Factoring Tutorial, Stack-Effect Comments Tutorial, Tutorial
2010: @section Types
1.66 anton 2011: @cindex types tutorial
1.48 anton 2012:
2013: In Forth the names of the operations are not overloaded; so similar
2014: operations on different types need different names; e.g., @code{+} adds
2015: integers, and you have to use @code{f+} to add floating-point numbers.
2016: The following prefixes are often used for related operations on
2017: different types:
2018:
2019: @table @code
2020: @item (none)
2021: signed integer
2022: @item u
2023: unsigned integer
2024: @item c
2025: character
2026: @item d
2027: signed double-cell integer
2028: @item ud, du
2029: unsigned double-cell integer
2030: @item 2
2031: two cells (not-necessarily double-cell numbers)
2032: @item m, um
2033: mixed single-cell and double-cell operations
2034: @item f
2035: floating-point (note that in stack comments @samp{f} represents flags,
1.66 anton 2036: and @samp{r} represents FP numbers).
1.48 anton 2037: @end table
2038:
2039: If there are no differences between the signed and the unsigned variant
2040: (e.g., for @code{+}), there is only the prefix-less variant.
2041:
2042: Forth does not perform type checking, neither at compile time, nor at
2043: run time. If you use the wrong oeration, the data are interpreted
2044: incorrectly:
2045:
2046: @example
2047: -1 u.
2048: @end example
2049:
2050: If you have only experience with type-checked languages until now, and
2051: have heard how important type-checking is, don't panic! In my
2052: experience (and that of other Forthers), type errors in Forth code are
2053: usually easy to find (once you get used to it), the increased vigilance
2054: of the programmer tends to catch some harder errors in addition to most
2055: type errors, and you never have to work around the type system, so in
2056: most situations the lack of type-checking seems to be a win (projects to
2057: add type checking to Forth have not caught on).
2058:
2059:
2060: @node Factoring Tutorial, Designing the stack effect Tutorial, Types Tutorial, Tutorial
2061: @section Factoring
1.66 anton 2062: @cindex factoring tutorial
1.48 anton 2063:
2064: If you try to write longer definitions, you will soon find it hard to
2065: keep track of the stack contents. Therefore, good Forth programmers
2066: tend to write only short definitions (e.g., three lines). The art of
2067: finding meaningful short definitions is known as factoring (as in
2068: factoring polynomials).
2069:
2070: Well-factored programs offer additional advantages: smaller, more
2071: general words, are easier to test and debug and can be reused more and
2072: better than larger, specialized words.
2073:
2074: So, if you run into difficulties with stack management, when writing
2075: code, try to define meaningful factors for the word, and define the word
2076: in terms of those. Even if a factor contains only two words, it is
2077: often helpful.
2078:
1.65 anton 2079: Good factoring is not easy, and it takes some practice to get the knack
2080: for it; but even experienced Forth programmers often don't find the
2081: right solution right away, but only when rewriting the program. So, if
2082: you don't come up with a good solution immediately, keep trying, don't
2083: despair.
1.48 anton 2084:
2085: @c example !!
2086:
2087:
2088: @node Designing the stack effect Tutorial, Local Variables Tutorial, Factoring Tutorial, Tutorial
2089: @section Designing the stack effect
1.66 anton 2090: @cindex Stack effect design, tutorial
2091: @cindex design of stack effects, tutorial
1.48 anton 2092:
2093: In other languages you can use an arbitrary order of parameters for a
1.65 anton 2094: function; and since there is only one result, you don't have to deal with
1.48 anton 2095: the order of results, either.
2096:
2097: In Forth (and other stack-based languages, e.g., Postscript) the
2098: parameter and result order of a definition is important and should be
2099: designed well. The general guideline is to design the stack effect such
2100: that the word is simple to use in most cases, even if that complicates
2101: the implementation of the word. Some concrete rules are:
2102:
2103: @itemize @bullet
2104:
2105: @item
2106: Words consume all of their parameters (e.g., @code{.}).
2107:
2108: @item
2109: If there is a convention on the order of parameters (e.g., from
2110: mathematics or another programming language), stick with it (e.g.,
2111: @code{-}).
2112:
2113: @item
2114: If one parameter usually requires only a short computation (e.g., it is
2115: a constant), pass it on the top of the stack. Conversely, parameters
2116: that usually require a long sequence of code to compute should be passed
2117: as the bottom (i.e., first) parameter. This makes the code easier to
2118: read, because reader does not need to keep track of the bottom item
2119: through a long sequence of code (or, alternatively, through stack
1.49 anton 2120: manipulations). E.g., @code{!} (store, @pxref{Memory}) expects the
1.48 anton 2121: address on top of the stack because it is usually simpler to compute
2122: than the stored value (often the address is just a variable).
2123:
2124: @item
2125: Similarly, results that are usually consumed quickly should be returned
2126: on the top of stack, whereas a result that is often used in long
2127: computations should be passed as bottom result. E.g., the file words
2128: like @code{open-file} return the error code on the top of stack, because
2129: it is usually consumed quickly by @code{throw}; moreover, the error code
2130: has to be checked before doing anything with the other results.
2131:
2132: @end itemize
2133:
2134: These rules are just general guidelines, don't lose sight of the overall
2135: goal to make the words easy to use. E.g., if the convention rule
2136: conflicts with the computation-length rule, you might decide in favour
2137: of the convention if the word will be used rarely, and in favour of the
2138: computation-length rule if the word will be used frequently (because
2139: with frequent use the cost of breaking the computation-length rule would
2140: be quite high, and frequent use makes it easier to remember an
2141: unconventional order).
2142:
2143: @c example !! structure package
2144:
1.65 anton 2145:
1.48 anton 2146: @node Local Variables Tutorial, Conditional execution Tutorial, Designing the stack effect Tutorial, Tutorial
2147: @section Local Variables
1.66 anton 2148: @cindex local variables, tutorial
1.48 anton 2149:
2150: You can define local variables (@emph{locals}) in a colon definition:
2151:
2152: @example
2153: : swap @{ a b -- b a @}
2154: b a ;
2155: 1 2 swap .s 2drop
2156: @end example
2157:
2158: (If your Forth system does not support this syntax, include
2159: @file{compat/anslocals.fs} first).
2160:
2161: In this example @code{@{ a b -- b a @}} is the locals definition; it
2162: takes two cells from the stack, puts the top of stack in @code{b} and
2163: the next stack element in @code{a}. @code{--} starts a comment ending
2164: with @code{@}}. After the locals definition, using the name of the
2165: local will push its value on the stack. You can leave the comment
2166: part (@code{-- b a}) away:
2167:
2168: @example
2169: : swap ( x1 x2 -- x2 x1 )
2170: @{ a b @} b a ;
2171: @end example
2172:
2173: In Gforth you can have several locals definitions, anywhere in a colon
2174: definition; in contrast, in a standard program you can have only one
2175: locals definition per colon definition, and that locals definition must
2176: be outside any controll structure.
2177:
2178: With locals you can write slightly longer definitions without running
2179: into stack trouble. However, I recommend trying to write colon
2180: definitions without locals for exercise purposes to help you gain the
2181: essential factoring skills.
2182:
2183: @assignment
2184: Rewrite your definitions until now with locals
2185: @endassignment
2186:
1.66 anton 2187: Reference: @ref{Locals}.
2188:
1.48 anton 2189:
2190: @node Conditional execution Tutorial, Flags and Comparisons Tutorial, Local Variables Tutorial, Tutorial
2191: @section Conditional execution
1.66 anton 2192: @cindex conditionals, tutorial
2193: @cindex if, tutorial
1.48 anton 2194:
2195: In Forth you can use control structures only inside colon definitions.
2196: An @code{if}-structure looks like this:
2197:
2198: @example
2199: : abs ( n1 -- +n2 )
2200: dup 0 < if
2201: negate
2202: endif ;
2203: 5 abs .
2204: -5 abs .
2205: @end example
2206:
2207: @code{if} takes a flag from the stack. If the flag is non-zero (true),
2208: the following code is performed, otherwise execution continues after the
1.51 pazsan 2209: @code{endif} (or @code{else}). @code{<} compares the top two stack
1.48 anton 2210: elements and prioduces a flag:
2211:
2212: @example
2213: 1 2 < .
2214: 2 1 < .
2215: 1 1 < .
2216: @end example
2217:
2218: Actually the standard name for @code{endif} is @code{then}. This
2219: tutorial presents the examples using @code{endif}, because this is often
2220: less confusing for people familiar with other programming languages
2221: where @code{then} has a different meaning. If your system does not have
2222: @code{endif}, define it with
2223:
2224: @example
2225: : endif postpone then ; immediate
2226: @end example
2227:
2228: You can optionally use an @code{else}-part:
2229:
2230: @example
2231: : min ( n1 n2 -- n )
2232: 2dup < if
2233: drop
2234: else
2235: nip
2236: endif ;
2237: 2 3 min .
2238: 3 2 min .
2239: @end example
2240:
2241: @assignment
2242: Write @code{min} without @code{else}-part (hint: what's the definition
2243: of @code{nip}?).
2244: @endassignment
2245:
1.66 anton 2246: Reference: @ref{Selection}.
2247:
1.48 anton 2248:
2249: @node Flags and Comparisons Tutorial, General Loops Tutorial, Conditional execution Tutorial, Tutorial
2250: @section Flags and Comparisons
1.66 anton 2251: @cindex flags tutorial
2252: @cindex comparison tutorial
1.48 anton 2253:
2254: In a false-flag all bits are clear (0 when interpreted as integer). In
2255: a canonical true-flag all bits are set (-1 as a twos-complement signed
2256: integer); in many contexts (e.g., @code{if}) any non-zero value is
2257: treated as true flag.
2258:
2259: @example
2260: false .
2261: true .
2262: true hex u. decimal
2263: @end example
2264:
2265: Comparison words produce canonical flags:
2266:
2267: @example
2268: 1 1 = .
2269: 1 0= .
2270: 0 1 < .
2271: 0 0 < .
2272: -1 1 u< . \ type error, u< interprets -1 as large unsigned number
2273: -1 1 < .
2274: @end example
2275:
1.66 anton 2276: Gforth supports all combinations of the prefixes @code{0 u d d0 du f f0}
2277: (or none) and the comparisons @code{= <> < > <= >=}. Only a part of
2278: these combinations are standard (for details see the standard,
2279: @ref{Numeric comparison}, @ref{Floating Point} or @ref{Word Index}).
1.48 anton 2280:
2281: You can use @code{and or xor invert} can be used as operations on
2282: canonical flags. Actually they are bitwise operations:
2283:
2284: @example
2285: 1 2 and .
2286: 1 2 or .
2287: 1 3 xor .
2288: 1 invert .
2289: @end example
2290:
2291: You can convert a zero/non-zero flag into a canonical flag with
2292: @code{0<>} (and complement it on the way with @code{0=}).
2293:
2294: @example
2295: 1 0= .
2296: 1 0<> .
2297: @end example
2298:
1.65 anton 2299: You can use the all-bits-set feature of canonical flags and the bitwise
1.48 anton 2300: operation of the Boolean operations to avoid @code{if}s:
2301:
2302: @example
2303: : foo ( n1 -- n2 )
2304: 0= if
2305: 14
2306: else
2307: 0
2308: endif ;
2309: 0 foo .
2310: 1 foo .
2311:
2312: : foo ( n1 -- n2 )
2313: 0= 14 and ;
2314: 0 foo .
2315: 1 foo .
2316: @end example
2317:
2318: @assignment
2319: Write @code{min} without @code{if}.
2320: @endassignment
2321:
1.66 anton 2322: For reference, see @ref{Boolean Flags}, @ref{Numeric comparison}, and
2323: @ref{Bitwise operations}.
2324:
1.48 anton 2325:
2326: @node General Loops Tutorial, Counted loops Tutorial, Flags and Comparisons Tutorial, Tutorial
2327: @section General Loops
1.66 anton 2328: @cindex loops, indefinite, tutorial
1.48 anton 2329:
2330: The endless loop is the most simple one:
2331:
2332: @example
2333: : endless ( -- )
2334: 0 begin
2335: dup . 1+
2336: again ;
2337: endless
2338: @end example
2339:
2340: Terminate this loop by pressing @kbd{Ctrl-C} (in Gforth). @code{begin}
2341: does nothing at run-time, @code{again} jumps back to @code{begin}.
2342:
2343: A loop with one exit at any place looks like this:
2344:
2345: @example
2346: : log2 ( +n1 -- n2 )
2347: \ logarithmus dualis of n1>0, rounded down to the next integer
2348: assert( dup 0> )
2349: 2/ 0 begin
2350: over 0> while
2351: 1+ swap 2/ swap
2352: repeat
2353: nip ;
2354: 7 log2 .
2355: 8 log2 .
2356: @end example
2357:
2358: At run-time @code{while} consumes a flag; if it is 0, execution
1.51 pazsan 2359: continues behind the @code{repeat}; if the flag is non-zero, execution
1.48 anton 2360: continues behind the @code{while}. @code{Repeat} jumps back to
2361: @code{begin}, just like @code{again}.
2362:
2363: In Forth there are many combinations/abbreviations, like @code{1+}.
1.90 anton 2364: However, @code{2/} is not one of them; it shifts its argument right by
1.48 anton 2365: one bit (arithmetic shift right):
2366:
2367: @example
2368: -5 2 / .
2369: -5 2/ .
2370: @end example
2371:
2372: @code{assert(} is no standard word, but you can get it on systems other
2373: then Gforth by including @file{compat/assert.fs}. You can see what it
2374: does by trying
2375:
2376: @example
2377: 0 log2 .
2378: @end example
2379:
2380: Here's a loop with an exit at the end:
2381:
2382: @example
2383: : log2 ( +n1 -- n2 )
2384: \ logarithmus dualis of n1>0, rounded down to the next integer
2385: assert( dup 0 > )
2386: -1 begin
2387: 1+ swap 2/ swap
2388: over 0 <=
2389: until
2390: nip ;
2391: @end example
2392:
2393: @code{Until} consumes a flag; if it is non-zero, execution continues at
2394: the @code{begin}, otherwise after the @code{until}.
2395:
2396: @assignment
2397: Write a definition for computing the greatest common divisor.
2398: @endassignment
2399:
1.66 anton 2400: Reference: @ref{Simple Loops}.
2401:
1.48 anton 2402:
2403: @node Counted loops Tutorial, Recursion Tutorial, General Loops Tutorial, Tutorial
2404: @section Counted loops
1.66 anton 2405: @cindex loops, counted, tutorial
1.48 anton 2406:
2407: @example
2408: : ^ ( n1 u -- n )
2409: \ n = the uth power of u1
2410: 1 swap 0 u+do
2411: over *
2412: loop
2413: nip ;
2414: 3 2 ^ .
2415: 4 3 ^ .
2416: @end example
2417:
2418: @code{U+do} (from @file{compat/loops.fs}, if your Forth system doesn't
2419: have it) takes two numbers of the stack @code{( u3 u4 -- )}, and then
2420: performs the code between @code{u+do} and @code{loop} for @code{u3-u4}
2421: times (or not at all, if @code{u3-u4<0}).
2422:
2423: You can see the stack effect design rules at work in the stack effect of
2424: the loop start words: Since the start value of the loop is more
2425: frequently constant than the end value, the start value is passed on
2426: the top-of-stack.
2427:
2428: You can access the counter of a counted loop with @code{i}:
2429:
2430: @example
2431: : fac ( u -- u! )
2432: 1 swap 1+ 1 u+do
2433: i *
2434: loop ;
2435: 5 fac .
2436: 7 fac .
2437: @end example
2438:
2439: There is also @code{+do}, which expects signed numbers (important for
2440: deciding whether to enter the loop).
2441:
2442: @assignment
2443: Write a definition for computing the nth Fibonacci number.
2444: @endassignment
2445:
1.65 anton 2446: You can also use increments other than 1:
2447:
2448: @example
2449: : up2 ( n1 n2 -- )
2450: +do
2451: i .
2452: 2 +loop ;
2453: 10 0 up2
2454:
2455: : down2 ( n1 n2 -- )
2456: -do
2457: i .
2458: 2 -loop ;
2459: 0 10 down2
2460: @end example
1.48 anton 2461:
1.66 anton 2462: Reference: @ref{Counted Loops}.
2463:
1.48 anton 2464:
2465: @node Recursion Tutorial, Leaving definitions or loops Tutorial, Counted loops Tutorial, Tutorial
2466: @section Recursion
1.66 anton 2467: @cindex recursion tutorial
1.48 anton 2468:
2469: Usually the name of a definition is not visible in the definition; but
2470: earlier definitions are usually visible:
2471:
2472: @example
2473: 1 0 / . \ "Floating-point unidentified fault" in Gforth on most platforms
2474: : / ( n1 n2 -- n )
2475: dup 0= if
2476: -10 throw \ report division by zero
2477: endif
2478: / \ old version
2479: ;
2480: 1 0 /
2481: @end example
2482:
2483: For recursive definitions you can use @code{recursive} (non-standard) or
2484: @code{recurse}:
2485:
2486: @example
2487: : fac1 ( n -- n! ) recursive
2488: dup 0> if
2489: dup 1- fac1 *
2490: else
2491: drop 1
2492: endif ;
2493: 7 fac1 .
2494:
2495: : fac2 ( n -- n! )
2496: dup 0> if
2497: dup 1- recurse *
2498: else
2499: drop 1
2500: endif ;
2501: 8 fac2 .
2502: @end example
2503:
2504: @assignment
2505: Write a recursive definition for computing the nth Fibonacci number.
2506: @endassignment
2507:
1.66 anton 2508: Reference (including indirect recursion): @xref{Calls and returns}.
2509:
1.48 anton 2510:
2511: @node Leaving definitions or loops Tutorial, Return Stack Tutorial, Recursion Tutorial, Tutorial
2512: @section Leaving definitions or loops
1.66 anton 2513: @cindex leaving definitions, tutorial
2514: @cindex leaving loops, tutorial
1.48 anton 2515:
2516: @code{EXIT} exits the current definition right away. For every counted
2517: loop that is left in this way, an @code{UNLOOP} has to be performed
2518: before the @code{EXIT}:
2519:
2520: @c !! real examples
2521: @example
2522: : ...
2523: ... u+do
2524: ... if
2525: ... unloop exit
2526: endif
2527: ...
2528: loop
2529: ... ;
2530: @end example
2531:
2532: @code{LEAVE} leaves the innermost counted loop right away:
2533:
2534: @example
2535: : ...
2536: ... u+do
2537: ... if
2538: ... leave
2539: endif
2540: ...
2541: loop
2542: ... ;
2543: @end example
2544:
1.65 anton 2545: @c !! example
1.48 anton 2546:
1.66 anton 2547: Reference: @ref{Calls and returns}, @ref{Counted Loops}.
2548:
2549:
1.48 anton 2550: @node Return Stack Tutorial, Memory Tutorial, Leaving definitions or loops Tutorial, Tutorial
2551: @section Return Stack
1.66 anton 2552: @cindex return stack tutorial
1.48 anton 2553:
2554: In addition to the data stack Forth also has a second stack, the return
2555: stack; most Forth systems store the return addresses of procedure calls
2556: there (thus its name). Programmers can also use this stack:
2557:
2558: @example
2559: : foo ( n1 n2 -- )
2560: .s
2561: >r .s
1.50 anton 2562: r@@ .
1.48 anton 2563: >r .s
1.50 anton 2564: r@@ .
1.48 anton 2565: r> .
1.50 anton 2566: r@@ .
1.48 anton 2567: r> . ;
2568: 1 2 foo
2569: @end example
2570:
2571: @code{>r} takes an element from the data stack and pushes it onto the
2572: return stack; conversely, @code{r>} moves an elementm from the return to
2573: the data stack; @code{r@@} pushes a copy of the top of the return stack
2574: on the return stack.
2575:
2576: Forth programmers usually use the return stack for storing data
2577: temporarily, if using the data stack alone would be too complex, and
2578: factoring and locals are not an option:
2579:
2580: @example
2581: : 2swap ( x1 x2 x3 x4 -- x3 x4 x1 x2 )
2582: rot >r rot r> ;
2583: @end example
2584:
2585: The return address of the definition and the loop control parameters of
2586: counted loops usually reside on the return stack, so you have to take
2587: all items, that you have pushed on the return stack in a colon
2588: definition or counted loop, from the return stack before the definition
2589: or loop ends. You cannot access items that you pushed on the return
2590: stack outside some definition or loop within the definition of loop.
2591:
2592: If you miscount the return stack items, this usually ends in a crash:
2593:
2594: @example
2595: : crash ( n -- )
2596: >r ;
2597: 5 crash
2598: @end example
2599:
2600: You cannot mix using locals and using the return stack (according to the
2601: standard; Gforth has no problem). However, they solve the same
2602: problems, so this shouldn't be an issue.
2603:
2604: @assignment
2605: Can you rewrite any of the definitions you wrote until now in a better
2606: way using the return stack?
2607: @endassignment
2608:
1.66 anton 2609: Reference: @ref{Return stack}.
2610:
1.48 anton 2611:
2612: @node Memory Tutorial, Characters and Strings Tutorial, Return Stack Tutorial, Tutorial
2613: @section Memory
1.66 anton 2614: @cindex memory access/allocation tutorial
1.48 anton 2615:
2616: You can create a global variable @code{v} with
2617:
2618: @example
2619: variable v ( -- addr )
2620: @end example
2621:
2622: @code{v} pushes the address of a cell in memory on the stack. This cell
2623: was reserved by @code{variable}. You can use @code{!} (store) to store
2624: values into this cell and @code{@@} (fetch) to load the value from the
2625: stack into memory:
2626:
2627: @example
2628: v .
2629: 5 v ! .s
1.50 anton 2630: v @@ .
1.48 anton 2631: @end example
2632:
1.65 anton 2633: You can see a raw dump of memory with @code{dump}:
2634:
2635: @example
2636: v 1 cells .s dump
2637: @end example
2638:
2639: @code{Cells ( n1 -- n2 )} gives you the number of bytes (or, more
2640: generally, address units (aus)) that @code{n1 cells} occupy. You can
2641: also reserve more memory:
1.48 anton 2642:
2643: @example
2644: create v2 20 cells allot
1.65 anton 2645: v2 20 cells dump
1.48 anton 2646: @end example
2647:
1.65 anton 2648: creates a word @code{v2} and reserves 20 uninitialized cells; the
2649: address pushed by @code{v2} points to the start of these 20 cells. You
2650: can use address arithmetic to access these cells:
1.48 anton 2651:
2652: @example
2653: 3 v2 5 cells + !
1.65 anton 2654: v2 20 cells dump
1.48 anton 2655: @end example
2656:
2657: You can reserve and initialize memory with @code{,}:
2658:
2659: @example
2660: create v3
2661: 5 , 4 , 3 , 2 , 1 ,
1.50 anton 2662: v3 @@ .
2663: v3 cell+ @@ .
2664: v3 2 cells + @@ .
1.65 anton 2665: v3 5 cells dump
1.48 anton 2666: @end example
2667:
2668: @assignment
2669: Write a definition @code{vsum ( addr u -- n )} that computes the sum of
2670: @code{u} cells, with the first of these cells at @code{addr}, the next
2671: one at @code{addr cell+} etc.
2672: @endassignment
2673:
2674: You can also reserve memory without creating a new word:
2675:
2676: @example
1.60 anton 2677: here 10 cells allot .
2678: here .
1.48 anton 2679: @end example
2680:
2681: @code{Here} pushes the start address of the memory area. You should
2682: store it somewhere, or you will have a hard time finding the memory area
2683: again.
2684:
2685: @code{Allot} manages dictionary memory. The dictionary memory contains
2686: the system's data structures for words etc. on Gforth and most other
2687: Forth systems. It is managed like a stack: You can free the memory that
2688: you have just @code{allot}ed with
2689:
2690: @example
2691: -10 cells allot
1.60 anton 2692: here .
1.48 anton 2693: @end example
2694:
2695: Note that you cannot do this if you have created a new word in the
2696: meantime (because then your @code{allot}ed memory is no longer on the
2697: top of the dictionary ``stack'').
2698:
2699: Alternatively, you can use @code{allocate} and @code{free} which allow
2700: freeing memory in any order:
2701:
2702: @example
2703: 10 cells allocate throw .s
2704: 20 cells allocate throw .s
2705: swap
2706: free throw
2707: free throw
2708: @end example
2709:
2710: The @code{throw}s deal with errors (e.g., out of memory).
2711:
1.65 anton 2712: And there is also a
2713: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
2714: garbage collector}, which eliminates the need to @code{free} memory
2715: explicitly.
1.48 anton 2716:
1.66 anton 2717: Reference: @ref{Memory}.
2718:
1.48 anton 2719:
2720: @node Characters and Strings Tutorial, Alignment Tutorial, Memory Tutorial, Tutorial
2721: @section Characters and Strings
1.66 anton 2722: @cindex strings tutorial
2723: @cindex characters tutorial
1.48 anton 2724:
2725: On the stack characters take up a cell, like numbers. In memory they
2726: have their own size (one 8-bit byte on most systems), and therefore
2727: require their own words for memory access:
2728:
2729: @example
2730: create v4
2731: 104 c, 97 c, 108 c, 108 c, 111 c,
1.50 anton 2732: v4 4 chars + c@@ .
1.65 anton 2733: v4 5 chars dump
1.48 anton 2734: @end example
2735:
2736: The preferred representation of strings on the stack is @code{addr
2737: u-count}, where @code{addr} is the address of the first character and
2738: @code{u-count} is the number of characters in the string.
2739:
2740: @example
2741: v4 5 type
2742: @end example
2743:
2744: You get a string constant with
2745:
2746: @example
2747: s" hello, world" .s
2748: type
2749: @end example
2750:
2751: Make sure you have a space between @code{s"} and the string; @code{s"}
2752: is a normal Forth word and must be delimited with white space (try what
2753: happens when you remove the space).
2754:
2755: However, this interpretive use of @code{s"} is quite restricted: the
2756: string exists only until the next call of @code{s"} (some Forth systems
2757: keep more than one of these strings, but usually they still have a
1.62 crook 2758: limited lifetime).
1.48 anton 2759:
2760: @example
2761: s" hello," s" world" .s
2762: type
2763: type
2764: @end example
2765:
1.62 crook 2766: You can also use @code{s"} in a definition, and the resulting
2767: strings then live forever (well, for as long as the definition):
1.48 anton 2768:
2769: @example
2770: : foo s" hello," s" world" ;
2771: foo .s
2772: type
2773: type
2774: @end example
2775:
2776: @assignment
2777: @code{Emit ( c -- )} types @code{c} as character (not a number).
2778: Implement @code{type ( addr u -- )}.
2779: @endassignment
2780:
1.66 anton 2781: Reference: @ref{Memory Blocks}.
2782:
2783:
1.84 pazsan 2784: @node Alignment Tutorial, Files Tutorial, Characters and Strings Tutorial, Tutorial
1.48 anton 2785: @section Alignment
1.66 anton 2786: @cindex alignment tutorial
2787: @cindex memory alignment tutorial
1.48 anton 2788:
2789: On many processors cells have to be aligned in memory, if you want to
2790: access them with @code{@@} and @code{!} (and even if the processor does
1.62 crook 2791: not require alignment, access to aligned cells is faster).
1.48 anton 2792:
2793: @code{Create} aligns @code{here} (i.e., the place where the next
2794: allocation will occur, and that the @code{create}d word points to).
2795: Likewise, the memory produced by @code{allocate} starts at an aligned
2796: address. Adding a number of @code{cells} to an aligned address produces
2797: another aligned address.
2798:
2799: However, address arithmetic involving @code{char+} and @code{chars} can
2800: create an address that is not cell-aligned. @code{Aligned ( addr --
2801: a-addr )} produces the next aligned address:
2802:
2803: @example
1.50 anton 2804: v3 char+ aligned .s @@ .
2805: v3 char+ .s @@ .
1.48 anton 2806: @end example
2807:
2808: Similarly, @code{align} advances @code{here} to the next aligned
2809: address:
2810:
2811: @example
2812: create v5 97 c,
2813: here .
2814: align here .
2815: 1000 ,
2816: @end example
2817:
2818: Note that you should use aligned addresses even if your processor does
2819: not require them, if you want your program to be portable.
2820:
1.66 anton 2821: Reference: @ref{Address arithmetic}.
2822:
1.48 anton 2823:
1.84 pazsan 2824: @node Files Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Alignment Tutorial, Tutorial
2825: @section Files
2826: @cindex files tutorial
2827:
2828: This section gives a short introduction into how to use files inside
2829: Forth. It's broken up into five easy steps:
2830:
2831: @enumerate 1
2832: @item Opened an ASCII text file for input
2833: @item Opened a file for output
2834: @item Read input file until string matched (or some other condition matched)
2835: @item Wrote some lines from input ( modified or not) to output
2836: @item Closed the files.
2837: @end enumerate
2838:
2839: @subsection Open file for input
2840:
2841: @example
2842: s" foo.in" r/o open-file throw Value fd-in
2843: @end example
2844:
2845: @subsection Create file for output
2846:
2847: @example
2848: s" foo.out" w/o create-file throw Value fd-out
2849: @end example
2850:
2851: The available file modes are r/o for read-only access, r/w for
2852: read-write access, and w/o for write-only access. You could open both
2853: files with r/w, too, if you like. All file words return error codes; for
2854: most applications, it's best to pass there error codes with @code{throw}
2855: to the outer error handler.
2856:
2857: If you want words for opening and assigning, define them as follows:
2858:
2859: @example
2860: 0 Value fd-in
2861: 0 Value fd-out
2862: : open-input ( addr u -- ) r/o open-file throw to fd-in ;
2863: : open-output ( addr u -- ) w/o create-file throw to fd-out ;
2864: @end example
2865:
2866: Usage example:
2867:
2868: @example
2869: s" foo.in" open-input
2870: s" foo.out" open-output
2871: @end example
2872:
2873: @subsection Scan file for a particular line
2874:
2875: @example
2876: 256 Constant max-line
2877: Create line-buffer max-line 2 + allot
2878:
2879: : scan-file ( addr u -- )
2880: begin
2881: line-buffer max-line fd-in read-line throw
2882: while
2883: >r 2dup line-buffer r> compare 0=
2884: until
2885: else
2886: drop
2887: then
2888: 2drop ;
2889: @end example
2890:
2891: @code{read-line ( addr u1 fd -- u2 flag ior )} reads up to u1 bytes into
1.94 anton 2892: the buffer at addr, and returns the number of bytes read, a flag that is
2893: false when the end of file is reached, and an error code.
1.84 pazsan 2894:
2895: @code{compare ( addr1 u1 addr2 u2 -- n )} compares two strings and
2896: returns zero if both strings are equal. It returns a positive number if
2897: the first string is lexically greater, a negative if the second string
2898: is lexically greater.
2899:
2900: We haven't seen this loop here; it has two exits. Since the @code{while}
2901: exits with the number of bytes read on the stack, we have to clean up
2902: that separately; that's after the @code{else}.
2903:
2904: Usage example:
2905:
2906: @example
2907: s" The text I search is here" scan-file
2908: @end example
2909:
2910: @subsection Copy input to output
2911:
2912: @example
2913: : copy-file ( -- )
2914: begin
2915: line-buffer max-line fd-in read-line throw
2916: while
2917: line-buffer swap fd-out write-file throw
2918: repeat ;
2919: @end example
2920:
2921: @subsection Close files
2922:
2923: @example
2924: fd-in close-file throw
2925: fd-out close-file throw
2926: @end example
2927:
2928: Likewise, you can put that into definitions, too:
2929:
2930: @example
2931: : close-input ( -- ) fd-in close-file throw ;
2932: : close-output ( -- ) fd-out close-file throw ;
2933: @end example
2934:
2935: @assignment
2936: How could you modify @code{copy-file} so that it copies until a second line is
2937: matched? Can you write a program that extracts a section of a text file,
2938: given the line that starts and the line that terminates that section?
2939: @endassignment
2940:
2941: @node Interpretation and Compilation Semantics and Immediacy Tutorial, Execution Tokens Tutorial, Files Tutorial, Tutorial
1.48 anton 2942: @section Interpretation and Compilation Semantics and Immediacy
1.66 anton 2943: @cindex semantics tutorial
2944: @cindex interpretation semantics tutorial
2945: @cindex compilation semantics tutorial
2946: @cindex immediate, tutorial
1.48 anton 2947:
2948: When a word is compiled, it behaves differently from being interpreted.
2949: E.g., consider @code{+}:
2950:
2951: @example
2952: 1 2 + .
2953: : foo + ;
2954: @end example
2955:
2956: These two behaviours are known as compilation and interpretation
2957: semantics. For normal words (e.g., @code{+}), the compilation semantics
2958: is to append the interpretation semantics to the currently defined word
2959: (@code{foo} in the example above). I.e., when @code{foo} is executed
2960: later, the interpretation semantics of @code{+} (i.e., adding two
2961: numbers) will be performed.
2962:
2963: However, there are words with non-default compilation semantics, e.g.,
2964: the control-flow words like @code{if}. You can use @code{immediate} to
2965: change the compilation semantics of the last defined word to be equal to
2966: the interpretation semantics:
2967:
2968: @example
2969: : [FOO] ( -- )
2970: 5 . ; immediate
2971:
2972: [FOO]
2973: : bar ( -- )
2974: [FOO] ;
2975: bar
2976: see bar
2977: @end example
2978:
2979: Two conventions to mark words with non-default compilation semnatics are
2980: names with brackets (more frequently used) and to write them all in
2981: upper case (less frequently used).
2982:
2983: In Gforth (and many other systems) you can also remove the
2984: interpretation semantics with @code{compile-only} (the compilation
2985: semantics is derived from the original interpretation semantics):
2986:
2987: @example
2988: : flip ( -- )
2989: 6 . ; compile-only \ but not immediate
2990: flip
2991:
2992: : flop ( -- )
2993: flip ;
2994: flop
2995: @end example
2996:
2997: In this example the interpretation semantics of @code{flop} is equal to
2998: the original interpretation semantics of @code{flip}.
2999:
3000: The text interpreter has two states: in interpret state, it performs the
3001: interpretation semantics of words it encounters; in compile state, it
3002: performs the compilation semantics of these words.
3003:
3004: Among other things, @code{:} switches into compile state, and @code{;}
3005: switches back to interpret state. They contain the factors @code{]}
3006: (switch to compile state) and @code{[} (switch to interpret state), that
3007: do nothing but switch the state.
3008:
3009: @example
3010: : xxx ( -- )
3011: [ 5 . ]
3012: ;
3013:
3014: xxx
3015: see xxx
3016: @end example
3017:
3018: These brackets are also the source of the naming convention mentioned
3019: above.
3020:
1.66 anton 3021: Reference: @ref{Interpretation and Compilation Semantics}.
3022:
1.48 anton 3023:
3024: @node Execution Tokens Tutorial, Exceptions Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Tutorial
3025: @section Execution Tokens
1.66 anton 3026: @cindex execution tokens tutorial
3027: @cindex XT tutorial
1.48 anton 3028:
3029: @code{' word} gives you the execution token (XT) of a word. The XT is a
3030: cell representing the interpretation semantics of a word. You can
3031: execute this semantics with @code{execute}:
3032:
3033: @example
3034: ' + .s
3035: 1 2 rot execute .
3036: @end example
3037:
3038: The XT is similar to a function pointer in C. However, parameter
3039: passing through the stack makes it a little more flexible:
3040:
3041: @example
3042: : map-array ( ... addr u xt -- ... )
1.50 anton 3043: \ executes xt ( ... x -- ... ) for every element of the array starting
3044: \ at addr and containing u elements
1.48 anton 3045: @{ xt @}
3046: cells over + swap ?do
1.50 anton 3047: i @@ xt execute
1.48 anton 3048: 1 cells +loop ;
3049:
3050: create a 3 , 4 , 2 , -1 , 4 ,
3051: a 5 ' . map-array .s
3052: 0 a 5 ' + map-array .
3053: s" max-n" environment? drop .s
3054: a 5 ' min map-array .
3055: @end example
3056:
3057: You can use map-array with the XTs of words that consume one element
3058: more than they produce. In theory you can also use it with other XTs,
3059: but the stack effect then depends on the size of the array, which is
3060: hard to understand.
3061:
1.51 pazsan 3062: Since XTs are cell-sized, you can store them in memory and manipulate
3063: them on the stack like other cells. You can also compile the XT into a
1.48 anton 3064: word with @code{compile,}:
3065:
3066: @example
3067: : foo1 ( n1 n2 -- n )
3068: [ ' + compile, ] ;
3069: see foo
3070: @end example
3071:
3072: This is non-standard, because @code{compile,} has no compilation
3073: semantics in the standard, but it works in good Forth systems. For the
3074: broken ones, use
3075:
3076: @example
3077: : [compile,] compile, ; immediate
3078:
3079: : foo1 ( n1 n2 -- n )
3080: [ ' + ] [compile,] ;
3081: see foo
3082: @end example
3083:
3084: @code{'} is a word with default compilation semantics; it parses the
3085: next word when its interpretation semantics are executed, not during
3086: compilation:
3087:
3088: @example
3089: : foo ( -- xt )
3090: ' ;
3091: see foo
3092: : bar ( ... "word" -- ... )
3093: ' execute ;
3094: see bar
1.60 anton 3095: 1 2 bar + .
1.48 anton 3096: @end example
3097:
3098: You often want to parse a word during compilation and compile its XT so
3099: it will be pushed on the stack at run-time. @code{[']} does this:
3100:
3101: @example
3102: : xt-+ ( -- xt )
3103: ['] + ;
3104: see xt-+
3105: 1 2 xt-+ execute .
3106: @end example
3107:
3108: Many programmers tend to see @code{'} and the word it parses as one
3109: unit, and expect it to behave like @code{[']} when compiled, and are
3110: confused by the actual behaviour. If you are, just remember that the
3111: Forth system just takes @code{'} as one unit and has no idea that it is
3112: a parsing word (attempts to convenience programmers in this issue have
3113: usually resulted in even worse pitfalls, see
1.66 anton 3114: @uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,
3115: @code{State}-smartness---Why it is evil and How to Exorcise it}).
1.48 anton 3116:
3117: Note that the state of the interpreter does not come into play when
1.51 pazsan 3118: creating and executing XTs. I.e., even when you execute @code{'} in
1.48 anton 3119: compile state, it still gives you the interpretation semantics. And
3120: whatever that state is, @code{execute} performs the semantics
1.66 anton 3121: represented by the XT (i.e., for XTs produced with @code{'} the
3122: interpretation semantics).
3123:
3124: Reference: @ref{Tokens for Words}.
1.48 anton 3125:
3126:
3127: @node Exceptions Tutorial, Defining Words Tutorial, Execution Tokens Tutorial, Tutorial
3128: @section Exceptions
1.66 anton 3129: @cindex exceptions tutorial
1.48 anton 3130:
3131: @code{throw ( n -- )} causes an exception unless n is zero.
3132:
3133: @example
3134: 100 throw .s
3135: 0 throw .s
3136: @end example
3137:
3138: @code{catch ( ... xt -- ... n )} behaves similar to @code{execute}, but
3139: it catches exceptions and pushes the number of the exception on the
3140: stack (or 0, if the xt executed without exception). If there was an
3141: exception, the stacks have the same depth as when entering @code{catch}:
3142:
3143: @example
3144: .s
3145: 3 0 ' / catch .s
3146: 3 2 ' / catch .s
3147: @end example
3148:
3149: @assignment
3150: Try the same with @code{execute} instead of @code{catch}.
3151: @endassignment
3152:
3153: @code{Throw} always jumps to the dynamically next enclosing
3154: @code{catch}, even if it has to leave several call levels to achieve
3155: this:
3156:
3157: @example
3158: : foo 100 throw ;
3159: : foo1 foo ." after foo" ;
1.51 pazsan 3160: : bar ['] foo1 catch ;
1.60 anton 3161: bar .
1.48 anton 3162: @end example
3163:
3164: It is often important to restore a value upon leaving a definition, even
3165: if the definition is left through an exception. You can ensure this
3166: like this:
3167:
3168: @example
3169: : ...
3170: save-x
1.51 pazsan 3171: ['] word-changing-x catch ( ... n )
1.48 anton 3172: restore-x
3173: ( ... n ) throw ;
3174: @end example
3175:
1.55 anton 3176: Gforth provides an alternative syntax in addition to @code{catch}:
1.48 anton 3177: @code{try ... recover ... endtry}. If the code between @code{try} and
3178: @code{recover} has an exception, the stack depths are restored, the
3179: exception number is pushed on the stack, and the code between
3180: @code{recover} and @code{endtry} is performed. E.g., the definition for
3181: @code{catch} is
3182:
3183: @example
3184: : catch ( x1 .. xn xt -- y1 .. ym 0 / z1 .. zn error ) \ exception
3185: try
3186: execute 0
3187: recover
3188: nip
3189: endtry ;
3190: @end example
3191:
3192: The equivalent to the restoration code above is
3193:
3194: @example
3195: : ...
3196: save-x
3197: try
1.92 anton 3198: word-changing-x 0
3199: recover endtry
1.48 anton 3200: restore-x
3201: throw ;
3202: @end example
3203:
1.92 anton 3204: This works if @code{word-changing-x} does not change the stack depth,
3205: otherwise you should add some code between @code{recover} and
3206: @code{endtry} to balance the stack.
1.48 anton 3207:
1.66 anton 3208: Reference: @ref{Exception Handling}.
3209:
1.48 anton 3210:
3211: @node Defining Words Tutorial, Arrays and Records Tutorial, Exceptions Tutorial, Tutorial
3212: @section Defining Words
1.66 anton 3213: @cindex defining words tutorial
3214: @cindex does> tutorial
3215: @cindex create...does> tutorial
3216:
3217: @c before semantics?
1.48 anton 3218:
3219: @code{:}, @code{create}, and @code{variable} are definition words: They
3220: define other words. @code{Constant} is another definition word:
3221:
3222: @example
3223: 5 constant foo
3224: foo .
3225: @end example
3226:
3227: You can also use the prefixes @code{2} (double-cell) and @code{f}
3228: (floating point) with @code{variable} and @code{constant}.
3229:
3230: You can also define your own defining words. E.g.:
3231:
3232: @example
3233: : variable ( "name" -- )
3234: create 0 , ;
3235: @end example
3236:
3237: You can also define defining words that create words that do something
3238: other than just producing their address:
3239:
3240: @example
3241: : constant ( n "name" -- )
3242: create ,
3243: does> ( -- n )
1.50 anton 3244: ( addr ) @@ ;
1.48 anton 3245:
3246: 5 constant foo
3247: foo .
3248: @end example
3249:
3250: The definition of @code{constant} above ends at the @code{does>}; i.e.,
3251: @code{does>} replaces @code{;}, but it also does something else: It
3252: changes the last defined word such that it pushes the address of the
3253: body of the word and then performs the code after the @code{does>}
3254: whenever it is called.
3255:
3256: In the example above, @code{constant} uses @code{,} to store 5 into the
3257: body of @code{foo}. When @code{foo} executes, it pushes the address of
3258: the body onto the stack, then (in the code after the @code{does>})
3259: fetches the 5 from there.
3260:
3261: The stack comment near the @code{does>} reflects the stack effect of the
3262: defined word, not the stack effect of the code after the @code{does>}
3263: (the difference is that the code expects the address of the body that
3264: the stack comment does not show).
3265:
3266: You can use these definition words to do factoring in cases that involve
3267: (other) definition words. E.g., a field offset is always added to an
3268: address. Instead of defining
3269:
3270: @example
3271: 2 cells constant offset-field1
3272: @end example
3273:
3274: and using this like
3275:
3276: @example
3277: ( addr ) offset-field1 +
3278: @end example
3279:
3280: you can define a definition word
3281:
3282: @example
3283: : simple-field ( n "name" -- )
3284: create ,
3285: does> ( n1 -- n1+n )
1.50 anton 3286: ( addr ) @@ + ;
1.48 anton 3287: @end example
1.21 crook 3288:
1.48 anton 3289: Definition and use of field offsets now look like this:
1.21 crook 3290:
1.48 anton 3291: @example
3292: 2 cells simple-field field1
1.60 anton 3293: create mystruct 4 cells allot
3294: mystruct .s field1 .s drop
1.48 anton 3295: @end example
1.21 crook 3296:
1.48 anton 3297: If you want to do something with the word without performing the code
3298: after the @code{does>}, you can access the body of a @code{create}d word
3299: with @code{>body ( xt -- addr )}:
1.21 crook 3300:
1.48 anton 3301: @example
3302: : value ( n "name" -- )
3303: create ,
3304: does> ( -- n1 )
1.50 anton 3305: @@ ;
1.48 anton 3306: : to ( n "name" -- )
3307: ' >body ! ;
1.21 crook 3308:
1.48 anton 3309: 5 value foo
3310: foo .
3311: 7 to foo
3312: foo .
3313: @end example
1.21 crook 3314:
1.48 anton 3315: @assignment
3316: Define @code{defer ( "name" -- )}, which creates a word that stores an
3317: XT (at the start the XT of @code{abort}), and upon execution
3318: @code{execute}s the XT. Define @code{is ( xt "name" -- )} that stores
3319: @code{xt} into @code{name}, a word defined with @code{defer}. Indirect
3320: recursion is one application of @code{defer}.
3321: @endassignment
1.29 crook 3322:
1.66 anton 3323: Reference: @ref{User-defined Defining Words}.
3324:
3325:
1.48 anton 3326: @node Arrays and Records Tutorial, POSTPONE Tutorial, Defining Words Tutorial, Tutorial
3327: @section Arrays and Records
1.66 anton 3328: @cindex arrays tutorial
3329: @cindex records tutorial
3330: @cindex structs tutorial
1.29 crook 3331:
1.48 anton 3332: Forth has no standard words for defining data structures such as arrays
3333: and records (structs in C terminology), but you can build them yourself
3334: based on address arithmetic. You can also define words for defining
3335: arrays and records (@pxref{Defining Words Tutorial,, Defining Words}).
1.29 crook 3336:
1.48 anton 3337: One of the first projects a Forth newcomer sets out upon when learning
3338: about defining words is an array defining word (possibly for
3339: n-dimensional arrays). Go ahead and do it, I did it, too; you will
3340: learn something from it. However, don't be disappointed when you later
3341: learn that you have little use for these words (inappropriate use would
3342: be even worse). I have not yet found a set of useful array words yet;
3343: the needs are just too diverse, and named, global arrays (the result of
3344: naive use of defining words) are often not flexible enough (e.g.,
1.66 anton 3345: consider how to pass them as parameters). Another such project is a set
3346: of words to help dealing with strings.
1.29 crook 3347:
1.48 anton 3348: On the other hand, there is a useful set of record words, and it has
3349: been defined in @file{compat/struct.fs}; these words are predefined in
3350: Gforth. They are explained in depth elsewhere in this manual (see
3351: @pxref{Structures}). The @code{simple-field} example above is
3352: simplified variant of fields in this package.
1.21 crook 3353:
3354:
1.48 anton 3355: @node POSTPONE Tutorial, Literal Tutorial, Arrays and Records Tutorial, Tutorial
3356: @section @code{POSTPONE}
1.66 anton 3357: @cindex postpone tutorial
1.21 crook 3358:
1.48 anton 3359: You can compile the compilation semantics (instead of compiling the
3360: interpretation semantics) of a word with @code{POSTPONE}:
1.21 crook 3361:
1.48 anton 3362: @example
3363: : MY-+ ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
1.51 pazsan 3364: POSTPONE + ; immediate
1.48 anton 3365: : foo ( n1 n2 -- n )
3366: MY-+ ;
3367: 1 2 foo .
3368: see foo
3369: @end example
1.21 crook 3370:
1.48 anton 3371: During the definition of @code{foo} the text interpreter performs the
3372: compilation semantics of @code{MY-+}, which performs the compilation
3373: semantics of @code{+}, i.e., it compiles @code{+} into @code{foo}.
3374:
3375: This example also displays separate stack comments for the compilation
3376: semantics and for the stack effect of the compiled code. For words with
3377: default compilation semantics these stack effects are usually not
3378: displayed; the stack effect of the compilation semantics is always
3379: @code{( -- )} for these words, the stack effect for the compiled code is
3380: the stack effect of the interpretation semantics.
3381:
3382: Note that the state of the interpreter does not come into play when
3383: performing the compilation semantics in this way. You can also perform
3384: it interpretively, e.g.:
3385:
3386: @example
3387: : foo2 ( n1 n2 -- n )
3388: [ MY-+ ] ;
3389: 1 2 foo .
3390: see foo
3391: @end example
1.21 crook 3392:
1.48 anton 3393: However, there are some broken Forth systems where this does not always
1.62 crook 3394: work, and therefore this practice was been declared non-standard in
1.48 anton 3395: 1999.
3396: @c !! repair.fs
3397:
3398: Here is another example for using @code{POSTPONE}:
1.44 crook 3399:
1.48 anton 3400: @example
3401: : MY-- ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
3402: POSTPONE negate POSTPONE + ; immediate compile-only
3403: : bar ( n1 n2 -- n )
3404: MY-- ;
3405: 2 1 bar .
3406: see bar
3407: @end example
1.21 crook 3408:
1.48 anton 3409: You can define @code{ENDIF} in this way:
1.21 crook 3410:
1.48 anton 3411: @example
3412: : ENDIF ( Compilation: orig -- )
3413: POSTPONE then ; immediate
3414: @end example
1.21 crook 3415:
1.48 anton 3416: @assignment
3417: Write @code{MY-2DUP} that has compilation semantics equivalent to
3418: @code{2dup}, but compiles @code{over over}.
3419: @endassignment
1.29 crook 3420:
1.66 anton 3421: @c !! @xref{Macros} for reference
3422:
3423:
1.48 anton 3424: @node Literal Tutorial, Advanced macros Tutorial, POSTPONE Tutorial, Tutorial
3425: @section @code{Literal}
1.66 anton 3426: @cindex literal tutorial
1.29 crook 3427:
1.48 anton 3428: You cannot @code{POSTPONE} numbers:
1.21 crook 3429:
1.48 anton 3430: @example
3431: : [FOO] POSTPONE 500 ; immediate
1.21 crook 3432: @end example
3433:
1.48 anton 3434: Instead, you can use @code{LITERAL (compilation: n --; run-time: -- n )}:
1.29 crook 3435:
1.48 anton 3436: @example
3437: : [FOO] ( compilation: --; run-time: -- n )
3438: 500 POSTPONE literal ; immediate
1.29 crook 3439:
1.60 anton 3440: : flip [FOO] ;
1.48 anton 3441: flip .
3442: see flip
3443: @end example
1.29 crook 3444:
1.48 anton 3445: @code{LITERAL} consumes a number at compile-time (when it's compilation
3446: semantics are executed) and pushes it at run-time (when the code it
3447: compiled is executed). A frequent use of @code{LITERAL} is to compile a
3448: number computed at compile time into the current word:
1.29 crook 3449:
1.48 anton 3450: @example
3451: : bar ( -- n )
3452: [ 2 2 + ] literal ;
3453: see bar
3454: @end example
1.29 crook 3455:
1.48 anton 3456: @assignment
3457: Write @code{]L} which allows writing the example above as @code{: bar (
3458: -- n ) [ 2 2 + ]L ;}
3459: @endassignment
3460:
1.66 anton 3461: @c !! @xref{Macros} for reference
3462:
1.48 anton 3463:
3464: @node Advanced macros Tutorial, Compilation Tokens Tutorial, Literal Tutorial, Tutorial
3465: @section Advanced macros
1.66 anton 3466: @cindex macros, advanced tutorial
3467: @cindex run-time code generation, tutorial
1.48 anton 3468:
1.66 anton 3469: Reconsider @code{map-array} from @ref{Execution Tokens Tutorial,,
3470: Execution Tokens}. It frequently performs @code{execute}, a relatively
3471: expensive operation in some Forth implementations. You can use
1.48 anton 3472: @code{compile,} and @code{POSTPONE} to eliminate these @code{execute}s
3473: and produce a word that contains the word to be performed directly:
3474:
3475: @c use ]] ... [[
3476: @example
3477: : compile-map-array ( compilation: xt -- ; run-time: ... addr u -- ... )
3478: \ at run-time, execute xt ( ... x -- ... ) for each element of the
3479: \ array beginning at addr and containing u elements
3480: @{ xt @}
3481: POSTPONE cells POSTPONE over POSTPONE + POSTPONE swap POSTPONE ?do
1.50 anton 3482: POSTPONE i POSTPONE @@ xt compile,
1.48 anton 3483: 1 cells POSTPONE literal POSTPONE +loop ;
3484:
3485: : sum-array ( addr u -- n )
3486: 0 rot rot [ ' + compile-map-array ] ;
3487: see sum-array
3488: a 5 sum-array .
3489: @end example
3490:
3491: You can use the full power of Forth for generating the code; here's an
3492: example where the code is generated in a loop:
3493:
3494: @example
3495: : compile-vmul-step ( compilation: n --; run-time: n1 addr1 -- n2 addr2 )
3496: \ n2=n1+(addr1)*n, addr2=addr1+cell
1.50 anton 3497: POSTPONE tuck POSTPONE @@
1.48 anton 3498: POSTPONE literal POSTPONE * POSTPONE +
3499: POSTPONE swap POSTPONE cell+ ;
3500:
3501: : compile-vmul ( compilation: addr1 u -- ; run-time: addr2 -- n )
1.51 pazsan 3502: \ n=v1*v2 (inner product), where the v_i are represented as addr_i u
1.48 anton 3503: 0 postpone literal postpone swap
3504: [ ' compile-vmul-step compile-map-array ]
3505: postpone drop ;
3506: see compile-vmul
3507:
3508: : a-vmul ( addr -- n )
1.51 pazsan 3509: \ n=a*v, where v is a vector that's as long as a and starts at addr
1.48 anton 3510: [ a 5 compile-vmul ] ;
3511: see a-vmul
3512: a a-vmul .
3513: @end example
3514:
3515: This example uses @code{compile-map-array} to show off, but you could
1.66 anton 3516: also use @code{map-array} instead (try it now!).
1.48 anton 3517:
3518: You can use this technique for efficient multiplication of large
3519: matrices. In matrix multiplication, you multiply every line of one
3520: matrix with every column of the other matrix. You can generate the code
3521: for one line once, and use it for every column. The only downside of
3522: this technique is that it is cumbersome to recover the memory consumed
3523: by the generated code when you are done (and in more complicated cases
3524: it is not possible portably).
3525:
1.66 anton 3526: @c !! @xref{Macros} for reference
3527:
3528:
1.48 anton 3529: @node Compilation Tokens Tutorial, Wordlists and Search Order Tutorial, Advanced macros Tutorial, Tutorial
3530: @section Compilation Tokens
1.66 anton 3531: @cindex compilation tokens, tutorial
3532: @cindex CT, tutorial
1.48 anton 3533:
3534: This section is Gforth-specific. You can skip it.
3535:
3536: @code{' word compile,} compiles the interpretation semantics. For words
3537: with default compilation semantics this is the same as performing the
3538: compilation semantics. To represent the compilation semantics of other
3539: words (e.g., words like @code{if} that have no interpretation
3540: semantics), Gforth has the concept of a compilation token (CT,
3541: consisting of two cells), and words @code{comp'} and @code{[comp']}.
3542: You can perform the compilation semantics represented by a CT with
3543: @code{execute}:
1.29 crook 3544:
1.48 anton 3545: @example
3546: : foo2 ( n1 n2 -- n )
3547: [ comp' + execute ] ;
3548: see foo
3549: @end example
1.29 crook 3550:
1.48 anton 3551: You can compile the compilation semantics represented by a CT with
3552: @code{postpone,}:
1.30 anton 3553:
1.48 anton 3554: @example
3555: : foo3 ( -- )
3556: [ comp' + postpone, ] ;
3557: see foo3
3558: @end example
1.30 anton 3559:
1.51 pazsan 3560: @code{[ comp' word postpone, ]} is equivalent to @code{POSTPONE word}.
1.48 anton 3561: @code{comp'} is particularly useful for words that have no
3562: interpretation semantics:
1.29 crook 3563:
1.30 anton 3564: @example
1.48 anton 3565: ' if
1.60 anton 3566: comp' if .s 2drop
1.30 anton 3567: @end example
3568:
1.66 anton 3569: Reference: @ref{Tokens for Words}.
3570:
1.29 crook 3571:
1.48 anton 3572: @node Wordlists and Search Order Tutorial, , Compilation Tokens Tutorial, Tutorial
3573: @section Wordlists and Search Order
1.66 anton 3574: @cindex wordlists tutorial
3575: @cindex search order, tutorial
1.48 anton 3576:
3577: The dictionary is not just a memory area that allows you to allocate
3578: memory with @code{allot}, it also contains the Forth words, arranged in
3579: several wordlists. When searching for a word in a wordlist,
3580: conceptually you start searching at the youngest and proceed towards
3581: older words (in reality most systems nowadays use hash-tables); i.e., if
3582: you define a word with the same name as an older word, the new word
3583: shadows the older word.
3584:
3585: Which wordlists are searched in which order is determined by the search
3586: order. You can display the search order with @code{order}. It displays
3587: first the search order, starting with the wordlist searched first, then
3588: it displays the wordlist that will contain newly defined words.
1.21 crook 3589:
1.48 anton 3590: You can create a new, empty wordlist with @code{wordlist ( -- wid )}:
1.21 crook 3591:
1.48 anton 3592: @example
3593: wordlist constant mywords
3594: @end example
1.21 crook 3595:
1.48 anton 3596: @code{Set-current ( wid -- )} sets the wordlist that will contain newly
3597: defined words (the @emph{current} wordlist):
1.21 crook 3598:
1.48 anton 3599: @example
3600: mywords set-current
3601: order
3602: @end example
1.26 crook 3603:
1.48 anton 3604: Gforth does not display a name for the wordlist in @code{mywords}
3605: because this wordlist was created anonymously with @code{wordlist}.
1.21 crook 3606:
1.48 anton 3607: You can get the current wordlist with @code{get-current ( -- wid)}. If
3608: you want to put something into a specific wordlist without overall
3609: effect on the current wordlist, this typically looks like this:
1.21 crook 3610:
1.48 anton 3611: @example
3612: get-current mywords set-current ( wid )
3613: create someword
3614: ( wid ) set-current
3615: @end example
1.21 crook 3616:
1.48 anton 3617: You can write the search order with @code{set-order ( wid1 .. widn n --
3618: )} and read it with @code{get-order ( -- wid1 .. widn n )}. The first
3619: searched wordlist is topmost.
1.21 crook 3620:
1.48 anton 3621: @example
3622: get-order mywords swap 1+ set-order
3623: order
3624: @end example
1.21 crook 3625:
1.48 anton 3626: Yes, the order of wordlists in the output of @code{order} is reversed
3627: from stack comments and the output of @code{.s} and thus unintuitive.
1.21 crook 3628:
1.48 anton 3629: @assignment
3630: Define @code{>order ( wid -- )} with adds @code{wid} as first searched
3631: wordlist to the search order. Define @code{previous ( -- )}, which
3632: removes the first searched wordlist from the search order. Experiment
3633: with boundary conditions (you will see some crashes or situations that
3634: are hard or impossible to leave).
3635: @endassignment
1.21 crook 3636:
1.48 anton 3637: The search order is a powerful foundation for providing features similar
3638: to Modula-2 modules and C++ namespaces. However, trying to modularize
3639: programs in this way has disadvantages for debugging and reuse/factoring
3640: that overcome the advantages in my experience (I don't do huge projects,
1.55 anton 3641: though). These disadvantages are not so clear in other
1.82 anton 3642: languages/programming environments, because these languages are not so
1.48 anton 3643: strong in debugging and reuse.
1.21 crook 3644:
1.66 anton 3645: @c !! example
3646:
3647: Reference: @ref{Word Lists}.
1.21 crook 3648:
1.29 crook 3649: @c ******************************************************************
1.48 anton 3650: @node Introduction, Words, Tutorial, Top
1.29 crook 3651: @comment node-name, next, previous, up
3652: @chapter An Introduction to ANS Forth
3653: @cindex Forth - an introduction
1.21 crook 3654:
1.83 anton 3655: The difference of this chapter from the Tutorial (@pxref{Tutorial}) is
3656: that it is slower-paced in its examples, but uses them to dive deep into
3657: explaining Forth internals (not covered by the Tutorial). Apart from
3658: that, this chapter covers far less material. It is suitable for reading
3659: without using a computer.
3660:
1.29 crook 3661: The primary purpose of this manual is to document Gforth. However, since
3662: Forth is not a widely-known language and there is a lack of up-to-date
3663: teaching material, it seems worthwhile to provide some introductory
1.49 anton 3664: material. For other sources of Forth-related
3665: information, see @ref{Forth-related information}.
1.21 crook 3666:
1.29 crook 3667: The examples in this section should work on any ANS Forth; the
3668: output shown was produced using Gforth. Each example attempts to
3669: reproduce the exact output that Gforth produces. If you try out the
3670: examples (and you should), what you should type is shown @kbd{like this}
3671: and Gforth's response is shown @code{like this}. The single exception is
1.30 anton 3672: that, where the example shows @key{RET} it means that you should
1.29 crook 3673: press the ``carriage return'' key. Unfortunately, some output formats for
3674: this manual cannot show the difference between @kbd{this} and
3675: @code{this} which will make trying out the examples harder (but not
3676: impossible).
1.21 crook 3677:
1.29 crook 3678: Forth is an unusual language. It provides an interactive development
3679: environment which includes both an interpreter and compiler. Forth
3680: programming style encourages you to break a problem down into many
3681: @cindex factoring
3682: small fragments (@dfn{factoring}), and then to develop and test each
3683: fragment interactively. Forth advocates assert that breaking the
3684: edit-compile-test cycle used by conventional programming languages can
3685: lead to great productivity improvements.
1.21 crook 3686:
1.29 crook 3687: @menu
1.67 anton 3688: * Introducing the Text Interpreter::
3689: * Stacks and Postfix notation::
3690: * Your first definition::
3691: * How does that work?::
3692: * Forth is written in Forth::
3693: * Review - elements of a Forth system::
3694: * Where to go next::
3695: * Exercises::
1.29 crook 3696: @end menu
1.21 crook 3697:
1.29 crook 3698: @comment ----------------------------------------------
3699: @node Introducing the Text Interpreter, Stacks and Postfix notation, Introduction, Introduction
3700: @section Introducing the Text Interpreter
3701: @cindex text interpreter
3702: @cindex outer interpreter
1.21 crook 3703:
1.30 anton 3704: @c IMO this is too detailed and the pace is too slow for
3705: @c an introduction. If you know German, take a look at
3706: @c http://www.complang.tuwien.ac.at/anton/lvas/skriptum-stack.html
3707: @c to see how I do it - anton
3708:
1.44 crook 3709: @c nac-> Where I have accepted your comments 100% and modified the text
3710: @c accordingly, I have deleted your comments. Elsewhere I have added a
3711: @c response like this to attempt to rationalise what I have done. Of
3712: @c course, this is a very clumsy mechanism for something that would be
3713: @c done far more efficiently over a beer. Please delete any dialogue
3714: @c you consider closed.
3715:
1.29 crook 3716: When you invoke the Forth image, you will see a startup banner printed
3717: and nothing else (if you have Gforth installed on your system, try
1.30 anton 3718: invoking it now, by typing @kbd{gforth@key{RET}}). Forth is now running
1.29 crook 3719: its command line interpreter, which is called the @dfn{Text Interpreter}
3720: (also known as the @dfn{Outer Interpreter}). (You will learn a lot
1.49 anton 3721: about the text interpreter as you read through this chapter, for more
3722: detail @pxref{The Text Interpreter}).
1.21 crook 3723:
1.29 crook 3724: Although it's not obvious, Forth is actually waiting for your
1.30 anton 3725: input. Type a number and press the @key{RET} key:
1.21 crook 3726:
1.26 crook 3727: @example
1.30 anton 3728: @kbd{45@key{RET}} ok
1.26 crook 3729: @end example
1.21 crook 3730:
1.29 crook 3731: Rather than give you a prompt to invite you to input something, the text
3732: interpreter prints a status message @i{after} it has processed a line
3733: of input. The status message in this case (``@code{ ok}'' followed by
3734: carriage-return) indicates that the text interpreter was able to process
3735: all of your input successfully. Now type something illegal:
3736:
3737: @example
1.30 anton 3738: @kbd{qwer341@key{RET}}
1.29 crook 3739: :1: Undefined word
3740: qwer341
3741: ^^^^^^^
3742: $400D2BA8 Bounce
3743: $400DBDA8 no.extensions
3744: @end example
1.23 crook 3745:
1.29 crook 3746: The exact text, other than the ``Undefined word'' may differ slightly on
3747: your system, but the effect is the same; when the text interpreter
3748: detects an error, it discards any remaining text on a line, resets
1.49 anton 3749: certain internal state and prints an error message. For a detailed description of error messages see @ref{Error
3750: messages}.
1.23 crook 3751:
1.29 crook 3752: The text interpreter waits for you to press carriage-return, and then
3753: processes your input line. Starting at the beginning of the line, it
3754: breaks the line into groups of characters separated by spaces. For each
3755: group of characters in turn, it makes two attempts to do something:
1.23 crook 3756:
1.29 crook 3757: @itemize @bullet
3758: @item
1.44 crook 3759: @cindex name dictionary
1.29 crook 3760: It tries to treat it as a command. It does this by searching a @dfn{name
3761: dictionary}. If the group of characters matches an entry in the name
3762: dictionary, the name dictionary provides the text interpreter with
3763: information that allows the text interpreter perform some actions. In
3764: Forth jargon, we say that the group
3765: @cindex word
3766: @cindex definition
3767: @cindex execution token
3768: @cindex xt
3769: of characters names a @dfn{word}, that the dictionary search returns an
3770: @dfn{execution token (xt)} corresponding to the @dfn{definition} of the
3771: word, and that the text interpreter executes the xt. Often, the terms
3772: @dfn{word} and @dfn{definition} are used interchangeably.
3773: @item
3774: If the text interpreter fails to find a match in the name dictionary, it
3775: tries to treat the group of characters as a number in the current number
3776: base (when you start up Forth, the current number base is base 10). If
3777: the group of characters legitimately represents a number, the text
3778: interpreter pushes the number onto a stack (we'll learn more about that
3779: in the next section).
3780: @end itemize
1.23 crook 3781:
1.29 crook 3782: If the text interpreter is unable to do either of these things with any
3783: group of characters, it discards the group of characters and the rest of
3784: the line, then prints an error message. If the text interpreter reaches
3785: the end of the line without error, it prints the status message ``@code{ ok}''
3786: followed by carriage-return.
1.21 crook 3787:
1.29 crook 3788: This is the simplest command we can give to the text interpreter:
1.23 crook 3789:
3790: @example
1.30 anton 3791: @key{RET} ok
1.23 crook 3792: @end example
1.21 crook 3793:
1.29 crook 3794: The text interpreter did everything we asked it to do (nothing) without
3795: an error, so it said that everything is ``@code{ ok}''. Try a slightly longer
3796: command:
1.21 crook 3797:
1.23 crook 3798: @example
1.30 anton 3799: @kbd{12 dup fred dup@key{RET}}
1.29 crook 3800: :1: Undefined word
3801: 12 dup fred dup
3802: ^^^^
3803: $400D2BA8 Bounce
3804: $400DBDA8 no.extensions
1.23 crook 3805: @end example
1.21 crook 3806:
1.29 crook 3807: When you press the carriage-return key, the text interpreter starts to
3808: work its way along the line:
1.21 crook 3809:
1.29 crook 3810: @itemize @bullet
3811: @item
3812: When it gets to the space after the @code{2}, it takes the group of
3813: characters @code{12} and looks them up in the name
3814: dictionary@footnote{We can't tell if it found them or not, but assume
3815: for now that it did not}. There is no match for this group of characters
3816: in the name dictionary, so it tries to treat them as a number. It is
3817: able to do this successfully, so it puts the number, 12, ``on the stack''
3818: (whatever that means).
3819: @item
3820: The text interpreter resumes scanning the line and gets the next group
3821: of characters, @code{dup}. It looks it up in the name dictionary and
3822: (you'll have to take my word for this) finds it, and executes the word
3823: @code{dup} (whatever that means).
3824: @item
3825: Once again, the text interpreter resumes scanning the line and gets the
3826: group of characters @code{fred}. It looks them up in the name
3827: dictionary, but can't find them. It tries to treat them as a number, but
3828: they don't represent any legal number.
3829: @end itemize
1.21 crook 3830:
1.29 crook 3831: At this point, the text interpreter gives up and prints an error
3832: message. The error message shows exactly how far the text interpreter
3833: got in processing the line. In particular, it shows that the text
3834: interpreter made no attempt to do anything with the final character
3835: group, @code{dup}, even though we have good reason to believe that the
3836: text interpreter would have no problem looking that word up and
3837: executing it a second time.
1.21 crook 3838:
3839:
1.29 crook 3840: @comment ----------------------------------------------
3841: @node Stacks and Postfix notation, Your first definition, Introducing the Text Interpreter, Introduction
3842: @section Stacks, postfix notation and parameter passing
3843: @cindex text interpreter
3844: @cindex outer interpreter
1.21 crook 3845:
1.29 crook 3846: In procedural programming languages (like C and Pascal), the
3847: building-block of programs is the @dfn{function} or @dfn{procedure}. These
3848: functions or procedures are called with @dfn{explicit parameters}. For
3849: example, in C we might write:
1.21 crook 3850:
1.23 crook 3851: @example
1.29 crook 3852: total = total + new_volume(length,height,depth);
1.23 crook 3853: @end example
1.21 crook 3854:
1.23 crook 3855: @noindent
1.29 crook 3856: where new_volume is a function-call to another piece of code, and total,
3857: length, height and depth are all variables. length, height and depth are
3858: parameters to the function-call.
1.21 crook 3859:
1.29 crook 3860: In Forth, the equivalent of the function or procedure is the
3861: @dfn{definition} and parameters are implicitly passed between
3862: definitions using a shared stack that is visible to the
3863: programmer. Although Forth does support variables, the existence of the
3864: stack means that they are used far less often than in most other
3865: programming languages. When the text interpreter encounters a number, it
3866: will place (@dfn{push}) it on the stack. There are several stacks (the
1.30 anton 3867: actual number is implementation-dependent ...) and the particular stack
1.29 crook 3868: used for any operation is implied unambiguously by the operation being
3869: performed. The stack used for all integer operations is called the @dfn{data
3870: stack} and, since this is the stack used most commonly, references to
3871: ``the data stack'' are often abbreviated to ``the stack''.
1.21 crook 3872:
1.29 crook 3873: The stacks have a last-in, first-out (LIFO) organisation. If you type:
1.21 crook 3874:
1.23 crook 3875: @example
1.30 anton 3876: @kbd{1 2 3@key{RET}} ok
1.23 crook 3877: @end example
1.21 crook 3878:
1.29 crook 3879: Then this instructs the text interpreter to placed three numbers on the
3880: (data) stack. An analogy for the behaviour of the stack is to take a
3881: pack of playing cards and deal out the ace (1), 2 and 3 into a pile on
3882: the table. The 3 was the last card onto the pile (``last-in'') and if
3883: you take a card off the pile then, unless you're prepared to fiddle a
3884: bit, the card that you take off will be the 3 (``first-out''). The
3885: number that will be first-out of the stack is called the @dfn{top of
3886: stack}, which
3887: @cindex TOS definition
3888: is often abbreviated to @dfn{TOS}.
1.21 crook 3889:
1.29 crook 3890: To understand how parameters are passed in Forth, consider the
3891: behaviour of the definition @code{+} (pronounced ``plus''). You will not
3892: be surprised to learn that this definition performs addition. More
3893: precisely, it adds two number together and produces a result. Where does
3894: it get the two numbers from? It takes the top two numbers off the
3895: stack. Where does it place the result? On the stack. You can act-out the
3896: behaviour of @code{+} with your playing cards like this:
1.21 crook 3897:
3898: @itemize @bullet
3899: @item
1.29 crook 3900: Pick up two cards from the stack on the table
1.21 crook 3901: @item
1.29 crook 3902: Stare at them intently and ask yourself ``what @i{is} the sum of these two
3903: numbers''
1.21 crook 3904: @item
1.29 crook 3905: Decide that the answer is 5
1.21 crook 3906: @item
1.29 crook 3907: Shuffle the two cards back into the pack and find a 5
1.21 crook 3908: @item
1.29 crook 3909: Put a 5 on the remaining ace that's on the table.
1.21 crook 3910: @end itemize
3911:
1.29 crook 3912: If you don't have a pack of cards handy but you do have Forth running,
3913: you can use the definition @code{.s} to show the current state of the stack,
3914: without affecting the stack. Type:
1.21 crook 3915:
3916: @example
1.30 anton 3917: @kbd{clearstack 1 2 3@key{RET}} ok
3918: @kbd{.s@key{RET}} <3> 1 2 3 ok
1.23 crook 3919: @end example
3920:
1.29 crook 3921: The text interpreter looks up the word @code{clearstack} and executes
3922: it; it tidies up the stack and removes any entries that may have been
3923: left on it by earlier examples. The text interpreter pushes each of the
3924: three numbers in turn onto the stack. Finally, the text interpreter
3925: looks up the word @code{.s} and executes it. The effect of executing
3926: @code{.s} is to print the ``<3>'' (the total number of items on the stack)
3927: followed by a list of all the items on the stack; the item on the far
3928: right-hand side is the TOS.
1.21 crook 3929:
1.29 crook 3930: You can now type:
1.21 crook 3931:
1.29 crook 3932: @example
1.30 anton 3933: @kbd{+ .s@key{RET}} <2> 1 5 ok
1.29 crook 3934: @end example
1.21 crook 3935:
1.29 crook 3936: @noindent
3937: which is correct; there are now 2 items on the stack and the result of
3938: the addition is 5.
1.23 crook 3939:
1.29 crook 3940: If you're playing with cards, try doing a second addition: pick up the
3941: two cards, work out that their sum is 6, shuffle them into the pack,
3942: look for a 6 and place that on the table. You now have just one item on
3943: the stack. What happens if you try to do a third addition? Pick up the
3944: first card, pick up the second card -- ah! There is no second card. This
3945: is called a @dfn{stack underflow} and consitutes an error. If you try to
1.95 anton 3946: do the same thing with Forth it often reports an error (probably a Stack
1.29 crook 3947: Underflow or an Invalid Memory Address error).
1.23 crook 3948:
1.29 crook 3949: The opposite situation to a stack underflow is a @dfn{stack overflow},
3950: which simply accepts that there is a finite amount of storage space
3951: reserved for the stack. To stretch the playing card analogy, if you had
3952: enough packs of cards and you piled the cards up on the table, you would
3953: eventually be unable to add another card; you'd hit the ceiling. Gforth
3954: allows you to set the maximum size of the stacks. In general, the only
3955: time that you will get a stack overflow is because a definition has a
3956: bug in it and is generating data on the stack uncontrollably.
1.23 crook 3957:
1.29 crook 3958: There's one final use for the playing card analogy. If you model your
3959: stack using a pack of playing cards, the maximum number of items on
3960: your stack will be 52 (I assume you didn't use the Joker). The maximum
3961: @i{value} of any item on the stack is 13 (the King). In fact, the only
3962: possible numbers are positive integer numbers 1 through 13; you can't
3963: have (for example) 0 or 27 or 3.52 or -2. If you change the way you
3964: think about some of the cards, you can accommodate different
3965: numbers. For example, you could think of the Jack as representing 0,
3966: the Queen as representing -1 and the King as representing -2. Your
1.45 crook 3967: @i{range} remains unchanged (you can still only represent a total of 13
1.29 crook 3968: numbers) but the numbers that you can represent are -2 through 10.
1.28 crook 3969:
1.29 crook 3970: In that analogy, the limit was the amount of information that a single
3971: stack entry could hold, and Forth has a similar limit. In Forth, the
3972: size of a stack entry is called a @dfn{cell}. The actual size of a cell is
3973: implementation dependent and affects the maximum value that a stack
3974: entry can hold. A Standard Forth provides a cell size of at least
3975: 16-bits, and most desktop systems use a cell size of 32-bits.
1.21 crook 3976:
1.29 crook 3977: Forth does not do any type checking for you, so you are free to
3978: manipulate and combine stack items in any way you wish. A convenient way
3979: of treating stack items is as 2's complement signed integers, and that
3980: is what Standard words like @code{+} do. Therefore you can type:
1.21 crook 3981:
1.29 crook 3982: @example
1.30 anton 3983: @kbd{-5 12 + .s@key{RET}} <1> 7 ok
1.29 crook 3984: @end example
1.21 crook 3985:
1.29 crook 3986: If you use numbers and definitions like @code{+} in order to turn Forth
3987: into a great big pocket calculator, you will realise that it's rather
3988: different from a normal calculator. Rather than typing 2 + 3 = you had
3989: to type 2 3 + (ignore the fact that you had to use @code{.s} to see the
3990: result). The terminology used to describe this difference is to say that
3991: your calculator uses @dfn{Infix Notation} (parameters and operators are
3992: mixed) whilst Forth uses @dfn{Postfix Notation} (parameters and
3993: operators are separate), also called @dfn{Reverse Polish Notation}.
1.21 crook 3994:
1.29 crook 3995: Whilst postfix notation might look confusing to begin with, it has
3996: several important advantages:
1.21 crook 3997:
1.23 crook 3998: @itemize @bullet
3999: @item
1.29 crook 4000: it is unambiguous
1.23 crook 4001: @item
1.29 crook 4002: it is more concise
1.23 crook 4003: @item
1.29 crook 4004: it fits naturally with a stack-based system
1.23 crook 4005: @end itemize
1.21 crook 4006:
1.29 crook 4007: To examine these claims in more detail, consider these sums:
1.21 crook 4008:
1.29 crook 4009: @example
4010: 6 + 5 * 4 =
4011: 4 * 5 + 6 =
4012: @end example
1.21 crook 4013:
1.29 crook 4014: If you're just learning maths or your maths is very rusty, you will
4015: probably come up with the answer 44 for the first and 26 for the
4016: second. If you are a bit of a whizz at maths you will remember the
4017: @i{convention} that multiplication takes precendence over addition, and
4018: you'd come up with the answer 26 both times. To explain the answer 26
4019: to someone who got the answer 44, you'd probably rewrite the first sum
4020: like this:
1.21 crook 4021:
1.29 crook 4022: @example
4023: 6 + (5 * 4) =
4024: @end example
1.21 crook 4025:
1.29 crook 4026: If what you really wanted was to perform the addition before the
4027: multiplication, you would have to use parentheses to force it.
1.21 crook 4028:
1.29 crook 4029: If you did the first two sums on a pocket calculator you would probably
4030: get the right answers, unless you were very cautious and entered them using
4031: these keystroke sequences:
1.21 crook 4032:
1.29 crook 4033: 6 + 5 = * 4 =
4034: 4 * 5 = + 6 =
1.21 crook 4035:
1.29 crook 4036: Postfix notation is unambiguous because the order that the operators
4037: are applied is always explicit; that also means that parentheses are
4038: never required. The operators are @i{active} (the act of quoting the
4039: operator makes the operation occur) which removes the need for ``=''.
1.28 crook 4040:
1.29 crook 4041: The sum 6 + 5 * 4 can be written (in postfix notation) in two
4042: equivalent ways:
1.26 crook 4043:
4044: @example
1.29 crook 4045: 6 5 4 * + or:
4046: 5 4 * 6 +
1.26 crook 4047: @end example
1.23 crook 4048:
1.29 crook 4049: An important thing that you should notice about this notation is that
4050: the @i{order} of the numbers does not change; if you want to subtract
4051: 2 from 10 you type @code{10 2 -}.
1.1 anton 4052:
1.29 crook 4053: The reason that Forth uses postfix notation is very simple to explain: it
4054: makes the implementation extremely simple, and it follows naturally from
4055: using the stack as a mechanism for passing parameters. Another way of
4056: thinking about this is to realise that all Forth definitions are
4057: @i{active}; they execute as they are encountered by the text
4058: interpreter. The result of this is that the syntax of Forth is trivially
4059: simple.
1.1 anton 4060:
4061:
4062:
1.29 crook 4063: @comment ----------------------------------------------
4064: @node Your first definition, How does that work?, Stacks and Postfix notation, Introduction
4065: @section Your first Forth definition
4066: @cindex first definition
1.1 anton 4067:
1.29 crook 4068: Until now, the examples we've seen have been trivial; we've just been
4069: using Forth as a bigger-than-pocket calculator. Also, each calculation
4070: we've shown has been a ``one-off'' -- to repeat it we'd need to type it in
4071: again@footnote{That's not quite true. If you press the up-arrow key on
4072: your keyboard you should be able to scroll back to any earlier command,
4073: edit it and re-enter it.} In this section we'll see how to add new
4074: words to Forth's vocabulary.
1.1 anton 4075:
1.29 crook 4076: The easiest way to create a new word is to use a @dfn{colon
4077: definition}. We'll define a few and try them out before worrying too
4078: much about how they work. Try typing in these examples; be careful to
4079: copy the spaces accurately:
1.1 anton 4080:
1.29 crook 4081: @example
4082: : add-two 2 + . ;
4083: : greet ." Hello and welcome" ;
4084: : demo 5 add-two ;
4085: @end example
1.1 anton 4086:
1.29 crook 4087: @noindent
4088: Now try them out:
1.1 anton 4089:
1.29 crook 4090: @example
1.30 anton 4091: @kbd{greet@key{RET}} Hello and welcome ok
4092: @kbd{greet greet@key{RET}} Hello and welcomeHello and welcome ok
4093: @kbd{4 add-two@key{RET}} 6 ok
4094: @kbd{demo@key{RET}} 7 ok
4095: @kbd{9 greet demo add-two@key{RET}} Hello and welcome7 11 ok
1.29 crook 4096: @end example
1.1 anton 4097:
1.29 crook 4098: The first new thing that we've introduced here is the pair of words
4099: @code{:} and @code{;}. These are used to start and terminate a new
4100: definition, respectively. The first word after the @code{:} is the name
4101: for the new definition.
1.1 anton 4102:
1.29 crook 4103: As you can see from the examples, a definition is built up of words that
4104: have already been defined; Forth makes no distinction between
4105: definitions that existed when you started the system up, and those that
4106: you define yourself.
1.1 anton 4107:
1.29 crook 4108: The examples also introduce the words @code{.} (dot), @code{."}
4109: (dot-quote) and @code{dup} (dewp). Dot takes the value from the top of
4110: the stack and displays it. It's like @code{.s} except that it only
4111: displays the top item of the stack and it is destructive; after it has
4112: executed, the number is no longer on the stack. There is always one
4113: space printed after the number, and no spaces before it. Dot-quote
4114: defines a string (a sequence of characters) that will be printed when
4115: the word is executed. The string can contain any printable characters
4116: except @code{"}. A @code{"} has a special function; it is not a Forth
4117: word but it acts as a delimiter (the way that delimiters work is
4118: described in the next section). Finally, @code{dup} duplicates the value
4119: at the top of the stack. Try typing @code{5 dup .s} to see what it does.
1.1 anton 4120:
1.29 crook 4121: We already know that the text interpreter searches through the
4122: dictionary to locate names. If you've followed the examples earlier, you
4123: will already have a definition called @code{add-two}. Lets try modifying
4124: it by typing in a new definition:
1.1 anton 4125:
1.29 crook 4126: @example
1.30 anton 4127: @kbd{: add-two dup . ." + 2 =" 2 + . ;@key{RET}} redefined add-two ok
1.29 crook 4128: @end example
1.5 anton 4129:
1.29 crook 4130: Forth recognised that we were defining a word that already exists, and
4131: printed a message to warn us of that fact. Let's try out the new
4132: definition:
1.5 anton 4133:
1.29 crook 4134: @example
1.30 anton 4135: @kbd{9 add-two@key{RET}} 9 + 2 =11 ok
1.29 crook 4136: @end example
1.1 anton 4137:
1.29 crook 4138: @noindent
4139: All that we've actually done here, though, is to create a new
4140: definition, with a particular name. The fact that there was already a
4141: definition with the same name did not make any difference to the way
4142: that the new definition was created (except that Forth printed a warning
4143: message). The old definition of add-two still exists (try @code{demo}
4144: again to see that this is true). Any new definition will use the new
4145: definition of @code{add-two}, but old definitions continue to use the
4146: version that already existed at the time that they were @code{compiled}.
1.1 anton 4147:
1.29 crook 4148: Before you go on to the next section, try defining and redefining some
4149: words of your own.
1.1 anton 4150:
1.29 crook 4151: @comment ----------------------------------------------
4152: @node How does that work?, Forth is written in Forth, Your first definition, Introduction
4153: @section How does that work?
4154: @cindex parsing words
1.1 anton 4155:
1.30 anton 4156: @c That's pretty deep (IMO way too deep) for an introduction. - anton
4157:
4158: @c Is it a good idea to talk about the interpretation semantics of a
4159: @c number? We don't have an xt to go along with it. - anton
4160:
4161: @c Now that I have eliminated execution semantics, I wonder if it would not
4162: @c be better to keep them (or add run-time semantics), to make it easier to
4163: @c explain what compilation semantics usually does. - anton
4164:
1.44 crook 4165: @c nac-> I removed the term ``default compilation sematics'' from the
4166: @c introductory chapter. Removing ``execution semantics'' was making
4167: @c everything simpler to explain, then I think the use of this term made
4168: @c everything more complex again. I replaced it with ``default
4169: @c semantics'' (which is used elsewhere in the manual) by which I mean
4170: @c ``a definition that has neither the immediate nor the compile-only
1.83 anton 4171: @c flag set''.
4172:
4173: @c anton: I have eliminated default semantics (except in one place where it
4174: @c means "default interpretation and compilation semantics"), because it
4175: @c makes no sense in the presence of combined words. I reverted to
4176: @c "execution semantics" where necessary.
4177:
4178: @c nac-> I reworded big chunks of the ``how does that work''
1.44 crook 4179: @c section (and, unusually for me, I think I even made it shorter!). See
4180: @c what you think -- I know I have not addressed your primary concern
4181: @c that it is too heavy-going for an introduction. From what I understood
4182: @c of your course notes it looks as though they might be a good framework.
4183: @c Things that I've tried to capture here are some things that came as a
4184: @c great revelation here when I first understood them. Also, I like the
4185: @c fact that a very simple code example shows up almost all of the issues
4186: @c that you need to understand to see how Forth works. That's unique and
4187: @c worthwhile to emphasise.
4188:
1.83 anton 4189: @c anton: I think it's a good idea to present the details, especially those
4190: @c that you found to be a revelation, and probably the tutorial tries to be
4191: @c too superficial and does not get some of the things across that make
4192: @c Forth special. I do believe that most of the time these things should
4193: @c be discussed at the end of a section or in separate sections instead of
4194: @c in the middle of a section (e.g., the stuff you added in "User-defined
4195: @c defining words" leads in a completely different direction from the rest
4196: @c of the section).
4197:
1.29 crook 4198: Now we're going to take another look at the definition of @code{add-two}
4199: from the previous section. From our knowledge of the way that the text
4200: interpreter works, we would have expected this result when we tried to
4201: define @code{add-two}:
1.21 crook 4202:
1.29 crook 4203: @example
1.44 crook 4204: @kbd{: add-two 2 + . ;@key{RET}}
1.29 crook 4205: ^^^^^^^
4206: Error: Undefined word
4207: @end example
1.28 crook 4208:
1.29 crook 4209: The reason that this didn't happen is bound up in the way that @code{:}
4210: works. The word @code{:} does two special things. The first special
4211: thing that it does prevents the text interpreter from ever seeing the
4212: characters @code{add-two}. The text interpreter uses a variable called
4213: @cindex modifying >IN
1.44 crook 4214: @code{>IN} (pronounced ``to-in'') to keep track of where it is in the
1.29 crook 4215: input line. When it encounters the word @code{:} it behaves in exactly
4216: the same way as it does for any other word; it looks it up in the name
4217: dictionary, finds its xt and executes it. When @code{:} executes, it
4218: looks at the input buffer, finds the word @code{add-two} and advances the
4219: value of @code{>IN} to point past it. It then does some other stuff
4220: associated with creating the new definition (including creating an entry
4221: for @code{add-two} in the name dictionary). When the execution of @code{:}
4222: completes, control returns to the text interpreter, which is oblivious
4223: to the fact that it has been tricked into ignoring part of the input
4224: line.
1.21 crook 4225:
1.29 crook 4226: @cindex parsing words
4227: Words like @code{:} -- words that advance the value of @code{>IN} and so
4228: prevent the text interpreter from acting on the whole of the input line
4229: -- are called @dfn{parsing words}.
1.21 crook 4230:
1.29 crook 4231: @cindex @code{state} - effect on the text interpreter
4232: @cindex text interpreter - effect of state
4233: The second special thing that @code{:} does is change the value of a
4234: variable called @code{state}, which affects the way that the text
4235: interpreter behaves. When Gforth starts up, @code{state} has the value
4236: 0, and the text interpreter is said to be @dfn{interpreting}. During a
4237: colon definition (started with @code{:}), @code{state} is set to -1 and
1.44 crook 4238: the text interpreter is said to be @dfn{compiling}.
4239:
4240: In this example, the text interpreter is compiling when it processes the
4241: string ``@code{2 + . ;}''. It still breaks the string down into
4242: character sequences in the same way. However, instead of pushing the
4243: number @code{2} onto the stack, it lays down (@dfn{compiles}) some magic
4244: into the definition of @code{add-two} that will make the number @code{2} get
4245: pushed onto the stack when @code{add-two} is @dfn{executed}. Similarly,
4246: the behaviours of @code{+} and @code{.} are also compiled into the
4247: definition.
4248:
4249: One category of words don't get compiled. These so-called @dfn{immediate
4250: words} get executed (performed @i{now}) regardless of whether the text
4251: interpreter is interpreting or compiling. The word @code{;} is an
4252: immediate word. Rather than being compiled into the definition, it
4253: executes. Its effect is to terminate the current definition, which
4254: includes changing the value of @code{state} back to 0.
4255:
4256: When you execute @code{add-two}, it has a @dfn{run-time effect} that is
4257: exactly the same as if you had typed @code{2 + . @key{RET}} outside of a
4258: definition.
1.28 crook 4259:
1.30 anton 4260: In Forth, every word or number can be described in terms of two
1.29 crook 4261: properties:
1.28 crook 4262:
4263: @itemize @bullet
4264: @item
1.29 crook 4265: @cindex interpretation semantics
1.44 crook 4266: Its @dfn{interpretation semantics} describe how it will behave when the
4267: text interpreter encounters it in @dfn{interpret} state. The
4268: interpretation semantics of a word are represented by an @dfn{execution
4269: token}.
1.28 crook 4270: @item
1.29 crook 4271: @cindex compilation semantics
1.44 crook 4272: Its @dfn{compilation semantics} describe how it will behave when the
4273: text interpreter encounters it in @dfn{compile} state. The compilation
4274: semantics of a word are represented in an implementation-dependent way;
4275: Gforth uses a @dfn{compilation token}.
1.29 crook 4276: @end itemize
4277:
4278: @noindent
4279: Numbers are always treated in a fixed way:
4280:
4281: @itemize @bullet
1.28 crook 4282: @item
1.44 crook 4283: When the number is @dfn{interpreted}, its behaviour is to push the
4284: number onto the stack.
1.28 crook 4285: @item
1.30 anton 4286: When the number is @dfn{compiled}, a piece of code is appended to the
4287: current definition that pushes the number when it runs. (In other words,
4288: the compilation semantics of a number are to postpone its interpretation
4289: semantics until the run-time of the definition that it is being compiled
4290: into.)
1.29 crook 4291: @end itemize
4292:
1.44 crook 4293: Words don't behave in such a regular way, but most have @i{default
4294: semantics} which means that they behave like this:
1.29 crook 4295:
4296: @itemize @bullet
1.28 crook 4297: @item
1.30 anton 4298: The @dfn{interpretation semantics} of the word are to do something useful.
4299: @item
1.29 crook 4300: The @dfn{compilation semantics} of the word are to append its
1.30 anton 4301: @dfn{interpretation semantics} to the current definition (so that its
4302: run-time behaviour is to do something useful).
1.28 crook 4303: @end itemize
4304:
1.30 anton 4305: @cindex immediate words
1.44 crook 4306: The actual behaviour of any particular word can be controlled by using
4307: the words @code{immediate} and @code{compile-only} when the word is
4308: defined. These words set flags in the name dictionary entry of the most
4309: recently defined word, and these flags are retrieved by the text
4310: interpreter when it finds the word in the name dictionary.
4311:
4312: A word that is marked as @dfn{immediate} has compilation semantics that
4313: are identical to its interpretation semantics. In other words, it
4314: behaves like this:
1.29 crook 4315:
4316: @itemize @bullet
4317: @item
1.30 anton 4318: The @dfn{interpretation semantics} of the word are to do something useful.
1.29 crook 4319: @item
1.30 anton 4320: The @dfn{compilation semantics} of the word are to do something useful
4321: (and actually the same thing); i.e., it is executed during compilation.
1.29 crook 4322: @end itemize
1.28 crook 4323:
1.44 crook 4324: Marking a word as @dfn{compile-only} prohibits the text interpreter from
4325: performing the interpretation semantics of the word directly; an attempt
4326: to do so will generate an error. It is never necessary to use
4327: @code{compile-only} (and it is not even part of ANS Forth, though it is
4328: provided by many implementations) but it is good etiquette to apply it
4329: to a word that will not behave correctly (and might have unexpected
4330: side-effects) in interpret state. For example, it is only legal to use
4331: the conditional word @code{IF} within a definition. If you forget this
4332: and try to use it elsewhere, the fact that (in Gforth) it is marked as
4333: @code{compile-only} allows the text interpreter to generate a helpful
4334: error message rather than subjecting you to the consequences of your
4335: folly.
4336:
1.29 crook 4337: This example shows the difference between an immediate and a
4338: non-immediate word:
1.28 crook 4339:
1.29 crook 4340: @example
4341: : show-state state @@ . ;
4342: : show-state-now show-state ; immediate
4343: : word1 show-state ;
4344: : word2 show-state-now ;
1.28 crook 4345: @end example
1.23 crook 4346:
1.29 crook 4347: The word @code{immediate} after the definition of @code{show-state-now}
4348: makes that word an immediate word. These definitions introduce a new
4349: word: @code{@@} (pronounced ``fetch''). This word fetches the value of a
4350: variable, and leaves it on the stack. Therefore, the behaviour of
4351: @code{show-state} is to print a number that represents the current value
4352: of @code{state}.
1.28 crook 4353:
1.29 crook 4354: When you execute @code{word1}, it prints the number 0, indicating that
4355: the system is interpreting. When the text interpreter compiled the
4356: definition of @code{word1}, it encountered @code{show-state} whose
1.30 anton 4357: compilation semantics are to append its interpretation semantics to the
1.29 crook 4358: current definition. When you execute @code{word1}, it performs the
1.30 anton 4359: interpretation semantics of @code{show-state}. At the time that @code{word1}
1.29 crook 4360: (and therefore @code{show-state}) are executed, the system is
4361: interpreting.
1.28 crook 4362:
1.30 anton 4363: When you pressed @key{RET} after entering the definition of @code{word2},
1.29 crook 4364: you should have seen the number -1 printed, followed by ``@code{
4365: ok}''. When the text interpreter compiled the definition of
4366: @code{word2}, it encountered @code{show-state-now}, an immediate word,
1.30 anton 4367: whose compilation semantics are therefore to perform its interpretation
1.29 crook 4368: semantics. It is executed straight away (even before the text
4369: interpreter has moved on to process another group of characters; the
4370: @code{;} in this example). The effect of executing it are to display the
4371: value of @code{state} @i{at the time that the definition of}
4372: @code{word2} @i{is being defined}. Printing -1 demonstrates that the
4373: system is compiling at this time. If you execute @code{word2} it does
4374: nothing at all.
1.28 crook 4375:
1.29 crook 4376: @cindex @code{."}, how it works
4377: Before leaving the subject of immediate words, consider the behaviour of
4378: @code{."} in the definition of @code{greet}, in the previous
4379: section. This word is both a parsing word and an immediate word. Notice
4380: that there is a space between @code{."} and the start of the text
4381: @code{Hello and welcome}, but that there is no space between the last
4382: letter of @code{welcome} and the @code{"} character. The reason for this
4383: is that @code{."} is a Forth word; it must have a space after it so that
4384: the text interpreter can identify it. The @code{"} is not a Forth word;
4385: it is a @dfn{delimiter}. The examples earlier show that, when the string
4386: is displayed, there is neither a space before the @code{H} nor after the
4387: @code{e}. Since @code{."} is an immediate word, it executes at the time
4388: that @code{greet} is defined. When it executes, its behaviour is to
4389: search forward in the input line looking for the delimiter. When it
4390: finds the delimiter, it updates @code{>IN} to point past the
4391: delimiter. It also compiles some magic code into the definition of
4392: @code{greet}; the xt of a run-time routine that prints a text string. It
4393: compiles the string @code{Hello and welcome} into memory so that it is
4394: available to be printed later. When the text interpreter gains control,
4395: the next word it finds in the input stream is @code{;} and so it
4396: terminates the definition of @code{greet}.
1.28 crook 4397:
4398:
4399: @comment ----------------------------------------------
1.29 crook 4400: @node Forth is written in Forth, Review - elements of a Forth system, How does that work?, Introduction
4401: @section Forth is written in Forth
4402: @cindex structure of Forth programs
4403:
4404: When you start up a Forth compiler, a large number of definitions
4405: already exist. In Forth, you develop a new application using bottom-up
4406: programming techniques to create new definitions that are defined in
4407: terms of existing definitions. As you create each definition you can
4408: test and debug it interactively.
4409:
4410: If you have tried out the examples in this section, you will probably
4411: have typed them in by hand; when you leave Gforth, your definitions will
4412: be lost. You can avoid this by using a text editor to enter Forth source
4413: code into a file, and then loading code from the file using
1.49 anton 4414: @code{include} (@pxref{Forth source files}). A Forth source file is
1.29 crook 4415: processed by the text interpreter, just as though you had typed it in by
4416: hand@footnote{Actually, there are some subtle differences -- see
4417: @ref{The Text Interpreter}.}.
4418:
4419: Gforth also supports the traditional Forth alternative to using text
1.49 anton 4420: files for program entry (@pxref{Blocks}).
1.28 crook 4421:
1.29 crook 4422: In common with many, if not most, Forth compilers, most of Gforth is
4423: actually written in Forth. All of the @file{.fs} files in the
4424: installation directory@footnote{For example,
1.30 anton 4425: @file{/usr/local/share/gforth...}} are Forth source files, which you can
1.29 crook 4426: study to see examples of Forth programming.
1.28 crook 4427:
1.29 crook 4428: Gforth maintains a history file that records every line that you type to
4429: the text interpreter. This file is preserved between sessions, and is
4430: used to provide a command-line recall facility. If you enter long
4431: definitions by hand, you can use a text editor to paste them out of the
4432: history file into a Forth source file for reuse at a later time
1.49 anton 4433: (for more information @pxref{Command-line editing}).
1.28 crook 4434:
4435:
4436: @comment ----------------------------------------------
1.29 crook 4437: @node Review - elements of a Forth system, Where to go next, Forth is written in Forth, Introduction
4438: @section Review - elements of a Forth system
4439: @cindex elements of a Forth system
1.28 crook 4440:
1.29 crook 4441: To summarise this chapter:
1.28 crook 4442:
4443: @itemize @bullet
4444: @item
1.29 crook 4445: Forth programs use @dfn{factoring} to break a problem down into small
4446: fragments called @dfn{words} or @dfn{definitions}.
4447: @item
4448: Forth program development is an interactive process.
4449: @item
4450: The main command loop that accepts input, and controls both
4451: interpretation and compilation, is called the @dfn{text interpreter}
4452: (also known as the @dfn{outer interpreter}).
4453: @item
4454: Forth has a very simple syntax, consisting of words and numbers
4455: separated by spaces or carriage-return characters. Any additional syntax
4456: is imposed by @dfn{parsing words}.
4457: @item
4458: Forth uses a stack to pass parameters between words. As a result, it
4459: uses postfix notation.
4460: @item
4461: To use a word that has previously been defined, the text interpreter
4462: searches for the word in the @dfn{name dictionary}.
4463: @item
1.30 anton 4464: Words have @dfn{interpretation semantics} and @dfn{compilation semantics}.
1.28 crook 4465: @item
1.29 crook 4466: The text interpreter uses the value of @code{state} to select between
4467: the use of the @dfn{interpretation semantics} and the @dfn{compilation
4468: semantics} of a word that it encounters.
1.28 crook 4469: @item
1.30 anton 4470: The relationship between the @dfn{interpretation semantics} and
4471: @dfn{compilation semantics} for a word
1.29 crook 4472: depend upon the way in which the word was defined (for example, whether
4473: it is an @dfn{immediate} word).
1.28 crook 4474: @item
1.29 crook 4475: Forth definitions can be implemented in Forth (called @dfn{high-level
4476: definitions}) or in some other way (usually a lower-level language and
4477: as a result often called @dfn{low-level definitions}, @dfn{code
4478: definitions} or @dfn{primitives}).
1.28 crook 4479: @item
1.29 crook 4480: Many Forth systems are implemented mainly in Forth.
1.28 crook 4481: @end itemize
4482:
4483:
1.29 crook 4484: @comment ----------------------------------------------
1.48 anton 4485: @node Where to go next, Exercises, Review - elements of a Forth system, Introduction
1.29 crook 4486: @section Where To Go Next
4487: @cindex where to go next
1.28 crook 4488:
1.29 crook 4489: Amazing as it may seem, if you have read (and understood) this far, you
4490: know almost all the fundamentals about the inner workings of a Forth
4491: system. You certainly know enough to be able to read and understand the
4492: rest of this manual and the ANS Forth document, to learn more about the
4493: facilities that Forth in general and Gforth in particular provide. Even
4494: scarier, you know almost enough to implement your own Forth system.
1.30 anton 4495: However, that's not a good idea just yet... better to try writing some
1.29 crook 4496: programs in Gforth.
1.28 crook 4497:
1.29 crook 4498: Forth has such a rich vocabulary that it can be hard to know where to
4499: start in learning it. This section suggests a few sets of words that are
4500: enough to write small but useful programs. Use the word index in this
4501: document to learn more about each word, then try it out and try to write
4502: small definitions using it. Start by experimenting with these words:
1.28 crook 4503:
4504: @itemize @bullet
4505: @item
1.29 crook 4506: Arithmetic: @code{+ - * / /MOD */ ABS INVERT}
4507: @item
4508: Comparison: @code{MIN MAX =}
4509: @item
4510: Logic: @code{AND OR XOR NOT}
4511: @item
4512: Stack manipulation: @code{DUP DROP SWAP OVER}
1.28 crook 4513: @item
1.29 crook 4514: Loops and decisions: @code{IF ELSE ENDIF ?DO I LOOP}
1.28 crook 4515: @item
1.29 crook 4516: Input/Output: @code{. ." EMIT CR KEY}
1.28 crook 4517: @item
1.29 crook 4518: Defining words: @code{: ; CREATE}
1.28 crook 4519: @item
1.29 crook 4520: Memory allocation words: @code{ALLOT ,}
1.28 crook 4521: @item
1.29 crook 4522: Tools: @code{SEE WORDS .S MARKER}
4523: @end itemize
4524:
4525: When you have mastered those, go on to:
4526:
4527: @itemize @bullet
1.28 crook 4528: @item
1.29 crook 4529: More defining words: @code{VARIABLE CONSTANT VALUE TO CREATE DOES>}
1.28 crook 4530: @item
1.29 crook 4531: Memory access: @code{@@ !}
1.28 crook 4532: @end itemize
1.23 crook 4533:
1.29 crook 4534: When you have mastered these, there's nothing for it but to read through
4535: the whole of this manual and find out what you've missed.
4536:
4537: @comment ----------------------------------------------
1.48 anton 4538: @node Exercises, , Where to go next, Introduction
1.29 crook 4539: @section Exercises
4540: @cindex exercises
4541:
4542: TODO: provide a set of programming excercises linked into the stuff done
4543: already and into other sections of the manual. Provide solutions to all
4544: the exercises in a .fs file in the distribution.
4545:
4546: @c Get some inspiration from Starting Forth and Kelly&Spies.
4547:
4548: @c excercises:
4549: @c 1. take inches and convert to feet and inches.
4550: @c 2. take temperature and convert from fahrenheight to celcius;
4551: @c may need to care about symmetric vs floored??
4552: @c 3. take input line and do character substitution
4553: @c to encipher or decipher
4554: @c 4. as above but work on a file for in and out
4555: @c 5. take input line and convert to pig-latin
4556: @c
4557: @c thing of sets of things to exercise then come up with
4558: @c problems that need those things.
4559:
4560:
1.26 crook 4561: @c ******************************************************************
1.29 crook 4562: @node Words, Error messages, Introduction, Top
1.1 anton 4563: @chapter Forth Words
1.26 crook 4564: @cindex words
1.1 anton 4565:
4566: @menu
4567: * Notation::
1.65 anton 4568: * Case insensitivity::
4569: * Comments::
4570: * Boolean Flags::
1.1 anton 4571: * Arithmetic::
4572: * Stack Manipulation::
1.5 anton 4573: * Memory::
1.1 anton 4574: * Control Structures::
4575: * Defining Words::
1.65 anton 4576: * Interpretation and Compilation Semantics::
1.47 crook 4577: * Tokens for Words::
1.81 anton 4578: * Compiling words::
1.65 anton 4579: * The Text Interpreter::
1.111 anton 4580: * The Input Stream::
1.65 anton 4581: * Word Lists::
4582: * Environmental Queries::
1.12 anton 4583: * Files::
4584: * Blocks::
4585: * Other I/O::
1.78 anton 4586: * Locals::
4587: * Structures::
4588: * Object-oriented Forth::
1.12 anton 4589: * Programming Tools::
4590: * Assembler and Code Words::
4591: * Threading Words::
1.65 anton 4592: * Passing Commands to the OS::
4593: * Keeping track of Time::
4594: * Miscellaneous Words::
1.1 anton 4595: @end menu
4596:
1.65 anton 4597: @node Notation, Case insensitivity, Words, Words
1.1 anton 4598: @section Notation
4599: @cindex notation of glossary entries
4600: @cindex format of glossary entries
4601: @cindex glossary notation format
4602: @cindex word glossary entry format
4603:
4604: The Forth words are described in this section in the glossary notation
1.67 anton 4605: that has become a de-facto standard for Forth texts:
1.1 anton 4606:
4607: @format
1.29 crook 4608: @i{word} @i{Stack effect} @i{wordset} @i{pronunciation}
1.1 anton 4609: @end format
1.29 crook 4610: @i{Description}
1.1 anton 4611:
4612: @table @var
4613: @item word
1.28 crook 4614: The name of the word.
1.1 anton 4615:
4616: @item Stack effect
4617: @cindex stack effect
1.29 crook 4618: The stack effect is written in the notation @code{@i{before} --
4619: @i{after}}, where @i{before} and @i{after} describe the top of
1.1 anton 4620: stack entries before and after the execution of the word. The rest of
4621: the stack is not touched by the word. The top of stack is rightmost,
4622: i.e., a stack sequence is written as it is typed in. Note that Gforth
4623: uses a separate floating point stack, but a unified stack
1.29 crook 4624: notation. Also, return stack effects are not shown in @i{stack
4625: effect}, but in @i{Description}. The name of a stack item describes
1.1 anton 4626: the type and/or the function of the item. See below for a discussion of
4627: the types.
4628:
4629: All words have two stack effects: A compile-time stack effect and a
4630: run-time stack effect. The compile-time stack-effect of most words is
1.29 crook 4631: @i{ -- }. If the compile-time stack-effect of a word deviates from
1.1 anton 4632: this standard behaviour, or the word does other unusual things at
4633: compile time, both stack effects are shown; otherwise only the run-time
4634: stack effect is shown.
4635:
4636: @cindex pronounciation of words
4637: @item pronunciation
4638: How the word is pronounced.
4639:
4640: @cindex wordset
1.67 anton 4641: @cindex environment wordset
1.1 anton 4642: @item wordset
1.21 crook 4643: The ANS Forth standard is divided into several word sets. A standard
4644: system need not support all of them. Therefore, in theory, the fewer
4645: word sets your program uses the more portable it will be. However, we
4646: suspect that most ANS Forth systems on personal machines will feature
1.26 crook 4647: all word sets. Words that are not defined in ANS Forth have
1.21 crook 4648: @code{gforth} or @code{gforth-internal} as word set. @code{gforth}
1.1 anton 4649: describes words that will work in future releases of Gforth;
4650: @code{gforth-internal} words are more volatile. Environmental query
4651: strings are also displayed like words; you can recognize them by the
1.21 crook 4652: @code{environment} in the word set field.
1.1 anton 4653:
4654: @item Description
4655: A description of the behaviour of the word.
4656: @end table
4657:
4658: @cindex types of stack items
4659: @cindex stack item types
4660: The type of a stack item is specified by the character(s) the name
4661: starts with:
4662:
4663: @table @code
4664: @item f
4665: @cindex @code{f}, stack item type
4666: Boolean flags, i.e. @code{false} or @code{true}.
4667: @item c
4668: @cindex @code{c}, stack item type
4669: Char
4670: @item w
4671: @cindex @code{w}, stack item type
4672: Cell, can contain an integer or an address
4673: @item n
4674: @cindex @code{n}, stack item type
4675: signed integer
4676: @item u
4677: @cindex @code{u}, stack item type
4678: unsigned integer
4679: @item d
4680: @cindex @code{d}, stack item type
4681: double sized signed integer
4682: @item ud
4683: @cindex @code{ud}, stack item type
4684: double sized unsigned integer
4685: @item r
4686: @cindex @code{r}, stack item type
4687: Float (on the FP stack)
1.21 crook 4688: @item a-
1.1 anton 4689: @cindex @code{a_}, stack item type
4690: Cell-aligned address
1.21 crook 4691: @item c-
1.1 anton 4692: @cindex @code{c_}, stack item type
4693: Char-aligned address (note that a Char may have two bytes in Windows NT)
1.21 crook 4694: @item f-
1.1 anton 4695: @cindex @code{f_}, stack item type
4696: Float-aligned address
1.21 crook 4697: @item df-
1.1 anton 4698: @cindex @code{df_}, stack item type
4699: Address aligned for IEEE double precision float
1.21 crook 4700: @item sf-
1.1 anton 4701: @cindex @code{sf_}, stack item type
4702: Address aligned for IEEE single precision float
4703: @item xt
4704: @cindex @code{xt}, stack item type
4705: Execution token, same size as Cell
4706: @item wid
4707: @cindex @code{wid}, stack item type
1.21 crook 4708: Word list ID, same size as Cell
1.68 anton 4709: @item ior, wior
4710: @cindex ior type description
4711: @cindex wior type description
4712: I/O result code, cell-sized. In Gforth, you can @code{throw} iors.
1.1 anton 4713: @item f83name
4714: @cindex @code{f83name}, stack item type
4715: Pointer to a name structure
4716: @item "
4717: @cindex @code{"}, stack item type
1.12 anton 4718: string in the input stream (not on the stack). The terminating character
4719: is a blank by default. If it is not a blank, it is shown in @code{<>}
1.1 anton 4720: quotes.
4721: @end table
4722:
1.65 anton 4723: @comment ----------------------------------------------
4724: @node Case insensitivity, Comments, Notation, Words
4725: @section Case insensitivity
4726: @cindex case sensitivity
4727: @cindex upper and lower case
4728:
4729: Gforth is case-insensitive; you can enter definitions and invoke
4730: Standard words using upper, lower or mixed case (however,
4731: @pxref{core-idef, Implementation-defined options, Implementation-defined
4732: options}).
4733:
4734: ANS Forth only @i{requires} implementations to recognise Standard words
4735: when they are typed entirely in upper case. Therefore, a Standard
4736: program must use upper case for all Standard words. You can use whatever
4737: case you like for words that you define, but in a Standard program you
4738: have to use the words in the same case that you defined them.
4739:
4740: Gforth supports case sensitivity through @code{table}s (case-sensitive
4741: wordlists, @pxref{Word Lists}).
4742:
4743: Two people have asked how to convert Gforth to be case-sensitive; while
4744: we think this is a bad idea, you can change all wordlists into tables
4745: like this:
4746:
4747: @example
4748: ' table-find forth-wordlist wordlist-map @ !
4749: @end example
4750:
4751: Note that you now have to type the predefined words in the same case
4752: that we defined them, which are varying. You may want to convert them
4753: to your favourite case before doing this operation (I won't explain how,
4754: because if you are even contemplating doing this, you'd better have
4755: enough knowledge of Forth systems to know this already).
4756:
4757: @node Comments, Boolean Flags, Case insensitivity, Words
1.21 crook 4758: @section Comments
1.26 crook 4759: @cindex comments
1.21 crook 4760:
1.29 crook 4761: Forth supports two styles of comment; the traditional @i{in-line} comment,
4762: @code{(} and its modern cousin, the @i{comment to end of line}; @code{\}.
1.21 crook 4763:
1.44 crook 4764:
1.23 crook 4765: doc-(
1.21 crook 4766: doc-\
1.23 crook 4767: doc-\G
1.21 crook 4768:
1.44 crook 4769:
1.21 crook 4770: @node Boolean Flags, Arithmetic, Comments, Words
4771: @section Boolean Flags
1.26 crook 4772: @cindex Boolean flags
1.21 crook 4773:
4774: A Boolean flag is cell-sized. A cell with all bits clear represents the
4775: flag @code{false} and a flag with all bits set represents the flag
1.26 crook 4776: @code{true}. Words that check a flag (for example, @code{IF}) will treat
1.29 crook 4777: a cell that has @i{any} bit set as @code{true}.
1.67 anton 4778: @c on and off to Memory?
4779: @c true and false to "Bitwise operations" or "Numeric comparison"?
1.44 crook 4780:
1.21 crook 4781: doc-true
4782: doc-false
1.29 crook 4783: doc-on
4784: doc-off
1.21 crook 4785:
1.44 crook 4786:
1.21 crook 4787: @node Arithmetic, Stack Manipulation, Boolean Flags, Words
1.1 anton 4788: @section Arithmetic
4789: @cindex arithmetic words
4790:
4791: @cindex division with potentially negative operands
4792: Forth arithmetic is not checked, i.e., you will not hear about integer
4793: overflow on addition or multiplication, you may hear about division by
4794: zero if you are lucky. The operator is written after the operands, but
4795: the operands are still in the original order. I.e., the infix @code{2-1}
4796: corresponds to @code{2 1 -}. Forth offers a variety of division
4797: operators. If you perform division with potentially negative operands,
4798: you do not want to use @code{/} or @code{/mod} with its undefined
4799: behaviour, but rather @code{fm/mod} or @code{sm/mod} (probably the
4800: former, @pxref{Mixed precision}).
1.26 crook 4801: @comment TODO discuss the different division forms and the std approach
1.1 anton 4802:
4803: @menu
4804: * Single precision::
1.67 anton 4805: * Double precision:: Double-cell integer arithmetic
1.1 anton 4806: * Bitwise operations::
1.67 anton 4807: * Numeric comparison::
1.29 crook 4808: * Mixed precision:: Operations with single and double-cell integers
1.1 anton 4809: * Floating Point::
4810: @end menu
4811:
1.67 anton 4812: @node Single precision, Double precision, Arithmetic, Arithmetic
1.1 anton 4813: @subsection Single precision
4814: @cindex single precision arithmetic words
4815:
1.67 anton 4816: @c !! cell undefined
4817:
4818: By default, numbers in Forth are single-precision integers that are one
1.26 crook 4819: cell in size. They can be signed or unsigned, depending upon how you
1.49 anton 4820: treat them. For the rules used by the text interpreter for recognising
4821: single-precision integers see @ref{Number Conversion}.
1.21 crook 4822:
1.67 anton 4823: These words are all defined for signed operands, but some of them also
4824: work for unsigned numbers: @code{+}, @code{1+}, @code{-}, @code{1-},
4825: @code{*}.
1.44 crook 4826:
1.1 anton 4827: doc-+
1.21 crook 4828: doc-1+
1.1 anton 4829: doc--
1.21 crook 4830: doc-1-
1.1 anton 4831: doc-*
4832: doc-/
4833: doc-mod
4834: doc-/mod
4835: doc-negate
4836: doc-abs
4837: doc-min
4838: doc-max
1.27 crook 4839: doc-floored
1.1 anton 4840:
1.44 crook 4841:
1.67 anton 4842: @node Double precision, Bitwise operations, Single precision, Arithmetic
1.21 crook 4843: @subsection Double precision
4844: @cindex double precision arithmetic words
4845:
1.49 anton 4846: For the rules used by the text interpreter for
4847: recognising double-precision integers, see @ref{Number Conversion}.
1.21 crook 4848:
4849: A double precision number is represented by a cell pair, with the most
1.67 anton 4850: significant cell at the TOS. It is trivial to convert an unsigned single
4851: to a double: simply push a @code{0} onto the TOS. Since numbers are
4852: represented by Gforth using 2's complement arithmetic, converting a
4853: signed single to a (signed) double requires sign-extension across the
4854: most significant cell. This can be achieved using @code{s>d}. The moral
4855: of the story is that you cannot convert a number without knowing whether
4856: it represents an unsigned or a signed number.
1.21 crook 4857:
1.67 anton 4858: These words are all defined for signed operands, but some of them also
4859: work for unsigned numbers: @code{d+}, @code{d-}.
1.44 crook 4860:
1.21 crook 4861: doc-s>d
1.67 anton 4862: doc-d>s
1.21 crook 4863: doc-d+
4864: doc-d-
4865: doc-dnegate
4866: doc-dabs
4867: doc-dmin
4868: doc-dmax
4869:
1.44 crook 4870:
1.67 anton 4871: @node Bitwise operations, Numeric comparison, Double precision, Arithmetic
4872: @subsection Bitwise operations
4873: @cindex bitwise operation words
4874:
4875:
4876: doc-and
4877: doc-or
4878: doc-xor
4879: doc-invert
4880: doc-lshift
4881: doc-rshift
4882: doc-2*
4883: doc-d2*
4884: doc-2/
4885: doc-d2/
4886:
4887:
4888: @node Numeric comparison, Mixed precision, Bitwise operations, Arithmetic
1.21 crook 4889: @subsection Numeric comparison
4890: @cindex numeric comparison words
4891:
1.67 anton 4892: Note that the words that compare for equality (@code{= <> 0= 0<> d= d<>
4893: d0= d0<>}) work for for both signed and unsigned numbers.
1.44 crook 4894:
1.28 crook 4895: doc-<
4896: doc-<=
4897: doc-<>
4898: doc-=
4899: doc->
4900: doc->=
4901:
1.21 crook 4902: doc-0<
1.23 crook 4903: doc-0<=
1.21 crook 4904: doc-0<>
4905: doc-0=
1.23 crook 4906: doc-0>
4907: doc-0>=
1.28 crook 4908:
4909: doc-u<
4910: doc-u<=
1.44 crook 4911: @c u<> and u= exist but are the same as <> and =
1.31 anton 4912: @c doc-u<>
4913: @c doc-u=
1.28 crook 4914: doc-u>
4915: doc-u>=
4916:
4917: doc-within
4918:
4919: doc-d<
4920: doc-d<=
4921: doc-d<>
4922: doc-d=
4923: doc-d>
4924: doc-d>=
1.23 crook 4925:
1.21 crook 4926: doc-d0<
1.23 crook 4927: doc-d0<=
4928: doc-d0<>
1.21 crook 4929: doc-d0=
1.23 crook 4930: doc-d0>
4931: doc-d0>=
4932:
1.21 crook 4933: doc-du<
1.28 crook 4934: doc-du<=
1.44 crook 4935: @c du<> and du= exist but are the same as d<> and d=
1.31 anton 4936: @c doc-du<>
4937: @c doc-du=
1.28 crook 4938: doc-du>
4939: doc-du>=
1.1 anton 4940:
1.44 crook 4941:
1.21 crook 4942: @node Mixed precision, Floating Point, Numeric comparison, Arithmetic
1.1 anton 4943: @subsection Mixed precision
4944: @cindex mixed precision arithmetic words
4945:
1.44 crook 4946:
1.1 anton 4947: doc-m+
4948: doc-*/
4949: doc-*/mod
4950: doc-m*
4951: doc-um*
4952: doc-m*/
4953: doc-um/mod
4954: doc-fm/mod
4955: doc-sm/rem
4956:
1.44 crook 4957:
1.21 crook 4958: @node Floating Point, , Mixed precision, Arithmetic
1.1 anton 4959: @subsection Floating Point
4960: @cindex floating point arithmetic words
4961:
1.49 anton 4962: For the rules used by the text interpreter for
4963: recognising floating-point numbers see @ref{Number Conversion}.
1.1 anton 4964:
1.67 anton 4965: Gforth has a separate floating point stack, but the documentation uses
4966: the unified notation.@footnote{It's easy to generate the separate
4967: notation from that by just separating the floating-point numbers out:
4968: e.g. @code{( n r1 u r2 -- r3 )} becomes @code{( n u -- ) ( F: r1 r2 --
4969: r3 )}.}
1.1 anton 4970:
4971: @cindex floating-point arithmetic, pitfalls
4972: Floating point numbers have a number of unpleasant surprises for the
4973: unwary (e.g., floating point addition is not associative) and even a few
4974: for the wary. You should not use them unless you know what you are doing
4975: or you don't care that the results you get are totally bogus. If you
4976: want to learn about the problems of floating point numbers (and how to
1.66 anton 4977: avoid them), you might start with @cite{David Goldberg,
4978: @uref{http://www.validgh.com/goldberg/paper.ps,What Every Computer
4979: Scientist Should Know About Floating-Point Arithmetic}, ACM Computing
4980: Surveys 23(1):5@minus{}48, March 1991}.
1.1 anton 4981:
1.44 crook 4982:
1.21 crook 4983: doc-d>f
4984: doc-f>d
1.1 anton 4985: doc-f+
4986: doc-f-
4987: doc-f*
4988: doc-f/
4989: doc-fnegate
4990: doc-fabs
4991: doc-fmax
4992: doc-fmin
4993: doc-floor
4994: doc-fround
4995: doc-f**
4996: doc-fsqrt
4997: doc-fexp
4998: doc-fexpm1
4999: doc-fln
5000: doc-flnp1
5001: doc-flog
5002: doc-falog
1.32 anton 5003: doc-f2*
5004: doc-f2/
5005: doc-1/f
5006: doc-precision
5007: doc-set-precision
5008:
5009: @cindex angles in trigonometric operations
5010: @cindex trigonometric operations
5011: Angles in floating point operations are given in radians (a full circle
5012: has 2 pi radians).
5013:
1.1 anton 5014: doc-fsin
5015: doc-fcos
5016: doc-fsincos
5017: doc-ftan
5018: doc-fasin
5019: doc-facos
5020: doc-fatan
5021: doc-fatan2
5022: doc-fsinh
5023: doc-fcosh
5024: doc-ftanh
5025: doc-fasinh
5026: doc-facosh
5027: doc-fatanh
1.21 crook 5028: doc-pi
1.28 crook 5029:
1.32 anton 5030: @cindex equality of floats
5031: @cindex floating-point comparisons
1.31 anton 5032: One particular problem with floating-point arithmetic is that comparison
5033: for equality often fails when you would expect it to succeed. For this
5034: reason approximate equality is often preferred (but you still have to
1.67 anton 5035: know what you are doing). Also note that IEEE NaNs may compare
1.68 anton 5036: differently from what you might expect. The comparison words are:
1.31 anton 5037:
5038: doc-f~rel
5039: doc-f~abs
1.68 anton 5040: doc-f~
1.31 anton 5041: doc-f=
5042: doc-f<>
5043:
5044: doc-f<
5045: doc-f<=
5046: doc-f>
5047: doc-f>=
5048:
1.21 crook 5049: doc-f0<
1.28 crook 5050: doc-f0<=
5051: doc-f0<>
1.21 crook 5052: doc-f0=
1.28 crook 5053: doc-f0>
5054: doc-f0>=
5055:
1.1 anton 5056:
5057: @node Stack Manipulation, Memory, Arithmetic, Words
5058: @section Stack Manipulation
5059: @cindex stack manipulation words
5060:
5061: @cindex floating-point stack in the standard
1.21 crook 5062: Gforth maintains a number of separate stacks:
5063:
1.29 crook 5064: @cindex data stack
5065: @cindex parameter stack
1.21 crook 5066: @itemize @bullet
5067: @item
1.29 crook 5068: A data stack (also known as the @dfn{parameter stack}) -- for
5069: characters, cells, addresses, and double cells.
1.21 crook 5070:
1.29 crook 5071: @cindex floating-point stack
1.21 crook 5072: @item
1.44 crook 5073: A floating point stack -- for holding floating point (FP) numbers.
1.21 crook 5074:
1.29 crook 5075: @cindex return stack
1.21 crook 5076: @item
1.44 crook 5077: A return stack -- for holding the return addresses of colon
1.32 anton 5078: definitions and other (non-FP) data.
1.21 crook 5079:
1.29 crook 5080: @cindex locals stack
1.21 crook 5081: @item
1.44 crook 5082: A locals stack -- for holding local variables.
1.21 crook 5083: @end itemize
5084:
1.1 anton 5085: @menu
5086: * Data stack::
5087: * Floating point stack::
5088: * Return stack::
5089: * Locals stack::
5090: * Stack pointer manipulation::
5091: @end menu
5092:
5093: @node Data stack, Floating point stack, Stack Manipulation, Stack Manipulation
5094: @subsection Data stack
5095: @cindex data stack manipulation words
5096: @cindex stack manipulations words, data stack
5097:
1.44 crook 5098:
1.1 anton 5099: doc-drop
5100: doc-nip
5101: doc-dup
5102: doc-over
5103: doc-tuck
5104: doc-swap
1.21 crook 5105: doc-pick
1.1 anton 5106: doc-rot
5107: doc--rot
5108: doc-?dup
5109: doc-roll
5110: doc-2drop
5111: doc-2nip
5112: doc-2dup
5113: doc-2over
5114: doc-2tuck
5115: doc-2swap
5116: doc-2rot
5117:
1.44 crook 5118:
1.1 anton 5119: @node Floating point stack, Return stack, Data stack, Stack Manipulation
5120: @subsection Floating point stack
5121: @cindex floating-point stack manipulation words
5122: @cindex stack manipulation words, floating-point stack
5123:
1.32 anton 5124: Whilst every sane Forth has a separate floating-point stack, it is not
5125: strictly required; an ANS Forth system could theoretically keep
5126: floating-point numbers on the data stack. As an additional difficulty,
5127: you don't know how many cells a floating-point number takes. It is
5128: reportedly possible to write words in a way that they work also for a
5129: unified stack model, but we do not recommend trying it. Instead, just
5130: say that your program has an environmental dependency on a separate
5131: floating-point stack.
5132:
5133: doc-floating-stack
5134:
1.1 anton 5135: doc-fdrop
5136: doc-fnip
5137: doc-fdup
5138: doc-fover
5139: doc-ftuck
5140: doc-fswap
1.21 crook 5141: doc-fpick
1.1 anton 5142: doc-frot
5143:
1.44 crook 5144:
1.1 anton 5145: @node Return stack, Locals stack, Floating point stack, Stack Manipulation
5146: @subsection Return stack
5147: @cindex return stack manipulation words
5148: @cindex stack manipulation words, return stack
5149:
1.32 anton 5150: @cindex return stack and locals
5151: @cindex locals and return stack
5152: A Forth system is allowed to keep local variables on the
5153: return stack. This is reasonable, as local variables usually eliminate
5154: the need to use the return stack explicitly. So, if you want to produce
5155: a standard compliant program and you are using local variables in a
5156: word, forget about return stack manipulations in that word (refer to the
5157: standard document for the exact rules).
5158:
1.1 anton 5159: doc->r
5160: doc-r>
5161: doc-r@
5162: doc-rdrop
5163: doc-2>r
5164: doc-2r>
5165: doc-2r@
5166: doc-2rdrop
5167:
1.44 crook 5168:
1.1 anton 5169: @node Locals stack, Stack pointer manipulation, Return stack, Stack Manipulation
5170: @subsection Locals stack
5171:
1.78 anton 5172: Gforth uses an extra locals stack. It is described, along with the
5173: reasons for its existence, in @ref{Locals implementation}.
1.21 crook 5174:
1.1 anton 5175: @node Stack pointer manipulation, , Locals stack, Stack Manipulation
5176: @subsection Stack pointer manipulation
5177: @cindex stack pointer manipulation words
5178:
1.44 crook 5179: @c removed s0 r0 l0 -- they are obsolete aliases for sp0 rp0 lp0
1.21 crook 5180: doc-sp0
1.1 anton 5181: doc-sp@
5182: doc-sp!
1.21 crook 5183: doc-fp0
1.1 anton 5184: doc-fp@
5185: doc-fp!
1.21 crook 5186: doc-rp0
1.1 anton 5187: doc-rp@
5188: doc-rp!
1.21 crook 5189: doc-lp0
1.1 anton 5190: doc-lp@
5191: doc-lp!
5192:
1.44 crook 5193:
1.1 anton 5194: @node Memory, Control Structures, Stack Manipulation, Words
5195: @section Memory
1.26 crook 5196: @cindex memory words
1.1 anton 5197:
1.32 anton 5198: @menu
5199: * Memory model::
5200: * Dictionary allocation::
5201: * Heap Allocation::
5202: * Memory Access::
5203: * Address arithmetic::
5204: * Memory Blocks::
5205: @end menu
5206:
1.67 anton 5207: In addition to the standard Forth memory allocation words, there is also
5208: a @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
5209: garbage collector}.
5210:
1.32 anton 5211: @node Memory model, Dictionary allocation, Memory, Memory
5212: @subsection ANS Forth and Gforth memory models
5213:
5214: @c The ANS Forth description is a mess (e.g., is the heap part of
5215: @c the dictionary?), so let's not stick to closely with it.
5216:
1.67 anton 5217: ANS Forth considers a Forth system as consisting of several address
5218: spaces, of which only @dfn{data space} is managed and accessible with
5219: the memory words. Memory not necessarily in data space includes the
5220: stacks, the code (called code space) and the headers (called name
5221: space). In Gforth everything is in data space, but the code for the
5222: primitives is usually read-only.
1.32 anton 5223:
5224: Data space is divided into a number of areas: The (data space portion of
5225: the) dictionary@footnote{Sometimes, the term @dfn{dictionary} is used to
5226: refer to the search data structure embodied in word lists and headers,
5227: because it is used for looking up names, just as you would in a
5228: conventional dictionary.}, the heap, and a number of system-allocated
5229: buffers.
5230:
1.68 anton 5231: @cindex address arithmetic restrictions, ANS vs. Gforth
5232: @cindex contiguous regions, ANS vs. Gforth
1.32 anton 5233: In ANS Forth data space is also divided into contiguous regions. You
5234: can only use address arithmetic within a contiguous region, not between
5235: them. Usually each allocation gives you one contiguous region, but the
1.33 anton 5236: dictionary allocation words have additional rules (@pxref{Dictionary
1.32 anton 5237: allocation}).
5238:
5239: Gforth provides one big address space, and address arithmetic can be
5240: performed between any addresses. However, in the dictionary headers or
5241: code are interleaved with data, so almost the only contiguous data space
5242: regions there are those described by ANS Forth as contiguous; but you
5243: can be sure that the dictionary is allocated towards increasing
5244: addresses even between contiguous regions. The memory order of
5245: allocations in the heap is platform-dependent (and possibly different
5246: from one run to the next).
5247:
1.27 crook 5248:
1.32 anton 5249: @node Dictionary allocation, Heap Allocation, Memory model, Memory
5250: @subsection Dictionary allocation
1.27 crook 5251: @cindex reserving data space
5252: @cindex data space - reserving some
5253:
1.32 anton 5254: Dictionary allocation is a stack-oriented allocation scheme, i.e., if
5255: you want to deallocate X, you also deallocate everything
5256: allocated after X.
5257:
1.68 anton 5258: @cindex contiguous regions in dictionary allocation
1.32 anton 5259: The allocations using the words below are contiguous and grow the region
5260: towards increasing addresses. Other words that allocate dictionary
5261: memory of any kind (i.e., defining words including @code{:noname}) end
5262: the contiguous region and start a new one.
5263:
5264: In ANS Forth only @code{create}d words are guaranteed to produce an
5265: address that is the start of the following contiguous region. In
5266: particular, the cell allocated by @code{variable} is not guaranteed to
5267: be contiguous with following @code{allot}ed memory.
5268:
5269: You can deallocate memory by using @code{allot} with a negative argument
5270: (with some restrictions, see @code{allot}). For larger deallocations use
5271: @code{marker}.
1.27 crook 5272:
1.29 crook 5273:
1.27 crook 5274: doc-here
5275: doc-unused
5276: doc-allot
5277: doc-c,
1.29 crook 5278: doc-f,
1.27 crook 5279: doc-,
5280: doc-2,
5281:
1.32 anton 5282: Memory accesses have to be aligned (@pxref{Address arithmetic}). So of
5283: course you should allocate memory in an aligned way, too. I.e., before
5284: allocating allocating a cell, @code{here} must be cell-aligned, etc.
5285: The words below align @code{here} if it is not already. Basically it is
5286: only already aligned for a type, if the last allocation was a multiple
5287: of the size of this type and if @code{here} was aligned for this type
5288: before.
5289:
5290: After freshly @code{create}ing a word, @code{here} is @code{align}ed in
5291: ANS Forth (@code{maxalign}ed in Gforth).
5292:
5293: doc-align
5294: doc-falign
5295: doc-sfalign
5296: doc-dfalign
5297: doc-maxalign
5298: doc-cfalign
5299:
5300:
5301: @node Heap Allocation, Memory Access, Dictionary allocation, Memory
5302: @subsection Heap allocation
5303: @cindex heap allocation
5304: @cindex dynamic allocation of memory
5305: @cindex memory-allocation word set
5306:
1.68 anton 5307: @cindex contiguous regions and heap allocation
1.32 anton 5308: Heap allocation supports deallocation of allocated memory in any
5309: order. Dictionary allocation is not affected by it (i.e., it does not
5310: end a contiguous region). In Gforth, these words are implemented using
5311: the standard C library calls malloc(), free() and resize().
5312:
1.68 anton 5313: The memory region produced by one invocation of @code{allocate} or
5314: @code{resize} is internally contiguous. There is no contiguity between
5315: such a region and any other region (including others allocated from the
5316: heap).
5317:
1.32 anton 5318: doc-allocate
5319: doc-free
5320: doc-resize
5321:
1.27 crook 5322:
1.32 anton 5323: @node Memory Access, Address arithmetic, Heap Allocation, Memory
1.1 anton 5324: @subsection Memory Access
5325: @cindex memory access words
5326:
5327: doc-@
5328: doc-!
5329: doc-+!
5330: doc-c@
5331: doc-c!
5332: doc-2@
5333: doc-2!
5334: doc-f@
5335: doc-f!
5336: doc-sf@
5337: doc-sf!
5338: doc-df@
5339: doc-df!
5340:
1.68 anton 5341:
1.32 anton 5342: @node Address arithmetic, Memory Blocks, Memory Access, Memory
5343: @subsection Address arithmetic
1.1 anton 5344: @cindex address arithmetic words
5345:
1.67 anton 5346: Address arithmetic is the foundation on which you can build data
5347: structures like arrays, records (@pxref{Structures}) and objects
5348: (@pxref{Object-oriented Forth}).
1.32 anton 5349:
1.68 anton 5350: @cindex address unit
5351: @cindex au (address unit)
1.1 anton 5352: ANS Forth does not specify the sizes of the data types. Instead, it
5353: offers a number of words for computing sizes and doing address
1.29 crook 5354: arithmetic. Address arithmetic is performed in terms of address units
5355: (aus); on most systems the address unit is one byte. Note that a
5356: character may have more than one au, so @code{chars} is no noop (on
1.68 anton 5357: platforms where it is a noop, it compiles to nothing).
1.1 anton 5358:
1.67 anton 5359: The basic address arithmetic words are @code{+} and @code{-}. E.g., if
5360: you have the address of a cell, perform @code{1 cells +}, and you will
5361: have the address of the next cell.
5362:
1.68 anton 5363: @cindex contiguous regions and address arithmetic
1.67 anton 5364: In ANS Forth you can perform address arithmetic only within a contiguous
5365: region, i.e., if you have an address into one region, you can only add
5366: and subtract such that the result is still within the region; you can
5367: only subtract or compare addresses from within the same contiguous
5368: region. Reasons: several contiguous regions can be arranged in memory
5369: in any way; on segmented systems addresses may have unusual
5370: representations, such that address arithmetic only works within a
5371: region. Gforth provides a few more guarantees (linear address space,
5372: dictionary grows upwards), but in general I have found it easy to stay
5373: within contiguous regions (exception: computing and comparing to the
5374: address just beyond the end of an array).
5375:
1.1 anton 5376: @cindex alignment of addresses for types
5377: ANS Forth also defines words for aligning addresses for specific
5378: types. Many computers require that accesses to specific data types
5379: must only occur at specific addresses; e.g., that cells may only be
5380: accessed at addresses divisible by 4. Even if a machine allows unaligned
5381: accesses, it can usually perform aligned accesses faster.
5382:
5383: For the performance-conscious: alignment operations are usually only
5384: necessary during the definition of a data structure, not during the
5385: (more frequent) accesses to it.
5386:
5387: ANS Forth defines no words for character-aligning addresses. This is not
5388: an oversight, but reflects the fact that addresses that are not
5389: char-aligned have no use in the standard and therefore will not be
5390: created.
5391:
5392: @cindex @code{CREATE} and alignment
1.29 crook 5393: ANS Forth guarantees that addresses returned by @code{CREATE}d words
1.1 anton 5394: are cell-aligned; in addition, Gforth guarantees that these addresses
5395: are aligned for all purposes.
5396:
1.26 crook 5397: Note that the ANS Forth word @code{char} has nothing to do with address
5398: arithmetic.
1.1 anton 5399:
1.44 crook 5400:
1.1 anton 5401: doc-chars
5402: doc-char+
5403: doc-cells
5404: doc-cell+
5405: doc-cell
5406: doc-aligned
5407: doc-floats
5408: doc-float+
5409: doc-float
5410: doc-faligned
5411: doc-sfloats
5412: doc-sfloat+
5413: doc-sfaligned
5414: doc-dfloats
5415: doc-dfloat+
5416: doc-dfaligned
5417: doc-maxaligned
5418: doc-cfaligned
5419: doc-address-unit-bits
5420:
1.44 crook 5421:
1.32 anton 5422: @node Memory Blocks, , Address arithmetic, Memory
1.1 anton 5423: @subsection Memory Blocks
5424: @cindex memory block words
1.27 crook 5425: @cindex character strings - moving and copying
5426:
1.49 anton 5427: Memory blocks often represent character strings; For ways of storing
5428: character strings in memory see @ref{String Formats}. For other
5429: string-processing words see @ref{Displaying characters and strings}.
1.1 anton 5430:
1.67 anton 5431: A few of these words work on address unit blocks. In that case, you
5432: usually have to insert @code{CHARS} before the word when working on
5433: character strings. Most words work on character blocks, and expect a
5434: char-aligned address.
5435:
5436: When copying characters between overlapping memory regions, use
5437: @code{chars move} or choose carefully between @code{cmove} and
5438: @code{cmove>}.
1.44 crook 5439:
1.1 anton 5440: doc-move
5441: doc-erase
5442: doc-cmove
5443: doc-cmove>
5444: doc-fill
5445: doc-blank
1.21 crook 5446: doc-compare
1.111 anton 5447: doc-str=
5448: doc-str<
5449: doc-string-prefix?
1.21 crook 5450: doc-search
1.27 crook 5451: doc--trailing
5452: doc-/string
1.82 anton 5453: doc-bounds
1.44 crook 5454:
1.111 anton 5455:
1.27 crook 5456: @comment TODO examples
5457:
1.1 anton 5458:
1.26 crook 5459: @node Control Structures, Defining Words, Memory, Words
1.1 anton 5460: @section Control Structures
5461: @cindex control structures
5462:
1.33 anton 5463: Control structures in Forth cannot be used interpretively, only in a
5464: colon definition@footnote{To be precise, they have no interpretation
5465: semantics (@pxref{Interpretation and Compilation Semantics}).}. We do
5466: not like this limitation, but have not seen a satisfying way around it
5467: yet, although many schemes have been proposed.
1.1 anton 5468:
5469: @menu
1.33 anton 5470: * Selection:: IF ... ELSE ... ENDIF
5471: * Simple Loops:: BEGIN ...
1.29 crook 5472: * Counted Loops:: DO
1.67 anton 5473: * Arbitrary control structures::
5474: * Calls and returns::
1.1 anton 5475: * Exception Handling::
5476: @end menu
5477:
5478: @node Selection, Simple Loops, Control Structures, Control Structures
5479: @subsection Selection
5480: @cindex selection control structures
5481: @cindex control structures for selection
5482:
5483: @cindex @code{IF} control structure
5484: @example
1.29 crook 5485: @i{flag}
1.1 anton 5486: IF
1.29 crook 5487: @i{code}
1.1 anton 5488: ENDIF
5489: @end example
1.21 crook 5490: @noindent
1.33 anton 5491:
1.44 crook 5492: If @i{flag} is non-zero (as far as @code{IF} etc. are concerned, a cell
5493: with any bit set represents truth) @i{code} is executed.
1.33 anton 5494:
1.1 anton 5495: @example
1.29 crook 5496: @i{flag}
1.1 anton 5497: IF
1.29 crook 5498: @i{code1}
1.1 anton 5499: ELSE
1.29 crook 5500: @i{code2}
1.1 anton 5501: ENDIF
5502: @end example
5503:
1.44 crook 5504: If @var{flag} is true, @i{code1} is executed, otherwise @i{code2} is
5505: executed.
1.33 anton 5506:
1.1 anton 5507: You can use @code{THEN} instead of @code{ENDIF}. Indeed, @code{THEN} is
5508: standard, and @code{ENDIF} is not, although it is quite popular. We
5509: recommend using @code{ENDIF}, because it is less confusing for people
5510: who also know other languages (and is not prone to reinforcing negative
5511: prejudices against Forth in these people). Adding @code{ENDIF} to a
5512: system that only supplies @code{THEN} is simple:
5513: @example
1.82 anton 5514: : ENDIF POSTPONE then ; immediate
1.1 anton 5515: @end example
5516:
5517: [According to @cite{Webster's New Encyclopedic Dictionary}, @dfn{then
5518: (adv.)} has the following meanings:
5519: @quotation
5520: ... 2b: following next after in order ... 3d: as a necessary consequence
5521: (if you were there, then you saw them).
5522: @end quotation
5523: Forth's @code{THEN} has the meaning 2b, whereas @code{THEN} in Pascal
5524: and many other programming languages has the meaning 3d.]
5525:
1.21 crook 5526: Gforth also provides the words @code{?DUP-IF} and @code{?DUP-0=-IF}, so
1.1 anton 5527: you can avoid using @code{?dup}. Using these alternatives is also more
1.26 crook 5528: efficient than using @code{?dup}. Definitions in ANS Forth
1.1 anton 5529: for @code{ENDIF}, @code{?DUP-IF} and @code{?DUP-0=-IF} are provided in
5530: @file{compat/control.fs}.
5531:
5532: @cindex @code{CASE} control structure
5533: @example
1.29 crook 5534: @i{n}
1.1 anton 5535: CASE
1.29 crook 5536: @i{n1} OF @i{code1} ENDOF
5537: @i{n2} OF @i{code2} ENDOF
1.1 anton 5538: @dots{}
1.68 anton 5539: ( n ) @i{default-code} ( n )
1.1 anton 5540: ENDCASE
5541: @end example
5542:
1.68 anton 5543: Executes the first @i{codei}, where the @i{ni} is equal to @i{n}. If no
5544: @i{ni} matches, the optional @i{default-code} is executed. The optional
5545: default case can be added by simply writing the code after the last
5546: @code{ENDOF}. It may use @i{n}, which is on top of the stack, but must
5547: not consume it.
1.1 anton 5548:
1.69 anton 5549: @progstyle
5550: To keep the code understandable, you should ensure that on all paths
5551: through a selection construct the stack is changed in the same way
5552: (wrt. number and types of stack items consumed and pushed).
5553:
1.1 anton 5554: @node Simple Loops, Counted Loops, Selection, Control Structures
5555: @subsection Simple Loops
5556: @cindex simple loops
5557: @cindex loops without count
5558:
5559: @cindex @code{WHILE} loop
5560: @example
5561: BEGIN
1.29 crook 5562: @i{code1}
5563: @i{flag}
1.1 anton 5564: WHILE
1.29 crook 5565: @i{code2}
1.1 anton 5566: REPEAT
5567: @end example
5568:
1.29 crook 5569: @i{code1} is executed and @i{flag} is computed. If it is true,
5570: @i{code2} is executed and the loop is restarted; If @i{flag} is
1.1 anton 5571: false, execution continues after the @code{REPEAT}.
5572:
5573: @cindex @code{UNTIL} loop
5574: @example
5575: BEGIN
1.29 crook 5576: @i{code}
5577: @i{flag}
1.1 anton 5578: UNTIL
5579: @end example
5580:
1.29 crook 5581: @i{code} is executed. The loop is restarted if @code{flag} is false.
1.1 anton 5582:
1.69 anton 5583: @progstyle
5584: To keep the code understandable, a complete iteration of the loop should
5585: not change the number and types of the items on the stacks.
5586:
1.1 anton 5587: @cindex endless loop
5588: @cindex loops, endless
5589: @example
5590: BEGIN
1.29 crook 5591: @i{code}
1.1 anton 5592: AGAIN
5593: @end example
5594:
5595: This is an endless loop.
5596:
5597: @node Counted Loops, Arbitrary control structures, Simple Loops, Control Structures
5598: @subsection Counted Loops
5599: @cindex counted loops
5600: @cindex loops, counted
5601: @cindex @code{DO} loops
5602:
5603: The basic counted loop is:
5604: @example
1.29 crook 5605: @i{limit} @i{start}
1.1 anton 5606: ?DO
1.29 crook 5607: @i{body}
1.1 anton 5608: LOOP
5609: @end example
5610:
1.29 crook 5611: This performs one iteration for every integer, starting from @i{start}
5612: and up to, but excluding @i{limit}. The counter, or @i{index}, can be
1.21 crook 5613: accessed with @code{i}. For example, the loop:
1.1 anton 5614: @example
5615: 10 0 ?DO
5616: i .
5617: LOOP
5618: @end example
1.21 crook 5619: @noindent
5620: prints @code{0 1 2 3 4 5 6 7 8 9}
5621:
1.1 anton 5622: The index of the innermost loop can be accessed with @code{i}, the index
5623: of the next loop with @code{j}, and the index of the third loop with
5624: @code{k}.
5625:
1.44 crook 5626:
1.1 anton 5627: doc-i
5628: doc-j
5629: doc-k
5630:
1.44 crook 5631:
1.1 anton 5632: The loop control data are kept on the return stack, so there are some
1.21 crook 5633: restrictions on mixing return stack accesses and counted loop words. In
5634: particuler, if you put values on the return stack outside the loop, you
5635: cannot read them inside the loop@footnote{well, not in a way that is
5636: portable.}. If you put values on the return stack within a loop, you
5637: have to remove them before the end of the loop and before accessing the
5638: index of the loop.
1.1 anton 5639:
5640: There are several variations on the counted loop:
5641:
1.21 crook 5642: @itemize @bullet
5643: @item
5644: @code{LEAVE} leaves the innermost counted loop immediately; execution
5645: continues after the associated @code{LOOP} or @code{NEXT}. For example:
5646:
5647: @example
5648: 10 0 ?DO i DUP . 3 = IF LEAVE THEN LOOP
5649: @end example
5650: prints @code{0 1 2 3}
5651:
1.1 anton 5652:
1.21 crook 5653: @item
5654: @code{UNLOOP} prepares for an abnormal loop exit, e.g., via
5655: @code{EXIT}. @code{UNLOOP} removes the loop control parameters from the
5656: return stack so @code{EXIT} can get to its return address. For example:
5657:
5658: @example
5659: : demo 10 0 ?DO i DUP . 3 = IF UNLOOP EXIT THEN LOOP ." Done" ;
5660: @end example
5661: prints @code{0 1 2 3}
5662:
5663:
5664: @item
1.29 crook 5665: If @i{start} is greater than @i{limit}, a @code{?DO} loop is entered
1.1 anton 5666: (and @code{LOOP} iterates until they become equal by wrap-around
5667: arithmetic). This behaviour is usually not what you want. Therefore,
5668: Gforth offers @code{+DO} and @code{U+DO} (as replacements for
1.29 crook 5669: @code{?DO}), which do not enter the loop if @i{start} is greater than
5670: @i{limit}; @code{+DO} is for signed loop parameters, @code{U+DO} for
1.1 anton 5671: unsigned loop parameters.
5672:
1.21 crook 5673: @item
5674: @code{?DO} can be replaced by @code{DO}. @code{DO} always enters
5675: the loop, independent of the loop parameters. Do not use @code{DO}, even
5676: if you know that the loop is entered in any case. Such knowledge tends
5677: to become invalid during maintenance of a program, and then the
5678: @code{DO} will make trouble.
5679:
5680: @item
1.29 crook 5681: @code{LOOP} can be replaced with @code{@i{n} +LOOP}; this updates the
5682: index by @i{n} instead of by 1. The loop is terminated when the border
5683: between @i{limit-1} and @i{limit} is crossed. E.g.:
1.1 anton 5684:
1.21 crook 5685: @example
5686: 4 0 +DO i . 2 +LOOP
5687: @end example
5688: @noindent
5689: prints @code{0 2}
5690:
5691: @example
5692: 4 1 +DO i . 2 +LOOP
5693: @end example
5694: @noindent
5695: prints @code{1 3}
1.1 anton 5696:
1.68 anton 5697: @item
1.1 anton 5698: @cindex negative increment for counted loops
5699: @cindex counted loops with negative increment
1.29 crook 5700: The behaviour of @code{@i{n} +LOOP} is peculiar when @i{n} is negative:
1.1 anton 5701:
1.21 crook 5702: @example
5703: -1 0 ?DO i . -1 +LOOP
5704: @end example
5705: @noindent
5706: prints @code{0 -1}
1.1 anton 5707:
1.21 crook 5708: @example
5709: 0 0 ?DO i . -1 +LOOP
5710: @end example
5711: prints nothing.
1.1 anton 5712:
1.29 crook 5713: Therefore we recommend avoiding @code{@i{n} +LOOP} with negative
5714: @i{n}. One alternative is @code{@i{u} -LOOP}, which reduces the
5715: index by @i{u} each iteration. The loop is terminated when the border
5716: between @i{limit+1} and @i{limit} is crossed. Gforth also provides
1.1 anton 5717: @code{-DO} and @code{U-DO} for down-counting loops. E.g.:
5718:
1.21 crook 5719: @example
5720: -2 0 -DO i . 1 -LOOP
5721: @end example
5722: @noindent
5723: prints @code{0 -1}
1.1 anton 5724:
1.21 crook 5725: @example
5726: -1 0 -DO i . 1 -LOOP
5727: @end example
5728: @noindent
5729: prints @code{0}
5730:
5731: @example
5732: 0 0 -DO i . 1 -LOOP
5733: @end example
5734: @noindent
5735: prints nothing.
1.1 anton 5736:
1.21 crook 5737: @end itemize
1.1 anton 5738:
5739: Unfortunately, @code{+DO}, @code{U+DO}, @code{-DO}, @code{U-DO} and
1.26 crook 5740: @code{-LOOP} are not defined in ANS Forth. However, an implementation
5741: for these words that uses only standard words is provided in
5742: @file{compat/loops.fs}.
1.1 anton 5743:
5744:
5745: @cindex @code{FOR} loops
1.26 crook 5746: Another counted loop is:
1.1 anton 5747: @example
1.29 crook 5748: @i{n}
1.1 anton 5749: FOR
1.29 crook 5750: @i{body}
1.1 anton 5751: NEXT
5752: @end example
5753: This is the preferred loop of native code compiler writers who are too
1.26 crook 5754: lazy to optimize @code{?DO} loops properly. This loop structure is not
1.29 crook 5755: defined in ANS Forth. In Gforth, this loop iterates @i{n+1} times;
5756: @code{i} produces values starting with @i{n} and ending with 0. Other
1.26 crook 5757: Forth systems may behave differently, even if they support @code{FOR}
5758: loops. To avoid problems, don't use @code{FOR} loops.
1.1 anton 5759:
5760: @node Arbitrary control structures, Calls and returns, Counted Loops, Control Structures
5761: @subsection Arbitrary control structures
5762: @cindex control structures, user-defined
5763:
5764: @cindex control-flow stack
5765: ANS Forth permits and supports using control structures in a non-nested
5766: way. Information about incomplete control structures is stored on the
5767: control-flow stack. This stack may be implemented on the Forth data
5768: stack, and this is what we have done in Gforth.
5769:
5770: @cindex @code{orig}, control-flow stack item
5771: @cindex @code{dest}, control-flow stack item
5772: An @i{orig} entry represents an unresolved forward branch, a @i{dest}
5773: entry represents a backward branch target. A few words are the basis for
5774: building any control structure possible (except control structures that
5775: need storage, like calls, coroutines, and backtracking).
5776:
1.44 crook 5777:
1.1 anton 5778: doc-if
5779: doc-ahead
5780: doc-then
5781: doc-begin
5782: doc-until
5783: doc-again
5784: doc-cs-pick
5785: doc-cs-roll
5786:
1.44 crook 5787:
1.21 crook 5788: The Standard words @code{CS-PICK} and @code{CS-ROLL} allow you to
5789: manipulate the control-flow stack in a portable way. Without them, you
5790: would need to know how many stack items are occupied by a control-flow
5791: entry (many systems use one cell. In Gforth they currently take three,
5792: but this may change in the future).
5793:
1.1 anton 5794: Some standard control structure words are built from these words:
5795:
1.44 crook 5796:
1.1 anton 5797: doc-else
5798: doc-while
5799: doc-repeat
5800:
1.44 crook 5801:
5802: @noindent
1.1 anton 5803: Gforth adds some more control-structure words:
5804:
1.44 crook 5805:
1.1 anton 5806: doc-endif
5807: doc-?dup-if
5808: doc-?dup-0=-if
5809:
1.44 crook 5810:
5811: @noindent
1.1 anton 5812: Counted loop words constitute a separate group of words:
5813:
1.44 crook 5814:
1.1 anton 5815: doc-?do
5816: doc-+do
5817: doc-u+do
5818: doc--do
5819: doc-u-do
5820: doc-do
5821: doc-for
5822: doc-loop
5823: doc-+loop
5824: doc--loop
5825: doc-next
5826: doc-leave
5827: doc-?leave
5828: doc-unloop
5829: doc-done
5830:
1.44 crook 5831:
1.21 crook 5832: The standard does not allow using @code{CS-PICK} and @code{CS-ROLL} on
5833: @i{do-sys}. Gforth allows it, but it's your job to ensure that for
1.1 anton 5834: every @code{?DO} etc. there is exactly one @code{UNLOOP} on any path
5835: through the definition (@code{LOOP} etc. compile an @code{UNLOOP} on the
5836: fall-through path). Also, you have to ensure that all @code{LEAVE}s are
5837: resolved (by using one of the loop-ending words or @code{DONE}).
5838:
1.44 crook 5839: @noindent
1.26 crook 5840: Another group of control structure words are:
1.1 anton 5841:
1.44 crook 5842:
1.1 anton 5843: doc-case
5844: doc-endcase
5845: doc-of
5846: doc-endof
5847:
1.44 crook 5848:
1.21 crook 5849: @i{case-sys} and @i{of-sys} cannot be processed using @code{CS-PICK} and
5850: @code{CS-ROLL}.
1.1 anton 5851:
5852: @subsubsection Programming Style
1.47 crook 5853: @cindex control structures programming style
5854: @cindex programming style, arbitrary control structures
1.1 anton 5855:
5856: In order to ensure readability we recommend that you do not create
5857: arbitrary control structures directly, but define new control structure
5858: words for the control structure you want and use these words in your
1.26 crook 5859: program. For example, instead of writing:
1.1 anton 5860:
5861: @example
1.26 crook 5862: BEGIN
1.1 anton 5863: ...
1.26 crook 5864: IF [ 1 CS-ROLL ]
1.1 anton 5865: ...
1.26 crook 5866: AGAIN THEN
1.1 anton 5867: @end example
5868:
1.21 crook 5869: @noindent
1.1 anton 5870: we recommend defining control structure words, e.g.,
5871:
5872: @example
1.26 crook 5873: : WHILE ( DEST -- ORIG DEST )
5874: POSTPONE IF
5875: 1 CS-ROLL ; immediate
5876:
5877: : REPEAT ( orig dest -- )
5878: POSTPONE AGAIN
5879: POSTPONE THEN ; immediate
1.1 anton 5880: @end example
5881:
1.21 crook 5882: @noindent
1.1 anton 5883: and then using these to create the control structure:
5884:
5885: @example
1.26 crook 5886: BEGIN
1.1 anton 5887: ...
1.26 crook 5888: WHILE
1.1 anton 5889: ...
1.26 crook 5890: REPEAT
1.1 anton 5891: @end example
5892:
5893: That's much easier to read, isn't it? Of course, @code{REPEAT} and
5894: @code{WHILE} are predefined, so in this example it would not be
5895: necessary to define them.
5896:
5897: @node Calls and returns, Exception Handling, Arbitrary control structures, Control Structures
5898: @subsection Calls and returns
5899: @cindex calling a definition
5900: @cindex returning from a definition
5901:
1.3 anton 5902: @cindex recursive definitions
5903: A definition can be called simply be writing the name of the definition
1.26 crook 5904: to be called. Normally a definition is invisible during its own
1.3 anton 5905: definition. If you want to write a directly recursive definition, you
1.26 crook 5906: can use @code{recursive} to make the current definition visible, or
5907: @code{recurse} to call the current definition directly.
1.3 anton 5908:
1.44 crook 5909:
1.3 anton 5910: doc-recursive
5911: doc-recurse
5912:
1.44 crook 5913:
1.21 crook 5914: @comment TODO add example of the two recursion methods
1.12 anton 5915: @quotation
5916: @progstyle
5917: I prefer using @code{recursive} to @code{recurse}, because calling the
5918: definition by name is more descriptive (if the name is well-chosen) than
5919: the somewhat cryptic @code{recurse}. E.g., in a quicksort
5920: implementation, it is much better to read (and think) ``now sort the
5921: partitions'' than to read ``now do a recursive call''.
5922: @end quotation
1.3 anton 5923:
1.29 crook 5924: For mutual recursion, use @code{Defer}red words, like this:
1.3 anton 5925:
5926: @example
1.28 crook 5927: Defer foo
1.3 anton 5928:
5929: : bar ( ... -- ... )
5930: ... foo ... ;
5931:
5932: :noname ( ... -- ... )
5933: ... bar ... ;
5934: IS foo
5935: @end example
5936:
1.44 crook 5937: Deferred words are discussed in more detail in @ref{Deferred words}.
1.33 anton 5938:
1.26 crook 5939: The current definition returns control to the calling definition when
1.33 anton 5940: the end of the definition is reached or @code{EXIT} is encountered.
1.1 anton 5941:
5942: doc-exit
5943: doc-;s
5944:
1.44 crook 5945:
1.1 anton 5946: @node Exception Handling, , Calls and returns, Control Structures
5947: @subsection Exception Handling
1.26 crook 5948: @cindex exceptions
1.1 anton 5949:
1.68 anton 5950: @c quit is a very bad idea for error handling,
5951: @c because it does not translate into a THROW
5952: @c it also does not belong into this chapter
5953:
5954: If a word detects an error condition that it cannot handle, it can
5955: @code{throw} an exception. In the simplest case, this will terminate
5956: your program, and report an appropriate error.
1.21 crook 5957:
1.68 anton 5958: doc-throw
1.1 anton 5959:
1.69 anton 5960: @code{Throw} consumes a cell-sized error number on the stack. There are
5961: some predefined error numbers in ANS Forth (see @file{errors.fs}). In
5962: Gforth (and most other systems) you can use the iors produced by various
5963: words as error numbers (e.g., a typical use of @code{allocate} is
5964: @code{allocate throw}). Gforth also provides the word @code{exception}
5965: to define your own error numbers (with decent error reporting); an ANS
5966: Forth version of this word (but without the error messages) is available
5967: in @code{compat/except.fs}. And finally, you can use your own error
1.68 anton 5968: numbers (anything outside the range -4095..0), but won't get nice error
5969: messages, only numbers. For example, try:
5970:
5971: @example
1.69 anton 5972: -10 throw \ ANS defined
5973: -267 throw \ system defined
5974: s" my error" exception throw \ user defined
5975: 7 throw \ arbitrary number
1.68 anton 5976: @end example
5977:
5978: doc---exception-exception
1.1 anton 5979:
1.69 anton 5980: A common idiom to @code{THROW} a specific error if a flag is true is
5981: this:
5982:
5983: @example
5984: @code{( flag ) 0<> @i{errno} and throw}
5985: @end example
5986:
5987: Your program can provide exception handlers to catch exceptions. An
5988: exception handler can be used to correct the problem, or to clean up
5989: some data structures and just throw the exception to the next exception
5990: handler. Note that @code{throw} jumps to the dynamically innermost
5991: exception handler. The system's exception handler is outermost, and just
5992: prints an error and restarts command-line interpretation (or, in batch
5993: mode (i.e., while processing the shell command line), leaves Gforth).
1.1 anton 5994:
1.68 anton 5995: The ANS Forth way to catch exceptions is @code{catch}:
1.1 anton 5996:
1.68 anton 5997: doc-catch
5998:
5999: The most common use of exception handlers is to clean up the state when
6000: an error happens. E.g.,
1.1 anton 6001:
1.26 crook 6002: @example
1.68 anton 6003: base @ >r hex \ actually the hex should be inside foo, or we h
6004: ['] foo catch ( nerror|0 )
6005: r> base !
1.69 anton 6006: ( nerror|0 ) throw \ pass it on
1.26 crook 6007: @end example
1.1 anton 6008:
1.69 anton 6009: A use of @code{catch} for handling the error @code{myerror} might look
6010: like this:
1.44 crook 6011:
1.68 anton 6012: @example
1.69 anton 6013: ['] foo catch
6014: CASE
6015: myerror OF ... ( do something about it ) ENDOF
6016: dup throw \ default: pass other errors on, do nothing on non-errors
6017: ENDCASE
1.68 anton 6018: @end example
1.44 crook 6019:
1.68 anton 6020: Having to wrap the code into a separate word is often cumbersome,
6021: therefore Gforth provides an alternative syntax:
1.1 anton 6022:
6023: @example
1.69 anton 6024: TRY
1.68 anton 6025: @i{code1}
1.69 anton 6026: RECOVER \ optional
1.68 anton 6027: @i{code2} \ optional
1.69 anton 6028: ENDTRY
1.1 anton 6029: @end example
6030:
1.68 anton 6031: This performs @i{Code1}. If @i{code1} completes normally, execution
6032: continues after the @code{endtry}. If @i{Code1} throws, the stacks are
6033: reset to the state during @code{try}, the throw value is pushed on the
6034: data stack, and execution constinues at @i{code2}, and finally falls
1.92 anton 6035: through the @code{endtry} into the following code.
1.26 crook 6036:
1.68 anton 6037: doc-try
6038: doc-recover
6039: doc-endtry
1.26 crook 6040:
1.69 anton 6041: The cleanup example from above in this syntax:
1.26 crook 6042:
1.68 anton 6043: @example
1.69 anton 6044: base @ >r TRY
1.68 anton 6045: hex foo \ now the hex is placed correctly
1.69 anton 6046: 0 \ value for throw
1.92 anton 6047: RECOVER ENDTRY
1.68 anton 6048: r> base ! throw
1.1 anton 6049: @end example
6050:
1.69 anton 6051: And here's the error handling example:
1.1 anton 6052:
1.68 anton 6053: @example
1.69 anton 6054: TRY
1.68 anton 6055: foo
1.69 anton 6056: RECOVER
6057: CASE
6058: myerror OF ... ( do something about it ) ENDOF
6059: throw \ pass other errors on
6060: ENDCASE
6061: ENDTRY
1.68 anton 6062: @end example
1.1 anton 6063:
1.69 anton 6064: @progstyle
6065: As usual, you should ensure that the stack depth is statically known at
6066: the end: either after the @code{throw} for passing on errors, or after
6067: the @code{ENDTRY} (or, if you use @code{catch}, after the end of the
6068: selection construct for handling the error).
6069:
1.68 anton 6070: There are two alternatives to @code{throw}: @code{Abort"} is conditional
6071: and you can provide an error message. @code{Abort} just produces an
6072: ``Aborted'' error.
1.1 anton 6073:
1.68 anton 6074: The problem with these words is that exception handlers cannot
6075: differentiate between different @code{abort"}s; they just look like
6076: @code{-2 throw} to them (the error message cannot be accessed by
6077: standard programs). Similar @code{abort} looks like @code{-1 throw} to
6078: exception handlers.
1.44 crook 6079:
1.68 anton 6080: doc-abort"
1.26 crook 6081: doc-abort
1.29 crook 6082:
6083:
1.44 crook 6084:
1.29 crook 6085: @c -------------------------------------------------------------
1.47 crook 6086: @node Defining Words, Interpretation and Compilation Semantics, Control Structures, Words
1.29 crook 6087: @section Defining Words
6088: @cindex defining words
6089:
1.47 crook 6090: Defining words are used to extend Forth by creating new entries in the dictionary.
6091:
1.29 crook 6092: @menu
1.67 anton 6093: * CREATE::
1.44 crook 6094: * Variables:: Variables and user variables
1.67 anton 6095: * Constants::
1.44 crook 6096: * Values:: Initialised variables
1.67 anton 6097: * Colon Definitions::
1.44 crook 6098: * Anonymous Definitions:: Definitions without names
1.69 anton 6099: * Supplying names:: Passing definition names as strings
1.67 anton 6100: * User-defined Defining Words::
1.44 crook 6101: * Deferred words:: Allow forward references
1.67 anton 6102: * Aliases::
1.29 crook 6103: @end menu
6104:
1.44 crook 6105: @node CREATE, Variables, Defining Words, Defining Words
6106: @subsection @code{CREATE}
1.29 crook 6107: @cindex simple defining words
6108: @cindex defining words, simple
6109:
6110: Defining words are used to create new entries in the dictionary. The
6111: simplest defining word is @code{CREATE}. @code{CREATE} is used like
6112: this:
6113:
6114: @example
6115: CREATE new-word1
6116: @end example
6117:
1.69 anton 6118: @code{CREATE} is a parsing word, i.e., it takes an argument from the
6119: input stream (@code{new-word1} in our example). It generates a
6120: dictionary entry for @code{new-word1}. When @code{new-word1} is
6121: executed, all that it does is leave an address on the stack. The address
6122: represents the value of the data space pointer (@code{HERE}) at the time
6123: that @code{new-word1} was defined. Therefore, @code{CREATE} is a way of
6124: associating a name with the address of a region of memory.
1.29 crook 6125:
1.34 anton 6126: doc-create
6127:
1.69 anton 6128: Note that in ANS Forth guarantees only for @code{create} that its body
6129: is in dictionary data space (i.e., where @code{here}, @code{allot}
6130: etc. work, @pxref{Dictionary allocation}). Also, in ANS Forth only
6131: @code{create}d words can be modified with @code{does>}
6132: (@pxref{User-defined Defining Words}). And in ANS Forth @code{>body}
6133: can only be applied to @code{create}d words.
6134:
1.29 crook 6135: By extending this example to reserve some memory in data space, we end
1.69 anton 6136: up with something like a @i{variable}. Here are two different ways to do
6137: it:
1.29 crook 6138:
6139: @example
6140: CREATE new-word2 1 cells allot \ reserve 1 cell - initial value undefined
6141: CREATE new-word3 4 , \ reserve 1 cell and initialise it (to 4)
6142: @end example
6143:
6144: The variable can be examined and modified using @code{@@} (``fetch'') and
6145: @code{!} (``store'') like this:
6146:
6147: @example
6148: new-word2 @@ . \ get address, fetch from it and display
6149: 1234 new-word2 ! \ new value, get address, store to it
6150: @end example
6151:
1.44 crook 6152: @cindex arrays
6153: A similar mechanism can be used to create arrays. For example, an
6154: 80-character text input buffer:
1.29 crook 6155:
6156: @example
1.44 crook 6157: CREATE text-buf 80 chars allot
6158:
6159: text-buf 0 chars c@@ \ the 1st character (offset 0)
6160: text-buf 3 chars c@@ \ the 4th character (offset 3)
6161: @end example
1.29 crook 6162:
1.44 crook 6163: You can build arbitrarily complex data structures by allocating
1.49 anton 6164: appropriate areas of memory. For further discussions of this, and to
1.66 anton 6165: learn about some Gforth tools that make it easier,
1.49 anton 6166: @xref{Structures}.
1.44 crook 6167:
6168:
6169: @node Variables, Constants, CREATE, Defining Words
6170: @subsection Variables
6171: @cindex variables
6172:
6173: The previous section showed how a sequence of commands could be used to
6174: generate a variable. As a final refinement, the whole code sequence can
6175: be wrapped up in a defining word (pre-empting the subject of the next
6176: section), making it easier to create new variables:
6177:
6178: @example
6179: : myvariableX ( "name" -- a-addr ) CREATE 1 cells allot ;
6180: : myvariable0 ( "name" -- a-addr ) CREATE 0 , ;
6181:
6182: myvariableX foo \ variable foo starts off with an unknown value
6183: myvariable0 joe \ whilst joe is initialised to 0
1.29 crook 6184:
6185: 45 3 * foo ! \ set foo to 135
6186: 1234 joe ! \ set joe to 1234
6187: 3 joe +! \ increment joe by 3.. to 1237
6188: @end example
6189:
6190: Not surprisingly, there is no need to define @code{myvariable}, since
1.44 crook 6191: Forth already has a definition @code{Variable}. ANS Forth does not
1.69 anton 6192: guarantee that a @code{Variable} is initialised when it is created
6193: (i.e., it may behave like @code{myvariableX}). In contrast, Gforth's
6194: @code{Variable} initialises the variable to 0 (i.e., it behaves exactly
6195: like @code{myvariable0}). Forth also provides @code{2Variable} and
1.47 crook 6196: @code{fvariable} for double and floating-point variables, respectively
1.69 anton 6197: -- they are initialised to 0. and 0e in Gforth. If you use a @code{Variable} to
1.47 crook 6198: store a boolean, you can use @code{on} and @code{off} to toggle its
6199: state.
1.29 crook 6200:
1.34 anton 6201: doc-variable
6202: doc-2variable
6203: doc-fvariable
6204:
1.29 crook 6205: @cindex user variables
6206: @cindex user space
6207: The defining word @code{User} behaves in the same way as @code{Variable}.
6208: The difference is that it reserves space in @i{user (data) space} rather
6209: than normal data space. In a Forth system that has a multi-tasker, each
6210: task has its own set of user variables.
6211:
1.34 anton 6212: doc-user
1.67 anton 6213: @c doc-udp
6214: @c doc-uallot
1.34 anton 6215:
1.29 crook 6216: @comment TODO is that stuff about user variables strictly correct? Is it
6217: @comment just terminal tasks that have user variables?
6218: @comment should document tasker.fs (with some examples) elsewhere
6219: @comment in this manual, then expand on user space and user variables.
6220:
1.44 crook 6221: @node Constants, Values, Variables, Defining Words
6222: @subsection Constants
6223: @cindex constants
6224:
6225: @code{Constant} allows you to declare a fixed value and refer to it by
6226: name. For example:
1.29 crook 6227:
6228: @example
6229: 12 Constant INCHES-PER-FOOT
6230: 3E+08 fconstant SPEED-O-LIGHT
6231: @end example
6232:
6233: A @code{Variable} can be both read and written, so its run-time
6234: behaviour is to supply an address through which its current value can be
6235: manipulated. In contrast, the value of a @code{Constant} cannot be
6236: changed once it has been declared@footnote{Well, often it can be -- but
6237: not in a Standard, portable way. It's safer to use a @code{Value} (read
6238: on).} so it's not necessary to supply the address -- it is more
6239: efficient to return the value of the constant directly. That's exactly
6240: what happens; the run-time effect of a constant is to put its value on
1.49 anton 6241: the top of the stack (You can find one
6242: way of implementing @code{Constant} in @ref{User-defined Defining Words}).
1.29 crook 6243:
1.69 anton 6244: Forth also provides @code{2Constant} and @code{fconstant} for defining
1.29 crook 6245: double and floating-point constants, respectively.
6246:
1.34 anton 6247: doc-constant
6248: doc-2constant
6249: doc-fconstant
6250:
6251: @c that's too deep, and it's not necessarily true for all ANS Forths. - anton
1.44 crook 6252: @c nac-> How could that not be true in an ANS Forth? You can't define a
6253: @c constant, use it and then delete the definition of the constant..
1.69 anton 6254:
6255: @c anton->An ANS Forth system can compile a constant to a literal; On
6256: @c decompilation you would see only the number, just as if it had been used
6257: @c in the first place. The word will stay, of course, but it will only be
6258: @c used by the text interpreter (no run-time duties, except when it is
6259: @c POSTPONEd or somesuch).
6260:
6261: @c nac:
1.44 crook 6262: @c I agree that it's rather deep, but IMO it is an important difference
6263: @c relative to other programming languages.. often it's annoying: it
6264: @c certainly changes my programming style relative to C.
6265:
1.69 anton 6266: @c anton: In what way?
6267:
1.29 crook 6268: Constants in Forth behave differently from their equivalents in other
6269: programming languages. In other languages, a constant (such as an EQU in
6270: assembler or a #define in C) only exists at compile-time; in the
6271: executable program the constant has been translated into an absolute
6272: number and, unless you are using a symbolic debugger, it's impossible to
6273: know what abstract thing that number represents. In Forth a constant has
1.44 crook 6274: an entry in the header space and remains there after the code that uses
6275: it has been defined. In fact, it must remain in the dictionary since it
6276: has run-time duties to perform. For example:
1.29 crook 6277:
6278: @example
6279: 12 Constant INCHES-PER-FOOT
6280: : FEET-TO-INCHES ( n1 -- n2 ) INCHES-PER-FOOT * ;
6281: @end example
6282:
6283: @cindex in-lining of constants
6284: When @code{FEET-TO-INCHES} is executed, it will in turn execute the xt
6285: associated with the constant @code{INCHES-PER-FOOT}. If you use
6286: @code{see} to decompile the definition of @code{FEET-TO-INCHES}, you can
6287: see that it makes a call to @code{INCHES-PER-FOOT}. Some Forth compilers
6288: attempt to optimise constants by in-lining them where they are used. You
6289: can force Gforth to in-line a constant like this:
6290:
6291: @example
6292: : FEET-TO-INCHES ( n1 -- n2 ) [ INCHES-PER-FOOT ] LITERAL * ;
6293: @end example
6294:
6295: If you use @code{see} to decompile @i{this} version of
6296: @code{FEET-TO-INCHES}, you can see that @code{INCHES-PER-FOOT} is no
1.49 anton 6297: longer present. To understand how this works, read
6298: @ref{Interpret/Compile states}, and @ref{Literals}.
1.29 crook 6299:
6300: In-lining constants in this way might improve execution time
6301: fractionally, and can ensure that a constant is now only referenced at
6302: compile-time. However, the definition of the constant still remains in
6303: the dictionary. Some Forth compilers provide a mechanism for controlling
6304: a second dictionary for holding transient words such that this second
6305: dictionary can be deleted later in order to recover memory
6306: space. However, there is no standard way of doing this.
6307:
6308:
1.44 crook 6309: @node Values, Colon Definitions, Constants, Defining Words
6310: @subsection Values
6311: @cindex values
1.34 anton 6312:
1.69 anton 6313: A @code{Value} behaves like a @code{Constant}, but it can be changed.
6314: @code{TO} is a parsing word that changes a @code{Values}. In Gforth
6315: (not in ANS Forth) you can access (and change) a @code{value} also with
6316: @code{>body}.
6317:
6318: Here are some
6319: examples:
1.29 crook 6320:
6321: @example
1.69 anton 6322: 12 Value APPLES \ Define APPLES with an initial value of 12
6323: 34 TO APPLES \ Change the value of APPLES. TO is a parsing word
6324: 1 ' APPLES >body +! \ Increment APPLES. Non-standard usage.
6325: APPLES \ puts 35 on the top of the stack.
1.29 crook 6326: @end example
6327:
1.44 crook 6328: doc-value
6329: doc-to
1.29 crook 6330:
1.35 anton 6331:
1.69 anton 6332:
1.44 crook 6333: @node Colon Definitions, Anonymous Definitions, Values, Defining Words
6334: @subsection Colon Definitions
6335: @cindex colon definitions
1.35 anton 6336:
6337: @example
1.44 crook 6338: : name ( ... -- ... )
6339: word1 word2 word3 ;
1.29 crook 6340: @end example
6341:
1.44 crook 6342: @noindent
6343: Creates a word called @code{name} that, upon execution, executes
6344: @code{word1 word2 word3}. @code{name} is a @dfn{(colon) definition}.
1.29 crook 6345:
1.49 anton 6346: The explanation above is somewhat superficial. For simple examples of
6347: colon definitions see @ref{Your first definition}. For an in-depth
1.66 anton 6348: discussion of some of the issues involved, @xref{Interpretation and
1.49 anton 6349: Compilation Semantics}.
1.29 crook 6350:
1.44 crook 6351: doc-:
6352: doc-;
1.1 anton 6353:
1.34 anton 6354:
1.69 anton 6355: @node Anonymous Definitions, Supplying names, Colon Definitions, Defining Words
1.44 crook 6356: @subsection Anonymous Definitions
6357: @cindex colon definitions
6358: @cindex defining words without name
1.34 anton 6359:
1.44 crook 6360: Sometimes you want to define an @dfn{anonymous word}; a word without a
6361: name. You can do this with:
1.1 anton 6362:
1.44 crook 6363: doc-:noname
1.1 anton 6364:
1.44 crook 6365: This leaves the execution token for the word on the stack after the
6366: closing @code{;}. Here's an example in which a deferred word is
6367: initialised with an @code{xt} from an anonymous colon definition:
1.1 anton 6368:
1.29 crook 6369: @example
1.44 crook 6370: Defer deferred
6371: :noname ( ... -- ... )
6372: ... ;
6373: IS deferred
1.29 crook 6374: @end example
1.26 crook 6375:
1.44 crook 6376: @noindent
6377: Gforth provides an alternative way of doing this, using two separate
6378: words:
1.27 crook 6379:
1.44 crook 6380: doc-noname
6381: @cindex execution token of last defined word
6382: doc-lastxt
1.1 anton 6383:
1.44 crook 6384: @noindent
6385: The previous example can be rewritten using @code{noname} and
6386: @code{lastxt}:
1.1 anton 6387:
1.26 crook 6388: @example
1.44 crook 6389: Defer deferred
6390: noname : ( ... -- ... )
6391: ... ;
6392: lastxt IS deferred
1.26 crook 6393: @end example
1.1 anton 6394:
1.29 crook 6395: @noindent
1.44 crook 6396: @code{noname} works with any defining word, not just @code{:}.
6397:
6398: @code{lastxt} also works when the last word was not defined as
1.71 anton 6399: @code{noname}. It does not work for combined words, though. It also has
6400: the useful property that is is valid as soon as the header for a
6401: definition has been built. Thus:
1.44 crook 6402:
6403: @example
6404: lastxt . : foo [ lastxt . ] ; ' foo .
6405: @end example
1.1 anton 6406:
1.44 crook 6407: @noindent
6408: prints 3 numbers; the last two are the same.
1.26 crook 6409:
1.69 anton 6410: @node Supplying names, User-defined Defining Words, Anonymous Definitions, Defining Words
6411: @subsection Supplying the name of a defined word
6412: @cindex names for defined words
6413: @cindex defining words, name given in a string
6414:
6415: By default, a defining word takes the name for the defined word from the
6416: input stream. Sometimes you want to supply the name from a string. You
6417: can do this with:
6418:
6419: doc-nextname
6420:
6421: For example:
6422:
6423: @example
6424: s" foo" nextname create
6425: @end example
6426:
6427: @noindent
6428: is equivalent to:
6429:
6430: @example
6431: create foo
6432: @end example
6433:
6434: @noindent
6435: @code{nextname} works with any defining word.
6436:
1.1 anton 6437:
1.69 anton 6438: @node User-defined Defining Words, Deferred words, Supplying names, Defining Words
1.26 crook 6439: @subsection User-defined Defining Words
6440: @cindex user-defined defining words
6441: @cindex defining words, user-defined
1.1 anton 6442:
1.29 crook 6443: You can create a new defining word by wrapping defining-time code around
6444: an existing defining word and putting the sequence in a colon
1.69 anton 6445: definition.
6446:
6447: @c anton: This example is very complex and leads in a quite different
6448: @c direction from the CREATE-DOES> stuff that follows. It should probably
6449: @c be done elsewhere, or as a subsubsection of this subsection (or as a
6450: @c subsection of Defining Words)
6451:
6452: For example, suppose that you have a word @code{stats} that
1.29 crook 6453: gathers statistics about colon definitions given the @i{xt} of the
6454: definition, and you want every colon definition in your application to
6455: make a call to @code{stats}. You can define and use a new version of
6456: @code{:} like this:
6457:
6458: @example
6459: : stats ( xt -- ) DUP ." (Gathering statistics for " . ." )"
6460: ... ; \ other code
6461:
6462: : my: : lastxt postpone literal ['] stats compile, ;
6463:
6464: my: foo + - ;
6465: @end example
6466:
6467: When @code{foo} is defined using @code{my:} these steps occur:
6468:
6469: @itemize @bullet
6470: @item
6471: @code{my:} is executed.
6472: @item
6473: The @code{:} within the definition (the one between @code{my:} and
6474: @code{lastxt}) is executed, and does just what it always does; it parses
6475: the input stream for a name, builds a dictionary header for the name
6476: @code{foo} and switches @code{state} from interpret to compile.
6477: @item
6478: The word @code{lastxt} is executed. It puts the @i{xt} for the word that is
6479: being defined -- @code{foo} -- onto the stack.
6480: @item
6481: The code that was produced by @code{postpone literal} is executed; this
6482: causes the value on the stack to be compiled as a literal in the code
6483: area of @code{foo}.
6484: @item
6485: The code @code{['] stats} compiles a literal into the definition of
6486: @code{my:}. When @code{compile,} is executed, that literal -- the
6487: execution token for @code{stats} -- is layed down in the code area of
6488: @code{foo} , following the literal@footnote{Strictly speaking, the
6489: mechanism that @code{compile,} uses to convert an @i{xt} into something
6490: in the code area is implementation-dependent. A threaded implementation
6491: might spit out the execution token directly whilst another
6492: implementation might spit out a native code sequence.}.
6493: @item
6494: At this point, the execution of @code{my:} is complete, and control
6495: returns to the text interpreter. The text interpreter is in compile
6496: state, so subsequent text @code{+ -} is compiled into the definition of
6497: @code{foo} and the @code{;} terminates the definition as always.
6498: @end itemize
6499:
6500: You can use @code{see} to decompile a word that was defined using
6501: @code{my:} and see how it is different from a normal @code{:}
6502: definition. For example:
6503:
6504: @example
6505: : bar + - ; \ like foo but using : rather than my:
6506: see bar
6507: : bar
6508: + - ;
6509: see foo
6510: : foo
6511: 107645672 stats + - ;
6512:
6513: \ use ' stats . to show that 107645672 is the xt for stats
6514: @end example
6515:
6516: You can use techniques like this to make new defining words in terms of
6517: @i{any} existing defining word.
1.1 anton 6518:
6519:
1.29 crook 6520: @cindex defining defining words
1.26 crook 6521: @cindex @code{CREATE} ... @code{DOES>}
6522: If you want the words defined with your defining words to behave
6523: differently from words defined with standard defining words, you can
6524: write your defining word like this:
1.1 anton 6525:
6526: @example
1.26 crook 6527: : def-word ( "name" -- )
1.29 crook 6528: CREATE @i{code1}
1.26 crook 6529: DOES> ( ... -- ... )
1.29 crook 6530: @i{code2} ;
1.26 crook 6531:
6532: def-word name
1.1 anton 6533: @end example
6534:
1.29 crook 6535: @cindex child words
6536: This fragment defines a @dfn{defining word} @code{def-word} and then
6537: executes it. When @code{def-word} executes, it @code{CREATE}s a new
6538: word, @code{name}, and executes the code @i{code1}. The code @i{code2}
6539: is not executed at this time. The word @code{name} is sometimes called a
6540: @dfn{child} of @code{def-word}.
6541:
6542: When you execute @code{name}, the address of the body of @code{name} is
6543: put on the data stack and @i{code2} is executed (the address of the body
6544: of @code{name} is the address @code{HERE} returns immediately after the
1.69 anton 6545: @code{CREATE}, i.e., the address a @code{create}d word returns by
6546: default).
6547:
6548: @c anton:
6549: @c www.dictionary.com says:
6550: @c at·a·vism: 1.The reappearance of a characteristic in an organism after
6551: @c several generations of absence, usually caused by the chance
6552: @c recombination of genes. 2.An individual or a part that exhibits
6553: @c atavism. Also called throwback. 3.The return of a trait or recurrence
6554: @c of previous behavior after a period of absence.
6555: @c
6556: @c Doesn't seem to fit.
1.29 crook 6557:
1.69 anton 6558: @c @cindex atavism in child words
1.33 anton 6559: You can use @code{def-word} to define a set of child words that behave
1.69 anton 6560: similarly; they all have a common run-time behaviour determined by
6561: @i{code2}. Typically, the @i{code1} sequence builds a data area in the
6562: body of the child word. The structure of the data is common to all
6563: children of @code{def-word}, but the data values are specific -- and
6564: private -- to each child word. When a child word is executed, the
6565: address of its private data area is passed as a parameter on TOS to be
6566: used and manipulated@footnote{It is legitimate both to read and write to
6567: this data area.} by @i{code2}.
1.29 crook 6568:
6569: The two fragments of code that make up the defining words act (are
6570: executed) at two completely separate times:
1.1 anton 6571:
1.29 crook 6572: @itemize @bullet
6573: @item
6574: At @i{define time}, the defining word executes @i{code1} to generate a
6575: child word
6576: @item
6577: At @i{child execution time}, when a child word is invoked, @i{code2}
6578: is executed, using parameters (data) that are private and specific to
6579: the child word.
6580: @end itemize
6581:
1.44 crook 6582: Another way of understanding the behaviour of @code{def-word} and
6583: @code{name} is to say that, if you make the following definitions:
1.33 anton 6584: @example
6585: : def-word1 ( "name" -- )
6586: CREATE @i{code1} ;
6587:
6588: : action1 ( ... -- ... )
6589: @i{code2} ;
6590:
6591: def-word1 name1
6592: @end example
6593:
1.44 crook 6594: @noindent
6595: Then using @code{name1 action1} is equivalent to using @code{name}.
1.1 anton 6596:
1.29 crook 6597: The classic example is that you can define @code{CONSTANT} in this way:
1.26 crook 6598:
1.1 anton 6599: @example
1.29 crook 6600: : CONSTANT ( w "name" -- )
6601: CREATE ,
1.26 crook 6602: DOES> ( -- w )
6603: @@ ;
1.1 anton 6604: @end example
6605:
1.29 crook 6606: @comment There is a beautiful description of how this works and what
6607: @comment it does in the Forthwrite 100th edition.. as well as an elegant
6608: @comment commentary on the Counting Fruits problem.
6609:
6610: When you create a constant with @code{5 CONSTANT five}, a set of
6611: define-time actions take place; first a new word @code{five} is created,
6612: then the value 5 is laid down in the body of @code{five} with
1.44 crook 6613: @code{,}. When @code{five} is executed, the address of the body is put on
1.29 crook 6614: the stack, and @code{@@} retrieves the value 5. The word @code{five} has
6615: no code of its own; it simply contains a data field and a pointer to the
6616: code that follows @code{DOES>} in its defining word. That makes words
6617: created in this way very compact.
6618:
6619: The final example in this section is intended to remind you that space
6620: reserved in @code{CREATE}d words is @i{data} space and therefore can be
6621: both read and written by a Standard program@footnote{Exercise: use this
6622: example as a starting point for your own implementation of @code{Value}
6623: and @code{TO} -- if you get stuck, investigate the behaviour of @code{'} and
6624: @code{[']}.}:
6625:
6626: @example
6627: : foo ( "name" -- )
6628: CREATE -1 ,
6629: DOES> ( -- )
1.33 anton 6630: @@ . ;
1.29 crook 6631:
6632: foo first-word
6633: foo second-word
6634:
6635: 123 ' first-word >BODY !
6636: @end example
6637:
6638: If @code{first-word} had been a @code{CREATE}d word, we could simply
6639: have executed it to get the address of its data field. However, since it
6640: was defined to have @code{DOES>} actions, its execution semantics are to
6641: perform those @code{DOES>} actions. To get the address of its data field
6642: it's necessary to use @code{'} to get its xt, then @code{>BODY} to
6643: translate the xt into the address of the data field. When you execute
6644: @code{first-word}, it will display @code{123}. When you execute
6645: @code{second-word} it will display @code{-1}.
1.26 crook 6646:
6647: @cindex stack effect of @code{DOES>}-parts
6648: @cindex @code{DOES>}-parts, stack effect
1.29 crook 6649: In the examples above the stack comment after the @code{DOES>} specifies
1.26 crook 6650: the stack effect of the defined words, not the stack effect of the
6651: following code (the following code expects the address of the body on
6652: the top of stack, which is not reflected in the stack comment). This is
6653: the convention that I use and recommend (it clashes a bit with using
6654: locals declarations for stack effect specification, though).
1.1 anton 6655:
1.53 anton 6656: @menu
6657: * CREATE..DOES> applications::
6658: * CREATE..DOES> details::
1.63 anton 6659: * Advanced does> usage example::
1.91 anton 6660: * @code{Const-does>}::
1.53 anton 6661: @end menu
6662:
6663: @node CREATE..DOES> applications, CREATE..DOES> details, User-defined Defining Words, User-defined Defining Words
1.26 crook 6664: @subsubsection Applications of @code{CREATE..DOES>}
6665: @cindex @code{CREATE} ... @code{DOES>}, applications
1.1 anton 6666:
1.26 crook 6667: You may wonder how to use this feature. Here are some usage patterns:
1.1 anton 6668:
1.26 crook 6669: @cindex factoring similar colon definitions
6670: When you see a sequence of code occurring several times, and you can
6671: identify a meaning, you will factor it out as a colon definition. When
6672: you see similar colon definitions, you can factor them using
6673: @code{CREATE..DOES>}. E.g., an assembler usually defines several words
6674: that look very similar:
1.1 anton 6675: @example
1.26 crook 6676: : ori, ( reg-target reg-source n -- )
6677: 0 asm-reg-reg-imm ;
6678: : andi, ( reg-target reg-source n -- )
6679: 1 asm-reg-reg-imm ;
1.1 anton 6680: @end example
6681:
1.26 crook 6682: @noindent
6683: This could be factored with:
6684: @example
6685: : reg-reg-imm ( op-code -- )
6686: CREATE ,
6687: DOES> ( reg-target reg-source n -- )
6688: @@ asm-reg-reg-imm ;
6689:
6690: 0 reg-reg-imm ori,
6691: 1 reg-reg-imm andi,
6692: @end example
1.1 anton 6693:
1.26 crook 6694: @cindex currying
6695: Another view of @code{CREATE..DOES>} is to consider it as a crude way to
6696: supply a part of the parameters for a word (known as @dfn{currying} in
6697: the functional language community). E.g., @code{+} needs two
6698: parameters. Creating versions of @code{+} with one parameter fixed can
6699: be done like this:
1.82 anton 6700:
1.1 anton 6701: @example
1.82 anton 6702: : curry+ ( n1 "name" -- )
1.26 crook 6703: CREATE ,
6704: DOES> ( n2 -- n1+n2 )
6705: @@ + ;
6706:
6707: 3 curry+ 3+
6708: -2 curry+ 2-
1.1 anton 6709: @end example
6710:
1.91 anton 6711:
1.63 anton 6712: @node CREATE..DOES> details, Advanced does> usage example, CREATE..DOES> applications, User-defined Defining Words
1.26 crook 6713: @subsubsection The gory details of @code{CREATE..DOES>}
6714: @cindex @code{CREATE} ... @code{DOES>}, details
1.1 anton 6715:
1.26 crook 6716: doc-does>
1.1 anton 6717:
1.26 crook 6718: @cindex @code{DOES>} in a separate definition
6719: This means that you need not use @code{CREATE} and @code{DOES>} in the
6720: same definition; you can put the @code{DOES>}-part in a separate
1.29 crook 6721: definition. This allows us to, e.g., select among different @code{DOES>}-parts:
1.26 crook 6722: @example
6723: : does1
6724: DOES> ( ... -- ... )
1.44 crook 6725: ... ;
6726:
6727: : does2
6728: DOES> ( ... -- ... )
6729: ... ;
6730:
6731: : def-word ( ... -- ... )
6732: create ...
6733: IF
6734: does1
6735: ELSE
6736: does2
6737: ENDIF ;
6738: @end example
6739:
6740: In this example, the selection of whether to use @code{does1} or
1.69 anton 6741: @code{does2} is made at definition-time; at the time that the child word is
1.44 crook 6742: @code{CREATE}d.
6743:
6744: @cindex @code{DOES>} in interpretation state
6745: In a standard program you can apply a @code{DOES>}-part only if the last
6746: word was defined with @code{CREATE}. In Gforth, the @code{DOES>}-part
6747: will override the behaviour of the last word defined in any case. In a
6748: standard program, you can use @code{DOES>} only in a colon
6749: definition. In Gforth, you can also use it in interpretation state, in a
6750: kind of one-shot mode; for example:
6751: @example
6752: CREATE name ( ... -- ... )
6753: @i{initialization}
6754: DOES>
6755: @i{code} ;
6756: @end example
6757:
6758: @noindent
6759: is equivalent to the standard:
6760: @example
6761: :noname
6762: DOES>
6763: @i{code} ;
6764: CREATE name EXECUTE ( ... -- ... )
6765: @i{initialization}
6766: @end example
6767:
1.53 anton 6768: doc->body
6769:
1.91 anton 6770: @node Advanced does> usage example, @code{Const-does>}, CREATE..DOES> details, User-defined Defining Words
1.63 anton 6771: @subsubsection Advanced does> usage example
6772:
6773: The MIPS disassembler (@file{arch/mips/disasm.fs}) contains many words
6774: for disassembling instructions, that follow a very repetetive scheme:
6775:
6776: @example
6777: :noname @var{disasm-operands} s" @var{inst-name}" type ;
6778: @var{entry-num} cells @var{table} + !
6779: @end example
6780:
6781: Of course, this inspires the idea to factor out the commonalities to
6782: allow a definition like
6783:
6784: @example
6785: @var{disasm-operands} @var{entry-num} @var{table} define-inst @var{inst-name}
6786: @end example
6787:
6788: The parameters @var{disasm-operands} and @var{table} are usually
1.69 anton 6789: correlated. Moreover, before I wrote the disassembler, there already
6790: existed code that defines instructions like this:
1.63 anton 6791:
6792: @example
6793: @var{entry-num} @var{inst-format} @var{inst-name}
6794: @end example
6795:
6796: This code comes from the assembler and resides in
6797: @file{arch/mips/insts.fs}.
6798:
6799: So I had to define the @var{inst-format} words that performed the scheme
6800: above when executed. At first I chose to use run-time code-generation:
6801:
6802: @example
6803: : @var{inst-format} ( entry-num "name" -- ; compiled code: addr w -- )
6804: :noname Postpone @var{disasm-operands}
6805: name Postpone sliteral Postpone type Postpone ;
6806: swap cells @var{table} + ! ;
6807: @end example
6808:
6809: Note that this supplies the other two parameters of the scheme above.
1.44 crook 6810:
1.63 anton 6811: An alternative would have been to write this using
6812: @code{create}/@code{does>}:
6813:
6814: @example
6815: : @var{inst-format} ( entry-num "name" -- )
6816: here name string, ( entry-num c-addr ) \ parse and save "name"
6817: noname create , ( entry-num )
6818: lastxt swap cells @var{table} + !
6819: does> ( addr w -- )
6820: \ disassemble instruction w at addr
6821: @@ >r
6822: @var{disasm-operands}
6823: r> count type ;
6824: @end example
6825:
6826: Somehow the first solution is simpler, mainly because it's simpler to
6827: shift a string from definition-time to use-time with @code{sliteral}
6828: than with @code{string,} and friends.
6829:
6830: I wrote a lot of words following this scheme and soon thought about
6831: factoring out the commonalities among them. Note that this uses a
6832: two-level defining word, i.e., a word that defines ordinary defining
6833: words.
6834:
6835: This time a solution involving @code{postpone} and friends seemed more
6836: difficult (try it as an exercise), so I decided to use a
6837: @code{create}/@code{does>} word; since I was already at it, I also used
6838: @code{create}/@code{does>} for the lower level (try using
6839: @code{postpone} etc. as an exercise), resulting in the following
6840: definition:
6841:
6842: @example
6843: : define-format ( disasm-xt table-xt -- )
6844: \ define an instruction format that uses disasm-xt for
6845: \ disassembling and enters the defined instructions into table
6846: \ table-xt
6847: create 2,
6848: does> ( u "inst" -- )
6849: \ defines an anonymous word for disassembling instruction inst,
6850: \ and enters it as u-th entry into table-xt
6851: 2@@ swap here name string, ( u table-xt disasm-xt c-addr ) \ remember string
6852: noname create 2, \ define anonymous word
6853: execute lastxt swap ! \ enter xt of defined word into table-xt
6854: does> ( addr w -- )
6855: \ disassemble instruction w at addr
6856: 2@@ >r ( addr w disasm-xt R: c-addr )
6857: execute ( R: c-addr ) \ disassemble operands
6858: r> count type ; \ print name
6859: @end example
6860:
6861: Note that the tables here (in contrast to above) do the @code{cells +}
6862: by themselves (that's why you have to pass an xt). This word is used in
6863: the following way:
6864:
6865: @example
6866: ' @var{disasm-operands} ' @var{table} define-format @var{inst-format}
6867: @end example
6868:
1.71 anton 6869: As shown above, the defined instruction format is then used like this:
6870:
6871: @example
6872: @var{entry-num} @var{inst-format} @var{inst-name}
6873: @end example
6874:
1.63 anton 6875: In terms of currying, this kind of two-level defining word provides the
6876: parameters in three stages: first @var{disasm-operands} and @var{table},
6877: then @var{entry-num} and @var{inst-name}, finally @code{addr w}, i.e.,
6878: the instruction to be disassembled.
6879:
6880: Of course this did not quite fit all the instruction format names used
6881: in @file{insts.fs}, so I had to define a few wrappers that conditioned
6882: the parameters into the right form.
6883:
6884: If you have trouble following this section, don't worry. First, this is
6885: involved and takes time (and probably some playing around) to
6886: understand; second, this is the first two-level
6887: @code{create}/@code{does>} word I have written in seventeen years of
6888: Forth; and if I did not have @file{insts.fs} to start with, I may well
6889: have elected to use just a one-level defining word (with some repeating
6890: of parameters when using the defining word). So it is not necessary to
6891: understand this, but it may improve your understanding of Forth.
1.44 crook 6892:
6893:
1.91 anton 6894: @node @code{Const-does>}, , Advanced does> usage example, User-defined Defining Words
6895: @subsubsection @code{Const-does>}
6896:
6897: A frequent use of @code{create}...@code{does>} is for transferring some
6898: values from definition-time to run-time. Gforth supports this use with
6899:
6900: doc-const-does>
6901:
6902: A typical use of this word is:
6903:
6904: @example
6905: : curry+ ( n1 "name" -- )
6906: 1 0 CONST-DOES> ( n2 -- n1+n2 )
6907: + ;
6908:
6909: 3 curry+ 3+
6910: @end example
6911:
6912: Here the @code{1 0} means that 1 cell and 0 floats are transferred from
6913: definition to run-time.
6914:
6915: The advantages of using @code{const-does>} are:
6916:
6917: @itemize
6918:
6919: @item
6920: You don't have to deal with storing and retrieving the values, i.e.,
6921: your program becomes more writable and readable.
6922:
6923: @item
6924: When using @code{does>}, you have to introduce a @code{@@} that cannot
6925: be optimized away (because you could change the data using
6926: @code{>body}...@code{!}); @code{const-does>} avoids this problem.
6927:
6928: @end itemize
6929:
6930: An ANS Forth implementation of @code{const-does>} is available in
6931: @file{compat/const-does.fs}.
6932:
6933:
1.44 crook 6934: @node Deferred words, Aliases, User-defined Defining Words, Defining Words
6935: @subsection Deferred words
6936: @cindex deferred words
6937:
6938: The defining word @code{Defer} allows you to define a word by name
6939: without defining its behaviour; the definition of its behaviour is
6940: deferred. Here are two situation where this can be useful:
6941:
6942: @itemize @bullet
6943: @item
6944: Where you want to allow the behaviour of a word to be altered later, and
6945: for all precompiled references to the word to change when its behaviour
6946: is changed.
6947: @item
6948: For mutual recursion; @xref{Calls and returns}.
6949: @end itemize
6950:
6951: In the following example, @code{foo} always invokes the version of
6952: @code{greet} that prints ``@code{Good morning}'' whilst @code{bar}
6953: always invokes the version that prints ``@code{Hello}''. There is no way
6954: of getting @code{foo} to use the later version without re-ordering the
6955: source code and recompiling it.
6956:
6957: @example
6958: : greet ." Good morning" ;
6959: : foo ... greet ... ;
6960: : greet ." Hello" ;
6961: : bar ... greet ... ;
6962: @end example
6963:
6964: This problem can be solved by defining @code{greet} as a @code{Defer}red
6965: word. The behaviour of a @code{Defer}red word can be defined and
6966: redefined at any time by using @code{IS} to associate the xt of a
6967: previously-defined word with it. The previous example becomes:
6968:
6969: @example
1.69 anton 6970: Defer greet ( -- )
1.44 crook 6971: : foo ... greet ... ;
6972: : bar ... greet ... ;
1.69 anton 6973: : greet1 ( -- ) ." Good morning" ;
6974: : greet2 ( -- ) ." Hello" ;
1.44 crook 6975: ' greet2 <IS> greet \ make greet behave like greet2
6976: @end example
6977:
1.69 anton 6978: @progstyle
6979: You should write a stack comment for every deferred word, and put only
6980: XTs into deferred words that conform to this stack effect. Otherwise
6981: it's too difficult to use the deferred word.
6982:
1.44 crook 6983: A deferred word can be used to improve the statistics-gathering example
6984: from @ref{User-defined Defining Words}; rather than edit the
6985: application's source code to change every @code{:} to a @code{my:}, do
6986: this:
6987:
6988: @example
6989: : real: : ; \ retain access to the original
6990: defer : \ redefine as a deferred word
1.69 anton 6991: ' my: <IS> : \ use special version of :
1.44 crook 6992: \
6993: \ load application here
6994: \
1.69 anton 6995: ' real: <IS> : \ go back to the original
1.44 crook 6996: @end example
6997:
6998:
6999: One thing to note is that @code{<IS>} consumes its name when it is
7000: executed. If you want to specify the name at compile time, use
7001: @code{[IS]}:
7002:
7003: @example
7004: : set-greet ( xt -- )
7005: [IS] greet ;
7006:
7007: ' greet1 set-greet
7008: @end example
7009:
1.69 anton 7010: A deferred word can only inherit execution semantics from the xt
7011: (because that is all that an xt can represent -- for more discussion of
7012: this @pxref{Tokens for Words}); by default it will have default
7013: interpretation and compilation semantics deriving from this execution
7014: semantics. However, you can change the interpretation and compilation
7015: semantics of the deferred word in the usual ways:
1.44 crook 7016:
7017: @example
7018: : bar .... ; compile-only
7019: Defer fred immediate
7020: Defer jim
7021:
7022: ' bar <IS> jim \ jim has default semantics
7023: ' bar <IS> fred \ fred is immediate
7024: @end example
7025:
7026: doc-defer
7027: doc-<is>
7028: doc-[is]
7029: doc-is
7030: @comment TODO document these: what's defers [is]
7031: doc-what's
7032: doc-defers
7033:
7034: @c Use @code{words-deferred} to see a list of deferred words.
7035:
7036: Definitions in ANS Forth for @code{defer}, @code{<is>} and @code{[is]}
7037: are provided in @file{compat/defer.fs}.
7038:
7039:
1.69 anton 7040: @node Aliases, , Deferred words, Defining Words
1.44 crook 7041: @subsection Aliases
7042: @cindex aliases
1.1 anton 7043:
1.44 crook 7044: The defining word @code{Alias} allows you to define a word by name that
7045: has the same behaviour as some other word. Here are two situation where
7046: this can be useful:
1.1 anton 7047:
1.44 crook 7048: @itemize @bullet
7049: @item
7050: When you want access to a word's definition from a different word list
7051: (for an example of this, see the definition of the @code{Root} word list
7052: in the Gforth source).
7053: @item
7054: When you want to create a synonym; a definition that can be known by
7055: either of two names (for example, @code{THEN} and @code{ENDIF} are
7056: aliases).
7057: @end itemize
1.1 anton 7058:
1.69 anton 7059: Like deferred words, an alias has default compilation and interpretation
7060: semantics at the beginning (not the modifications of the other word),
7061: but you can change them in the usual ways (@code{immediate},
7062: @code{compile-only}). For example:
1.1 anton 7063:
7064: @example
1.44 crook 7065: : foo ... ; immediate
7066:
7067: ' foo Alias bar \ bar is not an immediate word
7068: ' foo Alias fooby immediate \ fooby is an immediate word
1.1 anton 7069: @end example
7070:
1.44 crook 7071: Words that are aliases have the same xt, different headers in the
7072: dictionary, and consequently different name tokens (@pxref{Tokens for
7073: Words}) and possibly different immediate flags. An alias can only have
7074: default or immediate compilation semantics; you can define aliases for
7075: combined words with @code{interpret/compile:} -- see @ref{Combined words}.
1.1 anton 7076:
1.44 crook 7077: doc-alias
1.1 anton 7078:
7079:
1.47 crook 7080: @node Interpretation and Compilation Semantics, Tokens for Words, Defining Words, Words
7081: @section Interpretation and Compilation Semantics
1.26 crook 7082: @cindex semantics, interpretation and compilation
1.1 anton 7083:
1.71 anton 7084: @c !! state and ' are used without explanation
7085: @c example for immediate/compile-only? or is the tutorial enough
7086:
1.26 crook 7087: @cindex interpretation semantics
1.71 anton 7088: The @dfn{interpretation semantics} of a (named) word are what the text
1.26 crook 7089: interpreter does when it encounters the word in interpret state. It also
7090: appears in some other contexts, e.g., the execution token returned by
1.71 anton 7091: @code{' @i{word}} identifies the interpretation semantics of @i{word}
7092: (in other words, @code{' @i{word} execute} is equivalent to
1.29 crook 7093: interpret-state text interpretation of @code{@i{word}}).
1.1 anton 7094:
1.26 crook 7095: @cindex compilation semantics
1.71 anton 7096: The @dfn{compilation semantics} of a (named) word are what the text
7097: interpreter does when it encounters the word in compile state. It also
7098: appears in other contexts, e.g, @code{POSTPONE @i{word}}
7099: compiles@footnote{In standard terminology, ``appends to the current
7100: definition''.} the compilation semantics of @i{word}.
1.1 anton 7101:
1.26 crook 7102: @cindex execution semantics
7103: The standard also talks about @dfn{execution semantics}. They are used
7104: only for defining the interpretation and compilation semantics of many
7105: words. By default, the interpretation semantics of a word are to
7106: @code{execute} its execution semantics, and the compilation semantics of
7107: a word are to @code{compile,} its execution semantics.@footnote{In
7108: standard terminology: The default interpretation semantics are its
7109: execution semantics; the default compilation semantics are to append its
7110: execution semantics to the execution semantics of the current
7111: definition.}
7112:
1.71 anton 7113: Unnamed words (@pxref{Anonymous Definitions}) cannot be encountered by
7114: the text interpreter, ticked, or @code{postpone}d, so they have no
7115: interpretation or compilation semantics. Their behaviour is represented
7116: by their XT (@pxref{Tokens for Words}), and we call it execution
7117: semantics, too.
7118:
1.26 crook 7119: @comment TODO expand, make it co-operate with new sections on text interpreter.
7120:
7121: @cindex immediate words
7122: @cindex compile-only words
7123: You can change the semantics of the most-recently defined word:
7124:
1.44 crook 7125:
1.26 crook 7126: doc-immediate
7127: doc-compile-only
7128: doc-restrict
7129:
1.82 anton 7130: By convention, words with non-default compilation semantics (e.g.,
7131: immediate words) often have names surrounded with brackets (e.g.,
7132: @code{[']}, @pxref{Execution token}).
1.44 crook 7133:
1.26 crook 7134: Note that ticking (@code{'}) a compile-only word gives an error
7135: (``Interpreting a compile-only word'').
1.1 anton 7136:
1.47 crook 7137: @menu
1.67 anton 7138: * Combined words::
1.47 crook 7139: @end menu
1.44 crook 7140:
1.71 anton 7141:
1.48 anton 7142: @node Combined words, , Interpretation and Compilation Semantics, Interpretation and Compilation Semantics
1.44 crook 7143: @subsection Combined Words
7144: @cindex combined words
7145:
7146: Gforth allows you to define @dfn{combined words} -- words that have an
7147: arbitrary combination of interpretation and compilation semantics.
7148:
1.26 crook 7149: doc-interpret/compile:
1.1 anton 7150:
1.26 crook 7151: This feature was introduced for implementing @code{TO} and @code{S"}. I
7152: recommend that you do not define such words, as cute as they may be:
7153: they make it hard to get at both parts of the word in some contexts.
7154: E.g., assume you want to get an execution token for the compilation
7155: part. Instead, define two words, one that embodies the interpretation
7156: part, and one that embodies the compilation part. Once you have done
7157: that, you can define a combined word with @code{interpret/compile:} for
7158: the convenience of your users.
1.1 anton 7159:
1.26 crook 7160: You might try to use this feature to provide an optimizing
7161: implementation of the default compilation semantics of a word. For
7162: example, by defining:
1.1 anton 7163: @example
1.26 crook 7164: :noname
7165: foo bar ;
7166: :noname
7167: POSTPONE foo POSTPONE bar ;
1.29 crook 7168: interpret/compile: opti-foobar
1.1 anton 7169: @end example
1.26 crook 7170:
1.23 crook 7171: @noindent
1.26 crook 7172: as an optimizing version of:
7173:
1.1 anton 7174: @example
1.26 crook 7175: : foobar
7176: foo bar ;
1.1 anton 7177: @end example
7178:
1.26 crook 7179: Unfortunately, this does not work correctly with @code{[compile]},
7180: because @code{[compile]} assumes that the compilation semantics of all
7181: @code{interpret/compile:} words are non-default. I.e., @code{[compile]
1.29 crook 7182: opti-foobar} would compile compilation semantics, whereas
7183: @code{[compile] foobar} would compile interpretation semantics.
1.1 anton 7184:
1.26 crook 7185: @cindex state-smart words (are a bad idea)
1.82 anton 7186: @anchor{state-smartness}
1.29 crook 7187: Some people try to use @dfn{state-smart} words to emulate the feature provided
1.26 crook 7188: by @code{interpret/compile:} (words are state-smart if they check
7189: @code{STATE} during execution). E.g., they would try to code
7190: @code{foobar} like this:
1.1 anton 7191:
1.26 crook 7192: @example
7193: : foobar
7194: STATE @@
7195: IF ( compilation state )
7196: POSTPONE foo POSTPONE bar
7197: ELSE
7198: foo bar
7199: ENDIF ; immediate
7200: @end example
1.1 anton 7201:
1.26 crook 7202: Although this works if @code{foobar} is only processed by the text
7203: interpreter, it does not work in other contexts (like @code{'} or
7204: @code{POSTPONE}). E.g., @code{' foobar} will produce an execution token
7205: for a state-smart word, not for the interpretation semantics of the
7206: original @code{foobar}; when you execute this execution token (directly
7207: with @code{EXECUTE} or indirectly through @code{COMPILE,}) in compile
7208: state, the result will not be what you expected (i.e., it will not
7209: perform @code{foo bar}). State-smart words are a bad idea. Simply don't
7210: write them@footnote{For a more detailed discussion of this topic, see
1.66 anton 7211: M. Anton Ertl,
7212: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,@code{State}-smartness---Why
7213: it is Evil and How to Exorcise it}}, EuroForth '98.}!
1.1 anton 7214:
1.26 crook 7215: @cindex defining words with arbitrary semantics combinations
7216: It is also possible to write defining words that define words with
7217: arbitrary combinations of interpretation and compilation semantics. In
7218: general, they look like this:
1.1 anton 7219:
1.26 crook 7220: @example
7221: : def-word
7222: create-interpret/compile
1.29 crook 7223: @i{code1}
1.26 crook 7224: interpretation>
1.29 crook 7225: @i{code2}
1.26 crook 7226: <interpretation
7227: compilation>
1.29 crook 7228: @i{code3}
1.26 crook 7229: <compilation ;
7230: @end example
1.1 anton 7231:
1.29 crook 7232: For a @i{word} defined with @code{def-word}, the interpretation
7233: semantics are to push the address of the body of @i{word} and perform
7234: @i{code2}, and the compilation semantics are to push the address of
7235: the body of @i{word} and perform @i{code3}. E.g., @code{constant}
1.26 crook 7236: can also be defined like this (except that the defined constants don't
7237: behave correctly when @code{[compile]}d):
1.1 anton 7238:
1.26 crook 7239: @example
7240: : constant ( n "name" -- )
7241: create-interpret/compile
7242: ,
7243: interpretation> ( -- n )
7244: @@
7245: <interpretation
7246: compilation> ( compilation. -- ; run-time. -- n )
7247: @@ postpone literal
7248: <compilation ;
7249: @end example
1.1 anton 7250:
1.44 crook 7251:
1.26 crook 7252: doc-create-interpret/compile
7253: doc-interpretation>
7254: doc-<interpretation
7255: doc-compilation>
7256: doc-<compilation
1.1 anton 7257:
1.44 crook 7258:
1.29 crook 7259: Words defined with @code{interpret/compile:} and
1.26 crook 7260: @code{create-interpret/compile} have an extended header structure that
7261: differs from other words; however, unless you try to access them with
7262: plain address arithmetic, you should not notice this. Words for
7263: accessing the header structure usually know how to deal with this; e.g.,
1.29 crook 7264: @code{'} @i{word} @code{>body} also gives you the body of a word created
7265: with @code{create-interpret/compile}.
1.1 anton 7266:
1.44 crook 7267:
1.47 crook 7268: @c -------------------------------------------------------------
1.81 anton 7269: @node Tokens for Words, Compiling words, Interpretation and Compilation Semantics, Words
1.47 crook 7270: @section Tokens for Words
7271: @cindex tokens for words
7272:
7273: This section describes the creation and use of tokens that represent
7274: words.
7275:
1.71 anton 7276: @menu
7277: * Execution token:: represents execution/interpretation semantics
7278: * Compilation token:: represents compilation semantics
7279: * Name token:: represents named words
7280: @end menu
1.47 crook 7281:
1.71 anton 7282: @node Execution token, Compilation token, Tokens for Words, Tokens for Words
7283: @subsection Execution token
1.47 crook 7284:
7285: @cindex xt
7286: @cindex execution token
1.71 anton 7287: An @dfn{execution token} (@i{XT}) represents some behaviour of a word.
7288: You can use @code{execute} to invoke this behaviour.
1.47 crook 7289:
1.71 anton 7290: @cindex tick (')
7291: You can use @code{'} to get an execution token that represents the
7292: interpretation semantics of a named word:
1.47 crook 7293:
7294: @example
1.97 anton 7295: 5 ' . ( n xt )
7296: execute ( ) \ execute the xt (i.e., ".")
1.71 anton 7297: @end example
1.47 crook 7298:
1.71 anton 7299: doc-'
7300:
7301: @code{'} parses at run-time; there is also a word @code{[']} that parses
7302: when it is compiled, and compiles the resulting XT:
7303:
7304: @example
7305: : foo ['] . execute ;
7306: 5 foo
7307: : bar ' execute ; \ by contrast,
7308: 5 bar . \ ' parses "." when bar executes
7309: @end example
7310:
7311: doc-[']
7312:
7313: If you want the execution token of @i{word}, write @code{['] @i{word}}
7314: in compiled code and @code{' @i{word}} in interpreted code. Gforth's
7315: @code{'} and @code{[']} behave somewhat unusually by complaining about
7316: compile-only words (because these words have no interpretation
7317: semantics). You might get what you want by using @code{COMP' @i{word}
7318: DROP} or @code{[COMP'] @i{word} DROP} (for details @pxref{Compilation
7319: token}).
7320:
7321: Another way to get an XT is @code{:noname} or @code{lastxt}
7322: (@pxref{Anonymous Definitions}). For anonymous words this gives an xt
7323: for the only behaviour the word has (the execution semantics). For
7324: named words, @code{lastxt} produces an XT for the same behaviour it
7325: would produce if the word was defined anonymously.
7326:
7327: @example
7328: :noname ." hello" ;
7329: execute
1.47 crook 7330: @end example
7331:
1.71 anton 7332: An XT occupies one cell and can be manipulated like any other cell.
7333:
1.47 crook 7334: @cindex code field address
7335: @cindex CFA
1.71 anton 7336: In ANS Forth the XT is just an abstract data type (i.e., defined by the
7337: operations that produce or consume it). For old hands: In Gforth, the
7338: XT is implemented as a code field address (CFA).
7339:
7340: doc-execute
7341: doc-perform
7342:
7343: @node Compilation token, Name token, Execution token, Tokens for Words
7344: @subsection Compilation token
1.47 crook 7345:
7346: @cindex compilation token
1.71 anton 7347: @cindex CT (compilation token)
7348: Gforth represents the compilation semantics of a named word by a
1.47 crook 7349: @dfn{compilation token} consisting of two cells: @i{w xt}. The top cell
7350: @i{xt} is an execution token. The compilation semantics represented by
7351: the compilation token can be performed with @code{execute}, which
7352: consumes the whole compilation token, with an additional stack effect
7353: determined by the represented compilation semantics.
7354:
7355: At present, the @i{w} part of a compilation token is an execution token,
7356: and the @i{xt} part represents either @code{execute} or
7357: @code{compile,}@footnote{Depending upon the compilation semantics of the
7358: word. If the word has default compilation semantics, the @i{xt} will
7359: represent @code{compile,}. Otherwise (e.g., for immediate words), the
7360: @i{xt} will represent @code{execute}.}. However, don't rely on that
7361: knowledge, unless necessary; future versions of Gforth may introduce
7362: unusual compilation tokens (e.g., a compilation token that represents
7363: the compilation semantics of a literal).
7364:
1.71 anton 7365: You can perform the compilation semantics represented by the compilation
7366: token with @code{execute}. You can compile the compilation semantics
7367: with @code{postpone,}. I.e., @code{COMP' @i{word} postpone,} is
7368: equivalent to @code{postpone @i{word}}.
7369:
7370: doc-[comp']
7371: doc-comp'
7372: doc-postpone,
7373:
7374: @node Name token, , Compilation token, Tokens for Words
7375: @subsection Name token
1.47 crook 7376:
7377: @cindex name token
7378: @cindex name field address
7379: @cindex NFA
1.71 anton 7380: Gforth represents named words by the @dfn{name token}, (@i{nt}). In
1.47 crook 7381: Gforth, the abstract data type @emph{name token} is implemented as a
7382: name field address (NFA).
7383:
7384: doc-find-name
7385: doc-name>int
7386: doc-name?int
7387: doc-name>comp
7388: doc-name>string
1.109 anton 7389: doc-id.
7390: doc-.name
7391: doc-.id
1.47 crook 7392:
1.81 anton 7393: @c ----------------------------------------------------------
7394: @node Compiling words, The Text Interpreter, Tokens for Words, Words
7395: @section Compiling words
7396: @cindex compiling words
7397: @cindex macros
7398:
7399: In contrast to most other languages, Forth has no strict boundary
1.82 anton 7400: between compilation and run-time. E.g., you can run arbitrary code
7401: between defining words (or for computing data used by defining words
7402: like @code{constant}). Moreover, @code{Immediate} (@pxref{Interpretation
7403: and Compilation Semantics} and @code{[}...@code{]} (see below) allow
7404: running arbitrary code while compiling a colon definition (exception:
7405: you must not allot dictionary space).
7406:
7407: @menu
7408: * Literals:: Compiling data values
7409: * Macros:: Compiling words
7410: @end menu
7411:
7412: @node Literals, Macros, Compiling words, Compiling words
7413: @subsection Literals
7414: @cindex Literals
7415:
7416: The simplest and most frequent example is to compute a literal during
7417: compilation. E.g., the following definition prints an array of strings,
7418: one string per line:
7419:
7420: @example
7421: : .strings ( addr u -- ) \ gforth
7422: 2* cells bounds U+DO
7423: cr i 2@@ type
7424: 2 cells +LOOP ;
7425: @end example
1.81 anton 7426:
1.82 anton 7427: With a simple-minded compiler like Gforth's, this computes @code{2
7428: cells} on every loop iteration. You can compute this value once and for
7429: all at compile time and compile it into the definition like this:
7430:
7431: @example
7432: : .strings ( addr u -- ) \ gforth
7433: 2* cells bounds U+DO
7434: cr i 2@@ type
7435: [ 2 cells ] literal +LOOP ;
7436: @end example
7437:
7438: @code{[} switches the text interpreter to interpret state (you will get
7439: an @code{ok} prompt if you type this example interactively and insert a
7440: newline between @code{[} and @code{]}), so it performs the
7441: interpretation semantics of @code{2 cells}; this computes a number.
7442: @code{]} switches the text interpreter back into compile state. It then
7443: performs @code{Literal}'s compilation semantics, which are to compile
7444: this number into the current word. You can decompile the word with
7445: @code{see .strings} to see the effect on the compiled code.
1.81 anton 7446:
1.82 anton 7447: You can also optimize the @code{2* cells} into @code{[ 2 cells ] literal
7448: *} in this way.
1.81 anton 7449:
1.82 anton 7450: doc-[
7451: doc-]
1.81 anton 7452: doc-literal
7453: doc-]L
1.82 anton 7454:
7455: There are also words for compiling other data types than single cells as
7456: literals:
7457:
1.81 anton 7458: doc-2literal
7459: doc-fliteral
1.82 anton 7460: doc-sliteral
7461:
7462: @cindex colon-sys, passing data across @code{:}
7463: @cindex @code{:}, passing data across
7464: You might be tempted to pass data from outside a colon definition to the
7465: inside on the data stack. This does not work, because @code{:} puhes a
7466: colon-sys, making stuff below unaccessible. E.g., this does not work:
7467:
7468: @example
7469: 5 : foo literal ; \ error: "unstructured"
7470: @end example
7471:
7472: Instead, you have to pass the value in some other way, e.g., through a
7473: variable:
7474:
7475: @example
7476: variable temp
7477: 5 temp !
7478: : foo [ temp @@ ] literal ;
7479: @end example
7480:
7481:
7482: @node Macros, , Literals, Compiling words
7483: @subsection Macros
7484: @cindex Macros
7485: @cindex compiling compilation semantics
7486:
7487: @code{Literal} and friends compile data values into the current
7488: definition. You can also write words that compile other words into the
7489: current definition. E.g.,
7490:
7491: @example
7492: : compile-+ ( -- ) \ compiled code: ( n1 n2 -- n )
7493: POSTPONE + ;
7494:
7495: : foo ( n1 n2 -- n )
7496: [ compile-+ ] ;
7497: 1 2 foo .
7498: @end example
7499:
7500: This is equivalent to @code{: foo + ;} (@code{see foo} to check this).
7501: What happens in this example? @code{Postpone} compiles the compilation
7502: semantics of @code{+} into @code{compile-+}; later the text interpreter
7503: executes @code{compile-+} and thus the compilation semantics of +, which
7504: compile (the execution semantics of) @code{+} into
7505: @code{foo}.@footnote{A recent RFI answer requires that compiling words
7506: should only be executed in compile state, so this example is not
7507: guaranteed to work on all standard systems, but on any decent system it
7508: will work.}
7509:
7510: doc-postpone
7511: doc-[compile]
7512:
7513: Compiling words like @code{compile-+} are usually immediate (or similar)
7514: so you do not have to switch to interpret state to execute them;
7515: mopifying the last example accordingly produces:
7516:
7517: @example
7518: : [compile-+] ( compilation: --; interpretation: -- )
7519: \ compiled code: ( n1 n2 -- n )
7520: POSTPONE + ; immediate
7521:
7522: : foo ( n1 n2 -- n )
7523: [compile-+] ;
7524: 1 2 foo .
7525: @end example
7526:
7527: Immediate compiling words are similar to macros in other languages (in
7528: particular, Lisp). The important differences to macros in, e.g., C are:
7529:
7530: @itemize @bullet
7531:
7532: @item
7533: You use the same language for defining and processing macros, not a
7534: separate preprocessing language and processor.
7535:
7536: @item
7537: Consequently, the full power of Forth is available in macro definitions.
7538: E.g., you can perform arbitrarily complex computations, or generate
7539: different code conditionally or in a loop (e.g., @pxref{Advanced macros
7540: Tutorial}). This power is very useful when writing a parser generators
7541: or other code-generating software.
7542:
7543: @item
7544: Macros defined using @code{postpone} etc. deal with the language at a
7545: higher level than strings; name binding happens at macro definition
7546: time, so you can avoid the pitfalls of name collisions that can happen
7547: in C macros. Of course, Forth is a liberal language and also allows to
7548: shoot yourself in the foot with text-interpreted macros like
7549:
7550: @example
7551: : [compile-+] s" +" evaluate ; immediate
7552: @end example
7553:
7554: Apart from binding the name at macro use time, using @code{evaluate}
7555: also makes your definition @code{state}-smart (@pxref{state-smartness}).
7556: @end itemize
7557:
7558: You may want the macro to compile a number into a word. The word to do
7559: it is @code{literal}, but you have to @code{postpone} it, so its
7560: compilation semantics take effect when the macro is executed, not when
7561: it is compiled:
7562:
7563: @example
7564: : [compile-5] ( -- ) \ compiled code: ( -- n )
7565: 5 POSTPONE literal ; immediate
7566:
7567: : foo [compile-5] ;
7568: foo .
7569: @end example
7570:
7571: You may want to pass parameters to a macro, that the macro should
7572: compile into the current definition. If the parameter is a number, then
7573: you can use @code{postpone literal} (similar for other values).
7574:
7575: If you want to pass a word that is to be compiled, the usual way is to
7576: pass an execution token and @code{compile,} it:
7577:
7578: @example
7579: : twice1 ( xt -- ) \ compiled code: ... -- ...
7580: dup compile, compile, ;
7581:
7582: : 2+ ( n1 -- n2 )
7583: [ ' 1+ twice1 ] ;
7584: @end example
7585:
7586: doc-compile,
7587:
7588: An alternative available in Gforth, that allows you to pass compile-only
7589: words as parameters is to use the compilation token (@pxref{Compilation
7590: token}). The same example in this technique:
7591:
7592: @example
7593: : twice ( ... ct -- ... ) \ compiled code: ... -- ...
7594: 2dup 2>r execute 2r> execute ;
7595:
7596: : 2+ ( n1 -- n2 )
7597: [ comp' 1+ twice ] ;
7598: @end example
7599:
7600: In the example above @code{2>r} and @code{2r>} ensure that @code{twice}
7601: works even if the executed compilation semantics has an effect on the
7602: data stack.
7603:
7604: You can also define complete definitions with these words; this provides
7605: an alternative to using @code{does>} (@pxref{User-defined Defining
7606: Words}). E.g., instead of
7607:
7608: @example
7609: : curry+ ( n1 "name" -- )
7610: CREATE ,
7611: DOES> ( n2 -- n1+n2 )
7612: @@ + ;
7613: @end example
7614:
7615: you could define
7616:
7617: @example
7618: : curry+ ( n1 "name" -- )
7619: \ name execution: ( n2 -- n1+n2 )
7620: >r : r> POSTPONE literal POSTPONE + POSTPONE ; ;
1.81 anton 7621:
1.82 anton 7622: -3 curry+ 3-
7623: see 3-
7624: @end example
1.81 anton 7625:
1.82 anton 7626: The sequence @code{>r : r>} is necessary, because @code{:} puts a
7627: colon-sys on the data stack that makes everything below it unaccessible.
1.81 anton 7628:
1.82 anton 7629: This way of writing defining words is sometimes more, sometimes less
7630: convenient than using @code{does>} (@pxref{Advanced does> usage
7631: example}). One advantage of this method is that it can be optimized
7632: better, because the compiler knows that the value compiled with
7633: @code{literal} is fixed, whereas the data associated with a
7634: @code{create}d word can be changed.
1.47 crook 7635:
1.26 crook 7636: @c ----------------------------------------------------------
1.111 anton 7637: @node The Text Interpreter, The Input Stream, Compiling words, Words
1.26 crook 7638: @section The Text Interpreter
7639: @cindex interpreter - outer
7640: @cindex text interpreter
7641: @cindex outer interpreter
1.1 anton 7642:
1.34 anton 7643: @c Should we really describe all these ugly details? IMO the text
7644: @c interpreter should be much cleaner, but that may not be possible within
7645: @c ANS Forth. - anton
1.44 crook 7646: @c nac-> I wanted to explain how it works to show how you can exploit
7647: @c it in your own programs. When I was writing a cross-compiler, figuring out
7648: @c some of these gory details was very helpful to me. None of the textbooks
7649: @c I've seen cover it, and the most modern Forth textbook -- Forth Inc's,
7650: @c seems to positively avoid going into too much detail for some of
7651: @c the internals.
1.34 anton 7652:
1.71 anton 7653: @c anton: ok. I wonder, though, if this is the right place; for some stuff
7654: @c it is; for the ugly details, I would prefer another place. I wonder
7655: @c whether we should have a chapter before "Words" that describes some
7656: @c basic concepts referred to in words, and a chapter after "Words" that
7657: @c describes implementation details.
7658:
1.29 crook 7659: The text interpreter@footnote{This is an expanded version of the
7660: material in @ref{Introducing the Text Interpreter}.} is an endless loop
1.34 anton 7661: that processes input from the current input device. It is also called
7662: the outer interpreter, in contrast to the inner interpreter
7663: (@pxref{Engine}) which executes the compiled Forth code on interpretive
7664: implementations.
1.27 crook 7665:
1.29 crook 7666: @cindex interpret state
7667: @cindex compile state
7668: The text interpreter operates in one of two states: @dfn{interpret
7669: state} and @dfn{compile state}. The current state is defined by the
1.71 anton 7670: aptly-named variable @code{state}.
1.29 crook 7671:
7672: This section starts by describing how the text interpreter behaves when
7673: it is in interpret state, processing input from the user input device --
7674: the keyboard. This is the mode that a Forth system is in after it starts
7675: up.
7676:
7677: @cindex input buffer
7678: @cindex terminal input buffer
7679: The text interpreter works from an area of memory called the @dfn{input
7680: buffer}@footnote{When the text interpreter is processing input from the
7681: keyboard, this area of memory is called the @dfn{terminal input buffer}
7682: (TIB) and is addressed by the (obsolescent) words @code{TIB} and
7683: @code{#TIB}.}, which stores your keyboard input when you press the
1.30 anton 7684: @key{RET} key. Starting at the beginning of the input buffer, it skips
1.29 crook 7685: leading spaces (called @dfn{delimiters}) then parses a string (a
7686: sequence of non-space characters) until it reaches either a space
7687: character or the end of the buffer. Having parsed a string, it makes two
7688: attempts to process it:
1.27 crook 7689:
1.29 crook 7690: @cindex dictionary
1.27 crook 7691: @itemize @bullet
7692: @item
1.29 crook 7693: It looks for the string in a @dfn{dictionary} of definitions. If the
7694: string is found, the string names a @dfn{definition} (also known as a
7695: @dfn{word}) and the dictionary search returns information that allows
7696: the text interpreter to perform the word's @dfn{interpretation
7697: semantics}. In most cases, this simply means that the word will be
7698: executed.
1.27 crook 7699: @item
7700: If the string is not found in the dictionary, the text interpreter
1.29 crook 7701: attempts to treat it as a number, using the rules described in
7702: @ref{Number Conversion}. If the string represents a legal number in the
7703: current radix, the number is pushed onto a parameter stack (the data
7704: stack for integers, the floating-point stack for floating-point
7705: numbers).
7706: @end itemize
7707:
7708: If both attempts fail, or if the word is found in the dictionary but has
7709: no interpretation semantics@footnote{This happens if the word was
7710: defined as @code{COMPILE-ONLY}.} the text interpreter discards the
7711: remainder of the input buffer, issues an error message and waits for
7712: more input. If one of the attempts succeeds, the text interpreter
7713: repeats the parsing process until the whole of the input buffer has been
7714: processed, at which point it prints the status message ``@code{ ok}''
7715: and waits for more input.
7716:
1.71 anton 7717: @c anton: this should be in the input stream subsection (or below it)
7718:
1.29 crook 7719: @cindex parse area
7720: The text interpreter keeps track of its position in the input buffer by
7721: updating a variable called @code{>IN} (pronounced ``to-in''). The value
7722: of @code{>IN} starts out as 0, indicating an offset of 0 from the start
7723: of the input buffer. The region from offset @code{>IN @@} to the end of
7724: the input buffer is called the @dfn{parse area}@footnote{In other words,
7725: the text interpreter processes the contents of the input buffer by
7726: parsing strings from the parse area until the parse area is empty.}.
7727: This example shows how @code{>IN} changes as the text interpreter parses
7728: the input buffer:
7729:
7730: @example
7731: : remaining >IN @@ SOURCE 2 PICK - -ROT + SWAP
7732: CR ." ->" TYPE ." <-" ; IMMEDIATE
7733:
7734: 1 2 3 remaining + remaining .
7735:
7736: : foo 1 2 3 remaining SWAP remaining ;
7737: @end example
7738:
7739: @noindent
7740: The result is:
7741:
7742: @example
7743: ->+ remaining .<-
7744: ->.<-5 ok
7745:
7746: ->SWAP remaining ;-<
7747: ->;<- ok
7748: @end example
7749:
7750: @cindex parsing words
7751: The value of @code{>IN} can also be modified by a word in the input
7752: buffer that is executed by the text interpreter. This means that a word
7753: can ``trick'' the text interpreter into either skipping a section of the
7754: input buffer@footnote{This is how parsing words work.} or into parsing a
7755: section twice. For example:
1.27 crook 7756:
1.29 crook 7757: @example
1.71 anton 7758: : lat ." <<foo>>" ;
7759: : flat ." <<bar>>" >IN DUP @@ 3 - SWAP ! ;
1.29 crook 7760: @end example
7761:
7762: @noindent
7763: When @code{flat} is executed, this output is produced@footnote{Exercise
7764: for the reader: what would happen if the @code{3} were replaced with
7765: @code{4}?}:
7766:
7767: @example
1.71 anton 7768: <<bar>><<foo>>
1.29 crook 7769: @end example
7770:
1.71 anton 7771: This technique can be used to work around some of the interoperability
7772: problems of parsing words. Of course, it's better to avoid parsing
7773: words where possible.
7774:
1.29 crook 7775: @noindent
7776: Two important notes about the behaviour of the text interpreter:
1.27 crook 7777:
7778: @itemize @bullet
7779: @item
7780: It processes each input string to completion before parsing additional
1.29 crook 7781: characters from the input buffer.
7782: @item
7783: It treats the input buffer as a read-only region (and so must your code).
7784: @end itemize
7785:
7786: @noindent
7787: When the text interpreter is in compile state, its behaviour changes in
7788: these ways:
7789:
7790: @itemize @bullet
7791: @item
7792: If a parsed string is found in the dictionary, the text interpreter will
7793: perform the word's @dfn{compilation semantics}. In most cases, this
7794: simply means that the execution semantics of the word will be appended
7795: to the current definition.
1.27 crook 7796: @item
1.29 crook 7797: When a number is encountered, it is compiled into the current definition
7798: (as a literal) rather than being pushed onto a parameter stack.
7799: @item
7800: If an error occurs, @code{state} is modified to put the text interpreter
7801: back into interpret state.
7802: @item
7803: Each time a line is entered from the keyboard, Gforth prints
7804: ``@code{ compiled}'' rather than `` @code{ok}''.
7805: @end itemize
7806:
7807: @cindex text interpreter - input sources
7808: When the text interpreter is using an input device other than the
7809: keyboard, its behaviour changes in these ways:
7810:
7811: @itemize @bullet
7812: @item
7813: When the parse area is empty, the text interpreter attempts to refill
7814: the input buffer from the input source. When the input source is
1.71 anton 7815: exhausted, the input source is set back to the previous input source.
1.29 crook 7816: @item
7817: It doesn't print out ``@code{ ok}'' or ``@code{ compiled}'' messages each
7818: time the parse area is emptied.
7819: @item
7820: If an error occurs, the input source is set back to the user input
7821: device.
1.27 crook 7822: @end itemize
1.21 crook 7823:
1.49 anton 7824: You can read about this in more detail in @ref{Input Sources}.
1.44 crook 7825:
1.26 crook 7826: doc->in
1.27 crook 7827: doc-source
7828:
1.26 crook 7829: doc-tib
7830: doc-#tib
1.1 anton 7831:
1.44 crook 7832:
1.26 crook 7833: @menu
1.67 anton 7834: * Input Sources::
7835: * Number Conversion::
7836: * Interpret/Compile states::
7837: * Interpreter Directives::
1.26 crook 7838: @end menu
1.1 anton 7839:
1.29 crook 7840: @node Input Sources, Number Conversion, The Text Interpreter, The Text Interpreter
7841: @subsection Input Sources
7842: @cindex input sources
7843: @cindex text interpreter - input sources
7844:
1.44 crook 7845: By default, the text interpreter processes input from the user input
1.29 crook 7846: device (the keyboard) when Forth starts up. The text interpreter can
7847: process input from any of these sources:
7848:
7849: @itemize @bullet
7850: @item
7851: The user input device -- the keyboard.
7852: @item
7853: A file, using the words described in @ref{Forth source files}.
7854: @item
7855: A block, using the words described in @ref{Blocks}.
7856: @item
7857: A text string, using @code{evaluate}.
7858: @end itemize
7859:
7860: A program can identify the current input device from the values of
7861: @code{source-id} and @code{blk}.
7862:
1.44 crook 7863:
1.29 crook 7864: doc-source-id
7865: doc-blk
7866:
7867: doc-save-input
7868: doc-restore-input
7869:
7870: doc-evaluate
1.111 anton 7871: doc-query
1.1 anton 7872:
1.29 crook 7873:
1.44 crook 7874:
1.29 crook 7875: @node Number Conversion, Interpret/Compile states, Input Sources, The Text Interpreter
1.26 crook 7876: @subsection Number Conversion
7877: @cindex number conversion
7878: @cindex double-cell numbers, input format
7879: @cindex input format for double-cell numbers
7880: @cindex single-cell numbers, input format
7881: @cindex input format for single-cell numbers
7882: @cindex floating-point numbers, input format
7883: @cindex input format for floating-point numbers
1.1 anton 7884:
1.29 crook 7885: This section describes the rules that the text interpreter uses when it
7886: tries to convert a string into a number.
1.1 anton 7887:
1.26 crook 7888: Let <digit> represent any character that is a legal digit in the current
1.29 crook 7889: number base@footnote{For example, 0-9 when the number base is decimal or
7890: 0-9, A-F when the number base is hexadecimal.}.
1.1 anton 7891:
1.26 crook 7892: Let <decimal digit> represent any character in the range 0-9.
1.1 anton 7893:
1.29 crook 7894: Let @{@i{a b}@} represent the @i{optional} presence of any of the characters
7895: in the braces (@i{a} or @i{b} or neither).
1.1 anton 7896:
1.26 crook 7897: Let * represent any number of instances of the previous character
7898: (including none).
1.1 anton 7899:
1.26 crook 7900: Let any other character represent itself.
1.1 anton 7901:
1.29 crook 7902: @noindent
1.26 crook 7903: Now, the conversion rules are:
1.21 crook 7904:
1.26 crook 7905: @itemize @bullet
7906: @item
7907: A string of the form <digit><digit>* is treated as a single-precision
1.29 crook 7908: (cell-sized) positive integer. Examples are 0 123 6784532 32343212343456 42
1.26 crook 7909: @item
7910: A string of the form -<digit><digit>* is treated as a single-precision
1.29 crook 7911: (cell-sized) negative integer, and is represented using 2's-complement
1.26 crook 7912: arithmetic. Examples are -45 -5681 -0
7913: @item
7914: A string of the form <digit><digit>*.<digit>* is treated as a double-precision
1.29 crook 7915: (double-cell-sized) positive integer. Examples are 3465. 3.465 34.65
7916: (all three of these represent the same number).
1.26 crook 7917: @item
7918: A string of the form -<digit><digit>*.<digit>* is treated as a
1.29 crook 7919: double-precision (double-cell-sized) negative integer, and is
1.26 crook 7920: represented using 2's-complement arithmetic. Examples are -3465. -3.465
1.29 crook 7921: -34.65 (all three of these represent the same number).
1.26 crook 7922: @item
1.29 crook 7923: A string of the form @{+ -@}<decimal digit>@{.@}<decimal digit>*@{e
7924: E@}@{+ -@}<decimal digit><decimal digit>* is treated as a floating-point
1.35 anton 7925: number. Examples are 1e 1e0 1.e 1.e0 +1e+0 (which all represent the same
1.29 crook 7926: number) +12.E-4
1.26 crook 7927: @end itemize
1.1 anton 7928:
1.26 crook 7929: By default, the number base used for integer number conversion is given
1.35 anton 7930: by the contents of the variable @code{base}. Note that a lot of
7931: confusion can result from unexpected values of @code{base}. If you
7932: change @code{base} anywhere, make sure to save the old value and restore
7933: it afterwards. In general I recommend keeping @code{base} decimal, and
7934: using the prefixes described below for the popular non-decimal bases.
1.1 anton 7935:
1.29 crook 7936: doc-dpl
1.26 crook 7937: doc-base
7938: doc-hex
7939: doc-decimal
1.1 anton 7940:
1.44 crook 7941:
1.26 crook 7942: @cindex '-prefix for character strings
7943: @cindex &-prefix for decimal numbers
7944: @cindex %-prefix for binary numbers
7945: @cindex $-prefix for hexadecimal numbers
1.35 anton 7946: Gforth allows you to override the value of @code{base} by using a
1.29 crook 7947: prefix@footnote{Some Forth implementations provide a similar scheme by
7948: implementing @code{$} etc. as parsing words that process the subsequent
7949: number in the input stream and push it onto the stack. For example, see
7950: @cite{Number Conversion and Literals}, by Wil Baden; Forth Dimensions
7951: 20(3) pages 26--27. In such implementations, unlike in Gforth, a space
7952: is required between the prefix and the number.} before the first digit
7953: of an (integer) number. Four prefixes are supported:
1.1 anton 7954:
1.26 crook 7955: @itemize @bullet
7956: @item
1.35 anton 7957: @code{&} -- decimal
1.26 crook 7958: @item
1.35 anton 7959: @code{%} -- binary
1.26 crook 7960: @item
1.35 anton 7961: @code{$} -- hexadecimal
1.26 crook 7962: @item
1.35 anton 7963: @code{'} -- base @code{max-char+1}
1.26 crook 7964: @end itemize
1.1 anton 7965:
1.26 crook 7966: Here are some examples, with the equivalent decimal number shown after
7967: in braces:
1.1 anton 7968:
1.26 crook 7969: -$41 (-65), %1001101 (205), %1001.0001 (145 - a double-precision number),
7970: 'AB (16706; ascii A is 65, ascii B is 66, number is 65*256 + 66),
7971: 'ab (24930; ascii a is 97, ascii B is 98, number is 97*256 + 98),
7972: &905 (905), $abc (2478), $ABC (2478).
1.1 anton 7973:
1.26 crook 7974: @cindex number conversion - traps for the unwary
1.29 crook 7975: @noindent
1.26 crook 7976: Number conversion has a number of traps for the unwary:
1.1 anton 7977:
1.26 crook 7978: @itemize @bullet
7979: @item
7980: You cannot determine the current number base using the code sequence
1.35 anton 7981: @code{base @@ .} -- the number base is always 10 in the current number
7982: base. Instead, use something like @code{base @@ dec.}
1.26 crook 7983: @item
7984: If the number base is set to a value greater than 14 (for example,
7985: hexadecimal), the number 123E4 is ambiguous; the conversion rules allow
7986: it to be intepreted as either a single-precision integer or a
7987: floating-point number (Gforth treats it as an integer). The ambiguity
7988: can be resolved by explicitly stating the sign of the mantissa and/or
7989: exponent: 123E+4 or +123E4 -- if the number base is decimal, no
7990: ambiguity arises; either representation will be treated as a
7991: floating-point number.
7992: @item
1.29 crook 7993: There is a word @code{bin} but it does @i{not} set the number base!
1.26 crook 7994: It is used to specify file types.
7995: @item
1.72 anton 7996: ANS Forth requires the @code{.} of a double-precision number to be the
7997: final character in the string. Gforth allows the @code{.} to be
7998: anywhere after the first digit.
1.26 crook 7999: @item
8000: The number conversion process does not check for overflow.
8001: @item
1.72 anton 8002: In an ANS Forth program @code{base} is required to be decimal when
8003: converting floating-point numbers. In Gforth, number conversion to
8004: floating-point numbers always uses base &10, irrespective of the value
8005: of @code{base}.
1.26 crook 8006: @end itemize
1.1 anton 8007:
1.49 anton 8008: You can read numbers into your programs with the words described in
8009: @ref{Input}.
1.1 anton 8010:
1.82 anton 8011: @node Interpret/Compile states, Interpreter Directives, Number Conversion, The Text Interpreter
1.26 crook 8012: @subsection Interpret/Compile states
8013: @cindex Interpret/Compile states
1.1 anton 8014:
1.29 crook 8015: A standard program is not permitted to change @code{state}
8016: explicitly. However, it can change @code{state} implicitly, using the
8017: words @code{[} and @code{]}. When @code{[} is executed it switches
8018: @code{state} to interpret state, and therefore the text interpreter
8019: starts interpreting. When @code{]} is executed it switches @code{state}
8020: to compile state and therefore the text interpreter starts
1.44 crook 8021: compiling. The most common usage for these words is for switching into
8022: interpret state and back from within a colon definition; this technique
1.49 anton 8023: can be used to compile a literal (for an example, @pxref{Literals}) or
8024: for conditional compilation (for an example, @pxref{Interpreter
8025: Directives}).
1.44 crook 8026:
1.35 anton 8027:
8028: @c This is a bad example: It's non-standard, and it's not necessary.
8029: @c However, I can't think of a good example for switching into compile
8030: @c state when there is no current word (@code{state}-smart words are not a
8031: @c good reason). So maybe we should use an example for switching into
8032: @c interpret @code{state} in a colon def. - anton
1.44 crook 8033: @c nac-> I agree. I started out by putting in the example, then realised
8034: @c that it was non-ANS, so wrote more words around it. I hope this
8035: @c re-written version is acceptable to you. I do want to keep the example
8036: @c as it is helpful for showing what is and what is not portable, particularly
8037: @c where it outlaws a style in common use.
8038:
1.72 anton 8039: @c anton: it's more important to show what's portable. After we have done
1.83 anton 8040: @c that, we can also show what's not. In any case, I have written a
8041: @c section Compiling Words which also deals with [ ].
1.35 anton 8042:
1.95 anton 8043: @c !! The following example does not work in Gforth 0.5.9 or later.
1.29 crook 8044:
1.95 anton 8045: @c @code{[} and @code{]} also give you the ability to switch into compile
8046: @c state and back, but we cannot think of any useful Standard application
8047: @c for this ability. Pre-ANS Forth textbooks have examples like this:
8048:
8049: @c @example
8050: @c : AA ." this is A" ;
8051: @c : BB ." this is B" ;
8052: @c : CC ." this is C" ;
8053:
8054: @c create table ] aa bb cc [
8055:
8056: @c : go ( n -- ) \ n is offset into table.. 0 for 1st entry
8057: @c cells table + @@ execute ;
8058: @c @end example
8059:
8060: @c This example builds a jump table; @code{0 go} will display ``@code{this
8061: @c is A}''. Using @code{[} and @code{]} in this example is equivalent to
8062: @c defining @code{table} like this:
8063:
8064: @c @example
8065: @c create table ' aa COMPILE, ' bb COMPILE, ' cc COMPILE,
8066: @c @end example
8067:
8068: @c The problem with this code is that the definition of @code{table} is not
8069: @c portable -- it @i{compile}s execution tokens into code space. Whilst it
8070: @c @i{may} work on systems where code space and data space co-incide, the
8071: @c Standard only allows data space to be assigned for a @code{CREATE}d
8072: @c word. In addition, the Standard only allows @code{@@} to access data
8073: @c space, whilst this example is using it to access code space. The only
8074: @c portable, Standard way to build this table is to build it in data space,
8075: @c like this:
8076:
8077: @c @example
8078: @c create table ' aa , ' bb , ' cc ,
8079: @c @end example
1.29 crook 8080:
1.95 anton 8081: @c doc-state
1.44 crook 8082:
1.29 crook 8083:
1.82 anton 8084: @node Interpreter Directives, , Interpret/Compile states, The Text Interpreter
1.26 crook 8085: @subsection Interpreter Directives
8086: @cindex interpreter directives
1.72 anton 8087: @cindex conditional compilation
1.1 anton 8088:
1.29 crook 8089: These words are usually used in interpret state; typically to control
8090: which parts of a source file are processed by the text
1.26 crook 8091: interpreter. There are only a few ANS Forth Standard words, but Gforth
8092: supplements these with a rich set of immediate control structure words
8093: to compensate for the fact that the non-immediate versions can only be
1.29 crook 8094: used in compile state (@pxref{Control Structures}). Typical usages:
8095:
8096: @example
1.72 anton 8097: FALSE Constant HAVE-ASSEMBLER
1.29 crook 8098: .
8099: .
1.72 anton 8100: HAVE-ASSEMBLER [IF]
1.29 crook 8101: : ASSEMBLER-FEATURE
8102: ...
8103: ;
8104: [ENDIF]
8105: .
8106: .
8107: : SEE
8108: ... \ general-purpose SEE code
1.72 anton 8109: [ HAVE-ASSEMBLER [IF] ]
1.29 crook 8110: ... \ assembler-specific SEE code
8111: [ [ENDIF] ]
8112: ;
8113: @end example
1.1 anton 8114:
1.44 crook 8115:
1.26 crook 8116: doc-[IF]
8117: doc-[ELSE]
8118: doc-[THEN]
8119: doc-[ENDIF]
1.1 anton 8120:
1.26 crook 8121: doc-[IFDEF]
8122: doc-[IFUNDEF]
1.1 anton 8123:
1.26 crook 8124: doc-[?DO]
8125: doc-[DO]
8126: doc-[FOR]
8127: doc-[LOOP]
8128: doc-[+LOOP]
8129: doc-[NEXT]
1.1 anton 8130:
1.26 crook 8131: doc-[BEGIN]
8132: doc-[UNTIL]
8133: doc-[AGAIN]
8134: doc-[WHILE]
8135: doc-[REPEAT]
1.1 anton 8136:
1.27 crook 8137:
1.26 crook 8138: @c -------------------------------------------------------------
1.111 anton 8139: @node The Input Stream, Word Lists, The Text Interpreter, Words
8140: @section The Input Stream
8141: @cindex input stream
8142:
8143: @c !! integrate this better with the "Text Interpreter" section
8144: The text interpreter reads from the input stream, which can come from
8145: several sources (@pxref{Input Sources}). Some words, in particular
8146: defining words, but also words like @code{'}, read parameters from the
8147: input stream instead of from the stack.
8148:
8149: Such words are called parsing words, because they parse the input
8150: stream. Parsing words are hard to use in other words, because it is
8151: hard to pass program-generated parameters through the input stream.
8152: They also usually have an unintuitive combination of interpretation and
8153: compilation semantics when implemented naively, leading to various
8154: approaches that try to produce a more intuitive behaviour
8155: (@pxref{Combined words}).
8156:
8157: It should be obvious by now that parsing words are a bad idea. If you
8158: want to implement a parsing word for convenience, also provide a factor
8159: of the word that does not parse, but takes the parameters on the stack.
8160: To implement the parsing word on top if it, you can use the following
8161: words:
8162:
8163: @c anton: these belong in the input stream section
8164: doc-parse
8165: doc-parse-word
8166: doc-name
8167: doc-word
8168: doc-\"-parse
8169: doc-refill
8170:
8171: Conversely, if you have the bad luck (or lack of foresight) to have to
8172: deal with parsing words without having such factors, how do you pass a
8173: string that is not in the input stream to it?
8174:
8175: doc-execute-parsing
8176:
8177: If you want to run a parsing word on a file, the following word should
8178: help:
8179:
8180: doc-execute-parsing-file
8181:
8182: @c -------------------------------------------------------------
8183: @node Word Lists, Environmental Queries, The Input Stream, Words
1.26 crook 8184: @section Word Lists
8185: @cindex word lists
1.32 anton 8186: @cindex header space
1.1 anton 8187:
1.36 anton 8188: A wordlist is a list of named words; you can add new words and look up
8189: words by name (and you can remove words in a restricted way with
8190: markers). Every named (and @code{reveal}ed) word is in one wordlist.
8191:
8192: @cindex search order stack
8193: The text interpreter searches the wordlists present in the search order
8194: (a stack of wordlists), from the top to the bottom. Within each
8195: wordlist, the search starts conceptually at the newest word; i.e., if
8196: two words in a wordlist have the same name, the newer word is found.
1.1 anton 8197:
1.26 crook 8198: @cindex compilation word list
1.36 anton 8199: New words are added to the @dfn{compilation wordlist} (aka current
8200: wordlist).
1.1 anton 8201:
1.36 anton 8202: @cindex wid
8203: A word list is identified by a cell-sized word list identifier (@i{wid})
8204: in much the same way as a file is identified by a file handle. The
8205: numerical value of the wid has no (portable) meaning, and might change
8206: from session to session.
1.1 anton 8207:
1.29 crook 8208: The ANS Forth ``Search order'' word set is intended to provide a set of
8209: low-level tools that allow various different schemes to be
1.74 anton 8210: implemented. Gforth also provides @code{vocabulary}, a traditional Forth
1.26 crook 8211: word. @file{compat/vocabulary.fs} provides an implementation in ANS
1.45 crook 8212: Forth.
1.1 anton 8213:
1.27 crook 8214: @comment TODO: locals section refers to here, saying that every word list (aka
8215: @comment vocabulary) has its own methods for searching etc. Need to document that.
1.78 anton 8216: @c anton: but better in a separate subsection on wordlist internals
1.1 anton 8217:
1.45 crook 8218: @comment TODO: document markers, reveal, tables, mappedwordlist
8219:
8220: @comment the gforthman- prefix is used to pick out the true definition of a
1.27 crook 8221: @comment word from the source files, rather than some alias.
1.44 crook 8222:
1.26 crook 8223: doc-forth-wordlist
8224: doc-definitions
8225: doc-get-current
8226: doc-set-current
8227: doc-get-order
1.45 crook 8228: doc---gforthman-set-order
1.26 crook 8229: doc-wordlist
1.30 anton 8230: doc-table
1.79 anton 8231: doc->order
1.36 anton 8232: doc-previous
1.26 crook 8233: doc-also
1.45 crook 8234: doc---gforthman-forth
1.26 crook 8235: doc-only
1.45 crook 8236: doc---gforthman-order
1.15 anton 8237:
1.26 crook 8238: doc-find
8239: doc-search-wordlist
1.15 anton 8240:
1.26 crook 8241: doc-words
8242: doc-vlist
1.44 crook 8243: @c doc-words-deferred
1.1 anton 8244:
1.74 anton 8245: @c doc-mappedwordlist @c map-structure undefined, implemantation-specific
1.26 crook 8246: doc-root
8247: doc-vocabulary
8248: doc-seal
8249: doc-vocs
8250: doc-current
8251: doc-context
1.1 anton 8252:
1.44 crook 8253:
1.26 crook 8254: @menu
1.75 anton 8255: * Vocabularies::
1.67 anton 8256: * Why use word lists?::
1.75 anton 8257: * Word list example::
1.26 crook 8258: @end menu
8259:
1.75 anton 8260: @node Vocabularies, Why use word lists?, Word Lists, Word Lists
8261: @subsection Vocabularies
8262: @cindex Vocabularies, detailed explanation
8263:
8264: Here is an example of creating and using a new wordlist using ANS
8265: Forth words:
8266:
8267: @example
8268: wordlist constant my-new-words-wordlist
8269: : my-new-words get-order nip my-new-words-wordlist swap set-order ;
8270:
8271: \ add it to the search order
8272: also my-new-words
8273:
8274: \ alternatively, add it to the search order and make it
8275: \ the compilation word list
8276: also my-new-words definitions
8277: \ type "order" to see the problem
8278: @end example
8279:
8280: The problem with this example is that @code{order} has no way to
8281: associate the name @code{my-new-words} with the wid of the word list (in
8282: Gforth, @code{order} and @code{vocs} will display @code{???} for a wid
8283: that has no associated name). There is no Standard way of associating a
8284: name with a wid.
8285:
8286: In Gforth, this example can be re-coded using @code{vocabulary}, which
8287: associates a name with a wid:
8288:
8289: @example
8290: vocabulary my-new-words
8291:
8292: \ add it to the search order
8293: also my-new-words
8294:
8295: \ alternatively, add it to the search order and make it
8296: \ the compilation word list
8297: my-new-words definitions
8298: \ type "order" to see that the problem is solved
8299: @end example
8300:
8301:
8302: @node Why use word lists?, Word list example, Vocabularies, Word Lists
1.26 crook 8303: @subsection Why use word lists?
8304: @cindex word lists - why use them?
8305:
1.74 anton 8306: Here are some reasons why people use wordlists:
1.26 crook 8307:
8308: @itemize @bullet
1.74 anton 8309:
8310: @c anton: Gforth's hashing implementation makes the search speed
8311: @c independent from the number of words. But it is linear with the number
8312: @c of wordlists that have to be searched, so in effect using more wordlists
8313: @c actually slows down compilation.
8314:
8315: @c @item
8316: @c To improve compilation speed by reducing the number of header space
8317: @c entries that must be searched. This is achieved by creating a new
8318: @c word list that contains all of the definitions that are used in the
8319: @c definition of a Forth system but which would not usually be used by
8320: @c programs running on that system. That word list would be on the search
8321: @c list when the Forth system was compiled but would be removed from the
8322: @c search list for normal operation. This can be a useful technique for
8323: @c low-performance systems (for example, 8-bit processors in embedded
8324: @c systems) but is unlikely to be necessary in high-performance desktop
8325: @c systems.
8326:
1.26 crook 8327: @item
8328: To prevent a set of words from being used outside the context in which
8329: they are valid. Two classic examples of this are an integrated editor
8330: (all of the edit commands are defined in a separate word list; the
8331: search order is set to the editor word list when the editor is invoked;
8332: the old search order is restored when the editor is terminated) and an
8333: integrated assembler (the op-codes for the machine are defined in a
8334: separate word list which is used when a @code{CODE} word is defined).
1.74 anton 8335:
8336: @item
8337: To organize the words of an application or library into a user-visible
8338: set (in @code{forth-wordlist} or some other common wordlist) and a set
8339: of helper words used just for the implementation (hidden in a separate
1.75 anton 8340: wordlist). This keeps @code{words}' output smaller, separates
8341: implementation and interface, and reduces the chance of name conflicts
8342: within the common wordlist.
1.74 anton 8343:
1.26 crook 8344: @item
8345: To prevent a name-space clash between multiple definitions with the same
8346: name. For example, when building a cross-compiler you might have a word
8347: @code{IF} that generates conditional code for your target system. By
8348: placing this definition in a different word list you can control whether
8349: the host system's @code{IF} or the target system's @code{IF} get used in
8350: any particular context by controlling the order of the word lists on the
8351: search order stack.
1.74 anton 8352:
1.26 crook 8353: @end itemize
1.1 anton 8354:
1.74 anton 8355: The downsides of using wordlists are:
8356:
8357: @itemize
8358:
8359: @item
8360: Debugging becomes more cumbersome.
8361:
8362: @item
8363: Name conflicts worked around with wordlists are still there, and you
8364: have to arrange the search order carefully to get the desired results;
8365: if you forget to do that, you get hard-to-find errors (as in any case
8366: where you read the code differently from the compiler; @code{see} can
1.75 anton 8367: help seeing which of several possible words the name resolves to in such
8368: cases). @code{See} displays just the name of the words, not what
8369: wordlist they belong to, so it might be misleading. Using unique names
8370: is a better approach to avoid name conflicts.
1.74 anton 8371:
8372: @item
8373: You have to explicitly undo any changes to the search order. In many
8374: cases it would be more convenient if this happened implicitly. Gforth
8375: currently does not provide such a feature, but it may do so in the
8376: future.
8377: @end itemize
8378:
8379:
1.75 anton 8380: @node Word list example, , Why use word lists?, Word Lists
8381: @subsection Word list example
8382: @cindex word lists - example
1.1 anton 8383:
1.74 anton 8384: The following example is from the
8385: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
8386: garbage collector} and uses wordlists to separate public words from
8387: helper words:
8388:
8389: @example
8390: get-current ( wid )
8391: vocabulary garbage-collector also garbage-collector definitions
8392: ... \ define helper words
8393: ( wid ) set-current \ restore original (i.e., public) compilation wordlist
8394: ... \ define the public (i.e., API) words
8395: \ they can refer to the helper words
8396: previous \ restore original search order (helper words become invisible)
8397: @end example
8398:
1.26 crook 8399: @c -------------------------------------------------------------
8400: @node Environmental Queries, Files, Word Lists, Words
8401: @section Environmental Queries
8402: @cindex environmental queries
1.21 crook 8403:
1.26 crook 8404: ANS Forth introduced the idea of ``environmental queries'' as a way
8405: for a program running on a system to determine certain characteristics of the system.
8406: The Standard specifies a number of strings that might be recognised by a system.
1.21 crook 8407:
1.32 anton 8408: The Standard requires that the header space used for environmental queries
8409: be distinct from the header space used for definitions.
1.21 crook 8410:
1.26 crook 8411: Typically, environmental queries are supported by creating a set of
1.29 crook 8412: definitions in a word list that is @i{only} used during environmental
1.26 crook 8413: queries; that is what Gforth does. There is no Standard way of adding
8414: definitions to the set of recognised environmental queries, but any
8415: implementation that supports the loading of optional word sets must have
8416: some mechanism for doing this (after loading the word set, the
8417: associated environmental query string must return @code{true}). In
8418: Gforth, the word list used to honour environmental queries can be
8419: manipulated just like any other word list.
1.21 crook 8420:
1.44 crook 8421:
1.26 crook 8422: doc-environment?
8423: doc-environment-wordlist
1.21 crook 8424:
1.26 crook 8425: doc-gforth
8426: doc-os-class
1.21 crook 8427:
1.44 crook 8428:
1.26 crook 8429: Note that, whilst the documentation for (e.g.) @code{gforth} shows it
8430: returning two items on the stack, querying it using @code{environment?}
8431: will return an additional item; the @code{true} flag that shows that the
8432: string was recognised.
1.21 crook 8433:
1.26 crook 8434: @comment TODO Document the standard strings or note where they are documented herein
1.21 crook 8435:
1.26 crook 8436: Here are some examples of using environmental queries:
1.21 crook 8437:
1.26 crook 8438: @example
8439: s" address-unit-bits" environment? 0=
8440: [IF]
8441: cr .( environmental attribute address-units-bits unknown... ) cr
1.75 anton 8442: [ELSE]
8443: drop \ ensure balanced stack effect
1.26 crook 8444: [THEN]
1.21 crook 8445:
1.75 anton 8446: \ this might occur in the prelude of a standard program that uses THROW
8447: s" exception" environment? [IF]
8448: 0= [IF]
8449: : throw abort" exception thrown" ;
8450: [THEN]
8451: [ELSE] \ we don't know, so make sure
8452: : throw abort" exception thrown" ;
8453: [THEN]
1.21 crook 8454:
1.26 crook 8455: s" gforth" environment? [IF] .( Gforth version ) TYPE
8456: [ELSE] .( Not Gforth..) [THEN]
1.75 anton 8457:
8458: \ a program using v*
8459: s" gforth" environment? [IF]
8460: s" 0.5.0" compare 0< [IF] \ v* is a primitive since 0.5.0
8461: : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
8462: >r swap 2swap swap 0e r> 0 ?DO
8463: dup f@ over + 2swap dup f@ f* f+ over + 2swap
8464: LOOP
8465: 2drop 2drop ;
8466: [THEN]
8467: [ELSE] \
8468: : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
8469: ...
8470: [THEN]
1.26 crook 8471: @end example
1.21 crook 8472:
1.26 crook 8473: Here is an example of adding a definition to the environment word list:
1.21 crook 8474:
1.26 crook 8475: @example
8476: get-current environment-wordlist set-current
8477: true constant block
8478: true constant block-ext
8479: set-current
8480: @end example
1.21 crook 8481:
1.26 crook 8482: You can see what definitions are in the environment word list like this:
1.21 crook 8483:
1.26 crook 8484: @example
1.79 anton 8485: environment-wordlist >order words previous
1.26 crook 8486: @end example
1.21 crook 8487:
8488:
1.26 crook 8489: @c -------------------------------------------------------------
8490: @node Files, Blocks, Environmental Queries, Words
8491: @section Files
1.28 crook 8492: @cindex files
8493: @cindex I/O - file-handling
1.21 crook 8494:
1.26 crook 8495: Gforth provides facilities for accessing files that are stored in the
8496: host operating system's file-system. Files that are processed by Gforth
8497: can be divided into two categories:
1.21 crook 8498:
1.23 crook 8499: @itemize @bullet
8500: @item
1.29 crook 8501: Files that are processed by the Text Interpreter (@dfn{Forth source files}).
1.23 crook 8502: @item
1.29 crook 8503: Files that are processed by some other program (@dfn{general files}).
1.26 crook 8504: @end itemize
8505:
8506: @menu
1.48 anton 8507: * Forth source files::
8508: * General files::
8509: * Search Paths::
1.26 crook 8510: @end menu
8511:
8512: @c -------------------------------------------------------------
8513: @node Forth source files, General files, Files, Files
8514: @subsection Forth source files
8515: @cindex including files
8516: @cindex Forth source files
1.21 crook 8517:
1.26 crook 8518: The simplest way to interpret the contents of a file is to use one of
8519: these two formats:
1.21 crook 8520:
1.26 crook 8521: @example
8522: include mysource.fs
8523: s" mysource.fs" included
8524: @end example
1.21 crook 8525:
1.75 anton 8526: You usually want to include a file only if it is not included already
1.26 crook 8527: (by, say, another source file). In that case, you can use one of these
1.45 crook 8528: three formats:
1.21 crook 8529:
1.26 crook 8530: @example
8531: require mysource.fs
8532: needs mysource.fs
8533: s" mysource.fs" required
8534: @end example
1.21 crook 8535:
1.26 crook 8536: @cindex stack effect of included files
8537: @cindex including files, stack effect
1.45 crook 8538: It is good practice to write your source files such that interpreting them
8539: does not change the stack. Source files designed in this way can be used with
1.26 crook 8540: @code{required} and friends without complications. For example:
1.21 crook 8541:
1.26 crook 8542: @example
1.75 anton 8543: 1024 require foo.fs drop
1.26 crook 8544: @end example
1.21 crook 8545:
1.75 anton 8546: Here you want to pass the argument 1024 (e.g., a buffer size) to
8547: @file{foo.fs}. Interpreting @file{foo.fs} has the stack effect ( n -- n
8548: ), which allows its use with @code{require}. Of course with such
8549: parameters to required files, you have to ensure that the first
8550: @code{require} fits for all uses (i.e., @code{require} it early in the
8551: master load file).
1.44 crook 8552:
1.26 crook 8553: doc-include-file
8554: doc-included
1.28 crook 8555: doc-included?
1.26 crook 8556: doc-include
8557: doc-required
8558: doc-require
8559: doc-needs
1.75 anton 8560: @c doc-init-included-files @c internal
8561: doc-sourcefilename
8562: doc-sourceline#
1.44 crook 8563:
1.26 crook 8564: A definition in ANS Forth for @code{required} is provided in
8565: @file{compat/required.fs}.
1.21 crook 8566:
1.26 crook 8567: @c -------------------------------------------------------------
8568: @node General files, Search Paths, Forth source files, Files
8569: @subsection General files
8570: @cindex general files
8571: @cindex file-handling
1.21 crook 8572:
1.75 anton 8573: Files are opened/created by name and type. The following file access
8574: methods (FAMs) are recognised:
1.44 crook 8575:
1.75 anton 8576: @cindex fam (file access method)
1.26 crook 8577: doc-r/o
8578: doc-r/w
8579: doc-w/o
8580: doc-bin
1.1 anton 8581:
1.44 crook 8582:
1.26 crook 8583: When a file is opened/created, it returns a file identifier,
1.29 crook 8584: @i{wfileid} that is used for all other file commands. All file
8585: commands also return a status value, @i{wior}, that is 0 for a
1.26 crook 8586: successful operation and an implementation-defined non-zero value in the
8587: case of an error.
1.21 crook 8588:
1.44 crook 8589:
1.26 crook 8590: doc-open-file
8591: doc-create-file
1.21 crook 8592:
1.26 crook 8593: doc-close-file
8594: doc-delete-file
8595: doc-rename-file
8596: doc-read-file
8597: doc-read-line
8598: doc-write-file
8599: doc-write-line
8600: doc-emit-file
8601: doc-flush-file
1.21 crook 8602:
1.26 crook 8603: doc-file-status
8604: doc-file-position
8605: doc-reposition-file
8606: doc-file-size
8607: doc-resize-file
1.21 crook 8608:
1.93 anton 8609: doc-slurp-file
8610: doc-slurp-fid
1.112 ! anton 8611: doc-stdin
! 8612: doc-stdout
! 8613: doc-stderr
1.44 crook 8614:
1.26 crook 8615: @c ---------------------------------------------------------
1.48 anton 8616: @node Search Paths, , General files, Files
1.26 crook 8617: @subsection Search Paths
8618: @cindex path for @code{included}
8619: @cindex file search path
8620: @cindex @code{include} search path
8621: @cindex search path for files
1.21 crook 8622:
1.26 crook 8623: If you specify an absolute filename (i.e., a filename starting with
8624: @file{/} or @file{~}, or with @file{:} in the second position (as in
8625: @samp{C:...})) for @code{included} and friends, that file is included
8626: just as you would expect.
1.21 crook 8627:
1.75 anton 8628: If the filename starts with @file{./}, this refers to the directory that
8629: the present file was @code{included} from. This allows files to include
8630: other files relative to their own position (irrespective of the current
8631: working directory or the absolute position). This feature is essential
8632: for libraries consisting of several files, where a file may include
8633: other files from the library. It corresponds to @code{#include "..."}
8634: in C. If the current input source is not a file, @file{.} refers to the
8635: directory of the innermost file being included, or, if there is no file
8636: being included, to the current working directory.
8637:
8638: For relative filenames (not starting with @file{./}), Gforth uses a
8639: search path similar to Forth's search order (@pxref{Word Lists}). It
8640: tries to find the given filename in the directories present in the path,
8641: and includes the first one it finds. There are separate search paths for
8642: Forth source files and general files. If the search path contains the
8643: directory @file{.}, this refers to the directory of the current file, or
8644: the working directory, as if the file had been specified with @file{./}.
1.21 crook 8645:
1.26 crook 8646: Use @file{~+} to refer to the current working directory (as in the
8647: @code{bash}).
1.1 anton 8648:
1.75 anton 8649: @c anton: fold the following subsubsections into this subsection?
1.1 anton 8650:
1.48 anton 8651: @menu
1.75 anton 8652: * Source Search Paths::
1.48 anton 8653: * General Search Paths::
8654: @end menu
8655:
1.26 crook 8656: @c ---------------------------------------------------------
1.75 anton 8657: @node Source Search Paths, General Search Paths, Search Paths, Search Paths
8658: @subsubsection Source Search Paths
8659: @cindex search path control, source files
1.5 anton 8660:
1.26 crook 8661: The search path is initialized when you start Gforth (@pxref{Invoking
1.75 anton 8662: Gforth}). You can display it and change it using @code{fpath} in
8663: combination with the general path handling words.
1.5 anton 8664:
1.75 anton 8665: doc-fpath
8666: @c the functionality of the following words is easily available through
8667: @c fpath and the general path words. The may go away.
8668: @c doc-.fpath
8669: @c doc-fpath+
8670: @c doc-fpath=
8671: @c doc-open-fpath-file
1.44 crook 8672:
8673: @noindent
1.26 crook 8674: Here is an example of using @code{fpath} and @code{require}:
1.5 anton 8675:
1.26 crook 8676: @example
1.75 anton 8677: fpath path= /usr/lib/forth/|./
1.26 crook 8678: require timer.fs
8679: @end example
1.5 anton 8680:
1.75 anton 8681:
1.26 crook 8682: @c ---------------------------------------------------------
1.75 anton 8683: @node General Search Paths, , Source Search Paths, Search Paths
1.26 crook 8684: @subsubsection General Search Paths
1.75 anton 8685: @cindex search path control, source files
1.5 anton 8686:
1.26 crook 8687: Your application may need to search files in several directories, like
8688: @code{included} does. To facilitate this, Gforth allows you to define
8689: and use your own search paths, by providing generic equivalents of the
8690: Forth search path words:
1.5 anton 8691:
1.75 anton 8692: doc-open-path-file
8693: doc-path-allot
8694: doc-clear-path
8695: doc-also-path
1.26 crook 8696: doc-.path
8697: doc-path+
8698: doc-path=
1.5 anton 8699:
1.75 anton 8700: @c anton: better define a word for it, say "path-allot ( ucount -- path-addr )
1.44 crook 8701:
1.75 anton 8702: Here's an example of creating an empty search path:
8703: @c
1.26 crook 8704: @example
1.75 anton 8705: create mypath 500 path-allot \ maximum length 500 chars (is checked)
1.26 crook 8706: @end example
1.5 anton 8707:
1.26 crook 8708: @c -------------------------------------------------------------
8709: @node Blocks, Other I/O, Files, Words
8710: @section Blocks
1.28 crook 8711: @cindex I/O - blocks
8712: @cindex blocks
8713:
8714: When you run Gforth on a modern desk-top computer, it runs under the
8715: control of an operating system which provides certain services. One of
8716: these services is @var{file services}, which allows Forth source code
8717: and data to be stored in files and read into Gforth (@pxref{Files}).
8718:
8719: Traditionally, Forth has been an important programming language on
8720: systems where it has interfaced directly to the underlying hardware with
8721: no intervening operating system. Forth provides a mechanism, called
1.29 crook 8722: @dfn{blocks}, for accessing mass storage on such systems.
1.28 crook 8723:
8724: A block is a 1024-byte data area, which can be used to hold data or
8725: Forth source code. No structure is imposed on the contents of the
8726: block. A block is identified by its number; blocks are numbered
8727: contiguously from 1 to an implementation-defined maximum.
8728:
8729: A typical system that used blocks but no operating system might use a
8730: single floppy-disk drive for mass storage, with the disks formatted to
8731: provide 256-byte sectors. Blocks would be implemented by assigning the
8732: first four sectors of the disk to block 1, the second four sectors to
8733: block 2 and so on, up to the limit of the capacity of the disk. The disk
8734: would not contain any file system information, just the set of blocks.
8735:
1.29 crook 8736: @cindex blocks file
1.28 crook 8737: On systems that do provide file services, blocks are typically
1.29 crook 8738: implemented by storing a sequence of blocks within a single @dfn{blocks
1.28 crook 8739: file}. The size of the blocks file will be an exact multiple of 1024
8740: bytes, corresponding to the number of blocks it contains. This is the
8741: mechanism that Gforth uses.
8742:
1.29 crook 8743: @cindex @file{blocks.fb}
1.75 anton 8744: Only one blocks file can be open at a time. If you use block words without
1.28 crook 8745: having specified a blocks file, Gforth defaults to the blocks file
8746: @file{blocks.fb}. Gforth uses the Forth search path when attempting to
1.75 anton 8747: locate a blocks file (@pxref{Source Search Paths}).
1.28 crook 8748:
1.29 crook 8749: @cindex block buffers
1.28 crook 8750: When you read and write blocks under program control, Gforth uses a
1.29 crook 8751: number of @dfn{block buffers} as intermediate storage. These buffers are
1.28 crook 8752: not used when you use @code{load} to interpret the contents of a block.
8753:
1.75 anton 8754: The behaviour of the block buffers is analagous to that of a cache.
8755: Each block buffer has three states:
1.28 crook 8756:
8757: @itemize @bullet
8758: @item
8759: Unassigned
8760: @item
8761: Assigned-clean
8762: @item
8763: Assigned-dirty
8764: @end itemize
8765:
1.29 crook 8766: Initially, all block buffers are @i{unassigned}. In order to access a
1.28 crook 8767: block, the block (specified by its block number) must be assigned to a
8768: block buffer.
8769:
8770: The assignment of a block to a block buffer is performed by @code{block}
8771: or @code{buffer}. Use @code{block} when you wish to modify the existing
8772: contents of a block. Use @code{buffer} when you don't care about the
8773: existing contents of the block@footnote{The ANS Forth definition of
1.35 anton 8774: @code{buffer} is intended not to cause disk I/O; if the data associated
1.28 crook 8775: with the particular block is already stored in a block buffer due to an
8776: earlier @code{block} command, @code{buffer} will return that block
8777: buffer and the existing contents of the block will be
8778: available. Otherwise, @code{buffer} will simply assign a new, empty
1.29 crook 8779: block buffer for the block.}.
1.28 crook 8780:
1.47 crook 8781: Once a block has been assigned to a block buffer using @code{block} or
1.75 anton 8782: @code{buffer}, that block buffer becomes the @i{current block
8783: buffer}. Data may only be manipulated (read or written) within the
8784: current block buffer.
1.47 crook 8785:
8786: When the contents of the current block buffer has been modified it is
1.48 anton 8787: necessary, @emph{before calling @code{block} or @code{buffer} again}, to
1.75 anton 8788: either abandon the changes (by doing nothing) or mark the block as
8789: changed (assigned-dirty), using @code{update}. Using @code{update} does
8790: not change the blocks file; it simply changes a block buffer's state to
8791: @i{assigned-dirty}. The block will be written implicitly when it's
8792: buffer is needed for another block, or explicitly by @code{flush} or
8793: @code{save-buffers}.
8794:
8795: word @code{Flush} writes all @i{assigned-dirty} blocks back to the
8796: blocks file on disk. Leaving Gforth with @code{bye} also performs a
8797: @code{flush}.
1.28 crook 8798:
1.29 crook 8799: In Gforth, @code{block} and @code{buffer} use a @i{direct-mapped}
1.28 crook 8800: algorithm to assign a block buffer to a block. That means that any
8801: particular block can only be assigned to one specific block buffer,
1.29 crook 8802: called (for the particular operation) the @i{victim buffer}. If the
1.47 crook 8803: victim buffer is @i{unassigned} or @i{assigned-clean} it is allocated to
8804: the new block immediately. If it is @i{assigned-dirty} its current
8805: contents are written back to the blocks file on disk before it is
1.28 crook 8806: allocated to the new block.
8807:
8808: Although no structure is imposed on the contents of a block, it is
8809: traditional to display the contents as 16 lines each of 64 characters. A
8810: block provides a single, continuous stream of input (for example, it
8811: acts as a single parse area) -- there are no end-of-line characters
8812: within a block, and no end-of-file character at the end of a
8813: block. There are two consequences of this:
1.26 crook 8814:
1.28 crook 8815: @itemize @bullet
8816: @item
8817: The last character of one line wraps straight into the first character
8818: of the following line
8819: @item
8820: The word @code{\} -- comment to end of line -- requires special
8821: treatment; in the context of a block it causes all characters until the
8822: end of the current 64-character ``line'' to be ignored.
8823: @end itemize
8824:
8825: In Gforth, when you use @code{block} with a non-existent block number,
1.45 crook 8826: the current blocks file will be extended to the appropriate size and the
1.28 crook 8827: block buffer will be initialised with spaces.
8828:
1.47 crook 8829: Gforth includes a simple block editor (type @code{use blocked.fb 0 list}
8830: for details) but doesn't encourage the use of blocks; the mechanism is
8831: only provided for backward compatibility -- ANS Forth requires blocks to
8832: be available when files are.
1.28 crook 8833:
8834: Common techniques that are used when working with blocks include:
8835:
8836: @itemize @bullet
8837: @item
8838: A screen editor that allows you to edit blocks without leaving the Forth
8839: environment.
8840: @item
8841: Shadow screens; where every code block has an associated block
8842: containing comments (for example: code in odd block numbers, comments in
8843: even block numbers). Typically, the block editor provides a convenient
8844: mechanism to toggle between code and comments.
8845: @item
8846: Load blocks; a single block (typically block 1) contains a number of
8847: @code{thru} commands which @code{load} the whole of the application.
8848: @end itemize
1.26 crook 8849:
1.29 crook 8850: See Frank Sergeant's Pygmy Forth to see just how well blocks can be
8851: integrated into a Forth programming environment.
1.26 crook 8852:
8853: @comment TODO what about errors on open-blocks?
1.44 crook 8854:
1.26 crook 8855: doc-open-blocks
8856: doc-use
1.75 anton 8857: doc-block-offset
1.26 crook 8858: doc-get-block-fid
8859: doc-block-position
1.28 crook 8860:
1.75 anton 8861: doc-list
1.28 crook 8862: doc-scr
8863:
1.45 crook 8864: doc---gforthman-block
1.28 crook 8865: doc-buffer
8866:
1.75 anton 8867: doc-empty-buffers
8868: doc-empty-buffer
1.26 crook 8869: doc-update
1.28 crook 8870: doc-updated?
1.26 crook 8871: doc-save-buffers
1.75 anton 8872: doc-save-buffer
1.26 crook 8873: doc-flush
1.28 crook 8874:
1.26 crook 8875: doc-load
8876: doc-thru
8877: doc-+load
8878: doc-+thru
1.45 crook 8879: doc---gforthman--->
1.26 crook 8880: doc-block-included
8881:
1.44 crook 8882:
1.26 crook 8883: @c -------------------------------------------------------------
1.78 anton 8884: @node Other I/O, Locals, Blocks, Words
1.26 crook 8885: @section Other I/O
1.28 crook 8886: @cindex I/O - keyboard and display
1.26 crook 8887:
8888: @menu
8889: * Simple numeric output:: Predefined formats
8890: * Formatted numeric output:: Formatted (pictured) output
8891: * String Formats:: How Forth stores strings in memory
1.67 anton 8892: * Displaying characters and strings:: Other stuff
1.26 crook 8893: * Input:: Input
1.112 ! anton 8894: * Pipes:: How to create your own pipes
1.26 crook 8895: @end menu
8896:
8897: @node Simple numeric output, Formatted numeric output, Other I/O, Other I/O
8898: @subsection Simple numeric output
1.28 crook 8899: @cindex numeric output - simple/free-format
1.5 anton 8900:
1.26 crook 8901: The simplest output functions are those that display numbers from the
8902: data or floating-point stacks. Floating-point output is always displayed
8903: using base 10. Numbers displayed from the data stack use the value stored
8904: in @code{base}.
1.5 anton 8905:
1.44 crook 8906:
1.26 crook 8907: doc-.
8908: doc-dec.
8909: doc-hex.
8910: doc-u.
8911: doc-.r
8912: doc-u.r
8913: doc-d.
8914: doc-ud.
8915: doc-d.r
8916: doc-ud.r
8917: doc-f.
8918: doc-fe.
8919: doc-fs.
1.111 anton 8920: doc-f.rdp
1.44 crook 8921:
1.26 crook 8922: Examples of printing the number 1234.5678E23 in the different floating-point output
8923: formats are shown below:
1.5 anton 8924:
8925: @example
1.26 crook 8926: f. 123456779999999000000000000.
8927: fe. 123.456779999999E24
8928: fs. 1.23456779999999E26
1.5 anton 8929: @end example
8930:
8931:
1.26 crook 8932: @node Formatted numeric output, String Formats, Simple numeric output, Other I/O
8933: @subsection Formatted numeric output
1.28 crook 8934: @cindex formatted numeric output
1.26 crook 8935: @cindex pictured numeric output
1.28 crook 8936: @cindex numeric output - formatted
1.26 crook 8937:
1.29 crook 8938: Forth traditionally uses a technique called @dfn{pictured numeric
1.26 crook 8939: output} for formatted printing of integers. In this technique, digits
8940: are extracted from the number (using the current output radix defined by
8941: @code{base}), converted to ASCII codes and appended to a string that is
8942: built in a scratch-pad area of memory (@pxref{core-idef,
8943: Implementation-defined options, Implementation-defined
8944: options}). Arbitrary characters can be appended to the string during the
8945: extraction process. The completed string is specified by an address
8946: and length and can be manipulated (@code{TYPE}ed, copied, modified)
8947: under program control.
1.5 anton 8948:
1.75 anton 8949: All of the integer output words described in the previous section
8950: (@pxref{Simple numeric output}) are implemented in Gforth using pictured
8951: numeric output.
1.5 anton 8952:
1.47 crook 8953: Three important things to remember about pictured numeric output:
1.5 anton 8954:
1.26 crook 8955: @itemize @bullet
8956: @item
1.28 crook 8957: It always operates on double-precision numbers; to display a
1.49 anton 8958: single-precision number, convert it first (for ways of doing this
8959: @pxref{Double precision}).
1.26 crook 8960: @item
1.28 crook 8961: It always treats the double-precision number as though it were
8962: unsigned. The examples below show ways of printing signed numbers.
1.26 crook 8963: @item
8964: The string is built up from right to left; least significant digit first.
8965: @end itemize
1.5 anton 8966:
1.44 crook 8967:
1.26 crook 8968: doc-<#
1.47 crook 8969: doc-<<#
1.26 crook 8970: doc-#
8971: doc-#s
8972: doc-hold
8973: doc-sign
8974: doc-#>
1.47 crook 8975: doc-#>>
1.5 anton 8976:
1.26 crook 8977: doc-represent
1.111 anton 8978: doc-f>str-rdp
8979: doc-f>buf-rdp
1.5 anton 8980:
1.44 crook 8981:
8982: @noindent
1.26 crook 8983: Here are some examples of using pictured numeric output:
1.5 anton 8984:
8985: @example
1.26 crook 8986: : my-u. ( u -- )
8987: \ Simplest use of pns.. behaves like Standard u.
8988: 0 \ convert to unsigned double
1.75 anton 8989: <<# \ start conversion
1.26 crook 8990: #s \ convert all digits
8991: #> \ complete conversion
1.75 anton 8992: TYPE SPACE \ display, with trailing space
8993: #>> ; \ release hold area
1.5 anton 8994:
1.26 crook 8995: : cents-only ( u -- )
8996: 0 \ convert to unsigned double
1.75 anton 8997: <<# \ start conversion
1.26 crook 8998: # # \ convert two least-significant digits
8999: #> \ complete conversion, discard other digits
1.75 anton 9000: TYPE SPACE \ display, with trailing space
9001: #>> ; \ release hold area
1.5 anton 9002:
1.26 crook 9003: : dollars-and-cents ( u -- )
9004: 0 \ convert to unsigned double
1.75 anton 9005: <<# \ start conversion
1.26 crook 9006: # # \ convert two least-significant digits
9007: [char] . hold \ insert decimal point
9008: #s \ convert remaining digits
9009: [char] $ hold \ append currency symbol
9010: #> \ complete conversion
1.75 anton 9011: TYPE SPACE \ display, with trailing space
9012: #>> ; \ release hold area
1.5 anton 9013:
1.26 crook 9014: : my-. ( n -- )
9015: \ handling negatives.. behaves like Standard .
9016: s>d \ convert to signed double
9017: swap over dabs \ leave sign byte followed by unsigned double
1.75 anton 9018: <<# \ start conversion
1.26 crook 9019: #s \ convert all digits
9020: rot sign \ get at sign byte, append "-" if needed
9021: #> \ complete conversion
1.75 anton 9022: TYPE SPACE \ display, with trailing space
9023: #>> ; \ release hold area
1.5 anton 9024:
1.26 crook 9025: : account. ( n -- )
1.75 anton 9026: \ accountants don't like minus signs, they use parentheses
1.26 crook 9027: \ for negative numbers
9028: s>d \ convert to signed double
9029: swap over dabs \ leave sign byte followed by unsigned double
1.75 anton 9030: <<# \ start conversion
1.26 crook 9031: 2 pick \ get copy of sign byte
9032: 0< IF [char] ) hold THEN \ right-most character of output
9033: #s \ convert all digits
9034: rot \ get at sign byte
9035: 0< IF [char] ( hold THEN
9036: #> \ complete conversion
1.75 anton 9037: TYPE SPACE \ display, with trailing space
9038: #>> ; \ release hold area
9039:
1.5 anton 9040: @end example
9041:
1.26 crook 9042: Here are some examples of using these words:
1.5 anton 9043:
9044: @example
1.26 crook 9045: 1 my-u. 1
9046: hex -1 my-u. decimal FFFFFFFF
9047: 1 cents-only 01
9048: 1234 cents-only 34
9049: 2 dollars-and-cents $0.02
9050: 1234 dollars-and-cents $12.34
9051: 123 my-. 123
9052: -123 my. -123
9053: 123 account. 123
9054: -456 account. (456)
1.5 anton 9055: @end example
9056:
9057:
1.26 crook 9058: @node String Formats, Displaying characters and strings, Formatted numeric output, Other I/O
9059: @subsection String Formats
1.27 crook 9060: @cindex strings - see character strings
9061: @cindex character strings - formats
1.28 crook 9062: @cindex I/O - see character strings
1.75 anton 9063: @cindex counted strings
9064:
9065: @c anton: this does not really belong here; maybe the memory section,
9066: @c or the principles chapter
1.26 crook 9067:
1.27 crook 9068: Forth commonly uses two different methods for representing character
9069: strings:
1.26 crook 9070:
9071: @itemize @bullet
9072: @item
9073: @cindex address of counted string
1.45 crook 9074: @cindex counted string
1.29 crook 9075: As a @dfn{counted string}, represented by a @i{c-addr}. The char
9076: addressed by @i{c-addr} contains a character-count, @i{n}, of the
9077: string and the string occupies the subsequent @i{n} char addresses in
1.26 crook 9078: memory.
9079: @item
1.29 crook 9080: As cell pair on the stack; @i{c-addr u}, where @i{u} is the length
9081: of the string in characters, and @i{c-addr} is the address of the
1.26 crook 9082: first byte of the string.
9083: @end itemize
9084:
9085: ANS Forth encourages the use of the second format when representing
1.75 anton 9086: strings.
1.26 crook 9087:
1.44 crook 9088:
1.26 crook 9089: doc-count
9090:
1.44 crook 9091:
1.49 anton 9092: For words that move, copy and search for strings see @ref{Memory
9093: Blocks}. For words that display characters and strings see
9094: @ref{Displaying characters and strings}.
1.26 crook 9095:
9096: @node Displaying characters and strings, Input, String Formats, Other I/O
9097: @subsection Displaying characters and strings
1.27 crook 9098: @cindex characters - compiling and displaying
9099: @cindex character strings - compiling and displaying
1.26 crook 9100:
9101: This section starts with a glossary of Forth words and ends with a set
9102: of examples.
9103:
1.44 crook 9104:
1.26 crook 9105: doc-bl
9106: doc-space
9107: doc-spaces
9108: doc-emit
9109: doc-toupper
9110: doc-."
9111: doc-.(
1.98 anton 9112: doc-.\"
1.26 crook 9113: doc-type
1.44 crook 9114: doc-typewhite
1.26 crook 9115: doc-cr
1.27 crook 9116: @cindex cursor control
1.26 crook 9117: doc-at-xy
9118: doc-page
9119: doc-s"
1.98 anton 9120: doc-s\"
1.26 crook 9121: doc-c"
9122: doc-char
9123: doc-[char]
9124:
1.44 crook 9125:
9126: @noindent
1.26 crook 9127: As an example, consider the following text, stored in a file @file{test.fs}:
1.5 anton 9128:
9129: @example
1.26 crook 9130: .( text-1)
9131: : my-word
9132: ." text-2" cr
9133: .( text-3)
9134: ;
9135:
9136: ." text-4"
9137:
9138: : my-char
9139: [char] ALPHABET emit
9140: char emit
9141: ;
1.5 anton 9142: @end example
9143:
1.26 crook 9144: When you load this code into Gforth, the following output is generated:
1.5 anton 9145:
1.26 crook 9146: @example
1.30 anton 9147: @kbd{include test.fs @key{RET}} text-1text-3text-4 ok
1.26 crook 9148: @end example
1.5 anton 9149:
1.26 crook 9150: @itemize @bullet
9151: @item
9152: Messages @code{text-1} and @code{text-3} are displayed because @code{.(}
9153: is an immediate word; it behaves in the same way whether it is used inside
9154: or outside a colon definition.
9155: @item
9156: Message @code{text-4} is displayed because of Gforth's added interpretation
9157: semantics for @code{."}.
9158: @item
1.29 crook 9159: Message @code{text-2} is @i{not} displayed, because the text interpreter
1.26 crook 9160: performs the compilation semantics for @code{."} within the definition of
9161: @code{my-word}.
9162: @end itemize
1.5 anton 9163:
1.26 crook 9164: Here are some examples of executing @code{my-word} and @code{my-char}:
1.5 anton 9165:
1.26 crook 9166: @example
1.30 anton 9167: @kbd{my-word @key{RET}} text-2
1.26 crook 9168: ok
1.30 anton 9169: @kbd{my-char fred @key{RET}} Af ok
9170: @kbd{my-char jim @key{RET}} Aj ok
1.26 crook 9171: @end example
1.5 anton 9172:
9173: @itemize @bullet
9174: @item
1.26 crook 9175: Message @code{text-2} is displayed because of the run-time behaviour of
9176: @code{."}.
9177: @item
9178: @code{[char]} compiles the ``A'' from ``ALPHABET'' and puts its display code
9179: on the stack at run-time. @code{emit} always displays the character
9180: when @code{my-char} is executed.
9181: @item
9182: @code{char} parses a string at run-time and the second @code{emit} displays
9183: the first character of the string.
1.5 anton 9184: @item
1.26 crook 9185: If you type @code{see my-char} you can see that @code{[char]} discarded
9186: the text ``LPHABET'' and only compiled the display code for ``A'' into the
9187: definition of @code{my-char}.
1.5 anton 9188: @end itemize
9189:
9190:
9191:
1.112 ! anton 9192: @node Input, Pipes, Displaying characters and strings, Other I/O
1.26 crook 9193: @subsection Input
9194: @cindex input
1.28 crook 9195: @cindex I/O - see input
9196: @cindex parsing a string
1.5 anton 9197:
1.49 anton 9198: For ways of storing character strings in memory see @ref{String Formats}.
1.5 anton 9199:
1.27 crook 9200: @comment TODO examples for >number >float accept key key? pad parse word refill
1.29 crook 9201: @comment then index them
1.27 crook 9202:
1.44 crook 9203:
1.27 crook 9204: doc-key
9205: doc-key?
1.45 crook 9206: doc-ekey
9207: doc-ekey?
9208: doc-ekey>char
1.26 crook 9209: doc->number
9210: doc->float
9211: doc-accept
1.109 anton 9212: doc-edit-line
1.27 crook 9213: doc-pad
9214: @comment obsolescent words..
9215: doc-convert
1.26 crook 9216: doc-expect
1.27 crook 9217: doc-span
1.5 anton 9218:
9219:
1.112 ! anton 9220: @node Pipes, , Input, Other I/O
! 9221: @subsection Pipes
! 9222: @cindex pipes, creating your own
! 9223:
! 9224: In addition to using Gforth in pipes created by other processes
! 9225: (@pxref{Gforth in pipes}), you can create your own pipe with
! 9226: @code{open-pipe}, and read from or write to it.
! 9227:
! 9228: doc-open-pipe
! 9229: doc-close-pipe
! 9230:
! 9231: If you write to a pipe, Gforth can throw a @code{broken-pipe-error}; if
! 9232: you don't catch this exception, Gforth will catch it and exit, usually
! 9233: silently (@pxref{Gforth in pipes}). Since you probably do not want
! 9234: this, you should wrap a @code{catch} or @code{try} block around the code
! 9235: from @code{open-pipe} to @code{close-pipe}, so you can deal with the
! 9236: problem yourself, and then return to regular processing.
! 9237:
! 9238: doc-broken-pipe-error
! 9239:
! 9240:
1.78 anton 9241: @c -------------------------------------------------------------
9242: @node Locals, Structures, Other I/O, Words
9243: @section Locals
9244: @cindex locals
9245:
9246: Local variables can make Forth programming more enjoyable and Forth
9247: programs easier to read. Unfortunately, the locals of ANS Forth are
9248: laden with restrictions. Therefore, we provide not only the ANS Forth
9249: locals wordset, but also our own, more powerful locals wordset (we
9250: implemented the ANS Forth locals wordset through our locals wordset).
1.44 crook 9251:
1.78 anton 9252: The ideas in this section have also been published in M. Anton Ertl,
9253: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl94l.ps.gz,
9254: Automatic Scoping of Local Variables}}, EuroForth '94.
1.12 anton 9255:
9256: @menu
1.78 anton 9257: * Gforth locals::
9258: * ANS Forth locals::
1.5 anton 9259: @end menu
9260:
1.78 anton 9261: @node Gforth locals, ANS Forth locals, Locals, Locals
9262: @subsection Gforth locals
9263: @cindex Gforth locals
9264: @cindex locals, Gforth style
1.5 anton 9265:
1.78 anton 9266: Locals can be defined with
1.44 crook 9267:
1.78 anton 9268: @example
9269: @{ local1 local2 ... -- comment @}
9270: @end example
9271: or
9272: @example
9273: @{ local1 local2 ... @}
9274: @end example
1.5 anton 9275:
1.78 anton 9276: E.g.,
9277: @example
9278: : max @{ n1 n2 -- n3 @}
9279: n1 n2 > if
9280: n1
9281: else
9282: n2
9283: endif ;
9284: @end example
1.44 crook 9285:
1.78 anton 9286: The similarity of locals definitions with stack comments is intended. A
9287: locals definition often replaces the stack comment of a word. The order
9288: of the locals corresponds to the order in a stack comment and everything
9289: after the @code{--} is really a comment.
1.77 anton 9290:
1.78 anton 9291: This similarity has one disadvantage: It is too easy to confuse locals
9292: declarations with stack comments, causing bugs and making them hard to
9293: find. However, this problem can be avoided by appropriate coding
9294: conventions: Do not use both notations in the same program. If you do,
9295: they should be distinguished using additional means, e.g. by position.
1.77 anton 9296:
1.78 anton 9297: @cindex types of locals
9298: @cindex locals types
9299: The name of the local may be preceded by a type specifier, e.g.,
9300: @code{F:} for a floating point value:
1.5 anton 9301:
1.78 anton 9302: @example
9303: : CX* @{ F: Ar F: Ai F: Br F: Bi -- Cr Ci @}
9304: \ complex multiplication
9305: Ar Br f* Ai Bi f* f-
9306: Ar Bi f* Ai Br f* f+ ;
9307: @end example
1.44 crook 9308:
1.78 anton 9309: @cindex flavours of locals
9310: @cindex locals flavours
9311: @cindex value-flavoured locals
9312: @cindex variable-flavoured locals
9313: Gforth currently supports cells (@code{W:}, @code{W^}), doubles
9314: (@code{D:}, @code{D^}), floats (@code{F:}, @code{F^}) and characters
9315: (@code{C:}, @code{C^}) in two flavours: a value-flavoured local (defined
9316: with @code{W:}, @code{D:} etc.) produces its value and can be changed
9317: with @code{TO}. A variable-flavoured local (defined with @code{W^} etc.)
9318: produces its address (which becomes invalid when the variable's scope is
9319: left). E.g., the standard word @code{emit} can be defined in terms of
9320: @code{type} like this:
1.5 anton 9321:
1.78 anton 9322: @example
9323: : emit @{ C^ char* -- @}
9324: char* 1 type ;
9325: @end example
1.5 anton 9326:
1.78 anton 9327: @cindex default type of locals
9328: @cindex locals, default type
9329: A local without type specifier is a @code{W:} local. Both flavours of
9330: locals are initialized with values from the data or FP stack.
1.44 crook 9331:
1.78 anton 9332: Currently there is no way to define locals with user-defined data
9333: structures, but we are working on it.
1.5 anton 9334:
1.78 anton 9335: Gforth allows defining locals everywhere in a colon definition. This
9336: poses the following questions:
1.5 anton 9337:
1.78 anton 9338: @menu
9339: * Where are locals visible by name?::
9340: * How long do locals live?::
9341: * Locals programming style::
9342: * Locals implementation::
9343: @end menu
1.44 crook 9344:
1.78 anton 9345: @node Where are locals visible by name?, How long do locals live?, Gforth locals, Gforth locals
9346: @subsubsection Where are locals visible by name?
9347: @cindex locals visibility
9348: @cindex visibility of locals
9349: @cindex scope of locals
1.5 anton 9350:
1.78 anton 9351: Basically, the answer is that locals are visible where you would expect
9352: it in block-structured languages, and sometimes a little longer. If you
9353: want to restrict the scope of a local, enclose its definition in
9354: @code{SCOPE}...@code{ENDSCOPE}.
1.5 anton 9355:
9356:
1.78 anton 9357: doc-scope
9358: doc-endscope
1.5 anton 9359:
9360:
1.78 anton 9361: These words behave like control structure words, so you can use them
9362: with @code{CS-PICK} and @code{CS-ROLL} to restrict the scope in
9363: arbitrary ways.
1.77 anton 9364:
1.78 anton 9365: If you want a more exact answer to the visibility question, here's the
9366: basic principle: A local is visible in all places that can only be
9367: reached through the definition of the local@footnote{In compiler
9368: construction terminology, all places dominated by the definition of the
9369: local.}. In other words, it is not visible in places that can be reached
9370: without going through the definition of the local. E.g., locals defined
9371: in @code{IF}...@code{ENDIF} are visible until the @code{ENDIF}, locals
9372: defined in @code{BEGIN}...@code{UNTIL} are visible after the
9373: @code{UNTIL} (until, e.g., a subsequent @code{ENDSCOPE}).
1.77 anton 9374:
1.78 anton 9375: The reasoning behind this solution is: We want to have the locals
9376: visible as long as it is meaningful. The user can always make the
9377: visibility shorter by using explicit scoping. In a place that can
9378: only be reached through the definition of a local, the meaning of a
9379: local name is clear. In other places it is not: How is the local
9380: initialized at the control flow path that does not contain the
9381: definition? Which local is meant, if the same name is defined twice in
9382: two independent control flow paths?
1.77 anton 9383:
1.78 anton 9384: This should be enough detail for nearly all users, so you can skip the
9385: rest of this section. If you really must know all the gory details and
9386: options, read on.
1.77 anton 9387:
1.78 anton 9388: In order to implement this rule, the compiler has to know which places
9389: are unreachable. It knows this automatically after @code{AHEAD},
9390: @code{AGAIN}, @code{EXIT} and @code{LEAVE}; in other cases (e.g., after
9391: most @code{THROW}s), you can use the word @code{UNREACHABLE} to tell the
9392: compiler that the control flow never reaches that place. If
9393: @code{UNREACHABLE} is not used where it could, the only consequence is
9394: that the visibility of some locals is more limited than the rule above
9395: says. If @code{UNREACHABLE} is used where it should not (i.e., if you
9396: lie to the compiler), buggy code will be produced.
1.77 anton 9397:
1.5 anton 9398:
1.78 anton 9399: doc-unreachable
1.5 anton 9400:
1.23 crook 9401:
1.78 anton 9402: Another problem with this rule is that at @code{BEGIN}, the compiler
9403: does not know which locals will be visible on the incoming
9404: back-edge. All problems discussed in the following are due to this
9405: ignorance of the compiler (we discuss the problems using @code{BEGIN}
9406: loops as examples; the discussion also applies to @code{?DO} and other
9407: loops). Perhaps the most insidious example is:
1.26 crook 9408: @example
1.78 anton 9409: AHEAD
9410: BEGIN
9411: x
9412: [ 1 CS-ROLL ] THEN
9413: @{ x @}
9414: ...
9415: UNTIL
1.26 crook 9416: @end example
1.23 crook 9417:
1.78 anton 9418: This should be legal according to the visibility rule. The use of
9419: @code{x} can only be reached through the definition; but that appears
9420: textually below the use.
9421:
9422: From this example it is clear that the visibility rules cannot be fully
9423: implemented without major headaches. Our implementation treats common
9424: cases as advertised and the exceptions are treated in a safe way: The
9425: compiler makes a reasonable guess about the locals visible after a
9426: @code{BEGIN}; if it is too pessimistic, the
9427: user will get a spurious error about the local not being defined; if the
9428: compiler is too optimistic, it will notice this later and issue a
9429: warning. In the case above the compiler would complain about @code{x}
9430: being undefined at its use. You can see from the obscure examples in
9431: this section that it takes quite unusual control structures to get the
9432: compiler into trouble, and even then it will often do fine.
1.23 crook 9433:
1.78 anton 9434: If the @code{BEGIN} is reachable from above, the most optimistic guess
9435: is that all locals visible before the @code{BEGIN} will also be
9436: visible after the @code{BEGIN}. This guess is valid for all loops that
9437: are entered only through the @code{BEGIN}, in particular, for normal
9438: @code{BEGIN}...@code{WHILE}...@code{REPEAT} and
9439: @code{BEGIN}...@code{UNTIL} loops and it is implemented in our
9440: compiler. When the branch to the @code{BEGIN} is finally generated by
9441: @code{AGAIN} or @code{UNTIL}, the compiler checks the guess and
9442: warns the user if it was too optimistic:
1.26 crook 9443: @example
1.78 anton 9444: IF
9445: @{ x @}
9446: BEGIN
9447: \ x ?
9448: [ 1 cs-roll ] THEN
9449: ...
9450: UNTIL
1.26 crook 9451: @end example
1.23 crook 9452:
1.78 anton 9453: Here, @code{x} lives only until the @code{BEGIN}, but the compiler
9454: optimistically assumes that it lives until the @code{THEN}. It notices
9455: this difference when it compiles the @code{UNTIL} and issues a
9456: warning. The user can avoid the warning, and make sure that @code{x}
9457: is not used in the wrong area by using explicit scoping:
9458: @example
9459: IF
9460: SCOPE
9461: @{ x @}
9462: ENDSCOPE
9463: BEGIN
9464: [ 1 cs-roll ] THEN
9465: ...
9466: UNTIL
9467: @end example
1.23 crook 9468:
1.78 anton 9469: Since the guess is optimistic, there will be no spurious error messages
9470: about undefined locals.
1.44 crook 9471:
1.78 anton 9472: If the @code{BEGIN} is not reachable from above (e.g., after
9473: @code{AHEAD} or @code{EXIT}), the compiler cannot even make an
9474: optimistic guess, as the locals visible after the @code{BEGIN} may be
9475: defined later. Therefore, the compiler assumes that no locals are
9476: visible after the @code{BEGIN}. However, the user can use
9477: @code{ASSUME-LIVE} to make the compiler assume that the same locals are
9478: visible at the BEGIN as at the point where the top control-flow stack
9479: item was created.
1.23 crook 9480:
1.44 crook 9481:
1.78 anton 9482: doc-assume-live
1.26 crook 9483:
1.23 crook 9484:
1.78 anton 9485: @noindent
9486: E.g.,
9487: @example
9488: @{ x @}
9489: AHEAD
9490: ASSUME-LIVE
9491: BEGIN
9492: x
9493: [ 1 CS-ROLL ] THEN
9494: ...
9495: UNTIL
9496: @end example
1.44 crook 9497:
1.78 anton 9498: Other cases where the locals are defined before the @code{BEGIN} can be
9499: handled by inserting an appropriate @code{CS-ROLL} before the
9500: @code{ASSUME-LIVE} (and changing the control-flow stack manipulation
9501: behind the @code{ASSUME-LIVE}).
1.23 crook 9502:
1.78 anton 9503: Cases where locals are defined after the @code{BEGIN} (but should be
9504: visible immediately after the @code{BEGIN}) can only be handled by
9505: rearranging the loop. E.g., the ``most insidious'' example above can be
9506: arranged into:
9507: @example
9508: BEGIN
9509: @{ x @}
9510: ... 0=
9511: WHILE
9512: x
9513: REPEAT
9514: @end example
1.44 crook 9515:
1.78 anton 9516: @node How long do locals live?, Locals programming style, Where are locals visible by name?, Gforth locals
9517: @subsubsection How long do locals live?
9518: @cindex locals lifetime
9519: @cindex lifetime of locals
1.23 crook 9520:
1.78 anton 9521: The right answer for the lifetime question would be: A local lives at
9522: least as long as it can be accessed. For a value-flavoured local this
9523: means: until the end of its visibility. However, a variable-flavoured
9524: local could be accessed through its address far beyond its visibility
9525: scope. Ultimately, this would mean that such locals would have to be
9526: garbage collected. Since this entails un-Forth-like implementation
9527: complexities, I adopted the same cowardly solution as some other
9528: languages (e.g., C): The local lives only as long as it is visible;
9529: afterwards its address is invalid (and programs that access it
9530: afterwards are erroneous).
1.23 crook 9531:
1.78 anton 9532: @node Locals programming style, Locals implementation, How long do locals live?, Gforth locals
9533: @subsubsection Locals programming style
9534: @cindex locals programming style
9535: @cindex programming style, locals
1.23 crook 9536:
1.78 anton 9537: The freedom to define locals anywhere has the potential to change
9538: programming styles dramatically. In particular, the need to use the
9539: return stack for intermediate storage vanishes. Moreover, all stack
9540: manipulations (except @code{PICK}s and @code{ROLL}s with run-time
9541: determined arguments) can be eliminated: If the stack items are in the
9542: wrong order, just write a locals definition for all of them; then
9543: write the items in the order you want.
1.23 crook 9544:
1.78 anton 9545: This seems a little far-fetched and eliminating stack manipulations is
9546: unlikely to become a conscious programming objective. Still, the number
9547: of stack manipulations will be reduced dramatically if local variables
9548: are used liberally (e.g., compare @code{max} (@pxref{Gforth locals}) with
9549: a traditional implementation of @code{max}).
1.23 crook 9550:
1.78 anton 9551: This shows one potential benefit of locals: making Forth programs more
9552: readable. Of course, this benefit will only be realized if the
9553: programmers continue to honour the principle of factoring instead of
9554: using the added latitude to make the words longer.
1.23 crook 9555:
1.78 anton 9556: @cindex single-assignment style for locals
9557: Using @code{TO} can and should be avoided. Without @code{TO},
9558: every value-flavoured local has only a single assignment and many
9559: advantages of functional languages apply to Forth. I.e., programs are
9560: easier to analyse, to optimize and to read: It is clear from the
9561: definition what the local stands for, it does not turn into something
9562: different later.
1.23 crook 9563:
1.78 anton 9564: E.g., a definition using @code{TO} might look like this:
9565: @example
9566: : strcmp @{ addr1 u1 addr2 u2 -- n @}
9567: u1 u2 min 0
9568: ?do
9569: addr1 c@@ addr2 c@@ -
9570: ?dup-if
9571: unloop exit
9572: then
9573: addr1 char+ TO addr1
9574: addr2 char+ TO addr2
9575: loop
9576: u1 u2 - ;
1.26 crook 9577: @end example
1.78 anton 9578: Here, @code{TO} is used to update @code{addr1} and @code{addr2} at
9579: every loop iteration. @code{strcmp} is a typical example of the
9580: readability problems of using @code{TO}. When you start reading
9581: @code{strcmp}, you think that @code{addr1} refers to the start of the
9582: string. Only near the end of the loop you realize that it is something
9583: else.
1.23 crook 9584:
1.78 anton 9585: This can be avoided by defining two locals at the start of the loop that
9586: are initialized with the right value for the current iteration.
9587: @example
9588: : strcmp @{ addr1 u1 addr2 u2 -- n @}
9589: addr1 addr2
9590: u1 u2 min 0
9591: ?do @{ s1 s2 @}
9592: s1 c@@ s2 c@@ -
9593: ?dup-if
9594: unloop exit
9595: then
9596: s1 char+ s2 char+
9597: loop
9598: 2drop
9599: u1 u2 - ;
9600: @end example
9601: Here it is clear from the start that @code{s1} has a different value
9602: in every loop iteration.
1.23 crook 9603:
1.78 anton 9604: @node Locals implementation, , Locals programming style, Gforth locals
9605: @subsubsection Locals implementation
9606: @cindex locals implementation
9607: @cindex implementation of locals
1.23 crook 9608:
1.78 anton 9609: @cindex locals stack
9610: Gforth uses an extra locals stack. The most compelling reason for
9611: this is that the return stack is not float-aligned; using an extra stack
9612: also eliminates the problems and restrictions of using the return stack
9613: as locals stack. Like the other stacks, the locals stack grows toward
9614: lower addresses. A few primitives allow an efficient implementation:
9615:
9616:
9617: doc-@local#
9618: doc-f@local#
9619: doc-laddr#
9620: doc-lp+!#
9621: doc-lp!
9622: doc->l
9623: doc-f>l
9624:
9625:
9626: In addition to these primitives, some specializations of these
9627: primitives for commonly occurring inline arguments are provided for
9628: efficiency reasons, e.g., @code{@@local0} as specialization of
9629: @code{@@local#} for the inline argument 0. The following compiling words
9630: compile the right specialized version, or the general version, as
9631: appropriate:
1.23 crook 9632:
1.5 anton 9633:
1.107 dvdkhlng 9634: @c doc-compile-@local
9635: @c doc-compile-f@local
1.78 anton 9636: doc-compile-lp+!
1.5 anton 9637:
9638:
1.78 anton 9639: Combinations of conditional branches and @code{lp+!#} like
9640: @code{?branch-lp+!#} (the locals pointer is only changed if the branch
9641: is taken) are provided for efficiency and correctness in loops.
1.5 anton 9642:
1.78 anton 9643: A special area in the dictionary space is reserved for keeping the
9644: local variable names. @code{@{} switches the dictionary pointer to this
9645: area and @code{@}} switches it back and generates the locals
9646: initializing code. @code{W:} etc.@ are normal defining words. This
9647: special area is cleared at the start of every colon definition.
1.5 anton 9648:
1.78 anton 9649: @cindex word list for defining locals
9650: A special feature of Gforth's dictionary is used to implement the
9651: definition of locals without type specifiers: every word list (aka
9652: vocabulary) has its own methods for searching
9653: etc. (@pxref{Word Lists}). For the present purpose we defined a word list
9654: with a special search method: When it is searched for a word, it
9655: actually creates that word using @code{W:}. @code{@{} changes the search
9656: order to first search the word list containing @code{@}}, @code{W:} etc.,
9657: and then the word list for defining locals without type specifiers.
1.5 anton 9658:
1.78 anton 9659: The lifetime rules support a stack discipline within a colon
9660: definition: The lifetime of a local is either nested with other locals
9661: lifetimes or it does not overlap them.
1.23 crook 9662:
1.78 anton 9663: At @code{BEGIN}, @code{IF}, and @code{AHEAD} no code for locals stack
9664: pointer manipulation is generated. Between control structure words
9665: locals definitions can push locals onto the locals stack. @code{AGAIN}
9666: is the simplest of the other three control flow words. It has to
9667: restore the locals stack depth of the corresponding @code{BEGIN}
9668: before branching. The code looks like this:
9669: @format
9670: @code{lp+!#} current-locals-size @minus{} dest-locals-size
9671: @code{branch} <begin>
9672: @end format
1.26 crook 9673:
1.78 anton 9674: @code{UNTIL} is a little more complicated: If it branches back, it
9675: must adjust the stack just like @code{AGAIN}. But if it falls through,
9676: the locals stack must not be changed. The compiler generates the
9677: following code:
9678: @format
9679: @code{?branch-lp+!#} <begin> current-locals-size @minus{} dest-locals-size
9680: @end format
9681: The locals stack pointer is only adjusted if the branch is taken.
1.44 crook 9682:
1.78 anton 9683: @code{THEN} can produce somewhat inefficient code:
9684: @format
9685: @code{lp+!#} current-locals-size @minus{} orig-locals-size
9686: <orig target>:
9687: @code{lp+!#} orig-locals-size @minus{} new-locals-size
9688: @end format
9689: The second @code{lp+!#} adjusts the locals stack pointer from the
9690: level at the @i{orig} point to the level after the @code{THEN}. The
9691: first @code{lp+!#} adjusts the locals stack pointer from the current
9692: level to the level at the orig point, so the complete effect is an
9693: adjustment from the current level to the right level after the
9694: @code{THEN}.
1.26 crook 9695:
1.78 anton 9696: @cindex locals information on the control-flow stack
9697: @cindex control-flow stack items, locals information
9698: In a conventional Forth implementation a dest control-flow stack entry
9699: is just the target address and an orig entry is just the address to be
9700: patched. Our locals implementation adds a word list to every orig or dest
9701: item. It is the list of locals visible (or assumed visible) at the point
9702: described by the entry. Our implementation also adds a tag to identify
9703: the kind of entry, in particular to differentiate between live and dead
9704: (reachable and unreachable) orig entries.
1.26 crook 9705:
1.78 anton 9706: A few unusual operations have to be performed on locals word lists:
1.44 crook 9707:
1.5 anton 9708:
1.78 anton 9709: doc-common-list
9710: doc-sub-list?
9711: doc-list-size
1.52 anton 9712:
9713:
1.78 anton 9714: Several features of our locals word list implementation make these
9715: operations easy to implement: The locals word lists are organised as
9716: linked lists; the tails of these lists are shared, if the lists
9717: contain some of the same locals; and the address of a name is greater
9718: than the address of the names behind it in the list.
1.5 anton 9719:
1.78 anton 9720: Another important implementation detail is the variable
9721: @code{dead-code}. It is used by @code{BEGIN} and @code{THEN} to
9722: determine if they can be reached directly or only through the branch
9723: that they resolve. @code{dead-code} is set by @code{UNREACHABLE},
9724: @code{AHEAD}, @code{EXIT} etc., and cleared at the start of a colon
9725: definition, by @code{BEGIN} and usually by @code{THEN}.
1.5 anton 9726:
1.78 anton 9727: Counted loops are similar to other loops in most respects, but
9728: @code{LEAVE} requires special attention: It performs basically the same
9729: service as @code{AHEAD}, but it does not create a control-flow stack
9730: entry. Therefore the information has to be stored elsewhere;
9731: traditionally, the information was stored in the target fields of the
9732: branches created by the @code{LEAVE}s, by organizing these fields into a
9733: linked list. Unfortunately, this clever trick does not provide enough
9734: space for storing our extended control flow information. Therefore, we
9735: introduce another stack, the leave stack. It contains the control-flow
9736: stack entries for all unresolved @code{LEAVE}s.
1.44 crook 9737:
1.78 anton 9738: Local names are kept until the end of the colon definition, even if
9739: they are no longer visible in any control-flow path. In a few cases
9740: this may lead to increased space needs for the locals name area, but
9741: usually less than reclaiming this space would cost in code size.
1.5 anton 9742:
1.44 crook 9743:
1.78 anton 9744: @node ANS Forth locals, , Gforth locals, Locals
9745: @subsection ANS Forth locals
9746: @cindex locals, ANS Forth style
1.5 anton 9747:
1.78 anton 9748: The ANS Forth locals wordset does not define a syntax for locals, but
9749: words that make it possible to define various syntaxes. One of the
9750: possible syntaxes is a subset of the syntax we used in the Gforth locals
9751: wordset, i.e.:
1.29 crook 9752:
9753: @example
1.78 anton 9754: @{ local1 local2 ... -- comment @}
9755: @end example
9756: @noindent
9757: or
9758: @example
9759: @{ local1 local2 ... @}
1.29 crook 9760: @end example
9761:
1.78 anton 9762: The order of the locals corresponds to the order in a stack comment. The
9763: restrictions are:
1.5 anton 9764:
1.78 anton 9765: @itemize @bullet
9766: @item
9767: Locals can only be cell-sized values (no type specifiers are allowed).
9768: @item
9769: Locals can be defined only outside control structures.
9770: @item
9771: Locals can interfere with explicit usage of the return stack. For the
9772: exact (and long) rules, see the standard. If you don't use return stack
9773: accessing words in a definition using locals, you will be all right. The
9774: purpose of this rule is to make locals implementation on the return
9775: stack easier.
9776: @item
9777: The whole definition must be in one line.
9778: @end itemize
1.5 anton 9779:
1.78 anton 9780: Locals defined in ANS Forth behave like @code{VALUE}s
9781: (@pxref{Values}). I.e., they are initialized from the stack. Using their
9782: name produces their value. Their value can be changed using @code{TO}.
1.77 anton 9783:
1.78 anton 9784: Since the syntax above is supported by Gforth directly, you need not do
9785: anything to use it. If you want to port a program using this syntax to
9786: another ANS Forth system, use @file{compat/anslocal.fs} to implement the
9787: syntax on the other system.
1.5 anton 9788:
1.78 anton 9789: Note that a syntax shown in the standard, section A.13 looks
9790: similar, but is quite different in having the order of locals
9791: reversed. Beware!
1.5 anton 9792:
1.78 anton 9793: The ANS Forth locals wordset itself consists of one word:
1.5 anton 9794:
1.78 anton 9795: doc-(local)
1.5 anton 9796:
1.78 anton 9797: The ANS Forth locals extension wordset defines a syntax using
9798: @code{locals|}, but it is so awful that we strongly recommend not to use
9799: it. We have implemented this syntax to make porting to Gforth easy, but
9800: do not document it here. The problem with this syntax is that the locals
9801: are defined in an order reversed with respect to the standard stack
9802: comment notation, making programs harder to read, and easier to misread
9803: and miswrite. The only merit of this syntax is that it is easy to
9804: implement using the ANS Forth locals wordset.
1.53 anton 9805:
9806:
1.78 anton 9807: @c ----------------------------------------------------------
9808: @node Structures, Object-oriented Forth, Locals, Words
9809: @section Structures
9810: @cindex structures
9811: @cindex records
1.53 anton 9812:
1.78 anton 9813: This section presents the structure package that comes with Gforth. A
9814: version of the package implemented in ANS Forth is available in
9815: @file{compat/struct.fs}. This package was inspired by a posting on
9816: comp.lang.forth in 1989 (unfortunately I don't remember, by whom;
9817: possibly John Hayes). A version of this section has been published in
9818: M. Anton Ertl,
9819: @uref{http://www.complang.tuwien.ac.at/forth/objects/structs.html, Yet
9820: Another Forth Structures Package}, Forth Dimensions 19(3), pages
9821: 13--16. Marcel Hendrix provided helpful comments.
1.53 anton 9822:
1.78 anton 9823: @menu
9824: * Why explicit structure support?::
9825: * Structure Usage::
9826: * Structure Naming Convention::
9827: * Structure Implementation::
9828: * Structure Glossary::
9829: @end menu
1.55 anton 9830:
1.78 anton 9831: @node Why explicit structure support?, Structure Usage, Structures, Structures
9832: @subsection Why explicit structure support?
1.53 anton 9833:
1.78 anton 9834: @cindex address arithmetic for structures
9835: @cindex structures using address arithmetic
9836: If we want to use a structure containing several fields, we could simply
9837: reserve memory for it, and access the fields using address arithmetic
9838: (@pxref{Address arithmetic}). As an example, consider a structure with
9839: the following fields
1.57 anton 9840:
1.78 anton 9841: @table @code
9842: @item a
9843: is a float
9844: @item b
9845: is a cell
9846: @item c
9847: is a float
9848: @end table
1.57 anton 9849:
1.78 anton 9850: Given the (float-aligned) base address of the structure we get the
9851: address of the field
1.52 anton 9852:
1.78 anton 9853: @table @code
9854: @item a
9855: without doing anything further.
9856: @item b
9857: with @code{float+}
9858: @item c
9859: with @code{float+ cell+ faligned}
9860: @end table
1.52 anton 9861:
1.78 anton 9862: It is easy to see that this can become quite tiring.
1.52 anton 9863:
1.78 anton 9864: Moreover, it is not very readable, because seeing a
9865: @code{cell+} tells us neither which kind of structure is
9866: accessed nor what field is accessed; we have to somehow infer the kind
9867: of structure, and then look up in the documentation, which field of
9868: that structure corresponds to that offset.
1.53 anton 9869:
1.78 anton 9870: Finally, this kind of address arithmetic also causes maintenance
9871: troubles: If you add or delete a field somewhere in the middle of the
9872: structure, you have to find and change all computations for the fields
9873: afterwards.
1.52 anton 9874:
1.78 anton 9875: So, instead of using @code{cell+} and friends directly, how
9876: about storing the offsets in constants:
1.52 anton 9877:
1.78 anton 9878: @example
9879: 0 constant a-offset
9880: 0 float+ constant b-offset
9881: 0 float+ cell+ faligned c-offset
9882: @end example
1.64 pazsan 9883:
1.78 anton 9884: Now we can get the address of field @code{x} with @code{x-offset
9885: +}. This is much better in all respects. Of course, you still
9886: have to change all later offset definitions if you add a field. You can
9887: fix this by declaring the offsets in the following way:
1.57 anton 9888:
1.78 anton 9889: @example
9890: 0 constant a-offset
9891: a-offset float+ constant b-offset
9892: b-offset cell+ faligned constant c-offset
9893: @end example
1.57 anton 9894:
1.78 anton 9895: Since we always use the offsets with @code{+}, we could use a defining
9896: word @code{cfield} that includes the @code{+} in the action of the
9897: defined word:
1.64 pazsan 9898:
1.78 anton 9899: @example
9900: : cfield ( n "name" -- )
9901: create ,
9902: does> ( name execution: addr1 -- addr2 )
9903: @@ + ;
1.64 pazsan 9904:
1.78 anton 9905: 0 cfield a
9906: 0 a float+ cfield b
9907: 0 b cell+ faligned cfield c
9908: @end example
1.64 pazsan 9909:
1.78 anton 9910: Instead of @code{x-offset +}, we now simply write @code{x}.
1.64 pazsan 9911:
1.78 anton 9912: The structure field words now can be used quite nicely. However,
9913: their definition is still a bit cumbersome: We have to repeat the
9914: name, the information about size and alignment is distributed before
9915: and after the field definitions etc. The structure package presented
9916: here addresses these problems.
1.64 pazsan 9917:
1.78 anton 9918: @node Structure Usage, Structure Naming Convention, Why explicit structure support?, Structures
9919: @subsection Structure Usage
9920: @cindex structure usage
1.57 anton 9921:
1.78 anton 9922: @cindex @code{field} usage
9923: @cindex @code{struct} usage
9924: @cindex @code{end-struct} usage
9925: You can define a structure for a (data-less) linked list with:
1.57 anton 9926: @example
1.78 anton 9927: struct
9928: cell% field list-next
9929: end-struct list%
1.57 anton 9930: @end example
9931:
1.78 anton 9932: With the address of the list node on the stack, you can compute the
9933: address of the field that contains the address of the next node with
9934: @code{list-next}. E.g., you can determine the length of a list
9935: with:
1.57 anton 9936:
9937: @example
1.78 anton 9938: : list-length ( list -- n )
9939: \ "list" is a pointer to the first element of a linked list
9940: \ "n" is the length of the list
9941: 0 BEGIN ( list1 n1 )
9942: over
9943: WHILE ( list1 n1 )
9944: 1+ swap list-next @@ swap
9945: REPEAT
9946: nip ;
1.57 anton 9947: @end example
9948:
1.78 anton 9949: You can reserve memory for a list node in the dictionary with
9950: @code{list% %allot}, which leaves the address of the list node on the
9951: stack. For the equivalent allocation on the heap you can use @code{list%
9952: %alloc} (or, for an @code{allocate}-like stack effect (i.e., with ior),
9953: use @code{list% %allocate}). You can get the the size of a list
9954: node with @code{list% %size} and its alignment with @code{list%
9955: %alignment}.
9956:
9957: Note that in ANS Forth the body of a @code{create}d word is
9958: @code{aligned} but not necessarily @code{faligned};
9959: therefore, if you do a:
1.57 anton 9960:
9961: @example
1.78 anton 9962: create @emph{name} foo% %allot drop
1.57 anton 9963: @end example
9964:
1.78 anton 9965: @noindent
9966: then the memory alloted for @code{foo%} is guaranteed to start at the
9967: body of @code{@emph{name}} only if @code{foo%} contains only character,
9968: cell and double fields. Therefore, if your structure contains floats,
9969: better use
1.57 anton 9970:
9971: @example
1.78 anton 9972: foo% %allot constant @emph{name}
1.57 anton 9973: @end example
9974:
1.78 anton 9975: @cindex structures containing structures
9976: You can include a structure @code{foo%} as a field of
9977: another structure, like this:
1.65 anton 9978: @example
1.78 anton 9979: struct
9980: ...
9981: foo% field ...
9982: ...
9983: end-struct ...
1.65 anton 9984: @end example
1.52 anton 9985:
1.78 anton 9986: @cindex structure extension
9987: @cindex extended records
9988: Instead of starting with an empty structure, you can extend an
9989: existing structure. E.g., a plain linked list without data, as defined
9990: above, is hardly useful; You can extend it to a linked list of integers,
9991: like this:@footnote{This feature is also known as @emph{extended
9992: records}. It is the main innovation in the Oberon language; in other
9993: words, adding this feature to Modula-2 led Wirth to create a new
9994: language, write a new compiler etc. Adding this feature to Forth just
9995: required a few lines of code.}
1.52 anton 9996:
1.78 anton 9997: @example
9998: list%
9999: cell% field intlist-int
10000: end-struct intlist%
10001: @end example
1.55 anton 10002:
1.78 anton 10003: @code{intlist%} is a structure with two fields:
10004: @code{list-next} and @code{intlist-int}.
1.55 anton 10005:
1.78 anton 10006: @cindex structures containing arrays
10007: You can specify an array type containing @emph{n} elements of
10008: type @code{foo%} like this:
1.55 anton 10009:
10010: @example
1.78 anton 10011: foo% @emph{n} *
1.56 anton 10012: @end example
1.55 anton 10013:
1.78 anton 10014: You can use this array type in any place where you can use a normal
10015: type, e.g., when defining a @code{field}, or with
10016: @code{%allot}.
10017:
10018: @cindex first field optimization
10019: The first field is at the base address of a structure and the word for
10020: this field (e.g., @code{list-next}) actually does not change the address
10021: on the stack. You may be tempted to leave it away in the interest of
10022: run-time and space efficiency. This is not necessary, because the
10023: structure package optimizes this case: If you compile a first-field
10024: words, no code is generated. So, in the interest of readability and
10025: maintainability you should include the word for the field when accessing
10026: the field.
1.52 anton 10027:
10028:
1.78 anton 10029: @node Structure Naming Convention, Structure Implementation, Structure Usage, Structures
10030: @subsection Structure Naming Convention
10031: @cindex structure naming convention
1.52 anton 10032:
1.78 anton 10033: The field names that come to (my) mind are often quite generic, and,
10034: if used, would cause frequent name clashes. E.g., many structures
10035: probably contain a @code{counter} field. The structure names
10036: that come to (my) mind are often also the logical choice for the names
10037: of words that create such a structure.
1.52 anton 10038:
1.78 anton 10039: Therefore, I have adopted the following naming conventions:
1.52 anton 10040:
1.78 anton 10041: @itemize @bullet
10042: @cindex field naming convention
10043: @item
10044: The names of fields are of the form
10045: @code{@emph{struct}-@emph{field}}, where
10046: @code{@emph{struct}} is the basic name of the structure, and
10047: @code{@emph{field}} is the basic name of the field. You can
10048: think of field words as converting the (address of the)
10049: structure into the (address of the) field.
1.52 anton 10050:
1.78 anton 10051: @cindex structure naming convention
10052: @item
10053: The names of structures are of the form
10054: @code{@emph{struct}%}, where
10055: @code{@emph{struct}} is the basic name of the structure.
10056: @end itemize
1.52 anton 10057:
1.78 anton 10058: This naming convention does not work that well for fields of extended
10059: structures; e.g., the integer list structure has a field
10060: @code{intlist-int}, but has @code{list-next}, not
10061: @code{intlist-next}.
1.53 anton 10062:
1.78 anton 10063: @node Structure Implementation, Structure Glossary, Structure Naming Convention, Structures
10064: @subsection Structure Implementation
10065: @cindex structure implementation
10066: @cindex implementation of structures
1.52 anton 10067:
1.78 anton 10068: The central idea in the implementation is to pass the data about the
10069: structure being built on the stack, not in some global
10070: variable. Everything else falls into place naturally once this design
10071: decision is made.
1.53 anton 10072:
1.78 anton 10073: The type description on the stack is of the form @emph{align
10074: size}. Keeping the size on the top-of-stack makes dealing with arrays
10075: very simple.
1.53 anton 10076:
1.78 anton 10077: @code{field} is a defining word that uses @code{Create}
10078: and @code{DOES>}. The body of the field contains the offset
10079: of the field, and the normal @code{DOES>} action is simply:
1.53 anton 10080:
10081: @example
1.78 anton 10082: @@ +
1.53 anton 10083: @end example
10084:
1.78 anton 10085: @noindent
10086: i.e., add the offset to the address, giving the stack effect
10087: @i{addr1 -- addr2} for a field.
10088:
10089: @cindex first field optimization, implementation
10090: This simple structure is slightly complicated by the optimization
10091: for fields with offset 0, which requires a different
10092: @code{DOES>}-part (because we cannot rely on there being
10093: something on the stack if such a field is invoked during
10094: compilation). Therefore, we put the different @code{DOES>}-parts
10095: in separate words, and decide which one to invoke based on the
10096: offset. For a zero offset, the field is basically a noop; it is
10097: immediate, and therefore no code is generated when it is compiled.
1.53 anton 10098:
1.78 anton 10099: @node Structure Glossary, , Structure Implementation, Structures
10100: @subsection Structure Glossary
10101: @cindex structure glossary
1.53 anton 10102:
1.5 anton 10103:
1.78 anton 10104: doc-%align
10105: doc-%alignment
10106: doc-%alloc
10107: doc-%allocate
10108: doc-%allot
10109: doc-cell%
10110: doc-char%
10111: doc-dfloat%
10112: doc-double%
10113: doc-end-struct
10114: doc-field
10115: doc-float%
10116: doc-naligned
10117: doc-sfloat%
10118: doc-%size
10119: doc-struct
1.54 anton 10120:
10121:
1.26 crook 10122: @c -------------------------------------------------------------
1.78 anton 10123: @node Object-oriented Forth, Programming Tools, Structures, Words
10124: @section Object-oriented Forth
10125:
10126: Gforth comes with three packages for object-oriented programming:
10127: @file{objects.fs}, @file{oof.fs}, and @file{mini-oof.fs}; none of them
10128: is preloaded, so you have to @code{include} them before use. The most
10129: important differences between these packages (and others) are discussed
10130: in @ref{Comparison with other object models}. All packages are written
10131: in ANS Forth and can be used with any other ANS Forth.
1.5 anton 10132:
1.78 anton 10133: @menu
10134: * Why object-oriented programming?::
10135: * Object-Oriented Terminology::
10136: * Objects::
10137: * OOF::
10138: * Mini-OOF::
10139: * Comparison with other object models::
10140: @end menu
1.5 anton 10141:
1.78 anton 10142: @c ----------------------------------------------------------------
10143: @node Why object-oriented programming?, Object-Oriented Terminology, Object-oriented Forth, Object-oriented Forth
10144: @subsection Why object-oriented programming?
10145: @cindex object-oriented programming motivation
10146: @cindex motivation for object-oriented programming
1.44 crook 10147:
1.78 anton 10148: Often we have to deal with several data structures (@emph{objects}),
10149: that have to be treated similarly in some respects, but differently in
10150: others. Graphical objects are the textbook example: circles, triangles,
10151: dinosaurs, icons, and others, and we may want to add more during program
10152: development. We want to apply some operations to any graphical object,
10153: e.g., @code{draw} for displaying it on the screen. However, @code{draw}
10154: has to do something different for every kind of object.
10155: @comment TODO add some other operations eg perimeter, area
10156: @comment and tie in to concrete examples later..
1.5 anton 10157:
1.78 anton 10158: We could implement @code{draw} as a big @code{CASE}
10159: control structure that executes the appropriate code depending on the
10160: kind of object to be drawn. This would be not be very elegant, and,
10161: moreover, we would have to change @code{draw} every time we add
10162: a new kind of graphical object (say, a spaceship).
1.44 crook 10163:
1.78 anton 10164: What we would rather do is: When defining spaceships, we would tell
10165: the system: ``Here's how you @code{draw} a spaceship; you figure
10166: out the rest''.
1.5 anton 10167:
1.78 anton 10168: This is the problem that all systems solve that (rightfully) call
10169: themselves object-oriented; the object-oriented packages presented here
10170: solve this problem (and not much else).
10171: @comment TODO ?list properties of oo systems.. oo vs o-based?
1.44 crook 10172:
1.78 anton 10173: @c ------------------------------------------------------------------------
10174: @node Object-Oriented Terminology, Objects, Why object-oriented programming?, Object-oriented Forth
10175: @subsection Object-Oriented Terminology
10176: @cindex object-oriented terminology
10177: @cindex terminology for object-oriented programming
1.5 anton 10178:
1.78 anton 10179: This section is mainly for reference, so you don't have to understand
10180: all of it right away. The terminology is mainly Smalltalk-inspired. In
10181: short:
1.44 crook 10182:
1.78 anton 10183: @table @emph
10184: @cindex class
10185: @item class
10186: a data structure definition with some extras.
1.5 anton 10187:
1.78 anton 10188: @cindex object
10189: @item object
10190: an instance of the data structure described by the class definition.
1.5 anton 10191:
1.78 anton 10192: @cindex instance variables
10193: @item instance variables
10194: fields of the data structure.
1.5 anton 10195:
1.78 anton 10196: @cindex selector
10197: @cindex method selector
10198: @cindex virtual function
10199: @item selector
10200: (or @emph{method selector}) a word (e.g.,
10201: @code{draw}) that performs an operation on a variety of data
10202: structures (classes). A selector describes @emph{what} operation to
10203: perform. In C++ terminology: a (pure) virtual function.
1.5 anton 10204:
1.78 anton 10205: @cindex method
10206: @item method
10207: the concrete definition that performs the operation
10208: described by the selector for a specific class. A method specifies
10209: @emph{how} the operation is performed for a specific class.
1.5 anton 10210:
1.78 anton 10211: @cindex selector invocation
10212: @cindex message send
10213: @cindex invoking a selector
10214: @item selector invocation
10215: a call of a selector. One argument of the call (the TOS (top-of-stack))
10216: is used for determining which method is used. In Smalltalk terminology:
10217: a message (consisting of the selector and the other arguments) is sent
10218: to the object.
1.5 anton 10219:
1.78 anton 10220: @cindex receiving object
10221: @item receiving object
10222: the object used for determining the method executed by a selector
10223: invocation. In the @file{objects.fs} model, it is the object that is on
10224: the TOS when the selector is invoked. (@emph{Receiving} comes from
10225: the Smalltalk @emph{message} terminology.)
1.5 anton 10226:
1.78 anton 10227: @cindex child class
10228: @cindex parent class
10229: @cindex inheritance
10230: @item child class
10231: a class that has (@emph{inherits}) all properties (instance variables,
10232: selectors, methods) from a @emph{parent class}. In Smalltalk
10233: terminology: The subclass inherits from the superclass. In C++
10234: terminology: The derived class inherits from the base class.
1.5 anton 10235:
1.78 anton 10236: @end table
1.5 anton 10237:
1.78 anton 10238: @c If you wonder about the message sending terminology, it comes from
10239: @c a time when each object had it's own task and objects communicated via
10240: @c message passing; eventually the Smalltalk developers realized that
10241: @c they can do most things through simple (indirect) calls. They kept the
10242: @c terminology.
1.5 anton 10243:
1.78 anton 10244: @c --------------------------------------------------------------
10245: @node Objects, OOF, Object-Oriented Terminology, Object-oriented Forth
10246: @subsection The @file{objects.fs} model
10247: @cindex objects
10248: @cindex object-oriented programming
1.26 crook 10249:
1.78 anton 10250: @cindex @file{objects.fs}
10251: @cindex @file{oof.fs}
1.26 crook 10252:
1.78 anton 10253: This section describes the @file{objects.fs} package. This material also
10254: has been published in M. Anton Ertl,
10255: @cite{@uref{http://www.complang.tuwien.ac.at/forth/objects/objects.html,
10256: Yet Another Forth Objects Package}}, Forth Dimensions 19(2), pages
10257: 37--43.
10258: @c McKewan's and Zsoter's packages
1.26 crook 10259:
1.78 anton 10260: This section assumes that you have read @ref{Structures}.
1.5 anton 10261:
1.78 anton 10262: The techniques on which this model is based have been used to implement
10263: the parser generator, Gray, and have also been used in Gforth for
10264: implementing the various flavours of word lists (hashed or not,
10265: case-sensitive or not, special-purpose word lists for locals etc.).
1.5 anton 10266:
10267:
1.26 crook 10268: @menu
1.78 anton 10269: * Properties of the Objects model::
10270: * Basic Objects Usage::
10271: * The Objects base class::
10272: * Creating objects::
10273: * Object-Oriented Programming Style::
10274: * Class Binding::
10275: * Method conveniences::
10276: * Classes and Scoping::
10277: * Dividing classes::
10278: * Object Interfaces::
10279: * Objects Implementation::
10280: * Objects Glossary::
1.26 crook 10281: @end menu
1.5 anton 10282:
1.78 anton 10283: Marcel Hendrix provided helpful comments on this section.
1.5 anton 10284:
1.78 anton 10285: @node Properties of the Objects model, Basic Objects Usage, Objects, Objects
10286: @subsubsection Properties of the @file{objects.fs} model
10287: @cindex @file{objects.fs} properties
1.5 anton 10288:
1.78 anton 10289: @itemize @bullet
10290: @item
10291: It is straightforward to pass objects on the stack. Passing
10292: selectors on the stack is a little less convenient, but possible.
1.44 crook 10293:
1.78 anton 10294: @item
10295: Objects are just data structures in memory, and are referenced by their
10296: address. You can create words for objects with normal defining words
10297: like @code{constant}. Likewise, there is no difference between instance
10298: variables that contain objects and those that contain other data.
1.5 anton 10299:
1.78 anton 10300: @item
10301: Late binding is efficient and easy to use.
1.44 crook 10302:
1.78 anton 10303: @item
10304: It avoids parsing, and thus avoids problems with state-smartness
10305: and reduced extensibility; for convenience there are a few parsing
10306: words, but they have non-parsing counterparts. There are also a few
10307: defining words that parse. This is hard to avoid, because all standard
10308: defining words parse (except @code{:noname}); however, such
10309: words are not as bad as many other parsing words, because they are not
10310: state-smart.
1.5 anton 10311:
1.78 anton 10312: @item
10313: It does not try to incorporate everything. It does a few things and does
10314: them well (IMO). In particular, this model was not designed to support
10315: information hiding (although it has features that may help); you can use
10316: a separate package for achieving this.
1.5 anton 10317:
1.78 anton 10318: @item
10319: It is layered; you don't have to learn and use all features to use this
10320: model. Only a few features are necessary (@pxref{Basic Objects Usage},
10321: @pxref{The Objects base class}, @pxref{Creating objects}.), the others
10322: are optional and independent of each other.
1.5 anton 10323:
1.78 anton 10324: @item
10325: An implementation in ANS Forth is available.
1.5 anton 10326:
1.78 anton 10327: @end itemize
1.5 anton 10328:
1.44 crook 10329:
1.78 anton 10330: @node Basic Objects Usage, The Objects base class, Properties of the Objects model, Objects
10331: @subsubsection Basic @file{objects.fs} Usage
10332: @cindex basic objects usage
10333: @cindex objects, basic usage
1.5 anton 10334:
1.78 anton 10335: You can define a class for graphical objects like this:
1.44 crook 10336:
1.78 anton 10337: @cindex @code{class} usage
10338: @cindex @code{end-class} usage
10339: @cindex @code{selector} usage
1.5 anton 10340: @example
1.78 anton 10341: object class \ "object" is the parent class
10342: selector draw ( x y graphical -- )
10343: end-class graphical
10344: @end example
10345:
10346: This code defines a class @code{graphical} with an
10347: operation @code{draw}. We can perform the operation
10348: @code{draw} on any @code{graphical} object, e.g.:
10349:
10350: @example
10351: 100 100 t-rex draw
1.26 crook 10352: @end example
1.5 anton 10353:
1.78 anton 10354: @noindent
10355: where @code{t-rex} is a word (say, a constant) that produces a
10356: graphical object.
10357:
10358: @comment TODO add a 2nd operation eg perimeter.. and use for
10359: @comment a concrete example
1.5 anton 10360:
1.78 anton 10361: @cindex abstract class
10362: How do we create a graphical object? With the present definitions,
10363: we cannot create a useful graphical object. The class
10364: @code{graphical} describes graphical objects in general, but not
10365: any concrete graphical object type (C++ users would call it an
10366: @emph{abstract class}); e.g., there is no method for the selector
10367: @code{draw} in the class @code{graphical}.
1.5 anton 10368:
1.78 anton 10369: For concrete graphical objects, we define child classes of the
10370: class @code{graphical}, e.g.:
1.5 anton 10371:
1.78 anton 10372: @cindex @code{overrides} usage
10373: @cindex @code{field} usage in class definition
1.26 crook 10374: @example
1.78 anton 10375: graphical class \ "graphical" is the parent class
10376: cell% field circle-radius
1.5 anton 10377:
1.78 anton 10378: :noname ( x y circle -- )
10379: circle-radius @@ draw-circle ;
10380: overrides draw
1.5 anton 10381:
1.78 anton 10382: :noname ( n-radius circle -- )
10383: circle-radius ! ;
10384: overrides construct
1.5 anton 10385:
1.78 anton 10386: end-class circle
10387: @end example
1.44 crook 10388:
1.78 anton 10389: Here we define a class @code{circle} as a child of @code{graphical},
10390: with field @code{circle-radius} (which behaves just like a field
10391: (@pxref{Structures}); it defines (using @code{overrides}) new methods
10392: for the selectors @code{draw} and @code{construct} (@code{construct} is
10393: defined in @code{object}, the parent class of @code{graphical}).
1.5 anton 10394:
1.78 anton 10395: Now we can create a circle on the heap (i.e.,
10396: @code{allocate}d memory) with:
1.44 crook 10397:
1.78 anton 10398: @cindex @code{heap-new} usage
1.5 anton 10399: @example
1.78 anton 10400: 50 circle heap-new constant my-circle
1.5 anton 10401: @end example
10402:
1.78 anton 10403: @noindent
10404: @code{heap-new} invokes @code{construct}, thus
10405: initializing the field @code{circle-radius} with 50. We can draw
10406: this new circle at (100,100) with:
1.5 anton 10407:
10408: @example
1.78 anton 10409: 100 100 my-circle draw
1.5 anton 10410: @end example
10411:
1.78 anton 10412: @cindex selector invocation, restrictions
10413: @cindex class definition, restrictions
10414: Note: You can only invoke a selector if the object on the TOS
10415: (the receiving object) belongs to the class where the selector was
10416: defined or one of its descendents; e.g., you can invoke
10417: @code{draw} only for objects belonging to @code{graphical}
10418: or its descendents (e.g., @code{circle}). Immediately before
10419: @code{end-class}, the search order has to be the same as
10420: immediately after @code{class}.
10421:
10422: @node The Objects base class, Creating objects, Basic Objects Usage, Objects
10423: @subsubsection The @file{object.fs} base class
10424: @cindex @code{object} class
10425:
10426: When you define a class, you have to specify a parent class. So how do
10427: you start defining classes? There is one class available from the start:
10428: @code{object}. It is ancestor for all classes and so is the
10429: only class that has no parent. It has two selectors: @code{construct}
10430: and @code{print}.
10431:
10432: @node Creating objects, Object-Oriented Programming Style, The Objects base class, Objects
10433: @subsubsection Creating objects
10434: @cindex creating objects
10435: @cindex object creation
10436: @cindex object allocation options
10437:
10438: @cindex @code{heap-new} discussion
10439: @cindex @code{dict-new} discussion
10440: @cindex @code{construct} discussion
10441: You can create and initialize an object of a class on the heap with
10442: @code{heap-new} ( ... class -- object ) and in the dictionary
10443: (allocation with @code{allot}) with @code{dict-new} (
10444: ... class -- object ). Both words invoke @code{construct}, which
10445: consumes the stack items indicated by "..." above.
10446:
10447: @cindex @code{init-object} discussion
10448: @cindex @code{class-inst-size} discussion
10449: If you want to allocate memory for an object yourself, you can get its
10450: alignment and size with @code{class-inst-size 2@@} ( class --
10451: align size ). Once you have memory for an object, you can initialize
10452: it with @code{init-object} ( ... class object -- );
10453: @code{construct} does only a part of the necessary work.
10454:
10455: @node Object-Oriented Programming Style, Class Binding, Creating objects, Objects
10456: @subsubsection Object-Oriented Programming Style
10457: @cindex object-oriented programming style
10458: @cindex programming style, object-oriented
1.5 anton 10459:
1.78 anton 10460: This section is not exhaustive.
1.5 anton 10461:
1.78 anton 10462: @cindex stack effects of selectors
10463: @cindex selectors and stack effects
10464: In general, it is a good idea to ensure that all methods for the
10465: same selector have the same stack effect: when you invoke a selector,
10466: you often have no idea which method will be invoked, so, unless all
10467: methods have the same stack effect, you will not know the stack effect
10468: of the selector invocation.
1.5 anton 10469:
1.78 anton 10470: One exception to this rule is methods for the selector
10471: @code{construct}. We know which method is invoked, because we
10472: specify the class to be constructed at the same place. Actually, I
10473: defined @code{construct} as a selector only to give the users a
10474: convenient way to specify initialization. The way it is used, a
10475: mechanism different from selector invocation would be more natural
10476: (but probably would take more code and more space to explain).
1.5 anton 10477:
1.78 anton 10478: @node Class Binding, Method conveniences, Object-Oriented Programming Style, Objects
10479: @subsubsection Class Binding
10480: @cindex class binding
10481: @cindex early binding
1.5 anton 10482:
1.78 anton 10483: @cindex late binding
10484: Normal selector invocations determine the method at run-time depending
10485: on the class of the receiving object. This run-time selection is called
10486: @i{late binding}.
1.5 anton 10487:
1.78 anton 10488: Sometimes it's preferable to invoke a different method. For example,
10489: you might want to use the simple method for @code{print}ing
10490: @code{object}s instead of the possibly long-winded @code{print} method
10491: of the receiver class. You can achieve this by replacing the invocation
10492: of @code{print} with:
1.5 anton 10493:
1.78 anton 10494: @cindex @code{[bind]} usage
1.5 anton 10495: @example
1.78 anton 10496: [bind] object print
1.5 anton 10497: @end example
10498:
1.78 anton 10499: @noindent
10500: in compiled code or:
10501:
10502: @cindex @code{bind} usage
1.5 anton 10503: @example
1.78 anton 10504: bind object print
1.5 anton 10505: @end example
10506:
1.78 anton 10507: @cindex class binding, alternative to
10508: @noindent
10509: in interpreted code. Alternatively, you can define the method with a
10510: name (e.g., @code{print-object}), and then invoke it through the
10511: name. Class binding is just a (often more convenient) way to achieve
10512: the same effect; it avoids name clutter and allows you to invoke
10513: methods directly without naming them first.
1.5 anton 10514:
1.78 anton 10515: @cindex superclass binding
10516: @cindex parent class binding
10517: A frequent use of class binding is this: When we define a method
10518: for a selector, we often want the method to do what the selector does
10519: in the parent class, and a little more. There is a special word for
10520: this purpose: @code{[parent]}; @code{[parent]
10521: @emph{selector}} is equivalent to @code{[bind] @emph{parent
10522: selector}}, where @code{@emph{parent}} is the parent
10523: class of the current class. E.g., a method definition might look like:
1.44 crook 10524:
1.78 anton 10525: @cindex @code{[parent]} usage
10526: @example
10527: :noname
10528: dup [parent] foo \ do parent's foo on the receiving object
10529: ... \ do some more
10530: ; overrides foo
10531: @end example
1.6 pazsan 10532:
1.78 anton 10533: @cindex class binding as optimization
10534: In @cite{Object-oriented programming in ANS Forth} (Forth Dimensions,
10535: March 1997), Andrew McKewan presents class binding as an optimization
10536: technique. I recommend not using it for this purpose unless you are in
10537: an emergency. Late binding is pretty fast with this model anyway, so the
10538: benefit of using class binding is small; the cost of using class binding
10539: where it is not appropriate is reduced maintainability.
1.44 crook 10540:
1.78 anton 10541: While we are at programming style questions: You should bind
10542: selectors only to ancestor classes of the receiving object. E.g., say,
10543: you know that the receiving object is of class @code{foo} or its
10544: descendents; then you should bind only to @code{foo} and its
10545: ancestors.
1.12 anton 10546:
1.78 anton 10547: @node Method conveniences, Classes and Scoping, Class Binding, Objects
10548: @subsubsection Method conveniences
10549: @cindex method conveniences
1.44 crook 10550:
1.78 anton 10551: In a method you usually access the receiving object pretty often. If
10552: you define the method as a plain colon definition (e.g., with
10553: @code{:noname}), you may have to do a lot of stack
10554: gymnastics. To avoid this, you can define the method with @code{m:
10555: ... ;m}. E.g., you could define the method for
10556: @code{draw}ing a @code{circle} with
1.6 pazsan 10557:
1.78 anton 10558: @cindex @code{this} usage
10559: @cindex @code{m:} usage
10560: @cindex @code{;m} usage
10561: @example
10562: m: ( x y circle -- )
10563: ( x y ) this circle-radius @@ draw-circle ;m
10564: @end example
1.6 pazsan 10565:
1.78 anton 10566: @cindex @code{exit} in @code{m: ... ;m}
10567: @cindex @code{exitm} discussion
10568: @cindex @code{catch} in @code{m: ... ;m}
10569: When this method is executed, the receiver object is removed from the
10570: stack; you can access it with @code{this} (admittedly, in this
10571: example the use of @code{m: ... ;m} offers no advantage). Note
10572: that I specify the stack effect for the whole method (i.e. including
10573: the receiver object), not just for the code between @code{m:}
10574: and @code{;m}. You cannot use @code{exit} in
10575: @code{m:...;m}; instead, use
10576: @code{exitm}.@footnote{Moreover, for any word that calls
10577: @code{catch} and was defined before loading
10578: @code{objects.fs}, you have to redefine it like I redefined
10579: @code{catch}: @code{: catch this >r catch r> to-this ;}}
1.12 anton 10580:
1.78 anton 10581: @cindex @code{inst-var} usage
10582: You will frequently use sequences of the form @code{this
10583: @emph{field}} (in the example above: @code{this
10584: circle-radius}). If you use the field only in this way, you can
10585: define it with @code{inst-var} and eliminate the
10586: @code{this} before the field name. E.g., the @code{circle}
10587: class above could also be defined with:
1.6 pazsan 10588:
1.78 anton 10589: @example
10590: graphical class
10591: cell% inst-var radius
1.6 pazsan 10592:
1.78 anton 10593: m: ( x y circle -- )
10594: radius @@ draw-circle ;m
10595: overrides draw
1.6 pazsan 10596:
1.78 anton 10597: m: ( n-radius circle -- )
10598: radius ! ;m
10599: overrides construct
1.6 pazsan 10600:
1.78 anton 10601: end-class circle
10602: @end example
1.6 pazsan 10603:
1.78 anton 10604: @code{radius} can only be used in @code{circle} and its
10605: descendent classes and inside @code{m:...;m}.
1.6 pazsan 10606:
1.78 anton 10607: @cindex @code{inst-value} usage
10608: You can also define fields with @code{inst-value}, which is
10609: to @code{inst-var} what @code{value} is to
10610: @code{variable}. You can change the value of such a field with
10611: @code{[to-inst]}. E.g., we could also define the class
10612: @code{circle} like this:
1.44 crook 10613:
1.78 anton 10614: @example
10615: graphical class
10616: inst-value radius
1.6 pazsan 10617:
1.78 anton 10618: m: ( x y circle -- )
10619: radius draw-circle ;m
10620: overrides draw
1.44 crook 10621:
1.78 anton 10622: m: ( n-radius circle -- )
10623: [to-inst] radius ;m
10624: overrides construct
1.6 pazsan 10625:
1.78 anton 10626: end-class circle
10627: @end example
1.6 pazsan 10628:
1.78 anton 10629: @c !! :m is easy to confuse with m:. Another name would be better.
1.6 pazsan 10630:
1.78 anton 10631: @c Finally, you can define named methods with @code{:m}. One use of this
10632: @c feature is the definition of words that occur only in one class and are
10633: @c not intended to be overridden, but which still need method context
10634: @c (e.g., for accessing @code{inst-var}s). Another use is for methods that
10635: @c would be bound frequently, if defined anonymously.
1.6 pazsan 10636:
10637:
1.78 anton 10638: @node Classes and Scoping, Dividing classes, Method conveniences, Objects
10639: @subsubsection Classes and Scoping
10640: @cindex classes and scoping
10641: @cindex scoping and classes
1.6 pazsan 10642:
1.78 anton 10643: Inheritance is frequent, unlike structure extension. This exacerbates
10644: the problem with the field name convention (@pxref{Structure Naming
10645: Convention}): One always has to remember in which class the field was
10646: originally defined; changing a part of the class structure would require
10647: changes for renaming in otherwise unaffected code.
1.6 pazsan 10648:
1.78 anton 10649: @cindex @code{inst-var} visibility
10650: @cindex @code{inst-value} visibility
10651: To solve this problem, I added a scoping mechanism (which was not in my
10652: original charter): A field defined with @code{inst-var} (or
10653: @code{inst-value}) is visible only in the class where it is defined and in
10654: the descendent classes of this class. Using such fields only makes
10655: sense in @code{m:}-defined methods in these classes anyway.
1.6 pazsan 10656:
1.78 anton 10657: This scoping mechanism allows us to use the unadorned field name,
10658: because name clashes with unrelated words become much less likely.
1.6 pazsan 10659:
1.78 anton 10660: @cindex @code{protected} discussion
10661: @cindex @code{private} discussion
10662: Once we have this mechanism, we can also use it for controlling the
10663: visibility of other words: All words defined after
10664: @code{protected} are visible only in the current class and its
10665: descendents. @code{public} restores the compilation
10666: (i.e. @code{current}) word list that was in effect before. If you
10667: have several @code{protected}s without an intervening
10668: @code{public} or @code{set-current}, @code{public}
10669: will restore the compilation word list in effect before the first of
10670: these @code{protected}s.
1.6 pazsan 10671:
1.78 anton 10672: @node Dividing classes, Object Interfaces, Classes and Scoping, Objects
10673: @subsubsection Dividing classes
10674: @cindex Dividing classes
10675: @cindex @code{methods}...@code{end-methods}
1.6 pazsan 10676:
1.78 anton 10677: You may want to do the definition of methods separate from the
10678: definition of the class, its selectors, fields, and instance variables,
10679: i.e., separate the implementation from the definition. You can do this
10680: in the following way:
1.6 pazsan 10681:
1.78 anton 10682: @example
10683: graphical class
10684: inst-value radius
10685: end-class circle
1.6 pazsan 10686:
1.78 anton 10687: ... \ do some other stuff
1.6 pazsan 10688:
1.78 anton 10689: circle methods \ now we are ready
1.44 crook 10690:
1.78 anton 10691: m: ( x y circle -- )
10692: radius draw-circle ;m
10693: overrides draw
1.6 pazsan 10694:
1.78 anton 10695: m: ( n-radius circle -- )
10696: [to-inst] radius ;m
10697: overrides construct
1.44 crook 10698:
1.78 anton 10699: end-methods
10700: @end example
1.7 pazsan 10701:
1.78 anton 10702: You can use several @code{methods}...@code{end-methods} sections. The
10703: only things you can do to the class in these sections are: defining
10704: methods, and overriding the class's selectors. You must not define new
10705: selectors or fields.
1.7 pazsan 10706:
1.78 anton 10707: Note that you often have to override a selector before using it. In
10708: particular, you usually have to override @code{construct} with a new
10709: method before you can invoke @code{heap-new} and friends. E.g., you
10710: must not create a circle before the @code{overrides construct} sequence
10711: in the example above.
1.7 pazsan 10712:
1.78 anton 10713: @node Object Interfaces, Objects Implementation, Dividing classes, Objects
10714: @subsubsection Object Interfaces
10715: @cindex object interfaces
10716: @cindex interfaces for objects
1.7 pazsan 10717:
1.78 anton 10718: In this model you can only call selectors defined in the class of the
10719: receiving objects or in one of its ancestors. If you call a selector
10720: with a receiving object that is not in one of these classes, the
10721: result is undefined; if you are lucky, the program crashes
10722: immediately.
1.7 pazsan 10723:
1.78 anton 10724: @cindex selectors common to hardly-related classes
10725: Now consider the case when you want to have a selector (or several)
10726: available in two classes: You would have to add the selector to a
10727: common ancestor class, in the worst case to @code{object}. You
10728: may not want to do this, e.g., because someone else is responsible for
10729: this ancestor class.
1.7 pazsan 10730:
1.78 anton 10731: The solution for this problem is interfaces. An interface is a
10732: collection of selectors. If a class implements an interface, the
10733: selectors become available to the class and its descendents. A class
10734: can implement an unlimited number of interfaces. For the problem
10735: discussed above, we would define an interface for the selector(s), and
10736: both classes would implement the interface.
1.7 pazsan 10737:
1.78 anton 10738: As an example, consider an interface @code{storage} for
10739: writing objects to disk and getting them back, and a class
10740: @code{foo} that implements it. The code would look like this:
1.7 pazsan 10741:
1.78 anton 10742: @cindex @code{interface} usage
10743: @cindex @code{end-interface} usage
10744: @cindex @code{implementation} usage
10745: @example
10746: interface
10747: selector write ( file object -- )
10748: selector read1 ( file object -- )
10749: end-interface storage
1.13 pazsan 10750:
1.78 anton 10751: bar class
10752: storage implementation
1.13 pazsan 10753:
1.78 anton 10754: ... overrides write
10755: ... overrides read1
10756: ...
10757: end-class foo
10758: @end example
1.13 pazsan 10759:
1.78 anton 10760: @noindent
10761: (I would add a word @code{read} @i{( file -- object )} that uses
10762: @code{read1} internally, but that's beyond the point illustrated
10763: here.)
1.13 pazsan 10764:
1.78 anton 10765: Note that you cannot use @code{protected} in an interface; and
10766: of course you cannot define fields.
1.13 pazsan 10767:
1.78 anton 10768: In the Neon model, all selectors are available for all classes;
10769: therefore it does not need interfaces. The price you pay in this model
10770: is slower late binding, and therefore, added complexity to avoid late
10771: binding.
1.13 pazsan 10772:
1.78 anton 10773: @node Objects Implementation, Objects Glossary, Object Interfaces, Objects
10774: @subsubsection @file{objects.fs} Implementation
10775: @cindex @file{objects.fs} implementation
1.13 pazsan 10776:
1.78 anton 10777: @cindex @code{object-map} discussion
10778: An object is a piece of memory, like one of the data structures
10779: described with @code{struct...end-struct}. It has a field
10780: @code{object-map} that points to the method map for the object's
10781: class.
1.13 pazsan 10782:
1.78 anton 10783: @cindex method map
10784: @cindex virtual function table
10785: The @emph{method map}@footnote{This is Self terminology; in C++
10786: terminology: virtual function table.} is an array that contains the
10787: execution tokens (@i{xt}s) of the methods for the object's class. Each
10788: selector contains an offset into a method map.
1.13 pazsan 10789:
1.78 anton 10790: @cindex @code{selector} implementation, class
10791: @code{selector} is a defining word that uses
10792: @code{CREATE} and @code{DOES>}. The body of the
10793: selector contains the offset; the @code{DOES>} action for a
10794: class selector is, basically:
1.8 pazsan 10795:
10796: @example
1.78 anton 10797: ( object addr ) @@ over object-map @@ + @@ execute
1.13 pazsan 10798: @end example
10799:
1.78 anton 10800: Since @code{object-map} is the first field of the object, it
10801: does not generate any code. As you can see, calling a selector has a
10802: small, constant cost.
1.26 crook 10803:
1.78 anton 10804: @cindex @code{current-interface} discussion
10805: @cindex class implementation and representation
10806: A class is basically a @code{struct} combined with a method
10807: map. During the class definition the alignment and size of the class
10808: are passed on the stack, just as with @code{struct}s, so
10809: @code{field} can also be used for defining class
10810: fields. However, passing more items on the stack would be
10811: inconvenient, so @code{class} builds a data structure in memory,
10812: which is accessed through the variable
10813: @code{current-interface}. After its definition is complete, the
10814: class is represented on the stack by a pointer (e.g., as parameter for
10815: a child class definition).
1.26 crook 10816:
1.78 anton 10817: A new class starts off with the alignment and size of its parent,
10818: and a copy of the parent's method map. Defining new fields extends the
10819: size and alignment; likewise, defining new selectors extends the
10820: method map. @code{overrides} just stores a new @i{xt} in the method
10821: map at the offset given by the selector.
1.13 pazsan 10822:
1.78 anton 10823: @cindex class binding, implementation
10824: Class binding just gets the @i{xt} at the offset given by the selector
10825: from the class's method map and @code{compile,}s (in the case of
10826: @code{[bind]}) it.
1.13 pazsan 10827:
1.78 anton 10828: @cindex @code{this} implementation
10829: @cindex @code{catch} and @code{this}
10830: @cindex @code{this} and @code{catch}
10831: I implemented @code{this} as a @code{value}. At the
10832: start of an @code{m:...;m} method the old @code{this} is
10833: stored to the return stack and restored at the end; and the object on
10834: the TOS is stored @code{TO this}. This technique has one
10835: disadvantage: If the user does not leave the method via
10836: @code{;m}, but via @code{throw} or @code{exit},
10837: @code{this} is not restored (and @code{exit} may
10838: crash). To deal with the @code{throw} problem, I have redefined
10839: @code{catch} to save and restore @code{this}; the same
10840: should be done with any word that can catch an exception. As for
10841: @code{exit}, I simply forbid it (as a replacement, there is
10842: @code{exitm}).
1.13 pazsan 10843:
1.78 anton 10844: @cindex @code{inst-var} implementation
10845: @code{inst-var} is just the same as @code{field}, with
10846: a different @code{DOES>} action:
1.13 pazsan 10847: @example
1.78 anton 10848: @@ this +
1.8 pazsan 10849: @end example
1.78 anton 10850: Similar for @code{inst-value}.
1.8 pazsan 10851:
1.78 anton 10852: @cindex class scoping implementation
10853: Each class also has a word list that contains the words defined with
10854: @code{inst-var} and @code{inst-value}, and its protected
10855: words. It also has a pointer to its parent. @code{class} pushes
10856: the word lists of the class and all its ancestors onto the search order stack,
10857: and @code{end-class} drops them.
1.20 pazsan 10858:
1.78 anton 10859: @cindex interface implementation
10860: An interface is like a class without fields, parent and protected
10861: words; i.e., it just has a method map. If a class implements an
10862: interface, its method map contains a pointer to the method map of the
10863: interface. The positive offsets in the map are reserved for class
10864: methods, therefore interface map pointers have negative
10865: offsets. Interfaces have offsets that are unique throughout the
10866: system, unlike class selectors, whose offsets are only unique for the
10867: classes where the selector is available (invokable).
1.20 pazsan 10868:
1.78 anton 10869: This structure means that interface selectors have to perform one
10870: indirection more than class selectors to find their method. Their body
10871: contains the interface map pointer offset in the class method map, and
10872: the method offset in the interface method map. The
10873: @code{does>} action for an interface selector is, basically:
1.20 pazsan 10874:
10875: @example
1.78 anton 10876: ( object selector-body )
10877: 2dup selector-interface @@ ( object selector-body object interface-offset )
10878: swap object-map @@ + @@ ( object selector-body map )
10879: swap selector-offset @@ + @@ execute
1.20 pazsan 10880: @end example
10881:
1.78 anton 10882: where @code{object-map} and @code{selector-offset} are
10883: first fields and generate no code.
1.20 pazsan 10884:
1.78 anton 10885: As a concrete example, consider the following code:
1.20 pazsan 10886:
10887: @example
1.78 anton 10888: interface
10889: selector if1sel1
10890: selector if1sel2
10891: end-interface if1
1.20 pazsan 10892:
1.78 anton 10893: object class
10894: if1 implementation
10895: selector cl1sel1
10896: cell% inst-var cl1iv1
1.20 pazsan 10897:
1.78 anton 10898: ' m1 overrides construct
10899: ' m2 overrides if1sel1
10900: ' m3 overrides if1sel2
10901: ' m4 overrides cl1sel2
10902: end-class cl1
1.20 pazsan 10903:
1.78 anton 10904: create obj1 object dict-new drop
10905: create obj2 cl1 dict-new drop
10906: @end example
1.20 pazsan 10907:
1.78 anton 10908: The data structure created by this code (including the data structure
10909: for @code{object}) is shown in the
10910: @uref{objects-implementation.eps,figure}, assuming a cell size of 4.
10911: @comment TODO add this diagram..
1.20 pazsan 10912:
1.78 anton 10913: @node Objects Glossary, , Objects Implementation, Objects
10914: @subsubsection @file{objects.fs} Glossary
10915: @cindex @file{objects.fs} Glossary
1.20 pazsan 10916:
10917:
1.78 anton 10918: doc---objects-bind
10919: doc---objects-<bind>
10920: doc---objects-bind'
10921: doc---objects-[bind]
10922: doc---objects-class
10923: doc---objects-class->map
10924: doc---objects-class-inst-size
10925: doc---objects-class-override!
1.79 anton 10926: doc---objects-class-previous
10927: doc---objects-class>order
1.78 anton 10928: doc---objects-construct
10929: doc---objects-current'
10930: doc---objects-[current]
10931: doc---objects-current-interface
10932: doc---objects-dict-new
10933: doc---objects-end-class
10934: doc---objects-end-class-noname
10935: doc---objects-end-interface
10936: doc---objects-end-interface-noname
10937: doc---objects-end-methods
10938: doc---objects-exitm
10939: doc---objects-heap-new
10940: doc---objects-implementation
10941: doc---objects-init-object
10942: doc---objects-inst-value
10943: doc---objects-inst-var
10944: doc---objects-interface
10945: doc---objects-m:
10946: doc---objects-:m
10947: doc---objects-;m
10948: doc---objects-method
10949: doc---objects-methods
10950: doc---objects-object
10951: doc---objects-overrides
10952: doc---objects-[parent]
10953: doc---objects-print
10954: doc---objects-protected
10955: doc---objects-public
10956: doc---objects-selector
10957: doc---objects-this
10958: doc---objects-<to-inst>
10959: doc---objects-[to-inst]
10960: doc---objects-to-this
10961: doc---objects-xt-new
1.20 pazsan 10962:
10963:
1.78 anton 10964: @c -------------------------------------------------------------
10965: @node OOF, Mini-OOF, Objects, Object-oriented Forth
10966: @subsection The @file{oof.fs} model
10967: @cindex oof
10968: @cindex object-oriented programming
1.20 pazsan 10969:
1.78 anton 10970: @cindex @file{objects.fs}
10971: @cindex @file{oof.fs}
1.20 pazsan 10972:
1.78 anton 10973: This section describes the @file{oof.fs} package.
1.20 pazsan 10974:
1.78 anton 10975: The package described in this section has been used in bigFORTH since 1991, and
10976: used for two large applications: a chromatographic system used to
10977: create new medicaments, and a graphic user interface library (MINOS).
1.20 pazsan 10978:
1.78 anton 10979: You can find a description (in German) of @file{oof.fs} in @cite{Object
10980: oriented bigFORTH} by Bernd Paysan, published in @cite{Vierte Dimension}
10981: 10(2), 1994.
1.20 pazsan 10982:
1.78 anton 10983: @menu
10984: * Properties of the OOF model::
10985: * Basic OOF Usage::
10986: * The OOF base class::
10987: * Class Declaration::
10988: * Class Implementation::
10989: @end menu
1.20 pazsan 10990:
1.78 anton 10991: @node Properties of the OOF model, Basic OOF Usage, OOF, OOF
10992: @subsubsection Properties of the @file{oof.fs} model
10993: @cindex @file{oof.fs} properties
1.20 pazsan 10994:
1.78 anton 10995: @itemize @bullet
10996: @item
10997: This model combines object oriented programming with information
10998: hiding. It helps you writing large application, where scoping is
10999: necessary, because it provides class-oriented scoping.
1.20 pazsan 11000:
1.78 anton 11001: @item
11002: Named objects, object pointers, and object arrays can be created,
11003: selector invocation uses the ``object selector'' syntax. Selector invocation
11004: to objects and/or selectors on the stack is a bit less convenient, but
11005: possible.
1.44 crook 11006:
1.78 anton 11007: @item
11008: Selector invocation and instance variable usage of the active object is
11009: straightforward, since both make use of the active object.
1.44 crook 11010:
1.78 anton 11011: @item
11012: Late binding is efficient and easy to use.
1.20 pazsan 11013:
1.78 anton 11014: @item
11015: State-smart objects parse selectors. However, extensibility is provided
11016: using a (parsing) selector @code{postpone} and a selector @code{'}.
1.20 pazsan 11017:
1.78 anton 11018: @item
11019: An implementation in ANS Forth is available.
1.20 pazsan 11020:
1.78 anton 11021: @end itemize
1.23 crook 11022:
11023:
1.78 anton 11024: @node Basic OOF Usage, The OOF base class, Properties of the OOF model, OOF
11025: @subsubsection Basic @file{oof.fs} Usage
11026: @cindex @file{oof.fs} usage
1.23 crook 11027:
1.78 anton 11028: This section uses the same example as for @code{objects} (@pxref{Basic Objects Usage}).
1.23 crook 11029:
1.78 anton 11030: You can define a class for graphical objects like this:
1.23 crook 11031:
1.78 anton 11032: @cindex @code{class} usage
11033: @cindex @code{class;} usage
11034: @cindex @code{method} usage
11035: @example
11036: object class graphical \ "object" is the parent class
11037: method draw ( x y graphical -- )
11038: class;
11039: @end example
1.23 crook 11040:
1.78 anton 11041: This code defines a class @code{graphical} with an
11042: operation @code{draw}. We can perform the operation
11043: @code{draw} on any @code{graphical} object, e.g.:
1.23 crook 11044:
1.78 anton 11045: @example
11046: 100 100 t-rex draw
11047: @end example
1.23 crook 11048:
1.78 anton 11049: @noindent
11050: where @code{t-rex} is an object or object pointer, created with e.g.
11051: @code{graphical : t-rex}.
1.23 crook 11052:
1.78 anton 11053: @cindex abstract class
11054: How do we create a graphical object? With the present definitions,
11055: we cannot create a useful graphical object. The class
11056: @code{graphical} describes graphical objects in general, but not
11057: any concrete graphical object type (C++ users would call it an
11058: @emph{abstract class}); e.g., there is no method for the selector
11059: @code{draw} in the class @code{graphical}.
1.23 crook 11060:
1.78 anton 11061: For concrete graphical objects, we define child classes of the
11062: class @code{graphical}, e.g.:
1.23 crook 11063:
1.78 anton 11064: @example
11065: graphical class circle \ "graphical" is the parent class
11066: cell var circle-radius
11067: how:
11068: : draw ( x y -- )
11069: circle-radius @@ draw-circle ;
1.23 crook 11070:
1.78 anton 11071: : init ( n-radius -- (
11072: circle-radius ! ;
11073: class;
11074: @end example
1.1 anton 11075:
1.78 anton 11076: Here we define a class @code{circle} as a child of @code{graphical},
11077: with a field @code{circle-radius}; it defines new methods for the
11078: selectors @code{draw} and @code{init} (@code{init} is defined in
11079: @code{object}, the parent class of @code{graphical}).
1.1 anton 11080:
1.78 anton 11081: Now we can create a circle in the dictionary with:
1.1 anton 11082:
1.78 anton 11083: @example
11084: 50 circle : my-circle
11085: @end example
1.21 crook 11086:
1.78 anton 11087: @noindent
11088: @code{:} invokes @code{init}, thus initializing the field
11089: @code{circle-radius} with 50. We can draw this new circle at (100,100)
11090: with:
1.1 anton 11091:
1.78 anton 11092: @example
11093: 100 100 my-circle draw
11094: @end example
1.1 anton 11095:
1.78 anton 11096: @cindex selector invocation, restrictions
11097: @cindex class definition, restrictions
11098: Note: You can only invoke a selector if the receiving object belongs to
11099: the class where the selector was defined or one of its descendents;
11100: e.g., you can invoke @code{draw} only for objects belonging to
11101: @code{graphical} or its descendents (e.g., @code{circle}). The scoping
11102: mechanism will check if you try to invoke a selector that is not
11103: defined in this class hierarchy, so you'll get an error at compilation
11104: time.
1.1 anton 11105:
11106:
1.78 anton 11107: @node The OOF base class, Class Declaration, Basic OOF Usage, OOF
11108: @subsubsection The @file{oof.fs} base class
11109: @cindex @file{oof.fs} base class
1.1 anton 11110:
1.78 anton 11111: When you define a class, you have to specify a parent class. So how do
11112: you start defining classes? There is one class available from the start:
11113: @code{object}. You have to use it as ancestor for all classes. It is the
11114: only class that has no parent. Classes are also objects, except that
11115: they don't have instance variables; class manipulation such as
11116: inheritance or changing definitions of a class is handled through
11117: selectors of the class @code{object}.
1.1 anton 11118:
1.78 anton 11119: @code{object} provides a number of selectors:
1.1 anton 11120:
1.78 anton 11121: @itemize @bullet
11122: @item
11123: @code{class} for subclassing, @code{definitions} to add definitions
11124: later on, and @code{class?} to get type informations (is the class a
11125: subclass of the class passed on the stack?).
1.1 anton 11126:
1.78 anton 11127: doc---object-class
11128: doc---object-definitions
11129: doc---object-class?
1.1 anton 11130:
11131:
1.26 crook 11132: @item
1.78 anton 11133: @code{init} and @code{dispose} as constructor and destructor of the
11134: object. @code{init} is invocated after the object's memory is allocated,
11135: while @code{dispose} also handles deallocation. Thus if you redefine
11136: @code{dispose}, you have to call the parent's dispose with @code{super
11137: dispose}, too.
11138:
11139: doc---object-init
11140: doc---object-dispose
11141:
1.1 anton 11142:
1.26 crook 11143: @item
1.78 anton 11144: @code{new}, @code{new[]}, @code{:}, @code{ptr}, @code{asptr}, and
11145: @code{[]} to create named and unnamed objects and object arrays or
11146: object pointers.
11147:
11148: doc---object-new
11149: doc---object-new[]
11150: doc---object-:
11151: doc---object-ptr
11152: doc---object-asptr
11153: doc---object-[]
11154:
1.1 anton 11155:
1.26 crook 11156: @item
1.78 anton 11157: @code{::} and @code{super} for explicit scoping. You should use explicit
11158: scoping only for super classes or classes with the same set of instance
11159: variables. Explicitly-scoped selectors use early binding.
1.21 crook 11160:
1.78 anton 11161: doc---object-::
11162: doc---object-super
1.21 crook 11163:
11164:
1.26 crook 11165: @item
1.78 anton 11166: @code{self} to get the address of the object
1.21 crook 11167:
1.78 anton 11168: doc---object-self
1.21 crook 11169:
11170:
1.78 anton 11171: @item
11172: @code{bind}, @code{bound}, @code{link}, and @code{is} to assign object
11173: pointers and instance defers.
1.21 crook 11174:
1.78 anton 11175: doc---object-bind
11176: doc---object-bound
11177: doc---object-link
11178: doc---object-is
1.21 crook 11179:
11180:
1.78 anton 11181: @item
11182: @code{'} to obtain selector tokens, @code{send} to invocate selectors
11183: form the stack, and @code{postpone} to generate selector invocation code.
1.21 crook 11184:
1.78 anton 11185: doc---object-'
11186: doc---object-postpone
1.21 crook 11187:
11188:
1.78 anton 11189: @item
11190: @code{with} and @code{endwith} to select the active object from the
11191: stack, and enable its scope. Using @code{with} and @code{endwith}
11192: also allows you to create code using selector @code{postpone} without being
11193: trapped by the state-smart objects.
1.21 crook 11194:
1.78 anton 11195: doc---object-with
11196: doc---object-endwith
1.21 crook 11197:
11198:
1.78 anton 11199: @end itemize
1.21 crook 11200:
1.78 anton 11201: @node Class Declaration, Class Implementation, The OOF base class, OOF
11202: @subsubsection Class Declaration
11203: @cindex class declaration
1.21 crook 11204:
1.78 anton 11205: @itemize @bullet
11206: @item
11207: Instance variables
1.21 crook 11208:
1.78 anton 11209: doc---oof-var
1.21 crook 11210:
11211:
1.78 anton 11212: @item
11213: Object pointers
1.21 crook 11214:
1.78 anton 11215: doc---oof-ptr
11216: doc---oof-asptr
1.21 crook 11217:
11218:
1.78 anton 11219: @item
11220: Instance defers
1.21 crook 11221:
1.78 anton 11222: doc---oof-defer
1.21 crook 11223:
11224:
1.78 anton 11225: @item
11226: Method selectors
1.21 crook 11227:
1.78 anton 11228: doc---oof-early
11229: doc---oof-method
1.21 crook 11230:
11231:
1.78 anton 11232: @item
11233: Class-wide variables
1.21 crook 11234:
1.78 anton 11235: doc---oof-static
1.21 crook 11236:
11237:
1.78 anton 11238: @item
11239: End declaration
1.1 anton 11240:
1.78 anton 11241: doc---oof-how:
11242: doc---oof-class;
1.21 crook 11243:
11244:
1.78 anton 11245: @end itemize
1.21 crook 11246:
1.78 anton 11247: @c -------------------------------------------------------------
11248: @node Class Implementation, , Class Declaration, OOF
11249: @subsubsection Class Implementation
11250: @cindex class implementation
1.21 crook 11251:
1.78 anton 11252: @c -------------------------------------------------------------
11253: @node Mini-OOF, Comparison with other object models, OOF, Object-oriented Forth
11254: @subsection The @file{mini-oof.fs} model
11255: @cindex mini-oof
1.21 crook 11256:
1.78 anton 11257: Gforth's third object oriented Forth package is a 12-liner. It uses a
1.79 anton 11258: mixture of the @file{objects.fs} and the @file{oof.fs} syntax,
1.78 anton 11259: and reduces to the bare minimum of features. This is based on a posting
11260: of Bernd Paysan in comp.lang.forth.
1.21 crook 11261:
1.78 anton 11262: @menu
11263: * Basic Mini-OOF Usage::
11264: * Mini-OOF Example::
11265: * Mini-OOF Implementation::
11266: @end menu
1.21 crook 11267:
1.78 anton 11268: @c -------------------------------------------------------------
11269: @node Basic Mini-OOF Usage, Mini-OOF Example, Mini-OOF, Mini-OOF
11270: @subsubsection Basic @file{mini-oof.fs} Usage
11271: @cindex mini-oof usage
1.21 crook 11272:
1.78 anton 11273: There is a base class (@code{class}, which allocates one cell for the
11274: object pointer) plus seven other words: to define a method, a variable,
11275: a class; to end a class, to resolve binding, to allocate an object and
11276: to compile a class method.
11277: @comment TODO better description of the last one
1.26 crook 11278:
1.21 crook 11279:
1.78 anton 11280: doc-object
11281: doc-method
11282: doc-var
11283: doc-class
11284: doc-end-class
11285: doc-defines
11286: doc-new
11287: doc-::
1.21 crook 11288:
11289:
11290:
1.78 anton 11291: @c -------------------------------------------------------------
11292: @node Mini-OOF Example, Mini-OOF Implementation, Basic Mini-OOF Usage, Mini-OOF
11293: @subsubsection Mini-OOF Example
11294: @cindex mini-oof example
1.1 anton 11295:
1.78 anton 11296: A short example shows how to use this package. This example, in slightly
11297: extended form, is supplied as @file{moof-exm.fs}
11298: @comment TODO could flesh this out with some comments from the Forthwrite article
1.20 pazsan 11299:
1.26 crook 11300: @example
1.78 anton 11301: object class
11302: method init
11303: method draw
11304: end-class graphical
1.26 crook 11305: @end example
1.20 pazsan 11306:
1.78 anton 11307: This code defines a class @code{graphical} with an
11308: operation @code{draw}. We can perform the operation
11309: @code{draw} on any @code{graphical} object, e.g.:
1.20 pazsan 11310:
1.26 crook 11311: @example
1.78 anton 11312: 100 100 t-rex draw
1.26 crook 11313: @end example
1.12 anton 11314:
1.78 anton 11315: where @code{t-rex} is an object or object pointer, created with e.g.
11316: @code{graphical new Constant t-rex}.
1.12 anton 11317:
1.78 anton 11318: For concrete graphical objects, we define child classes of the
11319: class @code{graphical}, e.g.:
1.12 anton 11320:
1.26 crook 11321: @example
11322: graphical class
1.78 anton 11323: cell var circle-radius
11324: end-class circle \ "graphical" is the parent class
1.12 anton 11325:
1.78 anton 11326: :noname ( x y -- )
11327: circle-radius @@ draw-circle ; circle defines draw
11328: :noname ( r -- )
11329: circle-radius ! ; circle defines init
11330: @end example
1.12 anton 11331:
1.78 anton 11332: There is no implicit init method, so we have to define one. The creation
11333: code of the object now has to call init explicitely.
1.21 crook 11334:
1.78 anton 11335: @example
11336: circle new Constant my-circle
11337: 50 my-circle init
1.12 anton 11338: @end example
11339:
1.78 anton 11340: It is also possible to add a function to create named objects with
11341: automatic call of @code{init}, given that all objects have @code{init}
11342: on the same place:
1.38 anton 11343:
1.78 anton 11344: @example
11345: : new: ( .. o "name" -- )
11346: new dup Constant init ;
11347: 80 circle new: large-circle
11348: @end example
1.12 anton 11349:
1.78 anton 11350: We can draw this new circle at (100,100) with:
1.12 anton 11351:
1.78 anton 11352: @example
11353: 100 100 my-circle draw
11354: @end example
1.12 anton 11355:
1.78 anton 11356: @node Mini-OOF Implementation, , Mini-OOF Example, Mini-OOF
11357: @subsubsection @file{mini-oof.fs} Implementation
1.12 anton 11358:
1.78 anton 11359: Object-oriented systems with late binding typically use a
11360: ``vtable''-approach: the first variable in each object is a pointer to a
11361: table, which contains the methods as function pointers. The vtable
11362: may also contain other information.
1.12 anton 11363:
1.79 anton 11364: So first, let's declare selectors:
1.37 anton 11365:
11366: @example
1.79 anton 11367: : method ( m v "name" -- m' v ) Create over , swap cell+ swap
1.78 anton 11368: DOES> ( ... o -- ... ) @@ over @@ + @@ execute ;
11369: @end example
1.37 anton 11370:
1.79 anton 11371: During selector declaration, the number of selectors and instance
11372: variables is on the stack (in address units). @code{method} creates one
11373: selector and increments the selector number. To execute a selector, it
1.78 anton 11374: takes the object, fetches the vtable pointer, adds the offset, and
1.79 anton 11375: executes the method @i{xt} stored there. Each selector takes the object
11376: it is invoked with as top of stack parameter; it passes the parameters
11377: (including the object) unchanged to the appropriate method which should
1.78 anton 11378: consume that object.
1.37 anton 11379:
1.78 anton 11380: Now, we also have to declare instance variables
1.37 anton 11381:
1.78 anton 11382: @example
1.79 anton 11383: : var ( m v size "name" -- m v' ) Create over , +
1.78 anton 11384: DOES> ( o -- addr ) @@ + ;
1.37 anton 11385: @end example
11386:
1.78 anton 11387: As before, a word is created with the current offset. Instance
11388: variables can have different sizes (cells, floats, doubles, chars), so
11389: all we do is take the size and add it to the offset. If your machine
11390: has alignment restrictions, put the proper @code{aligned} or
11391: @code{faligned} before the variable, to adjust the variable
11392: offset. That's why it is on the top of stack.
1.37 anton 11393:
1.78 anton 11394: We need a starting point (the base object) and some syntactic sugar:
1.37 anton 11395:
1.78 anton 11396: @example
11397: Create object 1 cells , 2 cells ,
1.79 anton 11398: : class ( class -- class selectors vars ) dup 2@@ ;
1.78 anton 11399: @end example
1.12 anton 11400:
1.78 anton 11401: For inheritance, the vtable of the parent object has to be
11402: copied when a new, derived class is declared. This gives all the
11403: methods of the parent class, which can be overridden, though.
1.12 anton 11404:
1.78 anton 11405: @example
1.79 anton 11406: : end-class ( class selectors vars "name" -- )
1.78 anton 11407: Create here >r , dup , 2 cells ?DO ['] noop , 1 cells +LOOP
11408: cell+ dup cell+ r> rot @@ 2 cells /string move ;
11409: @end example
1.12 anton 11410:
1.78 anton 11411: The first line creates the vtable, initialized with
11412: @code{noop}s. The second line is the inheritance mechanism, it
11413: copies the xts from the parent vtable.
1.12 anton 11414:
1.78 anton 11415: We still have no way to define new methods, let's do that now:
1.12 anton 11416:
1.26 crook 11417: @example
1.79 anton 11418: : defines ( xt class "name" -- ) ' >body @@ + ! ;
1.78 anton 11419: @end example
1.12 anton 11420:
1.78 anton 11421: To allocate a new object, we need a word, too:
1.12 anton 11422:
1.78 anton 11423: @example
11424: : new ( class -- o ) here over @@ allot swap over ! ;
1.12 anton 11425: @end example
11426:
1.78 anton 11427: Sometimes derived classes want to access the method of the
11428: parent object. There are two ways to achieve this with Mini-OOF:
11429: first, you could use named words, and second, you could look up the
11430: vtable of the parent object.
1.12 anton 11431:
1.78 anton 11432: @example
11433: : :: ( class "name" -- ) ' >body @@ + @@ compile, ;
11434: @end example
1.12 anton 11435:
11436:
1.78 anton 11437: Nothing can be more confusing than a good example, so here is
11438: one. First let's declare a text object (called
11439: @code{button}), that stores text and position:
1.12 anton 11440:
1.78 anton 11441: @example
11442: object class
11443: cell var text
11444: cell var len
11445: cell var x
11446: cell var y
11447: method init
11448: method draw
11449: end-class button
11450: @end example
1.12 anton 11451:
1.78 anton 11452: @noindent
11453: Now, implement the two methods, @code{draw} and @code{init}:
1.21 crook 11454:
1.26 crook 11455: @example
1.78 anton 11456: :noname ( o -- )
11457: >r r@@ x @@ r@@ y @@ at-xy r@@ text @@ r> len @@ type ;
11458: button defines draw
11459: :noname ( addr u o -- )
11460: >r 0 r@@ x ! 0 r@@ y ! r@@ len ! r> text ! ;
11461: button defines init
1.26 crook 11462: @end example
1.12 anton 11463:
1.78 anton 11464: @noindent
11465: To demonstrate inheritance, we define a class @code{bold-button}, with no
1.79 anton 11466: new data and no new selectors:
1.78 anton 11467:
11468: @example
11469: button class
11470: end-class bold-button
1.12 anton 11471:
1.78 anton 11472: : bold 27 emit ." [1m" ;
11473: : normal 27 emit ." [0m" ;
11474: @end example
1.1 anton 11475:
1.78 anton 11476: @noindent
11477: The class @code{bold-button} has a different draw method to
11478: @code{button}, but the new method is defined in terms of the draw method
11479: for @code{button}:
1.20 pazsan 11480:
1.78 anton 11481: @example
11482: :noname bold [ button :: draw ] normal ; bold-button defines draw
11483: @end example
1.21 crook 11484:
1.78 anton 11485: @noindent
1.79 anton 11486: Finally, create two objects and apply selectors:
1.21 crook 11487:
1.26 crook 11488: @example
1.78 anton 11489: button new Constant foo
11490: s" thin foo" foo init
11491: page
11492: foo draw
11493: bold-button new Constant bar
11494: s" fat bar" bar init
11495: 1 bar y !
11496: bar draw
1.26 crook 11497: @end example
1.21 crook 11498:
11499:
1.78 anton 11500: @node Comparison with other object models, , Mini-OOF, Object-oriented Forth
11501: @subsection Comparison with other object models
11502: @cindex comparison of object models
11503: @cindex object models, comparison
11504:
11505: Many object-oriented Forth extensions have been proposed (@cite{A survey
11506: of object-oriented Forths} (SIGPLAN Notices, April 1996) by Bradford
11507: J. Rodriguez and W. F. S. Poehlman lists 17). This section discusses the
11508: relation of the object models described here to two well-known and two
11509: closely-related (by the use of method maps) models. Andras Zsoter
11510: helped us with this section.
11511:
11512: @cindex Neon model
11513: The most popular model currently seems to be the Neon model (see
11514: @cite{Object-oriented programming in ANS Forth} (Forth Dimensions, March
11515: 1997) by Andrew McKewan) but this model has a number of limitations
11516: @footnote{A longer version of this critique can be
11517: found in @cite{On Standardizing Object-Oriented Forth Extensions} (Forth
11518: Dimensions, May 1997) by Anton Ertl.}:
11519:
11520: @itemize @bullet
11521: @item
11522: It uses a @code{@emph{selector object}} syntax, which makes it unnatural
11523: to pass objects on the stack.
1.21 crook 11524:
1.78 anton 11525: @item
11526: It requires that the selector parses the input stream (at
1.79 anton 11527: compile time); this leads to reduced extensibility and to bugs that are
1.78 anton 11528: hard to find.
1.21 crook 11529:
1.78 anton 11530: @item
1.79 anton 11531: It allows using every selector on every object; this eliminates the
11532: need for interfaces, but makes it harder to create efficient
11533: implementations.
1.78 anton 11534: @end itemize
1.21 crook 11535:
1.78 anton 11536: @cindex Pountain's object-oriented model
11537: Another well-known publication is @cite{Object-Oriented Forth} (Academic
11538: Press, London, 1987) by Dick Pountain. However, it is not really about
11539: object-oriented programming, because it hardly deals with late
11540: binding. Instead, it focuses on features like information hiding and
11541: overloading that are characteristic of modular languages like Ada (83).
1.26 crook 11542:
1.78 anton 11543: @cindex Zsoter's object-oriented model
1.79 anton 11544: In @uref{http://www.forth.org/oopf.html, Does late binding have to be
11545: slow?} (Forth Dimensions 18(1) 1996, pages 31-35) Andras Zsoter
11546: describes a model that makes heavy use of an active object (like
11547: @code{this} in @file{objects.fs}): The active object is not only used
11548: for accessing all fields, but also specifies the receiving object of
11549: every selector invocation; you have to change the active object
11550: explicitly with @code{@{ ... @}}, whereas in @file{objects.fs} it
11551: changes more or less implicitly at @code{m: ... ;m}. Such a change at
11552: the method entry point is unnecessary with Zsoter's model, because the
11553: receiving object is the active object already. On the other hand, the
11554: explicit change is absolutely necessary in that model, because otherwise
11555: no one could ever change the active object. An ANS Forth implementation
11556: of this model is available through
11557: @uref{http://www.forth.org/oopf.html}.
1.21 crook 11558:
1.78 anton 11559: @cindex @file{oof.fs}, differences to other models
11560: The @file{oof.fs} model combines information hiding and overloading
11561: resolution (by keeping names in various word lists) with object-oriented
11562: programming. It sets the active object implicitly on method entry, but
11563: also allows explicit changing (with @code{>o...o>} or with
11564: @code{with...endwith}). It uses parsing and state-smart objects and
11565: classes for resolving overloading and for early binding: the object or
11566: class parses the selector and determines the method from this. If the
11567: selector is not parsed by an object or class, it performs a call to the
11568: selector for the active object (late binding), like Zsoter's model.
11569: Fields are always accessed through the active object. The big
11570: disadvantage of this model is the parsing and the state-smartness, which
11571: reduces extensibility and increases the opportunities for subtle bugs;
11572: essentially, you are only safe if you never tick or @code{postpone} an
11573: object or class (Bernd disagrees, but I (Anton) am not convinced).
1.21 crook 11574:
1.78 anton 11575: @cindex @file{mini-oof.fs}, differences to other models
11576: The @file{mini-oof.fs} model is quite similar to a very stripped-down
11577: version of the @file{objects.fs} model, but syntactically it is a
11578: mixture of the @file{objects.fs} and @file{oof.fs} models.
1.21 crook 11579:
11580:
1.78 anton 11581: @c -------------------------------------------------------------
11582: @node Programming Tools, Assembler and Code Words, Object-oriented Forth, Words
11583: @section Programming Tools
11584: @cindex programming tools
1.21 crook 11585:
1.78 anton 11586: @c !! move this and assembler down below OO stuff.
1.21 crook 11587:
1.78 anton 11588: @menu
11589: * Examining::
11590: * Forgetting words::
11591: * Debugging:: Simple and quick.
11592: * Assertions:: Making your programs self-checking.
11593: * Singlestep Debugger:: Executing your program word by word.
11594: @end menu
1.21 crook 11595:
1.78 anton 11596: @node Examining, Forgetting words, Programming Tools, Programming Tools
11597: @subsection Examining data and code
11598: @cindex examining data and code
11599: @cindex data examination
11600: @cindex code examination
1.44 crook 11601:
1.78 anton 11602: The following words inspect the stack non-destructively:
1.21 crook 11603:
1.78 anton 11604: doc-.s
11605: doc-f.s
1.44 crook 11606:
1.78 anton 11607: There is a word @code{.r} but it does @i{not} display the return stack!
11608: It is used for formatted numeric output (@pxref{Simple numeric output}).
1.21 crook 11609:
1.78 anton 11610: doc-depth
11611: doc-fdepth
11612: doc-clearstack
1.21 crook 11613:
1.78 anton 11614: The following words inspect memory.
1.21 crook 11615:
1.78 anton 11616: doc-?
11617: doc-dump
1.21 crook 11618:
1.78 anton 11619: And finally, @code{see} allows to inspect code:
1.21 crook 11620:
1.78 anton 11621: doc-see
11622: doc-xt-see
1.111 anton 11623: doc-simple-see
11624: doc-simple-see-range
1.21 crook 11625:
1.78 anton 11626: @node Forgetting words, Debugging, Examining, Programming Tools
11627: @subsection Forgetting words
11628: @cindex words, forgetting
11629: @cindex forgeting words
1.21 crook 11630:
1.78 anton 11631: @c anton: other, maybe better places for this subsection: Defining Words;
11632: @c Dictionary allocation. At least a reference should be there.
1.21 crook 11633:
1.78 anton 11634: Forth allows you to forget words (and everything that was alloted in the
11635: dictonary after them) in a LIFO manner.
1.21 crook 11636:
1.78 anton 11637: doc-marker
1.21 crook 11638:
1.78 anton 11639: The most common use of this feature is during progam development: when
11640: you change a source file, forget all the words it defined and load it
11641: again (since you also forget everything defined after the source file
11642: was loaded, you have to reload that, too). Note that effects like
11643: storing to variables and destroyed system words are not undone when you
11644: forget words. With a system like Gforth, that is fast enough at
11645: starting up and compiling, I find it more convenient to exit and restart
11646: Gforth, as this gives me a clean slate.
1.21 crook 11647:
1.78 anton 11648: Here's an example of using @code{marker} at the start of a source file
11649: that you are debugging; it ensures that you only ever have one copy of
11650: the file's definitions compiled at any time:
1.21 crook 11651:
1.78 anton 11652: @example
11653: [IFDEF] my-code
11654: my-code
11655: [ENDIF]
1.26 crook 11656:
1.78 anton 11657: marker my-code
11658: init-included-files
1.21 crook 11659:
1.78 anton 11660: \ .. definitions start here
11661: \ .
11662: \ .
11663: \ end
11664: @end example
1.21 crook 11665:
1.26 crook 11666:
1.78 anton 11667: @node Debugging, Assertions, Forgetting words, Programming Tools
11668: @subsection Debugging
11669: @cindex debugging
1.21 crook 11670:
1.78 anton 11671: Languages with a slow edit/compile/link/test development loop tend to
11672: require sophisticated tracing/stepping debuggers to facilate debugging.
1.21 crook 11673:
1.78 anton 11674: A much better (faster) way in fast-compiling languages is to add
11675: printing code at well-selected places, let the program run, look at
11676: the output, see where things went wrong, add more printing code, etc.,
11677: until the bug is found.
1.21 crook 11678:
1.78 anton 11679: The simple debugging aids provided in @file{debugs.fs}
11680: are meant to support this style of debugging.
1.21 crook 11681:
1.78 anton 11682: The word @code{~~} prints debugging information (by default the source
11683: location and the stack contents). It is easy to insert. If you use Emacs
11684: it is also easy to remove (@kbd{C-x ~} in the Emacs Forth mode to
11685: query-replace them with nothing). The deferred words
1.101 anton 11686: @code{printdebugdata} and @code{.debugline} control the output of
1.78 anton 11687: @code{~~}. The default source location output format works well with
11688: Emacs' compilation mode, so you can step through the program at the
11689: source level using @kbd{C-x `} (the advantage over a stepping debugger
11690: is that you can step in any direction and you know where the crash has
11691: happened or where the strange data has occurred).
1.21 crook 11692:
1.78 anton 11693: doc-~~
11694: doc-printdebugdata
1.101 anton 11695: doc-.debugline
1.21 crook 11696:
1.106 anton 11697: @cindex filenames in @code{~~} output
11698: @code{~~} (and assertions) will usually print the wrong file name if a
11699: marker is executed in the same file after their occurance. They will
11700: print @samp{*somewhere*} as file name if a marker is executed in the
11701: same file before their occurance.
11702:
11703:
1.78 anton 11704: @node Assertions, Singlestep Debugger, Debugging, Programming Tools
11705: @subsection Assertions
11706: @cindex assertions
1.21 crook 11707:
1.78 anton 11708: It is a good idea to make your programs self-checking, especially if you
11709: make an assumption that may become invalid during maintenance (for
11710: example, that a certain field of a data structure is never zero). Gforth
11711: supports @dfn{assertions} for this purpose. They are used like this:
1.21 crook 11712:
11713: @example
1.78 anton 11714: assert( @i{flag} )
1.26 crook 11715: @end example
11716:
1.78 anton 11717: The code between @code{assert(} and @code{)} should compute a flag, that
11718: should be true if everything is alright and false otherwise. It should
11719: not change anything else on the stack. The overall stack effect of the
11720: assertion is @code{( -- )}. E.g.
1.21 crook 11721:
1.26 crook 11722: @example
1.78 anton 11723: assert( 1 1 + 2 = ) \ what we learn in school
11724: assert( dup 0<> ) \ assert that the top of stack is not zero
11725: assert( false ) \ this code should not be reached
1.21 crook 11726: @end example
11727:
1.78 anton 11728: The need for assertions is different at different times. During
11729: debugging, we want more checking, in production we sometimes care more
11730: for speed. Therefore, assertions can be turned off, i.e., the assertion
11731: becomes a comment. Depending on the importance of an assertion and the
11732: time it takes to check it, you may want to turn off some assertions and
11733: keep others turned on. Gforth provides several levels of assertions for
11734: this purpose:
11735:
11736:
11737: doc-assert0(
11738: doc-assert1(
11739: doc-assert2(
11740: doc-assert3(
11741: doc-assert(
11742: doc-)
1.21 crook 11743:
11744:
1.78 anton 11745: The variable @code{assert-level} specifies the highest assertions that
11746: are turned on. I.e., at the default @code{assert-level} of one,
11747: @code{assert0(} and @code{assert1(} assertions perform checking, while
11748: @code{assert2(} and @code{assert3(} assertions are treated as comments.
1.26 crook 11749:
1.78 anton 11750: The value of @code{assert-level} is evaluated at compile-time, not at
11751: run-time. Therefore you cannot turn assertions on or off at run-time;
11752: you have to set the @code{assert-level} appropriately before compiling a
11753: piece of code. You can compile different pieces of code at different
11754: @code{assert-level}s (e.g., a trusted library at level 1 and
11755: newly-written code at level 3).
1.26 crook 11756:
11757:
1.78 anton 11758: doc-assert-level
1.26 crook 11759:
11760:
1.78 anton 11761: If an assertion fails, a message compatible with Emacs' compilation mode
11762: is produced and the execution is aborted (currently with @code{ABORT"}.
11763: If there is interest, we will introduce a special throw code. But if you
11764: intend to @code{catch} a specific condition, using @code{throw} is
11765: probably more appropriate than an assertion).
1.106 anton 11766:
11767: @cindex filenames in assertion output
11768: Assertions (and @code{~~}) will usually print the wrong file name if a
11769: marker is executed in the same file after their occurance. They will
11770: print @samp{*somewhere*} as file name if a marker is executed in the
11771: same file before their occurance.
1.44 crook 11772:
1.78 anton 11773: Definitions in ANS Forth for these assertion words are provided
11774: in @file{compat/assert.fs}.
1.26 crook 11775:
1.44 crook 11776:
1.78 anton 11777: @node Singlestep Debugger, , Assertions, Programming Tools
11778: @subsection Singlestep Debugger
11779: @cindex singlestep Debugger
11780: @cindex debugging Singlestep
1.44 crook 11781:
1.112 ! anton 11782: The singlestep debugger does not work in this release.
! 11783:
1.78 anton 11784: When you create a new word there's often the need to check whether it
11785: behaves correctly or not. You can do this by typing @code{dbg
11786: badword}. A debug session might look like this:
1.26 crook 11787:
1.78 anton 11788: @example
11789: : badword 0 DO i . LOOP ; ok
11790: 2 dbg badword
11791: : badword
11792: Scanning code...
1.44 crook 11793:
1.78 anton 11794: Nesting debugger ready!
1.44 crook 11795:
1.78 anton 11796: 400D4738 8049BC4 0 -> [ 2 ] 00002 00000
11797: 400D4740 8049F68 DO -> [ 0 ]
11798: 400D4744 804A0C8 i -> [ 1 ] 00000
11799: 400D4748 400C5E60 . -> 0 [ 0 ]
11800: 400D474C 8049D0C LOOP -> [ 0 ]
11801: 400D4744 804A0C8 i -> [ 1 ] 00001
11802: 400D4748 400C5E60 . -> 1 [ 0 ]
11803: 400D474C 8049D0C LOOP -> [ 0 ]
11804: 400D4758 804B384 ; -> ok
11805: @end example
1.21 crook 11806:
1.78 anton 11807: Each line displayed is one step. You always have to hit return to
11808: execute the next word that is displayed. If you don't want to execute
11809: the next word in a whole, you have to type @kbd{n} for @code{nest}. Here is
11810: an overview what keys are available:
1.44 crook 11811:
1.78 anton 11812: @table @i
1.44 crook 11813:
1.78 anton 11814: @item @key{RET}
11815: Next; Execute the next word.
1.21 crook 11816:
1.78 anton 11817: @item n
11818: Nest; Single step through next word.
1.44 crook 11819:
1.78 anton 11820: @item u
11821: Unnest; Stop debugging and execute rest of word. If we got to this word
11822: with nest, continue debugging with the calling word.
1.44 crook 11823:
1.78 anton 11824: @item d
11825: Done; Stop debugging and execute rest.
1.21 crook 11826:
1.78 anton 11827: @item s
11828: Stop; Abort immediately.
1.44 crook 11829:
1.78 anton 11830: @end table
1.44 crook 11831:
1.78 anton 11832: Debugging large application with this mechanism is very difficult, because
11833: you have to nest very deeply into the program before the interesting part
11834: begins. This takes a lot of time.
1.26 crook 11835:
1.78 anton 11836: To do it more directly put a @code{BREAK:} command into your source code.
11837: When program execution reaches @code{BREAK:} the single step debugger is
11838: invoked and you have all the features described above.
1.44 crook 11839:
1.78 anton 11840: If you have more than one part to debug it is useful to know where the
11841: program has stopped at the moment. You can do this by the
11842: @code{BREAK" string"} command. This behaves like @code{BREAK:} except that
11843: string is typed out when the ``breakpoint'' is reached.
1.44 crook 11844:
1.26 crook 11845:
1.78 anton 11846: doc-dbg
11847: doc-break:
11848: doc-break"
1.44 crook 11849:
11850:
1.26 crook 11851:
1.78 anton 11852: @c -------------------------------------------------------------
11853: @node Assembler and Code Words, Threading Words, Programming Tools, Words
11854: @section Assembler and Code Words
11855: @cindex assembler
11856: @cindex code words
1.44 crook 11857:
1.78 anton 11858: @menu
11859: * Code and ;code::
11860: * Common Assembler:: Assembler Syntax
11861: * Common Disassembler::
11862: * 386 Assembler:: Deviations and special cases
11863: * Alpha Assembler:: Deviations and special cases
11864: * MIPS assembler:: Deviations and special cases
11865: * Other assemblers:: How to write them
11866: @end menu
1.21 crook 11867:
1.78 anton 11868: @node Code and ;code, Common Assembler, Assembler and Code Words, Assembler and Code Words
11869: @subsection @code{Code} and @code{;code}
1.26 crook 11870:
1.78 anton 11871: Gforth provides some words for defining primitives (words written in
11872: machine code), and for defining the machine-code equivalent of
11873: @code{DOES>}-based defining words. However, the machine-independent
11874: nature of Gforth poses a few problems: First of all, Gforth runs on
11875: several architectures, so it can provide no standard assembler. What's
11876: worse is that the register allocation not only depends on the processor,
11877: but also on the @code{gcc} version and options used.
1.44 crook 11878:
1.78 anton 11879: The words that Gforth offers encapsulate some system dependences (e.g.,
11880: the header structure), so a system-independent assembler may be used in
11881: Gforth. If you do not have an assembler, you can compile machine code
11882: directly with @code{,} and @code{c,}@footnote{This isn't portable,
11883: because these words emit stuff in @i{data} space; it works because
11884: Gforth has unified code/data spaces. Assembler isn't likely to be
11885: portable anyway.}.
1.21 crook 11886:
1.44 crook 11887:
1.78 anton 11888: doc-assembler
11889: doc-init-asm
11890: doc-code
11891: doc-end-code
11892: doc-;code
11893: doc-flush-icache
1.44 crook 11894:
1.21 crook 11895:
1.78 anton 11896: If @code{flush-icache} does not work correctly, @code{code} words
11897: etc. will not work (reliably), either.
1.44 crook 11898:
1.78 anton 11899: The typical usage of these @code{code} words can be shown most easily by
11900: analogy to the equivalent high-level defining words:
1.44 crook 11901:
1.78 anton 11902: @example
11903: : foo code foo
11904: <high-level Forth words> <assembler>
11905: ; end-code
11906:
11907: : bar : bar
11908: <high-level Forth words> <high-level Forth words>
11909: CREATE CREATE
11910: <high-level Forth words> <high-level Forth words>
11911: DOES> ;code
11912: <high-level Forth words> <assembler>
11913: ; end-code
11914: @end example
1.21 crook 11915:
1.78 anton 11916: @c anton: the following stuff is also in "Common Assembler", in less detail.
1.44 crook 11917:
1.78 anton 11918: @cindex registers of the inner interpreter
11919: In the assembly code you will want to refer to the inner interpreter's
11920: registers (e.g., the data stack pointer) and you may want to use other
11921: registers for temporary storage. Unfortunately, the register allocation
11922: is installation-dependent.
1.44 crook 11923:
1.78 anton 11924: In particular, @code{ip} (Forth instruction pointer) and @code{rp}
1.100 anton 11925: (return stack pointer) may be in different places in @code{gforth} and
11926: @code{gforth-fast}, or different installations. This means that you
11927: cannot write a @code{NEXT} routine that works reliably on both versions
11928: or different installations; so for doing @code{NEXT}, I recommend
11929: jumping to @code{' noop >code-address}, which contains nothing but a
11930: @code{NEXT}.
1.21 crook 11931:
1.78 anton 11932: For general accesses to the inner interpreter's registers, the easiest
11933: solution is to use explicit register declarations (@pxref{Explicit Reg
11934: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) for
11935: all of the inner interpreter's registers: You have to compile Gforth
11936: with @code{-DFORCE_REG} (configure option @code{--enable-force-reg}) and
11937: the appropriate declarations must be present in the @code{machine.h}
11938: file (see @code{mips.h} for an example; you can find a full list of all
11939: declarable register symbols with @code{grep register engine.c}). If you
11940: give explicit registers to all variables that are declared at the
11941: beginning of @code{engine()}, you should be able to use the other
11942: caller-saved registers for temporary storage. Alternatively, you can use
11943: the @code{gcc} option @code{-ffixed-REG} (@pxref{Code Gen Options, ,
11944: Options for Code Generation Conventions, gcc.info, GNU C Manual}) to
11945: reserve a register (however, this restriction on register allocation may
11946: slow Gforth significantly).
1.44 crook 11947:
1.78 anton 11948: If this solution is not viable (e.g., because @code{gcc} does not allow
11949: you to explicitly declare all the registers you need), you have to find
11950: out by looking at the code where the inner interpreter's registers
11951: reside and which registers can be used for temporary storage. You can
11952: get an assembly listing of the engine's code with @code{make engine.s}.
1.44 crook 11953:
1.78 anton 11954: In any case, it is good practice to abstract your assembly code from the
11955: actual register allocation. E.g., if the data stack pointer resides in
11956: register @code{$17}, create an alias for this register called @code{sp},
11957: and use that in your assembly code.
1.21 crook 11958:
1.78 anton 11959: @cindex code words, portable
11960: Another option for implementing normal and defining words efficiently
11961: is to add the desired functionality to the source of Gforth. For normal
11962: words you just have to edit @file{primitives} (@pxref{Automatic
11963: Generation}). Defining words (equivalent to @code{;CODE} words, for fast
11964: defined words) may require changes in @file{engine.c}, @file{kernel.fs},
11965: @file{prims2x.fs}, and possibly @file{cross.fs}.
1.44 crook 11966:
1.78 anton 11967: @node Common Assembler, Common Disassembler, Code and ;code, Assembler and Code Words
11968: @subsection Common Assembler
1.44 crook 11969:
1.78 anton 11970: The assemblers in Gforth generally use a postfix syntax, i.e., the
11971: instruction name follows the operands.
1.21 crook 11972:
1.78 anton 11973: The operands are passed in the usual order (the same that is used in the
11974: manual of the architecture). Since they all are Forth words, they have
11975: to be separated by spaces; you can also use Forth words to compute the
11976: operands.
1.44 crook 11977:
1.78 anton 11978: The instruction names usually end with a @code{,}. This makes it easier
11979: to visually separate instructions if you put several of them on one
11980: line; it also avoids shadowing other Forth words (e.g., @code{and}).
1.21 crook 11981:
1.78 anton 11982: Registers are usually specified by number; e.g., (decimal) @code{11}
11983: specifies registers R11 and F11 on the Alpha architecture (which one,
11984: depends on the instruction). The usual names are also available, e.g.,
11985: @code{s2} for R11 on Alpha.
1.21 crook 11986:
1.78 anton 11987: Control flow is specified similar to normal Forth code (@pxref{Arbitrary
11988: control structures}), with @code{if,}, @code{ahead,}, @code{then,},
11989: @code{begin,}, @code{until,}, @code{again,}, @code{cs-roll},
11990: @code{cs-pick}, @code{else,}, @code{while,}, and @code{repeat,}. The
11991: conditions are specified in a way specific to each assembler.
1.1 anton 11992:
1.78 anton 11993: Note that the register assignments of the Gforth engine can change
11994: between Gforth versions, or even between different compilations of the
11995: same Gforth version (e.g., if you use a different GCC version). So if
11996: you want to refer to Gforth's registers (e.g., the stack pointer or
11997: TOS), I recommend defining your own words for refering to these
11998: registers, and using them later on; then you can easily adapt to a
11999: changed register assignment. The stability of the register assignment
12000: is usually better if you build Gforth with @code{--enable-force-reg}.
1.1 anton 12001:
1.100 anton 12002: The most common use of these registers is to dispatch to the next word
12003: (the @code{next} routine). A portable way to do this is to jump to
12004: @code{' noop >code-address} (of course, this is less efficient than
12005: integrating the @code{next} code and scheduling it well).
1.1 anton 12006:
1.96 anton 12007: Another difference between Gforth version is that the top of stack is
12008: kept in memory in @code{gforth} and, on most platforms, in a register in
12009: @code{gforth-fast}.
12010:
1.78 anton 12011: @node Common Disassembler, 386 Assembler, Common Assembler, Assembler and Code Words
12012: @subsection Common Disassembler
1.1 anton 12013:
1.78 anton 12014: You can disassemble a @code{code} word with @code{see}
12015: (@pxref{Debugging}). You can disassemble a section of memory with
1.1 anton 12016:
1.78 anton 12017: doc-disasm
1.44 crook 12018:
1.78 anton 12019: The disassembler generally produces output that can be fed into the
12020: assembler (i.e., same syntax, etc.). It also includes additional
12021: information in comments. In particular, the address of the instruction
12022: is given in a comment before the instruction.
1.1 anton 12023:
1.78 anton 12024: @code{See} may display more or less than the actual code of the word,
12025: because the recognition of the end of the code is unreliable. You can
12026: use @code{disasm} if it did not display enough. It may display more, if
12027: the code word is not immediately followed by a named word. If you have
12028: something else there, you can follow the word with @code{align last @ ,}
12029: to ensure that the end is recognized.
1.21 crook 12030:
1.78 anton 12031: @node 386 Assembler, Alpha Assembler, Common Disassembler, Assembler and Code Words
12032: @subsection 386 Assembler
1.44 crook 12033:
1.78 anton 12034: The 386 assembler included in Gforth was written by Bernd Paysan, it's
12035: available under GPL, and originally part of bigFORTH.
1.21 crook 12036:
1.78 anton 12037: The 386 disassembler included in Gforth was written by Andrew McKewan
12038: and is in the public domain.
1.21 crook 12039:
1.91 anton 12040: The disassembler displays code in an Intel-like prefix syntax.
1.21 crook 12041:
1.78 anton 12042: The assembler uses a postfix syntax with reversed parameters.
1.1 anton 12043:
1.78 anton 12044: The assembler includes all instruction of the Athlon, i.e. 486 core
12045: instructions, Pentium and PPro extensions, floating point, MMX, 3Dnow!,
12046: but not ISSE. It's an integrated 16- and 32-bit assembler. Default is 32
12047: bit, you can switch to 16 bit with .86 and back to 32 bit with .386.
1.1 anton 12048:
1.78 anton 12049: There are several prefixes to switch between different operation sizes,
12050: @code{.b} for byte accesses, @code{.w} for word accesses, @code{.d} for
12051: double-word accesses. Addressing modes can be switched with @code{.wa}
12052: for 16 bit addresses, and @code{.da} for 32 bit addresses. You don't
12053: need a prefix for byte register names (@code{AL} et al).
1.1 anton 12054:
1.78 anton 12055: For floating point operations, the prefixes are @code{.fs} (IEEE
12056: single), @code{.fl} (IEEE double), @code{.fx} (extended), @code{.fw}
12057: (word), @code{.fd} (double-word), and @code{.fq} (quad-word).
1.21 crook 12058:
1.78 anton 12059: The MMX opcodes don't have size prefixes, they are spelled out like in
12060: the Intel assembler. Instead of move from and to memory, there are
12061: PLDQ/PLDD and PSTQ/PSTD.
1.21 crook 12062:
1.78 anton 12063: The registers lack the 'e' prefix; even in 32 bit mode, eax is called
12064: ax. Immediate values are indicated by postfixing them with @code{#},
1.91 anton 12065: e.g., @code{3 #}. Here are some examples of addressing modes in various
12066: syntaxes:
1.21 crook 12067:
1.26 crook 12068: @example
1.91 anton 12069: Gforth Intel (NASM) AT&T (gas) Name
12070: .w ax ax %ax register (16 bit)
12071: ax eax %eax register (32 bit)
12072: 3 # offset 3 $3 immediate
12073: 1000 #) byte ptr 1000 1000 displacement
12074: bx ) [ebx] (%ebx) base
12075: 100 di d) 100[edi] 100(%edi) base+displacement
12076: 20 ax *4 i#) 20[eax*4] 20(,%eax,4) (index*scale)+displacement
12077: di ax *4 i) [edi][eax*4] (%edi,%eax,4) base+(index*scale)
12078: 4 bx cx di) 4[ebx][ecx] 4(%ebx,%ecx) base+index+displacement
12079: 12 sp ax *2 di) 12[esp][eax*2] 12(%esp,%eax,2) base+(index*scale)+displacement
12080: @end example
12081:
12082: You can use @code{L)} and @code{LI)} instead of @code{D)} and
12083: @code{DI)} to enforce 32-bit displacement fields (useful for
12084: later patching).
1.21 crook 12085:
1.78 anton 12086: Some example of instructions are:
1.1 anton 12087:
12088: @example
1.78 anton 12089: ax bx mov \ move ebx,eax
12090: 3 # ax mov \ mov eax,3
12091: 100 di ) ax mov \ mov eax,100[edi]
12092: 4 bx cx di) ax mov \ mov eax,4[ebx][ecx]
12093: .w ax bx mov \ mov bx,ax
1.1 anton 12094: @end example
12095:
1.78 anton 12096: The following forms are supported for binary instructions:
1.1 anton 12097:
12098: @example
1.78 anton 12099: <reg> <reg> <inst>
12100: <n> # <reg> <inst>
12101: <mem> <reg> <inst>
12102: <reg> <mem> <inst>
1.1 anton 12103: @end example
12104:
1.78 anton 12105: Immediate to memory is not supported. The shift/rotate syntax is:
1.1 anton 12106:
1.26 crook 12107: @example
1.78 anton 12108: <reg/mem> 1 # shl \ shortens to shift without immediate
12109: <reg/mem> 4 # shl
12110: <reg/mem> cl shl
1.26 crook 12111: @end example
1.1 anton 12112:
1.78 anton 12113: Precede string instructions (@code{movs} etc.) with @code{.b} to get
12114: the byte version.
1.1 anton 12115:
1.78 anton 12116: The control structure words @code{IF} @code{UNTIL} etc. must be preceded
12117: by one of these conditions: @code{vs vc u< u>= 0= 0<> u<= u> 0< 0>= ps
12118: pc < >= <= >}. (Note that most of these words shadow some Forth words
12119: when @code{assembler} is in front of @code{forth} in the search path,
12120: e.g., in @code{code} words). Currently the control structure words use
12121: one stack item, so you have to use @code{roll} instead of @code{cs-roll}
12122: to shuffle them (you can also use @code{swap} etc.).
1.21 crook 12123:
1.78 anton 12124: Here is an example of a @code{code} word (assumes that the stack pointer
12125: is in esi and the TOS is in ebx):
1.21 crook 12126:
1.26 crook 12127: @example
1.78 anton 12128: code my+ ( n1 n2 -- n )
12129: 4 si D) bx add
12130: 4 # si add
12131: Next
12132: end-code
1.26 crook 12133: @end example
1.21 crook 12134:
1.78 anton 12135: @node Alpha Assembler, MIPS assembler, 386 Assembler, Assembler and Code Words
12136: @subsection Alpha Assembler
1.21 crook 12137:
1.78 anton 12138: The Alpha assembler and disassembler were originally written by Bernd
12139: Thallner.
1.26 crook 12140:
1.78 anton 12141: The register names @code{a0}--@code{a5} are not available to avoid
12142: shadowing hex numbers.
1.2 jwilke 12143:
1.78 anton 12144: Immediate forms of arithmetic instructions are distinguished by a
12145: @code{#} just before the @code{,}, e.g., @code{and#,} (note: @code{lda,}
12146: does not count as arithmetic instruction).
1.2 jwilke 12147:
1.78 anton 12148: You have to specify all operands to an instruction, even those that
12149: other assemblers consider optional, e.g., the destination register for
12150: @code{br,}, or the destination register and hint for @code{jmp,}.
1.2 jwilke 12151:
1.78 anton 12152: You can specify conditions for @code{if,} by removing the first @code{b}
12153: and the trailing @code{,} from a branch with a corresponding name; e.g.,
1.2 jwilke 12154:
1.26 crook 12155: @example
1.78 anton 12156: 11 fgt if, \ if F11>0e
12157: ...
12158: endif,
1.26 crook 12159: @end example
1.2 jwilke 12160:
1.78 anton 12161: @code{fbgt,} gives @code{fgt}.
12162:
12163: @node MIPS assembler, Other assemblers, Alpha Assembler, Assembler and Code Words
12164: @subsection MIPS assembler
1.2 jwilke 12165:
1.78 anton 12166: The MIPS assembler was originally written by Christian Pirker.
1.2 jwilke 12167:
1.78 anton 12168: Currently the assembler and disassembler only cover the MIPS-I
12169: architecture (R3000), and don't support FP instructions.
1.2 jwilke 12170:
1.78 anton 12171: The register names @code{$a0}--@code{$a3} are not available to avoid
12172: shadowing hex numbers.
1.2 jwilke 12173:
1.78 anton 12174: Because there is no way to distinguish registers from immediate values,
12175: you have to explicitly use the immediate forms of instructions, i.e.,
12176: @code{addiu,}, not just @code{addu,} (@command{as} does this
12177: implicitly).
1.2 jwilke 12178:
1.78 anton 12179: If the architecture manual specifies several formats for the instruction
12180: (e.g., for @code{jalr,}), you usually have to use the one with more
12181: arguments (i.e., two for @code{jalr,}). When in doubt, see
12182: @code{arch/mips/testasm.fs} for an example of correct use.
1.2 jwilke 12183:
1.78 anton 12184: Branches and jumps in the MIPS architecture have a delay slot. You have
12185: to fill it yourself (the simplest way is to use @code{nop,}), the
12186: assembler does not do it for you (unlike @command{as}). Even
12187: @code{if,}, @code{ahead,}, @code{until,}, @code{again,}, @code{while,},
12188: @code{else,} and @code{repeat,} need a delay slot. Since @code{begin,}
12189: and @code{then,} just specify branch targets, they are not affected.
1.2 jwilke 12190:
1.78 anton 12191: Note that you must not put branches, jumps, or @code{li,} into the delay
12192: slot: @code{li,} may expand to several instructions, and control flow
12193: instructions may not be put into the branch delay slot in any case.
1.2 jwilke 12194:
1.78 anton 12195: For branches the argument specifying the target is a relative address;
12196: You have to add the address of the delay slot to get the absolute
12197: address.
1.1 anton 12198:
1.78 anton 12199: The MIPS architecture also has load delay slots and restrictions on
12200: using @code{mfhi,} and @code{mflo,}; you have to order the instructions
12201: yourself to satisfy these restrictions, the assembler does not do it for
12202: you.
1.1 anton 12203:
1.78 anton 12204: You can specify the conditions for @code{if,} etc. by taking a
12205: conditional branch and leaving away the @code{b} at the start and the
12206: @code{,} at the end. E.g.,
1.1 anton 12207:
1.26 crook 12208: @example
1.78 anton 12209: 4 5 eq if,
12210: ... \ do something if $4 equals $5
12211: then,
1.26 crook 12212: @end example
1.1 anton 12213:
1.78 anton 12214: @node Other assemblers, , MIPS assembler, Assembler and Code Words
12215: @subsection Other assemblers
12216:
12217: If you want to contribute another assembler/disassembler, please contact
1.103 anton 12218: us (@email{anton@@mips.complang.tuwien.ac.at}) to check if we have such
12219: an assembler already. If you are writing them from scratch, please use
12220: a similar syntax style as the one we use (i.e., postfix, commas at the
12221: end of the instruction names, @pxref{Common Assembler}); make the output
12222: of the disassembler be valid input for the assembler, and keep the style
1.78 anton 12223: similar to the style we used.
12224:
12225: Hints on implementation: The most important part is to have a good test
12226: suite that contains all instructions. Once you have that, the rest is
12227: easy. For actual coding you can take a look at
12228: @file{arch/mips/disasm.fs} to get some ideas on how to use data for both
12229: the assembler and disassembler, avoiding redundancy and some potential
12230: bugs. You can also look at that file (and @pxref{Advanced does> usage
12231: example}) to get ideas how to factor a disassembler.
12232:
12233: Start with the disassembler, because it's easier to reuse data from the
12234: disassembler for the assembler than the other way round.
1.1 anton 12235:
1.78 anton 12236: For the assembler, take a look at @file{arch/alpha/asm.fs}, which shows
12237: how simple it can be.
1.1 anton 12238:
1.78 anton 12239: @c -------------------------------------------------------------
12240: @node Threading Words, Passing Commands to the OS, Assembler and Code Words, Words
12241: @section Threading Words
12242: @cindex threading words
1.1 anton 12243:
1.78 anton 12244: @cindex code address
12245: These words provide access to code addresses and other threading stuff
12246: in Gforth (and, possibly, other interpretive Forths). It more or less
12247: abstracts away the differences between direct and indirect threading
12248: (and, for direct threading, the machine dependences). However, at
12249: present this wordset is still incomplete. It is also pretty low-level;
12250: some day it will hopefully be made unnecessary by an internals wordset
12251: that abstracts implementation details away completely.
1.1 anton 12252:
1.78 anton 12253: The terminology used here stems from indirect threaded Forth systems; in
12254: such a system, the XT of a word is represented by the CFA (code field
12255: address) of a word; the CFA points to a cell that contains the code
12256: address. The code address is the address of some machine code that
12257: performs the run-time action of invoking the word (e.g., the
12258: @code{dovar:} routine pushes the address of the body of the word (a
12259: variable) on the stack
12260: ).
1.1 anton 12261:
1.78 anton 12262: @cindex code address
12263: @cindex code field address
12264: In an indirect threaded Forth, you can get the code address of @i{name}
12265: with @code{' @i{name} @@}; in Gforth you can get it with @code{' @i{name}
12266: >code-address}, independent of the threading method.
1.1 anton 12267:
1.78 anton 12268: doc-threading-method
12269: doc->code-address
12270: doc-code-address!
1.1 anton 12271:
1.78 anton 12272: @cindex @code{does>}-handler
12273: @cindex @code{does>}-code
12274: For a word defined with @code{DOES>}, the code address usually points to
12275: a jump instruction (the @dfn{does-handler}) that jumps to the dodoes
12276: routine (in Gforth on some platforms, it can also point to the dodoes
12277: routine itself). What you are typically interested in, though, is
12278: whether a word is a @code{DOES>}-defined word, and what Forth code it
12279: executes; @code{>does-code} tells you that.
1.1 anton 12280:
1.78 anton 12281: doc->does-code
1.1 anton 12282:
1.78 anton 12283: To create a @code{DOES>}-defined word with the following basic words,
12284: you have to set up a @code{DOES>}-handler with @code{does-handler!};
12285: @code{/does-handler} aus behind you have to place your executable Forth
12286: code. Finally you have to create a word and modify its behaviour with
12287: @code{does-handler!}.
1.1 anton 12288:
1.78 anton 12289: doc-does-code!
12290: doc-does-handler!
12291: doc-/does-handler
1.1 anton 12292:
1.78 anton 12293: The code addresses produced by various defining words are produced by
12294: the following words:
1.1 anton 12295:
1.78 anton 12296: doc-docol:
12297: doc-docon:
12298: doc-dovar:
12299: doc-douser:
12300: doc-dodefer:
12301: doc-dofield:
1.1 anton 12302:
1.99 anton 12303: @cindex definer
12304: The following two words generalize @code{>code-address},
12305: @code{>does-code}, @code{code-address!}, and @code{does-code!}:
12306:
12307: doc->definer
12308: doc-definer!
12309:
1.26 crook 12310: @c -------------------------------------------------------------
1.78 anton 12311: @node Passing Commands to the OS, Keeping track of Time, Threading Words, Words
1.21 crook 12312: @section Passing Commands to the Operating System
12313: @cindex operating system - passing commands
12314: @cindex shell commands
12315:
12316: Gforth allows you to pass an arbitrary string to the host operating
12317: system shell (if such a thing exists) for execution.
12318:
1.44 crook 12319:
1.21 crook 12320: doc-sh
12321: doc-system
12322: doc-$?
1.23 crook 12323: doc-getenv
1.21 crook 12324:
1.44 crook 12325:
1.26 crook 12326: @c -------------------------------------------------------------
1.47 crook 12327: @node Keeping track of Time, Miscellaneous Words, Passing Commands to the OS, Words
12328: @section Keeping track of Time
12329: @cindex time-related words
12330:
12331: doc-ms
12332: doc-time&date
1.79 anton 12333: doc-utime
12334: doc-cputime
1.47 crook 12335:
12336:
12337: @c -------------------------------------------------------------
12338: @node Miscellaneous Words, , Keeping track of Time, Words
1.21 crook 12339: @section Miscellaneous Words
12340: @cindex miscellaneous words
12341:
1.29 crook 12342: @comment TODO find homes for these
12343:
1.26 crook 12344: These section lists the ANS Forth words that are not documented
1.21 crook 12345: elsewhere in this manual. Ultimately, they all need proper homes.
12346:
1.68 anton 12347: doc-quit
1.44 crook 12348:
1.26 crook 12349: The following ANS Forth words are not currently supported by Gforth
1.27 crook 12350: (@pxref{ANS conformance}):
1.21 crook 12351:
12352: @code{EDITOR}
12353: @code{EMIT?}
12354: @code{FORGET}
12355:
1.24 anton 12356: @c ******************************************************************
12357: @node Error messages, Tools, Words, Top
12358: @chapter Error messages
12359: @cindex error messages
12360: @cindex backtrace
12361:
12362: A typical Gforth error message looks like this:
12363:
12364: @example
1.86 anton 12365: in file included from \evaluated string/:-1
1.24 anton 12366: in file included from ./yyy.fs:1
12367: ./xxx.fs:4: Invalid memory address
12368: bar
12369: ^^^
1.79 anton 12370: Backtrace:
1.25 anton 12371: $400E664C @@
12372: $400E6664 foo
1.24 anton 12373: @end example
12374:
12375: The message identifying the error is @code{Invalid memory address}. The
12376: error happened when text-interpreting line 4 of the file
12377: @file{./xxx.fs}. This line is given (it contains @code{bar}), and the
12378: word on the line where the error happened, is pointed out (with
12379: @code{^^^}).
12380:
12381: The file containing the error was included in line 1 of @file{./yyy.fs},
12382: and @file{yyy.fs} was included from a non-file (in this case, by giving
12383: @file{yyy.fs} as command-line parameter to Gforth).
12384:
12385: At the end of the error message you find a return stack dump that can be
12386: interpreted as a backtrace (possibly empty). On top you find the top of
12387: the return stack when the @code{throw} happened, and at the bottom you
12388: find the return stack entry just above the return stack of the topmost
12389: text interpreter.
12390:
12391: To the right of most return stack entries you see a guess for the word
12392: that pushed that return stack entry as its return address. This gives a
12393: backtrace. In our case we see that @code{bar} called @code{foo}, and
12394: @code{foo} called @code{@@} (and @code{@@} had an @emph{Invalid memory
12395: address} exception).
12396:
12397: Note that the backtrace is not perfect: We don't know which return stack
12398: entries are return addresses (so we may get false positives); and in
12399: some cases (e.g., for @code{abort"}) we cannot determine from the return
12400: address the word that pushed the return address, so for some return
12401: addresses you see no names in the return stack dump.
1.25 anton 12402:
12403: @cindex @code{catch} and backtraces
12404: The return stack dump represents the return stack at the time when a
12405: specific @code{throw} was executed. In programs that make use of
12406: @code{catch}, it is not necessarily clear which @code{throw} should be
12407: used for the return stack dump (e.g., consider one @code{throw} that
12408: indicates an error, which is caught, and during recovery another error
1.42 anton 12409: happens; which @code{throw} should be used for the stack dump?). Gforth
1.25 anton 12410: presents the return stack dump for the first @code{throw} after the last
12411: executed (not returned-to) @code{catch}; this works well in the usual
12412: case.
12413:
12414: @cindex @code{gforth-fast} and backtraces
12415: @cindex @code{gforth-fast}, difference from @code{gforth}
12416: @cindex backtraces with @code{gforth-fast}
12417: @cindex return stack dump with @code{gforth-fast}
1.79 anton 12418: @code{Gforth} is able to do a return stack dump for throws generated
1.25 anton 12419: from primitives (e.g., invalid memory address, stack empty etc.);
12420: @code{gforth-fast} is only able to do a return stack dump from a
1.96 anton 12421: directly called @code{throw} (including @code{abort} etc.). Given an
1.30 anton 12422: exception caused by a primitive in @code{gforth-fast}, you will
12423: typically see no return stack dump at all; however, if the exception is
12424: caught by @code{catch} (e.g., for restoring some state), and then
12425: @code{throw}n again, the return stack dump will be for the first such
12426: @code{throw}.
1.2 jwilke 12427:
1.5 anton 12428: @c ******************************************************************
1.24 anton 12429: @node Tools, ANS conformance, Error messages, Top
1.1 anton 12430: @chapter Tools
12431:
12432: @menu
12433: * ANS Report:: Report the words used, sorted by wordset.
12434: @end menu
12435:
12436: See also @ref{Emacs and Gforth}.
12437:
12438: @node ANS Report, , Tools, Tools
12439: @section @file{ans-report.fs}: Report the words used, sorted by wordset
12440: @cindex @file{ans-report.fs}
12441: @cindex report the words used in your program
12442: @cindex words used in your program
12443:
12444: If you want to label a Forth program as ANS Forth Program, you must
12445: document which wordsets the program uses; for extension wordsets, it is
12446: helpful to list the words the program requires from these wordsets
12447: (because Forth systems are allowed to provide only some words of them).
12448:
12449: The @file{ans-report.fs} tool makes it easy for you to determine which
12450: words from which wordset and which non-ANS words your application
12451: uses. You simply have to include @file{ans-report.fs} before loading the
12452: program you want to check. After loading your program, you can get the
12453: report with @code{print-ans-report}. A typical use is to run this as
12454: batch job like this:
12455: @example
12456: gforth ans-report.fs myprog.fs -e "print-ans-report bye"
12457: @end example
12458:
12459: The output looks like this (for @file{compat/control.fs}):
12460: @example
12461: The program uses the following words
12462: from CORE :
12463: : POSTPONE THEN ; immediate ?dup IF 0=
12464: from BLOCK-EXT :
12465: \
12466: from FILE :
12467: (
12468: @end example
12469:
12470: @subsection Caveats
12471:
12472: Note that @file{ans-report.fs} just checks which words are used, not whether
12473: they are used in an ANS Forth conforming way!
12474:
12475: Some words are defined in several wordsets in the
12476: standard. @file{ans-report.fs} reports them for only one of the
12477: wordsets, and not necessarily the one you expect. It depends on usage
12478: which wordset is the right one to specify. E.g., if you only use the
12479: compilation semantics of @code{S"}, it is a Core word; if you also use
12480: its interpretation semantics, it is a File word.
12481:
12482: @c ******************************************************************
1.65 anton 12483: @node ANS conformance, Standard vs Extensions, Tools, Top
1.1 anton 12484: @chapter ANS conformance
12485: @cindex ANS conformance of Gforth
12486:
12487: To the best of our knowledge, Gforth is an
12488:
12489: ANS Forth System
12490: @itemize @bullet
12491: @item providing the Core Extensions word set
12492: @item providing the Block word set
12493: @item providing the Block Extensions word set
12494: @item providing the Double-Number word set
12495: @item providing the Double-Number Extensions word set
12496: @item providing the Exception word set
12497: @item providing the Exception Extensions word set
12498: @item providing the Facility word set
1.40 anton 12499: @item providing @code{EKEY}, @code{EKEY>CHAR}, @code{EKEY?}, @code{MS} and @code{TIME&DATE} from the Facility Extensions word set
1.1 anton 12500: @item providing the File Access word set
12501: @item providing the File Access Extensions word set
12502: @item providing the Floating-Point word set
12503: @item providing the Floating-Point Extensions word set
12504: @item providing the Locals word set
12505: @item providing the Locals Extensions word set
12506: @item providing the Memory-Allocation word set
12507: @item providing the Memory-Allocation Extensions word set (that one's easy)
12508: @item providing the Programming-Tools word set
12509: @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
12510: @item providing the Search-Order word set
12511: @item providing the Search-Order Extensions word set
12512: @item providing the String word set
12513: @item providing the String Extensions word set (another easy one)
12514: @end itemize
12515:
12516: @cindex system documentation
12517: In addition, ANS Forth systems are required to document certain
12518: implementation choices. This chapter tries to meet these
12519: requirements. In many cases it gives a way to ask the system for the
12520: information instead of providing the information directly, in
12521: particular, if the information depends on the processor, the operating
12522: system or the installation options chosen, or if they are likely to
12523: change during the maintenance of Gforth.
12524:
12525: @comment The framework for the rest has been taken from pfe.
12526:
12527: @menu
12528: * The Core Words::
12529: * The optional Block word set::
12530: * The optional Double Number word set::
12531: * The optional Exception word set::
12532: * The optional Facility word set::
12533: * The optional File-Access word set::
12534: * The optional Floating-Point word set::
12535: * The optional Locals word set::
12536: * The optional Memory-Allocation word set::
12537: * The optional Programming-Tools word set::
12538: * The optional Search-Order word set::
12539: @end menu
12540:
12541:
12542: @c =====================================================================
12543: @node The Core Words, The optional Block word set, ANS conformance, ANS conformance
12544: @comment node-name, next, previous, up
12545: @section The Core Words
12546: @c =====================================================================
12547: @cindex core words, system documentation
12548: @cindex system documentation, core words
12549:
12550: @menu
12551: * core-idef:: Implementation Defined Options
12552: * core-ambcond:: Ambiguous Conditions
12553: * core-other:: Other System Documentation
12554: @end menu
12555:
12556: @c ---------------------------------------------------------------------
12557: @node core-idef, core-ambcond, The Core Words, The Core Words
12558: @subsection Implementation Defined Options
12559: @c ---------------------------------------------------------------------
12560: @cindex core words, implementation-defined options
12561: @cindex implementation-defined options, core words
12562:
12563:
12564: @table @i
12565: @item (Cell) aligned addresses:
12566: @cindex cell-aligned addresses
12567: @cindex aligned addresses
12568: processor-dependent. Gforth's alignment words perform natural alignment
12569: (e.g., an address aligned for a datum of size 8 is divisible by
12570: 8). Unaligned accesses usually result in a @code{-23 THROW}.
12571:
12572: @item @code{EMIT} and non-graphic characters:
12573: @cindex @code{EMIT} and non-graphic characters
12574: @cindex non-graphic characters and @code{EMIT}
12575: The character is output using the C library function (actually, macro)
12576: @code{putc}.
12577:
12578: @item character editing of @code{ACCEPT} and @code{EXPECT}:
12579: @cindex character editing of @code{ACCEPT} and @code{EXPECT}
12580: @cindex editing in @code{ACCEPT} and @code{EXPECT}
12581: @cindex @code{ACCEPT}, editing
12582: @cindex @code{EXPECT}, editing
12583: This is modeled on the GNU readline library (@pxref{Readline
12584: Interaction, , Command Line Editing, readline, The GNU Readline
12585: Library}) with Emacs-like key bindings. @kbd{Tab} deviates a little by
12586: producing a full word completion every time you type it (instead of
1.28 crook 12587: producing the common prefix of all completions). @xref{Command-line editing}.
1.1 anton 12588:
12589: @item character set:
12590: @cindex character set
12591: The character set of your computer and display device. Gforth is
12592: 8-bit-clean (but some other component in your system may make trouble).
12593:
12594: @item Character-aligned address requirements:
12595: @cindex character-aligned address requirements
12596: installation-dependent. Currently a character is represented by a C
12597: @code{unsigned char}; in the future we might switch to @code{wchar_t}
12598: (Comments on that requested).
12599:
12600: @item character-set extensions and matching of names:
12601: @cindex character-set extensions and matching of names
1.26 crook 12602: @cindex case-sensitivity for name lookup
12603: @cindex name lookup, case-sensitivity
12604: @cindex locale and case-sensitivity
1.21 crook 12605: Any character except the ASCII NUL character can be used in a
1.1 anton 12606: name. Matching is case-insensitive (except in @code{TABLE}s). The
1.47 crook 12607: matching is performed using the C library function @code{strncasecmp}, whose
1.1 anton 12608: function is probably influenced by the locale. E.g., the @code{C} locale
12609: does not know about accents and umlauts, so they are matched
12610: case-sensitively in that locale. For portability reasons it is best to
12611: write programs such that they work in the @code{C} locale. Then one can
12612: use libraries written by a Polish programmer (who might use words
12613: containing ISO Latin-2 encoded characters) and by a French programmer
12614: (ISO Latin-1) in the same program (of course, @code{WORDS} will produce
12615: funny results for some of the words (which ones, depends on the font you
12616: are using)). Also, the locale you prefer may not be available in other
12617: operating systems. Hopefully, Unicode will solve these problems one day.
12618:
12619: @item conditions under which control characters match a space delimiter:
12620: @cindex space delimiters
12621: @cindex control characters as delimiters
12622: If @code{WORD} is called with the space character as a delimiter, all
12623: white-space characters (as identified by the C macro @code{isspace()})
12624: are delimiters. @code{PARSE}, on the other hand, treats space like other
1.44 crook 12625: delimiters. @code{SWORD} treats space like @code{WORD}, but behaves
1.79 anton 12626: like @code{PARSE} otherwise. @code{Name}, which is used by the outer
1.1 anton 12627: interpreter (aka text interpreter) by default, treats all white-space
12628: characters as delimiters.
12629:
1.26 crook 12630: @item format of the control-flow stack:
12631: @cindex control-flow stack, format
12632: The data stack is used as control-flow stack. The size of a control-flow
1.1 anton 12633: stack item in cells is given by the constant @code{cs-item-size}. At the
12634: time of this writing, an item consists of a (pointer to a) locals list
12635: (third), an address in the code (second), and a tag for identifying the
12636: item (TOS). The following tags are used: @code{defstart},
12637: @code{live-orig}, @code{dead-orig}, @code{dest}, @code{do-dest},
12638: @code{scopestart}.
12639:
12640: @item conversion of digits > 35
12641: @cindex digits > 35
12642: The characters @code{[\]^_'} are the digits with the decimal value
12643: 36@minus{}41. There is no way to input many of the larger digits.
12644:
12645: @item display after input terminates in @code{ACCEPT} and @code{EXPECT}:
12646: @cindex @code{EXPECT}, display after end of input
12647: @cindex @code{ACCEPT}, display after end of input
12648: The cursor is moved to the end of the entered string. If the input is
12649: terminated using the @kbd{Return} key, a space is typed.
12650:
12651: @item exception abort sequence of @code{ABORT"}:
12652: @cindex exception abort sequence of @code{ABORT"}
12653: @cindex @code{ABORT"}, exception abort sequence
12654: The error string is stored into the variable @code{"error} and a
12655: @code{-2 throw} is performed.
12656:
12657: @item input line terminator:
12658: @cindex input line terminator
12659: @cindex line terminator on input
1.26 crook 12660: @cindex newline character on input
1.1 anton 12661: For interactive input, @kbd{C-m} (CR) and @kbd{C-j} (LF) terminate
12662: lines. One of these characters is typically produced when you type the
12663: @kbd{Enter} or @kbd{Return} key.
12664:
12665: @item maximum size of a counted string:
12666: @cindex maximum size of a counted string
12667: @cindex counted string, maximum size
12668: @code{s" /counted-string" environment? drop .}. Currently 255 characters
1.79 anton 12669: on all platforms, but this may change.
1.1 anton 12670:
12671: @item maximum size of a parsed string:
12672: @cindex maximum size of a parsed string
12673: @cindex parsed string, maximum size
12674: Given by the constant @code{/line}. Currently 255 characters.
12675:
12676: @item maximum size of a definition name, in characters:
12677: @cindex maximum size of a definition name, in characters
12678: @cindex name, maximum length
12679: 31
12680:
12681: @item maximum string length for @code{ENVIRONMENT?}, in characters:
12682: @cindex maximum string length for @code{ENVIRONMENT?}, in characters
12683: @cindex @code{ENVIRONMENT?} string length, maximum
12684: 31
12685:
12686: @item method of selecting the user input device:
12687: @cindex user input device, method of selecting
12688: The user input device is the standard input. There is currently no way to
12689: change it from within Gforth. However, the input can typically be
12690: redirected in the command line that starts Gforth.
12691:
12692: @item method of selecting the user output device:
12693: @cindex user output device, method of selecting
12694: @code{EMIT} and @code{TYPE} output to the file-id stored in the value
1.10 anton 12695: @code{outfile-id} (@code{stdout} by default). Gforth uses unbuffered
12696: output when the user output device is a terminal, otherwise the output
12697: is buffered.
1.1 anton 12698:
12699: @item methods of dictionary compilation:
12700: What are we expected to document here?
12701:
12702: @item number of bits in one address unit:
12703: @cindex number of bits in one address unit
12704: @cindex address unit, size in bits
12705: @code{s" address-units-bits" environment? drop .}. 8 in all current
1.79 anton 12706: platforms.
1.1 anton 12707:
12708: @item number representation and arithmetic:
12709: @cindex number representation and arithmetic
1.79 anton 12710: Processor-dependent. Binary two's complement on all current platforms.
1.1 anton 12711:
12712: @item ranges for integer types:
12713: @cindex ranges for integer types
12714: @cindex integer types, ranges
12715: Installation-dependent. Make environmental queries for @code{MAX-N},
12716: @code{MAX-U}, @code{MAX-D} and @code{MAX-UD}. The lower bounds for
12717: unsigned (and positive) types is 0. The lower bound for signed types on
12718: two's complement and one's complement machines machines can be computed
12719: by adding 1 to the upper bound.
12720:
12721: @item read-only data space regions:
12722: @cindex read-only data space regions
12723: @cindex data-space, read-only regions
12724: The whole Forth data space is writable.
12725:
12726: @item size of buffer at @code{WORD}:
12727: @cindex size of buffer at @code{WORD}
12728: @cindex @code{WORD} buffer size
12729: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
12730: shared with the pictured numeric output string. If overwriting
12731: @code{PAD} is acceptable, it is as large as the remaining dictionary
12732: space, although only as much can be sensibly used as fits in a counted
12733: string.
12734:
12735: @item size of one cell in address units:
12736: @cindex cell size
12737: @code{1 cells .}.
12738:
12739: @item size of one character in address units:
12740: @cindex char size
1.79 anton 12741: @code{1 chars .}. 1 on all current platforms.
1.1 anton 12742:
12743: @item size of the keyboard terminal buffer:
12744: @cindex size of the keyboard terminal buffer
12745: @cindex terminal buffer, size
12746: Varies. You can determine the size at a specific time using @code{lp@@
12747: tib - .}. It is shared with the locals stack and TIBs of files that
12748: include the current file. You can change the amount of space for TIBs
12749: and locals stack at Gforth startup with the command line option
12750: @code{-l}.
12751:
12752: @item size of the pictured numeric output buffer:
12753: @cindex size of the pictured numeric output buffer
12754: @cindex pictured numeric output buffer, size
12755: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
12756: shared with @code{WORD}.
12757:
12758: @item size of the scratch area returned by @code{PAD}:
12759: @cindex size of the scratch area returned by @code{PAD}
12760: @cindex @code{PAD} size
12761: The remainder of dictionary space. @code{unused pad here - - .}.
12762:
12763: @item system case-sensitivity characteristics:
12764: @cindex case-sensitivity characteristics
1.26 crook 12765: Dictionary searches are case-insensitive (except in
1.1 anton 12766: @code{TABLE}s). However, as explained above under @i{character-set
12767: extensions}, the matching for non-ASCII characters is determined by the
12768: locale you are using. In the default @code{C} locale all non-ASCII
12769: characters are matched case-sensitively.
12770:
12771: @item system prompt:
12772: @cindex system prompt
12773: @cindex prompt
12774: @code{ ok} in interpret state, @code{ compiled} in compile state.
12775:
12776: @item division rounding:
12777: @cindex division rounding
12778: installation dependent. @code{s" floored" environment? drop .}. We leave
12779: the choice to @code{gcc} (what to use for @code{/}) and to you (whether
12780: to use @code{fm/mod}, @code{sm/rem} or simply @code{/}).
12781:
12782: @item values of @code{STATE} when true:
12783: @cindex @code{STATE} values
12784: -1.
12785:
12786: @item values returned after arithmetic overflow:
12787: On two's complement machines, arithmetic is performed modulo
12788: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
12789: arithmetic (with appropriate mapping for signed types). Division by zero
12790: typically results in a @code{-55 throw} (Floating-point unidentified
1.80 anton 12791: fault) or @code{-10 throw} (divide by zero).
1.1 anton 12792:
12793: @item whether the current definition can be found after @t{DOES>}:
12794: @cindex @t{DOES>}, visibility of current definition
12795: No.
12796:
12797: @end table
12798:
12799: @c ---------------------------------------------------------------------
12800: @node core-ambcond, core-other, core-idef, The Core Words
12801: @subsection Ambiguous conditions
12802: @c ---------------------------------------------------------------------
12803: @cindex core words, ambiguous conditions
12804: @cindex ambiguous conditions, core words
12805:
12806: @table @i
12807:
12808: @item a name is neither a word nor a number:
12809: @cindex name not found
1.26 crook 12810: @cindex undefined word
1.80 anton 12811: @code{-13 throw} (Undefined word).
1.1 anton 12812:
12813: @item a definition name exceeds the maximum length allowed:
1.26 crook 12814: @cindex word name too long
1.1 anton 12815: @code{-19 throw} (Word name too long)
12816:
12817: @item addressing a region not inside the various data spaces of the forth system:
12818: @cindex Invalid memory address
1.32 anton 12819: The stacks, code space and header space are accessible. Machine code space is
1.1 anton 12820: typically readable. Accessing other addresses gives results dependent on
12821: the operating system. On decent systems: @code{-9 throw} (Invalid memory
12822: address).
12823:
12824: @item argument type incompatible with parameter:
1.26 crook 12825: @cindex argument type mismatch
1.1 anton 12826: This is usually not caught. Some words perform checks, e.g., the control
12827: flow words, and issue a @code{ABORT"} or @code{-12 THROW} (Argument type
12828: mismatch).
12829:
12830: @item attempting to obtain the execution token of a word with undefined execution semantics:
12831: @cindex Interpreting a compile-only word, for @code{'} etc.
12832: @cindex execution token of words with undefined execution semantics
12833: @code{-14 throw} (Interpreting a compile-only word). In some cases, you
12834: get an execution token for @code{compile-only-error} (which performs a
12835: @code{-14 throw} when executed).
12836:
12837: @item dividing by zero:
12838: @cindex dividing by zero
12839: @cindex floating point unidentified fault, integer division
1.80 anton 12840: On some platforms, this produces a @code{-10 throw} (Division by
1.24 anton 12841: zero); on other systems, this typically results in a @code{-55 throw}
12842: (Floating-point unidentified fault).
1.1 anton 12843:
12844: @item insufficient data stack or return stack space:
12845: @cindex insufficient data stack or return stack space
12846: @cindex stack overflow
1.26 crook 12847: @cindex address alignment exception, stack overflow
1.1 anton 12848: @cindex Invalid memory address, stack overflow
12849: Depending on the operating system, the installation, and the invocation
12850: of Gforth, this is either checked by the memory management hardware, or
1.24 anton 12851: it is not checked. If it is checked, you typically get a @code{-3 throw}
12852: (Stack overflow), @code{-5 throw} (Return stack overflow), or @code{-9
12853: throw} (Invalid memory address) (depending on the platform and how you
12854: achieved the overflow) as soon as the overflow happens. If it is not
12855: checked, overflows typically result in mysterious illegal memory
12856: accesses, producing @code{-9 throw} (Invalid memory address) or
12857: @code{-23 throw} (Address alignment exception); they might also destroy
12858: the internal data structure of @code{ALLOCATE} and friends, resulting in
12859: various errors in these words.
1.1 anton 12860:
12861: @item insufficient space for loop control parameters:
12862: @cindex insufficient space for loop control parameters
1.80 anton 12863: Like other return stack overflows.
1.1 anton 12864:
12865: @item insufficient space in the dictionary:
12866: @cindex insufficient space in the dictionary
12867: @cindex dictionary overflow
1.12 anton 12868: If you try to allot (either directly with @code{allot}, or indirectly
12869: with @code{,}, @code{create} etc.) more memory than available in the
12870: dictionary, you get a @code{-8 throw} (Dictionary overflow). If you try
12871: to access memory beyond the end of the dictionary, the results are
12872: similar to stack overflows.
1.1 anton 12873:
12874: @item interpreting a word with undefined interpretation semantics:
12875: @cindex interpreting a word with undefined interpretation semantics
12876: @cindex Interpreting a compile-only word
12877: For some words, we have defined interpretation semantics. For the
12878: others: @code{-14 throw} (Interpreting a compile-only word).
12879:
12880: @item modifying the contents of the input buffer or a string literal:
12881: @cindex modifying the contents of the input buffer or a string literal
12882: These are located in writable memory and can be modified.
12883:
12884: @item overflow of the pictured numeric output string:
12885: @cindex overflow of the pictured numeric output string
12886: @cindex pictured numeric output string, overflow
1.24 anton 12887: @code{-17 throw} (Pictured numeric ouput string overflow).
1.1 anton 12888:
12889: @item parsed string overflow:
12890: @cindex parsed string overflow
12891: @code{PARSE} cannot overflow. @code{WORD} does not check for overflow.
12892:
12893: @item producing a result out of range:
12894: @cindex result out of range
12895: On two's complement machines, arithmetic is performed modulo
12896: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
12897: arithmetic (with appropriate mapping for signed types). Division by zero
1.24 anton 12898: typically results in a @code{-10 throw} (divide by zero) or @code{-55
12899: throw} (floating point unidentified fault). @code{convert} and
12900: @code{>number} currently overflow silently.
1.1 anton 12901:
12902: @item reading from an empty data or return stack:
12903: @cindex stack empty
12904: @cindex stack underflow
1.24 anton 12905: @cindex return stack underflow
1.1 anton 12906: The data stack is checked by the outer (aka text) interpreter after
12907: every word executed. If it has underflowed, a @code{-4 throw} (Stack
12908: underflow) is performed. Apart from that, stacks may be checked or not,
1.24 anton 12909: depending on operating system, installation, and invocation. If they are
12910: caught by a check, they typically result in @code{-4 throw} (Stack
12911: underflow), @code{-6 throw} (Return stack underflow) or @code{-9 throw}
12912: (Invalid memory address), depending on the platform and which stack
12913: underflows and by how much. Note that even if the system uses checking
12914: (through the MMU), your program may have to underflow by a significant
12915: number of stack items to trigger the reaction (the reason for this is
12916: that the MMU, and therefore the checking, works with a page-size
12917: granularity). If there is no checking, the symptoms resulting from an
12918: underflow are similar to those from an overflow. Unbalanced return
1.80 anton 12919: stack errors can result in a variety of symptoms, including @code{-9 throw}
1.24 anton 12920: (Invalid memory address) and Illegal Instruction (typically @code{-260
12921: throw}).
1.1 anton 12922:
12923: @item unexpected end of the input buffer, resulting in an attempt to use a zero-length string as a name:
12924: @cindex unexpected end of the input buffer
12925: @cindex zero-length string as a name
12926: @cindex Attempt to use zero-length string as a name
12927: @code{Create} and its descendants perform a @code{-16 throw} (Attempt to
12928: use zero-length string as a name). Words like @code{'} probably will not
12929: find what they search. Note that it is possible to create zero-length
12930: names with @code{nextname} (should it not?).
12931:
12932: @item @code{>IN} greater than input buffer:
12933: @cindex @code{>IN} greater than input buffer
12934: The next invocation of a parsing word returns a string with length 0.
12935:
12936: @item @code{RECURSE} appears after @code{DOES>}:
12937: @cindex @code{RECURSE} appears after @code{DOES>}
12938: Compiles a recursive call to the defining word, not to the defined word.
12939:
12940: @item argument input source different than current input source for @code{RESTORE-INPUT}:
12941: @cindex argument input source different than current input source for @code{RESTORE-INPUT}
1.26 crook 12942: @cindex argument type mismatch, @code{RESTORE-INPUT}
1.1 anton 12943: @cindex @code{RESTORE-INPUT}, Argument type mismatch
12944: @code{-12 THROW}. Note that, once an input file is closed (e.g., because
12945: the end of the file was reached), its source-id may be
12946: reused. Therefore, restoring an input source specification referencing a
12947: closed file may lead to unpredictable results instead of a @code{-12
12948: THROW}.
12949:
12950: In the future, Gforth may be able to restore input source specifications
12951: from other than the current input source.
12952:
12953: @item data space containing definitions gets de-allocated:
12954: @cindex data space containing definitions gets de-allocated
12955: Deallocation with @code{allot} is not checked. This typically results in
12956: memory access faults or execution of illegal instructions.
12957:
12958: @item data space read/write with incorrect alignment:
12959: @cindex data space read/write with incorrect alignment
12960: @cindex alignment faults
1.26 crook 12961: @cindex address alignment exception
1.1 anton 12962: Processor-dependent. Typically results in a @code{-23 throw} (Address
1.12 anton 12963: alignment exception). Under Linux-Intel on a 486 or later processor with
1.1 anton 12964: alignment turned on, incorrect alignment results in a @code{-9 throw}
12965: (Invalid memory address). There are reportedly some processors with
1.12 anton 12966: alignment restrictions that do not report violations.
1.1 anton 12967:
12968: @item data space pointer not properly aligned, @code{,}, @code{C,}:
12969: @cindex data space pointer not properly aligned, @code{,}, @code{C,}
12970: Like other alignment errors.
12971:
12972: @item less than u+2 stack items (@code{PICK} and @code{ROLL}):
12973: Like other stack underflows.
12974:
12975: @item loop control parameters not available:
12976: @cindex loop control parameters not available
12977: Not checked. The counted loop words simply assume that the top of return
12978: stack items are loop control parameters and behave accordingly.
12979:
12980: @item most recent definition does not have a name (@code{IMMEDIATE}):
12981: @cindex most recent definition does not have a name (@code{IMMEDIATE})
12982: @cindex last word was headerless
12983: @code{abort" last word was headerless"}.
12984:
12985: @item name not defined by @code{VALUE} used by @code{TO}:
12986: @cindex name not defined by @code{VALUE} used by @code{TO}
12987: @cindex @code{TO} on non-@code{VALUE}s
12988: @cindex Invalid name argument, @code{TO}
12989: @code{-32 throw} (Invalid name argument) (unless name is a local or was
12990: defined by @code{CONSTANT}; in the latter case it just changes the constant).
12991:
12992: @item name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}):
12993: @cindex name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]})
1.26 crook 12994: @cindex undefined word, @code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}
1.1 anton 12995: @code{-13 throw} (Undefined word)
12996:
12997: @item parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN}):
12998: @cindex parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN})
12999: Gforth behaves as if they were of the same type. I.e., you can predict
13000: the behaviour by interpreting all parameters as, e.g., signed.
13001:
13002: @item @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}:
13003: @cindex @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}
13004: Assume @code{: X POSTPONE TO ; IMMEDIATE}. @code{X} performs the
13005: compilation semantics of @code{TO}.
13006:
13007: @item String longer than a counted string returned by @code{WORD}:
1.26 crook 13008: @cindex string longer than a counted string returned by @code{WORD}
1.1 anton 13009: @cindex @code{WORD}, string overflow
13010: Not checked. The string will be ok, but the count will, of course,
13011: contain only the least significant bits of the length.
13012:
13013: @item u greater than or equal to the number of bits in a cell (@code{LSHIFT}, @code{RSHIFT}):
13014: @cindex @code{LSHIFT}, large shift counts
13015: @cindex @code{RSHIFT}, large shift counts
13016: Processor-dependent. Typical behaviours are returning 0 and using only
13017: the low bits of the shift count.
13018:
13019: @item word not defined via @code{CREATE}:
13020: @cindex @code{>BODY} of non-@code{CREATE}d words
13021: @code{>BODY} produces the PFA of the word no matter how it was defined.
13022:
13023: @cindex @code{DOES>} of non-@code{CREATE}d words
13024: @code{DOES>} changes the execution semantics of the last defined word no
13025: matter how it was defined. E.g., @code{CONSTANT DOES>} is equivalent to
13026: @code{CREATE , DOES>}.
13027:
13028: @item words improperly used outside @code{<#} and @code{#>}:
13029: Not checked. As usual, you can expect memory faults.
13030:
13031: @end table
13032:
13033:
13034: @c ---------------------------------------------------------------------
13035: @node core-other, , core-ambcond, The Core Words
13036: @subsection Other system documentation
13037: @c ---------------------------------------------------------------------
13038: @cindex other system documentation, core words
13039: @cindex core words, other system documentation
13040:
13041: @table @i
13042: @item nonstandard words using @code{PAD}:
13043: @cindex @code{PAD} use by nonstandard words
13044: None.
13045:
13046: @item operator's terminal facilities available:
13047: @cindex operator's terminal facilities available
1.80 anton 13048: After processing the OS's command line, Gforth goes into interactive mode,
1.1 anton 13049: and you can give commands to Gforth interactively. The actual facilities
13050: available depend on how you invoke Gforth.
13051:
13052: @item program data space available:
13053: @cindex program data space available
13054: @cindex data space available
13055: @code{UNUSED .} gives the remaining dictionary space. The total
13056: dictionary space can be specified with the @code{-m} switch
13057: (@pxref{Invoking Gforth}) when Gforth starts up.
13058:
13059: @item return stack space available:
13060: @cindex return stack space available
13061: You can compute the total return stack space in cells with
13062: @code{s" RETURN-STACK-CELLS" environment? drop .}. You can specify it at
13063: startup time with the @code{-r} switch (@pxref{Invoking Gforth}).
13064:
13065: @item stack space available:
13066: @cindex stack space available
13067: You can compute the total data stack space in cells with
13068: @code{s" STACK-CELLS" environment? drop .}. You can specify it at
13069: startup time with the @code{-d} switch (@pxref{Invoking Gforth}).
13070:
13071: @item system dictionary space required, in address units:
13072: @cindex system dictionary space required, in address units
13073: Type @code{here forthstart - .} after startup. At the time of this
13074: writing, this gives 80080 (bytes) on a 32-bit system.
13075: @end table
13076:
13077:
13078: @c =====================================================================
13079: @node The optional Block word set, The optional Double Number word set, The Core Words, ANS conformance
13080: @section The optional Block word set
13081: @c =====================================================================
13082: @cindex system documentation, block words
13083: @cindex block words, system documentation
13084:
13085: @menu
13086: * block-idef:: Implementation Defined Options
13087: * block-ambcond:: Ambiguous Conditions
13088: * block-other:: Other System Documentation
13089: @end menu
13090:
13091:
13092: @c ---------------------------------------------------------------------
13093: @node block-idef, block-ambcond, The optional Block word set, The optional Block word set
13094: @subsection Implementation Defined Options
13095: @c ---------------------------------------------------------------------
13096: @cindex implementation-defined options, block words
13097: @cindex block words, implementation-defined options
13098:
13099: @table @i
13100: @item the format for display by @code{LIST}:
13101: @cindex @code{LIST} display format
13102: First the screen number is displayed, then 16 lines of 64 characters,
13103: each line preceded by the line number.
13104:
13105: @item the length of a line affected by @code{\}:
13106: @cindex length of a line affected by @code{\}
13107: @cindex @code{\}, line length in blocks
13108: 64 characters.
13109: @end table
13110:
13111:
13112: @c ---------------------------------------------------------------------
13113: @node block-ambcond, block-other, block-idef, The optional Block word set
13114: @subsection Ambiguous conditions
13115: @c ---------------------------------------------------------------------
13116: @cindex block words, ambiguous conditions
13117: @cindex ambiguous conditions, block words
13118:
13119: @table @i
13120: @item correct block read was not possible:
13121: @cindex block read not possible
13122: Typically results in a @code{throw} of some OS-derived value (between
13123: -512 and -2048). If the blocks file was just not long enough, blanks are
13124: supplied for the missing portion.
13125:
13126: @item I/O exception in block transfer:
13127: @cindex I/O exception in block transfer
13128: @cindex block transfer, I/O exception
13129: Typically results in a @code{throw} of some OS-derived value (between
13130: -512 and -2048).
13131:
13132: @item invalid block number:
13133: @cindex invalid block number
13134: @cindex block number invalid
13135: @code{-35 throw} (Invalid block number)
13136:
13137: @item a program directly alters the contents of @code{BLK}:
13138: @cindex @code{BLK}, altering @code{BLK}
13139: The input stream is switched to that other block, at the same
13140: position. If the storing to @code{BLK} happens when interpreting
13141: non-block input, the system will get quite confused when the block ends.
13142:
13143: @item no current block buffer for @code{UPDATE}:
13144: @cindex @code{UPDATE}, no current block buffer
13145: @code{UPDATE} has no effect.
13146:
13147: @end table
13148:
13149: @c ---------------------------------------------------------------------
13150: @node block-other, , block-ambcond, The optional Block word set
13151: @subsection Other system documentation
13152: @c ---------------------------------------------------------------------
13153: @cindex other system documentation, block words
13154: @cindex block words, other system documentation
13155:
13156: @table @i
13157: @item any restrictions a multiprogramming system places on the use of buffer addresses:
13158: No restrictions (yet).
13159:
13160: @item the number of blocks available for source and data:
13161: depends on your disk space.
13162:
13163: @end table
13164:
13165:
13166: @c =====================================================================
13167: @node The optional Double Number word set, The optional Exception word set, The optional Block word set, ANS conformance
13168: @section The optional Double Number word set
13169: @c =====================================================================
13170: @cindex system documentation, double words
13171: @cindex double words, system documentation
13172:
13173: @menu
13174: * double-ambcond:: Ambiguous Conditions
13175: @end menu
13176:
13177:
13178: @c ---------------------------------------------------------------------
13179: @node double-ambcond, , The optional Double Number word set, The optional Double Number word set
13180: @subsection Ambiguous conditions
13181: @c ---------------------------------------------------------------------
13182: @cindex double words, ambiguous conditions
13183: @cindex ambiguous conditions, double words
13184:
13185: @table @i
1.29 crook 13186: @item @i{d} outside of range of @i{n} in @code{D>S}:
13187: @cindex @code{D>S}, @i{d} out of range of @i{n}
13188: The least significant cell of @i{d} is produced.
1.1 anton 13189:
13190: @end table
13191:
13192:
13193: @c =====================================================================
13194: @node The optional Exception word set, The optional Facility word set, The optional Double Number word set, ANS conformance
13195: @section The optional Exception word set
13196: @c =====================================================================
13197: @cindex system documentation, exception words
13198: @cindex exception words, system documentation
13199:
13200: @menu
13201: * exception-idef:: Implementation Defined Options
13202: @end menu
13203:
13204:
13205: @c ---------------------------------------------------------------------
13206: @node exception-idef, , The optional Exception word set, The optional Exception word set
13207: @subsection Implementation Defined Options
13208: @c ---------------------------------------------------------------------
13209: @cindex implementation-defined options, exception words
13210: @cindex exception words, implementation-defined options
13211:
13212: @table @i
13213: @item @code{THROW}-codes used in the system:
13214: @cindex @code{THROW}-codes used in the system
13215: The codes -256@minus{}-511 are used for reporting signals. The mapping
1.29 crook 13216: from OS signal numbers to throw codes is -256@minus{}@i{signal}. The
1.1 anton 13217: codes -512@minus{}-2047 are used for OS errors (for file and memory
13218: allocation operations). The mapping from OS error numbers to throw codes
13219: is -512@minus{}@code{errno}. One side effect of this mapping is that
13220: undefined OS errors produce a message with a strange number; e.g.,
13221: @code{-1000 THROW} results in @code{Unknown error 488} on my system.
13222: @end table
13223:
13224: @c =====================================================================
13225: @node The optional Facility word set, The optional File-Access word set, The optional Exception word set, ANS conformance
13226: @section The optional Facility word set
13227: @c =====================================================================
13228: @cindex system documentation, facility words
13229: @cindex facility words, system documentation
13230:
13231: @menu
13232: * facility-idef:: Implementation Defined Options
13233: * facility-ambcond:: Ambiguous Conditions
13234: @end menu
13235:
13236:
13237: @c ---------------------------------------------------------------------
13238: @node facility-idef, facility-ambcond, The optional Facility word set, The optional Facility word set
13239: @subsection Implementation Defined Options
13240: @c ---------------------------------------------------------------------
13241: @cindex implementation-defined options, facility words
13242: @cindex facility words, implementation-defined options
13243:
13244: @table @i
13245: @item encoding of keyboard events (@code{EKEY}):
13246: @cindex keyboard events, encoding in @code{EKEY}
13247: @cindex @code{EKEY}, encoding of keyboard events
1.40 anton 13248: Keys corresponding to ASCII characters are encoded as ASCII characters.
1.41 anton 13249: Other keys are encoded with the constants @code{k-left}, @code{k-right},
13250: @code{k-up}, @code{k-down}, @code{k-home}, @code{k-end}, @code{k1},
13251: @code{k2}, @code{k3}, @code{k4}, @code{k5}, @code{k6}, @code{k7},
13252: @code{k8}, @code{k9}, @code{k10}, @code{k11}, @code{k12}.
1.40 anton 13253:
1.1 anton 13254:
13255: @item duration of a system clock tick:
13256: @cindex duration of a system clock tick
13257: @cindex clock tick duration
13258: System dependent. With respect to @code{MS}, the time is specified in
13259: microseconds. How well the OS and the hardware implement this, is
13260: another question.
13261:
13262: @item repeatability to be expected from the execution of @code{MS}:
13263: @cindex repeatability to be expected from the execution of @code{MS}
13264: @cindex @code{MS}, repeatability to be expected
13265: System dependent. On Unix, a lot depends on load. If the system is
13266: lightly loaded, and the delay is short enough that Gforth does not get
13267: swapped out, the performance should be acceptable. Under MS-DOS and
13268: other single-tasking systems, it should be good.
13269:
13270: @end table
13271:
13272:
13273: @c ---------------------------------------------------------------------
13274: @node facility-ambcond, , facility-idef, The optional Facility word set
13275: @subsection Ambiguous conditions
13276: @c ---------------------------------------------------------------------
13277: @cindex facility words, ambiguous conditions
13278: @cindex ambiguous conditions, facility words
13279:
13280: @table @i
13281: @item @code{AT-XY} can't be performed on user output device:
13282: @cindex @code{AT-XY} can't be performed on user output device
13283: Largely terminal dependent. No range checks are done on the arguments.
13284: No errors are reported. You may see some garbage appearing, you may see
13285: simply nothing happen.
13286:
13287: @end table
13288:
13289:
13290: @c =====================================================================
13291: @node The optional File-Access word set, The optional Floating-Point word set, The optional Facility word set, ANS conformance
13292: @section The optional File-Access word set
13293: @c =====================================================================
13294: @cindex system documentation, file words
13295: @cindex file words, system documentation
13296:
13297: @menu
13298: * file-idef:: Implementation Defined Options
13299: * file-ambcond:: Ambiguous Conditions
13300: @end menu
13301:
13302: @c ---------------------------------------------------------------------
13303: @node file-idef, file-ambcond, The optional File-Access word set, The optional File-Access word set
13304: @subsection Implementation Defined Options
13305: @c ---------------------------------------------------------------------
13306: @cindex implementation-defined options, file words
13307: @cindex file words, implementation-defined options
13308:
13309: @table @i
13310: @item file access methods used:
13311: @cindex file access methods used
13312: @code{R/O}, @code{R/W} and @code{BIN} work as you would
13313: expect. @code{W/O} translates into the C file opening mode @code{w} (or
13314: @code{wb}): The file is cleared, if it exists, and created, if it does
13315: not (with both @code{open-file} and @code{create-file}). Under Unix
13316: @code{create-file} creates a file with 666 permissions modified by your
13317: umask.
13318:
13319: @item file exceptions:
13320: @cindex file exceptions
13321: The file words do not raise exceptions (except, perhaps, memory access
13322: faults when you pass illegal addresses or file-ids).
13323:
13324: @item file line terminator:
13325: @cindex file line terminator
13326: System-dependent. Gforth uses C's newline character as line
13327: terminator. What the actual character code(s) of this are is
13328: system-dependent.
13329:
13330: @item file name format:
13331: @cindex file name format
13332: System dependent. Gforth just uses the file name format of your OS.
13333:
13334: @item information returned by @code{FILE-STATUS}:
13335: @cindex @code{FILE-STATUS}, returned information
13336: @code{FILE-STATUS} returns the most powerful file access mode allowed
13337: for the file: Either @code{R/O}, @code{W/O} or @code{R/W}. If the file
13338: cannot be accessed, @code{R/O BIN} is returned. @code{BIN} is applicable
13339: along with the returned mode.
13340:
13341: @item input file state after an exception when including source:
13342: @cindex exception when including source
13343: All files that are left via the exception are closed.
13344:
1.29 crook 13345: @item @i{ior} values and meaning:
13346: @cindex @i{ior} values and meaning
1.68 anton 13347: @cindex @i{wior} values and meaning
1.29 crook 13348: The @i{ior}s returned by the file and memory allocation words are
1.1 anton 13349: intended as throw codes. They typically are in the range
13350: -512@minus{}-2047 of OS errors. The mapping from OS error numbers to
1.29 crook 13351: @i{ior}s is -512@minus{}@i{errno}.
1.1 anton 13352:
13353: @item maximum depth of file input nesting:
13354: @cindex maximum depth of file input nesting
13355: @cindex file input nesting, maximum depth
13356: limited by the amount of return stack, locals/TIB stack, and the number
13357: of open files available. This should not give you troubles.
13358:
13359: @item maximum size of input line:
13360: @cindex maximum size of input line
13361: @cindex input line size, maximum
13362: @code{/line}. Currently 255.
13363:
13364: @item methods of mapping block ranges to files:
13365: @cindex mapping block ranges to files
13366: @cindex files containing blocks
13367: @cindex blocks in files
13368: By default, blocks are accessed in the file @file{blocks.fb} in the
13369: current working directory. The file can be switched with @code{USE}.
13370:
13371: @item number of string buffers provided by @code{S"}:
13372: @cindex @code{S"}, number of string buffers
13373: 1
13374:
13375: @item size of string buffer used by @code{S"}:
13376: @cindex @code{S"}, size of string buffer
13377: @code{/line}. currently 255.
13378:
13379: @end table
13380:
13381: @c ---------------------------------------------------------------------
13382: @node file-ambcond, , file-idef, The optional File-Access word set
13383: @subsection Ambiguous conditions
13384: @c ---------------------------------------------------------------------
13385: @cindex file words, ambiguous conditions
13386: @cindex ambiguous conditions, file words
13387:
13388: @table @i
13389: @item attempting to position a file outside its boundaries:
13390: @cindex @code{REPOSITION-FILE}, outside the file's boundaries
13391: @code{REPOSITION-FILE} is performed as usual: Afterwards,
13392: @code{FILE-POSITION} returns the value given to @code{REPOSITION-FILE}.
13393:
13394: @item attempting to read from file positions not yet written:
13395: @cindex reading from file positions not yet written
13396: End-of-file, i.e., zero characters are read and no error is reported.
13397:
1.29 crook 13398: @item @i{file-id} is invalid (@code{INCLUDE-FILE}):
13399: @cindex @code{INCLUDE-FILE}, @i{file-id} is invalid
1.1 anton 13400: An appropriate exception may be thrown, but a memory fault or other
13401: problem is more probable.
13402:
1.29 crook 13403: @item I/O exception reading or closing @i{file-id} (@code{INCLUDE-FILE}, @code{INCLUDED}):
13404: @cindex @code{INCLUDE-FILE}, I/O exception reading or closing @i{file-id}
13405: @cindex @code{INCLUDED}, I/O exception reading or closing @i{file-id}
13406: The @i{ior} produced by the operation, that discovered the problem, is
1.1 anton 13407: thrown.
13408:
13409: @item named file cannot be opened (@code{INCLUDED}):
13410: @cindex @code{INCLUDED}, named file cannot be opened
1.29 crook 13411: The @i{ior} produced by @code{open-file} is thrown.
1.1 anton 13412:
13413: @item requesting an unmapped block number:
13414: @cindex unmapped block numbers
13415: There are no unmapped legal block numbers. On some operating systems,
13416: writing a block with a large number may overflow the file system and
13417: have an error message as consequence.
13418:
13419: @item using @code{source-id} when @code{blk} is non-zero:
13420: @cindex @code{SOURCE-ID}, behaviour when @code{BLK} is non-zero
13421: @code{source-id} performs its function. Typically it will give the id of
13422: the source which loaded the block. (Better ideas?)
13423:
13424: @end table
13425:
13426:
13427: @c =====================================================================
13428: @node The optional Floating-Point word set, The optional Locals word set, The optional File-Access word set, ANS conformance
13429: @section The optional Floating-Point word set
13430: @c =====================================================================
13431: @cindex system documentation, floating-point words
13432: @cindex floating-point words, system documentation
13433:
13434: @menu
13435: * floating-idef:: Implementation Defined Options
13436: * floating-ambcond:: Ambiguous Conditions
13437: @end menu
13438:
13439:
13440: @c ---------------------------------------------------------------------
13441: @node floating-idef, floating-ambcond, The optional Floating-Point word set, The optional Floating-Point word set
13442: @subsection Implementation Defined Options
13443: @c ---------------------------------------------------------------------
13444: @cindex implementation-defined options, floating-point words
13445: @cindex floating-point words, implementation-defined options
13446:
13447: @table @i
13448: @item format and range of floating point numbers:
13449: @cindex format and range of floating point numbers
13450: @cindex floating point numbers, format and range
13451: System-dependent; the @code{double} type of C.
13452:
1.29 crook 13453: @item results of @code{REPRESENT} when @i{float} is out of range:
13454: @cindex @code{REPRESENT}, results when @i{float} is out of range
1.1 anton 13455: System dependent; @code{REPRESENT} is implemented using the C library
13456: function @code{ecvt()} and inherits its behaviour in this respect.
13457:
13458: @item rounding or truncation of floating-point numbers:
13459: @cindex rounding of floating-point numbers
13460: @cindex truncation of floating-point numbers
13461: @cindex floating-point numbers, rounding or truncation
13462: System dependent; the rounding behaviour is inherited from the hosting C
13463: compiler. IEEE-FP-based (i.e., most) systems by default round to
13464: nearest, and break ties by rounding to even (i.e., such that the last
13465: bit of the mantissa is 0).
13466:
13467: @item size of floating-point stack:
13468: @cindex floating-point stack size
13469: @code{s" FLOATING-STACK" environment? drop .} gives the total size of
13470: the floating-point stack (in floats). You can specify this on startup
13471: with the command-line option @code{-f} (@pxref{Invoking Gforth}).
13472:
13473: @item width of floating-point stack:
13474: @cindex floating-point stack width
13475: @code{1 floats}.
13476:
13477: @end table
13478:
13479:
13480: @c ---------------------------------------------------------------------
13481: @node floating-ambcond, , floating-idef, The optional Floating-Point word set
13482: @subsection Ambiguous conditions
13483: @c ---------------------------------------------------------------------
13484: @cindex floating-point words, ambiguous conditions
13485: @cindex ambiguous conditions, floating-point words
13486:
13487: @table @i
13488: @item @code{df@@} or @code{df!} used with an address that is not double-float aligned:
13489: @cindex @code{df@@} or @code{df!} used with an address that is not double-float aligned
13490: System-dependent. Typically results in a @code{-23 THROW} like other
13491: alignment violations.
13492:
13493: @item @code{f@@} or @code{f!} used with an address that is not float aligned:
13494: @cindex @code{f@@} used with an address that is not float aligned
13495: @cindex @code{f!} used with an address that is not float aligned
13496: System-dependent. Typically results in a @code{-23 THROW} like other
13497: alignment violations.
13498:
13499: @item floating-point result out of range:
13500: @cindex floating-point result out of range
1.80 anton 13501: System-dependent. Can result in a @code{-43 throw} (floating point
13502: overflow), @code{-54 throw} (floating point underflow), @code{-41 throw}
13503: (floating point inexact result), @code{-55 THROW} (Floating-point
1.1 anton 13504: unidentified fault), or can produce a special value representing, e.g.,
13505: Infinity.
13506:
13507: @item @code{sf@@} or @code{sf!} used with an address that is not single-float aligned:
13508: @cindex @code{sf@@} or @code{sf!} used with an address that is not single-float aligned
13509: System-dependent. Typically results in an alignment fault like other
13510: alignment violations.
13511:
1.35 anton 13512: @item @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.}):
13513: @cindex @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.})
1.1 anton 13514: The floating-point number is converted into decimal nonetheless.
13515:
13516: @item Both arguments are equal to zero (@code{FATAN2}):
13517: @cindex @code{FATAN2}, both arguments are equal to zero
13518: System-dependent. @code{FATAN2} is implemented using the C library
13519: function @code{atan2()}.
13520:
1.29 crook 13521: @item Using @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero:
13522: @cindex @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero
13523: System-dependent. Anyway, typically the cos of @i{r1} will not be zero
1.1 anton 13524: because of small errors and the tan will be a very large (or very small)
13525: but finite number.
13526:
1.29 crook 13527: @item @i{d} cannot be presented precisely as a float in @code{D>F}:
13528: @cindex @code{D>F}, @i{d} cannot be presented precisely as a float
1.1 anton 13529: The result is rounded to the nearest float.
13530:
13531: @item dividing by zero:
13532: @cindex dividing by zero, floating-point
13533: @cindex floating-point dividing by zero
13534: @cindex floating-point unidentified fault, FP divide-by-zero
1.80 anton 13535: Platform-dependent; can produce an Infinity, NaN, @code{-42 throw}
13536: (floating point divide by zero) or @code{-55 throw} (Floating-point
13537: unidentified fault).
1.1 anton 13538:
13539: @item exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@}):
13540: @cindex exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@})
13541: System dependent. On IEEE-FP based systems the number is converted into
13542: an infinity.
13543:
1.29 crook 13544: @item @i{float}<1 (@code{FACOSH}):
13545: @cindex @code{FACOSH}, @i{float}<1
1.1 anton 13546: @cindex floating-point unidentified fault, @code{FACOSH}
1.80 anton 13547: Platform-dependent; on IEEE-FP systems typically produces a NaN.
1.1 anton 13548:
1.29 crook 13549: @item @i{float}=<-1 (@code{FLNP1}):
13550: @cindex @code{FLNP1}, @i{float}=<-1
1.1 anton 13551: @cindex floating-point unidentified fault, @code{FLNP1}
1.80 anton 13552: Platform-dependent; on IEEE-FP systems typically produces a NaN (or a
13553: negative infinity for @i{float}=-1).
1.1 anton 13554:
1.29 crook 13555: @item @i{float}=<0 (@code{FLN}, @code{FLOG}):
13556: @cindex @code{FLN}, @i{float}=<0
13557: @cindex @code{FLOG}, @i{float}=<0
1.1 anton 13558: @cindex floating-point unidentified fault, @code{FLN} or @code{FLOG}
1.80 anton 13559: Platform-dependent; on IEEE-FP systems typically produces a NaN (or a
13560: negative infinity for @i{float}=0).
1.1 anton 13561:
1.29 crook 13562: @item @i{float}<0 (@code{FASINH}, @code{FSQRT}):
13563: @cindex @code{FASINH}, @i{float}<0
13564: @cindex @code{FSQRT}, @i{float}<0
1.1 anton 13565: @cindex floating-point unidentified fault, @code{FASINH} or @code{FSQRT}
1.80 anton 13566: Platform-dependent; for @code{fsqrt} this typically gives a NaN, for
13567: @code{fasinh} some platforms produce a NaN, others a number (bug in the
13568: C library?).
1.1 anton 13569:
1.29 crook 13570: @item |@i{float}|>1 (@code{FACOS}, @code{FASIN}, @code{FATANH}):
13571: @cindex @code{FACOS}, |@i{float}|>1
13572: @cindex @code{FASIN}, |@i{float}|>1
13573: @cindex @code{FATANH}, |@i{float}|>1
1.1 anton 13574: @cindex floating-point unidentified fault, @code{FACOS}, @code{FASIN} or @code{FATANH}
1.80 anton 13575: Platform-dependent; IEEE-FP systems typically produce a NaN.
1.1 anton 13576:
1.29 crook 13577: @item integer part of float cannot be represented by @i{d} in @code{F>D}:
13578: @cindex @code{F>D}, integer part of float cannot be represented by @i{d}
1.1 anton 13579: @cindex floating-point unidentified fault, @code{F>D}
1.80 anton 13580: Platform-dependent; typically, some double number is produced and no
13581: error is reported.
1.1 anton 13582:
13583: @item string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.}):
13584: @cindex string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.})
1.80 anton 13585: @code{Precision} characters of the numeric output area are used. If
13586: @code{precision} is too high, these words will smash the data or code
13587: close to @code{here}.
1.1 anton 13588: @end table
13589:
13590: @c =====================================================================
13591: @node The optional Locals word set, The optional Memory-Allocation word set, The optional Floating-Point word set, ANS conformance
13592: @section The optional Locals word set
13593: @c =====================================================================
13594: @cindex system documentation, locals words
13595: @cindex locals words, system documentation
13596:
13597: @menu
13598: * locals-idef:: Implementation Defined Options
13599: * locals-ambcond:: Ambiguous Conditions
13600: @end menu
13601:
13602:
13603: @c ---------------------------------------------------------------------
13604: @node locals-idef, locals-ambcond, The optional Locals word set, The optional Locals word set
13605: @subsection Implementation Defined Options
13606: @c ---------------------------------------------------------------------
13607: @cindex implementation-defined options, locals words
13608: @cindex locals words, implementation-defined options
13609:
13610: @table @i
13611: @item maximum number of locals in a definition:
13612: @cindex maximum number of locals in a definition
13613: @cindex locals, maximum number in a definition
13614: @code{s" #locals" environment? drop .}. Currently 15. This is a lower
13615: bound, e.g., on a 32-bit machine there can be 41 locals of up to 8
13616: characters. The number of locals in a definition is bounded by the size
13617: of locals-buffer, which contains the names of the locals.
13618:
13619: @end table
13620:
13621:
13622: @c ---------------------------------------------------------------------
13623: @node locals-ambcond, , locals-idef, The optional Locals word set
13624: @subsection Ambiguous conditions
13625: @c ---------------------------------------------------------------------
13626: @cindex locals words, ambiguous conditions
13627: @cindex ambiguous conditions, locals words
13628:
13629: @table @i
13630: @item executing a named local in interpretation state:
13631: @cindex local in interpretation state
13632: @cindex Interpreting a compile-only word, for a local
13633: Locals have no interpretation semantics. If you try to perform the
13634: interpretation semantics, you will get a @code{-14 throw} somewhere
13635: (Interpreting a compile-only word). If you perform the compilation
13636: semantics, the locals access will be compiled (irrespective of state).
13637:
1.29 crook 13638: @item @i{name} not defined by @code{VALUE} or @code{(LOCAL)} (@code{TO}):
1.1 anton 13639: @cindex name not defined by @code{VALUE} or @code{(LOCAL)} used by @code{TO}
13640: @cindex @code{TO} on non-@code{VALUE}s and non-locals
13641: @cindex Invalid name argument, @code{TO}
13642: @code{-32 throw} (Invalid name argument)
13643:
13644: @end table
13645:
13646:
13647: @c =====================================================================
13648: @node The optional Memory-Allocation word set, The optional Programming-Tools word set, The optional Locals word set, ANS conformance
13649: @section The optional Memory-Allocation word set
13650: @c =====================================================================
13651: @cindex system documentation, memory-allocation words
13652: @cindex memory-allocation words, system documentation
13653:
13654: @menu
13655: * memory-idef:: Implementation Defined Options
13656: @end menu
13657:
13658:
13659: @c ---------------------------------------------------------------------
13660: @node memory-idef, , The optional Memory-Allocation word set, The optional Memory-Allocation word set
13661: @subsection Implementation Defined Options
13662: @c ---------------------------------------------------------------------
13663: @cindex implementation-defined options, memory-allocation words
13664: @cindex memory-allocation words, implementation-defined options
13665:
13666: @table @i
1.29 crook 13667: @item values and meaning of @i{ior}:
13668: @cindex @i{ior} values and meaning
13669: The @i{ior}s returned by the file and memory allocation words are
1.1 anton 13670: intended as throw codes. They typically are in the range
13671: -512@minus{}-2047 of OS errors. The mapping from OS error numbers to
1.29 crook 13672: @i{ior}s is -512@minus{}@i{errno}.
1.1 anton 13673:
13674: @end table
13675:
13676: @c =====================================================================
13677: @node The optional Programming-Tools word set, The optional Search-Order word set, The optional Memory-Allocation word set, ANS conformance
13678: @section The optional Programming-Tools word set
13679: @c =====================================================================
13680: @cindex system documentation, programming-tools words
13681: @cindex programming-tools words, system documentation
13682:
13683: @menu
13684: * programming-idef:: Implementation Defined Options
13685: * programming-ambcond:: Ambiguous Conditions
13686: @end menu
13687:
13688:
13689: @c ---------------------------------------------------------------------
13690: @node programming-idef, programming-ambcond, The optional Programming-Tools word set, The optional Programming-Tools word set
13691: @subsection Implementation Defined Options
13692: @c ---------------------------------------------------------------------
13693: @cindex implementation-defined options, programming-tools words
13694: @cindex programming-tools words, implementation-defined options
13695:
13696: @table @i
13697: @item ending sequence for input following @code{;CODE} and @code{CODE}:
13698: @cindex @code{;CODE} ending sequence
13699: @cindex @code{CODE} ending sequence
13700: @code{END-CODE}
13701:
13702: @item manner of processing input following @code{;CODE} and @code{CODE}:
13703: @cindex @code{;CODE}, processing input
13704: @cindex @code{CODE}, processing input
13705: The @code{ASSEMBLER} vocabulary is pushed on the search order stack, and
13706: the input is processed by the text interpreter, (starting) in interpret
13707: state.
13708:
13709: @item search order capability for @code{EDITOR} and @code{ASSEMBLER}:
13710: @cindex @code{ASSEMBLER}, search order capability
13711: The ANS Forth search order word set.
13712:
13713: @item source and format of display by @code{SEE}:
13714: @cindex @code{SEE}, source and format of output
1.80 anton 13715: The source for @code{see} is the executable code used by the inner
1.1 anton 13716: interpreter. The current @code{see} tries to output Forth source code
1.80 anton 13717: (and on some platforms, assembly code for primitives) as well as
13718: possible.
1.1 anton 13719:
13720: @end table
13721:
13722: @c ---------------------------------------------------------------------
13723: @node programming-ambcond, , programming-idef, The optional Programming-Tools word set
13724: @subsection Ambiguous conditions
13725: @c ---------------------------------------------------------------------
13726: @cindex programming-tools words, ambiguous conditions
13727: @cindex ambiguous conditions, programming-tools words
13728:
13729: @table @i
13730:
1.21 crook 13731: @item deleting the compilation word list (@code{FORGET}):
13732: @cindex @code{FORGET}, deleting the compilation word list
1.1 anton 13733: Not implemented (yet).
13734:
1.29 crook 13735: @item fewer than @i{u}+1 items on the control-flow stack (@code{CS-PICK}, @code{CS-ROLL}):
13736: @cindex @code{CS-PICK}, fewer than @i{u}+1 items on the control flow-stack
13737: @cindex @code{CS-ROLL}, fewer than @i{u}+1 items on the control flow-stack
1.1 anton 13738: @cindex control-flow stack underflow
13739: This typically results in an @code{abort"} with a descriptive error
13740: message (may change into a @code{-22 throw} (Control structure mismatch)
13741: in the future). You may also get a memory access error. If you are
13742: unlucky, this ambiguous condition is not caught.
13743:
1.29 crook 13744: @item @i{name} can't be found (@code{FORGET}):
13745: @cindex @code{FORGET}, @i{name} can't be found
1.1 anton 13746: Not implemented (yet).
13747:
1.29 crook 13748: @item @i{name} not defined via @code{CREATE}:
13749: @cindex @code{;CODE}, @i{name} not defined via @code{CREATE}
1.1 anton 13750: @code{;CODE} behaves like @code{DOES>} in this respect, i.e., it changes
13751: the execution semantics of the last defined word no matter how it was
13752: defined.
13753:
13754: @item @code{POSTPONE} applied to @code{[IF]}:
13755: @cindex @code{POSTPONE} applied to @code{[IF]}
13756: @cindex @code{[IF]} and @code{POSTPONE}
13757: After defining @code{: X POSTPONE [IF] ; IMMEDIATE}. @code{X} is
13758: equivalent to @code{[IF]}.
13759:
13760: @item reaching the end of the input source before matching @code{[ELSE]} or @code{[THEN]}:
13761: @cindex @code{[IF]}, end of the input source before matching @code{[ELSE]} or @code{[THEN]}
13762: Continue in the same state of conditional compilation in the next outer
13763: input source. Currently there is no warning to the user about this.
13764:
13765: @item removing a needed definition (@code{FORGET}):
13766: @cindex @code{FORGET}, removing a needed definition
13767: Not implemented (yet).
13768:
13769: @end table
13770:
13771:
13772: @c =====================================================================
13773: @node The optional Search-Order word set, , The optional Programming-Tools word set, ANS conformance
13774: @section The optional Search-Order word set
13775: @c =====================================================================
13776: @cindex system documentation, search-order words
13777: @cindex search-order words, system documentation
13778:
13779: @menu
13780: * search-idef:: Implementation Defined Options
13781: * search-ambcond:: Ambiguous Conditions
13782: @end menu
13783:
13784:
13785: @c ---------------------------------------------------------------------
13786: @node search-idef, search-ambcond, The optional Search-Order word set, The optional Search-Order word set
13787: @subsection Implementation Defined Options
13788: @c ---------------------------------------------------------------------
13789: @cindex implementation-defined options, search-order words
13790: @cindex search-order words, implementation-defined options
13791:
13792: @table @i
13793: @item maximum number of word lists in search order:
13794: @cindex maximum number of word lists in search order
13795: @cindex search order, maximum depth
13796: @code{s" wordlists" environment? drop .}. Currently 16.
13797:
13798: @item minimum search order:
13799: @cindex minimum search order
13800: @cindex search order, minimum
13801: @code{root root}.
13802:
13803: @end table
13804:
13805: @c ---------------------------------------------------------------------
13806: @node search-ambcond, , search-idef, The optional Search-Order word set
13807: @subsection Ambiguous conditions
13808: @c ---------------------------------------------------------------------
13809: @cindex search-order words, ambiguous conditions
13810: @cindex ambiguous conditions, search-order words
13811:
13812: @table @i
1.21 crook 13813: @item changing the compilation word list (during compilation):
13814: @cindex changing the compilation word list (during compilation)
13815: @cindex compilation word list, change before definition ends
13816: The word is entered into the word list that was the compilation word list
1.1 anton 13817: at the start of the definition. Any changes to the name field (e.g.,
13818: @code{immediate}) or the code field (e.g., when executing @code{DOES>})
13819: are applied to the latest defined word (as reported by @code{last} or
1.21 crook 13820: @code{lastxt}), if possible, irrespective of the compilation word list.
1.1 anton 13821:
13822: @item search order empty (@code{previous}):
13823: @cindex @code{previous}, search order empty
1.26 crook 13824: @cindex vocstack empty, @code{previous}
1.1 anton 13825: @code{abort" Vocstack empty"}.
13826:
13827: @item too many word lists in search order (@code{also}):
13828: @cindex @code{also}, too many word lists in search order
1.26 crook 13829: @cindex vocstack full, @code{also}
1.1 anton 13830: @code{abort" Vocstack full"}.
13831:
13832: @end table
13833:
13834: @c ***************************************************************
1.65 anton 13835: @node Standard vs Extensions, Model, ANS conformance, Top
13836: @chapter Should I use Gforth extensions?
13837: @cindex Gforth extensions
13838:
13839: As you read through the rest of this manual, you will see documentation
13840: for @i{Standard} words, and documentation for some appealing Gforth
13841: @i{extensions}. You might ask yourself the question: @i{``Should I
13842: restrict myself to the standard, or should I use the extensions?''}
13843:
13844: The answer depends on the goals you have for the program you are working
13845: on:
13846:
13847: @itemize @bullet
13848:
13849: @item Is it just for yourself or do you want to share it with others?
13850:
13851: @item
13852: If you want to share it, do the others all use Gforth?
13853:
13854: @item
13855: If it is just for yourself, do you want to restrict yourself to Gforth?
13856:
13857: @end itemize
13858:
13859: If restricting the program to Gforth is ok, then there is no reason not
13860: to use extensions. It is still a good idea to keep to the standard
13861: where it is easy, in case you want to reuse these parts in another
13862: program that you want to be portable.
13863:
13864: If you want to be able to port the program to other Forth systems, there
13865: are the following points to consider:
13866:
13867: @itemize @bullet
13868:
13869: @item
13870: Most Forth systems that are being maintained support the ANS Forth
13871: standard. So if your program complies with the standard, it will be
13872: portable among many systems.
13873:
13874: @item
13875: A number of the Gforth extensions can be implemented in ANS Forth using
13876: public-domain files provided in the @file{compat/} directory. These are
13877: mentioned in the text in passing. There is no reason not to use these
13878: extensions, your program will still be ANS Forth compliant; just include
13879: the appropriate compat files with your program.
13880:
13881: @item
13882: The tool @file{ans-report.fs} (@pxref{ANS Report}) makes it easy to
13883: analyse your program and determine what non-Standard words it relies
13884: upon. However, it does not check whether you use standard words in a
13885: non-standard way.
13886:
13887: @item
13888: Some techniques are not standardized by ANS Forth, and are hard or
13889: impossible to implement in a standard way, but can be implemented in
13890: most Forth systems easily, and usually in similar ways (e.g., accessing
13891: word headers). Forth has a rich historical precedent for programmers
13892: taking advantage of implementation-dependent features of their tools
13893: (for example, relying on a knowledge of the dictionary
13894: structure). Sometimes these techniques are necessary to extract every
13895: last bit of performance from the hardware, sometimes they are just a
13896: programming shorthand.
13897:
13898: @item
13899: Does using a Gforth extension save more work than the porting this part
13900: to other Forth systems (if any) will cost?
13901:
13902: @item
13903: Is the additional functionality worth the reduction in portability and
13904: the additional porting problems?
13905:
13906: @end itemize
13907:
13908: In order to perform these consideratios, you need to know what's
13909: standard and what's not. This manual generally states if something is
1.81 anton 13910: non-standard, but the authoritative source is the
13911: @uref{http://www.taygeta.com/forth/dpans.html,standard document}.
1.65 anton 13912: Appendix A of the Standard (@var{Rationale}) provides a valuable insight
13913: into the thought processes of the technical committee.
13914:
13915: Note also that portability between Forth systems is not the only
13916: portability issue; there is also the issue of portability between
13917: different platforms (processor/OS combinations).
13918:
13919: @c ***************************************************************
13920: @node Model, Integrating Gforth, Standard vs Extensions, Top
1.1 anton 13921: @chapter Model
13922:
13923: This chapter has yet to be written. It will contain information, on
13924: which internal structures you can rely.
13925:
13926: @c ***************************************************************
13927: @node Integrating Gforth, Emacs and Gforth, Model, Top
13928: @chapter Integrating Gforth into C programs
13929:
13930: This is not yet implemented.
13931:
13932: Several people like to use Forth as scripting language for applications
13933: that are otherwise written in C, C++, or some other language.
13934:
13935: The Forth system ATLAST provides facilities for embedding it into
13936: applications; unfortunately it has several disadvantages: most
13937: importantly, it is not based on ANS Forth, and it is apparently dead
13938: (i.e., not developed further and not supported). The facilities
1.21 crook 13939: provided by Gforth in this area are inspired by ATLAST's facilities, so
1.1 anton 13940: making the switch should not be hard.
13941:
13942: We also tried to design the interface such that it can easily be
13943: implemented by other Forth systems, so that we may one day arrive at a
13944: standardized interface. Such a standard interface would allow you to
13945: replace the Forth system without having to rewrite C code.
13946:
13947: You embed the Gforth interpreter by linking with the library
13948: @code{libgforth.a} (give the compiler the option @code{-lgforth}). All
13949: global symbols in this library that belong to the interface, have the
13950: prefix @code{forth_}. (Global symbols that are used internally have the
13951: prefix @code{gforth_}).
13952:
13953: You can include the declarations of Forth types and the functions and
13954: variables of the interface with @code{#include <forth.h>}.
13955:
13956: Types.
13957:
13958: Variables.
13959:
13960: Data and FP Stack pointer. Area sizes.
13961:
13962: functions.
13963:
13964: forth_init(imagefile)
13965: forth_evaluate(string) exceptions?
13966: forth_goto(address) (or forth_execute(xt)?)
13967: forth_continue() (a corountining mechanism)
13968:
13969: Adding primitives.
13970:
13971: No checking.
13972:
13973: Signals?
13974:
13975: Accessing the Stacks
13976:
1.26 crook 13977: @c ******************************************************************
1.1 anton 13978: @node Emacs and Gforth, Image Files, Integrating Gforth, Top
13979: @chapter Emacs and Gforth
13980: @cindex Emacs and Gforth
13981:
13982: @cindex @file{gforth.el}
13983: @cindex @file{forth.el}
13984: @cindex Rydqvist, Goran
1.107 dvdkhlng 13985: @cindex Kuehling, David
1.1 anton 13986: @cindex comment editing commands
13987: @cindex @code{\}, editing with Emacs
13988: @cindex debug tracer editing commands
13989: @cindex @code{~~}, removal with Emacs
13990: @cindex Forth mode in Emacs
1.107 dvdkhlng 13991:
1.1 anton 13992: Gforth comes with @file{gforth.el}, an improved version of
13993: @file{forth.el} by Goran Rydqvist (included in the TILE package). The
1.26 crook 13994: improvements are:
13995:
13996: @itemize @bullet
13997: @item
1.107 dvdkhlng 13998: A better handling of indentation.
13999: @item
14000: A custom hilighting engine for Forth-code.
1.26 crook 14001: @item
14002: Comment paragraph filling (@kbd{M-q})
14003: @item
14004: Commenting (@kbd{C-x \}) and uncommenting (@kbd{C-u C-x \}) of regions
14005: @item
14006: Removal of debugging tracers (@kbd{C-x ~}, @pxref{Debugging}).
1.41 anton 14007: @item
14008: Support of the @code{info-lookup} feature for looking up the
14009: documentation of a word.
1.107 dvdkhlng 14010: @item
14011: Support for reading and writing blocks files.
1.26 crook 14012: @end itemize
14013:
1.107 dvdkhlng 14014: To get a basic description of these features, enter Forth mode and
14015: type @kbd{C-h m}.
1.1 anton 14016:
14017: @cindex source location of error or debugging output in Emacs
14018: @cindex error output, finding the source location in Emacs
14019: @cindex debugging output, finding the source location in Emacs
14020: In addition, Gforth supports Emacs quite well: The source code locations
14021: given in error messages, debugging output (from @code{~~}) and failed
14022: assertion messages are in the right format for Emacs' compilation mode
14023: (@pxref{Compilation, , Running Compilations under Emacs, emacs, Emacs
14024: Manual}) so the source location corresponding to an error or other
14025: message is only a few keystrokes away (@kbd{C-x `} for the next error,
14026: @kbd{C-c C-c} for the error under the cursor).
14027:
1.107 dvdkhlng 14028: @cindex viewing the documentation of a word in Emacs
14029: @cindex context-sensitive help
14030: Moreover, for words documented in this manual, you can look up the
14031: glossary entry quickly by using @kbd{C-h TAB}
14032: (@code{info-lookup-symbol}, @pxref{Documentation, ,Documentation
14033: Commands, emacs, Emacs Manual}). This feature requires Emacs 20.3 or
14034: later and does not work for words containing @code{:}.
14035:
14036: @menu
14037: * Installing gforth.el:: Making Emacs aware of Forth.
14038: * Emacs Tags:: Viewing the source of a word in Emacs.
14039: * Hilighting:: Making Forth code look prettier.
14040: * Auto-Indentation:: Customizing auto-indentation.
14041: * Blocks Files:: Reading and writing blocks files.
14042: @end menu
14043:
14044: @c ----------------------------------
1.109 anton 14045: @node Installing gforth.el, Emacs Tags, Emacs and Gforth, Emacs and Gforth
1.107 dvdkhlng 14046: @section Installing gforth.el
14047: @cindex @file{.emacs}
14048: @cindex @file{gforth.el}, installation
14049: To make the features from @file{gforth.el} available in Emacs, add
14050: the following lines to your @file{.emacs} file:
14051:
14052: @example
14053: (autoload 'forth-mode "gforth.el")
14054: (setq auto-mode-alist (cons '("\\.fs\\'" . forth-mode)
14055: auto-mode-alist))
14056: (autoload 'forth-block-mode "gforth.el")
14057: (setq auto-mode-alist (cons '("\\.fb\\'" . forth-block-mode)
14058: auto-mode-alist))
14059: (add-hook 'forth-mode-hook (function (lambda ()
14060: ;; customize variables here:
14061: (setq forth-indent-level 4)
14062: (setq forth-minor-indent-level 2)
14063: (setq forth-hilight-level 3)
14064: ;;; ...
14065: )))
14066: @end example
14067:
14068: @c ----------------------------------
14069: @node Emacs Tags, Hilighting, Installing gforth.el, Emacs and Gforth
14070: @section Emacs Tags
1.1 anton 14071: @cindex @file{TAGS} file
14072: @cindex @file{etags.fs}
14073: @cindex viewing the source of a word in Emacs
1.43 anton 14074: @cindex @code{require}, placement in files
14075: @cindex @code{include}, placement in files
1.107 dvdkhlng 14076: If you @code{require} @file{etags.fs}, a new @file{TAGS} file will be
14077: produced (@pxref{Tags, , Tags Tables, emacs, Emacs Manual}) that
1.1 anton 14078: contains the definitions of all words defined afterwards. You can then
1.107 dvdkhlng 14079: find the source for a word using @kbd{M-.}. Note that Emacs can use
1.1 anton 14080: several tags files at the same time (e.g., one for the Gforth sources
14081: and one for your program, @pxref{Select Tags Table,,Selecting a Tags
14082: Table,emacs, Emacs Manual}). The TAGS file for the preloaded words is
14083: @file{$(datadir)/gforth/$(VERSION)/TAGS} (e.g.,
1.43 anton 14084: @file{/usr/local/share/gforth/0.2.0/TAGS}). To get the best behaviour
14085: with @file{etags.fs}, you should avoid putting definitions both before
14086: and after @code{require} etc., otherwise you will see the same file
14087: visited several times by commands like @code{tags-search}.
1.1 anton 14088:
1.107 dvdkhlng 14089: @c ----------------------------------
14090: @node Hilighting, Auto-Indentation, Emacs Tags, Emacs and Gforth
14091: @section Hilighting
14092: @cindex hilighting Forth code in Emacs
14093: @cindex highlighting Forth code in Emacs
14094: @file{gforth.el} comes with a custom source hilighting engine. When
14095: you open a file in @code{forth-mode}, it will be completely parsed,
14096: assigning faces to keywords, comments, strings etc. While you edit
14097: the file, modified regions get parsed and updated on-the-fly.
14098:
14099: Use the variable `forth-hilight-level' to change the level of
14100: decoration from 0 (no hilighting at all) to 3 (the default). Even if
14101: you set the hilighting level to 0, the parser will still work in the
14102: background, collecting information about whether regions of text are
14103: ``compiled'' or ``interpreted''. Those information are required for
14104: auto-indentation to work properly. Set `forth-disable-parser' to
14105: non-nil if your computer is too slow to handle parsing. This will
14106: have an impact on the smartness of the auto-indentation engine,
14107: though.
14108:
14109: Sometimes Forth sources define new features that should be hilighted,
14110: new control structures, defining-words etc. You can use the variable
14111: `forth-custom-words' to make @code{forth-mode} hilight additional
14112: words and constructs. See the docstring of `forth-words' for details
14113: (in Emacs, type @kbd{C-h v forth-words}).
14114:
14115: `forth-custom-words' is meant to be customized in your
14116: @file{.emacs} file. To customize hilighing in a file-specific manner,
14117: set `forth-local-words' in a local-variables section at the end of
14118: your source file (@pxref{Local Variables in Files,, Variables, emacs, Emacs Manual}).
14119:
14120: Example:
14121: @example
14122: 0 [IF]
14123: Local Variables:
14124: forth-local-words:
14125: ((("t:") definition-starter (font-lock-keyword-face . 1)
14126: "[ \t\n]" t name (font-lock-function-name-face . 3))
14127: ((";t") definition-ender (font-lock-keyword-face . 1)))
14128: End:
14129: [THEN]
14130: @end example
14131:
14132: @c ----------------------------------
14133: @node Auto-Indentation, Blocks Files, Hilighting, Emacs and Gforth
14134: @section Auto-Indentation
14135: @cindex auto-indentation of Forth code in Emacs
14136: @cindex indentation of Forth code in Emacs
14137: @code{forth-mode} automatically tries to indent lines in a smart way,
14138: whenever you type @key{TAB} or break a line with @kbd{C-m}.
14139:
14140: Simple customization can be achieved by setting
14141: `forth-indent-level' and `forth-minor-indent-level' in your
14142: @file{.emacs} file. For historical reasons @file{gforth.el} indents
14143: per default by multiples of 4 columns. To use the more traditional
14144: 3-column indentation, add the following lines to your @file{.emacs}:
14145:
14146: @example
14147: (add-hook 'forth-mode-hook (function (lambda ()
14148: ;; customize variables here:
14149: (setq forth-indent-level 3)
14150: (setq forth-minor-indent-level 1)
14151: )))
14152: @end example
14153:
14154: If you want indentation to recognize non-default words, customize it
14155: by setting `forth-custom-indent-words' in your @file{.emacs}. See the
14156: docstring of `forth-indent-words' for details (in Emacs, type @kbd{C-h
14157: v forth-indent-words}).
14158:
14159: To customize indentation in a file-specific manner, set
14160: `forth-local-indent-words' in a local-variables section at the end of
14161: your source file (@pxref{Local Variables in Files, Variables,,emacs,
14162: Emacs Manual}).
14163:
14164: Example:
14165: @example
14166: 0 [IF]
14167: Local Variables:
14168: forth-local-indent-words:
14169: ((("t:") (0 . 2) (0 . 2))
14170: ((";t") (-2 . 0) (0 . -2)))
14171: End:
14172: [THEN]
14173: @end example
14174:
14175: @c ----------------------------------
1.109 anton 14176: @node Blocks Files, , Auto-Indentation, Emacs and Gforth
1.107 dvdkhlng 14177: @section Blocks Files
14178: @cindex blocks files, use with Emacs
14179: @code{forth-mode} Autodetects blocks files by checking whether the
14180: length of the first line exceeds 1023 characters. It then tries to
14181: convert the file into normal text format. When you save the file, it
14182: will be written to disk as normal stream-source file.
14183:
14184: If you want to write blocks files, use @code{forth-blocks-mode}. It
14185: inherits all the features from @code{forth-mode}, plus some additions:
1.41 anton 14186:
1.107 dvdkhlng 14187: @itemize @bullet
14188: @item
14189: Files are written to disk in blocks file format.
14190: @item
14191: Screen numbers are displayed in the mode line (enumerated beginning
14192: with the value of `forth-block-base')
14193: @item
14194: Warnings are displayed when lines exceed 64 characters.
14195: @item
14196: The beginning of the currently edited block is marked with an
14197: overlay-arrow.
14198: @end itemize
1.41 anton 14199:
1.107 dvdkhlng 14200: There are some restrictions you should be aware of. When you open a
14201: blocks file that contains tabulator or newline characters, these
14202: characters will be translated into spaces when the file is written
14203: back to disk. If tabs or newlines are encountered during blocks file
14204: reading, an error is output to the echo area. So have a look at the
14205: `*Messages*' buffer, when Emacs' bell rings during reading.
1.1 anton 14206:
1.107 dvdkhlng 14207: Please consult the docstring of @code{forth-blocks-mode} for more
14208: information by typing @kbd{C-h v forth-blocks-mode}).
1.1 anton 14209:
1.26 crook 14210: @c ******************************************************************
1.1 anton 14211: @node Image Files, Engine, Emacs and Gforth, Top
14212: @chapter Image Files
1.26 crook 14213: @cindex image file
14214: @cindex @file{.fi} files
1.1 anton 14215: @cindex precompiled Forth code
14216: @cindex dictionary in persistent form
14217: @cindex persistent form of dictionary
14218:
14219: An image file is a file containing an image of the Forth dictionary,
14220: i.e., compiled Forth code and data residing in the dictionary. By
14221: convention, we use the extension @code{.fi} for image files.
14222:
14223: @menu
1.18 anton 14224: * Image Licensing Issues:: Distribution terms for images.
14225: * Image File Background:: Why have image files?
1.67 anton 14226: * Non-Relocatable Image Files:: don't always work.
1.18 anton 14227: * Data-Relocatable Image Files:: are better.
1.67 anton 14228: * Fully Relocatable Image Files:: better yet.
1.18 anton 14229: * Stack and Dictionary Sizes:: Setting the default sizes for an image.
1.29 crook 14230: * Running Image Files:: @code{gforth -i @i{file}} or @i{file}.
1.18 anton 14231: * Modifying the Startup Sequence:: and turnkey applications.
1.1 anton 14232: @end menu
14233:
1.18 anton 14234: @node Image Licensing Issues, Image File Background, Image Files, Image Files
14235: @section Image Licensing Issues
14236: @cindex license for images
14237: @cindex image license
14238:
14239: An image created with @code{gforthmi} (@pxref{gforthmi}) or
14240: @code{savesystem} (@pxref{Non-Relocatable Image Files}) includes the
14241: original image; i.e., according to copyright law it is a derived work of
14242: the original image.
14243:
14244: Since Gforth is distributed under the GNU GPL, the newly created image
14245: falls under the GNU GPL, too. In particular, this means that if you
14246: distribute the image, you have to make all of the sources for the image
14247: available, including those you wrote. For details see @ref{License, ,
14248: GNU General Public License (Section 3)}.
14249:
14250: If you create an image with @code{cross} (@pxref{cross.fs}), the image
14251: contains only code compiled from the sources you gave it; if none of
14252: these sources is under the GPL, the terms discussed above do not apply
14253: to the image. However, if your image needs an engine (a gforth binary)
14254: that is under the GPL, you should make sure that you distribute both in
14255: a way that is at most a @emph{mere aggregation}, if you don't want the
14256: terms of the GPL to apply to the image.
14257:
14258: @node Image File Background, Non-Relocatable Image Files, Image Licensing Issues, Image Files
1.1 anton 14259: @section Image File Background
14260: @cindex image file background
14261:
1.80 anton 14262: Gforth consists not only of primitives (in the engine), but also of
1.1 anton 14263: definitions written in Forth. Since the Forth compiler itself belongs to
14264: those definitions, it is not possible to start the system with the
1.80 anton 14265: engine and the Forth source alone. Therefore we provide the Forth
1.26 crook 14266: code as an image file in nearly executable form. When Gforth starts up,
14267: a C routine loads the image file into memory, optionally relocates the
14268: addresses, then sets up the memory (stacks etc.) according to
14269: information in the image file, and (finally) starts executing Forth
14270: code.
1.1 anton 14271:
14272: The image file variants represent different compromises between the
14273: goals of making it easy to generate image files and making them
14274: portable.
14275:
14276: @cindex relocation at run-time
1.26 crook 14277: Win32Forth 3.4 and Mitch Bradley's @code{cforth} use relocation at
1.1 anton 14278: run-time. This avoids many of the complications discussed below (image
14279: files are data relocatable without further ado), but costs performance
14280: (one addition per memory access).
14281:
14282: @cindex relocation at load-time
1.26 crook 14283: By contrast, the Gforth loader performs relocation at image load time. The
14284: loader also has to replace tokens that represent primitive calls with the
1.1 anton 14285: appropriate code-field addresses (or code addresses in the case of
14286: direct threading).
14287:
14288: There are three kinds of image files, with different degrees of
14289: relocatability: non-relocatable, data-relocatable, and fully relocatable
14290: image files.
14291:
14292: @cindex image file loader
14293: @cindex relocating loader
14294: @cindex loader for image files
14295: These image file variants have several restrictions in common; they are
14296: caused by the design of the image file loader:
14297:
14298: @itemize @bullet
14299: @item
14300: There is only one segment; in particular, this means, that an image file
14301: cannot represent @code{ALLOCATE}d memory chunks (and pointers to
1.26 crook 14302: them). The contents of the stacks are not represented, either.
1.1 anton 14303:
14304: @item
14305: The only kinds of relocation supported are: adding the same offset to
14306: all cells that represent data addresses; and replacing special tokens
14307: with code addresses or with pieces of machine code.
14308:
14309: If any complex computations involving addresses are performed, the
14310: results cannot be represented in the image file. Several applications that
14311: use such computations come to mind:
14312: @itemize @minus
14313: @item
14314: Hashing addresses (or data structures which contain addresses) for table
14315: lookup. If you use Gforth's @code{table}s or @code{wordlist}s for this
14316: purpose, you will have no problem, because the hash tables are
14317: recomputed automatically when the system is started. If you use your own
14318: hash tables, you will have to do something similar.
14319:
14320: @item
14321: There's a cute implementation of doubly-linked lists that uses
14322: @code{XOR}ed addresses. You could represent such lists as singly-linked
14323: in the image file, and restore the doubly-linked representation on
14324: startup.@footnote{In my opinion, though, you should think thrice before
14325: using a doubly-linked list (whatever implementation).}
14326:
14327: @item
14328: The code addresses of run-time routines like @code{docol:} cannot be
14329: represented in the image file (because their tokens would be replaced by
14330: machine code in direct threaded implementations). As a workaround,
14331: compute these addresses at run-time with @code{>code-address} from the
14332: executions tokens of appropriate words (see the definitions of
1.80 anton 14333: @code{docol:} and friends in @file{kernel/getdoers.fs}).
1.1 anton 14334:
14335: @item
14336: On many architectures addresses are represented in machine code in some
14337: shifted or mangled form. You cannot put @code{CODE} words that contain
14338: absolute addresses in this form in a relocatable image file. Workarounds
14339: are representing the address in some relative form (e.g., relative to
14340: the CFA, which is present in some register), or loading the address from
14341: a place where it is stored in a non-mangled form.
14342: @end itemize
14343: @end itemize
14344:
14345: @node Non-Relocatable Image Files, Data-Relocatable Image Files, Image File Background, Image Files
14346: @section Non-Relocatable Image Files
14347: @cindex non-relocatable image files
1.26 crook 14348: @cindex image file, non-relocatable
1.1 anton 14349:
14350: These files are simple memory dumps of the dictionary. They are specific
14351: to the executable (i.e., @file{gforth} file) they were created
14352: with. What's worse, they are specific to the place on which the
14353: dictionary resided when the image was created. Now, there is no
14354: guarantee that the dictionary will reside at the same place the next
14355: time you start Gforth, so there's no guarantee that a non-relocatable
14356: image will work the next time (Gforth will complain instead of crashing,
14357: though).
14358:
14359: You can create a non-relocatable image file with
14360:
1.44 crook 14361:
1.1 anton 14362: doc-savesystem
14363:
1.44 crook 14364:
1.1 anton 14365: @node Data-Relocatable Image Files, Fully Relocatable Image Files, Non-Relocatable Image Files, Image Files
14366: @section Data-Relocatable Image Files
14367: @cindex data-relocatable image files
1.26 crook 14368: @cindex image file, data-relocatable
1.1 anton 14369:
14370: These files contain relocatable data addresses, but fixed code addresses
14371: (instead of tokens). They are specific to the executable (i.e.,
14372: @file{gforth} file) they were created with. For direct threading on some
14373: architectures (e.g., the i386), data-relocatable images do not work. You
14374: get a data-relocatable image, if you use @file{gforthmi} with a
14375: Gforth binary that is not doubly indirect threaded (@pxref{Fully
14376: Relocatable Image Files}).
14377:
14378: @node Fully Relocatable Image Files, Stack and Dictionary Sizes, Data-Relocatable Image Files, Image Files
14379: @section Fully Relocatable Image Files
14380: @cindex fully relocatable image files
1.26 crook 14381: @cindex image file, fully relocatable
1.1 anton 14382:
14383: @cindex @file{kern*.fi}, relocatability
14384: @cindex @file{gforth.fi}, relocatability
14385: These image files have relocatable data addresses, and tokens for code
14386: addresses. They can be used with different binaries (e.g., with and
14387: without debugging) on the same machine, and even across machines with
14388: the same data formats (byte order, cell size, floating point
14389: format). However, they are usually specific to the version of Gforth
14390: they were created with. The files @file{gforth.fi} and @file{kernl*.fi}
14391: are fully relocatable.
14392:
14393: There are two ways to create a fully relocatable image file:
14394:
14395: @menu
1.29 crook 14396: * gforthmi:: The normal way
1.1 anton 14397: * cross.fs:: The hard way
14398: @end menu
14399:
14400: @node gforthmi, cross.fs, Fully Relocatable Image Files, Fully Relocatable Image Files
14401: @subsection @file{gforthmi}
14402: @cindex @file{comp-i.fs}
14403: @cindex @file{gforthmi}
14404:
14405: You will usually use @file{gforthmi}. If you want to create an
1.29 crook 14406: image @i{file} that contains everything you would load by invoking
14407: Gforth with @code{gforth @i{options}}, you simply say:
1.1 anton 14408: @example
1.29 crook 14409: gforthmi @i{file} @i{options}
1.1 anton 14410: @end example
14411:
14412: E.g., if you want to create an image @file{asm.fi} that has the file
14413: @file{asm.fs} loaded in addition to the usual stuff, you could do it
14414: like this:
14415:
14416: @example
14417: gforthmi asm.fi asm.fs
14418: @end example
14419:
1.27 crook 14420: @file{gforthmi} is implemented as a sh script and works like this: It
14421: produces two non-relocatable images for different addresses and then
14422: compares them. Its output reflects this: first you see the output (if
1.62 crook 14423: any) of the two Gforth invocations that produce the non-relocatable image
1.27 crook 14424: files, then you see the output of the comparing program: It displays the
14425: offset used for data addresses and the offset used for code addresses;
1.1 anton 14426: moreover, for each cell that cannot be represented correctly in the
1.44 crook 14427: image files, it displays a line like this:
1.1 anton 14428:
14429: @example
14430: 78DC BFFFFA50 BFFFFA40
14431: @end example
14432:
14433: This means that at offset $78dc from @code{forthstart}, one input image
14434: contains $bffffa50, and the other contains $bffffa40. Since these cells
14435: cannot be represented correctly in the output image, you should examine
14436: these places in the dictionary and verify that these cells are dead
14437: (i.e., not read before they are written).
1.39 anton 14438:
14439: @cindex --application, @code{gforthmi} option
14440: If you insert the option @code{--application} in front of the image file
14441: name, you will get an image that uses the @code{--appl-image} option
14442: instead of the @code{--image-file} option (@pxref{Invoking
14443: Gforth}). When you execute such an image on Unix (by typing the image
14444: name as command), the Gforth engine will pass all options to the image
14445: instead of trying to interpret them as engine options.
1.1 anton 14446:
1.27 crook 14447: If you type @file{gforthmi} with no arguments, it prints some usage
14448: instructions.
14449:
1.1 anton 14450: @cindex @code{savesystem} during @file{gforthmi}
14451: @cindex @code{bye} during @file{gforthmi}
14452: @cindex doubly indirect threaded code
1.44 crook 14453: @cindex environment variables
14454: @cindex @code{GFORTHD} -- environment variable
14455: @cindex @code{GFORTH} -- environment variable
1.1 anton 14456: @cindex @code{gforth-ditc}
1.29 crook 14457: There are a few wrinkles: After processing the passed @i{options}, the
1.1 anton 14458: words @code{savesystem} and @code{bye} must be visible. A special doubly
14459: indirect threaded version of the @file{gforth} executable is used for
1.62 crook 14460: creating the non-relocatable images; you can pass the exact filename of
1.1 anton 14461: this executable through the environment variable @code{GFORTHD}
14462: (default: @file{gforth-ditc}); if you pass a version that is not doubly
14463: indirect threaded, you will not get a fully relocatable image, but a
1.27 crook 14464: data-relocatable image (because there is no code address offset). The
14465: normal @file{gforth} executable is used for creating the relocatable
14466: image; you can pass the exact filename of this executable through the
14467: environment variable @code{GFORTH}.
1.1 anton 14468:
14469: @node cross.fs, , gforthmi, Fully Relocatable Image Files
14470: @subsection @file{cross.fs}
14471: @cindex @file{cross.fs}
14472: @cindex cross-compiler
14473: @cindex metacompiler
1.47 crook 14474: @cindex target compiler
1.1 anton 14475:
14476: You can also use @code{cross}, a batch compiler that accepts a Forth-like
1.47 crook 14477: programming language (@pxref{Cross Compiler}).
1.1 anton 14478:
1.47 crook 14479: @code{cross} allows you to create image files for machines with
1.1 anton 14480: different data sizes and data formats than the one used for generating
14481: the image file. You can also use it to create an application image that
14482: does not contain a Forth compiler. These features are bought with
14483: restrictions and inconveniences in programming. E.g., addresses have to
14484: be stored in memory with special words (@code{A!}, @code{A,}, etc.) in
14485: order to make the code relocatable.
14486:
14487:
14488: @node Stack and Dictionary Sizes, Running Image Files, Fully Relocatable Image Files, Image Files
14489: @section Stack and Dictionary Sizes
14490: @cindex image file, stack and dictionary sizes
14491: @cindex dictionary size default
14492: @cindex stack size default
14493:
14494: If you invoke Gforth with a command line flag for the size
14495: (@pxref{Invoking Gforth}), the size you specify is stored in the
14496: dictionary. If you save the dictionary with @code{savesystem} or create
14497: an image with @file{gforthmi}, this size will become the default
14498: for the resulting image file. E.g., the following will create a
1.21 crook 14499: fully relocatable version of @file{gforth.fi} with a 1MB dictionary:
1.1 anton 14500:
14501: @example
14502: gforthmi gforth.fi -m 1M
14503: @end example
14504:
14505: In other words, if you want to set the default size for the dictionary
14506: and the stacks of an image, just invoke @file{gforthmi} with the
14507: appropriate options when creating the image.
14508:
14509: @cindex stack size, cache-friendly
14510: Note: For cache-friendly behaviour (i.e., good performance), you should
14511: make the sizes of the stacks modulo, say, 2K, somewhat different. E.g.,
14512: the default stack sizes are: data: 16k (mod 2k=0); fp: 15.5k (mod
14513: 2k=1.5k); return: 15k(mod 2k=1k); locals: 14.5k (mod 2k=0.5k).
14514:
14515: @node Running Image Files, Modifying the Startup Sequence, Stack and Dictionary Sizes, Image Files
14516: @section Running Image Files
14517: @cindex running image files
14518: @cindex invoking image files
14519: @cindex image file invocation
14520:
14521: @cindex -i, invoke image file
14522: @cindex --image file, invoke image file
1.29 crook 14523: You can invoke Gforth with an image file @i{image} instead of the
1.1 anton 14524: default @file{gforth.fi} with the @code{-i} flag (@pxref{Invoking Gforth}):
14525: @example
1.29 crook 14526: gforth -i @i{image}
1.1 anton 14527: @end example
14528:
14529: @cindex executable image file
1.26 crook 14530: @cindex image file, executable
1.1 anton 14531: If your operating system supports starting scripts with a line of the
14532: form @code{#! ...}, you just have to type the image file name to start
14533: Gforth with this image file (note that the file extension @code{.fi} is
1.29 crook 14534: just a convention). I.e., to run Gforth with the image file @i{image},
14535: you can just type @i{image} instead of @code{gforth -i @i{image}}.
1.27 crook 14536: This works because every @code{.fi} file starts with a line of this
14537: format:
14538:
14539: @example
14540: #! /usr/local/bin/gforth-0.4.0 -i
14541: @end example
14542:
14543: The file and pathname for the Gforth engine specified on this line is
14544: the specific Gforth executable that it was built against; i.e. the value
14545: of the environment variable @code{GFORTH} at the time that
14546: @file{gforthmi} was executed.
1.1 anton 14547:
1.27 crook 14548: You can make use of the same shell capability to make a Forth source
14549: file into an executable. For example, if you place this text in a file:
1.26 crook 14550:
14551: @example
14552: #! /usr/local/bin/gforth
14553:
14554: ." Hello, world" CR
14555: bye
14556: @end example
14557:
14558: @noindent
1.27 crook 14559: and then make the file executable (chmod +x in Unix), you can run it
1.26 crook 14560: directly from the command line. The sequence @code{#!} is used in two
14561: ways; firstly, it is recognised as a ``magic sequence'' by the operating
1.29 crook 14562: system@footnote{The Unix kernel actually recognises two types of files:
14563: executable files and files of data, where the data is processed by an
14564: interpreter that is specified on the ``interpreter line'' -- the first
14565: line of the file, starting with the sequence #!. There may be a small
14566: limit (e.g., 32) on the number of characters that may be specified on
14567: the interpreter line.} secondly it is treated as a comment character by
14568: Gforth. Because of the second usage, a space is required between
1.80 anton 14569: @code{#!} and the path to the executable (moreover, some Unixes
14570: require the sequence @code{#! /}).
1.27 crook 14571:
14572: The disadvantage of this latter technique, compared with using
1.80 anton 14573: @file{gforthmi}, is that it is slightly slower; the Forth source code is
14574: compiled on-the-fly, each time the program is invoked.
1.26 crook 14575:
1.1 anton 14576: doc-#!
14577:
1.44 crook 14578:
1.1 anton 14579: @node Modifying the Startup Sequence, , Running Image Files, Image Files
14580: @section Modifying the Startup Sequence
14581: @cindex startup sequence for image file
14582: @cindex image file initialization sequence
14583: @cindex initialization sequence of image file
14584:
14585: You can add your own initialization to the startup sequence through the
1.26 crook 14586: deferred word @code{'cold}. @code{'cold} is invoked just before the
1.80 anton 14587: image-specific command line processing (i.e., loading files and
1.26 crook 14588: evaluating (@code{-e}) strings) starts.
1.1 anton 14589:
14590: A sequence for adding your initialization usually looks like this:
14591:
14592: @example
14593: :noname
14594: Defers 'cold \ do other initialization stuff (e.g., rehashing wordlists)
14595: ... \ your stuff
14596: ; IS 'cold
14597: @end example
14598:
14599: @cindex turnkey image files
1.26 crook 14600: @cindex image file, turnkey applications
1.1 anton 14601: You can make a turnkey image by letting @code{'cold} execute a word
14602: (your turnkey application) that never returns; instead, it exits Gforth
14603: via @code{bye} or @code{throw}.
14604:
14605: @cindex command-line arguments, access
14606: @cindex arguments on the command line, access
14607: You can access the (image-specific) command-line arguments through the
1.26 crook 14608: variables @code{argc} and @code{argv}. @code{arg} provides convenient
1.1 anton 14609: access to @code{argv}.
14610:
1.26 crook 14611: If @code{'cold} exits normally, Gforth processes the command-line
14612: arguments as files to be loaded and strings to be evaluated. Therefore,
14613: @code{'cold} should remove the arguments it has used in this case.
14614:
1.44 crook 14615:
14616:
1.26 crook 14617: doc-'cold
1.1 anton 14618: doc-argc
14619: doc-argv
14620: doc-arg
14621:
14622:
1.44 crook 14623:
1.1 anton 14624: @c ******************************************************************
1.13 pazsan 14625: @node Engine, Binding to System Library, Image Files, Top
1.1 anton 14626: @chapter Engine
14627: @cindex engine
14628: @cindex virtual machine
14629:
1.26 crook 14630: Reading this chapter is not necessary for programming with Gforth. It
1.1 anton 14631: may be helpful for finding your way in the Gforth sources.
14632:
1.109 anton 14633: The ideas in this section have also been published in the following
14634: papers: Bernd Paysan, @cite{ANS fig/GNU/??? Forth} (in German),
14635: Forth-Tagung '93; M. Anton Ertl,
14636: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl93.ps.Z, A
14637: Portable Forth Engine}}, EuroForth '93; M. Anton Ertl,
14638: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl02.ps.gz,
14639: Threaded code variations and optimizations (extended version)}},
14640: Forth-Tagung '02.
1.1 anton 14641:
14642: @menu
14643: * Portability::
14644: * Threading::
14645: * Primitives::
14646: * Performance::
14647: @end menu
14648:
14649: @node Portability, Threading, Engine, Engine
14650: @section Portability
14651: @cindex engine portability
14652:
1.26 crook 14653: An important goal of the Gforth Project is availability across a wide
14654: range of personal machines. fig-Forth, and, to a lesser extent, F83,
14655: achieved this goal by manually coding the engine in assembly language
14656: for several then-popular processors. This approach is very
14657: labor-intensive and the results are short-lived due to progress in
14658: computer architecture.
1.1 anton 14659:
14660: @cindex C, using C for the engine
14661: Others have avoided this problem by coding in C, e.g., Mitch Bradley
14662: (cforth), Mikael Patel (TILE) and Dirk Zoller (pfe). This approach is
14663: particularly popular for UNIX-based Forths due to the large variety of
14664: architectures of UNIX machines. Unfortunately an implementation in C
14665: does not mix well with the goals of efficiency and with using
14666: traditional techniques: Indirect or direct threading cannot be expressed
14667: in C, and switch threading, the fastest technique available in C, is
14668: significantly slower. Another problem with C is that it is very
14669: cumbersome to express double integer arithmetic.
14670:
14671: @cindex GNU C for the engine
14672: @cindex long long
14673: Fortunately, there is a portable language that does not have these
14674: limitations: GNU C, the version of C processed by the GNU C compiler
14675: (@pxref{C Extensions, , Extensions to the C Language Family, gcc.info,
14676: GNU C Manual}). Its labels as values feature (@pxref{Labels as Values, ,
14677: Labels as Values, gcc.info, GNU C Manual}) makes direct and indirect
14678: threading possible, its @code{long long} type (@pxref{Long Long, ,
14679: Double-Word Integers, gcc.info, GNU C Manual}) corresponds to Forth's
1.109 anton 14680: double numbers on many systems. GNU C is freely available on all
1.1 anton 14681: important (and many unimportant) UNIX machines, VMS, 80386s running
14682: MS-DOS, the Amiga, and the Atari ST, so a Forth written in GNU C can run
14683: on all these machines.
14684:
14685: Writing in a portable language has the reputation of producing code that
14686: is slower than assembly. For our Forth engine we repeatedly looked at
14687: the code produced by the compiler and eliminated most compiler-induced
14688: inefficiencies by appropriate changes in the source code.
14689:
14690: @cindex explicit register declarations
14691: @cindex --enable-force-reg, configuration flag
14692: @cindex -DFORCE_REG
14693: However, register allocation cannot be portably influenced by the
14694: programmer, leading to some inefficiencies on register-starved
14695: machines. We use explicit register declarations (@pxref{Explicit Reg
14696: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) to
14697: improve the speed on some machines. They are turned on by using the
14698: configuration flag @code{--enable-force-reg} (@code{gcc} switch
14699: @code{-DFORCE_REG}). Unfortunately, this feature not only depends on the
14700: machine, but also on the compiler version: On some machines some
14701: compiler versions produce incorrect code when certain explicit register
14702: declarations are used. So by default @code{-DFORCE_REG} is not used.
14703:
14704: @node Threading, Primitives, Portability, Engine
14705: @section Threading
14706: @cindex inner interpreter implementation
14707: @cindex threaded code implementation
14708:
14709: @cindex labels as values
14710: GNU C's labels as values extension (available since @code{gcc-2.0},
14711: @pxref{Labels as Values, , Labels as Values, gcc.info, GNU C Manual})
1.29 crook 14712: makes it possible to take the address of @i{label} by writing
14713: @code{&&@i{label}}. This address can then be used in a statement like
14714: @code{goto *@i{address}}. I.e., @code{goto *&&x} is the same as
1.1 anton 14715: @code{goto x}.
14716:
1.26 crook 14717: @cindex @code{NEXT}, indirect threaded
1.1 anton 14718: @cindex indirect threaded inner interpreter
14719: @cindex inner interpreter, indirect threaded
1.26 crook 14720: With this feature an indirect threaded @code{NEXT} looks like:
1.1 anton 14721: @example
14722: cfa = *ip++;
14723: ca = *cfa;
14724: goto *ca;
14725: @end example
14726: @cindex instruction pointer
14727: For those unfamiliar with the names: @code{ip} is the Forth instruction
14728: pointer; the @code{cfa} (code-field address) corresponds to ANS Forths
14729: execution token and points to the code field of the next word to be
14730: executed; The @code{ca} (code address) fetched from there points to some
14731: executable code, e.g., a primitive or the colon definition handler
14732: @code{docol}.
14733:
1.26 crook 14734: @cindex @code{NEXT}, direct threaded
1.1 anton 14735: @cindex direct threaded inner interpreter
14736: @cindex inner interpreter, direct threaded
14737: Direct threading is even simpler:
14738: @example
14739: ca = *ip++;
14740: goto *ca;
14741: @end example
14742:
14743: Of course we have packaged the whole thing neatly in macros called
1.26 crook 14744: @code{NEXT} and @code{NEXT1} (the part of @code{NEXT} after fetching the cfa).
1.1 anton 14745:
14746: @menu
14747: * Scheduling::
14748: * Direct or Indirect Threaded?::
1.109 anton 14749: * Dynamic Superinstructions::
1.1 anton 14750: * DOES>::
14751: @end menu
14752:
14753: @node Scheduling, Direct or Indirect Threaded?, Threading, Threading
14754: @subsection Scheduling
14755: @cindex inner interpreter optimization
14756:
14757: There is a little complication: Pipelined and superscalar processors,
14758: i.e., RISC and some modern CISC machines can process independent
14759: instructions while waiting for the results of an instruction. The
14760: compiler usually reorders (schedules) the instructions in a way that
14761: achieves good usage of these delay slots. However, on our first tries
14762: the compiler did not do well on scheduling primitives. E.g., for
14763: @code{+} implemented as
14764: @example
14765: n=sp[0]+sp[1];
14766: sp++;
14767: sp[0]=n;
14768: NEXT;
14769: @end example
1.81 anton 14770: the @code{NEXT} comes strictly after the other code, i.e., there is
14771: nearly no scheduling. After a little thought the problem becomes clear:
14772: The compiler cannot know that @code{sp} and @code{ip} point to different
1.21 crook 14773: addresses (and the version of @code{gcc} we used would not know it even
14774: if it was possible), so it could not move the load of the cfa above the
14775: store to the TOS. Indeed the pointers could be the same, if code on or
14776: very near the top of stack were executed. In the interest of speed we
14777: chose to forbid this probably unused ``feature'' and helped the compiler
1.81 anton 14778: in scheduling: @code{NEXT} is divided into several parts:
14779: @code{NEXT_P0}, @code{NEXT_P1} and @code{NEXT_P2}). @code{+} now looks
14780: like:
1.1 anton 14781: @example
1.81 anton 14782: NEXT_P0;
1.1 anton 14783: n=sp[0]+sp[1];
14784: sp++;
14785: NEXT_P1;
14786: sp[0]=n;
14787: NEXT_P2;
14788: @end example
14789:
1.81 anton 14790: There are various schemes that distribute the different operations of
14791: NEXT between these parts in several ways; in general, different schemes
14792: perform best on different processors. We use a scheme for most
14793: architectures that performs well for most processors of this
1.109 anton 14794: architecture; in the future we may switch to benchmarking and chosing
1.81 anton 14795: the scheme on installation time.
14796:
1.1 anton 14797:
1.109 anton 14798: @node Direct or Indirect Threaded?, Dynamic Superinstructions, Scheduling, Threading
1.1 anton 14799: @subsection Direct or Indirect Threaded?
14800: @cindex threading, direct or indirect?
14801:
1.109 anton 14802: Threaded forth code consists of references to primitives (simple machine
14803: code routines like @code{+}) and to non-primitives (e.g., colon
14804: definitions, variables, constants); for a specific class of
14805: non-primitives (e.g., variables) there is one code routine (e.g.,
14806: @code{dovar}), but each variable needs a separate reference to its data.
14807:
14808: Traditionally Forth has been implemented as indirect threaded code,
14809: because this allows to use only one cell to reference a non-primitive
14810: (basically you point to the data, and find the code address there).
14811:
14812: @cindex primitive-centric threaded code
14813: However, threaded code in Gforth (since 0.6.0) uses two cells for
14814: non-primitives, one for the code address, and one for the data address;
14815: the data pointer is an immediate argument for the virtual machine
14816: instruction represented by the code address. We call this
14817: @emph{primitive-centric} threaded code, because all code addresses point
14818: to simple primitives. E.g., for a variable, the code address is for
14819: @code{lit} (also used for integer literals like @code{99}).
14820:
14821: Primitive-centric threaded code allows us to use (faster) direct
14822: threading as dispatch method, completely portably (direct threaded code
14823: in Gforth before 0.6.0 required architecture-specific code). It also
14824: eliminates the performance problems related to I-cache consistency that
14825: 386 implementations have with direct threaded code, and allows
14826: additional optimizations.
14827:
14828: @cindex hybrid direct/indirect threaded code
14829: There is a catch, however: the @var{xt} parameter of @code{execute} can
14830: occupy only one cell, so how do we pass non-primitives with their code
14831: @emph{and} data addresses to them? Our answer is to use indirect
14832: threaded dispatch for @code{execute} and other words that use a
14833: single-cell xt. So, normal threaded code in colon definitions uses
14834: direct threading, and @code{execute} and similar words, which dispatch
14835: to xts on the data stack, use indirect threaded code. We call this
14836: @emph{hybrid direct/indirect} threaded code.
14837:
14838: @cindex engines, gforth vs. gforth-fast vs. gforth-itc
14839: @cindex gforth engine
14840: @cindex gforth-fast engine
14841: The engines @command{gforth} and @command{gforth-fast} use hybrid
14842: direct/indirect threaded code. This means that with these engines you
14843: cannot use @code{,} to compile an xt. Instead, you have to use
14844: @code{compile,}.
14845:
14846: @cindex gforth-itc engine
14847: If you want to compile xts with @code{,}, use @command{gforth-itc}. This
14848: engine uses plain old indirect threaded code. It still compiles in a
14849: primitive-centric style, so you cannot use @code{compile,} instead of
14850: @code{,} (e.g., for producing tables of xts with @code{] word1 word2
14851: ... [}. If you want to do that, you have to use @command{gforth-itc}
14852: and execute @code{' , is compile,}. Your program can check if it is
14853: running on a hybrid direct/indirect threaded engine or a pure indirect
14854: threaded engine with @code{threading-method} (@pxref{Threading Words}).
14855:
14856:
14857: @node Dynamic Superinstructions, DOES>, Direct or Indirect Threaded?, Threading
14858: @subsection Dynamic Superinstructions
14859: @cindex Dynamic superinstructions with replication
14860: @cindex Superinstructions
14861: @cindex Replication
14862:
14863: The engines @command{gforth} and @command{gforth-fast} use another
14864: optimization: Dynamic superinstructions with replication. As an
14865: example, consider the following colon definition:
14866:
14867: @example
14868: : squared ( n1 -- n2 )
14869: dup * ;
14870: @end example
14871:
14872: Gforth compiles this into the threaded code sequence
14873:
14874: @example
14875: dup
14876: *
14877: ;s
14878: @end example
14879:
14880: In normal direct threaded code there is a code address occupying one
14881: cell for each of these primitives. Each code address points to a
14882: machine code routine, and the interpreter jumps to this machine code in
14883: order to execute the primitive. The routines for these three
14884: primitives are (in @command{gforth-fast} on the 386):
14885:
14886: @example
14887: Code dup
14888: ( $804B950 ) add esi , # -4 \ $83 $C6 $FC
14889: ( $804B953 ) add ebx , # 4 \ $83 $C3 $4
14890: ( $804B956 ) mov dword ptr 4 [esi] , ecx \ $89 $4E $4
14891: ( $804B959 ) jmp dword ptr FC [ebx] \ $FF $63 $FC
14892: end-code
14893: Code *
14894: ( $804ACC4 ) mov eax , dword ptr 4 [esi] \ $8B $46 $4
14895: ( $804ACC7 ) add esi , # 4 \ $83 $C6 $4
14896: ( $804ACCA ) add ebx , # 4 \ $83 $C3 $4
14897: ( $804ACCD ) imul ecx , eax \ $F $AF $C8
14898: ( $804ACD0 ) jmp dword ptr FC [ebx] \ $FF $63 $FC
14899: end-code
14900: Code ;s
14901: ( $804A693 ) mov eax , dword ptr [edi] \ $8B $7
14902: ( $804A695 ) add edi , # 4 \ $83 $C7 $4
14903: ( $804A698 ) lea ebx , dword ptr 4 [eax] \ $8D $58 $4
14904: ( $804A69B ) jmp dword ptr FC [ebx] \ $FF $63 $FC
14905: end-code
14906: @end example
14907:
14908: With dynamic superinstructions and replication the compiler does not
14909: just lay down the threaded code, but also copies the machine code
14910: fragments, usually without the jump at the end.
14911:
14912: @example
14913: ( $4057D27D ) add esi , # -4 \ $83 $C6 $FC
14914: ( $4057D280 ) add ebx , # 4 \ $83 $C3 $4
14915: ( $4057D283 ) mov dword ptr 4 [esi] , ecx \ $89 $4E $4
14916: ( $4057D286 ) mov eax , dword ptr 4 [esi] \ $8B $46 $4
14917: ( $4057D289 ) add esi , # 4 \ $83 $C6 $4
14918: ( $4057D28C ) add ebx , # 4 \ $83 $C3 $4
14919: ( $4057D28F ) imul ecx , eax \ $F $AF $C8
14920: ( $4057D292 ) mov eax , dword ptr [edi] \ $8B $7
14921: ( $4057D294 ) add edi , # 4 \ $83 $C7 $4
14922: ( $4057D297 ) lea ebx , dword ptr 4 [eax] \ $8D $58 $4
14923: ( $4057D29A ) jmp dword ptr FC [ebx] \ $FF $63 $FC
14924: @end example
14925:
14926: Only when a threaded-code control-flow change happens (e.g., in
14927: @code{;s}), the jump is appended. This optimization eliminates many of
14928: these jumps and makes the rest much more predictable. The speedup
14929: depends on the processor and the application; on the Athlon and Pentium
14930: III this optimization typically produces a speedup by a factor of 2.
14931:
14932: The code addresses in the direct-threaded code are set to point to the
14933: appropriate points in the copied machine code, in this example like
14934: this:
1.1 anton 14935:
1.109 anton 14936: @example
14937: primitive code address
14938: dup $4057D27D
14939: * $4057D286
14940: ;s $4057D292
14941: @end example
14942:
14943: Thus there can be threaded-code jumps to any place in this piece of
14944: code. This also simplifies decompilation quite a bit.
14945:
14946: @cindex --no-dynamic command-line option
14947: @cindex --no-super command-line option
14948: You can disable this optimization with @option{--no-dynamic}. You can
14949: use the copying without eliminating the jumps (i.e., dynamic
14950: replication, but without superinstructions) with @option{--no-super};
14951: this gives the branch prediction benefit alone; the effect on
1.110 anton 14952: performance depends on the CPU; on the Athlon and Pentium III the
14953: speedup is a little less than for dynamic superinstructions with
14954: replication.
14955:
14956: @cindex patching threaded code
14957: One use of these options is if you want to patch the threaded code.
14958: With superinstructions, many of the dispatch jumps are eliminated, so
14959: patching often has no effect. These options preserve all the dispatch
14960: jumps.
1.109 anton 14961:
14962: @cindex --dynamic command-line option
1.110 anton 14963: On some machines dynamic superinstructions are disabled by default,
14964: because it is unsafe on these machines. However, if you feel
14965: adventurous, you can enable it with @option{--dynamic}.
1.109 anton 14966:
14967: @node DOES>, , Dynamic Superinstructions, Threading
1.1 anton 14968: @subsection DOES>
14969: @cindex @code{DOES>} implementation
14970:
1.26 crook 14971: @cindex @code{dodoes} routine
14972: @cindex @code{DOES>}-code
1.1 anton 14973: One of the most complex parts of a Forth engine is @code{dodoes}, i.e.,
14974: the chunk of code executed by every word defined by a
1.109 anton 14975: @code{CREATE}...@code{DOES>} pair; actually with primitive-centric code,
14976: this is only needed if the xt of the word is @code{execute}d. The main
14977: problem here is: How to find the Forth code to be executed, i.e. the
14978: code after the @code{DOES>} (the @code{DOES>}-code)? There are two
14979: solutions:
1.1 anton 14980:
1.21 crook 14981: In fig-Forth the code field points directly to the @code{dodoes} and the
1.109 anton 14982: @code{DOES>}-code address is stored in the cell after the code address
14983: (i.e. at @code{@i{CFA} cell+}). It may seem that this solution is
14984: illegal in the Forth-79 and all later standards, because in fig-Forth
14985: this address lies in the body (which is illegal in these
14986: standards). However, by making the code field larger for all words this
14987: solution becomes legal again. We use this approach. Leaving a cell
14988: unused in most words is a bit wasteful, but on the machines we are
14989: targeting this is hardly a problem.
14990:
1.1 anton 14991:
14992: @node Primitives, Performance, Threading, Engine
14993: @section Primitives
14994: @cindex primitives, implementation
14995: @cindex virtual machine instructions, implementation
14996:
14997: @menu
14998: * Automatic Generation::
14999: * TOS Optimization::
15000: * Produced code::
15001: @end menu
15002:
15003: @node Automatic Generation, TOS Optimization, Primitives, Primitives
15004: @subsection Automatic Generation
15005: @cindex primitives, automatic generation
15006:
15007: @cindex @file{prims2x.fs}
1.109 anton 15008:
1.1 anton 15009: Since the primitives are implemented in a portable language, there is no
15010: longer any need to minimize the number of primitives. On the contrary,
15011: having many primitives has an advantage: speed. In order to reduce the
15012: number of errors in primitives and to make programming them easier, we
1.109 anton 15013: provide a tool, the primitive generator (@file{prims2x.fs} aka Vmgen,
15014: @pxref{Top, Vmgen, Introduction, vmgen, Vmgen}), that automatically
15015: generates most (and sometimes all) of the C code for a primitive from
15016: the stack effect notation. The source for a primitive has the following
15017: form:
1.1 anton 15018:
15019: @cindex primitive source format
15020: @format
1.58 anton 15021: @i{Forth-name} ( @i{stack-effect} ) @i{category} [@i{pronounc.}]
1.29 crook 15022: [@code{""}@i{glossary entry}@code{""}]
15023: @i{C code}
1.1 anton 15024: [@code{:}
1.29 crook 15025: @i{Forth code}]
1.1 anton 15026: @end format
15027:
15028: The items in brackets are optional. The category and glossary fields
15029: are there for generating the documentation, the Forth code is there
15030: for manual implementations on machines without GNU C. E.g., the source
15031: for the primitive @code{+} is:
15032: @example
1.58 anton 15033: + ( n1 n2 -- n ) core plus
1.1 anton 15034: n = n1+n2;
15035: @end example
15036:
15037: This looks like a specification, but in fact @code{n = n1+n2} is C
15038: code. Our primitive generation tool extracts a lot of information from
15039: the stack effect notations@footnote{We use a one-stack notation, even
15040: though we have separate data and floating-point stacks; The separate
15041: notation can be generated easily from the unified notation.}: The number
15042: of items popped from and pushed on the stack, their type, and by what
15043: name they are referred to in the C code. It then generates a C code
15044: prelude and postlude for each primitive. The final C code for @code{+}
15045: looks like this:
15046:
15047: @example
1.46 pazsan 15048: I_plus: /* + ( n1 n2 -- n ) */ /* label, stack effect */
1.1 anton 15049: /* */ /* documentation */
1.81 anton 15050: NAME("+") /* debugging output (with -DDEBUG) */
1.1 anton 15051: @{
15052: DEF_CA /* definition of variable ca (indirect threading) */
15053: Cell n1; /* definitions of variables */
15054: Cell n2;
15055: Cell n;
1.81 anton 15056: NEXT_P0; /* NEXT part 0 */
1.1 anton 15057: n1 = (Cell) sp[1]; /* input */
15058: n2 = (Cell) TOS;
15059: sp += 1; /* stack adjustment */
15060: @{
15061: n = n1+n2; /* C code taken from the source */
15062: @}
15063: NEXT_P1; /* NEXT part 1 */
15064: TOS = (Cell)n; /* output */
15065: NEXT_P2; /* NEXT part 2 */
15066: @}
15067: @end example
15068:
15069: This looks long and inefficient, but the GNU C compiler optimizes quite
15070: well and produces optimal code for @code{+} on, e.g., the R3000 and the
15071: HP RISC machines: Defining the @code{n}s does not produce any code, and
15072: using them as intermediate storage also adds no cost.
15073:
1.26 crook 15074: There are also other optimizations that are not illustrated by this
15075: example: assignments between simple variables are usually for free (copy
1.1 anton 15076: propagation). If one of the stack items is not used by the primitive
15077: (e.g. in @code{drop}), the compiler eliminates the load from the stack
15078: (dead code elimination). On the other hand, there are some things that
15079: the compiler does not do, therefore they are performed by
15080: @file{prims2x.fs}: The compiler does not optimize code away that stores
15081: a stack item to the place where it just came from (e.g., @code{over}).
15082:
15083: While programming a primitive is usually easy, there are a few cases
15084: where the programmer has to take the actions of the generator into
15085: account, most notably @code{?dup}, but also words that do not (always)
1.26 crook 15086: fall through to @code{NEXT}.
1.109 anton 15087:
15088: For more information
1.1 anton 15089:
15090: @node TOS Optimization, Produced code, Automatic Generation, Primitives
15091: @subsection TOS Optimization
15092: @cindex TOS optimization for primitives
15093: @cindex primitives, keeping the TOS in a register
15094:
15095: An important optimization for stack machine emulators, e.g., Forth
15096: engines, is keeping one or more of the top stack items in
1.29 crook 15097: registers. If a word has the stack effect @i{in1}...@i{inx} @code{--}
15098: @i{out1}...@i{outy}, keeping the top @i{n} items in registers
1.1 anton 15099: @itemize @bullet
15100: @item
1.29 crook 15101: is better than keeping @i{n-1} items, if @i{x>=n} and @i{y>=n},
1.1 anton 15102: due to fewer loads from and stores to the stack.
1.29 crook 15103: @item is slower than keeping @i{n-1} items, if @i{x<>y} and @i{x<n} and
15104: @i{y<n}, due to additional moves between registers.
1.1 anton 15105: @end itemize
15106:
15107: @cindex -DUSE_TOS
15108: @cindex -DUSE_NO_TOS
15109: In particular, keeping one item in a register is never a disadvantage,
15110: if there are enough registers. Keeping two items in registers is a
15111: disadvantage for frequent words like @code{?branch}, constants,
15112: variables, literals and @code{i}. Therefore our generator only produces
15113: code that keeps zero or one items in registers. The generated C code
15114: covers both cases; the selection between these alternatives is made at
15115: C-compile time using the switch @code{-DUSE_TOS}. @code{TOS} in the C
15116: code for @code{+} is just a simple variable name in the one-item case,
15117: otherwise it is a macro that expands into @code{sp[0]}. Note that the
15118: GNU C compiler tries to keep simple variables like @code{TOS} in
15119: registers, and it usually succeeds, if there are enough registers.
15120:
15121: @cindex -DUSE_FTOS
15122: @cindex -DUSE_NO_FTOS
15123: The primitive generator performs the TOS optimization for the
15124: floating-point stack, too (@code{-DUSE_FTOS}). For floating-point
15125: operations the benefit of this optimization is even larger:
15126: floating-point operations take quite long on most processors, but can be
15127: performed in parallel with other operations as long as their results are
15128: not used. If the FP-TOS is kept in a register, this works. If
15129: it is kept on the stack, i.e., in memory, the store into memory has to
15130: wait for the result of the floating-point operation, lengthening the
15131: execution time of the primitive considerably.
15132:
15133: The TOS optimization makes the automatic generation of primitives a
15134: bit more complicated. Just replacing all occurrences of @code{sp[0]} by
15135: @code{TOS} is not sufficient. There are some special cases to
15136: consider:
15137: @itemize @bullet
15138: @item In the case of @code{dup ( w -- w w )} the generator must not
15139: eliminate the store to the original location of the item on the stack,
15140: if the TOS optimization is turned on.
15141: @item Primitives with stack effects of the form @code{--}
1.29 crook 15142: @i{out1}...@i{outy} must store the TOS to the stack at the start.
15143: Likewise, primitives with the stack effect @i{in1}...@i{inx} @code{--}
1.1 anton 15144: must load the TOS from the stack at the end. But for the null stack
15145: effect @code{--} no stores or loads should be generated.
15146: @end itemize
15147:
15148: @node Produced code, , TOS Optimization, Primitives
15149: @subsection Produced code
15150: @cindex primitives, assembly code listing
15151:
15152: @cindex @file{engine.s}
15153: To see what assembly code is produced for the primitives on your machine
15154: with your compiler and your flag settings, type @code{make engine.s} and
1.81 anton 15155: look at the resulting file @file{engine.s}. Alternatively, you can also
15156: disassemble the code of primitives with @code{see} on some architectures.
1.1 anton 15157:
15158: @node Performance, , Primitives, Engine
15159: @section Performance
15160: @cindex performance of some Forth interpreters
15161: @cindex engine performance
15162: @cindex benchmarking Forth systems
15163: @cindex Gforth performance
15164:
15165: On RISCs the Gforth engine is very close to optimal; i.e., it is usually
1.112 ! anton 15166: impossible to write a significantly faster threaded-code engine.
1.1 anton 15167:
15168: On register-starved machines like the 386 architecture processors
15169: improvements are possible, because @code{gcc} does not utilize the
15170: registers as well as a human, even with explicit register declarations;
15171: e.g., Bernd Beuster wrote a Forth system fragment in assembly language
15172: and hand-tuned it for the 486; this system is 1.19 times faster on the
15173: Sieve benchmark on a 486DX2/66 than Gforth compiled with
1.40 anton 15174: @code{gcc-2.6.3} with @code{-DFORCE_REG}. The situation has improved
15175: with gcc-2.95 and gforth-0.4.9; now the most important virtual machine
15176: registers fit in real registers (and we can even afford to use the TOS
15177: optimization), resulting in a speedup of 1.14 on the sieve over the
1.112 ! anton 15178: earlier results. And dynamic superinstructions provide another speedup
! 15179: (but only around a factor 1.2 on the 486).
1.1 anton 15180:
15181: @cindex Win32Forth performance
15182: @cindex NT Forth performance
15183: @cindex eforth performance
15184: @cindex ThisForth performance
15185: @cindex PFE performance
15186: @cindex TILE performance
1.81 anton 15187: The potential advantage of assembly language implementations is not
1.112 ! anton 15188: necessarily realized in complete Forth systems: We compared Gforth-0.5.9
1.81 anton 15189: (direct threaded, compiled with @code{gcc-2.95.1} and
15190: @code{-DFORCE_REG}) with Win32Forth 1.2093 (newer versions are
15191: reportedly much faster), LMI's NT Forth (Beta, May 1994) and Eforth
15192: (with and without peephole (aka pinhole) optimization of the threaded
15193: code); all these systems were written in assembly language. We also
15194: compared Gforth with three systems written in C: PFE-0.9.14 (compiled
15195: with @code{gcc-2.6.3} with the default configuration for Linux:
15196: @code{-O2 -fomit-frame-pointer -DUSE_REGS -DUNROLL_NEXT}), ThisForth
15197: Beta (compiled with @code{gcc-2.6.3 -O3 -fomit-frame-pointer}; ThisForth
15198: employs peephole optimization of the threaded code) and TILE (compiled
15199: with @code{make opt}). We benchmarked Gforth, PFE, ThisForth and TILE on
15200: a 486DX2/66 under Linux. Kenneth O'Heskin kindly provided the results
15201: for Win32Forth and NT Forth on a 486DX2/66 with similar memory
15202: performance under Windows NT. Marcel Hendrix ported Eforth to Linux,
15203: then extended it to run the benchmarks, added the peephole optimizer,
15204: ran the benchmarks and reported the results.
1.40 anton 15205:
1.1 anton 15206: We used four small benchmarks: the ubiquitous Sieve; bubble-sorting and
15207: matrix multiplication come from the Stanford integer benchmarks and have
15208: been translated into Forth by Martin Fraeman; we used the versions
15209: included in the TILE Forth package, but with bigger data set sizes; and
15210: a recursive Fibonacci number computation for benchmarking calling
15211: performance. The following table shows the time taken for the benchmarks
15212: scaled by the time taken by Gforth (in other words, it shows the speedup
15213: factor that Gforth achieved over the other systems).
15214:
15215: @example
1.112 ! anton 15216: relative Win32- NT eforth This-
! 15217: time Gforth Forth Forth eforth +opt PFE Forth TILE
! 15218: sieve 1.00 2.16 1.78 2.16 1.32 2.46 4.96 13.37
! 15219: bubble 1.00 1.93 2.07 2.18 1.29 2.21 5.70
! 15220: matmul 1.00 1.92 1.76 1.90 0.96 2.06 5.32
! 15221: fib 1.00 2.32 2.03 1.86 1.31 2.64 4.55 6.54
1.1 anton 15222: @end example
15223:
1.26 crook 15224: You may be quite surprised by the good performance of Gforth when
15225: compared with systems written in assembly language. One important reason
15226: for the disappointing performance of these other systems is probably
15227: that they are not written optimally for the 486 (e.g., they use the
15228: @code{lods} instruction). In addition, Win32Forth uses a comfortable,
15229: but costly method for relocating the Forth image: like @code{cforth}, it
15230: computes the actual addresses at run time, resulting in two address
15231: computations per @code{NEXT} (@pxref{Image File Background}).
15232:
1.1 anton 15233: The speedup of Gforth over PFE, ThisForth and TILE can be easily
15234: explained with the self-imposed restriction of the latter systems to
15235: standard C, which makes efficient threading impossible (however, the
1.4 anton 15236: measured implementation of PFE uses a GNU C extension: @pxref{Global Reg
1.1 anton 15237: Vars, , Defining Global Register Variables, gcc.info, GNU C Manual}).
15238: Moreover, current C compilers have a hard time optimizing other aspects
15239: of the ThisForth and the TILE source.
15240:
1.26 crook 15241: The performance of Gforth on 386 architecture processors varies widely
15242: with the version of @code{gcc} used. E.g., @code{gcc-2.5.8} failed to
15243: allocate any of the virtual machine registers into real machine
15244: registers by itself and would not work correctly with explicit register
1.112 ! anton 15245: declarations, giving a significantly slower engine (on a 486DX2/66
! 15246: running the Sieve) than the one measured above.
1.1 anton 15247:
1.26 crook 15248: Note that there have been several releases of Win32Forth since the
15249: release presented here, so the results presented above may have little
1.40 anton 15250: predictive value for the performance of Win32Forth today (results for
15251: the current release on an i486DX2/66 are welcome).
1.1 anton 15252:
15253: @cindex @file{Benchres}
1.66 anton 15254: In
15255: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl&maierhofer95.ps.gz,
15256: Translating Forth to Efficient C}} by M. Anton Ertl and Martin
1.1 anton 15257: Maierhofer (presented at EuroForth '95), an indirect threaded version of
1.66 anton 15258: Gforth is compared with Win32Forth, NT Forth, PFE, ThisForth, and
15259: several native code systems; that version of Gforth is slower on a 486
1.112 ! anton 15260: than the version used here. You can find a newer version of these
! 15261: measurements at
1.47 crook 15262: @uref{http://www.complang.tuwien.ac.at/forth/performance.html}. You can
1.1 anton 15263: find numbers for Gforth on various machines in @file{Benchres}.
15264:
1.26 crook 15265: @c ******************************************************************
1.13 pazsan 15266: @node Binding to System Library, Cross Compiler, Engine, Top
1.14 pazsan 15267: @chapter Binding to System Library
1.13 pazsan 15268:
15269: @node Cross Compiler, Bugs, Binding to System Library, Top
1.14 pazsan 15270: @chapter Cross Compiler
1.47 crook 15271: @cindex @file{cross.fs}
15272: @cindex cross-compiler
15273: @cindex metacompiler
15274: @cindex target compiler
1.13 pazsan 15275:
1.46 pazsan 15276: The cross compiler is used to bootstrap a Forth kernel. Since Gforth is
15277: mostly written in Forth, including crucial parts like the outer
15278: interpreter and compiler, it needs compiled Forth code to get
15279: started. The cross compiler allows to create new images for other
15280: architectures, even running under another Forth system.
1.13 pazsan 15281:
15282: @menu
1.67 anton 15283: * Using the Cross Compiler::
15284: * How the Cross Compiler Works::
1.13 pazsan 15285: @end menu
15286:
1.21 crook 15287: @node Using the Cross Compiler, How the Cross Compiler Works, Cross Compiler, Cross Compiler
1.14 pazsan 15288: @section Using the Cross Compiler
1.46 pazsan 15289:
15290: The cross compiler uses a language that resembles Forth, but isn't. The
15291: main difference is that you can execute Forth code after definition,
15292: while you usually can't execute the code compiled by cross, because the
15293: code you are compiling is typically for a different computer than the
15294: one you are compiling on.
15295:
1.81 anton 15296: @c anton: This chapter is somewhat different from waht I would expect: I
15297: @c would expect an explanation of the cross language and how to create an
15298: @c application image with it. The section explains some aspects of
15299: @c creating a Gforth kernel.
15300:
1.46 pazsan 15301: The Makefile is already set up to allow you to create kernels for new
15302: architectures with a simple make command. The generic kernels using the
15303: GCC compiled virtual machine are created in the normal build process
15304: with @code{make}. To create a embedded Gforth executable for e.g. the
15305: 8086 processor (running on a DOS machine), type
15306:
15307: @example
15308: make kernl-8086.fi
15309: @end example
15310:
15311: This will use the machine description from the @file{arch/8086}
15312: directory to create a new kernel. A machine file may look like that:
15313:
15314: @example
15315: \ Parameter for target systems 06oct92py
15316:
15317: 4 Constant cell \ cell size in bytes
15318: 2 Constant cell<< \ cell shift to bytes
15319: 5 Constant cell>bit \ cell shift to bits
15320: 8 Constant bits/char \ bits per character
15321: 8 Constant bits/byte \ bits per byte [default: 8]
15322: 8 Constant float \ bytes per float
15323: 8 Constant /maxalign \ maximum alignment in bytes
15324: false Constant bigendian \ byte order
15325: ( true=big, false=little )
15326:
15327: include machpc.fs \ feature list
15328: @end example
15329:
15330: This part is obligatory for the cross compiler itself, the feature list
15331: is used by the kernel to conditionally compile some features in and out,
15332: depending on whether the target supports these features.
15333:
15334: There are some optional features, if you define your own primitives,
15335: have an assembler, or need special, nonstandard preparation to make the
1.81 anton 15336: boot process work. @code{asm-include} includes an assembler,
1.46 pazsan 15337: @code{prims-include} includes primitives, and @code{>boot} prepares for
15338: booting.
15339:
15340: @example
15341: : asm-include ." Include assembler" cr
15342: s" arch/8086/asm.fs" included ;
15343:
15344: : prims-include ." Include primitives" cr
15345: s" arch/8086/prim.fs" included ;
15346:
15347: : >boot ." Prepare booting" cr
15348: s" ' boot >body into-forth 1+ !" evaluate ;
15349: @end example
15350:
15351: These words are used as sort of macro during the cross compilation in
1.81 anton 15352: the file @file{kernel/main.fs}. Instead of using these macros, it would
1.46 pazsan 15353: be possible --- but more complicated --- to write a new kernel project
15354: file, too.
15355:
15356: @file{kernel/main.fs} expects the machine description file name on the
15357: stack; the cross compiler itself (@file{cross.fs}) assumes that either
15358: @code{mach-file} leaves a counted string on the stack, or
15359: @code{machine-file} leaves an address, count pair of the filename on the
15360: stack.
15361:
15362: The feature list is typically controlled using @code{SetValue}, generic
15363: files that are used by several projects can use @code{DefaultValue}
15364: instead. Both functions work like @code{Value}, when the value isn't
15365: defined, but @code{SetValue} works like @code{to} if the value is
15366: defined, and @code{DefaultValue} doesn't set anything, if the value is
15367: defined.
15368:
15369: @example
15370: \ generic mach file for pc gforth 03sep97jaw
15371:
15372: true DefaultValue NIL \ relocating
15373:
15374: >ENVIRON
15375:
15376: true DefaultValue file \ controls the presence of the
15377: \ file access wordset
15378: true DefaultValue OS \ flag to indicate a operating system
15379:
15380: true DefaultValue prims \ true: primitives are c-code
15381:
15382: true DefaultValue floating \ floating point wordset is present
15383:
15384: true DefaultValue glocals \ gforth locals are present
15385: \ will be loaded
15386: true DefaultValue dcomps \ double number comparisons
15387:
15388: true DefaultValue hash \ hashing primitives are loaded/present
15389:
15390: true DefaultValue xconds \ used together with glocals,
15391: \ special conditionals supporting gforths'
15392: \ local variables
15393: true DefaultValue header \ save a header information
15394:
15395: true DefaultValue backtrace \ enables backtrace code
15396:
15397: false DefaultValue ec
15398: false DefaultValue crlf
15399:
15400: cell 2 = [IF] &32 [ELSE] &256 [THEN] KB DefaultValue kernel-size
15401:
15402: &16 KB DefaultValue stack-size
15403: &15 KB &512 + DefaultValue fstack-size
15404: &15 KB DefaultValue rstack-size
15405: &14 KB &512 + DefaultValue lstack-size
15406: @end example
1.13 pazsan 15407:
1.48 anton 15408: @node How the Cross Compiler Works, , Using the Cross Compiler, Cross Compiler
1.14 pazsan 15409: @section How the Cross Compiler Works
1.13 pazsan 15410:
15411: @node Bugs, Origin, Cross Compiler, Top
1.21 crook 15412: @appendix Bugs
1.1 anton 15413: @cindex bug reporting
15414:
1.21 crook 15415: Known bugs are described in the file @file{BUGS} in the Gforth distribution.
1.1 anton 15416:
1.103 anton 15417: If you find a bug, please submit a bug report through
15418: @uref{https://savannah.gnu.org/bugs/?func=addbug&group=gforth}.
1.21 crook 15419:
15420: @itemize @bullet
15421: @item
1.81 anton 15422: A program (or a sequence of keyboard commands) that reproduces the bug.
15423: @item
15424: A description of what you think constitutes the buggy behaviour.
15425: @item
1.21 crook 15426: The Gforth version used (it is announced at the start of an
15427: interactive Gforth session).
15428: @item
15429: The machine and operating system (on Unix
15430: systems @code{uname -a} will report this information).
15431: @item
1.81 anton 15432: The installation options (you can find the configure options at the
15433: start of @file{config.status}) and configuration (@code{configure}
15434: output or @file{config.cache}).
1.21 crook 15435: @item
15436: A complete list of changes (if any) you (or your installer) have made to the
15437: Gforth sources.
15438: @end itemize
1.1 anton 15439:
15440: For a thorough guide on reporting bugs read @ref{Bug Reporting, , How
15441: to Report Bugs, gcc.info, GNU C Manual}.
15442:
15443:
1.21 crook 15444: @node Origin, Forth-related information, Bugs, Top
15445: @appendix Authors and Ancestors of Gforth
1.1 anton 15446:
15447: @section Authors and Contributors
15448: @cindex authors of Gforth
15449: @cindex contributors to Gforth
15450:
15451: The Gforth project was started in mid-1992 by Bernd Paysan and Anton
1.81 anton 15452: Ertl. The third major author was Jens Wilke. Neal Crook contributed a
15453: lot to the manual. Assemblers and disassemblers were contributed by
15454: Andrew McKewan, Christian Pirker, and Bernd Thallner. Lennart Benschop
15455: (who was one of Gforth's first users, in mid-1993) and Stuart Ramsden
15456: inspired us with their continuous feedback. Lennart Benshop contributed
1.1 anton 15457: @file{glosgen.fs}, while Stuart Ramsden has been working on automatic
15458: support for calling C libraries. Helpful comments also came from Paul
15459: Kleinrubatscher, Christian Pirker, Dirk Zoller, Marcel Hendrix, John
1.58 anton 15460: Wavrik, Barrie Stott, Marc de Groot, Jorge Acerada, Bruce Hoyt, and
15461: Robert Epprecht. Since the release of Gforth-0.2.1 there were also
15462: helpful comments from many others; thank you all, sorry for not listing
15463: you here (but digging through my mailbox to extract your names is on my
1.81 anton 15464: to-do list).
1.1 anton 15465:
15466: Gforth also owes a lot to the authors of the tools we used (GCC, CVS,
15467: and autoconf, among others), and to the creators of the Internet: Gforth
1.21 crook 15468: was developed across the Internet, and its authors did not meet
1.20 pazsan 15469: physically for the first 4 years of development.
1.1 anton 15470:
15471: @section Pedigree
1.26 crook 15472: @cindex pedigree of Gforth
1.1 anton 15473:
1.81 anton 15474: Gforth descends from bigFORTH (1993) and fig-Forth. Of course, a
15475: significant part of the design of Gforth was prescribed by ANS Forth.
1.1 anton 15476:
1.20 pazsan 15477: Bernd Paysan wrote bigFORTH, a descendent from TurboForth, an unreleased
1.1 anton 15478: 32 bit native code version of VolksForth for the Atari ST, written
15479: mostly by Dietrich Weineck.
15480:
1.81 anton 15481: VolksForth was written by Klaus Schleisiek, Bernd Pennemann, Georg
15482: Rehfeld and Dietrich Weineck for the C64 (called UltraForth there) in
15483: the mid-80s and ported to the Atari ST in 1986. It descends from F83.
1.1 anton 15484:
15485: Henry Laxen and Mike Perry wrote F83 as a model implementation of the
15486: Forth-83 standard. !! Pedigree? When?
15487:
15488: A team led by Bill Ragsdale implemented fig-Forth on many processors in
15489: 1979. Robert Selzer and Bill Ragsdale developed the original
15490: implementation of fig-Forth for the 6502 based on microForth.
15491:
15492: The principal architect of microForth was Dean Sanderson. microForth was
15493: FORTH, Inc.'s first off-the-shelf product. It was developed in 1976 for
15494: the 1802, and subsequently implemented on the 8080, the 6800 and the
15495: Z80.
15496:
15497: All earlier Forth systems were custom-made, usually by Charles Moore,
15498: who discovered (as he puts it) Forth during the late 60s. The first full
15499: Forth existed in 1971.
15500:
1.81 anton 15501: A part of the information in this section comes from
15502: @cite{@uref{http://www.forth.com/Content/History/History1.htm,The
15503: Evolution of Forth}} by Elizabeth D. Rather, Donald R. Colburn and
15504: Charles H. Moore, presented at the HOPL-II conference and preprinted in
15505: SIGPLAN Notices 28(3), 1993. You can find more historical and
15506: genealogical information about Forth there.
1.1 anton 15507:
1.81 anton 15508: @c ------------------------------------------------------------------
1.21 crook 15509: @node Forth-related information, Word Index, Origin, Top
15510: @appendix Other Forth-related information
15511: @cindex Forth-related information
15512:
1.81 anton 15513: @c anton: I threw most of this stuff out, because it can be found through
15514: @c the FAQ and the FAQ is more likely to be up-to-date.
1.21 crook 15515:
15516: @cindex comp.lang.forth
15517: @cindex frequently asked questions
1.81 anton 15518: There is an active news group (comp.lang.forth) discussing Forth
15519: (including Gforth) and Forth-related issues. Its
15520: @uref{http://www.complang.tuwien.ac.at/forth/faq/faq-general-2.html,FAQs}
15521: (frequently asked questions and their answers) contains a lot of
15522: information on Forth. You should read it before posting to
15523: comp.lang.forth.
1.21 crook 15524:
1.81 anton 15525: The ANS Forth standard is most usable in its
15526: @uref{http://www.taygeta.com/forth/dpans.html, HTML form}.
1.21 crook 15527:
1.81 anton 15528: @c ------------------------------------------------------------------
15529: @node Word Index, Concept Index, Forth-related information, Top
1.1 anton 15530: @unnumbered Word Index
15531:
1.26 crook 15532: This index is a list of Forth words that have ``glossary'' entries
15533: within this manual. Each word is listed with its stack effect and
15534: wordset.
1.1 anton 15535:
15536: @printindex fn
15537:
1.81 anton 15538: @c anton: the name index seems superfluous given the word and concept indices.
15539:
15540: @c @node Name Index, Concept Index, Word Index, Top
15541: @c @unnumbered Name Index
1.41 anton 15542:
1.81 anton 15543: @c This index is a list of Forth words that have ``glossary'' entries
15544: @c within this manual.
1.41 anton 15545:
1.81 anton 15546: @c @printindex ky
1.41 anton 15547:
1.81 anton 15548: @node Concept Index, , Word Index, Top
1.1 anton 15549: @unnumbered Concept and Word Index
15550:
1.26 crook 15551: Not all entries listed in this index are present verbatim in the
15552: text. This index also duplicates, in abbreviated form, all of the words
15553: listed in the Word Index (only the names are listed for the words here).
1.1 anton 15554:
15555: @printindex cp
15556:
15557: @contents
15558: @bye
1.81 anton 15559:
15560:
1.1 anton 15561:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>