Annotation of gforth/doc/gforth.ds, revision 1.111
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
1.47 crook 115: @center This manual is permanently under construction and was last updated on 15-Mar-2000
1.1 anton 116:
117: @comment The following two commands start the copyright page.
118: @page
119: @vskip 0pt plus 1filll
1.108 anton 120: Copyright @copyright{} 1995, 1996, 1997, 1998, 2000, 2003 Free Software Foundation, Inc.
1.1 anton 121:
122: @comment !! Published by ... or You can get a copy of this manual ...
123:
124: Permission is granted to make and distribute verbatim copies of
125: this manual provided the copyright notice and this permission notice
126: are preserved on all copies.
127:
128: Permission is granted to copy and distribute modified versions of this
129: manual under the conditions for verbatim copying, provided also that the
130: sections entitled "Distribution" and "General Public License" are
131: included exactly as in the original, and provided that the entire
132: resulting derived work is distributed under the terms of a permission
133: notice identical to this one.
134:
135: Permission is granted to copy and distribute translations of this manual
136: into another language, under the above conditions for modified versions,
137: except that the sections entitled "Distribution" and "General Public
138: License" may be included in a translation approved by the author instead
139: of in the original English.
140: @end titlepage
141:
142: @node Top, License, (dir), (dir)
1.49 anton 143: @ifnottex
1.1 anton 144: Gforth is a free implementation of ANS Forth available on many
1.11 anton 145: personal machines. This manual corresponds to version @value{VERSION}.
1.49 anton 146: @end ifnottex
1.1 anton 147:
148: @menu
1.21 crook 149: * License:: The GPL
1.26 crook 150: * Goals:: About the Gforth Project
1.29 crook 151: * Gforth Environment:: Starting (and exiting) Gforth
1.48 anton 152: * Tutorial:: Hands-on Forth Tutorial
1.21 crook 153: * Introduction:: An introduction to ANS Forth
1.1 anton 154: * Words:: Forth words available in Gforth
1.24 anton 155: * Error messages:: How to interpret them
1.1 anton 156: * Tools:: Programming tools
157: * ANS conformance:: Implementation-defined options etc.
1.65 anton 158: * Standard vs Extensions:: Should I use extensions?
1.1 anton 159: * Model:: The abstract machine of Gforth
160: * Integrating Gforth:: Forth as scripting language for applications
161: * Emacs and Gforth:: The Gforth Mode
162: * Image Files:: @code{.fi} files contain compiled code
163: * Engine:: The inner interpreter and the primitives
1.24 anton 164: * Binding to System Library::
1.13 pazsan 165: * Cross Compiler:: The Cross Compiler
1.1 anton 166: * Bugs:: How to report them
167: * Origin:: Authors and ancestors of Gforth
1.21 crook 168: * Forth-related information:: Books and places to look on the WWW
1.1 anton 169: * Word Index:: An item for each Forth word
170: * Concept Index:: A menu covering many topics
1.12 anton 171:
1.91 anton 172: @detailmenu
173: --- The Detailed Node Listing ---
1.12 anton 174:
1.29 crook 175: Gforth Environment
176:
1.32 anton 177: * Invoking Gforth:: Getting in
178: * Leaving Gforth:: Getting out
179: * Command-line editing::
1.48 anton 180: * Environment variables:: that affect how Gforth starts up
1.32 anton 181: * Gforth Files:: What gets installed and where
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.26 crook 366:
367: Locals
368:
369: * Gforth locals::
370: * ANS Forth locals::
371:
372: Gforth locals
373:
374: * Where are locals visible by name?::
375: * How long do locals live?::
1.78 anton 376: * Locals programming style::
377: * Locals implementation::
1.26 crook 378:
1.12 anton 379: Structures
380:
381: * Why explicit structure support?::
382: * Structure Usage::
383: * Structure Naming Convention::
384: * Structure Implementation::
385: * Structure Glossary::
386:
387: Object-oriented Forth
388:
1.48 anton 389: * Why object-oriented programming?::
390: * Object-Oriented Terminology::
391: * Objects::
392: * OOF::
393: * Mini-OOF::
1.23 crook 394: * Comparison with other object models::
1.12 anton 395:
1.24 anton 396: The @file{objects.fs} model
1.12 anton 397:
398: * Properties of the Objects model::
399: * Basic Objects Usage::
1.41 anton 400: * The Objects base class::
1.12 anton 401: * Creating objects::
402: * Object-Oriented Programming Style::
403: * Class Binding::
404: * Method conveniences::
405: * Classes and Scoping::
1.41 anton 406: * Dividing classes::
1.12 anton 407: * Object Interfaces::
408: * Objects Implementation::
409: * Objects Glossary::
410:
1.24 anton 411: The @file{oof.fs} model
1.12 anton 412:
1.67 anton 413: * Properties of the OOF model::
414: * Basic OOF Usage::
415: * The OOF base class::
416: * Class Declaration::
417: * Class Implementation::
1.12 anton 418:
1.24 anton 419: The @file{mini-oof.fs} model
1.23 crook 420:
1.48 anton 421: * Basic Mini-OOF Usage::
422: * Mini-OOF Example::
423: * Mini-OOF Implementation::
1.23 crook 424:
1.78 anton 425: Programming Tools
426:
427: * Examining::
428: * Forgetting words::
429: * Debugging:: Simple and quick.
430: * Assertions:: Making your programs self-checking.
431: * Singlestep Debugger:: Executing your program word by word.
432:
433: Assembler and Code Words
434:
435: * Code and ;code::
436: * Common Assembler:: Assembler Syntax
437: * Common Disassembler::
438: * 386 Assembler:: Deviations and special cases
439: * Alpha Assembler:: Deviations and special cases
440: * MIPS assembler:: Deviations and special cases
441: * Other assemblers:: How to write them
442:
1.12 anton 443: Tools
444:
445: * ANS Report:: Report the words used, sorted by wordset.
446:
447: ANS conformance
448:
449: * The Core Words::
450: * The optional Block word set::
451: * The optional Double Number word set::
452: * The optional Exception word set::
453: * The optional Facility word set::
454: * The optional File-Access word set::
455: * The optional Floating-Point word set::
456: * The optional Locals word set::
457: * The optional Memory-Allocation word set::
458: * The optional Programming-Tools word set::
459: * The optional Search-Order word set::
460:
461: The Core Words
462:
463: * core-idef:: Implementation Defined Options
464: * core-ambcond:: Ambiguous Conditions
465: * core-other:: Other System Documentation
466:
467: The optional Block word set
468:
469: * block-idef:: Implementation Defined Options
470: * block-ambcond:: Ambiguous Conditions
471: * block-other:: Other System Documentation
472:
473: The optional Double Number word set
474:
475: * double-ambcond:: Ambiguous Conditions
476:
477: The optional Exception word set
478:
479: * exception-idef:: Implementation Defined Options
480:
481: The optional Facility word set
482:
483: * facility-idef:: Implementation Defined Options
484: * facility-ambcond:: Ambiguous Conditions
485:
486: The optional File-Access word set
487:
488: * file-idef:: Implementation Defined Options
489: * file-ambcond:: Ambiguous Conditions
490:
491: The optional Floating-Point word set
492:
493: * floating-idef:: Implementation Defined Options
494: * floating-ambcond:: Ambiguous Conditions
495:
496: The optional Locals word set
497:
498: * locals-idef:: Implementation Defined Options
499: * locals-ambcond:: Ambiguous Conditions
500:
501: The optional Memory-Allocation word set
502:
503: * memory-idef:: Implementation Defined Options
504:
505: The optional Programming-Tools word set
506:
507: * programming-idef:: Implementation Defined Options
508: * programming-ambcond:: Ambiguous Conditions
509:
510: The optional Search-Order word set
511:
512: * search-idef:: Implementation Defined Options
513: * search-ambcond:: Ambiguous Conditions
514:
1.109 anton 515: Emacs and Gforth
516:
517: * Installing gforth.el:: Making Emacs aware of Forth.
518: * Emacs Tags:: Viewing the source of a word in Emacs.
519: * Hilighting:: Making Forth code look prettier.
520: * Auto-Indentation:: Customizing auto-indentation.
521: * Blocks Files:: Reading and writing blocks files.
522:
1.12 anton 523: Image Files
524:
1.24 anton 525: * Image Licensing Issues:: Distribution terms for images.
526: * Image File Background:: Why have image files?
1.67 anton 527: * Non-Relocatable Image Files:: don't always work.
1.24 anton 528: * Data-Relocatable Image Files:: are better.
1.67 anton 529: * Fully Relocatable Image Files:: better yet.
1.24 anton 530: * Stack and Dictionary Sizes:: Setting the default sizes for an image.
1.32 anton 531: * Running Image Files:: @code{gforth -i @i{file}} or @i{file}.
1.24 anton 532: * Modifying the Startup Sequence:: and turnkey applications.
1.12 anton 533:
534: Fully Relocatable Image Files
535:
1.27 crook 536: * gforthmi:: The normal way
1.12 anton 537: * cross.fs:: The hard way
538:
539: Engine
540:
541: * Portability::
542: * Threading::
543: * Primitives::
544: * Performance::
545:
546: Threading
547:
548: * Scheduling::
549: * Direct or Indirect Threaded?::
1.109 anton 550: * Dynamic Superinstructions::
1.12 anton 551: * DOES>::
552:
553: Primitives
554:
555: * Automatic Generation::
556: * TOS Optimization::
557: * Produced code::
1.13 pazsan 558:
559: Cross Compiler
560:
1.67 anton 561: * Using the Cross Compiler::
562: * How the Cross Compiler Works::
1.13 pazsan 563:
1.24 anton 564: @end detailmenu
1.1 anton 565: @end menu
566:
1.26 crook 567: @node License, Goals, Top, Top
1.1 anton 568: @unnumbered GNU GENERAL PUBLIC LICENSE
569: @center Version 2, June 1991
570:
571: @display
572: Copyright @copyright{} 1989, 1991 Free Software Foundation, Inc.
1.88 anton 573: 59 Temple Place, Suite 330, Boston, MA 02111, USA
1.1 anton 574:
575: Everyone is permitted to copy and distribute verbatim copies
576: of this license document, but changing it is not allowed.
577: @end display
578:
579: @unnumberedsec Preamble
580:
581: The licenses for most software are designed to take away your
582: freedom to share and change it. By contrast, the GNU General Public
583: License is intended to guarantee your freedom to share and change free
584: software---to make sure the software is free for all its users. This
585: General Public License applies to most of the Free Software
586: Foundation's software and to any other program whose authors commit to
587: using it. (Some other Free Software Foundation software is covered by
588: the GNU Library General Public License instead.) You can apply it to
589: your programs, too.
590:
591: When we speak of free software, we are referring to freedom, not
592: price. Our General Public Licenses are designed to make sure that you
593: have the freedom to distribute copies of free software (and charge for
594: this service if you wish), that you receive source code or can get it
595: if you want it, that you can change the software or use pieces of it
596: in new free programs; and that you know you can do these things.
597:
598: To protect your rights, we need to make restrictions that forbid
599: anyone to deny you these rights or to ask you to surrender the rights.
600: These restrictions translate to certain responsibilities for you if you
601: distribute copies of the software, or if you modify it.
602:
603: For example, if you distribute copies of such a program, whether
604: gratis or for a fee, you must give the recipients all the rights that
605: you have. You must make sure that they, too, receive or can get the
606: source code. And you must show them these terms so they know their
607: rights.
608:
609: We protect your rights with two steps: (1) copyright the software, and
610: (2) offer you this license which gives you legal permission to copy,
611: distribute and/or modify the software.
612:
613: Also, for each author's protection and ours, we want to make certain
614: that everyone understands that there is no warranty for this free
615: software. If the software is modified by someone else and passed on, we
616: want its recipients to know that what they have is not the original, so
617: that any problems introduced by others will not reflect on the original
618: authors' reputations.
619:
620: Finally, any free program is threatened constantly by software
621: patents. We wish to avoid the danger that redistributors of a free
622: program will individually obtain patent licenses, in effect making the
623: program proprietary. To prevent this, we have made it clear that any
624: patent must be licensed for everyone's free use or not licensed at all.
625:
626: The precise terms and conditions for copying, distribution and
627: modification follow.
628:
629: @iftex
630: @unnumberedsec TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
631: @end iftex
1.49 anton 632: @ifnottex
1.1 anton 633: @center TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
1.49 anton 634: @end ifnottex
1.1 anton 635:
636: @enumerate 0
637: @item
638: This License applies to any program or other work which contains
639: a notice placed by the copyright holder saying it may be distributed
640: under the terms of this General Public License. The ``Program'', below,
641: refers to any such program or work, and a ``work based on the Program''
642: means either the Program or any derivative work under copyright law:
643: that is to say, a work containing the Program or a portion of it,
644: either verbatim or with modifications and/or translated into another
645: language. (Hereinafter, translation is included without limitation in
646: the term ``modification''.) Each licensee is addressed as ``you''.
647:
648: Activities other than copying, distribution and modification are not
649: covered by this License; they are outside its scope. The act of
650: running the Program is not restricted, and the output from the Program
651: is covered only if its contents constitute a work based on the
652: Program (independent of having been made by running the Program).
653: Whether that is true depends on what the Program does.
654:
655: @item
656: You may copy and distribute verbatim copies of the Program's
657: source code as you receive it, in any medium, provided that you
658: conspicuously and appropriately publish on each copy an appropriate
659: copyright notice and disclaimer of warranty; keep intact all the
660: notices that refer to this License and to the absence of any warranty;
661: and give any other recipients of the Program a copy of this License
662: along with the Program.
663:
664: You may charge a fee for the physical act of transferring a copy, and
665: you may at your option offer warranty protection in exchange for a fee.
666:
667: @item
668: You may modify your copy or copies of the Program or any portion
669: of it, thus forming a work based on the Program, and copy and
670: distribute such modifications or work under the terms of Section 1
671: above, provided that you also meet all of these conditions:
672:
673: @enumerate a
674: @item
675: You must cause the modified files to carry prominent notices
676: stating that you changed the files and the date of any change.
677:
678: @item
679: You must cause any work that you distribute or publish, that in
680: whole or in part contains or is derived from the Program or any
681: part thereof, to be licensed as a whole at no charge to all third
682: parties under the terms of this License.
683:
684: @item
685: If the modified program normally reads commands interactively
686: when run, you must cause it, when started running for such
687: interactive use in the most ordinary way, to print or display an
688: announcement including an appropriate copyright notice and a
689: notice that there is no warranty (or else, saying that you provide
690: a warranty) and that users may redistribute the program under
691: these conditions, and telling the user how to view a copy of this
692: License. (Exception: if the Program itself is interactive but
693: does not normally print such an announcement, your work based on
694: the Program is not required to print an announcement.)
695: @end enumerate
696:
697: These requirements apply to the modified work as a whole. If
698: identifiable sections of that work are not derived from the Program,
699: and can be reasonably considered independent and separate works in
700: themselves, then this License, and its terms, do not apply to those
701: sections when you distribute them as separate works. But when you
702: distribute the same sections as part of a whole which is a work based
703: on the Program, the distribution of the whole must be on the terms of
704: this License, whose permissions for other licensees extend to the
705: entire whole, and thus to each and every part regardless of who wrote it.
706:
707: Thus, it is not the intent of this section to claim rights or contest
708: your rights to work written entirely by you; rather, the intent is to
709: exercise the right to control the distribution of derivative or
710: collective works based on the Program.
711:
712: In addition, mere aggregation of another work not based on the Program
713: with the Program (or with a work based on the Program) on a volume of
714: a storage or distribution medium does not bring the other work under
715: the scope of this License.
716:
717: @item
718: You may copy and distribute the Program (or a work based on it,
719: under Section 2) in object code or executable form under the terms of
720: Sections 1 and 2 above provided that you also do one of the following:
721:
722: @enumerate a
723: @item
724: Accompany it with the complete corresponding machine-readable
725: source code, which must be distributed under the terms of Sections
726: 1 and 2 above on a medium customarily used for software interchange; or,
727:
728: @item
729: Accompany it with a written offer, valid for at least three
730: years, to give any third party, for a charge no more than your
731: cost of physically performing source distribution, a complete
732: machine-readable copy of the corresponding source code, to be
733: distributed under the terms of Sections 1 and 2 above on a medium
734: customarily used for software interchange; or,
735:
736: @item
737: Accompany it with the information you received as to the offer
738: to distribute corresponding source code. (This alternative is
739: allowed only for noncommercial distribution and only if you
740: received the program in object code or executable form with such
741: an offer, in accord with Subsection b above.)
742: @end enumerate
743:
744: The source code for a work means the preferred form of the work for
745: making modifications to it. For an executable work, complete source
746: code means all the source code for all modules it contains, plus any
747: associated interface definition files, plus the scripts used to
748: control compilation and installation of the executable. However, as a
749: special exception, the source code distributed need not include
750: anything that is normally distributed (in either source or binary
751: form) with the major components (compiler, kernel, and so on) of the
752: operating system on which the executable runs, unless that component
753: itself accompanies the executable.
754:
755: If distribution of executable or object code is made by offering
756: access to copy from a designated place, then offering equivalent
757: access to copy the source code from the same place counts as
758: distribution of the source code, even though third parties are not
759: compelled to copy the source along with the object code.
760:
761: @item
762: You may not copy, modify, sublicense, or distribute the Program
763: except as expressly provided under this License. Any attempt
764: otherwise to copy, modify, sublicense or distribute the Program is
765: void, and will automatically terminate your rights under this License.
766: However, parties who have received copies, or rights, from you under
767: this License will not have their licenses terminated so long as such
768: parties remain in full compliance.
769:
770: @item
771: You are not required to accept this License, since you have not
772: signed it. However, nothing else grants you permission to modify or
773: distribute the Program or its derivative works. These actions are
774: prohibited by law if you do not accept this License. Therefore, by
775: modifying or distributing the Program (or any work based on the
776: Program), you indicate your acceptance of this License to do so, and
777: all its terms and conditions for copying, distributing or modifying
778: the Program or works based on it.
779:
780: @item
781: Each time you redistribute the Program (or any work based on the
782: Program), the recipient automatically receives a license from the
783: original licensor to copy, distribute or modify the Program subject to
784: these terms and conditions. You may not impose any further
785: restrictions on the recipients' exercise of the rights granted herein.
786: You are not responsible for enforcing compliance by third parties to
787: this License.
788:
789: @item
790: If, as a consequence of a court judgment or allegation of patent
791: infringement or for any other reason (not limited to patent issues),
792: conditions are imposed on you (whether by court order, agreement or
793: otherwise) that contradict the conditions of this License, they do not
794: excuse you from the conditions of this License. If you cannot
795: distribute so as to satisfy simultaneously your obligations under this
796: License and any other pertinent obligations, then as a consequence you
797: may not distribute the Program at all. For example, if a patent
798: license would not permit royalty-free redistribution of the Program by
799: all those who receive copies directly or indirectly through you, then
800: the only way you could satisfy both it and this License would be to
801: refrain entirely from distribution of the Program.
802:
803: If any portion of this section is held invalid or unenforceable under
804: any particular circumstance, the balance of the section is intended to
805: apply and the section as a whole is intended to apply in other
806: circumstances.
807:
808: It is not the purpose of this section to induce you to infringe any
809: patents or other property right claims or to contest validity of any
810: such claims; this section has the sole purpose of protecting the
811: integrity of the free software distribution system, which is
812: implemented by public license practices. Many people have made
813: generous contributions to the wide range of software distributed
814: through that system in reliance on consistent application of that
815: system; it is up to the author/donor to decide if he or she is willing
816: to distribute software through any other system and a licensee cannot
817: impose that choice.
818:
819: This section is intended to make thoroughly clear what is believed to
820: be a consequence of the rest of this License.
821:
822: @item
823: If the distribution and/or use of the Program is restricted in
824: certain countries either by patents or by copyrighted interfaces, the
825: original copyright holder who places the Program under this License
826: may add an explicit geographical distribution limitation excluding
827: those countries, so that distribution is permitted only in or among
828: countries not thus excluded. In such case, this License incorporates
829: the limitation as if written in the body of this License.
830:
831: @item
832: The Free Software Foundation may publish revised and/or new versions
833: of the General Public License from time to time. Such new versions will
834: be similar in spirit to the present version, but may differ in detail to
835: address new problems or concerns.
836:
837: Each version is given a distinguishing version number. If the Program
838: specifies a version number of this License which applies to it and ``any
839: later version'', you have the option of following the terms and conditions
840: either of that version or of any later version published by the Free
841: Software Foundation. If the Program does not specify a version number of
842: this License, you may choose any version ever published by the Free Software
843: Foundation.
844:
845: @item
846: If you wish to incorporate parts of the Program into other free
847: programs whose distribution conditions are different, write to the author
848: to ask for permission. For software which is copyrighted by the Free
849: Software Foundation, write to the Free Software Foundation; we sometimes
850: make exceptions for this. Our decision will be guided by the two goals
851: of preserving the free status of all derivatives of our free software and
852: of promoting the sharing and reuse of software generally.
853:
854: @iftex
855: @heading NO WARRANTY
856: @end iftex
1.49 anton 857: @ifnottex
1.1 anton 858: @center NO WARRANTY
1.49 anton 859: @end ifnottex
1.1 anton 860:
861: @item
862: BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
863: FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
864: OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
865: PROVIDE THE PROGRAM ``AS IS'' WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
866: OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
867: MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
868: TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
869: PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
870: REPAIR OR CORRECTION.
871:
872: @item
873: IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
874: WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
875: REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
876: INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
877: OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
878: TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
879: YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
880: PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
881: POSSIBILITY OF SUCH DAMAGES.
882: @end enumerate
883:
884: @iftex
885: @heading END OF TERMS AND CONDITIONS
886: @end iftex
1.49 anton 887: @ifnottex
1.1 anton 888: @center END OF TERMS AND CONDITIONS
1.49 anton 889: @end ifnottex
1.1 anton 890:
891: @page
892: @unnumberedsec How to Apply These Terms to Your New Programs
893:
894: If you develop a new program, and you want it to be of the greatest
895: possible use to the public, the best way to achieve this is to make it
896: free software which everyone can redistribute and change under these terms.
897:
898: To do so, attach the following notices to the program. It is safest
899: to attach them to the start of each source file to most effectively
900: convey the exclusion of warranty; and each file should have at least
901: the ``copyright'' line and a pointer to where the full notice is found.
902:
903: @smallexample
904: @var{one line to give the program's name and a brief idea of what it does.}
905: Copyright (C) 19@var{yy} @var{name of author}
906:
907: This program is free software; you can redistribute it and/or modify
908: it under the terms of the GNU General Public License as published by
909: the Free Software Foundation; either version 2 of the License, or
910: (at your option) any later version.
911:
912: This program is distributed in the hope that it will be useful,
913: but WITHOUT ANY WARRANTY; without even the implied warranty of
914: MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
915: GNU General Public License for more details.
916:
917: You should have received a copy of the GNU General Public License
918: along with this program; if not, write to the Free Software
1.88 anton 919: Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
1.1 anton 920: @end smallexample
921:
922: Also add information on how to contact you by electronic and paper mail.
923:
924: If the program is interactive, make it output a short notice like this
925: when it starts in an interactive mode:
926:
927: @smallexample
928: Gnomovision version 69, Copyright (C) 19@var{yy} @var{name of author}
929: Gnomovision comes with ABSOLUTELY NO WARRANTY; for details
930: type `show w'.
931: This is free software, and you are welcome to redistribute it
932: under certain conditions; type `show c' for details.
933: @end smallexample
934:
935: The hypothetical commands @samp{show w} and @samp{show c} should show
936: the appropriate parts of the General Public License. Of course, the
937: commands you use may be called something other than @samp{show w} and
938: @samp{show c}; they could even be mouse-clicks or menu items---whatever
939: suits your program.
940:
941: You should also get your employer (if you work as a programmer) or your
942: school, if any, to sign a ``copyright disclaimer'' for the program, if
943: necessary. Here is a sample; alter the names:
944:
945: @smallexample
946: Yoyodyne, Inc., hereby disclaims all copyright interest in the program
947: `Gnomovision' (which makes passes at compilers) written by James Hacker.
948:
949: @var{signature of Ty Coon}, 1 April 1989
950: Ty Coon, President of Vice
951: @end smallexample
952:
953: This General Public License does not permit incorporating your program into
954: proprietary programs. If your program is a subroutine library, you may
955: consider it more useful to permit linking proprietary applications with the
956: library. If this is what you want to do, use the GNU Library General
957: Public License instead of this License.
958:
959: @iftex
960: @unnumbered Preface
961: @cindex Preface
1.21 crook 962: This manual documents Gforth. Some introductory material is provided for
963: readers who are unfamiliar with Forth or who are migrating to Gforth
964: from other Forth compilers. However, this manual is primarily a
965: reference manual.
1.1 anton 966: @end iftex
967:
1.28 crook 968: @comment TODO much more blurb here.
1.26 crook 969:
970: @c ******************************************************************
1.29 crook 971: @node Goals, Gforth Environment, License, Top
1.26 crook 972: @comment node-name, next, previous, up
973: @chapter Goals of Gforth
974: @cindex goals of the Gforth project
975: The goal of the Gforth Project is to develop a standard model for
976: ANS Forth. This can be split into several subgoals:
977:
978: @itemize @bullet
979: @item
980: Gforth should conform to the ANS Forth Standard.
981: @item
982: It should be a model, i.e. it should define all the
983: implementation-dependent things.
984: @item
985: It should become standard, i.e. widely accepted and used. This goal
986: is the most difficult one.
987: @end itemize
988:
989: To achieve these goals Gforth should be
990: @itemize @bullet
991: @item
992: Similar to previous models (fig-Forth, F83)
993: @item
994: Powerful. It should provide for all the things that are considered
995: necessary today and even some that are not yet considered necessary.
996: @item
997: Efficient. It should not get the reputation of being exceptionally
998: slow.
999: @item
1000: Free.
1001: @item
1002: Available on many machines/easy to port.
1003: @end itemize
1004:
1005: Have we achieved these goals? Gforth conforms to the ANS Forth
1006: standard. It may be considered a model, but we have not yet documented
1007: which parts of the model are stable and which parts we are likely to
1008: change. It certainly has not yet become a de facto standard, but it
1009: appears to be quite popular. It has some similarities to and some
1010: differences from previous models. It has some powerful features, but not
1011: yet everything that we envisioned. We certainly have achieved our
1.65 anton 1012: execution speed goals (@pxref{Performance})@footnote{However, in 1998
1013: the bar was raised when the major commercial Forth vendors switched to
1014: native code compilers.}. It is free and available on many machines.
1.29 crook 1015:
1.26 crook 1016: @c ******************************************************************
1.48 anton 1017: @node Gforth Environment, Tutorial, Goals, Top
1.29 crook 1018: @chapter Gforth Environment
1019: @cindex Gforth environment
1.21 crook 1020:
1.45 crook 1021: Note: ultimately, the Gforth man page will be auto-generated from the
1.29 crook 1022: material in this chapter.
1.21 crook 1023:
1024: @menu
1.29 crook 1025: * Invoking Gforth:: Getting in
1026: * Leaving Gforth:: Getting out
1027: * Command-line editing::
1.48 anton 1028: * Environment variables:: that affect how Gforth starts up
1.29 crook 1029: * Gforth Files:: What gets installed and where
1.48 anton 1030: * Startup speed:: When 35ms is not fast enough ...
1.21 crook 1031: @end menu
1032:
1.49 anton 1033: For related information about the creation of images see @ref{Image Files}.
1.29 crook 1034:
1.21 crook 1035: @comment ----------------------------------------------
1.48 anton 1036: @node Invoking Gforth, Leaving Gforth, Gforth Environment, Gforth Environment
1.29 crook 1037: @section Invoking Gforth
1038: @cindex invoking Gforth
1039: @cindex running Gforth
1040: @cindex command-line options
1041: @cindex options on the command line
1042: @cindex flags on the command line
1.21 crook 1043:
1.30 anton 1044: Gforth is made up of two parts; an executable ``engine'' (named
1.109 anton 1045: @command{gforth} or @command{gforth-fast}) and an image file. To start it, you
1.30 anton 1046: will usually just say @code{gforth} -- this automatically loads the
1047: default image file @file{gforth.fi}. In many other cases the default
1048: Gforth image will be invoked like this:
1.21 crook 1049: @example
1.30 anton 1050: gforth [file | -e forth-code] ...
1.21 crook 1051: @end example
1.29 crook 1052: @noindent
1053: This interprets the contents of the files and the Forth code in the order they
1054: are given.
1.21 crook 1055:
1.109 anton 1056: In addition to the @command{gforth} engine, there is also an engine
1057: called @command{gforth-fast}, which is faster, but gives less
1058: informative error messages (@pxref{Error messages}) and may catch some
1059: stack underflows later or not at all. You should use it for debugged,
1060: performance-critical programs.
1061:
1062: Moreover, there is an engine called @command{gforth-itc}, which is
1063: useful in some backwards-compatibility situations (@pxref{Direct or
1064: Indirect Threaded?}).
1.30 anton 1065:
1.29 crook 1066: In general, the command line looks like this:
1.21 crook 1067:
1068: @example
1.30 anton 1069: gforth[-fast] [engine options] [image options]
1.21 crook 1070: @end example
1071:
1.30 anton 1072: The engine options must come before the rest of the command
1.29 crook 1073: line. They are:
1.26 crook 1074:
1.29 crook 1075: @table @code
1076: @cindex -i, command-line option
1077: @cindex --image-file, command-line option
1078: @item --image-file @i{file}
1079: @itemx -i @i{file}
1080: Loads the Forth image @i{file} instead of the default
1081: @file{gforth.fi} (@pxref{Image Files}).
1.21 crook 1082:
1.39 anton 1083: @cindex --appl-image, command-line option
1084: @item --appl-image @i{file}
1085: Loads the image @i{file} and leaves all further command-line arguments
1.65 anton 1086: to the image (instead of processing them as engine options). This is
1087: useful for building executable application images on Unix, built with
1.39 anton 1088: @code{gforthmi --application ...}.
1089:
1.29 crook 1090: @cindex --path, command-line option
1091: @cindex -p, command-line option
1092: @item --path @i{path}
1093: @itemx -p @i{path}
1094: Uses @i{path} for searching the image file and Forth source code files
1095: instead of the default in the environment variable @code{GFORTHPATH} or
1096: the path specified at installation time (e.g.,
1097: @file{/usr/local/share/gforth/0.2.0:.}). A path is given as a list of
1098: directories, separated by @samp{:} (on Unix) or @samp{;} (on other OSs).
1.21 crook 1099:
1.29 crook 1100: @cindex --dictionary-size, command-line option
1101: @cindex -m, command-line option
1102: @cindex @i{size} parameters for command-line options
1103: @cindex size of the dictionary and the stacks
1104: @item --dictionary-size @i{size}
1105: @itemx -m @i{size}
1106: Allocate @i{size} space for the Forth dictionary space instead of
1107: using the default specified in the image (typically 256K). The
1108: @i{size} specification for this and subsequent options consists of
1109: an integer and a unit (e.g.,
1110: @code{4M}). The unit can be one of @code{b} (bytes), @code{e} (element
1111: size, in this case Cells), @code{k} (kilobytes), @code{M} (Megabytes),
1112: @code{G} (Gigabytes), and @code{T} (Terabytes). If no unit is specified,
1113: @code{e} is used.
1.21 crook 1114:
1.29 crook 1115: @cindex --data-stack-size, command-line option
1116: @cindex -d, command-line option
1117: @item --data-stack-size @i{size}
1118: @itemx -d @i{size}
1119: Allocate @i{size} space for the data stack instead of using the
1120: default specified in the image (typically 16K).
1.21 crook 1121:
1.29 crook 1122: @cindex --return-stack-size, command-line option
1123: @cindex -r, command-line option
1124: @item --return-stack-size @i{size}
1125: @itemx -r @i{size}
1126: Allocate @i{size} space for the return stack instead of using the
1127: default specified in the image (typically 15K).
1.21 crook 1128:
1.29 crook 1129: @cindex --fp-stack-size, command-line option
1130: @cindex -f, command-line option
1131: @item --fp-stack-size @i{size}
1132: @itemx -f @i{size}
1133: Allocate @i{size} space for the floating point stack instead of
1134: using the default specified in the image (typically 15.5K). In this case
1135: the unit specifier @code{e} refers to floating point numbers.
1.21 crook 1136:
1.48 anton 1137: @cindex --locals-stack-size, command-line option
1138: @cindex -l, command-line option
1139: @item --locals-stack-size @i{size}
1140: @itemx -l @i{size}
1141: Allocate @i{size} space for the locals stack instead of using the
1142: default specified in the image (typically 14.5K).
1143:
1144: @cindex -h, command-line option
1145: @cindex --help, command-line option
1146: @item --help
1147: @itemx -h
1148: Print a message about the command-line options
1149:
1150: @cindex -v, command-line option
1151: @cindex --version, command-line option
1152: @item --version
1153: @itemx -v
1154: Print version and exit
1155:
1156: @cindex --debug, command-line option
1157: @item --debug
1158: Print some information useful for debugging on startup.
1159:
1160: @cindex --offset-image, command-line option
1161: @item --offset-image
1162: Start the dictionary at a slightly different position than would be used
1163: otherwise (useful for creating data-relocatable images,
1164: @pxref{Data-Relocatable Image Files}).
1165:
1166: @cindex --no-offset-im, command-line option
1167: @item --no-offset-im
1168: Start the dictionary at the normal position.
1169:
1170: @cindex --clear-dictionary, command-line option
1171: @item --clear-dictionary
1172: Initialize all bytes in the dictionary to 0 before loading the image
1173: (@pxref{Data-Relocatable Image Files}).
1174:
1175: @cindex --die-on-signal, command-line-option
1176: @item --die-on-signal
1177: Normally Gforth handles most signals (e.g., the user interrupt SIGINT,
1178: or the segmentation violation SIGSEGV) by translating it into a Forth
1179: @code{THROW}. With this option, Gforth exits if it receives such a
1180: signal. This option is useful when the engine and/or the image might be
1181: severely broken (such that it causes another signal before recovering
1182: from the first); this option avoids endless loops in such cases.
1.109 anton 1183:
1184: @item --no-dynamic
1185: @item --dynamic
1186: Disable or enable dynamic superinstructions with replication
1187: (@pxref{Dynamic Superinstructions}).
1188:
1189: @item --no-super
1.110 anton 1190: Disable dynamic superinstructions, use just dynamic replication; this is
1191: useful if you want to patch threaded code (@pxref{Dynamic
1192: Superinstructions}).
1.109 anton 1193:
1.48 anton 1194: @end table
1195:
1196: @cindex loading files at startup
1197: @cindex executing code on startup
1198: @cindex batch processing with Gforth
1199: As explained above, the image-specific command-line arguments for the
1200: default image @file{gforth.fi} consist of a sequence of filenames and
1201: @code{-e @var{forth-code}} options that are interpreted in the sequence
1202: in which they are given. The @code{-e @var{forth-code}} or
1203: @code{--evaluate @var{forth-code}} option evaluates the Forth
1204: code. This option takes only one argument; if you want to evaluate more
1205: Forth words, you have to quote them or use @code{-e} several times. To exit
1206: after processing the command line (instead of entering interactive mode)
1207: append @code{-e bye} to the command line.
1208:
1209: @cindex versions, invoking other versions of Gforth
1210: If you have several versions of Gforth installed, @code{gforth} will
1211: invoke the version that was installed last. @code{gforth-@i{version}}
1212: invokes a specific version. If your environment contains the variable
1213: @code{GFORTHPATH}, you may want to override it by using the
1214: @code{--path} option.
1215:
1216: Not yet implemented:
1217: On startup the system first executes the system initialization file
1218: (unless the option @code{--no-init-file} is given; note that the system
1219: resulting from using this option may not be ANS Forth conformant). Then
1220: the user initialization file @file{.gforth.fs} is executed, unless the
1.62 crook 1221: option @code{--no-rc} is given; this file is searched for in @file{.},
1.48 anton 1222: then in @file{~}, then in the normal path (see above).
1223:
1224:
1225:
1226: @comment ----------------------------------------------
1227: @node Leaving Gforth, Command-line editing, Invoking Gforth, Gforth Environment
1228: @section Leaving Gforth
1229: @cindex Gforth - leaving
1230: @cindex leaving Gforth
1231:
1232: You can leave Gforth by typing @code{bye} or @kbd{Ctrl-d} (at the start
1233: of a line) or (if you invoked Gforth with the @code{--die-on-signal}
1234: option) @kbd{Ctrl-c}. When you leave Gforth, all of your definitions and
1.49 anton 1235: data are discarded. For ways of saving the state of the system before
1236: leaving Gforth see @ref{Image Files}.
1.48 anton 1237:
1238: doc-bye
1239:
1240:
1241: @comment ----------------------------------------------
1.65 anton 1242: @node Command-line editing, Environment variables, Leaving Gforth, Gforth Environment
1.48 anton 1243: @section Command-line editing
1244: @cindex command-line editing
1245:
1246: Gforth maintains a history file that records every line that you type to
1247: the text interpreter. This file is preserved between sessions, and is
1248: used to provide a command-line recall facility; if you type @kbd{Ctrl-P}
1249: repeatedly you can recall successively older commands from this (or
1250: previous) session(s). The full list of command-line editing facilities is:
1251:
1252: @itemize @bullet
1253: @item
1254: @kbd{Ctrl-p} (``previous'') (or up-arrow) to recall successively older
1255: commands from the history buffer.
1256: @item
1257: @kbd{Ctrl-n} (``next'') (or down-arrow) to recall successively newer commands
1258: from the history buffer.
1259: @item
1260: @kbd{Ctrl-f} (or right-arrow) to move the cursor right, non-destructively.
1261: @item
1262: @kbd{Ctrl-b} (or left-arrow) to move the cursor left, non-destructively.
1263: @item
1264: @kbd{Ctrl-h} (backspace) to delete the character to the left of the cursor,
1265: closing up the line.
1266: @item
1267: @kbd{Ctrl-k} to delete (``kill'') from the cursor to the end of the line.
1268: @item
1269: @kbd{Ctrl-a} to move the cursor to the start of the line.
1270: @item
1271: @kbd{Ctrl-e} to move the cursor to the end of the line.
1272: @item
1273: @key{RET} (@kbd{Ctrl-m}) or @key{LFD} (@kbd{Ctrl-j}) to submit the current
1274: line.
1275: @item
1276: @key{TAB} to step through all possible full-word completions of the word
1277: currently being typed.
1278: @item
1.65 anton 1279: @kbd{Ctrl-d} on an empty line line to terminate Gforth (gracefully,
1280: using @code{bye}).
1281: @item
1282: @kbd{Ctrl-x} (or @code{Ctrl-d} on a non-empty line) to delete the
1283: character under the cursor.
1.48 anton 1284: @end itemize
1285:
1286: When editing, displayable characters are inserted to the left of the
1287: cursor position; the line is always in ``insert'' (as opposed to
1288: ``overstrike'') mode.
1289:
1290: @cindex history file
1291: @cindex @file{.gforth-history}
1292: On Unix systems, the history file is @file{~/.gforth-history} by
1293: default@footnote{i.e. it is stored in the user's home directory.}. You
1294: can find out the name and location of your history file using:
1295:
1296: @example
1297: history-file type \ Unix-class systems
1298:
1299: history-file type \ Other systems
1300: history-dir type
1301: @end example
1302:
1303: If you enter long definitions by hand, you can use a text editor to
1304: paste them out of the history file into a Forth source file for reuse at
1305: a later time.
1306:
1307: Gforth never trims the size of the history file, so you should do this
1308: periodically, if necessary.
1309:
1310: @comment this is all defined in history.fs
1311: @comment NAC TODO the ctrl-D behaviour can either do a bye or a beep.. how is that option
1312: @comment chosen?
1313:
1314:
1315: @comment ----------------------------------------------
1.65 anton 1316: @node Environment variables, Gforth Files, Command-line editing, Gforth Environment
1.48 anton 1317: @section Environment variables
1318: @cindex environment variables
1319:
1320: Gforth uses these environment variables:
1321:
1322: @itemize @bullet
1323: @item
1324: @cindex @code{GFORTHHIST} -- environment variable
1325: @code{GFORTHHIST} -- (Unix systems only) specifies the directory in which to
1326: open/create the history file, @file{.gforth-history}. Default:
1327: @code{$HOME}.
1328:
1329: @item
1330: @cindex @code{GFORTHPATH} -- environment variable
1331: @code{GFORTHPATH} -- specifies the path used when searching for the gforth image file and
1332: for Forth source-code files.
1333:
1334: @item
1335: @cindex @code{GFORTH} -- environment variable
1.49 anton 1336: @code{GFORTH} -- used by @file{gforthmi}, @xref{gforthmi}.
1.48 anton 1337:
1338: @item
1339: @cindex @code{GFORTHD} -- environment variable
1.62 crook 1340: @code{GFORTHD} -- used by @file{gforthmi}, @xref{gforthmi}.
1.48 anton 1341:
1342: @item
1343: @cindex @code{TMP}, @code{TEMP} - environment variable
1344: @code{TMP}, @code{TEMP} - (non-Unix systems only) used as a potential
1345: location for the history file.
1346: @end itemize
1347:
1348: @comment also POSIXELY_CORRECT LINES COLUMNS HOME but no interest in
1349: @comment mentioning these.
1350:
1351: All the Gforth environment variables default to sensible values if they
1352: are not set.
1353:
1354:
1355: @comment ----------------------------------------------
1356: @node Gforth Files, Startup speed, Environment variables, Gforth Environment
1357: @section Gforth files
1358: @cindex Gforth files
1359:
1360: When you install Gforth on a Unix system, it installs files in these
1361: locations by default:
1362:
1363: @itemize @bullet
1364: @item
1365: @file{/usr/local/bin/gforth}
1366: @item
1367: @file{/usr/local/bin/gforthmi}
1368: @item
1369: @file{/usr/local/man/man1/gforth.1} - man page.
1370: @item
1371: @file{/usr/local/info} - the Info version of this manual.
1372: @item
1373: @file{/usr/local/lib/gforth/<version>/...} - Gforth @file{.fi} files.
1374: @item
1375: @file{/usr/local/share/gforth/<version>/TAGS} - Emacs TAGS file.
1376: @item
1377: @file{/usr/local/share/gforth/<version>/...} - Gforth source files.
1378: @item
1379: @file{.../emacs/site-lisp/gforth.el} - Emacs gforth mode.
1380: @end itemize
1381:
1382: You can select different places for installation by using
1383: @code{configure} options (listed with @code{configure --help}).
1384:
1385: @comment ----------------------------------------------
1386: @node Startup speed, , Gforth Files, Gforth Environment
1387: @section Startup speed
1388: @cindex Startup speed
1389: @cindex speed, startup
1390:
1391: If Gforth is used for CGI scripts or in shell scripts, its startup
1392: speed may become a problem. On a 300MHz 21064a under Linux-2.2.13 with
1393: glibc-2.0.7, @code{gforth -e bye} takes about 24.6ms user and 11.3ms
1394: system time.
1395:
1396: If startup speed is a problem, you may consider the following ways to
1397: improve it; or you may consider ways to reduce the number of startups
1.62 crook 1398: (for example, by using Fast-CGI).
1.48 anton 1399:
1400: The first step to improve startup speed is to statically link Gforth, by
1401: building it with @code{XLDFLAGS=-static}. This requires more memory for
1402: the code and will therefore slow down the first invocation, but
1403: subsequent invocations avoid the dynamic linking overhead. Another
1404: disadvantage is that Gforth won't profit from library upgrades. As a
1405: result, @code{gforth-static -e bye} takes about 17.1ms user and
1406: 8.2ms system time.
1407:
1408: The next step to improve startup speed is to use a non-relocatable image
1.65 anton 1409: (@pxref{Non-Relocatable Image Files}). You can create this image with
1.48 anton 1410: @code{gforth -e "savesystem gforthnr.fi bye"} and later use it with
1411: @code{gforth -i gforthnr.fi ...}. This avoids the relocation overhead
1412: and a part of the copy-on-write overhead. The disadvantage is that the
1.62 crook 1413: non-relocatable image does not work if the OS gives Gforth a different
1.48 anton 1414: address for the dictionary, for whatever reason; so you better provide a
1415: fallback on a relocatable image. @code{gforth-static -i gforthnr.fi -e
1416: bye} takes about 15.3ms user and 7.5ms system time.
1417:
1418: The final step is to disable dictionary hashing in Gforth. Gforth
1419: builds the hash table on startup, which takes much of the startup
1420: overhead. You can do this by commenting out the @code{include hash.fs}
1421: in @file{startup.fs} and everything that requires @file{hash.fs} (at the
1422: moment @file{table.fs} and @file{ekey.fs}) and then doing @code{make}.
1423: The disadvantages are that functionality like @code{table} and
1424: @code{ekey} is missing and that text interpretation (e.g., compiling)
1425: now takes much longer. So, you should only use this method if there is
1426: no significant text interpretation to perform (the script should be
1.62 crook 1427: compiled into the image, amongst other things). @code{gforth-static -i
1.48 anton 1428: gforthnrnh.fi -e bye} takes about 2.1ms user and 6.1ms system time.
1429:
1430: @c ******************************************************************
1431: @node Tutorial, Introduction, Gforth Environment, Top
1432: @chapter Forth Tutorial
1433: @cindex Tutorial
1434: @cindex Forth Tutorial
1435:
1.67 anton 1436: @c Topics from nac's Introduction that could be mentioned:
1437: @c press <ret> after each line
1438: @c Prompt
1439: @c numbers vs. words in dictionary on text interpretation
1440: @c what happens on redefinition
1441: @c parsing words (in particular, defining words)
1442:
1.83 anton 1443: The difference of this chapter from the Introduction
1444: (@pxref{Introduction}) is that this tutorial is more fast-paced, should
1445: be used while sitting in front of a computer, and covers much more
1446: material, but does not explain how the Forth system works.
1447:
1.62 crook 1448: This tutorial can be used with any ANS-compliant Forth; any
1449: Gforth-specific features are marked as such and you can skip them if you
1450: work with another Forth. This tutorial does not explain all features of
1451: Forth, just enough to get you started and give you some ideas about the
1452: facilities available in Forth. Read the rest of the manual and the
1453: standard when you are through this.
1.48 anton 1454:
1455: The intended way to use this tutorial is that you work through it while
1456: sitting in front of the console, take a look at the examples and predict
1457: what they will do, then try them out; if the outcome is not as expected,
1458: find out why (e.g., by trying out variations of the example), so you
1459: understand what's going on. There are also some assignments that you
1460: should solve.
1461:
1462: This tutorial assumes that you have programmed before and know what,
1463: e.g., a loop is.
1464:
1465: @c !! explain compat library
1466:
1467: @menu
1468: * Starting Gforth Tutorial::
1469: * Syntax Tutorial::
1470: * Crash Course Tutorial::
1471: * Stack Tutorial::
1472: * Arithmetics Tutorial::
1473: * Stack Manipulation Tutorial::
1474: * Using files for Forth code Tutorial::
1475: * Comments Tutorial::
1476: * Colon Definitions Tutorial::
1477: * Decompilation Tutorial::
1478: * Stack-Effect Comments Tutorial::
1479: * Types Tutorial::
1480: * Factoring Tutorial::
1481: * Designing the stack effect Tutorial::
1482: * Local Variables Tutorial::
1483: * Conditional execution Tutorial::
1484: * Flags and Comparisons Tutorial::
1485: * General Loops Tutorial::
1486: * Counted loops Tutorial::
1487: * Recursion Tutorial::
1488: * Leaving definitions or loops Tutorial::
1489: * Return Stack Tutorial::
1490: * Memory Tutorial::
1491: * Characters and Strings Tutorial::
1492: * Alignment Tutorial::
1.87 anton 1493: * Files Tutorial::
1.48 anton 1494: * Interpretation and Compilation Semantics and Immediacy Tutorial::
1495: * Execution Tokens Tutorial::
1496: * Exceptions Tutorial::
1497: * Defining Words Tutorial::
1498: * Arrays and Records Tutorial::
1499: * POSTPONE Tutorial::
1500: * Literal Tutorial::
1501: * Advanced macros Tutorial::
1502: * Compilation Tokens Tutorial::
1503: * Wordlists and Search Order Tutorial::
1504: @end menu
1505:
1506: @node Starting Gforth Tutorial, Syntax Tutorial, Tutorial, Tutorial
1507: @section Starting Gforth
1.66 anton 1508: @cindex starting Gforth tutorial
1.48 anton 1509: You can start Gforth by typing its name:
1510:
1511: @example
1512: gforth
1513: @end example
1514:
1515: That puts you into interactive mode; you can leave Gforth by typing
1516: @code{bye}. While in Gforth, you can edit the command line and access
1517: the command line history with cursor keys, similar to bash.
1518:
1519:
1520: @node Syntax Tutorial, Crash Course Tutorial, Starting Gforth Tutorial, Tutorial
1521: @section Syntax
1.66 anton 1522: @cindex syntax tutorial
1.48 anton 1523:
1524: A @dfn{word} is a sequence of arbitrary characters (expcept white
1525: space). Words are separated by white space. E.g., each of the
1526: following lines contains exactly one word:
1527:
1528: @example
1529: word
1530: !@@#$%^&*()
1531: 1234567890
1532: 5!a
1533: @end example
1534:
1535: A frequent beginner's error is to leave away necessary white space,
1536: resulting in an error like @samp{Undefined word}; so if you see such an
1537: error, check if you have put spaces wherever necessary.
1538:
1539: @example
1540: ." hello, world" \ correct
1541: ."hello, world" \ gives an "Undefined word" error
1542: @end example
1543:
1.65 anton 1544: Gforth and most other Forth systems ignore differences in case (they are
1.48 anton 1545: case-insensitive), i.e., @samp{word} is the same as @samp{Word}. If
1546: your system is case-sensitive, you may have to type all the examples
1547: given here in upper case.
1548:
1549:
1550: @node Crash Course Tutorial, Stack Tutorial, Syntax Tutorial, Tutorial
1551: @section Crash Course
1552:
1553: Type
1554:
1555: @example
1556: 0 0 !
1557: here execute
1558: ' catch >body 20 erase abort
1559: ' (quit) >body 20 erase
1560: @end example
1561:
1562: The last two examples are guaranteed to destroy parts of Gforth (and
1563: most other systems), so you better leave Gforth afterwards (if it has
1564: not finished by itself). On some systems you may have to kill gforth
1565: from outside (e.g., in Unix with @code{kill}).
1566:
1567: Now that you know how to produce crashes (and that there's not much to
1568: them), let's learn how to produce meaningful programs.
1569:
1570:
1571: @node Stack Tutorial, Arithmetics Tutorial, Crash Course Tutorial, Tutorial
1572: @section Stack
1.66 anton 1573: @cindex stack tutorial
1.48 anton 1574:
1575: The most obvious feature of Forth is the stack. When you type in a
1576: number, it is pushed on the stack. You can display the content of the
1577: stack with @code{.s}.
1578:
1579: @example
1580: 1 2 .s
1581: 3 .s
1582: @end example
1583:
1584: @code{.s} displays the top-of-stack to the right, i.e., the numbers
1585: appear in @code{.s} output as they appeared in the input.
1586:
1587: You can print the top of stack element with @code{.}.
1588:
1589: @example
1590: 1 2 3 . . .
1591: @end example
1592:
1593: In general, words consume their stack arguments (@code{.s} is an
1594: exception).
1595:
1596: @assignment
1597: What does the stack contain after @code{5 6 7 .}?
1598: @endassignment
1599:
1600:
1601: @node Arithmetics Tutorial, Stack Manipulation Tutorial, Stack Tutorial, Tutorial
1602: @section Arithmetics
1.66 anton 1603: @cindex arithmetics tutorial
1.48 anton 1604:
1605: The words @code{+}, @code{-}, @code{*}, @code{/}, and @code{mod} always
1606: operate on the top two stack items:
1607:
1608: @example
1.67 anton 1609: 2 2 .s
1610: + .s
1611: .
1.48 anton 1612: 2 1 - .
1613: 7 3 mod .
1614: @end example
1615:
1616: The operands of @code{-}, @code{/}, and @code{mod} are in the same order
1617: as in the corresponding infix expression (this is generally the case in
1618: Forth).
1619:
1620: Parentheses are superfluous (and not available), because the order of
1621: the words unambiguously determines the order of evaluation and the
1622: operands:
1623:
1624: @example
1625: 3 4 + 5 * .
1626: 3 4 5 * + .
1627: @end example
1628:
1629: @assignment
1630: What are the infix expressions corresponding to the Forth code above?
1631: Write @code{6-7*8+9} in Forth notation@footnote{This notation is also
1632: known as Postfix or RPN (Reverse Polish Notation).}.
1633: @endassignment
1634:
1635: To change the sign, use @code{negate}:
1636:
1637: @example
1638: 2 negate .
1639: @end example
1640:
1641: @assignment
1642: Convert -(-3)*4-5 to Forth.
1643: @endassignment
1644:
1645: @code{/mod} performs both @code{/} and @code{mod}.
1646:
1647: @example
1648: 7 3 /mod . .
1649: @end example
1650:
1.66 anton 1651: Reference: @ref{Arithmetic}.
1652:
1653:
1.48 anton 1654: @node Stack Manipulation Tutorial, Using files for Forth code Tutorial, Arithmetics Tutorial, Tutorial
1655: @section Stack Manipulation
1.66 anton 1656: @cindex stack manipulation tutorial
1.48 anton 1657:
1658: Stack manipulation words rearrange the data on the stack.
1659:
1660: @example
1661: 1 .s drop .s
1662: 1 .s dup .s drop drop .s
1663: 1 2 .s over .s drop drop drop
1664: 1 2 .s swap .s drop drop
1665: 1 2 3 .s rot .s drop drop drop
1666: @end example
1667:
1668: These are the most important stack manipulation words. There are also
1669: variants that manipulate twice as many stack items:
1670:
1671: @example
1672: 1 2 3 4 .s 2swap .s 2drop 2drop
1673: @end example
1674:
1675: Two more stack manipulation words are:
1676:
1677: @example
1678: 1 2 .s nip .s drop
1679: 1 2 .s tuck .s 2drop drop
1680: @end example
1681:
1682: @assignment
1683: Replace @code{nip} and @code{tuck} with combinations of other stack
1684: manipulation words.
1685:
1686: @example
1687: Given: How do you get:
1688: 1 2 3 3 2 1
1689: 1 2 3 1 2 3 2
1690: 1 2 3 1 2 3 3
1691: 1 2 3 1 3 3
1692: 1 2 3 2 1 3
1693: 1 2 3 4 4 3 2 1
1694: 1 2 3 1 2 3 1 2 3
1695: 1 2 3 4 1 2 3 4 1 2
1696: 1 2 3
1697: 1 2 3 1 2 3 4
1698: 1 2 3 1 3
1699: @end example
1700: @endassignment
1701:
1702: @example
1703: 5 dup * .
1704: @end example
1705:
1706: @assignment
1707: Write 17^3 and 17^4 in Forth, without writing @code{17} more than once.
1708: Write a piece of Forth code that expects two numbers on the stack
1709: (@var{a} and @var{b}, with @var{b} on top) and computes
1710: @code{(a-b)(a+1)}.
1711: @endassignment
1712:
1.66 anton 1713: Reference: @ref{Stack Manipulation}.
1714:
1715:
1.48 anton 1716: @node Using files for Forth code Tutorial, Comments Tutorial, Stack Manipulation Tutorial, Tutorial
1717: @section Using files for Forth code
1.66 anton 1718: @cindex loading Forth code, tutorial
1719: @cindex files containing Forth code, tutorial
1.48 anton 1720:
1721: While working at the Forth command line is convenient for one-line
1722: examples and short one-off code, you probably want to store your source
1723: code in files for convenient editing and persistence. You can use your
1724: favourite editor (Gforth includes Emacs support, @pxref{Emacs and
1.102 anton 1725: Gforth}) to create @var{file.fs} and use
1.48 anton 1726:
1727: @example
1.102 anton 1728: s" @var{file.fs}" included
1.48 anton 1729: @end example
1730:
1731: to load it into your Forth system. The file name extension I use for
1732: Forth files is @samp{.fs}.
1733:
1734: You can easily start Gforth with some files loaded like this:
1735:
1736: @example
1.102 anton 1737: gforth @var{file1.fs} @var{file2.fs}
1.48 anton 1738: @end example
1739:
1740: If an error occurs during loading these files, Gforth terminates,
1741: whereas an error during @code{INCLUDED} within Gforth usually gives you
1742: a Gforth command line. Starting the Forth system every time gives you a
1743: clean start every time, without interference from the results of earlier
1744: tries.
1745:
1746: I often put all the tests in a file, then load the code and run the
1747: tests with
1748:
1749: @example
1.102 anton 1750: gforth @var{code.fs} @var{tests.fs} -e bye
1.48 anton 1751: @end example
1752:
1753: (often by performing this command with @kbd{C-x C-e} in Emacs). The
1754: @code{-e bye} ensures that Gforth terminates afterwards so that I can
1755: restart this command without ado.
1756:
1757: The advantage of this approach is that the tests can be repeated easily
1758: every time the program ist changed, making it easy to catch bugs
1759: introduced by the change.
1760:
1.66 anton 1761: Reference: @ref{Forth source files}.
1762:
1.48 anton 1763:
1764: @node Comments Tutorial, Colon Definitions Tutorial, Using files for Forth code Tutorial, Tutorial
1765: @section Comments
1.66 anton 1766: @cindex comments tutorial
1.48 anton 1767:
1768: @example
1769: \ That's a comment; it ends at the end of the line
1770: ( Another comment; it ends here: ) .s
1771: @end example
1772:
1773: @code{\} and @code{(} are ordinary Forth words and therefore have to be
1774: separated with white space from the following text.
1775:
1776: @example
1777: \This gives an "Undefined word" error
1778: @end example
1779:
1780: The first @code{)} ends a comment started with @code{(}, so you cannot
1781: nest @code{(}-comments; and you cannot comment out text containing a
1782: @code{)} with @code{( ... )}@footnote{therefore it's a good idea to
1783: avoid @code{)} in word names.}.
1784:
1785: I use @code{\}-comments for descriptive text and for commenting out code
1786: of one or more line; I use @code{(}-comments for describing the stack
1787: effect, the stack contents, or for commenting out sub-line pieces of
1788: code.
1789:
1790: The Emacs mode @file{gforth.el} (@pxref{Emacs and Gforth}) supports
1791: these uses by commenting out a region with @kbd{C-x \}, uncommenting a
1792: region with @kbd{C-u C-x \}, and filling a @code{\}-commented region
1793: with @kbd{M-q}.
1794:
1.66 anton 1795: Reference: @ref{Comments}.
1796:
1.48 anton 1797:
1798: @node Colon Definitions Tutorial, Decompilation Tutorial, Comments Tutorial, Tutorial
1799: @section Colon Definitions
1.66 anton 1800: @cindex colon definitions, tutorial
1801: @cindex definitions, tutorial
1802: @cindex procedures, tutorial
1803: @cindex functions, tutorial
1.48 anton 1804:
1805: are similar to procedures and functions in other programming languages.
1806:
1807: @example
1808: : squared ( n -- n^2 )
1809: dup * ;
1810: 5 squared .
1811: 7 squared .
1812: @end example
1813:
1814: @code{:} starts the colon definition; its name is @code{squared}. The
1815: following comment describes its stack effect. The words @code{dup *}
1816: are not executed, but compiled into the definition. @code{;} ends the
1817: colon definition.
1818:
1819: The newly-defined word can be used like any other word, including using
1820: it in other definitions:
1821:
1822: @example
1823: : cubed ( n -- n^3 )
1824: dup squared * ;
1825: -5 cubed .
1826: : fourth-power ( n -- n^4 )
1827: squared squared ;
1828: 3 fourth-power .
1829: @end example
1830:
1831: @assignment
1832: Write colon definitions for @code{nip}, @code{tuck}, @code{negate}, and
1833: @code{/mod} in terms of other Forth words, and check if they work (hint:
1834: test your tests on the originals first). Don't let the
1835: @samp{redefined}-Messages spook you, they are just warnings.
1836: @endassignment
1837:
1.66 anton 1838: Reference: @ref{Colon Definitions}.
1839:
1.48 anton 1840:
1841: @node Decompilation Tutorial, Stack-Effect Comments Tutorial, Colon Definitions Tutorial, Tutorial
1842: @section Decompilation
1.66 anton 1843: @cindex decompilation tutorial
1844: @cindex see tutorial
1.48 anton 1845:
1846: You can decompile colon definitions with @code{see}:
1847:
1848: @example
1849: see squared
1850: see cubed
1851: @end example
1852:
1853: In Gforth @code{see} shows you a reconstruction of the source code from
1854: the executable code. Informations that were present in the source, but
1855: not in the executable code, are lost (e.g., comments).
1856:
1.65 anton 1857: You can also decompile the predefined words:
1858:
1859: @example
1860: see .
1861: see +
1862: @end example
1863:
1864:
1.48 anton 1865: @node Stack-Effect Comments Tutorial, Types Tutorial, Decompilation Tutorial, Tutorial
1866: @section Stack-Effect Comments
1.66 anton 1867: @cindex stack-effect comments, tutorial
1868: @cindex --, tutorial
1.48 anton 1869: By convention the comment after the name of a definition describes the
1870: stack effect: The part in from of the @samp{--} describes the state of
1871: the stack before the execution of the definition, i.e., the parameters
1872: that are passed into the colon definition; the part behind the @samp{--}
1873: is the state of the stack after the execution of the definition, i.e.,
1874: the results of the definition. The stack comment only shows the top
1875: stack items that the definition accesses and/or changes.
1876:
1877: You should put a correct stack effect on every definition, even if it is
1878: just @code{( -- )}. You should also add some descriptive comment to
1879: more complicated words (I usually do this in the lines following
1880: @code{:}). If you don't do this, your code becomes unreadable (because
1881: you have to work through every definition before you can undertsand
1882: any).
1883:
1884: @assignment
1885: The stack effect of @code{swap} can be written like this: @code{x1 x2 --
1886: x2 x1}. Describe the stack effect of @code{-}, @code{drop}, @code{dup},
1887: @code{over}, @code{rot}, @code{nip}, and @code{tuck}. Hint: When you
1.65 anton 1888: are done, you can compare your stack effects to those in this manual
1.48 anton 1889: (@pxref{Word Index}).
1890: @endassignment
1891:
1892: Sometimes programmers put comments at various places in colon
1893: definitions that describe the contents of the stack at that place (stack
1894: comments); i.e., they are like the first part of a stack-effect
1895: comment. E.g.,
1896:
1897: @example
1898: : cubed ( n -- n^3 )
1899: dup squared ( n n^2 ) * ;
1900: @end example
1901:
1902: In this case the stack comment is pretty superfluous, because the word
1903: is simple enough. If you think it would be a good idea to add such a
1904: comment to increase readability, you should also consider factoring the
1905: word into several simpler words (@pxref{Factoring Tutorial,,
1.60 anton 1906: Factoring}), which typically eliminates the need for the stack comment;
1.48 anton 1907: however, if you decide not to refactor it, then having such a comment is
1908: better than not having it.
1909:
1910: The names of the stack items in stack-effect and stack comments in the
1911: standard, in this manual, and in many programs specify the type through
1912: a type prefix, similar to Fortran and Hungarian notation. The most
1913: frequent prefixes are:
1914:
1915: @table @code
1916: @item n
1917: signed integer
1918: @item u
1919: unsigned integer
1920: @item c
1921: character
1922: @item f
1923: Boolean flags, i.e. @code{false} or @code{true}.
1924: @item a-addr,a-
1925: Cell-aligned address
1926: @item c-addr,c-
1927: Char-aligned address (note that a Char may have two bytes in Windows NT)
1928: @item xt
1929: Execution token, same size as Cell
1930: @item w,x
1931: Cell, can contain an integer or an address. It usually takes 32, 64 or
1932: 16 bits (depending on your platform and Forth system). A cell is more
1933: commonly known as machine word, but the term @emph{word} already means
1934: something different in Forth.
1935: @item d
1936: signed double-cell integer
1937: @item ud
1938: unsigned double-cell integer
1939: @item r
1940: Float (on the FP stack)
1941: @end table
1942:
1943: You can find a more complete list in @ref{Notation}.
1944:
1945: @assignment
1946: Write stack-effect comments for all definitions you have written up to
1947: now.
1948: @endassignment
1949:
1950:
1951: @node Types Tutorial, Factoring Tutorial, Stack-Effect Comments Tutorial, Tutorial
1952: @section Types
1.66 anton 1953: @cindex types tutorial
1.48 anton 1954:
1955: In Forth the names of the operations are not overloaded; so similar
1956: operations on different types need different names; e.g., @code{+} adds
1957: integers, and you have to use @code{f+} to add floating-point numbers.
1958: The following prefixes are often used for related operations on
1959: different types:
1960:
1961: @table @code
1962: @item (none)
1963: signed integer
1964: @item u
1965: unsigned integer
1966: @item c
1967: character
1968: @item d
1969: signed double-cell integer
1970: @item ud, du
1971: unsigned double-cell integer
1972: @item 2
1973: two cells (not-necessarily double-cell numbers)
1974: @item m, um
1975: mixed single-cell and double-cell operations
1976: @item f
1977: floating-point (note that in stack comments @samp{f} represents flags,
1.66 anton 1978: and @samp{r} represents FP numbers).
1.48 anton 1979: @end table
1980:
1981: If there are no differences between the signed and the unsigned variant
1982: (e.g., for @code{+}), there is only the prefix-less variant.
1983:
1984: Forth does not perform type checking, neither at compile time, nor at
1985: run time. If you use the wrong oeration, the data are interpreted
1986: incorrectly:
1987:
1988: @example
1989: -1 u.
1990: @end example
1991:
1992: If you have only experience with type-checked languages until now, and
1993: have heard how important type-checking is, don't panic! In my
1994: experience (and that of other Forthers), type errors in Forth code are
1995: usually easy to find (once you get used to it), the increased vigilance
1996: of the programmer tends to catch some harder errors in addition to most
1997: type errors, and you never have to work around the type system, so in
1998: most situations the lack of type-checking seems to be a win (projects to
1999: add type checking to Forth have not caught on).
2000:
2001:
2002: @node Factoring Tutorial, Designing the stack effect Tutorial, Types Tutorial, Tutorial
2003: @section Factoring
1.66 anton 2004: @cindex factoring tutorial
1.48 anton 2005:
2006: If you try to write longer definitions, you will soon find it hard to
2007: keep track of the stack contents. Therefore, good Forth programmers
2008: tend to write only short definitions (e.g., three lines). The art of
2009: finding meaningful short definitions is known as factoring (as in
2010: factoring polynomials).
2011:
2012: Well-factored programs offer additional advantages: smaller, more
2013: general words, are easier to test and debug and can be reused more and
2014: better than larger, specialized words.
2015:
2016: So, if you run into difficulties with stack management, when writing
2017: code, try to define meaningful factors for the word, and define the word
2018: in terms of those. Even if a factor contains only two words, it is
2019: often helpful.
2020:
1.65 anton 2021: Good factoring is not easy, and it takes some practice to get the knack
2022: for it; but even experienced Forth programmers often don't find the
2023: right solution right away, but only when rewriting the program. So, if
2024: you don't come up with a good solution immediately, keep trying, don't
2025: despair.
1.48 anton 2026:
2027: @c example !!
2028:
2029:
2030: @node Designing the stack effect Tutorial, Local Variables Tutorial, Factoring Tutorial, Tutorial
2031: @section Designing the stack effect
1.66 anton 2032: @cindex Stack effect design, tutorial
2033: @cindex design of stack effects, tutorial
1.48 anton 2034:
2035: In other languages you can use an arbitrary order of parameters for a
1.65 anton 2036: function; and since there is only one result, you don't have to deal with
1.48 anton 2037: the order of results, either.
2038:
2039: In Forth (and other stack-based languages, e.g., Postscript) the
2040: parameter and result order of a definition is important and should be
2041: designed well. The general guideline is to design the stack effect such
2042: that the word is simple to use in most cases, even if that complicates
2043: the implementation of the word. Some concrete rules are:
2044:
2045: @itemize @bullet
2046:
2047: @item
2048: Words consume all of their parameters (e.g., @code{.}).
2049:
2050: @item
2051: If there is a convention on the order of parameters (e.g., from
2052: mathematics or another programming language), stick with it (e.g.,
2053: @code{-}).
2054:
2055: @item
2056: If one parameter usually requires only a short computation (e.g., it is
2057: a constant), pass it on the top of the stack. Conversely, parameters
2058: that usually require a long sequence of code to compute should be passed
2059: as the bottom (i.e., first) parameter. This makes the code easier to
2060: read, because reader does not need to keep track of the bottom item
2061: through a long sequence of code (or, alternatively, through stack
1.49 anton 2062: manipulations). E.g., @code{!} (store, @pxref{Memory}) expects the
1.48 anton 2063: address on top of the stack because it is usually simpler to compute
2064: than the stored value (often the address is just a variable).
2065:
2066: @item
2067: Similarly, results that are usually consumed quickly should be returned
2068: on the top of stack, whereas a result that is often used in long
2069: computations should be passed as bottom result. E.g., the file words
2070: like @code{open-file} return the error code on the top of stack, because
2071: it is usually consumed quickly by @code{throw}; moreover, the error code
2072: has to be checked before doing anything with the other results.
2073:
2074: @end itemize
2075:
2076: These rules are just general guidelines, don't lose sight of the overall
2077: goal to make the words easy to use. E.g., if the convention rule
2078: conflicts with the computation-length rule, you might decide in favour
2079: of the convention if the word will be used rarely, and in favour of the
2080: computation-length rule if the word will be used frequently (because
2081: with frequent use the cost of breaking the computation-length rule would
2082: be quite high, and frequent use makes it easier to remember an
2083: unconventional order).
2084:
2085: @c example !! structure package
2086:
1.65 anton 2087:
1.48 anton 2088: @node Local Variables Tutorial, Conditional execution Tutorial, Designing the stack effect Tutorial, Tutorial
2089: @section Local Variables
1.66 anton 2090: @cindex local variables, tutorial
1.48 anton 2091:
2092: You can define local variables (@emph{locals}) in a colon definition:
2093:
2094: @example
2095: : swap @{ a b -- b a @}
2096: b a ;
2097: 1 2 swap .s 2drop
2098: @end example
2099:
2100: (If your Forth system does not support this syntax, include
2101: @file{compat/anslocals.fs} first).
2102:
2103: In this example @code{@{ a b -- b a @}} is the locals definition; it
2104: takes two cells from the stack, puts the top of stack in @code{b} and
2105: the next stack element in @code{a}. @code{--} starts a comment ending
2106: with @code{@}}. After the locals definition, using the name of the
2107: local will push its value on the stack. You can leave the comment
2108: part (@code{-- b a}) away:
2109:
2110: @example
2111: : swap ( x1 x2 -- x2 x1 )
2112: @{ a b @} b a ;
2113: @end example
2114:
2115: In Gforth you can have several locals definitions, anywhere in a colon
2116: definition; in contrast, in a standard program you can have only one
2117: locals definition per colon definition, and that locals definition must
2118: be outside any controll structure.
2119:
2120: With locals you can write slightly longer definitions without running
2121: into stack trouble. However, I recommend trying to write colon
2122: definitions without locals for exercise purposes to help you gain the
2123: essential factoring skills.
2124:
2125: @assignment
2126: Rewrite your definitions until now with locals
2127: @endassignment
2128:
1.66 anton 2129: Reference: @ref{Locals}.
2130:
1.48 anton 2131:
2132: @node Conditional execution Tutorial, Flags and Comparisons Tutorial, Local Variables Tutorial, Tutorial
2133: @section Conditional execution
1.66 anton 2134: @cindex conditionals, tutorial
2135: @cindex if, tutorial
1.48 anton 2136:
2137: In Forth you can use control structures only inside colon definitions.
2138: An @code{if}-structure looks like this:
2139:
2140: @example
2141: : abs ( n1 -- +n2 )
2142: dup 0 < if
2143: negate
2144: endif ;
2145: 5 abs .
2146: -5 abs .
2147: @end example
2148:
2149: @code{if} takes a flag from the stack. If the flag is non-zero (true),
2150: the following code is performed, otherwise execution continues after the
1.51 pazsan 2151: @code{endif} (or @code{else}). @code{<} compares the top two stack
1.48 anton 2152: elements and prioduces a flag:
2153:
2154: @example
2155: 1 2 < .
2156: 2 1 < .
2157: 1 1 < .
2158: @end example
2159:
2160: Actually the standard name for @code{endif} is @code{then}. This
2161: tutorial presents the examples using @code{endif}, because this is often
2162: less confusing for people familiar with other programming languages
2163: where @code{then} has a different meaning. If your system does not have
2164: @code{endif}, define it with
2165:
2166: @example
2167: : endif postpone then ; immediate
2168: @end example
2169:
2170: You can optionally use an @code{else}-part:
2171:
2172: @example
2173: : min ( n1 n2 -- n )
2174: 2dup < if
2175: drop
2176: else
2177: nip
2178: endif ;
2179: 2 3 min .
2180: 3 2 min .
2181: @end example
2182:
2183: @assignment
2184: Write @code{min} without @code{else}-part (hint: what's the definition
2185: of @code{nip}?).
2186: @endassignment
2187:
1.66 anton 2188: Reference: @ref{Selection}.
2189:
1.48 anton 2190:
2191: @node Flags and Comparisons Tutorial, General Loops Tutorial, Conditional execution Tutorial, Tutorial
2192: @section Flags and Comparisons
1.66 anton 2193: @cindex flags tutorial
2194: @cindex comparison tutorial
1.48 anton 2195:
2196: In a false-flag all bits are clear (0 when interpreted as integer). In
2197: a canonical true-flag all bits are set (-1 as a twos-complement signed
2198: integer); in many contexts (e.g., @code{if}) any non-zero value is
2199: treated as true flag.
2200:
2201: @example
2202: false .
2203: true .
2204: true hex u. decimal
2205: @end example
2206:
2207: Comparison words produce canonical flags:
2208:
2209: @example
2210: 1 1 = .
2211: 1 0= .
2212: 0 1 < .
2213: 0 0 < .
2214: -1 1 u< . \ type error, u< interprets -1 as large unsigned number
2215: -1 1 < .
2216: @end example
2217:
1.66 anton 2218: Gforth supports all combinations of the prefixes @code{0 u d d0 du f f0}
2219: (or none) and the comparisons @code{= <> < > <= >=}. Only a part of
2220: these combinations are standard (for details see the standard,
2221: @ref{Numeric comparison}, @ref{Floating Point} or @ref{Word Index}).
1.48 anton 2222:
2223: You can use @code{and or xor invert} can be used as operations on
2224: canonical flags. Actually they are bitwise operations:
2225:
2226: @example
2227: 1 2 and .
2228: 1 2 or .
2229: 1 3 xor .
2230: 1 invert .
2231: @end example
2232:
2233: You can convert a zero/non-zero flag into a canonical flag with
2234: @code{0<>} (and complement it on the way with @code{0=}).
2235:
2236: @example
2237: 1 0= .
2238: 1 0<> .
2239: @end example
2240:
1.65 anton 2241: You can use the all-bits-set feature of canonical flags and the bitwise
1.48 anton 2242: operation of the Boolean operations to avoid @code{if}s:
2243:
2244: @example
2245: : foo ( n1 -- n2 )
2246: 0= if
2247: 14
2248: else
2249: 0
2250: endif ;
2251: 0 foo .
2252: 1 foo .
2253:
2254: : foo ( n1 -- n2 )
2255: 0= 14 and ;
2256: 0 foo .
2257: 1 foo .
2258: @end example
2259:
2260: @assignment
2261: Write @code{min} without @code{if}.
2262: @endassignment
2263:
1.66 anton 2264: For reference, see @ref{Boolean Flags}, @ref{Numeric comparison}, and
2265: @ref{Bitwise operations}.
2266:
1.48 anton 2267:
2268: @node General Loops Tutorial, Counted loops Tutorial, Flags and Comparisons Tutorial, Tutorial
2269: @section General Loops
1.66 anton 2270: @cindex loops, indefinite, tutorial
1.48 anton 2271:
2272: The endless loop is the most simple one:
2273:
2274: @example
2275: : endless ( -- )
2276: 0 begin
2277: dup . 1+
2278: again ;
2279: endless
2280: @end example
2281:
2282: Terminate this loop by pressing @kbd{Ctrl-C} (in Gforth). @code{begin}
2283: does nothing at run-time, @code{again} jumps back to @code{begin}.
2284:
2285: A loop with one exit at any place looks like this:
2286:
2287: @example
2288: : log2 ( +n1 -- n2 )
2289: \ logarithmus dualis of n1>0, rounded down to the next integer
2290: assert( dup 0> )
2291: 2/ 0 begin
2292: over 0> while
2293: 1+ swap 2/ swap
2294: repeat
2295: nip ;
2296: 7 log2 .
2297: 8 log2 .
2298: @end example
2299:
2300: At run-time @code{while} consumes a flag; if it is 0, execution
1.51 pazsan 2301: continues behind the @code{repeat}; if the flag is non-zero, execution
1.48 anton 2302: continues behind the @code{while}. @code{Repeat} jumps back to
2303: @code{begin}, just like @code{again}.
2304:
2305: In Forth there are many combinations/abbreviations, like @code{1+}.
1.90 anton 2306: However, @code{2/} is not one of them; it shifts its argument right by
1.48 anton 2307: one bit (arithmetic shift right):
2308:
2309: @example
2310: -5 2 / .
2311: -5 2/ .
2312: @end example
2313:
2314: @code{assert(} is no standard word, but you can get it on systems other
2315: then Gforth by including @file{compat/assert.fs}. You can see what it
2316: does by trying
2317:
2318: @example
2319: 0 log2 .
2320: @end example
2321:
2322: Here's a loop with an exit at the end:
2323:
2324: @example
2325: : log2 ( +n1 -- n2 )
2326: \ logarithmus dualis of n1>0, rounded down to the next integer
2327: assert( dup 0 > )
2328: -1 begin
2329: 1+ swap 2/ swap
2330: over 0 <=
2331: until
2332: nip ;
2333: @end example
2334:
2335: @code{Until} consumes a flag; if it is non-zero, execution continues at
2336: the @code{begin}, otherwise after the @code{until}.
2337:
2338: @assignment
2339: Write a definition for computing the greatest common divisor.
2340: @endassignment
2341:
1.66 anton 2342: Reference: @ref{Simple Loops}.
2343:
1.48 anton 2344:
2345: @node Counted loops Tutorial, Recursion Tutorial, General Loops Tutorial, Tutorial
2346: @section Counted loops
1.66 anton 2347: @cindex loops, counted, tutorial
1.48 anton 2348:
2349: @example
2350: : ^ ( n1 u -- n )
2351: \ n = the uth power of u1
2352: 1 swap 0 u+do
2353: over *
2354: loop
2355: nip ;
2356: 3 2 ^ .
2357: 4 3 ^ .
2358: @end example
2359:
2360: @code{U+do} (from @file{compat/loops.fs}, if your Forth system doesn't
2361: have it) takes two numbers of the stack @code{( u3 u4 -- )}, and then
2362: performs the code between @code{u+do} and @code{loop} for @code{u3-u4}
2363: times (or not at all, if @code{u3-u4<0}).
2364:
2365: You can see the stack effect design rules at work in the stack effect of
2366: the loop start words: Since the start value of the loop is more
2367: frequently constant than the end value, the start value is passed on
2368: the top-of-stack.
2369:
2370: You can access the counter of a counted loop with @code{i}:
2371:
2372: @example
2373: : fac ( u -- u! )
2374: 1 swap 1+ 1 u+do
2375: i *
2376: loop ;
2377: 5 fac .
2378: 7 fac .
2379: @end example
2380:
2381: There is also @code{+do}, which expects signed numbers (important for
2382: deciding whether to enter the loop).
2383:
2384: @assignment
2385: Write a definition for computing the nth Fibonacci number.
2386: @endassignment
2387:
1.65 anton 2388: You can also use increments other than 1:
2389:
2390: @example
2391: : up2 ( n1 n2 -- )
2392: +do
2393: i .
2394: 2 +loop ;
2395: 10 0 up2
2396:
2397: : down2 ( n1 n2 -- )
2398: -do
2399: i .
2400: 2 -loop ;
2401: 0 10 down2
2402: @end example
1.48 anton 2403:
1.66 anton 2404: Reference: @ref{Counted Loops}.
2405:
1.48 anton 2406:
2407: @node Recursion Tutorial, Leaving definitions or loops Tutorial, Counted loops Tutorial, Tutorial
2408: @section Recursion
1.66 anton 2409: @cindex recursion tutorial
1.48 anton 2410:
2411: Usually the name of a definition is not visible in the definition; but
2412: earlier definitions are usually visible:
2413:
2414: @example
2415: 1 0 / . \ "Floating-point unidentified fault" in Gforth on most platforms
2416: : / ( n1 n2 -- n )
2417: dup 0= if
2418: -10 throw \ report division by zero
2419: endif
2420: / \ old version
2421: ;
2422: 1 0 /
2423: @end example
2424:
2425: For recursive definitions you can use @code{recursive} (non-standard) or
2426: @code{recurse}:
2427:
2428: @example
2429: : fac1 ( n -- n! ) recursive
2430: dup 0> if
2431: dup 1- fac1 *
2432: else
2433: drop 1
2434: endif ;
2435: 7 fac1 .
2436:
2437: : fac2 ( n -- n! )
2438: dup 0> if
2439: dup 1- recurse *
2440: else
2441: drop 1
2442: endif ;
2443: 8 fac2 .
2444: @end example
2445:
2446: @assignment
2447: Write a recursive definition for computing the nth Fibonacci number.
2448: @endassignment
2449:
1.66 anton 2450: Reference (including indirect recursion): @xref{Calls and returns}.
2451:
1.48 anton 2452:
2453: @node Leaving definitions or loops Tutorial, Return Stack Tutorial, Recursion Tutorial, Tutorial
2454: @section Leaving definitions or loops
1.66 anton 2455: @cindex leaving definitions, tutorial
2456: @cindex leaving loops, tutorial
1.48 anton 2457:
2458: @code{EXIT} exits the current definition right away. For every counted
2459: loop that is left in this way, an @code{UNLOOP} has to be performed
2460: before the @code{EXIT}:
2461:
2462: @c !! real examples
2463: @example
2464: : ...
2465: ... u+do
2466: ... if
2467: ... unloop exit
2468: endif
2469: ...
2470: loop
2471: ... ;
2472: @end example
2473:
2474: @code{LEAVE} leaves the innermost counted loop right away:
2475:
2476: @example
2477: : ...
2478: ... u+do
2479: ... if
2480: ... leave
2481: endif
2482: ...
2483: loop
2484: ... ;
2485: @end example
2486:
1.65 anton 2487: @c !! example
1.48 anton 2488:
1.66 anton 2489: Reference: @ref{Calls and returns}, @ref{Counted Loops}.
2490:
2491:
1.48 anton 2492: @node Return Stack Tutorial, Memory Tutorial, Leaving definitions or loops Tutorial, Tutorial
2493: @section Return Stack
1.66 anton 2494: @cindex return stack tutorial
1.48 anton 2495:
2496: In addition to the data stack Forth also has a second stack, the return
2497: stack; most Forth systems store the return addresses of procedure calls
2498: there (thus its name). Programmers can also use this stack:
2499:
2500: @example
2501: : foo ( n1 n2 -- )
2502: .s
2503: >r .s
1.50 anton 2504: r@@ .
1.48 anton 2505: >r .s
1.50 anton 2506: r@@ .
1.48 anton 2507: r> .
1.50 anton 2508: r@@ .
1.48 anton 2509: r> . ;
2510: 1 2 foo
2511: @end example
2512:
2513: @code{>r} takes an element from the data stack and pushes it onto the
2514: return stack; conversely, @code{r>} moves an elementm from the return to
2515: the data stack; @code{r@@} pushes a copy of the top of the return stack
2516: on the return stack.
2517:
2518: Forth programmers usually use the return stack for storing data
2519: temporarily, if using the data stack alone would be too complex, and
2520: factoring and locals are not an option:
2521:
2522: @example
2523: : 2swap ( x1 x2 x3 x4 -- x3 x4 x1 x2 )
2524: rot >r rot r> ;
2525: @end example
2526:
2527: The return address of the definition and the loop control parameters of
2528: counted loops usually reside on the return stack, so you have to take
2529: all items, that you have pushed on the return stack in a colon
2530: definition or counted loop, from the return stack before the definition
2531: or loop ends. You cannot access items that you pushed on the return
2532: stack outside some definition or loop within the definition of loop.
2533:
2534: If you miscount the return stack items, this usually ends in a crash:
2535:
2536: @example
2537: : crash ( n -- )
2538: >r ;
2539: 5 crash
2540: @end example
2541:
2542: You cannot mix using locals and using the return stack (according to the
2543: standard; Gforth has no problem). However, they solve the same
2544: problems, so this shouldn't be an issue.
2545:
2546: @assignment
2547: Can you rewrite any of the definitions you wrote until now in a better
2548: way using the return stack?
2549: @endassignment
2550:
1.66 anton 2551: Reference: @ref{Return stack}.
2552:
1.48 anton 2553:
2554: @node Memory Tutorial, Characters and Strings Tutorial, Return Stack Tutorial, Tutorial
2555: @section Memory
1.66 anton 2556: @cindex memory access/allocation tutorial
1.48 anton 2557:
2558: You can create a global variable @code{v} with
2559:
2560: @example
2561: variable v ( -- addr )
2562: @end example
2563:
2564: @code{v} pushes the address of a cell in memory on the stack. This cell
2565: was reserved by @code{variable}. You can use @code{!} (store) to store
2566: values into this cell and @code{@@} (fetch) to load the value from the
2567: stack into memory:
2568:
2569: @example
2570: v .
2571: 5 v ! .s
1.50 anton 2572: v @@ .
1.48 anton 2573: @end example
2574:
1.65 anton 2575: You can see a raw dump of memory with @code{dump}:
2576:
2577: @example
2578: v 1 cells .s dump
2579: @end example
2580:
2581: @code{Cells ( n1 -- n2 )} gives you the number of bytes (or, more
2582: generally, address units (aus)) that @code{n1 cells} occupy. You can
2583: also reserve more memory:
1.48 anton 2584:
2585: @example
2586: create v2 20 cells allot
1.65 anton 2587: v2 20 cells dump
1.48 anton 2588: @end example
2589:
1.65 anton 2590: creates a word @code{v2} and reserves 20 uninitialized cells; the
2591: address pushed by @code{v2} points to the start of these 20 cells. You
2592: can use address arithmetic to access these cells:
1.48 anton 2593:
2594: @example
2595: 3 v2 5 cells + !
1.65 anton 2596: v2 20 cells dump
1.48 anton 2597: @end example
2598:
2599: You can reserve and initialize memory with @code{,}:
2600:
2601: @example
2602: create v3
2603: 5 , 4 , 3 , 2 , 1 ,
1.50 anton 2604: v3 @@ .
2605: v3 cell+ @@ .
2606: v3 2 cells + @@ .
1.65 anton 2607: v3 5 cells dump
1.48 anton 2608: @end example
2609:
2610: @assignment
2611: Write a definition @code{vsum ( addr u -- n )} that computes the sum of
2612: @code{u} cells, with the first of these cells at @code{addr}, the next
2613: one at @code{addr cell+} etc.
2614: @endassignment
2615:
2616: You can also reserve memory without creating a new word:
2617:
2618: @example
1.60 anton 2619: here 10 cells allot .
2620: here .
1.48 anton 2621: @end example
2622:
2623: @code{Here} pushes the start address of the memory area. You should
2624: store it somewhere, or you will have a hard time finding the memory area
2625: again.
2626:
2627: @code{Allot} manages dictionary memory. The dictionary memory contains
2628: the system's data structures for words etc. on Gforth and most other
2629: Forth systems. It is managed like a stack: You can free the memory that
2630: you have just @code{allot}ed with
2631:
2632: @example
2633: -10 cells allot
1.60 anton 2634: here .
1.48 anton 2635: @end example
2636:
2637: Note that you cannot do this if you have created a new word in the
2638: meantime (because then your @code{allot}ed memory is no longer on the
2639: top of the dictionary ``stack'').
2640:
2641: Alternatively, you can use @code{allocate} and @code{free} which allow
2642: freeing memory in any order:
2643:
2644: @example
2645: 10 cells allocate throw .s
2646: 20 cells allocate throw .s
2647: swap
2648: free throw
2649: free throw
2650: @end example
2651:
2652: The @code{throw}s deal with errors (e.g., out of memory).
2653:
1.65 anton 2654: And there is also a
2655: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
2656: garbage collector}, which eliminates the need to @code{free} memory
2657: explicitly.
1.48 anton 2658:
1.66 anton 2659: Reference: @ref{Memory}.
2660:
1.48 anton 2661:
2662: @node Characters and Strings Tutorial, Alignment Tutorial, Memory Tutorial, Tutorial
2663: @section Characters and Strings
1.66 anton 2664: @cindex strings tutorial
2665: @cindex characters tutorial
1.48 anton 2666:
2667: On the stack characters take up a cell, like numbers. In memory they
2668: have their own size (one 8-bit byte on most systems), and therefore
2669: require their own words for memory access:
2670:
2671: @example
2672: create v4
2673: 104 c, 97 c, 108 c, 108 c, 111 c,
1.50 anton 2674: v4 4 chars + c@@ .
1.65 anton 2675: v4 5 chars dump
1.48 anton 2676: @end example
2677:
2678: The preferred representation of strings on the stack is @code{addr
2679: u-count}, where @code{addr} is the address of the first character and
2680: @code{u-count} is the number of characters in the string.
2681:
2682: @example
2683: v4 5 type
2684: @end example
2685:
2686: You get a string constant with
2687:
2688: @example
2689: s" hello, world" .s
2690: type
2691: @end example
2692:
2693: Make sure you have a space between @code{s"} and the string; @code{s"}
2694: is a normal Forth word and must be delimited with white space (try what
2695: happens when you remove the space).
2696:
2697: However, this interpretive use of @code{s"} is quite restricted: the
2698: string exists only until the next call of @code{s"} (some Forth systems
2699: keep more than one of these strings, but usually they still have a
1.62 crook 2700: limited lifetime).
1.48 anton 2701:
2702: @example
2703: s" hello," s" world" .s
2704: type
2705: type
2706: @end example
2707:
1.62 crook 2708: You can also use @code{s"} in a definition, and the resulting
2709: strings then live forever (well, for as long as the definition):
1.48 anton 2710:
2711: @example
2712: : foo s" hello," s" world" ;
2713: foo .s
2714: type
2715: type
2716: @end example
2717:
2718: @assignment
2719: @code{Emit ( c -- )} types @code{c} as character (not a number).
2720: Implement @code{type ( addr u -- )}.
2721: @endassignment
2722:
1.66 anton 2723: Reference: @ref{Memory Blocks}.
2724:
2725:
1.84 pazsan 2726: @node Alignment Tutorial, Files Tutorial, Characters and Strings Tutorial, Tutorial
1.48 anton 2727: @section Alignment
1.66 anton 2728: @cindex alignment tutorial
2729: @cindex memory alignment tutorial
1.48 anton 2730:
2731: On many processors cells have to be aligned in memory, if you want to
2732: access them with @code{@@} and @code{!} (and even if the processor does
1.62 crook 2733: not require alignment, access to aligned cells is faster).
1.48 anton 2734:
2735: @code{Create} aligns @code{here} (i.e., the place where the next
2736: allocation will occur, and that the @code{create}d word points to).
2737: Likewise, the memory produced by @code{allocate} starts at an aligned
2738: address. Adding a number of @code{cells} to an aligned address produces
2739: another aligned address.
2740:
2741: However, address arithmetic involving @code{char+} and @code{chars} can
2742: create an address that is not cell-aligned. @code{Aligned ( addr --
2743: a-addr )} produces the next aligned address:
2744:
2745: @example
1.50 anton 2746: v3 char+ aligned .s @@ .
2747: v3 char+ .s @@ .
1.48 anton 2748: @end example
2749:
2750: Similarly, @code{align} advances @code{here} to the next aligned
2751: address:
2752:
2753: @example
2754: create v5 97 c,
2755: here .
2756: align here .
2757: 1000 ,
2758: @end example
2759:
2760: Note that you should use aligned addresses even if your processor does
2761: not require them, if you want your program to be portable.
2762:
1.66 anton 2763: Reference: @ref{Address arithmetic}.
2764:
1.48 anton 2765:
1.84 pazsan 2766: @node Files Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Alignment Tutorial, Tutorial
2767: @section Files
2768: @cindex files tutorial
2769:
2770: This section gives a short introduction into how to use files inside
2771: Forth. It's broken up into five easy steps:
2772:
2773: @enumerate 1
2774: @item Opened an ASCII text file for input
2775: @item Opened a file for output
2776: @item Read input file until string matched (or some other condition matched)
2777: @item Wrote some lines from input ( modified or not) to output
2778: @item Closed the files.
2779: @end enumerate
2780:
2781: @subsection Open file for input
2782:
2783: @example
2784: s" foo.in" r/o open-file throw Value fd-in
2785: @end example
2786:
2787: @subsection Create file for output
2788:
2789: @example
2790: s" foo.out" w/o create-file throw Value fd-out
2791: @end example
2792:
2793: The available file modes are r/o for read-only access, r/w for
2794: read-write access, and w/o for write-only access. You could open both
2795: files with r/w, too, if you like. All file words return error codes; for
2796: most applications, it's best to pass there error codes with @code{throw}
2797: to the outer error handler.
2798:
2799: If you want words for opening and assigning, define them as follows:
2800:
2801: @example
2802: 0 Value fd-in
2803: 0 Value fd-out
2804: : open-input ( addr u -- ) r/o open-file throw to fd-in ;
2805: : open-output ( addr u -- ) w/o create-file throw to fd-out ;
2806: @end example
2807:
2808: Usage example:
2809:
2810: @example
2811: s" foo.in" open-input
2812: s" foo.out" open-output
2813: @end example
2814:
2815: @subsection Scan file for a particular line
2816:
2817: @example
2818: 256 Constant max-line
2819: Create line-buffer max-line 2 + allot
2820:
2821: : scan-file ( addr u -- )
2822: begin
2823: line-buffer max-line fd-in read-line throw
2824: while
2825: >r 2dup line-buffer r> compare 0=
2826: until
2827: else
2828: drop
2829: then
2830: 2drop ;
2831: @end example
2832:
2833: @code{read-line ( addr u1 fd -- u2 flag ior )} reads up to u1 bytes into
1.94 anton 2834: the buffer at addr, and returns the number of bytes read, a flag that is
2835: false when the end of file is reached, and an error code.
1.84 pazsan 2836:
2837: @code{compare ( addr1 u1 addr2 u2 -- n )} compares two strings and
2838: returns zero if both strings are equal. It returns a positive number if
2839: the first string is lexically greater, a negative if the second string
2840: is lexically greater.
2841:
2842: We haven't seen this loop here; it has two exits. Since the @code{while}
2843: exits with the number of bytes read on the stack, we have to clean up
2844: that separately; that's after the @code{else}.
2845:
2846: Usage example:
2847:
2848: @example
2849: s" The text I search is here" scan-file
2850: @end example
2851:
2852: @subsection Copy input to output
2853:
2854: @example
2855: : copy-file ( -- )
2856: begin
2857: line-buffer max-line fd-in read-line throw
2858: while
2859: line-buffer swap fd-out write-file throw
2860: repeat ;
2861: @end example
2862:
2863: @subsection Close files
2864:
2865: @example
2866: fd-in close-file throw
2867: fd-out close-file throw
2868: @end example
2869:
2870: Likewise, you can put that into definitions, too:
2871:
2872: @example
2873: : close-input ( -- ) fd-in close-file throw ;
2874: : close-output ( -- ) fd-out close-file throw ;
2875: @end example
2876:
2877: @assignment
2878: How could you modify @code{copy-file} so that it copies until a second line is
2879: matched? Can you write a program that extracts a section of a text file,
2880: given the line that starts and the line that terminates that section?
2881: @endassignment
2882:
2883: @node Interpretation and Compilation Semantics and Immediacy Tutorial, Execution Tokens Tutorial, Files Tutorial, Tutorial
1.48 anton 2884: @section Interpretation and Compilation Semantics and Immediacy
1.66 anton 2885: @cindex semantics tutorial
2886: @cindex interpretation semantics tutorial
2887: @cindex compilation semantics tutorial
2888: @cindex immediate, tutorial
1.48 anton 2889:
2890: When a word is compiled, it behaves differently from being interpreted.
2891: E.g., consider @code{+}:
2892:
2893: @example
2894: 1 2 + .
2895: : foo + ;
2896: @end example
2897:
2898: These two behaviours are known as compilation and interpretation
2899: semantics. For normal words (e.g., @code{+}), the compilation semantics
2900: is to append the interpretation semantics to the currently defined word
2901: (@code{foo} in the example above). I.e., when @code{foo} is executed
2902: later, the interpretation semantics of @code{+} (i.e., adding two
2903: numbers) will be performed.
2904:
2905: However, there are words with non-default compilation semantics, e.g.,
2906: the control-flow words like @code{if}. You can use @code{immediate} to
2907: change the compilation semantics of the last defined word to be equal to
2908: the interpretation semantics:
2909:
2910: @example
2911: : [FOO] ( -- )
2912: 5 . ; immediate
2913:
2914: [FOO]
2915: : bar ( -- )
2916: [FOO] ;
2917: bar
2918: see bar
2919: @end example
2920:
2921: Two conventions to mark words with non-default compilation semnatics are
2922: names with brackets (more frequently used) and to write them all in
2923: upper case (less frequently used).
2924:
2925: In Gforth (and many other systems) you can also remove the
2926: interpretation semantics with @code{compile-only} (the compilation
2927: semantics is derived from the original interpretation semantics):
2928:
2929: @example
2930: : flip ( -- )
2931: 6 . ; compile-only \ but not immediate
2932: flip
2933:
2934: : flop ( -- )
2935: flip ;
2936: flop
2937: @end example
2938:
2939: In this example the interpretation semantics of @code{flop} is equal to
2940: the original interpretation semantics of @code{flip}.
2941:
2942: The text interpreter has two states: in interpret state, it performs the
2943: interpretation semantics of words it encounters; in compile state, it
2944: performs the compilation semantics of these words.
2945:
2946: Among other things, @code{:} switches into compile state, and @code{;}
2947: switches back to interpret state. They contain the factors @code{]}
2948: (switch to compile state) and @code{[} (switch to interpret state), that
2949: do nothing but switch the state.
2950:
2951: @example
2952: : xxx ( -- )
2953: [ 5 . ]
2954: ;
2955:
2956: xxx
2957: see xxx
2958: @end example
2959:
2960: These brackets are also the source of the naming convention mentioned
2961: above.
2962:
1.66 anton 2963: Reference: @ref{Interpretation and Compilation Semantics}.
2964:
1.48 anton 2965:
2966: @node Execution Tokens Tutorial, Exceptions Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Tutorial
2967: @section Execution Tokens
1.66 anton 2968: @cindex execution tokens tutorial
2969: @cindex XT tutorial
1.48 anton 2970:
2971: @code{' word} gives you the execution token (XT) of a word. The XT is a
2972: cell representing the interpretation semantics of a word. You can
2973: execute this semantics with @code{execute}:
2974:
2975: @example
2976: ' + .s
2977: 1 2 rot execute .
2978: @end example
2979:
2980: The XT is similar to a function pointer in C. However, parameter
2981: passing through the stack makes it a little more flexible:
2982:
2983: @example
2984: : map-array ( ... addr u xt -- ... )
1.50 anton 2985: \ executes xt ( ... x -- ... ) for every element of the array starting
2986: \ at addr and containing u elements
1.48 anton 2987: @{ xt @}
2988: cells over + swap ?do
1.50 anton 2989: i @@ xt execute
1.48 anton 2990: 1 cells +loop ;
2991:
2992: create a 3 , 4 , 2 , -1 , 4 ,
2993: a 5 ' . map-array .s
2994: 0 a 5 ' + map-array .
2995: s" max-n" environment? drop .s
2996: a 5 ' min map-array .
2997: @end example
2998:
2999: You can use map-array with the XTs of words that consume one element
3000: more than they produce. In theory you can also use it with other XTs,
3001: but the stack effect then depends on the size of the array, which is
3002: hard to understand.
3003:
1.51 pazsan 3004: Since XTs are cell-sized, you can store them in memory and manipulate
3005: them on the stack like other cells. You can also compile the XT into a
1.48 anton 3006: word with @code{compile,}:
3007:
3008: @example
3009: : foo1 ( n1 n2 -- n )
3010: [ ' + compile, ] ;
3011: see foo
3012: @end example
3013:
3014: This is non-standard, because @code{compile,} has no compilation
3015: semantics in the standard, but it works in good Forth systems. For the
3016: broken ones, use
3017:
3018: @example
3019: : [compile,] compile, ; immediate
3020:
3021: : foo1 ( n1 n2 -- n )
3022: [ ' + ] [compile,] ;
3023: see foo
3024: @end example
3025:
3026: @code{'} is a word with default compilation semantics; it parses the
3027: next word when its interpretation semantics are executed, not during
3028: compilation:
3029:
3030: @example
3031: : foo ( -- xt )
3032: ' ;
3033: see foo
3034: : bar ( ... "word" -- ... )
3035: ' execute ;
3036: see bar
1.60 anton 3037: 1 2 bar + .
1.48 anton 3038: @end example
3039:
3040: You often want to parse a word during compilation and compile its XT so
3041: it will be pushed on the stack at run-time. @code{[']} does this:
3042:
3043: @example
3044: : xt-+ ( -- xt )
3045: ['] + ;
3046: see xt-+
3047: 1 2 xt-+ execute .
3048: @end example
3049:
3050: Many programmers tend to see @code{'} and the word it parses as one
3051: unit, and expect it to behave like @code{[']} when compiled, and are
3052: confused by the actual behaviour. If you are, just remember that the
3053: Forth system just takes @code{'} as one unit and has no idea that it is
3054: a parsing word (attempts to convenience programmers in this issue have
3055: usually resulted in even worse pitfalls, see
1.66 anton 3056: @uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,
3057: @code{State}-smartness---Why it is evil and How to Exorcise it}).
1.48 anton 3058:
3059: Note that the state of the interpreter does not come into play when
1.51 pazsan 3060: creating and executing XTs. I.e., even when you execute @code{'} in
1.48 anton 3061: compile state, it still gives you the interpretation semantics. And
3062: whatever that state is, @code{execute} performs the semantics
1.66 anton 3063: represented by the XT (i.e., for XTs produced with @code{'} the
3064: interpretation semantics).
3065:
3066: Reference: @ref{Tokens for Words}.
1.48 anton 3067:
3068:
3069: @node Exceptions Tutorial, Defining Words Tutorial, Execution Tokens Tutorial, Tutorial
3070: @section Exceptions
1.66 anton 3071: @cindex exceptions tutorial
1.48 anton 3072:
3073: @code{throw ( n -- )} causes an exception unless n is zero.
3074:
3075: @example
3076: 100 throw .s
3077: 0 throw .s
3078: @end example
3079:
3080: @code{catch ( ... xt -- ... n )} behaves similar to @code{execute}, but
3081: it catches exceptions and pushes the number of the exception on the
3082: stack (or 0, if the xt executed without exception). If there was an
3083: exception, the stacks have the same depth as when entering @code{catch}:
3084:
3085: @example
3086: .s
3087: 3 0 ' / catch .s
3088: 3 2 ' / catch .s
3089: @end example
3090:
3091: @assignment
3092: Try the same with @code{execute} instead of @code{catch}.
3093: @endassignment
3094:
3095: @code{Throw} always jumps to the dynamically next enclosing
3096: @code{catch}, even if it has to leave several call levels to achieve
3097: this:
3098:
3099: @example
3100: : foo 100 throw ;
3101: : foo1 foo ." after foo" ;
1.51 pazsan 3102: : bar ['] foo1 catch ;
1.60 anton 3103: bar .
1.48 anton 3104: @end example
3105:
3106: It is often important to restore a value upon leaving a definition, even
3107: if the definition is left through an exception. You can ensure this
3108: like this:
3109:
3110: @example
3111: : ...
3112: save-x
1.51 pazsan 3113: ['] word-changing-x catch ( ... n )
1.48 anton 3114: restore-x
3115: ( ... n ) throw ;
3116: @end example
3117:
1.55 anton 3118: Gforth provides an alternative syntax in addition to @code{catch}:
1.48 anton 3119: @code{try ... recover ... endtry}. If the code between @code{try} and
3120: @code{recover} has an exception, the stack depths are restored, the
3121: exception number is pushed on the stack, and the code between
3122: @code{recover} and @code{endtry} is performed. E.g., the definition for
3123: @code{catch} is
3124:
3125: @example
3126: : catch ( x1 .. xn xt -- y1 .. ym 0 / z1 .. zn error ) \ exception
3127: try
3128: execute 0
3129: recover
3130: nip
3131: endtry ;
3132: @end example
3133:
3134: The equivalent to the restoration code above is
3135:
3136: @example
3137: : ...
3138: save-x
3139: try
1.92 anton 3140: word-changing-x 0
3141: recover endtry
1.48 anton 3142: restore-x
3143: throw ;
3144: @end example
3145:
1.92 anton 3146: This works if @code{word-changing-x} does not change the stack depth,
3147: otherwise you should add some code between @code{recover} and
3148: @code{endtry} to balance the stack.
1.48 anton 3149:
1.66 anton 3150: Reference: @ref{Exception Handling}.
3151:
1.48 anton 3152:
3153: @node Defining Words Tutorial, Arrays and Records Tutorial, Exceptions Tutorial, Tutorial
3154: @section Defining Words
1.66 anton 3155: @cindex defining words tutorial
3156: @cindex does> tutorial
3157: @cindex create...does> tutorial
3158:
3159: @c before semantics?
1.48 anton 3160:
3161: @code{:}, @code{create}, and @code{variable} are definition words: They
3162: define other words. @code{Constant} is another definition word:
3163:
3164: @example
3165: 5 constant foo
3166: foo .
3167: @end example
3168:
3169: You can also use the prefixes @code{2} (double-cell) and @code{f}
3170: (floating point) with @code{variable} and @code{constant}.
3171:
3172: You can also define your own defining words. E.g.:
3173:
3174: @example
3175: : variable ( "name" -- )
3176: create 0 , ;
3177: @end example
3178:
3179: You can also define defining words that create words that do something
3180: other than just producing their address:
3181:
3182: @example
3183: : constant ( n "name" -- )
3184: create ,
3185: does> ( -- n )
1.50 anton 3186: ( addr ) @@ ;
1.48 anton 3187:
3188: 5 constant foo
3189: foo .
3190: @end example
3191:
3192: The definition of @code{constant} above ends at the @code{does>}; i.e.,
3193: @code{does>} replaces @code{;}, but it also does something else: It
3194: changes the last defined word such that it pushes the address of the
3195: body of the word and then performs the code after the @code{does>}
3196: whenever it is called.
3197:
3198: In the example above, @code{constant} uses @code{,} to store 5 into the
3199: body of @code{foo}. When @code{foo} executes, it pushes the address of
3200: the body onto the stack, then (in the code after the @code{does>})
3201: fetches the 5 from there.
3202:
3203: The stack comment near the @code{does>} reflects the stack effect of the
3204: defined word, not the stack effect of the code after the @code{does>}
3205: (the difference is that the code expects the address of the body that
3206: the stack comment does not show).
3207:
3208: You can use these definition words to do factoring in cases that involve
3209: (other) definition words. E.g., a field offset is always added to an
3210: address. Instead of defining
3211:
3212: @example
3213: 2 cells constant offset-field1
3214: @end example
3215:
3216: and using this like
3217:
3218: @example
3219: ( addr ) offset-field1 +
3220: @end example
3221:
3222: you can define a definition word
3223:
3224: @example
3225: : simple-field ( n "name" -- )
3226: create ,
3227: does> ( n1 -- n1+n )
1.50 anton 3228: ( addr ) @@ + ;
1.48 anton 3229: @end example
1.21 crook 3230:
1.48 anton 3231: Definition and use of field offsets now look like this:
1.21 crook 3232:
1.48 anton 3233: @example
3234: 2 cells simple-field field1
1.60 anton 3235: create mystruct 4 cells allot
3236: mystruct .s field1 .s drop
1.48 anton 3237: @end example
1.21 crook 3238:
1.48 anton 3239: If you want to do something with the word without performing the code
3240: after the @code{does>}, you can access the body of a @code{create}d word
3241: with @code{>body ( xt -- addr )}:
1.21 crook 3242:
1.48 anton 3243: @example
3244: : value ( n "name" -- )
3245: create ,
3246: does> ( -- n1 )
1.50 anton 3247: @@ ;
1.48 anton 3248: : to ( n "name" -- )
3249: ' >body ! ;
1.21 crook 3250:
1.48 anton 3251: 5 value foo
3252: foo .
3253: 7 to foo
3254: foo .
3255: @end example
1.21 crook 3256:
1.48 anton 3257: @assignment
3258: Define @code{defer ( "name" -- )}, which creates a word that stores an
3259: XT (at the start the XT of @code{abort}), and upon execution
3260: @code{execute}s the XT. Define @code{is ( xt "name" -- )} that stores
3261: @code{xt} into @code{name}, a word defined with @code{defer}. Indirect
3262: recursion is one application of @code{defer}.
3263: @endassignment
1.29 crook 3264:
1.66 anton 3265: Reference: @ref{User-defined Defining Words}.
3266:
3267:
1.48 anton 3268: @node Arrays and Records Tutorial, POSTPONE Tutorial, Defining Words Tutorial, Tutorial
3269: @section Arrays and Records
1.66 anton 3270: @cindex arrays tutorial
3271: @cindex records tutorial
3272: @cindex structs tutorial
1.29 crook 3273:
1.48 anton 3274: Forth has no standard words for defining data structures such as arrays
3275: and records (structs in C terminology), but you can build them yourself
3276: based on address arithmetic. You can also define words for defining
3277: arrays and records (@pxref{Defining Words Tutorial,, Defining Words}).
1.29 crook 3278:
1.48 anton 3279: One of the first projects a Forth newcomer sets out upon when learning
3280: about defining words is an array defining word (possibly for
3281: n-dimensional arrays). Go ahead and do it, I did it, too; you will
3282: learn something from it. However, don't be disappointed when you later
3283: learn that you have little use for these words (inappropriate use would
3284: be even worse). I have not yet found a set of useful array words yet;
3285: the needs are just too diverse, and named, global arrays (the result of
3286: naive use of defining words) are often not flexible enough (e.g.,
1.66 anton 3287: consider how to pass them as parameters). Another such project is a set
3288: of words to help dealing with strings.
1.29 crook 3289:
1.48 anton 3290: On the other hand, there is a useful set of record words, and it has
3291: been defined in @file{compat/struct.fs}; these words are predefined in
3292: Gforth. They are explained in depth elsewhere in this manual (see
3293: @pxref{Structures}). The @code{simple-field} example above is
3294: simplified variant of fields in this package.
1.21 crook 3295:
3296:
1.48 anton 3297: @node POSTPONE Tutorial, Literal Tutorial, Arrays and Records Tutorial, Tutorial
3298: @section @code{POSTPONE}
1.66 anton 3299: @cindex postpone tutorial
1.21 crook 3300:
1.48 anton 3301: You can compile the compilation semantics (instead of compiling the
3302: interpretation semantics) of a word with @code{POSTPONE}:
1.21 crook 3303:
1.48 anton 3304: @example
3305: : MY-+ ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
1.51 pazsan 3306: POSTPONE + ; immediate
1.48 anton 3307: : foo ( n1 n2 -- n )
3308: MY-+ ;
3309: 1 2 foo .
3310: see foo
3311: @end example
1.21 crook 3312:
1.48 anton 3313: During the definition of @code{foo} the text interpreter performs the
3314: compilation semantics of @code{MY-+}, which performs the compilation
3315: semantics of @code{+}, i.e., it compiles @code{+} into @code{foo}.
3316:
3317: This example also displays separate stack comments for the compilation
3318: semantics and for the stack effect of the compiled code. For words with
3319: default compilation semantics these stack effects are usually not
3320: displayed; the stack effect of the compilation semantics is always
3321: @code{( -- )} for these words, the stack effect for the compiled code is
3322: the stack effect of the interpretation semantics.
3323:
3324: Note that the state of the interpreter does not come into play when
3325: performing the compilation semantics in this way. You can also perform
3326: it interpretively, e.g.:
3327:
3328: @example
3329: : foo2 ( n1 n2 -- n )
3330: [ MY-+ ] ;
3331: 1 2 foo .
3332: see foo
3333: @end example
1.21 crook 3334:
1.48 anton 3335: However, there are some broken Forth systems where this does not always
1.62 crook 3336: work, and therefore this practice was been declared non-standard in
1.48 anton 3337: 1999.
3338: @c !! repair.fs
3339:
3340: Here is another example for using @code{POSTPONE}:
1.44 crook 3341:
1.48 anton 3342: @example
3343: : MY-- ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
3344: POSTPONE negate POSTPONE + ; immediate compile-only
3345: : bar ( n1 n2 -- n )
3346: MY-- ;
3347: 2 1 bar .
3348: see bar
3349: @end example
1.21 crook 3350:
1.48 anton 3351: You can define @code{ENDIF} in this way:
1.21 crook 3352:
1.48 anton 3353: @example
3354: : ENDIF ( Compilation: orig -- )
3355: POSTPONE then ; immediate
3356: @end example
1.21 crook 3357:
1.48 anton 3358: @assignment
3359: Write @code{MY-2DUP} that has compilation semantics equivalent to
3360: @code{2dup}, but compiles @code{over over}.
3361: @endassignment
1.29 crook 3362:
1.66 anton 3363: @c !! @xref{Macros} for reference
3364:
3365:
1.48 anton 3366: @node Literal Tutorial, Advanced macros Tutorial, POSTPONE Tutorial, Tutorial
3367: @section @code{Literal}
1.66 anton 3368: @cindex literal tutorial
1.29 crook 3369:
1.48 anton 3370: You cannot @code{POSTPONE} numbers:
1.21 crook 3371:
1.48 anton 3372: @example
3373: : [FOO] POSTPONE 500 ; immediate
1.21 crook 3374: @end example
3375:
1.48 anton 3376: Instead, you can use @code{LITERAL (compilation: n --; run-time: -- n )}:
1.29 crook 3377:
1.48 anton 3378: @example
3379: : [FOO] ( compilation: --; run-time: -- n )
3380: 500 POSTPONE literal ; immediate
1.29 crook 3381:
1.60 anton 3382: : flip [FOO] ;
1.48 anton 3383: flip .
3384: see flip
3385: @end example
1.29 crook 3386:
1.48 anton 3387: @code{LITERAL} consumes a number at compile-time (when it's compilation
3388: semantics are executed) and pushes it at run-time (when the code it
3389: compiled is executed). A frequent use of @code{LITERAL} is to compile a
3390: number computed at compile time into the current word:
1.29 crook 3391:
1.48 anton 3392: @example
3393: : bar ( -- n )
3394: [ 2 2 + ] literal ;
3395: see bar
3396: @end example
1.29 crook 3397:
1.48 anton 3398: @assignment
3399: Write @code{]L} which allows writing the example above as @code{: bar (
3400: -- n ) [ 2 2 + ]L ;}
3401: @endassignment
3402:
1.66 anton 3403: @c !! @xref{Macros} for reference
3404:
1.48 anton 3405:
3406: @node Advanced macros Tutorial, Compilation Tokens Tutorial, Literal Tutorial, Tutorial
3407: @section Advanced macros
1.66 anton 3408: @cindex macros, advanced tutorial
3409: @cindex run-time code generation, tutorial
1.48 anton 3410:
1.66 anton 3411: Reconsider @code{map-array} from @ref{Execution Tokens Tutorial,,
3412: Execution Tokens}. It frequently performs @code{execute}, a relatively
3413: expensive operation in some Forth implementations. You can use
1.48 anton 3414: @code{compile,} and @code{POSTPONE} to eliminate these @code{execute}s
3415: and produce a word that contains the word to be performed directly:
3416:
3417: @c use ]] ... [[
3418: @example
3419: : compile-map-array ( compilation: xt -- ; run-time: ... addr u -- ... )
3420: \ at run-time, execute xt ( ... x -- ... ) for each element of the
3421: \ array beginning at addr and containing u elements
3422: @{ xt @}
3423: POSTPONE cells POSTPONE over POSTPONE + POSTPONE swap POSTPONE ?do
1.50 anton 3424: POSTPONE i POSTPONE @@ xt compile,
1.48 anton 3425: 1 cells POSTPONE literal POSTPONE +loop ;
3426:
3427: : sum-array ( addr u -- n )
3428: 0 rot rot [ ' + compile-map-array ] ;
3429: see sum-array
3430: a 5 sum-array .
3431: @end example
3432:
3433: You can use the full power of Forth for generating the code; here's an
3434: example where the code is generated in a loop:
3435:
3436: @example
3437: : compile-vmul-step ( compilation: n --; run-time: n1 addr1 -- n2 addr2 )
3438: \ n2=n1+(addr1)*n, addr2=addr1+cell
1.50 anton 3439: POSTPONE tuck POSTPONE @@
1.48 anton 3440: POSTPONE literal POSTPONE * POSTPONE +
3441: POSTPONE swap POSTPONE cell+ ;
3442:
3443: : compile-vmul ( compilation: addr1 u -- ; run-time: addr2 -- n )
1.51 pazsan 3444: \ n=v1*v2 (inner product), where the v_i are represented as addr_i u
1.48 anton 3445: 0 postpone literal postpone swap
3446: [ ' compile-vmul-step compile-map-array ]
3447: postpone drop ;
3448: see compile-vmul
3449:
3450: : a-vmul ( addr -- n )
1.51 pazsan 3451: \ n=a*v, where v is a vector that's as long as a and starts at addr
1.48 anton 3452: [ a 5 compile-vmul ] ;
3453: see a-vmul
3454: a a-vmul .
3455: @end example
3456:
3457: This example uses @code{compile-map-array} to show off, but you could
1.66 anton 3458: also use @code{map-array} instead (try it now!).
1.48 anton 3459:
3460: You can use this technique for efficient multiplication of large
3461: matrices. In matrix multiplication, you multiply every line of one
3462: matrix with every column of the other matrix. You can generate the code
3463: for one line once, and use it for every column. The only downside of
3464: this technique is that it is cumbersome to recover the memory consumed
3465: by the generated code when you are done (and in more complicated cases
3466: it is not possible portably).
3467:
1.66 anton 3468: @c !! @xref{Macros} for reference
3469:
3470:
1.48 anton 3471: @node Compilation Tokens Tutorial, Wordlists and Search Order Tutorial, Advanced macros Tutorial, Tutorial
3472: @section Compilation Tokens
1.66 anton 3473: @cindex compilation tokens, tutorial
3474: @cindex CT, tutorial
1.48 anton 3475:
3476: This section is Gforth-specific. You can skip it.
3477:
3478: @code{' word compile,} compiles the interpretation semantics. For words
3479: with default compilation semantics this is the same as performing the
3480: compilation semantics. To represent the compilation semantics of other
3481: words (e.g., words like @code{if} that have no interpretation
3482: semantics), Gforth has the concept of a compilation token (CT,
3483: consisting of two cells), and words @code{comp'} and @code{[comp']}.
3484: You can perform the compilation semantics represented by a CT with
3485: @code{execute}:
1.29 crook 3486:
1.48 anton 3487: @example
3488: : foo2 ( n1 n2 -- n )
3489: [ comp' + execute ] ;
3490: see foo
3491: @end example
1.29 crook 3492:
1.48 anton 3493: You can compile the compilation semantics represented by a CT with
3494: @code{postpone,}:
1.30 anton 3495:
1.48 anton 3496: @example
3497: : foo3 ( -- )
3498: [ comp' + postpone, ] ;
3499: see foo3
3500: @end example
1.30 anton 3501:
1.51 pazsan 3502: @code{[ comp' word postpone, ]} is equivalent to @code{POSTPONE word}.
1.48 anton 3503: @code{comp'} is particularly useful for words that have no
3504: interpretation semantics:
1.29 crook 3505:
1.30 anton 3506: @example
1.48 anton 3507: ' if
1.60 anton 3508: comp' if .s 2drop
1.30 anton 3509: @end example
3510:
1.66 anton 3511: Reference: @ref{Tokens for Words}.
3512:
1.29 crook 3513:
1.48 anton 3514: @node Wordlists and Search Order Tutorial, , Compilation Tokens Tutorial, Tutorial
3515: @section Wordlists and Search Order
1.66 anton 3516: @cindex wordlists tutorial
3517: @cindex search order, tutorial
1.48 anton 3518:
3519: The dictionary is not just a memory area that allows you to allocate
3520: memory with @code{allot}, it also contains the Forth words, arranged in
3521: several wordlists. When searching for a word in a wordlist,
3522: conceptually you start searching at the youngest and proceed towards
3523: older words (in reality most systems nowadays use hash-tables); i.e., if
3524: you define a word with the same name as an older word, the new word
3525: shadows the older word.
3526:
3527: Which wordlists are searched in which order is determined by the search
3528: order. You can display the search order with @code{order}. It displays
3529: first the search order, starting with the wordlist searched first, then
3530: it displays the wordlist that will contain newly defined words.
1.21 crook 3531:
1.48 anton 3532: You can create a new, empty wordlist with @code{wordlist ( -- wid )}:
1.21 crook 3533:
1.48 anton 3534: @example
3535: wordlist constant mywords
3536: @end example
1.21 crook 3537:
1.48 anton 3538: @code{Set-current ( wid -- )} sets the wordlist that will contain newly
3539: defined words (the @emph{current} wordlist):
1.21 crook 3540:
1.48 anton 3541: @example
3542: mywords set-current
3543: order
3544: @end example
1.26 crook 3545:
1.48 anton 3546: Gforth does not display a name for the wordlist in @code{mywords}
3547: because this wordlist was created anonymously with @code{wordlist}.
1.21 crook 3548:
1.48 anton 3549: You can get the current wordlist with @code{get-current ( -- wid)}. If
3550: you want to put something into a specific wordlist without overall
3551: effect on the current wordlist, this typically looks like this:
1.21 crook 3552:
1.48 anton 3553: @example
3554: get-current mywords set-current ( wid )
3555: create someword
3556: ( wid ) set-current
3557: @end example
1.21 crook 3558:
1.48 anton 3559: You can write the search order with @code{set-order ( wid1 .. widn n --
3560: )} and read it with @code{get-order ( -- wid1 .. widn n )}. The first
3561: searched wordlist is topmost.
1.21 crook 3562:
1.48 anton 3563: @example
3564: get-order mywords swap 1+ set-order
3565: order
3566: @end example
1.21 crook 3567:
1.48 anton 3568: Yes, the order of wordlists in the output of @code{order} is reversed
3569: from stack comments and the output of @code{.s} and thus unintuitive.
1.21 crook 3570:
1.48 anton 3571: @assignment
3572: Define @code{>order ( wid -- )} with adds @code{wid} as first searched
3573: wordlist to the search order. Define @code{previous ( -- )}, which
3574: removes the first searched wordlist from the search order. Experiment
3575: with boundary conditions (you will see some crashes or situations that
3576: are hard or impossible to leave).
3577: @endassignment
1.21 crook 3578:
1.48 anton 3579: The search order is a powerful foundation for providing features similar
3580: to Modula-2 modules and C++ namespaces. However, trying to modularize
3581: programs in this way has disadvantages for debugging and reuse/factoring
3582: that overcome the advantages in my experience (I don't do huge projects,
1.55 anton 3583: though). These disadvantages are not so clear in other
1.82 anton 3584: languages/programming environments, because these languages are not so
1.48 anton 3585: strong in debugging and reuse.
1.21 crook 3586:
1.66 anton 3587: @c !! example
3588:
3589: Reference: @ref{Word Lists}.
1.21 crook 3590:
1.29 crook 3591: @c ******************************************************************
1.48 anton 3592: @node Introduction, Words, Tutorial, Top
1.29 crook 3593: @comment node-name, next, previous, up
3594: @chapter An Introduction to ANS Forth
3595: @cindex Forth - an introduction
1.21 crook 3596:
1.83 anton 3597: The difference of this chapter from the Tutorial (@pxref{Tutorial}) is
3598: that it is slower-paced in its examples, but uses them to dive deep into
3599: explaining Forth internals (not covered by the Tutorial). Apart from
3600: that, this chapter covers far less material. It is suitable for reading
3601: without using a computer.
3602:
1.29 crook 3603: The primary purpose of this manual is to document Gforth. However, since
3604: Forth is not a widely-known language and there is a lack of up-to-date
3605: teaching material, it seems worthwhile to provide some introductory
1.49 anton 3606: material. For other sources of Forth-related
3607: information, see @ref{Forth-related information}.
1.21 crook 3608:
1.29 crook 3609: The examples in this section should work on any ANS Forth; the
3610: output shown was produced using Gforth. Each example attempts to
3611: reproduce the exact output that Gforth produces. If you try out the
3612: examples (and you should), what you should type is shown @kbd{like this}
3613: and Gforth's response is shown @code{like this}. The single exception is
1.30 anton 3614: that, where the example shows @key{RET} it means that you should
1.29 crook 3615: press the ``carriage return'' key. Unfortunately, some output formats for
3616: this manual cannot show the difference between @kbd{this} and
3617: @code{this} which will make trying out the examples harder (but not
3618: impossible).
1.21 crook 3619:
1.29 crook 3620: Forth is an unusual language. It provides an interactive development
3621: environment which includes both an interpreter and compiler. Forth
3622: programming style encourages you to break a problem down into many
3623: @cindex factoring
3624: small fragments (@dfn{factoring}), and then to develop and test each
3625: fragment interactively. Forth advocates assert that breaking the
3626: edit-compile-test cycle used by conventional programming languages can
3627: lead to great productivity improvements.
1.21 crook 3628:
1.29 crook 3629: @menu
1.67 anton 3630: * Introducing the Text Interpreter::
3631: * Stacks and Postfix notation::
3632: * Your first definition::
3633: * How does that work?::
3634: * Forth is written in Forth::
3635: * Review - elements of a Forth system::
3636: * Where to go next::
3637: * Exercises::
1.29 crook 3638: @end menu
1.21 crook 3639:
1.29 crook 3640: @comment ----------------------------------------------
3641: @node Introducing the Text Interpreter, Stacks and Postfix notation, Introduction, Introduction
3642: @section Introducing the Text Interpreter
3643: @cindex text interpreter
3644: @cindex outer interpreter
1.21 crook 3645:
1.30 anton 3646: @c IMO this is too detailed and the pace is too slow for
3647: @c an introduction. If you know German, take a look at
3648: @c http://www.complang.tuwien.ac.at/anton/lvas/skriptum-stack.html
3649: @c to see how I do it - anton
3650:
1.44 crook 3651: @c nac-> Where I have accepted your comments 100% and modified the text
3652: @c accordingly, I have deleted your comments. Elsewhere I have added a
3653: @c response like this to attempt to rationalise what I have done. Of
3654: @c course, this is a very clumsy mechanism for something that would be
3655: @c done far more efficiently over a beer. Please delete any dialogue
3656: @c you consider closed.
3657:
1.29 crook 3658: When you invoke the Forth image, you will see a startup banner printed
3659: and nothing else (if you have Gforth installed on your system, try
1.30 anton 3660: invoking it now, by typing @kbd{gforth@key{RET}}). Forth is now running
1.29 crook 3661: its command line interpreter, which is called the @dfn{Text Interpreter}
3662: (also known as the @dfn{Outer Interpreter}). (You will learn a lot
1.49 anton 3663: about the text interpreter as you read through this chapter, for more
3664: detail @pxref{The Text Interpreter}).
1.21 crook 3665:
1.29 crook 3666: Although it's not obvious, Forth is actually waiting for your
1.30 anton 3667: input. Type a number and press the @key{RET} key:
1.21 crook 3668:
1.26 crook 3669: @example
1.30 anton 3670: @kbd{45@key{RET}} ok
1.26 crook 3671: @end example
1.21 crook 3672:
1.29 crook 3673: Rather than give you a prompt to invite you to input something, the text
3674: interpreter prints a status message @i{after} it has processed a line
3675: of input. The status message in this case (``@code{ ok}'' followed by
3676: carriage-return) indicates that the text interpreter was able to process
3677: all of your input successfully. Now type something illegal:
3678:
3679: @example
1.30 anton 3680: @kbd{qwer341@key{RET}}
1.29 crook 3681: :1: Undefined word
3682: qwer341
3683: ^^^^^^^
3684: $400D2BA8 Bounce
3685: $400DBDA8 no.extensions
3686: @end example
1.23 crook 3687:
1.29 crook 3688: The exact text, other than the ``Undefined word'' may differ slightly on
3689: your system, but the effect is the same; when the text interpreter
3690: detects an error, it discards any remaining text on a line, resets
1.49 anton 3691: certain internal state and prints an error message. For a detailed description of error messages see @ref{Error
3692: messages}.
1.23 crook 3693:
1.29 crook 3694: The text interpreter waits for you to press carriage-return, and then
3695: processes your input line. Starting at the beginning of the line, it
3696: breaks the line into groups of characters separated by spaces. For each
3697: group of characters in turn, it makes two attempts to do something:
1.23 crook 3698:
1.29 crook 3699: @itemize @bullet
3700: @item
1.44 crook 3701: @cindex name dictionary
1.29 crook 3702: It tries to treat it as a command. It does this by searching a @dfn{name
3703: dictionary}. If the group of characters matches an entry in the name
3704: dictionary, the name dictionary provides the text interpreter with
3705: information that allows the text interpreter perform some actions. In
3706: Forth jargon, we say that the group
3707: @cindex word
3708: @cindex definition
3709: @cindex execution token
3710: @cindex xt
3711: of characters names a @dfn{word}, that the dictionary search returns an
3712: @dfn{execution token (xt)} corresponding to the @dfn{definition} of the
3713: word, and that the text interpreter executes the xt. Often, the terms
3714: @dfn{word} and @dfn{definition} are used interchangeably.
3715: @item
3716: If the text interpreter fails to find a match in the name dictionary, it
3717: tries to treat the group of characters as a number in the current number
3718: base (when you start up Forth, the current number base is base 10). If
3719: the group of characters legitimately represents a number, the text
3720: interpreter pushes the number onto a stack (we'll learn more about that
3721: in the next section).
3722: @end itemize
1.23 crook 3723:
1.29 crook 3724: If the text interpreter is unable to do either of these things with any
3725: group of characters, it discards the group of characters and the rest of
3726: the line, then prints an error message. If the text interpreter reaches
3727: the end of the line without error, it prints the status message ``@code{ ok}''
3728: followed by carriage-return.
1.21 crook 3729:
1.29 crook 3730: This is the simplest command we can give to the text interpreter:
1.23 crook 3731:
3732: @example
1.30 anton 3733: @key{RET} ok
1.23 crook 3734: @end example
1.21 crook 3735:
1.29 crook 3736: The text interpreter did everything we asked it to do (nothing) without
3737: an error, so it said that everything is ``@code{ ok}''. Try a slightly longer
3738: command:
1.21 crook 3739:
1.23 crook 3740: @example
1.30 anton 3741: @kbd{12 dup fred dup@key{RET}}
1.29 crook 3742: :1: Undefined word
3743: 12 dup fred dup
3744: ^^^^
3745: $400D2BA8 Bounce
3746: $400DBDA8 no.extensions
1.23 crook 3747: @end example
1.21 crook 3748:
1.29 crook 3749: When you press the carriage-return key, the text interpreter starts to
3750: work its way along the line:
1.21 crook 3751:
1.29 crook 3752: @itemize @bullet
3753: @item
3754: When it gets to the space after the @code{2}, it takes the group of
3755: characters @code{12} and looks them up in the name
3756: dictionary@footnote{We can't tell if it found them or not, but assume
3757: for now that it did not}. There is no match for this group of characters
3758: in the name dictionary, so it tries to treat them as a number. It is
3759: able to do this successfully, so it puts the number, 12, ``on the stack''
3760: (whatever that means).
3761: @item
3762: The text interpreter resumes scanning the line and gets the next group
3763: of characters, @code{dup}. It looks it up in the name dictionary and
3764: (you'll have to take my word for this) finds it, and executes the word
3765: @code{dup} (whatever that means).
3766: @item
3767: Once again, the text interpreter resumes scanning the line and gets the
3768: group of characters @code{fred}. It looks them up in the name
3769: dictionary, but can't find them. It tries to treat them as a number, but
3770: they don't represent any legal number.
3771: @end itemize
1.21 crook 3772:
1.29 crook 3773: At this point, the text interpreter gives up and prints an error
3774: message. The error message shows exactly how far the text interpreter
3775: got in processing the line. In particular, it shows that the text
3776: interpreter made no attempt to do anything with the final character
3777: group, @code{dup}, even though we have good reason to believe that the
3778: text interpreter would have no problem looking that word up and
3779: executing it a second time.
1.21 crook 3780:
3781:
1.29 crook 3782: @comment ----------------------------------------------
3783: @node Stacks and Postfix notation, Your first definition, Introducing the Text Interpreter, Introduction
3784: @section Stacks, postfix notation and parameter passing
3785: @cindex text interpreter
3786: @cindex outer interpreter
1.21 crook 3787:
1.29 crook 3788: In procedural programming languages (like C and Pascal), the
3789: building-block of programs is the @dfn{function} or @dfn{procedure}. These
3790: functions or procedures are called with @dfn{explicit parameters}. For
3791: example, in C we might write:
1.21 crook 3792:
1.23 crook 3793: @example
1.29 crook 3794: total = total + new_volume(length,height,depth);
1.23 crook 3795: @end example
1.21 crook 3796:
1.23 crook 3797: @noindent
1.29 crook 3798: where new_volume is a function-call to another piece of code, and total,
3799: length, height and depth are all variables. length, height and depth are
3800: parameters to the function-call.
1.21 crook 3801:
1.29 crook 3802: In Forth, the equivalent of the function or procedure is the
3803: @dfn{definition} and parameters are implicitly passed between
3804: definitions using a shared stack that is visible to the
3805: programmer. Although Forth does support variables, the existence of the
3806: stack means that they are used far less often than in most other
3807: programming languages. When the text interpreter encounters a number, it
3808: will place (@dfn{push}) it on the stack. There are several stacks (the
1.30 anton 3809: actual number is implementation-dependent ...) and the particular stack
1.29 crook 3810: used for any operation is implied unambiguously by the operation being
3811: performed. The stack used for all integer operations is called the @dfn{data
3812: stack} and, since this is the stack used most commonly, references to
3813: ``the data stack'' are often abbreviated to ``the stack''.
1.21 crook 3814:
1.29 crook 3815: The stacks have a last-in, first-out (LIFO) organisation. If you type:
1.21 crook 3816:
1.23 crook 3817: @example
1.30 anton 3818: @kbd{1 2 3@key{RET}} ok
1.23 crook 3819: @end example
1.21 crook 3820:
1.29 crook 3821: Then this instructs the text interpreter to placed three numbers on the
3822: (data) stack. An analogy for the behaviour of the stack is to take a
3823: pack of playing cards and deal out the ace (1), 2 and 3 into a pile on
3824: the table. The 3 was the last card onto the pile (``last-in'') and if
3825: you take a card off the pile then, unless you're prepared to fiddle a
3826: bit, the card that you take off will be the 3 (``first-out''). The
3827: number that will be first-out of the stack is called the @dfn{top of
3828: stack}, which
3829: @cindex TOS definition
3830: is often abbreviated to @dfn{TOS}.
1.21 crook 3831:
1.29 crook 3832: To understand how parameters are passed in Forth, consider the
3833: behaviour of the definition @code{+} (pronounced ``plus''). You will not
3834: be surprised to learn that this definition performs addition. More
3835: precisely, it adds two number together and produces a result. Where does
3836: it get the two numbers from? It takes the top two numbers off the
3837: stack. Where does it place the result? On the stack. You can act-out the
3838: behaviour of @code{+} with your playing cards like this:
1.21 crook 3839:
3840: @itemize @bullet
3841: @item
1.29 crook 3842: Pick up two cards from the stack on the table
1.21 crook 3843: @item
1.29 crook 3844: Stare at them intently and ask yourself ``what @i{is} the sum of these two
3845: numbers''
1.21 crook 3846: @item
1.29 crook 3847: Decide that the answer is 5
1.21 crook 3848: @item
1.29 crook 3849: Shuffle the two cards back into the pack and find a 5
1.21 crook 3850: @item
1.29 crook 3851: Put a 5 on the remaining ace that's on the table.
1.21 crook 3852: @end itemize
3853:
1.29 crook 3854: If you don't have a pack of cards handy but you do have Forth running,
3855: you can use the definition @code{.s} to show the current state of the stack,
3856: without affecting the stack. Type:
1.21 crook 3857:
3858: @example
1.30 anton 3859: @kbd{clearstack 1 2 3@key{RET}} ok
3860: @kbd{.s@key{RET}} <3> 1 2 3 ok
1.23 crook 3861: @end example
3862:
1.29 crook 3863: The text interpreter looks up the word @code{clearstack} and executes
3864: it; it tidies up the stack and removes any entries that may have been
3865: left on it by earlier examples. The text interpreter pushes each of the
3866: three numbers in turn onto the stack. Finally, the text interpreter
3867: looks up the word @code{.s} and executes it. The effect of executing
3868: @code{.s} is to print the ``<3>'' (the total number of items on the stack)
3869: followed by a list of all the items on the stack; the item on the far
3870: right-hand side is the TOS.
1.21 crook 3871:
1.29 crook 3872: You can now type:
1.21 crook 3873:
1.29 crook 3874: @example
1.30 anton 3875: @kbd{+ .s@key{RET}} <2> 1 5 ok
1.29 crook 3876: @end example
1.21 crook 3877:
1.29 crook 3878: @noindent
3879: which is correct; there are now 2 items on the stack and the result of
3880: the addition is 5.
1.23 crook 3881:
1.29 crook 3882: If you're playing with cards, try doing a second addition: pick up the
3883: two cards, work out that their sum is 6, shuffle them into the pack,
3884: look for a 6 and place that on the table. You now have just one item on
3885: the stack. What happens if you try to do a third addition? Pick up the
3886: first card, pick up the second card -- ah! There is no second card. This
3887: is called a @dfn{stack underflow} and consitutes an error. If you try to
1.95 anton 3888: do the same thing with Forth it often reports an error (probably a Stack
1.29 crook 3889: Underflow or an Invalid Memory Address error).
1.23 crook 3890:
1.29 crook 3891: The opposite situation to a stack underflow is a @dfn{stack overflow},
3892: which simply accepts that there is a finite amount of storage space
3893: reserved for the stack. To stretch the playing card analogy, if you had
3894: enough packs of cards and you piled the cards up on the table, you would
3895: eventually be unable to add another card; you'd hit the ceiling. Gforth
3896: allows you to set the maximum size of the stacks. In general, the only
3897: time that you will get a stack overflow is because a definition has a
3898: bug in it and is generating data on the stack uncontrollably.
1.23 crook 3899:
1.29 crook 3900: There's one final use for the playing card analogy. If you model your
3901: stack using a pack of playing cards, the maximum number of items on
3902: your stack will be 52 (I assume you didn't use the Joker). The maximum
3903: @i{value} of any item on the stack is 13 (the King). In fact, the only
3904: possible numbers are positive integer numbers 1 through 13; you can't
3905: have (for example) 0 or 27 or 3.52 or -2. If you change the way you
3906: think about some of the cards, you can accommodate different
3907: numbers. For example, you could think of the Jack as representing 0,
3908: the Queen as representing -1 and the King as representing -2. Your
1.45 crook 3909: @i{range} remains unchanged (you can still only represent a total of 13
1.29 crook 3910: numbers) but the numbers that you can represent are -2 through 10.
1.28 crook 3911:
1.29 crook 3912: In that analogy, the limit was the amount of information that a single
3913: stack entry could hold, and Forth has a similar limit. In Forth, the
3914: size of a stack entry is called a @dfn{cell}. The actual size of a cell is
3915: implementation dependent and affects the maximum value that a stack
3916: entry can hold. A Standard Forth provides a cell size of at least
3917: 16-bits, and most desktop systems use a cell size of 32-bits.
1.21 crook 3918:
1.29 crook 3919: Forth does not do any type checking for you, so you are free to
3920: manipulate and combine stack items in any way you wish. A convenient way
3921: of treating stack items is as 2's complement signed integers, and that
3922: is what Standard words like @code{+} do. Therefore you can type:
1.21 crook 3923:
1.29 crook 3924: @example
1.30 anton 3925: @kbd{-5 12 + .s@key{RET}} <1> 7 ok
1.29 crook 3926: @end example
1.21 crook 3927:
1.29 crook 3928: If you use numbers and definitions like @code{+} in order to turn Forth
3929: into a great big pocket calculator, you will realise that it's rather
3930: different from a normal calculator. Rather than typing 2 + 3 = you had
3931: to type 2 3 + (ignore the fact that you had to use @code{.s} to see the
3932: result). The terminology used to describe this difference is to say that
3933: your calculator uses @dfn{Infix Notation} (parameters and operators are
3934: mixed) whilst Forth uses @dfn{Postfix Notation} (parameters and
3935: operators are separate), also called @dfn{Reverse Polish Notation}.
1.21 crook 3936:
1.29 crook 3937: Whilst postfix notation might look confusing to begin with, it has
3938: several important advantages:
1.21 crook 3939:
1.23 crook 3940: @itemize @bullet
3941: @item
1.29 crook 3942: it is unambiguous
1.23 crook 3943: @item
1.29 crook 3944: it is more concise
1.23 crook 3945: @item
1.29 crook 3946: it fits naturally with a stack-based system
1.23 crook 3947: @end itemize
1.21 crook 3948:
1.29 crook 3949: To examine these claims in more detail, consider these sums:
1.21 crook 3950:
1.29 crook 3951: @example
3952: 6 + 5 * 4 =
3953: 4 * 5 + 6 =
3954: @end example
1.21 crook 3955:
1.29 crook 3956: If you're just learning maths or your maths is very rusty, you will
3957: probably come up with the answer 44 for the first and 26 for the
3958: second. If you are a bit of a whizz at maths you will remember the
3959: @i{convention} that multiplication takes precendence over addition, and
3960: you'd come up with the answer 26 both times. To explain the answer 26
3961: to someone who got the answer 44, you'd probably rewrite the first sum
3962: like this:
1.21 crook 3963:
1.29 crook 3964: @example
3965: 6 + (5 * 4) =
3966: @end example
1.21 crook 3967:
1.29 crook 3968: If what you really wanted was to perform the addition before the
3969: multiplication, you would have to use parentheses to force it.
1.21 crook 3970:
1.29 crook 3971: If you did the first two sums on a pocket calculator you would probably
3972: get the right answers, unless you were very cautious and entered them using
3973: these keystroke sequences:
1.21 crook 3974:
1.29 crook 3975: 6 + 5 = * 4 =
3976: 4 * 5 = + 6 =
1.21 crook 3977:
1.29 crook 3978: Postfix notation is unambiguous because the order that the operators
3979: are applied is always explicit; that also means that parentheses are
3980: never required. The operators are @i{active} (the act of quoting the
3981: operator makes the operation occur) which removes the need for ``=''.
1.28 crook 3982:
1.29 crook 3983: The sum 6 + 5 * 4 can be written (in postfix notation) in two
3984: equivalent ways:
1.26 crook 3985:
3986: @example
1.29 crook 3987: 6 5 4 * + or:
3988: 5 4 * 6 +
1.26 crook 3989: @end example
1.23 crook 3990:
1.29 crook 3991: An important thing that you should notice about this notation is that
3992: the @i{order} of the numbers does not change; if you want to subtract
3993: 2 from 10 you type @code{10 2 -}.
1.1 anton 3994:
1.29 crook 3995: The reason that Forth uses postfix notation is very simple to explain: it
3996: makes the implementation extremely simple, and it follows naturally from
3997: using the stack as a mechanism for passing parameters. Another way of
3998: thinking about this is to realise that all Forth definitions are
3999: @i{active}; they execute as they are encountered by the text
4000: interpreter. The result of this is that the syntax of Forth is trivially
4001: simple.
1.1 anton 4002:
4003:
4004:
1.29 crook 4005: @comment ----------------------------------------------
4006: @node Your first definition, How does that work?, Stacks and Postfix notation, Introduction
4007: @section Your first Forth definition
4008: @cindex first definition
1.1 anton 4009:
1.29 crook 4010: Until now, the examples we've seen have been trivial; we've just been
4011: using Forth as a bigger-than-pocket calculator. Also, each calculation
4012: we've shown has been a ``one-off'' -- to repeat it we'd need to type it in
4013: again@footnote{That's not quite true. If you press the up-arrow key on
4014: your keyboard you should be able to scroll back to any earlier command,
4015: edit it and re-enter it.} In this section we'll see how to add new
4016: words to Forth's vocabulary.
1.1 anton 4017:
1.29 crook 4018: The easiest way to create a new word is to use a @dfn{colon
4019: definition}. We'll define a few and try them out before worrying too
4020: much about how they work. Try typing in these examples; be careful to
4021: copy the spaces accurately:
1.1 anton 4022:
1.29 crook 4023: @example
4024: : add-two 2 + . ;
4025: : greet ." Hello and welcome" ;
4026: : demo 5 add-two ;
4027: @end example
1.1 anton 4028:
1.29 crook 4029: @noindent
4030: Now try them out:
1.1 anton 4031:
1.29 crook 4032: @example
1.30 anton 4033: @kbd{greet@key{RET}} Hello and welcome ok
4034: @kbd{greet greet@key{RET}} Hello and welcomeHello and welcome ok
4035: @kbd{4 add-two@key{RET}} 6 ok
4036: @kbd{demo@key{RET}} 7 ok
4037: @kbd{9 greet demo add-two@key{RET}} Hello and welcome7 11 ok
1.29 crook 4038: @end example
1.1 anton 4039:
1.29 crook 4040: The first new thing that we've introduced here is the pair of words
4041: @code{:} and @code{;}. These are used to start and terminate a new
4042: definition, respectively. The first word after the @code{:} is the name
4043: for the new definition.
1.1 anton 4044:
1.29 crook 4045: As you can see from the examples, a definition is built up of words that
4046: have already been defined; Forth makes no distinction between
4047: definitions that existed when you started the system up, and those that
4048: you define yourself.
1.1 anton 4049:
1.29 crook 4050: The examples also introduce the words @code{.} (dot), @code{."}
4051: (dot-quote) and @code{dup} (dewp). Dot takes the value from the top of
4052: the stack and displays it. It's like @code{.s} except that it only
4053: displays the top item of the stack and it is destructive; after it has
4054: executed, the number is no longer on the stack. There is always one
4055: space printed after the number, and no spaces before it. Dot-quote
4056: defines a string (a sequence of characters) that will be printed when
4057: the word is executed. The string can contain any printable characters
4058: except @code{"}. A @code{"} has a special function; it is not a Forth
4059: word but it acts as a delimiter (the way that delimiters work is
4060: described in the next section). Finally, @code{dup} duplicates the value
4061: at the top of the stack. Try typing @code{5 dup .s} to see what it does.
1.1 anton 4062:
1.29 crook 4063: We already know that the text interpreter searches through the
4064: dictionary to locate names. If you've followed the examples earlier, you
4065: will already have a definition called @code{add-two}. Lets try modifying
4066: it by typing in a new definition:
1.1 anton 4067:
1.29 crook 4068: @example
1.30 anton 4069: @kbd{: add-two dup . ." + 2 =" 2 + . ;@key{RET}} redefined add-two ok
1.29 crook 4070: @end example
1.5 anton 4071:
1.29 crook 4072: Forth recognised that we were defining a word that already exists, and
4073: printed a message to warn us of that fact. Let's try out the new
4074: definition:
1.5 anton 4075:
1.29 crook 4076: @example
1.30 anton 4077: @kbd{9 add-two@key{RET}} 9 + 2 =11 ok
1.29 crook 4078: @end example
1.1 anton 4079:
1.29 crook 4080: @noindent
4081: All that we've actually done here, though, is to create a new
4082: definition, with a particular name. The fact that there was already a
4083: definition with the same name did not make any difference to the way
4084: that the new definition was created (except that Forth printed a warning
4085: message). The old definition of add-two still exists (try @code{demo}
4086: again to see that this is true). Any new definition will use the new
4087: definition of @code{add-two}, but old definitions continue to use the
4088: version that already existed at the time that they were @code{compiled}.
1.1 anton 4089:
1.29 crook 4090: Before you go on to the next section, try defining and redefining some
4091: words of your own.
1.1 anton 4092:
1.29 crook 4093: @comment ----------------------------------------------
4094: @node How does that work?, Forth is written in Forth, Your first definition, Introduction
4095: @section How does that work?
4096: @cindex parsing words
1.1 anton 4097:
1.30 anton 4098: @c That's pretty deep (IMO way too deep) for an introduction. - anton
4099:
4100: @c Is it a good idea to talk about the interpretation semantics of a
4101: @c number? We don't have an xt to go along with it. - anton
4102:
4103: @c Now that I have eliminated execution semantics, I wonder if it would not
4104: @c be better to keep them (or add run-time semantics), to make it easier to
4105: @c explain what compilation semantics usually does. - anton
4106:
1.44 crook 4107: @c nac-> I removed the term ``default compilation sematics'' from the
4108: @c introductory chapter. Removing ``execution semantics'' was making
4109: @c everything simpler to explain, then I think the use of this term made
4110: @c everything more complex again. I replaced it with ``default
4111: @c semantics'' (which is used elsewhere in the manual) by which I mean
4112: @c ``a definition that has neither the immediate nor the compile-only
1.83 anton 4113: @c flag set''.
4114:
4115: @c anton: I have eliminated default semantics (except in one place where it
4116: @c means "default interpretation and compilation semantics"), because it
4117: @c makes no sense in the presence of combined words. I reverted to
4118: @c "execution semantics" where necessary.
4119:
4120: @c nac-> I reworded big chunks of the ``how does that work''
1.44 crook 4121: @c section (and, unusually for me, I think I even made it shorter!). See
4122: @c what you think -- I know I have not addressed your primary concern
4123: @c that it is too heavy-going for an introduction. From what I understood
4124: @c of your course notes it looks as though they might be a good framework.
4125: @c Things that I've tried to capture here are some things that came as a
4126: @c great revelation here when I first understood them. Also, I like the
4127: @c fact that a very simple code example shows up almost all of the issues
4128: @c that you need to understand to see how Forth works. That's unique and
4129: @c worthwhile to emphasise.
4130:
1.83 anton 4131: @c anton: I think it's a good idea to present the details, especially those
4132: @c that you found to be a revelation, and probably the tutorial tries to be
4133: @c too superficial and does not get some of the things across that make
4134: @c Forth special. I do believe that most of the time these things should
4135: @c be discussed at the end of a section or in separate sections instead of
4136: @c in the middle of a section (e.g., the stuff you added in "User-defined
4137: @c defining words" leads in a completely different direction from the rest
4138: @c of the section).
4139:
1.29 crook 4140: Now we're going to take another look at the definition of @code{add-two}
4141: from the previous section. From our knowledge of the way that the text
4142: interpreter works, we would have expected this result when we tried to
4143: define @code{add-two}:
1.21 crook 4144:
1.29 crook 4145: @example
1.44 crook 4146: @kbd{: add-two 2 + . ;@key{RET}}
1.29 crook 4147: ^^^^^^^
4148: Error: Undefined word
4149: @end example
1.28 crook 4150:
1.29 crook 4151: The reason that this didn't happen is bound up in the way that @code{:}
4152: works. The word @code{:} does two special things. The first special
4153: thing that it does prevents the text interpreter from ever seeing the
4154: characters @code{add-two}. The text interpreter uses a variable called
4155: @cindex modifying >IN
1.44 crook 4156: @code{>IN} (pronounced ``to-in'') to keep track of where it is in the
1.29 crook 4157: input line. When it encounters the word @code{:} it behaves in exactly
4158: the same way as it does for any other word; it looks it up in the name
4159: dictionary, finds its xt and executes it. When @code{:} executes, it
4160: looks at the input buffer, finds the word @code{add-two} and advances the
4161: value of @code{>IN} to point past it. It then does some other stuff
4162: associated with creating the new definition (including creating an entry
4163: for @code{add-two} in the name dictionary). When the execution of @code{:}
4164: completes, control returns to the text interpreter, which is oblivious
4165: to the fact that it has been tricked into ignoring part of the input
4166: line.
1.21 crook 4167:
1.29 crook 4168: @cindex parsing words
4169: Words like @code{:} -- words that advance the value of @code{>IN} and so
4170: prevent the text interpreter from acting on the whole of the input line
4171: -- are called @dfn{parsing words}.
1.21 crook 4172:
1.29 crook 4173: @cindex @code{state} - effect on the text interpreter
4174: @cindex text interpreter - effect of state
4175: The second special thing that @code{:} does is change the value of a
4176: variable called @code{state}, which affects the way that the text
4177: interpreter behaves. When Gforth starts up, @code{state} has the value
4178: 0, and the text interpreter is said to be @dfn{interpreting}. During a
4179: colon definition (started with @code{:}), @code{state} is set to -1 and
1.44 crook 4180: the text interpreter is said to be @dfn{compiling}.
4181:
4182: In this example, the text interpreter is compiling when it processes the
4183: string ``@code{2 + . ;}''. It still breaks the string down into
4184: character sequences in the same way. However, instead of pushing the
4185: number @code{2} onto the stack, it lays down (@dfn{compiles}) some magic
4186: into the definition of @code{add-two} that will make the number @code{2} get
4187: pushed onto the stack when @code{add-two} is @dfn{executed}. Similarly,
4188: the behaviours of @code{+} and @code{.} are also compiled into the
4189: definition.
4190:
4191: One category of words don't get compiled. These so-called @dfn{immediate
4192: words} get executed (performed @i{now}) regardless of whether the text
4193: interpreter is interpreting or compiling. The word @code{;} is an
4194: immediate word. Rather than being compiled into the definition, it
4195: executes. Its effect is to terminate the current definition, which
4196: includes changing the value of @code{state} back to 0.
4197:
4198: When you execute @code{add-two}, it has a @dfn{run-time effect} that is
4199: exactly the same as if you had typed @code{2 + . @key{RET}} outside of a
4200: definition.
1.28 crook 4201:
1.30 anton 4202: In Forth, every word or number can be described in terms of two
1.29 crook 4203: properties:
1.28 crook 4204:
4205: @itemize @bullet
4206: @item
1.29 crook 4207: @cindex interpretation semantics
1.44 crook 4208: Its @dfn{interpretation semantics} describe how it will behave when the
4209: text interpreter encounters it in @dfn{interpret} state. The
4210: interpretation semantics of a word are represented by an @dfn{execution
4211: token}.
1.28 crook 4212: @item
1.29 crook 4213: @cindex compilation semantics
1.44 crook 4214: Its @dfn{compilation semantics} describe how it will behave when the
4215: text interpreter encounters it in @dfn{compile} state. The compilation
4216: semantics of a word are represented in an implementation-dependent way;
4217: Gforth uses a @dfn{compilation token}.
1.29 crook 4218: @end itemize
4219:
4220: @noindent
4221: Numbers are always treated in a fixed way:
4222:
4223: @itemize @bullet
1.28 crook 4224: @item
1.44 crook 4225: When the number is @dfn{interpreted}, its behaviour is to push the
4226: number onto the stack.
1.28 crook 4227: @item
1.30 anton 4228: When the number is @dfn{compiled}, a piece of code is appended to the
4229: current definition that pushes the number when it runs. (In other words,
4230: the compilation semantics of a number are to postpone its interpretation
4231: semantics until the run-time of the definition that it is being compiled
4232: into.)
1.29 crook 4233: @end itemize
4234:
1.44 crook 4235: Words don't behave in such a regular way, but most have @i{default
4236: semantics} which means that they behave like this:
1.29 crook 4237:
4238: @itemize @bullet
1.28 crook 4239: @item
1.30 anton 4240: The @dfn{interpretation semantics} of the word are to do something useful.
4241: @item
1.29 crook 4242: The @dfn{compilation semantics} of the word are to append its
1.30 anton 4243: @dfn{interpretation semantics} to the current definition (so that its
4244: run-time behaviour is to do something useful).
1.28 crook 4245: @end itemize
4246:
1.30 anton 4247: @cindex immediate words
1.44 crook 4248: The actual behaviour of any particular word can be controlled by using
4249: the words @code{immediate} and @code{compile-only} when the word is
4250: defined. These words set flags in the name dictionary entry of the most
4251: recently defined word, and these flags are retrieved by the text
4252: interpreter when it finds the word in the name dictionary.
4253:
4254: A word that is marked as @dfn{immediate} has compilation semantics that
4255: are identical to its interpretation semantics. In other words, it
4256: behaves like this:
1.29 crook 4257:
4258: @itemize @bullet
4259: @item
1.30 anton 4260: The @dfn{interpretation semantics} of the word are to do something useful.
1.29 crook 4261: @item
1.30 anton 4262: The @dfn{compilation semantics} of the word are to do something useful
4263: (and actually the same thing); i.e., it is executed during compilation.
1.29 crook 4264: @end itemize
1.28 crook 4265:
1.44 crook 4266: Marking a word as @dfn{compile-only} prohibits the text interpreter from
4267: performing the interpretation semantics of the word directly; an attempt
4268: to do so will generate an error. It is never necessary to use
4269: @code{compile-only} (and it is not even part of ANS Forth, though it is
4270: provided by many implementations) but it is good etiquette to apply it
4271: to a word that will not behave correctly (and might have unexpected
4272: side-effects) in interpret state. For example, it is only legal to use
4273: the conditional word @code{IF} within a definition. If you forget this
4274: and try to use it elsewhere, the fact that (in Gforth) it is marked as
4275: @code{compile-only} allows the text interpreter to generate a helpful
4276: error message rather than subjecting you to the consequences of your
4277: folly.
4278:
1.29 crook 4279: This example shows the difference between an immediate and a
4280: non-immediate word:
1.28 crook 4281:
1.29 crook 4282: @example
4283: : show-state state @@ . ;
4284: : show-state-now show-state ; immediate
4285: : word1 show-state ;
4286: : word2 show-state-now ;
1.28 crook 4287: @end example
1.23 crook 4288:
1.29 crook 4289: The word @code{immediate} after the definition of @code{show-state-now}
4290: makes that word an immediate word. These definitions introduce a new
4291: word: @code{@@} (pronounced ``fetch''). This word fetches the value of a
4292: variable, and leaves it on the stack. Therefore, the behaviour of
4293: @code{show-state} is to print a number that represents the current value
4294: of @code{state}.
1.28 crook 4295:
1.29 crook 4296: When you execute @code{word1}, it prints the number 0, indicating that
4297: the system is interpreting. When the text interpreter compiled the
4298: definition of @code{word1}, it encountered @code{show-state} whose
1.30 anton 4299: compilation semantics are to append its interpretation semantics to the
1.29 crook 4300: current definition. When you execute @code{word1}, it performs the
1.30 anton 4301: interpretation semantics of @code{show-state}. At the time that @code{word1}
1.29 crook 4302: (and therefore @code{show-state}) are executed, the system is
4303: interpreting.
1.28 crook 4304:
1.30 anton 4305: When you pressed @key{RET} after entering the definition of @code{word2},
1.29 crook 4306: you should have seen the number -1 printed, followed by ``@code{
4307: ok}''. When the text interpreter compiled the definition of
4308: @code{word2}, it encountered @code{show-state-now}, an immediate word,
1.30 anton 4309: whose compilation semantics are therefore to perform its interpretation
1.29 crook 4310: semantics. It is executed straight away (even before the text
4311: interpreter has moved on to process another group of characters; the
4312: @code{;} in this example). The effect of executing it are to display the
4313: value of @code{state} @i{at the time that the definition of}
4314: @code{word2} @i{is being defined}. Printing -1 demonstrates that the
4315: system is compiling at this time. If you execute @code{word2} it does
4316: nothing at all.
1.28 crook 4317:
1.29 crook 4318: @cindex @code{."}, how it works
4319: Before leaving the subject of immediate words, consider the behaviour of
4320: @code{."} in the definition of @code{greet}, in the previous
4321: section. This word is both a parsing word and an immediate word. Notice
4322: that there is a space between @code{."} and the start of the text
4323: @code{Hello and welcome}, but that there is no space between the last
4324: letter of @code{welcome} and the @code{"} character. The reason for this
4325: is that @code{."} is a Forth word; it must have a space after it so that
4326: the text interpreter can identify it. The @code{"} is not a Forth word;
4327: it is a @dfn{delimiter}. The examples earlier show that, when the string
4328: is displayed, there is neither a space before the @code{H} nor after the
4329: @code{e}. Since @code{."} is an immediate word, it executes at the time
4330: that @code{greet} is defined. When it executes, its behaviour is to
4331: search forward in the input line looking for the delimiter. When it
4332: finds the delimiter, it updates @code{>IN} to point past the
4333: delimiter. It also compiles some magic code into the definition of
4334: @code{greet}; the xt of a run-time routine that prints a text string. It
4335: compiles the string @code{Hello and welcome} into memory so that it is
4336: available to be printed later. When the text interpreter gains control,
4337: the next word it finds in the input stream is @code{;} and so it
4338: terminates the definition of @code{greet}.
1.28 crook 4339:
4340:
4341: @comment ----------------------------------------------
1.29 crook 4342: @node Forth is written in Forth, Review - elements of a Forth system, How does that work?, Introduction
4343: @section Forth is written in Forth
4344: @cindex structure of Forth programs
4345:
4346: When you start up a Forth compiler, a large number of definitions
4347: already exist. In Forth, you develop a new application using bottom-up
4348: programming techniques to create new definitions that are defined in
4349: terms of existing definitions. As you create each definition you can
4350: test and debug it interactively.
4351:
4352: If you have tried out the examples in this section, you will probably
4353: have typed them in by hand; when you leave Gforth, your definitions will
4354: be lost. You can avoid this by using a text editor to enter Forth source
4355: code into a file, and then loading code from the file using
1.49 anton 4356: @code{include} (@pxref{Forth source files}). A Forth source file is
1.29 crook 4357: processed by the text interpreter, just as though you had typed it in by
4358: hand@footnote{Actually, there are some subtle differences -- see
4359: @ref{The Text Interpreter}.}.
4360:
4361: Gforth also supports the traditional Forth alternative to using text
1.49 anton 4362: files for program entry (@pxref{Blocks}).
1.28 crook 4363:
1.29 crook 4364: In common with many, if not most, Forth compilers, most of Gforth is
4365: actually written in Forth. All of the @file{.fs} files in the
4366: installation directory@footnote{For example,
1.30 anton 4367: @file{/usr/local/share/gforth...}} are Forth source files, which you can
1.29 crook 4368: study to see examples of Forth programming.
1.28 crook 4369:
1.29 crook 4370: Gforth maintains a history file that records every line that you type to
4371: the text interpreter. This file is preserved between sessions, and is
4372: used to provide a command-line recall facility. If you enter long
4373: definitions by hand, you can use a text editor to paste them out of the
4374: history file into a Forth source file for reuse at a later time
1.49 anton 4375: (for more information @pxref{Command-line editing}).
1.28 crook 4376:
4377:
4378: @comment ----------------------------------------------
1.29 crook 4379: @node Review - elements of a Forth system, Where to go next, Forth is written in Forth, Introduction
4380: @section Review - elements of a Forth system
4381: @cindex elements of a Forth system
1.28 crook 4382:
1.29 crook 4383: To summarise this chapter:
1.28 crook 4384:
4385: @itemize @bullet
4386: @item
1.29 crook 4387: Forth programs use @dfn{factoring} to break a problem down into small
4388: fragments called @dfn{words} or @dfn{definitions}.
4389: @item
4390: Forth program development is an interactive process.
4391: @item
4392: The main command loop that accepts input, and controls both
4393: interpretation and compilation, is called the @dfn{text interpreter}
4394: (also known as the @dfn{outer interpreter}).
4395: @item
4396: Forth has a very simple syntax, consisting of words and numbers
4397: separated by spaces or carriage-return characters. Any additional syntax
4398: is imposed by @dfn{parsing words}.
4399: @item
4400: Forth uses a stack to pass parameters between words. As a result, it
4401: uses postfix notation.
4402: @item
4403: To use a word that has previously been defined, the text interpreter
4404: searches for the word in the @dfn{name dictionary}.
4405: @item
1.30 anton 4406: Words have @dfn{interpretation semantics} and @dfn{compilation semantics}.
1.28 crook 4407: @item
1.29 crook 4408: The text interpreter uses the value of @code{state} to select between
4409: the use of the @dfn{interpretation semantics} and the @dfn{compilation
4410: semantics} of a word that it encounters.
1.28 crook 4411: @item
1.30 anton 4412: The relationship between the @dfn{interpretation semantics} and
4413: @dfn{compilation semantics} for a word
1.29 crook 4414: depend upon the way in which the word was defined (for example, whether
4415: it is an @dfn{immediate} word).
1.28 crook 4416: @item
1.29 crook 4417: Forth definitions can be implemented in Forth (called @dfn{high-level
4418: definitions}) or in some other way (usually a lower-level language and
4419: as a result often called @dfn{low-level definitions}, @dfn{code
4420: definitions} or @dfn{primitives}).
1.28 crook 4421: @item
1.29 crook 4422: Many Forth systems are implemented mainly in Forth.
1.28 crook 4423: @end itemize
4424:
4425:
1.29 crook 4426: @comment ----------------------------------------------
1.48 anton 4427: @node Where to go next, Exercises, Review - elements of a Forth system, Introduction
1.29 crook 4428: @section Where To Go Next
4429: @cindex where to go next
1.28 crook 4430:
1.29 crook 4431: Amazing as it may seem, if you have read (and understood) this far, you
4432: know almost all the fundamentals about the inner workings of a Forth
4433: system. You certainly know enough to be able to read and understand the
4434: rest of this manual and the ANS Forth document, to learn more about the
4435: facilities that Forth in general and Gforth in particular provide. Even
4436: scarier, you know almost enough to implement your own Forth system.
1.30 anton 4437: However, that's not a good idea just yet... better to try writing some
1.29 crook 4438: programs in Gforth.
1.28 crook 4439:
1.29 crook 4440: Forth has such a rich vocabulary that it can be hard to know where to
4441: start in learning it. This section suggests a few sets of words that are
4442: enough to write small but useful programs. Use the word index in this
4443: document to learn more about each word, then try it out and try to write
4444: small definitions using it. Start by experimenting with these words:
1.28 crook 4445:
4446: @itemize @bullet
4447: @item
1.29 crook 4448: Arithmetic: @code{+ - * / /MOD */ ABS INVERT}
4449: @item
4450: Comparison: @code{MIN MAX =}
4451: @item
4452: Logic: @code{AND OR XOR NOT}
4453: @item
4454: Stack manipulation: @code{DUP DROP SWAP OVER}
1.28 crook 4455: @item
1.29 crook 4456: Loops and decisions: @code{IF ELSE ENDIF ?DO I LOOP}
1.28 crook 4457: @item
1.29 crook 4458: Input/Output: @code{. ." EMIT CR KEY}
1.28 crook 4459: @item
1.29 crook 4460: Defining words: @code{: ; CREATE}
1.28 crook 4461: @item
1.29 crook 4462: Memory allocation words: @code{ALLOT ,}
1.28 crook 4463: @item
1.29 crook 4464: Tools: @code{SEE WORDS .S MARKER}
4465: @end itemize
4466:
4467: When you have mastered those, go on to:
4468:
4469: @itemize @bullet
1.28 crook 4470: @item
1.29 crook 4471: More defining words: @code{VARIABLE CONSTANT VALUE TO CREATE DOES>}
1.28 crook 4472: @item
1.29 crook 4473: Memory access: @code{@@ !}
1.28 crook 4474: @end itemize
1.23 crook 4475:
1.29 crook 4476: When you have mastered these, there's nothing for it but to read through
4477: the whole of this manual and find out what you've missed.
4478:
4479: @comment ----------------------------------------------
1.48 anton 4480: @node Exercises, , Where to go next, Introduction
1.29 crook 4481: @section Exercises
4482: @cindex exercises
4483:
4484: TODO: provide a set of programming excercises linked into the stuff done
4485: already and into other sections of the manual. Provide solutions to all
4486: the exercises in a .fs file in the distribution.
4487:
4488: @c Get some inspiration from Starting Forth and Kelly&Spies.
4489:
4490: @c excercises:
4491: @c 1. take inches and convert to feet and inches.
4492: @c 2. take temperature and convert from fahrenheight to celcius;
4493: @c may need to care about symmetric vs floored??
4494: @c 3. take input line and do character substitution
4495: @c to encipher or decipher
4496: @c 4. as above but work on a file for in and out
4497: @c 5. take input line and convert to pig-latin
4498: @c
4499: @c thing of sets of things to exercise then come up with
4500: @c problems that need those things.
4501:
4502:
1.26 crook 4503: @c ******************************************************************
1.29 crook 4504: @node Words, Error messages, Introduction, Top
1.1 anton 4505: @chapter Forth Words
1.26 crook 4506: @cindex words
1.1 anton 4507:
4508: @menu
4509: * Notation::
1.65 anton 4510: * Case insensitivity::
4511: * Comments::
4512: * Boolean Flags::
1.1 anton 4513: * Arithmetic::
4514: * Stack Manipulation::
1.5 anton 4515: * Memory::
1.1 anton 4516: * Control Structures::
4517: * Defining Words::
1.65 anton 4518: * Interpretation and Compilation Semantics::
1.47 crook 4519: * Tokens for Words::
1.81 anton 4520: * Compiling words::
1.65 anton 4521: * The Text Interpreter::
1.111 ! anton 4522: * The Input Stream::
1.65 anton 4523: * Word Lists::
4524: * Environmental Queries::
1.12 anton 4525: * Files::
4526: * Blocks::
4527: * Other I/O::
1.78 anton 4528: * Locals::
4529: * Structures::
4530: * Object-oriented Forth::
1.12 anton 4531: * Programming Tools::
4532: * Assembler and Code Words::
4533: * Threading Words::
1.65 anton 4534: * Passing Commands to the OS::
4535: * Keeping track of Time::
4536: * Miscellaneous Words::
1.1 anton 4537: @end menu
4538:
1.65 anton 4539: @node Notation, Case insensitivity, Words, Words
1.1 anton 4540: @section Notation
4541: @cindex notation of glossary entries
4542: @cindex format of glossary entries
4543: @cindex glossary notation format
4544: @cindex word glossary entry format
4545:
4546: The Forth words are described in this section in the glossary notation
1.67 anton 4547: that has become a de-facto standard for Forth texts:
1.1 anton 4548:
4549: @format
1.29 crook 4550: @i{word} @i{Stack effect} @i{wordset} @i{pronunciation}
1.1 anton 4551: @end format
1.29 crook 4552: @i{Description}
1.1 anton 4553:
4554: @table @var
4555: @item word
1.28 crook 4556: The name of the word.
1.1 anton 4557:
4558: @item Stack effect
4559: @cindex stack effect
1.29 crook 4560: The stack effect is written in the notation @code{@i{before} --
4561: @i{after}}, where @i{before} and @i{after} describe the top of
1.1 anton 4562: stack entries before and after the execution of the word. The rest of
4563: the stack is not touched by the word. The top of stack is rightmost,
4564: i.e., a stack sequence is written as it is typed in. Note that Gforth
4565: uses a separate floating point stack, but a unified stack
1.29 crook 4566: notation. Also, return stack effects are not shown in @i{stack
4567: effect}, but in @i{Description}. The name of a stack item describes
1.1 anton 4568: the type and/or the function of the item. See below for a discussion of
4569: the types.
4570:
4571: All words have two stack effects: A compile-time stack effect and a
4572: run-time stack effect. The compile-time stack-effect of most words is
1.29 crook 4573: @i{ -- }. If the compile-time stack-effect of a word deviates from
1.1 anton 4574: this standard behaviour, or the word does other unusual things at
4575: compile time, both stack effects are shown; otherwise only the run-time
4576: stack effect is shown.
4577:
4578: @cindex pronounciation of words
4579: @item pronunciation
4580: How the word is pronounced.
4581:
4582: @cindex wordset
1.67 anton 4583: @cindex environment wordset
1.1 anton 4584: @item wordset
1.21 crook 4585: The ANS Forth standard is divided into several word sets. A standard
4586: system need not support all of them. Therefore, in theory, the fewer
4587: word sets your program uses the more portable it will be. However, we
4588: suspect that most ANS Forth systems on personal machines will feature
1.26 crook 4589: all word sets. Words that are not defined in ANS Forth have
1.21 crook 4590: @code{gforth} or @code{gforth-internal} as word set. @code{gforth}
1.1 anton 4591: describes words that will work in future releases of Gforth;
4592: @code{gforth-internal} words are more volatile. Environmental query
4593: strings are also displayed like words; you can recognize them by the
1.21 crook 4594: @code{environment} in the word set field.
1.1 anton 4595:
4596: @item Description
4597: A description of the behaviour of the word.
4598: @end table
4599:
4600: @cindex types of stack items
4601: @cindex stack item types
4602: The type of a stack item is specified by the character(s) the name
4603: starts with:
4604:
4605: @table @code
4606: @item f
4607: @cindex @code{f}, stack item type
4608: Boolean flags, i.e. @code{false} or @code{true}.
4609: @item c
4610: @cindex @code{c}, stack item type
4611: Char
4612: @item w
4613: @cindex @code{w}, stack item type
4614: Cell, can contain an integer or an address
4615: @item n
4616: @cindex @code{n}, stack item type
4617: signed integer
4618: @item u
4619: @cindex @code{u}, stack item type
4620: unsigned integer
4621: @item d
4622: @cindex @code{d}, stack item type
4623: double sized signed integer
4624: @item ud
4625: @cindex @code{ud}, stack item type
4626: double sized unsigned integer
4627: @item r
4628: @cindex @code{r}, stack item type
4629: Float (on the FP stack)
1.21 crook 4630: @item a-
1.1 anton 4631: @cindex @code{a_}, stack item type
4632: Cell-aligned address
1.21 crook 4633: @item c-
1.1 anton 4634: @cindex @code{c_}, stack item type
4635: Char-aligned address (note that a Char may have two bytes in Windows NT)
1.21 crook 4636: @item f-
1.1 anton 4637: @cindex @code{f_}, stack item type
4638: Float-aligned address
1.21 crook 4639: @item df-
1.1 anton 4640: @cindex @code{df_}, stack item type
4641: Address aligned for IEEE double precision float
1.21 crook 4642: @item sf-
1.1 anton 4643: @cindex @code{sf_}, stack item type
4644: Address aligned for IEEE single precision float
4645: @item xt
4646: @cindex @code{xt}, stack item type
4647: Execution token, same size as Cell
4648: @item wid
4649: @cindex @code{wid}, stack item type
1.21 crook 4650: Word list ID, same size as Cell
1.68 anton 4651: @item ior, wior
4652: @cindex ior type description
4653: @cindex wior type description
4654: I/O result code, cell-sized. In Gforth, you can @code{throw} iors.
1.1 anton 4655: @item f83name
4656: @cindex @code{f83name}, stack item type
4657: Pointer to a name structure
4658: @item "
4659: @cindex @code{"}, stack item type
1.12 anton 4660: string in the input stream (not on the stack). The terminating character
4661: is a blank by default. If it is not a blank, it is shown in @code{<>}
1.1 anton 4662: quotes.
4663: @end table
4664:
1.65 anton 4665: @comment ----------------------------------------------
4666: @node Case insensitivity, Comments, Notation, Words
4667: @section Case insensitivity
4668: @cindex case sensitivity
4669: @cindex upper and lower case
4670:
4671: Gforth is case-insensitive; you can enter definitions and invoke
4672: Standard words using upper, lower or mixed case (however,
4673: @pxref{core-idef, Implementation-defined options, Implementation-defined
4674: options}).
4675:
4676: ANS Forth only @i{requires} implementations to recognise Standard words
4677: when they are typed entirely in upper case. Therefore, a Standard
4678: program must use upper case for all Standard words. You can use whatever
4679: case you like for words that you define, but in a Standard program you
4680: have to use the words in the same case that you defined them.
4681:
4682: Gforth supports case sensitivity through @code{table}s (case-sensitive
4683: wordlists, @pxref{Word Lists}).
4684:
4685: Two people have asked how to convert Gforth to be case-sensitive; while
4686: we think this is a bad idea, you can change all wordlists into tables
4687: like this:
4688:
4689: @example
4690: ' table-find forth-wordlist wordlist-map @ !
4691: @end example
4692:
4693: Note that you now have to type the predefined words in the same case
4694: that we defined them, which are varying. You may want to convert them
4695: to your favourite case before doing this operation (I won't explain how,
4696: because if you are even contemplating doing this, you'd better have
4697: enough knowledge of Forth systems to know this already).
4698:
4699: @node Comments, Boolean Flags, Case insensitivity, Words
1.21 crook 4700: @section Comments
1.26 crook 4701: @cindex comments
1.21 crook 4702:
1.29 crook 4703: Forth supports two styles of comment; the traditional @i{in-line} comment,
4704: @code{(} and its modern cousin, the @i{comment to end of line}; @code{\}.
1.21 crook 4705:
1.44 crook 4706:
1.23 crook 4707: doc-(
1.21 crook 4708: doc-\
1.23 crook 4709: doc-\G
1.21 crook 4710:
1.44 crook 4711:
1.21 crook 4712: @node Boolean Flags, Arithmetic, Comments, Words
4713: @section Boolean Flags
1.26 crook 4714: @cindex Boolean flags
1.21 crook 4715:
4716: A Boolean flag is cell-sized. A cell with all bits clear represents the
4717: flag @code{false} and a flag with all bits set represents the flag
1.26 crook 4718: @code{true}. Words that check a flag (for example, @code{IF}) will treat
1.29 crook 4719: a cell that has @i{any} bit set as @code{true}.
1.67 anton 4720: @c on and off to Memory?
4721: @c true and false to "Bitwise operations" or "Numeric comparison"?
1.44 crook 4722:
1.21 crook 4723: doc-true
4724: doc-false
1.29 crook 4725: doc-on
4726: doc-off
1.21 crook 4727:
1.44 crook 4728:
1.21 crook 4729: @node Arithmetic, Stack Manipulation, Boolean Flags, Words
1.1 anton 4730: @section Arithmetic
4731: @cindex arithmetic words
4732:
4733: @cindex division with potentially negative operands
4734: Forth arithmetic is not checked, i.e., you will not hear about integer
4735: overflow on addition or multiplication, you may hear about division by
4736: zero if you are lucky. The operator is written after the operands, but
4737: the operands are still in the original order. I.e., the infix @code{2-1}
4738: corresponds to @code{2 1 -}. Forth offers a variety of division
4739: operators. If you perform division with potentially negative operands,
4740: you do not want to use @code{/} or @code{/mod} with its undefined
4741: behaviour, but rather @code{fm/mod} or @code{sm/mod} (probably the
4742: former, @pxref{Mixed precision}).
1.26 crook 4743: @comment TODO discuss the different division forms and the std approach
1.1 anton 4744:
4745: @menu
4746: * Single precision::
1.67 anton 4747: * Double precision:: Double-cell integer arithmetic
1.1 anton 4748: * Bitwise operations::
1.67 anton 4749: * Numeric comparison::
1.29 crook 4750: * Mixed precision:: Operations with single and double-cell integers
1.1 anton 4751: * Floating Point::
4752: @end menu
4753:
1.67 anton 4754: @node Single precision, Double precision, Arithmetic, Arithmetic
1.1 anton 4755: @subsection Single precision
4756: @cindex single precision arithmetic words
4757:
1.67 anton 4758: @c !! cell undefined
4759:
4760: By default, numbers in Forth are single-precision integers that are one
1.26 crook 4761: cell in size. They can be signed or unsigned, depending upon how you
1.49 anton 4762: treat them. For the rules used by the text interpreter for recognising
4763: single-precision integers see @ref{Number Conversion}.
1.21 crook 4764:
1.67 anton 4765: These words are all defined for signed operands, but some of them also
4766: work for unsigned numbers: @code{+}, @code{1+}, @code{-}, @code{1-},
4767: @code{*}.
1.44 crook 4768:
1.1 anton 4769: doc-+
1.21 crook 4770: doc-1+
1.1 anton 4771: doc--
1.21 crook 4772: doc-1-
1.1 anton 4773: doc-*
4774: doc-/
4775: doc-mod
4776: doc-/mod
4777: doc-negate
4778: doc-abs
4779: doc-min
4780: doc-max
1.27 crook 4781: doc-floored
1.1 anton 4782:
1.44 crook 4783:
1.67 anton 4784: @node Double precision, Bitwise operations, Single precision, Arithmetic
1.21 crook 4785: @subsection Double precision
4786: @cindex double precision arithmetic words
4787:
1.49 anton 4788: For the rules used by the text interpreter for
4789: recognising double-precision integers, see @ref{Number Conversion}.
1.21 crook 4790:
4791: A double precision number is represented by a cell pair, with the most
1.67 anton 4792: significant cell at the TOS. It is trivial to convert an unsigned single
4793: to a double: simply push a @code{0} onto the TOS. Since numbers are
4794: represented by Gforth using 2's complement arithmetic, converting a
4795: signed single to a (signed) double requires sign-extension across the
4796: most significant cell. This can be achieved using @code{s>d}. The moral
4797: of the story is that you cannot convert a number without knowing whether
4798: it represents an unsigned or a signed number.
1.21 crook 4799:
1.67 anton 4800: These words are all defined for signed operands, but some of them also
4801: work for unsigned numbers: @code{d+}, @code{d-}.
1.44 crook 4802:
1.21 crook 4803: doc-s>d
1.67 anton 4804: doc-d>s
1.21 crook 4805: doc-d+
4806: doc-d-
4807: doc-dnegate
4808: doc-dabs
4809: doc-dmin
4810: doc-dmax
4811:
1.44 crook 4812:
1.67 anton 4813: @node Bitwise operations, Numeric comparison, Double precision, Arithmetic
4814: @subsection Bitwise operations
4815: @cindex bitwise operation words
4816:
4817:
4818: doc-and
4819: doc-or
4820: doc-xor
4821: doc-invert
4822: doc-lshift
4823: doc-rshift
4824: doc-2*
4825: doc-d2*
4826: doc-2/
4827: doc-d2/
4828:
4829:
4830: @node Numeric comparison, Mixed precision, Bitwise operations, Arithmetic
1.21 crook 4831: @subsection Numeric comparison
4832: @cindex numeric comparison words
4833:
1.67 anton 4834: Note that the words that compare for equality (@code{= <> 0= 0<> d= d<>
4835: d0= d0<>}) work for for both signed and unsigned numbers.
1.44 crook 4836:
1.28 crook 4837: doc-<
4838: doc-<=
4839: doc-<>
4840: doc-=
4841: doc->
4842: doc->=
4843:
1.21 crook 4844: doc-0<
1.23 crook 4845: doc-0<=
1.21 crook 4846: doc-0<>
4847: doc-0=
1.23 crook 4848: doc-0>
4849: doc-0>=
1.28 crook 4850:
4851: doc-u<
4852: doc-u<=
1.44 crook 4853: @c u<> and u= exist but are the same as <> and =
1.31 anton 4854: @c doc-u<>
4855: @c doc-u=
1.28 crook 4856: doc-u>
4857: doc-u>=
4858:
4859: doc-within
4860:
4861: doc-d<
4862: doc-d<=
4863: doc-d<>
4864: doc-d=
4865: doc-d>
4866: doc-d>=
1.23 crook 4867:
1.21 crook 4868: doc-d0<
1.23 crook 4869: doc-d0<=
4870: doc-d0<>
1.21 crook 4871: doc-d0=
1.23 crook 4872: doc-d0>
4873: doc-d0>=
4874:
1.21 crook 4875: doc-du<
1.28 crook 4876: doc-du<=
1.44 crook 4877: @c du<> and du= exist but are the same as d<> and d=
1.31 anton 4878: @c doc-du<>
4879: @c doc-du=
1.28 crook 4880: doc-du>
4881: doc-du>=
1.1 anton 4882:
1.44 crook 4883:
1.21 crook 4884: @node Mixed precision, Floating Point, Numeric comparison, Arithmetic
1.1 anton 4885: @subsection Mixed precision
4886: @cindex mixed precision arithmetic words
4887:
1.44 crook 4888:
1.1 anton 4889: doc-m+
4890: doc-*/
4891: doc-*/mod
4892: doc-m*
4893: doc-um*
4894: doc-m*/
4895: doc-um/mod
4896: doc-fm/mod
4897: doc-sm/rem
4898:
1.44 crook 4899:
1.21 crook 4900: @node Floating Point, , Mixed precision, Arithmetic
1.1 anton 4901: @subsection Floating Point
4902: @cindex floating point arithmetic words
4903:
1.49 anton 4904: For the rules used by the text interpreter for
4905: recognising floating-point numbers see @ref{Number Conversion}.
1.1 anton 4906:
1.67 anton 4907: Gforth has a separate floating point stack, but the documentation uses
4908: the unified notation.@footnote{It's easy to generate the separate
4909: notation from that by just separating the floating-point numbers out:
4910: e.g. @code{( n r1 u r2 -- r3 )} becomes @code{( n u -- ) ( F: r1 r2 --
4911: r3 )}.}
1.1 anton 4912:
4913: @cindex floating-point arithmetic, pitfalls
4914: Floating point numbers have a number of unpleasant surprises for the
4915: unwary (e.g., floating point addition is not associative) and even a few
4916: for the wary. You should not use them unless you know what you are doing
4917: or you don't care that the results you get are totally bogus. If you
4918: want to learn about the problems of floating point numbers (and how to
1.66 anton 4919: avoid them), you might start with @cite{David Goldberg,
4920: @uref{http://www.validgh.com/goldberg/paper.ps,What Every Computer
4921: Scientist Should Know About Floating-Point Arithmetic}, ACM Computing
4922: Surveys 23(1):5@minus{}48, March 1991}.
1.1 anton 4923:
1.44 crook 4924:
1.21 crook 4925: doc-d>f
4926: doc-f>d
1.1 anton 4927: doc-f+
4928: doc-f-
4929: doc-f*
4930: doc-f/
4931: doc-fnegate
4932: doc-fabs
4933: doc-fmax
4934: doc-fmin
4935: doc-floor
4936: doc-fround
4937: doc-f**
4938: doc-fsqrt
4939: doc-fexp
4940: doc-fexpm1
4941: doc-fln
4942: doc-flnp1
4943: doc-flog
4944: doc-falog
1.32 anton 4945: doc-f2*
4946: doc-f2/
4947: doc-1/f
4948: doc-precision
4949: doc-set-precision
4950:
4951: @cindex angles in trigonometric operations
4952: @cindex trigonometric operations
4953: Angles in floating point operations are given in radians (a full circle
4954: has 2 pi radians).
4955:
1.1 anton 4956: doc-fsin
4957: doc-fcos
4958: doc-fsincos
4959: doc-ftan
4960: doc-fasin
4961: doc-facos
4962: doc-fatan
4963: doc-fatan2
4964: doc-fsinh
4965: doc-fcosh
4966: doc-ftanh
4967: doc-fasinh
4968: doc-facosh
4969: doc-fatanh
1.21 crook 4970: doc-pi
1.28 crook 4971:
1.32 anton 4972: @cindex equality of floats
4973: @cindex floating-point comparisons
1.31 anton 4974: One particular problem with floating-point arithmetic is that comparison
4975: for equality often fails when you would expect it to succeed. For this
4976: reason approximate equality is often preferred (but you still have to
1.67 anton 4977: know what you are doing). Also note that IEEE NaNs may compare
1.68 anton 4978: differently from what you might expect. The comparison words are:
1.31 anton 4979:
4980: doc-f~rel
4981: doc-f~abs
1.68 anton 4982: doc-f~
1.31 anton 4983: doc-f=
4984: doc-f<>
4985:
4986: doc-f<
4987: doc-f<=
4988: doc-f>
4989: doc-f>=
4990:
1.21 crook 4991: doc-f0<
1.28 crook 4992: doc-f0<=
4993: doc-f0<>
1.21 crook 4994: doc-f0=
1.28 crook 4995: doc-f0>
4996: doc-f0>=
4997:
1.1 anton 4998:
4999: @node Stack Manipulation, Memory, Arithmetic, Words
5000: @section Stack Manipulation
5001: @cindex stack manipulation words
5002:
5003: @cindex floating-point stack in the standard
1.21 crook 5004: Gforth maintains a number of separate stacks:
5005:
1.29 crook 5006: @cindex data stack
5007: @cindex parameter stack
1.21 crook 5008: @itemize @bullet
5009: @item
1.29 crook 5010: A data stack (also known as the @dfn{parameter stack}) -- for
5011: characters, cells, addresses, and double cells.
1.21 crook 5012:
1.29 crook 5013: @cindex floating-point stack
1.21 crook 5014: @item
1.44 crook 5015: A floating point stack -- for holding floating point (FP) numbers.
1.21 crook 5016:
1.29 crook 5017: @cindex return stack
1.21 crook 5018: @item
1.44 crook 5019: A return stack -- for holding the return addresses of colon
1.32 anton 5020: definitions and other (non-FP) data.
1.21 crook 5021:
1.29 crook 5022: @cindex locals stack
1.21 crook 5023: @item
1.44 crook 5024: A locals stack -- for holding local variables.
1.21 crook 5025: @end itemize
5026:
1.1 anton 5027: @menu
5028: * Data stack::
5029: * Floating point stack::
5030: * Return stack::
5031: * Locals stack::
5032: * Stack pointer manipulation::
5033: @end menu
5034:
5035: @node Data stack, Floating point stack, Stack Manipulation, Stack Manipulation
5036: @subsection Data stack
5037: @cindex data stack manipulation words
5038: @cindex stack manipulations words, data stack
5039:
1.44 crook 5040:
1.1 anton 5041: doc-drop
5042: doc-nip
5043: doc-dup
5044: doc-over
5045: doc-tuck
5046: doc-swap
1.21 crook 5047: doc-pick
1.1 anton 5048: doc-rot
5049: doc--rot
5050: doc-?dup
5051: doc-roll
5052: doc-2drop
5053: doc-2nip
5054: doc-2dup
5055: doc-2over
5056: doc-2tuck
5057: doc-2swap
5058: doc-2rot
5059:
1.44 crook 5060:
1.1 anton 5061: @node Floating point stack, Return stack, Data stack, Stack Manipulation
5062: @subsection Floating point stack
5063: @cindex floating-point stack manipulation words
5064: @cindex stack manipulation words, floating-point stack
5065:
1.32 anton 5066: Whilst every sane Forth has a separate floating-point stack, it is not
5067: strictly required; an ANS Forth system could theoretically keep
5068: floating-point numbers on the data stack. As an additional difficulty,
5069: you don't know how many cells a floating-point number takes. It is
5070: reportedly possible to write words in a way that they work also for a
5071: unified stack model, but we do not recommend trying it. Instead, just
5072: say that your program has an environmental dependency on a separate
5073: floating-point stack.
5074:
5075: doc-floating-stack
5076:
1.1 anton 5077: doc-fdrop
5078: doc-fnip
5079: doc-fdup
5080: doc-fover
5081: doc-ftuck
5082: doc-fswap
1.21 crook 5083: doc-fpick
1.1 anton 5084: doc-frot
5085:
1.44 crook 5086:
1.1 anton 5087: @node Return stack, Locals stack, Floating point stack, Stack Manipulation
5088: @subsection Return stack
5089: @cindex return stack manipulation words
5090: @cindex stack manipulation words, return stack
5091:
1.32 anton 5092: @cindex return stack and locals
5093: @cindex locals and return stack
5094: A Forth system is allowed to keep local variables on the
5095: return stack. This is reasonable, as local variables usually eliminate
5096: the need to use the return stack explicitly. So, if you want to produce
5097: a standard compliant program and you are using local variables in a
5098: word, forget about return stack manipulations in that word (refer to the
5099: standard document for the exact rules).
5100:
1.1 anton 5101: doc->r
5102: doc-r>
5103: doc-r@
5104: doc-rdrop
5105: doc-2>r
5106: doc-2r>
5107: doc-2r@
5108: doc-2rdrop
5109:
1.44 crook 5110:
1.1 anton 5111: @node Locals stack, Stack pointer manipulation, Return stack, Stack Manipulation
5112: @subsection Locals stack
5113:
1.78 anton 5114: Gforth uses an extra locals stack. It is described, along with the
5115: reasons for its existence, in @ref{Locals implementation}.
1.21 crook 5116:
1.1 anton 5117: @node Stack pointer manipulation, , Locals stack, Stack Manipulation
5118: @subsection Stack pointer manipulation
5119: @cindex stack pointer manipulation words
5120:
1.44 crook 5121: @c removed s0 r0 l0 -- they are obsolete aliases for sp0 rp0 lp0
1.21 crook 5122: doc-sp0
1.1 anton 5123: doc-sp@
5124: doc-sp!
1.21 crook 5125: doc-fp0
1.1 anton 5126: doc-fp@
5127: doc-fp!
1.21 crook 5128: doc-rp0
1.1 anton 5129: doc-rp@
5130: doc-rp!
1.21 crook 5131: doc-lp0
1.1 anton 5132: doc-lp@
5133: doc-lp!
5134:
1.44 crook 5135:
1.1 anton 5136: @node Memory, Control Structures, Stack Manipulation, Words
5137: @section Memory
1.26 crook 5138: @cindex memory words
1.1 anton 5139:
1.32 anton 5140: @menu
5141: * Memory model::
5142: * Dictionary allocation::
5143: * Heap Allocation::
5144: * Memory Access::
5145: * Address arithmetic::
5146: * Memory Blocks::
5147: @end menu
5148:
1.67 anton 5149: In addition to the standard Forth memory allocation words, there is also
5150: a @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
5151: garbage collector}.
5152:
1.32 anton 5153: @node Memory model, Dictionary allocation, Memory, Memory
5154: @subsection ANS Forth and Gforth memory models
5155:
5156: @c The ANS Forth description is a mess (e.g., is the heap part of
5157: @c the dictionary?), so let's not stick to closely with it.
5158:
1.67 anton 5159: ANS Forth considers a Forth system as consisting of several address
5160: spaces, of which only @dfn{data space} is managed and accessible with
5161: the memory words. Memory not necessarily in data space includes the
5162: stacks, the code (called code space) and the headers (called name
5163: space). In Gforth everything is in data space, but the code for the
5164: primitives is usually read-only.
1.32 anton 5165:
5166: Data space is divided into a number of areas: The (data space portion of
5167: the) dictionary@footnote{Sometimes, the term @dfn{dictionary} is used to
5168: refer to the search data structure embodied in word lists and headers,
5169: because it is used for looking up names, just as you would in a
5170: conventional dictionary.}, the heap, and a number of system-allocated
5171: buffers.
5172:
1.68 anton 5173: @cindex address arithmetic restrictions, ANS vs. Gforth
5174: @cindex contiguous regions, ANS vs. Gforth
1.32 anton 5175: In ANS Forth data space is also divided into contiguous regions. You
5176: can only use address arithmetic within a contiguous region, not between
5177: them. Usually each allocation gives you one contiguous region, but the
1.33 anton 5178: dictionary allocation words have additional rules (@pxref{Dictionary
1.32 anton 5179: allocation}).
5180:
5181: Gforth provides one big address space, and address arithmetic can be
5182: performed between any addresses. However, in the dictionary headers or
5183: code are interleaved with data, so almost the only contiguous data space
5184: regions there are those described by ANS Forth as contiguous; but you
5185: can be sure that the dictionary is allocated towards increasing
5186: addresses even between contiguous regions. The memory order of
5187: allocations in the heap is platform-dependent (and possibly different
5188: from one run to the next).
5189:
1.27 crook 5190:
1.32 anton 5191: @node Dictionary allocation, Heap Allocation, Memory model, Memory
5192: @subsection Dictionary allocation
1.27 crook 5193: @cindex reserving data space
5194: @cindex data space - reserving some
5195:
1.32 anton 5196: Dictionary allocation is a stack-oriented allocation scheme, i.e., if
5197: you want to deallocate X, you also deallocate everything
5198: allocated after X.
5199:
1.68 anton 5200: @cindex contiguous regions in dictionary allocation
1.32 anton 5201: The allocations using the words below are contiguous and grow the region
5202: towards increasing addresses. Other words that allocate dictionary
5203: memory of any kind (i.e., defining words including @code{:noname}) end
5204: the contiguous region and start a new one.
5205:
5206: In ANS Forth only @code{create}d words are guaranteed to produce an
5207: address that is the start of the following contiguous region. In
5208: particular, the cell allocated by @code{variable} is not guaranteed to
5209: be contiguous with following @code{allot}ed memory.
5210:
5211: You can deallocate memory by using @code{allot} with a negative argument
5212: (with some restrictions, see @code{allot}). For larger deallocations use
5213: @code{marker}.
1.27 crook 5214:
1.29 crook 5215:
1.27 crook 5216: doc-here
5217: doc-unused
5218: doc-allot
5219: doc-c,
1.29 crook 5220: doc-f,
1.27 crook 5221: doc-,
5222: doc-2,
5223:
1.32 anton 5224: Memory accesses have to be aligned (@pxref{Address arithmetic}). So of
5225: course you should allocate memory in an aligned way, too. I.e., before
5226: allocating allocating a cell, @code{here} must be cell-aligned, etc.
5227: The words below align @code{here} if it is not already. Basically it is
5228: only already aligned for a type, if the last allocation was a multiple
5229: of the size of this type and if @code{here} was aligned for this type
5230: before.
5231:
5232: After freshly @code{create}ing a word, @code{here} is @code{align}ed in
5233: ANS Forth (@code{maxalign}ed in Gforth).
5234:
5235: doc-align
5236: doc-falign
5237: doc-sfalign
5238: doc-dfalign
5239: doc-maxalign
5240: doc-cfalign
5241:
5242:
5243: @node Heap Allocation, Memory Access, Dictionary allocation, Memory
5244: @subsection Heap allocation
5245: @cindex heap allocation
5246: @cindex dynamic allocation of memory
5247: @cindex memory-allocation word set
5248:
1.68 anton 5249: @cindex contiguous regions and heap allocation
1.32 anton 5250: Heap allocation supports deallocation of allocated memory in any
5251: order. Dictionary allocation is not affected by it (i.e., it does not
5252: end a contiguous region). In Gforth, these words are implemented using
5253: the standard C library calls malloc(), free() and resize().
5254:
1.68 anton 5255: The memory region produced by one invocation of @code{allocate} or
5256: @code{resize} is internally contiguous. There is no contiguity between
5257: such a region and any other region (including others allocated from the
5258: heap).
5259:
1.32 anton 5260: doc-allocate
5261: doc-free
5262: doc-resize
5263:
1.27 crook 5264:
1.32 anton 5265: @node Memory Access, Address arithmetic, Heap Allocation, Memory
1.1 anton 5266: @subsection Memory Access
5267: @cindex memory access words
5268:
5269: doc-@
5270: doc-!
5271: doc-+!
5272: doc-c@
5273: doc-c!
5274: doc-2@
5275: doc-2!
5276: doc-f@
5277: doc-f!
5278: doc-sf@
5279: doc-sf!
5280: doc-df@
5281: doc-df!
5282:
1.68 anton 5283:
1.32 anton 5284: @node Address arithmetic, Memory Blocks, Memory Access, Memory
5285: @subsection Address arithmetic
1.1 anton 5286: @cindex address arithmetic words
5287:
1.67 anton 5288: Address arithmetic is the foundation on which you can build data
5289: structures like arrays, records (@pxref{Structures}) and objects
5290: (@pxref{Object-oriented Forth}).
1.32 anton 5291:
1.68 anton 5292: @cindex address unit
5293: @cindex au (address unit)
1.1 anton 5294: ANS Forth does not specify the sizes of the data types. Instead, it
5295: offers a number of words for computing sizes and doing address
1.29 crook 5296: arithmetic. Address arithmetic is performed in terms of address units
5297: (aus); on most systems the address unit is one byte. Note that a
5298: character may have more than one au, so @code{chars} is no noop (on
1.68 anton 5299: platforms where it is a noop, it compiles to nothing).
1.1 anton 5300:
1.67 anton 5301: The basic address arithmetic words are @code{+} and @code{-}. E.g., if
5302: you have the address of a cell, perform @code{1 cells +}, and you will
5303: have the address of the next cell.
5304:
1.68 anton 5305: @cindex contiguous regions and address arithmetic
1.67 anton 5306: In ANS Forth you can perform address arithmetic only within a contiguous
5307: region, i.e., if you have an address into one region, you can only add
5308: and subtract such that the result is still within the region; you can
5309: only subtract or compare addresses from within the same contiguous
5310: region. Reasons: several contiguous regions can be arranged in memory
5311: in any way; on segmented systems addresses may have unusual
5312: representations, such that address arithmetic only works within a
5313: region. Gforth provides a few more guarantees (linear address space,
5314: dictionary grows upwards), but in general I have found it easy to stay
5315: within contiguous regions (exception: computing and comparing to the
5316: address just beyond the end of an array).
5317:
1.1 anton 5318: @cindex alignment of addresses for types
5319: ANS Forth also defines words for aligning addresses for specific
5320: types. Many computers require that accesses to specific data types
5321: must only occur at specific addresses; e.g., that cells may only be
5322: accessed at addresses divisible by 4. Even if a machine allows unaligned
5323: accesses, it can usually perform aligned accesses faster.
5324:
5325: For the performance-conscious: alignment operations are usually only
5326: necessary during the definition of a data structure, not during the
5327: (more frequent) accesses to it.
5328:
5329: ANS Forth defines no words for character-aligning addresses. This is not
5330: an oversight, but reflects the fact that addresses that are not
5331: char-aligned have no use in the standard and therefore will not be
5332: created.
5333:
5334: @cindex @code{CREATE} and alignment
1.29 crook 5335: ANS Forth guarantees that addresses returned by @code{CREATE}d words
1.1 anton 5336: are cell-aligned; in addition, Gforth guarantees that these addresses
5337: are aligned for all purposes.
5338:
1.26 crook 5339: Note that the ANS Forth word @code{char} has nothing to do with address
5340: arithmetic.
1.1 anton 5341:
1.44 crook 5342:
1.1 anton 5343: doc-chars
5344: doc-char+
5345: doc-cells
5346: doc-cell+
5347: doc-cell
5348: doc-aligned
5349: doc-floats
5350: doc-float+
5351: doc-float
5352: doc-faligned
5353: doc-sfloats
5354: doc-sfloat+
5355: doc-sfaligned
5356: doc-dfloats
5357: doc-dfloat+
5358: doc-dfaligned
5359: doc-maxaligned
5360: doc-cfaligned
5361: doc-address-unit-bits
5362:
1.44 crook 5363:
1.32 anton 5364: @node Memory Blocks, , Address arithmetic, Memory
1.1 anton 5365: @subsection Memory Blocks
5366: @cindex memory block words
1.27 crook 5367: @cindex character strings - moving and copying
5368:
1.49 anton 5369: Memory blocks often represent character strings; For ways of storing
5370: character strings in memory see @ref{String Formats}. For other
5371: string-processing words see @ref{Displaying characters and strings}.
1.1 anton 5372:
1.67 anton 5373: A few of these words work on address unit blocks. In that case, you
5374: usually have to insert @code{CHARS} before the word when working on
5375: character strings. Most words work on character blocks, and expect a
5376: char-aligned address.
5377:
5378: When copying characters between overlapping memory regions, use
5379: @code{chars move} or choose carefully between @code{cmove} and
5380: @code{cmove>}.
1.44 crook 5381:
1.1 anton 5382: doc-move
5383: doc-erase
5384: doc-cmove
5385: doc-cmove>
5386: doc-fill
5387: doc-blank
1.21 crook 5388: doc-compare
1.111 ! anton 5389: doc-str=
! 5390: doc-str<
! 5391: doc-string-prefix?
1.21 crook 5392: doc-search
1.27 crook 5393: doc--trailing
5394: doc-/string
1.82 anton 5395: doc-bounds
1.44 crook 5396:
1.111 ! anton 5397:
1.27 crook 5398: @comment TODO examples
5399:
1.1 anton 5400:
1.26 crook 5401: @node Control Structures, Defining Words, Memory, Words
1.1 anton 5402: @section Control Structures
5403: @cindex control structures
5404:
1.33 anton 5405: Control structures in Forth cannot be used interpretively, only in a
5406: colon definition@footnote{To be precise, they have no interpretation
5407: semantics (@pxref{Interpretation and Compilation Semantics}).}. We do
5408: not like this limitation, but have not seen a satisfying way around it
5409: yet, although many schemes have been proposed.
1.1 anton 5410:
5411: @menu
1.33 anton 5412: * Selection:: IF ... ELSE ... ENDIF
5413: * Simple Loops:: BEGIN ...
1.29 crook 5414: * Counted Loops:: DO
1.67 anton 5415: * Arbitrary control structures::
5416: * Calls and returns::
1.1 anton 5417: * Exception Handling::
5418: @end menu
5419:
5420: @node Selection, Simple Loops, Control Structures, Control Structures
5421: @subsection Selection
5422: @cindex selection control structures
5423: @cindex control structures for selection
5424:
5425: @cindex @code{IF} control structure
5426: @example
1.29 crook 5427: @i{flag}
1.1 anton 5428: IF
1.29 crook 5429: @i{code}
1.1 anton 5430: ENDIF
5431: @end example
1.21 crook 5432: @noindent
1.33 anton 5433:
1.44 crook 5434: If @i{flag} is non-zero (as far as @code{IF} etc. are concerned, a cell
5435: with any bit set represents truth) @i{code} is executed.
1.33 anton 5436:
1.1 anton 5437: @example
1.29 crook 5438: @i{flag}
1.1 anton 5439: IF
1.29 crook 5440: @i{code1}
1.1 anton 5441: ELSE
1.29 crook 5442: @i{code2}
1.1 anton 5443: ENDIF
5444: @end example
5445:
1.44 crook 5446: If @var{flag} is true, @i{code1} is executed, otherwise @i{code2} is
5447: executed.
1.33 anton 5448:
1.1 anton 5449: You can use @code{THEN} instead of @code{ENDIF}. Indeed, @code{THEN} is
5450: standard, and @code{ENDIF} is not, although it is quite popular. We
5451: recommend using @code{ENDIF}, because it is less confusing for people
5452: who also know other languages (and is not prone to reinforcing negative
5453: prejudices against Forth in these people). Adding @code{ENDIF} to a
5454: system that only supplies @code{THEN} is simple:
5455: @example
1.82 anton 5456: : ENDIF POSTPONE then ; immediate
1.1 anton 5457: @end example
5458:
5459: [According to @cite{Webster's New Encyclopedic Dictionary}, @dfn{then
5460: (adv.)} has the following meanings:
5461: @quotation
5462: ... 2b: following next after in order ... 3d: as a necessary consequence
5463: (if you were there, then you saw them).
5464: @end quotation
5465: Forth's @code{THEN} has the meaning 2b, whereas @code{THEN} in Pascal
5466: and many other programming languages has the meaning 3d.]
5467:
1.21 crook 5468: Gforth also provides the words @code{?DUP-IF} and @code{?DUP-0=-IF}, so
1.1 anton 5469: you can avoid using @code{?dup}. Using these alternatives is also more
1.26 crook 5470: efficient than using @code{?dup}. Definitions in ANS Forth
1.1 anton 5471: for @code{ENDIF}, @code{?DUP-IF} and @code{?DUP-0=-IF} are provided in
5472: @file{compat/control.fs}.
5473:
5474: @cindex @code{CASE} control structure
5475: @example
1.29 crook 5476: @i{n}
1.1 anton 5477: CASE
1.29 crook 5478: @i{n1} OF @i{code1} ENDOF
5479: @i{n2} OF @i{code2} ENDOF
1.1 anton 5480: @dots{}
1.68 anton 5481: ( n ) @i{default-code} ( n )
1.1 anton 5482: ENDCASE
5483: @end example
5484:
1.68 anton 5485: Executes the first @i{codei}, where the @i{ni} is equal to @i{n}. If no
5486: @i{ni} matches, the optional @i{default-code} is executed. The optional
5487: default case can be added by simply writing the code after the last
5488: @code{ENDOF}. It may use @i{n}, which is on top of the stack, but must
5489: not consume it.
1.1 anton 5490:
1.69 anton 5491: @progstyle
5492: To keep the code understandable, you should ensure that on all paths
5493: through a selection construct the stack is changed in the same way
5494: (wrt. number and types of stack items consumed and pushed).
5495:
1.1 anton 5496: @node Simple Loops, Counted Loops, Selection, Control Structures
5497: @subsection Simple Loops
5498: @cindex simple loops
5499: @cindex loops without count
5500:
5501: @cindex @code{WHILE} loop
5502: @example
5503: BEGIN
1.29 crook 5504: @i{code1}
5505: @i{flag}
1.1 anton 5506: WHILE
1.29 crook 5507: @i{code2}
1.1 anton 5508: REPEAT
5509: @end example
5510:
1.29 crook 5511: @i{code1} is executed and @i{flag} is computed. If it is true,
5512: @i{code2} is executed and the loop is restarted; If @i{flag} is
1.1 anton 5513: false, execution continues after the @code{REPEAT}.
5514:
5515: @cindex @code{UNTIL} loop
5516: @example
5517: BEGIN
1.29 crook 5518: @i{code}
5519: @i{flag}
1.1 anton 5520: UNTIL
5521: @end example
5522:
1.29 crook 5523: @i{code} is executed. The loop is restarted if @code{flag} is false.
1.1 anton 5524:
1.69 anton 5525: @progstyle
5526: To keep the code understandable, a complete iteration of the loop should
5527: not change the number and types of the items on the stacks.
5528:
1.1 anton 5529: @cindex endless loop
5530: @cindex loops, endless
5531: @example
5532: BEGIN
1.29 crook 5533: @i{code}
1.1 anton 5534: AGAIN
5535: @end example
5536:
5537: This is an endless loop.
5538:
5539: @node Counted Loops, Arbitrary control structures, Simple Loops, Control Structures
5540: @subsection Counted Loops
5541: @cindex counted loops
5542: @cindex loops, counted
5543: @cindex @code{DO} loops
5544:
5545: The basic counted loop is:
5546: @example
1.29 crook 5547: @i{limit} @i{start}
1.1 anton 5548: ?DO
1.29 crook 5549: @i{body}
1.1 anton 5550: LOOP
5551: @end example
5552:
1.29 crook 5553: This performs one iteration for every integer, starting from @i{start}
5554: and up to, but excluding @i{limit}. The counter, or @i{index}, can be
1.21 crook 5555: accessed with @code{i}. For example, the loop:
1.1 anton 5556: @example
5557: 10 0 ?DO
5558: i .
5559: LOOP
5560: @end example
1.21 crook 5561: @noindent
5562: prints @code{0 1 2 3 4 5 6 7 8 9}
5563:
1.1 anton 5564: The index of the innermost loop can be accessed with @code{i}, the index
5565: of the next loop with @code{j}, and the index of the third loop with
5566: @code{k}.
5567:
1.44 crook 5568:
1.1 anton 5569: doc-i
5570: doc-j
5571: doc-k
5572:
1.44 crook 5573:
1.1 anton 5574: The loop control data are kept on the return stack, so there are some
1.21 crook 5575: restrictions on mixing return stack accesses and counted loop words. In
5576: particuler, if you put values on the return stack outside the loop, you
5577: cannot read them inside the loop@footnote{well, not in a way that is
5578: portable.}. If you put values on the return stack within a loop, you
5579: have to remove them before the end of the loop and before accessing the
5580: index of the loop.
1.1 anton 5581:
5582: There are several variations on the counted loop:
5583:
1.21 crook 5584: @itemize @bullet
5585: @item
5586: @code{LEAVE} leaves the innermost counted loop immediately; execution
5587: continues after the associated @code{LOOP} or @code{NEXT}. For example:
5588:
5589: @example
5590: 10 0 ?DO i DUP . 3 = IF LEAVE THEN LOOP
5591: @end example
5592: prints @code{0 1 2 3}
5593:
1.1 anton 5594:
1.21 crook 5595: @item
5596: @code{UNLOOP} prepares for an abnormal loop exit, e.g., via
5597: @code{EXIT}. @code{UNLOOP} removes the loop control parameters from the
5598: return stack so @code{EXIT} can get to its return address. For example:
5599:
5600: @example
5601: : demo 10 0 ?DO i DUP . 3 = IF UNLOOP EXIT THEN LOOP ." Done" ;
5602: @end example
5603: prints @code{0 1 2 3}
5604:
5605:
5606: @item
1.29 crook 5607: If @i{start} is greater than @i{limit}, a @code{?DO} loop is entered
1.1 anton 5608: (and @code{LOOP} iterates until they become equal by wrap-around
5609: arithmetic). This behaviour is usually not what you want. Therefore,
5610: Gforth offers @code{+DO} and @code{U+DO} (as replacements for
1.29 crook 5611: @code{?DO}), which do not enter the loop if @i{start} is greater than
5612: @i{limit}; @code{+DO} is for signed loop parameters, @code{U+DO} for
1.1 anton 5613: unsigned loop parameters.
5614:
1.21 crook 5615: @item
5616: @code{?DO} can be replaced by @code{DO}. @code{DO} always enters
5617: the loop, independent of the loop parameters. Do not use @code{DO}, even
5618: if you know that the loop is entered in any case. Such knowledge tends
5619: to become invalid during maintenance of a program, and then the
5620: @code{DO} will make trouble.
5621:
5622: @item
1.29 crook 5623: @code{LOOP} can be replaced with @code{@i{n} +LOOP}; this updates the
5624: index by @i{n} instead of by 1. The loop is terminated when the border
5625: between @i{limit-1} and @i{limit} is crossed. E.g.:
1.1 anton 5626:
1.21 crook 5627: @example
5628: 4 0 +DO i . 2 +LOOP
5629: @end example
5630: @noindent
5631: prints @code{0 2}
5632:
5633: @example
5634: 4 1 +DO i . 2 +LOOP
5635: @end example
5636: @noindent
5637: prints @code{1 3}
1.1 anton 5638:
1.68 anton 5639: @item
1.1 anton 5640: @cindex negative increment for counted loops
5641: @cindex counted loops with negative increment
1.29 crook 5642: The behaviour of @code{@i{n} +LOOP} is peculiar when @i{n} is negative:
1.1 anton 5643:
1.21 crook 5644: @example
5645: -1 0 ?DO i . -1 +LOOP
5646: @end example
5647: @noindent
5648: prints @code{0 -1}
1.1 anton 5649:
1.21 crook 5650: @example
5651: 0 0 ?DO i . -1 +LOOP
5652: @end example
5653: prints nothing.
1.1 anton 5654:
1.29 crook 5655: Therefore we recommend avoiding @code{@i{n} +LOOP} with negative
5656: @i{n}. One alternative is @code{@i{u} -LOOP}, which reduces the
5657: index by @i{u} each iteration. The loop is terminated when the border
5658: between @i{limit+1} and @i{limit} is crossed. Gforth also provides
1.1 anton 5659: @code{-DO} and @code{U-DO} for down-counting loops. E.g.:
5660:
1.21 crook 5661: @example
5662: -2 0 -DO i . 1 -LOOP
5663: @end example
5664: @noindent
5665: prints @code{0 -1}
1.1 anton 5666:
1.21 crook 5667: @example
5668: -1 0 -DO i . 1 -LOOP
5669: @end example
5670: @noindent
5671: prints @code{0}
5672:
5673: @example
5674: 0 0 -DO i . 1 -LOOP
5675: @end example
5676: @noindent
5677: prints nothing.
1.1 anton 5678:
1.21 crook 5679: @end itemize
1.1 anton 5680:
5681: Unfortunately, @code{+DO}, @code{U+DO}, @code{-DO}, @code{U-DO} and
1.26 crook 5682: @code{-LOOP} are not defined in ANS Forth. However, an implementation
5683: for these words that uses only standard words is provided in
5684: @file{compat/loops.fs}.
1.1 anton 5685:
5686:
5687: @cindex @code{FOR} loops
1.26 crook 5688: Another counted loop is:
1.1 anton 5689: @example
1.29 crook 5690: @i{n}
1.1 anton 5691: FOR
1.29 crook 5692: @i{body}
1.1 anton 5693: NEXT
5694: @end example
5695: This is the preferred loop of native code compiler writers who are too
1.26 crook 5696: lazy to optimize @code{?DO} loops properly. This loop structure is not
1.29 crook 5697: defined in ANS Forth. In Gforth, this loop iterates @i{n+1} times;
5698: @code{i} produces values starting with @i{n} and ending with 0. Other
1.26 crook 5699: Forth systems may behave differently, even if they support @code{FOR}
5700: loops. To avoid problems, don't use @code{FOR} loops.
1.1 anton 5701:
5702: @node Arbitrary control structures, Calls and returns, Counted Loops, Control Structures
5703: @subsection Arbitrary control structures
5704: @cindex control structures, user-defined
5705:
5706: @cindex control-flow stack
5707: ANS Forth permits and supports using control structures in a non-nested
5708: way. Information about incomplete control structures is stored on the
5709: control-flow stack. This stack may be implemented on the Forth data
5710: stack, and this is what we have done in Gforth.
5711:
5712: @cindex @code{orig}, control-flow stack item
5713: @cindex @code{dest}, control-flow stack item
5714: An @i{orig} entry represents an unresolved forward branch, a @i{dest}
5715: entry represents a backward branch target. A few words are the basis for
5716: building any control structure possible (except control structures that
5717: need storage, like calls, coroutines, and backtracking).
5718:
1.44 crook 5719:
1.1 anton 5720: doc-if
5721: doc-ahead
5722: doc-then
5723: doc-begin
5724: doc-until
5725: doc-again
5726: doc-cs-pick
5727: doc-cs-roll
5728:
1.44 crook 5729:
1.21 crook 5730: The Standard words @code{CS-PICK} and @code{CS-ROLL} allow you to
5731: manipulate the control-flow stack in a portable way. Without them, you
5732: would need to know how many stack items are occupied by a control-flow
5733: entry (many systems use one cell. In Gforth they currently take three,
5734: but this may change in the future).
5735:
1.1 anton 5736: Some standard control structure words are built from these words:
5737:
1.44 crook 5738:
1.1 anton 5739: doc-else
5740: doc-while
5741: doc-repeat
5742:
1.44 crook 5743:
5744: @noindent
1.1 anton 5745: Gforth adds some more control-structure words:
5746:
1.44 crook 5747:
1.1 anton 5748: doc-endif
5749: doc-?dup-if
5750: doc-?dup-0=-if
5751:
1.44 crook 5752:
5753: @noindent
1.1 anton 5754: Counted loop words constitute a separate group of words:
5755:
1.44 crook 5756:
1.1 anton 5757: doc-?do
5758: doc-+do
5759: doc-u+do
5760: doc--do
5761: doc-u-do
5762: doc-do
5763: doc-for
5764: doc-loop
5765: doc-+loop
5766: doc--loop
5767: doc-next
5768: doc-leave
5769: doc-?leave
5770: doc-unloop
5771: doc-done
5772:
1.44 crook 5773:
1.21 crook 5774: The standard does not allow using @code{CS-PICK} and @code{CS-ROLL} on
5775: @i{do-sys}. Gforth allows it, but it's your job to ensure that for
1.1 anton 5776: every @code{?DO} etc. there is exactly one @code{UNLOOP} on any path
5777: through the definition (@code{LOOP} etc. compile an @code{UNLOOP} on the
5778: fall-through path). Also, you have to ensure that all @code{LEAVE}s are
5779: resolved (by using one of the loop-ending words or @code{DONE}).
5780:
1.44 crook 5781: @noindent
1.26 crook 5782: Another group of control structure words are:
1.1 anton 5783:
1.44 crook 5784:
1.1 anton 5785: doc-case
5786: doc-endcase
5787: doc-of
5788: doc-endof
5789:
1.44 crook 5790:
1.21 crook 5791: @i{case-sys} and @i{of-sys} cannot be processed using @code{CS-PICK} and
5792: @code{CS-ROLL}.
1.1 anton 5793:
5794: @subsubsection Programming Style
1.47 crook 5795: @cindex control structures programming style
5796: @cindex programming style, arbitrary control structures
1.1 anton 5797:
5798: In order to ensure readability we recommend that you do not create
5799: arbitrary control structures directly, but define new control structure
5800: words for the control structure you want and use these words in your
1.26 crook 5801: program. For example, instead of writing:
1.1 anton 5802:
5803: @example
1.26 crook 5804: BEGIN
1.1 anton 5805: ...
1.26 crook 5806: IF [ 1 CS-ROLL ]
1.1 anton 5807: ...
1.26 crook 5808: AGAIN THEN
1.1 anton 5809: @end example
5810:
1.21 crook 5811: @noindent
1.1 anton 5812: we recommend defining control structure words, e.g.,
5813:
5814: @example
1.26 crook 5815: : WHILE ( DEST -- ORIG DEST )
5816: POSTPONE IF
5817: 1 CS-ROLL ; immediate
5818:
5819: : REPEAT ( orig dest -- )
5820: POSTPONE AGAIN
5821: POSTPONE THEN ; immediate
1.1 anton 5822: @end example
5823:
1.21 crook 5824: @noindent
1.1 anton 5825: and then using these to create the control structure:
5826:
5827: @example
1.26 crook 5828: BEGIN
1.1 anton 5829: ...
1.26 crook 5830: WHILE
1.1 anton 5831: ...
1.26 crook 5832: REPEAT
1.1 anton 5833: @end example
5834:
5835: That's much easier to read, isn't it? Of course, @code{REPEAT} and
5836: @code{WHILE} are predefined, so in this example it would not be
5837: necessary to define them.
5838:
5839: @node Calls and returns, Exception Handling, Arbitrary control structures, Control Structures
5840: @subsection Calls and returns
5841: @cindex calling a definition
5842: @cindex returning from a definition
5843:
1.3 anton 5844: @cindex recursive definitions
5845: A definition can be called simply be writing the name of the definition
1.26 crook 5846: to be called. Normally a definition is invisible during its own
1.3 anton 5847: definition. If you want to write a directly recursive definition, you
1.26 crook 5848: can use @code{recursive} to make the current definition visible, or
5849: @code{recurse} to call the current definition directly.
1.3 anton 5850:
1.44 crook 5851:
1.3 anton 5852: doc-recursive
5853: doc-recurse
5854:
1.44 crook 5855:
1.21 crook 5856: @comment TODO add example of the two recursion methods
1.12 anton 5857: @quotation
5858: @progstyle
5859: I prefer using @code{recursive} to @code{recurse}, because calling the
5860: definition by name is more descriptive (if the name is well-chosen) than
5861: the somewhat cryptic @code{recurse}. E.g., in a quicksort
5862: implementation, it is much better to read (and think) ``now sort the
5863: partitions'' than to read ``now do a recursive call''.
5864: @end quotation
1.3 anton 5865:
1.29 crook 5866: For mutual recursion, use @code{Defer}red words, like this:
1.3 anton 5867:
5868: @example
1.28 crook 5869: Defer foo
1.3 anton 5870:
5871: : bar ( ... -- ... )
5872: ... foo ... ;
5873:
5874: :noname ( ... -- ... )
5875: ... bar ... ;
5876: IS foo
5877: @end example
5878:
1.44 crook 5879: Deferred words are discussed in more detail in @ref{Deferred words}.
1.33 anton 5880:
1.26 crook 5881: The current definition returns control to the calling definition when
1.33 anton 5882: the end of the definition is reached or @code{EXIT} is encountered.
1.1 anton 5883:
5884: doc-exit
5885: doc-;s
5886:
1.44 crook 5887:
1.1 anton 5888: @node Exception Handling, , Calls and returns, Control Structures
5889: @subsection Exception Handling
1.26 crook 5890: @cindex exceptions
1.1 anton 5891:
1.68 anton 5892: @c quit is a very bad idea for error handling,
5893: @c because it does not translate into a THROW
5894: @c it also does not belong into this chapter
5895:
5896: If a word detects an error condition that it cannot handle, it can
5897: @code{throw} an exception. In the simplest case, this will terminate
5898: your program, and report an appropriate error.
1.21 crook 5899:
1.68 anton 5900: doc-throw
1.1 anton 5901:
1.69 anton 5902: @code{Throw} consumes a cell-sized error number on the stack. There are
5903: some predefined error numbers in ANS Forth (see @file{errors.fs}). In
5904: Gforth (and most other systems) you can use the iors produced by various
5905: words as error numbers (e.g., a typical use of @code{allocate} is
5906: @code{allocate throw}). Gforth also provides the word @code{exception}
5907: to define your own error numbers (with decent error reporting); an ANS
5908: Forth version of this word (but without the error messages) is available
5909: in @code{compat/except.fs}. And finally, you can use your own error
1.68 anton 5910: numbers (anything outside the range -4095..0), but won't get nice error
5911: messages, only numbers. For example, try:
5912:
5913: @example
1.69 anton 5914: -10 throw \ ANS defined
5915: -267 throw \ system defined
5916: s" my error" exception throw \ user defined
5917: 7 throw \ arbitrary number
1.68 anton 5918: @end example
5919:
5920: doc---exception-exception
1.1 anton 5921:
1.69 anton 5922: A common idiom to @code{THROW} a specific error if a flag is true is
5923: this:
5924:
5925: @example
5926: @code{( flag ) 0<> @i{errno} and throw}
5927: @end example
5928:
5929: Your program can provide exception handlers to catch exceptions. An
5930: exception handler can be used to correct the problem, or to clean up
5931: some data structures and just throw the exception to the next exception
5932: handler. Note that @code{throw} jumps to the dynamically innermost
5933: exception handler. The system's exception handler is outermost, and just
5934: prints an error and restarts command-line interpretation (or, in batch
5935: mode (i.e., while processing the shell command line), leaves Gforth).
1.1 anton 5936:
1.68 anton 5937: The ANS Forth way to catch exceptions is @code{catch}:
1.1 anton 5938:
1.68 anton 5939: doc-catch
5940:
5941: The most common use of exception handlers is to clean up the state when
5942: an error happens. E.g.,
1.1 anton 5943:
1.26 crook 5944: @example
1.68 anton 5945: base @ >r hex \ actually the hex should be inside foo, or we h
5946: ['] foo catch ( nerror|0 )
5947: r> base !
1.69 anton 5948: ( nerror|0 ) throw \ pass it on
1.26 crook 5949: @end example
1.1 anton 5950:
1.69 anton 5951: A use of @code{catch} for handling the error @code{myerror} might look
5952: like this:
1.44 crook 5953:
1.68 anton 5954: @example
1.69 anton 5955: ['] foo catch
5956: CASE
5957: myerror OF ... ( do something about it ) ENDOF
5958: dup throw \ default: pass other errors on, do nothing on non-errors
5959: ENDCASE
1.68 anton 5960: @end example
1.44 crook 5961:
1.68 anton 5962: Having to wrap the code into a separate word is often cumbersome,
5963: therefore Gforth provides an alternative syntax:
1.1 anton 5964:
5965: @example
1.69 anton 5966: TRY
1.68 anton 5967: @i{code1}
1.69 anton 5968: RECOVER \ optional
1.68 anton 5969: @i{code2} \ optional
1.69 anton 5970: ENDTRY
1.1 anton 5971: @end example
5972:
1.68 anton 5973: This performs @i{Code1}. If @i{code1} completes normally, execution
5974: continues after the @code{endtry}. If @i{Code1} throws, the stacks are
5975: reset to the state during @code{try}, the throw value is pushed on the
5976: data stack, and execution constinues at @i{code2}, and finally falls
1.92 anton 5977: through the @code{endtry} into the following code.
1.26 crook 5978:
1.68 anton 5979: doc-try
5980: doc-recover
5981: doc-endtry
1.26 crook 5982:
1.69 anton 5983: The cleanup example from above in this syntax:
1.26 crook 5984:
1.68 anton 5985: @example
1.69 anton 5986: base @ >r TRY
1.68 anton 5987: hex foo \ now the hex is placed correctly
1.69 anton 5988: 0 \ value for throw
1.92 anton 5989: RECOVER ENDTRY
1.68 anton 5990: r> base ! throw
1.1 anton 5991: @end example
5992:
1.69 anton 5993: And here's the error handling example:
1.1 anton 5994:
1.68 anton 5995: @example
1.69 anton 5996: TRY
1.68 anton 5997: foo
1.69 anton 5998: RECOVER
5999: CASE
6000: myerror OF ... ( do something about it ) ENDOF
6001: throw \ pass other errors on
6002: ENDCASE
6003: ENDTRY
1.68 anton 6004: @end example
1.1 anton 6005:
1.69 anton 6006: @progstyle
6007: As usual, you should ensure that the stack depth is statically known at
6008: the end: either after the @code{throw} for passing on errors, or after
6009: the @code{ENDTRY} (or, if you use @code{catch}, after the end of the
6010: selection construct for handling the error).
6011:
1.68 anton 6012: There are two alternatives to @code{throw}: @code{Abort"} is conditional
6013: and you can provide an error message. @code{Abort} just produces an
6014: ``Aborted'' error.
1.1 anton 6015:
1.68 anton 6016: The problem with these words is that exception handlers cannot
6017: differentiate between different @code{abort"}s; they just look like
6018: @code{-2 throw} to them (the error message cannot be accessed by
6019: standard programs). Similar @code{abort} looks like @code{-1 throw} to
6020: exception handlers.
1.44 crook 6021:
1.68 anton 6022: doc-abort"
1.26 crook 6023: doc-abort
1.29 crook 6024:
6025:
1.44 crook 6026:
1.29 crook 6027: @c -------------------------------------------------------------
1.47 crook 6028: @node Defining Words, Interpretation and Compilation Semantics, Control Structures, Words
1.29 crook 6029: @section Defining Words
6030: @cindex defining words
6031:
1.47 crook 6032: Defining words are used to extend Forth by creating new entries in the dictionary.
6033:
1.29 crook 6034: @menu
1.67 anton 6035: * CREATE::
1.44 crook 6036: * Variables:: Variables and user variables
1.67 anton 6037: * Constants::
1.44 crook 6038: * Values:: Initialised variables
1.67 anton 6039: * Colon Definitions::
1.44 crook 6040: * Anonymous Definitions:: Definitions without names
1.69 anton 6041: * Supplying names:: Passing definition names as strings
1.67 anton 6042: * User-defined Defining Words::
1.44 crook 6043: * Deferred words:: Allow forward references
1.67 anton 6044: * Aliases::
1.29 crook 6045: @end menu
6046:
1.44 crook 6047: @node CREATE, Variables, Defining Words, Defining Words
6048: @subsection @code{CREATE}
1.29 crook 6049: @cindex simple defining words
6050: @cindex defining words, simple
6051:
6052: Defining words are used to create new entries in the dictionary. The
6053: simplest defining word is @code{CREATE}. @code{CREATE} is used like
6054: this:
6055:
6056: @example
6057: CREATE new-word1
6058: @end example
6059:
1.69 anton 6060: @code{CREATE} is a parsing word, i.e., it takes an argument from the
6061: input stream (@code{new-word1} in our example). It generates a
6062: dictionary entry for @code{new-word1}. When @code{new-word1} is
6063: executed, all that it does is leave an address on the stack. The address
6064: represents the value of the data space pointer (@code{HERE}) at the time
6065: that @code{new-word1} was defined. Therefore, @code{CREATE} is a way of
6066: associating a name with the address of a region of memory.
1.29 crook 6067:
1.34 anton 6068: doc-create
6069:
1.69 anton 6070: Note that in ANS Forth guarantees only for @code{create} that its body
6071: is in dictionary data space (i.e., where @code{here}, @code{allot}
6072: etc. work, @pxref{Dictionary allocation}). Also, in ANS Forth only
6073: @code{create}d words can be modified with @code{does>}
6074: (@pxref{User-defined Defining Words}). And in ANS Forth @code{>body}
6075: can only be applied to @code{create}d words.
6076:
1.29 crook 6077: By extending this example to reserve some memory in data space, we end
1.69 anton 6078: up with something like a @i{variable}. Here are two different ways to do
6079: it:
1.29 crook 6080:
6081: @example
6082: CREATE new-word2 1 cells allot \ reserve 1 cell - initial value undefined
6083: CREATE new-word3 4 , \ reserve 1 cell and initialise it (to 4)
6084: @end example
6085:
6086: The variable can be examined and modified using @code{@@} (``fetch'') and
6087: @code{!} (``store'') like this:
6088:
6089: @example
6090: new-word2 @@ . \ get address, fetch from it and display
6091: 1234 new-word2 ! \ new value, get address, store to it
6092: @end example
6093:
1.44 crook 6094: @cindex arrays
6095: A similar mechanism can be used to create arrays. For example, an
6096: 80-character text input buffer:
1.29 crook 6097:
6098: @example
1.44 crook 6099: CREATE text-buf 80 chars allot
6100:
6101: text-buf 0 chars c@@ \ the 1st character (offset 0)
6102: text-buf 3 chars c@@ \ the 4th character (offset 3)
6103: @end example
1.29 crook 6104:
1.44 crook 6105: You can build arbitrarily complex data structures by allocating
1.49 anton 6106: appropriate areas of memory. For further discussions of this, and to
1.66 anton 6107: learn about some Gforth tools that make it easier,
1.49 anton 6108: @xref{Structures}.
1.44 crook 6109:
6110:
6111: @node Variables, Constants, CREATE, Defining Words
6112: @subsection Variables
6113: @cindex variables
6114:
6115: The previous section showed how a sequence of commands could be used to
6116: generate a variable. As a final refinement, the whole code sequence can
6117: be wrapped up in a defining word (pre-empting the subject of the next
6118: section), making it easier to create new variables:
6119:
6120: @example
6121: : myvariableX ( "name" -- a-addr ) CREATE 1 cells allot ;
6122: : myvariable0 ( "name" -- a-addr ) CREATE 0 , ;
6123:
6124: myvariableX foo \ variable foo starts off with an unknown value
6125: myvariable0 joe \ whilst joe is initialised to 0
1.29 crook 6126:
6127: 45 3 * foo ! \ set foo to 135
6128: 1234 joe ! \ set joe to 1234
6129: 3 joe +! \ increment joe by 3.. to 1237
6130: @end example
6131:
6132: Not surprisingly, there is no need to define @code{myvariable}, since
1.44 crook 6133: Forth already has a definition @code{Variable}. ANS Forth does not
1.69 anton 6134: guarantee that a @code{Variable} is initialised when it is created
6135: (i.e., it may behave like @code{myvariableX}). In contrast, Gforth's
6136: @code{Variable} initialises the variable to 0 (i.e., it behaves exactly
6137: like @code{myvariable0}). Forth also provides @code{2Variable} and
1.47 crook 6138: @code{fvariable} for double and floating-point variables, respectively
1.69 anton 6139: -- they are initialised to 0. and 0e in Gforth. If you use a @code{Variable} to
1.47 crook 6140: store a boolean, you can use @code{on} and @code{off} to toggle its
6141: state.
1.29 crook 6142:
1.34 anton 6143: doc-variable
6144: doc-2variable
6145: doc-fvariable
6146:
1.29 crook 6147: @cindex user variables
6148: @cindex user space
6149: The defining word @code{User} behaves in the same way as @code{Variable}.
6150: The difference is that it reserves space in @i{user (data) space} rather
6151: than normal data space. In a Forth system that has a multi-tasker, each
6152: task has its own set of user variables.
6153:
1.34 anton 6154: doc-user
1.67 anton 6155: @c doc-udp
6156: @c doc-uallot
1.34 anton 6157:
1.29 crook 6158: @comment TODO is that stuff about user variables strictly correct? Is it
6159: @comment just terminal tasks that have user variables?
6160: @comment should document tasker.fs (with some examples) elsewhere
6161: @comment in this manual, then expand on user space and user variables.
6162:
1.44 crook 6163: @node Constants, Values, Variables, Defining Words
6164: @subsection Constants
6165: @cindex constants
6166:
6167: @code{Constant} allows you to declare a fixed value and refer to it by
6168: name. For example:
1.29 crook 6169:
6170: @example
6171: 12 Constant INCHES-PER-FOOT
6172: 3E+08 fconstant SPEED-O-LIGHT
6173: @end example
6174:
6175: A @code{Variable} can be both read and written, so its run-time
6176: behaviour is to supply an address through which its current value can be
6177: manipulated. In contrast, the value of a @code{Constant} cannot be
6178: changed once it has been declared@footnote{Well, often it can be -- but
6179: not in a Standard, portable way. It's safer to use a @code{Value} (read
6180: on).} so it's not necessary to supply the address -- it is more
6181: efficient to return the value of the constant directly. That's exactly
6182: what happens; the run-time effect of a constant is to put its value on
1.49 anton 6183: the top of the stack (You can find one
6184: way of implementing @code{Constant} in @ref{User-defined Defining Words}).
1.29 crook 6185:
1.69 anton 6186: Forth also provides @code{2Constant} and @code{fconstant} for defining
1.29 crook 6187: double and floating-point constants, respectively.
6188:
1.34 anton 6189: doc-constant
6190: doc-2constant
6191: doc-fconstant
6192:
6193: @c that's too deep, and it's not necessarily true for all ANS Forths. - anton
1.44 crook 6194: @c nac-> How could that not be true in an ANS Forth? You can't define a
6195: @c constant, use it and then delete the definition of the constant..
1.69 anton 6196:
6197: @c anton->An ANS Forth system can compile a constant to a literal; On
6198: @c decompilation you would see only the number, just as if it had been used
6199: @c in the first place. The word will stay, of course, but it will only be
6200: @c used by the text interpreter (no run-time duties, except when it is
6201: @c POSTPONEd or somesuch).
6202:
6203: @c nac:
1.44 crook 6204: @c I agree that it's rather deep, but IMO it is an important difference
6205: @c relative to other programming languages.. often it's annoying: it
6206: @c certainly changes my programming style relative to C.
6207:
1.69 anton 6208: @c anton: In what way?
6209:
1.29 crook 6210: Constants in Forth behave differently from their equivalents in other
6211: programming languages. In other languages, a constant (such as an EQU in
6212: assembler or a #define in C) only exists at compile-time; in the
6213: executable program the constant has been translated into an absolute
6214: number and, unless you are using a symbolic debugger, it's impossible to
6215: know what abstract thing that number represents. In Forth a constant has
1.44 crook 6216: an entry in the header space and remains there after the code that uses
6217: it has been defined. In fact, it must remain in the dictionary since it
6218: has run-time duties to perform. For example:
1.29 crook 6219:
6220: @example
6221: 12 Constant INCHES-PER-FOOT
6222: : FEET-TO-INCHES ( n1 -- n2 ) INCHES-PER-FOOT * ;
6223: @end example
6224:
6225: @cindex in-lining of constants
6226: When @code{FEET-TO-INCHES} is executed, it will in turn execute the xt
6227: associated with the constant @code{INCHES-PER-FOOT}. If you use
6228: @code{see} to decompile the definition of @code{FEET-TO-INCHES}, you can
6229: see that it makes a call to @code{INCHES-PER-FOOT}. Some Forth compilers
6230: attempt to optimise constants by in-lining them where they are used. You
6231: can force Gforth to in-line a constant like this:
6232:
6233: @example
6234: : FEET-TO-INCHES ( n1 -- n2 ) [ INCHES-PER-FOOT ] LITERAL * ;
6235: @end example
6236:
6237: If you use @code{see} to decompile @i{this} version of
6238: @code{FEET-TO-INCHES}, you can see that @code{INCHES-PER-FOOT} is no
1.49 anton 6239: longer present. To understand how this works, read
6240: @ref{Interpret/Compile states}, and @ref{Literals}.
1.29 crook 6241:
6242: In-lining constants in this way might improve execution time
6243: fractionally, and can ensure that a constant is now only referenced at
6244: compile-time. However, the definition of the constant still remains in
6245: the dictionary. Some Forth compilers provide a mechanism for controlling
6246: a second dictionary for holding transient words such that this second
6247: dictionary can be deleted later in order to recover memory
6248: space. However, there is no standard way of doing this.
6249:
6250:
1.44 crook 6251: @node Values, Colon Definitions, Constants, Defining Words
6252: @subsection Values
6253: @cindex values
1.34 anton 6254:
1.69 anton 6255: A @code{Value} behaves like a @code{Constant}, but it can be changed.
6256: @code{TO} is a parsing word that changes a @code{Values}. In Gforth
6257: (not in ANS Forth) you can access (and change) a @code{value} also with
6258: @code{>body}.
6259:
6260: Here are some
6261: examples:
1.29 crook 6262:
6263: @example
1.69 anton 6264: 12 Value APPLES \ Define APPLES with an initial value of 12
6265: 34 TO APPLES \ Change the value of APPLES. TO is a parsing word
6266: 1 ' APPLES >body +! \ Increment APPLES. Non-standard usage.
6267: APPLES \ puts 35 on the top of the stack.
1.29 crook 6268: @end example
6269:
1.44 crook 6270: doc-value
6271: doc-to
1.29 crook 6272:
1.35 anton 6273:
1.69 anton 6274:
1.44 crook 6275: @node Colon Definitions, Anonymous Definitions, Values, Defining Words
6276: @subsection Colon Definitions
6277: @cindex colon definitions
1.35 anton 6278:
6279: @example
1.44 crook 6280: : name ( ... -- ... )
6281: word1 word2 word3 ;
1.29 crook 6282: @end example
6283:
1.44 crook 6284: @noindent
6285: Creates a word called @code{name} that, upon execution, executes
6286: @code{word1 word2 word3}. @code{name} is a @dfn{(colon) definition}.
1.29 crook 6287:
1.49 anton 6288: The explanation above is somewhat superficial. For simple examples of
6289: colon definitions see @ref{Your first definition}. For an in-depth
1.66 anton 6290: discussion of some of the issues involved, @xref{Interpretation and
1.49 anton 6291: Compilation Semantics}.
1.29 crook 6292:
1.44 crook 6293: doc-:
6294: doc-;
1.1 anton 6295:
1.34 anton 6296:
1.69 anton 6297: @node Anonymous Definitions, Supplying names, Colon Definitions, Defining Words
1.44 crook 6298: @subsection Anonymous Definitions
6299: @cindex colon definitions
6300: @cindex defining words without name
1.34 anton 6301:
1.44 crook 6302: Sometimes you want to define an @dfn{anonymous word}; a word without a
6303: name. You can do this with:
1.1 anton 6304:
1.44 crook 6305: doc-:noname
1.1 anton 6306:
1.44 crook 6307: This leaves the execution token for the word on the stack after the
6308: closing @code{;}. Here's an example in which a deferred word is
6309: initialised with an @code{xt} from an anonymous colon definition:
1.1 anton 6310:
1.29 crook 6311: @example
1.44 crook 6312: Defer deferred
6313: :noname ( ... -- ... )
6314: ... ;
6315: IS deferred
1.29 crook 6316: @end example
1.26 crook 6317:
1.44 crook 6318: @noindent
6319: Gforth provides an alternative way of doing this, using two separate
6320: words:
1.27 crook 6321:
1.44 crook 6322: doc-noname
6323: @cindex execution token of last defined word
6324: doc-lastxt
1.1 anton 6325:
1.44 crook 6326: @noindent
6327: The previous example can be rewritten using @code{noname} and
6328: @code{lastxt}:
1.1 anton 6329:
1.26 crook 6330: @example
1.44 crook 6331: Defer deferred
6332: noname : ( ... -- ... )
6333: ... ;
6334: lastxt IS deferred
1.26 crook 6335: @end example
1.1 anton 6336:
1.29 crook 6337: @noindent
1.44 crook 6338: @code{noname} works with any defining word, not just @code{:}.
6339:
6340: @code{lastxt} also works when the last word was not defined as
1.71 anton 6341: @code{noname}. It does not work for combined words, though. It also has
6342: the useful property that is is valid as soon as the header for a
6343: definition has been built. Thus:
1.44 crook 6344:
6345: @example
6346: lastxt . : foo [ lastxt . ] ; ' foo .
6347: @end example
1.1 anton 6348:
1.44 crook 6349: @noindent
6350: prints 3 numbers; the last two are the same.
1.26 crook 6351:
1.69 anton 6352: @node Supplying names, User-defined Defining Words, Anonymous Definitions, Defining Words
6353: @subsection Supplying the name of a defined word
6354: @cindex names for defined words
6355: @cindex defining words, name given in a string
6356:
6357: By default, a defining word takes the name for the defined word from the
6358: input stream. Sometimes you want to supply the name from a string. You
6359: can do this with:
6360:
6361: doc-nextname
6362:
6363: For example:
6364:
6365: @example
6366: s" foo" nextname create
6367: @end example
6368:
6369: @noindent
6370: is equivalent to:
6371:
6372: @example
6373: create foo
6374: @end example
6375:
6376: @noindent
6377: @code{nextname} works with any defining word.
6378:
1.1 anton 6379:
1.69 anton 6380: @node User-defined Defining Words, Deferred words, Supplying names, Defining Words
1.26 crook 6381: @subsection User-defined Defining Words
6382: @cindex user-defined defining words
6383: @cindex defining words, user-defined
1.1 anton 6384:
1.29 crook 6385: You can create a new defining word by wrapping defining-time code around
6386: an existing defining word and putting the sequence in a colon
1.69 anton 6387: definition.
6388:
6389: @c anton: This example is very complex and leads in a quite different
6390: @c direction from the CREATE-DOES> stuff that follows. It should probably
6391: @c be done elsewhere, or as a subsubsection of this subsection (or as a
6392: @c subsection of Defining Words)
6393:
6394: For example, suppose that you have a word @code{stats} that
1.29 crook 6395: gathers statistics about colon definitions given the @i{xt} of the
6396: definition, and you want every colon definition in your application to
6397: make a call to @code{stats}. You can define and use a new version of
6398: @code{:} like this:
6399:
6400: @example
6401: : stats ( xt -- ) DUP ." (Gathering statistics for " . ." )"
6402: ... ; \ other code
6403:
6404: : my: : lastxt postpone literal ['] stats compile, ;
6405:
6406: my: foo + - ;
6407: @end example
6408:
6409: When @code{foo} is defined using @code{my:} these steps occur:
6410:
6411: @itemize @bullet
6412: @item
6413: @code{my:} is executed.
6414: @item
6415: The @code{:} within the definition (the one between @code{my:} and
6416: @code{lastxt}) is executed, and does just what it always does; it parses
6417: the input stream for a name, builds a dictionary header for the name
6418: @code{foo} and switches @code{state} from interpret to compile.
6419: @item
6420: The word @code{lastxt} is executed. It puts the @i{xt} for the word that is
6421: being defined -- @code{foo} -- onto the stack.
6422: @item
6423: The code that was produced by @code{postpone literal} is executed; this
6424: causes the value on the stack to be compiled as a literal in the code
6425: area of @code{foo}.
6426: @item
6427: The code @code{['] stats} compiles a literal into the definition of
6428: @code{my:}. When @code{compile,} is executed, that literal -- the
6429: execution token for @code{stats} -- is layed down in the code area of
6430: @code{foo} , following the literal@footnote{Strictly speaking, the
6431: mechanism that @code{compile,} uses to convert an @i{xt} into something
6432: in the code area is implementation-dependent. A threaded implementation
6433: might spit out the execution token directly whilst another
6434: implementation might spit out a native code sequence.}.
6435: @item
6436: At this point, the execution of @code{my:} is complete, and control
6437: returns to the text interpreter. The text interpreter is in compile
6438: state, so subsequent text @code{+ -} is compiled into the definition of
6439: @code{foo} and the @code{;} terminates the definition as always.
6440: @end itemize
6441:
6442: You can use @code{see} to decompile a word that was defined using
6443: @code{my:} and see how it is different from a normal @code{:}
6444: definition. For example:
6445:
6446: @example
6447: : bar + - ; \ like foo but using : rather than my:
6448: see bar
6449: : bar
6450: + - ;
6451: see foo
6452: : foo
6453: 107645672 stats + - ;
6454:
6455: \ use ' stats . to show that 107645672 is the xt for stats
6456: @end example
6457:
6458: You can use techniques like this to make new defining words in terms of
6459: @i{any} existing defining word.
1.1 anton 6460:
6461:
1.29 crook 6462: @cindex defining defining words
1.26 crook 6463: @cindex @code{CREATE} ... @code{DOES>}
6464: If you want the words defined with your defining words to behave
6465: differently from words defined with standard defining words, you can
6466: write your defining word like this:
1.1 anton 6467:
6468: @example
1.26 crook 6469: : def-word ( "name" -- )
1.29 crook 6470: CREATE @i{code1}
1.26 crook 6471: DOES> ( ... -- ... )
1.29 crook 6472: @i{code2} ;
1.26 crook 6473:
6474: def-word name
1.1 anton 6475: @end example
6476:
1.29 crook 6477: @cindex child words
6478: This fragment defines a @dfn{defining word} @code{def-word} and then
6479: executes it. When @code{def-word} executes, it @code{CREATE}s a new
6480: word, @code{name}, and executes the code @i{code1}. The code @i{code2}
6481: is not executed at this time. The word @code{name} is sometimes called a
6482: @dfn{child} of @code{def-word}.
6483:
6484: When you execute @code{name}, the address of the body of @code{name} is
6485: put on the data stack and @i{code2} is executed (the address of the body
6486: of @code{name} is the address @code{HERE} returns immediately after the
1.69 anton 6487: @code{CREATE}, i.e., the address a @code{create}d word returns by
6488: default).
6489:
6490: @c anton:
6491: @c www.dictionary.com says:
6492: @c at·a·vism: 1.The reappearance of a characteristic in an organism after
6493: @c several generations of absence, usually caused by the chance
6494: @c recombination of genes. 2.An individual or a part that exhibits
6495: @c atavism. Also called throwback. 3.The return of a trait or recurrence
6496: @c of previous behavior after a period of absence.
6497: @c
6498: @c Doesn't seem to fit.
1.29 crook 6499:
1.69 anton 6500: @c @cindex atavism in child words
1.33 anton 6501: You can use @code{def-word} to define a set of child words that behave
1.69 anton 6502: similarly; they all have a common run-time behaviour determined by
6503: @i{code2}. Typically, the @i{code1} sequence builds a data area in the
6504: body of the child word. The structure of the data is common to all
6505: children of @code{def-word}, but the data values are specific -- and
6506: private -- to each child word. When a child word is executed, the
6507: address of its private data area is passed as a parameter on TOS to be
6508: used and manipulated@footnote{It is legitimate both to read and write to
6509: this data area.} by @i{code2}.
1.29 crook 6510:
6511: The two fragments of code that make up the defining words act (are
6512: executed) at two completely separate times:
1.1 anton 6513:
1.29 crook 6514: @itemize @bullet
6515: @item
6516: At @i{define time}, the defining word executes @i{code1} to generate a
6517: child word
6518: @item
6519: At @i{child execution time}, when a child word is invoked, @i{code2}
6520: is executed, using parameters (data) that are private and specific to
6521: the child word.
6522: @end itemize
6523:
1.44 crook 6524: Another way of understanding the behaviour of @code{def-word} and
6525: @code{name} is to say that, if you make the following definitions:
1.33 anton 6526: @example
6527: : def-word1 ( "name" -- )
6528: CREATE @i{code1} ;
6529:
6530: : action1 ( ... -- ... )
6531: @i{code2} ;
6532:
6533: def-word1 name1
6534: @end example
6535:
1.44 crook 6536: @noindent
6537: Then using @code{name1 action1} is equivalent to using @code{name}.
1.1 anton 6538:
1.29 crook 6539: The classic example is that you can define @code{CONSTANT} in this way:
1.26 crook 6540:
1.1 anton 6541: @example
1.29 crook 6542: : CONSTANT ( w "name" -- )
6543: CREATE ,
1.26 crook 6544: DOES> ( -- w )
6545: @@ ;
1.1 anton 6546: @end example
6547:
1.29 crook 6548: @comment There is a beautiful description of how this works and what
6549: @comment it does in the Forthwrite 100th edition.. as well as an elegant
6550: @comment commentary on the Counting Fruits problem.
6551:
6552: When you create a constant with @code{5 CONSTANT five}, a set of
6553: define-time actions take place; first a new word @code{five} is created,
6554: then the value 5 is laid down in the body of @code{five} with
1.44 crook 6555: @code{,}. When @code{five} is executed, the address of the body is put on
1.29 crook 6556: the stack, and @code{@@} retrieves the value 5. The word @code{five} has
6557: no code of its own; it simply contains a data field and a pointer to the
6558: code that follows @code{DOES>} in its defining word. That makes words
6559: created in this way very compact.
6560:
6561: The final example in this section is intended to remind you that space
6562: reserved in @code{CREATE}d words is @i{data} space and therefore can be
6563: both read and written by a Standard program@footnote{Exercise: use this
6564: example as a starting point for your own implementation of @code{Value}
6565: and @code{TO} -- if you get stuck, investigate the behaviour of @code{'} and
6566: @code{[']}.}:
6567:
6568: @example
6569: : foo ( "name" -- )
6570: CREATE -1 ,
6571: DOES> ( -- )
1.33 anton 6572: @@ . ;
1.29 crook 6573:
6574: foo first-word
6575: foo second-word
6576:
6577: 123 ' first-word >BODY !
6578: @end example
6579:
6580: If @code{first-word} had been a @code{CREATE}d word, we could simply
6581: have executed it to get the address of its data field. However, since it
6582: was defined to have @code{DOES>} actions, its execution semantics are to
6583: perform those @code{DOES>} actions. To get the address of its data field
6584: it's necessary to use @code{'} to get its xt, then @code{>BODY} to
6585: translate the xt into the address of the data field. When you execute
6586: @code{first-word}, it will display @code{123}. When you execute
6587: @code{second-word} it will display @code{-1}.
1.26 crook 6588:
6589: @cindex stack effect of @code{DOES>}-parts
6590: @cindex @code{DOES>}-parts, stack effect
1.29 crook 6591: In the examples above the stack comment after the @code{DOES>} specifies
1.26 crook 6592: the stack effect of the defined words, not the stack effect of the
6593: following code (the following code expects the address of the body on
6594: the top of stack, which is not reflected in the stack comment). This is
6595: the convention that I use and recommend (it clashes a bit with using
6596: locals declarations for stack effect specification, though).
1.1 anton 6597:
1.53 anton 6598: @menu
6599: * CREATE..DOES> applications::
6600: * CREATE..DOES> details::
1.63 anton 6601: * Advanced does> usage example::
1.91 anton 6602: * @code{Const-does>}::
1.53 anton 6603: @end menu
6604:
6605: @node CREATE..DOES> applications, CREATE..DOES> details, User-defined Defining Words, User-defined Defining Words
1.26 crook 6606: @subsubsection Applications of @code{CREATE..DOES>}
6607: @cindex @code{CREATE} ... @code{DOES>}, applications
1.1 anton 6608:
1.26 crook 6609: You may wonder how to use this feature. Here are some usage patterns:
1.1 anton 6610:
1.26 crook 6611: @cindex factoring similar colon definitions
6612: When you see a sequence of code occurring several times, and you can
6613: identify a meaning, you will factor it out as a colon definition. When
6614: you see similar colon definitions, you can factor them using
6615: @code{CREATE..DOES>}. E.g., an assembler usually defines several words
6616: that look very similar:
1.1 anton 6617: @example
1.26 crook 6618: : ori, ( reg-target reg-source n -- )
6619: 0 asm-reg-reg-imm ;
6620: : andi, ( reg-target reg-source n -- )
6621: 1 asm-reg-reg-imm ;
1.1 anton 6622: @end example
6623:
1.26 crook 6624: @noindent
6625: This could be factored with:
6626: @example
6627: : reg-reg-imm ( op-code -- )
6628: CREATE ,
6629: DOES> ( reg-target reg-source n -- )
6630: @@ asm-reg-reg-imm ;
6631:
6632: 0 reg-reg-imm ori,
6633: 1 reg-reg-imm andi,
6634: @end example
1.1 anton 6635:
1.26 crook 6636: @cindex currying
6637: Another view of @code{CREATE..DOES>} is to consider it as a crude way to
6638: supply a part of the parameters for a word (known as @dfn{currying} in
6639: the functional language community). E.g., @code{+} needs two
6640: parameters. Creating versions of @code{+} with one parameter fixed can
6641: be done like this:
1.82 anton 6642:
1.1 anton 6643: @example
1.82 anton 6644: : curry+ ( n1 "name" -- )
1.26 crook 6645: CREATE ,
6646: DOES> ( n2 -- n1+n2 )
6647: @@ + ;
6648:
6649: 3 curry+ 3+
6650: -2 curry+ 2-
1.1 anton 6651: @end example
6652:
1.91 anton 6653:
1.63 anton 6654: @node CREATE..DOES> details, Advanced does> usage example, CREATE..DOES> applications, User-defined Defining Words
1.26 crook 6655: @subsubsection The gory details of @code{CREATE..DOES>}
6656: @cindex @code{CREATE} ... @code{DOES>}, details
1.1 anton 6657:
1.26 crook 6658: doc-does>
1.1 anton 6659:
1.26 crook 6660: @cindex @code{DOES>} in a separate definition
6661: This means that you need not use @code{CREATE} and @code{DOES>} in the
6662: same definition; you can put the @code{DOES>}-part in a separate
1.29 crook 6663: definition. This allows us to, e.g., select among different @code{DOES>}-parts:
1.26 crook 6664: @example
6665: : does1
6666: DOES> ( ... -- ... )
1.44 crook 6667: ... ;
6668:
6669: : does2
6670: DOES> ( ... -- ... )
6671: ... ;
6672:
6673: : def-word ( ... -- ... )
6674: create ...
6675: IF
6676: does1
6677: ELSE
6678: does2
6679: ENDIF ;
6680: @end example
6681:
6682: In this example, the selection of whether to use @code{does1} or
1.69 anton 6683: @code{does2} is made at definition-time; at the time that the child word is
1.44 crook 6684: @code{CREATE}d.
6685:
6686: @cindex @code{DOES>} in interpretation state
6687: In a standard program you can apply a @code{DOES>}-part only if the last
6688: word was defined with @code{CREATE}. In Gforth, the @code{DOES>}-part
6689: will override the behaviour of the last word defined in any case. In a
6690: standard program, you can use @code{DOES>} only in a colon
6691: definition. In Gforth, you can also use it in interpretation state, in a
6692: kind of one-shot mode; for example:
6693: @example
6694: CREATE name ( ... -- ... )
6695: @i{initialization}
6696: DOES>
6697: @i{code} ;
6698: @end example
6699:
6700: @noindent
6701: is equivalent to the standard:
6702: @example
6703: :noname
6704: DOES>
6705: @i{code} ;
6706: CREATE name EXECUTE ( ... -- ... )
6707: @i{initialization}
6708: @end example
6709:
1.53 anton 6710: doc->body
6711:
1.91 anton 6712: @node Advanced does> usage example, @code{Const-does>}, CREATE..DOES> details, User-defined Defining Words
1.63 anton 6713: @subsubsection Advanced does> usage example
6714:
6715: The MIPS disassembler (@file{arch/mips/disasm.fs}) contains many words
6716: for disassembling instructions, that follow a very repetetive scheme:
6717:
6718: @example
6719: :noname @var{disasm-operands} s" @var{inst-name}" type ;
6720: @var{entry-num} cells @var{table} + !
6721: @end example
6722:
6723: Of course, this inspires the idea to factor out the commonalities to
6724: allow a definition like
6725:
6726: @example
6727: @var{disasm-operands} @var{entry-num} @var{table} define-inst @var{inst-name}
6728: @end example
6729:
6730: The parameters @var{disasm-operands} and @var{table} are usually
1.69 anton 6731: correlated. Moreover, before I wrote the disassembler, there already
6732: existed code that defines instructions like this:
1.63 anton 6733:
6734: @example
6735: @var{entry-num} @var{inst-format} @var{inst-name}
6736: @end example
6737:
6738: This code comes from the assembler and resides in
6739: @file{arch/mips/insts.fs}.
6740:
6741: So I had to define the @var{inst-format} words that performed the scheme
6742: above when executed. At first I chose to use run-time code-generation:
6743:
6744: @example
6745: : @var{inst-format} ( entry-num "name" -- ; compiled code: addr w -- )
6746: :noname Postpone @var{disasm-operands}
6747: name Postpone sliteral Postpone type Postpone ;
6748: swap cells @var{table} + ! ;
6749: @end example
6750:
6751: Note that this supplies the other two parameters of the scheme above.
1.44 crook 6752:
1.63 anton 6753: An alternative would have been to write this using
6754: @code{create}/@code{does>}:
6755:
6756: @example
6757: : @var{inst-format} ( entry-num "name" -- )
6758: here name string, ( entry-num c-addr ) \ parse and save "name"
6759: noname create , ( entry-num )
6760: lastxt swap cells @var{table} + !
6761: does> ( addr w -- )
6762: \ disassemble instruction w at addr
6763: @@ >r
6764: @var{disasm-operands}
6765: r> count type ;
6766: @end example
6767:
6768: Somehow the first solution is simpler, mainly because it's simpler to
6769: shift a string from definition-time to use-time with @code{sliteral}
6770: than with @code{string,} and friends.
6771:
6772: I wrote a lot of words following this scheme and soon thought about
6773: factoring out the commonalities among them. Note that this uses a
6774: two-level defining word, i.e., a word that defines ordinary defining
6775: words.
6776:
6777: This time a solution involving @code{postpone} and friends seemed more
6778: difficult (try it as an exercise), so I decided to use a
6779: @code{create}/@code{does>} word; since I was already at it, I also used
6780: @code{create}/@code{does>} for the lower level (try using
6781: @code{postpone} etc. as an exercise), resulting in the following
6782: definition:
6783:
6784: @example
6785: : define-format ( disasm-xt table-xt -- )
6786: \ define an instruction format that uses disasm-xt for
6787: \ disassembling and enters the defined instructions into table
6788: \ table-xt
6789: create 2,
6790: does> ( u "inst" -- )
6791: \ defines an anonymous word for disassembling instruction inst,
6792: \ and enters it as u-th entry into table-xt
6793: 2@@ swap here name string, ( u table-xt disasm-xt c-addr ) \ remember string
6794: noname create 2, \ define anonymous word
6795: execute lastxt swap ! \ enter xt of defined word into table-xt
6796: does> ( addr w -- )
6797: \ disassemble instruction w at addr
6798: 2@@ >r ( addr w disasm-xt R: c-addr )
6799: execute ( R: c-addr ) \ disassemble operands
6800: r> count type ; \ print name
6801: @end example
6802:
6803: Note that the tables here (in contrast to above) do the @code{cells +}
6804: by themselves (that's why you have to pass an xt). This word is used in
6805: the following way:
6806:
6807: @example
6808: ' @var{disasm-operands} ' @var{table} define-format @var{inst-format}
6809: @end example
6810:
1.71 anton 6811: As shown above, the defined instruction format is then used like this:
6812:
6813: @example
6814: @var{entry-num} @var{inst-format} @var{inst-name}
6815: @end example
6816:
1.63 anton 6817: In terms of currying, this kind of two-level defining word provides the
6818: parameters in three stages: first @var{disasm-operands} and @var{table},
6819: then @var{entry-num} and @var{inst-name}, finally @code{addr w}, i.e.,
6820: the instruction to be disassembled.
6821:
6822: Of course this did not quite fit all the instruction format names used
6823: in @file{insts.fs}, so I had to define a few wrappers that conditioned
6824: the parameters into the right form.
6825:
6826: If you have trouble following this section, don't worry. First, this is
6827: involved and takes time (and probably some playing around) to
6828: understand; second, this is the first two-level
6829: @code{create}/@code{does>} word I have written in seventeen years of
6830: Forth; and if I did not have @file{insts.fs} to start with, I may well
6831: have elected to use just a one-level defining word (with some repeating
6832: of parameters when using the defining word). So it is not necessary to
6833: understand this, but it may improve your understanding of Forth.
1.44 crook 6834:
6835:
1.91 anton 6836: @node @code{Const-does>}, , Advanced does> usage example, User-defined Defining Words
6837: @subsubsection @code{Const-does>}
6838:
6839: A frequent use of @code{create}...@code{does>} is for transferring some
6840: values from definition-time to run-time. Gforth supports this use with
6841:
6842: doc-const-does>
6843:
6844: A typical use of this word is:
6845:
6846: @example
6847: : curry+ ( n1 "name" -- )
6848: 1 0 CONST-DOES> ( n2 -- n1+n2 )
6849: + ;
6850:
6851: 3 curry+ 3+
6852: @end example
6853:
6854: Here the @code{1 0} means that 1 cell and 0 floats are transferred from
6855: definition to run-time.
6856:
6857: The advantages of using @code{const-does>} are:
6858:
6859: @itemize
6860:
6861: @item
6862: You don't have to deal with storing and retrieving the values, i.e.,
6863: your program becomes more writable and readable.
6864:
6865: @item
6866: When using @code{does>}, you have to introduce a @code{@@} that cannot
6867: be optimized away (because you could change the data using
6868: @code{>body}...@code{!}); @code{const-does>} avoids this problem.
6869:
6870: @end itemize
6871:
6872: An ANS Forth implementation of @code{const-does>} is available in
6873: @file{compat/const-does.fs}.
6874:
6875:
1.44 crook 6876: @node Deferred words, Aliases, User-defined Defining Words, Defining Words
6877: @subsection Deferred words
6878: @cindex deferred words
6879:
6880: The defining word @code{Defer} allows you to define a word by name
6881: without defining its behaviour; the definition of its behaviour is
6882: deferred. Here are two situation where this can be useful:
6883:
6884: @itemize @bullet
6885: @item
6886: Where you want to allow the behaviour of a word to be altered later, and
6887: for all precompiled references to the word to change when its behaviour
6888: is changed.
6889: @item
6890: For mutual recursion; @xref{Calls and returns}.
6891: @end itemize
6892:
6893: In the following example, @code{foo} always invokes the version of
6894: @code{greet} that prints ``@code{Good morning}'' whilst @code{bar}
6895: always invokes the version that prints ``@code{Hello}''. There is no way
6896: of getting @code{foo} to use the later version without re-ordering the
6897: source code and recompiling it.
6898:
6899: @example
6900: : greet ." Good morning" ;
6901: : foo ... greet ... ;
6902: : greet ." Hello" ;
6903: : bar ... greet ... ;
6904: @end example
6905:
6906: This problem can be solved by defining @code{greet} as a @code{Defer}red
6907: word. The behaviour of a @code{Defer}red word can be defined and
6908: redefined at any time by using @code{IS} to associate the xt of a
6909: previously-defined word with it. The previous example becomes:
6910:
6911: @example
1.69 anton 6912: Defer greet ( -- )
1.44 crook 6913: : foo ... greet ... ;
6914: : bar ... greet ... ;
1.69 anton 6915: : greet1 ( -- ) ." Good morning" ;
6916: : greet2 ( -- ) ." Hello" ;
1.44 crook 6917: ' greet2 <IS> greet \ make greet behave like greet2
6918: @end example
6919:
1.69 anton 6920: @progstyle
6921: You should write a stack comment for every deferred word, and put only
6922: XTs into deferred words that conform to this stack effect. Otherwise
6923: it's too difficult to use the deferred word.
6924:
1.44 crook 6925: A deferred word can be used to improve the statistics-gathering example
6926: from @ref{User-defined Defining Words}; rather than edit the
6927: application's source code to change every @code{:} to a @code{my:}, do
6928: this:
6929:
6930: @example
6931: : real: : ; \ retain access to the original
6932: defer : \ redefine as a deferred word
1.69 anton 6933: ' my: <IS> : \ use special version of :
1.44 crook 6934: \
6935: \ load application here
6936: \
1.69 anton 6937: ' real: <IS> : \ go back to the original
1.44 crook 6938: @end example
6939:
6940:
6941: One thing to note is that @code{<IS>} consumes its name when it is
6942: executed. If you want to specify the name at compile time, use
6943: @code{[IS]}:
6944:
6945: @example
6946: : set-greet ( xt -- )
6947: [IS] greet ;
6948:
6949: ' greet1 set-greet
6950: @end example
6951:
1.69 anton 6952: A deferred word can only inherit execution semantics from the xt
6953: (because that is all that an xt can represent -- for more discussion of
6954: this @pxref{Tokens for Words}); by default it will have default
6955: interpretation and compilation semantics deriving from this execution
6956: semantics. However, you can change the interpretation and compilation
6957: semantics of the deferred word in the usual ways:
1.44 crook 6958:
6959: @example
6960: : bar .... ; compile-only
6961: Defer fred immediate
6962: Defer jim
6963:
6964: ' bar <IS> jim \ jim has default semantics
6965: ' bar <IS> fred \ fred is immediate
6966: @end example
6967:
6968: doc-defer
6969: doc-<is>
6970: doc-[is]
6971: doc-is
6972: @comment TODO document these: what's defers [is]
6973: doc-what's
6974: doc-defers
6975:
6976: @c Use @code{words-deferred} to see a list of deferred words.
6977:
6978: Definitions in ANS Forth for @code{defer}, @code{<is>} and @code{[is]}
6979: are provided in @file{compat/defer.fs}.
6980:
6981:
1.69 anton 6982: @node Aliases, , Deferred words, Defining Words
1.44 crook 6983: @subsection Aliases
6984: @cindex aliases
1.1 anton 6985:
1.44 crook 6986: The defining word @code{Alias} allows you to define a word by name that
6987: has the same behaviour as some other word. Here are two situation where
6988: this can be useful:
1.1 anton 6989:
1.44 crook 6990: @itemize @bullet
6991: @item
6992: When you want access to a word's definition from a different word list
6993: (for an example of this, see the definition of the @code{Root} word list
6994: in the Gforth source).
6995: @item
6996: When you want to create a synonym; a definition that can be known by
6997: either of two names (for example, @code{THEN} and @code{ENDIF} are
6998: aliases).
6999: @end itemize
1.1 anton 7000:
1.69 anton 7001: Like deferred words, an alias has default compilation and interpretation
7002: semantics at the beginning (not the modifications of the other word),
7003: but you can change them in the usual ways (@code{immediate},
7004: @code{compile-only}). For example:
1.1 anton 7005:
7006: @example
1.44 crook 7007: : foo ... ; immediate
7008:
7009: ' foo Alias bar \ bar is not an immediate word
7010: ' foo Alias fooby immediate \ fooby is an immediate word
1.1 anton 7011: @end example
7012:
1.44 crook 7013: Words that are aliases have the same xt, different headers in the
7014: dictionary, and consequently different name tokens (@pxref{Tokens for
7015: Words}) and possibly different immediate flags. An alias can only have
7016: default or immediate compilation semantics; you can define aliases for
7017: combined words with @code{interpret/compile:} -- see @ref{Combined words}.
1.1 anton 7018:
1.44 crook 7019: doc-alias
1.1 anton 7020:
7021:
1.47 crook 7022: @node Interpretation and Compilation Semantics, Tokens for Words, Defining Words, Words
7023: @section Interpretation and Compilation Semantics
1.26 crook 7024: @cindex semantics, interpretation and compilation
1.1 anton 7025:
1.71 anton 7026: @c !! state and ' are used without explanation
7027: @c example for immediate/compile-only? or is the tutorial enough
7028:
1.26 crook 7029: @cindex interpretation semantics
1.71 anton 7030: The @dfn{interpretation semantics} of a (named) word are what the text
1.26 crook 7031: interpreter does when it encounters the word in interpret state. It also
7032: appears in some other contexts, e.g., the execution token returned by
1.71 anton 7033: @code{' @i{word}} identifies the interpretation semantics of @i{word}
7034: (in other words, @code{' @i{word} execute} is equivalent to
1.29 crook 7035: interpret-state text interpretation of @code{@i{word}}).
1.1 anton 7036:
1.26 crook 7037: @cindex compilation semantics
1.71 anton 7038: The @dfn{compilation semantics} of a (named) word are what the text
7039: interpreter does when it encounters the word in compile state. It also
7040: appears in other contexts, e.g, @code{POSTPONE @i{word}}
7041: compiles@footnote{In standard terminology, ``appends to the current
7042: definition''.} the compilation semantics of @i{word}.
1.1 anton 7043:
1.26 crook 7044: @cindex execution semantics
7045: The standard also talks about @dfn{execution semantics}. They are used
7046: only for defining the interpretation and compilation semantics of many
7047: words. By default, the interpretation semantics of a word are to
7048: @code{execute} its execution semantics, and the compilation semantics of
7049: a word are to @code{compile,} its execution semantics.@footnote{In
7050: standard terminology: The default interpretation semantics are its
7051: execution semantics; the default compilation semantics are to append its
7052: execution semantics to the execution semantics of the current
7053: definition.}
7054:
1.71 anton 7055: Unnamed words (@pxref{Anonymous Definitions}) cannot be encountered by
7056: the text interpreter, ticked, or @code{postpone}d, so they have no
7057: interpretation or compilation semantics. Their behaviour is represented
7058: by their XT (@pxref{Tokens for Words}), and we call it execution
7059: semantics, too.
7060:
1.26 crook 7061: @comment TODO expand, make it co-operate with new sections on text interpreter.
7062:
7063: @cindex immediate words
7064: @cindex compile-only words
7065: You can change the semantics of the most-recently defined word:
7066:
1.44 crook 7067:
1.26 crook 7068: doc-immediate
7069: doc-compile-only
7070: doc-restrict
7071:
1.82 anton 7072: By convention, words with non-default compilation semantics (e.g.,
7073: immediate words) often have names surrounded with brackets (e.g.,
7074: @code{[']}, @pxref{Execution token}).
1.44 crook 7075:
1.26 crook 7076: Note that ticking (@code{'}) a compile-only word gives an error
7077: (``Interpreting a compile-only word'').
1.1 anton 7078:
1.47 crook 7079: @menu
1.67 anton 7080: * Combined words::
1.47 crook 7081: @end menu
1.44 crook 7082:
1.71 anton 7083:
1.48 anton 7084: @node Combined words, , Interpretation and Compilation Semantics, Interpretation and Compilation Semantics
1.44 crook 7085: @subsection Combined Words
7086: @cindex combined words
7087:
7088: Gforth allows you to define @dfn{combined words} -- words that have an
7089: arbitrary combination of interpretation and compilation semantics.
7090:
1.26 crook 7091: doc-interpret/compile:
1.1 anton 7092:
1.26 crook 7093: This feature was introduced for implementing @code{TO} and @code{S"}. I
7094: recommend that you do not define such words, as cute as they may be:
7095: they make it hard to get at both parts of the word in some contexts.
7096: E.g., assume you want to get an execution token for the compilation
7097: part. Instead, define two words, one that embodies the interpretation
7098: part, and one that embodies the compilation part. Once you have done
7099: that, you can define a combined word with @code{interpret/compile:} for
7100: the convenience of your users.
1.1 anton 7101:
1.26 crook 7102: You might try to use this feature to provide an optimizing
7103: implementation of the default compilation semantics of a word. For
7104: example, by defining:
1.1 anton 7105: @example
1.26 crook 7106: :noname
7107: foo bar ;
7108: :noname
7109: POSTPONE foo POSTPONE bar ;
1.29 crook 7110: interpret/compile: opti-foobar
1.1 anton 7111: @end example
1.26 crook 7112:
1.23 crook 7113: @noindent
1.26 crook 7114: as an optimizing version of:
7115:
1.1 anton 7116: @example
1.26 crook 7117: : foobar
7118: foo bar ;
1.1 anton 7119: @end example
7120:
1.26 crook 7121: Unfortunately, this does not work correctly with @code{[compile]},
7122: because @code{[compile]} assumes that the compilation semantics of all
7123: @code{interpret/compile:} words are non-default. I.e., @code{[compile]
1.29 crook 7124: opti-foobar} would compile compilation semantics, whereas
7125: @code{[compile] foobar} would compile interpretation semantics.
1.1 anton 7126:
1.26 crook 7127: @cindex state-smart words (are a bad idea)
1.82 anton 7128: @anchor{state-smartness}
1.29 crook 7129: Some people try to use @dfn{state-smart} words to emulate the feature provided
1.26 crook 7130: by @code{interpret/compile:} (words are state-smart if they check
7131: @code{STATE} during execution). E.g., they would try to code
7132: @code{foobar} like this:
1.1 anton 7133:
1.26 crook 7134: @example
7135: : foobar
7136: STATE @@
7137: IF ( compilation state )
7138: POSTPONE foo POSTPONE bar
7139: ELSE
7140: foo bar
7141: ENDIF ; immediate
7142: @end example
1.1 anton 7143:
1.26 crook 7144: Although this works if @code{foobar} is only processed by the text
7145: interpreter, it does not work in other contexts (like @code{'} or
7146: @code{POSTPONE}). E.g., @code{' foobar} will produce an execution token
7147: for a state-smart word, not for the interpretation semantics of the
7148: original @code{foobar}; when you execute this execution token (directly
7149: with @code{EXECUTE} or indirectly through @code{COMPILE,}) in compile
7150: state, the result will not be what you expected (i.e., it will not
7151: perform @code{foo bar}). State-smart words are a bad idea. Simply don't
7152: write them@footnote{For a more detailed discussion of this topic, see
1.66 anton 7153: M. Anton Ertl,
7154: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,@code{State}-smartness---Why
7155: it is Evil and How to Exorcise it}}, EuroForth '98.}!
1.1 anton 7156:
1.26 crook 7157: @cindex defining words with arbitrary semantics combinations
7158: It is also possible to write defining words that define words with
7159: arbitrary combinations of interpretation and compilation semantics. In
7160: general, they look like this:
1.1 anton 7161:
1.26 crook 7162: @example
7163: : def-word
7164: create-interpret/compile
1.29 crook 7165: @i{code1}
1.26 crook 7166: interpretation>
1.29 crook 7167: @i{code2}
1.26 crook 7168: <interpretation
7169: compilation>
1.29 crook 7170: @i{code3}
1.26 crook 7171: <compilation ;
7172: @end example
1.1 anton 7173:
1.29 crook 7174: For a @i{word} defined with @code{def-word}, the interpretation
7175: semantics are to push the address of the body of @i{word} and perform
7176: @i{code2}, and the compilation semantics are to push the address of
7177: the body of @i{word} and perform @i{code3}. E.g., @code{constant}
1.26 crook 7178: can also be defined like this (except that the defined constants don't
7179: behave correctly when @code{[compile]}d):
1.1 anton 7180:
1.26 crook 7181: @example
7182: : constant ( n "name" -- )
7183: create-interpret/compile
7184: ,
7185: interpretation> ( -- n )
7186: @@
7187: <interpretation
7188: compilation> ( compilation. -- ; run-time. -- n )
7189: @@ postpone literal
7190: <compilation ;
7191: @end example
1.1 anton 7192:
1.44 crook 7193:
1.26 crook 7194: doc-create-interpret/compile
7195: doc-interpretation>
7196: doc-<interpretation
7197: doc-compilation>
7198: doc-<compilation
1.1 anton 7199:
1.44 crook 7200:
1.29 crook 7201: Words defined with @code{interpret/compile:} and
1.26 crook 7202: @code{create-interpret/compile} have an extended header structure that
7203: differs from other words; however, unless you try to access them with
7204: plain address arithmetic, you should not notice this. Words for
7205: accessing the header structure usually know how to deal with this; e.g.,
1.29 crook 7206: @code{'} @i{word} @code{>body} also gives you the body of a word created
7207: with @code{create-interpret/compile}.
1.1 anton 7208:
1.44 crook 7209:
1.47 crook 7210: @c -------------------------------------------------------------
1.81 anton 7211: @node Tokens for Words, Compiling words, Interpretation and Compilation Semantics, Words
1.47 crook 7212: @section Tokens for Words
7213: @cindex tokens for words
7214:
7215: This section describes the creation and use of tokens that represent
7216: words.
7217:
1.71 anton 7218: @menu
7219: * Execution token:: represents execution/interpretation semantics
7220: * Compilation token:: represents compilation semantics
7221: * Name token:: represents named words
7222: @end menu
1.47 crook 7223:
1.71 anton 7224: @node Execution token, Compilation token, Tokens for Words, Tokens for Words
7225: @subsection Execution token
1.47 crook 7226:
7227: @cindex xt
7228: @cindex execution token
1.71 anton 7229: An @dfn{execution token} (@i{XT}) represents some behaviour of a word.
7230: You can use @code{execute} to invoke this behaviour.
1.47 crook 7231:
1.71 anton 7232: @cindex tick (')
7233: You can use @code{'} to get an execution token that represents the
7234: interpretation semantics of a named word:
1.47 crook 7235:
7236: @example
1.97 anton 7237: 5 ' . ( n xt )
7238: execute ( ) \ execute the xt (i.e., ".")
1.71 anton 7239: @end example
1.47 crook 7240:
1.71 anton 7241: doc-'
7242:
7243: @code{'} parses at run-time; there is also a word @code{[']} that parses
7244: when it is compiled, and compiles the resulting XT:
7245:
7246: @example
7247: : foo ['] . execute ;
7248: 5 foo
7249: : bar ' execute ; \ by contrast,
7250: 5 bar . \ ' parses "." when bar executes
7251: @end example
7252:
7253: doc-[']
7254:
7255: If you want the execution token of @i{word}, write @code{['] @i{word}}
7256: in compiled code and @code{' @i{word}} in interpreted code. Gforth's
7257: @code{'} and @code{[']} behave somewhat unusually by complaining about
7258: compile-only words (because these words have no interpretation
7259: semantics). You might get what you want by using @code{COMP' @i{word}
7260: DROP} or @code{[COMP'] @i{word} DROP} (for details @pxref{Compilation
7261: token}).
7262:
7263: Another way to get an XT is @code{:noname} or @code{lastxt}
7264: (@pxref{Anonymous Definitions}). For anonymous words this gives an xt
7265: for the only behaviour the word has (the execution semantics). For
7266: named words, @code{lastxt} produces an XT for the same behaviour it
7267: would produce if the word was defined anonymously.
7268:
7269: @example
7270: :noname ." hello" ;
7271: execute
1.47 crook 7272: @end example
7273:
1.71 anton 7274: An XT occupies one cell and can be manipulated like any other cell.
7275:
1.47 crook 7276: @cindex code field address
7277: @cindex CFA
1.71 anton 7278: In ANS Forth the XT is just an abstract data type (i.e., defined by the
7279: operations that produce or consume it). For old hands: In Gforth, the
7280: XT is implemented as a code field address (CFA).
7281:
7282: doc-execute
7283: doc-perform
7284:
7285: @node Compilation token, Name token, Execution token, Tokens for Words
7286: @subsection Compilation token
1.47 crook 7287:
7288: @cindex compilation token
1.71 anton 7289: @cindex CT (compilation token)
7290: Gforth represents the compilation semantics of a named word by a
1.47 crook 7291: @dfn{compilation token} consisting of two cells: @i{w xt}. The top cell
7292: @i{xt} is an execution token. The compilation semantics represented by
7293: the compilation token can be performed with @code{execute}, which
7294: consumes the whole compilation token, with an additional stack effect
7295: determined by the represented compilation semantics.
7296:
7297: At present, the @i{w} part of a compilation token is an execution token,
7298: and the @i{xt} part represents either @code{execute} or
7299: @code{compile,}@footnote{Depending upon the compilation semantics of the
7300: word. If the word has default compilation semantics, the @i{xt} will
7301: represent @code{compile,}. Otherwise (e.g., for immediate words), the
7302: @i{xt} will represent @code{execute}.}. However, don't rely on that
7303: knowledge, unless necessary; future versions of Gforth may introduce
7304: unusual compilation tokens (e.g., a compilation token that represents
7305: the compilation semantics of a literal).
7306:
1.71 anton 7307: You can perform the compilation semantics represented by the compilation
7308: token with @code{execute}. You can compile the compilation semantics
7309: with @code{postpone,}. I.e., @code{COMP' @i{word} postpone,} is
7310: equivalent to @code{postpone @i{word}}.
7311:
7312: doc-[comp']
7313: doc-comp'
7314: doc-postpone,
7315:
7316: @node Name token, , Compilation token, Tokens for Words
7317: @subsection Name token
1.47 crook 7318:
7319: @cindex name token
7320: @cindex name field address
7321: @cindex NFA
1.71 anton 7322: Gforth represents named words by the @dfn{name token}, (@i{nt}). In
1.47 crook 7323: Gforth, the abstract data type @emph{name token} is implemented as a
7324: name field address (NFA).
7325:
7326: doc-find-name
7327: doc-name>int
7328: doc-name?int
7329: doc-name>comp
7330: doc-name>string
1.109 anton 7331: doc-id.
7332: doc-.name
7333: doc-.id
1.47 crook 7334:
1.81 anton 7335: @c ----------------------------------------------------------
7336: @node Compiling words, The Text Interpreter, Tokens for Words, Words
7337: @section Compiling words
7338: @cindex compiling words
7339: @cindex macros
7340:
7341: In contrast to most other languages, Forth has no strict boundary
1.82 anton 7342: between compilation and run-time. E.g., you can run arbitrary code
7343: between defining words (or for computing data used by defining words
7344: like @code{constant}). Moreover, @code{Immediate} (@pxref{Interpretation
7345: and Compilation Semantics} and @code{[}...@code{]} (see below) allow
7346: running arbitrary code while compiling a colon definition (exception:
7347: you must not allot dictionary space).
7348:
7349: @menu
7350: * Literals:: Compiling data values
7351: * Macros:: Compiling words
7352: @end menu
7353:
7354: @node Literals, Macros, Compiling words, Compiling words
7355: @subsection Literals
7356: @cindex Literals
7357:
7358: The simplest and most frequent example is to compute a literal during
7359: compilation. E.g., the following definition prints an array of strings,
7360: one string per line:
7361:
7362: @example
7363: : .strings ( addr u -- ) \ gforth
7364: 2* cells bounds U+DO
7365: cr i 2@@ type
7366: 2 cells +LOOP ;
7367: @end example
1.81 anton 7368:
1.82 anton 7369: With a simple-minded compiler like Gforth's, this computes @code{2
7370: cells} on every loop iteration. You can compute this value once and for
7371: all at compile time and compile it into the definition like this:
7372:
7373: @example
7374: : .strings ( addr u -- ) \ gforth
7375: 2* cells bounds U+DO
7376: cr i 2@@ type
7377: [ 2 cells ] literal +LOOP ;
7378: @end example
7379:
7380: @code{[} switches the text interpreter to interpret state (you will get
7381: an @code{ok} prompt if you type this example interactively and insert a
7382: newline between @code{[} and @code{]}), so it performs the
7383: interpretation semantics of @code{2 cells}; this computes a number.
7384: @code{]} switches the text interpreter back into compile state. It then
7385: performs @code{Literal}'s compilation semantics, which are to compile
7386: this number into the current word. You can decompile the word with
7387: @code{see .strings} to see the effect on the compiled code.
1.81 anton 7388:
1.82 anton 7389: You can also optimize the @code{2* cells} into @code{[ 2 cells ] literal
7390: *} in this way.
1.81 anton 7391:
1.82 anton 7392: doc-[
7393: doc-]
1.81 anton 7394: doc-literal
7395: doc-]L
1.82 anton 7396:
7397: There are also words for compiling other data types than single cells as
7398: literals:
7399:
1.81 anton 7400: doc-2literal
7401: doc-fliteral
1.82 anton 7402: doc-sliteral
7403:
7404: @cindex colon-sys, passing data across @code{:}
7405: @cindex @code{:}, passing data across
7406: You might be tempted to pass data from outside a colon definition to the
7407: inside on the data stack. This does not work, because @code{:} puhes a
7408: colon-sys, making stuff below unaccessible. E.g., this does not work:
7409:
7410: @example
7411: 5 : foo literal ; \ error: "unstructured"
7412: @end example
7413:
7414: Instead, you have to pass the value in some other way, e.g., through a
7415: variable:
7416:
7417: @example
7418: variable temp
7419: 5 temp !
7420: : foo [ temp @@ ] literal ;
7421: @end example
7422:
7423:
7424: @node Macros, , Literals, Compiling words
7425: @subsection Macros
7426: @cindex Macros
7427: @cindex compiling compilation semantics
7428:
7429: @code{Literal} and friends compile data values into the current
7430: definition. You can also write words that compile other words into the
7431: current definition. E.g.,
7432:
7433: @example
7434: : compile-+ ( -- ) \ compiled code: ( n1 n2 -- n )
7435: POSTPONE + ;
7436:
7437: : foo ( n1 n2 -- n )
7438: [ compile-+ ] ;
7439: 1 2 foo .
7440: @end example
7441:
7442: This is equivalent to @code{: foo + ;} (@code{see foo} to check this).
7443: What happens in this example? @code{Postpone} compiles the compilation
7444: semantics of @code{+} into @code{compile-+}; later the text interpreter
7445: executes @code{compile-+} and thus the compilation semantics of +, which
7446: compile (the execution semantics of) @code{+} into
7447: @code{foo}.@footnote{A recent RFI answer requires that compiling words
7448: should only be executed in compile state, so this example is not
7449: guaranteed to work on all standard systems, but on any decent system it
7450: will work.}
7451:
7452: doc-postpone
7453: doc-[compile]
7454:
7455: Compiling words like @code{compile-+} are usually immediate (or similar)
7456: so you do not have to switch to interpret state to execute them;
7457: mopifying the last example accordingly produces:
7458:
7459: @example
7460: : [compile-+] ( compilation: --; interpretation: -- )
7461: \ compiled code: ( n1 n2 -- n )
7462: POSTPONE + ; immediate
7463:
7464: : foo ( n1 n2 -- n )
7465: [compile-+] ;
7466: 1 2 foo .
7467: @end example
7468:
7469: Immediate compiling words are similar to macros in other languages (in
7470: particular, Lisp). The important differences to macros in, e.g., C are:
7471:
7472: @itemize @bullet
7473:
7474: @item
7475: You use the same language for defining and processing macros, not a
7476: separate preprocessing language and processor.
7477:
7478: @item
7479: Consequently, the full power of Forth is available in macro definitions.
7480: E.g., you can perform arbitrarily complex computations, or generate
7481: different code conditionally or in a loop (e.g., @pxref{Advanced macros
7482: Tutorial}). This power is very useful when writing a parser generators
7483: or other code-generating software.
7484:
7485: @item
7486: Macros defined using @code{postpone} etc. deal with the language at a
7487: higher level than strings; name binding happens at macro definition
7488: time, so you can avoid the pitfalls of name collisions that can happen
7489: in C macros. Of course, Forth is a liberal language and also allows to
7490: shoot yourself in the foot with text-interpreted macros like
7491:
7492: @example
7493: : [compile-+] s" +" evaluate ; immediate
7494: @end example
7495:
7496: Apart from binding the name at macro use time, using @code{evaluate}
7497: also makes your definition @code{state}-smart (@pxref{state-smartness}).
7498: @end itemize
7499:
7500: You may want the macro to compile a number into a word. The word to do
7501: it is @code{literal}, but you have to @code{postpone} it, so its
7502: compilation semantics take effect when the macro is executed, not when
7503: it is compiled:
7504:
7505: @example
7506: : [compile-5] ( -- ) \ compiled code: ( -- n )
7507: 5 POSTPONE literal ; immediate
7508:
7509: : foo [compile-5] ;
7510: foo .
7511: @end example
7512:
7513: You may want to pass parameters to a macro, that the macro should
7514: compile into the current definition. If the parameter is a number, then
7515: you can use @code{postpone literal} (similar for other values).
7516:
7517: If you want to pass a word that is to be compiled, the usual way is to
7518: pass an execution token and @code{compile,} it:
7519:
7520: @example
7521: : twice1 ( xt -- ) \ compiled code: ... -- ...
7522: dup compile, compile, ;
7523:
7524: : 2+ ( n1 -- n2 )
7525: [ ' 1+ twice1 ] ;
7526: @end example
7527:
7528: doc-compile,
7529:
7530: An alternative available in Gforth, that allows you to pass compile-only
7531: words as parameters is to use the compilation token (@pxref{Compilation
7532: token}). The same example in this technique:
7533:
7534: @example
7535: : twice ( ... ct -- ... ) \ compiled code: ... -- ...
7536: 2dup 2>r execute 2r> execute ;
7537:
7538: : 2+ ( n1 -- n2 )
7539: [ comp' 1+ twice ] ;
7540: @end example
7541:
7542: In the example above @code{2>r} and @code{2r>} ensure that @code{twice}
7543: works even if the executed compilation semantics has an effect on the
7544: data stack.
7545:
7546: You can also define complete definitions with these words; this provides
7547: an alternative to using @code{does>} (@pxref{User-defined Defining
7548: Words}). E.g., instead of
7549:
7550: @example
7551: : curry+ ( n1 "name" -- )
7552: CREATE ,
7553: DOES> ( n2 -- n1+n2 )
7554: @@ + ;
7555: @end example
7556:
7557: you could define
7558:
7559: @example
7560: : curry+ ( n1 "name" -- )
7561: \ name execution: ( n2 -- n1+n2 )
7562: >r : r> POSTPONE literal POSTPONE + POSTPONE ; ;
1.81 anton 7563:
1.82 anton 7564: -3 curry+ 3-
7565: see 3-
7566: @end example
1.81 anton 7567:
1.82 anton 7568: The sequence @code{>r : r>} is necessary, because @code{:} puts a
7569: colon-sys on the data stack that makes everything below it unaccessible.
1.81 anton 7570:
1.82 anton 7571: This way of writing defining words is sometimes more, sometimes less
7572: convenient than using @code{does>} (@pxref{Advanced does> usage
7573: example}). One advantage of this method is that it can be optimized
7574: better, because the compiler knows that the value compiled with
7575: @code{literal} is fixed, whereas the data associated with a
7576: @code{create}d word can be changed.
1.47 crook 7577:
1.26 crook 7578: @c ----------------------------------------------------------
1.111 ! anton 7579: @node The Text Interpreter, The Input Stream, Compiling words, Words
1.26 crook 7580: @section The Text Interpreter
7581: @cindex interpreter - outer
7582: @cindex text interpreter
7583: @cindex outer interpreter
1.1 anton 7584:
1.34 anton 7585: @c Should we really describe all these ugly details? IMO the text
7586: @c interpreter should be much cleaner, but that may not be possible within
7587: @c ANS Forth. - anton
1.44 crook 7588: @c nac-> I wanted to explain how it works to show how you can exploit
7589: @c it in your own programs. When I was writing a cross-compiler, figuring out
7590: @c some of these gory details was very helpful to me. None of the textbooks
7591: @c I've seen cover it, and the most modern Forth textbook -- Forth Inc's,
7592: @c seems to positively avoid going into too much detail for some of
7593: @c the internals.
1.34 anton 7594:
1.71 anton 7595: @c anton: ok. I wonder, though, if this is the right place; for some stuff
7596: @c it is; for the ugly details, I would prefer another place. I wonder
7597: @c whether we should have a chapter before "Words" that describes some
7598: @c basic concepts referred to in words, and a chapter after "Words" that
7599: @c describes implementation details.
7600:
1.29 crook 7601: The text interpreter@footnote{This is an expanded version of the
7602: material in @ref{Introducing the Text Interpreter}.} is an endless loop
1.34 anton 7603: that processes input from the current input device. It is also called
7604: the outer interpreter, in contrast to the inner interpreter
7605: (@pxref{Engine}) which executes the compiled Forth code on interpretive
7606: implementations.
1.27 crook 7607:
1.29 crook 7608: @cindex interpret state
7609: @cindex compile state
7610: The text interpreter operates in one of two states: @dfn{interpret
7611: state} and @dfn{compile state}. The current state is defined by the
1.71 anton 7612: aptly-named variable @code{state}.
1.29 crook 7613:
7614: This section starts by describing how the text interpreter behaves when
7615: it is in interpret state, processing input from the user input device --
7616: the keyboard. This is the mode that a Forth system is in after it starts
7617: up.
7618:
7619: @cindex input buffer
7620: @cindex terminal input buffer
7621: The text interpreter works from an area of memory called the @dfn{input
7622: buffer}@footnote{When the text interpreter is processing input from the
7623: keyboard, this area of memory is called the @dfn{terminal input buffer}
7624: (TIB) and is addressed by the (obsolescent) words @code{TIB} and
7625: @code{#TIB}.}, which stores your keyboard input when you press the
1.30 anton 7626: @key{RET} key. Starting at the beginning of the input buffer, it skips
1.29 crook 7627: leading spaces (called @dfn{delimiters}) then parses a string (a
7628: sequence of non-space characters) until it reaches either a space
7629: character or the end of the buffer. Having parsed a string, it makes two
7630: attempts to process it:
1.27 crook 7631:
1.29 crook 7632: @cindex dictionary
1.27 crook 7633: @itemize @bullet
7634: @item
1.29 crook 7635: It looks for the string in a @dfn{dictionary} of definitions. If the
7636: string is found, the string names a @dfn{definition} (also known as a
7637: @dfn{word}) and the dictionary search returns information that allows
7638: the text interpreter to perform the word's @dfn{interpretation
7639: semantics}. In most cases, this simply means that the word will be
7640: executed.
1.27 crook 7641: @item
7642: If the string is not found in the dictionary, the text interpreter
1.29 crook 7643: attempts to treat it as a number, using the rules described in
7644: @ref{Number Conversion}. If the string represents a legal number in the
7645: current radix, the number is pushed onto a parameter stack (the data
7646: stack for integers, the floating-point stack for floating-point
7647: numbers).
7648: @end itemize
7649:
7650: If both attempts fail, or if the word is found in the dictionary but has
7651: no interpretation semantics@footnote{This happens if the word was
7652: defined as @code{COMPILE-ONLY}.} the text interpreter discards the
7653: remainder of the input buffer, issues an error message and waits for
7654: more input. If one of the attempts succeeds, the text interpreter
7655: repeats the parsing process until the whole of the input buffer has been
7656: processed, at which point it prints the status message ``@code{ ok}''
7657: and waits for more input.
7658:
1.71 anton 7659: @c anton: this should be in the input stream subsection (or below it)
7660:
1.29 crook 7661: @cindex parse area
7662: The text interpreter keeps track of its position in the input buffer by
7663: updating a variable called @code{>IN} (pronounced ``to-in''). The value
7664: of @code{>IN} starts out as 0, indicating an offset of 0 from the start
7665: of the input buffer. The region from offset @code{>IN @@} to the end of
7666: the input buffer is called the @dfn{parse area}@footnote{In other words,
7667: the text interpreter processes the contents of the input buffer by
7668: parsing strings from the parse area until the parse area is empty.}.
7669: This example shows how @code{>IN} changes as the text interpreter parses
7670: the input buffer:
7671:
7672: @example
7673: : remaining >IN @@ SOURCE 2 PICK - -ROT + SWAP
7674: CR ." ->" TYPE ." <-" ; IMMEDIATE
7675:
7676: 1 2 3 remaining + remaining .
7677:
7678: : foo 1 2 3 remaining SWAP remaining ;
7679: @end example
7680:
7681: @noindent
7682: The result is:
7683:
7684: @example
7685: ->+ remaining .<-
7686: ->.<-5 ok
7687:
7688: ->SWAP remaining ;-<
7689: ->;<- ok
7690: @end example
7691:
7692: @cindex parsing words
7693: The value of @code{>IN} can also be modified by a word in the input
7694: buffer that is executed by the text interpreter. This means that a word
7695: can ``trick'' the text interpreter into either skipping a section of the
7696: input buffer@footnote{This is how parsing words work.} or into parsing a
7697: section twice. For example:
1.27 crook 7698:
1.29 crook 7699: @example
1.71 anton 7700: : lat ." <<foo>>" ;
7701: : flat ." <<bar>>" >IN DUP @@ 3 - SWAP ! ;
1.29 crook 7702: @end example
7703:
7704: @noindent
7705: When @code{flat} is executed, this output is produced@footnote{Exercise
7706: for the reader: what would happen if the @code{3} were replaced with
7707: @code{4}?}:
7708:
7709: @example
1.71 anton 7710: <<bar>><<foo>>
1.29 crook 7711: @end example
7712:
1.71 anton 7713: This technique can be used to work around some of the interoperability
7714: problems of parsing words. Of course, it's better to avoid parsing
7715: words where possible.
7716:
1.29 crook 7717: @noindent
7718: Two important notes about the behaviour of the text interpreter:
1.27 crook 7719:
7720: @itemize @bullet
7721: @item
7722: It processes each input string to completion before parsing additional
1.29 crook 7723: characters from the input buffer.
7724: @item
7725: It treats the input buffer as a read-only region (and so must your code).
7726: @end itemize
7727:
7728: @noindent
7729: When the text interpreter is in compile state, its behaviour changes in
7730: these ways:
7731:
7732: @itemize @bullet
7733: @item
7734: If a parsed string is found in the dictionary, the text interpreter will
7735: perform the word's @dfn{compilation semantics}. In most cases, this
7736: simply means that the execution semantics of the word will be appended
7737: to the current definition.
1.27 crook 7738: @item
1.29 crook 7739: When a number is encountered, it is compiled into the current definition
7740: (as a literal) rather than being pushed onto a parameter stack.
7741: @item
7742: If an error occurs, @code{state} is modified to put the text interpreter
7743: back into interpret state.
7744: @item
7745: Each time a line is entered from the keyboard, Gforth prints
7746: ``@code{ compiled}'' rather than `` @code{ok}''.
7747: @end itemize
7748:
7749: @cindex text interpreter - input sources
7750: When the text interpreter is using an input device other than the
7751: keyboard, its behaviour changes in these ways:
7752:
7753: @itemize @bullet
7754: @item
7755: When the parse area is empty, the text interpreter attempts to refill
7756: the input buffer from the input source. When the input source is
1.71 anton 7757: exhausted, the input source is set back to the previous input source.
1.29 crook 7758: @item
7759: It doesn't print out ``@code{ ok}'' or ``@code{ compiled}'' messages each
7760: time the parse area is emptied.
7761: @item
7762: If an error occurs, the input source is set back to the user input
7763: device.
1.27 crook 7764: @end itemize
1.21 crook 7765:
1.49 anton 7766: You can read about this in more detail in @ref{Input Sources}.
1.44 crook 7767:
1.26 crook 7768: doc->in
1.27 crook 7769: doc-source
7770:
1.26 crook 7771: doc-tib
7772: doc-#tib
1.1 anton 7773:
1.44 crook 7774:
1.26 crook 7775: @menu
1.67 anton 7776: * Input Sources::
7777: * Number Conversion::
7778: * Interpret/Compile states::
7779: * Interpreter Directives::
1.26 crook 7780: @end menu
1.1 anton 7781:
1.29 crook 7782: @node Input Sources, Number Conversion, The Text Interpreter, The Text Interpreter
7783: @subsection Input Sources
7784: @cindex input sources
7785: @cindex text interpreter - input sources
7786:
1.44 crook 7787: By default, the text interpreter processes input from the user input
1.29 crook 7788: device (the keyboard) when Forth starts up. The text interpreter can
7789: process input from any of these sources:
7790:
7791: @itemize @bullet
7792: @item
7793: The user input device -- the keyboard.
7794: @item
7795: A file, using the words described in @ref{Forth source files}.
7796: @item
7797: A block, using the words described in @ref{Blocks}.
7798: @item
7799: A text string, using @code{evaluate}.
7800: @end itemize
7801:
7802: A program can identify the current input device from the values of
7803: @code{source-id} and @code{blk}.
7804:
1.44 crook 7805:
1.29 crook 7806: doc-source-id
7807: doc-blk
7808:
7809: doc-save-input
7810: doc-restore-input
7811:
7812: doc-evaluate
1.111 ! anton 7813: doc-query
1.1 anton 7814:
1.29 crook 7815:
1.44 crook 7816:
1.29 crook 7817: @node Number Conversion, Interpret/Compile states, Input Sources, The Text Interpreter
1.26 crook 7818: @subsection Number Conversion
7819: @cindex number conversion
7820: @cindex double-cell numbers, input format
7821: @cindex input format for double-cell numbers
7822: @cindex single-cell numbers, input format
7823: @cindex input format for single-cell numbers
7824: @cindex floating-point numbers, input format
7825: @cindex input format for floating-point numbers
1.1 anton 7826:
1.29 crook 7827: This section describes the rules that the text interpreter uses when it
7828: tries to convert a string into a number.
1.1 anton 7829:
1.26 crook 7830: Let <digit> represent any character that is a legal digit in the current
1.29 crook 7831: number base@footnote{For example, 0-9 when the number base is decimal or
7832: 0-9, A-F when the number base is hexadecimal.}.
1.1 anton 7833:
1.26 crook 7834: Let <decimal digit> represent any character in the range 0-9.
1.1 anton 7835:
1.29 crook 7836: Let @{@i{a b}@} represent the @i{optional} presence of any of the characters
7837: in the braces (@i{a} or @i{b} or neither).
1.1 anton 7838:
1.26 crook 7839: Let * represent any number of instances of the previous character
7840: (including none).
1.1 anton 7841:
1.26 crook 7842: Let any other character represent itself.
1.1 anton 7843:
1.29 crook 7844: @noindent
1.26 crook 7845: Now, the conversion rules are:
1.21 crook 7846:
1.26 crook 7847: @itemize @bullet
7848: @item
7849: A string of the form <digit><digit>* is treated as a single-precision
1.29 crook 7850: (cell-sized) positive integer. Examples are 0 123 6784532 32343212343456 42
1.26 crook 7851: @item
7852: A string of the form -<digit><digit>* is treated as a single-precision
1.29 crook 7853: (cell-sized) negative integer, and is represented using 2's-complement
1.26 crook 7854: arithmetic. Examples are -45 -5681 -0
7855: @item
7856: A string of the form <digit><digit>*.<digit>* is treated as a double-precision
1.29 crook 7857: (double-cell-sized) positive integer. Examples are 3465. 3.465 34.65
7858: (all three of these represent the same number).
1.26 crook 7859: @item
7860: A string of the form -<digit><digit>*.<digit>* is treated as a
1.29 crook 7861: double-precision (double-cell-sized) negative integer, and is
1.26 crook 7862: represented using 2's-complement arithmetic. Examples are -3465. -3.465
1.29 crook 7863: -34.65 (all three of these represent the same number).
1.26 crook 7864: @item
1.29 crook 7865: A string of the form @{+ -@}<decimal digit>@{.@}<decimal digit>*@{e
7866: E@}@{+ -@}<decimal digit><decimal digit>* is treated as a floating-point
1.35 anton 7867: number. Examples are 1e 1e0 1.e 1.e0 +1e+0 (which all represent the same
1.29 crook 7868: number) +12.E-4
1.26 crook 7869: @end itemize
1.1 anton 7870:
1.26 crook 7871: By default, the number base used for integer number conversion is given
1.35 anton 7872: by the contents of the variable @code{base}. Note that a lot of
7873: confusion can result from unexpected values of @code{base}. If you
7874: change @code{base} anywhere, make sure to save the old value and restore
7875: it afterwards. In general I recommend keeping @code{base} decimal, and
7876: using the prefixes described below for the popular non-decimal bases.
1.1 anton 7877:
1.29 crook 7878: doc-dpl
1.26 crook 7879: doc-base
7880: doc-hex
7881: doc-decimal
1.1 anton 7882:
1.44 crook 7883:
1.26 crook 7884: @cindex '-prefix for character strings
7885: @cindex &-prefix for decimal numbers
7886: @cindex %-prefix for binary numbers
7887: @cindex $-prefix for hexadecimal numbers
1.35 anton 7888: Gforth allows you to override the value of @code{base} by using a
1.29 crook 7889: prefix@footnote{Some Forth implementations provide a similar scheme by
7890: implementing @code{$} etc. as parsing words that process the subsequent
7891: number in the input stream and push it onto the stack. For example, see
7892: @cite{Number Conversion and Literals}, by Wil Baden; Forth Dimensions
7893: 20(3) pages 26--27. In such implementations, unlike in Gforth, a space
7894: is required between the prefix and the number.} before the first digit
7895: of an (integer) number. Four prefixes are supported:
1.1 anton 7896:
1.26 crook 7897: @itemize @bullet
7898: @item
1.35 anton 7899: @code{&} -- decimal
1.26 crook 7900: @item
1.35 anton 7901: @code{%} -- binary
1.26 crook 7902: @item
1.35 anton 7903: @code{$} -- hexadecimal
1.26 crook 7904: @item
1.35 anton 7905: @code{'} -- base @code{max-char+1}
1.26 crook 7906: @end itemize
1.1 anton 7907:
1.26 crook 7908: Here are some examples, with the equivalent decimal number shown after
7909: in braces:
1.1 anton 7910:
1.26 crook 7911: -$41 (-65), %1001101 (205), %1001.0001 (145 - a double-precision number),
7912: 'AB (16706; ascii A is 65, ascii B is 66, number is 65*256 + 66),
7913: 'ab (24930; ascii a is 97, ascii B is 98, number is 97*256 + 98),
7914: &905 (905), $abc (2478), $ABC (2478).
1.1 anton 7915:
1.26 crook 7916: @cindex number conversion - traps for the unwary
1.29 crook 7917: @noindent
1.26 crook 7918: Number conversion has a number of traps for the unwary:
1.1 anton 7919:
1.26 crook 7920: @itemize @bullet
7921: @item
7922: You cannot determine the current number base using the code sequence
1.35 anton 7923: @code{base @@ .} -- the number base is always 10 in the current number
7924: base. Instead, use something like @code{base @@ dec.}
1.26 crook 7925: @item
7926: If the number base is set to a value greater than 14 (for example,
7927: hexadecimal), the number 123E4 is ambiguous; the conversion rules allow
7928: it to be intepreted as either a single-precision integer or a
7929: floating-point number (Gforth treats it as an integer). The ambiguity
7930: can be resolved by explicitly stating the sign of the mantissa and/or
7931: exponent: 123E+4 or +123E4 -- if the number base is decimal, no
7932: ambiguity arises; either representation will be treated as a
7933: floating-point number.
7934: @item
1.29 crook 7935: There is a word @code{bin} but it does @i{not} set the number base!
1.26 crook 7936: It is used to specify file types.
7937: @item
1.72 anton 7938: ANS Forth requires the @code{.} of a double-precision number to be the
7939: final character in the string. Gforth allows the @code{.} to be
7940: anywhere after the first digit.
1.26 crook 7941: @item
7942: The number conversion process does not check for overflow.
7943: @item
1.72 anton 7944: In an ANS Forth program @code{base} is required to be decimal when
7945: converting floating-point numbers. In Gforth, number conversion to
7946: floating-point numbers always uses base &10, irrespective of the value
7947: of @code{base}.
1.26 crook 7948: @end itemize
1.1 anton 7949:
1.49 anton 7950: You can read numbers into your programs with the words described in
7951: @ref{Input}.
1.1 anton 7952:
1.82 anton 7953: @node Interpret/Compile states, Interpreter Directives, Number Conversion, The Text Interpreter
1.26 crook 7954: @subsection Interpret/Compile states
7955: @cindex Interpret/Compile states
1.1 anton 7956:
1.29 crook 7957: A standard program is not permitted to change @code{state}
7958: explicitly. However, it can change @code{state} implicitly, using the
7959: words @code{[} and @code{]}. When @code{[} is executed it switches
7960: @code{state} to interpret state, and therefore the text interpreter
7961: starts interpreting. When @code{]} is executed it switches @code{state}
7962: to compile state and therefore the text interpreter starts
1.44 crook 7963: compiling. The most common usage for these words is for switching into
7964: interpret state and back from within a colon definition; this technique
1.49 anton 7965: can be used to compile a literal (for an example, @pxref{Literals}) or
7966: for conditional compilation (for an example, @pxref{Interpreter
7967: Directives}).
1.44 crook 7968:
1.35 anton 7969:
7970: @c This is a bad example: It's non-standard, and it's not necessary.
7971: @c However, I can't think of a good example for switching into compile
7972: @c state when there is no current word (@code{state}-smart words are not a
7973: @c good reason). So maybe we should use an example for switching into
7974: @c interpret @code{state} in a colon def. - anton
1.44 crook 7975: @c nac-> I agree. I started out by putting in the example, then realised
7976: @c that it was non-ANS, so wrote more words around it. I hope this
7977: @c re-written version is acceptable to you. I do want to keep the example
7978: @c as it is helpful for showing what is and what is not portable, particularly
7979: @c where it outlaws a style in common use.
7980:
1.72 anton 7981: @c anton: it's more important to show what's portable. After we have done
1.83 anton 7982: @c that, we can also show what's not. In any case, I have written a
7983: @c section Compiling Words which also deals with [ ].
1.35 anton 7984:
1.95 anton 7985: @c !! The following example does not work in Gforth 0.5.9 or later.
1.29 crook 7986:
1.95 anton 7987: @c @code{[} and @code{]} also give you the ability to switch into compile
7988: @c state and back, but we cannot think of any useful Standard application
7989: @c for this ability. Pre-ANS Forth textbooks have examples like this:
7990:
7991: @c @example
7992: @c : AA ." this is A" ;
7993: @c : BB ." this is B" ;
7994: @c : CC ." this is C" ;
7995:
7996: @c create table ] aa bb cc [
7997:
7998: @c : go ( n -- ) \ n is offset into table.. 0 for 1st entry
7999: @c cells table + @@ execute ;
8000: @c @end example
8001:
8002: @c This example builds a jump table; @code{0 go} will display ``@code{this
8003: @c is A}''. Using @code{[} and @code{]} in this example is equivalent to
8004: @c defining @code{table} like this:
8005:
8006: @c @example
8007: @c create table ' aa COMPILE, ' bb COMPILE, ' cc COMPILE,
8008: @c @end example
8009:
8010: @c The problem with this code is that the definition of @code{table} is not
8011: @c portable -- it @i{compile}s execution tokens into code space. Whilst it
8012: @c @i{may} work on systems where code space and data space co-incide, the
8013: @c Standard only allows data space to be assigned for a @code{CREATE}d
8014: @c word. In addition, the Standard only allows @code{@@} to access data
8015: @c space, whilst this example is using it to access code space. The only
8016: @c portable, Standard way to build this table is to build it in data space,
8017: @c like this:
8018:
8019: @c @example
8020: @c create table ' aa , ' bb , ' cc ,
8021: @c @end example
1.29 crook 8022:
1.95 anton 8023: @c doc-state
1.44 crook 8024:
1.29 crook 8025:
1.82 anton 8026: @node Interpreter Directives, , Interpret/Compile states, The Text Interpreter
1.26 crook 8027: @subsection Interpreter Directives
8028: @cindex interpreter directives
1.72 anton 8029: @cindex conditional compilation
1.1 anton 8030:
1.29 crook 8031: These words are usually used in interpret state; typically to control
8032: which parts of a source file are processed by the text
1.26 crook 8033: interpreter. There are only a few ANS Forth Standard words, but Gforth
8034: supplements these with a rich set of immediate control structure words
8035: to compensate for the fact that the non-immediate versions can only be
1.29 crook 8036: used in compile state (@pxref{Control Structures}). Typical usages:
8037:
8038: @example
1.72 anton 8039: FALSE Constant HAVE-ASSEMBLER
1.29 crook 8040: .
8041: .
1.72 anton 8042: HAVE-ASSEMBLER [IF]
1.29 crook 8043: : ASSEMBLER-FEATURE
8044: ...
8045: ;
8046: [ENDIF]
8047: .
8048: .
8049: : SEE
8050: ... \ general-purpose SEE code
1.72 anton 8051: [ HAVE-ASSEMBLER [IF] ]
1.29 crook 8052: ... \ assembler-specific SEE code
8053: [ [ENDIF] ]
8054: ;
8055: @end example
1.1 anton 8056:
1.44 crook 8057:
1.26 crook 8058: doc-[IF]
8059: doc-[ELSE]
8060: doc-[THEN]
8061: doc-[ENDIF]
1.1 anton 8062:
1.26 crook 8063: doc-[IFDEF]
8064: doc-[IFUNDEF]
1.1 anton 8065:
1.26 crook 8066: doc-[?DO]
8067: doc-[DO]
8068: doc-[FOR]
8069: doc-[LOOP]
8070: doc-[+LOOP]
8071: doc-[NEXT]
1.1 anton 8072:
1.26 crook 8073: doc-[BEGIN]
8074: doc-[UNTIL]
8075: doc-[AGAIN]
8076: doc-[WHILE]
8077: doc-[REPEAT]
1.1 anton 8078:
1.27 crook 8079:
1.26 crook 8080: @c -------------------------------------------------------------
1.111 ! anton 8081: @node The Input Stream, Word Lists, The Text Interpreter, Words
! 8082: @section The Input Stream
! 8083: @cindex input stream
! 8084:
! 8085: @c !! integrate this better with the "Text Interpreter" section
! 8086: The text interpreter reads from the input stream, which can come from
! 8087: several sources (@pxref{Input Sources}). Some words, in particular
! 8088: defining words, but also words like @code{'}, read parameters from the
! 8089: input stream instead of from the stack.
! 8090:
! 8091: Such words are called parsing words, because they parse the input
! 8092: stream. Parsing words are hard to use in other words, because it is
! 8093: hard to pass program-generated parameters through the input stream.
! 8094: They also usually have an unintuitive combination of interpretation and
! 8095: compilation semantics when implemented naively, leading to various
! 8096: approaches that try to produce a more intuitive behaviour
! 8097: (@pxref{Combined words}).
! 8098:
! 8099: It should be obvious by now that parsing words are a bad idea. If you
! 8100: want to implement a parsing word for convenience, also provide a factor
! 8101: of the word that does not parse, but takes the parameters on the stack.
! 8102: To implement the parsing word on top if it, you can use the following
! 8103: words:
! 8104:
! 8105: @c anton: these belong in the input stream section
! 8106: doc-parse
! 8107: doc-parse-word
! 8108: doc-name
! 8109: doc-word
! 8110: doc-\"-parse
! 8111: doc-refill
! 8112:
! 8113: Conversely, if you have the bad luck (or lack of foresight) to have to
! 8114: deal with parsing words without having such factors, how do you pass a
! 8115: string that is not in the input stream to it?
! 8116:
! 8117: doc-execute-parsing
! 8118:
! 8119: If you want to run a parsing word on a file, the following word should
! 8120: help:
! 8121:
! 8122: doc-execute-parsing-file
! 8123:
! 8124: @c -------------------------------------------------------------
! 8125: @node Word Lists, Environmental Queries, The Input Stream, Words
1.26 crook 8126: @section Word Lists
8127: @cindex word lists
1.32 anton 8128: @cindex header space
1.1 anton 8129:
1.36 anton 8130: A wordlist is a list of named words; you can add new words and look up
8131: words by name (and you can remove words in a restricted way with
8132: markers). Every named (and @code{reveal}ed) word is in one wordlist.
8133:
8134: @cindex search order stack
8135: The text interpreter searches the wordlists present in the search order
8136: (a stack of wordlists), from the top to the bottom. Within each
8137: wordlist, the search starts conceptually at the newest word; i.e., if
8138: two words in a wordlist have the same name, the newer word is found.
1.1 anton 8139:
1.26 crook 8140: @cindex compilation word list
1.36 anton 8141: New words are added to the @dfn{compilation wordlist} (aka current
8142: wordlist).
1.1 anton 8143:
1.36 anton 8144: @cindex wid
8145: A word list is identified by a cell-sized word list identifier (@i{wid})
8146: in much the same way as a file is identified by a file handle. The
8147: numerical value of the wid has no (portable) meaning, and might change
8148: from session to session.
1.1 anton 8149:
1.29 crook 8150: The ANS Forth ``Search order'' word set is intended to provide a set of
8151: low-level tools that allow various different schemes to be
1.74 anton 8152: implemented. Gforth also provides @code{vocabulary}, a traditional Forth
1.26 crook 8153: word. @file{compat/vocabulary.fs} provides an implementation in ANS
1.45 crook 8154: Forth.
1.1 anton 8155:
1.27 crook 8156: @comment TODO: locals section refers to here, saying that every word list (aka
8157: @comment vocabulary) has its own methods for searching etc. Need to document that.
1.78 anton 8158: @c anton: but better in a separate subsection on wordlist internals
1.1 anton 8159:
1.45 crook 8160: @comment TODO: document markers, reveal, tables, mappedwordlist
8161:
8162: @comment the gforthman- prefix is used to pick out the true definition of a
1.27 crook 8163: @comment word from the source files, rather than some alias.
1.44 crook 8164:
1.26 crook 8165: doc-forth-wordlist
8166: doc-definitions
8167: doc-get-current
8168: doc-set-current
8169: doc-get-order
1.45 crook 8170: doc---gforthman-set-order
1.26 crook 8171: doc-wordlist
1.30 anton 8172: doc-table
1.79 anton 8173: doc->order
1.36 anton 8174: doc-previous
1.26 crook 8175: doc-also
1.45 crook 8176: doc---gforthman-forth
1.26 crook 8177: doc-only
1.45 crook 8178: doc---gforthman-order
1.15 anton 8179:
1.26 crook 8180: doc-find
8181: doc-search-wordlist
1.15 anton 8182:
1.26 crook 8183: doc-words
8184: doc-vlist
1.44 crook 8185: @c doc-words-deferred
1.1 anton 8186:
1.74 anton 8187: @c doc-mappedwordlist @c map-structure undefined, implemantation-specific
1.26 crook 8188: doc-root
8189: doc-vocabulary
8190: doc-seal
8191: doc-vocs
8192: doc-current
8193: doc-context
1.1 anton 8194:
1.44 crook 8195:
1.26 crook 8196: @menu
1.75 anton 8197: * Vocabularies::
1.67 anton 8198: * Why use word lists?::
1.75 anton 8199: * Word list example::
1.26 crook 8200: @end menu
8201:
1.75 anton 8202: @node Vocabularies, Why use word lists?, Word Lists, Word Lists
8203: @subsection Vocabularies
8204: @cindex Vocabularies, detailed explanation
8205:
8206: Here is an example of creating and using a new wordlist using ANS
8207: Forth words:
8208:
8209: @example
8210: wordlist constant my-new-words-wordlist
8211: : my-new-words get-order nip my-new-words-wordlist swap set-order ;
8212:
8213: \ add it to the search order
8214: also my-new-words
8215:
8216: \ alternatively, add it to the search order and make it
8217: \ the compilation word list
8218: also my-new-words definitions
8219: \ type "order" to see the problem
8220: @end example
8221:
8222: The problem with this example is that @code{order} has no way to
8223: associate the name @code{my-new-words} with the wid of the word list (in
8224: Gforth, @code{order} and @code{vocs} will display @code{???} for a wid
8225: that has no associated name). There is no Standard way of associating a
8226: name with a wid.
8227:
8228: In Gforth, this example can be re-coded using @code{vocabulary}, which
8229: associates a name with a wid:
8230:
8231: @example
8232: vocabulary my-new-words
8233:
8234: \ add it to the search order
8235: also my-new-words
8236:
8237: \ alternatively, add it to the search order and make it
8238: \ the compilation word list
8239: my-new-words definitions
8240: \ type "order" to see that the problem is solved
8241: @end example
8242:
8243:
8244: @node Why use word lists?, Word list example, Vocabularies, Word Lists
1.26 crook 8245: @subsection Why use word lists?
8246: @cindex word lists - why use them?
8247:
1.74 anton 8248: Here are some reasons why people use wordlists:
1.26 crook 8249:
8250: @itemize @bullet
1.74 anton 8251:
8252: @c anton: Gforth's hashing implementation makes the search speed
8253: @c independent from the number of words. But it is linear with the number
8254: @c of wordlists that have to be searched, so in effect using more wordlists
8255: @c actually slows down compilation.
8256:
8257: @c @item
8258: @c To improve compilation speed by reducing the number of header space
8259: @c entries that must be searched. This is achieved by creating a new
8260: @c word list that contains all of the definitions that are used in the
8261: @c definition of a Forth system but which would not usually be used by
8262: @c programs running on that system. That word list would be on the search
8263: @c list when the Forth system was compiled but would be removed from the
8264: @c search list for normal operation. This can be a useful technique for
8265: @c low-performance systems (for example, 8-bit processors in embedded
8266: @c systems) but is unlikely to be necessary in high-performance desktop
8267: @c systems.
8268:
1.26 crook 8269: @item
8270: To prevent a set of words from being used outside the context in which
8271: they are valid. Two classic examples of this are an integrated editor
8272: (all of the edit commands are defined in a separate word list; the
8273: search order is set to the editor word list when the editor is invoked;
8274: the old search order is restored when the editor is terminated) and an
8275: integrated assembler (the op-codes for the machine are defined in a
8276: separate word list which is used when a @code{CODE} word is defined).
1.74 anton 8277:
8278: @item
8279: To organize the words of an application or library into a user-visible
8280: set (in @code{forth-wordlist} or some other common wordlist) and a set
8281: of helper words used just for the implementation (hidden in a separate
1.75 anton 8282: wordlist). This keeps @code{words}' output smaller, separates
8283: implementation and interface, and reduces the chance of name conflicts
8284: within the common wordlist.
1.74 anton 8285:
1.26 crook 8286: @item
8287: To prevent a name-space clash between multiple definitions with the same
8288: name. For example, when building a cross-compiler you might have a word
8289: @code{IF} that generates conditional code for your target system. By
8290: placing this definition in a different word list you can control whether
8291: the host system's @code{IF} or the target system's @code{IF} get used in
8292: any particular context by controlling the order of the word lists on the
8293: search order stack.
1.74 anton 8294:
1.26 crook 8295: @end itemize
1.1 anton 8296:
1.74 anton 8297: The downsides of using wordlists are:
8298:
8299: @itemize
8300:
8301: @item
8302: Debugging becomes more cumbersome.
8303:
8304: @item
8305: Name conflicts worked around with wordlists are still there, and you
8306: have to arrange the search order carefully to get the desired results;
8307: if you forget to do that, you get hard-to-find errors (as in any case
8308: where you read the code differently from the compiler; @code{see} can
1.75 anton 8309: help seeing which of several possible words the name resolves to in such
8310: cases). @code{See} displays just the name of the words, not what
8311: wordlist they belong to, so it might be misleading. Using unique names
8312: is a better approach to avoid name conflicts.
1.74 anton 8313:
8314: @item
8315: You have to explicitly undo any changes to the search order. In many
8316: cases it would be more convenient if this happened implicitly. Gforth
8317: currently does not provide such a feature, but it may do so in the
8318: future.
8319: @end itemize
8320:
8321:
1.75 anton 8322: @node Word list example, , Why use word lists?, Word Lists
8323: @subsection Word list example
8324: @cindex word lists - example
1.1 anton 8325:
1.74 anton 8326: The following example is from the
8327: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
8328: garbage collector} and uses wordlists to separate public words from
8329: helper words:
8330:
8331: @example
8332: get-current ( wid )
8333: vocabulary garbage-collector also garbage-collector definitions
8334: ... \ define helper words
8335: ( wid ) set-current \ restore original (i.e., public) compilation wordlist
8336: ... \ define the public (i.e., API) words
8337: \ they can refer to the helper words
8338: previous \ restore original search order (helper words become invisible)
8339: @end example
8340:
1.26 crook 8341: @c -------------------------------------------------------------
8342: @node Environmental Queries, Files, Word Lists, Words
8343: @section Environmental Queries
8344: @cindex environmental queries
1.21 crook 8345:
1.26 crook 8346: ANS Forth introduced the idea of ``environmental queries'' as a way
8347: for a program running on a system to determine certain characteristics of the system.
8348: The Standard specifies a number of strings that might be recognised by a system.
1.21 crook 8349:
1.32 anton 8350: The Standard requires that the header space used for environmental queries
8351: be distinct from the header space used for definitions.
1.21 crook 8352:
1.26 crook 8353: Typically, environmental queries are supported by creating a set of
1.29 crook 8354: definitions in a word list that is @i{only} used during environmental
1.26 crook 8355: queries; that is what Gforth does. There is no Standard way of adding
8356: definitions to the set of recognised environmental queries, but any
8357: implementation that supports the loading of optional word sets must have
8358: some mechanism for doing this (after loading the word set, the
8359: associated environmental query string must return @code{true}). In
8360: Gforth, the word list used to honour environmental queries can be
8361: manipulated just like any other word list.
1.21 crook 8362:
1.44 crook 8363:
1.26 crook 8364: doc-environment?
8365: doc-environment-wordlist
1.21 crook 8366:
1.26 crook 8367: doc-gforth
8368: doc-os-class
1.21 crook 8369:
1.44 crook 8370:
1.26 crook 8371: Note that, whilst the documentation for (e.g.) @code{gforth} shows it
8372: returning two items on the stack, querying it using @code{environment?}
8373: will return an additional item; the @code{true} flag that shows that the
8374: string was recognised.
1.21 crook 8375:
1.26 crook 8376: @comment TODO Document the standard strings or note where they are documented herein
1.21 crook 8377:
1.26 crook 8378: Here are some examples of using environmental queries:
1.21 crook 8379:
1.26 crook 8380: @example
8381: s" address-unit-bits" environment? 0=
8382: [IF]
8383: cr .( environmental attribute address-units-bits unknown... ) cr
1.75 anton 8384: [ELSE]
8385: drop \ ensure balanced stack effect
1.26 crook 8386: [THEN]
1.21 crook 8387:
1.75 anton 8388: \ this might occur in the prelude of a standard program that uses THROW
8389: s" exception" environment? [IF]
8390: 0= [IF]
8391: : throw abort" exception thrown" ;
8392: [THEN]
8393: [ELSE] \ we don't know, so make sure
8394: : throw abort" exception thrown" ;
8395: [THEN]
1.21 crook 8396:
1.26 crook 8397: s" gforth" environment? [IF] .( Gforth version ) TYPE
8398: [ELSE] .( Not Gforth..) [THEN]
1.75 anton 8399:
8400: \ a program using v*
8401: s" gforth" environment? [IF]
8402: s" 0.5.0" compare 0< [IF] \ v* is a primitive since 0.5.0
8403: : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
8404: >r swap 2swap swap 0e r> 0 ?DO
8405: dup f@ over + 2swap dup f@ f* f+ over + 2swap
8406: LOOP
8407: 2drop 2drop ;
8408: [THEN]
8409: [ELSE] \
8410: : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
8411: ...
8412: [THEN]
1.26 crook 8413: @end example
1.21 crook 8414:
1.26 crook 8415: Here is an example of adding a definition to the environment word list:
1.21 crook 8416:
1.26 crook 8417: @example
8418: get-current environment-wordlist set-current
8419: true constant block
8420: true constant block-ext
8421: set-current
8422: @end example
1.21 crook 8423:
1.26 crook 8424: You can see what definitions are in the environment word list like this:
1.21 crook 8425:
1.26 crook 8426: @example
1.79 anton 8427: environment-wordlist >order words previous
1.26 crook 8428: @end example
1.21 crook 8429:
8430:
1.26 crook 8431: @c -------------------------------------------------------------
8432: @node Files, Blocks, Environmental Queries, Words
8433: @section Files
1.28 crook 8434: @cindex files
8435: @cindex I/O - file-handling
1.21 crook 8436:
1.26 crook 8437: Gforth provides facilities for accessing files that are stored in the
8438: host operating system's file-system. Files that are processed by Gforth
8439: can be divided into two categories:
1.21 crook 8440:
1.23 crook 8441: @itemize @bullet
8442: @item
1.29 crook 8443: Files that are processed by the Text Interpreter (@dfn{Forth source files}).
1.23 crook 8444: @item
1.29 crook 8445: Files that are processed by some other program (@dfn{general files}).
1.26 crook 8446: @end itemize
8447:
8448: @menu
1.48 anton 8449: * Forth source files::
8450: * General files::
8451: * Search Paths::
1.26 crook 8452: @end menu
8453:
8454: @c -------------------------------------------------------------
8455: @node Forth source files, General files, Files, Files
8456: @subsection Forth source files
8457: @cindex including files
8458: @cindex Forth source files
1.21 crook 8459:
1.26 crook 8460: The simplest way to interpret the contents of a file is to use one of
8461: these two formats:
1.21 crook 8462:
1.26 crook 8463: @example
8464: include mysource.fs
8465: s" mysource.fs" included
8466: @end example
1.21 crook 8467:
1.75 anton 8468: You usually want to include a file only if it is not included already
1.26 crook 8469: (by, say, another source file). In that case, you can use one of these
1.45 crook 8470: three formats:
1.21 crook 8471:
1.26 crook 8472: @example
8473: require mysource.fs
8474: needs mysource.fs
8475: s" mysource.fs" required
8476: @end example
1.21 crook 8477:
1.26 crook 8478: @cindex stack effect of included files
8479: @cindex including files, stack effect
1.45 crook 8480: It is good practice to write your source files such that interpreting them
8481: does not change the stack. Source files designed in this way can be used with
1.26 crook 8482: @code{required} and friends without complications. For example:
1.21 crook 8483:
1.26 crook 8484: @example
1.75 anton 8485: 1024 require foo.fs drop
1.26 crook 8486: @end example
1.21 crook 8487:
1.75 anton 8488: Here you want to pass the argument 1024 (e.g., a buffer size) to
8489: @file{foo.fs}. Interpreting @file{foo.fs} has the stack effect ( n -- n
8490: ), which allows its use with @code{require}. Of course with such
8491: parameters to required files, you have to ensure that the first
8492: @code{require} fits for all uses (i.e., @code{require} it early in the
8493: master load file).
1.44 crook 8494:
1.26 crook 8495: doc-include-file
8496: doc-included
1.28 crook 8497: doc-included?
1.26 crook 8498: doc-include
8499: doc-required
8500: doc-require
8501: doc-needs
1.75 anton 8502: @c doc-init-included-files @c internal
8503: doc-sourcefilename
8504: doc-sourceline#
1.44 crook 8505:
1.26 crook 8506: A definition in ANS Forth for @code{required} is provided in
8507: @file{compat/required.fs}.
1.21 crook 8508:
1.26 crook 8509: @c -------------------------------------------------------------
8510: @node General files, Search Paths, Forth source files, Files
8511: @subsection General files
8512: @cindex general files
8513: @cindex file-handling
1.21 crook 8514:
1.75 anton 8515: Files are opened/created by name and type. The following file access
8516: methods (FAMs) are recognised:
1.44 crook 8517:
1.75 anton 8518: @cindex fam (file access method)
1.26 crook 8519: doc-r/o
8520: doc-r/w
8521: doc-w/o
8522: doc-bin
1.1 anton 8523:
1.44 crook 8524:
1.26 crook 8525: When a file is opened/created, it returns a file identifier,
1.29 crook 8526: @i{wfileid} that is used for all other file commands. All file
8527: commands also return a status value, @i{wior}, that is 0 for a
1.26 crook 8528: successful operation and an implementation-defined non-zero value in the
8529: case of an error.
1.21 crook 8530:
1.44 crook 8531:
1.26 crook 8532: doc-open-file
8533: doc-create-file
1.21 crook 8534:
1.26 crook 8535: doc-close-file
8536: doc-delete-file
8537: doc-rename-file
8538: doc-read-file
8539: doc-read-line
8540: doc-write-file
8541: doc-write-line
8542: doc-emit-file
8543: doc-flush-file
1.21 crook 8544:
1.26 crook 8545: doc-file-status
8546: doc-file-position
8547: doc-reposition-file
8548: doc-file-size
8549: doc-resize-file
1.21 crook 8550:
1.93 anton 8551: doc-slurp-file
8552: doc-slurp-fid
1.44 crook 8553:
1.26 crook 8554: @c ---------------------------------------------------------
1.48 anton 8555: @node Search Paths, , General files, Files
1.26 crook 8556: @subsection Search Paths
8557: @cindex path for @code{included}
8558: @cindex file search path
8559: @cindex @code{include} search path
8560: @cindex search path for files
1.21 crook 8561:
1.26 crook 8562: If you specify an absolute filename (i.e., a filename starting with
8563: @file{/} or @file{~}, or with @file{:} in the second position (as in
8564: @samp{C:...})) for @code{included} and friends, that file is included
8565: just as you would expect.
1.21 crook 8566:
1.75 anton 8567: If the filename starts with @file{./}, this refers to the directory that
8568: the present file was @code{included} from. This allows files to include
8569: other files relative to their own position (irrespective of the current
8570: working directory or the absolute position). This feature is essential
8571: for libraries consisting of several files, where a file may include
8572: other files from the library. It corresponds to @code{#include "..."}
8573: in C. If the current input source is not a file, @file{.} refers to the
8574: directory of the innermost file being included, or, if there is no file
8575: being included, to the current working directory.
8576:
8577: For relative filenames (not starting with @file{./}), Gforth uses a
8578: search path similar to Forth's search order (@pxref{Word Lists}). It
8579: tries to find the given filename in the directories present in the path,
8580: and includes the first one it finds. There are separate search paths for
8581: Forth source files and general files. If the search path contains the
8582: directory @file{.}, this refers to the directory of the current file, or
8583: the working directory, as if the file had been specified with @file{./}.
1.21 crook 8584:
1.26 crook 8585: Use @file{~+} to refer to the current working directory (as in the
8586: @code{bash}).
1.1 anton 8587:
1.75 anton 8588: @c anton: fold the following subsubsections into this subsection?
1.1 anton 8589:
1.48 anton 8590: @menu
1.75 anton 8591: * Source Search Paths::
1.48 anton 8592: * General Search Paths::
8593: @end menu
8594:
1.26 crook 8595: @c ---------------------------------------------------------
1.75 anton 8596: @node Source Search Paths, General Search Paths, Search Paths, Search Paths
8597: @subsubsection Source Search Paths
8598: @cindex search path control, source files
1.5 anton 8599:
1.26 crook 8600: The search path is initialized when you start Gforth (@pxref{Invoking
1.75 anton 8601: Gforth}). You can display it and change it using @code{fpath} in
8602: combination with the general path handling words.
1.5 anton 8603:
1.75 anton 8604: doc-fpath
8605: @c the functionality of the following words is easily available through
8606: @c fpath and the general path words. The may go away.
8607: @c doc-.fpath
8608: @c doc-fpath+
8609: @c doc-fpath=
8610: @c doc-open-fpath-file
1.44 crook 8611:
8612: @noindent
1.26 crook 8613: Here is an example of using @code{fpath} and @code{require}:
1.5 anton 8614:
1.26 crook 8615: @example
1.75 anton 8616: fpath path= /usr/lib/forth/|./
1.26 crook 8617: require timer.fs
8618: @end example
1.5 anton 8619:
1.75 anton 8620:
1.26 crook 8621: @c ---------------------------------------------------------
1.75 anton 8622: @node General Search Paths, , Source Search Paths, Search Paths
1.26 crook 8623: @subsubsection General Search Paths
1.75 anton 8624: @cindex search path control, source files
1.5 anton 8625:
1.26 crook 8626: Your application may need to search files in several directories, like
8627: @code{included} does. To facilitate this, Gforth allows you to define
8628: and use your own search paths, by providing generic equivalents of the
8629: Forth search path words:
1.5 anton 8630:
1.75 anton 8631: doc-open-path-file
8632: doc-path-allot
8633: doc-clear-path
8634: doc-also-path
1.26 crook 8635: doc-.path
8636: doc-path+
8637: doc-path=
1.5 anton 8638:
1.75 anton 8639: @c anton: better define a word for it, say "path-allot ( ucount -- path-addr )
1.44 crook 8640:
1.75 anton 8641: Here's an example of creating an empty search path:
8642: @c
1.26 crook 8643: @example
1.75 anton 8644: create mypath 500 path-allot \ maximum length 500 chars (is checked)
1.26 crook 8645: @end example
1.5 anton 8646:
1.26 crook 8647: @c -------------------------------------------------------------
8648: @node Blocks, Other I/O, Files, Words
8649: @section Blocks
1.28 crook 8650: @cindex I/O - blocks
8651: @cindex blocks
8652:
8653: When you run Gforth on a modern desk-top computer, it runs under the
8654: control of an operating system which provides certain services. One of
8655: these services is @var{file services}, which allows Forth source code
8656: and data to be stored in files and read into Gforth (@pxref{Files}).
8657:
8658: Traditionally, Forth has been an important programming language on
8659: systems where it has interfaced directly to the underlying hardware with
8660: no intervening operating system. Forth provides a mechanism, called
1.29 crook 8661: @dfn{blocks}, for accessing mass storage on such systems.
1.28 crook 8662:
8663: A block is a 1024-byte data area, which can be used to hold data or
8664: Forth source code. No structure is imposed on the contents of the
8665: block. A block is identified by its number; blocks are numbered
8666: contiguously from 1 to an implementation-defined maximum.
8667:
8668: A typical system that used blocks but no operating system might use a
8669: single floppy-disk drive for mass storage, with the disks formatted to
8670: provide 256-byte sectors. Blocks would be implemented by assigning the
8671: first four sectors of the disk to block 1, the second four sectors to
8672: block 2 and so on, up to the limit of the capacity of the disk. The disk
8673: would not contain any file system information, just the set of blocks.
8674:
1.29 crook 8675: @cindex blocks file
1.28 crook 8676: On systems that do provide file services, blocks are typically
1.29 crook 8677: implemented by storing a sequence of blocks within a single @dfn{blocks
1.28 crook 8678: file}. The size of the blocks file will be an exact multiple of 1024
8679: bytes, corresponding to the number of blocks it contains. This is the
8680: mechanism that Gforth uses.
8681:
1.29 crook 8682: @cindex @file{blocks.fb}
1.75 anton 8683: Only one blocks file can be open at a time. If you use block words without
1.28 crook 8684: having specified a blocks file, Gforth defaults to the blocks file
8685: @file{blocks.fb}. Gforth uses the Forth search path when attempting to
1.75 anton 8686: locate a blocks file (@pxref{Source Search Paths}).
1.28 crook 8687:
1.29 crook 8688: @cindex block buffers
1.28 crook 8689: When you read and write blocks under program control, Gforth uses a
1.29 crook 8690: number of @dfn{block buffers} as intermediate storage. These buffers are
1.28 crook 8691: not used when you use @code{load} to interpret the contents of a block.
8692:
1.75 anton 8693: The behaviour of the block buffers is analagous to that of a cache.
8694: Each block buffer has three states:
1.28 crook 8695:
8696: @itemize @bullet
8697: @item
8698: Unassigned
8699: @item
8700: Assigned-clean
8701: @item
8702: Assigned-dirty
8703: @end itemize
8704:
1.29 crook 8705: Initially, all block buffers are @i{unassigned}. In order to access a
1.28 crook 8706: block, the block (specified by its block number) must be assigned to a
8707: block buffer.
8708:
8709: The assignment of a block to a block buffer is performed by @code{block}
8710: or @code{buffer}. Use @code{block} when you wish to modify the existing
8711: contents of a block. Use @code{buffer} when you don't care about the
8712: existing contents of the block@footnote{The ANS Forth definition of
1.35 anton 8713: @code{buffer} is intended not to cause disk I/O; if the data associated
1.28 crook 8714: with the particular block is already stored in a block buffer due to an
8715: earlier @code{block} command, @code{buffer} will return that block
8716: buffer and the existing contents of the block will be
8717: available. Otherwise, @code{buffer} will simply assign a new, empty
1.29 crook 8718: block buffer for the block.}.
1.28 crook 8719:
1.47 crook 8720: Once a block has been assigned to a block buffer using @code{block} or
1.75 anton 8721: @code{buffer}, that block buffer becomes the @i{current block
8722: buffer}. Data may only be manipulated (read or written) within the
8723: current block buffer.
1.47 crook 8724:
8725: When the contents of the current block buffer has been modified it is
1.48 anton 8726: necessary, @emph{before calling @code{block} or @code{buffer} again}, to
1.75 anton 8727: either abandon the changes (by doing nothing) or mark the block as
8728: changed (assigned-dirty), using @code{update}. Using @code{update} does
8729: not change the blocks file; it simply changes a block buffer's state to
8730: @i{assigned-dirty}. The block will be written implicitly when it's
8731: buffer is needed for another block, or explicitly by @code{flush} or
8732: @code{save-buffers}.
8733:
8734: word @code{Flush} writes all @i{assigned-dirty} blocks back to the
8735: blocks file on disk. Leaving Gforth with @code{bye} also performs a
8736: @code{flush}.
1.28 crook 8737:
1.29 crook 8738: In Gforth, @code{block} and @code{buffer} use a @i{direct-mapped}
1.28 crook 8739: algorithm to assign a block buffer to a block. That means that any
8740: particular block can only be assigned to one specific block buffer,
1.29 crook 8741: called (for the particular operation) the @i{victim buffer}. If the
1.47 crook 8742: victim buffer is @i{unassigned} or @i{assigned-clean} it is allocated to
8743: the new block immediately. If it is @i{assigned-dirty} its current
8744: contents are written back to the blocks file on disk before it is
1.28 crook 8745: allocated to the new block.
8746:
8747: Although no structure is imposed on the contents of a block, it is
8748: traditional to display the contents as 16 lines each of 64 characters. A
8749: block provides a single, continuous stream of input (for example, it
8750: acts as a single parse area) -- there are no end-of-line characters
8751: within a block, and no end-of-file character at the end of a
8752: block. There are two consequences of this:
1.26 crook 8753:
1.28 crook 8754: @itemize @bullet
8755: @item
8756: The last character of one line wraps straight into the first character
8757: of the following line
8758: @item
8759: The word @code{\} -- comment to end of line -- requires special
8760: treatment; in the context of a block it causes all characters until the
8761: end of the current 64-character ``line'' to be ignored.
8762: @end itemize
8763:
8764: In Gforth, when you use @code{block} with a non-existent block number,
1.45 crook 8765: the current blocks file will be extended to the appropriate size and the
1.28 crook 8766: block buffer will be initialised with spaces.
8767:
1.47 crook 8768: Gforth includes a simple block editor (type @code{use blocked.fb 0 list}
8769: for details) but doesn't encourage the use of blocks; the mechanism is
8770: only provided for backward compatibility -- ANS Forth requires blocks to
8771: be available when files are.
1.28 crook 8772:
8773: Common techniques that are used when working with blocks include:
8774:
8775: @itemize @bullet
8776: @item
8777: A screen editor that allows you to edit blocks without leaving the Forth
8778: environment.
8779: @item
8780: Shadow screens; where every code block has an associated block
8781: containing comments (for example: code in odd block numbers, comments in
8782: even block numbers). Typically, the block editor provides a convenient
8783: mechanism to toggle between code and comments.
8784: @item
8785: Load blocks; a single block (typically block 1) contains a number of
8786: @code{thru} commands which @code{load} the whole of the application.
8787: @end itemize
1.26 crook 8788:
1.29 crook 8789: See Frank Sergeant's Pygmy Forth to see just how well blocks can be
8790: integrated into a Forth programming environment.
1.26 crook 8791:
8792: @comment TODO what about errors on open-blocks?
1.44 crook 8793:
1.26 crook 8794: doc-open-blocks
8795: doc-use
1.75 anton 8796: doc-block-offset
1.26 crook 8797: doc-get-block-fid
8798: doc-block-position
1.28 crook 8799:
1.75 anton 8800: doc-list
1.28 crook 8801: doc-scr
8802:
1.45 crook 8803: doc---gforthman-block
1.28 crook 8804: doc-buffer
8805:
1.75 anton 8806: doc-empty-buffers
8807: doc-empty-buffer
1.26 crook 8808: doc-update
1.28 crook 8809: doc-updated?
1.26 crook 8810: doc-save-buffers
1.75 anton 8811: doc-save-buffer
1.26 crook 8812: doc-flush
1.28 crook 8813:
1.26 crook 8814: doc-load
8815: doc-thru
8816: doc-+load
8817: doc-+thru
1.45 crook 8818: doc---gforthman--->
1.26 crook 8819: doc-block-included
8820:
1.44 crook 8821:
1.26 crook 8822: @c -------------------------------------------------------------
1.78 anton 8823: @node Other I/O, Locals, Blocks, Words
1.26 crook 8824: @section Other I/O
1.28 crook 8825: @cindex I/O - keyboard and display
1.26 crook 8826:
8827: @menu
8828: * Simple numeric output:: Predefined formats
8829: * Formatted numeric output:: Formatted (pictured) output
8830: * String Formats:: How Forth stores strings in memory
1.67 anton 8831: * Displaying characters and strings:: Other stuff
1.26 crook 8832: * Input:: Input
8833: @end menu
8834:
8835: @node Simple numeric output, Formatted numeric output, Other I/O, Other I/O
8836: @subsection Simple numeric output
1.28 crook 8837: @cindex numeric output - simple/free-format
1.5 anton 8838:
1.26 crook 8839: The simplest output functions are those that display numbers from the
8840: data or floating-point stacks. Floating-point output is always displayed
8841: using base 10. Numbers displayed from the data stack use the value stored
8842: in @code{base}.
1.5 anton 8843:
1.44 crook 8844:
1.26 crook 8845: doc-.
8846: doc-dec.
8847: doc-hex.
8848: doc-u.
8849: doc-.r
8850: doc-u.r
8851: doc-d.
8852: doc-ud.
8853: doc-d.r
8854: doc-ud.r
8855: doc-f.
8856: doc-fe.
8857: doc-fs.
1.111 ! anton 8858: doc-f.rdp
1.44 crook 8859:
1.26 crook 8860: Examples of printing the number 1234.5678E23 in the different floating-point output
8861: formats are shown below:
1.5 anton 8862:
8863: @example
1.26 crook 8864: f. 123456779999999000000000000.
8865: fe. 123.456779999999E24
8866: fs. 1.23456779999999E26
1.5 anton 8867: @end example
8868:
8869:
1.26 crook 8870: @node Formatted numeric output, String Formats, Simple numeric output, Other I/O
8871: @subsection Formatted numeric output
1.28 crook 8872: @cindex formatted numeric output
1.26 crook 8873: @cindex pictured numeric output
1.28 crook 8874: @cindex numeric output - formatted
1.26 crook 8875:
1.29 crook 8876: Forth traditionally uses a technique called @dfn{pictured numeric
1.26 crook 8877: output} for formatted printing of integers. In this technique, digits
8878: are extracted from the number (using the current output radix defined by
8879: @code{base}), converted to ASCII codes and appended to a string that is
8880: built in a scratch-pad area of memory (@pxref{core-idef,
8881: Implementation-defined options, Implementation-defined
8882: options}). Arbitrary characters can be appended to the string during the
8883: extraction process. The completed string is specified by an address
8884: and length and can be manipulated (@code{TYPE}ed, copied, modified)
8885: under program control.
1.5 anton 8886:
1.75 anton 8887: All of the integer output words described in the previous section
8888: (@pxref{Simple numeric output}) are implemented in Gforth using pictured
8889: numeric output.
1.5 anton 8890:
1.47 crook 8891: Three important things to remember about pictured numeric output:
1.5 anton 8892:
1.26 crook 8893: @itemize @bullet
8894: @item
1.28 crook 8895: It always operates on double-precision numbers; to display a
1.49 anton 8896: single-precision number, convert it first (for ways of doing this
8897: @pxref{Double precision}).
1.26 crook 8898: @item
1.28 crook 8899: It always treats the double-precision number as though it were
8900: unsigned. The examples below show ways of printing signed numbers.
1.26 crook 8901: @item
8902: The string is built up from right to left; least significant digit first.
8903: @end itemize
1.5 anton 8904:
1.44 crook 8905:
1.26 crook 8906: doc-<#
1.47 crook 8907: doc-<<#
1.26 crook 8908: doc-#
8909: doc-#s
8910: doc-hold
8911: doc-sign
8912: doc-#>
1.47 crook 8913: doc-#>>
1.5 anton 8914:
1.26 crook 8915: doc-represent
1.111 ! anton 8916: doc-f>str-rdp
! 8917: doc-f>buf-rdp
1.5 anton 8918:
1.44 crook 8919:
8920: @noindent
1.26 crook 8921: Here are some examples of using pictured numeric output:
1.5 anton 8922:
8923: @example
1.26 crook 8924: : my-u. ( u -- )
8925: \ Simplest use of pns.. behaves like Standard u.
8926: 0 \ convert to unsigned double
1.75 anton 8927: <<# \ start conversion
1.26 crook 8928: #s \ convert all digits
8929: #> \ complete conversion
1.75 anton 8930: TYPE SPACE \ display, with trailing space
8931: #>> ; \ release hold area
1.5 anton 8932:
1.26 crook 8933: : cents-only ( u -- )
8934: 0 \ convert to unsigned double
1.75 anton 8935: <<# \ start conversion
1.26 crook 8936: # # \ convert two least-significant digits
8937: #> \ complete conversion, discard other digits
1.75 anton 8938: TYPE SPACE \ display, with trailing space
8939: #>> ; \ release hold area
1.5 anton 8940:
1.26 crook 8941: : dollars-and-cents ( u -- )
8942: 0 \ convert to unsigned double
1.75 anton 8943: <<# \ start conversion
1.26 crook 8944: # # \ convert two least-significant digits
8945: [char] . hold \ insert decimal point
8946: #s \ convert remaining digits
8947: [char] $ hold \ append currency symbol
8948: #> \ complete conversion
1.75 anton 8949: TYPE SPACE \ display, with trailing space
8950: #>> ; \ release hold area
1.5 anton 8951:
1.26 crook 8952: : my-. ( n -- )
8953: \ handling negatives.. behaves like Standard .
8954: s>d \ convert to signed double
8955: swap over dabs \ leave sign byte followed by unsigned double
1.75 anton 8956: <<# \ start conversion
1.26 crook 8957: #s \ convert all digits
8958: rot sign \ get at sign byte, append "-" if needed
8959: #> \ complete conversion
1.75 anton 8960: TYPE SPACE \ display, with trailing space
8961: #>> ; \ release hold area
1.5 anton 8962:
1.26 crook 8963: : account. ( n -- )
1.75 anton 8964: \ accountants don't like minus signs, they use parentheses
1.26 crook 8965: \ for negative numbers
8966: s>d \ convert to signed double
8967: swap over dabs \ leave sign byte followed by unsigned double
1.75 anton 8968: <<# \ start conversion
1.26 crook 8969: 2 pick \ get copy of sign byte
8970: 0< IF [char] ) hold THEN \ right-most character of output
8971: #s \ convert all digits
8972: rot \ get at sign byte
8973: 0< IF [char] ( hold THEN
8974: #> \ complete conversion
1.75 anton 8975: TYPE SPACE \ display, with trailing space
8976: #>> ; \ release hold area
8977:
1.5 anton 8978: @end example
8979:
1.26 crook 8980: Here are some examples of using these words:
1.5 anton 8981:
8982: @example
1.26 crook 8983: 1 my-u. 1
8984: hex -1 my-u. decimal FFFFFFFF
8985: 1 cents-only 01
8986: 1234 cents-only 34
8987: 2 dollars-and-cents $0.02
8988: 1234 dollars-and-cents $12.34
8989: 123 my-. 123
8990: -123 my. -123
8991: 123 account. 123
8992: -456 account. (456)
1.5 anton 8993: @end example
8994:
8995:
1.26 crook 8996: @node String Formats, Displaying characters and strings, Formatted numeric output, Other I/O
8997: @subsection String Formats
1.27 crook 8998: @cindex strings - see character strings
8999: @cindex character strings - formats
1.28 crook 9000: @cindex I/O - see character strings
1.75 anton 9001: @cindex counted strings
9002:
9003: @c anton: this does not really belong here; maybe the memory section,
9004: @c or the principles chapter
1.26 crook 9005:
1.27 crook 9006: Forth commonly uses two different methods for representing character
9007: strings:
1.26 crook 9008:
9009: @itemize @bullet
9010: @item
9011: @cindex address of counted string
1.45 crook 9012: @cindex counted string
1.29 crook 9013: As a @dfn{counted string}, represented by a @i{c-addr}. The char
9014: addressed by @i{c-addr} contains a character-count, @i{n}, of the
9015: string and the string occupies the subsequent @i{n} char addresses in
1.26 crook 9016: memory.
9017: @item
1.29 crook 9018: As cell pair on the stack; @i{c-addr u}, where @i{u} is the length
9019: of the string in characters, and @i{c-addr} is the address of the
1.26 crook 9020: first byte of the string.
9021: @end itemize
9022:
9023: ANS Forth encourages the use of the second format when representing
1.75 anton 9024: strings.
1.26 crook 9025:
1.44 crook 9026:
1.26 crook 9027: doc-count
9028:
1.44 crook 9029:
1.49 anton 9030: For words that move, copy and search for strings see @ref{Memory
9031: Blocks}. For words that display characters and strings see
9032: @ref{Displaying characters and strings}.
1.26 crook 9033:
9034: @node Displaying characters and strings, Input, String Formats, Other I/O
9035: @subsection Displaying characters and strings
1.27 crook 9036: @cindex characters - compiling and displaying
9037: @cindex character strings - compiling and displaying
1.26 crook 9038:
9039: This section starts with a glossary of Forth words and ends with a set
9040: of examples.
9041:
1.44 crook 9042:
1.26 crook 9043: doc-bl
9044: doc-space
9045: doc-spaces
9046: doc-emit
9047: doc-toupper
9048: doc-."
9049: doc-.(
1.98 anton 9050: doc-.\"
1.26 crook 9051: doc-type
1.44 crook 9052: doc-typewhite
1.26 crook 9053: doc-cr
1.27 crook 9054: @cindex cursor control
1.26 crook 9055: doc-at-xy
9056: doc-page
9057: doc-s"
1.98 anton 9058: doc-s\"
1.26 crook 9059: doc-c"
9060: doc-char
9061: doc-[char]
9062:
1.44 crook 9063:
9064: @noindent
1.26 crook 9065: As an example, consider the following text, stored in a file @file{test.fs}:
1.5 anton 9066:
9067: @example
1.26 crook 9068: .( text-1)
9069: : my-word
9070: ." text-2" cr
9071: .( text-3)
9072: ;
9073:
9074: ." text-4"
9075:
9076: : my-char
9077: [char] ALPHABET emit
9078: char emit
9079: ;
1.5 anton 9080: @end example
9081:
1.26 crook 9082: When you load this code into Gforth, the following output is generated:
1.5 anton 9083:
1.26 crook 9084: @example
1.30 anton 9085: @kbd{include test.fs @key{RET}} text-1text-3text-4 ok
1.26 crook 9086: @end example
1.5 anton 9087:
1.26 crook 9088: @itemize @bullet
9089: @item
9090: Messages @code{text-1} and @code{text-3} are displayed because @code{.(}
9091: is an immediate word; it behaves in the same way whether it is used inside
9092: or outside a colon definition.
9093: @item
9094: Message @code{text-4} is displayed because of Gforth's added interpretation
9095: semantics for @code{."}.
9096: @item
1.29 crook 9097: Message @code{text-2} is @i{not} displayed, because the text interpreter
1.26 crook 9098: performs the compilation semantics for @code{."} within the definition of
9099: @code{my-word}.
9100: @end itemize
1.5 anton 9101:
1.26 crook 9102: Here are some examples of executing @code{my-word} and @code{my-char}:
1.5 anton 9103:
1.26 crook 9104: @example
1.30 anton 9105: @kbd{my-word @key{RET}} text-2
1.26 crook 9106: ok
1.30 anton 9107: @kbd{my-char fred @key{RET}} Af ok
9108: @kbd{my-char jim @key{RET}} Aj ok
1.26 crook 9109: @end example
1.5 anton 9110:
9111: @itemize @bullet
9112: @item
1.26 crook 9113: Message @code{text-2} is displayed because of the run-time behaviour of
9114: @code{."}.
9115: @item
9116: @code{[char]} compiles the ``A'' from ``ALPHABET'' and puts its display code
9117: on the stack at run-time. @code{emit} always displays the character
9118: when @code{my-char} is executed.
9119: @item
9120: @code{char} parses a string at run-time and the second @code{emit} displays
9121: the first character of the string.
1.5 anton 9122: @item
1.26 crook 9123: If you type @code{see my-char} you can see that @code{[char]} discarded
9124: the text ``LPHABET'' and only compiled the display code for ``A'' into the
9125: definition of @code{my-char}.
1.5 anton 9126: @end itemize
9127:
9128:
9129:
1.48 anton 9130: @node Input, , Displaying characters and strings, Other I/O
1.26 crook 9131: @subsection Input
9132: @cindex input
1.28 crook 9133: @cindex I/O - see input
9134: @cindex parsing a string
1.5 anton 9135:
1.49 anton 9136: For ways of storing character strings in memory see @ref{String Formats}.
1.5 anton 9137:
1.27 crook 9138: @comment TODO examples for >number >float accept key key? pad parse word refill
1.29 crook 9139: @comment then index them
1.27 crook 9140:
1.44 crook 9141:
1.27 crook 9142: doc-key
9143: doc-key?
1.45 crook 9144: doc-ekey
9145: doc-ekey?
9146: doc-ekey>char
1.26 crook 9147: doc->number
9148: doc->float
9149: doc-accept
1.109 anton 9150: doc-edit-line
1.27 crook 9151: doc-pad
9152: @comment obsolescent words..
9153: doc-convert
1.26 crook 9154: doc-expect
1.27 crook 9155: doc-span
1.5 anton 9156:
9157:
1.78 anton 9158: @c -------------------------------------------------------------
9159: @node Locals, Structures, Other I/O, Words
9160: @section Locals
9161: @cindex locals
9162:
9163: Local variables can make Forth programming more enjoyable and Forth
9164: programs easier to read. Unfortunately, the locals of ANS Forth are
9165: laden with restrictions. Therefore, we provide not only the ANS Forth
9166: locals wordset, but also our own, more powerful locals wordset (we
9167: implemented the ANS Forth locals wordset through our locals wordset).
1.44 crook 9168:
1.78 anton 9169: The ideas in this section have also been published in M. Anton Ertl,
9170: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl94l.ps.gz,
9171: Automatic Scoping of Local Variables}}, EuroForth '94.
1.12 anton 9172:
9173: @menu
1.78 anton 9174: * Gforth locals::
9175: * ANS Forth locals::
1.5 anton 9176: @end menu
9177:
1.78 anton 9178: @node Gforth locals, ANS Forth locals, Locals, Locals
9179: @subsection Gforth locals
9180: @cindex Gforth locals
9181: @cindex locals, Gforth style
1.5 anton 9182:
1.78 anton 9183: Locals can be defined with
1.44 crook 9184:
1.78 anton 9185: @example
9186: @{ local1 local2 ... -- comment @}
9187: @end example
9188: or
9189: @example
9190: @{ local1 local2 ... @}
9191: @end example
1.5 anton 9192:
1.78 anton 9193: E.g.,
9194: @example
9195: : max @{ n1 n2 -- n3 @}
9196: n1 n2 > if
9197: n1
9198: else
9199: n2
9200: endif ;
9201: @end example
1.44 crook 9202:
1.78 anton 9203: The similarity of locals definitions with stack comments is intended. A
9204: locals definition often replaces the stack comment of a word. The order
9205: of the locals corresponds to the order in a stack comment and everything
9206: after the @code{--} is really a comment.
1.77 anton 9207:
1.78 anton 9208: This similarity has one disadvantage: It is too easy to confuse locals
9209: declarations with stack comments, causing bugs and making them hard to
9210: find. However, this problem can be avoided by appropriate coding
9211: conventions: Do not use both notations in the same program. If you do,
9212: they should be distinguished using additional means, e.g. by position.
1.77 anton 9213:
1.78 anton 9214: @cindex types of locals
9215: @cindex locals types
9216: The name of the local may be preceded by a type specifier, e.g.,
9217: @code{F:} for a floating point value:
1.5 anton 9218:
1.78 anton 9219: @example
9220: : CX* @{ F: Ar F: Ai F: Br F: Bi -- Cr Ci @}
9221: \ complex multiplication
9222: Ar Br f* Ai Bi f* f-
9223: Ar Bi f* Ai Br f* f+ ;
9224: @end example
1.44 crook 9225:
1.78 anton 9226: @cindex flavours of locals
9227: @cindex locals flavours
9228: @cindex value-flavoured locals
9229: @cindex variable-flavoured locals
9230: Gforth currently supports cells (@code{W:}, @code{W^}), doubles
9231: (@code{D:}, @code{D^}), floats (@code{F:}, @code{F^}) and characters
9232: (@code{C:}, @code{C^}) in two flavours: a value-flavoured local (defined
9233: with @code{W:}, @code{D:} etc.) produces its value and can be changed
9234: with @code{TO}. A variable-flavoured local (defined with @code{W^} etc.)
9235: produces its address (which becomes invalid when the variable's scope is
9236: left). E.g., the standard word @code{emit} can be defined in terms of
9237: @code{type} like this:
1.5 anton 9238:
1.78 anton 9239: @example
9240: : emit @{ C^ char* -- @}
9241: char* 1 type ;
9242: @end example
1.5 anton 9243:
1.78 anton 9244: @cindex default type of locals
9245: @cindex locals, default type
9246: A local without type specifier is a @code{W:} local. Both flavours of
9247: locals are initialized with values from the data or FP stack.
1.44 crook 9248:
1.78 anton 9249: Currently there is no way to define locals with user-defined data
9250: structures, but we are working on it.
1.5 anton 9251:
1.78 anton 9252: Gforth allows defining locals everywhere in a colon definition. This
9253: poses the following questions:
1.5 anton 9254:
1.78 anton 9255: @menu
9256: * Where are locals visible by name?::
9257: * How long do locals live?::
9258: * Locals programming style::
9259: * Locals implementation::
9260: @end menu
1.44 crook 9261:
1.78 anton 9262: @node Where are locals visible by name?, How long do locals live?, Gforth locals, Gforth locals
9263: @subsubsection Where are locals visible by name?
9264: @cindex locals visibility
9265: @cindex visibility of locals
9266: @cindex scope of locals
1.5 anton 9267:
1.78 anton 9268: Basically, the answer is that locals are visible where you would expect
9269: it in block-structured languages, and sometimes a little longer. If you
9270: want to restrict the scope of a local, enclose its definition in
9271: @code{SCOPE}...@code{ENDSCOPE}.
1.5 anton 9272:
9273:
1.78 anton 9274: doc-scope
9275: doc-endscope
1.5 anton 9276:
9277:
1.78 anton 9278: These words behave like control structure words, so you can use them
9279: with @code{CS-PICK} and @code{CS-ROLL} to restrict the scope in
9280: arbitrary ways.
1.77 anton 9281:
1.78 anton 9282: If you want a more exact answer to the visibility question, here's the
9283: basic principle: A local is visible in all places that can only be
9284: reached through the definition of the local@footnote{In compiler
9285: construction terminology, all places dominated by the definition of the
9286: local.}. In other words, it is not visible in places that can be reached
9287: without going through the definition of the local. E.g., locals defined
9288: in @code{IF}...@code{ENDIF} are visible until the @code{ENDIF}, locals
9289: defined in @code{BEGIN}...@code{UNTIL} are visible after the
9290: @code{UNTIL} (until, e.g., a subsequent @code{ENDSCOPE}).
1.77 anton 9291:
1.78 anton 9292: The reasoning behind this solution is: We want to have the locals
9293: visible as long as it is meaningful. The user can always make the
9294: visibility shorter by using explicit scoping. In a place that can
9295: only be reached through the definition of a local, the meaning of a
9296: local name is clear. In other places it is not: How is the local
9297: initialized at the control flow path that does not contain the
9298: definition? Which local is meant, if the same name is defined twice in
9299: two independent control flow paths?
1.77 anton 9300:
1.78 anton 9301: This should be enough detail for nearly all users, so you can skip the
9302: rest of this section. If you really must know all the gory details and
9303: options, read on.
1.77 anton 9304:
1.78 anton 9305: In order to implement this rule, the compiler has to know which places
9306: are unreachable. It knows this automatically after @code{AHEAD},
9307: @code{AGAIN}, @code{EXIT} and @code{LEAVE}; in other cases (e.g., after
9308: most @code{THROW}s), you can use the word @code{UNREACHABLE} to tell the
9309: compiler that the control flow never reaches that place. If
9310: @code{UNREACHABLE} is not used where it could, the only consequence is
9311: that the visibility of some locals is more limited than the rule above
9312: says. If @code{UNREACHABLE} is used where it should not (i.e., if you
9313: lie to the compiler), buggy code will be produced.
1.77 anton 9314:
1.5 anton 9315:
1.78 anton 9316: doc-unreachable
1.5 anton 9317:
1.23 crook 9318:
1.78 anton 9319: Another problem with this rule is that at @code{BEGIN}, the compiler
9320: does not know which locals will be visible on the incoming
9321: back-edge. All problems discussed in the following are due to this
9322: ignorance of the compiler (we discuss the problems using @code{BEGIN}
9323: loops as examples; the discussion also applies to @code{?DO} and other
9324: loops). Perhaps the most insidious example is:
1.26 crook 9325: @example
1.78 anton 9326: AHEAD
9327: BEGIN
9328: x
9329: [ 1 CS-ROLL ] THEN
9330: @{ x @}
9331: ...
9332: UNTIL
1.26 crook 9333: @end example
1.23 crook 9334:
1.78 anton 9335: This should be legal according to the visibility rule. The use of
9336: @code{x} can only be reached through the definition; but that appears
9337: textually below the use.
9338:
9339: From this example it is clear that the visibility rules cannot be fully
9340: implemented without major headaches. Our implementation treats common
9341: cases as advertised and the exceptions are treated in a safe way: The
9342: compiler makes a reasonable guess about the locals visible after a
9343: @code{BEGIN}; if it is too pessimistic, the
9344: user will get a spurious error about the local not being defined; if the
9345: compiler is too optimistic, it will notice this later and issue a
9346: warning. In the case above the compiler would complain about @code{x}
9347: being undefined at its use. You can see from the obscure examples in
9348: this section that it takes quite unusual control structures to get the
9349: compiler into trouble, and even then it will often do fine.
1.23 crook 9350:
1.78 anton 9351: If the @code{BEGIN} is reachable from above, the most optimistic guess
9352: is that all locals visible before the @code{BEGIN} will also be
9353: visible after the @code{BEGIN}. This guess is valid for all loops that
9354: are entered only through the @code{BEGIN}, in particular, for normal
9355: @code{BEGIN}...@code{WHILE}...@code{REPEAT} and
9356: @code{BEGIN}...@code{UNTIL} loops and it is implemented in our
9357: compiler. When the branch to the @code{BEGIN} is finally generated by
9358: @code{AGAIN} or @code{UNTIL}, the compiler checks the guess and
9359: warns the user if it was too optimistic:
1.26 crook 9360: @example
1.78 anton 9361: IF
9362: @{ x @}
9363: BEGIN
9364: \ x ?
9365: [ 1 cs-roll ] THEN
9366: ...
9367: UNTIL
1.26 crook 9368: @end example
1.23 crook 9369:
1.78 anton 9370: Here, @code{x} lives only until the @code{BEGIN}, but the compiler
9371: optimistically assumes that it lives until the @code{THEN}. It notices
9372: this difference when it compiles the @code{UNTIL} and issues a
9373: warning. The user can avoid the warning, and make sure that @code{x}
9374: is not used in the wrong area by using explicit scoping:
9375: @example
9376: IF
9377: SCOPE
9378: @{ x @}
9379: ENDSCOPE
9380: BEGIN
9381: [ 1 cs-roll ] THEN
9382: ...
9383: UNTIL
9384: @end example
1.23 crook 9385:
1.78 anton 9386: Since the guess is optimistic, there will be no spurious error messages
9387: about undefined locals.
1.44 crook 9388:
1.78 anton 9389: If the @code{BEGIN} is not reachable from above (e.g., after
9390: @code{AHEAD} or @code{EXIT}), the compiler cannot even make an
9391: optimistic guess, as the locals visible after the @code{BEGIN} may be
9392: defined later. Therefore, the compiler assumes that no locals are
9393: visible after the @code{BEGIN}. However, the user can use
9394: @code{ASSUME-LIVE} to make the compiler assume that the same locals are
9395: visible at the BEGIN as at the point where the top control-flow stack
9396: item was created.
1.23 crook 9397:
1.44 crook 9398:
1.78 anton 9399: doc-assume-live
1.26 crook 9400:
1.23 crook 9401:
1.78 anton 9402: @noindent
9403: E.g.,
9404: @example
9405: @{ x @}
9406: AHEAD
9407: ASSUME-LIVE
9408: BEGIN
9409: x
9410: [ 1 CS-ROLL ] THEN
9411: ...
9412: UNTIL
9413: @end example
1.44 crook 9414:
1.78 anton 9415: Other cases where the locals are defined before the @code{BEGIN} can be
9416: handled by inserting an appropriate @code{CS-ROLL} before the
9417: @code{ASSUME-LIVE} (and changing the control-flow stack manipulation
9418: behind the @code{ASSUME-LIVE}).
1.23 crook 9419:
1.78 anton 9420: Cases where locals are defined after the @code{BEGIN} (but should be
9421: visible immediately after the @code{BEGIN}) can only be handled by
9422: rearranging the loop. E.g., the ``most insidious'' example above can be
9423: arranged into:
9424: @example
9425: BEGIN
9426: @{ x @}
9427: ... 0=
9428: WHILE
9429: x
9430: REPEAT
9431: @end example
1.44 crook 9432:
1.78 anton 9433: @node How long do locals live?, Locals programming style, Where are locals visible by name?, Gforth locals
9434: @subsubsection How long do locals live?
9435: @cindex locals lifetime
9436: @cindex lifetime of locals
1.23 crook 9437:
1.78 anton 9438: The right answer for the lifetime question would be: A local lives at
9439: least as long as it can be accessed. For a value-flavoured local this
9440: means: until the end of its visibility. However, a variable-flavoured
9441: local could be accessed through its address far beyond its visibility
9442: scope. Ultimately, this would mean that such locals would have to be
9443: garbage collected. Since this entails un-Forth-like implementation
9444: complexities, I adopted the same cowardly solution as some other
9445: languages (e.g., C): The local lives only as long as it is visible;
9446: afterwards its address is invalid (and programs that access it
9447: afterwards are erroneous).
1.23 crook 9448:
1.78 anton 9449: @node Locals programming style, Locals implementation, How long do locals live?, Gforth locals
9450: @subsubsection Locals programming style
9451: @cindex locals programming style
9452: @cindex programming style, locals
1.23 crook 9453:
1.78 anton 9454: The freedom to define locals anywhere has the potential to change
9455: programming styles dramatically. In particular, the need to use the
9456: return stack for intermediate storage vanishes. Moreover, all stack
9457: manipulations (except @code{PICK}s and @code{ROLL}s with run-time
9458: determined arguments) can be eliminated: If the stack items are in the
9459: wrong order, just write a locals definition for all of them; then
9460: write the items in the order you want.
1.23 crook 9461:
1.78 anton 9462: This seems a little far-fetched and eliminating stack manipulations is
9463: unlikely to become a conscious programming objective. Still, the number
9464: of stack manipulations will be reduced dramatically if local variables
9465: are used liberally (e.g., compare @code{max} (@pxref{Gforth locals}) with
9466: a traditional implementation of @code{max}).
1.23 crook 9467:
1.78 anton 9468: This shows one potential benefit of locals: making Forth programs more
9469: readable. Of course, this benefit will only be realized if the
9470: programmers continue to honour the principle of factoring instead of
9471: using the added latitude to make the words longer.
1.23 crook 9472:
1.78 anton 9473: @cindex single-assignment style for locals
9474: Using @code{TO} can and should be avoided. Without @code{TO},
9475: every value-flavoured local has only a single assignment and many
9476: advantages of functional languages apply to Forth. I.e., programs are
9477: easier to analyse, to optimize and to read: It is clear from the
9478: definition what the local stands for, it does not turn into something
9479: different later.
1.23 crook 9480:
1.78 anton 9481: E.g., a definition using @code{TO} might look like this:
9482: @example
9483: : strcmp @{ addr1 u1 addr2 u2 -- n @}
9484: u1 u2 min 0
9485: ?do
9486: addr1 c@@ addr2 c@@ -
9487: ?dup-if
9488: unloop exit
9489: then
9490: addr1 char+ TO addr1
9491: addr2 char+ TO addr2
9492: loop
9493: u1 u2 - ;
1.26 crook 9494: @end example
1.78 anton 9495: Here, @code{TO} is used to update @code{addr1} and @code{addr2} at
9496: every loop iteration. @code{strcmp} is a typical example of the
9497: readability problems of using @code{TO}. When you start reading
9498: @code{strcmp}, you think that @code{addr1} refers to the start of the
9499: string. Only near the end of the loop you realize that it is something
9500: else.
1.23 crook 9501:
1.78 anton 9502: This can be avoided by defining two locals at the start of the loop that
9503: are initialized with the right value for the current iteration.
9504: @example
9505: : strcmp @{ addr1 u1 addr2 u2 -- n @}
9506: addr1 addr2
9507: u1 u2 min 0
9508: ?do @{ s1 s2 @}
9509: s1 c@@ s2 c@@ -
9510: ?dup-if
9511: unloop exit
9512: then
9513: s1 char+ s2 char+
9514: loop
9515: 2drop
9516: u1 u2 - ;
9517: @end example
9518: Here it is clear from the start that @code{s1} has a different value
9519: in every loop iteration.
1.23 crook 9520:
1.78 anton 9521: @node Locals implementation, , Locals programming style, Gforth locals
9522: @subsubsection Locals implementation
9523: @cindex locals implementation
9524: @cindex implementation of locals
1.23 crook 9525:
1.78 anton 9526: @cindex locals stack
9527: Gforth uses an extra locals stack. The most compelling reason for
9528: this is that the return stack is not float-aligned; using an extra stack
9529: also eliminates the problems and restrictions of using the return stack
9530: as locals stack. Like the other stacks, the locals stack grows toward
9531: lower addresses. A few primitives allow an efficient implementation:
9532:
9533:
9534: doc-@local#
9535: doc-f@local#
9536: doc-laddr#
9537: doc-lp+!#
9538: doc-lp!
9539: doc->l
9540: doc-f>l
9541:
9542:
9543: In addition to these primitives, some specializations of these
9544: primitives for commonly occurring inline arguments are provided for
9545: efficiency reasons, e.g., @code{@@local0} as specialization of
9546: @code{@@local#} for the inline argument 0. The following compiling words
9547: compile the right specialized version, or the general version, as
9548: appropriate:
1.23 crook 9549:
1.5 anton 9550:
1.107 dvdkhlng 9551: @c doc-compile-@local
9552: @c doc-compile-f@local
1.78 anton 9553: doc-compile-lp+!
1.5 anton 9554:
9555:
1.78 anton 9556: Combinations of conditional branches and @code{lp+!#} like
9557: @code{?branch-lp+!#} (the locals pointer is only changed if the branch
9558: is taken) are provided for efficiency and correctness in loops.
1.5 anton 9559:
1.78 anton 9560: A special area in the dictionary space is reserved for keeping the
9561: local variable names. @code{@{} switches the dictionary pointer to this
9562: area and @code{@}} switches it back and generates the locals
9563: initializing code. @code{W:} etc.@ are normal defining words. This
9564: special area is cleared at the start of every colon definition.
1.5 anton 9565:
1.78 anton 9566: @cindex word list for defining locals
9567: A special feature of Gforth's dictionary is used to implement the
9568: definition of locals without type specifiers: every word list (aka
9569: vocabulary) has its own methods for searching
9570: etc. (@pxref{Word Lists}). For the present purpose we defined a word list
9571: with a special search method: When it is searched for a word, it
9572: actually creates that word using @code{W:}. @code{@{} changes the search
9573: order to first search the word list containing @code{@}}, @code{W:} etc.,
9574: and then the word list for defining locals without type specifiers.
1.5 anton 9575:
1.78 anton 9576: The lifetime rules support a stack discipline within a colon
9577: definition: The lifetime of a local is either nested with other locals
9578: lifetimes or it does not overlap them.
1.23 crook 9579:
1.78 anton 9580: At @code{BEGIN}, @code{IF}, and @code{AHEAD} no code for locals stack
9581: pointer manipulation is generated. Between control structure words
9582: locals definitions can push locals onto the locals stack. @code{AGAIN}
9583: is the simplest of the other three control flow words. It has to
9584: restore the locals stack depth of the corresponding @code{BEGIN}
9585: before branching. The code looks like this:
9586: @format
9587: @code{lp+!#} current-locals-size @minus{} dest-locals-size
9588: @code{branch} <begin>
9589: @end format
1.26 crook 9590:
1.78 anton 9591: @code{UNTIL} is a little more complicated: If it branches back, it
9592: must adjust the stack just like @code{AGAIN}. But if it falls through,
9593: the locals stack must not be changed. The compiler generates the
9594: following code:
9595: @format
9596: @code{?branch-lp+!#} <begin> current-locals-size @minus{} dest-locals-size
9597: @end format
9598: The locals stack pointer is only adjusted if the branch is taken.
1.44 crook 9599:
1.78 anton 9600: @code{THEN} can produce somewhat inefficient code:
9601: @format
9602: @code{lp+!#} current-locals-size @minus{} orig-locals-size
9603: <orig target>:
9604: @code{lp+!#} orig-locals-size @minus{} new-locals-size
9605: @end format
9606: The second @code{lp+!#} adjusts the locals stack pointer from the
9607: level at the @i{orig} point to the level after the @code{THEN}. The
9608: first @code{lp+!#} adjusts the locals stack pointer from the current
9609: level to the level at the orig point, so the complete effect is an
9610: adjustment from the current level to the right level after the
9611: @code{THEN}.
1.26 crook 9612:
1.78 anton 9613: @cindex locals information on the control-flow stack
9614: @cindex control-flow stack items, locals information
9615: In a conventional Forth implementation a dest control-flow stack entry
9616: is just the target address and an orig entry is just the address to be
9617: patched. Our locals implementation adds a word list to every orig or dest
9618: item. It is the list of locals visible (or assumed visible) at the point
9619: described by the entry. Our implementation also adds a tag to identify
9620: the kind of entry, in particular to differentiate between live and dead
9621: (reachable and unreachable) orig entries.
1.26 crook 9622:
1.78 anton 9623: A few unusual operations have to be performed on locals word lists:
1.44 crook 9624:
1.5 anton 9625:
1.78 anton 9626: doc-common-list
9627: doc-sub-list?
9628: doc-list-size
1.52 anton 9629:
9630:
1.78 anton 9631: Several features of our locals word list implementation make these
9632: operations easy to implement: The locals word lists are organised as
9633: linked lists; the tails of these lists are shared, if the lists
9634: contain some of the same locals; and the address of a name is greater
9635: than the address of the names behind it in the list.
1.5 anton 9636:
1.78 anton 9637: Another important implementation detail is the variable
9638: @code{dead-code}. It is used by @code{BEGIN} and @code{THEN} to
9639: determine if they can be reached directly or only through the branch
9640: that they resolve. @code{dead-code} is set by @code{UNREACHABLE},
9641: @code{AHEAD}, @code{EXIT} etc., and cleared at the start of a colon
9642: definition, by @code{BEGIN} and usually by @code{THEN}.
1.5 anton 9643:
1.78 anton 9644: Counted loops are similar to other loops in most respects, but
9645: @code{LEAVE} requires special attention: It performs basically the same
9646: service as @code{AHEAD}, but it does not create a control-flow stack
9647: entry. Therefore the information has to be stored elsewhere;
9648: traditionally, the information was stored in the target fields of the
9649: branches created by the @code{LEAVE}s, by organizing these fields into a
9650: linked list. Unfortunately, this clever trick does not provide enough
9651: space for storing our extended control flow information. Therefore, we
9652: introduce another stack, the leave stack. It contains the control-flow
9653: stack entries for all unresolved @code{LEAVE}s.
1.44 crook 9654:
1.78 anton 9655: Local names are kept until the end of the colon definition, even if
9656: they are no longer visible in any control-flow path. In a few cases
9657: this may lead to increased space needs for the locals name area, but
9658: usually less than reclaiming this space would cost in code size.
1.5 anton 9659:
1.44 crook 9660:
1.78 anton 9661: @node ANS Forth locals, , Gforth locals, Locals
9662: @subsection ANS Forth locals
9663: @cindex locals, ANS Forth style
1.5 anton 9664:
1.78 anton 9665: The ANS Forth locals wordset does not define a syntax for locals, but
9666: words that make it possible to define various syntaxes. One of the
9667: possible syntaxes is a subset of the syntax we used in the Gforth locals
9668: wordset, i.e.:
1.29 crook 9669:
9670: @example
1.78 anton 9671: @{ local1 local2 ... -- comment @}
9672: @end example
9673: @noindent
9674: or
9675: @example
9676: @{ local1 local2 ... @}
1.29 crook 9677: @end example
9678:
1.78 anton 9679: The order of the locals corresponds to the order in a stack comment. The
9680: restrictions are:
1.5 anton 9681:
1.78 anton 9682: @itemize @bullet
9683: @item
9684: Locals can only be cell-sized values (no type specifiers are allowed).
9685: @item
9686: Locals can be defined only outside control structures.
9687: @item
9688: Locals can interfere with explicit usage of the return stack. For the
9689: exact (and long) rules, see the standard. If you don't use return stack
9690: accessing words in a definition using locals, you will be all right. The
9691: purpose of this rule is to make locals implementation on the return
9692: stack easier.
9693: @item
9694: The whole definition must be in one line.
9695: @end itemize
1.5 anton 9696:
1.78 anton 9697: Locals defined in ANS Forth behave like @code{VALUE}s
9698: (@pxref{Values}). I.e., they are initialized from the stack. Using their
9699: name produces their value. Their value can be changed using @code{TO}.
1.77 anton 9700:
1.78 anton 9701: Since the syntax above is supported by Gforth directly, you need not do
9702: anything to use it. If you want to port a program using this syntax to
9703: another ANS Forth system, use @file{compat/anslocal.fs} to implement the
9704: syntax on the other system.
1.5 anton 9705:
1.78 anton 9706: Note that a syntax shown in the standard, section A.13 looks
9707: similar, but is quite different in having the order of locals
9708: reversed. Beware!
1.5 anton 9709:
1.78 anton 9710: The ANS Forth locals wordset itself consists of one word:
1.5 anton 9711:
1.78 anton 9712: doc-(local)
1.5 anton 9713:
1.78 anton 9714: The ANS Forth locals extension wordset defines a syntax using
9715: @code{locals|}, but it is so awful that we strongly recommend not to use
9716: it. We have implemented this syntax to make porting to Gforth easy, but
9717: do not document it here. The problem with this syntax is that the locals
9718: are defined in an order reversed with respect to the standard stack
9719: comment notation, making programs harder to read, and easier to misread
9720: and miswrite. The only merit of this syntax is that it is easy to
9721: implement using the ANS Forth locals wordset.
1.53 anton 9722:
9723:
1.78 anton 9724: @c ----------------------------------------------------------
9725: @node Structures, Object-oriented Forth, Locals, Words
9726: @section Structures
9727: @cindex structures
9728: @cindex records
1.53 anton 9729:
1.78 anton 9730: This section presents the structure package that comes with Gforth. A
9731: version of the package implemented in ANS Forth is available in
9732: @file{compat/struct.fs}. This package was inspired by a posting on
9733: comp.lang.forth in 1989 (unfortunately I don't remember, by whom;
9734: possibly John Hayes). A version of this section has been published in
9735: M. Anton Ertl,
9736: @uref{http://www.complang.tuwien.ac.at/forth/objects/structs.html, Yet
9737: Another Forth Structures Package}, Forth Dimensions 19(3), pages
9738: 13--16. Marcel Hendrix provided helpful comments.
1.53 anton 9739:
1.78 anton 9740: @menu
9741: * Why explicit structure support?::
9742: * Structure Usage::
9743: * Structure Naming Convention::
9744: * Structure Implementation::
9745: * Structure Glossary::
9746: @end menu
1.55 anton 9747:
1.78 anton 9748: @node Why explicit structure support?, Structure Usage, Structures, Structures
9749: @subsection Why explicit structure support?
1.53 anton 9750:
1.78 anton 9751: @cindex address arithmetic for structures
9752: @cindex structures using address arithmetic
9753: If we want to use a structure containing several fields, we could simply
9754: reserve memory for it, and access the fields using address arithmetic
9755: (@pxref{Address arithmetic}). As an example, consider a structure with
9756: the following fields
1.57 anton 9757:
1.78 anton 9758: @table @code
9759: @item a
9760: is a float
9761: @item b
9762: is a cell
9763: @item c
9764: is a float
9765: @end table
1.57 anton 9766:
1.78 anton 9767: Given the (float-aligned) base address of the structure we get the
9768: address of the field
1.52 anton 9769:
1.78 anton 9770: @table @code
9771: @item a
9772: without doing anything further.
9773: @item b
9774: with @code{float+}
9775: @item c
9776: with @code{float+ cell+ faligned}
9777: @end table
1.52 anton 9778:
1.78 anton 9779: It is easy to see that this can become quite tiring.
1.52 anton 9780:
1.78 anton 9781: Moreover, it is not very readable, because seeing a
9782: @code{cell+} tells us neither which kind of structure is
9783: accessed nor what field is accessed; we have to somehow infer the kind
9784: of structure, and then look up in the documentation, which field of
9785: that structure corresponds to that offset.
1.53 anton 9786:
1.78 anton 9787: Finally, this kind of address arithmetic also causes maintenance
9788: troubles: If you add or delete a field somewhere in the middle of the
9789: structure, you have to find and change all computations for the fields
9790: afterwards.
1.52 anton 9791:
1.78 anton 9792: So, instead of using @code{cell+} and friends directly, how
9793: about storing the offsets in constants:
1.52 anton 9794:
1.78 anton 9795: @example
9796: 0 constant a-offset
9797: 0 float+ constant b-offset
9798: 0 float+ cell+ faligned c-offset
9799: @end example
1.64 pazsan 9800:
1.78 anton 9801: Now we can get the address of field @code{x} with @code{x-offset
9802: +}. This is much better in all respects. Of course, you still
9803: have to change all later offset definitions if you add a field. You can
9804: fix this by declaring the offsets in the following way:
1.57 anton 9805:
1.78 anton 9806: @example
9807: 0 constant a-offset
9808: a-offset float+ constant b-offset
9809: b-offset cell+ faligned constant c-offset
9810: @end example
1.57 anton 9811:
1.78 anton 9812: Since we always use the offsets with @code{+}, we could use a defining
9813: word @code{cfield} that includes the @code{+} in the action of the
9814: defined word:
1.64 pazsan 9815:
1.78 anton 9816: @example
9817: : cfield ( n "name" -- )
9818: create ,
9819: does> ( name execution: addr1 -- addr2 )
9820: @@ + ;
1.64 pazsan 9821:
1.78 anton 9822: 0 cfield a
9823: 0 a float+ cfield b
9824: 0 b cell+ faligned cfield c
9825: @end example
1.64 pazsan 9826:
1.78 anton 9827: Instead of @code{x-offset +}, we now simply write @code{x}.
1.64 pazsan 9828:
1.78 anton 9829: The structure field words now can be used quite nicely. However,
9830: their definition is still a bit cumbersome: We have to repeat the
9831: name, the information about size and alignment is distributed before
9832: and after the field definitions etc. The structure package presented
9833: here addresses these problems.
1.64 pazsan 9834:
1.78 anton 9835: @node Structure Usage, Structure Naming Convention, Why explicit structure support?, Structures
9836: @subsection Structure Usage
9837: @cindex structure usage
1.57 anton 9838:
1.78 anton 9839: @cindex @code{field} usage
9840: @cindex @code{struct} usage
9841: @cindex @code{end-struct} usage
9842: You can define a structure for a (data-less) linked list with:
1.57 anton 9843: @example
1.78 anton 9844: struct
9845: cell% field list-next
9846: end-struct list%
1.57 anton 9847: @end example
9848:
1.78 anton 9849: With the address of the list node on the stack, you can compute the
9850: address of the field that contains the address of the next node with
9851: @code{list-next}. E.g., you can determine the length of a list
9852: with:
1.57 anton 9853:
9854: @example
1.78 anton 9855: : list-length ( list -- n )
9856: \ "list" is a pointer to the first element of a linked list
9857: \ "n" is the length of the list
9858: 0 BEGIN ( list1 n1 )
9859: over
9860: WHILE ( list1 n1 )
9861: 1+ swap list-next @@ swap
9862: REPEAT
9863: nip ;
1.57 anton 9864: @end example
9865:
1.78 anton 9866: You can reserve memory for a list node in the dictionary with
9867: @code{list% %allot}, which leaves the address of the list node on the
9868: stack. For the equivalent allocation on the heap you can use @code{list%
9869: %alloc} (or, for an @code{allocate}-like stack effect (i.e., with ior),
9870: use @code{list% %allocate}). You can get the the size of a list
9871: node with @code{list% %size} and its alignment with @code{list%
9872: %alignment}.
9873:
9874: Note that in ANS Forth the body of a @code{create}d word is
9875: @code{aligned} but not necessarily @code{faligned};
9876: therefore, if you do a:
1.57 anton 9877:
9878: @example
1.78 anton 9879: create @emph{name} foo% %allot drop
1.57 anton 9880: @end example
9881:
1.78 anton 9882: @noindent
9883: then the memory alloted for @code{foo%} is guaranteed to start at the
9884: body of @code{@emph{name}} only if @code{foo%} contains only character,
9885: cell and double fields. Therefore, if your structure contains floats,
9886: better use
1.57 anton 9887:
9888: @example
1.78 anton 9889: foo% %allot constant @emph{name}
1.57 anton 9890: @end example
9891:
1.78 anton 9892: @cindex structures containing structures
9893: You can include a structure @code{foo%} as a field of
9894: another structure, like this:
1.65 anton 9895: @example
1.78 anton 9896: struct
9897: ...
9898: foo% field ...
9899: ...
9900: end-struct ...
1.65 anton 9901: @end example
1.52 anton 9902:
1.78 anton 9903: @cindex structure extension
9904: @cindex extended records
9905: Instead of starting with an empty structure, you can extend an
9906: existing structure. E.g., a plain linked list without data, as defined
9907: above, is hardly useful; You can extend it to a linked list of integers,
9908: like this:@footnote{This feature is also known as @emph{extended
9909: records}. It is the main innovation in the Oberon language; in other
9910: words, adding this feature to Modula-2 led Wirth to create a new
9911: language, write a new compiler etc. Adding this feature to Forth just
9912: required a few lines of code.}
1.52 anton 9913:
1.78 anton 9914: @example
9915: list%
9916: cell% field intlist-int
9917: end-struct intlist%
9918: @end example
1.55 anton 9919:
1.78 anton 9920: @code{intlist%} is a structure with two fields:
9921: @code{list-next} and @code{intlist-int}.
1.55 anton 9922:
1.78 anton 9923: @cindex structures containing arrays
9924: You can specify an array type containing @emph{n} elements of
9925: type @code{foo%} like this:
1.55 anton 9926:
9927: @example
1.78 anton 9928: foo% @emph{n} *
1.56 anton 9929: @end example
1.55 anton 9930:
1.78 anton 9931: You can use this array type in any place where you can use a normal
9932: type, e.g., when defining a @code{field}, or with
9933: @code{%allot}.
9934:
9935: @cindex first field optimization
9936: The first field is at the base address of a structure and the word for
9937: this field (e.g., @code{list-next}) actually does not change the address
9938: on the stack. You may be tempted to leave it away in the interest of
9939: run-time and space efficiency. This is not necessary, because the
9940: structure package optimizes this case: If you compile a first-field
9941: words, no code is generated. So, in the interest of readability and
9942: maintainability you should include the word for the field when accessing
9943: the field.
1.52 anton 9944:
9945:
1.78 anton 9946: @node Structure Naming Convention, Structure Implementation, Structure Usage, Structures
9947: @subsection Structure Naming Convention
9948: @cindex structure naming convention
1.52 anton 9949:
1.78 anton 9950: The field names that come to (my) mind are often quite generic, and,
9951: if used, would cause frequent name clashes. E.g., many structures
9952: probably contain a @code{counter} field. The structure names
9953: that come to (my) mind are often also the logical choice for the names
9954: of words that create such a structure.
1.52 anton 9955:
1.78 anton 9956: Therefore, I have adopted the following naming conventions:
1.52 anton 9957:
1.78 anton 9958: @itemize @bullet
9959: @cindex field naming convention
9960: @item
9961: The names of fields are of the form
9962: @code{@emph{struct}-@emph{field}}, where
9963: @code{@emph{struct}} is the basic name of the structure, and
9964: @code{@emph{field}} is the basic name of the field. You can
9965: think of field words as converting the (address of the)
9966: structure into the (address of the) field.
1.52 anton 9967:
1.78 anton 9968: @cindex structure naming convention
9969: @item
9970: The names of structures are of the form
9971: @code{@emph{struct}%}, where
9972: @code{@emph{struct}} is the basic name of the structure.
9973: @end itemize
1.52 anton 9974:
1.78 anton 9975: This naming convention does not work that well for fields of extended
9976: structures; e.g., the integer list structure has a field
9977: @code{intlist-int}, but has @code{list-next}, not
9978: @code{intlist-next}.
1.53 anton 9979:
1.78 anton 9980: @node Structure Implementation, Structure Glossary, Structure Naming Convention, Structures
9981: @subsection Structure Implementation
9982: @cindex structure implementation
9983: @cindex implementation of structures
1.52 anton 9984:
1.78 anton 9985: The central idea in the implementation is to pass the data about the
9986: structure being built on the stack, not in some global
9987: variable. Everything else falls into place naturally once this design
9988: decision is made.
1.53 anton 9989:
1.78 anton 9990: The type description on the stack is of the form @emph{align
9991: size}. Keeping the size on the top-of-stack makes dealing with arrays
9992: very simple.
1.53 anton 9993:
1.78 anton 9994: @code{field} is a defining word that uses @code{Create}
9995: and @code{DOES>}. The body of the field contains the offset
9996: of the field, and the normal @code{DOES>} action is simply:
1.53 anton 9997:
9998: @example
1.78 anton 9999: @@ +
1.53 anton 10000: @end example
10001:
1.78 anton 10002: @noindent
10003: i.e., add the offset to the address, giving the stack effect
10004: @i{addr1 -- addr2} for a field.
10005:
10006: @cindex first field optimization, implementation
10007: This simple structure is slightly complicated by the optimization
10008: for fields with offset 0, which requires a different
10009: @code{DOES>}-part (because we cannot rely on there being
10010: something on the stack if such a field is invoked during
10011: compilation). Therefore, we put the different @code{DOES>}-parts
10012: in separate words, and decide which one to invoke based on the
10013: offset. For a zero offset, the field is basically a noop; it is
10014: immediate, and therefore no code is generated when it is compiled.
1.53 anton 10015:
1.78 anton 10016: @node Structure Glossary, , Structure Implementation, Structures
10017: @subsection Structure Glossary
10018: @cindex structure glossary
1.53 anton 10019:
1.5 anton 10020:
1.78 anton 10021: doc-%align
10022: doc-%alignment
10023: doc-%alloc
10024: doc-%allocate
10025: doc-%allot
10026: doc-cell%
10027: doc-char%
10028: doc-dfloat%
10029: doc-double%
10030: doc-end-struct
10031: doc-field
10032: doc-float%
10033: doc-naligned
10034: doc-sfloat%
10035: doc-%size
10036: doc-struct
1.54 anton 10037:
10038:
1.26 crook 10039: @c -------------------------------------------------------------
1.78 anton 10040: @node Object-oriented Forth, Programming Tools, Structures, Words
10041: @section Object-oriented Forth
10042:
10043: Gforth comes with three packages for object-oriented programming:
10044: @file{objects.fs}, @file{oof.fs}, and @file{mini-oof.fs}; none of them
10045: is preloaded, so you have to @code{include} them before use. The most
10046: important differences between these packages (and others) are discussed
10047: in @ref{Comparison with other object models}. All packages are written
10048: in ANS Forth and can be used with any other ANS Forth.
1.5 anton 10049:
1.78 anton 10050: @menu
10051: * Why object-oriented programming?::
10052: * Object-Oriented Terminology::
10053: * Objects::
10054: * OOF::
10055: * Mini-OOF::
10056: * Comparison with other object models::
10057: @end menu
1.5 anton 10058:
1.78 anton 10059: @c ----------------------------------------------------------------
10060: @node Why object-oriented programming?, Object-Oriented Terminology, Object-oriented Forth, Object-oriented Forth
10061: @subsection Why object-oriented programming?
10062: @cindex object-oriented programming motivation
10063: @cindex motivation for object-oriented programming
1.44 crook 10064:
1.78 anton 10065: Often we have to deal with several data structures (@emph{objects}),
10066: that have to be treated similarly in some respects, but differently in
10067: others. Graphical objects are the textbook example: circles, triangles,
10068: dinosaurs, icons, and others, and we may want to add more during program
10069: development. We want to apply some operations to any graphical object,
10070: e.g., @code{draw} for displaying it on the screen. However, @code{draw}
10071: has to do something different for every kind of object.
10072: @comment TODO add some other operations eg perimeter, area
10073: @comment and tie in to concrete examples later..
1.5 anton 10074:
1.78 anton 10075: We could implement @code{draw} as a big @code{CASE}
10076: control structure that executes the appropriate code depending on the
10077: kind of object to be drawn. This would be not be very elegant, and,
10078: moreover, we would have to change @code{draw} every time we add
10079: a new kind of graphical object (say, a spaceship).
1.44 crook 10080:
1.78 anton 10081: What we would rather do is: When defining spaceships, we would tell
10082: the system: ``Here's how you @code{draw} a spaceship; you figure
10083: out the rest''.
1.5 anton 10084:
1.78 anton 10085: This is the problem that all systems solve that (rightfully) call
10086: themselves object-oriented; the object-oriented packages presented here
10087: solve this problem (and not much else).
10088: @comment TODO ?list properties of oo systems.. oo vs o-based?
1.44 crook 10089:
1.78 anton 10090: @c ------------------------------------------------------------------------
10091: @node Object-Oriented Terminology, Objects, Why object-oriented programming?, Object-oriented Forth
10092: @subsection Object-Oriented Terminology
10093: @cindex object-oriented terminology
10094: @cindex terminology for object-oriented programming
1.5 anton 10095:
1.78 anton 10096: This section is mainly for reference, so you don't have to understand
10097: all of it right away. The terminology is mainly Smalltalk-inspired. In
10098: short:
1.44 crook 10099:
1.78 anton 10100: @table @emph
10101: @cindex class
10102: @item class
10103: a data structure definition with some extras.
1.5 anton 10104:
1.78 anton 10105: @cindex object
10106: @item object
10107: an instance of the data structure described by the class definition.
1.5 anton 10108:
1.78 anton 10109: @cindex instance variables
10110: @item instance variables
10111: fields of the data structure.
1.5 anton 10112:
1.78 anton 10113: @cindex selector
10114: @cindex method selector
10115: @cindex virtual function
10116: @item selector
10117: (or @emph{method selector}) a word (e.g.,
10118: @code{draw}) that performs an operation on a variety of data
10119: structures (classes). A selector describes @emph{what} operation to
10120: perform. In C++ terminology: a (pure) virtual function.
1.5 anton 10121:
1.78 anton 10122: @cindex method
10123: @item method
10124: the concrete definition that performs the operation
10125: described by the selector for a specific class. A method specifies
10126: @emph{how} the operation is performed for a specific class.
1.5 anton 10127:
1.78 anton 10128: @cindex selector invocation
10129: @cindex message send
10130: @cindex invoking a selector
10131: @item selector invocation
10132: a call of a selector. One argument of the call (the TOS (top-of-stack))
10133: is used for determining which method is used. In Smalltalk terminology:
10134: a message (consisting of the selector and the other arguments) is sent
10135: to the object.
1.5 anton 10136:
1.78 anton 10137: @cindex receiving object
10138: @item receiving object
10139: the object used for determining the method executed by a selector
10140: invocation. In the @file{objects.fs} model, it is the object that is on
10141: the TOS when the selector is invoked. (@emph{Receiving} comes from
10142: the Smalltalk @emph{message} terminology.)
1.5 anton 10143:
1.78 anton 10144: @cindex child class
10145: @cindex parent class
10146: @cindex inheritance
10147: @item child class
10148: a class that has (@emph{inherits}) all properties (instance variables,
10149: selectors, methods) from a @emph{parent class}. In Smalltalk
10150: terminology: The subclass inherits from the superclass. In C++
10151: terminology: The derived class inherits from the base class.
1.5 anton 10152:
1.78 anton 10153: @end table
1.5 anton 10154:
1.78 anton 10155: @c If you wonder about the message sending terminology, it comes from
10156: @c a time when each object had it's own task and objects communicated via
10157: @c message passing; eventually the Smalltalk developers realized that
10158: @c they can do most things through simple (indirect) calls. They kept the
10159: @c terminology.
1.5 anton 10160:
1.78 anton 10161: @c --------------------------------------------------------------
10162: @node Objects, OOF, Object-Oriented Terminology, Object-oriented Forth
10163: @subsection The @file{objects.fs} model
10164: @cindex objects
10165: @cindex object-oriented programming
1.26 crook 10166:
1.78 anton 10167: @cindex @file{objects.fs}
10168: @cindex @file{oof.fs}
1.26 crook 10169:
1.78 anton 10170: This section describes the @file{objects.fs} package. This material also
10171: has been published in M. Anton Ertl,
10172: @cite{@uref{http://www.complang.tuwien.ac.at/forth/objects/objects.html,
10173: Yet Another Forth Objects Package}}, Forth Dimensions 19(2), pages
10174: 37--43.
10175: @c McKewan's and Zsoter's packages
1.26 crook 10176:
1.78 anton 10177: This section assumes that you have read @ref{Structures}.
1.5 anton 10178:
1.78 anton 10179: The techniques on which this model is based have been used to implement
10180: the parser generator, Gray, and have also been used in Gforth for
10181: implementing the various flavours of word lists (hashed or not,
10182: case-sensitive or not, special-purpose word lists for locals etc.).
1.5 anton 10183:
10184:
1.26 crook 10185: @menu
1.78 anton 10186: * Properties of the Objects model::
10187: * Basic Objects Usage::
10188: * The Objects base class::
10189: * Creating objects::
10190: * Object-Oriented Programming Style::
10191: * Class Binding::
10192: * Method conveniences::
10193: * Classes and Scoping::
10194: * Dividing classes::
10195: * Object Interfaces::
10196: * Objects Implementation::
10197: * Objects Glossary::
1.26 crook 10198: @end menu
1.5 anton 10199:
1.78 anton 10200: Marcel Hendrix provided helpful comments on this section.
1.5 anton 10201:
1.78 anton 10202: @node Properties of the Objects model, Basic Objects Usage, Objects, Objects
10203: @subsubsection Properties of the @file{objects.fs} model
10204: @cindex @file{objects.fs} properties
1.5 anton 10205:
1.78 anton 10206: @itemize @bullet
10207: @item
10208: It is straightforward to pass objects on the stack. Passing
10209: selectors on the stack is a little less convenient, but possible.
1.44 crook 10210:
1.78 anton 10211: @item
10212: Objects are just data structures in memory, and are referenced by their
10213: address. You can create words for objects with normal defining words
10214: like @code{constant}. Likewise, there is no difference between instance
10215: variables that contain objects and those that contain other data.
1.5 anton 10216:
1.78 anton 10217: @item
10218: Late binding is efficient and easy to use.
1.44 crook 10219:
1.78 anton 10220: @item
10221: It avoids parsing, and thus avoids problems with state-smartness
10222: and reduced extensibility; for convenience there are a few parsing
10223: words, but they have non-parsing counterparts. There are also a few
10224: defining words that parse. This is hard to avoid, because all standard
10225: defining words parse (except @code{:noname}); however, such
10226: words are not as bad as many other parsing words, because they are not
10227: state-smart.
1.5 anton 10228:
1.78 anton 10229: @item
10230: It does not try to incorporate everything. It does a few things and does
10231: them well (IMO). In particular, this model was not designed to support
10232: information hiding (although it has features that may help); you can use
10233: a separate package for achieving this.
1.5 anton 10234:
1.78 anton 10235: @item
10236: It is layered; you don't have to learn and use all features to use this
10237: model. Only a few features are necessary (@pxref{Basic Objects Usage},
10238: @pxref{The Objects base class}, @pxref{Creating objects}.), the others
10239: are optional and independent of each other.
1.5 anton 10240:
1.78 anton 10241: @item
10242: An implementation in ANS Forth is available.
1.5 anton 10243:
1.78 anton 10244: @end itemize
1.5 anton 10245:
1.44 crook 10246:
1.78 anton 10247: @node Basic Objects Usage, The Objects base class, Properties of the Objects model, Objects
10248: @subsubsection Basic @file{objects.fs} Usage
10249: @cindex basic objects usage
10250: @cindex objects, basic usage
1.5 anton 10251:
1.78 anton 10252: You can define a class for graphical objects like this:
1.44 crook 10253:
1.78 anton 10254: @cindex @code{class} usage
10255: @cindex @code{end-class} usage
10256: @cindex @code{selector} usage
1.5 anton 10257: @example
1.78 anton 10258: object class \ "object" is the parent class
10259: selector draw ( x y graphical -- )
10260: end-class graphical
10261: @end example
10262:
10263: This code defines a class @code{graphical} with an
10264: operation @code{draw}. We can perform the operation
10265: @code{draw} on any @code{graphical} object, e.g.:
10266:
10267: @example
10268: 100 100 t-rex draw
1.26 crook 10269: @end example
1.5 anton 10270:
1.78 anton 10271: @noindent
10272: where @code{t-rex} is a word (say, a constant) that produces a
10273: graphical object.
10274:
10275: @comment TODO add a 2nd operation eg perimeter.. and use for
10276: @comment a concrete example
1.5 anton 10277:
1.78 anton 10278: @cindex abstract class
10279: How do we create a graphical object? With the present definitions,
10280: we cannot create a useful graphical object. The class
10281: @code{graphical} describes graphical objects in general, but not
10282: any concrete graphical object type (C++ users would call it an
10283: @emph{abstract class}); e.g., there is no method for the selector
10284: @code{draw} in the class @code{graphical}.
1.5 anton 10285:
1.78 anton 10286: For concrete graphical objects, we define child classes of the
10287: class @code{graphical}, e.g.:
1.5 anton 10288:
1.78 anton 10289: @cindex @code{overrides} usage
10290: @cindex @code{field} usage in class definition
1.26 crook 10291: @example
1.78 anton 10292: graphical class \ "graphical" is the parent class
10293: cell% field circle-radius
1.5 anton 10294:
1.78 anton 10295: :noname ( x y circle -- )
10296: circle-radius @@ draw-circle ;
10297: overrides draw
1.5 anton 10298:
1.78 anton 10299: :noname ( n-radius circle -- )
10300: circle-radius ! ;
10301: overrides construct
1.5 anton 10302:
1.78 anton 10303: end-class circle
10304: @end example
1.44 crook 10305:
1.78 anton 10306: Here we define a class @code{circle} as a child of @code{graphical},
10307: with field @code{circle-radius} (which behaves just like a field
10308: (@pxref{Structures}); it defines (using @code{overrides}) new methods
10309: for the selectors @code{draw} and @code{construct} (@code{construct} is
10310: defined in @code{object}, the parent class of @code{graphical}).
1.5 anton 10311:
1.78 anton 10312: Now we can create a circle on the heap (i.e.,
10313: @code{allocate}d memory) with:
1.44 crook 10314:
1.78 anton 10315: @cindex @code{heap-new} usage
1.5 anton 10316: @example
1.78 anton 10317: 50 circle heap-new constant my-circle
1.5 anton 10318: @end example
10319:
1.78 anton 10320: @noindent
10321: @code{heap-new} invokes @code{construct}, thus
10322: initializing the field @code{circle-radius} with 50. We can draw
10323: this new circle at (100,100) with:
1.5 anton 10324:
10325: @example
1.78 anton 10326: 100 100 my-circle draw
1.5 anton 10327: @end example
10328:
1.78 anton 10329: @cindex selector invocation, restrictions
10330: @cindex class definition, restrictions
10331: Note: You can only invoke a selector if the object on the TOS
10332: (the receiving object) belongs to the class where the selector was
10333: defined or one of its descendents; e.g., you can invoke
10334: @code{draw} only for objects belonging to @code{graphical}
10335: or its descendents (e.g., @code{circle}). Immediately before
10336: @code{end-class}, the search order has to be the same as
10337: immediately after @code{class}.
10338:
10339: @node The Objects base class, Creating objects, Basic Objects Usage, Objects
10340: @subsubsection The @file{object.fs} base class
10341: @cindex @code{object} class
10342:
10343: When you define a class, you have to specify a parent class. So how do
10344: you start defining classes? There is one class available from the start:
10345: @code{object}. It is ancestor for all classes and so is the
10346: only class that has no parent. It has two selectors: @code{construct}
10347: and @code{print}.
10348:
10349: @node Creating objects, Object-Oriented Programming Style, The Objects base class, Objects
10350: @subsubsection Creating objects
10351: @cindex creating objects
10352: @cindex object creation
10353: @cindex object allocation options
10354:
10355: @cindex @code{heap-new} discussion
10356: @cindex @code{dict-new} discussion
10357: @cindex @code{construct} discussion
10358: You can create and initialize an object of a class on the heap with
10359: @code{heap-new} ( ... class -- object ) and in the dictionary
10360: (allocation with @code{allot}) with @code{dict-new} (
10361: ... class -- object ). Both words invoke @code{construct}, which
10362: consumes the stack items indicated by "..." above.
10363:
10364: @cindex @code{init-object} discussion
10365: @cindex @code{class-inst-size} discussion
10366: If you want to allocate memory for an object yourself, you can get its
10367: alignment and size with @code{class-inst-size 2@@} ( class --
10368: align size ). Once you have memory for an object, you can initialize
10369: it with @code{init-object} ( ... class object -- );
10370: @code{construct} does only a part of the necessary work.
10371:
10372: @node Object-Oriented Programming Style, Class Binding, Creating objects, Objects
10373: @subsubsection Object-Oriented Programming Style
10374: @cindex object-oriented programming style
10375: @cindex programming style, object-oriented
1.5 anton 10376:
1.78 anton 10377: This section is not exhaustive.
1.5 anton 10378:
1.78 anton 10379: @cindex stack effects of selectors
10380: @cindex selectors and stack effects
10381: In general, it is a good idea to ensure that all methods for the
10382: same selector have the same stack effect: when you invoke a selector,
10383: you often have no idea which method will be invoked, so, unless all
10384: methods have the same stack effect, you will not know the stack effect
10385: of the selector invocation.
1.5 anton 10386:
1.78 anton 10387: One exception to this rule is methods for the selector
10388: @code{construct}. We know which method is invoked, because we
10389: specify the class to be constructed at the same place. Actually, I
10390: defined @code{construct} as a selector only to give the users a
10391: convenient way to specify initialization. The way it is used, a
10392: mechanism different from selector invocation would be more natural
10393: (but probably would take more code and more space to explain).
1.5 anton 10394:
1.78 anton 10395: @node Class Binding, Method conveniences, Object-Oriented Programming Style, Objects
10396: @subsubsection Class Binding
10397: @cindex class binding
10398: @cindex early binding
1.5 anton 10399:
1.78 anton 10400: @cindex late binding
10401: Normal selector invocations determine the method at run-time depending
10402: on the class of the receiving object. This run-time selection is called
10403: @i{late binding}.
1.5 anton 10404:
1.78 anton 10405: Sometimes it's preferable to invoke a different method. For example,
10406: you might want to use the simple method for @code{print}ing
10407: @code{object}s instead of the possibly long-winded @code{print} method
10408: of the receiver class. You can achieve this by replacing the invocation
10409: of @code{print} with:
1.5 anton 10410:
1.78 anton 10411: @cindex @code{[bind]} usage
1.5 anton 10412: @example
1.78 anton 10413: [bind] object print
1.5 anton 10414: @end example
10415:
1.78 anton 10416: @noindent
10417: in compiled code or:
10418:
10419: @cindex @code{bind} usage
1.5 anton 10420: @example
1.78 anton 10421: bind object print
1.5 anton 10422: @end example
10423:
1.78 anton 10424: @cindex class binding, alternative to
10425: @noindent
10426: in interpreted code. Alternatively, you can define the method with a
10427: name (e.g., @code{print-object}), and then invoke it through the
10428: name. Class binding is just a (often more convenient) way to achieve
10429: the same effect; it avoids name clutter and allows you to invoke
10430: methods directly without naming them first.
1.5 anton 10431:
1.78 anton 10432: @cindex superclass binding
10433: @cindex parent class binding
10434: A frequent use of class binding is this: When we define a method
10435: for a selector, we often want the method to do what the selector does
10436: in the parent class, and a little more. There is a special word for
10437: this purpose: @code{[parent]}; @code{[parent]
10438: @emph{selector}} is equivalent to @code{[bind] @emph{parent
10439: selector}}, where @code{@emph{parent}} is the parent
10440: class of the current class. E.g., a method definition might look like:
1.44 crook 10441:
1.78 anton 10442: @cindex @code{[parent]} usage
10443: @example
10444: :noname
10445: dup [parent] foo \ do parent's foo on the receiving object
10446: ... \ do some more
10447: ; overrides foo
10448: @end example
1.6 pazsan 10449:
1.78 anton 10450: @cindex class binding as optimization
10451: In @cite{Object-oriented programming in ANS Forth} (Forth Dimensions,
10452: March 1997), Andrew McKewan presents class binding as an optimization
10453: technique. I recommend not using it for this purpose unless you are in
10454: an emergency. Late binding is pretty fast with this model anyway, so the
10455: benefit of using class binding is small; the cost of using class binding
10456: where it is not appropriate is reduced maintainability.
1.44 crook 10457:
1.78 anton 10458: While we are at programming style questions: You should bind
10459: selectors only to ancestor classes of the receiving object. E.g., say,
10460: you know that the receiving object is of class @code{foo} or its
10461: descendents; then you should bind only to @code{foo} and its
10462: ancestors.
1.12 anton 10463:
1.78 anton 10464: @node Method conveniences, Classes and Scoping, Class Binding, Objects
10465: @subsubsection Method conveniences
10466: @cindex method conveniences
1.44 crook 10467:
1.78 anton 10468: In a method you usually access the receiving object pretty often. If
10469: you define the method as a plain colon definition (e.g., with
10470: @code{:noname}), you may have to do a lot of stack
10471: gymnastics. To avoid this, you can define the method with @code{m:
10472: ... ;m}. E.g., you could define the method for
10473: @code{draw}ing a @code{circle} with
1.6 pazsan 10474:
1.78 anton 10475: @cindex @code{this} usage
10476: @cindex @code{m:} usage
10477: @cindex @code{;m} usage
10478: @example
10479: m: ( x y circle -- )
10480: ( x y ) this circle-radius @@ draw-circle ;m
10481: @end example
1.6 pazsan 10482:
1.78 anton 10483: @cindex @code{exit} in @code{m: ... ;m}
10484: @cindex @code{exitm} discussion
10485: @cindex @code{catch} in @code{m: ... ;m}
10486: When this method is executed, the receiver object is removed from the
10487: stack; you can access it with @code{this} (admittedly, in this
10488: example the use of @code{m: ... ;m} offers no advantage). Note
10489: that I specify the stack effect for the whole method (i.e. including
10490: the receiver object), not just for the code between @code{m:}
10491: and @code{;m}. You cannot use @code{exit} in
10492: @code{m:...;m}; instead, use
10493: @code{exitm}.@footnote{Moreover, for any word that calls
10494: @code{catch} and was defined before loading
10495: @code{objects.fs}, you have to redefine it like I redefined
10496: @code{catch}: @code{: catch this >r catch r> to-this ;}}
1.12 anton 10497:
1.78 anton 10498: @cindex @code{inst-var} usage
10499: You will frequently use sequences of the form @code{this
10500: @emph{field}} (in the example above: @code{this
10501: circle-radius}). If you use the field only in this way, you can
10502: define it with @code{inst-var} and eliminate the
10503: @code{this} before the field name. E.g., the @code{circle}
10504: class above could also be defined with:
1.6 pazsan 10505:
1.78 anton 10506: @example
10507: graphical class
10508: cell% inst-var radius
1.6 pazsan 10509:
1.78 anton 10510: m: ( x y circle -- )
10511: radius @@ draw-circle ;m
10512: overrides draw
1.6 pazsan 10513:
1.78 anton 10514: m: ( n-radius circle -- )
10515: radius ! ;m
10516: overrides construct
1.6 pazsan 10517:
1.78 anton 10518: end-class circle
10519: @end example
1.6 pazsan 10520:
1.78 anton 10521: @code{radius} can only be used in @code{circle} and its
10522: descendent classes and inside @code{m:...;m}.
1.6 pazsan 10523:
1.78 anton 10524: @cindex @code{inst-value} usage
10525: You can also define fields with @code{inst-value}, which is
10526: to @code{inst-var} what @code{value} is to
10527: @code{variable}. You can change the value of such a field with
10528: @code{[to-inst]}. E.g., we could also define the class
10529: @code{circle} like this:
1.44 crook 10530:
1.78 anton 10531: @example
10532: graphical class
10533: inst-value radius
1.6 pazsan 10534:
1.78 anton 10535: m: ( x y circle -- )
10536: radius draw-circle ;m
10537: overrides draw
1.44 crook 10538:
1.78 anton 10539: m: ( n-radius circle -- )
10540: [to-inst] radius ;m
10541: overrides construct
1.6 pazsan 10542:
1.78 anton 10543: end-class circle
10544: @end example
1.6 pazsan 10545:
1.78 anton 10546: @c !! :m is easy to confuse with m:. Another name would be better.
1.6 pazsan 10547:
1.78 anton 10548: @c Finally, you can define named methods with @code{:m}. One use of this
10549: @c feature is the definition of words that occur only in one class and are
10550: @c not intended to be overridden, but which still need method context
10551: @c (e.g., for accessing @code{inst-var}s). Another use is for methods that
10552: @c would be bound frequently, if defined anonymously.
1.6 pazsan 10553:
10554:
1.78 anton 10555: @node Classes and Scoping, Dividing classes, Method conveniences, Objects
10556: @subsubsection Classes and Scoping
10557: @cindex classes and scoping
10558: @cindex scoping and classes
1.6 pazsan 10559:
1.78 anton 10560: Inheritance is frequent, unlike structure extension. This exacerbates
10561: the problem with the field name convention (@pxref{Structure Naming
10562: Convention}): One always has to remember in which class the field was
10563: originally defined; changing a part of the class structure would require
10564: changes for renaming in otherwise unaffected code.
1.6 pazsan 10565:
1.78 anton 10566: @cindex @code{inst-var} visibility
10567: @cindex @code{inst-value} visibility
10568: To solve this problem, I added a scoping mechanism (which was not in my
10569: original charter): A field defined with @code{inst-var} (or
10570: @code{inst-value}) is visible only in the class where it is defined and in
10571: the descendent classes of this class. Using such fields only makes
10572: sense in @code{m:}-defined methods in these classes anyway.
1.6 pazsan 10573:
1.78 anton 10574: This scoping mechanism allows us to use the unadorned field name,
10575: because name clashes with unrelated words become much less likely.
1.6 pazsan 10576:
1.78 anton 10577: @cindex @code{protected} discussion
10578: @cindex @code{private} discussion
10579: Once we have this mechanism, we can also use it for controlling the
10580: visibility of other words: All words defined after
10581: @code{protected} are visible only in the current class and its
10582: descendents. @code{public} restores the compilation
10583: (i.e. @code{current}) word list that was in effect before. If you
10584: have several @code{protected}s without an intervening
10585: @code{public} or @code{set-current}, @code{public}
10586: will restore the compilation word list in effect before the first of
10587: these @code{protected}s.
1.6 pazsan 10588:
1.78 anton 10589: @node Dividing classes, Object Interfaces, Classes and Scoping, Objects
10590: @subsubsection Dividing classes
10591: @cindex Dividing classes
10592: @cindex @code{methods}...@code{end-methods}
1.6 pazsan 10593:
1.78 anton 10594: You may want to do the definition of methods separate from the
10595: definition of the class, its selectors, fields, and instance variables,
10596: i.e., separate the implementation from the definition. You can do this
10597: in the following way:
1.6 pazsan 10598:
1.78 anton 10599: @example
10600: graphical class
10601: inst-value radius
10602: end-class circle
1.6 pazsan 10603:
1.78 anton 10604: ... \ do some other stuff
1.6 pazsan 10605:
1.78 anton 10606: circle methods \ now we are ready
1.44 crook 10607:
1.78 anton 10608: m: ( x y circle -- )
10609: radius draw-circle ;m
10610: overrides draw
1.6 pazsan 10611:
1.78 anton 10612: m: ( n-radius circle -- )
10613: [to-inst] radius ;m
10614: overrides construct
1.44 crook 10615:
1.78 anton 10616: end-methods
10617: @end example
1.7 pazsan 10618:
1.78 anton 10619: You can use several @code{methods}...@code{end-methods} sections. The
10620: only things you can do to the class in these sections are: defining
10621: methods, and overriding the class's selectors. You must not define new
10622: selectors or fields.
1.7 pazsan 10623:
1.78 anton 10624: Note that you often have to override a selector before using it. In
10625: particular, you usually have to override @code{construct} with a new
10626: method before you can invoke @code{heap-new} and friends. E.g., you
10627: must not create a circle before the @code{overrides construct} sequence
10628: in the example above.
1.7 pazsan 10629:
1.78 anton 10630: @node Object Interfaces, Objects Implementation, Dividing classes, Objects
10631: @subsubsection Object Interfaces
10632: @cindex object interfaces
10633: @cindex interfaces for objects
1.7 pazsan 10634:
1.78 anton 10635: In this model you can only call selectors defined in the class of the
10636: receiving objects or in one of its ancestors. If you call a selector
10637: with a receiving object that is not in one of these classes, the
10638: result is undefined; if you are lucky, the program crashes
10639: immediately.
1.7 pazsan 10640:
1.78 anton 10641: @cindex selectors common to hardly-related classes
10642: Now consider the case when you want to have a selector (or several)
10643: available in two classes: You would have to add the selector to a
10644: common ancestor class, in the worst case to @code{object}. You
10645: may not want to do this, e.g., because someone else is responsible for
10646: this ancestor class.
1.7 pazsan 10647:
1.78 anton 10648: The solution for this problem is interfaces. An interface is a
10649: collection of selectors. If a class implements an interface, the
10650: selectors become available to the class and its descendents. A class
10651: can implement an unlimited number of interfaces. For the problem
10652: discussed above, we would define an interface for the selector(s), and
10653: both classes would implement the interface.
1.7 pazsan 10654:
1.78 anton 10655: As an example, consider an interface @code{storage} for
10656: writing objects to disk and getting them back, and a class
10657: @code{foo} that implements it. The code would look like this:
1.7 pazsan 10658:
1.78 anton 10659: @cindex @code{interface} usage
10660: @cindex @code{end-interface} usage
10661: @cindex @code{implementation} usage
10662: @example
10663: interface
10664: selector write ( file object -- )
10665: selector read1 ( file object -- )
10666: end-interface storage
1.13 pazsan 10667:
1.78 anton 10668: bar class
10669: storage implementation
1.13 pazsan 10670:
1.78 anton 10671: ... overrides write
10672: ... overrides read1
10673: ...
10674: end-class foo
10675: @end example
1.13 pazsan 10676:
1.78 anton 10677: @noindent
10678: (I would add a word @code{read} @i{( file -- object )} that uses
10679: @code{read1} internally, but that's beyond the point illustrated
10680: here.)
1.13 pazsan 10681:
1.78 anton 10682: Note that you cannot use @code{protected} in an interface; and
10683: of course you cannot define fields.
1.13 pazsan 10684:
1.78 anton 10685: In the Neon model, all selectors are available for all classes;
10686: therefore it does not need interfaces. The price you pay in this model
10687: is slower late binding, and therefore, added complexity to avoid late
10688: binding.
1.13 pazsan 10689:
1.78 anton 10690: @node Objects Implementation, Objects Glossary, Object Interfaces, Objects
10691: @subsubsection @file{objects.fs} Implementation
10692: @cindex @file{objects.fs} implementation
1.13 pazsan 10693:
1.78 anton 10694: @cindex @code{object-map} discussion
10695: An object is a piece of memory, like one of the data structures
10696: described with @code{struct...end-struct}. It has a field
10697: @code{object-map} that points to the method map for the object's
10698: class.
1.13 pazsan 10699:
1.78 anton 10700: @cindex method map
10701: @cindex virtual function table
10702: The @emph{method map}@footnote{This is Self terminology; in C++
10703: terminology: virtual function table.} is an array that contains the
10704: execution tokens (@i{xt}s) of the methods for the object's class. Each
10705: selector contains an offset into a method map.
1.13 pazsan 10706:
1.78 anton 10707: @cindex @code{selector} implementation, class
10708: @code{selector} is a defining word that uses
10709: @code{CREATE} and @code{DOES>}. The body of the
10710: selector contains the offset; the @code{DOES>} action for a
10711: class selector is, basically:
1.8 pazsan 10712:
10713: @example
1.78 anton 10714: ( object addr ) @@ over object-map @@ + @@ execute
1.13 pazsan 10715: @end example
10716:
1.78 anton 10717: Since @code{object-map} is the first field of the object, it
10718: does not generate any code. As you can see, calling a selector has a
10719: small, constant cost.
1.26 crook 10720:
1.78 anton 10721: @cindex @code{current-interface} discussion
10722: @cindex class implementation and representation
10723: A class is basically a @code{struct} combined with a method
10724: map. During the class definition the alignment and size of the class
10725: are passed on the stack, just as with @code{struct}s, so
10726: @code{field} can also be used for defining class
10727: fields. However, passing more items on the stack would be
10728: inconvenient, so @code{class} builds a data structure in memory,
10729: which is accessed through the variable
10730: @code{current-interface}. After its definition is complete, the
10731: class is represented on the stack by a pointer (e.g., as parameter for
10732: a child class definition).
1.26 crook 10733:
1.78 anton 10734: A new class starts off with the alignment and size of its parent,
10735: and a copy of the parent's method map. Defining new fields extends the
10736: size and alignment; likewise, defining new selectors extends the
10737: method map. @code{overrides} just stores a new @i{xt} in the method
10738: map at the offset given by the selector.
1.13 pazsan 10739:
1.78 anton 10740: @cindex class binding, implementation
10741: Class binding just gets the @i{xt} at the offset given by the selector
10742: from the class's method map and @code{compile,}s (in the case of
10743: @code{[bind]}) it.
1.13 pazsan 10744:
1.78 anton 10745: @cindex @code{this} implementation
10746: @cindex @code{catch} and @code{this}
10747: @cindex @code{this} and @code{catch}
10748: I implemented @code{this} as a @code{value}. At the
10749: start of an @code{m:...;m} method the old @code{this} is
10750: stored to the return stack and restored at the end; and the object on
10751: the TOS is stored @code{TO this}. This technique has one
10752: disadvantage: If the user does not leave the method via
10753: @code{;m}, but via @code{throw} or @code{exit},
10754: @code{this} is not restored (and @code{exit} may
10755: crash). To deal with the @code{throw} problem, I have redefined
10756: @code{catch} to save and restore @code{this}; the same
10757: should be done with any word that can catch an exception. As for
10758: @code{exit}, I simply forbid it (as a replacement, there is
10759: @code{exitm}).
1.13 pazsan 10760:
1.78 anton 10761: @cindex @code{inst-var} implementation
10762: @code{inst-var} is just the same as @code{field}, with
10763: a different @code{DOES>} action:
1.13 pazsan 10764: @example
1.78 anton 10765: @@ this +
1.8 pazsan 10766: @end example
1.78 anton 10767: Similar for @code{inst-value}.
1.8 pazsan 10768:
1.78 anton 10769: @cindex class scoping implementation
10770: Each class also has a word list that contains the words defined with
10771: @code{inst-var} and @code{inst-value}, and its protected
10772: words. It also has a pointer to its parent. @code{class} pushes
10773: the word lists of the class and all its ancestors onto the search order stack,
10774: and @code{end-class} drops them.
1.20 pazsan 10775:
1.78 anton 10776: @cindex interface implementation
10777: An interface is like a class without fields, parent and protected
10778: words; i.e., it just has a method map. If a class implements an
10779: interface, its method map contains a pointer to the method map of the
10780: interface. The positive offsets in the map are reserved for class
10781: methods, therefore interface map pointers have negative
10782: offsets. Interfaces have offsets that are unique throughout the
10783: system, unlike class selectors, whose offsets are only unique for the
10784: classes where the selector is available (invokable).
1.20 pazsan 10785:
1.78 anton 10786: This structure means that interface selectors have to perform one
10787: indirection more than class selectors to find their method. Their body
10788: contains the interface map pointer offset in the class method map, and
10789: the method offset in the interface method map. The
10790: @code{does>} action for an interface selector is, basically:
1.20 pazsan 10791:
10792: @example
1.78 anton 10793: ( object selector-body )
10794: 2dup selector-interface @@ ( object selector-body object interface-offset )
10795: swap object-map @@ + @@ ( object selector-body map )
10796: swap selector-offset @@ + @@ execute
1.20 pazsan 10797: @end example
10798:
1.78 anton 10799: where @code{object-map} and @code{selector-offset} are
10800: first fields and generate no code.
1.20 pazsan 10801:
1.78 anton 10802: As a concrete example, consider the following code:
1.20 pazsan 10803:
10804: @example
1.78 anton 10805: interface
10806: selector if1sel1
10807: selector if1sel2
10808: end-interface if1
1.20 pazsan 10809:
1.78 anton 10810: object class
10811: if1 implementation
10812: selector cl1sel1
10813: cell% inst-var cl1iv1
1.20 pazsan 10814:
1.78 anton 10815: ' m1 overrides construct
10816: ' m2 overrides if1sel1
10817: ' m3 overrides if1sel2
10818: ' m4 overrides cl1sel2
10819: end-class cl1
1.20 pazsan 10820:
1.78 anton 10821: create obj1 object dict-new drop
10822: create obj2 cl1 dict-new drop
10823: @end example
1.20 pazsan 10824:
1.78 anton 10825: The data structure created by this code (including the data structure
10826: for @code{object}) is shown in the
10827: @uref{objects-implementation.eps,figure}, assuming a cell size of 4.
10828: @comment TODO add this diagram..
1.20 pazsan 10829:
1.78 anton 10830: @node Objects Glossary, , Objects Implementation, Objects
10831: @subsubsection @file{objects.fs} Glossary
10832: @cindex @file{objects.fs} Glossary
1.20 pazsan 10833:
10834:
1.78 anton 10835: doc---objects-bind
10836: doc---objects-<bind>
10837: doc---objects-bind'
10838: doc---objects-[bind]
10839: doc---objects-class
10840: doc---objects-class->map
10841: doc---objects-class-inst-size
10842: doc---objects-class-override!
1.79 anton 10843: doc---objects-class-previous
10844: doc---objects-class>order
1.78 anton 10845: doc---objects-construct
10846: doc---objects-current'
10847: doc---objects-[current]
10848: doc---objects-current-interface
10849: doc---objects-dict-new
10850: doc---objects-end-class
10851: doc---objects-end-class-noname
10852: doc---objects-end-interface
10853: doc---objects-end-interface-noname
10854: doc---objects-end-methods
10855: doc---objects-exitm
10856: doc---objects-heap-new
10857: doc---objects-implementation
10858: doc---objects-init-object
10859: doc---objects-inst-value
10860: doc---objects-inst-var
10861: doc---objects-interface
10862: doc---objects-m:
10863: doc---objects-:m
10864: doc---objects-;m
10865: doc---objects-method
10866: doc---objects-methods
10867: doc---objects-object
10868: doc---objects-overrides
10869: doc---objects-[parent]
10870: doc---objects-print
10871: doc---objects-protected
10872: doc---objects-public
10873: doc---objects-selector
10874: doc---objects-this
10875: doc---objects-<to-inst>
10876: doc---objects-[to-inst]
10877: doc---objects-to-this
10878: doc---objects-xt-new
1.20 pazsan 10879:
10880:
1.78 anton 10881: @c -------------------------------------------------------------
10882: @node OOF, Mini-OOF, Objects, Object-oriented Forth
10883: @subsection The @file{oof.fs} model
10884: @cindex oof
10885: @cindex object-oriented programming
1.20 pazsan 10886:
1.78 anton 10887: @cindex @file{objects.fs}
10888: @cindex @file{oof.fs}
1.20 pazsan 10889:
1.78 anton 10890: This section describes the @file{oof.fs} package.
1.20 pazsan 10891:
1.78 anton 10892: The package described in this section has been used in bigFORTH since 1991, and
10893: used for two large applications: a chromatographic system used to
10894: create new medicaments, and a graphic user interface library (MINOS).
1.20 pazsan 10895:
1.78 anton 10896: You can find a description (in German) of @file{oof.fs} in @cite{Object
10897: oriented bigFORTH} by Bernd Paysan, published in @cite{Vierte Dimension}
10898: 10(2), 1994.
1.20 pazsan 10899:
1.78 anton 10900: @menu
10901: * Properties of the OOF model::
10902: * Basic OOF Usage::
10903: * The OOF base class::
10904: * Class Declaration::
10905: * Class Implementation::
10906: @end menu
1.20 pazsan 10907:
1.78 anton 10908: @node Properties of the OOF model, Basic OOF Usage, OOF, OOF
10909: @subsubsection Properties of the @file{oof.fs} model
10910: @cindex @file{oof.fs} properties
1.20 pazsan 10911:
1.78 anton 10912: @itemize @bullet
10913: @item
10914: This model combines object oriented programming with information
10915: hiding. It helps you writing large application, where scoping is
10916: necessary, because it provides class-oriented scoping.
1.20 pazsan 10917:
1.78 anton 10918: @item
10919: Named objects, object pointers, and object arrays can be created,
10920: selector invocation uses the ``object selector'' syntax. Selector invocation
10921: to objects and/or selectors on the stack is a bit less convenient, but
10922: possible.
1.44 crook 10923:
1.78 anton 10924: @item
10925: Selector invocation and instance variable usage of the active object is
10926: straightforward, since both make use of the active object.
1.44 crook 10927:
1.78 anton 10928: @item
10929: Late binding is efficient and easy to use.
1.20 pazsan 10930:
1.78 anton 10931: @item
10932: State-smart objects parse selectors. However, extensibility is provided
10933: using a (parsing) selector @code{postpone} and a selector @code{'}.
1.20 pazsan 10934:
1.78 anton 10935: @item
10936: An implementation in ANS Forth is available.
1.20 pazsan 10937:
1.78 anton 10938: @end itemize
1.23 crook 10939:
10940:
1.78 anton 10941: @node Basic OOF Usage, The OOF base class, Properties of the OOF model, OOF
10942: @subsubsection Basic @file{oof.fs} Usage
10943: @cindex @file{oof.fs} usage
1.23 crook 10944:
1.78 anton 10945: This section uses the same example as for @code{objects} (@pxref{Basic Objects Usage}).
1.23 crook 10946:
1.78 anton 10947: You can define a class for graphical objects like this:
1.23 crook 10948:
1.78 anton 10949: @cindex @code{class} usage
10950: @cindex @code{class;} usage
10951: @cindex @code{method} usage
10952: @example
10953: object class graphical \ "object" is the parent class
10954: method draw ( x y graphical -- )
10955: class;
10956: @end example
1.23 crook 10957:
1.78 anton 10958: This code defines a class @code{graphical} with an
10959: operation @code{draw}. We can perform the operation
10960: @code{draw} on any @code{graphical} object, e.g.:
1.23 crook 10961:
1.78 anton 10962: @example
10963: 100 100 t-rex draw
10964: @end example
1.23 crook 10965:
1.78 anton 10966: @noindent
10967: where @code{t-rex} is an object or object pointer, created with e.g.
10968: @code{graphical : t-rex}.
1.23 crook 10969:
1.78 anton 10970: @cindex abstract class
10971: How do we create a graphical object? With the present definitions,
10972: we cannot create a useful graphical object. The class
10973: @code{graphical} describes graphical objects in general, but not
10974: any concrete graphical object type (C++ users would call it an
10975: @emph{abstract class}); e.g., there is no method for the selector
10976: @code{draw} in the class @code{graphical}.
1.23 crook 10977:
1.78 anton 10978: For concrete graphical objects, we define child classes of the
10979: class @code{graphical}, e.g.:
1.23 crook 10980:
1.78 anton 10981: @example
10982: graphical class circle \ "graphical" is the parent class
10983: cell var circle-radius
10984: how:
10985: : draw ( x y -- )
10986: circle-radius @@ draw-circle ;
1.23 crook 10987:
1.78 anton 10988: : init ( n-radius -- (
10989: circle-radius ! ;
10990: class;
10991: @end example
1.1 anton 10992:
1.78 anton 10993: Here we define a class @code{circle} as a child of @code{graphical},
10994: with a field @code{circle-radius}; it defines new methods for the
10995: selectors @code{draw} and @code{init} (@code{init} is defined in
10996: @code{object}, the parent class of @code{graphical}).
1.1 anton 10997:
1.78 anton 10998: Now we can create a circle in the dictionary with:
1.1 anton 10999:
1.78 anton 11000: @example
11001: 50 circle : my-circle
11002: @end example
1.21 crook 11003:
1.78 anton 11004: @noindent
11005: @code{:} invokes @code{init}, thus initializing the field
11006: @code{circle-radius} with 50. We can draw this new circle at (100,100)
11007: with:
1.1 anton 11008:
1.78 anton 11009: @example
11010: 100 100 my-circle draw
11011: @end example
1.1 anton 11012:
1.78 anton 11013: @cindex selector invocation, restrictions
11014: @cindex class definition, restrictions
11015: Note: You can only invoke a selector if the receiving object belongs to
11016: the class where the selector was defined or one of its descendents;
11017: e.g., you can invoke @code{draw} only for objects belonging to
11018: @code{graphical} or its descendents (e.g., @code{circle}). The scoping
11019: mechanism will check if you try to invoke a selector that is not
11020: defined in this class hierarchy, so you'll get an error at compilation
11021: time.
1.1 anton 11022:
11023:
1.78 anton 11024: @node The OOF base class, Class Declaration, Basic OOF Usage, OOF
11025: @subsubsection The @file{oof.fs} base class
11026: @cindex @file{oof.fs} base class
1.1 anton 11027:
1.78 anton 11028: When you define a class, you have to specify a parent class. So how do
11029: you start defining classes? There is one class available from the start:
11030: @code{object}. You have to use it as ancestor for all classes. It is the
11031: only class that has no parent. Classes are also objects, except that
11032: they don't have instance variables; class manipulation such as
11033: inheritance or changing definitions of a class is handled through
11034: selectors of the class @code{object}.
1.1 anton 11035:
1.78 anton 11036: @code{object} provides a number of selectors:
1.1 anton 11037:
1.78 anton 11038: @itemize @bullet
11039: @item
11040: @code{class} for subclassing, @code{definitions} to add definitions
11041: later on, and @code{class?} to get type informations (is the class a
11042: subclass of the class passed on the stack?).
1.1 anton 11043:
1.78 anton 11044: doc---object-class
11045: doc---object-definitions
11046: doc---object-class?
1.1 anton 11047:
11048:
1.26 crook 11049: @item
1.78 anton 11050: @code{init} and @code{dispose} as constructor and destructor of the
11051: object. @code{init} is invocated after the object's memory is allocated,
11052: while @code{dispose} also handles deallocation. Thus if you redefine
11053: @code{dispose}, you have to call the parent's dispose with @code{super
11054: dispose}, too.
11055:
11056: doc---object-init
11057: doc---object-dispose
11058:
1.1 anton 11059:
1.26 crook 11060: @item
1.78 anton 11061: @code{new}, @code{new[]}, @code{:}, @code{ptr}, @code{asptr}, and
11062: @code{[]} to create named and unnamed objects and object arrays or
11063: object pointers.
11064:
11065: doc---object-new
11066: doc---object-new[]
11067: doc---object-:
11068: doc---object-ptr
11069: doc---object-asptr
11070: doc---object-[]
11071:
1.1 anton 11072:
1.26 crook 11073: @item
1.78 anton 11074: @code{::} and @code{super} for explicit scoping. You should use explicit
11075: scoping only for super classes or classes with the same set of instance
11076: variables. Explicitly-scoped selectors use early binding.
1.21 crook 11077:
1.78 anton 11078: doc---object-::
11079: doc---object-super
1.21 crook 11080:
11081:
1.26 crook 11082: @item
1.78 anton 11083: @code{self} to get the address of the object
1.21 crook 11084:
1.78 anton 11085: doc---object-self
1.21 crook 11086:
11087:
1.78 anton 11088: @item
11089: @code{bind}, @code{bound}, @code{link}, and @code{is} to assign object
11090: pointers and instance defers.
1.21 crook 11091:
1.78 anton 11092: doc---object-bind
11093: doc---object-bound
11094: doc---object-link
11095: doc---object-is
1.21 crook 11096:
11097:
1.78 anton 11098: @item
11099: @code{'} to obtain selector tokens, @code{send} to invocate selectors
11100: form the stack, and @code{postpone} to generate selector invocation code.
1.21 crook 11101:
1.78 anton 11102: doc---object-'
11103: doc---object-postpone
1.21 crook 11104:
11105:
1.78 anton 11106: @item
11107: @code{with} and @code{endwith} to select the active object from the
11108: stack, and enable its scope. Using @code{with} and @code{endwith}
11109: also allows you to create code using selector @code{postpone} without being
11110: trapped by the state-smart objects.
1.21 crook 11111:
1.78 anton 11112: doc---object-with
11113: doc---object-endwith
1.21 crook 11114:
11115:
1.78 anton 11116: @end itemize
1.21 crook 11117:
1.78 anton 11118: @node Class Declaration, Class Implementation, The OOF base class, OOF
11119: @subsubsection Class Declaration
11120: @cindex class declaration
1.21 crook 11121:
1.78 anton 11122: @itemize @bullet
11123: @item
11124: Instance variables
1.21 crook 11125:
1.78 anton 11126: doc---oof-var
1.21 crook 11127:
11128:
1.78 anton 11129: @item
11130: Object pointers
1.21 crook 11131:
1.78 anton 11132: doc---oof-ptr
11133: doc---oof-asptr
1.21 crook 11134:
11135:
1.78 anton 11136: @item
11137: Instance defers
1.21 crook 11138:
1.78 anton 11139: doc---oof-defer
1.21 crook 11140:
11141:
1.78 anton 11142: @item
11143: Method selectors
1.21 crook 11144:
1.78 anton 11145: doc---oof-early
11146: doc---oof-method
1.21 crook 11147:
11148:
1.78 anton 11149: @item
11150: Class-wide variables
1.21 crook 11151:
1.78 anton 11152: doc---oof-static
1.21 crook 11153:
11154:
1.78 anton 11155: @item
11156: End declaration
1.1 anton 11157:
1.78 anton 11158: doc---oof-how:
11159: doc---oof-class;
1.21 crook 11160:
11161:
1.78 anton 11162: @end itemize
1.21 crook 11163:
1.78 anton 11164: @c -------------------------------------------------------------
11165: @node Class Implementation, , Class Declaration, OOF
11166: @subsubsection Class Implementation
11167: @cindex class implementation
1.21 crook 11168:
1.78 anton 11169: @c -------------------------------------------------------------
11170: @node Mini-OOF, Comparison with other object models, OOF, Object-oriented Forth
11171: @subsection The @file{mini-oof.fs} model
11172: @cindex mini-oof
1.21 crook 11173:
1.78 anton 11174: Gforth's third object oriented Forth package is a 12-liner. It uses a
1.79 anton 11175: mixture of the @file{objects.fs} and the @file{oof.fs} syntax,
1.78 anton 11176: and reduces to the bare minimum of features. This is based on a posting
11177: of Bernd Paysan in comp.lang.forth.
1.21 crook 11178:
1.78 anton 11179: @menu
11180: * Basic Mini-OOF Usage::
11181: * Mini-OOF Example::
11182: * Mini-OOF Implementation::
11183: @end menu
1.21 crook 11184:
1.78 anton 11185: @c -------------------------------------------------------------
11186: @node Basic Mini-OOF Usage, Mini-OOF Example, Mini-OOF, Mini-OOF
11187: @subsubsection Basic @file{mini-oof.fs} Usage
11188: @cindex mini-oof usage
1.21 crook 11189:
1.78 anton 11190: There is a base class (@code{class}, which allocates one cell for the
11191: object pointer) plus seven other words: to define a method, a variable,
11192: a class; to end a class, to resolve binding, to allocate an object and
11193: to compile a class method.
11194: @comment TODO better description of the last one
1.26 crook 11195:
1.21 crook 11196:
1.78 anton 11197: doc-object
11198: doc-method
11199: doc-var
11200: doc-class
11201: doc-end-class
11202: doc-defines
11203: doc-new
11204: doc-::
1.21 crook 11205:
11206:
11207:
1.78 anton 11208: @c -------------------------------------------------------------
11209: @node Mini-OOF Example, Mini-OOF Implementation, Basic Mini-OOF Usage, Mini-OOF
11210: @subsubsection Mini-OOF Example
11211: @cindex mini-oof example
1.1 anton 11212:
1.78 anton 11213: A short example shows how to use this package. This example, in slightly
11214: extended form, is supplied as @file{moof-exm.fs}
11215: @comment TODO could flesh this out with some comments from the Forthwrite article
1.20 pazsan 11216:
1.26 crook 11217: @example
1.78 anton 11218: object class
11219: method init
11220: method draw
11221: end-class graphical
1.26 crook 11222: @end example
1.20 pazsan 11223:
1.78 anton 11224: This code defines a class @code{graphical} with an
11225: operation @code{draw}. We can perform the operation
11226: @code{draw} on any @code{graphical} object, e.g.:
1.20 pazsan 11227:
1.26 crook 11228: @example
1.78 anton 11229: 100 100 t-rex draw
1.26 crook 11230: @end example
1.12 anton 11231:
1.78 anton 11232: where @code{t-rex} is an object or object pointer, created with e.g.
11233: @code{graphical new Constant t-rex}.
1.12 anton 11234:
1.78 anton 11235: For concrete graphical objects, we define child classes of the
11236: class @code{graphical}, e.g.:
1.12 anton 11237:
1.26 crook 11238: @example
11239: graphical class
1.78 anton 11240: cell var circle-radius
11241: end-class circle \ "graphical" is the parent class
1.12 anton 11242:
1.78 anton 11243: :noname ( x y -- )
11244: circle-radius @@ draw-circle ; circle defines draw
11245: :noname ( r -- )
11246: circle-radius ! ; circle defines init
11247: @end example
1.12 anton 11248:
1.78 anton 11249: There is no implicit init method, so we have to define one. The creation
11250: code of the object now has to call init explicitely.
1.21 crook 11251:
1.78 anton 11252: @example
11253: circle new Constant my-circle
11254: 50 my-circle init
1.12 anton 11255: @end example
11256:
1.78 anton 11257: It is also possible to add a function to create named objects with
11258: automatic call of @code{init}, given that all objects have @code{init}
11259: on the same place:
1.38 anton 11260:
1.78 anton 11261: @example
11262: : new: ( .. o "name" -- )
11263: new dup Constant init ;
11264: 80 circle new: large-circle
11265: @end example
1.12 anton 11266:
1.78 anton 11267: We can draw this new circle at (100,100) with:
1.12 anton 11268:
1.78 anton 11269: @example
11270: 100 100 my-circle draw
11271: @end example
1.12 anton 11272:
1.78 anton 11273: @node Mini-OOF Implementation, , Mini-OOF Example, Mini-OOF
11274: @subsubsection @file{mini-oof.fs} Implementation
1.12 anton 11275:
1.78 anton 11276: Object-oriented systems with late binding typically use a
11277: ``vtable''-approach: the first variable in each object is a pointer to a
11278: table, which contains the methods as function pointers. The vtable
11279: may also contain other information.
1.12 anton 11280:
1.79 anton 11281: So first, let's declare selectors:
1.37 anton 11282:
11283: @example
1.79 anton 11284: : method ( m v "name" -- m' v ) Create over , swap cell+ swap
1.78 anton 11285: DOES> ( ... o -- ... ) @@ over @@ + @@ execute ;
11286: @end example
1.37 anton 11287:
1.79 anton 11288: During selector declaration, the number of selectors and instance
11289: variables is on the stack (in address units). @code{method} creates one
11290: selector and increments the selector number. To execute a selector, it
1.78 anton 11291: takes the object, fetches the vtable pointer, adds the offset, and
1.79 anton 11292: executes the method @i{xt} stored there. Each selector takes the object
11293: it is invoked with as top of stack parameter; it passes the parameters
11294: (including the object) unchanged to the appropriate method which should
1.78 anton 11295: consume that object.
1.37 anton 11296:
1.78 anton 11297: Now, we also have to declare instance variables
1.37 anton 11298:
1.78 anton 11299: @example
1.79 anton 11300: : var ( m v size "name" -- m v' ) Create over , +
1.78 anton 11301: DOES> ( o -- addr ) @@ + ;
1.37 anton 11302: @end example
11303:
1.78 anton 11304: As before, a word is created with the current offset. Instance
11305: variables can have different sizes (cells, floats, doubles, chars), so
11306: all we do is take the size and add it to the offset. If your machine
11307: has alignment restrictions, put the proper @code{aligned} or
11308: @code{faligned} before the variable, to adjust the variable
11309: offset. That's why it is on the top of stack.
1.37 anton 11310:
1.78 anton 11311: We need a starting point (the base object) and some syntactic sugar:
1.37 anton 11312:
1.78 anton 11313: @example
11314: Create object 1 cells , 2 cells ,
1.79 anton 11315: : class ( class -- class selectors vars ) dup 2@@ ;
1.78 anton 11316: @end example
1.12 anton 11317:
1.78 anton 11318: For inheritance, the vtable of the parent object has to be
11319: copied when a new, derived class is declared. This gives all the
11320: methods of the parent class, which can be overridden, though.
1.12 anton 11321:
1.78 anton 11322: @example
1.79 anton 11323: : end-class ( class selectors vars "name" -- )
1.78 anton 11324: Create here >r , dup , 2 cells ?DO ['] noop , 1 cells +LOOP
11325: cell+ dup cell+ r> rot @@ 2 cells /string move ;
11326: @end example
1.12 anton 11327:
1.78 anton 11328: The first line creates the vtable, initialized with
11329: @code{noop}s. The second line is the inheritance mechanism, it
11330: copies the xts from the parent vtable.
1.12 anton 11331:
1.78 anton 11332: We still have no way to define new methods, let's do that now:
1.12 anton 11333:
1.26 crook 11334: @example
1.79 anton 11335: : defines ( xt class "name" -- ) ' >body @@ + ! ;
1.78 anton 11336: @end example
1.12 anton 11337:
1.78 anton 11338: To allocate a new object, we need a word, too:
1.12 anton 11339:
1.78 anton 11340: @example
11341: : new ( class -- o ) here over @@ allot swap over ! ;
1.12 anton 11342: @end example
11343:
1.78 anton 11344: Sometimes derived classes want to access the method of the
11345: parent object. There are two ways to achieve this with Mini-OOF:
11346: first, you could use named words, and second, you could look up the
11347: vtable of the parent object.
1.12 anton 11348:
1.78 anton 11349: @example
11350: : :: ( class "name" -- ) ' >body @@ + @@ compile, ;
11351: @end example
1.12 anton 11352:
11353:
1.78 anton 11354: Nothing can be more confusing than a good example, so here is
11355: one. First let's declare a text object (called
11356: @code{button}), that stores text and position:
1.12 anton 11357:
1.78 anton 11358: @example
11359: object class
11360: cell var text
11361: cell var len
11362: cell var x
11363: cell var y
11364: method init
11365: method draw
11366: end-class button
11367: @end example
1.12 anton 11368:
1.78 anton 11369: @noindent
11370: Now, implement the two methods, @code{draw} and @code{init}:
1.21 crook 11371:
1.26 crook 11372: @example
1.78 anton 11373: :noname ( o -- )
11374: >r r@@ x @@ r@@ y @@ at-xy r@@ text @@ r> len @@ type ;
11375: button defines draw
11376: :noname ( addr u o -- )
11377: >r 0 r@@ x ! 0 r@@ y ! r@@ len ! r> text ! ;
11378: button defines init
1.26 crook 11379: @end example
1.12 anton 11380:
1.78 anton 11381: @noindent
11382: To demonstrate inheritance, we define a class @code{bold-button}, with no
1.79 anton 11383: new data and no new selectors:
1.78 anton 11384:
11385: @example
11386: button class
11387: end-class bold-button
1.12 anton 11388:
1.78 anton 11389: : bold 27 emit ." [1m" ;
11390: : normal 27 emit ." [0m" ;
11391: @end example
1.1 anton 11392:
1.78 anton 11393: @noindent
11394: The class @code{bold-button} has a different draw method to
11395: @code{button}, but the new method is defined in terms of the draw method
11396: for @code{button}:
1.20 pazsan 11397:
1.78 anton 11398: @example
11399: :noname bold [ button :: draw ] normal ; bold-button defines draw
11400: @end example
1.21 crook 11401:
1.78 anton 11402: @noindent
1.79 anton 11403: Finally, create two objects and apply selectors:
1.21 crook 11404:
1.26 crook 11405: @example
1.78 anton 11406: button new Constant foo
11407: s" thin foo" foo init
11408: page
11409: foo draw
11410: bold-button new Constant bar
11411: s" fat bar" bar init
11412: 1 bar y !
11413: bar draw
1.26 crook 11414: @end example
1.21 crook 11415:
11416:
1.78 anton 11417: @node Comparison with other object models, , Mini-OOF, Object-oriented Forth
11418: @subsection Comparison with other object models
11419: @cindex comparison of object models
11420: @cindex object models, comparison
11421:
11422: Many object-oriented Forth extensions have been proposed (@cite{A survey
11423: of object-oriented Forths} (SIGPLAN Notices, April 1996) by Bradford
11424: J. Rodriguez and W. F. S. Poehlman lists 17). This section discusses the
11425: relation of the object models described here to two well-known and two
11426: closely-related (by the use of method maps) models. Andras Zsoter
11427: helped us with this section.
11428:
11429: @cindex Neon model
11430: The most popular model currently seems to be the Neon model (see
11431: @cite{Object-oriented programming in ANS Forth} (Forth Dimensions, March
11432: 1997) by Andrew McKewan) but this model has a number of limitations
11433: @footnote{A longer version of this critique can be
11434: found in @cite{On Standardizing Object-Oriented Forth Extensions} (Forth
11435: Dimensions, May 1997) by Anton Ertl.}:
11436:
11437: @itemize @bullet
11438: @item
11439: It uses a @code{@emph{selector object}} syntax, which makes it unnatural
11440: to pass objects on the stack.
1.21 crook 11441:
1.78 anton 11442: @item
11443: It requires that the selector parses the input stream (at
1.79 anton 11444: compile time); this leads to reduced extensibility and to bugs that are
1.78 anton 11445: hard to find.
1.21 crook 11446:
1.78 anton 11447: @item
1.79 anton 11448: It allows using every selector on every object; this eliminates the
11449: need for interfaces, but makes it harder to create efficient
11450: implementations.
1.78 anton 11451: @end itemize
1.21 crook 11452:
1.78 anton 11453: @cindex Pountain's object-oriented model
11454: Another well-known publication is @cite{Object-Oriented Forth} (Academic
11455: Press, London, 1987) by Dick Pountain. However, it is not really about
11456: object-oriented programming, because it hardly deals with late
11457: binding. Instead, it focuses on features like information hiding and
11458: overloading that are characteristic of modular languages like Ada (83).
1.26 crook 11459:
1.78 anton 11460: @cindex Zsoter's object-oriented model
1.79 anton 11461: In @uref{http://www.forth.org/oopf.html, Does late binding have to be
11462: slow?} (Forth Dimensions 18(1) 1996, pages 31-35) Andras Zsoter
11463: describes a model that makes heavy use of an active object (like
11464: @code{this} in @file{objects.fs}): The active object is not only used
11465: for accessing all fields, but also specifies the receiving object of
11466: every selector invocation; you have to change the active object
11467: explicitly with @code{@{ ... @}}, whereas in @file{objects.fs} it
11468: changes more or less implicitly at @code{m: ... ;m}. Such a change at
11469: the method entry point is unnecessary with Zsoter's model, because the
11470: receiving object is the active object already. On the other hand, the
11471: explicit change is absolutely necessary in that model, because otherwise
11472: no one could ever change the active object. An ANS Forth implementation
11473: of this model is available through
11474: @uref{http://www.forth.org/oopf.html}.
1.21 crook 11475:
1.78 anton 11476: @cindex @file{oof.fs}, differences to other models
11477: The @file{oof.fs} model combines information hiding and overloading
11478: resolution (by keeping names in various word lists) with object-oriented
11479: programming. It sets the active object implicitly on method entry, but
11480: also allows explicit changing (with @code{>o...o>} or with
11481: @code{with...endwith}). It uses parsing and state-smart objects and
11482: classes for resolving overloading and for early binding: the object or
11483: class parses the selector and determines the method from this. If the
11484: selector is not parsed by an object or class, it performs a call to the
11485: selector for the active object (late binding), like Zsoter's model.
11486: Fields are always accessed through the active object. The big
11487: disadvantage of this model is the parsing and the state-smartness, which
11488: reduces extensibility and increases the opportunities for subtle bugs;
11489: essentially, you are only safe if you never tick or @code{postpone} an
11490: object or class (Bernd disagrees, but I (Anton) am not convinced).
1.21 crook 11491:
1.78 anton 11492: @cindex @file{mini-oof.fs}, differences to other models
11493: The @file{mini-oof.fs} model is quite similar to a very stripped-down
11494: version of the @file{objects.fs} model, but syntactically it is a
11495: mixture of the @file{objects.fs} and @file{oof.fs} models.
1.21 crook 11496:
11497:
1.78 anton 11498: @c -------------------------------------------------------------
11499: @node Programming Tools, Assembler and Code Words, Object-oriented Forth, Words
11500: @section Programming Tools
11501: @cindex programming tools
1.21 crook 11502:
1.78 anton 11503: @c !! move this and assembler down below OO stuff.
1.21 crook 11504:
1.78 anton 11505: @menu
11506: * Examining::
11507: * Forgetting words::
11508: * Debugging:: Simple and quick.
11509: * Assertions:: Making your programs self-checking.
11510: * Singlestep Debugger:: Executing your program word by word.
11511: @end menu
1.21 crook 11512:
1.78 anton 11513: @node Examining, Forgetting words, Programming Tools, Programming Tools
11514: @subsection Examining data and code
11515: @cindex examining data and code
11516: @cindex data examination
11517: @cindex code examination
1.44 crook 11518:
1.78 anton 11519: The following words inspect the stack non-destructively:
1.21 crook 11520:
1.78 anton 11521: doc-.s
11522: doc-f.s
1.44 crook 11523:
1.78 anton 11524: There is a word @code{.r} but it does @i{not} display the return stack!
11525: It is used for formatted numeric output (@pxref{Simple numeric output}).
1.21 crook 11526:
1.78 anton 11527: doc-depth
11528: doc-fdepth
11529: doc-clearstack
1.21 crook 11530:
1.78 anton 11531: The following words inspect memory.
1.21 crook 11532:
1.78 anton 11533: doc-?
11534: doc-dump
1.21 crook 11535:
1.78 anton 11536: And finally, @code{see} allows to inspect code:
1.21 crook 11537:
1.78 anton 11538: doc-see
11539: doc-xt-see
1.111 ! anton 11540: doc-simple-see
! 11541: doc-simple-see-range
1.21 crook 11542:
1.78 anton 11543: @node Forgetting words, Debugging, Examining, Programming Tools
11544: @subsection Forgetting words
11545: @cindex words, forgetting
11546: @cindex forgeting words
1.21 crook 11547:
1.78 anton 11548: @c anton: other, maybe better places for this subsection: Defining Words;
11549: @c Dictionary allocation. At least a reference should be there.
1.21 crook 11550:
1.78 anton 11551: Forth allows you to forget words (and everything that was alloted in the
11552: dictonary after them) in a LIFO manner.
1.21 crook 11553:
1.78 anton 11554: doc-marker
1.21 crook 11555:
1.78 anton 11556: The most common use of this feature is during progam development: when
11557: you change a source file, forget all the words it defined and load it
11558: again (since you also forget everything defined after the source file
11559: was loaded, you have to reload that, too). Note that effects like
11560: storing to variables and destroyed system words are not undone when you
11561: forget words. With a system like Gforth, that is fast enough at
11562: starting up and compiling, I find it more convenient to exit and restart
11563: Gforth, as this gives me a clean slate.
1.21 crook 11564:
1.78 anton 11565: Here's an example of using @code{marker} at the start of a source file
11566: that you are debugging; it ensures that you only ever have one copy of
11567: the file's definitions compiled at any time:
1.21 crook 11568:
1.78 anton 11569: @example
11570: [IFDEF] my-code
11571: my-code
11572: [ENDIF]
1.26 crook 11573:
1.78 anton 11574: marker my-code
11575: init-included-files
1.21 crook 11576:
1.78 anton 11577: \ .. definitions start here
11578: \ .
11579: \ .
11580: \ end
11581: @end example
1.21 crook 11582:
1.26 crook 11583:
1.78 anton 11584: @node Debugging, Assertions, Forgetting words, Programming Tools
11585: @subsection Debugging
11586: @cindex debugging
1.21 crook 11587:
1.78 anton 11588: Languages with a slow edit/compile/link/test development loop tend to
11589: require sophisticated tracing/stepping debuggers to facilate debugging.
1.21 crook 11590:
1.78 anton 11591: A much better (faster) way in fast-compiling languages is to add
11592: printing code at well-selected places, let the program run, look at
11593: the output, see where things went wrong, add more printing code, etc.,
11594: until the bug is found.
1.21 crook 11595:
1.78 anton 11596: The simple debugging aids provided in @file{debugs.fs}
11597: are meant to support this style of debugging.
1.21 crook 11598:
1.78 anton 11599: The word @code{~~} prints debugging information (by default the source
11600: location and the stack contents). It is easy to insert. If you use Emacs
11601: it is also easy to remove (@kbd{C-x ~} in the Emacs Forth mode to
11602: query-replace them with nothing). The deferred words
1.101 anton 11603: @code{printdebugdata} and @code{.debugline} control the output of
1.78 anton 11604: @code{~~}. The default source location output format works well with
11605: Emacs' compilation mode, so you can step through the program at the
11606: source level using @kbd{C-x `} (the advantage over a stepping debugger
11607: is that you can step in any direction and you know where the crash has
11608: happened or where the strange data has occurred).
1.21 crook 11609:
1.78 anton 11610: doc-~~
11611: doc-printdebugdata
1.101 anton 11612: doc-.debugline
1.21 crook 11613:
1.106 anton 11614: @cindex filenames in @code{~~} output
11615: @code{~~} (and assertions) will usually print the wrong file name if a
11616: marker is executed in the same file after their occurance. They will
11617: print @samp{*somewhere*} as file name if a marker is executed in the
11618: same file before their occurance.
11619:
11620:
1.78 anton 11621: @node Assertions, Singlestep Debugger, Debugging, Programming Tools
11622: @subsection Assertions
11623: @cindex assertions
1.21 crook 11624:
1.78 anton 11625: It is a good idea to make your programs self-checking, especially if you
11626: make an assumption that may become invalid during maintenance (for
11627: example, that a certain field of a data structure is never zero). Gforth
11628: supports @dfn{assertions} for this purpose. They are used like this:
1.21 crook 11629:
11630: @example
1.78 anton 11631: assert( @i{flag} )
1.26 crook 11632: @end example
11633:
1.78 anton 11634: The code between @code{assert(} and @code{)} should compute a flag, that
11635: should be true if everything is alright and false otherwise. It should
11636: not change anything else on the stack. The overall stack effect of the
11637: assertion is @code{( -- )}. E.g.
1.21 crook 11638:
1.26 crook 11639: @example
1.78 anton 11640: assert( 1 1 + 2 = ) \ what we learn in school
11641: assert( dup 0<> ) \ assert that the top of stack is not zero
11642: assert( false ) \ this code should not be reached
1.21 crook 11643: @end example
11644:
1.78 anton 11645: The need for assertions is different at different times. During
11646: debugging, we want more checking, in production we sometimes care more
11647: for speed. Therefore, assertions can be turned off, i.e., the assertion
11648: becomes a comment. Depending on the importance of an assertion and the
11649: time it takes to check it, you may want to turn off some assertions and
11650: keep others turned on. Gforth provides several levels of assertions for
11651: this purpose:
11652:
11653:
11654: doc-assert0(
11655: doc-assert1(
11656: doc-assert2(
11657: doc-assert3(
11658: doc-assert(
11659: doc-)
1.21 crook 11660:
11661:
1.78 anton 11662: The variable @code{assert-level} specifies the highest assertions that
11663: are turned on. I.e., at the default @code{assert-level} of one,
11664: @code{assert0(} and @code{assert1(} assertions perform checking, while
11665: @code{assert2(} and @code{assert3(} assertions are treated as comments.
1.26 crook 11666:
1.78 anton 11667: The value of @code{assert-level} is evaluated at compile-time, not at
11668: run-time. Therefore you cannot turn assertions on or off at run-time;
11669: you have to set the @code{assert-level} appropriately before compiling a
11670: piece of code. You can compile different pieces of code at different
11671: @code{assert-level}s (e.g., a trusted library at level 1 and
11672: newly-written code at level 3).
1.26 crook 11673:
11674:
1.78 anton 11675: doc-assert-level
1.26 crook 11676:
11677:
1.78 anton 11678: If an assertion fails, a message compatible with Emacs' compilation mode
11679: is produced and the execution is aborted (currently with @code{ABORT"}.
11680: If there is interest, we will introduce a special throw code. But if you
11681: intend to @code{catch} a specific condition, using @code{throw} is
11682: probably more appropriate than an assertion).
1.106 anton 11683:
11684: @cindex filenames in assertion output
11685: Assertions (and @code{~~}) will usually print the wrong file name if a
11686: marker is executed in the same file after their occurance. They will
11687: print @samp{*somewhere*} as file name if a marker is executed in the
11688: same file before their occurance.
1.44 crook 11689:
1.78 anton 11690: Definitions in ANS Forth for these assertion words are provided
11691: in @file{compat/assert.fs}.
1.26 crook 11692:
1.44 crook 11693:
1.78 anton 11694: @node Singlestep Debugger, , Assertions, Programming Tools
11695: @subsection Singlestep Debugger
11696: @cindex singlestep Debugger
11697: @cindex debugging Singlestep
1.44 crook 11698:
1.78 anton 11699: When you create a new word there's often the need to check whether it
11700: behaves correctly or not. You can do this by typing @code{dbg
11701: badword}. A debug session might look like this:
1.26 crook 11702:
1.78 anton 11703: @example
11704: : badword 0 DO i . LOOP ; ok
11705: 2 dbg badword
11706: : badword
11707: Scanning code...
1.44 crook 11708:
1.78 anton 11709: Nesting debugger ready!
1.44 crook 11710:
1.78 anton 11711: 400D4738 8049BC4 0 -> [ 2 ] 00002 00000
11712: 400D4740 8049F68 DO -> [ 0 ]
11713: 400D4744 804A0C8 i -> [ 1 ] 00000
11714: 400D4748 400C5E60 . -> 0 [ 0 ]
11715: 400D474C 8049D0C LOOP -> [ 0 ]
11716: 400D4744 804A0C8 i -> [ 1 ] 00001
11717: 400D4748 400C5E60 . -> 1 [ 0 ]
11718: 400D474C 8049D0C LOOP -> [ 0 ]
11719: 400D4758 804B384 ; -> ok
11720: @end example
1.21 crook 11721:
1.78 anton 11722: Each line displayed is one step. You always have to hit return to
11723: execute the next word that is displayed. If you don't want to execute
11724: the next word in a whole, you have to type @kbd{n} for @code{nest}. Here is
11725: an overview what keys are available:
1.44 crook 11726:
1.78 anton 11727: @table @i
1.44 crook 11728:
1.78 anton 11729: @item @key{RET}
11730: Next; Execute the next word.
1.21 crook 11731:
1.78 anton 11732: @item n
11733: Nest; Single step through next word.
1.44 crook 11734:
1.78 anton 11735: @item u
11736: Unnest; Stop debugging and execute rest of word. If we got to this word
11737: with nest, continue debugging with the calling word.
1.44 crook 11738:
1.78 anton 11739: @item d
11740: Done; Stop debugging and execute rest.
1.21 crook 11741:
1.78 anton 11742: @item s
11743: Stop; Abort immediately.
1.44 crook 11744:
1.78 anton 11745: @end table
1.44 crook 11746:
1.78 anton 11747: Debugging large application with this mechanism is very difficult, because
11748: you have to nest very deeply into the program before the interesting part
11749: begins. This takes a lot of time.
1.26 crook 11750:
1.78 anton 11751: To do it more directly put a @code{BREAK:} command into your source code.
11752: When program execution reaches @code{BREAK:} the single step debugger is
11753: invoked and you have all the features described above.
1.44 crook 11754:
1.78 anton 11755: If you have more than one part to debug it is useful to know where the
11756: program has stopped at the moment. You can do this by the
11757: @code{BREAK" string"} command. This behaves like @code{BREAK:} except that
11758: string is typed out when the ``breakpoint'' is reached.
1.44 crook 11759:
1.26 crook 11760:
1.78 anton 11761: doc-dbg
11762: doc-break:
11763: doc-break"
1.44 crook 11764:
11765:
1.26 crook 11766:
1.78 anton 11767: @c -------------------------------------------------------------
11768: @node Assembler and Code Words, Threading Words, Programming Tools, Words
11769: @section Assembler and Code Words
11770: @cindex assembler
11771: @cindex code words
1.44 crook 11772:
1.78 anton 11773: @menu
11774: * Code and ;code::
11775: * Common Assembler:: Assembler Syntax
11776: * Common Disassembler::
11777: * 386 Assembler:: Deviations and special cases
11778: * Alpha Assembler:: Deviations and special cases
11779: * MIPS assembler:: Deviations and special cases
11780: * Other assemblers:: How to write them
11781: @end menu
1.21 crook 11782:
1.78 anton 11783: @node Code and ;code, Common Assembler, Assembler and Code Words, Assembler and Code Words
11784: @subsection @code{Code} and @code{;code}
1.26 crook 11785:
1.78 anton 11786: Gforth provides some words for defining primitives (words written in
11787: machine code), and for defining the machine-code equivalent of
11788: @code{DOES>}-based defining words. However, the machine-independent
11789: nature of Gforth poses a few problems: First of all, Gforth runs on
11790: several architectures, so it can provide no standard assembler. What's
11791: worse is that the register allocation not only depends on the processor,
11792: but also on the @code{gcc} version and options used.
1.44 crook 11793:
1.78 anton 11794: The words that Gforth offers encapsulate some system dependences (e.g.,
11795: the header structure), so a system-independent assembler may be used in
11796: Gforth. If you do not have an assembler, you can compile machine code
11797: directly with @code{,} and @code{c,}@footnote{This isn't portable,
11798: because these words emit stuff in @i{data} space; it works because
11799: Gforth has unified code/data spaces. Assembler isn't likely to be
11800: portable anyway.}.
1.21 crook 11801:
1.44 crook 11802:
1.78 anton 11803: doc-assembler
11804: doc-init-asm
11805: doc-code
11806: doc-end-code
11807: doc-;code
11808: doc-flush-icache
1.44 crook 11809:
1.21 crook 11810:
1.78 anton 11811: If @code{flush-icache} does not work correctly, @code{code} words
11812: etc. will not work (reliably), either.
1.44 crook 11813:
1.78 anton 11814: The typical usage of these @code{code} words can be shown most easily by
11815: analogy to the equivalent high-level defining words:
1.44 crook 11816:
1.78 anton 11817: @example
11818: : foo code foo
11819: <high-level Forth words> <assembler>
11820: ; end-code
11821:
11822: : bar : bar
11823: <high-level Forth words> <high-level Forth words>
11824: CREATE CREATE
11825: <high-level Forth words> <high-level Forth words>
11826: DOES> ;code
11827: <high-level Forth words> <assembler>
11828: ; end-code
11829: @end example
1.21 crook 11830:
1.78 anton 11831: @c anton: the following stuff is also in "Common Assembler", in less detail.
1.44 crook 11832:
1.78 anton 11833: @cindex registers of the inner interpreter
11834: In the assembly code you will want to refer to the inner interpreter's
11835: registers (e.g., the data stack pointer) and you may want to use other
11836: registers for temporary storage. Unfortunately, the register allocation
11837: is installation-dependent.
1.44 crook 11838:
1.78 anton 11839: In particular, @code{ip} (Forth instruction pointer) and @code{rp}
1.100 anton 11840: (return stack pointer) may be in different places in @code{gforth} and
11841: @code{gforth-fast}, or different installations. This means that you
11842: cannot write a @code{NEXT} routine that works reliably on both versions
11843: or different installations; so for doing @code{NEXT}, I recommend
11844: jumping to @code{' noop >code-address}, which contains nothing but a
11845: @code{NEXT}.
1.21 crook 11846:
1.78 anton 11847: For general accesses to the inner interpreter's registers, the easiest
11848: solution is to use explicit register declarations (@pxref{Explicit Reg
11849: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) for
11850: all of the inner interpreter's registers: You have to compile Gforth
11851: with @code{-DFORCE_REG} (configure option @code{--enable-force-reg}) and
11852: the appropriate declarations must be present in the @code{machine.h}
11853: file (see @code{mips.h} for an example; you can find a full list of all
11854: declarable register symbols with @code{grep register engine.c}). If you
11855: give explicit registers to all variables that are declared at the
11856: beginning of @code{engine()}, you should be able to use the other
11857: caller-saved registers for temporary storage. Alternatively, you can use
11858: the @code{gcc} option @code{-ffixed-REG} (@pxref{Code Gen Options, ,
11859: Options for Code Generation Conventions, gcc.info, GNU C Manual}) to
11860: reserve a register (however, this restriction on register allocation may
11861: slow Gforth significantly).
1.44 crook 11862:
1.78 anton 11863: If this solution is not viable (e.g., because @code{gcc} does not allow
11864: you to explicitly declare all the registers you need), you have to find
11865: out by looking at the code where the inner interpreter's registers
11866: reside and which registers can be used for temporary storage. You can
11867: get an assembly listing of the engine's code with @code{make engine.s}.
1.44 crook 11868:
1.78 anton 11869: In any case, it is good practice to abstract your assembly code from the
11870: actual register allocation. E.g., if the data stack pointer resides in
11871: register @code{$17}, create an alias for this register called @code{sp},
11872: and use that in your assembly code.
1.21 crook 11873:
1.78 anton 11874: @cindex code words, portable
11875: Another option for implementing normal and defining words efficiently
11876: is to add the desired functionality to the source of Gforth. For normal
11877: words you just have to edit @file{primitives} (@pxref{Automatic
11878: Generation}). Defining words (equivalent to @code{;CODE} words, for fast
11879: defined words) may require changes in @file{engine.c}, @file{kernel.fs},
11880: @file{prims2x.fs}, and possibly @file{cross.fs}.
1.44 crook 11881:
1.78 anton 11882: @node Common Assembler, Common Disassembler, Code and ;code, Assembler and Code Words
11883: @subsection Common Assembler
1.44 crook 11884:
1.78 anton 11885: The assemblers in Gforth generally use a postfix syntax, i.e., the
11886: instruction name follows the operands.
1.21 crook 11887:
1.78 anton 11888: The operands are passed in the usual order (the same that is used in the
11889: manual of the architecture). Since they all are Forth words, they have
11890: to be separated by spaces; you can also use Forth words to compute the
11891: operands.
1.44 crook 11892:
1.78 anton 11893: The instruction names usually end with a @code{,}. This makes it easier
11894: to visually separate instructions if you put several of them on one
11895: line; it also avoids shadowing other Forth words (e.g., @code{and}).
1.21 crook 11896:
1.78 anton 11897: Registers are usually specified by number; e.g., (decimal) @code{11}
11898: specifies registers R11 and F11 on the Alpha architecture (which one,
11899: depends on the instruction). The usual names are also available, e.g.,
11900: @code{s2} for R11 on Alpha.
1.21 crook 11901:
1.78 anton 11902: Control flow is specified similar to normal Forth code (@pxref{Arbitrary
11903: control structures}), with @code{if,}, @code{ahead,}, @code{then,},
11904: @code{begin,}, @code{until,}, @code{again,}, @code{cs-roll},
11905: @code{cs-pick}, @code{else,}, @code{while,}, and @code{repeat,}. The
11906: conditions are specified in a way specific to each assembler.
1.1 anton 11907:
1.78 anton 11908: Note that the register assignments of the Gforth engine can change
11909: between Gforth versions, or even between different compilations of the
11910: same Gforth version (e.g., if you use a different GCC version). So if
11911: you want to refer to Gforth's registers (e.g., the stack pointer or
11912: TOS), I recommend defining your own words for refering to these
11913: registers, and using them later on; then you can easily adapt to a
11914: changed register assignment. The stability of the register assignment
11915: is usually better if you build Gforth with @code{--enable-force-reg}.
1.1 anton 11916:
1.100 anton 11917: The most common use of these registers is to dispatch to the next word
11918: (the @code{next} routine). A portable way to do this is to jump to
11919: @code{' noop >code-address} (of course, this is less efficient than
11920: integrating the @code{next} code and scheduling it well).
1.1 anton 11921:
1.96 anton 11922: Another difference between Gforth version is that the top of stack is
11923: kept in memory in @code{gforth} and, on most platforms, in a register in
11924: @code{gforth-fast}.
11925:
1.78 anton 11926: @node Common Disassembler, 386 Assembler, Common Assembler, Assembler and Code Words
11927: @subsection Common Disassembler
1.1 anton 11928:
1.78 anton 11929: You can disassemble a @code{code} word with @code{see}
11930: (@pxref{Debugging}). You can disassemble a section of memory with
1.1 anton 11931:
1.78 anton 11932: doc-disasm
1.44 crook 11933:
1.78 anton 11934: The disassembler generally produces output that can be fed into the
11935: assembler (i.e., same syntax, etc.). It also includes additional
11936: information in comments. In particular, the address of the instruction
11937: is given in a comment before the instruction.
1.1 anton 11938:
1.78 anton 11939: @code{See} may display more or less than the actual code of the word,
11940: because the recognition of the end of the code is unreliable. You can
11941: use @code{disasm} if it did not display enough. It may display more, if
11942: the code word is not immediately followed by a named word. If you have
11943: something else there, you can follow the word with @code{align last @ ,}
11944: to ensure that the end is recognized.
1.21 crook 11945:
1.78 anton 11946: @node 386 Assembler, Alpha Assembler, Common Disassembler, Assembler and Code Words
11947: @subsection 386 Assembler
1.44 crook 11948:
1.78 anton 11949: The 386 assembler included in Gforth was written by Bernd Paysan, it's
11950: available under GPL, and originally part of bigFORTH.
1.21 crook 11951:
1.78 anton 11952: The 386 disassembler included in Gforth was written by Andrew McKewan
11953: and is in the public domain.
1.21 crook 11954:
1.91 anton 11955: The disassembler displays code in an Intel-like prefix syntax.
1.21 crook 11956:
1.78 anton 11957: The assembler uses a postfix syntax with reversed parameters.
1.1 anton 11958:
1.78 anton 11959: The assembler includes all instruction of the Athlon, i.e. 486 core
11960: instructions, Pentium and PPro extensions, floating point, MMX, 3Dnow!,
11961: but not ISSE. It's an integrated 16- and 32-bit assembler. Default is 32
11962: bit, you can switch to 16 bit with .86 and back to 32 bit with .386.
1.1 anton 11963:
1.78 anton 11964: There are several prefixes to switch between different operation sizes,
11965: @code{.b} for byte accesses, @code{.w} for word accesses, @code{.d} for
11966: double-word accesses. Addressing modes can be switched with @code{.wa}
11967: for 16 bit addresses, and @code{.da} for 32 bit addresses. You don't
11968: need a prefix for byte register names (@code{AL} et al).
1.1 anton 11969:
1.78 anton 11970: For floating point operations, the prefixes are @code{.fs} (IEEE
11971: single), @code{.fl} (IEEE double), @code{.fx} (extended), @code{.fw}
11972: (word), @code{.fd} (double-word), and @code{.fq} (quad-word).
1.21 crook 11973:
1.78 anton 11974: The MMX opcodes don't have size prefixes, they are spelled out like in
11975: the Intel assembler. Instead of move from and to memory, there are
11976: PLDQ/PLDD and PSTQ/PSTD.
1.21 crook 11977:
1.78 anton 11978: The registers lack the 'e' prefix; even in 32 bit mode, eax is called
11979: ax. Immediate values are indicated by postfixing them with @code{#},
1.91 anton 11980: e.g., @code{3 #}. Here are some examples of addressing modes in various
11981: syntaxes:
1.21 crook 11982:
1.26 crook 11983: @example
1.91 anton 11984: Gforth Intel (NASM) AT&T (gas) Name
11985: .w ax ax %ax register (16 bit)
11986: ax eax %eax register (32 bit)
11987: 3 # offset 3 $3 immediate
11988: 1000 #) byte ptr 1000 1000 displacement
11989: bx ) [ebx] (%ebx) base
11990: 100 di d) 100[edi] 100(%edi) base+displacement
11991: 20 ax *4 i#) 20[eax*4] 20(,%eax,4) (index*scale)+displacement
11992: di ax *4 i) [edi][eax*4] (%edi,%eax,4) base+(index*scale)
11993: 4 bx cx di) 4[ebx][ecx] 4(%ebx,%ecx) base+index+displacement
11994: 12 sp ax *2 di) 12[esp][eax*2] 12(%esp,%eax,2) base+(index*scale)+displacement
11995: @end example
11996:
11997: You can use @code{L)} and @code{LI)} instead of @code{D)} and
11998: @code{DI)} to enforce 32-bit displacement fields (useful for
11999: later patching).
1.21 crook 12000:
1.78 anton 12001: Some example of instructions are:
1.1 anton 12002:
12003: @example
1.78 anton 12004: ax bx mov \ move ebx,eax
12005: 3 # ax mov \ mov eax,3
12006: 100 di ) ax mov \ mov eax,100[edi]
12007: 4 bx cx di) ax mov \ mov eax,4[ebx][ecx]
12008: .w ax bx mov \ mov bx,ax
1.1 anton 12009: @end example
12010:
1.78 anton 12011: The following forms are supported for binary instructions:
1.1 anton 12012:
12013: @example
1.78 anton 12014: <reg> <reg> <inst>
12015: <n> # <reg> <inst>
12016: <mem> <reg> <inst>
12017: <reg> <mem> <inst>
1.1 anton 12018: @end example
12019:
1.78 anton 12020: Immediate to memory is not supported. The shift/rotate syntax is:
1.1 anton 12021:
1.26 crook 12022: @example
1.78 anton 12023: <reg/mem> 1 # shl \ shortens to shift without immediate
12024: <reg/mem> 4 # shl
12025: <reg/mem> cl shl
1.26 crook 12026: @end example
1.1 anton 12027:
1.78 anton 12028: Precede string instructions (@code{movs} etc.) with @code{.b} to get
12029: the byte version.
1.1 anton 12030:
1.78 anton 12031: The control structure words @code{IF} @code{UNTIL} etc. must be preceded
12032: by one of these conditions: @code{vs vc u< u>= 0= 0<> u<= u> 0< 0>= ps
12033: pc < >= <= >}. (Note that most of these words shadow some Forth words
12034: when @code{assembler} is in front of @code{forth} in the search path,
12035: e.g., in @code{code} words). Currently the control structure words use
12036: one stack item, so you have to use @code{roll} instead of @code{cs-roll}
12037: to shuffle them (you can also use @code{swap} etc.).
1.21 crook 12038:
1.78 anton 12039: Here is an example of a @code{code} word (assumes that the stack pointer
12040: is in esi and the TOS is in ebx):
1.21 crook 12041:
1.26 crook 12042: @example
1.78 anton 12043: code my+ ( n1 n2 -- n )
12044: 4 si D) bx add
12045: 4 # si add
12046: Next
12047: end-code
1.26 crook 12048: @end example
1.21 crook 12049:
1.78 anton 12050: @node Alpha Assembler, MIPS assembler, 386 Assembler, Assembler and Code Words
12051: @subsection Alpha Assembler
1.21 crook 12052:
1.78 anton 12053: The Alpha assembler and disassembler were originally written by Bernd
12054: Thallner.
1.26 crook 12055:
1.78 anton 12056: The register names @code{a0}--@code{a5} are not available to avoid
12057: shadowing hex numbers.
1.2 jwilke 12058:
1.78 anton 12059: Immediate forms of arithmetic instructions are distinguished by a
12060: @code{#} just before the @code{,}, e.g., @code{and#,} (note: @code{lda,}
12061: does not count as arithmetic instruction).
1.2 jwilke 12062:
1.78 anton 12063: You have to specify all operands to an instruction, even those that
12064: other assemblers consider optional, e.g., the destination register for
12065: @code{br,}, or the destination register and hint for @code{jmp,}.
1.2 jwilke 12066:
1.78 anton 12067: You can specify conditions for @code{if,} by removing the first @code{b}
12068: and the trailing @code{,} from a branch with a corresponding name; e.g.,
1.2 jwilke 12069:
1.26 crook 12070: @example
1.78 anton 12071: 11 fgt if, \ if F11>0e
12072: ...
12073: endif,
1.26 crook 12074: @end example
1.2 jwilke 12075:
1.78 anton 12076: @code{fbgt,} gives @code{fgt}.
12077:
12078: @node MIPS assembler, Other assemblers, Alpha Assembler, Assembler and Code Words
12079: @subsection MIPS assembler
1.2 jwilke 12080:
1.78 anton 12081: The MIPS assembler was originally written by Christian Pirker.
1.2 jwilke 12082:
1.78 anton 12083: Currently the assembler and disassembler only cover the MIPS-I
12084: architecture (R3000), and don't support FP instructions.
1.2 jwilke 12085:
1.78 anton 12086: The register names @code{$a0}--@code{$a3} are not available to avoid
12087: shadowing hex numbers.
1.2 jwilke 12088:
1.78 anton 12089: Because there is no way to distinguish registers from immediate values,
12090: you have to explicitly use the immediate forms of instructions, i.e.,
12091: @code{addiu,}, not just @code{addu,} (@command{as} does this
12092: implicitly).
1.2 jwilke 12093:
1.78 anton 12094: If the architecture manual specifies several formats for the instruction
12095: (e.g., for @code{jalr,}), you usually have to use the one with more
12096: arguments (i.e., two for @code{jalr,}). When in doubt, see
12097: @code{arch/mips/testasm.fs} for an example of correct use.
1.2 jwilke 12098:
1.78 anton 12099: Branches and jumps in the MIPS architecture have a delay slot. You have
12100: to fill it yourself (the simplest way is to use @code{nop,}), the
12101: assembler does not do it for you (unlike @command{as}). Even
12102: @code{if,}, @code{ahead,}, @code{until,}, @code{again,}, @code{while,},
12103: @code{else,} and @code{repeat,} need a delay slot. Since @code{begin,}
12104: and @code{then,} just specify branch targets, they are not affected.
1.2 jwilke 12105:
1.78 anton 12106: Note that you must not put branches, jumps, or @code{li,} into the delay
12107: slot: @code{li,} may expand to several instructions, and control flow
12108: instructions may not be put into the branch delay slot in any case.
1.2 jwilke 12109:
1.78 anton 12110: For branches the argument specifying the target is a relative address;
12111: You have to add the address of the delay slot to get the absolute
12112: address.
1.1 anton 12113:
1.78 anton 12114: The MIPS architecture also has load delay slots and restrictions on
12115: using @code{mfhi,} and @code{mflo,}; you have to order the instructions
12116: yourself to satisfy these restrictions, the assembler does not do it for
12117: you.
1.1 anton 12118:
1.78 anton 12119: You can specify the conditions for @code{if,} etc. by taking a
12120: conditional branch and leaving away the @code{b} at the start and the
12121: @code{,} at the end. E.g.,
1.1 anton 12122:
1.26 crook 12123: @example
1.78 anton 12124: 4 5 eq if,
12125: ... \ do something if $4 equals $5
12126: then,
1.26 crook 12127: @end example
1.1 anton 12128:
1.78 anton 12129: @node Other assemblers, , MIPS assembler, Assembler and Code Words
12130: @subsection Other assemblers
12131:
12132: If you want to contribute another assembler/disassembler, please contact
1.103 anton 12133: us (@email{anton@@mips.complang.tuwien.ac.at}) to check if we have such
12134: an assembler already. If you are writing them from scratch, please use
12135: a similar syntax style as the one we use (i.e., postfix, commas at the
12136: end of the instruction names, @pxref{Common Assembler}); make the output
12137: of the disassembler be valid input for the assembler, and keep the style
1.78 anton 12138: similar to the style we used.
12139:
12140: Hints on implementation: The most important part is to have a good test
12141: suite that contains all instructions. Once you have that, the rest is
12142: easy. For actual coding you can take a look at
12143: @file{arch/mips/disasm.fs} to get some ideas on how to use data for both
12144: the assembler and disassembler, avoiding redundancy and some potential
12145: bugs. You can also look at that file (and @pxref{Advanced does> usage
12146: example}) to get ideas how to factor a disassembler.
12147:
12148: Start with the disassembler, because it's easier to reuse data from the
12149: disassembler for the assembler than the other way round.
1.1 anton 12150:
1.78 anton 12151: For the assembler, take a look at @file{arch/alpha/asm.fs}, which shows
12152: how simple it can be.
1.1 anton 12153:
1.78 anton 12154: @c -------------------------------------------------------------
12155: @node Threading Words, Passing Commands to the OS, Assembler and Code Words, Words
12156: @section Threading Words
12157: @cindex threading words
1.1 anton 12158:
1.78 anton 12159: @cindex code address
12160: These words provide access to code addresses and other threading stuff
12161: in Gforth (and, possibly, other interpretive Forths). It more or less
12162: abstracts away the differences between direct and indirect threading
12163: (and, for direct threading, the machine dependences). However, at
12164: present this wordset is still incomplete. It is also pretty low-level;
12165: some day it will hopefully be made unnecessary by an internals wordset
12166: that abstracts implementation details away completely.
1.1 anton 12167:
1.78 anton 12168: The terminology used here stems from indirect threaded Forth systems; in
12169: such a system, the XT of a word is represented by the CFA (code field
12170: address) of a word; the CFA points to a cell that contains the code
12171: address. The code address is the address of some machine code that
12172: performs the run-time action of invoking the word (e.g., the
12173: @code{dovar:} routine pushes the address of the body of the word (a
12174: variable) on the stack
12175: ).
1.1 anton 12176:
1.78 anton 12177: @cindex code address
12178: @cindex code field address
12179: In an indirect threaded Forth, you can get the code address of @i{name}
12180: with @code{' @i{name} @@}; in Gforth you can get it with @code{' @i{name}
12181: >code-address}, independent of the threading method.
1.1 anton 12182:
1.78 anton 12183: doc-threading-method
12184: doc->code-address
12185: doc-code-address!
1.1 anton 12186:
1.78 anton 12187: @cindex @code{does>}-handler
12188: @cindex @code{does>}-code
12189: For a word defined with @code{DOES>}, the code address usually points to
12190: a jump instruction (the @dfn{does-handler}) that jumps to the dodoes
12191: routine (in Gforth on some platforms, it can also point to the dodoes
12192: routine itself). What you are typically interested in, though, is
12193: whether a word is a @code{DOES>}-defined word, and what Forth code it
12194: executes; @code{>does-code} tells you that.
1.1 anton 12195:
1.78 anton 12196: doc->does-code
1.1 anton 12197:
1.78 anton 12198: To create a @code{DOES>}-defined word with the following basic words,
12199: you have to set up a @code{DOES>}-handler with @code{does-handler!};
12200: @code{/does-handler} aus behind you have to place your executable Forth
12201: code. Finally you have to create a word and modify its behaviour with
12202: @code{does-handler!}.
1.1 anton 12203:
1.78 anton 12204: doc-does-code!
12205: doc-does-handler!
12206: doc-/does-handler
1.1 anton 12207:
1.78 anton 12208: The code addresses produced by various defining words are produced by
12209: the following words:
1.1 anton 12210:
1.78 anton 12211: doc-docol:
12212: doc-docon:
12213: doc-dovar:
12214: doc-douser:
12215: doc-dodefer:
12216: doc-dofield:
1.1 anton 12217:
1.99 anton 12218: @cindex definer
12219: The following two words generalize @code{>code-address},
12220: @code{>does-code}, @code{code-address!}, and @code{does-code!}:
12221:
12222: doc->definer
12223: doc-definer!
12224:
1.26 crook 12225: @c -------------------------------------------------------------
1.78 anton 12226: @node Passing Commands to the OS, Keeping track of Time, Threading Words, Words
1.21 crook 12227: @section Passing Commands to the Operating System
12228: @cindex operating system - passing commands
12229: @cindex shell commands
12230:
12231: Gforth allows you to pass an arbitrary string to the host operating
12232: system shell (if such a thing exists) for execution.
12233:
1.44 crook 12234:
1.21 crook 12235: doc-sh
12236: doc-system
12237: doc-$?
1.23 crook 12238: doc-getenv
1.21 crook 12239:
1.44 crook 12240:
1.26 crook 12241: @c -------------------------------------------------------------
1.47 crook 12242: @node Keeping track of Time, Miscellaneous Words, Passing Commands to the OS, Words
12243: @section Keeping track of Time
12244: @cindex time-related words
12245:
12246: doc-ms
12247: doc-time&date
1.79 anton 12248: doc-utime
12249: doc-cputime
1.47 crook 12250:
12251:
12252: @c -------------------------------------------------------------
12253: @node Miscellaneous Words, , Keeping track of Time, Words
1.21 crook 12254: @section Miscellaneous Words
12255: @cindex miscellaneous words
12256:
1.29 crook 12257: @comment TODO find homes for these
12258:
1.26 crook 12259: These section lists the ANS Forth words that are not documented
1.21 crook 12260: elsewhere in this manual. Ultimately, they all need proper homes.
12261:
1.68 anton 12262: doc-quit
1.44 crook 12263:
1.26 crook 12264: The following ANS Forth words are not currently supported by Gforth
1.27 crook 12265: (@pxref{ANS conformance}):
1.21 crook 12266:
12267: @code{EDITOR}
12268: @code{EMIT?}
12269: @code{FORGET}
12270:
1.24 anton 12271: @c ******************************************************************
12272: @node Error messages, Tools, Words, Top
12273: @chapter Error messages
12274: @cindex error messages
12275: @cindex backtrace
12276:
12277: A typical Gforth error message looks like this:
12278:
12279: @example
1.86 anton 12280: in file included from \evaluated string/:-1
1.24 anton 12281: in file included from ./yyy.fs:1
12282: ./xxx.fs:4: Invalid memory address
12283: bar
12284: ^^^
1.79 anton 12285: Backtrace:
1.25 anton 12286: $400E664C @@
12287: $400E6664 foo
1.24 anton 12288: @end example
12289:
12290: The message identifying the error is @code{Invalid memory address}. The
12291: error happened when text-interpreting line 4 of the file
12292: @file{./xxx.fs}. This line is given (it contains @code{bar}), and the
12293: word on the line where the error happened, is pointed out (with
12294: @code{^^^}).
12295:
12296: The file containing the error was included in line 1 of @file{./yyy.fs},
12297: and @file{yyy.fs} was included from a non-file (in this case, by giving
12298: @file{yyy.fs} as command-line parameter to Gforth).
12299:
12300: At the end of the error message you find a return stack dump that can be
12301: interpreted as a backtrace (possibly empty). On top you find the top of
12302: the return stack when the @code{throw} happened, and at the bottom you
12303: find the return stack entry just above the return stack of the topmost
12304: text interpreter.
12305:
12306: To the right of most return stack entries you see a guess for the word
12307: that pushed that return stack entry as its return address. This gives a
12308: backtrace. In our case we see that @code{bar} called @code{foo}, and
12309: @code{foo} called @code{@@} (and @code{@@} had an @emph{Invalid memory
12310: address} exception).
12311:
12312: Note that the backtrace is not perfect: We don't know which return stack
12313: entries are return addresses (so we may get false positives); and in
12314: some cases (e.g., for @code{abort"}) we cannot determine from the return
12315: address the word that pushed the return address, so for some return
12316: addresses you see no names in the return stack dump.
1.25 anton 12317:
12318: @cindex @code{catch} and backtraces
12319: The return stack dump represents the return stack at the time when a
12320: specific @code{throw} was executed. In programs that make use of
12321: @code{catch}, it is not necessarily clear which @code{throw} should be
12322: used for the return stack dump (e.g., consider one @code{throw} that
12323: indicates an error, which is caught, and during recovery another error
1.42 anton 12324: happens; which @code{throw} should be used for the stack dump?). Gforth
1.25 anton 12325: presents the return stack dump for the first @code{throw} after the last
12326: executed (not returned-to) @code{catch}; this works well in the usual
12327: case.
12328:
12329: @cindex @code{gforth-fast} and backtraces
12330: @cindex @code{gforth-fast}, difference from @code{gforth}
12331: @cindex backtraces with @code{gforth-fast}
12332: @cindex return stack dump with @code{gforth-fast}
1.79 anton 12333: @code{Gforth} is able to do a return stack dump for throws generated
1.25 anton 12334: from primitives (e.g., invalid memory address, stack empty etc.);
12335: @code{gforth-fast} is only able to do a return stack dump from a
1.96 anton 12336: directly called @code{throw} (including @code{abort} etc.). Given an
1.30 anton 12337: exception caused by a primitive in @code{gforth-fast}, you will
12338: typically see no return stack dump at all; however, if the exception is
12339: caught by @code{catch} (e.g., for restoring some state), and then
12340: @code{throw}n again, the return stack dump will be for the first such
12341: @code{throw}.
1.2 jwilke 12342:
1.5 anton 12343: @c ******************************************************************
1.24 anton 12344: @node Tools, ANS conformance, Error messages, Top
1.1 anton 12345: @chapter Tools
12346:
12347: @menu
12348: * ANS Report:: Report the words used, sorted by wordset.
12349: @end menu
12350:
12351: See also @ref{Emacs and Gforth}.
12352:
12353: @node ANS Report, , Tools, Tools
12354: @section @file{ans-report.fs}: Report the words used, sorted by wordset
12355: @cindex @file{ans-report.fs}
12356: @cindex report the words used in your program
12357: @cindex words used in your program
12358:
12359: If you want to label a Forth program as ANS Forth Program, you must
12360: document which wordsets the program uses; for extension wordsets, it is
12361: helpful to list the words the program requires from these wordsets
12362: (because Forth systems are allowed to provide only some words of them).
12363:
12364: The @file{ans-report.fs} tool makes it easy for you to determine which
12365: words from which wordset and which non-ANS words your application
12366: uses. You simply have to include @file{ans-report.fs} before loading the
12367: program you want to check. After loading your program, you can get the
12368: report with @code{print-ans-report}. A typical use is to run this as
12369: batch job like this:
12370: @example
12371: gforth ans-report.fs myprog.fs -e "print-ans-report bye"
12372: @end example
12373:
12374: The output looks like this (for @file{compat/control.fs}):
12375: @example
12376: The program uses the following words
12377: from CORE :
12378: : POSTPONE THEN ; immediate ?dup IF 0=
12379: from BLOCK-EXT :
12380: \
12381: from FILE :
12382: (
12383: @end example
12384:
12385: @subsection Caveats
12386:
12387: Note that @file{ans-report.fs} just checks which words are used, not whether
12388: they are used in an ANS Forth conforming way!
12389:
12390: Some words are defined in several wordsets in the
12391: standard. @file{ans-report.fs} reports them for only one of the
12392: wordsets, and not necessarily the one you expect. It depends on usage
12393: which wordset is the right one to specify. E.g., if you only use the
12394: compilation semantics of @code{S"}, it is a Core word; if you also use
12395: its interpretation semantics, it is a File word.
12396:
12397: @c ******************************************************************
1.65 anton 12398: @node ANS conformance, Standard vs Extensions, Tools, Top
1.1 anton 12399: @chapter ANS conformance
12400: @cindex ANS conformance of Gforth
12401:
12402: To the best of our knowledge, Gforth is an
12403:
12404: ANS Forth System
12405: @itemize @bullet
12406: @item providing the Core Extensions word set
12407: @item providing the Block word set
12408: @item providing the Block Extensions word set
12409: @item providing the Double-Number word set
12410: @item providing the Double-Number Extensions word set
12411: @item providing the Exception word set
12412: @item providing the Exception Extensions word set
12413: @item providing the Facility word set
1.40 anton 12414: @item providing @code{EKEY}, @code{EKEY>CHAR}, @code{EKEY?}, @code{MS} and @code{TIME&DATE} from the Facility Extensions word set
1.1 anton 12415: @item providing the File Access word set
12416: @item providing the File Access Extensions word set
12417: @item providing the Floating-Point word set
12418: @item providing the Floating-Point Extensions word set
12419: @item providing the Locals word set
12420: @item providing the Locals Extensions word set
12421: @item providing the Memory-Allocation word set
12422: @item providing the Memory-Allocation Extensions word set (that one's easy)
12423: @item providing the Programming-Tools word set
12424: @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
12425: @item providing the Search-Order word set
12426: @item providing the Search-Order Extensions word set
12427: @item providing the String word set
12428: @item providing the String Extensions word set (another easy one)
12429: @end itemize
12430:
12431: @cindex system documentation
12432: In addition, ANS Forth systems are required to document certain
12433: implementation choices. This chapter tries to meet these
12434: requirements. In many cases it gives a way to ask the system for the
12435: information instead of providing the information directly, in
12436: particular, if the information depends on the processor, the operating
12437: system or the installation options chosen, or if they are likely to
12438: change during the maintenance of Gforth.
12439:
12440: @comment The framework for the rest has been taken from pfe.
12441:
12442: @menu
12443: * The Core Words::
12444: * The optional Block word set::
12445: * The optional Double Number word set::
12446: * The optional Exception word set::
12447: * The optional Facility word set::
12448: * The optional File-Access word set::
12449: * The optional Floating-Point word set::
12450: * The optional Locals word set::
12451: * The optional Memory-Allocation word set::
12452: * The optional Programming-Tools word set::
12453: * The optional Search-Order word set::
12454: @end menu
12455:
12456:
12457: @c =====================================================================
12458: @node The Core Words, The optional Block word set, ANS conformance, ANS conformance
12459: @comment node-name, next, previous, up
12460: @section The Core Words
12461: @c =====================================================================
12462: @cindex core words, system documentation
12463: @cindex system documentation, core words
12464:
12465: @menu
12466: * core-idef:: Implementation Defined Options
12467: * core-ambcond:: Ambiguous Conditions
12468: * core-other:: Other System Documentation
12469: @end menu
12470:
12471: @c ---------------------------------------------------------------------
12472: @node core-idef, core-ambcond, The Core Words, The Core Words
12473: @subsection Implementation Defined Options
12474: @c ---------------------------------------------------------------------
12475: @cindex core words, implementation-defined options
12476: @cindex implementation-defined options, core words
12477:
12478:
12479: @table @i
12480: @item (Cell) aligned addresses:
12481: @cindex cell-aligned addresses
12482: @cindex aligned addresses
12483: processor-dependent. Gforth's alignment words perform natural alignment
12484: (e.g., an address aligned for a datum of size 8 is divisible by
12485: 8). Unaligned accesses usually result in a @code{-23 THROW}.
12486:
12487: @item @code{EMIT} and non-graphic characters:
12488: @cindex @code{EMIT} and non-graphic characters
12489: @cindex non-graphic characters and @code{EMIT}
12490: The character is output using the C library function (actually, macro)
12491: @code{putc}.
12492:
12493: @item character editing of @code{ACCEPT} and @code{EXPECT}:
12494: @cindex character editing of @code{ACCEPT} and @code{EXPECT}
12495: @cindex editing in @code{ACCEPT} and @code{EXPECT}
12496: @cindex @code{ACCEPT}, editing
12497: @cindex @code{EXPECT}, editing
12498: This is modeled on the GNU readline library (@pxref{Readline
12499: Interaction, , Command Line Editing, readline, The GNU Readline
12500: Library}) with Emacs-like key bindings. @kbd{Tab} deviates a little by
12501: producing a full word completion every time you type it (instead of
1.28 crook 12502: producing the common prefix of all completions). @xref{Command-line editing}.
1.1 anton 12503:
12504: @item character set:
12505: @cindex character set
12506: The character set of your computer and display device. Gforth is
12507: 8-bit-clean (but some other component in your system may make trouble).
12508:
12509: @item Character-aligned address requirements:
12510: @cindex character-aligned address requirements
12511: installation-dependent. Currently a character is represented by a C
12512: @code{unsigned char}; in the future we might switch to @code{wchar_t}
12513: (Comments on that requested).
12514:
12515: @item character-set extensions and matching of names:
12516: @cindex character-set extensions and matching of names
1.26 crook 12517: @cindex case-sensitivity for name lookup
12518: @cindex name lookup, case-sensitivity
12519: @cindex locale and case-sensitivity
1.21 crook 12520: Any character except the ASCII NUL character can be used in a
1.1 anton 12521: name. Matching is case-insensitive (except in @code{TABLE}s). The
1.47 crook 12522: matching is performed using the C library function @code{strncasecmp}, whose
1.1 anton 12523: function is probably influenced by the locale. E.g., the @code{C} locale
12524: does not know about accents and umlauts, so they are matched
12525: case-sensitively in that locale. For portability reasons it is best to
12526: write programs such that they work in the @code{C} locale. Then one can
12527: use libraries written by a Polish programmer (who might use words
12528: containing ISO Latin-2 encoded characters) and by a French programmer
12529: (ISO Latin-1) in the same program (of course, @code{WORDS} will produce
12530: funny results for some of the words (which ones, depends on the font you
12531: are using)). Also, the locale you prefer may not be available in other
12532: operating systems. Hopefully, Unicode will solve these problems one day.
12533:
12534: @item conditions under which control characters match a space delimiter:
12535: @cindex space delimiters
12536: @cindex control characters as delimiters
12537: If @code{WORD} is called with the space character as a delimiter, all
12538: white-space characters (as identified by the C macro @code{isspace()})
12539: are delimiters. @code{PARSE}, on the other hand, treats space like other
1.44 crook 12540: delimiters. @code{SWORD} treats space like @code{WORD}, but behaves
1.79 anton 12541: like @code{PARSE} otherwise. @code{Name}, which is used by the outer
1.1 anton 12542: interpreter (aka text interpreter) by default, treats all white-space
12543: characters as delimiters.
12544:
1.26 crook 12545: @item format of the control-flow stack:
12546: @cindex control-flow stack, format
12547: The data stack is used as control-flow stack. The size of a control-flow
1.1 anton 12548: stack item in cells is given by the constant @code{cs-item-size}. At the
12549: time of this writing, an item consists of a (pointer to a) locals list
12550: (third), an address in the code (second), and a tag for identifying the
12551: item (TOS). The following tags are used: @code{defstart},
12552: @code{live-orig}, @code{dead-orig}, @code{dest}, @code{do-dest},
12553: @code{scopestart}.
12554:
12555: @item conversion of digits > 35
12556: @cindex digits > 35
12557: The characters @code{[\]^_'} are the digits with the decimal value
12558: 36@minus{}41. There is no way to input many of the larger digits.
12559:
12560: @item display after input terminates in @code{ACCEPT} and @code{EXPECT}:
12561: @cindex @code{EXPECT}, display after end of input
12562: @cindex @code{ACCEPT}, display after end of input
12563: The cursor is moved to the end of the entered string. If the input is
12564: terminated using the @kbd{Return} key, a space is typed.
12565:
12566: @item exception abort sequence of @code{ABORT"}:
12567: @cindex exception abort sequence of @code{ABORT"}
12568: @cindex @code{ABORT"}, exception abort sequence
12569: The error string is stored into the variable @code{"error} and a
12570: @code{-2 throw} is performed.
12571:
12572: @item input line terminator:
12573: @cindex input line terminator
12574: @cindex line terminator on input
1.26 crook 12575: @cindex newline character on input
1.1 anton 12576: For interactive input, @kbd{C-m} (CR) and @kbd{C-j} (LF) terminate
12577: lines. One of these characters is typically produced when you type the
12578: @kbd{Enter} or @kbd{Return} key.
12579:
12580: @item maximum size of a counted string:
12581: @cindex maximum size of a counted string
12582: @cindex counted string, maximum size
12583: @code{s" /counted-string" environment? drop .}. Currently 255 characters
1.79 anton 12584: on all platforms, but this may change.
1.1 anton 12585:
12586: @item maximum size of a parsed string:
12587: @cindex maximum size of a parsed string
12588: @cindex parsed string, maximum size
12589: Given by the constant @code{/line}. Currently 255 characters.
12590:
12591: @item maximum size of a definition name, in characters:
12592: @cindex maximum size of a definition name, in characters
12593: @cindex name, maximum length
12594: 31
12595:
12596: @item maximum string length for @code{ENVIRONMENT?}, in characters:
12597: @cindex maximum string length for @code{ENVIRONMENT?}, in characters
12598: @cindex @code{ENVIRONMENT?} string length, maximum
12599: 31
12600:
12601: @item method of selecting the user input device:
12602: @cindex user input device, method of selecting
12603: The user input device is the standard input. There is currently no way to
12604: change it from within Gforth. However, the input can typically be
12605: redirected in the command line that starts Gforth.
12606:
12607: @item method of selecting the user output device:
12608: @cindex user output device, method of selecting
12609: @code{EMIT} and @code{TYPE} output to the file-id stored in the value
1.10 anton 12610: @code{outfile-id} (@code{stdout} by default). Gforth uses unbuffered
12611: output when the user output device is a terminal, otherwise the output
12612: is buffered.
1.1 anton 12613:
12614: @item methods of dictionary compilation:
12615: What are we expected to document here?
12616:
12617: @item number of bits in one address unit:
12618: @cindex number of bits in one address unit
12619: @cindex address unit, size in bits
12620: @code{s" address-units-bits" environment? drop .}. 8 in all current
1.79 anton 12621: platforms.
1.1 anton 12622:
12623: @item number representation and arithmetic:
12624: @cindex number representation and arithmetic
1.79 anton 12625: Processor-dependent. Binary two's complement on all current platforms.
1.1 anton 12626:
12627: @item ranges for integer types:
12628: @cindex ranges for integer types
12629: @cindex integer types, ranges
12630: Installation-dependent. Make environmental queries for @code{MAX-N},
12631: @code{MAX-U}, @code{MAX-D} and @code{MAX-UD}. The lower bounds for
12632: unsigned (and positive) types is 0. The lower bound for signed types on
12633: two's complement and one's complement machines machines can be computed
12634: by adding 1 to the upper bound.
12635:
12636: @item read-only data space regions:
12637: @cindex read-only data space regions
12638: @cindex data-space, read-only regions
12639: The whole Forth data space is writable.
12640:
12641: @item size of buffer at @code{WORD}:
12642: @cindex size of buffer at @code{WORD}
12643: @cindex @code{WORD} buffer size
12644: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
12645: shared with the pictured numeric output string. If overwriting
12646: @code{PAD} is acceptable, it is as large as the remaining dictionary
12647: space, although only as much can be sensibly used as fits in a counted
12648: string.
12649:
12650: @item size of one cell in address units:
12651: @cindex cell size
12652: @code{1 cells .}.
12653:
12654: @item size of one character in address units:
12655: @cindex char size
1.79 anton 12656: @code{1 chars .}. 1 on all current platforms.
1.1 anton 12657:
12658: @item size of the keyboard terminal buffer:
12659: @cindex size of the keyboard terminal buffer
12660: @cindex terminal buffer, size
12661: Varies. You can determine the size at a specific time using @code{lp@@
12662: tib - .}. It is shared with the locals stack and TIBs of files that
12663: include the current file. You can change the amount of space for TIBs
12664: and locals stack at Gforth startup with the command line option
12665: @code{-l}.
12666:
12667: @item size of the pictured numeric output buffer:
12668: @cindex size of the pictured numeric output buffer
12669: @cindex pictured numeric output buffer, size
12670: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
12671: shared with @code{WORD}.
12672:
12673: @item size of the scratch area returned by @code{PAD}:
12674: @cindex size of the scratch area returned by @code{PAD}
12675: @cindex @code{PAD} size
12676: The remainder of dictionary space. @code{unused pad here - - .}.
12677:
12678: @item system case-sensitivity characteristics:
12679: @cindex case-sensitivity characteristics
1.26 crook 12680: Dictionary searches are case-insensitive (except in
1.1 anton 12681: @code{TABLE}s). However, as explained above under @i{character-set
12682: extensions}, the matching for non-ASCII characters is determined by the
12683: locale you are using. In the default @code{C} locale all non-ASCII
12684: characters are matched case-sensitively.
12685:
12686: @item system prompt:
12687: @cindex system prompt
12688: @cindex prompt
12689: @code{ ok} in interpret state, @code{ compiled} in compile state.
12690:
12691: @item division rounding:
12692: @cindex division rounding
12693: installation dependent. @code{s" floored" environment? drop .}. We leave
12694: the choice to @code{gcc} (what to use for @code{/}) and to you (whether
12695: to use @code{fm/mod}, @code{sm/rem} or simply @code{/}).
12696:
12697: @item values of @code{STATE} when true:
12698: @cindex @code{STATE} values
12699: -1.
12700:
12701: @item values returned after arithmetic overflow:
12702: On two's complement machines, arithmetic is performed modulo
12703: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
12704: arithmetic (with appropriate mapping for signed types). Division by zero
12705: typically results in a @code{-55 throw} (Floating-point unidentified
1.80 anton 12706: fault) or @code{-10 throw} (divide by zero).
1.1 anton 12707:
12708: @item whether the current definition can be found after @t{DOES>}:
12709: @cindex @t{DOES>}, visibility of current definition
12710: No.
12711:
12712: @end table
12713:
12714: @c ---------------------------------------------------------------------
12715: @node core-ambcond, core-other, core-idef, The Core Words
12716: @subsection Ambiguous conditions
12717: @c ---------------------------------------------------------------------
12718: @cindex core words, ambiguous conditions
12719: @cindex ambiguous conditions, core words
12720:
12721: @table @i
12722:
12723: @item a name is neither a word nor a number:
12724: @cindex name not found
1.26 crook 12725: @cindex undefined word
1.80 anton 12726: @code{-13 throw} (Undefined word).
1.1 anton 12727:
12728: @item a definition name exceeds the maximum length allowed:
1.26 crook 12729: @cindex word name too long
1.1 anton 12730: @code{-19 throw} (Word name too long)
12731:
12732: @item addressing a region not inside the various data spaces of the forth system:
12733: @cindex Invalid memory address
1.32 anton 12734: The stacks, code space and header space are accessible. Machine code space is
1.1 anton 12735: typically readable. Accessing other addresses gives results dependent on
12736: the operating system. On decent systems: @code{-9 throw} (Invalid memory
12737: address).
12738:
12739: @item argument type incompatible with parameter:
1.26 crook 12740: @cindex argument type mismatch
1.1 anton 12741: This is usually not caught. Some words perform checks, e.g., the control
12742: flow words, and issue a @code{ABORT"} or @code{-12 THROW} (Argument type
12743: mismatch).
12744:
12745: @item attempting to obtain the execution token of a word with undefined execution semantics:
12746: @cindex Interpreting a compile-only word, for @code{'} etc.
12747: @cindex execution token of words with undefined execution semantics
12748: @code{-14 throw} (Interpreting a compile-only word). In some cases, you
12749: get an execution token for @code{compile-only-error} (which performs a
12750: @code{-14 throw} when executed).
12751:
12752: @item dividing by zero:
12753: @cindex dividing by zero
12754: @cindex floating point unidentified fault, integer division
1.80 anton 12755: On some platforms, this produces a @code{-10 throw} (Division by
1.24 anton 12756: zero); on other systems, this typically results in a @code{-55 throw}
12757: (Floating-point unidentified fault).
1.1 anton 12758:
12759: @item insufficient data stack or return stack space:
12760: @cindex insufficient data stack or return stack space
12761: @cindex stack overflow
1.26 crook 12762: @cindex address alignment exception, stack overflow
1.1 anton 12763: @cindex Invalid memory address, stack overflow
12764: Depending on the operating system, the installation, and the invocation
12765: of Gforth, this is either checked by the memory management hardware, or
1.24 anton 12766: it is not checked. If it is checked, you typically get a @code{-3 throw}
12767: (Stack overflow), @code{-5 throw} (Return stack overflow), or @code{-9
12768: throw} (Invalid memory address) (depending on the platform and how you
12769: achieved the overflow) as soon as the overflow happens. If it is not
12770: checked, overflows typically result in mysterious illegal memory
12771: accesses, producing @code{-9 throw} (Invalid memory address) or
12772: @code{-23 throw} (Address alignment exception); they might also destroy
12773: the internal data structure of @code{ALLOCATE} and friends, resulting in
12774: various errors in these words.
1.1 anton 12775:
12776: @item insufficient space for loop control parameters:
12777: @cindex insufficient space for loop control parameters
1.80 anton 12778: Like other return stack overflows.
1.1 anton 12779:
12780: @item insufficient space in the dictionary:
12781: @cindex insufficient space in the dictionary
12782: @cindex dictionary overflow
1.12 anton 12783: If you try to allot (either directly with @code{allot}, or indirectly
12784: with @code{,}, @code{create} etc.) more memory than available in the
12785: dictionary, you get a @code{-8 throw} (Dictionary overflow). If you try
12786: to access memory beyond the end of the dictionary, the results are
12787: similar to stack overflows.
1.1 anton 12788:
12789: @item interpreting a word with undefined interpretation semantics:
12790: @cindex interpreting a word with undefined interpretation semantics
12791: @cindex Interpreting a compile-only word
12792: For some words, we have defined interpretation semantics. For the
12793: others: @code{-14 throw} (Interpreting a compile-only word).
12794:
12795: @item modifying the contents of the input buffer or a string literal:
12796: @cindex modifying the contents of the input buffer or a string literal
12797: These are located in writable memory and can be modified.
12798:
12799: @item overflow of the pictured numeric output string:
12800: @cindex overflow of the pictured numeric output string
12801: @cindex pictured numeric output string, overflow
1.24 anton 12802: @code{-17 throw} (Pictured numeric ouput string overflow).
1.1 anton 12803:
12804: @item parsed string overflow:
12805: @cindex parsed string overflow
12806: @code{PARSE} cannot overflow. @code{WORD} does not check for overflow.
12807:
12808: @item producing a result out of range:
12809: @cindex result out of range
12810: On two's complement machines, arithmetic is performed modulo
12811: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
12812: arithmetic (with appropriate mapping for signed types). Division by zero
1.24 anton 12813: typically results in a @code{-10 throw} (divide by zero) or @code{-55
12814: throw} (floating point unidentified fault). @code{convert} and
12815: @code{>number} currently overflow silently.
1.1 anton 12816:
12817: @item reading from an empty data or return stack:
12818: @cindex stack empty
12819: @cindex stack underflow
1.24 anton 12820: @cindex return stack underflow
1.1 anton 12821: The data stack is checked by the outer (aka text) interpreter after
12822: every word executed. If it has underflowed, a @code{-4 throw} (Stack
12823: underflow) is performed. Apart from that, stacks may be checked or not,
1.24 anton 12824: depending on operating system, installation, and invocation. If they are
12825: caught by a check, they typically result in @code{-4 throw} (Stack
12826: underflow), @code{-6 throw} (Return stack underflow) or @code{-9 throw}
12827: (Invalid memory address), depending on the platform and which stack
12828: underflows and by how much. Note that even if the system uses checking
12829: (through the MMU), your program may have to underflow by a significant
12830: number of stack items to trigger the reaction (the reason for this is
12831: that the MMU, and therefore the checking, works with a page-size
12832: granularity). If there is no checking, the symptoms resulting from an
12833: underflow are similar to those from an overflow. Unbalanced return
1.80 anton 12834: stack errors can result in a variety of symptoms, including @code{-9 throw}
1.24 anton 12835: (Invalid memory address) and Illegal Instruction (typically @code{-260
12836: throw}).
1.1 anton 12837:
12838: @item unexpected end of the input buffer, resulting in an attempt to use a zero-length string as a name:
12839: @cindex unexpected end of the input buffer
12840: @cindex zero-length string as a name
12841: @cindex Attempt to use zero-length string as a name
12842: @code{Create} and its descendants perform a @code{-16 throw} (Attempt to
12843: use zero-length string as a name). Words like @code{'} probably will not
12844: find what they search. Note that it is possible to create zero-length
12845: names with @code{nextname} (should it not?).
12846:
12847: @item @code{>IN} greater than input buffer:
12848: @cindex @code{>IN} greater than input buffer
12849: The next invocation of a parsing word returns a string with length 0.
12850:
12851: @item @code{RECURSE} appears after @code{DOES>}:
12852: @cindex @code{RECURSE} appears after @code{DOES>}
12853: Compiles a recursive call to the defining word, not to the defined word.
12854:
12855: @item argument input source different than current input source for @code{RESTORE-INPUT}:
12856: @cindex argument input source different than current input source for @code{RESTORE-INPUT}
1.26 crook 12857: @cindex argument type mismatch, @code{RESTORE-INPUT}
1.1 anton 12858: @cindex @code{RESTORE-INPUT}, Argument type mismatch
12859: @code{-12 THROW}. Note that, once an input file is closed (e.g., because
12860: the end of the file was reached), its source-id may be
12861: reused. Therefore, restoring an input source specification referencing a
12862: closed file may lead to unpredictable results instead of a @code{-12
12863: THROW}.
12864:
12865: In the future, Gforth may be able to restore input source specifications
12866: from other than the current input source.
12867:
12868: @item data space containing definitions gets de-allocated:
12869: @cindex data space containing definitions gets de-allocated
12870: Deallocation with @code{allot} is not checked. This typically results in
12871: memory access faults or execution of illegal instructions.
12872:
12873: @item data space read/write with incorrect alignment:
12874: @cindex data space read/write with incorrect alignment
12875: @cindex alignment faults
1.26 crook 12876: @cindex address alignment exception
1.1 anton 12877: Processor-dependent. Typically results in a @code{-23 throw} (Address
1.12 anton 12878: alignment exception). Under Linux-Intel on a 486 or later processor with
1.1 anton 12879: alignment turned on, incorrect alignment results in a @code{-9 throw}
12880: (Invalid memory address). There are reportedly some processors with
1.12 anton 12881: alignment restrictions that do not report violations.
1.1 anton 12882:
12883: @item data space pointer not properly aligned, @code{,}, @code{C,}:
12884: @cindex data space pointer not properly aligned, @code{,}, @code{C,}
12885: Like other alignment errors.
12886:
12887: @item less than u+2 stack items (@code{PICK} and @code{ROLL}):
12888: Like other stack underflows.
12889:
12890: @item loop control parameters not available:
12891: @cindex loop control parameters not available
12892: Not checked. The counted loop words simply assume that the top of return
12893: stack items are loop control parameters and behave accordingly.
12894:
12895: @item most recent definition does not have a name (@code{IMMEDIATE}):
12896: @cindex most recent definition does not have a name (@code{IMMEDIATE})
12897: @cindex last word was headerless
12898: @code{abort" last word was headerless"}.
12899:
12900: @item name not defined by @code{VALUE} used by @code{TO}:
12901: @cindex name not defined by @code{VALUE} used by @code{TO}
12902: @cindex @code{TO} on non-@code{VALUE}s
12903: @cindex Invalid name argument, @code{TO}
12904: @code{-32 throw} (Invalid name argument) (unless name is a local or was
12905: defined by @code{CONSTANT}; in the latter case it just changes the constant).
12906:
12907: @item name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}):
12908: @cindex name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]})
1.26 crook 12909: @cindex undefined word, @code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}
1.1 anton 12910: @code{-13 throw} (Undefined word)
12911:
12912: @item parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN}):
12913: @cindex parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN})
12914: Gforth behaves as if they were of the same type. I.e., you can predict
12915: the behaviour by interpreting all parameters as, e.g., signed.
12916:
12917: @item @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}:
12918: @cindex @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}
12919: Assume @code{: X POSTPONE TO ; IMMEDIATE}. @code{X} performs the
12920: compilation semantics of @code{TO}.
12921:
12922: @item String longer than a counted string returned by @code{WORD}:
1.26 crook 12923: @cindex string longer than a counted string returned by @code{WORD}
1.1 anton 12924: @cindex @code{WORD}, string overflow
12925: Not checked. The string will be ok, but the count will, of course,
12926: contain only the least significant bits of the length.
12927:
12928: @item u greater than or equal to the number of bits in a cell (@code{LSHIFT}, @code{RSHIFT}):
12929: @cindex @code{LSHIFT}, large shift counts
12930: @cindex @code{RSHIFT}, large shift counts
12931: Processor-dependent. Typical behaviours are returning 0 and using only
12932: the low bits of the shift count.
12933:
12934: @item word not defined via @code{CREATE}:
12935: @cindex @code{>BODY} of non-@code{CREATE}d words
12936: @code{>BODY} produces the PFA of the word no matter how it was defined.
12937:
12938: @cindex @code{DOES>} of non-@code{CREATE}d words
12939: @code{DOES>} changes the execution semantics of the last defined word no
12940: matter how it was defined. E.g., @code{CONSTANT DOES>} is equivalent to
12941: @code{CREATE , DOES>}.
12942:
12943: @item words improperly used outside @code{<#} and @code{#>}:
12944: Not checked. As usual, you can expect memory faults.
12945:
12946: @end table
12947:
12948:
12949: @c ---------------------------------------------------------------------
12950: @node core-other, , core-ambcond, The Core Words
12951: @subsection Other system documentation
12952: @c ---------------------------------------------------------------------
12953: @cindex other system documentation, core words
12954: @cindex core words, other system documentation
12955:
12956: @table @i
12957: @item nonstandard words using @code{PAD}:
12958: @cindex @code{PAD} use by nonstandard words
12959: None.
12960:
12961: @item operator's terminal facilities available:
12962: @cindex operator's terminal facilities available
1.80 anton 12963: After processing the OS's command line, Gforth goes into interactive mode,
1.1 anton 12964: and you can give commands to Gforth interactively. The actual facilities
12965: available depend on how you invoke Gforth.
12966:
12967: @item program data space available:
12968: @cindex program data space available
12969: @cindex data space available
12970: @code{UNUSED .} gives the remaining dictionary space. The total
12971: dictionary space can be specified with the @code{-m} switch
12972: (@pxref{Invoking Gforth}) when Gforth starts up.
12973:
12974: @item return stack space available:
12975: @cindex return stack space available
12976: You can compute the total return stack space in cells with
12977: @code{s" RETURN-STACK-CELLS" environment? drop .}. You can specify it at
12978: startup time with the @code{-r} switch (@pxref{Invoking Gforth}).
12979:
12980: @item stack space available:
12981: @cindex stack space available
12982: You can compute the total data stack space in cells with
12983: @code{s" STACK-CELLS" environment? drop .}. You can specify it at
12984: startup time with the @code{-d} switch (@pxref{Invoking Gforth}).
12985:
12986: @item system dictionary space required, in address units:
12987: @cindex system dictionary space required, in address units
12988: Type @code{here forthstart - .} after startup. At the time of this
12989: writing, this gives 80080 (bytes) on a 32-bit system.
12990: @end table
12991:
12992:
12993: @c =====================================================================
12994: @node The optional Block word set, The optional Double Number word set, The Core Words, ANS conformance
12995: @section The optional Block word set
12996: @c =====================================================================
12997: @cindex system documentation, block words
12998: @cindex block words, system documentation
12999:
13000: @menu
13001: * block-idef:: Implementation Defined Options
13002: * block-ambcond:: Ambiguous Conditions
13003: * block-other:: Other System Documentation
13004: @end menu
13005:
13006:
13007: @c ---------------------------------------------------------------------
13008: @node block-idef, block-ambcond, The optional Block word set, The optional Block word set
13009: @subsection Implementation Defined Options
13010: @c ---------------------------------------------------------------------
13011: @cindex implementation-defined options, block words
13012: @cindex block words, implementation-defined options
13013:
13014: @table @i
13015: @item the format for display by @code{LIST}:
13016: @cindex @code{LIST} display format
13017: First the screen number is displayed, then 16 lines of 64 characters,
13018: each line preceded by the line number.
13019:
13020: @item the length of a line affected by @code{\}:
13021: @cindex length of a line affected by @code{\}
13022: @cindex @code{\}, line length in blocks
13023: 64 characters.
13024: @end table
13025:
13026:
13027: @c ---------------------------------------------------------------------
13028: @node block-ambcond, block-other, block-idef, The optional Block word set
13029: @subsection Ambiguous conditions
13030: @c ---------------------------------------------------------------------
13031: @cindex block words, ambiguous conditions
13032: @cindex ambiguous conditions, block words
13033:
13034: @table @i
13035: @item correct block read was not possible:
13036: @cindex block read not possible
13037: Typically results in a @code{throw} of some OS-derived value (between
13038: -512 and -2048). If the blocks file was just not long enough, blanks are
13039: supplied for the missing portion.
13040:
13041: @item I/O exception in block transfer:
13042: @cindex I/O exception in block transfer
13043: @cindex block transfer, I/O exception
13044: Typically results in a @code{throw} of some OS-derived value (between
13045: -512 and -2048).
13046:
13047: @item invalid block number:
13048: @cindex invalid block number
13049: @cindex block number invalid
13050: @code{-35 throw} (Invalid block number)
13051:
13052: @item a program directly alters the contents of @code{BLK}:
13053: @cindex @code{BLK}, altering @code{BLK}
13054: The input stream is switched to that other block, at the same
13055: position. If the storing to @code{BLK} happens when interpreting
13056: non-block input, the system will get quite confused when the block ends.
13057:
13058: @item no current block buffer for @code{UPDATE}:
13059: @cindex @code{UPDATE}, no current block buffer
13060: @code{UPDATE} has no effect.
13061:
13062: @end table
13063:
13064: @c ---------------------------------------------------------------------
13065: @node block-other, , block-ambcond, The optional Block word set
13066: @subsection Other system documentation
13067: @c ---------------------------------------------------------------------
13068: @cindex other system documentation, block words
13069: @cindex block words, other system documentation
13070:
13071: @table @i
13072: @item any restrictions a multiprogramming system places on the use of buffer addresses:
13073: No restrictions (yet).
13074:
13075: @item the number of blocks available for source and data:
13076: depends on your disk space.
13077:
13078: @end table
13079:
13080:
13081: @c =====================================================================
13082: @node The optional Double Number word set, The optional Exception word set, The optional Block word set, ANS conformance
13083: @section The optional Double Number word set
13084: @c =====================================================================
13085: @cindex system documentation, double words
13086: @cindex double words, system documentation
13087:
13088: @menu
13089: * double-ambcond:: Ambiguous Conditions
13090: @end menu
13091:
13092:
13093: @c ---------------------------------------------------------------------
13094: @node double-ambcond, , The optional Double Number word set, The optional Double Number word set
13095: @subsection Ambiguous conditions
13096: @c ---------------------------------------------------------------------
13097: @cindex double words, ambiguous conditions
13098: @cindex ambiguous conditions, double words
13099:
13100: @table @i
1.29 crook 13101: @item @i{d} outside of range of @i{n} in @code{D>S}:
13102: @cindex @code{D>S}, @i{d} out of range of @i{n}
13103: The least significant cell of @i{d} is produced.
1.1 anton 13104:
13105: @end table
13106:
13107:
13108: @c =====================================================================
13109: @node The optional Exception word set, The optional Facility word set, The optional Double Number word set, ANS conformance
13110: @section The optional Exception word set
13111: @c =====================================================================
13112: @cindex system documentation, exception words
13113: @cindex exception words, system documentation
13114:
13115: @menu
13116: * exception-idef:: Implementation Defined Options
13117: @end menu
13118:
13119:
13120: @c ---------------------------------------------------------------------
13121: @node exception-idef, , The optional Exception word set, The optional Exception word set
13122: @subsection Implementation Defined Options
13123: @c ---------------------------------------------------------------------
13124: @cindex implementation-defined options, exception words
13125: @cindex exception words, implementation-defined options
13126:
13127: @table @i
13128: @item @code{THROW}-codes used in the system:
13129: @cindex @code{THROW}-codes used in the system
13130: The codes -256@minus{}-511 are used for reporting signals. The mapping
1.29 crook 13131: from OS signal numbers to throw codes is -256@minus{}@i{signal}. The
1.1 anton 13132: codes -512@minus{}-2047 are used for OS errors (for file and memory
13133: allocation operations). The mapping from OS error numbers to throw codes
13134: is -512@minus{}@code{errno}. One side effect of this mapping is that
13135: undefined OS errors produce a message with a strange number; e.g.,
13136: @code{-1000 THROW} results in @code{Unknown error 488} on my system.
13137: @end table
13138:
13139: @c =====================================================================
13140: @node The optional Facility word set, The optional File-Access word set, The optional Exception word set, ANS conformance
13141: @section The optional Facility word set
13142: @c =====================================================================
13143: @cindex system documentation, facility words
13144: @cindex facility words, system documentation
13145:
13146: @menu
13147: * facility-idef:: Implementation Defined Options
13148: * facility-ambcond:: Ambiguous Conditions
13149: @end menu
13150:
13151:
13152: @c ---------------------------------------------------------------------
13153: @node facility-idef, facility-ambcond, The optional Facility word set, The optional Facility word set
13154: @subsection Implementation Defined Options
13155: @c ---------------------------------------------------------------------
13156: @cindex implementation-defined options, facility words
13157: @cindex facility words, implementation-defined options
13158:
13159: @table @i
13160: @item encoding of keyboard events (@code{EKEY}):
13161: @cindex keyboard events, encoding in @code{EKEY}
13162: @cindex @code{EKEY}, encoding of keyboard events
1.40 anton 13163: Keys corresponding to ASCII characters are encoded as ASCII characters.
1.41 anton 13164: Other keys are encoded with the constants @code{k-left}, @code{k-right},
13165: @code{k-up}, @code{k-down}, @code{k-home}, @code{k-end}, @code{k1},
13166: @code{k2}, @code{k3}, @code{k4}, @code{k5}, @code{k6}, @code{k7},
13167: @code{k8}, @code{k9}, @code{k10}, @code{k11}, @code{k12}.
1.40 anton 13168:
1.1 anton 13169:
13170: @item duration of a system clock tick:
13171: @cindex duration of a system clock tick
13172: @cindex clock tick duration
13173: System dependent. With respect to @code{MS}, the time is specified in
13174: microseconds. How well the OS and the hardware implement this, is
13175: another question.
13176:
13177: @item repeatability to be expected from the execution of @code{MS}:
13178: @cindex repeatability to be expected from the execution of @code{MS}
13179: @cindex @code{MS}, repeatability to be expected
13180: System dependent. On Unix, a lot depends on load. If the system is
13181: lightly loaded, and the delay is short enough that Gforth does not get
13182: swapped out, the performance should be acceptable. Under MS-DOS and
13183: other single-tasking systems, it should be good.
13184:
13185: @end table
13186:
13187:
13188: @c ---------------------------------------------------------------------
13189: @node facility-ambcond, , facility-idef, The optional Facility word set
13190: @subsection Ambiguous conditions
13191: @c ---------------------------------------------------------------------
13192: @cindex facility words, ambiguous conditions
13193: @cindex ambiguous conditions, facility words
13194:
13195: @table @i
13196: @item @code{AT-XY} can't be performed on user output device:
13197: @cindex @code{AT-XY} can't be performed on user output device
13198: Largely terminal dependent. No range checks are done on the arguments.
13199: No errors are reported. You may see some garbage appearing, you may see
13200: simply nothing happen.
13201:
13202: @end table
13203:
13204:
13205: @c =====================================================================
13206: @node The optional File-Access word set, The optional Floating-Point word set, The optional Facility word set, ANS conformance
13207: @section The optional File-Access word set
13208: @c =====================================================================
13209: @cindex system documentation, file words
13210: @cindex file words, system documentation
13211:
13212: @menu
13213: * file-idef:: Implementation Defined Options
13214: * file-ambcond:: Ambiguous Conditions
13215: @end menu
13216:
13217: @c ---------------------------------------------------------------------
13218: @node file-idef, file-ambcond, The optional File-Access word set, The optional File-Access word set
13219: @subsection Implementation Defined Options
13220: @c ---------------------------------------------------------------------
13221: @cindex implementation-defined options, file words
13222: @cindex file words, implementation-defined options
13223:
13224: @table @i
13225: @item file access methods used:
13226: @cindex file access methods used
13227: @code{R/O}, @code{R/W} and @code{BIN} work as you would
13228: expect. @code{W/O} translates into the C file opening mode @code{w} (or
13229: @code{wb}): The file is cleared, if it exists, and created, if it does
13230: not (with both @code{open-file} and @code{create-file}). Under Unix
13231: @code{create-file} creates a file with 666 permissions modified by your
13232: umask.
13233:
13234: @item file exceptions:
13235: @cindex file exceptions
13236: The file words do not raise exceptions (except, perhaps, memory access
13237: faults when you pass illegal addresses or file-ids).
13238:
13239: @item file line terminator:
13240: @cindex file line terminator
13241: System-dependent. Gforth uses C's newline character as line
13242: terminator. What the actual character code(s) of this are is
13243: system-dependent.
13244:
13245: @item file name format:
13246: @cindex file name format
13247: System dependent. Gforth just uses the file name format of your OS.
13248:
13249: @item information returned by @code{FILE-STATUS}:
13250: @cindex @code{FILE-STATUS}, returned information
13251: @code{FILE-STATUS} returns the most powerful file access mode allowed
13252: for the file: Either @code{R/O}, @code{W/O} or @code{R/W}. If the file
13253: cannot be accessed, @code{R/O BIN} is returned. @code{BIN} is applicable
13254: along with the returned mode.
13255:
13256: @item input file state after an exception when including source:
13257: @cindex exception when including source
13258: All files that are left via the exception are closed.
13259:
1.29 crook 13260: @item @i{ior} values and meaning:
13261: @cindex @i{ior} values and meaning
1.68 anton 13262: @cindex @i{wior} values and meaning
1.29 crook 13263: The @i{ior}s returned by the file and memory allocation words are
1.1 anton 13264: intended as throw codes. They typically are in the range
13265: -512@minus{}-2047 of OS errors. The mapping from OS error numbers to
1.29 crook 13266: @i{ior}s is -512@minus{}@i{errno}.
1.1 anton 13267:
13268: @item maximum depth of file input nesting:
13269: @cindex maximum depth of file input nesting
13270: @cindex file input nesting, maximum depth
13271: limited by the amount of return stack, locals/TIB stack, and the number
13272: of open files available. This should not give you troubles.
13273:
13274: @item maximum size of input line:
13275: @cindex maximum size of input line
13276: @cindex input line size, maximum
13277: @code{/line}. Currently 255.
13278:
13279: @item methods of mapping block ranges to files:
13280: @cindex mapping block ranges to files
13281: @cindex files containing blocks
13282: @cindex blocks in files
13283: By default, blocks are accessed in the file @file{blocks.fb} in the
13284: current working directory. The file can be switched with @code{USE}.
13285:
13286: @item number of string buffers provided by @code{S"}:
13287: @cindex @code{S"}, number of string buffers
13288: 1
13289:
13290: @item size of string buffer used by @code{S"}:
13291: @cindex @code{S"}, size of string buffer
13292: @code{/line}. currently 255.
13293:
13294: @end table
13295:
13296: @c ---------------------------------------------------------------------
13297: @node file-ambcond, , file-idef, The optional File-Access word set
13298: @subsection Ambiguous conditions
13299: @c ---------------------------------------------------------------------
13300: @cindex file words, ambiguous conditions
13301: @cindex ambiguous conditions, file words
13302:
13303: @table @i
13304: @item attempting to position a file outside its boundaries:
13305: @cindex @code{REPOSITION-FILE}, outside the file's boundaries
13306: @code{REPOSITION-FILE} is performed as usual: Afterwards,
13307: @code{FILE-POSITION} returns the value given to @code{REPOSITION-FILE}.
13308:
13309: @item attempting to read from file positions not yet written:
13310: @cindex reading from file positions not yet written
13311: End-of-file, i.e., zero characters are read and no error is reported.
13312:
1.29 crook 13313: @item @i{file-id} is invalid (@code{INCLUDE-FILE}):
13314: @cindex @code{INCLUDE-FILE}, @i{file-id} is invalid
1.1 anton 13315: An appropriate exception may be thrown, but a memory fault or other
13316: problem is more probable.
13317:
1.29 crook 13318: @item I/O exception reading or closing @i{file-id} (@code{INCLUDE-FILE}, @code{INCLUDED}):
13319: @cindex @code{INCLUDE-FILE}, I/O exception reading or closing @i{file-id}
13320: @cindex @code{INCLUDED}, I/O exception reading or closing @i{file-id}
13321: The @i{ior} produced by the operation, that discovered the problem, is
1.1 anton 13322: thrown.
13323:
13324: @item named file cannot be opened (@code{INCLUDED}):
13325: @cindex @code{INCLUDED}, named file cannot be opened
1.29 crook 13326: The @i{ior} produced by @code{open-file} is thrown.
1.1 anton 13327:
13328: @item requesting an unmapped block number:
13329: @cindex unmapped block numbers
13330: There are no unmapped legal block numbers. On some operating systems,
13331: writing a block with a large number may overflow the file system and
13332: have an error message as consequence.
13333:
13334: @item using @code{source-id} when @code{blk} is non-zero:
13335: @cindex @code{SOURCE-ID}, behaviour when @code{BLK} is non-zero
13336: @code{source-id} performs its function. Typically it will give the id of
13337: the source which loaded the block. (Better ideas?)
13338:
13339: @end table
13340:
13341:
13342: @c =====================================================================
13343: @node The optional Floating-Point word set, The optional Locals word set, The optional File-Access word set, ANS conformance
13344: @section The optional Floating-Point word set
13345: @c =====================================================================
13346: @cindex system documentation, floating-point words
13347: @cindex floating-point words, system documentation
13348:
13349: @menu
13350: * floating-idef:: Implementation Defined Options
13351: * floating-ambcond:: Ambiguous Conditions
13352: @end menu
13353:
13354:
13355: @c ---------------------------------------------------------------------
13356: @node floating-idef, floating-ambcond, The optional Floating-Point word set, The optional Floating-Point word set
13357: @subsection Implementation Defined Options
13358: @c ---------------------------------------------------------------------
13359: @cindex implementation-defined options, floating-point words
13360: @cindex floating-point words, implementation-defined options
13361:
13362: @table @i
13363: @item format and range of floating point numbers:
13364: @cindex format and range of floating point numbers
13365: @cindex floating point numbers, format and range
13366: System-dependent; the @code{double} type of C.
13367:
1.29 crook 13368: @item results of @code{REPRESENT} when @i{float} is out of range:
13369: @cindex @code{REPRESENT}, results when @i{float} is out of range
1.1 anton 13370: System dependent; @code{REPRESENT} is implemented using the C library
13371: function @code{ecvt()} and inherits its behaviour in this respect.
13372:
13373: @item rounding or truncation of floating-point numbers:
13374: @cindex rounding of floating-point numbers
13375: @cindex truncation of floating-point numbers
13376: @cindex floating-point numbers, rounding or truncation
13377: System dependent; the rounding behaviour is inherited from the hosting C
13378: compiler. IEEE-FP-based (i.e., most) systems by default round to
13379: nearest, and break ties by rounding to even (i.e., such that the last
13380: bit of the mantissa is 0).
13381:
13382: @item size of floating-point stack:
13383: @cindex floating-point stack size
13384: @code{s" FLOATING-STACK" environment? drop .} gives the total size of
13385: the floating-point stack (in floats). You can specify this on startup
13386: with the command-line option @code{-f} (@pxref{Invoking Gforth}).
13387:
13388: @item width of floating-point stack:
13389: @cindex floating-point stack width
13390: @code{1 floats}.
13391:
13392: @end table
13393:
13394:
13395: @c ---------------------------------------------------------------------
13396: @node floating-ambcond, , floating-idef, The optional Floating-Point word set
13397: @subsection Ambiguous conditions
13398: @c ---------------------------------------------------------------------
13399: @cindex floating-point words, ambiguous conditions
13400: @cindex ambiguous conditions, floating-point words
13401:
13402: @table @i
13403: @item @code{df@@} or @code{df!} used with an address that is not double-float aligned:
13404: @cindex @code{df@@} or @code{df!} used with an address that is not double-float aligned
13405: System-dependent. Typically results in a @code{-23 THROW} like other
13406: alignment violations.
13407:
13408: @item @code{f@@} or @code{f!} used with an address that is not float aligned:
13409: @cindex @code{f@@} used with an address that is not float aligned
13410: @cindex @code{f!} used with an address that is not float aligned
13411: System-dependent. Typically results in a @code{-23 THROW} like other
13412: alignment violations.
13413:
13414: @item floating-point result out of range:
13415: @cindex floating-point result out of range
1.80 anton 13416: System-dependent. Can result in a @code{-43 throw} (floating point
13417: overflow), @code{-54 throw} (floating point underflow), @code{-41 throw}
13418: (floating point inexact result), @code{-55 THROW} (Floating-point
1.1 anton 13419: unidentified fault), or can produce a special value representing, e.g.,
13420: Infinity.
13421:
13422: @item @code{sf@@} or @code{sf!} used with an address that is not single-float aligned:
13423: @cindex @code{sf@@} or @code{sf!} used with an address that is not single-float aligned
13424: System-dependent. Typically results in an alignment fault like other
13425: alignment violations.
13426:
1.35 anton 13427: @item @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.}):
13428: @cindex @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.})
1.1 anton 13429: The floating-point number is converted into decimal nonetheless.
13430:
13431: @item Both arguments are equal to zero (@code{FATAN2}):
13432: @cindex @code{FATAN2}, both arguments are equal to zero
13433: System-dependent. @code{FATAN2} is implemented using the C library
13434: function @code{atan2()}.
13435:
1.29 crook 13436: @item Using @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero:
13437: @cindex @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero
13438: System-dependent. Anyway, typically the cos of @i{r1} will not be zero
1.1 anton 13439: because of small errors and the tan will be a very large (or very small)
13440: but finite number.
13441:
1.29 crook 13442: @item @i{d} cannot be presented precisely as a float in @code{D>F}:
13443: @cindex @code{D>F}, @i{d} cannot be presented precisely as a float
1.1 anton 13444: The result is rounded to the nearest float.
13445:
13446: @item dividing by zero:
13447: @cindex dividing by zero, floating-point
13448: @cindex floating-point dividing by zero
13449: @cindex floating-point unidentified fault, FP divide-by-zero
1.80 anton 13450: Platform-dependent; can produce an Infinity, NaN, @code{-42 throw}
13451: (floating point divide by zero) or @code{-55 throw} (Floating-point
13452: unidentified fault).
1.1 anton 13453:
13454: @item exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@}):
13455: @cindex exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@})
13456: System dependent. On IEEE-FP based systems the number is converted into
13457: an infinity.
13458:
1.29 crook 13459: @item @i{float}<1 (@code{FACOSH}):
13460: @cindex @code{FACOSH}, @i{float}<1
1.1 anton 13461: @cindex floating-point unidentified fault, @code{FACOSH}
1.80 anton 13462: Platform-dependent; on IEEE-FP systems typically produces a NaN.
1.1 anton 13463:
1.29 crook 13464: @item @i{float}=<-1 (@code{FLNP1}):
13465: @cindex @code{FLNP1}, @i{float}=<-1
1.1 anton 13466: @cindex floating-point unidentified fault, @code{FLNP1}
1.80 anton 13467: Platform-dependent; on IEEE-FP systems typically produces a NaN (or a
13468: negative infinity for @i{float}=-1).
1.1 anton 13469:
1.29 crook 13470: @item @i{float}=<0 (@code{FLN}, @code{FLOG}):
13471: @cindex @code{FLN}, @i{float}=<0
13472: @cindex @code{FLOG}, @i{float}=<0
1.1 anton 13473: @cindex floating-point unidentified fault, @code{FLN} or @code{FLOG}
1.80 anton 13474: Platform-dependent; on IEEE-FP systems typically produces a NaN (or a
13475: negative infinity for @i{float}=0).
1.1 anton 13476:
1.29 crook 13477: @item @i{float}<0 (@code{FASINH}, @code{FSQRT}):
13478: @cindex @code{FASINH}, @i{float}<0
13479: @cindex @code{FSQRT}, @i{float}<0
1.1 anton 13480: @cindex floating-point unidentified fault, @code{FASINH} or @code{FSQRT}
1.80 anton 13481: Platform-dependent; for @code{fsqrt} this typically gives a NaN, for
13482: @code{fasinh} some platforms produce a NaN, others a number (bug in the
13483: C library?).
1.1 anton 13484:
1.29 crook 13485: @item |@i{float}|>1 (@code{FACOS}, @code{FASIN}, @code{FATANH}):
13486: @cindex @code{FACOS}, |@i{float}|>1
13487: @cindex @code{FASIN}, |@i{float}|>1
13488: @cindex @code{FATANH}, |@i{float}|>1
1.1 anton 13489: @cindex floating-point unidentified fault, @code{FACOS}, @code{FASIN} or @code{FATANH}
1.80 anton 13490: Platform-dependent; IEEE-FP systems typically produce a NaN.
1.1 anton 13491:
1.29 crook 13492: @item integer part of float cannot be represented by @i{d} in @code{F>D}:
13493: @cindex @code{F>D}, integer part of float cannot be represented by @i{d}
1.1 anton 13494: @cindex floating-point unidentified fault, @code{F>D}
1.80 anton 13495: Platform-dependent; typically, some double number is produced and no
13496: error is reported.
1.1 anton 13497:
13498: @item string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.}):
13499: @cindex string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.})
1.80 anton 13500: @code{Precision} characters of the numeric output area are used. If
13501: @code{precision} is too high, these words will smash the data or code
13502: close to @code{here}.
1.1 anton 13503: @end table
13504:
13505: @c =====================================================================
13506: @node The optional Locals word set, The optional Memory-Allocation word set, The optional Floating-Point word set, ANS conformance
13507: @section The optional Locals word set
13508: @c =====================================================================
13509: @cindex system documentation, locals words
13510: @cindex locals words, system documentation
13511:
13512: @menu
13513: * locals-idef:: Implementation Defined Options
13514: * locals-ambcond:: Ambiguous Conditions
13515: @end menu
13516:
13517:
13518: @c ---------------------------------------------------------------------
13519: @node locals-idef, locals-ambcond, The optional Locals word set, The optional Locals word set
13520: @subsection Implementation Defined Options
13521: @c ---------------------------------------------------------------------
13522: @cindex implementation-defined options, locals words
13523: @cindex locals words, implementation-defined options
13524:
13525: @table @i
13526: @item maximum number of locals in a definition:
13527: @cindex maximum number of locals in a definition
13528: @cindex locals, maximum number in a definition
13529: @code{s" #locals" environment? drop .}. Currently 15. This is a lower
13530: bound, e.g., on a 32-bit machine there can be 41 locals of up to 8
13531: characters. The number of locals in a definition is bounded by the size
13532: of locals-buffer, which contains the names of the locals.
13533:
13534: @end table
13535:
13536:
13537: @c ---------------------------------------------------------------------
13538: @node locals-ambcond, , locals-idef, The optional Locals word set
13539: @subsection Ambiguous conditions
13540: @c ---------------------------------------------------------------------
13541: @cindex locals words, ambiguous conditions
13542: @cindex ambiguous conditions, locals words
13543:
13544: @table @i
13545: @item executing a named local in interpretation state:
13546: @cindex local in interpretation state
13547: @cindex Interpreting a compile-only word, for a local
13548: Locals have no interpretation semantics. If you try to perform the
13549: interpretation semantics, you will get a @code{-14 throw} somewhere
13550: (Interpreting a compile-only word). If you perform the compilation
13551: semantics, the locals access will be compiled (irrespective of state).
13552:
1.29 crook 13553: @item @i{name} not defined by @code{VALUE} or @code{(LOCAL)} (@code{TO}):
1.1 anton 13554: @cindex name not defined by @code{VALUE} or @code{(LOCAL)} used by @code{TO}
13555: @cindex @code{TO} on non-@code{VALUE}s and non-locals
13556: @cindex Invalid name argument, @code{TO}
13557: @code{-32 throw} (Invalid name argument)
13558:
13559: @end table
13560:
13561:
13562: @c =====================================================================
13563: @node The optional Memory-Allocation word set, The optional Programming-Tools word set, The optional Locals word set, ANS conformance
13564: @section The optional Memory-Allocation word set
13565: @c =====================================================================
13566: @cindex system documentation, memory-allocation words
13567: @cindex memory-allocation words, system documentation
13568:
13569: @menu
13570: * memory-idef:: Implementation Defined Options
13571: @end menu
13572:
13573:
13574: @c ---------------------------------------------------------------------
13575: @node memory-idef, , The optional Memory-Allocation word set, The optional Memory-Allocation word set
13576: @subsection Implementation Defined Options
13577: @c ---------------------------------------------------------------------
13578: @cindex implementation-defined options, memory-allocation words
13579: @cindex memory-allocation words, implementation-defined options
13580:
13581: @table @i
1.29 crook 13582: @item values and meaning of @i{ior}:
13583: @cindex @i{ior} values and meaning
13584: The @i{ior}s returned by the file and memory allocation words are
1.1 anton 13585: intended as throw codes. They typically are in the range
13586: -512@minus{}-2047 of OS errors. The mapping from OS error numbers to
1.29 crook 13587: @i{ior}s is -512@minus{}@i{errno}.
1.1 anton 13588:
13589: @end table
13590:
13591: @c =====================================================================
13592: @node The optional Programming-Tools word set, The optional Search-Order word set, The optional Memory-Allocation word set, ANS conformance
13593: @section The optional Programming-Tools word set
13594: @c =====================================================================
13595: @cindex system documentation, programming-tools words
13596: @cindex programming-tools words, system documentation
13597:
13598: @menu
13599: * programming-idef:: Implementation Defined Options
13600: * programming-ambcond:: Ambiguous Conditions
13601: @end menu
13602:
13603:
13604: @c ---------------------------------------------------------------------
13605: @node programming-idef, programming-ambcond, The optional Programming-Tools word set, The optional Programming-Tools word set
13606: @subsection Implementation Defined Options
13607: @c ---------------------------------------------------------------------
13608: @cindex implementation-defined options, programming-tools words
13609: @cindex programming-tools words, implementation-defined options
13610:
13611: @table @i
13612: @item ending sequence for input following @code{;CODE} and @code{CODE}:
13613: @cindex @code{;CODE} ending sequence
13614: @cindex @code{CODE} ending sequence
13615: @code{END-CODE}
13616:
13617: @item manner of processing input following @code{;CODE} and @code{CODE}:
13618: @cindex @code{;CODE}, processing input
13619: @cindex @code{CODE}, processing input
13620: The @code{ASSEMBLER} vocabulary is pushed on the search order stack, and
13621: the input is processed by the text interpreter, (starting) in interpret
13622: state.
13623:
13624: @item search order capability for @code{EDITOR} and @code{ASSEMBLER}:
13625: @cindex @code{ASSEMBLER}, search order capability
13626: The ANS Forth search order word set.
13627:
13628: @item source and format of display by @code{SEE}:
13629: @cindex @code{SEE}, source and format of output
1.80 anton 13630: The source for @code{see} is the executable code used by the inner
1.1 anton 13631: interpreter. The current @code{see} tries to output Forth source code
1.80 anton 13632: (and on some platforms, assembly code for primitives) as well as
13633: possible.
1.1 anton 13634:
13635: @end table
13636:
13637: @c ---------------------------------------------------------------------
13638: @node programming-ambcond, , programming-idef, The optional Programming-Tools word set
13639: @subsection Ambiguous conditions
13640: @c ---------------------------------------------------------------------
13641: @cindex programming-tools words, ambiguous conditions
13642: @cindex ambiguous conditions, programming-tools words
13643:
13644: @table @i
13645:
1.21 crook 13646: @item deleting the compilation word list (@code{FORGET}):
13647: @cindex @code{FORGET}, deleting the compilation word list
1.1 anton 13648: Not implemented (yet).
13649:
1.29 crook 13650: @item fewer than @i{u}+1 items on the control-flow stack (@code{CS-PICK}, @code{CS-ROLL}):
13651: @cindex @code{CS-PICK}, fewer than @i{u}+1 items on the control flow-stack
13652: @cindex @code{CS-ROLL}, fewer than @i{u}+1 items on the control flow-stack
1.1 anton 13653: @cindex control-flow stack underflow
13654: This typically results in an @code{abort"} with a descriptive error
13655: message (may change into a @code{-22 throw} (Control structure mismatch)
13656: in the future). You may also get a memory access error. If you are
13657: unlucky, this ambiguous condition is not caught.
13658:
1.29 crook 13659: @item @i{name} can't be found (@code{FORGET}):
13660: @cindex @code{FORGET}, @i{name} can't be found
1.1 anton 13661: Not implemented (yet).
13662:
1.29 crook 13663: @item @i{name} not defined via @code{CREATE}:
13664: @cindex @code{;CODE}, @i{name} not defined via @code{CREATE}
1.1 anton 13665: @code{;CODE} behaves like @code{DOES>} in this respect, i.e., it changes
13666: the execution semantics of the last defined word no matter how it was
13667: defined.
13668:
13669: @item @code{POSTPONE} applied to @code{[IF]}:
13670: @cindex @code{POSTPONE} applied to @code{[IF]}
13671: @cindex @code{[IF]} and @code{POSTPONE}
13672: After defining @code{: X POSTPONE [IF] ; IMMEDIATE}. @code{X} is
13673: equivalent to @code{[IF]}.
13674:
13675: @item reaching the end of the input source before matching @code{[ELSE]} or @code{[THEN]}:
13676: @cindex @code{[IF]}, end of the input source before matching @code{[ELSE]} or @code{[THEN]}
13677: Continue in the same state of conditional compilation in the next outer
13678: input source. Currently there is no warning to the user about this.
13679:
13680: @item removing a needed definition (@code{FORGET}):
13681: @cindex @code{FORGET}, removing a needed definition
13682: Not implemented (yet).
13683:
13684: @end table
13685:
13686:
13687: @c =====================================================================
13688: @node The optional Search-Order word set, , The optional Programming-Tools word set, ANS conformance
13689: @section The optional Search-Order word set
13690: @c =====================================================================
13691: @cindex system documentation, search-order words
13692: @cindex search-order words, system documentation
13693:
13694: @menu
13695: * search-idef:: Implementation Defined Options
13696: * search-ambcond:: Ambiguous Conditions
13697: @end menu
13698:
13699:
13700: @c ---------------------------------------------------------------------
13701: @node search-idef, search-ambcond, The optional Search-Order word set, The optional Search-Order word set
13702: @subsection Implementation Defined Options
13703: @c ---------------------------------------------------------------------
13704: @cindex implementation-defined options, search-order words
13705: @cindex search-order words, implementation-defined options
13706:
13707: @table @i
13708: @item maximum number of word lists in search order:
13709: @cindex maximum number of word lists in search order
13710: @cindex search order, maximum depth
13711: @code{s" wordlists" environment? drop .}. Currently 16.
13712:
13713: @item minimum search order:
13714: @cindex minimum search order
13715: @cindex search order, minimum
13716: @code{root root}.
13717:
13718: @end table
13719:
13720: @c ---------------------------------------------------------------------
13721: @node search-ambcond, , search-idef, The optional Search-Order word set
13722: @subsection Ambiguous conditions
13723: @c ---------------------------------------------------------------------
13724: @cindex search-order words, ambiguous conditions
13725: @cindex ambiguous conditions, search-order words
13726:
13727: @table @i
1.21 crook 13728: @item changing the compilation word list (during compilation):
13729: @cindex changing the compilation word list (during compilation)
13730: @cindex compilation word list, change before definition ends
13731: The word is entered into the word list that was the compilation word list
1.1 anton 13732: at the start of the definition. Any changes to the name field (e.g.,
13733: @code{immediate}) or the code field (e.g., when executing @code{DOES>})
13734: are applied to the latest defined word (as reported by @code{last} or
1.21 crook 13735: @code{lastxt}), if possible, irrespective of the compilation word list.
1.1 anton 13736:
13737: @item search order empty (@code{previous}):
13738: @cindex @code{previous}, search order empty
1.26 crook 13739: @cindex vocstack empty, @code{previous}
1.1 anton 13740: @code{abort" Vocstack empty"}.
13741:
13742: @item too many word lists in search order (@code{also}):
13743: @cindex @code{also}, too many word lists in search order
1.26 crook 13744: @cindex vocstack full, @code{also}
1.1 anton 13745: @code{abort" Vocstack full"}.
13746:
13747: @end table
13748:
13749: @c ***************************************************************
1.65 anton 13750: @node Standard vs Extensions, Model, ANS conformance, Top
13751: @chapter Should I use Gforth extensions?
13752: @cindex Gforth extensions
13753:
13754: As you read through the rest of this manual, you will see documentation
13755: for @i{Standard} words, and documentation for some appealing Gforth
13756: @i{extensions}. You might ask yourself the question: @i{``Should I
13757: restrict myself to the standard, or should I use the extensions?''}
13758:
13759: The answer depends on the goals you have for the program you are working
13760: on:
13761:
13762: @itemize @bullet
13763:
13764: @item Is it just for yourself or do you want to share it with others?
13765:
13766: @item
13767: If you want to share it, do the others all use Gforth?
13768:
13769: @item
13770: If it is just for yourself, do you want to restrict yourself to Gforth?
13771:
13772: @end itemize
13773:
13774: If restricting the program to Gforth is ok, then there is no reason not
13775: to use extensions. It is still a good idea to keep to the standard
13776: where it is easy, in case you want to reuse these parts in another
13777: program that you want to be portable.
13778:
13779: If you want to be able to port the program to other Forth systems, there
13780: are the following points to consider:
13781:
13782: @itemize @bullet
13783:
13784: @item
13785: Most Forth systems that are being maintained support the ANS Forth
13786: standard. So if your program complies with the standard, it will be
13787: portable among many systems.
13788:
13789: @item
13790: A number of the Gforth extensions can be implemented in ANS Forth using
13791: public-domain files provided in the @file{compat/} directory. These are
13792: mentioned in the text in passing. There is no reason not to use these
13793: extensions, your program will still be ANS Forth compliant; just include
13794: the appropriate compat files with your program.
13795:
13796: @item
13797: The tool @file{ans-report.fs} (@pxref{ANS Report}) makes it easy to
13798: analyse your program and determine what non-Standard words it relies
13799: upon. However, it does not check whether you use standard words in a
13800: non-standard way.
13801:
13802: @item
13803: Some techniques are not standardized by ANS Forth, and are hard or
13804: impossible to implement in a standard way, but can be implemented in
13805: most Forth systems easily, and usually in similar ways (e.g., accessing
13806: word headers). Forth has a rich historical precedent for programmers
13807: taking advantage of implementation-dependent features of their tools
13808: (for example, relying on a knowledge of the dictionary
13809: structure). Sometimes these techniques are necessary to extract every
13810: last bit of performance from the hardware, sometimes they are just a
13811: programming shorthand.
13812:
13813: @item
13814: Does using a Gforth extension save more work than the porting this part
13815: to other Forth systems (if any) will cost?
13816:
13817: @item
13818: Is the additional functionality worth the reduction in portability and
13819: the additional porting problems?
13820:
13821: @end itemize
13822:
13823: In order to perform these consideratios, you need to know what's
13824: standard and what's not. This manual generally states if something is
1.81 anton 13825: non-standard, but the authoritative source is the
13826: @uref{http://www.taygeta.com/forth/dpans.html,standard document}.
1.65 anton 13827: Appendix A of the Standard (@var{Rationale}) provides a valuable insight
13828: into the thought processes of the technical committee.
13829:
13830: Note also that portability between Forth systems is not the only
13831: portability issue; there is also the issue of portability between
13832: different platforms (processor/OS combinations).
13833:
13834: @c ***************************************************************
13835: @node Model, Integrating Gforth, Standard vs Extensions, Top
1.1 anton 13836: @chapter Model
13837:
13838: This chapter has yet to be written. It will contain information, on
13839: which internal structures you can rely.
13840:
13841: @c ***************************************************************
13842: @node Integrating Gforth, Emacs and Gforth, Model, Top
13843: @chapter Integrating Gforth into C programs
13844:
13845: This is not yet implemented.
13846:
13847: Several people like to use Forth as scripting language for applications
13848: that are otherwise written in C, C++, or some other language.
13849:
13850: The Forth system ATLAST provides facilities for embedding it into
13851: applications; unfortunately it has several disadvantages: most
13852: importantly, it is not based on ANS Forth, and it is apparently dead
13853: (i.e., not developed further and not supported). The facilities
1.21 crook 13854: provided by Gforth in this area are inspired by ATLAST's facilities, so
1.1 anton 13855: making the switch should not be hard.
13856:
13857: We also tried to design the interface such that it can easily be
13858: implemented by other Forth systems, so that we may one day arrive at a
13859: standardized interface. Such a standard interface would allow you to
13860: replace the Forth system without having to rewrite C code.
13861:
13862: You embed the Gforth interpreter by linking with the library
13863: @code{libgforth.a} (give the compiler the option @code{-lgforth}). All
13864: global symbols in this library that belong to the interface, have the
13865: prefix @code{forth_}. (Global symbols that are used internally have the
13866: prefix @code{gforth_}).
13867:
13868: You can include the declarations of Forth types and the functions and
13869: variables of the interface with @code{#include <forth.h>}.
13870:
13871: Types.
13872:
13873: Variables.
13874:
13875: Data and FP Stack pointer. Area sizes.
13876:
13877: functions.
13878:
13879: forth_init(imagefile)
13880: forth_evaluate(string) exceptions?
13881: forth_goto(address) (or forth_execute(xt)?)
13882: forth_continue() (a corountining mechanism)
13883:
13884: Adding primitives.
13885:
13886: No checking.
13887:
13888: Signals?
13889:
13890: Accessing the Stacks
13891:
1.26 crook 13892: @c ******************************************************************
1.1 anton 13893: @node Emacs and Gforth, Image Files, Integrating Gforth, Top
13894: @chapter Emacs and Gforth
13895: @cindex Emacs and Gforth
13896:
13897: @cindex @file{gforth.el}
13898: @cindex @file{forth.el}
13899: @cindex Rydqvist, Goran
1.107 dvdkhlng 13900: @cindex Kuehling, David
1.1 anton 13901: @cindex comment editing commands
13902: @cindex @code{\}, editing with Emacs
13903: @cindex debug tracer editing commands
13904: @cindex @code{~~}, removal with Emacs
13905: @cindex Forth mode in Emacs
1.107 dvdkhlng 13906:
1.1 anton 13907: Gforth comes with @file{gforth.el}, an improved version of
13908: @file{forth.el} by Goran Rydqvist (included in the TILE package). The
1.26 crook 13909: improvements are:
13910:
13911: @itemize @bullet
13912: @item
1.107 dvdkhlng 13913: A better handling of indentation.
13914: @item
13915: A custom hilighting engine for Forth-code.
1.26 crook 13916: @item
13917: Comment paragraph filling (@kbd{M-q})
13918: @item
13919: Commenting (@kbd{C-x \}) and uncommenting (@kbd{C-u C-x \}) of regions
13920: @item
13921: Removal of debugging tracers (@kbd{C-x ~}, @pxref{Debugging}).
1.41 anton 13922: @item
13923: Support of the @code{info-lookup} feature for looking up the
13924: documentation of a word.
1.107 dvdkhlng 13925: @item
13926: Support for reading and writing blocks files.
1.26 crook 13927: @end itemize
13928:
1.107 dvdkhlng 13929: To get a basic description of these features, enter Forth mode and
13930: type @kbd{C-h m}.
1.1 anton 13931:
13932: @cindex source location of error or debugging output in Emacs
13933: @cindex error output, finding the source location in Emacs
13934: @cindex debugging output, finding the source location in Emacs
13935: In addition, Gforth supports Emacs quite well: The source code locations
13936: given in error messages, debugging output (from @code{~~}) and failed
13937: assertion messages are in the right format for Emacs' compilation mode
13938: (@pxref{Compilation, , Running Compilations under Emacs, emacs, Emacs
13939: Manual}) so the source location corresponding to an error or other
13940: message is only a few keystrokes away (@kbd{C-x `} for the next error,
13941: @kbd{C-c C-c} for the error under the cursor).
13942:
1.107 dvdkhlng 13943: @cindex viewing the documentation of a word in Emacs
13944: @cindex context-sensitive help
13945: Moreover, for words documented in this manual, you can look up the
13946: glossary entry quickly by using @kbd{C-h TAB}
13947: (@code{info-lookup-symbol}, @pxref{Documentation, ,Documentation
13948: Commands, emacs, Emacs Manual}). This feature requires Emacs 20.3 or
13949: later and does not work for words containing @code{:}.
13950:
13951: @menu
13952: * Installing gforth.el:: Making Emacs aware of Forth.
13953: * Emacs Tags:: Viewing the source of a word in Emacs.
13954: * Hilighting:: Making Forth code look prettier.
13955: * Auto-Indentation:: Customizing auto-indentation.
13956: * Blocks Files:: Reading and writing blocks files.
13957: @end menu
13958:
13959: @c ----------------------------------
1.109 anton 13960: @node Installing gforth.el, Emacs Tags, Emacs and Gforth, Emacs and Gforth
1.107 dvdkhlng 13961: @section Installing gforth.el
13962: @cindex @file{.emacs}
13963: @cindex @file{gforth.el}, installation
13964: To make the features from @file{gforth.el} available in Emacs, add
13965: the following lines to your @file{.emacs} file:
13966:
13967: @example
13968: (autoload 'forth-mode "gforth.el")
13969: (setq auto-mode-alist (cons '("\\.fs\\'" . forth-mode)
13970: auto-mode-alist))
13971: (autoload 'forth-block-mode "gforth.el")
13972: (setq auto-mode-alist (cons '("\\.fb\\'" . forth-block-mode)
13973: auto-mode-alist))
13974: (add-hook 'forth-mode-hook (function (lambda ()
13975: ;; customize variables here:
13976: (setq forth-indent-level 4)
13977: (setq forth-minor-indent-level 2)
13978: (setq forth-hilight-level 3)
13979: ;;; ...
13980: )))
13981: @end example
13982:
13983: @c ----------------------------------
13984: @node Emacs Tags, Hilighting, Installing gforth.el, Emacs and Gforth
13985: @section Emacs Tags
1.1 anton 13986: @cindex @file{TAGS} file
13987: @cindex @file{etags.fs}
13988: @cindex viewing the source of a word in Emacs
1.43 anton 13989: @cindex @code{require}, placement in files
13990: @cindex @code{include}, placement in files
1.107 dvdkhlng 13991: If you @code{require} @file{etags.fs}, a new @file{TAGS} file will be
13992: produced (@pxref{Tags, , Tags Tables, emacs, Emacs Manual}) that
1.1 anton 13993: contains the definitions of all words defined afterwards. You can then
1.107 dvdkhlng 13994: find the source for a word using @kbd{M-.}. Note that Emacs can use
1.1 anton 13995: several tags files at the same time (e.g., one for the Gforth sources
13996: and one for your program, @pxref{Select Tags Table,,Selecting a Tags
13997: Table,emacs, Emacs Manual}). The TAGS file for the preloaded words is
13998: @file{$(datadir)/gforth/$(VERSION)/TAGS} (e.g.,
1.43 anton 13999: @file{/usr/local/share/gforth/0.2.0/TAGS}). To get the best behaviour
14000: with @file{etags.fs}, you should avoid putting definitions both before
14001: and after @code{require} etc., otherwise you will see the same file
14002: visited several times by commands like @code{tags-search}.
1.1 anton 14003:
1.107 dvdkhlng 14004: @c ----------------------------------
14005: @node Hilighting, Auto-Indentation, Emacs Tags, Emacs and Gforth
14006: @section Hilighting
14007: @cindex hilighting Forth code in Emacs
14008: @cindex highlighting Forth code in Emacs
14009: @file{gforth.el} comes with a custom source hilighting engine. When
14010: you open a file in @code{forth-mode}, it will be completely parsed,
14011: assigning faces to keywords, comments, strings etc. While you edit
14012: the file, modified regions get parsed and updated on-the-fly.
14013:
14014: Use the variable `forth-hilight-level' to change the level of
14015: decoration from 0 (no hilighting at all) to 3 (the default). Even if
14016: you set the hilighting level to 0, the parser will still work in the
14017: background, collecting information about whether regions of text are
14018: ``compiled'' or ``interpreted''. Those information are required for
14019: auto-indentation to work properly. Set `forth-disable-parser' to
14020: non-nil if your computer is too slow to handle parsing. This will
14021: have an impact on the smartness of the auto-indentation engine,
14022: though.
14023:
14024: Sometimes Forth sources define new features that should be hilighted,
14025: new control structures, defining-words etc. You can use the variable
14026: `forth-custom-words' to make @code{forth-mode} hilight additional
14027: words and constructs. See the docstring of `forth-words' for details
14028: (in Emacs, type @kbd{C-h v forth-words}).
14029:
14030: `forth-custom-words' is meant to be customized in your
14031: @file{.emacs} file. To customize hilighing in a file-specific manner,
14032: set `forth-local-words' in a local-variables section at the end of
14033: your source file (@pxref{Local Variables in Files,, Variables, emacs, Emacs Manual}).
14034:
14035: Example:
14036: @example
14037: 0 [IF]
14038: Local Variables:
14039: forth-local-words:
14040: ((("t:") definition-starter (font-lock-keyword-face . 1)
14041: "[ \t\n]" t name (font-lock-function-name-face . 3))
14042: ((";t") definition-ender (font-lock-keyword-face . 1)))
14043: End:
14044: [THEN]
14045: @end example
14046:
14047: @c ----------------------------------
14048: @node Auto-Indentation, Blocks Files, Hilighting, Emacs and Gforth
14049: @section Auto-Indentation
14050: @cindex auto-indentation of Forth code in Emacs
14051: @cindex indentation of Forth code in Emacs
14052: @code{forth-mode} automatically tries to indent lines in a smart way,
14053: whenever you type @key{TAB} or break a line with @kbd{C-m}.
14054:
14055: Simple customization can be achieved by setting
14056: `forth-indent-level' and `forth-minor-indent-level' in your
14057: @file{.emacs} file. For historical reasons @file{gforth.el} indents
14058: per default by multiples of 4 columns. To use the more traditional
14059: 3-column indentation, add the following lines to your @file{.emacs}:
14060:
14061: @example
14062: (add-hook 'forth-mode-hook (function (lambda ()
14063: ;; customize variables here:
14064: (setq forth-indent-level 3)
14065: (setq forth-minor-indent-level 1)
14066: )))
14067: @end example
14068:
14069: If you want indentation to recognize non-default words, customize it
14070: by setting `forth-custom-indent-words' in your @file{.emacs}. See the
14071: docstring of `forth-indent-words' for details (in Emacs, type @kbd{C-h
14072: v forth-indent-words}).
14073:
14074: To customize indentation in a file-specific manner, set
14075: `forth-local-indent-words' in a local-variables section at the end of
14076: your source file (@pxref{Local Variables in Files, Variables,,emacs,
14077: Emacs Manual}).
14078:
14079: Example:
14080: @example
14081: 0 [IF]
14082: Local Variables:
14083: forth-local-indent-words:
14084: ((("t:") (0 . 2) (0 . 2))
14085: ((";t") (-2 . 0) (0 . -2)))
14086: End:
14087: [THEN]
14088: @end example
14089:
14090: @c ----------------------------------
1.109 anton 14091: @node Blocks Files, , Auto-Indentation, Emacs and Gforth
1.107 dvdkhlng 14092: @section Blocks Files
14093: @cindex blocks files, use with Emacs
14094: @code{forth-mode} Autodetects blocks files by checking whether the
14095: length of the first line exceeds 1023 characters. It then tries to
14096: convert the file into normal text format. When you save the file, it
14097: will be written to disk as normal stream-source file.
14098:
14099: If you want to write blocks files, use @code{forth-blocks-mode}. It
14100: inherits all the features from @code{forth-mode}, plus some additions:
1.41 anton 14101:
1.107 dvdkhlng 14102: @itemize @bullet
14103: @item
14104: Files are written to disk in blocks file format.
14105: @item
14106: Screen numbers are displayed in the mode line (enumerated beginning
14107: with the value of `forth-block-base')
14108: @item
14109: Warnings are displayed when lines exceed 64 characters.
14110: @item
14111: The beginning of the currently edited block is marked with an
14112: overlay-arrow.
14113: @end itemize
1.41 anton 14114:
1.107 dvdkhlng 14115: There are some restrictions you should be aware of. When you open a
14116: blocks file that contains tabulator or newline characters, these
14117: characters will be translated into spaces when the file is written
14118: back to disk. If tabs or newlines are encountered during blocks file
14119: reading, an error is output to the echo area. So have a look at the
14120: `*Messages*' buffer, when Emacs' bell rings during reading.
1.1 anton 14121:
1.107 dvdkhlng 14122: Please consult the docstring of @code{forth-blocks-mode} for more
14123: information by typing @kbd{C-h v forth-blocks-mode}).
1.1 anton 14124:
1.26 crook 14125: @c ******************************************************************
1.1 anton 14126: @node Image Files, Engine, Emacs and Gforth, Top
14127: @chapter Image Files
1.26 crook 14128: @cindex image file
14129: @cindex @file{.fi} files
1.1 anton 14130: @cindex precompiled Forth code
14131: @cindex dictionary in persistent form
14132: @cindex persistent form of dictionary
14133:
14134: An image file is a file containing an image of the Forth dictionary,
14135: i.e., compiled Forth code and data residing in the dictionary. By
14136: convention, we use the extension @code{.fi} for image files.
14137:
14138: @menu
1.18 anton 14139: * Image Licensing Issues:: Distribution terms for images.
14140: * Image File Background:: Why have image files?
1.67 anton 14141: * Non-Relocatable Image Files:: don't always work.
1.18 anton 14142: * Data-Relocatable Image Files:: are better.
1.67 anton 14143: * Fully Relocatable Image Files:: better yet.
1.18 anton 14144: * Stack and Dictionary Sizes:: Setting the default sizes for an image.
1.29 crook 14145: * Running Image Files:: @code{gforth -i @i{file}} or @i{file}.
1.18 anton 14146: * Modifying the Startup Sequence:: and turnkey applications.
1.1 anton 14147: @end menu
14148:
1.18 anton 14149: @node Image Licensing Issues, Image File Background, Image Files, Image Files
14150: @section Image Licensing Issues
14151: @cindex license for images
14152: @cindex image license
14153:
14154: An image created with @code{gforthmi} (@pxref{gforthmi}) or
14155: @code{savesystem} (@pxref{Non-Relocatable Image Files}) includes the
14156: original image; i.e., according to copyright law it is a derived work of
14157: the original image.
14158:
14159: Since Gforth is distributed under the GNU GPL, the newly created image
14160: falls under the GNU GPL, too. In particular, this means that if you
14161: distribute the image, you have to make all of the sources for the image
14162: available, including those you wrote. For details see @ref{License, ,
14163: GNU General Public License (Section 3)}.
14164:
14165: If you create an image with @code{cross} (@pxref{cross.fs}), the image
14166: contains only code compiled from the sources you gave it; if none of
14167: these sources is under the GPL, the terms discussed above do not apply
14168: to the image. However, if your image needs an engine (a gforth binary)
14169: that is under the GPL, you should make sure that you distribute both in
14170: a way that is at most a @emph{mere aggregation}, if you don't want the
14171: terms of the GPL to apply to the image.
14172:
14173: @node Image File Background, Non-Relocatable Image Files, Image Licensing Issues, Image Files
1.1 anton 14174: @section Image File Background
14175: @cindex image file background
14176:
1.80 anton 14177: Gforth consists not only of primitives (in the engine), but also of
1.1 anton 14178: definitions written in Forth. Since the Forth compiler itself belongs to
14179: those definitions, it is not possible to start the system with the
1.80 anton 14180: engine and the Forth source alone. Therefore we provide the Forth
1.26 crook 14181: code as an image file in nearly executable form. When Gforth starts up,
14182: a C routine loads the image file into memory, optionally relocates the
14183: addresses, then sets up the memory (stacks etc.) according to
14184: information in the image file, and (finally) starts executing Forth
14185: code.
1.1 anton 14186:
14187: The image file variants represent different compromises between the
14188: goals of making it easy to generate image files and making them
14189: portable.
14190:
14191: @cindex relocation at run-time
1.26 crook 14192: Win32Forth 3.4 and Mitch Bradley's @code{cforth} use relocation at
1.1 anton 14193: run-time. This avoids many of the complications discussed below (image
14194: files are data relocatable without further ado), but costs performance
14195: (one addition per memory access).
14196:
14197: @cindex relocation at load-time
1.26 crook 14198: By contrast, the Gforth loader performs relocation at image load time. The
14199: loader also has to replace tokens that represent primitive calls with the
1.1 anton 14200: appropriate code-field addresses (or code addresses in the case of
14201: direct threading).
14202:
14203: There are three kinds of image files, with different degrees of
14204: relocatability: non-relocatable, data-relocatable, and fully relocatable
14205: image files.
14206:
14207: @cindex image file loader
14208: @cindex relocating loader
14209: @cindex loader for image files
14210: These image file variants have several restrictions in common; they are
14211: caused by the design of the image file loader:
14212:
14213: @itemize @bullet
14214: @item
14215: There is only one segment; in particular, this means, that an image file
14216: cannot represent @code{ALLOCATE}d memory chunks (and pointers to
1.26 crook 14217: them). The contents of the stacks are not represented, either.
1.1 anton 14218:
14219: @item
14220: The only kinds of relocation supported are: adding the same offset to
14221: all cells that represent data addresses; and replacing special tokens
14222: with code addresses or with pieces of machine code.
14223:
14224: If any complex computations involving addresses are performed, the
14225: results cannot be represented in the image file. Several applications that
14226: use such computations come to mind:
14227: @itemize @minus
14228: @item
14229: Hashing addresses (or data structures which contain addresses) for table
14230: lookup. If you use Gforth's @code{table}s or @code{wordlist}s for this
14231: purpose, you will have no problem, because the hash tables are
14232: recomputed automatically when the system is started. If you use your own
14233: hash tables, you will have to do something similar.
14234:
14235: @item
14236: There's a cute implementation of doubly-linked lists that uses
14237: @code{XOR}ed addresses. You could represent such lists as singly-linked
14238: in the image file, and restore the doubly-linked representation on
14239: startup.@footnote{In my opinion, though, you should think thrice before
14240: using a doubly-linked list (whatever implementation).}
14241:
14242: @item
14243: The code addresses of run-time routines like @code{docol:} cannot be
14244: represented in the image file (because their tokens would be replaced by
14245: machine code in direct threaded implementations). As a workaround,
14246: compute these addresses at run-time with @code{>code-address} from the
14247: executions tokens of appropriate words (see the definitions of
1.80 anton 14248: @code{docol:} and friends in @file{kernel/getdoers.fs}).
1.1 anton 14249:
14250: @item
14251: On many architectures addresses are represented in machine code in some
14252: shifted or mangled form. You cannot put @code{CODE} words that contain
14253: absolute addresses in this form in a relocatable image file. Workarounds
14254: are representing the address in some relative form (e.g., relative to
14255: the CFA, which is present in some register), or loading the address from
14256: a place where it is stored in a non-mangled form.
14257: @end itemize
14258: @end itemize
14259:
14260: @node Non-Relocatable Image Files, Data-Relocatable Image Files, Image File Background, Image Files
14261: @section Non-Relocatable Image Files
14262: @cindex non-relocatable image files
1.26 crook 14263: @cindex image file, non-relocatable
1.1 anton 14264:
14265: These files are simple memory dumps of the dictionary. They are specific
14266: to the executable (i.e., @file{gforth} file) they were created
14267: with. What's worse, they are specific to the place on which the
14268: dictionary resided when the image was created. Now, there is no
14269: guarantee that the dictionary will reside at the same place the next
14270: time you start Gforth, so there's no guarantee that a non-relocatable
14271: image will work the next time (Gforth will complain instead of crashing,
14272: though).
14273:
14274: You can create a non-relocatable image file with
14275:
1.44 crook 14276:
1.1 anton 14277: doc-savesystem
14278:
1.44 crook 14279:
1.1 anton 14280: @node Data-Relocatable Image Files, Fully Relocatable Image Files, Non-Relocatable Image Files, Image Files
14281: @section Data-Relocatable Image Files
14282: @cindex data-relocatable image files
1.26 crook 14283: @cindex image file, data-relocatable
1.1 anton 14284:
14285: These files contain relocatable data addresses, but fixed code addresses
14286: (instead of tokens). They are specific to the executable (i.e.,
14287: @file{gforth} file) they were created with. For direct threading on some
14288: architectures (e.g., the i386), data-relocatable images do not work. You
14289: get a data-relocatable image, if you use @file{gforthmi} with a
14290: Gforth binary that is not doubly indirect threaded (@pxref{Fully
14291: Relocatable Image Files}).
14292:
14293: @node Fully Relocatable Image Files, Stack and Dictionary Sizes, Data-Relocatable Image Files, Image Files
14294: @section Fully Relocatable Image Files
14295: @cindex fully relocatable image files
1.26 crook 14296: @cindex image file, fully relocatable
1.1 anton 14297:
14298: @cindex @file{kern*.fi}, relocatability
14299: @cindex @file{gforth.fi}, relocatability
14300: These image files have relocatable data addresses, and tokens for code
14301: addresses. They can be used with different binaries (e.g., with and
14302: without debugging) on the same machine, and even across machines with
14303: the same data formats (byte order, cell size, floating point
14304: format). However, they are usually specific to the version of Gforth
14305: they were created with. The files @file{gforth.fi} and @file{kernl*.fi}
14306: are fully relocatable.
14307:
14308: There are two ways to create a fully relocatable image file:
14309:
14310: @menu
1.29 crook 14311: * gforthmi:: The normal way
1.1 anton 14312: * cross.fs:: The hard way
14313: @end menu
14314:
14315: @node gforthmi, cross.fs, Fully Relocatable Image Files, Fully Relocatable Image Files
14316: @subsection @file{gforthmi}
14317: @cindex @file{comp-i.fs}
14318: @cindex @file{gforthmi}
14319:
14320: You will usually use @file{gforthmi}. If you want to create an
1.29 crook 14321: image @i{file} that contains everything you would load by invoking
14322: Gforth with @code{gforth @i{options}}, you simply say:
1.1 anton 14323: @example
1.29 crook 14324: gforthmi @i{file} @i{options}
1.1 anton 14325: @end example
14326:
14327: E.g., if you want to create an image @file{asm.fi} that has the file
14328: @file{asm.fs} loaded in addition to the usual stuff, you could do it
14329: like this:
14330:
14331: @example
14332: gforthmi asm.fi asm.fs
14333: @end example
14334:
1.27 crook 14335: @file{gforthmi} is implemented as a sh script and works like this: It
14336: produces two non-relocatable images for different addresses and then
14337: compares them. Its output reflects this: first you see the output (if
1.62 crook 14338: any) of the two Gforth invocations that produce the non-relocatable image
1.27 crook 14339: files, then you see the output of the comparing program: It displays the
14340: offset used for data addresses and the offset used for code addresses;
1.1 anton 14341: moreover, for each cell that cannot be represented correctly in the
1.44 crook 14342: image files, it displays a line like this:
1.1 anton 14343:
14344: @example
14345: 78DC BFFFFA50 BFFFFA40
14346: @end example
14347:
14348: This means that at offset $78dc from @code{forthstart}, one input image
14349: contains $bffffa50, and the other contains $bffffa40. Since these cells
14350: cannot be represented correctly in the output image, you should examine
14351: these places in the dictionary and verify that these cells are dead
14352: (i.e., not read before they are written).
1.39 anton 14353:
14354: @cindex --application, @code{gforthmi} option
14355: If you insert the option @code{--application} in front of the image file
14356: name, you will get an image that uses the @code{--appl-image} option
14357: instead of the @code{--image-file} option (@pxref{Invoking
14358: Gforth}). When you execute such an image on Unix (by typing the image
14359: name as command), the Gforth engine will pass all options to the image
14360: instead of trying to interpret them as engine options.
1.1 anton 14361:
1.27 crook 14362: If you type @file{gforthmi} with no arguments, it prints some usage
14363: instructions.
14364:
1.1 anton 14365: @cindex @code{savesystem} during @file{gforthmi}
14366: @cindex @code{bye} during @file{gforthmi}
14367: @cindex doubly indirect threaded code
1.44 crook 14368: @cindex environment variables
14369: @cindex @code{GFORTHD} -- environment variable
14370: @cindex @code{GFORTH} -- environment variable
1.1 anton 14371: @cindex @code{gforth-ditc}
1.29 crook 14372: There are a few wrinkles: After processing the passed @i{options}, the
1.1 anton 14373: words @code{savesystem} and @code{bye} must be visible. A special doubly
14374: indirect threaded version of the @file{gforth} executable is used for
1.62 crook 14375: creating the non-relocatable images; you can pass the exact filename of
1.1 anton 14376: this executable through the environment variable @code{GFORTHD}
14377: (default: @file{gforth-ditc}); if you pass a version that is not doubly
14378: indirect threaded, you will not get a fully relocatable image, but a
1.27 crook 14379: data-relocatable image (because there is no code address offset). The
14380: normal @file{gforth} executable is used for creating the relocatable
14381: image; you can pass the exact filename of this executable through the
14382: environment variable @code{GFORTH}.
1.1 anton 14383:
14384: @node cross.fs, , gforthmi, Fully Relocatable Image Files
14385: @subsection @file{cross.fs}
14386: @cindex @file{cross.fs}
14387: @cindex cross-compiler
14388: @cindex metacompiler
1.47 crook 14389: @cindex target compiler
1.1 anton 14390:
14391: You can also use @code{cross}, a batch compiler that accepts a Forth-like
1.47 crook 14392: programming language (@pxref{Cross Compiler}).
1.1 anton 14393:
1.47 crook 14394: @code{cross} allows you to create image files for machines with
1.1 anton 14395: different data sizes and data formats than the one used for generating
14396: the image file. You can also use it to create an application image that
14397: does not contain a Forth compiler. These features are bought with
14398: restrictions and inconveniences in programming. E.g., addresses have to
14399: be stored in memory with special words (@code{A!}, @code{A,}, etc.) in
14400: order to make the code relocatable.
14401:
14402:
14403: @node Stack and Dictionary Sizes, Running Image Files, Fully Relocatable Image Files, Image Files
14404: @section Stack and Dictionary Sizes
14405: @cindex image file, stack and dictionary sizes
14406: @cindex dictionary size default
14407: @cindex stack size default
14408:
14409: If you invoke Gforth with a command line flag for the size
14410: (@pxref{Invoking Gforth}), the size you specify is stored in the
14411: dictionary. If you save the dictionary with @code{savesystem} or create
14412: an image with @file{gforthmi}, this size will become the default
14413: for the resulting image file. E.g., the following will create a
1.21 crook 14414: fully relocatable version of @file{gforth.fi} with a 1MB dictionary:
1.1 anton 14415:
14416: @example
14417: gforthmi gforth.fi -m 1M
14418: @end example
14419:
14420: In other words, if you want to set the default size for the dictionary
14421: and the stacks of an image, just invoke @file{gforthmi} with the
14422: appropriate options when creating the image.
14423:
14424: @cindex stack size, cache-friendly
14425: Note: For cache-friendly behaviour (i.e., good performance), you should
14426: make the sizes of the stacks modulo, say, 2K, somewhat different. E.g.,
14427: the default stack sizes are: data: 16k (mod 2k=0); fp: 15.5k (mod
14428: 2k=1.5k); return: 15k(mod 2k=1k); locals: 14.5k (mod 2k=0.5k).
14429:
14430: @node Running Image Files, Modifying the Startup Sequence, Stack and Dictionary Sizes, Image Files
14431: @section Running Image Files
14432: @cindex running image files
14433: @cindex invoking image files
14434: @cindex image file invocation
14435:
14436: @cindex -i, invoke image file
14437: @cindex --image file, invoke image file
1.29 crook 14438: You can invoke Gforth with an image file @i{image} instead of the
1.1 anton 14439: default @file{gforth.fi} with the @code{-i} flag (@pxref{Invoking Gforth}):
14440: @example
1.29 crook 14441: gforth -i @i{image}
1.1 anton 14442: @end example
14443:
14444: @cindex executable image file
1.26 crook 14445: @cindex image file, executable
1.1 anton 14446: If your operating system supports starting scripts with a line of the
14447: form @code{#! ...}, you just have to type the image file name to start
14448: Gforth with this image file (note that the file extension @code{.fi} is
1.29 crook 14449: just a convention). I.e., to run Gforth with the image file @i{image},
14450: you can just type @i{image} instead of @code{gforth -i @i{image}}.
1.27 crook 14451: This works because every @code{.fi} file starts with a line of this
14452: format:
14453:
14454: @example
14455: #! /usr/local/bin/gforth-0.4.0 -i
14456: @end example
14457:
14458: The file and pathname for the Gforth engine specified on this line is
14459: the specific Gforth executable that it was built against; i.e. the value
14460: of the environment variable @code{GFORTH} at the time that
14461: @file{gforthmi} was executed.
1.1 anton 14462:
1.27 crook 14463: You can make use of the same shell capability to make a Forth source
14464: file into an executable. For example, if you place this text in a file:
1.26 crook 14465:
14466: @example
14467: #! /usr/local/bin/gforth
14468:
14469: ." Hello, world" CR
14470: bye
14471: @end example
14472:
14473: @noindent
1.27 crook 14474: and then make the file executable (chmod +x in Unix), you can run it
1.26 crook 14475: directly from the command line. The sequence @code{#!} is used in two
14476: ways; firstly, it is recognised as a ``magic sequence'' by the operating
1.29 crook 14477: system@footnote{The Unix kernel actually recognises two types of files:
14478: executable files and files of data, where the data is processed by an
14479: interpreter that is specified on the ``interpreter line'' -- the first
14480: line of the file, starting with the sequence #!. There may be a small
14481: limit (e.g., 32) on the number of characters that may be specified on
14482: the interpreter line.} secondly it is treated as a comment character by
14483: Gforth. Because of the second usage, a space is required between
1.80 anton 14484: @code{#!} and the path to the executable (moreover, some Unixes
14485: require the sequence @code{#! /}).
1.27 crook 14486:
14487: The disadvantage of this latter technique, compared with using
1.80 anton 14488: @file{gforthmi}, is that it is slightly slower; the Forth source code is
14489: compiled on-the-fly, each time the program is invoked.
1.26 crook 14490:
1.1 anton 14491: doc-#!
14492:
1.44 crook 14493:
1.1 anton 14494: @node Modifying the Startup Sequence, , Running Image Files, Image Files
14495: @section Modifying the Startup Sequence
14496: @cindex startup sequence for image file
14497: @cindex image file initialization sequence
14498: @cindex initialization sequence of image file
14499:
14500: You can add your own initialization to the startup sequence through the
1.26 crook 14501: deferred word @code{'cold}. @code{'cold} is invoked just before the
1.80 anton 14502: image-specific command line processing (i.e., loading files and
1.26 crook 14503: evaluating (@code{-e}) strings) starts.
1.1 anton 14504:
14505: A sequence for adding your initialization usually looks like this:
14506:
14507: @example
14508: :noname
14509: Defers 'cold \ do other initialization stuff (e.g., rehashing wordlists)
14510: ... \ your stuff
14511: ; IS 'cold
14512: @end example
14513:
14514: @cindex turnkey image files
1.26 crook 14515: @cindex image file, turnkey applications
1.1 anton 14516: You can make a turnkey image by letting @code{'cold} execute a word
14517: (your turnkey application) that never returns; instead, it exits Gforth
14518: via @code{bye} or @code{throw}.
14519:
14520: @cindex command-line arguments, access
14521: @cindex arguments on the command line, access
14522: You can access the (image-specific) command-line arguments through the
1.26 crook 14523: variables @code{argc} and @code{argv}. @code{arg} provides convenient
1.1 anton 14524: access to @code{argv}.
14525:
1.26 crook 14526: If @code{'cold} exits normally, Gforth processes the command-line
14527: arguments as files to be loaded and strings to be evaluated. Therefore,
14528: @code{'cold} should remove the arguments it has used in this case.
14529:
1.44 crook 14530:
14531:
1.26 crook 14532: doc-'cold
1.1 anton 14533: doc-argc
14534: doc-argv
14535: doc-arg
14536:
14537:
1.44 crook 14538:
1.1 anton 14539: @c ******************************************************************
1.13 pazsan 14540: @node Engine, Binding to System Library, Image Files, Top
1.1 anton 14541: @chapter Engine
14542: @cindex engine
14543: @cindex virtual machine
14544:
1.26 crook 14545: Reading this chapter is not necessary for programming with Gforth. It
1.1 anton 14546: may be helpful for finding your way in the Gforth sources.
14547:
1.109 anton 14548: The ideas in this section have also been published in the following
14549: papers: Bernd Paysan, @cite{ANS fig/GNU/??? Forth} (in German),
14550: Forth-Tagung '93; M. Anton Ertl,
14551: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl93.ps.Z, A
14552: Portable Forth Engine}}, EuroForth '93; M. Anton Ertl,
14553: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl02.ps.gz,
14554: Threaded code variations and optimizations (extended version)}},
14555: Forth-Tagung '02.
1.1 anton 14556:
14557: @menu
14558: * Portability::
14559: * Threading::
14560: * Primitives::
14561: * Performance::
14562: @end menu
14563:
14564: @node Portability, Threading, Engine, Engine
14565: @section Portability
14566: @cindex engine portability
14567:
1.26 crook 14568: An important goal of the Gforth Project is availability across a wide
14569: range of personal machines. fig-Forth, and, to a lesser extent, F83,
14570: achieved this goal by manually coding the engine in assembly language
14571: for several then-popular processors. This approach is very
14572: labor-intensive and the results are short-lived due to progress in
14573: computer architecture.
1.1 anton 14574:
14575: @cindex C, using C for the engine
14576: Others have avoided this problem by coding in C, e.g., Mitch Bradley
14577: (cforth), Mikael Patel (TILE) and Dirk Zoller (pfe). This approach is
14578: particularly popular for UNIX-based Forths due to the large variety of
14579: architectures of UNIX machines. Unfortunately an implementation in C
14580: does not mix well with the goals of efficiency and with using
14581: traditional techniques: Indirect or direct threading cannot be expressed
14582: in C, and switch threading, the fastest technique available in C, is
14583: significantly slower. Another problem with C is that it is very
14584: cumbersome to express double integer arithmetic.
14585:
14586: @cindex GNU C for the engine
14587: @cindex long long
14588: Fortunately, there is a portable language that does not have these
14589: limitations: GNU C, the version of C processed by the GNU C compiler
14590: (@pxref{C Extensions, , Extensions to the C Language Family, gcc.info,
14591: GNU C Manual}). Its labels as values feature (@pxref{Labels as Values, ,
14592: Labels as Values, gcc.info, GNU C Manual}) makes direct and indirect
14593: threading possible, its @code{long long} type (@pxref{Long Long, ,
14594: Double-Word Integers, gcc.info, GNU C Manual}) corresponds to Forth's
1.109 anton 14595: double numbers on many systems. GNU C is freely available on all
1.1 anton 14596: important (and many unimportant) UNIX machines, VMS, 80386s running
14597: MS-DOS, the Amiga, and the Atari ST, so a Forth written in GNU C can run
14598: on all these machines.
14599:
14600: Writing in a portable language has the reputation of producing code that
14601: is slower than assembly. For our Forth engine we repeatedly looked at
14602: the code produced by the compiler and eliminated most compiler-induced
14603: inefficiencies by appropriate changes in the source code.
14604:
14605: @cindex explicit register declarations
14606: @cindex --enable-force-reg, configuration flag
14607: @cindex -DFORCE_REG
14608: However, register allocation cannot be portably influenced by the
14609: programmer, leading to some inefficiencies on register-starved
14610: machines. We use explicit register declarations (@pxref{Explicit Reg
14611: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) to
14612: improve the speed on some machines. They are turned on by using the
14613: configuration flag @code{--enable-force-reg} (@code{gcc} switch
14614: @code{-DFORCE_REG}). Unfortunately, this feature not only depends on the
14615: machine, but also on the compiler version: On some machines some
14616: compiler versions produce incorrect code when certain explicit register
14617: declarations are used. So by default @code{-DFORCE_REG} is not used.
14618:
14619: @node Threading, Primitives, Portability, Engine
14620: @section Threading
14621: @cindex inner interpreter implementation
14622: @cindex threaded code implementation
14623:
14624: @cindex labels as values
14625: GNU C's labels as values extension (available since @code{gcc-2.0},
14626: @pxref{Labels as Values, , Labels as Values, gcc.info, GNU C Manual})
1.29 crook 14627: makes it possible to take the address of @i{label} by writing
14628: @code{&&@i{label}}. This address can then be used in a statement like
14629: @code{goto *@i{address}}. I.e., @code{goto *&&x} is the same as
1.1 anton 14630: @code{goto x}.
14631:
1.26 crook 14632: @cindex @code{NEXT}, indirect threaded
1.1 anton 14633: @cindex indirect threaded inner interpreter
14634: @cindex inner interpreter, indirect threaded
1.26 crook 14635: With this feature an indirect threaded @code{NEXT} looks like:
1.1 anton 14636: @example
14637: cfa = *ip++;
14638: ca = *cfa;
14639: goto *ca;
14640: @end example
14641: @cindex instruction pointer
14642: For those unfamiliar with the names: @code{ip} is the Forth instruction
14643: pointer; the @code{cfa} (code-field address) corresponds to ANS Forths
14644: execution token and points to the code field of the next word to be
14645: executed; The @code{ca} (code address) fetched from there points to some
14646: executable code, e.g., a primitive or the colon definition handler
14647: @code{docol}.
14648:
1.26 crook 14649: @cindex @code{NEXT}, direct threaded
1.1 anton 14650: @cindex direct threaded inner interpreter
14651: @cindex inner interpreter, direct threaded
14652: Direct threading is even simpler:
14653: @example
14654: ca = *ip++;
14655: goto *ca;
14656: @end example
14657:
14658: Of course we have packaged the whole thing neatly in macros called
1.26 crook 14659: @code{NEXT} and @code{NEXT1} (the part of @code{NEXT} after fetching the cfa).
1.1 anton 14660:
14661: @menu
14662: * Scheduling::
14663: * Direct or Indirect Threaded?::
1.109 anton 14664: * Dynamic Superinstructions::
1.1 anton 14665: * DOES>::
14666: @end menu
14667:
14668: @node Scheduling, Direct or Indirect Threaded?, Threading, Threading
14669: @subsection Scheduling
14670: @cindex inner interpreter optimization
14671:
14672: There is a little complication: Pipelined and superscalar processors,
14673: i.e., RISC and some modern CISC machines can process independent
14674: instructions while waiting for the results of an instruction. The
14675: compiler usually reorders (schedules) the instructions in a way that
14676: achieves good usage of these delay slots. However, on our first tries
14677: the compiler did not do well on scheduling primitives. E.g., for
14678: @code{+} implemented as
14679: @example
14680: n=sp[0]+sp[1];
14681: sp++;
14682: sp[0]=n;
14683: NEXT;
14684: @end example
1.81 anton 14685: the @code{NEXT} comes strictly after the other code, i.e., there is
14686: nearly no scheduling. After a little thought the problem becomes clear:
14687: The compiler cannot know that @code{sp} and @code{ip} point to different
1.21 crook 14688: addresses (and the version of @code{gcc} we used would not know it even
14689: if it was possible), so it could not move the load of the cfa above the
14690: store to the TOS. Indeed the pointers could be the same, if code on or
14691: very near the top of stack were executed. In the interest of speed we
14692: chose to forbid this probably unused ``feature'' and helped the compiler
1.81 anton 14693: in scheduling: @code{NEXT} is divided into several parts:
14694: @code{NEXT_P0}, @code{NEXT_P1} and @code{NEXT_P2}). @code{+} now looks
14695: like:
1.1 anton 14696: @example
1.81 anton 14697: NEXT_P0;
1.1 anton 14698: n=sp[0]+sp[1];
14699: sp++;
14700: NEXT_P1;
14701: sp[0]=n;
14702: NEXT_P2;
14703: @end example
14704:
1.81 anton 14705: There are various schemes that distribute the different operations of
14706: NEXT between these parts in several ways; in general, different schemes
14707: perform best on different processors. We use a scheme for most
14708: architectures that performs well for most processors of this
1.109 anton 14709: architecture; in the future we may switch to benchmarking and chosing
1.81 anton 14710: the scheme on installation time.
14711:
1.1 anton 14712:
1.109 anton 14713: @node Direct or Indirect Threaded?, Dynamic Superinstructions, Scheduling, Threading
1.1 anton 14714: @subsection Direct or Indirect Threaded?
14715: @cindex threading, direct or indirect?
14716:
1.109 anton 14717: Threaded forth code consists of references to primitives (simple machine
14718: code routines like @code{+}) and to non-primitives (e.g., colon
14719: definitions, variables, constants); for a specific class of
14720: non-primitives (e.g., variables) there is one code routine (e.g.,
14721: @code{dovar}), but each variable needs a separate reference to its data.
14722:
14723: Traditionally Forth has been implemented as indirect threaded code,
14724: because this allows to use only one cell to reference a non-primitive
14725: (basically you point to the data, and find the code address there).
14726:
14727: @cindex primitive-centric threaded code
14728: However, threaded code in Gforth (since 0.6.0) uses two cells for
14729: non-primitives, one for the code address, and one for the data address;
14730: the data pointer is an immediate argument for the virtual machine
14731: instruction represented by the code address. We call this
14732: @emph{primitive-centric} threaded code, because all code addresses point
14733: to simple primitives. E.g., for a variable, the code address is for
14734: @code{lit} (also used for integer literals like @code{99}).
14735:
14736: Primitive-centric threaded code allows us to use (faster) direct
14737: threading as dispatch method, completely portably (direct threaded code
14738: in Gforth before 0.6.0 required architecture-specific code). It also
14739: eliminates the performance problems related to I-cache consistency that
14740: 386 implementations have with direct threaded code, and allows
14741: additional optimizations.
14742:
14743: @cindex hybrid direct/indirect threaded code
14744: There is a catch, however: the @var{xt} parameter of @code{execute} can
14745: occupy only one cell, so how do we pass non-primitives with their code
14746: @emph{and} data addresses to them? Our answer is to use indirect
14747: threaded dispatch for @code{execute} and other words that use a
14748: single-cell xt. So, normal threaded code in colon definitions uses
14749: direct threading, and @code{execute} and similar words, which dispatch
14750: to xts on the data stack, use indirect threaded code. We call this
14751: @emph{hybrid direct/indirect} threaded code.
14752:
14753: @cindex engines, gforth vs. gforth-fast vs. gforth-itc
14754: @cindex gforth engine
14755: @cindex gforth-fast engine
14756: The engines @command{gforth} and @command{gforth-fast} use hybrid
14757: direct/indirect threaded code. This means that with these engines you
14758: cannot use @code{,} to compile an xt. Instead, you have to use
14759: @code{compile,}.
14760:
14761: @cindex gforth-itc engine
14762: If you want to compile xts with @code{,}, use @command{gforth-itc}. This
14763: engine uses plain old indirect threaded code. It still compiles in a
14764: primitive-centric style, so you cannot use @code{compile,} instead of
14765: @code{,} (e.g., for producing tables of xts with @code{] word1 word2
14766: ... [}. If you want to do that, you have to use @command{gforth-itc}
14767: and execute @code{' , is compile,}. Your program can check if it is
14768: running on a hybrid direct/indirect threaded engine or a pure indirect
14769: threaded engine with @code{threading-method} (@pxref{Threading Words}).
14770:
14771:
14772: @node Dynamic Superinstructions, DOES>, Direct or Indirect Threaded?, Threading
14773: @subsection Dynamic Superinstructions
14774: @cindex Dynamic superinstructions with replication
14775: @cindex Superinstructions
14776: @cindex Replication
14777:
14778: The engines @command{gforth} and @command{gforth-fast} use another
14779: optimization: Dynamic superinstructions with replication. As an
14780: example, consider the following colon definition:
14781:
14782: @example
14783: : squared ( n1 -- n2 )
14784: dup * ;
14785: @end example
14786:
14787: Gforth compiles this into the threaded code sequence
14788:
14789: @example
14790: dup
14791: *
14792: ;s
14793: @end example
14794:
14795: In normal direct threaded code there is a code address occupying one
14796: cell for each of these primitives. Each code address points to a
14797: machine code routine, and the interpreter jumps to this machine code in
14798: order to execute the primitive. The routines for these three
14799: primitives are (in @command{gforth-fast} on the 386):
14800:
14801: @example
14802: Code dup
14803: ( $804B950 ) add esi , # -4 \ $83 $C6 $FC
14804: ( $804B953 ) add ebx , # 4 \ $83 $C3 $4
14805: ( $804B956 ) mov dword ptr 4 [esi] , ecx \ $89 $4E $4
14806: ( $804B959 ) jmp dword ptr FC [ebx] \ $FF $63 $FC
14807: end-code
14808: Code *
14809: ( $804ACC4 ) mov eax , dword ptr 4 [esi] \ $8B $46 $4
14810: ( $804ACC7 ) add esi , # 4 \ $83 $C6 $4
14811: ( $804ACCA ) add ebx , # 4 \ $83 $C3 $4
14812: ( $804ACCD ) imul ecx , eax \ $F $AF $C8
14813: ( $804ACD0 ) jmp dword ptr FC [ebx] \ $FF $63 $FC
14814: end-code
14815: Code ;s
14816: ( $804A693 ) mov eax , dword ptr [edi] \ $8B $7
14817: ( $804A695 ) add edi , # 4 \ $83 $C7 $4
14818: ( $804A698 ) lea ebx , dword ptr 4 [eax] \ $8D $58 $4
14819: ( $804A69B ) jmp dword ptr FC [ebx] \ $FF $63 $FC
14820: end-code
14821: @end example
14822:
14823: With dynamic superinstructions and replication the compiler does not
14824: just lay down the threaded code, but also copies the machine code
14825: fragments, usually without the jump at the end.
14826:
14827: @example
14828: ( $4057D27D ) add esi , # -4 \ $83 $C6 $FC
14829: ( $4057D280 ) add ebx , # 4 \ $83 $C3 $4
14830: ( $4057D283 ) mov dword ptr 4 [esi] , ecx \ $89 $4E $4
14831: ( $4057D286 ) mov eax , dword ptr 4 [esi] \ $8B $46 $4
14832: ( $4057D289 ) add esi , # 4 \ $83 $C6 $4
14833: ( $4057D28C ) add ebx , # 4 \ $83 $C3 $4
14834: ( $4057D28F ) imul ecx , eax \ $F $AF $C8
14835: ( $4057D292 ) mov eax , dword ptr [edi] \ $8B $7
14836: ( $4057D294 ) add edi , # 4 \ $83 $C7 $4
14837: ( $4057D297 ) lea ebx , dword ptr 4 [eax] \ $8D $58 $4
14838: ( $4057D29A ) jmp dword ptr FC [ebx] \ $FF $63 $FC
14839: @end example
14840:
14841: Only when a threaded-code control-flow change happens (e.g., in
14842: @code{;s}), the jump is appended. This optimization eliminates many of
14843: these jumps and makes the rest much more predictable. The speedup
14844: depends on the processor and the application; on the Athlon and Pentium
14845: III this optimization typically produces a speedup by a factor of 2.
14846:
14847: The code addresses in the direct-threaded code are set to point to the
14848: appropriate points in the copied machine code, in this example like
14849: this:
1.1 anton 14850:
1.109 anton 14851: @example
14852: primitive code address
14853: dup $4057D27D
14854: * $4057D286
14855: ;s $4057D292
14856: @end example
14857:
14858: Thus there can be threaded-code jumps to any place in this piece of
14859: code. This also simplifies decompilation quite a bit.
14860:
14861: @cindex --no-dynamic command-line option
14862: @cindex --no-super command-line option
14863: You can disable this optimization with @option{--no-dynamic}. You can
14864: use the copying without eliminating the jumps (i.e., dynamic
14865: replication, but without superinstructions) with @option{--no-super};
14866: this gives the branch prediction benefit alone; the effect on
1.110 anton 14867: performance depends on the CPU; on the Athlon and Pentium III the
14868: speedup is a little less than for dynamic superinstructions with
14869: replication.
14870:
14871: @cindex patching threaded code
14872: One use of these options is if you want to patch the threaded code.
14873: With superinstructions, many of the dispatch jumps are eliminated, so
14874: patching often has no effect. These options preserve all the dispatch
14875: jumps.
1.109 anton 14876:
14877: @cindex --dynamic command-line option
1.110 anton 14878: On some machines dynamic superinstructions are disabled by default,
14879: because it is unsafe on these machines. However, if you feel
14880: adventurous, you can enable it with @option{--dynamic}.
1.109 anton 14881:
14882: @node DOES>, , Dynamic Superinstructions, Threading
1.1 anton 14883: @subsection DOES>
14884: @cindex @code{DOES>} implementation
14885:
1.26 crook 14886: @cindex @code{dodoes} routine
14887: @cindex @code{DOES>}-code
1.1 anton 14888: One of the most complex parts of a Forth engine is @code{dodoes}, i.e.,
14889: the chunk of code executed by every word defined by a
1.109 anton 14890: @code{CREATE}...@code{DOES>} pair; actually with primitive-centric code,
14891: this is only needed if the xt of the word is @code{execute}d. The main
14892: problem here is: How to find the Forth code to be executed, i.e. the
14893: code after the @code{DOES>} (the @code{DOES>}-code)? There are two
14894: solutions:
1.1 anton 14895:
1.21 crook 14896: In fig-Forth the code field points directly to the @code{dodoes} and the
1.109 anton 14897: @code{DOES>}-code address is stored in the cell after the code address
14898: (i.e. at @code{@i{CFA} cell+}). It may seem that this solution is
14899: illegal in the Forth-79 and all later standards, because in fig-Forth
14900: this address lies in the body (which is illegal in these
14901: standards). However, by making the code field larger for all words this
14902: solution becomes legal again. We use this approach. Leaving a cell
14903: unused in most words is a bit wasteful, but on the machines we are
14904: targeting this is hardly a problem.
14905:
1.1 anton 14906:
14907: @node Primitives, Performance, Threading, Engine
14908: @section Primitives
14909: @cindex primitives, implementation
14910: @cindex virtual machine instructions, implementation
14911:
14912: @menu
14913: * Automatic Generation::
14914: * TOS Optimization::
14915: * Produced code::
14916: @end menu
14917:
14918: @node Automatic Generation, TOS Optimization, Primitives, Primitives
14919: @subsection Automatic Generation
14920: @cindex primitives, automatic generation
14921:
14922: @cindex @file{prims2x.fs}
1.109 anton 14923:
1.1 anton 14924: Since the primitives are implemented in a portable language, there is no
14925: longer any need to minimize the number of primitives. On the contrary,
14926: having many primitives has an advantage: speed. In order to reduce the
14927: number of errors in primitives and to make programming them easier, we
1.109 anton 14928: provide a tool, the primitive generator (@file{prims2x.fs} aka Vmgen,
14929: @pxref{Top, Vmgen, Introduction, vmgen, Vmgen}), that automatically
14930: generates most (and sometimes all) of the C code for a primitive from
14931: the stack effect notation. The source for a primitive has the following
14932: form:
1.1 anton 14933:
14934: @cindex primitive source format
14935: @format
1.58 anton 14936: @i{Forth-name} ( @i{stack-effect} ) @i{category} [@i{pronounc.}]
1.29 crook 14937: [@code{""}@i{glossary entry}@code{""}]
14938: @i{C code}
1.1 anton 14939: [@code{:}
1.29 crook 14940: @i{Forth code}]
1.1 anton 14941: @end format
14942:
14943: The items in brackets are optional. The category and glossary fields
14944: are there for generating the documentation, the Forth code is there
14945: for manual implementations on machines without GNU C. E.g., the source
14946: for the primitive @code{+} is:
14947: @example
1.58 anton 14948: + ( n1 n2 -- n ) core plus
1.1 anton 14949: n = n1+n2;
14950: @end example
14951:
14952: This looks like a specification, but in fact @code{n = n1+n2} is C
14953: code. Our primitive generation tool extracts a lot of information from
14954: the stack effect notations@footnote{We use a one-stack notation, even
14955: though we have separate data and floating-point stacks; The separate
14956: notation can be generated easily from the unified notation.}: The number
14957: of items popped from and pushed on the stack, their type, and by what
14958: name they are referred to in the C code. It then generates a C code
14959: prelude and postlude for each primitive. The final C code for @code{+}
14960: looks like this:
14961:
14962: @example
1.46 pazsan 14963: I_plus: /* + ( n1 n2 -- n ) */ /* label, stack effect */
1.1 anton 14964: /* */ /* documentation */
1.81 anton 14965: NAME("+") /* debugging output (with -DDEBUG) */
1.1 anton 14966: @{
14967: DEF_CA /* definition of variable ca (indirect threading) */
14968: Cell n1; /* definitions of variables */
14969: Cell n2;
14970: Cell n;
1.81 anton 14971: NEXT_P0; /* NEXT part 0 */
1.1 anton 14972: n1 = (Cell) sp[1]; /* input */
14973: n2 = (Cell) TOS;
14974: sp += 1; /* stack adjustment */
14975: @{
14976: n = n1+n2; /* C code taken from the source */
14977: @}
14978: NEXT_P1; /* NEXT part 1 */
14979: TOS = (Cell)n; /* output */
14980: NEXT_P2; /* NEXT part 2 */
14981: @}
14982: @end example
14983:
14984: This looks long and inefficient, but the GNU C compiler optimizes quite
14985: well and produces optimal code for @code{+} on, e.g., the R3000 and the
14986: HP RISC machines: Defining the @code{n}s does not produce any code, and
14987: using them as intermediate storage also adds no cost.
14988:
1.26 crook 14989: There are also other optimizations that are not illustrated by this
14990: example: assignments between simple variables are usually for free (copy
1.1 anton 14991: propagation). If one of the stack items is not used by the primitive
14992: (e.g. in @code{drop}), the compiler eliminates the load from the stack
14993: (dead code elimination). On the other hand, there are some things that
14994: the compiler does not do, therefore they are performed by
14995: @file{prims2x.fs}: The compiler does not optimize code away that stores
14996: a stack item to the place where it just came from (e.g., @code{over}).
14997:
14998: While programming a primitive is usually easy, there are a few cases
14999: where the programmer has to take the actions of the generator into
15000: account, most notably @code{?dup}, but also words that do not (always)
1.26 crook 15001: fall through to @code{NEXT}.
1.109 anton 15002:
15003: For more information
1.1 anton 15004:
15005: @node TOS Optimization, Produced code, Automatic Generation, Primitives
15006: @subsection TOS Optimization
15007: @cindex TOS optimization for primitives
15008: @cindex primitives, keeping the TOS in a register
15009:
15010: An important optimization for stack machine emulators, e.g., Forth
15011: engines, is keeping one or more of the top stack items in
1.29 crook 15012: registers. If a word has the stack effect @i{in1}...@i{inx} @code{--}
15013: @i{out1}...@i{outy}, keeping the top @i{n} items in registers
1.1 anton 15014: @itemize @bullet
15015: @item
1.29 crook 15016: is better than keeping @i{n-1} items, if @i{x>=n} and @i{y>=n},
1.1 anton 15017: due to fewer loads from and stores to the stack.
1.29 crook 15018: @item is slower than keeping @i{n-1} items, if @i{x<>y} and @i{x<n} and
15019: @i{y<n}, due to additional moves between registers.
1.1 anton 15020: @end itemize
15021:
15022: @cindex -DUSE_TOS
15023: @cindex -DUSE_NO_TOS
15024: In particular, keeping one item in a register is never a disadvantage,
15025: if there are enough registers. Keeping two items in registers is a
15026: disadvantage for frequent words like @code{?branch}, constants,
15027: variables, literals and @code{i}. Therefore our generator only produces
15028: code that keeps zero or one items in registers. The generated C code
15029: covers both cases; the selection between these alternatives is made at
15030: C-compile time using the switch @code{-DUSE_TOS}. @code{TOS} in the C
15031: code for @code{+} is just a simple variable name in the one-item case,
15032: otherwise it is a macro that expands into @code{sp[0]}. Note that the
15033: GNU C compiler tries to keep simple variables like @code{TOS} in
15034: registers, and it usually succeeds, if there are enough registers.
15035:
15036: @cindex -DUSE_FTOS
15037: @cindex -DUSE_NO_FTOS
15038: The primitive generator performs the TOS optimization for the
15039: floating-point stack, too (@code{-DUSE_FTOS}). For floating-point
15040: operations the benefit of this optimization is even larger:
15041: floating-point operations take quite long on most processors, but can be
15042: performed in parallel with other operations as long as their results are
15043: not used. If the FP-TOS is kept in a register, this works. If
15044: it is kept on the stack, i.e., in memory, the store into memory has to
15045: wait for the result of the floating-point operation, lengthening the
15046: execution time of the primitive considerably.
15047:
15048: The TOS optimization makes the automatic generation of primitives a
15049: bit more complicated. Just replacing all occurrences of @code{sp[0]} by
15050: @code{TOS} is not sufficient. There are some special cases to
15051: consider:
15052: @itemize @bullet
15053: @item In the case of @code{dup ( w -- w w )} the generator must not
15054: eliminate the store to the original location of the item on the stack,
15055: if the TOS optimization is turned on.
15056: @item Primitives with stack effects of the form @code{--}
1.29 crook 15057: @i{out1}...@i{outy} must store the TOS to the stack at the start.
15058: Likewise, primitives with the stack effect @i{in1}...@i{inx} @code{--}
1.1 anton 15059: must load the TOS from the stack at the end. But for the null stack
15060: effect @code{--} no stores or loads should be generated.
15061: @end itemize
15062:
15063: @node Produced code, , TOS Optimization, Primitives
15064: @subsection Produced code
15065: @cindex primitives, assembly code listing
15066:
15067: @cindex @file{engine.s}
15068: To see what assembly code is produced for the primitives on your machine
15069: with your compiler and your flag settings, type @code{make engine.s} and
1.81 anton 15070: look at the resulting file @file{engine.s}. Alternatively, you can also
15071: disassemble the code of primitives with @code{see} on some architectures.
1.1 anton 15072:
15073: @node Performance, , Primitives, Engine
15074: @section Performance
15075: @cindex performance of some Forth interpreters
15076: @cindex engine performance
15077: @cindex benchmarking Forth systems
15078: @cindex Gforth performance
15079:
15080: On RISCs the Gforth engine is very close to optimal; i.e., it is usually
15081: impossible to write a significantly faster engine.
15082:
15083: On register-starved machines like the 386 architecture processors
15084: improvements are possible, because @code{gcc} does not utilize the
15085: registers as well as a human, even with explicit register declarations;
15086: e.g., Bernd Beuster wrote a Forth system fragment in assembly language
15087: and hand-tuned it for the 486; this system is 1.19 times faster on the
15088: Sieve benchmark on a 486DX2/66 than Gforth compiled with
1.40 anton 15089: @code{gcc-2.6.3} with @code{-DFORCE_REG}. The situation has improved
15090: with gcc-2.95 and gforth-0.4.9; now the most important virtual machine
15091: registers fit in real registers (and we can even afford to use the TOS
15092: optimization), resulting in a speedup of 1.14 on the sieve over the
15093: earlier results.
1.1 anton 15094:
15095: @cindex Win32Forth performance
15096: @cindex NT Forth performance
15097: @cindex eforth performance
15098: @cindex ThisForth performance
15099: @cindex PFE performance
15100: @cindex TILE performance
1.81 anton 15101: The potential advantage of assembly language implementations is not
15102: necessarily realized in complete Forth systems: We compared Gforth-0.4.9
15103: (direct threaded, compiled with @code{gcc-2.95.1} and
15104: @code{-DFORCE_REG}) with Win32Forth 1.2093 (newer versions are
15105: reportedly much faster), LMI's NT Forth (Beta, May 1994) and Eforth
15106: (with and without peephole (aka pinhole) optimization of the threaded
15107: code); all these systems were written in assembly language. We also
15108: compared Gforth with three systems written in C: PFE-0.9.14 (compiled
15109: with @code{gcc-2.6.3} with the default configuration for Linux:
15110: @code{-O2 -fomit-frame-pointer -DUSE_REGS -DUNROLL_NEXT}), ThisForth
15111: Beta (compiled with @code{gcc-2.6.3 -O3 -fomit-frame-pointer}; ThisForth
15112: employs peephole optimization of the threaded code) and TILE (compiled
15113: with @code{make opt}). We benchmarked Gforth, PFE, ThisForth and TILE on
15114: a 486DX2/66 under Linux. Kenneth O'Heskin kindly provided the results
15115: for Win32Forth and NT Forth on a 486DX2/66 with similar memory
15116: performance under Windows NT. Marcel Hendrix ported Eforth to Linux,
15117: then extended it to run the benchmarks, added the peephole optimizer,
15118: ran the benchmarks and reported the results.
1.40 anton 15119:
1.1 anton 15120: We used four small benchmarks: the ubiquitous Sieve; bubble-sorting and
15121: matrix multiplication come from the Stanford integer benchmarks and have
15122: been translated into Forth by Martin Fraeman; we used the versions
15123: included in the TILE Forth package, but with bigger data set sizes; and
15124: a recursive Fibonacci number computation for benchmarking calling
15125: performance. The following table shows the time taken for the benchmarks
15126: scaled by the time taken by Gforth (in other words, it shows the speedup
15127: factor that Gforth achieved over the other systems).
15128:
15129: @example
1.40 anton 15130: relative Win32- NT eforth This-
1.1 anton 15131: time Gforth Forth Forth eforth +opt PFE Forth TILE
1.81 anton 15132: sieve 1.00 1.60 1.32 1.60 0.98 1.82 3.67 9.91
15133: bubble 1.00 1.55 1.66 1.75 1.04 1.78 4.58
15134: matmul 1.00 1.71 1.57 1.69 0.86 1.83 4.74
15135: fib 1.00 1.76 1.54 1.41 1.00 2.01 3.45 4.96
1.1 anton 15136: @end example
15137:
1.26 crook 15138: You may be quite surprised by the good performance of Gforth when
15139: compared with systems written in assembly language. One important reason
15140: for the disappointing performance of these other systems is probably
15141: that they are not written optimally for the 486 (e.g., they use the
15142: @code{lods} instruction). In addition, Win32Forth uses a comfortable,
15143: but costly method for relocating the Forth image: like @code{cforth}, it
15144: computes the actual addresses at run time, resulting in two address
15145: computations per @code{NEXT} (@pxref{Image File Background}).
15146:
1.40 anton 15147: Only Eforth with the peephole optimizer performs comparable to
15148: Gforth. The speedups achieved with peephole optimization of threaded
15149: code are quite remarkable. Adding a peephole optimizer to Gforth should
15150: cause similar speedups.
1.1 anton 15151:
15152: The speedup of Gforth over PFE, ThisForth and TILE can be easily
15153: explained with the self-imposed restriction of the latter systems to
15154: standard C, which makes efficient threading impossible (however, the
1.4 anton 15155: measured implementation of PFE uses a GNU C extension: @pxref{Global Reg
1.1 anton 15156: Vars, , Defining Global Register Variables, gcc.info, GNU C Manual}).
15157: Moreover, current C compilers have a hard time optimizing other aspects
15158: of the ThisForth and the TILE source.
15159:
1.26 crook 15160: The performance of Gforth on 386 architecture processors varies widely
15161: with the version of @code{gcc} used. E.g., @code{gcc-2.5.8} failed to
15162: allocate any of the virtual machine registers into real machine
15163: registers by itself and would not work correctly with explicit register
1.40 anton 15164: declarations, giving a 1.5 times slower engine (on a 486DX2/66 running
1.26 crook 15165: the Sieve) than the one measured above.
1.1 anton 15166:
1.26 crook 15167: Note that there have been several releases of Win32Forth since the
15168: release presented here, so the results presented above may have little
1.40 anton 15169: predictive value for the performance of Win32Forth today (results for
15170: the current release on an i486DX2/66 are welcome).
1.1 anton 15171:
15172: @cindex @file{Benchres}
1.66 anton 15173: In
15174: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl&maierhofer95.ps.gz,
15175: Translating Forth to Efficient C}} by M. Anton Ertl and Martin
1.1 anton 15176: Maierhofer (presented at EuroForth '95), an indirect threaded version of
1.66 anton 15177: Gforth is compared with Win32Forth, NT Forth, PFE, ThisForth, and
15178: several native code systems; that version of Gforth is slower on a 486
15179: than the direct threaded version used here. You can find a newer version
15180: of these measurements at
1.47 crook 15181: @uref{http://www.complang.tuwien.ac.at/forth/performance.html}. You can
1.1 anton 15182: find numbers for Gforth on various machines in @file{Benchres}.
15183:
1.26 crook 15184: @c ******************************************************************
1.13 pazsan 15185: @node Binding to System Library, Cross Compiler, Engine, Top
1.14 pazsan 15186: @chapter Binding to System Library
1.13 pazsan 15187:
15188: @node Cross Compiler, Bugs, Binding to System Library, Top
1.14 pazsan 15189: @chapter Cross Compiler
1.47 crook 15190: @cindex @file{cross.fs}
15191: @cindex cross-compiler
15192: @cindex metacompiler
15193: @cindex target compiler
1.13 pazsan 15194:
1.46 pazsan 15195: The cross compiler is used to bootstrap a Forth kernel. Since Gforth is
15196: mostly written in Forth, including crucial parts like the outer
15197: interpreter and compiler, it needs compiled Forth code to get
15198: started. The cross compiler allows to create new images for other
15199: architectures, even running under another Forth system.
1.13 pazsan 15200:
15201: @menu
1.67 anton 15202: * Using the Cross Compiler::
15203: * How the Cross Compiler Works::
1.13 pazsan 15204: @end menu
15205:
1.21 crook 15206: @node Using the Cross Compiler, How the Cross Compiler Works, Cross Compiler, Cross Compiler
1.14 pazsan 15207: @section Using the Cross Compiler
1.46 pazsan 15208:
15209: The cross compiler uses a language that resembles Forth, but isn't. The
15210: main difference is that you can execute Forth code after definition,
15211: while you usually can't execute the code compiled by cross, because the
15212: code you are compiling is typically for a different computer than the
15213: one you are compiling on.
15214:
1.81 anton 15215: @c anton: This chapter is somewhat different from waht I would expect: I
15216: @c would expect an explanation of the cross language and how to create an
15217: @c application image with it. The section explains some aspects of
15218: @c creating a Gforth kernel.
15219:
1.46 pazsan 15220: The Makefile is already set up to allow you to create kernels for new
15221: architectures with a simple make command. The generic kernels using the
15222: GCC compiled virtual machine are created in the normal build process
15223: with @code{make}. To create a embedded Gforth executable for e.g. the
15224: 8086 processor (running on a DOS machine), type
15225:
15226: @example
15227: make kernl-8086.fi
15228: @end example
15229:
15230: This will use the machine description from the @file{arch/8086}
15231: directory to create a new kernel. A machine file may look like that:
15232:
15233: @example
15234: \ Parameter for target systems 06oct92py
15235:
15236: 4 Constant cell \ cell size in bytes
15237: 2 Constant cell<< \ cell shift to bytes
15238: 5 Constant cell>bit \ cell shift to bits
15239: 8 Constant bits/char \ bits per character
15240: 8 Constant bits/byte \ bits per byte [default: 8]
15241: 8 Constant float \ bytes per float
15242: 8 Constant /maxalign \ maximum alignment in bytes
15243: false Constant bigendian \ byte order
15244: ( true=big, false=little )
15245:
15246: include machpc.fs \ feature list
15247: @end example
15248:
15249: This part is obligatory for the cross compiler itself, the feature list
15250: is used by the kernel to conditionally compile some features in and out,
15251: depending on whether the target supports these features.
15252:
15253: There are some optional features, if you define your own primitives,
15254: have an assembler, or need special, nonstandard preparation to make the
1.81 anton 15255: boot process work. @code{asm-include} includes an assembler,
1.46 pazsan 15256: @code{prims-include} includes primitives, and @code{>boot} prepares for
15257: booting.
15258:
15259: @example
15260: : asm-include ." Include assembler" cr
15261: s" arch/8086/asm.fs" included ;
15262:
15263: : prims-include ." Include primitives" cr
15264: s" arch/8086/prim.fs" included ;
15265:
15266: : >boot ." Prepare booting" cr
15267: s" ' boot >body into-forth 1+ !" evaluate ;
15268: @end example
15269:
15270: These words are used as sort of macro during the cross compilation in
1.81 anton 15271: the file @file{kernel/main.fs}. Instead of using these macros, it would
1.46 pazsan 15272: be possible --- but more complicated --- to write a new kernel project
15273: file, too.
15274:
15275: @file{kernel/main.fs} expects the machine description file name on the
15276: stack; the cross compiler itself (@file{cross.fs}) assumes that either
15277: @code{mach-file} leaves a counted string on the stack, or
15278: @code{machine-file} leaves an address, count pair of the filename on the
15279: stack.
15280:
15281: The feature list is typically controlled using @code{SetValue}, generic
15282: files that are used by several projects can use @code{DefaultValue}
15283: instead. Both functions work like @code{Value}, when the value isn't
15284: defined, but @code{SetValue} works like @code{to} if the value is
15285: defined, and @code{DefaultValue} doesn't set anything, if the value is
15286: defined.
15287:
15288: @example
15289: \ generic mach file for pc gforth 03sep97jaw
15290:
15291: true DefaultValue NIL \ relocating
15292:
15293: >ENVIRON
15294:
15295: true DefaultValue file \ controls the presence of the
15296: \ file access wordset
15297: true DefaultValue OS \ flag to indicate a operating system
15298:
15299: true DefaultValue prims \ true: primitives are c-code
15300:
15301: true DefaultValue floating \ floating point wordset is present
15302:
15303: true DefaultValue glocals \ gforth locals are present
15304: \ will be loaded
15305: true DefaultValue dcomps \ double number comparisons
15306:
15307: true DefaultValue hash \ hashing primitives are loaded/present
15308:
15309: true DefaultValue xconds \ used together with glocals,
15310: \ special conditionals supporting gforths'
15311: \ local variables
15312: true DefaultValue header \ save a header information
15313:
15314: true DefaultValue backtrace \ enables backtrace code
15315:
15316: false DefaultValue ec
15317: false DefaultValue crlf
15318:
15319: cell 2 = [IF] &32 [ELSE] &256 [THEN] KB DefaultValue kernel-size
15320:
15321: &16 KB DefaultValue stack-size
15322: &15 KB &512 + DefaultValue fstack-size
15323: &15 KB DefaultValue rstack-size
15324: &14 KB &512 + DefaultValue lstack-size
15325: @end example
1.13 pazsan 15326:
1.48 anton 15327: @node How the Cross Compiler Works, , Using the Cross Compiler, Cross Compiler
1.14 pazsan 15328: @section How the Cross Compiler Works
1.13 pazsan 15329:
15330: @node Bugs, Origin, Cross Compiler, Top
1.21 crook 15331: @appendix Bugs
1.1 anton 15332: @cindex bug reporting
15333:
1.21 crook 15334: Known bugs are described in the file @file{BUGS} in the Gforth distribution.
1.1 anton 15335:
1.103 anton 15336: If you find a bug, please submit a bug report through
15337: @uref{https://savannah.gnu.org/bugs/?func=addbug&group=gforth}.
1.21 crook 15338:
15339: @itemize @bullet
15340: @item
1.81 anton 15341: A program (or a sequence of keyboard commands) that reproduces the bug.
15342: @item
15343: A description of what you think constitutes the buggy behaviour.
15344: @item
1.21 crook 15345: The Gforth version used (it is announced at the start of an
15346: interactive Gforth session).
15347: @item
15348: The machine and operating system (on Unix
15349: systems @code{uname -a} will report this information).
15350: @item
1.81 anton 15351: The installation options (you can find the configure options at the
15352: start of @file{config.status}) and configuration (@code{configure}
15353: output or @file{config.cache}).
1.21 crook 15354: @item
15355: A complete list of changes (if any) you (or your installer) have made to the
15356: Gforth sources.
15357: @end itemize
1.1 anton 15358:
15359: For a thorough guide on reporting bugs read @ref{Bug Reporting, , How
15360: to Report Bugs, gcc.info, GNU C Manual}.
15361:
15362:
1.21 crook 15363: @node Origin, Forth-related information, Bugs, Top
15364: @appendix Authors and Ancestors of Gforth
1.1 anton 15365:
15366: @section Authors and Contributors
15367: @cindex authors of Gforth
15368: @cindex contributors to Gforth
15369:
15370: The Gforth project was started in mid-1992 by Bernd Paysan and Anton
1.81 anton 15371: Ertl. The third major author was Jens Wilke. Neal Crook contributed a
15372: lot to the manual. Assemblers and disassemblers were contributed by
15373: Andrew McKewan, Christian Pirker, and Bernd Thallner. Lennart Benschop
15374: (who was one of Gforth's first users, in mid-1993) and Stuart Ramsden
15375: inspired us with their continuous feedback. Lennart Benshop contributed
1.1 anton 15376: @file{glosgen.fs}, while Stuart Ramsden has been working on automatic
15377: support for calling C libraries. Helpful comments also came from Paul
15378: Kleinrubatscher, Christian Pirker, Dirk Zoller, Marcel Hendrix, John
1.58 anton 15379: Wavrik, Barrie Stott, Marc de Groot, Jorge Acerada, Bruce Hoyt, and
15380: Robert Epprecht. Since the release of Gforth-0.2.1 there were also
15381: helpful comments from many others; thank you all, sorry for not listing
15382: you here (but digging through my mailbox to extract your names is on my
1.81 anton 15383: to-do list).
1.1 anton 15384:
15385: Gforth also owes a lot to the authors of the tools we used (GCC, CVS,
15386: and autoconf, among others), and to the creators of the Internet: Gforth
1.21 crook 15387: was developed across the Internet, and its authors did not meet
1.20 pazsan 15388: physically for the first 4 years of development.
1.1 anton 15389:
15390: @section Pedigree
1.26 crook 15391: @cindex pedigree of Gforth
1.1 anton 15392:
1.81 anton 15393: Gforth descends from bigFORTH (1993) and fig-Forth. Of course, a
15394: significant part of the design of Gforth was prescribed by ANS Forth.
1.1 anton 15395:
1.20 pazsan 15396: Bernd Paysan wrote bigFORTH, a descendent from TurboForth, an unreleased
1.1 anton 15397: 32 bit native code version of VolksForth for the Atari ST, written
15398: mostly by Dietrich Weineck.
15399:
1.81 anton 15400: VolksForth was written by Klaus Schleisiek, Bernd Pennemann, Georg
15401: Rehfeld and Dietrich Weineck for the C64 (called UltraForth there) in
15402: the mid-80s and ported to the Atari ST in 1986. It descends from F83.
1.1 anton 15403:
15404: Henry Laxen and Mike Perry wrote F83 as a model implementation of the
15405: Forth-83 standard. !! Pedigree? When?
15406:
15407: A team led by Bill Ragsdale implemented fig-Forth on many processors in
15408: 1979. Robert Selzer and Bill Ragsdale developed the original
15409: implementation of fig-Forth for the 6502 based on microForth.
15410:
15411: The principal architect of microForth was Dean Sanderson. microForth was
15412: FORTH, Inc.'s first off-the-shelf product. It was developed in 1976 for
15413: the 1802, and subsequently implemented on the 8080, the 6800 and the
15414: Z80.
15415:
15416: All earlier Forth systems were custom-made, usually by Charles Moore,
15417: who discovered (as he puts it) Forth during the late 60s. The first full
15418: Forth existed in 1971.
15419:
1.81 anton 15420: A part of the information in this section comes from
15421: @cite{@uref{http://www.forth.com/Content/History/History1.htm,The
15422: Evolution of Forth}} by Elizabeth D. Rather, Donald R. Colburn and
15423: Charles H. Moore, presented at the HOPL-II conference and preprinted in
15424: SIGPLAN Notices 28(3), 1993. You can find more historical and
15425: genealogical information about Forth there.
1.1 anton 15426:
1.81 anton 15427: @c ------------------------------------------------------------------
1.21 crook 15428: @node Forth-related information, Word Index, Origin, Top
15429: @appendix Other Forth-related information
15430: @cindex Forth-related information
15431:
1.81 anton 15432: @c anton: I threw most of this stuff out, because it can be found through
15433: @c the FAQ and the FAQ is more likely to be up-to-date.
1.21 crook 15434:
15435: @cindex comp.lang.forth
15436: @cindex frequently asked questions
1.81 anton 15437: There is an active news group (comp.lang.forth) discussing Forth
15438: (including Gforth) and Forth-related issues. Its
15439: @uref{http://www.complang.tuwien.ac.at/forth/faq/faq-general-2.html,FAQs}
15440: (frequently asked questions and their answers) contains a lot of
15441: information on Forth. You should read it before posting to
15442: comp.lang.forth.
1.21 crook 15443:
1.81 anton 15444: The ANS Forth standard is most usable in its
15445: @uref{http://www.taygeta.com/forth/dpans.html, HTML form}.
1.21 crook 15446:
1.81 anton 15447: @c ------------------------------------------------------------------
15448: @node Word Index, Concept Index, Forth-related information, Top
1.1 anton 15449: @unnumbered Word Index
15450:
1.26 crook 15451: This index is a list of Forth words that have ``glossary'' entries
15452: within this manual. Each word is listed with its stack effect and
15453: wordset.
1.1 anton 15454:
15455: @printindex fn
15456:
1.81 anton 15457: @c anton: the name index seems superfluous given the word and concept indices.
15458:
15459: @c @node Name Index, Concept Index, Word Index, Top
15460: @c @unnumbered Name Index
1.41 anton 15461:
1.81 anton 15462: @c This index is a list of Forth words that have ``glossary'' entries
15463: @c within this manual.
1.41 anton 15464:
1.81 anton 15465: @c @printindex ky
1.41 anton 15466:
1.81 anton 15467: @node Concept Index, , Word Index, Top
1.1 anton 15468: @unnumbered Concept and Word Index
15469:
1.26 crook 15470: Not all entries listed in this index are present verbatim in the
15471: text. This index also duplicates, in abbreviated form, all of the words
15472: listed in the Word Index (only the names are listed for the words here).
1.1 anton 15473:
15474: @printindex cp
15475:
15476: @contents
15477: @bye
1.81 anton 15478:
15479:
1.1 anton 15480:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>