Annotation of gforth/doc/gforth.ds, revision 1.68
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
22: @dircategory GNU programming tools
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.62 crook 76: Copyright @copyright{} 1995--2000 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.62 crook 120: Copyright @copyright{} 1995--2000 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
1.41 anton 170: * Name Index:: Forth words, only names listed
1.1 anton 171: * Concept Index:: A menu covering many topics
1.12 anton 172:
1.48 anton 173: @detailmenu --- 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::
211: * Interpretation and Compilation Semantics and Immediacy Tutorial::
212: * Execution Tokens Tutorial::
213: * Exceptions Tutorial::
214: * Defining Words Tutorial::
215: * Arrays and Records Tutorial::
216: * POSTPONE Tutorial::
217: * Literal Tutorial::
218: * Advanced macros Tutorial::
219: * Compilation Tokens Tutorial::
220: * Wordlists and Search Order Tutorial::
1.29 crook 221:
1.24 anton 222: An Introduction to ANS Forth
223:
1.67 anton 224: * Introducing the Text Interpreter::
225: * Stacks and Postfix notation::
226: * Your first definition::
227: * How does that work?::
228: * Forth is written in Forth::
229: * Review - elements of a Forth system::
230: * Where to go next::
231: * Exercises::
1.24 anton 232:
1.12 anton 233: Forth Words
234:
235: * Notation::
1.65 anton 236: * Case insensitivity::
237: * Comments::
238: * Boolean Flags::
1.12 anton 239: * Arithmetic::
240: * Stack Manipulation::
241: * Memory::
242: * Control Structures::
243: * Defining Words::
1.65 anton 244: * Interpretation and Compilation Semantics::
1.47 crook 245: * Tokens for Words::
1.65 anton 246: * The Text Interpreter::
247: * Word Lists::
248: * Environmental Queries::
1.12 anton 249: * Files::
250: * Blocks::
251: * Other I/O::
252: * Programming Tools::
253: * Assembler and Code Words::
254: * Threading Words::
1.26 crook 255: * Locals::
256: * Structures::
257: * Object-oriented Forth::
1.65 anton 258: * Passing Commands to the OS::
259: * Keeping track of Time::
260: * Miscellaneous Words::
1.12 anton 261:
262: Arithmetic
263:
264: * Single precision::
1.67 anton 265: * Double precision:: Double-cell integer arithmetic
1.12 anton 266: * Bitwise operations::
1.67 anton 267: * Numeric comparison::
1.32 anton 268: * Mixed precision:: Operations with single and double-cell integers
1.12 anton 269: * Floating Point::
270:
271: Stack Manipulation
272:
273: * Data stack::
274: * Floating point stack::
275: * Return stack::
276: * Locals stack::
277: * Stack pointer manipulation::
278:
279: Memory
280:
1.32 anton 281: * Memory model::
282: * Dictionary allocation::
283: * Heap Allocation::
284: * Memory Access::
285: * Address arithmetic::
286: * Memory Blocks::
1.12 anton 287:
288: Control Structures
289:
1.41 anton 290: * Selection:: IF ... ELSE ... ENDIF
291: * Simple Loops:: BEGIN ...
1.32 anton 292: * Counted Loops:: DO
1.67 anton 293: * Arbitrary control structures::
294: * Calls and returns::
1.12 anton 295: * Exception Handling::
296:
297: Defining Words
298:
1.67 anton 299: * CREATE::
1.44 crook 300: * Variables:: Variables and user variables
1.67 anton 301: * Constants::
1.44 crook 302: * Values:: Initialised variables
1.67 anton 303: * Colon Definitions::
1.44 crook 304: * Anonymous Definitions:: Definitions without names
1.67 anton 305: * User-defined Defining Words::
1.44 crook 306: * Deferred words:: Allow forward references
1.67 anton 307: * Aliases::
308: * Supplying names::
1.47 crook 309:
1.63 anton 310: User-defined Defining Words
311:
312: * CREATE..DOES> applications::
313: * CREATE..DOES> details::
314: * Advanced does> usage example::
315:
1.47 crook 316: Interpretation and Compilation Semantics
317:
1.67 anton 318: * Combined words::
1.12 anton 319:
1.21 crook 320: The Text Interpreter
321:
1.67 anton 322: * Input Sources::
323: * Number Conversion::
324: * Interpret/Compile states::
325: * Literals::
326: * Interpreter Directives::
1.21 crook 327:
1.26 crook 328: Word Lists
329:
1.67 anton 330: * Why use word lists?::
331: * Word list examples::
1.26 crook 332:
333: Files
334:
1.48 anton 335: * Forth source files::
336: * General files::
337: * Search Paths::
338:
339: Search Paths
340:
341: * Forth Search Paths::
1.26 crook 342: * General Search Paths::
343:
344: Other I/O
345:
1.32 anton 346: * Simple numeric output:: Predefined formats
347: * Formatted numeric output:: Formatted (pictured) output
348: * String Formats:: How Forth stores strings in memory
1.67 anton 349: * Displaying characters and strings:: Other stuff
1.32 anton 350: * Input:: Input
1.26 crook 351:
352: Programming Tools
353:
354: * Debugging:: Simple and quick.
355: * Assertions:: Making your programs self-checking.
1.46 pazsan 356: * Singlestep Debugger:: Executing your program word by word.
1.26 crook 357:
1.63 anton 358: Assembler and Code Words
359:
360: * Code and ;code::
361: * Common Assembler:: Assembler Syntax
362: * Common Disassembler::
363: * 386 Assembler:: Deviations and special cases
364: * Alpha Assembler:: Deviations and special cases
365: * MIPS assembler:: Deviations and special cases
366: * Other assemblers:: How to write them
367:
1.26 crook 368: Locals
369:
370: * Gforth locals::
371: * ANS Forth locals::
372:
373: Gforth locals
374:
375: * Where are locals visible by name?::
376: * How long do locals live?::
377: * Programming Style::
378: * Implementation::
379:
1.12 anton 380: Structures
381:
382: * Why explicit structure support?::
383: * Structure Usage::
384: * Structure Naming Convention::
385: * Structure Implementation::
386: * Structure Glossary::
387:
388: Object-oriented Forth
389:
1.48 anton 390: * Why object-oriented programming?::
391: * Object-Oriented Terminology::
392: * Objects::
393: * OOF::
394: * Mini-OOF::
1.23 crook 395: * Comparison with other object models::
1.12 anton 396:
1.24 anton 397: The @file{objects.fs} model
1.12 anton 398:
399: * Properties of the Objects model::
400: * Basic Objects Usage::
1.41 anton 401: * The Objects base class::
1.12 anton 402: * Creating objects::
403: * Object-Oriented Programming Style::
404: * Class Binding::
405: * Method conveniences::
406: * Classes and Scoping::
1.41 anton 407: * Dividing classes::
1.12 anton 408: * Object Interfaces::
409: * Objects Implementation::
410: * Objects Glossary::
411:
1.24 anton 412: The @file{oof.fs} model
1.12 anton 413:
1.67 anton 414: * Properties of the OOF model::
415: * Basic OOF Usage::
416: * The OOF base class::
417: * Class Declaration::
418: * Class Implementation::
1.12 anton 419:
1.24 anton 420: The @file{mini-oof.fs} model
1.23 crook 421:
1.48 anton 422: * Basic Mini-OOF Usage::
423: * Mini-OOF Example::
424: * Mini-OOF Implementation::
1.23 crook 425:
1.12 anton 426: Tools
427:
428: * ANS Report:: Report the words used, sorted by wordset.
429:
430: ANS conformance
431:
432: * The Core Words::
433: * The optional Block word set::
434: * The optional Double Number word set::
435: * The optional Exception word set::
436: * The optional Facility word set::
437: * The optional File-Access word set::
438: * The optional Floating-Point word set::
439: * The optional Locals word set::
440: * The optional Memory-Allocation word set::
441: * The optional Programming-Tools word set::
442: * The optional Search-Order word set::
443:
444: The Core Words
445:
446: * core-idef:: Implementation Defined Options
447: * core-ambcond:: Ambiguous Conditions
448: * core-other:: Other System Documentation
449:
450: The optional Block word set
451:
452: * block-idef:: Implementation Defined Options
453: * block-ambcond:: Ambiguous Conditions
454: * block-other:: Other System Documentation
455:
456: The optional Double Number word set
457:
458: * double-ambcond:: Ambiguous Conditions
459:
460: The optional Exception word set
461:
462: * exception-idef:: Implementation Defined Options
463:
464: The optional Facility word set
465:
466: * facility-idef:: Implementation Defined Options
467: * facility-ambcond:: Ambiguous Conditions
468:
469: The optional File-Access word set
470:
471: * file-idef:: Implementation Defined Options
472: * file-ambcond:: Ambiguous Conditions
473:
474: The optional Floating-Point word set
475:
476: * floating-idef:: Implementation Defined Options
477: * floating-ambcond:: Ambiguous Conditions
478:
479: The optional Locals word set
480:
481: * locals-idef:: Implementation Defined Options
482: * locals-ambcond:: Ambiguous Conditions
483:
484: The optional Memory-Allocation word set
485:
486: * memory-idef:: Implementation Defined Options
487:
488: The optional Programming-Tools word set
489:
490: * programming-idef:: Implementation Defined Options
491: * programming-ambcond:: Ambiguous Conditions
492:
493: The optional Search-Order word set
494:
495: * search-idef:: Implementation Defined Options
496: * search-ambcond:: Ambiguous Conditions
497:
498: Image Files
499:
1.24 anton 500: * Image Licensing Issues:: Distribution terms for images.
501: * Image File Background:: Why have image files?
1.67 anton 502: * Non-Relocatable Image Files:: don't always work.
1.24 anton 503: * Data-Relocatable Image Files:: are better.
1.67 anton 504: * Fully Relocatable Image Files:: better yet.
1.24 anton 505: * Stack and Dictionary Sizes:: Setting the default sizes for an image.
1.32 anton 506: * Running Image Files:: @code{gforth -i @i{file}} or @i{file}.
1.24 anton 507: * Modifying the Startup Sequence:: and turnkey applications.
1.12 anton 508:
509: Fully Relocatable Image Files
510:
1.27 crook 511: * gforthmi:: The normal way
1.12 anton 512: * cross.fs:: The hard way
513:
514: Engine
515:
516: * Portability::
517: * Threading::
518: * Primitives::
519: * Performance::
520:
521: Threading
522:
523: * Scheduling::
524: * Direct or Indirect Threaded?::
525: * DOES>::
526:
527: Primitives
528:
529: * Automatic Generation::
530: * TOS Optimization::
531: * Produced code::
1.13 pazsan 532:
533: Cross Compiler
534:
1.67 anton 535: * Using the Cross Compiler::
536: * How the Cross Compiler Works::
1.13 pazsan 537:
1.24 anton 538: Other Forth-related information
1.21 crook 539:
1.67 anton 540: * Internet resources::
541: * Books::
542: * The Forth Interest Group::
543: * Conferences::
1.21 crook 544:
1.24 anton 545: @end detailmenu
1.1 anton 546: @end menu
547:
1.26 crook 548: @node License, Goals, Top, Top
1.1 anton 549: @unnumbered GNU GENERAL PUBLIC LICENSE
550: @center Version 2, June 1991
551:
552: @display
553: Copyright @copyright{} 1989, 1991 Free Software Foundation, Inc.
554: 675 Mass Ave, Cambridge, MA 02139, USA
555:
556: Everyone is permitted to copy and distribute verbatim copies
557: of this license document, but changing it is not allowed.
558: @end display
559:
560: @unnumberedsec Preamble
561:
562: The licenses for most software are designed to take away your
563: freedom to share and change it. By contrast, the GNU General Public
564: License is intended to guarantee your freedom to share and change free
565: software---to make sure the software is free for all its users. This
566: General Public License applies to most of the Free Software
567: Foundation's software and to any other program whose authors commit to
568: using it. (Some other Free Software Foundation software is covered by
569: the GNU Library General Public License instead.) You can apply it to
570: your programs, too.
571:
572: When we speak of free software, we are referring to freedom, not
573: price. Our General Public Licenses are designed to make sure that you
574: have the freedom to distribute copies of free software (and charge for
575: this service if you wish), that you receive source code or can get it
576: if you want it, that you can change the software or use pieces of it
577: in new free programs; and that you know you can do these things.
578:
579: To protect your rights, we need to make restrictions that forbid
580: anyone to deny you these rights or to ask you to surrender the rights.
581: These restrictions translate to certain responsibilities for you if you
582: distribute copies of the software, or if you modify it.
583:
584: For example, if you distribute copies of such a program, whether
585: gratis or for a fee, you must give the recipients all the rights that
586: you have. You must make sure that they, too, receive or can get the
587: source code. And you must show them these terms so they know their
588: rights.
589:
590: We protect your rights with two steps: (1) copyright the software, and
591: (2) offer you this license which gives you legal permission to copy,
592: distribute and/or modify the software.
593:
594: Also, for each author's protection and ours, we want to make certain
595: that everyone understands that there is no warranty for this free
596: software. If the software is modified by someone else and passed on, we
597: want its recipients to know that what they have is not the original, so
598: that any problems introduced by others will not reflect on the original
599: authors' reputations.
600:
601: Finally, any free program is threatened constantly by software
602: patents. We wish to avoid the danger that redistributors of a free
603: program will individually obtain patent licenses, in effect making the
604: program proprietary. To prevent this, we have made it clear that any
605: patent must be licensed for everyone's free use or not licensed at all.
606:
607: The precise terms and conditions for copying, distribution and
608: modification follow.
609:
610: @iftex
611: @unnumberedsec TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
612: @end iftex
1.49 anton 613: @ifnottex
1.1 anton 614: @center TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
1.49 anton 615: @end ifnottex
1.1 anton 616:
617: @enumerate 0
618: @item
619: This License applies to any program or other work which contains
620: a notice placed by the copyright holder saying it may be distributed
621: under the terms of this General Public License. The ``Program'', below,
622: refers to any such program or work, and a ``work based on the Program''
623: means either the Program or any derivative work under copyright law:
624: that is to say, a work containing the Program or a portion of it,
625: either verbatim or with modifications and/or translated into another
626: language. (Hereinafter, translation is included without limitation in
627: the term ``modification''.) Each licensee is addressed as ``you''.
628:
629: Activities other than copying, distribution and modification are not
630: covered by this License; they are outside its scope. The act of
631: running the Program is not restricted, and the output from the Program
632: is covered only if its contents constitute a work based on the
633: Program (independent of having been made by running the Program).
634: Whether that is true depends on what the Program does.
635:
636: @item
637: You may copy and distribute verbatim copies of the Program's
638: source code as you receive it, in any medium, provided that you
639: conspicuously and appropriately publish on each copy an appropriate
640: copyright notice and disclaimer of warranty; keep intact all the
641: notices that refer to this License and to the absence of any warranty;
642: and give any other recipients of the Program a copy of this License
643: along with the Program.
644:
645: You may charge a fee for the physical act of transferring a copy, and
646: you may at your option offer warranty protection in exchange for a fee.
647:
648: @item
649: You may modify your copy or copies of the Program or any portion
650: of it, thus forming a work based on the Program, and copy and
651: distribute such modifications or work under the terms of Section 1
652: above, provided that you also meet all of these conditions:
653:
654: @enumerate a
655: @item
656: You must cause the modified files to carry prominent notices
657: stating that you changed the files and the date of any change.
658:
659: @item
660: You must cause any work that you distribute or publish, that in
661: whole or in part contains or is derived from the Program or any
662: part thereof, to be licensed as a whole at no charge to all third
663: parties under the terms of this License.
664:
665: @item
666: If the modified program normally reads commands interactively
667: when run, you must cause it, when started running for such
668: interactive use in the most ordinary way, to print or display an
669: announcement including an appropriate copyright notice and a
670: notice that there is no warranty (or else, saying that you provide
671: a warranty) and that users may redistribute the program under
672: these conditions, and telling the user how to view a copy of this
673: License. (Exception: if the Program itself is interactive but
674: does not normally print such an announcement, your work based on
675: the Program is not required to print an announcement.)
676: @end enumerate
677:
678: These requirements apply to the modified work as a whole. If
679: identifiable sections of that work are not derived from the Program,
680: and can be reasonably considered independent and separate works in
681: themselves, then this License, and its terms, do not apply to those
682: sections when you distribute them as separate works. But when you
683: distribute the same sections as part of a whole which is a work based
684: on the Program, the distribution of the whole must be on the terms of
685: this License, whose permissions for other licensees extend to the
686: entire whole, and thus to each and every part regardless of who wrote it.
687:
688: Thus, it is not the intent of this section to claim rights or contest
689: your rights to work written entirely by you; rather, the intent is to
690: exercise the right to control the distribution of derivative or
691: collective works based on the Program.
692:
693: In addition, mere aggregation of another work not based on the Program
694: with the Program (or with a work based on the Program) on a volume of
695: a storage or distribution medium does not bring the other work under
696: the scope of this License.
697:
698: @item
699: You may copy and distribute the Program (or a work based on it,
700: under Section 2) in object code or executable form under the terms of
701: Sections 1 and 2 above provided that you also do one of the following:
702:
703: @enumerate a
704: @item
705: Accompany it with the complete corresponding machine-readable
706: source code, which must be distributed under the terms of Sections
707: 1 and 2 above on a medium customarily used for software interchange; or,
708:
709: @item
710: Accompany it with a written offer, valid for at least three
711: years, to give any third party, for a charge no more than your
712: cost of physically performing source distribution, a complete
713: machine-readable copy of the corresponding source code, to be
714: distributed under the terms of Sections 1 and 2 above on a medium
715: customarily used for software interchange; or,
716:
717: @item
718: Accompany it with the information you received as to the offer
719: to distribute corresponding source code. (This alternative is
720: allowed only for noncommercial distribution and only if you
721: received the program in object code or executable form with such
722: an offer, in accord with Subsection b above.)
723: @end enumerate
724:
725: The source code for a work means the preferred form of the work for
726: making modifications to it. For an executable work, complete source
727: code means all the source code for all modules it contains, plus any
728: associated interface definition files, plus the scripts used to
729: control compilation and installation of the executable. However, as a
730: special exception, the source code distributed need not include
731: anything that is normally distributed (in either source or binary
732: form) with the major components (compiler, kernel, and so on) of the
733: operating system on which the executable runs, unless that component
734: itself accompanies the executable.
735:
736: If distribution of executable or object code is made by offering
737: access to copy from a designated place, then offering equivalent
738: access to copy the source code from the same place counts as
739: distribution of the source code, even though third parties are not
740: compelled to copy the source along with the object code.
741:
742: @item
743: You may not copy, modify, sublicense, or distribute the Program
744: except as expressly provided under this License. Any attempt
745: otherwise to copy, modify, sublicense or distribute the Program is
746: void, and will automatically terminate your rights under this License.
747: However, parties who have received copies, or rights, from you under
748: this License will not have their licenses terminated so long as such
749: parties remain in full compliance.
750:
751: @item
752: You are not required to accept this License, since you have not
753: signed it. However, nothing else grants you permission to modify or
754: distribute the Program or its derivative works. These actions are
755: prohibited by law if you do not accept this License. Therefore, by
756: modifying or distributing the Program (or any work based on the
757: Program), you indicate your acceptance of this License to do so, and
758: all its terms and conditions for copying, distributing or modifying
759: the Program or works based on it.
760:
761: @item
762: Each time you redistribute the Program (or any work based on the
763: Program), the recipient automatically receives a license from the
764: original licensor to copy, distribute or modify the Program subject to
765: these terms and conditions. You may not impose any further
766: restrictions on the recipients' exercise of the rights granted herein.
767: You are not responsible for enforcing compliance by third parties to
768: this License.
769:
770: @item
771: If, as a consequence of a court judgment or allegation of patent
772: infringement or for any other reason (not limited to patent issues),
773: conditions are imposed on you (whether by court order, agreement or
774: otherwise) that contradict the conditions of this License, they do not
775: excuse you from the conditions of this License. If you cannot
776: distribute so as to satisfy simultaneously your obligations under this
777: License and any other pertinent obligations, then as a consequence you
778: may not distribute the Program at all. For example, if a patent
779: license would not permit royalty-free redistribution of the Program by
780: all those who receive copies directly or indirectly through you, then
781: the only way you could satisfy both it and this License would be to
782: refrain entirely from distribution of the Program.
783:
784: If any portion of this section is held invalid or unenforceable under
785: any particular circumstance, the balance of the section is intended to
786: apply and the section as a whole is intended to apply in other
787: circumstances.
788:
789: It is not the purpose of this section to induce you to infringe any
790: patents or other property right claims or to contest validity of any
791: such claims; this section has the sole purpose of protecting the
792: integrity of the free software distribution system, which is
793: implemented by public license practices. Many people have made
794: generous contributions to the wide range of software distributed
795: through that system in reliance on consistent application of that
796: system; it is up to the author/donor to decide if he or she is willing
797: to distribute software through any other system and a licensee cannot
798: impose that choice.
799:
800: This section is intended to make thoroughly clear what is believed to
801: be a consequence of the rest of this License.
802:
803: @item
804: If the distribution and/or use of the Program is restricted in
805: certain countries either by patents or by copyrighted interfaces, the
806: original copyright holder who places the Program under this License
807: may add an explicit geographical distribution limitation excluding
808: those countries, so that distribution is permitted only in or among
809: countries not thus excluded. In such case, this License incorporates
810: the limitation as if written in the body of this License.
811:
812: @item
813: The Free Software Foundation may publish revised and/or new versions
814: of the General Public License from time to time. Such new versions will
815: be similar in spirit to the present version, but may differ in detail to
816: address new problems or concerns.
817:
818: Each version is given a distinguishing version number. If the Program
819: specifies a version number of this License which applies to it and ``any
820: later version'', you have the option of following the terms and conditions
821: either of that version or of any later version published by the Free
822: Software Foundation. If the Program does not specify a version number of
823: this License, you may choose any version ever published by the Free Software
824: Foundation.
825:
826: @item
827: If you wish to incorporate parts of the Program into other free
828: programs whose distribution conditions are different, write to the author
829: to ask for permission. For software which is copyrighted by the Free
830: Software Foundation, write to the Free Software Foundation; we sometimes
831: make exceptions for this. Our decision will be guided by the two goals
832: of preserving the free status of all derivatives of our free software and
833: of promoting the sharing and reuse of software generally.
834:
835: @iftex
836: @heading NO WARRANTY
837: @end iftex
1.49 anton 838: @ifnottex
1.1 anton 839: @center NO WARRANTY
1.49 anton 840: @end ifnottex
1.1 anton 841:
842: @item
843: BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
844: FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
845: OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
846: PROVIDE THE PROGRAM ``AS IS'' WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
847: OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
848: MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
849: TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
850: PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
851: REPAIR OR CORRECTION.
852:
853: @item
854: IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
855: WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
856: REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
857: INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
858: OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
859: TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
860: YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
861: PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
862: POSSIBILITY OF SUCH DAMAGES.
863: @end enumerate
864:
865: @iftex
866: @heading END OF TERMS AND CONDITIONS
867: @end iftex
1.49 anton 868: @ifnottex
1.1 anton 869: @center END OF TERMS AND CONDITIONS
1.49 anton 870: @end ifnottex
1.1 anton 871:
872: @page
873: @unnumberedsec How to Apply These Terms to Your New Programs
874:
875: If you develop a new program, and you want it to be of the greatest
876: possible use to the public, the best way to achieve this is to make it
877: free software which everyone can redistribute and change under these terms.
878:
879: To do so, attach the following notices to the program. It is safest
880: to attach them to the start of each source file to most effectively
881: convey the exclusion of warranty; and each file should have at least
882: the ``copyright'' line and a pointer to where the full notice is found.
883:
884: @smallexample
885: @var{one line to give the program's name and a brief idea of what it does.}
886: Copyright (C) 19@var{yy} @var{name of author}
887:
888: This program is free software; you can redistribute it and/or modify
889: it under the terms of the GNU General Public License as published by
890: the Free Software Foundation; either version 2 of the License, or
891: (at your option) any later version.
892:
893: This program is distributed in the hope that it will be useful,
894: but WITHOUT ANY WARRANTY; without even the implied warranty of
895: MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
896: GNU General Public License for more details.
897:
898: You should have received a copy of the GNU General Public License
899: along with this program; if not, write to the Free Software
900: Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
901: @end smallexample
902:
903: Also add information on how to contact you by electronic and paper mail.
904:
905: If the program is interactive, make it output a short notice like this
906: when it starts in an interactive mode:
907:
908: @smallexample
909: Gnomovision version 69, Copyright (C) 19@var{yy} @var{name of author}
910: Gnomovision comes with ABSOLUTELY NO WARRANTY; for details
911: type `show w'.
912: This is free software, and you are welcome to redistribute it
913: under certain conditions; type `show c' for details.
914: @end smallexample
915:
916: The hypothetical commands @samp{show w} and @samp{show c} should show
917: the appropriate parts of the General Public License. Of course, the
918: commands you use may be called something other than @samp{show w} and
919: @samp{show c}; they could even be mouse-clicks or menu items---whatever
920: suits your program.
921:
922: You should also get your employer (if you work as a programmer) or your
923: school, if any, to sign a ``copyright disclaimer'' for the program, if
924: necessary. Here is a sample; alter the names:
925:
926: @smallexample
927: Yoyodyne, Inc., hereby disclaims all copyright interest in the program
928: `Gnomovision' (which makes passes at compilers) written by James Hacker.
929:
930: @var{signature of Ty Coon}, 1 April 1989
931: Ty Coon, President of Vice
932: @end smallexample
933:
934: This General Public License does not permit incorporating your program into
935: proprietary programs. If your program is a subroutine library, you may
936: consider it more useful to permit linking proprietary applications with the
937: library. If this is what you want to do, use the GNU Library General
938: Public License instead of this License.
939:
940: @iftex
941: @unnumbered Preface
942: @cindex Preface
1.21 crook 943: This manual documents Gforth. Some introductory material is provided for
944: readers who are unfamiliar with Forth or who are migrating to Gforth
945: from other Forth compilers. However, this manual is primarily a
946: reference manual.
1.1 anton 947: @end iftex
948:
1.28 crook 949: @comment TODO much more blurb here.
1.26 crook 950:
951: @c ******************************************************************
1.29 crook 952: @node Goals, Gforth Environment, License, Top
1.26 crook 953: @comment node-name, next, previous, up
954: @chapter Goals of Gforth
955: @cindex goals of the Gforth project
956: The goal of the Gforth Project is to develop a standard model for
957: ANS Forth. This can be split into several subgoals:
958:
959: @itemize @bullet
960: @item
961: Gforth should conform to the ANS Forth Standard.
962: @item
963: It should be a model, i.e. it should define all the
964: implementation-dependent things.
965: @item
966: It should become standard, i.e. widely accepted and used. This goal
967: is the most difficult one.
968: @end itemize
969:
970: To achieve these goals Gforth should be
971: @itemize @bullet
972: @item
973: Similar to previous models (fig-Forth, F83)
974: @item
975: Powerful. It should provide for all the things that are considered
976: necessary today and even some that are not yet considered necessary.
977: @item
978: Efficient. It should not get the reputation of being exceptionally
979: slow.
980: @item
981: Free.
982: @item
983: Available on many machines/easy to port.
984: @end itemize
985:
986: Have we achieved these goals? Gforth conforms to the ANS Forth
987: standard. It may be considered a model, but we have not yet documented
988: which parts of the model are stable and which parts we are likely to
989: change. It certainly has not yet become a de facto standard, but it
990: appears to be quite popular. It has some similarities to and some
991: differences from previous models. It has some powerful features, but not
992: yet everything that we envisioned. We certainly have achieved our
1.65 anton 993: execution speed goals (@pxref{Performance})@footnote{However, in 1998
994: the bar was raised when the major commercial Forth vendors switched to
995: native code compilers.}. It is free and available on many machines.
1.29 crook 996:
1.26 crook 997: @c ******************************************************************
1.48 anton 998: @node Gforth Environment, Tutorial, Goals, Top
1.29 crook 999: @chapter Gforth Environment
1000: @cindex Gforth environment
1.21 crook 1001:
1.45 crook 1002: Note: ultimately, the Gforth man page will be auto-generated from the
1.29 crook 1003: material in this chapter.
1.21 crook 1004:
1005: @menu
1.29 crook 1006: * Invoking Gforth:: Getting in
1007: * Leaving Gforth:: Getting out
1008: * Command-line editing::
1.48 anton 1009: * Environment variables:: that affect how Gforth starts up
1.29 crook 1010: * Gforth Files:: What gets installed and where
1.48 anton 1011: * Startup speed:: When 35ms is not fast enough ...
1.21 crook 1012: @end menu
1013:
1.49 anton 1014: For related information about the creation of images see @ref{Image Files}.
1.29 crook 1015:
1.21 crook 1016: @comment ----------------------------------------------
1.48 anton 1017: @node Invoking Gforth, Leaving Gforth, Gforth Environment, Gforth Environment
1.29 crook 1018: @section Invoking Gforth
1019: @cindex invoking Gforth
1020: @cindex running Gforth
1021: @cindex command-line options
1022: @cindex options on the command line
1023: @cindex flags on the command line
1.21 crook 1024:
1.30 anton 1025: Gforth is made up of two parts; an executable ``engine'' (named
1026: @file{gforth} or @file{gforth-fast}) and an image file. To start it, you
1027: will usually just say @code{gforth} -- this automatically loads the
1028: default image file @file{gforth.fi}. In many other cases the default
1029: Gforth image will be invoked like this:
1.21 crook 1030: @example
1.30 anton 1031: gforth [file | -e forth-code] ...
1.21 crook 1032: @end example
1.29 crook 1033: @noindent
1034: This interprets the contents of the files and the Forth code in the order they
1035: are given.
1.21 crook 1036:
1.30 anton 1037: In addition to the @file{gforth} engine, there is also an engine called
1038: @file{gforth-fast}, which is faster, but gives less informative error
1039: messages (@pxref{Error messages}).
1040:
1.29 crook 1041: In general, the command line looks like this:
1.21 crook 1042:
1043: @example
1.30 anton 1044: gforth[-fast] [engine options] [image options]
1.21 crook 1045: @end example
1046:
1.30 anton 1047: The engine options must come before the rest of the command
1.29 crook 1048: line. They are:
1.26 crook 1049:
1.29 crook 1050: @table @code
1051: @cindex -i, command-line option
1052: @cindex --image-file, command-line option
1053: @item --image-file @i{file}
1054: @itemx -i @i{file}
1055: Loads the Forth image @i{file} instead of the default
1056: @file{gforth.fi} (@pxref{Image Files}).
1.21 crook 1057:
1.39 anton 1058: @cindex --appl-image, command-line option
1059: @item --appl-image @i{file}
1060: Loads the image @i{file} and leaves all further command-line arguments
1.65 anton 1061: to the image (instead of processing them as engine options). This is
1062: useful for building executable application images on Unix, built with
1.39 anton 1063: @code{gforthmi --application ...}.
1064:
1.29 crook 1065: @cindex --path, command-line option
1066: @cindex -p, command-line option
1067: @item --path @i{path}
1068: @itemx -p @i{path}
1069: Uses @i{path} for searching the image file and Forth source code files
1070: instead of the default in the environment variable @code{GFORTHPATH} or
1071: the path specified at installation time (e.g.,
1072: @file{/usr/local/share/gforth/0.2.0:.}). A path is given as a list of
1073: directories, separated by @samp{:} (on Unix) or @samp{;} (on other OSs).
1.21 crook 1074:
1.29 crook 1075: @cindex --dictionary-size, command-line option
1076: @cindex -m, command-line option
1077: @cindex @i{size} parameters for command-line options
1078: @cindex size of the dictionary and the stacks
1079: @item --dictionary-size @i{size}
1080: @itemx -m @i{size}
1081: Allocate @i{size} space for the Forth dictionary space instead of
1082: using the default specified in the image (typically 256K). The
1083: @i{size} specification for this and subsequent options consists of
1084: an integer and a unit (e.g.,
1085: @code{4M}). The unit can be one of @code{b} (bytes), @code{e} (element
1086: size, in this case Cells), @code{k} (kilobytes), @code{M} (Megabytes),
1087: @code{G} (Gigabytes), and @code{T} (Terabytes). If no unit is specified,
1088: @code{e} is used.
1.21 crook 1089:
1.29 crook 1090: @cindex --data-stack-size, command-line option
1091: @cindex -d, command-line option
1092: @item --data-stack-size @i{size}
1093: @itemx -d @i{size}
1094: Allocate @i{size} space for the data stack instead of using the
1095: default specified in the image (typically 16K).
1.21 crook 1096:
1.29 crook 1097: @cindex --return-stack-size, command-line option
1098: @cindex -r, command-line option
1099: @item --return-stack-size @i{size}
1100: @itemx -r @i{size}
1101: Allocate @i{size} space for the return stack instead of using the
1102: default specified in the image (typically 15K).
1.21 crook 1103:
1.29 crook 1104: @cindex --fp-stack-size, command-line option
1105: @cindex -f, command-line option
1106: @item --fp-stack-size @i{size}
1107: @itemx -f @i{size}
1108: Allocate @i{size} space for the floating point stack instead of
1109: using the default specified in the image (typically 15.5K). In this case
1110: the unit specifier @code{e} refers to floating point numbers.
1.21 crook 1111:
1.48 anton 1112: @cindex --locals-stack-size, command-line option
1113: @cindex -l, command-line option
1114: @item --locals-stack-size @i{size}
1115: @itemx -l @i{size}
1116: Allocate @i{size} space for the locals stack instead of using the
1117: default specified in the image (typically 14.5K).
1118:
1119: @cindex -h, command-line option
1120: @cindex --help, command-line option
1121: @item --help
1122: @itemx -h
1123: Print a message about the command-line options
1124:
1125: @cindex -v, command-line option
1126: @cindex --version, command-line option
1127: @item --version
1128: @itemx -v
1129: Print version and exit
1130:
1131: @cindex --debug, command-line option
1132: @item --debug
1133: Print some information useful for debugging on startup.
1134:
1135: @cindex --offset-image, command-line option
1136: @item --offset-image
1137: Start the dictionary at a slightly different position than would be used
1138: otherwise (useful for creating data-relocatable images,
1139: @pxref{Data-Relocatable Image Files}).
1140:
1141: @cindex --no-offset-im, command-line option
1142: @item --no-offset-im
1143: Start the dictionary at the normal position.
1144:
1145: @cindex --clear-dictionary, command-line option
1146: @item --clear-dictionary
1147: Initialize all bytes in the dictionary to 0 before loading the image
1148: (@pxref{Data-Relocatable Image Files}).
1149:
1150: @cindex --die-on-signal, command-line-option
1151: @item --die-on-signal
1152: Normally Gforth handles most signals (e.g., the user interrupt SIGINT,
1153: or the segmentation violation SIGSEGV) by translating it into a Forth
1154: @code{THROW}. With this option, Gforth exits if it receives such a
1155: signal. This option is useful when the engine and/or the image might be
1156: severely broken (such that it causes another signal before recovering
1157: from the first); this option avoids endless loops in such cases.
1158: @end table
1159:
1160: @cindex loading files at startup
1161: @cindex executing code on startup
1162: @cindex batch processing with Gforth
1163: As explained above, the image-specific command-line arguments for the
1164: default image @file{gforth.fi} consist of a sequence of filenames and
1165: @code{-e @var{forth-code}} options that are interpreted in the sequence
1166: in which they are given. The @code{-e @var{forth-code}} or
1167: @code{--evaluate @var{forth-code}} option evaluates the Forth
1168: code. This option takes only one argument; if you want to evaluate more
1169: Forth words, you have to quote them or use @code{-e} several times. To exit
1170: after processing the command line (instead of entering interactive mode)
1171: append @code{-e bye} to the command line.
1172:
1173: @cindex versions, invoking other versions of Gforth
1174: If you have several versions of Gforth installed, @code{gforth} will
1175: invoke the version that was installed last. @code{gforth-@i{version}}
1176: invokes a specific version. If your environment contains the variable
1177: @code{GFORTHPATH}, you may want to override it by using the
1178: @code{--path} option.
1179:
1180: Not yet implemented:
1181: On startup the system first executes the system initialization file
1182: (unless the option @code{--no-init-file} is given; note that the system
1183: resulting from using this option may not be ANS Forth conformant). Then
1184: the user initialization file @file{.gforth.fs} is executed, unless the
1.62 crook 1185: option @code{--no-rc} is given; this file is searched for in @file{.},
1.48 anton 1186: then in @file{~}, then in the normal path (see above).
1187:
1188:
1189:
1190: @comment ----------------------------------------------
1191: @node Leaving Gforth, Command-line editing, Invoking Gforth, Gforth Environment
1192: @section Leaving Gforth
1193: @cindex Gforth - leaving
1194: @cindex leaving Gforth
1195:
1196: You can leave Gforth by typing @code{bye} or @kbd{Ctrl-d} (at the start
1197: of a line) or (if you invoked Gforth with the @code{--die-on-signal}
1198: option) @kbd{Ctrl-c}. When you leave Gforth, all of your definitions and
1.49 anton 1199: data are discarded. For ways of saving the state of the system before
1200: leaving Gforth see @ref{Image Files}.
1.48 anton 1201:
1202: doc-bye
1203:
1204:
1205: @comment ----------------------------------------------
1.65 anton 1206: @node Command-line editing, Environment variables, Leaving Gforth, Gforth Environment
1.48 anton 1207: @section Command-line editing
1208: @cindex command-line editing
1209:
1210: Gforth maintains a history file that records every line that you type to
1211: the text interpreter. This file is preserved between sessions, and is
1212: used to provide a command-line recall facility; if you type @kbd{Ctrl-P}
1213: repeatedly you can recall successively older commands from this (or
1214: previous) session(s). The full list of command-line editing facilities is:
1215:
1216: @itemize @bullet
1217: @item
1218: @kbd{Ctrl-p} (``previous'') (or up-arrow) to recall successively older
1219: commands from the history buffer.
1220: @item
1221: @kbd{Ctrl-n} (``next'') (or down-arrow) to recall successively newer commands
1222: from the history buffer.
1223: @item
1224: @kbd{Ctrl-f} (or right-arrow) to move the cursor right, non-destructively.
1225: @item
1226: @kbd{Ctrl-b} (or left-arrow) to move the cursor left, non-destructively.
1227: @item
1228: @kbd{Ctrl-h} (backspace) to delete the character to the left of the cursor,
1229: closing up the line.
1230: @item
1231: @kbd{Ctrl-k} to delete (``kill'') from the cursor to the end of the line.
1232: @item
1233: @kbd{Ctrl-a} to move the cursor to the start of the line.
1234: @item
1235: @kbd{Ctrl-e} to move the cursor to the end of the line.
1236: @item
1237: @key{RET} (@kbd{Ctrl-m}) or @key{LFD} (@kbd{Ctrl-j}) to submit the current
1238: line.
1239: @item
1240: @key{TAB} to step through all possible full-word completions of the word
1241: currently being typed.
1242: @item
1.65 anton 1243: @kbd{Ctrl-d} on an empty line line to terminate Gforth (gracefully,
1244: using @code{bye}).
1245: @item
1246: @kbd{Ctrl-x} (or @code{Ctrl-d} on a non-empty line) to delete the
1247: character under the cursor.
1.48 anton 1248: @end itemize
1249:
1250: When editing, displayable characters are inserted to the left of the
1251: cursor position; the line is always in ``insert'' (as opposed to
1252: ``overstrike'') mode.
1253:
1254: @cindex history file
1255: @cindex @file{.gforth-history}
1256: On Unix systems, the history file is @file{~/.gforth-history} by
1257: default@footnote{i.e. it is stored in the user's home directory.}. You
1258: can find out the name and location of your history file using:
1259:
1260: @example
1261: history-file type \ Unix-class systems
1262:
1263: history-file type \ Other systems
1264: history-dir type
1265: @end example
1266:
1267: If you enter long definitions by hand, you can use a text editor to
1268: paste them out of the history file into a Forth source file for reuse at
1269: a later time.
1270:
1271: Gforth never trims the size of the history file, so you should do this
1272: periodically, if necessary.
1273:
1274: @comment this is all defined in history.fs
1275: @comment NAC TODO the ctrl-D behaviour can either do a bye or a beep.. how is that option
1276: @comment chosen?
1277:
1278:
1279: @comment ----------------------------------------------
1.65 anton 1280: @node Environment variables, Gforth Files, Command-line editing, Gforth Environment
1.48 anton 1281: @section Environment variables
1282: @cindex environment variables
1283:
1284: Gforth uses these environment variables:
1285:
1286: @itemize @bullet
1287: @item
1288: @cindex @code{GFORTHHIST} -- environment variable
1289: @code{GFORTHHIST} -- (Unix systems only) specifies the directory in which to
1290: open/create the history file, @file{.gforth-history}. Default:
1291: @code{$HOME}.
1292:
1293: @item
1294: @cindex @code{GFORTHPATH} -- environment variable
1295: @code{GFORTHPATH} -- specifies the path used when searching for the gforth image file and
1296: for Forth source-code files.
1297:
1298: @item
1299: @cindex @code{GFORTH} -- environment variable
1.49 anton 1300: @code{GFORTH} -- used by @file{gforthmi}, @xref{gforthmi}.
1.48 anton 1301:
1302: @item
1303: @cindex @code{GFORTHD} -- environment variable
1.62 crook 1304: @code{GFORTHD} -- used by @file{gforthmi}, @xref{gforthmi}.
1.48 anton 1305:
1306: @item
1307: @cindex @code{TMP}, @code{TEMP} - environment variable
1308: @code{TMP}, @code{TEMP} - (non-Unix systems only) used as a potential
1309: location for the history file.
1310: @end itemize
1311:
1312: @comment also POSIXELY_CORRECT LINES COLUMNS HOME but no interest in
1313: @comment mentioning these.
1314:
1315: All the Gforth environment variables default to sensible values if they
1316: are not set.
1317:
1318:
1319: @comment ----------------------------------------------
1320: @node Gforth Files, Startup speed, Environment variables, Gforth Environment
1321: @section Gforth files
1322: @cindex Gforth files
1323:
1324: When you install Gforth on a Unix system, it installs files in these
1325: locations by default:
1326:
1327: @itemize @bullet
1328: @item
1329: @file{/usr/local/bin/gforth}
1330: @item
1331: @file{/usr/local/bin/gforthmi}
1332: @item
1333: @file{/usr/local/man/man1/gforth.1} - man page.
1334: @item
1335: @file{/usr/local/info} - the Info version of this manual.
1336: @item
1337: @file{/usr/local/lib/gforth/<version>/...} - Gforth @file{.fi} files.
1338: @item
1339: @file{/usr/local/share/gforth/<version>/TAGS} - Emacs TAGS file.
1340: @item
1341: @file{/usr/local/share/gforth/<version>/...} - Gforth source files.
1342: @item
1343: @file{.../emacs/site-lisp/gforth.el} - Emacs gforth mode.
1344: @end itemize
1345:
1346: You can select different places for installation by using
1347: @code{configure} options (listed with @code{configure --help}).
1348:
1349: @comment ----------------------------------------------
1350: @node Startup speed, , Gforth Files, Gforth Environment
1351: @section Startup speed
1352: @cindex Startup speed
1353: @cindex speed, startup
1354:
1355: If Gforth is used for CGI scripts or in shell scripts, its startup
1356: speed may become a problem. On a 300MHz 21064a under Linux-2.2.13 with
1357: glibc-2.0.7, @code{gforth -e bye} takes about 24.6ms user and 11.3ms
1358: system time.
1359:
1360: If startup speed is a problem, you may consider the following ways to
1361: improve it; or you may consider ways to reduce the number of startups
1.62 crook 1362: (for example, by using Fast-CGI).
1.48 anton 1363:
1364: The first step to improve startup speed is to statically link Gforth, by
1365: building it with @code{XLDFLAGS=-static}. This requires more memory for
1366: the code and will therefore slow down the first invocation, but
1367: subsequent invocations avoid the dynamic linking overhead. Another
1368: disadvantage is that Gforth won't profit from library upgrades. As a
1369: result, @code{gforth-static -e bye} takes about 17.1ms user and
1370: 8.2ms system time.
1371:
1372: The next step to improve startup speed is to use a non-relocatable image
1.65 anton 1373: (@pxref{Non-Relocatable Image Files}). You can create this image with
1.48 anton 1374: @code{gforth -e "savesystem gforthnr.fi bye"} and later use it with
1375: @code{gforth -i gforthnr.fi ...}. This avoids the relocation overhead
1376: and a part of the copy-on-write overhead. The disadvantage is that the
1.62 crook 1377: non-relocatable image does not work if the OS gives Gforth a different
1.48 anton 1378: address for the dictionary, for whatever reason; so you better provide a
1379: fallback on a relocatable image. @code{gforth-static -i gforthnr.fi -e
1380: bye} takes about 15.3ms user and 7.5ms system time.
1381:
1382: The final step is to disable dictionary hashing in Gforth. Gforth
1383: builds the hash table on startup, which takes much of the startup
1384: overhead. You can do this by commenting out the @code{include hash.fs}
1385: in @file{startup.fs} and everything that requires @file{hash.fs} (at the
1386: moment @file{table.fs} and @file{ekey.fs}) and then doing @code{make}.
1387: The disadvantages are that functionality like @code{table} and
1388: @code{ekey} is missing and that text interpretation (e.g., compiling)
1389: now takes much longer. So, you should only use this method if there is
1390: no significant text interpretation to perform (the script should be
1.62 crook 1391: compiled into the image, amongst other things). @code{gforth-static -i
1.48 anton 1392: gforthnrnh.fi -e bye} takes about 2.1ms user and 6.1ms system time.
1393:
1394: @c ******************************************************************
1395: @node Tutorial, Introduction, Gforth Environment, Top
1396: @chapter Forth Tutorial
1397: @cindex Tutorial
1398: @cindex Forth Tutorial
1399:
1.67 anton 1400: @c Topics from nac's Introduction that could be mentioned:
1401: @c press <ret> after each line
1402: @c Prompt
1403: @c numbers vs. words in dictionary on text interpretation
1404: @c what happens on redefinition
1405: @c parsing words (in particular, defining words)
1406:
1.62 crook 1407: This tutorial can be used with any ANS-compliant Forth; any
1408: Gforth-specific features are marked as such and you can skip them if you
1409: work with another Forth. This tutorial does not explain all features of
1410: Forth, just enough to get you started and give you some ideas about the
1411: facilities available in Forth. Read the rest of the manual and the
1412: standard when you are through this.
1.48 anton 1413:
1414: The intended way to use this tutorial is that you work through it while
1415: sitting in front of the console, take a look at the examples and predict
1416: what they will do, then try them out; if the outcome is not as expected,
1417: find out why (e.g., by trying out variations of the example), so you
1418: understand what's going on. There are also some assignments that you
1419: should solve.
1420:
1421: This tutorial assumes that you have programmed before and know what,
1422: e.g., a loop is.
1423:
1424: @c !! explain compat library
1425:
1426: @menu
1427: * Starting Gforth Tutorial::
1428: * Syntax Tutorial::
1429: * Crash Course Tutorial::
1430: * Stack Tutorial::
1431: * Arithmetics Tutorial::
1432: * Stack Manipulation Tutorial::
1433: * Using files for Forth code Tutorial::
1434: * Comments Tutorial::
1435: * Colon Definitions Tutorial::
1436: * Decompilation Tutorial::
1437: * Stack-Effect Comments Tutorial::
1438: * Types Tutorial::
1439: * Factoring Tutorial::
1440: * Designing the stack effect Tutorial::
1441: * Local Variables Tutorial::
1442: * Conditional execution Tutorial::
1443: * Flags and Comparisons Tutorial::
1444: * General Loops Tutorial::
1445: * Counted loops Tutorial::
1446: * Recursion Tutorial::
1447: * Leaving definitions or loops Tutorial::
1448: * Return Stack Tutorial::
1449: * Memory Tutorial::
1450: * Characters and Strings Tutorial::
1451: * Alignment Tutorial::
1452: * Interpretation and Compilation Semantics and Immediacy Tutorial::
1453: * Execution Tokens Tutorial::
1454: * Exceptions Tutorial::
1455: * Defining Words Tutorial::
1456: * Arrays and Records Tutorial::
1457: * POSTPONE Tutorial::
1458: * Literal Tutorial::
1459: * Advanced macros Tutorial::
1460: * Compilation Tokens Tutorial::
1461: * Wordlists and Search Order Tutorial::
1462: @end menu
1463:
1464: @node Starting Gforth Tutorial, Syntax Tutorial, Tutorial, Tutorial
1465: @section Starting Gforth
1.66 anton 1466: @cindex starting Gforth tutorial
1.48 anton 1467: You can start Gforth by typing its name:
1468:
1469: @example
1470: gforth
1471: @end example
1472:
1473: That puts you into interactive mode; you can leave Gforth by typing
1474: @code{bye}. While in Gforth, you can edit the command line and access
1475: the command line history with cursor keys, similar to bash.
1476:
1477:
1478: @node Syntax Tutorial, Crash Course Tutorial, Starting Gforth Tutorial, Tutorial
1479: @section Syntax
1.66 anton 1480: @cindex syntax tutorial
1.48 anton 1481:
1482: A @dfn{word} is a sequence of arbitrary characters (expcept white
1483: space). Words are separated by white space. E.g., each of the
1484: following lines contains exactly one word:
1485:
1486: @example
1487: word
1488: !@@#$%^&*()
1489: 1234567890
1490: 5!a
1491: @end example
1492:
1493: A frequent beginner's error is to leave away necessary white space,
1494: resulting in an error like @samp{Undefined word}; so if you see such an
1495: error, check if you have put spaces wherever necessary.
1496:
1497: @example
1498: ." hello, world" \ correct
1499: ."hello, world" \ gives an "Undefined word" error
1500: @end example
1501:
1.65 anton 1502: Gforth and most other Forth systems ignore differences in case (they are
1.48 anton 1503: case-insensitive), i.e., @samp{word} is the same as @samp{Word}. If
1504: your system is case-sensitive, you may have to type all the examples
1505: given here in upper case.
1506:
1507:
1508: @node Crash Course Tutorial, Stack Tutorial, Syntax Tutorial, Tutorial
1509: @section Crash Course
1510:
1511: Type
1512:
1513: @example
1514: 0 0 !
1515: here execute
1516: ' catch >body 20 erase abort
1517: ' (quit) >body 20 erase
1518: @end example
1519:
1520: The last two examples are guaranteed to destroy parts of Gforth (and
1521: most other systems), so you better leave Gforth afterwards (if it has
1522: not finished by itself). On some systems you may have to kill gforth
1523: from outside (e.g., in Unix with @code{kill}).
1524:
1525: Now that you know how to produce crashes (and that there's not much to
1526: them), let's learn how to produce meaningful programs.
1527:
1528:
1529: @node Stack Tutorial, Arithmetics Tutorial, Crash Course Tutorial, Tutorial
1530: @section Stack
1.66 anton 1531: @cindex stack tutorial
1.48 anton 1532:
1533: The most obvious feature of Forth is the stack. When you type in a
1534: number, it is pushed on the stack. You can display the content of the
1535: stack with @code{.s}.
1536:
1537: @example
1538: 1 2 .s
1539: 3 .s
1540: @end example
1541:
1542: @code{.s} displays the top-of-stack to the right, i.e., the numbers
1543: appear in @code{.s} output as they appeared in the input.
1544:
1545: You can print the top of stack element with @code{.}.
1546:
1547: @example
1548: 1 2 3 . . .
1549: @end example
1550:
1551: In general, words consume their stack arguments (@code{.s} is an
1552: exception).
1553:
1554: @assignment
1555: What does the stack contain after @code{5 6 7 .}?
1556: @endassignment
1557:
1558:
1559: @node Arithmetics Tutorial, Stack Manipulation Tutorial, Stack Tutorial, Tutorial
1560: @section Arithmetics
1.66 anton 1561: @cindex arithmetics tutorial
1.48 anton 1562:
1563: The words @code{+}, @code{-}, @code{*}, @code{/}, and @code{mod} always
1564: operate on the top two stack items:
1565:
1566: @example
1.67 anton 1567: 2 2 .s
1568: + .s
1569: .
1.48 anton 1570: 2 1 - .
1571: 7 3 mod .
1572: @end example
1573:
1574: The operands of @code{-}, @code{/}, and @code{mod} are in the same order
1575: as in the corresponding infix expression (this is generally the case in
1576: Forth).
1577:
1578: Parentheses are superfluous (and not available), because the order of
1579: the words unambiguously determines the order of evaluation and the
1580: operands:
1581:
1582: @example
1583: 3 4 + 5 * .
1584: 3 4 5 * + .
1585: @end example
1586:
1587: @assignment
1588: What are the infix expressions corresponding to the Forth code above?
1589: Write @code{6-7*8+9} in Forth notation@footnote{This notation is also
1590: known as Postfix or RPN (Reverse Polish Notation).}.
1591: @endassignment
1592:
1593: To change the sign, use @code{negate}:
1594:
1595: @example
1596: 2 negate .
1597: @end example
1598:
1599: @assignment
1600: Convert -(-3)*4-5 to Forth.
1601: @endassignment
1602:
1603: @code{/mod} performs both @code{/} and @code{mod}.
1604:
1605: @example
1606: 7 3 /mod . .
1607: @end example
1608:
1.66 anton 1609: Reference: @ref{Arithmetic}.
1610:
1611:
1.48 anton 1612: @node Stack Manipulation Tutorial, Using files for Forth code Tutorial, Arithmetics Tutorial, Tutorial
1613: @section Stack Manipulation
1.66 anton 1614: @cindex stack manipulation tutorial
1.48 anton 1615:
1616: Stack manipulation words rearrange the data on the stack.
1617:
1618: @example
1619: 1 .s drop .s
1620: 1 .s dup .s drop drop .s
1621: 1 2 .s over .s drop drop drop
1622: 1 2 .s swap .s drop drop
1623: 1 2 3 .s rot .s drop drop drop
1624: @end example
1625:
1626: These are the most important stack manipulation words. There are also
1627: variants that manipulate twice as many stack items:
1628:
1629: @example
1630: 1 2 3 4 .s 2swap .s 2drop 2drop
1631: @end example
1632:
1633: Two more stack manipulation words are:
1634:
1635: @example
1636: 1 2 .s nip .s drop
1637: 1 2 .s tuck .s 2drop drop
1638: @end example
1639:
1640: @assignment
1641: Replace @code{nip} and @code{tuck} with combinations of other stack
1642: manipulation words.
1643:
1644: @example
1645: Given: How do you get:
1646: 1 2 3 3 2 1
1647: 1 2 3 1 2 3 2
1648: 1 2 3 1 2 3 3
1649: 1 2 3 1 3 3
1650: 1 2 3 2 1 3
1651: 1 2 3 4 4 3 2 1
1652: 1 2 3 1 2 3 1 2 3
1653: 1 2 3 4 1 2 3 4 1 2
1654: 1 2 3
1655: 1 2 3 1 2 3 4
1656: 1 2 3 1 3
1657: @end example
1658: @endassignment
1659:
1660: @example
1661: 5 dup * .
1662: @end example
1663:
1664: @assignment
1665: Write 17^3 and 17^4 in Forth, without writing @code{17} more than once.
1666: Write a piece of Forth code that expects two numbers on the stack
1667: (@var{a} and @var{b}, with @var{b} on top) and computes
1668: @code{(a-b)(a+1)}.
1669: @endassignment
1670:
1.66 anton 1671: Reference: @ref{Stack Manipulation}.
1672:
1673:
1.48 anton 1674: @node Using files for Forth code Tutorial, Comments Tutorial, Stack Manipulation Tutorial, Tutorial
1675: @section Using files for Forth code
1.66 anton 1676: @cindex loading Forth code, tutorial
1677: @cindex files containing Forth code, tutorial
1.48 anton 1678:
1679: While working at the Forth command line is convenient for one-line
1680: examples and short one-off code, you probably want to store your source
1681: code in files for convenient editing and persistence. You can use your
1682: favourite editor (Gforth includes Emacs support, @pxref{Emacs and
1683: Gforth}) to create @var{file} and use
1684:
1685: @example
1686: s" @var{file}" included
1687: @end example
1688:
1689: to load it into your Forth system. The file name extension I use for
1690: Forth files is @samp{.fs}.
1691:
1692: You can easily start Gforth with some files loaded like this:
1693:
1694: @example
1695: gforth @var{file1} @var{file2}
1696: @end example
1697:
1698: If an error occurs during loading these files, Gforth terminates,
1699: whereas an error during @code{INCLUDED} within Gforth usually gives you
1700: a Gforth command line. Starting the Forth system every time gives you a
1701: clean start every time, without interference from the results of earlier
1702: tries.
1703:
1704: I often put all the tests in a file, then load the code and run the
1705: tests with
1706:
1707: @example
1708: gforth @var{code} @var{tests} -e bye
1709: @end example
1710:
1711: (often by performing this command with @kbd{C-x C-e} in Emacs). The
1712: @code{-e bye} ensures that Gforth terminates afterwards so that I can
1713: restart this command without ado.
1714:
1715: The advantage of this approach is that the tests can be repeated easily
1716: every time the program ist changed, making it easy to catch bugs
1717: introduced by the change.
1718:
1.66 anton 1719: Reference: @ref{Forth source files}.
1720:
1.48 anton 1721:
1722: @node Comments Tutorial, Colon Definitions Tutorial, Using files for Forth code Tutorial, Tutorial
1723: @section Comments
1.66 anton 1724: @cindex comments tutorial
1.48 anton 1725:
1726: @example
1727: \ That's a comment; it ends at the end of the line
1728: ( Another comment; it ends here: ) .s
1729: @end example
1730:
1731: @code{\} and @code{(} are ordinary Forth words and therefore have to be
1732: separated with white space from the following text.
1733:
1734: @example
1735: \This gives an "Undefined word" error
1736: @end example
1737:
1738: The first @code{)} ends a comment started with @code{(}, so you cannot
1739: nest @code{(}-comments; and you cannot comment out text containing a
1740: @code{)} with @code{( ... )}@footnote{therefore it's a good idea to
1741: avoid @code{)} in word names.}.
1742:
1743: I use @code{\}-comments for descriptive text and for commenting out code
1744: of one or more line; I use @code{(}-comments for describing the stack
1745: effect, the stack contents, or for commenting out sub-line pieces of
1746: code.
1747:
1748: The Emacs mode @file{gforth.el} (@pxref{Emacs and Gforth}) supports
1749: these uses by commenting out a region with @kbd{C-x \}, uncommenting a
1750: region with @kbd{C-u C-x \}, and filling a @code{\}-commented region
1751: with @kbd{M-q}.
1752:
1.66 anton 1753: Reference: @ref{Comments}.
1754:
1.48 anton 1755:
1756: @node Colon Definitions Tutorial, Decompilation Tutorial, Comments Tutorial, Tutorial
1757: @section Colon Definitions
1.66 anton 1758: @cindex colon definitions, tutorial
1759: @cindex definitions, tutorial
1760: @cindex procedures, tutorial
1761: @cindex functions, tutorial
1.48 anton 1762:
1763: are similar to procedures and functions in other programming languages.
1764:
1765: @example
1766: : squared ( n -- n^2 )
1767: dup * ;
1768: 5 squared .
1769: 7 squared .
1770: @end example
1771:
1772: @code{:} starts the colon definition; its name is @code{squared}. The
1773: following comment describes its stack effect. The words @code{dup *}
1774: are not executed, but compiled into the definition. @code{;} ends the
1775: colon definition.
1776:
1777: The newly-defined word can be used like any other word, including using
1778: it in other definitions:
1779:
1780: @example
1781: : cubed ( n -- n^3 )
1782: dup squared * ;
1783: -5 cubed .
1784: : fourth-power ( n -- n^4 )
1785: squared squared ;
1786: 3 fourth-power .
1787: @end example
1788:
1789: @assignment
1790: Write colon definitions for @code{nip}, @code{tuck}, @code{negate}, and
1791: @code{/mod} in terms of other Forth words, and check if they work (hint:
1792: test your tests on the originals first). Don't let the
1793: @samp{redefined}-Messages spook you, they are just warnings.
1794: @endassignment
1795:
1.66 anton 1796: Reference: @ref{Colon Definitions}.
1797:
1.48 anton 1798:
1799: @node Decompilation Tutorial, Stack-Effect Comments Tutorial, Colon Definitions Tutorial, Tutorial
1800: @section Decompilation
1.66 anton 1801: @cindex decompilation tutorial
1802: @cindex see tutorial
1.48 anton 1803:
1804: You can decompile colon definitions with @code{see}:
1805:
1806: @example
1807: see squared
1808: see cubed
1809: @end example
1810:
1811: In Gforth @code{see} shows you a reconstruction of the source code from
1812: the executable code. Informations that were present in the source, but
1813: not in the executable code, are lost (e.g., comments).
1814:
1.65 anton 1815: You can also decompile the predefined words:
1816:
1817: @example
1818: see .
1819: see +
1820: @end example
1821:
1822:
1.48 anton 1823: @node Stack-Effect Comments Tutorial, Types Tutorial, Decompilation Tutorial, Tutorial
1824: @section Stack-Effect Comments
1.66 anton 1825: @cindex stack-effect comments, tutorial
1826: @cindex --, tutorial
1.48 anton 1827: By convention the comment after the name of a definition describes the
1828: stack effect: The part in from of the @samp{--} describes the state of
1829: the stack before the execution of the definition, i.e., the parameters
1830: that are passed into the colon definition; the part behind the @samp{--}
1831: is the state of the stack after the execution of the definition, i.e.,
1832: the results of the definition. The stack comment only shows the top
1833: stack items that the definition accesses and/or changes.
1834:
1835: You should put a correct stack effect on every definition, even if it is
1836: just @code{( -- )}. You should also add some descriptive comment to
1837: more complicated words (I usually do this in the lines following
1838: @code{:}). If you don't do this, your code becomes unreadable (because
1839: you have to work through every definition before you can undertsand
1840: any).
1841:
1842: @assignment
1843: The stack effect of @code{swap} can be written like this: @code{x1 x2 --
1844: x2 x1}. Describe the stack effect of @code{-}, @code{drop}, @code{dup},
1845: @code{over}, @code{rot}, @code{nip}, and @code{tuck}. Hint: When you
1.65 anton 1846: are done, you can compare your stack effects to those in this manual
1.48 anton 1847: (@pxref{Word Index}).
1848: @endassignment
1849:
1850: Sometimes programmers put comments at various places in colon
1851: definitions that describe the contents of the stack at that place (stack
1852: comments); i.e., they are like the first part of a stack-effect
1853: comment. E.g.,
1854:
1855: @example
1856: : cubed ( n -- n^3 )
1857: dup squared ( n n^2 ) * ;
1858: @end example
1859:
1860: In this case the stack comment is pretty superfluous, because the word
1861: is simple enough. If you think it would be a good idea to add such a
1862: comment to increase readability, you should also consider factoring the
1863: word into several simpler words (@pxref{Factoring Tutorial,,
1.60 anton 1864: Factoring}), which typically eliminates the need for the stack comment;
1.48 anton 1865: however, if you decide not to refactor it, then having such a comment is
1866: better than not having it.
1867:
1868: The names of the stack items in stack-effect and stack comments in the
1869: standard, in this manual, and in many programs specify the type through
1870: a type prefix, similar to Fortran and Hungarian notation. The most
1871: frequent prefixes are:
1872:
1873: @table @code
1874: @item n
1875: signed integer
1876: @item u
1877: unsigned integer
1878: @item c
1879: character
1880: @item f
1881: Boolean flags, i.e. @code{false} or @code{true}.
1882: @item a-addr,a-
1883: Cell-aligned address
1884: @item c-addr,c-
1885: Char-aligned address (note that a Char may have two bytes in Windows NT)
1886: @item xt
1887: Execution token, same size as Cell
1888: @item w,x
1889: Cell, can contain an integer or an address. It usually takes 32, 64 or
1890: 16 bits (depending on your platform and Forth system). A cell is more
1891: commonly known as machine word, but the term @emph{word} already means
1892: something different in Forth.
1893: @item d
1894: signed double-cell integer
1895: @item ud
1896: unsigned double-cell integer
1897: @item r
1898: Float (on the FP stack)
1899: @end table
1900:
1901: You can find a more complete list in @ref{Notation}.
1902:
1903: @assignment
1904: Write stack-effect comments for all definitions you have written up to
1905: now.
1906: @endassignment
1907:
1908:
1909: @node Types Tutorial, Factoring Tutorial, Stack-Effect Comments Tutorial, Tutorial
1910: @section Types
1.66 anton 1911: @cindex types tutorial
1.48 anton 1912:
1913: In Forth the names of the operations are not overloaded; so similar
1914: operations on different types need different names; e.g., @code{+} adds
1915: integers, and you have to use @code{f+} to add floating-point numbers.
1916: The following prefixes are often used for related operations on
1917: different types:
1918:
1919: @table @code
1920: @item (none)
1921: signed integer
1922: @item u
1923: unsigned integer
1924: @item c
1925: character
1926: @item d
1927: signed double-cell integer
1928: @item ud, du
1929: unsigned double-cell integer
1930: @item 2
1931: two cells (not-necessarily double-cell numbers)
1932: @item m, um
1933: mixed single-cell and double-cell operations
1934: @item f
1935: floating-point (note that in stack comments @samp{f} represents flags,
1.66 anton 1936: and @samp{r} represents FP numbers).
1.48 anton 1937: @end table
1938:
1939: If there are no differences between the signed and the unsigned variant
1940: (e.g., for @code{+}), there is only the prefix-less variant.
1941:
1942: Forth does not perform type checking, neither at compile time, nor at
1943: run time. If you use the wrong oeration, the data are interpreted
1944: incorrectly:
1945:
1946: @example
1947: -1 u.
1948: @end example
1949:
1950: If you have only experience with type-checked languages until now, and
1951: have heard how important type-checking is, don't panic! In my
1952: experience (and that of other Forthers), type errors in Forth code are
1953: usually easy to find (once you get used to it), the increased vigilance
1954: of the programmer tends to catch some harder errors in addition to most
1955: type errors, and you never have to work around the type system, so in
1956: most situations the lack of type-checking seems to be a win (projects to
1957: add type checking to Forth have not caught on).
1958:
1959:
1960: @node Factoring Tutorial, Designing the stack effect Tutorial, Types Tutorial, Tutorial
1961: @section Factoring
1.66 anton 1962: @cindex factoring tutorial
1.48 anton 1963:
1964: If you try to write longer definitions, you will soon find it hard to
1965: keep track of the stack contents. Therefore, good Forth programmers
1966: tend to write only short definitions (e.g., three lines). The art of
1967: finding meaningful short definitions is known as factoring (as in
1968: factoring polynomials).
1969:
1970: Well-factored programs offer additional advantages: smaller, more
1971: general words, are easier to test and debug and can be reused more and
1972: better than larger, specialized words.
1973:
1974: So, if you run into difficulties with stack management, when writing
1975: code, try to define meaningful factors for the word, and define the word
1976: in terms of those. Even if a factor contains only two words, it is
1977: often helpful.
1978:
1.65 anton 1979: Good factoring is not easy, and it takes some practice to get the knack
1980: for it; but even experienced Forth programmers often don't find the
1981: right solution right away, but only when rewriting the program. So, if
1982: you don't come up with a good solution immediately, keep trying, don't
1983: despair.
1.48 anton 1984:
1985: @c example !!
1986:
1987:
1988: @node Designing the stack effect Tutorial, Local Variables Tutorial, Factoring Tutorial, Tutorial
1989: @section Designing the stack effect
1.66 anton 1990: @cindex Stack effect design, tutorial
1991: @cindex design of stack effects, tutorial
1.48 anton 1992:
1993: In other languages you can use an arbitrary order of parameters for a
1.65 anton 1994: function; and since there is only one result, you don't have to deal with
1.48 anton 1995: the order of results, either.
1996:
1997: In Forth (and other stack-based languages, e.g., Postscript) the
1998: parameter and result order of a definition is important and should be
1999: designed well. The general guideline is to design the stack effect such
2000: that the word is simple to use in most cases, even if that complicates
2001: the implementation of the word. Some concrete rules are:
2002:
2003: @itemize @bullet
2004:
2005: @item
2006: Words consume all of their parameters (e.g., @code{.}).
2007:
2008: @item
2009: If there is a convention on the order of parameters (e.g., from
2010: mathematics or another programming language), stick with it (e.g.,
2011: @code{-}).
2012:
2013: @item
2014: If one parameter usually requires only a short computation (e.g., it is
2015: a constant), pass it on the top of the stack. Conversely, parameters
2016: that usually require a long sequence of code to compute should be passed
2017: as the bottom (i.e., first) parameter. This makes the code easier to
2018: read, because reader does not need to keep track of the bottom item
2019: through a long sequence of code (or, alternatively, through stack
1.49 anton 2020: manipulations). E.g., @code{!} (store, @pxref{Memory}) expects the
1.48 anton 2021: address on top of the stack because it is usually simpler to compute
2022: than the stored value (often the address is just a variable).
2023:
2024: @item
2025: Similarly, results that are usually consumed quickly should be returned
2026: on the top of stack, whereas a result that is often used in long
2027: computations should be passed as bottom result. E.g., the file words
2028: like @code{open-file} return the error code on the top of stack, because
2029: it is usually consumed quickly by @code{throw}; moreover, the error code
2030: has to be checked before doing anything with the other results.
2031:
2032: @end itemize
2033:
2034: These rules are just general guidelines, don't lose sight of the overall
2035: goal to make the words easy to use. E.g., if the convention rule
2036: conflicts with the computation-length rule, you might decide in favour
2037: of the convention if the word will be used rarely, and in favour of the
2038: computation-length rule if the word will be used frequently (because
2039: with frequent use the cost of breaking the computation-length rule would
2040: be quite high, and frequent use makes it easier to remember an
2041: unconventional order).
2042:
2043: @c example !! structure package
2044:
1.65 anton 2045:
1.48 anton 2046: @node Local Variables Tutorial, Conditional execution Tutorial, Designing the stack effect Tutorial, Tutorial
2047: @section Local Variables
1.66 anton 2048: @cindex local variables, tutorial
1.48 anton 2049:
2050: You can define local variables (@emph{locals}) in a colon definition:
2051:
2052: @example
2053: : swap @{ a b -- b a @}
2054: b a ;
2055: 1 2 swap .s 2drop
2056: @end example
2057:
2058: (If your Forth system does not support this syntax, include
2059: @file{compat/anslocals.fs} first).
2060:
2061: In this example @code{@{ a b -- b a @}} is the locals definition; it
2062: takes two cells from the stack, puts the top of stack in @code{b} and
2063: the next stack element in @code{a}. @code{--} starts a comment ending
2064: with @code{@}}. After the locals definition, using the name of the
2065: local will push its value on the stack. You can leave the comment
2066: part (@code{-- b a}) away:
2067:
2068: @example
2069: : swap ( x1 x2 -- x2 x1 )
2070: @{ a b @} b a ;
2071: @end example
2072:
2073: In Gforth you can have several locals definitions, anywhere in a colon
2074: definition; in contrast, in a standard program you can have only one
2075: locals definition per colon definition, and that locals definition must
2076: be outside any controll structure.
2077:
2078: With locals you can write slightly longer definitions without running
2079: into stack trouble. However, I recommend trying to write colon
2080: definitions without locals for exercise purposes to help you gain the
2081: essential factoring skills.
2082:
2083: @assignment
2084: Rewrite your definitions until now with locals
2085: @endassignment
2086:
1.66 anton 2087: Reference: @ref{Locals}.
2088:
1.48 anton 2089:
2090: @node Conditional execution Tutorial, Flags and Comparisons Tutorial, Local Variables Tutorial, Tutorial
2091: @section Conditional execution
1.66 anton 2092: @cindex conditionals, tutorial
2093: @cindex if, tutorial
1.48 anton 2094:
2095: In Forth you can use control structures only inside colon definitions.
2096: An @code{if}-structure looks like this:
2097:
2098: @example
2099: : abs ( n1 -- +n2 )
2100: dup 0 < if
2101: negate
2102: endif ;
2103: 5 abs .
2104: -5 abs .
2105: @end example
2106:
2107: @code{if} takes a flag from the stack. If the flag is non-zero (true),
2108: the following code is performed, otherwise execution continues after the
1.51 pazsan 2109: @code{endif} (or @code{else}). @code{<} compares the top two stack
1.48 anton 2110: elements and prioduces a flag:
2111:
2112: @example
2113: 1 2 < .
2114: 2 1 < .
2115: 1 1 < .
2116: @end example
2117:
2118: Actually the standard name for @code{endif} is @code{then}. This
2119: tutorial presents the examples using @code{endif}, because this is often
2120: less confusing for people familiar with other programming languages
2121: where @code{then} has a different meaning. If your system does not have
2122: @code{endif}, define it with
2123:
2124: @example
2125: : endif postpone then ; immediate
2126: @end example
2127:
2128: You can optionally use an @code{else}-part:
2129:
2130: @example
2131: : min ( n1 n2 -- n )
2132: 2dup < if
2133: drop
2134: else
2135: nip
2136: endif ;
2137: 2 3 min .
2138: 3 2 min .
2139: @end example
2140:
2141: @assignment
2142: Write @code{min} without @code{else}-part (hint: what's the definition
2143: of @code{nip}?).
2144: @endassignment
2145:
1.66 anton 2146: Reference: @ref{Selection}.
2147:
1.48 anton 2148:
2149: @node Flags and Comparisons Tutorial, General Loops Tutorial, Conditional execution Tutorial, Tutorial
2150: @section Flags and Comparisons
1.66 anton 2151: @cindex flags tutorial
2152: @cindex comparison tutorial
1.48 anton 2153:
2154: In a false-flag all bits are clear (0 when interpreted as integer). In
2155: a canonical true-flag all bits are set (-1 as a twos-complement signed
2156: integer); in many contexts (e.g., @code{if}) any non-zero value is
2157: treated as true flag.
2158:
2159: @example
2160: false .
2161: true .
2162: true hex u. decimal
2163: @end example
2164:
2165: Comparison words produce canonical flags:
2166:
2167: @example
2168: 1 1 = .
2169: 1 0= .
2170: 0 1 < .
2171: 0 0 < .
2172: -1 1 u< . \ type error, u< interprets -1 as large unsigned number
2173: -1 1 < .
2174: @end example
2175:
1.66 anton 2176: Gforth supports all combinations of the prefixes @code{0 u d d0 du f f0}
2177: (or none) and the comparisons @code{= <> < > <= >=}. Only a part of
2178: these combinations are standard (for details see the standard,
2179: @ref{Numeric comparison}, @ref{Floating Point} or @ref{Word Index}).
1.48 anton 2180:
2181: You can use @code{and or xor invert} can be used as operations on
2182: canonical flags. Actually they are bitwise operations:
2183:
2184: @example
2185: 1 2 and .
2186: 1 2 or .
2187: 1 3 xor .
2188: 1 invert .
2189: @end example
2190:
2191: You can convert a zero/non-zero flag into a canonical flag with
2192: @code{0<>} (and complement it on the way with @code{0=}).
2193:
2194: @example
2195: 1 0= .
2196: 1 0<> .
2197: @end example
2198:
1.65 anton 2199: You can use the all-bits-set feature of canonical flags and the bitwise
1.48 anton 2200: operation of the Boolean operations to avoid @code{if}s:
2201:
2202: @example
2203: : foo ( n1 -- n2 )
2204: 0= if
2205: 14
2206: else
2207: 0
2208: endif ;
2209: 0 foo .
2210: 1 foo .
2211:
2212: : foo ( n1 -- n2 )
2213: 0= 14 and ;
2214: 0 foo .
2215: 1 foo .
2216: @end example
2217:
2218: @assignment
2219: Write @code{min} without @code{if}.
2220: @endassignment
2221:
1.66 anton 2222: For reference, see @ref{Boolean Flags}, @ref{Numeric comparison}, and
2223: @ref{Bitwise operations}.
2224:
1.48 anton 2225:
2226: @node General Loops Tutorial, Counted loops Tutorial, Flags and Comparisons Tutorial, Tutorial
2227: @section General Loops
1.66 anton 2228: @cindex loops, indefinite, tutorial
1.48 anton 2229:
2230: The endless loop is the most simple one:
2231:
2232: @example
2233: : endless ( -- )
2234: 0 begin
2235: dup . 1+
2236: again ;
2237: endless
2238: @end example
2239:
2240: Terminate this loop by pressing @kbd{Ctrl-C} (in Gforth). @code{begin}
2241: does nothing at run-time, @code{again} jumps back to @code{begin}.
2242:
2243: A loop with one exit at any place looks like this:
2244:
2245: @example
2246: : log2 ( +n1 -- n2 )
2247: \ logarithmus dualis of n1>0, rounded down to the next integer
2248: assert( dup 0> )
2249: 2/ 0 begin
2250: over 0> while
2251: 1+ swap 2/ swap
2252: repeat
2253: nip ;
2254: 7 log2 .
2255: 8 log2 .
2256: @end example
2257:
2258: At run-time @code{while} consumes a flag; if it is 0, execution
1.51 pazsan 2259: continues behind the @code{repeat}; if the flag is non-zero, execution
1.48 anton 2260: continues behind the @code{while}. @code{Repeat} jumps back to
2261: @code{begin}, just like @code{again}.
2262:
2263: In Forth there are many combinations/abbreviations, like @code{1+}.
2264: However, @code{2/} is not one of them; it shifts it's argument right by
2265: one bit (arithmetic shift right):
2266:
2267: @example
2268: -5 2 / .
2269: -5 2/ .
2270: @end example
2271:
2272: @code{assert(} is no standard word, but you can get it on systems other
2273: then Gforth by including @file{compat/assert.fs}. You can see what it
2274: does by trying
2275:
2276: @example
2277: 0 log2 .
2278: @end example
2279:
2280: Here's a loop with an exit at the end:
2281:
2282: @example
2283: : log2 ( +n1 -- n2 )
2284: \ logarithmus dualis of n1>0, rounded down to the next integer
2285: assert( dup 0 > )
2286: -1 begin
2287: 1+ swap 2/ swap
2288: over 0 <=
2289: until
2290: nip ;
2291: @end example
2292:
2293: @code{Until} consumes a flag; if it is non-zero, execution continues at
2294: the @code{begin}, otherwise after the @code{until}.
2295:
2296: @assignment
2297: Write a definition for computing the greatest common divisor.
2298: @endassignment
2299:
1.66 anton 2300: Reference: @ref{Simple Loops}.
2301:
1.48 anton 2302:
2303: @node Counted loops Tutorial, Recursion Tutorial, General Loops Tutorial, Tutorial
2304: @section Counted loops
1.66 anton 2305: @cindex loops, counted, tutorial
1.48 anton 2306:
2307: @example
2308: : ^ ( n1 u -- n )
2309: \ n = the uth power of u1
2310: 1 swap 0 u+do
2311: over *
2312: loop
2313: nip ;
2314: 3 2 ^ .
2315: 4 3 ^ .
2316: @end example
2317:
2318: @code{U+do} (from @file{compat/loops.fs}, if your Forth system doesn't
2319: have it) takes two numbers of the stack @code{( u3 u4 -- )}, and then
2320: performs the code between @code{u+do} and @code{loop} for @code{u3-u4}
2321: times (or not at all, if @code{u3-u4<0}).
2322:
2323: You can see the stack effect design rules at work in the stack effect of
2324: the loop start words: Since the start value of the loop is more
2325: frequently constant than the end value, the start value is passed on
2326: the top-of-stack.
2327:
2328: You can access the counter of a counted loop with @code{i}:
2329:
2330: @example
2331: : fac ( u -- u! )
2332: 1 swap 1+ 1 u+do
2333: i *
2334: loop ;
2335: 5 fac .
2336: 7 fac .
2337: @end example
2338:
2339: There is also @code{+do}, which expects signed numbers (important for
2340: deciding whether to enter the loop).
2341:
2342: @assignment
2343: Write a definition for computing the nth Fibonacci number.
2344: @endassignment
2345:
1.65 anton 2346: You can also use increments other than 1:
2347:
2348: @example
2349: : up2 ( n1 n2 -- )
2350: +do
2351: i .
2352: 2 +loop ;
2353: 10 0 up2
2354:
2355: : down2 ( n1 n2 -- )
2356: -do
2357: i .
2358: 2 -loop ;
2359: 0 10 down2
2360: @end example
1.48 anton 2361:
1.66 anton 2362: Reference: @ref{Counted Loops}.
2363:
1.48 anton 2364:
2365: @node Recursion Tutorial, Leaving definitions or loops Tutorial, Counted loops Tutorial, Tutorial
2366: @section Recursion
1.66 anton 2367: @cindex recursion tutorial
1.48 anton 2368:
2369: Usually the name of a definition is not visible in the definition; but
2370: earlier definitions are usually visible:
2371:
2372: @example
2373: 1 0 / . \ "Floating-point unidentified fault" in Gforth on most platforms
2374: : / ( n1 n2 -- n )
2375: dup 0= if
2376: -10 throw \ report division by zero
2377: endif
2378: / \ old version
2379: ;
2380: 1 0 /
2381: @end example
2382:
2383: For recursive definitions you can use @code{recursive} (non-standard) or
2384: @code{recurse}:
2385:
2386: @example
2387: : fac1 ( n -- n! ) recursive
2388: dup 0> if
2389: dup 1- fac1 *
2390: else
2391: drop 1
2392: endif ;
2393: 7 fac1 .
2394:
2395: : fac2 ( n -- n! )
2396: dup 0> if
2397: dup 1- recurse *
2398: else
2399: drop 1
2400: endif ;
2401: 8 fac2 .
2402: @end example
2403:
2404: @assignment
2405: Write a recursive definition for computing the nth Fibonacci number.
2406: @endassignment
2407:
1.66 anton 2408: Reference (including indirect recursion): @xref{Calls and returns}.
2409:
1.48 anton 2410:
2411: @node Leaving definitions or loops Tutorial, Return Stack Tutorial, Recursion Tutorial, Tutorial
2412: @section Leaving definitions or loops
1.66 anton 2413: @cindex leaving definitions, tutorial
2414: @cindex leaving loops, tutorial
1.48 anton 2415:
2416: @code{EXIT} exits the current definition right away. For every counted
2417: loop that is left in this way, an @code{UNLOOP} has to be performed
2418: before the @code{EXIT}:
2419:
2420: @c !! real examples
2421: @example
2422: : ...
2423: ... u+do
2424: ... if
2425: ... unloop exit
2426: endif
2427: ...
2428: loop
2429: ... ;
2430: @end example
2431:
2432: @code{LEAVE} leaves the innermost counted loop right away:
2433:
2434: @example
2435: : ...
2436: ... u+do
2437: ... if
2438: ... leave
2439: endif
2440: ...
2441: loop
2442: ... ;
2443: @end example
2444:
1.65 anton 2445: @c !! example
1.48 anton 2446:
1.66 anton 2447: Reference: @ref{Calls and returns}, @ref{Counted Loops}.
2448:
2449:
1.48 anton 2450: @node Return Stack Tutorial, Memory Tutorial, Leaving definitions or loops Tutorial, Tutorial
2451: @section Return Stack
1.66 anton 2452: @cindex return stack tutorial
1.48 anton 2453:
2454: In addition to the data stack Forth also has a second stack, the return
2455: stack; most Forth systems store the return addresses of procedure calls
2456: there (thus its name). Programmers can also use this stack:
2457:
2458: @example
2459: : foo ( n1 n2 -- )
2460: .s
2461: >r .s
1.50 anton 2462: r@@ .
1.48 anton 2463: >r .s
1.50 anton 2464: r@@ .
1.48 anton 2465: r> .
1.50 anton 2466: r@@ .
1.48 anton 2467: r> . ;
2468: 1 2 foo
2469: @end example
2470:
2471: @code{>r} takes an element from the data stack and pushes it onto the
2472: return stack; conversely, @code{r>} moves an elementm from the return to
2473: the data stack; @code{r@@} pushes a copy of the top of the return stack
2474: on the return stack.
2475:
2476: Forth programmers usually use the return stack for storing data
2477: temporarily, if using the data stack alone would be too complex, and
2478: factoring and locals are not an option:
2479:
2480: @example
2481: : 2swap ( x1 x2 x3 x4 -- x3 x4 x1 x2 )
2482: rot >r rot r> ;
2483: @end example
2484:
2485: The return address of the definition and the loop control parameters of
2486: counted loops usually reside on the return stack, so you have to take
2487: all items, that you have pushed on the return stack in a colon
2488: definition or counted loop, from the return stack before the definition
2489: or loop ends. You cannot access items that you pushed on the return
2490: stack outside some definition or loop within the definition of loop.
2491:
2492: If you miscount the return stack items, this usually ends in a crash:
2493:
2494: @example
2495: : crash ( n -- )
2496: >r ;
2497: 5 crash
2498: @end example
2499:
2500: You cannot mix using locals and using the return stack (according to the
2501: standard; Gforth has no problem). However, they solve the same
2502: problems, so this shouldn't be an issue.
2503:
2504: @assignment
2505: Can you rewrite any of the definitions you wrote until now in a better
2506: way using the return stack?
2507: @endassignment
2508:
1.66 anton 2509: Reference: @ref{Return stack}.
2510:
1.48 anton 2511:
2512: @node Memory Tutorial, Characters and Strings Tutorial, Return Stack Tutorial, Tutorial
2513: @section Memory
1.66 anton 2514: @cindex memory access/allocation tutorial
1.48 anton 2515:
2516: You can create a global variable @code{v} with
2517:
2518: @example
2519: variable v ( -- addr )
2520: @end example
2521:
2522: @code{v} pushes the address of a cell in memory on the stack. This cell
2523: was reserved by @code{variable}. You can use @code{!} (store) to store
2524: values into this cell and @code{@@} (fetch) to load the value from the
2525: stack into memory:
2526:
2527: @example
2528: v .
2529: 5 v ! .s
1.50 anton 2530: v @@ .
1.48 anton 2531: @end example
2532:
1.65 anton 2533: You can see a raw dump of memory with @code{dump}:
2534:
2535: @example
2536: v 1 cells .s dump
2537: @end example
2538:
2539: @code{Cells ( n1 -- n2 )} gives you the number of bytes (or, more
2540: generally, address units (aus)) that @code{n1 cells} occupy. You can
2541: also reserve more memory:
1.48 anton 2542:
2543: @example
2544: create v2 20 cells allot
1.65 anton 2545: v2 20 cells dump
1.48 anton 2546: @end example
2547:
1.65 anton 2548: creates a word @code{v2} and reserves 20 uninitialized cells; the
2549: address pushed by @code{v2} points to the start of these 20 cells. You
2550: can use address arithmetic to access these cells:
1.48 anton 2551:
2552: @example
2553: 3 v2 5 cells + !
1.65 anton 2554: v2 20 cells dump
1.48 anton 2555: @end example
2556:
2557: You can reserve and initialize memory with @code{,}:
2558:
2559: @example
2560: create v3
2561: 5 , 4 , 3 , 2 , 1 ,
1.50 anton 2562: v3 @@ .
2563: v3 cell+ @@ .
2564: v3 2 cells + @@ .
1.65 anton 2565: v3 5 cells dump
1.48 anton 2566: @end example
2567:
2568: @assignment
2569: Write a definition @code{vsum ( addr u -- n )} that computes the sum of
2570: @code{u} cells, with the first of these cells at @code{addr}, the next
2571: one at @code{addr cell+} etc.
2572: @endassignment
2573:
2574: You can also reserve memory without creating a new word:
2575:
2576: @example
1.60 anton 2577: here 10 cells allot .
2578: here .
1.48 anton 2579: @end example
2580:
2581: @code{Here} pushes the start address of the memory area. You should
2582: store it somewhere, or you will have a hard time finding the memory area
2583: again.
2584:
2585: @code{Allot} manages dictionary memory. The dictionary memory contains
2586: the system's data structures for words etc. on Gforth and most other
2587: Forth systems. It is managed like a stack: You can free the memory that
2588: you have just @code{allot}ed with
2589:
2590: @example
2591: -10 cells allot
1.60 anton 2592: here .
1.48 anton 2593: @end example
2594:
2595: Note that you cannot do this if you have created a new word in the
2596: meantime (because then your @code{allot}ed memory is no longer on the
2597: top of the dictionary ``stack'').
2598:
2599: Alternatively, you can use @code{allocate} and @code{free} which allow
2600: freeing memory in any order:
2601:
2602: @example
2603: 10 cells allocate throw .s
2604: 20 cells allocate throw .s
2605: swap
2606: free throw
2607: free throw
2608: @end example
2609:
2610: The @code{throw}s deal with errors (e.g., out of memory).
2611:
1.65 anton 2612: And there is also a
2613: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
2614: garbage collector}, which eliminates the need to @code{free} memory
2615: explicitly.
1.48 anton 2616:
1.66 anton 2617: Reference: @ref{Memory}.
2618:
1.48 anton 2619:
2620: @node Characters and Strings Tutorial, Alignment Tutorial, Memory Tutorial, Tutorial
2621: @section Characters and Strings
1.66 anton 2622: @cindex strings tutorial
2623: @cindex characters tutorial
1.48 anton 2624:
2625: On the stack characters take up a cell, like numbers. In memory they
2626: have their own size (one 8-bit byte on most systems), and therefore
2627: require their own words for memory access:
2628:
2629: @example
2630: create v4
2631: 104 c, 97 c, 108 c, 108 c, 111 c,
1.50 anton 2632: v4 4 chars + c@@ .
1.65 anton 2633: v4 5 chars dump
1.48 anton 2634: @end example
2635:
2636: The preferred representation of strings on the stack is @code{addr
2637: u-count}, where @code{addr} is the address of the first character and
2638: @code{u-count} is the number of characters in the string.
2639:
2640: @example
2641: v4 5 type
2642: @end example
2643:
2644: You get a string constant with
2645:
2646: @example
2647: s" hello, world" .s
2648: type
2649: @end example
2650:
2651: Make sure you have a space between @code{s"} and the string; @code{s"}
2652: is a normal Forth word and must be delimited with white space (try what
2653: happens when you remove the space).
2654:
2655: However, this interpretive use of @code{s"} is quite restricted: the
2656: string exists only until the next call of @code{s"} (some Forth systems
2657: keep more than one of these strings, but usually they still have a
1.62 crook 2658: limited lifetime).
1.48 anton 2659:
2660: @example
2661: s" hello," s" world" .s
2662: type
2663: type
2664: @end example
2665:
1.62 crook 2666: You can also use @code{s"} in a definition, and the resulting
2667: strings then live forever (well, for as long as the definition):
1.48 anton 2668:
2669: @example
2670: : foo s" hello," s" world" ;
2671: foo .s
2672: type
2673: type
2674: @end example
2675:
2676: @assignment
2677: @code{Emit ( c -- )} types @code{c} as character (not a number).
2678: Implement @code{type ( addr u -- )}.
2679: @endassignment
2680:
1.66 anton 2681: Reference: @ref{Memory Blocks}.
2682:
2683:
1.48 anton 2684: @node Alignment Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Characters and Strings Tutorial, Tutorial
2685: @section Alignment
1.66 anton 2686: @cindex alignment tutorial
2687: @cindex memory alignment tutorial
1.48 anton 2688:
2689: On many processors cells have to be aligned in memory, if you want to
2690: access them with @code{@@} and @code{!} (and even if the processor does
1.62 crook 2691: not require alignment, access to aligned cells is faster).
1.48 anton 2692:
2693: @code{Create} aligns @code{here} (i.e., the place where the next
2694: allocation will occur, and that the @code{create}d word points to).
2695: Likewise, the memory produced by @code{allocate} starts at an aligned
2696: address. Adding a number of @code{cells} to an aligned address produces
2697: another aligned address.
2698:
2699: However, address arithmetic involving @code{char+} and @code{chars} can
2700: create an address that is not cell-aligned. @code{Aligned ( addr --
2701: a-addr )} produces the next aligned address:
2702:
2703: @example
1.50 anton 2704: v3 char+ aligned .s @@ .
2705: v3 char+ .s @@ .
1.48 anton 2706: @end example
2707:
2708: Similarly, @code{align} advances @code{here} to the next aligned
2709: address:
2710:
2711: @example
2712: create v5 97 c,
2713: here .
2714: align here .
2715: 1000 ,
2716: @end example
2717:
2718: Note that you should use aligned addresses even if your processor does
2719: not require them, if you want your program to be portable.
2720:
1.66 anton 2721: Reference: @ref{Address arithmetic}.
2722:
1.48 anton 2723:
2724: @node Interpretation and Compilation Semantics and Immediacy Tutorial, Execution Tokens Tutorial, Alignment Tutorial, Tutorial
2725: @section Interpretation and Compilation Semantics and Immediacy
1.66 anton 2726: @cindex semantics tutorial
2727: @cindex interpretation semantics tutorial
2728: @cindex compilation semantics tutorial
2729: @cindex immediate, tutorial
1.48 anton 2730:
2731: When a word is compiled, it behaves differently from being interpreted.
2732: E.g., consider @code{+}:
2733:
2734: @example
2735: 1 2 + .
2736: : foo + ;
2737: @end example
2738:
2739: These two behaviours are known as compilation and interpretation
2740: semantics. For normal words (e.g., @code{+}), the compilation semantics
2741: is to append the interpretation semantics to the currently defined word
2742: (@code{foo} in the example above). I.e., when @code{foo} is executed
2743: later, the interpretation semantics of @code{+} (i.e., adding two
2744: numbers) will be performed.
2745:
2746: However, there are words with non-default compilation semantics, e.g.,
2747: the control-flow words like @code{if}. You can use @code{immediate} to
2748: change the compilation semantics of the last defined word to be equal to
2749: the interpretation semantics:
2750:
2751: @example
2752: : [FOO] ( -- )
2753: 5 . ; immediate
2754:
2755: [FOO]
2756: : bar ( -- )
2757: [FOO] ;
2758: bar
2759: see bar
2760: @end example
2761:
2762: Two conventions to mark words with non-default compilation semnatics are
2763: names with brackets (more frequently used) and to write them all in
2764: upper case (less frequently used).
2765:
2766: In Gforth (and many other systems) you can also remove the
2767: interpretation semantics with @code{compile-only} (the compilation
2768: semantics is derived from the original interpretation semantics):
2769:
2770: @example
2771: : flip ( -- )
2772: 6 . ; compile-only \ but not immediate
2773: flip
2774:
2775: : flop ( -- )
2776: flip ;
2777: flop
2778: @end example
2779:
2780: In this example the interpretation semantics of @code{flop} is equal to
2781: the original interpretation semantics of @code{flip}.
2782:
2783: The text interpreter has two states: in interpret state, it performs the
2784: interpretation semantics of words it encounters; in compile state, it
2785: performs the compilation semantics of these words.
2786:
2787: Among other things, @code{:} switches into compile state, and @code{;}
2788: switches back to interpret state. They contain the factors @code{]}
2789: (switch to compile state) and @code{[} (switch to interpret state), that
2790: do nothing but switch the state.
2791:
2792: @example
2793: : xxx ( -- )
2794: [ 5 . ]
2795: ;
2796:
2797: xxx
2798: see xxx
2799: @end example
2800:
2801: These brackets are also the source of the naming convention mentioned
2802: above.
2803:
1.66 anton 2804: Reference: @ref{Interpretation and Compilation Semantics}.
2805:
1.48 anton 2806:
2807: @node Execution Tokens Tutorial, Exceptions Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Tutorial
2808: @section Execution Tokens
1.66 anton 2809: @cindex execution tokens tutorial
2810: @cindex XT tutorial
1.48 anton 2811:
2812: @code{' word} gives you the execution token (XT) of a word. The XT is a
2813: cell representing the interpretation semantics of a word. You can
2814: execute this semantics with @code{execute}:
2815:
2816: @example
2817: ' + .s
2818: 1 2 rot execute .
2819: @end example
2820:
2821: The XT is similar to a function pointer in C. However, parameter
2822: passing through the stack makes it a little more flexible:
2823:
2824: @example
2825: : map-array ( ... addr u xt -- ... )
1.50 anton 2826: \ executes xt ( ... x -- ... ) for every element of the array starting
2827: \ at addr and containing u elements
1.48 anton 2828: @{ xt @}
2829: cells over + swap ?do
1.50 anton 2830: i @@ xt execute
1.48 anton 2831: 1 cells +loop ;
2832:
2833: create a 3 , 4 , 2 , -1 , 4 ,
2834: a 5 ' . map-array .s
2835: 0 a 5 ' + map-array .
2836: s" max-n" environment? drop .s
2837: a 5 ' min map-array .
2838: @end example
2839:
2840: You can use map-array with the XTs of words that consume one element
2841: more than they produce. In theory you can also use it with other XTs,
2842: but the stack effect then depends on the size of the array, which is
2843: hard to understand.
2844:
1.51 pazsan 2845: Since XTs are cell-sized, you can store them in memory and manipulate
2846: them on the stack like other cells. You can also compile the XT into a
1.48 anton 2847: word with @code{compile,}:
2848:
2849: @example
2850: : foo1 ( n1 n2 -- n )
2851: [ ' + compile, ] ;
2852: see foo
2853: @end example
2854:
2855: This is non-standard, because @code{compile,} has no compilation
2856: semantics in the standard, but it works in good Forth systems. For the
2857: broken ones, use
2858:
2859: @example
2860: : [compile,] compile, ; immediate
2861:
2862: : foo1 ( n1 n2 -- n )
2863: [ ' + ] [compile,] ;
2864: see foo
2865: @end example
2866:
2867: @code{'} is a word with default compilation semantics; it parses the
2868: next word when its interpretation semantics are executed, not during
2869: compilation:
2870:
2871: @example
2872: : foo ( -- xt )
2873: ' ;
2874: see foo
2875: : bar ( ... "word" -- ... )
2876: ' execute ;
2877: see bar
1.60 anton 2878: 1 2 bar + .
1.48 anton 2879: @end example
2880:
2881: You often want to parse a word during compilation and compile its XT so
2882: it will be pushed on the stack at run-time. @code{[']} does this:
2883:
2884: @example
2885: : xt-+ ( -- xt )
2886: ['] + ;
2887: see xt-+
2888: 1 2 xt-+ execute .
2889: @end example
2890:
2891: Many programmers tend to see @code{'} and the word it parses as one
2892: unit, and expect it to behave like @code{[']} when compiled, and are
2893: confused by the actual behaviour. If you are, just remember that the
2894: Forth system just takes @code{'} as one unit and has no idea that it is
2895: a parsing word (attempts to convenience programmers in this issue have
2896: usually resulted in even worse pitfalls, see
1.66 anton 2897: @uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,
2898: @code{State}-smartness---Why it is evil and How to Exorcise it}).
1.48 anton 2899:
2900: Note that the state of the interpreter does not come into play when
1.51 pazsan 2901: creating and executing XTs. I.e., even when you execute @code{'} in
1.48 anton 2902: compile state, it still gives you the interpretation semantics. And
2903: whatever that state is, @code{execute} performs the semantics
1.66 anton 2904: represented by the XT (i.e., for XTs produced with @code{'} the
2905: interpretation semantics).
2906:
2907: Reference: @ref{Tokens for Words}.
1.48 anton 2908:
2909:
2910: @node Exceptions Tutorial, Defining Words Tutorial, Execution Tokens Tutorial, Tutorial
2911: @section Exceptions
1.66 anton 2912: @cindex exceptions tutorial
1.48 anton 2913:
2914: @code{throw ( n -- )} causes an exception unless n is zero.
2915:
2916: @example
2917: 100 throw .s
2918: 0 throw .s
2919: @end example
2920:
2921: @code{catch ( ... xt -- ... n )} behaves similar to @code{execute}, but
2922: it catches exceptions and pushes the number of the exception on the
2923: stack (or 0, if the xt executed without exception). If there was an
2924: exception, the stacks have the same depth as when entering @code{catch}:
2925:
2926: @example
2927: .s
2928: 3 0 ' / catch .s
2929: 3 2 ' / catch .s
2930: @end example
2931:
2932: @assignment
2933: Try the same with @code{execute} instead of @code{catch}.
2934: @endassignment
2935:
2936: @code{Throw} always jumps to the dynamically next enclosing
2937: @code{catch}, even if it has to leave several call levels to achieve
2938: this:
2939:
2940: @example
2941: : foo 100 throw ;
2942: : foo1 foo ." after foo" ;
1.51 pazsan 2943: : bar ['] foo1 catch ;
1.60 anton 2944: bar .
1.48 anton 2945: @end example
2946:
2947: It is often important to restore a value upon leaving a definition, even
2948: if the definition is left through an exception. You can ensure this
2949: like this:
2950:
2951: @example
2952: : ...
2953: save-x
1.51 pazsan 2954: ['] word-changing-x catch ( ... n )
1.48 anton 2955: restore-x
2956: ( ... n ) throw ;
2957: @end example
2958:
1.55 anton 2959: Gforth provides an alternative syntax in addition to @code{catch}:
1.48 anton 2960: @code{try ... recover ... endtry}. If the code between @code{try} and
2961: @code{recover} has an exception, the stack depths are restored, the
2962: exception number is pushed on the stack, and the code between
2963: @code{recover} and @code{endtry} is performed. E.g., the definition for
2964: @code{catch} is
2965:
2966: @example
2967: : catch ( x1 .. xn xt -- y1 .. ym 0 / z1 .. zn error ) \ exception
2968: try
2969: execute 0
2970: recover
2971: nip
2972: endtry ;
2973: @end example
2974:
2975: The equivalent to the restoration code above is
2976:
2977: @example
2978: : ...
2979: save-x
2980: try
2981: word-changing-x
2982: end-try
2983: restore-x
2984: throw ;
2985: @end example
2986:
2987: As you can see, the @code{recover} part is optional.
2988:
1.66 anton 2989: Reference: @ref{Exception Handling}.
2990:
1.48 anton 2991:
2992: @node Defining Words Tutorial, Arrays and Records Tutorial, Exceptions Tutorial, Tutorial
2993: @section Defining Words
1.66 anton 2994: @cindex defining words tutorial
2995: @cindex does> tutorial
2996: @cindex create...does> tutorial
2997:
2998: @c before semantics?
1.48 anton 2999:
3000: @code{:}, @code{create}, and @code{variable} are definition words: They
3001: define other words. @code{Constant} is another definition word:
3002:
3003: @example
3004: 5 constant foo
3005: foo .
3006: @end example
3007:
3008: You can also use the prefixes @code{2} (double-cell) and @code{f}
3009: (floating point) with @code{variable} and @code{constant}.
3010:
3011: You can also define your own defining words. E.g.:
3012:
3013: @example
3014: : variable ( "name" -- )
3015: create 0 , ;
3016: @end example
3017:
3018: You can also define defining words that create words that do something
3019: other than just producing their address:
3020:
3021: @example
3022: : constant ( n "name" -- )
3023: create ,
3024: does> ( -- n )
1.50 anton 3025: ( addr ) @@ ;
1.48 anton 3026:
3027: 5 constant foo
3028: foo .
3029: @end example
3030:
3031: The definition of @code{constant} above ends at the @code{does>}; i.e.,
3032: @code{does>} replaces @code{;}, but it also does something else: It
3033: changes the last defined word such that it pushes the address of the
3034: body of the word and then performs the code after the @code{does>}
3035: whenever it is called.
3036:
3037: In the example above, @code{constant} uses @code{,} to store 5 into the
3038: body of @code{foo}. When @code{foo} executes, it pushes the address of
3039: the body onto the stack, then (in the code after the @code{does>})
3040: fetches the 5 from there.
3041:
3042: The stack comment near the @code{does>} reflects the stack effect of the
3043: defined word, not the stack effect of the code after the @code{does>}
3044: (the difference is that the code expects the address of the body that
3045: the stack comment does not show).
3046:
3047: You can use these definition words to do factoring in cases that involve
3048: (other) definition words. E.g., a field offset is always added to an
3049: address. Instead of defining
3050:
3051: @example
3052: 2 cells constant offset-field1
3053: @end example
3054:
3055: and using this like
3056:
3057: @example
3058: ( addr ) offset-field1 +
3059: @end example
3060:
3061: you can define a definition word
3062:
3063: @example
3064: : simple-field ( n "name" -- )
3065: create ,
3066: does> ( n1 -- n1+n )
1.50 anton 3067: ( addr ) @@ + ;
1.48 anton 3068: @end example
1.21 crook 3069:
1.48 anton 3070: Definition and use of field offsets now look like this:
1.21 crook 3071:
1.48 anton 3072: @example
3073: 2 cells simple-field field1
1.60 anton 3074: create mystruct 4 cells allot
3075: mystruct .s field1 .s drop
1.48 anton 3076: @end example
1.21 crook 3077:
1.48 anton 3078: If you want to do something with the word without performing the code
3079: after the @code{does>}, you can access the body of a @code{create}d word
3080: with @code{>body ( xt -- addr )}:
1.21 crook 3081:
1.48 anton 3082: @example
3083: : value ( n "name" -- )
3084: create ,
3085: does> ( -- n1 )
1.50 anton 3086: @@ ;
1.48 anton 3087: : to ( n "name" -- )
3088: ' >body ! ;
1.21 crook 3089:
1.48 anton 3090: 5 value foo
3091: foo .
3092: 7 to foo
3093: foo .
3094: @end example
1.21 crook 3095:
1.48 anton 3096: @assignment
3097: Define @code{defer ( "name" -- )}, which creates a word that stores an
3098: XT (at the start the XT of @code{abort}), and upon execution
3099: @code{execute}s the XT. Define @code{is ( xt "name" -- )} that stores
3100: @code{xt} into @code{name}, a word defined with @code{defer}. Indirect
3101: recursion is one application of @code{defer}.
3102: @endassignment
1.29 crook 3103:
1.66 anton 3104: Reference: @ref{User-defined Defining Words}.
3105:
3106:
1.48 anton 3107: @node Arrays and Records Tutorial, POSTPONE Tutorial, Defining Words Tutorial, Tutorial
3108: @section Arrays and Records
1.66 anton 3109: @cindex arrays tutorial
3110: @cindex records tutorial
3111: @cindex structs tutorial
1.29 crook 3112:
1.48 anton 3113: Forth has no standard words for defining data structures such as arrays
3114: and records (structs in C terminology), but you can build them yourself
3115: based on address arithmetic. You can also define words for defining
3116: arrays and records (@pxref{Defining Words Tutorial,, Defining Words}).
1.29 crook 3117:
1.48 anton 3118: One of the first projects a Forth newcomer sets out upon when learning
3119: about defining words is an array defining word (possibly for
3120: n-dimensional arrays). Go ahead and do it, I did it, too; you will
3121: learn something from it. However, don't be disappointed when you later
3122: learn that you have little use for these words (inappropriate use would
3123: be even worse). I have not yet found a set of useful array words yet;
3124: the needs are just too diverse, and named, global arrays (the result of
3125: naive use of defining words) are often not flexible enough (e.g.,
1.66 anton 3126: consider how to pass them as parameters). Another such project is a set
3127: of words to help dealing with strings.
1.29 crook 3128:
1.48 anton 3129: On the other hand, there is a useful set of record words, and it has
3130: been defined in @file{compat/struct.fs}; these words are predefined in
3131: Gforth. They are explained in depth elsewhere in this manual (see
3132: @pxref{Structures}). The @code{simple-field} example above is
3133: simplified variant of fields in this package.
1.21 crook 3134:
3135:
1.48 anton 3136: @node POSTPONE Tutorial, Literal Tutorial, Arrays and Records Tutorial, Tutorial
3137: @section @code{POSTPONE}
1.66 anton 3138: @cindex postpone tutorial
1.21 crook 3139:
1.48 anton 3140: You can compile the compilation semantics (instead of compiling the
3141: interpretation semantics) of a word with @code{POSTPONE}:
1.21 crook 3142:
1.48 anton 3143: @example
3144: : MY-+ ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
1.51 pazsan 3145: POSTPONE + ; immediate
1.48 anton 3146: : foo ( n1 n2 -- n )
3147: MY-+ ;
3148: 1 2 foo .
3149: see foo
3150: @end example
1.21 crook 3151:
1.48 anton 3152: During the definition of @code{foo} the text interpreter performs the
3153: compilation semantics of @code{MY-+}, which performs the compilation
3154: semantics of @code{+}, i.e., it compiles @code{+} into @code{foo}.
3155:
3156: This example also displays separate stack comments for the compilation
3157: semantics and for the stack effect of the compiled code. For words with
3158: default compilation semantics these stack effects are usually not
3159: displayed; the stack effect of the compilation semantics is always
3160: @code{( -- )} for these words, the stack effect for the compiled code is
3161: the stack effect of the interpretation semantics.
3162:
3163: Note that the state of the interpreter does not come into play when
3164: performing the compilation semantics in this way. You can also perform
3165: it interpretively, e.g.:
3166:
3167: @example
3168: : foo2 ( n1 n2 -- n )
3169: [ MY-+ ] ;
3170: 1 2 foo .
3171: see foo
3172: @end example
1.21 crook 3173:
1.48 anton 3174: However, there are some broken Forth systems where this does not always
1.62 crook 3175: work, and therefore this practice was been declared non-standard in
1.48 anton 3176: 1999.
3177: @c !! repair.fs
3178:
3179: Here is another example for using @code{POSTPONE}:
1.44 crook 3180:
1.48 anton 3181: @example
3182: : MY-- ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
3183: POSTPONE negate POSTPONE + ; immediate compile-only
3184: : bar ( n1 n2 -- n )
3185: MY-- ;
3186: 2 1 bar .
3187: see bar
3188: @end example
1.21 crook 3189:
1.48 anton 3190: You can define @code{ENDIF} in this way:
1.21 crook 3191:
1.48 anton 3192: @example
3193: : ENDIF ( Compilation: orig -- )
3194: POSTPONE then ; immediate
3195: @end example
1.21 crook 3196:
1.48 anton 3197: @assignment
3198: Write @code{MY-2DUP} that has compilation semantics equivalent to
3199: @code{2dup}, but compiles @code{over over}.
3200: @endassignment
1.29 crook 3201:
1.66 anton 3202: @c !! @xref{Macros} for reference
3203:
3204:
1.48 anton 3205: @node Literal Tutorial, Advanced macros Tutorial, POSTPONE Tutorial, Tutorial
3206: @section @code{Literal}
1.66 anton 3207: @cindex literal tutorial
1.29 crook 3208:
1.48 anton 3209: You cannot @code{POSTPONE} numbers:
1.21 crook 3210:
1.48 anton 3211: @example
3212: : [FOO] POSTPONE 500 ; immediate
1.21 crook 3213: @end example
3214:
1.48 anton 3215: Instead, you can use @code{LITERAL (compilation: n --; run-time: -- n )}:
1.29 crook 3216:
1.48 anton 3217: @example
3218: : [FOO] ( compilation: --; run-time: -- n )
3219: 500 POSTPONE literal ; immediate
1.29 crook 3220:
1.60 anton 3221: : flip [FOO] ;
1.48 anton 3222: flip .
3223: see flip
3224: @end example
1.29 crook 3225:
1.48 anton 3226: @code{LITERAL} consumes a number at compile-time (when it's compilation
3227: semantics are executed) and pushes it at run-time (when the code it
3228: compiled is executed). A frequent use of @code{LITERAL} is to compile a
3229: number computed at compile time into the current word:
1.29 crook 3230:
1.48 anton 3231: @example
3232: : bar ( -- n )
3233: [ 2 2 + ] literal ;
3234: see bar
3235: @end example
1.29 crook 3236:
1.48 anton 3237: @assignment
3238: Write @code{]L} which allows writing the example above as @code{: bar (
3239: -- n ) [ 2 2 + ]L ;}
3240: @endassignment
3241:
1.66 anton 3242: @c !! @xref{Macros} for reference
3243:
1.48 anton 3244:
3245: @node Advanced macros Tutorial, Compilation Tokens Tutorial, Literal Tutorial, Tutorial
3246: @section Advanced macros
1.66 anton 3247: @cindex macros, advanced tutorial
3248: @cindex run-time code generation, tutorial
1.48 anton 3249:
1.66 anton 3250: Reconsider @code{map-array} from @ref{Execution Tokens Tutorial,,
3251: Execution Tokens}. It frequently performs @code{execute}, a relatively
3252: expensive operation in some Forth implementations. You can use
1.48 anton 3253: @code{compile,} and @code{POSTPONE} to eliminate these @code{execute}s
3254: and produce a word that contains the word to be performed directly:
3255:
3256: @c use ]] ... [[
3257: @example
3258: : compile-map-array ( compilation: xt -- ; run-time: ... addr u -- ... )
3259: \ at run-time, execute xt ( ... x -- ... ) for each element of the
3260: \ array beginning at addr and containing u elements
3261: @{ xt @}
3262: POSTPONE cells POSTPONE over POSTPONE + POSTPONE swap POSTPONE ?do
1.50 anton 3263: POSTPONE i POSTPONE @@ xt compile,
1.48 anton 3264: 1 cells POSTPONE literal POSTPONE +loop ;
3265:
3266: : sum-array ( addr u -- n )
3267: 0 rot rot [ ' + compile-map-array ] ;
3268: see sum-array
3269: a 5 sum-array .
3270: @end example
3271:
3272: You can use the full power of Forth for generating the code; here's an
3273: example where the code is generated in a loop:
3274:
3275: @example
3276: : compile-vmul-step ( compilation: n --; run-time: n1 addr1 -- n2 addr2 )
3277: \ n2=n1+(addr1)*n, addr2=addr1+cell
1.50 anton 3278: POSTPONE tuck POSTPONE @@
1.48 anton 3279: POSTPONE literal POSTPONE * POSTPONE +
3280: POSTPONE swap POSTPONE cell+ ;
3281:
3282: : compile-vmul ( compilation: addr1 u -- ; run-time: addr2 -- n )
1.51 pazsan 3283: \ n=v1*v2 (inner product), where the v_i are represented as addr_i u
1.48 anton 3284: 0 postpone literal postpone swap
3285: [ ' compile-vmul-step compile-map-array ]
3286: postpone drop ;
3287: see compile-vmul
3288:
3289: : a-vmul ( addr -- n )
1.51 pazsan 3290: \ n=a*v, where v is a vector that's as long as a and starts at addr
1.48 anton 3291: [ a 5 compile-vmul ] ;
3292: see a-vmul
3293: a a-vmul .
3294: @end example
3295:
3296: This example uses @code{compile-map-array} to show off, but you could
1.66 anton 3297: also use @code{map-array} instead (try it now!).
1.48 anton 3298:
3299: You can use this technique for efficient multiplication of large
3300: matrices. In matrix multiplication, you multiply every line of one
3301: matrix with every column of the other matrix. You can generate the code
3302: for one line once, and use it for every column. The only downside of
3303: this technique is that it is cumbersome to recover the memory consumed
3304: by the generated code when you are done (and in more complicated cases
3305: it is not possible portably).
3306:
1.66 anton 3307: @c !! @xref{Macros} for reference
3308:
3309:
1.48 anton 3310: @node Compilation Tokens Tutorial, Wordlists and Search Order Tutorial, Advanced macros Tutorial, Tutorial
3311: @section Compilation Tokens
1.66 anton 3312: @cindex compilation tokens, tutorial
3313: @cindex CT, tutorial
1.48 anton 3314:
3315: This section is Gforth-specific. You can skip it.
3316:
3317: @code{' word compile,} compiles the interpretation semantics. For words
3318: with default compilation semantics this is the same as performing the
3319: compilation semantics. To represent the compilation semantics of other
3320: words (e.g., words like @code{if} that have no interpretation
3321: semantics), Gforth has the concept of a compilation token (CT,
3322: consisting of two cells), and words @code{comp'} and @code{[comp']}.
3323: You can perform the compilation semantics represented by a CT with
3324: @code{execute}:
1.29 crook 3325:
1.48 anton 3326: @example
3327: : foo2 ( n1 n2 -- n )
3328: [ comp' + execute ] ;
3329: see foo
3330: @end example
1.29 crook 3331:
1.48 anton 3332: You can compile the compilation semantics represented by a CT with
3333: @code{postpone,}:
1.30 anton 3334:
1.48 anton 3335: @example
3336: : foo3 ( -- )
3337: [ comp' + postpone, ] ;
3338: see foo3
3339: @end example
1.30 anton 3340:
1.51 pazsan 3341: @code{[ comp' word postpone, ]} is equivalent to @code{POSTPONE word}.
1.48 anton 3342: @code{comp'} is particularly useful for words that have no
3343: interpretation semantics:
1.29 crook 3344:
1.30 anton 3345: @example
1.48 anton 3346: ' if
1.60 anton 3347: comp' if .s 2drop
1.30 anton 3348: @end example
3349:
1.66 anton 3350: Reference: @ref{Tokens for Words}.
3351:
1.29 crook 3352:
1.48 anton 3353: @node Wordlists and Search Order Tutorial, , Compilation Tokens Tutorial, Tutorial
3354: @section Wordlists and Search Order
1.66 anton 3355: @cindex wordlists tutorial
3356: @cindex search order, tutorial
1.48 anton 3357:
3358: The dictionary is not just a memory area that allows you to allocate
3359: memory with @code{allot}, it also contains the Forth words, arranged in
3360: several wordlists. When searching for a word in a wordlist,
3361: conceptually you start searching at the youngest and proceed towards
3362: older words (in reality most systems nowadays use hash-tables); i.e., if
3363: you define a word with the same name as an older word, the new word
3364: shadows the older word.
3365:
3366: Which wordlists are searched in which order is determined by the search
3367: order. You can display the search order with @code{order}. It displays
3368: first the search order, starting with the wordlist searched first, then
3369: it displays the wordlist that will contain newly defined words.
1.21 crook 3370:
1.48 anton 3371: You can create a new, empty wordlist with @code{wordlist ( -- wid )}:
1.21 crook 3372:
1.48 anton 3373: @example
3374: wordlist constant mywords
3375: @end example
1.21 crook 3376:
1.48 anton 3377: @code{Set-current ( wid -- )} sets the wordlist that will contain newly
3378: defined words (the @emph{current} wordlist):
1.21 crook 3379:
1.48 anton 3380: @example
3381: mywords set-current
3382: order
3383: @end example
1.26 crook 3384:
1.48 anton 3385: Gforth does not display a name for the wordlist in @code{mywords}
3386: because this wordlist was created anonymously with @code{wordlist}.
1.21 crook 3387:
1.48 anton 3388: You can get the current wordlist with @code{get-current ( -- wid)}. If
3389: you want to put something into a specific wordlist without overall
3390: effect on the current wordlist, this typically looks like this:
1.21 crook 3391:
1.48 anton 3392: @example
3393: get-current mywords set-current ( wid )
3394: create someword
3395: ( wid ) set-current
3396: @end example
1.21 crook 3397:
1.48 anton 3398: You can write the search order with @code{set-order ( wid1 .. widn n --
3399: )} and read it with @code{get-order ( -- wid1 .. widn n )}. The first
3400: searched wordlist is topmost.
1.21 crook 3401:
1.48 anton 3402: @example
3403: get-order mywords swap 1+ set-order
3404: order
3405: @end example
1.21 crook 3406:
1.48 anton 3407: Yes, the order of wordlists in the output of @code{order} is reversed
3408: from stack comments and the output of @code{.s} and thus unintuitive.
1.21 crook 3409:
1.48 anton 3410: @assignment
3411: Define @code{>order ( wid -- )} with adds @code{wid} as first searched
3412: wordlist to the search order. Define @code{previous ( -- )}, which
3413: removes the first searched wordlist from the search order. Experiment
3414: with boundary conditions (you will see some crashes or situations that
3415: are hard or impossible to leave).
3416: @endassignment
1.21 crook 3417:
1.48 anton 3418: The search order is a powerful foundation for providing features similar
3419: to Modula-2 modules and C++ namespaces. However, trying to modularize
3420: programs in this way has disadvantages for debugging and reuse/factoring
3421: that overcome the advantages in my experience (I don't do huge projects,
1.55 anton 3422: though). These disadvantages are not so clear in other
1.48 anton 3423: languages/programming environments, because these langauges are not so
3424: strong in debugging and reuse.
1.21 crook 3425:
1.66 anton 3426: @c !! example
3427:
3428: Reference: @ref{Word Lists}.
1.21 crook 3429:
1.29 crook 3430: @c ******************************************************************
1.48 anton 3431: @node Introduction, Words, Tutorial, Top
1.29 crook 3432: @comment node-name, next, previous, up
3433: @chapter An Introduction to ANS Forth
3434: @cindex Forth - an introduction
1.21 crook 3435:
1.29 crook 3436: The primary purpose of this manual is to document Gforth. However, since
3437: Forth is not a widely-known language and there is a lack of up-to-date
3438: teaching material, it seems worthwhile to provide some introductory
1.49 anton 3439: material. For other sources of Forth-related
3440: information, see @ref{Forth-related information}.
1.21 crook 3441:
1.29 crook 3442: The examples in this section should work on any ANS Forth; the
3443: output shown was produced using Gforth. Each example attempts to
3444: reproduce the exact output that Gforth produces. If you try out the
3445: examples (and you should), what you should type is shown @kbd{like this}
3446: and Gforth's response is shown @code{like this}. The single exception is
1.30 anton 3447: that, where the example shows @key{RET} it means that you should
1.29 crook 3448: press the ``carriage return'' key. Unfortunately, some output formats for
3449: this manual cannot show the difference between @kbd{this} and
3450: @code{this} which will make trying out the examples harder (but not
3451: impossible).
1.21 crook 3452:
1.29 crook 3453: Forth is an unusual language. It provides an interactive development
3454: environment which includes both an interpreter and compiler. Forth
3455: programming style encourages you to break a problem down into many
3456: @cindex factoring
3457: small fragments (@dfn{factoring}), and then to develop and test each
3458: fragment interactively. Forth advocates assert that breaking the
3459: edit-compile-test cycle used by conventional programming languages can
3460: lead to great productivity improvements.
1.21 crook 3461:
1.29 crook 3462: @menu
1.67 anton 3463: * Introducing the Text Interpreter::
3464: * Stacks and Postfix notation::
3465: * Your first definition::
3466: * How does that work?::
3467: * Forth is written in Forth::
3468: * Review - elements of a Forth system::
3469: * Where to go next::
3470: * Exercises::
1.29 crook 3471: @end menu
1.21 crook 3472:
1.29 crook 3473: @comment ----------------------------------------------
3474: @node Introducing the Text Interpreter, Stacks and Postfix notation, Introduction, Introduction
3475: @section Introducing the Text Interpreter
3476: @cindex text interpreter
3477: @cindex outer interpreter
1.21 crook 3478:
1.30 anton 3479: @c IMO this is too detailed and the pace is too slow for
3480: @c an introduction. If you know German, take a look at
3481: @c http://www.complang.tuwien.ac.at/anton/lvas/skriptum-stack.html
3482: @c to see how I do it - anton
3483:
1.44 crook 3484: @c nac-> Where I have accepted your comments 100% and modified the text
3485: @c accordingly, I have deleted your comments. Elsewhere I have added a
3486: @c response like this to attempt to rationalise what I have done. Of
3487: @c course, this is a very clumsy mechanism for something that would be
3488: @c done far more efficiently over a beer. Please delete any dialogue
3489: @c you consider closed.
3490:
1.29 crook 3491: When you invoke the Forth image, you will see a startup banner printed
3492: and nothing else (if you have Gforth installed on your system, try
1.30 anton 3493: invoking it now, by typing @kbd{gforth@key{RET}}). Forth is now running
1.29 crook 3494: its command line interpreter, which is called the @dfn{Text Interpreter}
3495: (also known as the @dfn{Outer Interpreter}). (You will learn a lot
1.49 anton 3496: about the text interpreter as you read through this chapter, for more
3497: detail @pxref{The Text Interpreter}).
1.21 crook 3498:
1.29 crook 3499: Although it's not obvious, Forth is actually waiting for your
1.30 anton 3500: input. Type a number and press the @key{RET} key:
1.21 crook 3501:
1.26 crook 3502: @example
1.30 anton 3503: @kbd{45@key{RET}} ok
1.26 crook 3504: @end example
1.21 crook 3505:
1.29 crook 3506: Rather than give you a prompt to invite you to input something, the text
3507: interpreter prints a status message @i{after} it has processed a line
3508: of input. The status message in this case (``@code{ ok}'' followed by
3509: carriage-return) indicates that the text interpreter was able to process
3510: all of your input successfully. Now type something illegal:
3511:
3512: @example
1.30 anton 3513: @kbd{qwer341@key{RET}}
1.29 crook 3514: :1: Undefined word
3515: qwer341
3516: ^^^^^^^
3517: $400D2BA8 Bounce
3518: $400DBDA8 no.extensions
3519: @end example
1.23 crook 3520:
1.29 crook 3521: The exact text, other than the ``Undefined word'' may differ slightly on
3522: your system, but the effect is the same; when the text interpreter
3523: detects an error, it discards any remaining text on a line, resets
1.49 anton 3524: certain internal state and prints an error message. For a detailed description of error messages see @ref{Error
3525: messages}.
1.23 crook 3526:
1.29 crook 3527: The text interpreter waits for you to press carriage-return, and then
3528: processes your input line. Starting at the beginning of the line, it
3529: breaks the line into groups of characters separated by spaces. For each
3530: group of characters in turn, it makes two attempts to do something:
1.23 crook 3531:
1.29 crook 3532: @itemize @bullet
3533: @item
1.44 crook 3534: @cindex name dictionary
1.29 crook 3535: It tries to treat it as a command. It does this by searching a @dfn{name
3536: dictionary}. If the group of characters matches an entry in the name
3537: dictionary, the name dictionary provides the text interpreter with
3538: information that allows the text interpreter perform some actions. In
3539: Forth jargon, we say that the group
3540: @cindex word
3541: @cindex definition
3542: @cindex execution token
3543: @cindex xt
3544: of characters names a @dfn{word}, that the dictionary search returns an
3545: @dfn{execution token (xt)} corresponding to the @dfn{definition} of the
3546: word, and that the text interpreter executes the xt. Often, the terms
3547: @dfn{word} and @dfn{definition} are used interchangeably.
3548: @item
3549: If the text interpreter fails to find a match in the name dictionary, it
3550: tries to treat the group of characters as a number in the current number
3551: base (when you start up Forth, the current number base is base 10). If
3552: the group of characters legitimately represents a number, the text
3553: interpreter pushes the number onto a stack (we'll learn more about that
3554: in the next section).
3555: @end itemize
1.23 crook 3556:
1.29 crook 3557: If the text interpreter is unable to do either of these things with any
3558: group of characters, it discards the group of characters and the rest of
3559: the line, then prints an error message. If the text interpreter reaches
3560: the end of the line without error, it prints the status message ``@code{ ok}''
3561: followed by carriage-return.
1.21 crook 3562:
1.29 crook 3563: This is the simplest command we can give to the text interpreter:
1.23 crook 3564:
3565: @example
1.30 anton 3566: @key{RET} ok
1.23 crook 3567: @end example
1.21 crook 3568:
1.29 crook 3569: The text interpreter did everything we asked it to do (nothing) without
3570: an error, so it said that everything is ``@code{ ok}''. Try a slightly longer
3571: command:
1.21 crook 3572:
1.23 crook 3573: @example
1.30 anton 3574: @kbd{12 dup fred dup@key{RET}}
1.29 crook 3575: :1: Undefined word
3576: 12 dup fred dup
3577: ^^^^
3578: $400D2BA8 Bounce
3579: $400DBDA8 no.extensions
1.23 crook 3580: @end example
1.21 crook 3581:
1.29 crook 3582: When you press the carriage-return key, the text interpreter starts to
3583: work its way along the line:
1.21 crook 3584:
1.29 crook 3585: @itemize @bullet
3586: @item
3587: When it gets to the space after the @code{2}, it takes the group of
3588: characters @code{12} and looks them up in the name
3589: dictionary@footnote{We can't tell if it found them or not, but assume
3590: for now that it did not}. There is no match for this group of characters
3591: in the name dictionary, so it tries to treat them as a number. It is
3592: able to do this successfully, so it puts the number, 12, ``on the stack''
3593: (whatever that means).
3594: @item
3595: The text interpreter resumes scanning the line and gets the next group
3596: of characters, @code{dup}. It looks it up in the name dictionary and
3597: (you'll have to take my word for this) finds it, and executes the word
3598: @code{dup} (whatever that means).
3599: @item
3600: Once again, the text interpreter resumes scanning the line and gets the
3601: group of characters @code{fred}. It looks them up in the name
3602: dictionary, but can't find them. It tries to treat them as a number, but
3603: they don't represent any legal number.
3604: @end itemize
1.21 crook 3605:
1.29 crook 3606: At this point, the text interpreter gives up and prints an error
3607: message. The error message shows exactly how far the text interpreter
3608: got in processing the line. In particular, it shows that the text
3609: interpreter made no attempt to do anything with the final character
3610: group, @code{dup}, even though we have good reason to believe that the
3611: text interpreter would have no problem looking that word up and
3612: executing it a second time.
1.21 crook 3613:
3614:
1.29 crook 3615: @comment ----------------------------------------------
3616: @node Stacks and Postfix notation, Your first definition, Introducing the Text Interpreter, Introduction
3617: @section Stacks, postfix notation and parameter passing
3618: @cindex text interpreter
3619: @cindex outer interpreter
1.21 crook 3620:
1.29 crook 3621: In procedural programming languages (like C and Pascal), the
3622: building-block of programs is the @dfn{function} or @dfn{procedure}. These
3623: functions or procedures are called with @dfn{explicit parameters}. For
3624: example, in C we might write:
1.21 crook 3625:
1.23 crook 3626: @example
1.29 crook 3627: total = total + new_volume(length,height,depth);
1.23 crook 3628: @end example
1.21 crook 3629:
1.23 crook 3630: @noindent
1.29 crook 3631: where new_volume is a function-call to another piece of code, and total,
3632: length, height and depth are all variables. length, height and depth are
3633: parameters to the function-call.
1.21 crook 3634:
1.29 crook 3635: In Forth, the equivalent of the function or procedure is the
3636: @dfn{definition} and parameters are implicitly passed between
3637: definitions using a shared stack that is visible to the
3638: programmer. Although Forth does support variables, the existence of the
3639: stack means that they are used far less often than in most other
3640: programming languages. When the text interpreter encounters a number, it
3641: will place (@dfn{push}) it on the stack. There are several stacks (the
1.30 anton 3642: actual number is implementation-dependent ...) and the particular stack
1.29 crook 3643: used for any operation is implied unambiguously by the operation being
3644: performed. The stack used for all integer operations is called the @dfn{data
3645: stack} and, since this is the stack used most commonly, references to
3646: ``the data stack'' are often abbreviated to ``the stack''.
1.21 crook 3647:
1.29 crook 3648: The stacks have a last-in, first-out (LIFO) organisation. If you type:
1.21 crook 3649:
1.23 crook 3650: @example
1.30 anton 3651: @kbd{1 2 3@key{RET}} ok
1.23 crook 3652: @end example
1.21 crook 3653:
1.29 crook 3654: Then this instructs the text interpreter to placed three numbers on the
3655: (data) stack. An analogy for the behaviour of the stack is to take a
3656: pack of playing cards and deal out the ace (1), 2 and 3 into a pile on
3657: the table. The 3 was the last card onto the pile (``last-in'') and if
3658: you take a card off the pile then, unless you're prepared to fiddle a
3659: bit, the card that you take off will be the 3 (``first-out''). The
3660: number that will be first-out of the stack is called the @dfn{top of
3661: stack}, which
3662: @cindex TOS definition
3663: is often abbreviated to @dfn{TOS}.
1.21 crook 3664:
1.29 crook 3665: To understand how parameters are passed in Forth, consider the
3666: behaviour of the definition @code{+} (pronounced ``plus''). You will not
3667: be surprised to learn that this definition performs addition. More
3668: precisely, it adds two number together and produces a result. Where does
3669: it get the two numbers from? It takes the top two numbers off the
3670: stack. Where does it place the result? On the stack. You can act-out the
3671: behaviour of @code{+} with your playing cards like this:
1.21 crook 3672:
3673: @itemize @bullet
3674: @item
1.29 crook 3675: Pick up two cards from the stack on the table
1.21 crook 3676: @item
1.29 crook 3677: Stare at them intently and ask yourself ``what @i{is} the sum of these two
3678: numbers''
1.21 crook 3679: @item
1.29 crook 3680: Decide that the answer is 5
1.21 crook 3681: @item
1.29 crook 3682: Shuffle the two cards back into the pack and find a 5
1.21 crook 3683: @item
1.29 crook 3684: Put a 5 on the remaining ace that's on the table.
1.21 crook 3685: @end itemize
3686:
1.29 crook 3687: If you don't have a pack of cards handy but you do have Forth running,
3688: you can use the definition @code{.s} to show the current state of the stack,
3689: without affecting the stack. Type:
1.21 crook 3690:
3691: @example
1.30 anton 3692: @kbd{clearstack 1 2 3@key{RET}} ok
3693: @kbd{.s@key{RET}} <3> 1 2 3 ok
1.23 crook 3694: @end example
3695:
1.29 crook 3696: The text interpreter looks up the word @code{clearstack} and executes
3697: it; it tidies up the stack and removes any entries that may have been
3698: left on it by earlier examples. The text interpreter pushes each of the
3699: three numbers in turn onto the stack. Finally, the text interpreter
3700: looks up the word @code{.s} and executes it. The effect of executing
3701: @code{.s} is to print the ``<3>'' (the total number of items on the stack)
3702: followed by a list of all the items on the stack; the item on the far
3703: right-hand side is the TOS.
1.21 crook 3704:
1.29 crook 3705: You can now type:
1.21 crook 3706:
1.29 crook 3707: @example
1.30 anton 3708: @kbd{+ .s@key{RET}} <2> 1 5 ok
1.29 crook 3709: @end example
1.21 crook 3710:
1.29 crook 3711: @noindent
3712: which is correct; there are now 2 items on the stack and the result of
3713: the addition is 5.
1.23 crook 3714:
1.29 crook 3715: If you're playing with cards, try doing a second addition: pick up the
3716: two cards, work out that their sum is 6, shuffle them into the pack,
3717: look for a 6 and place that on the table. You now have just one item on
3718: the stack. What happens if you try to do a third addition? Pick up the
3719: first card, pick up the second card -- ah! There is no second card. This
3720: is called a @dfn{stack underflow} and consitutes an error. If you try to
3721: do the same thing with Forth it will report an error (probably a Stack
3722: Underflow or an Invalid Memory Address error).
1.23 crook 3723:
1.29 crook 3724: The opposite situation to a stack underflow is a @dfn{stack overflow},
3725: which simply accepts that there is a finite amount of storage space
3726: reserved for the stack. To stretch the playing card analogy, if you had
3727: enough packs of cards and you piled the cards up on the table, you would
3728: eventually be unable to add another card; you'd hit the ceiling. Gforth
3729: allows you to set the maximum size of the stacks. In general, the only
3730: time that you will get a stack overflow is because a definition has a
3731: bug in it and is generating data on the stack uncontrollably.
1.23 crook 3732:
1.29 crook 3733: There's one final use for the playing card analogy. If you model your
3734: stack using a pack of playing cards, the maximum number of items on
3735: your stack will be 52 (I assume you didn't use the Joker). The maximum
3736: @i{value} of any item on the stack is 13 (the King). In fact, the only
3737: possible numbers are positive integer numbers 1 through 13; you can't
3738: have (for example) 0 or 27 or 3.52 or -2. If you change the way you
3739: think about some of the cards, you can accommodate different
3740: numbers. For example, you could think of the Jack as representing 0,
3741: the Queen as representing -1 and the King as representing -2. Your
1.45 crook 3742: @i{range} remains unchanged (you can still only represent a total of 13
1.29 crook 3743: numbers) but the numbers that you can represent are -2 through 10.
1.28 crook 3744:
1.29 crook 3745: In that analogy, the limit was the amount of information that a single
3746: stack entry could hold, and Forth has a similar limit. In Forth, the
3747: size of a stack entry is called a @dfn{cell}. The actual size of a cell is
3748: implementation dependent and affects the maximum value that a stack
3749: entry can hold. A Standard Forth provides a cell size of at least
3750: 16-bits, and most desktop systems use a cell size of 32-bits.
1.21 crook 3751:
1.29 crook 3752: Forth does not do any type checking for you, so you are free to
3753: manipulate and combine stack items in any way you wish. A convenient way
3754: of treating stack items is as 2's complement signed integers, and that
3755: is what Standard words like @code{+} do. Therefore you can type:
1.21 crook 3756:
1.29 crook 3757: @example
1.30 anton 3758: @kbd{-5 12 + .s@key{RET}} <1> 7 ok
1.29 crook 3759: @end example
1.21 crook 3760:
1.29 crook 3761: If you use numbers and definitions like @code{+} in order to turn Forth
3762: into a great big pocket calculator, you will realise that it's rather
3763: different from a normal calculator. Rather than typing 2 + 3 = you had
3764: to type 2 3 + (ignore the fact that you had to use @code{.s} to see the
3765: result). The terminology used to describe this difference is to say that
3766: your calculator uses @dfn{Infix Notation} (parameters and operators are
3767: mixed) whilst Forth uses @dfn{Postfix Notation} (parameters and
3768: operators are separate), also called @dfn{Reverse Polish Notation}.
1.21 crook 3769:
1.29 crook 3770: Whilst postfix notation might look confusing to begin with, it has
3771: several important advantages:
1.21 crook 3772:
1.23 crook 3773: @itemize @bullet
3774: @item
1.29 crook 3775: it is unambiguous
1.23 crook 3776: @item
1.29 crook 3777: it is more concise
1.23 crook 3778: @item
1.29 crook 3779: it fits naturally with a stack-based system
1.23 crook 3780: @end itemize
1.21 crook 3781:
1.29 crook 3782: To examine these claims in more detail, consider these sums:
1.21 crook 3783:
1.29 crook 3784: @example
3785: 6 + 5 * 4 =
3786: 4 * 5 + 6 =
3787: @end example
1.21 crook 3788:
1.29 crook 3789: If you're just learning maths or your maths is very rusty, you will
3790: probably come up with the answer 44 for the first and 26 for the
3791: second. If you are a bit of a whizz at maths you will remember the
3792: @i{convention} that multiplication takes precendence over addition, and
3793: you'd come up with the answer 26 both times. To explain the answer 26
3794: to someone who got the answer 44, you'd probably rewrite the first sum
3795: like this:
1.21 crook 3796:
1.29 crook 3797: @example
3798: 6 + (5 * 4) =
3799: @end example
1.21 crook 3800:
1.29 crook 3801: If what you really wanted was to perform the addition before the
3802: multiplication, you would have to use parentheses to force it.
1.21 crook 3803:
1.29 crook 3804: If you did the first two sums on a pocket calculator you would probably
3805: get the right answers, unless you were very cautious and entered them using
3806: these keystroke sequences:
1.21 crook 3807:
1.29 crook 3808: 6 + 5 = * 4 =
3809: 4 * 5 = + 6 =
1.21 crook 3810:
1.29 crook 3811: Postfix notation is unambiguous because the order that the operators
3812: are applied is always explicit; that also means that parentheses are
3813: never required. The operators are @i{active} (the act of quoting the
3814: operator makes the operation occur) which removes the need for ``=''.
1.28 crook 3815:
1.29 crook 3816: The sum 6 + 5 * 4 can be written (in postfix notation) in two
3817: equivalent ways:
1.26 crook 3818:
3819: @example
1.29 crook 3820: 6 5 4 * + or:
3821: 5 4 * 6 +
1.26 crook 3822: @end example
1.23 crook 3823:
1.29 crook 3824: An important thing that you should notice about this notation is that
3825: the @i{order} of the numbers does not change; if you want to subtract
3826: 2 from 10 you type @code{10 2 -}.
1.1 anton 3827:
1.29 crook 3828: The reason that Forth uses postfix notation is very simple to explain: it
3829: makes the implementation extremely simple, and it follows naturally from
3830: using the stack as a mechanism for passing parameters. Another way of
3831: thinking about this is to realise that all Forth definitions are
3832: @i{active}; they execute as they are encountered by the text
3833: interpreter. The result of this is that the syntax of Forth is trivially
3834: simple.
1.1 anton 3835:
3836:
3837:
1.29 crook 3838: @comment ----------------------------------------------
3839: @node Your first definition, How does that work?, Stacks and Postfix notation, Introduction
3840: @section Your first Forth definition
3841: @cindex first definition
1.1 anton 3842:
1.29 crook 3843: Until now, the examples we've seen have been trivial; we've just been
3844: using Forth as a bigger-than-pocket calculator. Also, each calculation
3845: we've shown has been a ``one-off'' -- to repeat it we'd need to type it in
3846: again@footnote{That's not quite true. If you press the up-arrow key on
3847: your keyboard you should be able to scroll back to any earlier command,
3848: edit it and re-enter it.} In this section we'll see how to add new
3849: words to Forth's vocabulary.
1.1 anton 3850:
1.29 crook 3851: The easiest way to create a new word is to use a @dfn{colon
3852: definition}. We'll define a few and try them out before worrying too
3853: much about how they work. Try typing in these examples; be careful to
3854: copy the spaces accurately:
1.1 anton 3855:
1.29 crook 3856: @example
3857: : add-two 2 + . ;
3858: : greet ." Hello and welcome" ;
3859: : demo 5 add-two ;
3860: @end example
1.1 anton 3861:
1.29 crook 3862: @noindent
3863: Now try them out:
1.1 anton 3864:
1.29 crook 3865: @example
1.30 anton 3866: @kbd{greet@key{RET}} Hello and welcome ok
3867: @kbd{greet greet@key{RET}} Hello and welcomeHello and welcome ok
3868: @kbd{4 add-two@key{RET}} 6 ok
3869: @kbd{demo@key{RET}} 7 ok
3870: @kbd{9 greet demo add-two@key{RET}} Hello and welcome7 11 ok
1.29 crook 3871: @end example
1.1 anton 3872:
1.29 crook 3873: The first new thing that we've introduced here is the pair of words
3874: @code{:} and @code{;}. These are used to start and terminate a new
3875: definition, respectively. The first word after the @code{:} is the name
3876: for the new definition.
1.1 anton 3877:
1.29 crook 3878: As you can see from the examples, a definition is built up of words that
3879: have already been defined; Forth makes no distinction between
3880: definitions that existed when you started the system up, and those that
3881: you define yourself.
1.1 anton 3882:
1.29 crook 3883: The examples also introduce the words @code{.} (dot), @code{."}
3884: (dot-quote) and @code{dup} (dewp). Dot takes the value from the top of
3885: the stack and displays it. It's like @code{.s} except that it only
3886: displays the top item of the stack and it is destructive; after it has
3887: executed, the number is no longer on the stack. There is always one
3888: space printed after the number, and no spaces before it. Dot-quote
3889: defines a string (a sequence of characters) that will be printed when
3890: the word is executed. The string can contain any printable characters
3891: except @code{"}. A @code{"} has a special function; it is not a Forth
3892: word but it acts as a delimiter (the way that delimiters work is
3893: described in the next section). Finally, @code{dup} duplicates the value
3894: at the top of the stack. Try typing @code{5 dup .s} to see what it does.
1.1 anton 3895:
1.29 crook 3896: We already know that the text interpreter searches through the
3897: dictionary to locate names. If you've followed the examples earlier, you
3898: will already have a definition called @code{add-two}. Lets try modifying
3899: it by typing in a new definition:
1.1 anton 3900:
1.29 crook 3901: @example
1.30 anton 3902: @kbd{: add-two dup . ." + 2 =" 2 + . ;@key{RET}} redefined add-two ok
1.29 crook 3903: @end example
1.5 anton 3904:
1.29 crook 3905: Forth recognised that we were defining a word that already exists, and
3906: printed a message to warn us of that fact. Let's try out the new
3907: definition:
1.5 anton 3908:
1.29 crook 3909: @example
1.30 anton 3910: @kbd{9 add-two@key{RET}} 9 + 2 =11 ok
1.29 crook 3911: @end example
1.1 anton 3912:
1.29 crook 3913: @noindent
3914: All that we've actually done here, though, is to create a new
3915: definition, with a particular name. The fact that there was already a
3916: definition with the same name did not make any difference to the way
3917: that the new definition was created (except that Forth printed a warning
3918: message). The old definition of add-two still exists (try @code{demo}
3919: again to see that this is true). Any new definition will use the new
3920: definition of @code{add-two}, but old definitions continue to use the
3921: version that already existed at the time that they were @code{compiled}.
1.1 anton 3922:
1.29 crook 3923: Before you go on to the next section, try defining and redefining some
3924: words of your own.
1.1 anton 3925:
1.29 crook 3926: @comment ----------------------------------------------
3927: @node How does that work?, Forth is written in Forth, Your first definition, Introduction
3928: @section How does that work?
3929: @cindex parsing words
1.1 anton 3930:
1.30 anton 3931: @c That's pretty deep (IMO way too deep) for an introduction. - anton
3932:
3933: @c Is it a good idea to talk about the interpretation semantics of a
3934: @c number? We don't have an xt to go along with it. - anton
3935:
3936: @c Now that I have eliminated execution semantics, I wonder if it would not
3937: @c be better to keep them (or add run-time semantics), to make it easier to
3938: @c explain what compilation semantics usually does. - anton
3939:
1.44 crook 3940: @c nac-> I removed the term ``default compilation sematics'' from the
3941: @c introductory chapter. Removing ``execution semantics'' was making
3942: @c everything simpler to explain, then I think the use of this term made
3943: @c everything more complex again. I replaced it with ``default
3944: @c semantics'' (which is used elsewhere in the manual) by which I mean
3945: @c ``a definition that has neither the immediate nor the compile-only
3946: @c flag set''. I reworded big chunks of the ``how does that work''
3947: @c section (and, unusually for me, I think I even made it shorter!). See
3948: @c what you think -- I know I have not addressed your primary concern
3949: @c that it is too heavy-going for an introduction. From what I understood
3950: @c of your course notes it looks as though they might be a good framework.
3951: @c Things that I've tried to capture here are some things that came as a
3952: @c great revelation here when I first understood them. Also, I like the
3953: @c fact that a very simple code example shows up almost all of the issues
3954: @c that you need to understand to see how Forth works. That's unique and
3955: @c worthwhile to emphasise.
3956:
1.29 crook 3957: Now we're going to take another look at the definition of @code{add-two}
3958: from the previous section. From our knowledge of the way that the text
3959: interpreter works, we would have expected this result when we tried to
3960: define @code{add-two}:
1.21 crook 3961:
1.29 crook 3962: @example
1.44 crook 3963: @kbd{: add-two 2 + . ;@key{RET}}
1.29 crook 3964: ^^^^^^^
3965: Error: Undefined word
3966: @end example
1.28 crook 3967:
1.29 crook 3968: The reason that this didn't happen is bound up in the way that @code{:}
3969: works. The word @code{:} does two special things. The first special
3970: thing that it does prevents the text interpreter from ever seeing the
3971: characters @code{add-two}. The text interpreter uses a variable called
3972: @cindex modifying >IN
1.44 crook 3973: @code{>IN} (pronounced ``to-in'') to keep track of where it is in the
1.29 crook 3974: input line. When it encounters the word @code{:} it behaves in exactly
3975: the same way as it does for any other word; it looks it up in the name
3976: dictionary, finds its xt and executes it. When @code{:} executes, it
3977: looks at the input buffer, finds the word @code{add-two} and advances the
3978: value of @code{>IN} to point past it. It then does some other stuff
3979: associated with creating the new definition (including creating an entry
3980: for @code{add-two} in the name dictionary). When the execution of @code{:}
3981: completes, control returns to the text interpreter, which is oblivious
3982: to the fact that it has been tricked into ignoring part of the input
3983: line.
1.21 crook 3984:
1.29 crook 3985: @cindex parsing words
3986: Words like @code{:} -- words that advance the value of @code{>IN} and so
3987: prevent the text interpreter from acting on the whole of the input line
3988: -- are called @dfn{parsing words}.
1.21 crook 3989:
1.29 crook 3990: @cindex @code{state} - effect on the text interpreter
3991: @cindex text interpreter - effect of state
3992: The second special thing that @code{:} does is change the value of a
3993: variable called @code{state}, which affects the way that the text
3994: interpreter behaves. When Gforth starts up, @code{state} has the value
3995: 0, and the text interpreter is said to be @dfn{interpreting}. During a
3996: colon definition (started with @code{:}), @code{state} is set to -1 and
1.44 crook 3997: the text interpreter is said to be @dfn{compiling}.
3998:
3999: In this example, the text interpreter is compiling when it processes the
4000: string ``@code{2 + . ;}''. It still breaks the string down into
4001: character sequences in the same way. However, instead of pushing the
4002: number @code{2} onto the stack, it lays down (@dfn{compiles}) some magic
4003: into the definition of @code{add-two} that will make the number @code{2} get
4004: pushed onto the stack when @code{add-two} is @dfn{executed}. Similarly,
4005: the behaviours of @code{+} and @code{.} are also compiled into the
4006: definition.
4007:
4008: One category of words don't get compiled. These so-called @dfn{immediate
4009: words} get executed (performed @i{now}) regardless of whether the text
4010: interpreter is interpreting or compiling. The word @code{;} is an
4011: immediate word. Rather than being compiled into the definition, it
4012: executes. Its effect is to terminate the current definition, which
4013: includes changing the value of @code{state} back to 0.
4014:
4015: When you execute @code{add-two}, it has a @dfn{run-time effect} that is
4016: exactly the same as if you had typed @code{2 + . @key{RET}} outside of a
4017: definition.
1.28 crook 4018:
1.30 anton 4019: In Forth, every word or number can be described in terms of two
1.29 crook 4020: properties:
1.28 crook 4021:
4022: @itemize @bullet
4023: @item
1.29 crook 4024: @cindex interpretation semantics
1.44 crook 4025: Its @dfn{interpretation semantics} describe how it will behave when the
4026: text interpreter encounters it in @dfn{interpret} state. The
4027: interpretation semantics of a word are represented by an @dfn{execution
4028: token}.
1.28 crook 4029: @item
1.29 crook 4030: @cindex compilation semantics
1.44 crook 4031: Its @dfn{compilation semantics} describe how it will behave when the
4032: text interpreter encounters it in @dfn{compile} state. The compilation
4033: semantics of a word are represented in an implementation-dependent way;
4034: Gforth uses a @dfn{compilation token}.
1.29 crook 4035: @end itemize
4036:
4037: @noindent
4038: Numbers are always treated in a fixed way:
4039:
4040: @itemize @bullet
1.28 crook 4041: @item
1.44 crook 4042: When the number is @dfn{interpreted}, its behaviour is to push the
4043: number onto the stack.
1.28 crook 4044: @item
1.30 anton 4045: When the number is @dfn{compiled}, a piece of code is appended to the
4046: current definition that pushes the number when it runs. (In other words,
4047: the compilation semantics of a number are to postpone its interpretation
4048: semantics until the run-time of the definition that it is being compiled
4049: into.)
1.29 crook 4050: @end itemize
4051:
1.44 crook 4052: Words don't behave in such a regular way, but most have @i{default
4053: semantics} which means that they behave like this:
1.29 crook 4054:
4055: @itemize @bullet
1.28 crook 4056: @item
1.30 anton 4057: The @dfn{interpretation semantics} of the word are to do something useful.
4058: @item
1.29 crook 4059: The @dfn{compilation semantics} of the word are to append its
1.30 anton 4060: @dfn{interpretation semantics} to the current definition (so that its
4061: run-time behaviour is to do something useful).
1.28 crook 4062: @end itemize
4063:
1.30 anton 4064: @cindex immediate words
1.44 crook 4065: The actual behaviour of any particular word can be controlled by using
4066: the words @code{immediate} and @code{compile-only} when the word is
4067: defined. These words set flags in the name dictionary entry of the most
4068: recently defined word, and these flags are retrieved by the text
4069: interpreter when it finds the word in the name dictionary.
4070:
4071: A word that is marked as @dfn{immediate} has compilation semantics that
4072: are identical to its interpretation semantics. In other words, it
4073: behaves like this:
1.29 crook 4074:
4075: @itemize @bullet
4076: @item
1.30 anton 4077: The @dfn{interpretation semantics} of the word are to do something useful.
1.29 crook 4078: @item
1.30 anton 4079: The @dfn{compilation semantics} of the word are to do something useful
4080: (and actually the same thing); i.e., it is executed during compilation.
1.29 crook 4081: @end itemize
1.28 crook 4082:
1.44 crook 4083: Marking a word as @dfn{compile-only} prohibits the text interpreter from
4084: performing the interpretation semantics of the word directly; an attempt
4085: to do so will generate an error. It is never necessary to use
4086: @code{compile-only} (and it is not even part of ANS Forth, though it is
4087: provided by many implementations) but it is good etiquette to apply it
4088: to a word that will not behave correctly (and might have unexpected
4089: side-effects) in interpret state. For example, it is only legal to use
4090: the conditional word @code{IF} within a definition. If you forget this
4091: and try to use it elsewhere, the fact that (in Gforth) it is marked as
4092: @code{compile-only} allows the text interpreter to generate a helpful
4093: error message rather than subjecting you to the consequences of your
4094: folly.
4095:
1.29 crook 4096: This example shows the difference between an immediate and a
4097: non-immediate word:
1.28 crook 4098:
1.29 crook 4099: @example
4100: : show-state state @@ . ;
4101: : show-state-now show-state ; immediate
4102: : word1 show-state ;
4103: : word2 show-state-now ;
1.28 crook 4104: @end example
1.23 crook 4105:
1.29 crook 4106: The word @code{immediate} after the definition of @code{show-state-now}
4107: makes that word an immediate word. These definitions introduce a new
4108: word: @code{@@} (pronounced ``fetch''). This word fetches the value of a
4109: variable, and leaves it on the stack. Therefore, the behaviour of
4110: @code{show-state} is to print a number that represents the current value
4111: of @code{state}.
1.28 crook 4112:
1.29 crook 4113: When you execute @code{word1}, it prints the number 0, indicating that
4114: the system is interpreting. When the text interpreter compiled the
4115: definition of @code{word1}, it encountered @code{show-state} whose
1.30 anton 4116: compilation semantics are to append its interpretation semantics to the
1.29 crook 4117: current definition. When you execute @code{word1}, it performs the
1.30 anton 4118: interpretation semantics of @code{show-state}. At the time that @code{word1}
1.29 crook 4119: (and therefore @code{show-state}) are executed, the system is
4120: interpreting.
1.28 crook 4121:
1.30 anton 4122: When you pressed @key{RET} after entering the definition of @code{word2},
1.29 crook 4123: you should have seen the number -1 printed, followed by ``@code{
4124: ok}''. When the text interpreter compiled the definition of
4125: @code{word2}, it encountered @code{show-state-now}, an immediate word,
1.30 anton 4126: whose compilation semantics are therefore to perform its interpretation
1.29 crook 4127: semantics. It is executed straight away (even before the text
4128: interpreter has moved on to process another group of characters; the
4129: @code{;} in this example). The effect of executing it are to display the
4130: value of @code{state} @i{at the time that the definition of}
4131: @code{word2} @i{is being defined}. Printing -1 demonstrates that the
4132: system is compiling at this time. If you execute @code{word2} it does
4133: nothing at all.
1.28 crook 4134:
1.29 crook 4135: @cindex @code{."}, how it works
4136: Before leaving the subject of immediate words, consider the behaviour of
4137: @code{."} in the definition of @code{greet}, in the previous
4138: section. This word is both a parsing word and an immediate word. Notice
4139: that there is a space between @code{."} and the start of the text
4140: @code{Hello and welcome}, but that there is no space between the last
4141: letter of @code{welcome} and the @code{"} character. The reason for this
4142: is that @code{."} is a Forth word; it must have a space after it so that
4143: the text interpreter can identify it. The @code{"} is not a Forth word;
4144: it is a @dfn{delimiter}. The examples earlier show that, when the string
4145: is displayed, there is neither a space before the @code{H} nor after the
4146: @code{e}. Since @code{."} is an immediate word, it executes at the time
4147: that @code{greet} is defined. When it executes, its behaviour is to
4148: search forward in the input line looking for the delimiter. When it
4149: finds the delimiter, it updates @code{>IN} to point past the
4150: delimiter. It also compiles some magic code into the definition of
4151: @code{greet}; the xt of a run-time routine that prints a text string. It
4152: compiles the string @code{Hello and welcome} into memory so that it is
4153: available to be printed later. When the text interpreter gains control,
4154: the next word it finds in the input stream is @code{;} and so it
4155: terminates the definition of @code{greet}.
1.28 crook 4156:
4157:
4158: @comment ----------------------------------------------
1.29 crook 4159: @node Forth is written in Forth, Review - elements of a Forth system, How does that work?, Introduction
4160: @section Forth is written in Forth
4161: @cindex structure of Forth programs
4162:
4163: When you start up a Forth compiler, a large number of definitions
4164: already exist. In Forth, you develop a new application using bottom-up
4165: programming techniques to create new definitions that are defined in
4166: terms of existing definitions. As you create each definition you can
4167: test and debug it interactively.
4168:
4169: If you have tried out the examples in this section, you will probably
4170: have typed them in by hand; when you leave Gforth, your definitions will
4171: be lost. You can avoid this by using a text editor to enter Forth source
4172: code into a file, and then loading code from the file using
1.49 anton 4173: @code{include} (@pxref{Forth source files}). A Forth source file is
1.29 crook 4174: processed by the text interpreter, just as though you had typed it in by
4175: hand@footnote{Actually, there are some subtle differences -- see
4176: @ref{The Text Interpreter}.}.
4177:
4178: Gforth also supports the traditional Forth alternative to using text
1.49 anton 4179: files for program entry (@pxref{Blocks}).
1.28 crook 4180:
1.29 crook 4181: In common with many, if not most, Forth compilers, most of Gforth is
4182: actually written in Forth. All of the @file{.fs} files in the
4183: installation directory@footnote{For example,
1.30 anton 4184: @file{/usr/local/share/gforth...}} are Forth source files, which you can
1.29 crook 4185: study to see examples of Forth programming.
1.28 crook 4186:
1.29 crook 4187: Gforth maintains a history file that records every line that you type to
4188: the text interpreter. This file is preserved between sessions, and is
4189: used to provide a command-line recall facility. If you enter long
4190: definitions by hand, you can use a text editor to paste them out of the
4191: history file into a Forth source file for reuse at a later time
1.49 anton 4192: (for more information @pxref{Command-line editing}).
1.28 crook 4193:
4194:
4195: @comment ----------------------------------------------
1.29 crook 4196: @node Review - elements of a Forth system, Where to go next, Forth is written in Forth, Introduction
4197: @section Review - elements of a Forth system
4198: @cindex elements of a Forth system
1.28 crook 4199:
1.29 crook 4200: To summarise this chapter:
1.28 crook 4201:
4202: @itemize @bullet
4203: @item
1.29 crook 4204: Forth programs use @dfn{factoring} to break a problem down into small
4205: fragments called @dfn{words} or @dfn{definitions}.
4206: @item
4207: Forth program development is an interactive process.
4208: @item
4209: The main command loop that accepts input, and controls both
4210: interpretation and compilation, is called the @dfn{text interpreter}
4211: (also known as the @dfn{outer interpreter}).
4212: @item
4213: Forth has a very simple syntax, consisting of words and numbers
4214: separated by spaces or carriage-return characters. Any additional syntax
4215: is imposed by @dfn{parsing words}.
4216: @item
4217: Forth uses a stack to pass parameters between words. As a result, it
4218: uses postfix notation.
4219: @item
4220: To use a word that has previously been defined, the text interpreter
4221: searches for the word in the @dfn{name dictionary}.
4222: @item
1.30 anton 4223: Words have @dfn{interpretation semantics} and @dfn{compilation semantics}.
1.28 crook 4224: @item
1.29 crook 4225: The text interpreter uses the value of @code{state} to select between
4226: the use of the @dfn{interpretation semantics} and the @dfn{compilation
4227: semantics} of a word that it encounters.
1.28 crook 4228: @item
1.30 anton 4229: The relationship between the @dfn{interpretation semantics} and
4230: @dfn{compilation semantics} for a word
1.29 crook 4231: depend upon the way in which the word was defined (for example, whether
4232: it is an @dfn{immediate} word).
1.28 crook 4233: @item
1.29 crook 4234: Forth definitions can be implemented in Forth (called @dfn{high-level
4235: definitions}) or in some other way (usually a lower-level language and
4236: as a result often called @dfn{low-level definitions}, @dfn{code
4237: definitions} or @dfn{primitives}).
1.28 crook 4238: @item
1.29 crook 4239: Many Forth systems are implemented mainly in Forth.
1.28 crook 4240: @end itemize
4241:
4242:
1.29 crook 4243: @comment ----------------------------------------------
1.48 anton 4244: @node Where to go next, Exercises, Review - elements of a Forth system, Introduction
1.29 crook 4245: @section Where To Go Next
4246: @cindex where to go next
1.28 crook 4247:
1.29 crook 4248: Amazing as it may seem, if you have read (and understood) this far, you
4249: know almost all the fundamentals about the inner workings of a Forth
4250: system. You certainly know enough to be able to read and understand the
4251: rest of this manual and the ANS Forth document, to learn more about the
4252: facilities that Forth in general and Gforth in particular provide. Even
4253: scarier, you know almost enough to implement your own Forth system.
1.30 anton 4254: However, that's not a good idea just yet... better to try writing some
1.29 crook 4255: programs in Gforth.
1.28 crook 4256:
1.29 crook 4257: Forth has such a rich vocabulary that it can be hard to know where to
4258: start in learning it. This section suggests a few sets of words that are
4259: enough to write small but useful programs. Use the word index in this
4260: document to learn more about each word, then try it out and try to write
4261: small definitions using it. Start by experimenting with these words:
1.28 crook 4262:
4263: @itemize @bullet
4264: @item
1.29 crook 4265: Arithmetic: @code{+ - * / /MOD */ ABS INVERT}
4266: @item
4267: Comparison: @code{MIN MAX =}
4268: @item
4269: Logic: @code{AND OR XOR NOT}
4270: @item
4271: Stack manipulation: @code{DUP DROP SWAP OVER}
1.28 crook 4272: @item
1.29 crook 4273: Loops and decisions: @code{IF ELSE ENDIF ?DO I LOOP}
1.28 crook 4274: @item
1.29 crook 4275: Input/Output: @code{. ." EMIT CR KEY}
1.28 crook 4276: @item
1.29 crook 4277: Defining words: @code{: ; CREATE}
1.28 crook 4278: @item
1.29 crook 4279: Memory allocation words: @code{ALLOT ,}
1.28 crook 4280: @item
1.29 crook 4281: Tools: @code{SEE WORDS .S MARKER}
4282: @end itemize
4283:
4284: When you have mastered those, go on to:
4285:
4286: @itemize @bullet
1.28 crook 4287: @item
1.29 crook 4288: More defining words: @code{VARIABLE CONSTANT VALUE TO CREATE DOES>}
1.28 crook 4289: @item
1.29 crook 4290: Memory access: @code{@@ !}
1.28 crook 4291: @end itemize
1.23 crook 4292:
1.29 crook 4293: When you have mastered these, there's nothing for it but to read through
4294: the whole of this manual and find out what you've missed.
4295:
4296: @comment ----------------------------------------------
1.48 anton 4297: @node Exercises, , Where to go next, Introduction
1.29 crook 4298: @section Exercises
4299: @cindex exercises
4300:
4301: TODO: provide a set of programming excercises linked into the stuff done
4302: already and into other sections of the manual. Provide solutions to all
4303: the exercises in a .fs file in the distribution.
4304:
4305: @c Get some inspiration from Starting Forth and Kelly&Spies.
4306:
4307: @c excercises:
4308: @c 1. take inches and convert to feet and inches.
4309: @c 2. take temperature and convert from fahrenheight to celcius;
4310: @c may need to care about symmetric vs floored??
4311: @c 3. take input line and do character substitution
4312: @c to encipher or decipher
4313: @c 4. as above but work on a file for in and out
4314: @c 5. take input line and convert to pig-latin
4315: @c
4316: @c thing of sets of things to exercise then come up with
4317: @c problems that need those things.
4318:
4319:
1.26 crook 4320: @c ******************************************************************
1.29 crook 4321: @node Words, Error messages, Introduction, Top
1.1 anton 4322: @chapter Forth Words
1.26 crook 4323: @cindex words
1.1 anton 4324:
4325: @menu
4326: * Notation::
1.65 anton 4327: * Case insensitivity::
4328: * Comments::
4329: * Boolean Flags::
1.1 anton 4330: * Arithmetic::
4331: * Stack Manipulation::
1.5 anton 4332: * Memory::
1.1 anton 4333: * Control Structures::
4334: * Defining Words::
1.65 anton 4335: * Interpretation and Compilation Semantics::
1.47 crook 4336: * Tokens for Words::
1.65 anton 4337: * The Text Interpreter::
4338: * Word Lists::
4339: * Environmental Queries::
1.12 anton 4340: * Files::
4341: * Blocks::
4342: * Other I/O::
4343: * Programming Tools::
4344: * Assembler and Code Words::
4345: * Threading Words::
1.26 crook 4346: * Locals::
4347: * Structures::
4348: * Object-oriented Forth::
1.65 anton 4349: * Passing Commands to the OS::
4350: * Keeping track of Time::
4351: * Miscellaneous Words::
1.1 anton 4352: @end menu
4353:
1.65 anton 4354: @node Notation, Case insensitivity, Words, Words
1.1 anton 4355: @section Notation
4356: @cindex notation of glossary entries
4357: @cindex format of glossary entries
4358: @cindex glossary notation format
4359: @cindex word glossary entry format
4360:
4361: The Forth words are described in this section in the glossary notation
1.67 anton 4362: that has become a de-facto standard for Forth texts:
1.1 anton 4363:
4364: @format
1.29 crook 4365: @i{word} @i{Stack effect} @i{wordset} @i{pronunciation}
1.1 anton 4366: @end format
1.29 crook 4367: @i{Description}
1.1 anton 4368:
4369: @table @var
4370: @item word
1.28 crook 4371: The name of the word.
1.1 anton 4372:
4373: @item Stack effect
4374: @cindex stack effect
1.29 crook 4375: The stack effect is written in the notation @code{@i{before} --
4376: @i{after}}, where @i{before} and @i{after} describe the top of
1.1 anton 4377: stack entries before and after the execution of the word. The rest of
4378: the stack is not touched by the word. The top of stack is rightmost,
4379: i.e., a stack sequence is written as it is typed in. Note that Gforth
4380: uses a separate floating point stack, but a unified stack
1.29 crook 4381: notation. Also, return stack effects are not shown in @i{stack
4382: effect}, but in @i{Description}. The name of a stack item describes
1.1 anton 4383: the type and/or the function of the item. See below for a discussion of
4384: the types.
4385:
4386: All words have two stack effects: A compile-time stack effect and a
4387: run-time stack effect. The compile-time stack-effect of most words is
1.29 crook 4388: @i{ -- }. If the compile-time stack-effect of a word deviates from
1.1 anton 4389: this standard behaviour, or the word does other unusual things at
4390: compile time, both stack effects are shown; otherwise only the run-time
4391: stack effect is shown.
4392:
4393: @cindex pronounciation of words
4394: @item pronunciation
4395: How the word is pronounced.
4396:
4397: @cindex wordset
1.67 anton 4398: @cindex environment wordset
1.1 anton 4399: @item wordset
1.21 crook 4400: The ANS Forth standard is divided into several word sets. A standard
4401: system need not support all of them. Therefore, in theory, the fewer
4402: word sets your program uses the more portable it will be. However, we
4403: suspect that most ANS Forth systems on personal machines will feature
1.26 crook 4404: all word sets. Words that are not defined in ANS Forth have
1.21 crook 4405: @code{gforth} or @code{gforth-internal} as word set. @code{gforth}
1.1 anton 4406: describes words that will work in future releases of Gforth;
4407: @code{gforth-internal} words are more volatile. Environmental query
4408: strings are also displayed like words; you can recognize them by the
1.21 crook 4409: @code{environment} in the word set field.
1.1 anton 4410:
4411: @item Description
4412: A description of the behaviour of the word.
4413: @end table
4414:
4415: @cindex types of stack items
4416: @cindex stack item types
4417: The type of a stack item is specified by the character(s) the name
4418: starts with:
4419:
4420: @table @code
4421: @item f
4422: @cindex @code{f}, stack item type
4423: Boolean flags, i.e. @code{false} or @code{true}.
4424: @item c
4425: @cindex @code{c}, stack item type
4426: Char
4427: @item w
4428: @cindex @code{w}, stack item type
4429: Cell, can contain an integer or an address
4430: @item n
4431: @cindex @code{n}, stack item type
4432: signed integer
4433: @item u
4434: @cindex @code{u}, stack item type
4435: unsigned integer
4436: @item d
4437: @cindex @code{d}, stack item type
4438: double sized signed integer
4439: @item ud
4440: @cindex @code{ud}, stack item type
4441: double sized unsigned integer
4442: @item r
4443: @cindex @code{r}, stack item type
4444: Float (on the FP stack)
1.21 crook 4445: @item a-
1.1 anton 4446: @cindex @code{a_}, stack item type
4447: Cell-aligned address
1.21 crook 4448: @item c-
1.1 anton 4449: @cindex @code{c_}, stack item type
4450: Char-aligned address (note that a Char may have two bytes in Windows NT)
1.21 crook 4451: @item f-
1.1 anton 4452: @cindex @code{f_}, stack item type
4453: Float-aligned address
1.21 crook 4454: @item df-
1.1 anton 4455: @cindex @code{df_}, stack item type
4456: Address aligned for IEEE double precision float
1.21 crook 4457: @item sf-
1.1 anton 4458: @cindex @code{sf_}, stack item type
4459: Address aligned for IEEE single precision float
4460: @item xt
4461: @cindex @code{xt}, stack item type
4462: Execution token, same size as Cell
4463: @item wid
4464: @cindex @code{wid}, stack item type
1.21 crook 4465: Word list ID, same size as Cell
1.68 ! anton 4466: @item ior, wior
! 4467: @cindex ior type description
! 4468: @cindex wior type description
! 4469: I/O result code, cell-sized. In Gforth, you can @code{throw} iors.
1.1 anton 4470: @item f83name
4471: @cindex @code{f83name}, stack item type
4472: Pointer to a name structure
4473: @item "
4474: @cindex @code{"}, stack item type
1.12 anton 4475: string in the input stream (not on the stack). The terminating character
4476: is a blank by default. If it is not a blank, it is shown in @code{<>}
1.1 anton 4477: quotes.
4478: @end table
4479:
1.65 anton 4480: @comment ----------------------------------------------
4481: @node Case insensitivity, Comments, Notation, Words
4482: @section Case insensitivity
4483: @cindex case sensitivity
4484: @cindex upper and lower case
4485:
4486: Gforth is case-insensitive; you can enter definitions and invoke
4487: Standard words using upper, lower or mixed case (however,
4488: @pxref{core-idef, Implementation-defined options, Implementation-defined
4489: options}).
4490:
4491: ANS Forth only @i{requires} implementations to recognise Standard words
4492: when they are typed entirely in upper case. Therefore, a Standard
4493: program must use upper case for all Standard words. You can use whatever
4494: case you like for words that you define, but in a Standard program you
4495: have to use the words in the same case that you defined them.
4496:
4497: Gforth supports case sensitivity through @code{table}s (case-sensitive
4498: wordlists, @pxref{Word Lists}).
4499:
4500: Two people have asked how to convert Gforth to be case-sensitive; while
4501: we think this is a bad idea, you can change all wordlists into tables
4502: like this:
4503:
4504: @example
4505: ' table-find forth-wordlist wordlist-map @ !
4506: @end example
4507:
4508: Note that you now have to type the predefined words in the same case
4509: that we defined them, which are varying. You may want to convert them
4510: to your favourite case before doing this operation (I won't explain how,
4511: because if you are even contemplating doing this, you'd better have
4512: enough knowledge of Forth systems to know this already).
4513:
4514: @node Comments, Boolean Flags, Case insensitivity, Words
1.21 crook 4515: @section Comments
1.26 crook 4516: @cindex comments
1.21 crook 4517:
1.29 crook 4518: Forth supports two styles of comment; the traditional @i{in-line} comment,
4519: @code{(} and its modern cousin, the @i{comment to end of line}; @code{\}.
1.21 crook 4520:
1.44 crook 4521:
1.23 crook 4522: doc-(
1.21 crook 4523: doc-\
1.23 crook 4524: doc-\G
1.21 crook 4525:
1.44 crook 4526:
1.21 crook 4527: @node Boolean Flags, Arithmetic, Comments, Words
4528: @section Boolean Flags
1.26 crook 4529: @cindex Boolean flags
1.21 crook 4530:
4531: A Boolean flag is cell-sized. A cell with all bits clear represents the
4532: flag @code{false} and a flag with all bits set represents the flag
1.26 crook 4533: @code{true}. Words that check a flag (for example, @code{IF}) will treat
1.29 crook 4534: a cell that has @i{any} bit set as @code{true}.
1.67 anton 4535: @c on and off to Memory?
4536: @c true and false to "Bitwise operations" or "Numeric comparison"?
1.44 crook 4537:
1.21 crook 4538: doc-true
4539: doc-false
1.29 crook 4540: doc-on
4541: doc-off
1.21 crook 4542:
1.44 crook 4543:
1.21 crook 4544: @node Arithmetic, Stack Manipulation, Boolean Flags, Words
1.1 anton 4545: @section Arithmetic
4546: @cindex arithmetic words
4547:
4548: @cindex division with potentially negative operands
4549: Forth arithmetic is not checked, i.e., you will not hear about integer
4550: overflow on addition or multiplication, you may hear about division by
4551: zero if you are lucky. The operator is written after the operands, but
4552: the operands are still in the original order. I.e., the infix @code{2-1}
4553: corresponds to @code{2 1 -}. Forth offers a variety of division
4554: operators. If you perform division with potentially negative operands,
4555: you do not want to use @code{/} or @code{/mod} with its undefined
4556: behaviour, but rather @code{fm/mod} or @code{sm/mod} (probably the
4557: former, @pxref{Mixed precision}).
1.26 crook 4558: @comment TODO discuss the different division forms and the std approach
1.1 anton 4559:
4560: @menu
4561: * Single precision::
1.67 anton 4562: * Double precision:: Double-cell integer arithmetic
1.1 anton 4563: * Bitwise operations::
1.67 anton 4564: * Numeric comparison::
1.29 crook 4565: * Mixed precision:: Operations with single and double-cell integers
1.1 anton 4566: * Floating Point::
4567: @end menu
4568:
1.67 anton 4569: @node Single precision, Double precision, Arithmetic, Arithmetic
1.1 anton 4570: @subsection Single precision
4571: @cindex single precision arithmetic words
4572:
1.67 anton 4573: @c !! cell undefined
4574:
4575: By default, numbers in Forth are single-precision integers that are one
1.26 crook 4576: cell in size. They can be signed or unsigned, depending upon how you
1.49 anton 4577: treat them. For the rules used by the text interpreter for recognising
4578: single-precision integers see @ref{Number Conversion}.
1.21 crook 4579:
1.67 anton 4580: These words are all defined for signed operands, but some of them also
4581: work for unsigned numbers: @code{+}, @code{1+}, @code{-}, @code{1-},
4582: @code{*}.
1.44 crook 4583:
1.1 anton 4584: doc-+
1.21 crook 4585: doc-1+
1.1 anton 4586: doc--
1.21 crook 4587: doc-1-
1.1 anton 4588: doc-*
4589: doc-/
4590: doc-mod
4591: doc-/mod
4592: doc-negate
4593: doc-abs
4594: doc-min
4595: doc-max
1.27 crook 4596: doc-floored
1.1 anton 4597:
1.44 crook 4598:
1.67 anton 4599: @node Double precision, Bitwise operations, Single precision, Arithmetic
1.21 crook 4600: @subsection Double precision
4601: @cindex double precision arithmetic words
4602:
1.49 anton 4603: For the rules used by the text interpreter for
4604: recognising double-precision integers, see @ref{Number Conversion}.
1.21 crook 4605:
4606: A double precision number is represented by a cell pair, with the most
1.67 anton 4607: significant cell at the TOS. It is trivial to convert an unsigned single
4608: to a double: simply push a @code{0} onto the TOS. Since numbers are
4609: represented by Gforth using 2's complement arithmetic, converting a
4610: signed single to a (signed) double requires sign-extension across the
4611: most significant cell. This can be achieved using @code{s>d}. The moral
4612: of the story is that you cannot convert a number without knowing whether
4613: it represents an unsigned or a signed number.
1.21 crook 4614:
1.67 anton 4615: These words are all defined for signed operands, but some of them also
4616: work for unsigned numbers: @code{d+}, @code{d-}.
1.44 crook 4617:
1.21 crook 4618: doc-s>d
1.67 anton 4619: doc-d>s
1.21 crook 4620: doc-d+
4621: doc-d-
4622: doc-dnegate
4623: doc-dabs
4624: doc-dmin
4625: doc-dmax
4626:
1.44 crook 4627:
1.67 anton 4628: @node Bitwise operations, Numeric comparison, Double precision, Arithmetic
4629: @subsection Bitwise operations
4630: @cindex bitwise operation words
4631:
4632:
4633: doc-and
4634: doc-or
4635: doc-xor
4636: doc-invert
4637: doc-lshift
4638: doc-rshift
4639: doc-2*
4640: doc-d2*
4641: doc-2/
4642: doc-d2/
4643:
4644:
4645: @node Numeric comparison, Mixed precision, Bitwise operations, Arithmetic
1.21 crook 4646: @subsection Numeric comparison
4647: @cindex numeric comparison words
4648:
1.67 anton 4649: Note that the words that compare for equality (@code{= <> 0= 0<> d= d<>
4650: d0= d0<>}) work for for both signed and unsigned numbers.
1.44 crook 4651:
1.28 crook 4652: doc-<
4653: doc-<=
4654: doc-<>
4655: doc-=
4656: doc->
4657: doc->=
4658:
1.21 crook 4659: doc-0<
1.23 crook 4660: doc-0<=
1.21 crook 4661: doc-0<>
4662: doc-0=
1.23 crook 4663: doc-0>
4664: doc-0>=
1.28 crook 4665:
4666: doc-u<
4667: doc-u<=
1.44 crook 4668: @c u<> and u= exist but are the same as <> and =
1.31 anton 4669: @c doc-u<>
4670: @c doc-u=
1.28 crook 4671: doc-u>
4672: doc-u>=
4673:
4674: doc-within
4675:
4676: doc-d<
4677: doc-d<=
4678: doc-d<>
4679: doc-d=
4680: doc-d>
4681: doc-d>=
1.23 crook 4682:
1.21 crook 4683: doc-d0<
1.23 crook 4684: doc-d0<=
4685: doc-d0<>
1.21 crook 4686: doc-d0=
1.23 crook 4687: doc-d0>
4688: doc-d0>=
4689:
1.21 crook 4690: doc-du<
1.28 crook 4691: doc-du<=
1.44 crook 4692: @c du<> and du= exist but are the same as d<> and d=
1.31 anton 4693: @c doc-du<>
4694: @c doc-du=
1.28 crook 4695: doc-du>
4696: doc-du>=
1.1 anton 4697:
1.44 crook 4698:
1.21 crook 4699: @node Mixed precision, Floating Point, Numeric comparison, Arithmetic
1.1 anton 4700: @subsection Mixed precision
4701: @cindex mixed precision arithmetic words
4702:
1.44 crook 4703:
1.1 anton 4704: doc-m+
4705: doc-*/
4706: doc-*/mod
4707: doc-m*
4708: doc-um*
4709: doc-m*/
4710: doc-um/mod
4711: doc-fm/mod
4712: doc-sm/rem
4713:
1.44 crook 4714:
1.21 crook 4715: @node Floating Point, , Mixed precision, Arithmetic
1.1 anton 4716: @subsection Floating Point
4717: @cindex floating point arithmetic words
4718:
1.49 anton 4719: For the rules used by the text interpreter for
4720: recognising floating-point numbers see @ref{Number Conversion}.
1.1 anton 4721:
1.67 anton 4722: Gforth has a separate floating point stack, but the documentation uses
4723: the unified notation.@footnote{It's easy to generate the separate
4724: notation from that by just separating the floating-point numbers out:
4725: e.g. @code{( n r1 u r2 -- r3 )} becomes @code{( n u -- ) ( F: r1 r2 --
4726: r3 )}.}
1.1 anton 4727:
4728: @cindex floating-point arithmetic, pitfalls
4729: Floating point numbers have a number of unpleasant surprises for the
4730: unwary (e.g., floating point addition is not associative) and even a few
4731: for the wary. You should not use them unless you know what you are doing
4732: or you don't care that the results you get are totally bogus. If you
4733: want to learn about the problems of floating point numbers (and how to
1.66 anton 4734: avoid them), you might start with @cite{David Goldberg,
4735: @uref{http://www.validgh.com/goldberg/paper.ps,What Every Computer
4736: Scientist Should Know About Floating-Point Arithmetic}, ACM Computing
4737: Surveys 23(1):5@minus{}48, March 1991}.
1.1 anton 4738:
1.44 crook 4739:
1.21 crook 4740: doc-d>f
4741: doc-f>d
1.1 anton 4742: doc-f+
4743: doc-f-
4744: doc-f*
4745: doc-f/
4746: doc-fnegate
4747: doc-fabs
4748: doc-fmax
4749: doc-fmin
4750: doc-floor
4751: doc-fround
4752: doc-f**
4753: doc-fsqrt
4754: doc-fexp
4755: doc-fexpm1
4756: doc-fln
4757: doc-flnp1
4758: doc-flog
4759: doc-falog
1.32 anton 4760: doc-f2*
4761: doc-f2/
4762: doc-1/f
4763: doc-precision
4764: doc-set-precision
4765:
4766: @cindex angles in trigonometric operations
4767: @cindex trigonometric operations
4768: Angles in floating point operations are given in radians (a full circle
4769: has 2 pi radians).
4770:
1.1 anton 4771: doc-fsin
4772: doc-fcos
4773: doc-fsincos
4774: doc-ftan
4775: doc-fasin
4776: doc-facos
4777: doc-fatan
4778: doc-fatan2
4779: doc-fsinh
4780: doc-fcosh
4781: doc-ftanh
4782: doc-fasinh
4783: doc-facosh
4784: doc-fatanh
1.21 crook 4785: doc-pi
1.28 crook 4786:
1.32 anton 4787: @cindex equality of floats
4788: @cindex floating-point comparisons
1.31 anton 4789: One particular problem with floating-point arithmetic is that comparison
4790: for equality often fails when you would expect it to succeed. For this
4791: reason approximate equality is often preferred (but you still have to
1.67 anton 4792: know what you are doing). Also note that IEEE NaNs may compare
1.68 ! anton 4793: differently from what you might expect. The comparison words are:
1.31 anton 4794:
4795: doc-f~rel
4796: doc-f~abs
1.68 ! anton 4797: doc-f~
1.31 anton 4798: doc-f=
4799: doc-f<>
4800:
4801: doc-f<
4802: doc-f<=
4803: doc-f>
4804: doc-f>=
4805:
1.21 crook 4806: doc-f0<
1.28 crook 4807: doc-f0<=
4808: doc-f0<>
1.21 crook 4809: doc-f0=
1.28 crook 4810: doc-f0>
4811: doc-f0>=
4812:
1.1 anton 4813:
4814: @node Stack Manipulation, Memory, Arithmetic, Words
4815: @section Stack Manipulation
4816: @cindex stack manipulation words
4817:
4818: @cindex floating-point stack in the standard
1.21 crook 4819: Gforth maintains a number of separate stacks:
4820:
1.29 crook 4821: @cindex data stack
4822: @cindex parameter stack
1.21 crook 4823: @itemize @bullet
4824: @item
1.29 crook 4825: A data stack (also known as the @dfn{parameter stack}) -- for
4826: characters, cells, addresses, and double cells.
1.21 crook 4827:
1.29 crook 4828: @cindex floating-point stack
1.21 crook 4829: @item
1.44 crook 4830: A floating point stack -- for holding floating point (FP) numbers.
1.21 crook 4831:
1.29 crook 4832: @cindex return stack
1.21 crook 4833: @item
1.44 crook 4834: A return stack -- for holding the return addresses of colon
1.32 anton 4835: definitions and other (non-FP) data.
1.21 crook 4836:
1.29 crook 4837: @cindex locals stack
1.21 crook 4838: @item
1.44 crook 4839: A locals stack -- for holding local variables.
1.21 crook 4840: @end itemize
4841:
1.1 anton 4842: @menu
4843: * Data stack::
4844: * Floating point stack::
4845: * Return stack::
4846: * Locals stack::
4847: * Stack pointer manipulation::
4848: @end menu
4849:
4850: @node Data stack, Floating point stack, Stack Manipulation, Stack Manipulation
4851: @subsection Data stack
4852: @cindex data stack manipulation words
4853: @cindex stack manipulations words, data stack
4854:
1.44 crook 4855:
1.1 anton 4856: doc-drop
4857: doc-nip
4858: doc-dup
4859: doc-over
4860: doc-tuck
4861: doc-swap
1.21 crook 4862: doc-pick
1.1 anton 4863: doc-rot
4864: doc--rot
4865: doc-?dup
4866: doc-roll
4867: doc-2drop
4868: doc-2nip
4869: doc-2dup
4870: doc-2over
4871: doc-2tuck
4872: doc-2swap
4873: doc-2rot
4874:
1.44 crook 4875:
1.1 anton 4876: @node Floating point stack, Return stack, Data stack, Stack Manipulation
4877: @subsection Floating point stack
4878: @cindex floating-point stack manipulation words
4879: @cindex stack manipulation words, floating-point stack
4880:
1.32 anton 4881: Whilst every sane Forth has a separate floating-point stack, it is not
4882: strictly required; an ANS Forth system could theoretically keep
4883: floating-point numbers on the data stack. As an additional difficulty,
4884: you don't know how many cells a floating-point number takes. It is
4885: reportedly possible to write words in a way that they work also for a
4886: unified stack model, but we do not recommend trying it. Instead, just
4887: say that your program has an environmental dependency on a separate
4888: floating-point stack.
4889:
4890: doc-floating-stack
4891:
1.1 anton 4892: doc-fdrop
4893: doc-fnip
4894: doc-fdup
4895: doc-fover
4896: doc-ftuck
4897: doc-fswap
1.21 crook 4898: doc-fpick
1.1 anton 4899: doc-frot
4900:
1.44 crook 4901:
1.1 anton 4902: @node Return stack, Locals stack, Floating point stack, Stack Manipulation
4903: @subsection Return stack
4904: @cindex return stack manipulation words
4905: @cindex stack manipulation words, return stack
4906:
1.32 anton 4907: @cindex return stack and locals
4908: @cindex locals and return stack
4909: A Forth system is allowed to keep local variables on the
4910: return stack. This is reasonable, as local variables usually eliminate
4911: the need to use the return stack explicitly. So, if you want to produce
4912: a standard compliant program and you are using local variables in a
4913: word, forget about return stack manipulations in that word (refer to the
4914: standard document for the exact rules).
4915:
1.1 anton 4916: doc->r
4917: doc-r>
4918: doc-r@
4919: doc-rdrop
4920: doc-2>r
4921: doc-2r>
4922: doc-2r@
4923: doc-2rdrop
4924:
1.44 crook 4925:
1.1 anton 4926: @node Locals stack, Stack pointer manipulation, Return stack, Stack Manipulation
4927: @subsection Locals stack
4928:
1.47 crook 4929: Gforth uses an extra locals stack. It is described, along with the
4930: reasons for its existence, in @ref{Implementation,Implementation of locals}.
1.21 crook 4931:
1.1 anton 4932: @node Stack pointer manipulation, , Locals stack, Stack Manipulation
4933: @subsection Stack pointer manipulation
4934: @cindex stack pointer manipulation words
4935:
1.44 crook 4936: @c removed s0 r0 l0 -- they are obsolete aliases for sp0 rp0 lp0
1.21 crook 4937: doc-sp0
1.1 anton 4938: doc-sp@
4939: doc-sp!
1.21 crook 4940: doc-fp0
1.1 anton 4941: doc-fp@
4942: doc-fp!
1.21 crook 4943: doc-rp0
1.1 anton 4944: doc-rp@
4945: doc-rp!
1.21 crook 4946: doc-lp0
1.1 anton 4947: doc-lp@
4948: doc-lp!
4949:
1.44 crook 4950:
1.1 anton 4951: @node Memory, Control Structures, Stack Manipulation, Words
4952: @section Memory
1.26 crook 4953: @cindex memory words
1.1 anton 4954:
1.32 anton 4955: @menu
4956: * Memory model::
4957: * Dictionary allocation::
4958: * Heap Allocation::
4959: * Memory Access::
4960: * Address arithmetic::
4961: * Memory Blocks::
4962: @end menu
4963:
1.67 anton 4964: In addition to the standard Forth memory allocation words, there is also
4965: a @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
4966: garbage collector}.
4967:
1.32 anton 4968: @node Memory model, Dictionary allocation, Memory, Memory
4969: @subsection ANS Forth and Gforth memory models
4970:
4971: @c The ANS Forth description is a mess (e.g., is the heap part of
4972: @c the dictionary?), so let's not stick to closely with it.
4973:
1.67 anton 4974: ANS Forth considers a Forth system as consisting of several address
4975: spaces, of which only @dfn{data space} is managed and accessible with
4976: the memory words. Memory not necessarily in data space includes the
4977: stacks, the code (called code space) and the headers (called name
4978: space). In Gforth everything is in data space, but the code for the
4979: primitives is usually read-only.
1.32 anton 4980:
4981: Data space is divided into a number of areas: The (data space portion of
4982: the) dictionary@footnote{Sometimes, the term @dfn{dictionary} is used to
4983: refer to the search data structure embodied in word lists and headers,
4984: because it is used for looking up names, just as you would in a
4985: conventional dictionary.}, the heap, and a number of system-allocated
4986: buffers.
4987:
1.68 ! anton 4988: @cindex address arithmetic restrictions, ANS vs. Gforth
! 4989: @cindex contiguous regions, ANS vs. Gforth
1.32 anton 4990: In ANS Forth data space is also divided into contiguous regions. You
4991: can only use address arithmetic within a contiguous region, not between
4992: them. Usually each allocation gives you one contiguous region, but the
1.33 anton 4993: dictionary allocation words have additional rules (@pxref{Dictionary
1.32 anton 4994: allocation}).
4995:
4996: Gforth provides one big address space, and address arithmetic can be
4997: performed between any addresses. However, in the dictionary headers or
4998: code are interleaved with data, so almost the only contiguous data space
4999: regions there are those described by ANS Forth as contiguous; but you
5000: can be sure that the dictionary is allocated towards increasing
5001: addresses even between contiguous regions. The memory order of
5002: allocations in the heap is platform-dependent (and possibly different
5003: from one run to the next).
5004:
1.27 crook 5005:
1.32 anton 5006: @node Dictionary allocation, Heap Allocation, Memory model, Memory
5007: @subsection Dictionary allocation
1.27 crook 5008: @cindex reserving data space
5009: @cindex data space - reserving some
5010:
1.32 anton 5011: Dictionary allocation is a stack-oriented allocation scheme, i.e., if
5012: you want to deallocate X, you also deallocate everything
5013: allocated after X.
5014:
1.68 ! anton 5015: @cindex contiguous regions in dictionary allocation
1.32 anton 5016: The allocations using the words below are contiguous and grow the region
5017: towards increasing addresses. Other words that allocate dictionary
5018: memory of any kind (i.e., defining words including @code{:noname}) end
5019: the contiguous region and start a new one.
5020:
5021: In ANS Forth only @code{create}d words are guaranteed to produce an
5022: address that is the start of the following contiguous region. In
5023: particular, the cell allocated by @code{variable} is not guaranteed to
5024: be contiguous with following @code{allot}ed memory.
5025:
5026: You can deallocate memory by using @code{allot} with a negative argument
5027: (with some restrictions, see @code{allot}). For larger deallocations use
5028: @code{marker}.
1.27 crook 5029:
1.29 crook 5030:
1.27 crook 5031: doc-here
5032: doc-unused
5033: doc-allot
5034: doc-c,
1.29 crook 5035: doc-f,
1.27 crook 5036: doc-,
5037: doc-2,
5038:
1.32 anton 5039: Memory accesses have to be aligned (@pxref{Address arithmetic}). So of
5040: course you should allocate memory in an aligned way, too. I.e., before
5041: allocating allocating a cell, @code{here} must be cell-aligned, etc.
5042: The words below align @code{here} if it is not already. Basically it is
5043: only already aligned for a type, if the last allocation was a multiple
5044: of the size of this type and if @code{here} was aligned for this type
5045: before.
5046:
5047: After freshly @code{create}ing a word, @code{here} is @code{align}ed in
5048: ANS Forth (@code{maxalign}ed in Gforth).
5049:
5050: doc-align
5051: doc-falign
5052: doc-sfalign
5053: doc-dfalign
5054: doc-maxalign
5055: doc-cfalign
5056:
5057:
5058: @node Heap Allocation, Memory Access, Dictionary allocation, Memory
5059: @subsection Heap allocation
5060: @cindex heap allocation
5061: @cindex dynamic allocation of memory
5062: @cindex memory-allocation word set
5063:
1.68 ! anton 5064: @cindex contiguous regions and heap allocation
1.32 anton 5065: Heap allocation supports deallocation of allocated memory in any
5066: order. Dictionary allocation is not affected by it (i.e., it does not
5067: end a contiguous region). In Gforth, these words are implemented using
5068: the standard C library calls malloc(), free() and resize().
5069:
1.68 ! anton 5070: The memory region produced by one invocation of @code{allocate} or
! 5071: @code{resize} is internally contiguous. There is no contiguity between
! 5072: such a region and any other region (including others allocated from the
! 5073: heap).
! 5074:
1.32 anton 5075: doc-allocate
5076: doc-free
5077: doc-resize
5078:
1.27 crook 5079:
1.32 anton 5080: @node Memory Access, Address arithmetic, Heap Allocation, Memory
1.1 anton 5081: @subsection Memory Access
5082: @cindex memory access words
5083:
5084: doc-@
5085: doc-!
5086: doc-+!
5087: doc-c@
5088: doc-c!
5089: doc-2@
5090: doc-2!
5091: doc-f@
5092: doc-f!
5093: doc-sf@
5094: doc-sf!
5095: doc-df@
5096: doc-df!
5097:
1.68 ! anton 5098:
1.32 anton 5099: @node Address arithmetic, Memory Blocks, Memory Access, Memory
5100: @subsection Address arithmetic
1.1 anton 5101: @cindex address arithmetic words
5102:
1.67 anton 5103: Address arithmetic is the foundation on which you can build data
5104: structures like arrays, records (@pxref{Structures}) and objects
5105: (@pxref{Object-oriented Forth}).
1.32 anton 5106:
1.68 ! anton 5107: @cindex address unit
! 5108: @cindex au (address unit)
1.1 anton 5109: ANS Forth does not specify the sizes of the data types. Instead, it
5110: offers a number of words for computing sizes and doing address
1.29 crook 5111: arithmetic. Address arithmetic is performed in terms of address units
5112: (aus); on most systems the address unit is one byte. Note that a
5113: character may have more than one au, so @code{chars} is no noop (on
1.68 ! anton 5114: platforms where it is a noop, it compiles to nothing).
1.1 anton 5115:
1.67 anton 5116: The basic address arithmetic words are @code{+} and @code{-}. E.g., if
5117: you have the address of a cell, perform @code{1 cells +}, and you will
5118: have the address of the next cell.
5119:
1.68 ! anton 5120: @cindex contiguous regions and address arithmetic
1.67 anton 5121: In ANS Forth you can perform address arithmetic only within a contiguous
5122: region, i.e., if you have an address into one region, you can only add
5123: and subtract such that the result is still within the region; you can
5124: only subtract or compare addresses from within the same contiguous
5125: region. Reasons: several contiguous regions can be arranged in memory
5126: in any way; on segmented systems addresses may have unusual
5127: representations, such that address arithmetic only works within a
5128: region. Gforth provides a few more guarantees (linear address space,
5129: dictionary grows upwards), but in general I have found it easy to stay
5130: within contiguous regions (exception: computing and comparing to the
5131: address just beyond the end of an array).
5132:
1.1 anton 5133: @cindex alignment of addresses for types
5134: ANS Forth also defines words for aligning addresses for specific
5135: types. Many computers require that accesses to specific data types
5136: must only occur at specific addresses; e.g., that cells may only be
5137: accessed at addresses divisible by 4. Even if a machine allows unaligned
5138: accesses, it can usually perform aligned accesses faster.
5139:
5140: For the performance-conscious: alignment operations are usually only
5141: necessary during the definition of a data structure, not during the
5142: (more frequent) accesses to it.
5143:
5144: ANS Forth defines no words for character-aligning addresses. This is not
5145: an oversight, but reflects the fact that addresses that are not
5146: char-aligned have no use in the standard and therefore will not be
5147: created.
5148:
5149: @cindex @code{CREATE} and alignment
1.29 crook 5150: ANS Forth guarantees that addresses returned by @code{CREATE}d words
1.1 anton 5151: are cell-aligned; in addition, Gforth guarantees that these addresses
5152: are aligned for all purposes.
5153:
1.26 crook 5154: Note that the ANS Forth word @code{char} has nothing to do with address
5155: arithmetic.
1.1 anton 5156:
1.44 crook 5157:
1.1 anton 5158: doc-chars
5159: doc-char+
5160: doc-cells
5161: doc-cell+
5162: doc-cell
5163: doc-aligned
5164: doc-floats
5165: doc-float+
5166: doc-float
5167: doc-faligned
5168: doc-sfloats
5169: doc-sfloat+
5170: doc-sfaligned
5171: doc-dfloats
5172: doc-dfloat+
5173: doc-dfaligned
5174: doc-maxaligned
5175: doc-cfaligned
5176: doc-address-unit-bits
5177:
1.44 crook 5178:
1.32 anton 5179: @node Memory Blocks, , Address arithmetic, Memory
1.1 anton 5180: @subsection Memory Blocks
5181: @cindex memory block words
1.27 crook 5182: @cindex character strings - moving and copying
5183:
1.49 anton 5184: Memory blocks often represent character strings; For ways of storing
5185: character strings in memory see @ref{String Formats}. For other
5186: string-processing words see @ref{Displaying characters and strings}.
1.1 anton 5187:
1.67 anton 5188: A few of these words work on address unit blocks. In that case, you
5189: usually have to insert @code{CHARS} before the word when working on
5190: character strings. Most words work on character blocks, and expect a
5191: char-aligned address.
5192:
5193: When copying characters between overlapping memory regions, use
5194: @code{chars move} or choose carefully between @code{cmove} and
5195: @code{cmove>}.
1.44 crook 5196:
1.1 anton 5197: doc-move
5198: doc-erase
5199: doc-cmove
5200: doc-cmove>
5201: doc-fill
5202: doc-blank
1.21 crook 5203: doc-compare
5204: doc-search
1.27 crook 5205: doc--trailing
5206: doc-/string
5207:
1.44 crook 5208:
1.27 crook 5209: @comment TODO examples
5210:
1.1 anton 5211:
1.26 crook 5212: @node Control Structures, Defining Words, Memory, Words
1.1 anton 5213: @section Control Structures
5214: @cindex control structures
5215:
1.33 anton 5216: Control structures in Forth cannot be used interpretively, only in a
5217: colon definition@footnote{To be precise, they have no interpretation
5218: semantics (@pxref{Interpretation and Compilation Semantics}).}. We do
5219: not like this limitation, but have not seen a satisfying way around it
5220: yet, although many schemes have been proposed.
1.1 anton 5221:
5222: @menu
1.33 anton 5223: * Selection:: IF ... ELSE ... ENDIF
5224: * Simple Loops:: BEGIN ...
1.29 crook 5225: * Counted Loops:: DO
1.67 anton 5226: * Arbitrary control structures::
5227: * Calls and returns::
1.1 anton 5228: * Exception Handling::
5229: @end menu
5230:
5231: @node Selection, Simple Loops, Control Structures, Control Structures
5232: @subsection Selection
5233: @cindex selection control structures
5234: @cindex control structures for selection
5235:
1.33 anton 5236: @c what's the purpose of all these @i? Maybe we should define a macro
5237: @c so we can produce logical markup. - anton
5238:
1.44 crook 5239: @c nac-> When I started working on the manual, a mixture of @i and @var
5240: @c were used inconsistently in code examples and \Glossary entries. These
5241: @c two behave differently in info format so I decided to standardize on @i.
5242: @c Logical markup would be better but texi isn't really upto it, and
5243: @c texi2html just ignores macros.
1.47 crook 5244: @c nac02dec1999-> update: the latest texinfo release can spit out html
5245: @c and it handles macros, so we could do some logical markup. Unfortunately
5246: @c texinfo will not split html output, which would be a big pain if you
5247: @c wanted to put the document on the web, which would be nice.
1.44 crook 5248:
1.1 anton 5249: @cindex @code{IF} control structure
5250: @example
1.29 crook 5251: @i{flag}
1.1 anton 5252: IF
1.29 crook 5253: @i{code}
1.1 anton 5254: ENDIF
5255: @end example
1.21 crook 5256: @noindent
1.33 anton 5257:
1.44 crook 5258: If @i{flag} is non-zero (as far as @code{IF} etc. are concerned, a cell
5259: with any bit set represents truth) @i{code} is executed.
1.33 anton 5260:
1.1 anton 5261: @example
1.29 crook 5262: @i{flag}
1.1 anton 5263: IF
1.29 crook 5264: @i{code1}
1.1 anton 5265: ELSE
1.29 crook 5266: @i{code2}
1.1 anton 5267: ENDIF
5268: @end example
5269:
1.44 crook 5270: If @var{flag} is true, @i{code1} is executed, otherwise @i{code2} is
5271: executed.
1.33 anton 5272:
1.1 anton 5273: You can use @code{THEN} instead of @code{ENDIF}. Indeed, @code{THEN} is
5274: standard, and @code{ENDIF} is not, although it is quite popular. We
5275: recommend using @code{ENDIF}, because it is less confusing for people
5276: who also know other languages (and is not prone to reinforcing negative
5277: prejudices against Forth in these people). Adding @code{ENDIF} to a
5278: system that only supplies @code{THEN} is simple:
5279: @example
1.21 crook 5280: : ENDIF POSTPONE THEN ; immediate
1.1 anton 5281: @end example
5282:
5283: [According to @cite{Webster's New Encyclopedic Dictionary}, @dfn{then
5284: (adv.)} has the following meanings:
5285: @quotation
5286: ... 2b: following next after in order ... 3d: as a necessary consequence
5287: (if you were there, then you saw them).
5288: @end quotation
5289: Forth's @code{THEN} has the meaning 2b, whereas @code{THEN} in Pascal
5290: and many other programming languages has the meaning 3d.]
5291:
1.21 crook 5292: Gforth also provides the words @code{?DUP-IF} and @code{?DUP-0=-IF}, so
1.1 anton 5293: you can avoid using @code{?dup}. Using these alternatives is also more
1.26 crook 5294: efficient than using @code{?dup}. Definitions in ANS Forth
1.1 anton 5295: for @code{ENDIF}, @code{?DUP-IF} and @code{?DUP-0=-IF} are provided in
5296: @file{compat/control.fs}.
5297:
5298: @cindex @code{CASE} control structure
5299: @example
1.29 crook 5300: @i{n}
1.1 anton 5301: CASE
1.29 crook 5302: @i{n1} OF @i{code1} ENDOF
5303: @i{n2} OF @i{code2} ENDOF
1.1 anton 5304: @dots{}
1.68 ! anton 5305: ( n ) @i{default-code} ( n )
1.1 anton 5306: ENDCASE
5307: @end example
5308:
1.68 ! anton 5309: Executes the first @i{codei}, where the @i{ni} is equal to @i{n}. If no
! 5310: @i{ni} matches, the optional @i{default-code} is executed. The optional
! 5311: default case can be added by simply writing the code after the last
! 5312: @code{ENDOF}. It may use @i{n}, which is on top of the stack, but must
! 5313: not consume it.
1.1 anton 5314:
5315: @node Simple Loops, Counted Loops, Selection, Control Structures
5316: @subsection Simple Loops
5317: @cindex simple loops
5318: @cindex loops without count
5319:
5320: @cindex @code{WHILE} loop
5321: @example
5322: BEGIN
1.29 crook 5323: @i{code1}
5324: @i{flag}
1.1 anton 5325: WHILE
1.29 crook 5326: @i{code2}
1.1 anton 5327: REPEAT
5328: @end example
5329:
1.29 crook 5330: @i{code1} is executed and @i{flag} is computed. If it is true,
5331: @i{code2} is executed and the loop is restarted; If @i{flag} is
1.1 anton 5332: false, execution continues after the @code{REPEAT}.
5333:
5334: @cindex @code{UNTIL} loop
5335: @example
5336: BEGIN
1.29 crook 5337: @i{code}
5338: @i{flag}
1.1 anton 5339: UNTIL
5340: @end example
5341:
1.29 crook 5342: @i{code} is executed. The loop is restarted if @code{flag} is false.
1.1 anton 5343:
5344: @cindex endless loop
5345: @cindex loops, endless
5346: @example
5347: BEGIN
1.29 crook 5348: @i{code}
1.1 anton 5349: AGAIN
5350: @end example
5351:
5352: This is an endless loop.
5353:
5354: @node Counted Loops, Arbitrary control structures, Simple Loops, Control Structures
5355: @subsection Counted Loops
5356: @cindex counted loops
5357: @cindex loops, counted
5358: @cindex @code{DO} loops
5359:
5360: The basic counted loop is:
5361: @example
1.29 crook 5362: @i{limit} @i{start}
1.1 anton 5363: ?DO
1.29 crook 5364: @i{body}
1.1 anton 5365: LOOP
5366: @end example
5367:
1.29 crook 5368: This performs one iteration for every integer, starting from @i{start}
5369: and up to, but excluding @i{limit}. The counter, or @i{index}, can be
1.21 crook 5370: accessed with @code{i}. For example, the loop:
1.1 anton 5371: @example
5372: 10 0 ?DO
5373: i .
5374: LOOP
5375: @end example
1.21 crook 5376: @noindent
5377: prints @code{0 1 2 3 4 5 6 7 8 9}
5378:
1.1 anton 5379: The index of the innermost loop can be accessed with @code{i}, the index
5380: of the next loop with @code{j}, and the index of the third loop with
5381: @code{k}.
5382:
1.44 crook 5383:
1.1 anton 5384: doc-i
5385: doc-j
5386: doc-k
5387:
1.44 crook 5388:
1.1 anton 5389: The loop control data are kept on the return stack, so there are some
1.21 crook 5390: restrictions on mixing return stack accesses and counted loop words. In
5391: particuler, if you put values on the return stack outside the loop, you
5392: cannot read them inside the loop@footnote{well, not in a way that is
5393: portable.}. If you put values on the return stack within a loop, you
5394: have to remove them before the end of the loop and before accessing the
5395: index of the loop.
1.1 anton 5396:
5397: There are several variations on the counted loop:
5398:
1.21 crook 5399: @itemize @bullet
5400: @item
5401: @code{LEAVE} leaves the innermost counted loop immediately; execution
5402: continues after the associated @code{LOOP} or @code{NEXT}. For example:
5403:
5404: @example
5405: 10 0 ?DO i DUP . 3 = IF LEAVE THEN LOOP
5406: @end example
5407: prints @code{0 1 2 3}
5408:
1.1 anton 5409:
1.21 crook 5410: @item
5411: @code{UNLOOP} prepares for an abnormal loop exit, e.g., via
5412: @code{EXIT}. @code{UNLOOP} removes the loop control parameters from the
5413: return stack so @code{EXIT} can get to its return address. For example:
5414:
5415: @example
5416: : demo 10 0 ?DO i DUP . 3 = IF UNLOOP EXIT THEN LOOP ." Done" ;
5417: @end example
5418: prints @code{0 1 2 3}
5419:
5420:
5421: @item
1.29 crook 5422: If @i{start} is greater than @i{limit}, a @code{?DO} loop is entered
1.1 anton 5423: (and @code{LOOP} iterates until they become equal by wrap-around
5424: arithmetic). This behaviour is usually not what you want. Therefore,
5425: Gforth offers @code{+DO} and @code{U+DO} (as replacements for
1.29 crook 5426: @code{?DO}), which do not enter the loop if @i{start} is greater than
5427: @i{limit}; @code{+DO} is for signed loop parameters, @code{U+DO} for
1.1 anton 5428: unsigned loop parameters.
5429:
1.21 crook 5430: @item
5431: @code{?DO} can be replaced by @code{DO}. @code{DO} always enters
5432: the loop, independent of the loop parameters. Do not use @code{DO}, even
5433: if you know that the loop is entered in any case. Such knowledge tends
5434: to become invalid during maintenance of a program, and then the
5435: @code{DO} will make trouble.
5436:
5437: @item
1.29 crook 5438: @code{LOOP} can be replaced with @code{@i{n} +LOOP}; this updates the
5439: index by @i{n} instead of by 1. The loop is terminated when the border
5440: between @i{limit-1} and @i{limit} is crossed. E.g.:
1.1 anton 5441:
1.21 crook 5442: @example
5443: 4 0 +DO i . 2 +LOOP
5444: @end example
5445: @noindent
5446: prints @code{0 2}
5447:
5448: @example
5449: 4 1 +DO i . 2 +LOOP
5450: @end example
5451: @noindent
5452: prints @code{1 3}
1.1 anton 5453:
1.68 ! anton 5454: @item
1.1 anton 5455: @cindex negative increment for counted loops
5456: @cindex counted loops with negative increment
1.29 crook 5457: The behaviour of @code{@i{n} +LOOP} is peculiar when @i{n} is negative:
1.1 anton 5458:
1.21 crook 5459: @example
5460: -1 0 ?DO i . -1 +LOOP
5461: @end example
5462: @noindent
5463: prints @code{0 -1}
1.1 anton 5464:
1.21 crook 5465: @example
5466: 0 0 ?DO i . -1 +LOOP
5467: @end example
5468: prints nothing.
1.1 anton 5469:
1.29 crook 5470: Therefore we recommend avoiding @code{@i{n} +LOOP} with negative
5471: @i{n}. One alternative is @code{@i{u} -LOOP}, which reduces the
5472: index by @i{u} each iteration. The loop is terminated when the border
5473: between @i{limit+1} and @i{limit} is crossed. Gforth also provides
1.1 anton 5474: @code{-DO} and @code{U-DO} for down-counting loops. E.g.:
5475:
1.21 crook 5476: @example
5477: -2 0 -DO i . 1 -LOOP
5478: @end example
5479: @noindent
5480: prints @code{0 -1}
1.1 anton 5481:
1.21 crook 5482: @example
5483: -1 0 -DO i . 1 -LOOP
5484: @end example
5485: @noindent
5486: prints @code{0}
5487:
5488: @example
5489: 0 0 -DO i . 1 -LOOP
5490: @end example
5491: @noindent
5492: prints nothing.
1.1 anton 5493:
1.21 crook 5494: @end itemize
1.1 anton 5495:
5496: Unfortunately, @code{+DO}, @code{U+DO}, @code{-DO}, @code{U-DO} and
1.26 crook 5497: @code{-LOOP} are not defined in ANS Forth. However, an implementation
5498: for these words that uses only standard words is provided in
5499: @file{compat/loops.fs}.
1.1 anton 5500:
5501:
5502: @cindex @code{FOR} loops
1.26 crook 5503: Another counted loop is:
1.1 anton 5504: @example
1.29 crook 5505: @i{n}
1.1 anton 5506: FOR
1.29 crook 5507: @i{body}
1.1 anton 5508: NEXT
5509: @end example
5510: This is the preferred loop of native code compiler writers who are too
1.26 crook 5511: lazy to optimize @code{?DO} loops properly. This loop structure is not
1.29 crook 5512: defined in ANS Forth. In Gforth, this loop iterates @i{n+1} times;
5513: @code{i} produces values starting with @i{n} and ending with 0. Other
1.26 crook 5514: Forth systems may behave differently, even if they support @code{FOR}
5515: loops. To avoid problems, don't use @code{FOR} loops.
1.1 anton 5516:
5517: @node Arbitrary control structures, Calls and returns, Counted Loops, Control Structures
5518: @subsection Arbitrary control structures
5519: @cindex control structures, user-defined
5520:
5521: @cindex control-flow stack
5522: ANS Forth permits and supports using control structures in a non-nested
5523: way. Information about incomplete control structures is stored on the
5524: control-flow stack. This stack may be implemented on the Forth data
5525: stack, and this is what we have done in Gforth.
5526:
5527: @cindex @code{orig}, control-flow stack item
5528: @cindex @code{dest}, control-flow stack item
5529: An @i{orig} entry represents an unresolved forward branch, a @i{dest}
5530: entry represents a backward branch target. A few words are the basis for
5531: building any control structure possible (except control structures that
5532: need storage, like calls, coroutines, and backtracking).
5533:
1.44 crook 5534:
1.1 anton 5535: doc-if
5536: doc-ahead
5537: doc-then
5538: doc-begin
5539: doc-until
5540: doc-again
5541: doc-cs-pick
5542: doc-cs-roll
5543:
1.44 crook 5544:
1.21 crook 5545: The Standard words @code{CS-PICK} and @code{CS-ROLL} allow you to
5546: manipulate the control-flow stack in a portable way. Without them, you
5547: would need to know how many stack items are occupied by a control-flow
5548: entry (many systems use one cell. In Gforth they currently take three,
5549: but this may change in the future).
5550:
1.1 anton 5551: Some standard control structure words are built from these words:
5552:
1.44 crook 5553:
1.1 anton 5554: doc-else
5555: doc-while
5556: doc-repeat
5557:
1.44 crook 5558:
5559: @noindent
1.1 anton 5560: Gforth adds some more control-structure words:
5561:
1.44 crook 5562:
1.1 anton 5563: doc-endif
5564: doc-?dup-if
5565: doc-?dup-0=-if
5566:
1.44 crook 5567:
5568: @noindent
1.1 anton 5569: Counted loop words constitute a separate group of words:
5570:
1.44 crook 5571:
1.1 anton 5572: doc-?do
5573: doc-+do
5574: doc-u+do
5575: doc--do
5576: doc-u-do
5577: doc-do
5578: doc-for
5579: doc-loop
5580: doc-+loop
5581: doc--loop
5582: doc-next
5583: doc-leave
5584: doc-?leave
5585: doc-unloop
5586: doc-done
5587:
1.44 crook 5588:
1.21 crook 5589: The standard does not allow using @code{CS-PICK} and @code{CS-ROLL} on
5590: @i{do-sys}. Gforth allows it, but it's your job to ensure that for
1.1 anton 5591: every @code{?DO} etc. there is exactly one @code{UNLOOP} on any path
5592: through the definition (@code{LOOP} etc. compile an @code{UNLOOP} on the
5593: fall-through path). Also, you have to ensure that all @code{LEAVE}s are
5594: resolved (by using one of the loop-ending words or @code{DONE}).
5595:
1.44 crook 5596: @noindent
1.26 crook 5597: Another group of control structure words are:
1.1 anton 5598:
1.44 crook 5599:
1.1 anton 5600: doc-case
5601: doc-endcase
5602: doc-of
5603: doc-endof
5604:
1.44 crook 5605:
1.21 crook 5606: @i{case-sys} and @i{of-sys} cannot be processed using @code{CS-PICK} and
5607: @code{CS-ROLL}.
1.1 anton 5608:
5609: @subsubsection Programming Style
1.47 crook 5610: @cindex control structures programming style
5611: @cindex programming style, arbitrary control structures
1.1 anton 5612:
5613: In order to ensure readability we recommend that you do not create
5614: arbitrary control structures directly, but define new control structure
5615: words for the control structure you want and use these words in your
1.26 crook 5616: program. For example, instead of writing:
1.1 anton 5617:
5618: @example
1.26 crook 5619: BEGIN
1.1 anton 5620: ...
1.26 crook 5621: IF [ 1 CS-ROLL ]
1.1 anton 5622: ...
1.26 crook 5623: AGAIN THEN
1.1 anton 5624: @end example
5625:
1.21 crook 5626: @noindent
1.1 anton 5627: we recommend defining control structure words, e.g.,
5628:
5629: @example
1.26 crook 5630: : WHILE ( DEST -- ORIG DEST )
5631: POSTPONE IF
5632: 1 CS-ROLL ; immediate
5633:
5634: : REPEAT ( orig dest -- )
5635: POSTPONE AGAIN
5636: POSTPONE THEN ; immediate
1.1 anton 5637: @end example
5638:
1.21 crook 5639: @noindent
1.1 anton 5640: and then using these to create the control structure:
5641:
5642: @example
1.26 crook 5643: BEGIN
1.1 anton 5644: ...
1.26 crook 5645: WHILE
1.1 anton 5646: ...
1.26 crook 5647: REPEAT
1.1 anton 5648: @end example
5649:
5650: That's much easier to read, isn't it? Of course, @code{REPEAT} and
5651: @code{WHILE} are predefined, so in this example it would not be
5652: necessary to define them.
5653:
5654: @node Calls and returns, Exception Handling, Arbitrary control structures, Control Structures
5655: @subsection Calls and returns
5656: @cindex calling a definition
5657: @cindex returning from a definition
5658:
1.3 anton 5659: @cindex recursive definitions
5660: A definition can be called simply be writing the name of the definition
1.26 crook 5661: to be called. Normally a definition is invisible during its own
1.3 anton 5662: definition. If you want to write a directly recursive definition, you
1.26 crook 5663: can use @code{recursive} to make the current definition visible, or
5664: @code{recurse} to call the current definition directly.
1.3 anton 5665:
1.44 crook 5666:
1.3 anton 5667: doc-recursive
5668: doc-recurse
5669:
1.44 crook 5670:
1.21 crook 5671: @comment TODO add example of the two recursion methods
1.12 anton 5672: @quotation
5673: @progstyle
5674: I prefer using @code{recursive} to @code{recurse}, because calling the
5675: definition by name is more descriptive (if the name is well-chosen) than
5676: the somewhat cryptic @code{recurse}. E.g., in a quicksort
5677: implementation, it is much better to read (and think) ``now sort the
5678: partitions'' than to read ``now do a recursive call''.
5679: @end quotation
1.3 anton 5680:
1.29 crook 5681: For mutual recursion, use @code{Defer}red words, like this:
1.3 anton 5682:
5683: @example
1.28 crook 5684: Defer foo
1.3 anton 5685:
5686: : bar ( ... -- ... )
5687: ... foo ... ;
5688:
5689: :noname ( ... -- ... )
5690: ... bar ... ;
5691: IS foo
5692: @end example
5693:
1.44 crook 5694: Deferred words are discussed in more detail in @ref{Deferred words}.
1.33 anton 5695:
1.26 crook 5696: The current definition returns control to the calling definition when
1.33 anton 5697: the end of the definition is reached or @code{EXIT} is encountered.
1.1 anton 5698:
5699: doc-exit
5700: doc-;s
5701:
1.44 crook 5702:
1.1 anton 5703: @node Exception Handling, , Calls and returns, Control Structures
5704: @subsection Exception Handling
1.26 crook 5705: @cindex exceptions
1.1 anton 5706:
1.68 ! anton 5707: @c quit is a very bad idea for error handling,
! 5708: @c because it does not translate into a THROW
! 5709: @c it also does not belong into this chapter
! 5710:
! 5711: If a word detects an error condition that it cannot handle, it can
! 5712: @code{throw} an exception. In the simplest case, this will terminate
! 5713: your program, and report an appropriate error.
1.21 crook 5714:
1.68 ! anton 5715: doc-throw
1.1 anton 5716:
1.68 ! anton 5717: @code{Throw} consumes a cell-sized error number on the stack; there are
! 5718: some predefined error numbers (see @file{errors.fs}). In Gforth (and
! 5719: most other systems) you can use the iors produced by various words as
! 5720: error numbers (e.g., a typical use of @code{allocate} is @code{allocate
! 5721: throw}). Gforth also provides the word @code{exception} to define your
! 5722: own error numbers (with decent error reporting); an ANS Forth version of
! 5723: this word (but without the error messages) is available in
! 5724: @code{compat/except.fs}. And finally, you can use your own error
! 5725: numbers (anything outside the range -4095..0), but won't get nice error
! 5726: messages, only numbers. For example, try:
! 5727:
! 5728: @example
! 5729: -10 throw
! 5730: -267 throw
! 5731: s" my error" exception throw
! 5732: 7 throw
! 5733: @end example
! 5734:
! 5735: doc---exception-exception
1.1 anton 5736:
1.68 ! anton 5737: Your program can catch exceptions and then either correct the problem,
! 5738: or clean up some data structures and just throw the exception to the
! 5739: next exception handler. Note that @code{throw} always executes the
! 5740: dynamically innermost exception handler; the system's exception handler
! 5741: is outermost, and just prints an error and restarts command-line
! 5742: interpretation (or, in batch mode (i.e., while processing the shell
! 5743: command line), leaves Gforth).
1.1 anton 5744:
1.68 ! anton 5745: The ANS Forth way to catch exceptions is @code{catch}:
1.1 anton 5746:
1.68 ! anton 5747: doc-catch
! 5748:
! 5749: The most common use of exception handlers is to clean up the state when
! 5750: an error happens. E.g.,
1.1 anton 5751:
1.26 crook 5752: @example
1.68 ! anton 5753: base @ >r hex \ actually the hex should be inside foo, or we h
! 5754: ['] foo catch ( nerror|0 )
! 5755: r> base !
! 5756: ( nerror|0 ) throw \ throw on
1.26 crook 5757: @end example
1.1 anton 5758:
1.68 ! anton 5759: A use of @code{catch} for handling an error might look like this:
1.44 crook 5760:
1.68 ! anton 5761: @example
! 5762: ['] foo catch
! 5763: dup myerror = if \ an error we can do something about?
! 5764: ... \ do something about it
! 5765: else
! 5766: throw \ if there is an error, throw it on
! 5767: endif
! 5768: @end example
1.44 crook 5769:
1.68 ! anton 5770: Having to wrap the code into a separate word is often cumbersome,
! 5771: therefore Gforth provides an alternative syntax:
1.1 anton 5772:
5773: @example
1.68 ! anton 5774: try
! 5775: @i{code1}
! 5776: recover \ optional
! 5777: @i{code2} \ optional
! 5778: endtry
1.1 anton 5779: @end example
5780:
1.68 ! anton 5781: This performs @i{Code1}. If @i{code1} completes normally, execution
! 5782: continues after the @code{endtry}. If @i{Code1} throws, the stacks are
! 5783: reset to the state during @code{try}, the throw value is pushed on the
! 5784: data stack, and execution constinues at @i{code2}, and finally falls
! 5785: through the @code{endtry} into the following code. If there is no
! 5786: @code{recover} clause, this works like an empty recover clause.
1.26 crook 5787:
1.68 ! anton 5788: doc-try
! 5789: doc-recover
! 5790: doc-endtry
1.26 crook 5791:
1.68 ! anton 5792: The cleanup example above in this syntax:
1.26 crook 5793:
1.68 ! anton 5794: @example
! 5795: base @ >r try
! 5796: hex foo \ now the hex is placed correctly
! 5797: 0 \ value for throw
! 5798: endtry
! 5799: r> base ! throw
1.1 anton 5800: @end example
5801:
1.68 ! anton 5802: And here's the error handling example
1.1 anton 5803:
1.68 ! anton 5804: @example
! 5805: try
! 5806: foo
! 5807: recover
! 5808: dup myerror = if
! 5809: ... \ do something about it
! 5810: else
! 5811: throw
! 5812: endif
! 5813: endtry
! 5814: @end example
1.1 anton 5815:
1.68 ! anton 5816: There are two alternatives to @code{throw}: @code{Abort"} is conditional
! 5817: and you can provide an error message. @code{Abort} just produces an
! 5818: ``Aborted'' error.
1.1 anton 5819:
1.68 ! anton 5820: The problem with these words is that exception handlers cannot
! 5821: differentiate between different @code{abort"}s; they just look like
! 5822: @code{-2 throw} to them (the error message cannot be accessed by
! 5823: standard programs). Similar @code{abort} looks like @code{-1 throw} to
! 5824: exception handlers.
1.44 crook 5825:
1.68 ! anton 5826: doc-abort"
1.26 crook 5827: doc-abort
1.29 crook 5828:
5829:
1.44 crook 5830:
1.29 crook 5831: @c -------------------------------------------------------------
1.47 crook 5832: @node Defining Words, Interpretation and Compilation Semantics, Control Structures, Words
1.29 crook 5833: @section Defining Words
5834: @cindex defining words
5835:
1.47 crook 5836: Defining words are used to extend Forth by creating new entries in the dictionary.
5837:
1.29 crook 5838: @menu
1.67 anton 5839: * CREATE::
1.44 crook 5840: * Variables:: Variables and user variables
1.67 anton 5841: * Constants::
1.44 crook 5842: * Values:: Initialised variables
1.67 anton 5843: * Colon Definitions::
1.44 crook 5844: * Anonymous Definitions:: Definitions without names
1.67 anton 5845: * User-defined Defining Words::
1.44 crook 5846: * Deferred words:: Allow forward references
1.67 anton 5847: * Aliases::
5848: * Supplying names::
1.29 crook 5849: @end menu
5850:
1.44 crook 5851: @node CREATE, Variables, Defining Words, Defining Words
5852: @subsection @code{CREATE}
1.29 crook 5853: @cindex simple defining words
5854: @cindex defining words, simple
5855:
5856: Defining words are used to create new entries in the dictionary. The
5857: simplest defining word is @code{CREATE}. @code{CREATE} is used like
5858: this:
5859:
5860: @example
5861: CREATE new-word1
5862: @end example
5863:
5864: @code{CREATE} is a parsing word that generates a dictionary entry for
5865: @code{new-word1}. When @code{new-word1} is executed, all that it does is
5866: leave an address on the stack. The address represents the value of
5867: the data space pointer (@code{HERE}) at the time that @code{new-word1}
5868: was defined. Therefore, @code{CREATE} is a way of associating a name
5869: with the address of a region of memory.
5870:
1.34 anton 5871: doc-create
5872:
1.29 crook 5873: By extending this example to reserve some memory in data space, we end
5874: up with a @i{variable}. Here are two different ways to do it:
5875:
5876: @example
5877: CREATE new-word2 1 cells allot \ reserve 1 cell - initial value undefined
5878: CREATE new-word3 4 , \ reserve 1 cell and initialise it (to 4)
5879: @end example
5880:
5881: The variable can be examined and modified using @code{@@} (``fetch'') and
5882: @code{!} (``store'') like this:
5883:
5884: @example
5885: new-word2 @@ . \ get address, fetch from it and display
5886: 1234 new-word2 ! \ new value, get address, store to it
5887: @end example
5888:
1.44 crook 5889: @cindex arrays
5890: A similar mechanism can be used to create arrays. For example, an
5891: 80-character text input buffer:
1.29 crook 5892:
5893: @example
1.44 crook 5894: CREATE text-buf 80 chars allot
5895:
5896: text-buf 0 chars c@@ \ the 1st character (offset 0)
5897: text-buf 3 chars c@@ \ the 4th character (offset 3)
5898: @end example
1.29 crook 5899:
1.44 crook 5900: You can build arbitrarily complex data structures by allocating
1.49 anton 5901: appropriate areas of memory. For further discussions of this, and to
1.66 anton 5902: learn about some Gforth tools that make it easier,
1.49 anton 5903: @xref{Structures}.
1.44 crook 5904:
5905:
5906: @node Variables, Constants, CREATE, Defining Words
5907: @subsection Variables
5908: @cindex variables
5909:
5910: The previous section showed how a sequence of commands could be used to
5911: generate a variable. As a final refinement, the whole code sequence can
5912: be wrapped up in a defining word (pre-empting the subject of the next
5913: section), making it easier to create new variables:
5914:
5915: @example
5916: : myvariableX ( "name" -- a-addr ) CREATE 1 cells allot ;
5917: : myvariable0 ( "name" -- a-addr ) CREATE 0 , ;
5918:
5919: myvariableX foo \ variable foo starts off with an unknown value
5920: myvariable0 joe \ whilst joe is initialised to 0
1.29 crook 5921:
5922: 45 3 * foo ! \ set foo to 135
5923: 1234 joe ! \ set joe to 1234
5924: 3 joe +! \ increment joe by 3.. to 1237
5925: @end example
5926:
5927: Not surprisingly, there is no need to define @code{myvariable}, since
1.44 crook 5928: Forth already has a definition @code{Variable}. ANS Forth does not
5929: require a @code{Variable} to be initialised when it is created (i.e., it
5930: behaves like @code{myvariableX}). In contrast, Gforth's @code{Variable}
5931: initialises the variable to 0 (i.e., it behaves exactly like
5932: @code{myvariable0}). Forth also provides @code{2Variable} and
1.47 crook 5933: @code{fvariable} for double and floating-point variables, respectively
5934: -- both are initialised to 0 in Gforth. If you use a @code{Variable} to
5935: store a boolean, you can use @code{on} and @code{off} to toggle its
5936: state.
1.29 crook 5937:
1.34 anton 5938: doc-variable
5939: doc-2variable
5940: doc-fvariable
5941:
1.29 crook 5942: @cindex user variables
5943: @cindex user space
5944: The defining word @code{User} behaves in the same way as @code{Variable}.
5945: The difference is that it reserves space in @i{user (data) space} rather
5946: than normal data space. In a Forth system that has a multi-tasker, each
5947: task has its own set of user variables.
5948:
1.34 anton 5949: doc-user
1.67 anton 5950: @c doc-udp
5951: @c doc-uallot
1.34 anton 5952:
1.29 crook 5953: @comment TODO is that stuff about user variables strictly correct? Is it
5954: @comment just terminal tasks that have user variables?
5955: @comment should document tasker.fs (with some examples) elsewhere
5956: @comment in this manual, then expand on user space and user variables.
5957:
1.44 crook 5958: @node Constants, Values, Variables, Defining Words
5959: @subsection Constants
5960: @cindex constants
5961:
5962: @code{Constant} allows you to declare a fixed value and refer to it by
5963: name. For example:
1.29 crook 5964:
5965: @example
5966: 12 Constant INCHES-PER-FOOT
5967: 3E+08 fconstant SPEED-O-LIGHT
5968: @end example
5969:
5970: A @code{Variable} can be both read and written, so its run-time
5971: behaviour is to supply an address through which its current value can be
5972: manipulated. In contrast, the value of a @code{Constant} cannot be
5973: changed once it has been declared@footnote{Well, often it can be -- but
5974: not in a Standard, portable way. It's safer to use a @code{Value} (read
5975: on).} so it's not necessary to supply the address -- it is more
5976: efficient to return the value of the constant directly. That's exactly
5977: what happens; the run-time effect of a constant is to put its value on
1.49 anton 5978: the top of the stack (You can find one
5979: way of implementing @code{Constant} in @ref{User-defined Defining Words}).
1.29 crook 5980:
5981: Gforth also provides @code{2Constant} and @code{fconstant} for defining
5982: double and floating-point constants, respectively.
5983:
1.34 anton 5984: doc-constant
5985: doc-2constant
5986: doc-fconstant
5987:
5988: @c that's too deep, and it's not necessarily true for all ANS Forths. - anton
1.44 crook 5989: @c nac-> How could that not be true in an ANS Forth? You can't define a
5990: @c constant, use it and then delete the definition of the constant..
5991: @c I agree that it's rather deep, but IMO it is an important difference
5992: @c relative to other programming languages.. often it's annoying: it
5993: @c certainly changes my programming style relative to C.
5994:
1.29 crook 5995: Constants in Forth behave differently from their equivalents in other
5996: programming languages. In other languages, a constant (such as an EQU in
5997: assembler or a #define in C) only exists at compile-time; in the
5998: executable program the constant has been translated into an absolute
5999: number and, unless you are using a symbolic debugger, it's impossible to
6000: know what abstract thing that number represents. In Forth a constant has
1.44 crook 6001: an entry in the header space and remains there after the code that uses
6002: it has been defined. In fact, it must remain in the dictionary since it
6003: has run-time duties to perform. For example:
1.29 crook 6004:
6005: @example
6006: 12 Constant INCHES-PER-FOOT
6007: : FEET-TO-INCHES ( n1 -- n2 ) INCHES-PER-FOOT * ;
6008: @end example
6009:
6010: @cindex in-lining of constants
6011: When @code{FEET-TO-INCHES} is executed, it will in turn execute the xt
6012: associated with the constant @code{INCHES-PER-FOOT}. If you use
6013: @code{see} to decompile the definition of @code{FEET-TO-INCHES}, you can
6014: see that it makes a call to @code{INCHES-PER-FOOT}. Some Forth compilers
6015: attempt to optimise constants by in-lining them where they are used. You
6016: can force Gforth to in-line a constant like this:
6017:
6018: @example
6019: : FEET-TO-INCHES ( n1 -- n2 ) [ INCHES-PER-FOOT ] LITERAL * ;
6020: @end example
6021:
6022: If you use @code{see} to decompile @i{this} version of
6023: @code{FEET-TO-INCHES}, you can see that @code{INCHES-PER-FOOT} is no
1.49 anton 6024: longer present. To understand how this works, read
6025: @ref{Interpret/Compile states}, and @ref{Literals}.
1.29 crook 6026:
6027: In-lining constants in this way might improve execution time
6028: fractionally, and can ensure that a constant is now only referenced at
6029: compile-time. However, the definition of the constant still remains in
6030: the dictionary. Some Forth compilers provide a mechanism for controlling
6031: a second dictionary for holding transient words such that this second
6032: dictionary can be deleted later in order to recover memory
6033: space. However, there is no standard way of doing this.
6034:
6035:
1.44 crook 6036: @node Values, Colon Definitions, Constants, Defining Words
6037: @subsection Values
6038: @cindex values
1.34 anton 6039:
1.44 crook 6040: A @code{Value} is like a @code{Variable} but with two important
6041: differences:
1.29 crook 6042:
6043: @itemize @bullet
6044: @item
1.44 crook 6045: A @code{Value} is initialised when it is declared; like a
6046: @code{Constant} but unlike a @code{Variable}.
1.29 crook 6047: @item
1.44 crook 6048: A @code{Value} returns its value rather than its address when it is
6049: executed; i.e., it has the same run-time behaviour as @code{Constant}.
1.29 crook 6050: @end itemize
6051:
1.44 crook 6052: A @code{Value} needs an additional word, @code{TO} to allow its value to
6053: be changed. Here are some examples:
1.29 crook 6054:
6055: @example
1.44 crook 6056: 12 Value APPLES \ Define APPLES with an initial value of 12
6057: 34 TO APPLES \ Change the value of APPLES. TO is a parsing word
6058: APPLES \ puts 34 on the top of the stack.
1.29 crook 6059: @end example
6060:
1.44 crook 6061: doc-value
6062: doc-to
1.29 crook 6063:
1.35 anton 6064:
1.44 crook 6065: @node Colon Definitions, Anonymous Definitions, Values, Defining Words
6066: @subsection Colon Definitions
6067: @cindex colon definitions
1.35 anton 6068:
6069: @example
1.44 crook 6070: : name ( ... -- ... )
6071: word1 word2 word3 ;
1.29 crook 6072: @end example
6073:
1.44 crook 6074: @noindent
6075: Creates a word called @code{name} that, upon execution, executes
6076: @code{word1 word2 word3}. @code{name} is a @dfn{(colon) definition}.
1.29 crook 6077:
1.49 anton 6078: The explanation above is somewhat superficial. For simple examples of
6079: colon definitions see @ref{Your first definition}. For an in-depth
1.66 anton 6080: discussion of some of the issues involved, @xref{Interpretation and
1.49 anton 6081: Compilation Semantics}.
1.29 crook 6082:
1.44 crook 6083: doc-:
6084: doc-;
1.1 anton 6085:
1.34 anton 6086:
1.44 crook 6087: @node Anonymous Definitions, User-defined Defining Words, Colon Definitions, Defining Words
6088: @subsection Anonymous Definitions
6089: @cindex colon definitions
6090: @cindex defining words without name
1.34 anton 6091:
1.44 crook 6092: Sometimes you want to define an @dfn{anonymous word}; a word without a
6093: name. You can do this with:
1.1 anton 6094:
1.44 crook 6095: doc-:noname
1.1 anton 6096:
1.44 crook 6097: This leaves the execution token for the word on the stack after the
6098: closing @code{;}. Here's an example in which a deferred word is
6099: initialised with an @code{xt} from an anonymous colon definition:
1.1 anton 6100:
1.29 crook 6101: @example
1.44 crook 6102: Defer deferred
6103: :noname ( ... -- ... )
6104: ... ;
6105: IS deferred
1.29 crook 6106: @end example
1.26 crook 6107:
1.44 crook 6108: @noindent
6109: Gforth provides an alternative way of doing this, using two separate
6110: words:
1.27 crook 6111:
1.44 crook 6112: doc-noname
6113: @cindex execution token of last defined word
6114: doc-lastxt
1.1 anton 6115:
1.44 crook 6116: @noindent
6117: The previous example can be rewritten using @code{noname} and
6118: @code{lastxt}:
1.1 anton 6119:
1.26 crook 6120: @example
1.44 crook 6121: Defer deferred
6122: noname : ( ... -- ... )
6123: ... ;
6124: lastxt IS deferred
1.26 crook 6125: @end example
1.1 anton 6126:
1.29 crook 6127: @noindent
1.44 crook 6128: @code{noname} works with any defining word, not just @code{:}.
6129:
6130: @code{lastxt} also works when the last word was not defined as
6131: @code{noname}. It also has the useful property that is is valid as soon
6132: as the header for a definition has been built. Thus:
6133:
6134: @example
6135: lastxt . : foo [ lastxt . ] ; ' foo .
6136: @end example
1.1 anton 6137:
1.44 crook 6138: @noindent
6139: prints 3 numbers; the last two are the same.
1.26 crook 6140:
1.1 anton 6141:
1.44 crook 6142: @node User-defined Defining Words, Deferred words, Anonymous Definitions, Defining Words
1.26 crook 6143: @subsection User-defined Defining Words
6144: @cindex user-defined defining words
6145: @cindex defining words, user-defined
1.1 anton 6146:
1.29 crook 6147: You can create a new defining word by wrapping defining-time code around
6148: an existing defining word and putting the sequence in a colon
6149: definition. For example, suppose that you have a word @code{stats} that
6150: gathers statistics about colon definitions given the @i{xt} of the
6151: definition, and you want every colon definition in your application to
6152: make a call to @code{stats}. You can define and use a new version of
6153: @code{:} like this:
6154:
6155: @example
6156: : stats ( xt -- ) DUP ." (Gathering statistics for " . ." )"
6157: ... ; \ other code
6158:
6159: : my: : lastxt postpone literal ['] stats compile, ;
6160:
6161: my: foo + - ;
6162: @end example
6163:
6164: When @code{foo} is defined using @code{my:} these steps occur:
6165:
6166: @itemize @bullet
6167: @item
6168: @code{my:} is executed.
6169: @item
6170: The @code{:} within the definition (the one between @code{my:} and
6171: @code{lastxt}) is executed, and does just what it always does; it parses
6172: the input stream for a name, builds a dictionary header for the name
6173: @code{foo} and switches @code{state} from interpret to compile.
6174: @item
6175: The word @code{lastxt} is executed. It puts the @i{xt} for the word that is
6176: being defined -- @code{foo} -- onto the stack.
6177: @item
6178: The code that was produced by @code{postpone literal} is executed; this
6179: causes the value on the stack to be compiled as a literal in the code
6180: area of @code{foo}.
6181: @item
6182: The code @code{['] stats} compiles a literal into the definition of
6183: @code{my:}. When @code{compile,} is executed, that literal -- the
6184: execution token for @code{stats} -- is layed down in the code area of
6185: @code{foo} , following the literal@footnote{Strictly speaking, the
6186: mechanism that @code{compile,} uses to convert an @i{xt} into something
6187: in the code area is implementation-dependent. A threaded implementation
6188: might spit out the execution token directly whilst another
6189: implementation might spit out a native code sequence.}.
6190: @item
6191: At this point, the execution of @code{my:} is complete, and control
6192: returns to the text interpreter. The text interpreter is in compile
6193: state, so subsequent text @code{+ -} is compiled into the definition of
6194: @code{foo} and the @code{;} terminates the definition as always.
6195: @end itemize
6196:
6197: You can use @code{see} to decompile a word that was defined using
6198: @code{my:} and see how it is different from a normal @code{:}
6199: definition. For example:
6200:
6201: @example
6202: : bar + - ; \ like foo but using : rather than my:
6203: see bar
6204: : bar
6205: + - ;
6206: see foo
6207: : foo
6208: 107645672 stats + - ;
6209:
6210: \ use ' stats . to show that 107645672 is the xt for stats
6211: @end example
6212:
6213: You can use techniques like this to make new defining words in terms of
6214: @i{any} existing defining word.
1.1 anton 6215:
6216:
1.29 crook 6217: @cindex defining defining words
1.26 crook 6218: @cindex @code{CREATE} ... @code{DOES>}
6219: If you want the words defined with your defining words to behave
6220: differently from words defined with standard defining words, you can
6221: write your defining word like this:
1.1 anton 6222:
6223: @example
1.26 crook 6224: : def-word ( "name" -- )
1.29 crook 6225: CREATE @i{code1}
1.26 crook 6226: DOES> ( ... -- ... )
1.29 crook 6227: @i{code2} ;
1.26 crook 6228:
6229: def-word name
1.1 anton 6230: @end example
6231:
1.29 crook 6232: @cindex child words
6233: This fragment defines a @dfn{defining word} @code{def-word} and then
6234: executes it. When @code{def-word} executes, it @code{CREATE}s a new
6235: word, @code{name}, and executes the code @i{code1}. The code @i{code2}
6236: is not executed at this time. The word @code{name} is sometimes called a
6237: @dfn{child} of @code{def-word}.
6238:
6239: When you execute @code{name}, the address of the body of @code{name} is
6240: put on the data stack and @i{code2} is executed (the address of the body
6241: of @code{name} is the address @code{HERE} returns immediately after the
6242: @code{CREATE}).
6243:
6244: @cindex atavism in child words
1.33 anton 6245: You can use @code{def-word} to define a set of child words that behave
1.29 crook 6246: differently, though atavistically; they all have a common run-time
6247: behaviour determined by @i{code2}. Typically, the @i{code1} sequence
6248: builds a data area in the body of the child word. The structure of the
6249: data is common to all children of @code{def-word}, but the data values
6250: are specific -- and private -- to each child word. When a child word is
6251: executed, the address of its private data area is passed as a parameter
6252: on TOS to be used and manipulated@footnote{It is legitimate both to read
6253: and write to this data area.} by @i{code2}.
6254:
6255: The two fragments of code that make up the defining words act (are
6256: executed) at two completely separate times:
1.1 anton 6257:
1.29 crook 6258: @itemize @bullet
6259: @item
6260: At @i{define time}, the defining word executes @i{code1} to generate a
6261: child word
6262: @item
6263: At @i{child execution time}, when a child word is invoked, @i{code2}
6264: is executed, using parameters (data) that are private and specific to
6265: the child word.
6266: @end itemize
6267:
1.44 crook 6268: Another way of understanding the behaviour of @code{def-word} and
6269: @code{name} is to say that, if you make the following definitions:
1.33 anton 6270: @example
6271: : def-word1 ( "name" -- )
6272: CREATE @i{code1} ;
6273:
6274: : action1 ( ... -- ... )
6275: @i{code2} ;
6276:
6277: def-word1 name1
6278: @end example
6279:
1.44 crook 6280: @noindent
6281: Then using @code{name1 action1} is equivalent to using @code{name}.
1.1 anton 6282:
1.29 crook 6283: The classic example is that you can define @code{CONSTANT} in this way:
1.26 crook 6284:
1.1 anton 6285: @example
1.29 crook 6286: : CONSTANT ( w "name" -- )
6287: CREATE ,
1.26 crook 6288: DOES> ( -- w )
6289: @@ ;
1.1 anton 6290: @end example
6291:
1.29 crook 6292: @comment There is a beautiful description of how this works and what
6293: @comment it does in the Forthwrite 100th edition.. as well as an elegant
6294: @comment commentary on the Counting Fruits problem.
6295:
6296: When you create a constant with @code{5 CONSTANT five}, a set of
6297: define-time actions take place; first a new word @code{five} is created,
6298: then the value 5 is laid down in the body of @code{five} with
1.44 crook 6299: @code{,}. When @code{five} is executed, the address of the body is put on
1.29 crook 6300: the stack, and @code{@@} retrieves the value 5. The word @code{five} has
6301: no code of its own; it simply contains a data field and a pointer to the
6302: code that follows @code{DOES>} in its defining word. That makes words
6303: created in this way very compact.
6304:
6305: The final example in this section is intended to remind you that space
6306: reserved in @code{CREATE}d words is @i{data} space and therefore can be
6307: both read and written by a Standard program@footnote{Exercise: use this
6308: example as a starting point for your own implementation of @code{Value}
6309: and @code{TO} -- if you get stuck, investigate the behaviour of @code{'} and
6310: @code{[']}.}:
6311:
6312: @example
6313: : foo ( "name" -- )
6314: CREATE -1 ,
6315: DOES> ( -- )
1.33 anton 6316: @@ . ;
1.29 crook 6317:
6318: foo first-word
6319: foo second-word
6320:
6321: 123 ' first-word >BODY !
6322: @end example
6323:
6324: If @code{first-word} had been a @code{CREATE}d word, we could simply
6325: have executed it to get the address of its data field. However, since it
6326: was defined to have @code{DOES>} actions, its execution semantics are to
6327: perform those @code{DOES>} actions. To get the address of its data field
6328: it's necessary to use @code{'} to get its xt, then @code{>BODY} to
6329: translate the xt into the address of the data field. When you execute
6330: @code{first-word}, it will display @code{123}. When you execute
6331: @code{second-word} it will display @code{-1}.
1.26 crook 6332:
6333: @cindex stack effect of @code{DOES>}-parts
6334: @cindex @code{DOES>}-parts, stack effect
1.29 crook 6335: In the examples above the stack comment after the @code{DOES>} specifies
1.26 crook 6336: the stack effect of the defined words, not the stack effect of the
6337: following code (the following code expects the address of the body on
6338: the top of stack, which is not reflected in the stack comment). This is
6339: the convention that I use and recommend (it clashes a bit with using
6340: locals declarations for stack effect specification, though).
1.1 anton 6341:
1.53 anton 6342: @menu
6343: * CREATE..DOES> applications::
6344: * CREATE..DOES> details::
1.63 anton 6345: * Advanced does> usage example::
1.53 anton 6346: @end menu
6347:
6348: @node CREATE..DOES> applications, CREATE..DOES> details, User-defined Defining Words, User-defined Defining Words
1.26 crook 6349: @subsubsection Applications of @code{CREATE..DOES>}
6350: @cindex @code{CREATE} ... @code{DOES>}, applications
1.1 anton 6351:
1.26 crook 6352: You may wonder how to use this feature. Here are some usage patterns:
1.1 anton 6353:
1.26 crook 6354: @cindex factoring similar colon definitions
6355: When you see a sequence of code occurring several times, and you can
6356: identify a meaning, you will factor it out as a colon definition. When
6357: you see similar colon definitions, you can factor them using
6358: @code{CREATE..DOES>}. E.g., an assembler usually defines several words
6359: that look very similar:
1.1 anton 6360: @example
1.26 crook 6361: : ori, ( reg-target reg-source n -- )
6362: 0 asm-reg-reg-imm ;
6363: : andi, ( reg-target reg-source n -- )
6364: 1 asm-reg-reg-imm ;
1.1 anton 6365: @end example
6366:
1.26 crook 6367: @noindent
6368: This could be factored with:
6369: @example
6370: : reg-reg-imm ( op-code -- )
6371: CREATE ,
6372: DOES> ( reg-target reg-source n -- )
6373: @@ asm-reg-reg-imm ;
6374:
6375: 0 reg-reg-imm ori,
6376: 1 reg-reg-imm andi,
6377: @end example
1.1 anton 6378:
1.26 crook 6379: @cindex currying
6380: Another view of @code{CREATE..DOES>} is to consider it as a crude way to
6381: supply a part of the parameters for a word (known as @dfn{currying} in
6382: the functional language community). E.g., @code{+} needs two
6383: parameters. Creating versions of @code{+} with one parameter fixed can
6384: be done like this:
1.1 anton 6385: @example
1.26 crook 6386: : curry+ ( n1 -- )
6387: CREATE ,
6388: DOES> ( n2 -- n1+n2 )
6389: @@ + ;
6390:
6391: 3 curry+ 3+
6392: -2 curry+ 2-
1.1 anton 6393: @end example
6394:
1.63 anton 6395: @node CREATE..DOES> details, Advanced does> usage example, CREATE..DOES> applications, User-defined Defining Words
1.26 crook 6396: @subsubsection The gory details of @code{CREATE..DOES>}
6397: @cindex @code{CREATE} ... @code{DOES>}, details
1.1 anton 6398:
1.26 crook 6399: doc-does>
1.1 anton 6400:
1.26 crook 6401: @cindex @code{DOES>} in a separate definition
6402: This means that you need not use @code{CREATE} and @code{DOES>} in the
6403: same definition; you can put the @code{DOES>}-part in a separate
1.29 crook 6404: definition. This allows us to, e.g., select among different @code{DOES>}-parts:
1.26 crook 6405: @example
6406: : does1
6407: DOES> ( ... -- ... )
1.44 crook 6408: ... ;
6409:
6410: : does2
6411: DOES> ( ... -- ... )
6412: ... ;
6413:
6414: : def-word ( ... -- ... )
6415: create ...
6416: IF
6417: does1
6418: ELSE
6419: does2
6420: ENDIF ;
6421: @end example
6422:
6423: In this example, the selection of whether to use @code{does1} or
6424: @code{does2} is made at compile-time; at the time that the child word is
6425: @code{CREATE}d.
6426:
6427: @cindex @code{DOES>} in interpretation state
6428: In a standard program you can apply a @code{DOES>}-part only if the last
6429: word was defined with @code{CREATE}. In Gforth, the @code{DOES>}-part
6430: will override the behaviour of the last word defined in any case. In a
6431: standard program, you can use @code{DOES>} only in a colon
6432: definition. In Gforth, you can also use it in interpretation state, in a
6433: kind of one-shot mode; for example:
6434: @example
6435: CREATE name ( ... -- ... )
6436: @i{initialization}
6437: DOES>
6438: @i{code} ;
6439: @end example
6440:
6441: @noindent
6442: is equivalent to the standard:
6443: @example
6444: :noname
6445: DOES>
6446: @i{code} ;
6447: CREATE name EXECUTE ( ... -- ... )
6448: @i{initialization}
6449: @end example
6450:
1.53 anton 6451: doc->body
6452:
1.63 anton 6453: @node Advanced does> usage example, , CREATE..DOES> details, User-defined Defining Words
6454: @subsubsection Advanced does> usage example
6455:
6456: The MIPS disassembler (@file{arch/mips/disasm.fs}) contains many words
6457: for disassembling instructions, that follow a very repetetive scheme:
6458:
6459: @example
6460: :noname @var{disasm-operands} s" @var{inst-name}" type ;
6461: @var{entry-num} cells @var{table} + !
6462: @end example
6463:
6464: Of course, this inspires the idea to factor out the commonalities to
6465: allow a definition like
6466:
6467: @example
6468: @var{disasm-operands} @var{entry-num} @var{table} define-inst @var{inst-name}
6469: @end example
6470:
6471: The parameters @var{disasm-operands} and @var{table} are usually
6472: correlated. Moreover, there existed code defining instructions like
6473: this:
6474:
6475: @example
6476: @var{entry-num} @var{inst-format} @var{inst-name}
6477: @end example
6478:
6479: This code comes from the assembler and resides in
6480: @file{arch/mips/insts.fs}.
6481:
6482: So I had to define the @var{inst-format} words that performed the scheme
6483: above when executed. At first I chose to use run-time code-generation:
6484:
6485: @example
6486: : @var{inst-format} ( entry-num "name" -- ; compiled code: addr w -- )
6487: :noname Postpone @var{disasm-operands}
6488: name Postpone sliteral Postpone type Postpone ;
6489: swap cells @var{table} + ! ;
6490: @end example
6491:
6492: Note that this supplies the other two parameters of the scheme above.
1.44 crook 6493:
1.63 anton 6494: An alternative would have been to write this using
6495: @code{create}/@code{does>}:
6496:
6497: @example
6498: : @var{inst-format} ( entry-num "name" -- )
6499: here name string, ( entry-num c-addr ) \ parse and save "name"
6500: noname create , ( entry-num )
6501: lastxt swap cells @var{table} + !
6502: does> ( addr w -- )
6503: \ disassemble instruction w at addr
6504: @@ >r
6505: @var{disasm-operands}
6506: r> count type ;
6507: @end example
6508:
6509: Somehow the first solution is simpler, mainly because it's simpler to
6510: shift a string from definition-time to use-time with @code{sliteral}
6511: than with @code{string,} and friends.
6512:
6513: I wrote a lot of words following this scheme and soon thought about
6514: factoring out the commonalities among them. Note that this uses a
6515: two-level defining word, i.e., a word that defines ordinary defining
6516: words.
6517:
6518: This time a solution involving @code{postpone} and friends seemed more
6519: difficult (try it as an exercise), so I decided to use a
6520: @code{create}/@code{does>} word; since I was already at it, I also used
6521: @code{create}/@code{does>} for the lower level (try using
6522: @code{postpone} etc. as an exercise), resulting in the following
6523: definition:
6524:
6525: @example
6526: : define-format ( disasm-xt table-xt -- )
6527: \ define an instruction format that uses disasm-xt for
6528: \ disassembling and enters the defined instructions into table
6529: \ table-xt
6530: create 2,
6531: does> ( u "inst" -- )
6532: \ defines an anonymous word for disassembling instruction inst,
6533: \ and enters it as u-th entry into table-xt
6534: 2@@ swap here name string, ( u table-xt disasm-xt c-addr ) \ remember string
6535: noname create 2, \ define anonymous word
6536: execute lastxt swap ! \ enter xt of defined word into table-xt
6537: does> ( addr w -- )
6538: \ disassemble instruction w at addr
6539: 2@@ >r ( addr w disasm-xt R: c-addr )
6540: execute ( R: c-addr ) \ disassemble operands
6541: r> count type ; \ print name
6542: @end example
6543:
6544: Note that the tables here (in contrast to above) do the @code{cells +}
6545: by themselves (that's why you have to pass an xt). This word is used in
6546: the following way:
6547:
6548: @example
6549: ' @var{disasm-operands} ' @var{table} define-format @var{inst-format}
6550: @end example
6551:
6552: In terms of currying, this kind of two-level defining word provides the
6553: parameters in three stages: first @var{disasm-operands} and @var{table},
6554: then @var{entry-num} and @var{inst-name}, finally @code{addr w}, i.e.,
6555: the instruction to be disassembled.
6556:
6557: Of course this did not quite fit all the instruction format names used
6558: in @file{insts.fs}, so I had to define a few wrappers that conditioned
6559: the parameters into the right form.
6560:
6561: If you have trouble following this section, don't worry. First, this is
6562: involved and takes time (and probably some playing around) to
6563: understand; second, this is the first two-level
6564: @code{create}/@code{does>} word I have written in seventeen years of
6565: Forth; and if I did not have @file{insts.fs} to start with, I may well
6566: have elected to use just a one-level defining word (with some repeating
6567: of parameters when using the defining word). So it is not necessary to
6568: understand this, but it may improve your understanding of Forth.
1.44 crook 6569:
6570:
6571: @node Deferred words, Aliases, User-defined Defining Words, Defining Words
6572: @subsection Deferred words
6573: @cindex deferred words
6574:
6575: The defining word @code{Defer} allows you to define a word by name
6576: without defining its behaviour; the definition of its behaviour is
6577: deferred. Here are two situation where this can be useful:
6578:
6579: @itemize @bullet
6580: @item
6581: Where you want to allow the behaviour of a word to be altered later, and
6582: for all precompiled references to the word to change when its behaviour
6583: is changed.
6584: @item
6585: For mutual recursion; @xref{Calls and returns}.
6586: @end itemize
6587:
6588: In the following example, @code{foo} always invokes the version of
6589: @code{greet} that prints ``@code{Good morning}'' whilst @code{bar}
6590: always invokes the version that prints ``@code{Hello}''. There is no way
6591: of getting @code{foo} to use the later version without re-ordering the
6592: source code and recompiling it.
6593:
6594: @example
6595: : greet ." Good morning" ;
6596: : foo ... greet ... ;
6597: : greet ." Hello" ;
6598: : bar ... greet ... ;
6599: @end example
6600:
6601: This problem can be solved by defining @code{greet} as a @code{Defer}red
6602: word. The behaviour of a @code{Defer}red word can be defined and
6603: redefined at any time by using @code{IS} to associate the xt of a
6604: previously-defined word with it. The previous example becomes:
6605:
6606: @example
6607: Defer greet
6608: : foo ... greet ... ;
6609: : bar ... greet ... ;
6610: : greet1 ." Good morning" ;
6611: : greet2 ." Hello" ;
6612: ' greet2 <IS> greet \ make greet behave like greet2
6613: @end example
6614:
6615: A deferred word can be used to improve the statistics-gathering example
6616: from @ref{User-defined Defining Words}; rather than edit the
6617: application's source code to change every @code{:} to a @code{my:}, do
6618: this:
6619:
6620: @example
6621: : real: : ; \ retain access to the original
6622: defer : \ redefine as a deferred word
6623: ' my: IS : \ use special version of :
6624: \
6625: \ load application here
6626: \
6627: ' real: IS : \ go back to the original
6628: @end example
6629:
6630:
6631: One thing to note is that @code{<IS>} consumes its name when it is
6632: executed. If you want to specify the name at compile time, use
6633: @code{[IS]}:
6634:
6635: @example
6636: : set-greet ( xt -- )
6637: [IS] greet ;
6638:
6639: ' greet1 set-greet
6640: @end example
6641:
6642: A deferred word can only inherit default semantics from the xt (because
1.49 anton 6643: that is all that an xt can represent -- for more discussion of this
6644: @pxref{Tokens for Words}). However, the semantics of the deferred word
1.44 crook 6645: itself can be modified at the time that it is defined. For example:
6646:
6647: @example
6648: : bar .... ; compile-only
6649: Defer fred immediate
6650: Defer jim
6651:
6652: ' bar <IS> jim \ jim has default semantics
6653: ' bar <IS> fred \ fred is immediate
6654: @end example
6655:
6656: doc-defer
6657: doc-<is>
6658: doc-[is]
6659: doc-is
6660: @comment TODO document these: what's defers [is]
6661: doc-what's
6662: doc-defers
6663:
6664: @c Use @code{words-deferred} to see a list of deferred words.
6665:
6666: Definitions in ANS Forth for @code{defer}, @code{<is>} and @code{[is]}
6667: are provided in @file{compat/defer.fs}.
6668:
6669:
6670: @node Aliases, Supplying names, Deferred words, Defining Words
6671: @subsection Aliases
6672: @cindex aliases
1.1 anton 6673:
1.44 crook 6674: The defining word @code{Alias} allows you to define a word by name that
6675: has the same behaviour as some other word. Here are two situation where
6676: this can be useful:
1.1 anton 6677:
1.44 crook 6678: @itemize @bullet
6679: @item
6680: When you want access to a word's definition from a different word list
6681: (for an example of this, see the definition of the @code{Root} word list
6682: in the Gforth source).
6683: @item
6684: When you want to create a synonym; a definition that can be known by
6685: either of two names (for example, @code{THEN} and @code{ENDIF} are
6686: aliases).
6687: @end itemize
1.1 anton 6688:
1.44 crook 6689: The word whose behaviour the alias is to inherit is represented by an
6690: xt. Therefore, the alias only inherits default semantics from its
6691: ancestor. The semantics of the alias itself can be modified at the time
6692: that it is defined. For example:
1.1 anton 6693:
6694: @example
1.44 crook 6695: : foo ... ; immediate
6696:
6697: ' foo Alias bar \ bar is not an immediate word
6698: ' foo Alias fooby immediate \ fooby is an immediate word
1.1 anton 6699: @end example
6700:
1.44 crook 6701: Words that are aliases have the same xt, different headers in the
6702: dictionary, and consequently different name tokens (@pxref{Tokens for
6703: Words}) and possibly different immediate flags. An alias can only have
6704: default or immediate compilation semantics; you can define aliases for
6705: combined words with @code{interpret/compile:} -- see @ref{Combined words}.
1.1 anton 6706:
1.44 crook 6707: doc-alias
1.26 crook 6708:
1.1 anton 6709:
1.52 anton 6710: @node Supplying names, , Aliases, Defining Words
1.29 crook 6711: @subsection Supplying the name of a defined word
1.26 crook 6712: @cindex names for defined words
1.44 crook 6713: @cindex defining words, name given in a string
1.1 anton 6714:
1.29 crook 6715: By default, a defining word takes the name for the defined word from the
1.26 crook 6716: input stream. Sometimes you want to supply the name from a string. You
6717: can do this with:
1.1 anton 6718:
1.26 crook 6719: doc-nextname
1.1 anton 6720:
1.26 crook 6721: For example:
1.1 anton 6722:
1.26 crook 6723: @example
6724: s" foo" nextname create
6725: @end example
1.44 crook 6726:
1.26 crook 6727: @noindent
6728: is equivalent to:
1.44 crook 6729:
1.26 crook 6730: @example
6731: create foo
6732: @end example
1.1 anton 6733:
1.29 crook 6734: @noindent
1.44 crook 6735: @code{nextname} works with any defining word, not just @code{:}.
1.1 anton 6736:
6737:
1.47 crook 6738: @node Interpretation and Compilation Semantics, Tokens for Words, Defining Words, Words
6739: @section Interpretation and Compilation Semantics
1.26 crook 6740: @cindex semantics, interpretation and compilation
1.1 anton 6741:
1.26 crook 6742: @cindex interpretation semantics
6743: The @dfn{interpretation semantics} of a word are what the text
6744: interpreter does when it encounters the word in interpret state. It also
6745: appears in some other contexts, e.g., the execution token returned by
1.29 crook 6746: @code{' @i{word}} identifies the interpretation semantics of
6747: @i{word} (in other words, @code{' @i{word} execute} is equivalent to
6748: interpret-state text interpretation of @code{@i{word}}).
1.1 anton 6749:
1.26 crook 6750: @cindex compilation semantics
6751: The @dfn{compilation semantics} of a word are what the text interpreter
6752: does when it encounters the word in compile state. It also appears in
1.29 crook 6753: other contexts, e.g, @code{POSTPONE @i{word}} compiles@footnote{In
1.26 crook 6754: standard terminology, ``appends to the current definition''.} the
1.29 crook 6755: compilation semantics of @i{word}.
1.1 anton 6756:
1.26 crook 6757: @cindex execution semantics
6758: The standard also talks about @dfn{execution semantics}. They are used
6759: only for defining the interpretation and compilation semantics of many
6760: words. By default, the interpretation semantics of a word are to
6761: @code{execute} its execution semantics, and the compilation semantics of
6762: a word are to @code{compile,} its execution semantics.@footnote{In
6763: standard terminology: The default interpretation semantics are its
6764: execution semantics; the default compilation semantics are to append its
6765: execution semantics to the execution semantics of the current
6766: definition.}
6767:
6768: @comment TODO expand, make it co-operate with new sections on text interpreter.
6769:
6770: @cindex immediate words
6771: @cindex compile-only words
6772: You can change the semantics of the most-recently defined word:
6773:
1.44 crook 6774:
1.26 crook 6775: doc-immediate
6776: doc-compile-only
6777: doc-restrict
6778:
1.44 crook 6779:
1.26 crook 6780: Note that ticking (@code{'}) a compile-only word gives an error
6781: (``Interpreting a compile-only word'').
1.1 anton 6782:
1.47 crook 6783: @menu
1.67 anton 6784: * Combined words::
1.47 crook 6785: @end menu
1.44 crook 6786:
1.48 anton 6787: @node Combined words, , Interpretation and Compilation Semantics, Interpretation and Compilation Semantics
1.44 crook 6788: @subsection Combined Words
6789: @cindex combined words
6790:
6791: Gforth allows you to define @dfn{combined words} -- words that have an
6792: arbitrary combination of interpretation and compilation semantics.
6793:
1.1 anton 6794:
1.26 crook 6795: doc-interpret/compile:
1.1 anton 6796:
1.44 crook 6797:
1.26 crook 6798: This feature was introduced for implementing @code{TO} and @code{S"}. I
6799: recommend that you do not define such words, as cute as they may be:
6800: they make it hard to get at both parts of the word in some contexts.
6801: E.g., assume you want to get an execution token for the compilation
6802: part. Instead, define two words, one that embodies the interpretation
6803: part, and one that embodies the compilation part. Once you have done
6804: that, you can define a combined word with @code{interpret/compile:} for
6805: the convenience of your users.
1.1 anton 6806:
1.26 crook 6807: You might try to use this feature to provide an optimizing
6808: implementation of the default compilation semantics of a word. For
6809: example, by defining:
1.1 anton 6810: @example
1.26 crook 6811: :noname
6812: foo bar ;
6813: :noname
6814: POSTPONE foo POSTPONE bar ;
1.29 crook 6815: interpret/compile: opti-foobar
1.1 anton 6816: @end example
1.26 crook 6817:
1.23 crook 6818: @noindent
1.26 crook 6819: as an optimizing version of:
6820:
1.1 anton 6821: @example
1.26 crook 6822: : foobar
6823: foo bar ;
1.1 anton 6824: @end example
6825:
1.26 crook 6826: Unfortunately, this does not work correctly with @code{[compile]},
6827: because @code{[compile]} assumes that the compilation semantics of all
6828: @code{interpret/compile:} words are non-default. I.e., @code{[compile]
1.29 crook 6829: opti-foobar} would compile compilation semantics, whereas
6830: @code{[compile] foobar} would compile interpretation semantics.
1.1 anton 6831:
1.26 crook 6832: @cindex state-smart words (are a bad idea)
1.29 crook 6833: Some people try to use @dfn{state-smart} words to emulate the feature provided
1.26 crook 6834: by @code{interpret/compile:} (words are state-smart if they check
6835: @code{STATE} during execution). E.g., they would try to code
6836: @code{foobar} like this:
1.1 anton 6837:
1.26 crook 6838: @example
6839: : foobar
6840: STATE @@
6841: IF ( compilation state )
6842: POSTPONE foo POSTPONE bar
6843: ELSE
6844: foo bar
6845: ENDIF ; immediate
6846: @end example
1.1 anton 6847:
1.26 crook 6848: Although this works if @code{foobar} is only processed by the text
6849: interpreter, it does not work in other contexts (like @code{'} or
6850: @code{POSTPONE}). E.g., @code{' foobar} will produce an execution token
6851: for a state-smart word, not for the interpretation semantics of the
6852: original @code{foobar}; when you execute this execution token (directly
6853: with @code{EXECUTE} or indirectly through @code{COMPILE,}) in compile
6854: state, the result will not be what you expected (i.e., it will not
6855: perform @code{foo bar}). State-smart words are a bad idea. Simply don't
6856: write them@footnote{For a more detailed discussion of this topic, see
1.66 anton 6857: M. Anton Ertl,
6858: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,@code{State}-smartness---Why
6859: it is Evil and How to Exorcise it}}, EuroForth '98.}!
1.1 anton 6860:
1.26 crook 6861: @cindex defining words with arbitrary semantics combinations
6862: It is also possible to write defining words that define words with
6863: arbitrary combinations of interpretation and compilation semantics. In
6864: general, they look like this:
1.1 anton 6865:
1.26 crook 6866: @example
6867: : def-word
6868: create-interpret/compile
1.29 crook 6869: @i{code1}
1.26 crook 6870: interpretation>
1.29 crook 6871: @i{code2}
1.26 crook 6872: <interpretation
6873: compilation>
1.29 crook 6874: @i{code3}
1.26 crook 6875: <compilation ;
6876: @end example
1.1 anton 6877:
1.29 crook 6878: For a @i{word} defined with @code{def-word}, the interpretation
6879: semantics are to push the address of the body of @i{word} and perform
6880: @i{code2}, and the compilation semantics are to push the address of
6881: the body of @i{word} and perform @i{code3}. E.g., @code{constant}
1.26 crook 6882: can also be defined like this (except that the defined constants don't
6883: behave correctly when @code{[compile]}d):
1.1 anton 6884:
1.26 crook 6885: @example
6886: : constant ( n "name" -- )
6887: create-interpret/compile
6888: ,
6889: interpretation> ( -- n )
6890: @@
6891: <interpretation
6892: compilation> ( compilation. -- ; run-time. -- n )
6893: @@ postpone literal
6894: <compilation ;
6895: @end example
1.1 anton 6896:
1.44 crook 6897:
1.26 crook 6898: doc-create-interpret/compile
6899: doc-interpretation>
6900: doc-<interpretation
6901: doc-compilation>
6902: doc-<compilation
1.1 anton 6903:
1.44 crook 6904:
1.29 crook 6905: Words defined with @code{interpret/compile:} and
1.26 crook 6906: @code{create-interpret/compile} have an extended header structure that
6907: differs from other words; however, unless you try to access them with
6908: plain address arithmetic, you should not notice this. Words for
6909: accessing the header structure usually know how to deal with this; e.g.,
1.29 crook 6910: @code{'} @i{word} @code{>body} also gives you the body of a word created
6911: with @code{create-interpret/compile}.
1.1 anton 6912:
1.44 crook 6913:
1.27 crook 6914: doc-postpone
1.44 crook 6915:
1.29 crook 6916: @comment TODO -- expand glossary text for POSTPONE
1.27 crook 6917:
1.47 crook 6918:
6919: @c -------------------------------------------------------------
6920: @node Tokens for Words, The Text Interpreter, Interpretation and Compilation Semantics, Words
6921: @section Tokens for Words
6922: @cindex tokens for words
6923:
6924: This section describes the creation and use of tokens that represent
6925: words.
6926:
6927: Named words have information stored in their header space entries to
6928: indicate any non-default semantics (@pxref{Interpretation and
6929: Compilation Semantics}). The semantics can be modified, using
6930: @code{immediate} and/or @code{compile-only}, at the time that the words
6931: are defined. Unnamed words have (by definition) no header space
6932: entry, and therefore must have default semantics.
6933:
6934: Named words have interpretation and compilation semantics. Unnamed words
6935: just have execution semantics.
6936:
6937: @cindex xt
6938: @cindex execution token
6939: The execution semantics of an unnamed word are represented by an
6940: @dfn{execution token} (@i{xt}). As explained in @ref{Supplying names},
6941: the execution token of the last word defined can be produced with
6942: @code{lastxt}.
6943:
6944: The interpretation semantics of a named word are also represented by an
6945: execution token. You can produce the execution token using @code{'} or
6946: @code{[']}. A simple example shows the difference between the two:
6947:
6948: @example
6949: : greet ( -- ) ." Hello" ;
6950: : foo ( -- xt ) ['] greet execute ; \ ['] parses greet at compile-time
6951: : bar ( -- ) ' execute ; \ ' parses at run-time
6952:
6953: \ the next four lines all do the same thing
6954: foo
6955: bar greet
6956: greet
6957: ' greet EXECUTE
6958: @end example
6959:
6960: An execution token occupies one cell.
6961: @cindex code field address
6962: @cindex CFA
6963: In Gforth, the abstract data type @i{execution token} is implemented
6964: as a code field address (CFA).
6965: @comment TODO note that the standard does not say what it represents..
6966: @comment and you cannot necessarily compile it in all Forths (eg native
6967: @comment compilers?).
6968:
6969: For literals, use @code{'} in interpreted code and @code{[']} in
6970: compiled code. Gforth's @code{'} and @code{[']} behave somewhat
6971: unusually by complaining about compile-only words. To get the execution
6972: token for a compile-only word @i{name}, use @code{COMP' @i{name} DROP}
6973: or @code{[COMP'] @i{name} DROP}.
6974:
6975: @cindex compilation token
6976: The compilation semantics of a named word are represented by a
6977: @dfn{compilation token} consisting of two cells: @i{w xt}. The top cell
6978: @i{xt} is an execution token. The compilation semantics represented by
6979: the compilation token can be performed with @code{execute}, which
6980: consumes the whole compilation token, with an additional stack effect
6981: determined by the represented compilation semantics.
6982:
6983: At present, the @i{w} part of a compilation token is an execution token,
6984: and the @i{xt} part represents either @code{execute} or
6985: @code{compile,}@footnote{Depending upon the compilation semantics of the
6986: word. If the word has default compilation semantics, the @i{xt} will
6987: represent @code{compile,}. Otherwise (e.g., for immediate words), the
6988: @i{xt} will represent @code{execute}.}. However, don't rely on that
6989: knowledge, unless necessary; future versions of Gforth may introduce
6990: unusual compilation tokens (e.g., a compilation token that represents
6991: the compilation semantics of a literal).
6992:
6993: You can compile the compilation semantics with @code{postpone,}. I.e.,
6994: @code{COMP' @i{word} postpone,} is equivalent to @code{postpone
6995: @i{word}}.
6996:
6997: @cindex name token
6998: @cindex name field address
6999: @cindex NFA
7000: Named words are also represented by the @dfn{name token}, (@i{nt}). In
7001: Gforth, the abstract data type @emph{name token} is implemented as a
7002: name field address (NFA).
7003:
7004:
7005: doc-execute
7006: doc-perform
7007: doc-compile,
7008: doc-[']
7009: doc-'
7010: doc-[comp']
7011: doc-comp'
7012: doc-postpone,
7013:
7014: doc-find-name
7015: doc-name>int
7016: doc-name?int
7017: doc-name>comp
7018: doc-name>string
7019:
7020:
1.26 crook 7021: @c ----------------------------------------------------------
1.47 crook 7022: @node The Text Interpreter, Word Lists, Tokens for Words, Words
1.26 crook 7023: @section The Text Interpreter
7024: @cindex interpreter - outer
7025: @cindex text interpreter
7026: @cindex outer interpreter
1.1 anton 7027:
1.34 anton 7028: @c Should we really describe all these ugly details? IMO the text
7029: @c interpreter should be much cleaner, but that may not be possible within
7030: @c ANS Forth. - anton
1.44 crook 7031: @c nac-> I wanted to explain how it works to show how you can exploit
7032: @c it in your own programs. When I was writing a cross-compiler, figuring out
7033: @c some of these gory details was very helpful to me. None of the textbooks
7034: @c I've seen cover it, and the most modern Forth textbook -- Forth Inc's,
7035: @c seems to positively avoid going into too much detail for some of
7036: @c the internals.
1.34 anton 7037:
1.29 crook 7038: The text interpreter@footnote{This is an expanded version of the
7039: material in @ref{Introducing the Text Interpreter}.} is an endless loop
1.34 anton 7040: that processes input from the current input device. It is also called
7041: the outer interpreter, in contrast to the inner interpreter
7042: (@pxref{Engine}) which executes the compiled Forth code on interpretive
7043: implementations.
1.27 crook 7044:
1.29 crook 7045: @cindex interpret state
7046: @cindex compile state
7047: The text interpreter operates in one of two states: @dfn{interpret
7048: state} and @dfn{compile state}. The current state is defined by the
7049: aptly-named variable, @code{state}.
7050:
7051: This section starts by describing how the text interpreter behaves when
7052: it is in interpret state, processing input from the user input device --
7053: the keyboard. This is the mode that a Forth system is in after it starts
7054: up.
7055:
7056: @cindex input buffer
7057: @cindex terminal input buffer
7058: The text interpreter works from an area of memory called the @dfn{input
7059: buffer}@footnote{When the text interpreter is processing input from the
7060: keyboard, this area of memory is called the @dfn{terminal input buffer}
7061: (TIB) and is addressed by the (obsolescent) words @code{TIB} and
7062: @code{#TIB}.}, which stores your keyboard input when you press the
1.30 anton 7063: @key{RET} key. Starting at the beginning of the input buffer, it skips
1.29 crook 7064: leading spaces (called @dfn{delimiters}) then parses a string (a
7065: sequence of non-space characters) until it reaches either a space
7066: character or the end of the buffer. Having parsed a string, it makes two
7067: attempts to process it:
1.27 crook 7068:
1.29 crook 7069: @cindex dictionary
1.27 crook 7070: @itemize @bullet
7071: @item
1.29 crook 7072: It looks for the string in a @dfn{dictionary} of definitions. If the
7073: string is found, the string names a @dfn{definition} (also known as a
7074: @dfn{word}) and the dictionary search returns information that allows
7075: the text interpreter to perform the word's @dfn{interpretation
7076: semantics}. In most cases, this simply means that the word will be
7077: executed.
1.27 crook 7078: @item
7079: If the string is not found in the dictionary, the text interpreter
1.29 crook 7080: attempts to treat it as a number, using the rules described in
7081: @ref{Number Conversion}. If the string represents a legal number in the
7082: current radix, the number is pushed onto a parameter stack (the data
7083: stack for integers, the floating-point stack for floating-point
7084: numbers).
7085: @end itemize
7086:
7087: If both attempts fail, or if the word is found in the dictionary but has
7088: no interpretation semantics@footnote{This happens if the word was
7089: defined as @code{COMPILE-ONLY}.} the text interpreter discards the
7090: remainder of the input buffer, issues an error message and waits for
7091: more input. If one of the attempts succeeds, the text interpreter
7092: repeats the parsing process until the whole of the input buffer has been
7093: processed, at which point it prints the status message ``@code{ ok}''
7094: and waits for more input.
7095:
7096: @cindex parse area
7097: The text interpreter keeps track of its position in the input buffer by
7098: updating a variable called @code{>IN} (pronounced ``to-in''). The value
7099: of @code{>IN} starts out as 0, indicating an offset of 0 from the start
7100: of the input buffer. The region from offset @code{>IN @@} to the end of
7101: the input buffer is called the @dfn{parse area}@footnote{In other words,
7102: the text interpreter processes the contents of the input buffer by
7103: parsing strings from the parse area until the parse area is empty.}.
7104: This example shows how @code{>IN} changes as the text interpreter parses
7105: the input buffer:
7106:
7107: @example
7108: : remaining >IN @@ SOURCE 2 PICK - -ROT + SWAP
7109: CR ." ->" TYPE ." <-" ; IMMEDIATE
7110:
7111: 1 2 3 remaining + remaining .
7112:
7113: : foo 1 2 3 remaining SWAP remaining ;
7114: @end example
7115:
7116: @noindent
7117: The result is:
7118:
7119: @example
7120: ->+ remaining .<-
7121: ->.<-5 ok
7122:
7123: ->SWAP remaining ;-<
7124: ->;<- ok
7125: @end example
7126:
7127: @cindex parsing words
7128: The value of @code{>IN} can also be modified by a word in the input
7129: buffer that is executed by the text interpreter. This means that a word
7130: can ``trick'' the text interpreter into either skipping a section of the
7131: input buffer@footnote{This is how parsing words work.} or into parsing a
7132: section twice. For example:
1.27 crook 7133:
1.29 crook 7134: @example
7135: : lat ." <<lat>>" ;
7136: : flat ." <<flat>>" >IN DUP @@ 3 - SWAP ! ;
7137: @end example
7138:
7139: @noindent
7140: When @code{flat} is executed, this output is produced@footnote{Exercise
7141: for the reader: what would happen if the @code{3} were replaced with
7142: @code{4}?}:
7143:
7144: @example
7145: <<flat>><<lat>>
7146: @end example
7147:
7148: @noindent
7149: Two important notes about the behaviour of the text interpreter:
1.27 crook 7150:
7151: @itemize @bullet
7152: @item
7153: It processes each input string to completion before parsing additional
1.29 crook 7154: characters from the input buffer.
7155: @item
7156: It treats the input buffer as a read-only region (and so must your code).
7157: @end itemize
7158:
7159: @noindent
7160: When the text interpreter is in compile state, its behaviour changes in
7161: these ways:
7162:
7163: @itemize @bullet
7164: @item
7165: If a parsed string is found in the dictionary, the text interpreter will
7166: perform the word's @dfn{compilation semantics}. In most cases, this
7167: simply means that the execution semantics of the word will be appended
7168: to the current definition.
1.27 crook 7169: @item
1.29 crook 7170: When a number is encountered, it is compiled into the current definition
7171: (as a literal) rather than being pushed onto a parameter stack.
7172: @item
7173: If an error occurs, @code{state} is modified to put the text interpreter
7174: back into interpret state.
7175: @item
7176: Each time a line is entered from the keyboard, Gforth prints
7177: ``@code{ compiled}'' rather than `` @code{ok}''.
7178: @end itemize
7179:
7180: @cindex text interpreter - input sources
7181: When the text interpreter is using an input device other than the
7182: keyboard, its behaviour changes in these ways:
7183:
7184: @itemize @bullet
7185: @item
7186: When the parse area is empty, the text interpreter attempts to refill
7187: the input buffer from the input source. When the input source is
7188: exhausted, the input source is set back to the user input device.
7189: @item
7190: It doesn't print out ``@code{ ok}'' or ``@code{ compiled}'' messages each
7191: time the parse area is emptied.
7192: @item
7193: If an error occurs, the input source is set back to the user input
7194: device.
1.27 crook 7195: @end itemize
1.21 crook 7196:
1.49 anton 7197: You can read about this in more detail in @ref{Input Sources}.
1.44 crook 7198:
1.26 crook 7199: doc->in
1.27 crook 7200: doc-source
7201:
1.26 crook 7202: doc-tib
7203: doc-#tib
1.1 anton 7204:
1.44 crook 7205:
1.26 crook 7206: @menu
1.67 anton 7207: * Input Sources::
7208: * Number Conversion::
7209: * Interpret/Compile states::
7210: * Literals::
7211: * Interpreter Directives::
1.26 crook 7212: @end menu
1.1 anton 7213:
1.29 crook 7214: @node Input Sources, Number Conversion, The Text Interpreter, The Text Interpreter
7215: @subsection Input Sources
7216: @cindex input sources
7217: @cindex text interpreter - input sources
7218:
1.44 crook 7219: By default, the text interpreter processes input from the user input
1.29 crook 7220: device (the keyboard) when Forth starts up. The text interpreter can
7221: process input from any of these sources:
7222:
7223: @itemize @bullet
7224: @item
7225: The user input device -- the keyboard.
7226: @item
7227: A file, using the words described in @ref{Forth source files}.
7228: @item
7229: A block, using the words described in @ref{Blocks}.
7230: @item
7231: A text string, using @code{evaluate}.
7232: @end itemize
7233:
7234: A program can identify the current input device from the values of
7235: @code{source-id} and @code{blk}.
7236:
1.44 crook 7237:
1.29 crook 7238: doc-source-id
7239: doc-blk
7240:
7241: doc-save-input
7242: doc-restore-input
7243:
7244: doc-evaluate
1.1 anton 7245:
1.29 crook 7246:
1.44 crook 7247:
1.29 crook 7248: @node Number Conversion, Interpret/Compile states, Input Sources, The Text Interpreter
1.26 crook 7249: @subsection Number Conversion
7250: @cindex number conversion
7251: @cindex double-cell numbers, input format
7252: @cindex input format for double-cell numbers
7253: @cindex single-cell numbers, input format
7254: @cindex input format for single-cell numbers
7255: @cindex floating-point numbers, input format
7256: @cindex input format for floating-point numbers
1.1 anton 7257:
1.29 crook 7258: This section describes the rules that the text interpreter uses when it
7259: tries to convert a string into a number.
1.1 anton 7260:
1.26 crook 7261: Let <digit> represent any character that is a legal digit in the current
1.29 crook 7262: number base@footnote{For example, 0-9 when the number base is decimal or
7263: 0-9, A-F when the number base is hexadecimal.}.
1.1 anton 7264:
1.26 crook 7265: Let <decimal digit> represent any character in the range 0-9.
1.1 anton 7266:
1.29 crook 7267: Let @{@i{a b}@} represent the @i{optional} presence of any of the characters
7268: in the braces (@i{a} or @i{b} or neither).
1.1 anton 7269:
1.26 crook 7270: Let * represent any number of instances of the previous character
7271: (including none).
1.1 anton 7272:
1.26 crook 7273: Let any other character represent itself.
1.1 anton 7274:
1.29 crook 7275: @noindent
1.26 crook 7276: Now, the conversion rules are:
1.21 crook 7277:
1.26 crook 7278: @itemize @bullet
7279: @item
7280: A string of the form <digit><digit>* is treated as a single-precision
1.29 crook 7281: (cell-sized) positive integer. Examples are 0 123 6784532 32343212343456 42
1.26 crook 7282: @item
7283: A string of the form -<digit><digit>* is treated as a single-precision
1.29 crook 7284: (cell-sized) negative integer, and is represented using 2's-complement
1.26 crook 7285: arithmetic. Examples are -45 -5681 -0
7286: @item
7287: A string of the form <digit><digit>*.<digit>* is treated as a double-precision
1.29 crook 7288: (double-cell-sized) positive integer. Examples are 3465. 3.465 34.65
7289: (all three of these represent the same number).
1.26 crook 7290: @item
7291: A string of the form -<digit><digit>*.<digit>* is treated as a
1.29 crook 7292: double-precision (double-cell-sized) negative integer, and is
1.26 crook 7293: represented using 2's-complement arithmetic. Examples are -3465. -3.465
1.29 crook 7294: -34.65 (all three of these represent the same number).
1.26 crook 7295: @item
1.29 crook 7296: A string of the form @{+ -@}<decimal digit>@{.@}<decimal digit>*@{e
7297: E@}@{+ -@}<decimal digit><decimal digit>* is treated as a floating-point
1.35 anton 7298: number. Examples are 1e 1e0 1.e 1.e0 +1e+0 (which all represent the same
1.29 crook 7299: number) +12.E-4
1.26 crook 7300: @end itemize
1.1 anton 7301:
1.26 crook 7302: By default, the number base used for integer number conversion is given
1.35 anton 7303: by the contents of the variable @code{base}. Note that a lot of
7304: confusion can result from unexpected values of @code{base}. If you
7305: change @code{base} anywhere, make sure to save the old value and restore
7306: it afterwards. In general I recommend keeping @code{base} decimal, and
7307: using the prefixes described below for the popular non-decimal bases.
1.1 anton 7308:
1.29 crook 7309: doc-dpl
1.26 crook 7310: doc-base
7311: doc-hex
7312: doc-decimal
1.1 anton 7313:
1.44 crook 7314:
1.26 crook 7315: @cindex '-prefix for character strings
7316: @cindex &-prefix for decimal numbers
7317: @cindex %-prefix for binary numbers
7318: @cindex $-prefix for hexadecimal numbers
1.35 anton 7319: Gforth allows you to override the value of @code{base} by using a
1.29 crook 7320: prefix@footnote{Some Forth implementations provide a similar scheme by
7321: implementing @code{$} etc. as parsing words that process the subsequent
7322: number in the input stream and push it onto the stack. For example, see
7323: @cite{Number Conversion and Literals}, by Wil Baden; Forth Dimensions
7324: 20(3) pages 26--27. In such implementations, unlike in Gforth, a space
7325: is required between the prefix and the number.} before the first digit
7326: of an (integer) number. Four prefixes are supported:
1.1 anton 7327:
1.26 crook 7328: @itemize @bullet
7329: @item
1.35 anton 7330: @code{&} -- decimal
1.26 crook 7331: @item
1.35 anton 7332: @code{%} -- binary
1.26 crook 7333: @item
1.35 anton 7334: @code{$} -- hexadecimal
1.26 crook 7335: @item
1.35 anton 7336: @code{'} -- base @code{max-char+1}
1.26 crook 7337: @end itemize
1.1 anton 7338:
1.26 crook 7339: Here are some examples, with the equivalent decimal number shown after
7340: in braces:
1.1 anton 7341:
1.26 crook 7342: -$41 (-65), %1001101 (205), %1001.0001 (145 - a double-precision number),
7343: 'AB (16706; ascii A is 65, ascii B is 66, number is 65*256 + 66),
7344: 'ab (24930; ascii a is 97, ascii B is 98, number is 97*256 + 98),
7345: &905 (905), $abc (2478), $ABC (2478).
1.1 anton 7346:
1.26 crook 7347: @cindex number conversion - traps for the unwary
1.29 crook 7348: @noindent
1.26 crook 7349: Number conversion has a number of traps for the unwary:
1.1 anton 7350:
1.26 crook 7351: @itemize @bullet
7352: @item
7353: You cannot determine the current number base using the code sequence
1.35 anton 7354: @code{base @@ .} -- the number base is always 10 in the current number
7355: base. Instead, use something like @code{base @@ dec.}
1.26 crook 7356: @item
7357: If the number base is set to a value greater than 14 (for example,
7358: hexadecimal), the number 123E4 is ambiguous; the conversion rules allow
7359: it to be intepreted as either a single-precision integer or a
7360: floating-point number (Gforth treats it as an integer). The ambiguity
7361: can be resolved by explicitly stating the sign of the mantissa and/or
7362: exponent: 123E+4 or +123E4 -- if the number base is decimal, no
7363: ambiguity arises; either representation will be treated as a
7364: floating-point number.
7365: @item
1.29 crook 7366: There is a word @code{bin} but it does @i{not} set the number base!
1.26 crook 7367: It is used to specify file types.
7368: @item
7369: ANS Forth requires the @code{.} of a double-precision number to
7370: be the final character in the string. Allowing the @code{.} to be
7371: anywhere after the first digit is a Gforth extension.
7372: @item
7373: The number conversion process does not check for overflow.
7374: @item
7375: In Gforth, number conversion to floating-point numbers always use base
1.35 anton 7376: 10, irrespective of the value of @code{base}. In ANS Forth,
1.26 crook 7377: conversion to floating-point numbers whilst the value of
1.35 anton 7378: @code{base} is not 10 is an ambiguous condition.
1.26 crook 7379: @end itemize
1.1 anton 7380:
1.49 anton 7381: You can read numbers into your programs with the words described in
7382: @ref{Input}.
1.1 anton 7383:
1.26 crook 7384: @node Interpret/Compile states, Literals, Number Conversion, The Text Interpreter
7385: @subsection Interpret/Compile states
7386: @cindex Interpret/Compile states
1.1 anton 7387:
1.29 crook 7388: A standard program is not permitted to change @code{state}
7389: explicitly. However, it can change @code{state} implicitly, using the
7390: words @code{[} and @code{]}. When @code{[} is executed it switches
7391: @code{state} to interpret state, and therefore the text interpreter
7392: starts interpreting. When @code{]} is executed it switches @code{state}
7393: to compile state and therefore the text interpreter starts
1.44 crook 7394: compiling. The most common usage for these words is for switching into
7395: interpret state and back from within a colon definition; this technique
1.49 anton 7396: can be used to compile a literal (for an example, @pxref{Literals}) or
7397: for conditional compilation (for an example, @pxref{Interpreter
7398: Directives}).
1.44 crook 7399:
1.35 anton 7400:
7401: @c This is a bad example: It's non-standard, and it's not necessary.
7402: @c However, I can't think of a good example for switching into compile
7403: @c state when there is no current word (@code{state}-smart words are not a
7404: @c good reason). So maybe we should use an example for switching into
7405: @c interpret @code{state} in a colon def. - anton
1.44 crook 7406: @c nac-> I agree. I started out by putting in the example, then realised
7407: @c that it was non-ANS, so wrote more words around it. I hope this
7408: @c re-written version is acceptable to you. I do want to keep the example
7409: @c as it is helpful for showing what is and what is not portable, particularly
7410: @c where it outlaws a style in common use.
7411:
1.35 anton 7412:
1.44 crook 7413: @code{[} and @code{]} also give you the ability to switch into compile
7414: state and back, but we cannot think of any useful Standard application
7415: for this ability. Pre-ANS Forth textbooks have examples like this:
1.29 crook 7416:
7417: @example
7418: : AA ." this is A" ;
7419: : BB ." this is B" ;
7420: : CC ." this is C" ;
7421:
1.44 crook 7422: create table ] aa bb cc [
7423:
1.29 crook 7424: : go ( n -- ) \ n is offset into table.. 0 for 1st entry
7425: cells table + @ execute ;
7426: @end example
7427:
1.44 crook 7428: This example builds a jump table; @code{0 go} will display ``@code{this
7429: is A}''. Using @code{[} and @code{]} in this example is equivalent to
7430: defining @code{table} like this:
1.29 crook 7431:
7432: @example
1.44 crook 7433: create table ' aa COMPILE, ' bb COMPILE, ' cc COMPILE,
1.29 crook 7434: @end example
7435:
1.44 crook 7436: The problem with this code is that the definition of @code{table} is not
7437: portable -- it @i{compile}s execution tokens into code space. Whilst it
7438: @i{may} work on systems where code space and data space co-incide, the
1.29 crook 7439: Standard only allows data space to be assigned for a @code{CREATE}d
7440: word. In addition, the Standard only allows @code{@@} to access data
7441: space, whilst this example is using it to access code space. The only
7442: portable, Standard way to build this table is to build it in data space,
7443: like this:
7444:
7445: @example
7446: create table ' aa , ' bb , ' cc ,
7447: @end example
7448:
1.26 crook 7449: doc-state
7450: doc-[
7451: doc-]
1.1 anton 7452:
1.44 crook 7453:
1.26 crook 7454: @node Literals, Interpreter Directives, Interpret/Compile states, The Text Interpreter
7455: @subsection Literals
7456: @cindex Literals
1.21 crook 7457:
1.29 crook 7458: Often, you want to use a number within a colon definition. When you do
7459: this, the text interpreter automatically compiles the number as a
7460: @i{literal}. A literal is a number whose run-time effect is to be pushed
7461: onto the stack. If you had to do some maths to generate the number, you
7462: might write it like this:
7463:
7464: @example
7465: : HOUR-TO-SEC ( n1 -- n2 )
7466: 60 * \ to minutes
7467: 60 * ; \ to seconds
7468: @end example
7469:
7470: It is very clear what this definition is doing, but it's inefficient
7471: since it is performing 2 multiples at run-time. An alternative would be
7472: to write:
7473:
7474: @example
7475: : HOUR-TO-SEC ( n1 -- n2 )
7476: 3600 * ; \ to seconds
7477: @end example
7478:
7479: Which does the same thing, and has the advantage of using a single
7480: multiply. Ideally, we'd like the efficiency of the second with the
7481: readability of the first.
7482:
7483: @code{Literal} allows us to achieve that. It takes a number from the
7484: stack and lays it down in the current definition just as though the
7485: number had been typed directly into the definition. Our first attempt
7486: might look like this:
7487:
7488: @example
7489: 60 \ mins per hour
7490: 60 * \ seconds per minute
7491: : HOUR-TO-SEC ( n1 -- n2 )
7492: Literal * ; \ to seconds
7493: @end example
7494:
7495: But this produces the error message @code{unstructured}. What happened?
7496: The stack notation for @code{:} is (@i{ -- colon-sys}) and the size of
7497: @i{colon-sys} is implementation-defined. In other words, once we start a
7498: colon definition we can't portably access anything that was on the stack
7499: before the definition began@footnote{@cite{Two Problems in ANS Forth},
7500: by Thomas Worthington; Forth Dimensions 20(2) pages 32--34 describes
7501: some situations where you might want to access stack items above
7502: colon-sys, and provides a solution to the problem.}. The correct way of
7503: solving this problem in this instance is to use @code{[ ]} like this:
7504:
7505: @example
7506: : HOUR-TO-SEC ( n1 -- n2 )
7507: [ 60 \ minutes per hour
7508: 60 * ] \ seconds per minute
7509: LITERAL * ; \ to seconds
7510: @end example
1.23 crook 7511:
1.44 crook 7512:
1.26 crook 7513: doc-literal
7514: doc-]L
7515: doc-2literal
7516: doc-fliteral
1.1 anton 7517:
1.44 crook 7518:
1.48 anton 7519: @node Interpreter Directives, , Literals, The Text Interpreter
1.26 crook 7520: @subsection Interpreter Directives
7521: @cindex interpreter directives
1.1 anton 7522:
1.29 crook 7523: These words are usually used in interpret state; typically to control
7524: which parts of a source file are processed by the text
1.26 crook 7525: interpreter. There are only a few ANS Forth Standard words, but Gforth
7526: supplements these with a rich set of immediate control structure words
7527: to compensate for the fact that the non-immediate versions can only be
1.29 crook 7528: used in compile state (@pxref{Control Structures}). Typical usages:
7529:
7530: @example
7531: FALSE Constant ASSEMBLER
7532: .
7533: .
7534: ASSEMBLER [IF]
7535: : ASSEMBLER-FEATURE
7536: ...
7537: ;
7538: [ENDIF]
7539: .
7540: .
7541: : SEE
7542: ... \ general-purpose SEE code
7543: [ ASSEMBLER [IF] ]
7544: ... \ assembler-specific SEE code
7545: [ [ENDIF] ]
7546: ;
7547: @end example
1.1 anton 7548:
1.44 crook 7549:
1.26 crook 7550: doc-[IF]
7551: doc-[ELSE]
7552: doc-[THEN]
7553: doc-[ENDIF]
1.1 anton 7554:
1.26 crook 7555: doc-[IFDEF]
7556: doc-[IFUNDEF]
1.1 anton 7557:
1.26 crook 7558: doc-[?DO]
7559: doc-[DO]
7560: doc-[FOR]
7561: doc-[LOOP]
7562: doc-[+LOOP]
7563: doc-[NEXT]
1.1 anton 7564:
1.26 crook 7565: doc-[BEGIN]
7566: doc-[UNTIL]
7567: doc-[AGAIN]
7568: doc-[WHILE]
7569: doc-[REPEAT]
1.1 anton 7570:
1.27 crook 7571:
1.26 crook 7572: @c -------------------------------------------------------------
1.47 crook 7573: @node Word Lists, Environmental Queries, The Text Interpreter, Words
1.26 crook 7574: @section Word Lists
7575: @cindex word lists
1.32 anton 7576: @cindex header space
1.1 anton 7577:
1.36 anton 7578: A wordlist is a list of named words; you can add new words and look up
7579: words by name (and you can remove words in a restricted way with
7580: markers). Every named (and @code{reveal}ed) word is in one wordlist.
7581:
7582: @cindex search order stack
7583: The text interpreter searches the wordlists present in the search order
7584: (a stack of wordlists), from the top to the bottom. Within each
7585: wordlist, the search starts conceptually at the newest word; i.e., if
7586: two words in a wordlist have the same name, the newer word is found.
1.1 anton 7587:
1.26 crook 7588: @cindex compilation word list
1.36 anton 7589: New words are added to the @dfn{compilation wordlist} (aka current
7590: wordlist).
1.1 anton 7591:
1.36 anton 7592: @cindex wid
7593: A word list is identified by a cell-sized word list identifier (@i{wid})
7594: in much the same way as a file is identified by a file handle. The
7595: numerical value of the wid has no (portable) meaning, and might change
7596: from session to session.
1.1 anton 7597:
1.29 crook 7598: The ANS Forth ``Search order'' word set is intended to provide a set of
7599: low-level tools that allow various different schemes to be
1.26 crook 7600: implemented. Gforth provides @code{vocabulary}, a traditional Forth
7601: word. @file{compat/vocabulary.fs} provides an implementation in ANS
1.45 crook 7602: Forth.
1.1 anton 7603:
1.27 crook 7604: @comment TODO: locals section refers to here, saying that every word list (aka
7605: @comment vocabulary) has its own methods for searching etc. Need to document that.
1.1 anton 7606:
1.45 crook 7607: @comment TODO: document markers, reveal, tables, mappedwordlist
7608:
7609: @comment the gforthman- prefix is used to pick out the true definition of a
1.27 crook 7610: @comment word from the source files, rather than some alias.
1.44 crook 7611:
1.26 crook 7612: doc-forth-wordlist
7613: doc-definitions
7614: doc-get-current
7615: doc-set-current
7616: doc-get-order
1.45 crook 7617: doc---gforthman-set-order
1.26 crook 7618: doc-wordlist
1.30 anton 7619: doc-table
1.36 anton 7620: doc-push-order
7621: doc-previous
1.26 crook 7622: doc-also
1.45 crook 7623: doc---gforthman-forth
1.26 crook 7624: doc-only
1.45 crook 7625: doc---gforthman-order
1.15 anton 7626:
1.26 crook 7627: doc-find
7628: doc-search-wordlist
1.15 anton 7629:
1.26 crook 7630: doc-words
7631: doc-vlist
1.44 crook 7632: @c doc-words-deferred
1.1 anton 7633:
1.26 crook 7634: doc-mappedwordlist
7635: doc-root
7636: doc-vocabulary
7637: doc-seal
7638: doc-vocs
7639: doc-current
7640: doc-context
1.1 anton 7641:
1.44 crook 7642:
1.26 crook 7643: @menu
1.67 anton 7644: * Why use word lists?::
7645: * Word list examples::
1.26 crook 7646: @end menu
7647:
7648: @node Why use word lists?, Word list examples, Word Lists, Word Lists
7649: @subsection Why use word lists?
7650: @cindex word lists - why use them?
7651:
1.29 crook 7652: Here are some reasons for using multiple word lists:
1.26 crook 7653:
7654: @itemize @bullet
7655: @item
1.32 anton 7656: To improve compilation speed by reducing the number of header space
1.26 crook 7657: entries that must be searched. This is achieved by creating a new
7658: word list that contains all of the definitions that are used in the
7659: definition of a Forth system but which would not usually be used by
7660: programs running on that system. That word list would be on the search
7661: list when the Forth system was compiled but would be removed from the
7662: search list for normal operation. This can be a useful technique for
7663: low-performance systems (for example, 8-bit processors in embedded
7664: systems) but is unlikely to be necessary in high-performance desktop
7665: systems.
7666: @item
7667: To prevent a set of words from being used outside the context in which
7668: they are valid. Two classic examples of this are an integrated editor
7669: (all of the edit commands are defined in a separate word list; the
7670: search order is set to the editor word list when the editor is invoked;
7671: the old search order is restored when the editor is terminated) and an
7672: integrated assembler (the op-codes for the machine are defined in a
7673: separate word list which is used when a @code{CODE} word is defined).
7674: @item
7675: To prevent a name-space clash between multiple definitions with the same
7676: name. For example, when building a cross-compiler you might have a word
7677: @code{IF} that generates conditional code for your target system. By
7678: placing this definition in a different word list you can control whether
7679: the host system's @code{IF} or the target system's @code{IF} get used in
7680: any particular context by controlling the order of the word lists on the
7681: search order stack.
7682: @end itemize
1.1 anton 7683:
1.48 anton 7684: @node Word list examples, , Why use word lists?, Word Lists
1.26 crook 7685: @subsection Word list examples
7686: @cindex word lists - examples
1.1 anton 7687:
1.26 crook 7688: Here is an example of creating and using a new wordlist using ANS
7689: Forth Standard words:
1.1 anton 7690:
7691: @example
1.26 crook 7692: wordlist constant my-new-words-wordlist
7693: : my-new-words get-order nip my-new-words-wordlist swap set-order ;
1.21 crook 7694:
1.26 crook 7695: \ add it to the search order
7696: also my-new-words
1.21 crook 7697:
1.26 crook 7698: \ alternatively, add it to the search order and make it
7699: \ the compilation word list
7700: also my-new-words definitions
7701: \ type "order" to see the problem
1.21 crook 7702: @end example
7703:
1.26 crook 7704: The problem with this example is that @code{order} has no way to
7705: associate the name @code{my-new-words} with the wid of the word list (in
7706: Gforth, @code{order} and @code{vocs} will display @code{???} for a wid
7707: that has no associated name). There is no Standard way of associating a
7708: name with a wid.
7709:
7710: In Gforth, this example can be re-coded using @code{vocabulary}, which
7711: associates a name with a wid:
1.21 crook 7712:
1.26 crook 7713: @example
7714: vocabulary my-new-words
1.21 crook 7715:
1.26 crook 7716: \ add it to the search order
1.45 crook 7717: also my-new-words
1.21 crook 7718:
1.26 crook 7719: \ alternatively, add it to the search order and make it
7720: \ the compilation word list
7721: my-new-words definitions
7722: \ type "order" to see that the problem is solved
7723: @end example
1.23 crook 7724:
1.26 crook 7725: @c -------------------------------------------------------------
7726: @node Environmental Queries, Files, Word Lists, Words
7727: @section Environmental Queries
7728: @cindex environmental queries
1.21 crook 7729:
1.26 crook 7730: ANS Forth introduced the idea of ``environmental queries'' as a way
7731: for a program running on a system to determine certain characteristics of the system.
7732: The Standard specifies a number of strings that might be recognised by a system.
1.21 crook 7733:
1.32 anton 7734: The Standard requires that the header space used for environmental queries
7735: be distinct from the header space used for definitions.
1.21 crook 7736:
1.26 crook 7737: Typically, environmental queries are supported by creating a set of
1.29 crook 7738: definitions in a word list that is @i{only} used during environmental
1.26 crook 7739: queries; that is what Gforth does. There is no Standard way of adding
7740: definitions to the set of recognised environmental queries, but any
7741: implementation that supports the loading of optional word sets must have
7742: some mechanism for doing this (after loading the word set, the
7743: associated environmental query string must return @code{true}). In
7744: Gforth, the word list used to honour environmental queries can be
7745: manipulated just like any other word list.
1.21 crook 7746:
1.44 crook 7747:
1.26 crook 7748: doc-environment?
7749: doc-environment-wordlist
1.21 crook 7750:
1.26 crook 7751: doc-gforth
7752: doc-os-class
1.21 crook 7753:
1.44 crook 7754:
1.26 crook 7755: Note that, whilst the documentation for (e.g.) @code{gforth} shows it
7756: returning two items on the stack, querying it using @code{environment?}
7757: will return an additional item; the @code{true} flag that shows that the
7758: string was recognised.
1.21 crook 7759:
1.26 crook 7760: @comment TODO Document the standard strings or note where they are documented herein
1.21 crook 7761:
1.26 crook 7762: Here are some examples of using environmental queries:
1.21 crook 7763:
1.26 crook 7764: @example
7765: s" address-unit-bits" environment? 0=
7766: [IF]
7767: cr .( environmental attribute address-units-bits unknown... ) cr
7768: [THEN]
1.21 crook 7769:
1.26 crook 7770: s" block" environment? [IF] DROP include block.fs [THEN]
1.21 crook 7771:
1.26 crook 7772: s" gforth" environment? [IF] 2DROP include compat/vocabulary.fs [THEN]
1.21 crook 7773:
1.26 crook 7774: s" gforth" environment? [IF] .( Gforth version ) TYPE
7775: [ELSE] .( Not Gforth..) [THEN]
7776: @end example
1.21 crook 7777:
7778:
1.26 crook 7779: Here is an example of adding a definition to the environment word list:
1.21 crook 7780:
1.26 crook 7781: @example
7782: get-current environment-wordlist set-current
7783: true constant block
7784: true constant block-ext
7785: set-current
7786: @end example
1.21 crook 7787:
1.26 crook 7788: You can see what definitions are in the environment word list like this:
1.21 crook 7789:
1.26 crook 7790: @example
7791: get-order 1+ environment-wordlist swap set-order words previous
7792: @end example
1.21 crook 7793:
7794:
1.26 crook 7795: @c -------------------------------------------------------------
7796: @node Files, Blocks, Environmental Queries, Words
7797: @section Files
1.28 crook 7798: @cindex files
7799: @cindex I/O - file-handling
1.21 crook 7800:
1.26 crook 7801: Gforth provides facilities for accessing files that are stored in the
7802: host operating system's file-system. Files that are processed by Gforth
7803: can be divided into two categories:
1.21 crook 7804:
1.23 crook 7805: @itemize @bullet
7806: @item
1.29 crook 7807: Files that are processed by the Text Interpreter (@dfn{Forth source files}).
1.23 crook 7808: @item
1.29 crook 7809: Files that are processed by some other program (@dfn{general files}).
1.26 crook 7810: @end itemize
7811:
1.45 crook 7812: doc-loadfilename
7813: doc-sourcefilename
7814: doc-sourceline#
7815:
1.26 crook 7816: @menu
1.48 anton 7817: * Forth source files::
7818: * General files::
7819: * Search Paths::
1.26 crook 7820: @end menu
7821:
1.21 crook 7822:
1.26 crook 7823: @c -------------------------------------------------------------
7824: @node Forth source files, General files, Files, Files
7825: @subsection Forth source files
7826: @cindex including files
7827: @cindex Forth source files
1.21 crook 7828:
1.26 crook 7829: The simplest way to interpret the contents of a file is to use one of
7830: these two formats:
1.21 crook 7831:
1.26 crook 7832: @example
7833: include mysource.fs
7834: s" mysource.fs" included
7835: @end example
1.21 crook 7836:
1.26 crook 7837: Sometimes you want to include a file only if it is not included already
7838: (by, say, another source file). In that case, you can use one of these
1.45 crook 7839: three formats:
1.21 crook 7840:
1.26 crook 7841: @example
7842: require mysource.fs
7843: needs mysource.fs
7844: s" mysource.fs" required
7845: @end example
1.21 crook 7846:
1.26 crook 7847: @cindex stack effect of included files
7848: @cindex including files, stack effect
1.45 crook 7849: It is good practice to write your source files such that interpreting them
7850: does not change the stack. Source files designed in this way can be used with
1.26 crook 7851: @code{required} and friends without complications. For example:
1.21 crook 7852:
1.26 crook 7853: @example
7854: 1 require foo.fs drop
7855: @end example
1.21 crook 7856:
1.44 crook 7857:
1.26 crook 7858: doc-include-file
7859: doc-included
1.28 crook 7860: doc-included?
1.26 crook 7861: doc-include
7862: doc-required
7863: doc-require
7864: doc-needs
1.28 crook 7865: doc-init-included-files
1.21 crook 7866:
1.44 crook 7867:
1.26 crook 7868: A definition in ANS Forth for @code{required} is provided in
7869: @file{compat/required.fs}.
1.21 crook 7870:
1.26 crook 7871: @c -------------------------------------------------------------
7872: @node General files, Search Paths, Forth source files, Files
7873: @subsection General files
7874: @cindex general files
7875: @cindex file-handling
1.21 crook 7876:
1.26 crook 7877: Files are opened/created by name and type. The following types are
7878: recognised:
1.1 anton 7879:
1.44 crook 7880:
1.26 crook 7881: doc-r/o
7882: doc-r/w
7883: doc-w/o
7884: doc-bin
1.1 anton 7885:
1.44 crook 7886:
1.26 crook 7887: When a file is opened/created, it returns a file identifier,
1.29 crook 7888: @i{wfileid} that is used for all other file commands. All file
7889: commands also return a status value, @i{wior}, that is 0 for a
1.26 crook 7890: successful operation and an implementation-defined non-zero value in the
7891: case of an error.
1.21 crook 7892:
1.44 crook 7893:
1.26 crook 7894: doc-open-file
7895: doc-create-file
1.21 crook 7896:
1.26 crook 7897: doc-close-file
7898: doc-delete-file
7899: doc-rename-file
7900: doc-read-file
7901: doc-read-line
7902: doc-write-file
7903: doc-write-line
7904: doc-emit-file
7905: doc-flush-file
1.21 crook 7906:
1.26 crook 7907: doc-file-status
7908: doc-file-position
7909: doc-reposition-file
7910: doc-file-size
7911: doc-resize-file
1.21 crook 7912:
1.44 crook 7913:
1.26 crook 7914: @c ---------------------------------------------------------
1.48 anton 7915: @node Search Paths, , General files, Files
1.26 crook 7916: @subsection Search Paths
7917: @cindex path for @code{included}
7918: @cindex file search path
7919: @cindex @code{include} search path
7920: @cindex search path for files
1.21 crook 7921:
1.26 crook 7922: If you specify an absolute filename (i.e., a filename starting with
7923: @file{/} or @file{~}, or with @file{:} in the second position (as in
7924: @samp{C:...})) for @code{included} and friends, that file is included
7925: just as you would expect.
1.21 crook 7926:
1.26 crook 7927: For relative filenames, Gforth uses a search path similar to Forth's
7928: search order (@pxref{Word Lists}). It tries to find the given filename
7929: in the directories present in the path, and includes the first one it
7930: finds. There are separate search paths for Forth source files and
7931: general files.
1.21 crook 7932:
1.26 crook 7933: If the search path contains the directory @file{.} (as it should), this
7934: refers to the directory that the present file was @code{included}
7935: from. This allows files to include other files relative to their own
7936: position (irrespective of the current working directory or the absolute
7937: position). This feature is essential for libraries consisting of
7938: several files, where a file may include other files from the library.
7939: It corresponds to @code{#include "..."} in C. If the current input
7940: source is not a file, @file{.} refers to the directory of the innermost
7941: file being included, or, if there is no file being included, to the
7942: current working directory.
1.21 crook 7943:
1.26 crook 7944: Use @file{~+} to refer to the current working directory (as in the
7945: @code{bash}).
1.1 anton 7946:
1.26 crook 7947: If the filename starts with @file{./}, the search path is not searched
7948: (just as with absolute filenames), and the @file{.} has the same meaning
7949: as described above.
1.1 anton 7950:
1.48 anton 7951: @menu
7952: * Forth Search Paths::
7953: * General Search Paths::
7954: @end menu
7955:
1.26 crook 7956: @c ---------------------------------------------------------
1.48 anton 7957: @node Forth Search Paths, General Search Paths, Search Paths, Search Paths
1.26 crook 7958: @subsubsection Forth Search Paths
1.28 crook 7959: @cindex search path control - Forth
1.5 anton 7960:
1.26 crook 7961: The search path is initialized when you start Gforth (@pxref{Invoking
7962: Gforth}). You can display it and change it using these words:
1.5 anton 7963:
1.44 crook 7964:
1.26 crook 7965: doc-.fpath
7966: doc-fpath+
7967: doc-fpath=
7968: doc-open-fpath-file
1.5 anton 7969:
1.44 crook 7970:
7971: @noindent
1.26 crook 7972: Here is an example of using @code{fpath} and @code{require}:
1.5 anton 7973:
1.26 crook 7974: @example
7975: fpath= /usr/lib/forth/|./
7976: require timer.fs
7977: @end example
1.5 anton 7978:
1.26 crook 7979: @c ---------------------------------------------------------
1.48 anton 7980: @node General Search Paths, , Forth Search Paths, Search Paths
1.26 crook 7981: @subsubsection General Search Paths
7982: @cindex search path control - for user applications
1.5 anton 7983:
1.26 crook 7984: Your application may need to search files in several directories, like
7985: @code{included} does. To facilitate this, Gforth allows you to define
7986: and use your own search paths, by providing generic equivalents of the
7987: Forth search path words:
1.5 anton 7988:
1.44 crook 7989:
1.26 crook 7990: doc-.path
7991: doc-path+
7992: doc-path=
7993: doc-open-path-file
1.5 anton 7994:
1.44 crook 7995:
1.26 crook 7996: Here's an example of creating a search path:
1.5 anton 7997:
1.26 crook 7998: @example
7999: \ Make a buffer for the path:
8000: create mypath 100 chars , \ maximum length (is checked)
8001: 0 , \ real len
8002: 100 chars allot \ space for path
8003: @end example
1.5 anton 8004:
1.26 crook 8005: @c -------------------------------------------------------------
8006: @node Blocks, Other I/O, Files, Words
8007: @section Blocks
1.28 crook 8008: @cindex I/O - blocks
8009: @cindex blocks
8010:
8011: When you run Gforth on a modern desk-top computer, it runs under the
8012: control of an operating system which provides certain services. One of
8013: these services is @var{file services}, which allows Forth source code
8014: and data to be stored in files and read into Gforth (@pxref{Files}).
8015:
8016: Traditionally, Forth has been an important programming language on
8017: systems where it has interfaced directly to the underlying hardware with
8018: no intervening operating system. Forth provides a mechanism, called
1.29 crook 8019: @dfn{blocks}, for accessing mass storage on such systems.
1.28 crook 8020:
8021: A block is a 1024-byte data area, which can be used to hold data or
8022: Forth source code. No structure is imposed on the contents of the
8023: block. A block is identified by its number; blocks are numbered
8024: contiguously from 1 to an implementation-defined maximum.
8025:
8026: A typical system that used blocks but no operating system might use a
8027: single floppy-disk drive for mass storage, with the disks formatted to
8028: provide 256-byte sectors. Blocks would be implemented by assigning the
8029: first four sectors of the disk to block 1, the second four sectors to
8030: block 2 and so on, up to the limit of the capacity of the disk. The disk
8031: would not contain any file system information, just the set of blocks.
8032:
1.29 crook 8033: @cindex blocks file
1.28 crook 8034: On systems that do provide file services, blocks are typically
1.29 crook 8035: implemented by storing a sequence of blocks within a single @dfn{blocks
1.28 crook 8036: file}. The size of the blocks file will be an exact multiple of 1024
8037: bytes, corresponding to the number of blocks it contains. This is the
8038: mechanism that Gforth uses.
8039:
1.29 crook 8040: @cindex @file{blocks.fb}
1.28 crook 8041: Only 1 blocks file can be open at a time. If you use block words without
8042: having specified a blocks file, Gforth defaults to the blocks file
8043: @file{blocks.fb}. Gforth uses the Forth search path when attempting to
8044: locate a blocks file (@pxref{Forth Search Paths}).
8045:
1.29 crook 8046: @cindex block buffers
1.28 crook 8047: When you read and write blocks under program control, Gforth uses a
1.29 crook 8048: number of @dfn{block buffers} as intermediate storage. These buffers are
1.28 crook 8049: not used when you use @code{load} to interpret the contents of a block.
8050:
8051: The behaviour of the block buffers is directly analagous to that of a
8052: cache. Each block buffer has three states:
8053:
8054: @itemize @bullet
8055: @item
8056: Unassigned
8057: @item
8058: Assigned-clean
8059: @item
8060: Assigned-dirty
8061: @end itemize
8062:
1.29 crook 8063: Initially, all block buffers are @i{unassigned}. In order to access a
1.28 crook 8064: block, the block (specified by its block number) must be assigned to a
8065: block buffer.
8066:
8067: The assignment of a block to a block buffer is performed by @code{block}
8068: or @code{buffer}. Use @code{block} when you wish to modify the existing
8069: contents of a block. Use @code{buffer} when you don't care about the
8070: existing contents of the block@footnote{The ANS Forth definition of
1.35 anton 8071: @code{buffer} is intended not to cause disk I/O; if the data associated
1.28 crook 8072: with the particular block is already stored in a block buffer due to an
8073: earlier @code{block} command, @code{buffer} will return that block
8074: buffer and the existing contents of the block will be
8075: available. Otherwise, @code{buffer} will simply assign a new, empty
1.29 crook 8076: block buffer for the block.}.
1.28 crook 8077:
1.47 crook 8078: Once a block has been assigned to a block buffer using @code{block} or
8079: @code{buffer}, that block buffer becomes the @i{current block buffer}
8080: and its state changes to @i{assigned-clean}. Data may only be
8081: manipulated (read or written) within the current block buffer.
8082:
8083: When the contents of the current block buffer has been modified it is
1.48 anton 8084: necessary, @emph{before calling @code{block} or @code{buffer} again}, to
8085: either abandon the changes (by doing nothing) or commit the changes,
8086: using @code{update}. Using @code{update} does not change the blocks
8087: file; it simply changes a block buffer's state to @i{assigned-dirty}.
1.28 crook 8088:
1.29 crook 8089: The word @code{flush} causes all @i{assigned-dirty} blocks to be
1.28 crook 8090: written back to the blocks file on disk. Leaving Gforth using @code{bye}
8091: also causes a @code{flush} to be performed.
8092:
1.29 crook 8093: In Gforth, @code{block} and @code{buffer} use a @i{direct-mapped}
1.28 crook 8094: algorithm to assign a block buffer to a block. That means that any
8095: particular block can only be assigned to one specific block buffer,
1.29 crook 8096: called (for the particular operation) the @i{victim buffer}. If the
1.47 crook 8097: victim buffer is @i{unassigned} or @i{assigned-clean} it is allocated to
8098: the new block immediately. If it is @i{assigned-dirty} its current
8099: contents are written back to the blocks file on disk before it is
1.28 crook 8100: allocated to the new block.
8101:
8102: Although no structure is imposed on the contents of a block, it is
8103: traditional to display the contents as 16 lines each of 64 characters. A
8104: block provides a single, continuous stream of input (for example, it
8105: acts as a single parse area) -- there are no end-of-line characters
8106: within a block, and no end-of-file character at the end of a
8107: block. There are two consequences of this:
1.26 crook 8108:
1.28 crook 8109: @itemize @bullet
8110: @item
8111: The last character of one line wraps straight into the first character
8112: of the following line
8113: @item
8114: The word @code{\} -- comment to end of line -- requires special
8115: treatment; in the context of a block it causes all characters until the
8116: end of the current 64-character ``line'' to be ignored.
8117: @end itemize
8118:
8119: In Gforth, when you use @code{block} with a non-existent block number,
1.45 crook 8120: the current blocks file will be extended to the appropriate size and the
1.28 crook 8121: block buffer will be initialised with spaces.
8122:
1.47 crook 8123: Gforth includes a simple block editor (type @code{use blocked.fb 0 list}
8124: for details) but doesn't encourage the use of blocks; the mechanism is
8125: only provided for backward compatibility -- ANS Forth requires blocks to
8126: be available when files are.
1.28 crook 8127:
8128: Common techniques that are used when working with blocks include:
8129:
8130: @itemize @bullet
8131: @item
8132: A screen editor that allows you to edit blocks without leaving the Forth
8133: environment.
8134: @item
8135: Shadow screens; where every code block has an associated block
8136: containing comments (for example: code in odd block numbers, comments in
8137: even block numbers). Typically, the block editor provides a convenient
8138: mechanism to toggle between code and comments.
8139: @item
8140: Load blocks; a single block (typically block 1) contains a number of
8141: @code{thru} commands which @code{load} the whole of the application.
8142: @end itemize
1.26 crook 8143:
1.29 crook 8144: See Frank Sergeant's Pygmy Forth to see just how well blocks can be
8145: integrated into a Forth programming environment.
1.26 crook 8146:
8147: @comment TODO what about errors on open-blocks?
1.44 crook 8148:
1.26 crook 8149: doc-open-blocks
8150: doc-use
8151: doc-get-block-fid
8152: doc-block-position
1.28 crook 8153:
8154: doc-scr
8155: doc-list
8156:
1.45 crook 8157: doc---gforthman-block
1.28 crook 8158: doc-buffer
8159:
1.26 crook 8160: doc-update
1.28 crook 8161: doc-updated?
1.26 crook 8162: doc-save-buffers
8163: doc-empty-buffers
8164: doc-empty-buffer
8165: doc-flush
1.28 crook 8166:
1.26 crook 8167: doc-load
8168: doc-thru
8169: doc-+load
8170: doc-+thru
1.45 crook 8171: doc---gforthman--->
1.26 crook 8172: doc-block-included
8173:
1.44 crook 8174:
1.26 crook 8175: @c -------------------------------------------------------------
8176: @node Other I/O, Programming Tools, Blocks, Words
8177: @section Other I/O
1.28 crook 8178: @cindex I/O - keyboard and display
1.26 crook 8179:
8180: @menu
8181: * Simple numeric output:: Predefined formats
8182: * Formatted numeric output:: Formatted (pictured) output
8183: * String Formats:: How Forth stores strings in memory
1.67 anton 8184: * Displaying characters and strings:: Other stuff
1.26 crook 8185: * Input:: Input
8186: @end menu
8187:
8188: @node Simple numeric output, Formatted numeric output, Other I/O, Other I/O
8189: @subsection Simple numeric output
1.28 crook 8190: @cindex numeric output - simple/free-format
1.5 anton 8191:
1.26 crook 8192: The simplest output functions are those that display numbers from the
8193: data or floating-point stacks. Floating-point output is always displayed
8194: using base 10. Numbers displayed from the data stack use the value stored
8195: in @code{base}.
1.5 anton 8196:
1.44 crook 8197:
1.26 crook 8198: doc-.
8199: doc-dec.
8200: doc-hex.
8201: doc-u.
8202: doc-.r
8203: doc-u.r
8204: doc-d.
8205: doc-ud.
8206: doc-d.r
8207: doc-ud.r
8208: doc-f.
8209: doc-fe.
8210: doc-fs.
1.5 anton 8211:
1.44 crook 8212:
1.26 crook 8213: Examples of printing the number 1234.5678E23 in the different floating-point output
8214: formats are shown below:
1.5 anton 8215:
8216: @example
1.26 crook 8217: f. 123456779999999000000000000.
8218: fe. 123.456779999999E24
8219: fs. 1.23456779999999E26
1.5 anton 8220: @end example
8221:
8222:
1.26 crook 8223: @node Formatted numeric output, String Formats, Simple numeric output, Other I/O
8224: @subsection Formatted numeric output
1.28 crook 8225: @cindex formatted numeric output
1.26 crook 8226: @cindex pictured numeric output
1.28 crook 8227: @cindex numeric output - formatted
1.26 crook 8228:
1.29 crook 8229: Forth traditionally uses a technique called @dfn{pictured numeric
1.26 crook 8230: output} for formatted printing of integers. In this technique, digits
8231: are extracted from the number (using the current output radix defined by
8232: @code{base}), converted to ASCII codes and appended to a string that is
8233: built in a scratch-pad area of memory (@pxref{core-idef,
8234: Implementation-defined options, Implementation-defined
8235: options}). Arbitrary characters can be appended to the string during the
8236: extraction process. The completed string is specified by an address
8237: and length and can be manipulated (@code{TYPE}ed, copied, modified)
8238: under program control.
1.5 anton 8239:
1.26 crook 8240: All of the words described in the previous section for simple numeric
8241: output are implemented in Gforth using pictured numeric output.
1.5 anton 8242:
1.47 crook 8243: Three important things to remember about pictured numeric output:
1.5 anton 8244:
1.26 crook 8245: @itemize @bullet
8246: @item
1.28 crook 8247: It always operates on double-precision numbers; to display a
1.49 anton 8248: single-precision number, convert it first (for ways of doing this
8249: @pxref{Double precision}).
1.26 crook 8250: @item
1.28 crook 8251: It always treats the double-precision number as though it were
8252: unsigned. The examples below show ways of printing signed numbers.
1.26 crook 8253: @item
8254: The string is built up from right to left; least significant digit first.
8255: @end itemize
1.5 anton 8256:
1.44 crook 8257:
1.26 crook 8258: doc-<#
1.47 crook 8259: doc-<<#
1.26 crook 8260: doc-#
8261: doc-#s
8262: doc-hold
8263: doc-sign
8264: doc-#>
1.47 crook 8265: doc-#>>
1.5 anton 8266:
1.26 crook 8267: doc-represent
1.5 anton 8268:
1.44 crook 8269:
8270: @noindent
1.26 crook 8271: Here are some examples of using pictured numeric output:
1.5 anton 8272:
8273: @example
1.26 crook 8274: : my-u. ( u -- )
8275: \ Simplest use of pns.. behaves like Standard u.
8276: 0 \ convert to unsigned double
8277: <# \ start conversion
8278: #s \ convert all digits
8279: #> \ complete conversion
8280: TYPE SPACE ; \ display, with trailing space
1.5 anton 8281:
1.26 crook 8282: : cents-only ( u -- )
8283: 0 \ convert to unsigned double
8284: <# \ start conversion
8285: # # \ convert two least-significant digits
8286: #> \ complete conversion, discard other digits
8287: TYPE SPACE ; \ display, with trailing space
1.5 anton 8288:
1.26 crook 8289: : dollars-and-cents ( u -- )
8290: 0 \ convert to unsigned double
8291: <# \ start conversion
8292: # # \ convert two least-significant digits
8293: [char] . hold \ insert decimal point
8294: #s \ convert remaining digits
8295: [char] $ hold \ append currency symbol
8296: #> \ complete conversion
8297: TYPE SPACE ; \ display, with trailing space
1.5 anton 8298:
1.26 crook 8299: : my-. ( n -- )
8300: \ handling negatives.. behaves like Standard .
8301: s>d \ convert to signed double
8302: swap over dabs \ leave sign byte followed by unsigned double
8303: <# \ start conversion
8304: #s \ convert all digits
8305: rot sign \ get at sign byte, append "-" if needed
8306: #> \ complete conversion
8307: TYPE SPACE ; \ display, with trailing space
1.5 anton 8308:
1.26 crook 8309: : account. ( n -- )
8310: \ accountants don't like minus signs, they use braces
8311: \ for negative numbers
8312: s>d \ convert to signed double
8313: swap over dabs \ leave sign byte followed by unsigned double
8314: <# \ start conversion
8315: 2 pick \ get copy of sign byte
8316: 0< IF [char] ) hold THEN \ right-most character of output
8317: #s \ convert all digits
8318: rot \ get at sign byte
8319: 0< IF [char] ( hold THEN
8320: #> \ complete conversion
8321: TYPE SPACE ; \ display, with trailing space
1.5 anton 8322: @end example
8323:
1.26 crook 8324: Here are some examples of using these words:
1.5 anton 8325:
8326: @example
1.26 crook 8327: 1 my-u. 1
8328: hex -1 my-u. decimal FFFFFFFF
8329: 1 cents-only 01
8330: 1234 cents-only 34
8331: 2 dollars-and-cents $0.02
8332: 1234 dollars-and-cents $12.34
8333: 123 my-. 123
8334: -123 my. -123
8335: 123 account. 123
8336: -456 account. (456)
1.5 anton 8337: @end example
8338:
8339:
1.26 crook 8340: @node String Formats, Displaying characters and strings, Formatted numeric output, Other I/O
8341: @subsection String Formats
1.27 crook 8342: @cindex strings - see character strings
8343: @cindex character strings - formats
1.28 crook 8344: @cindex I/O - see character strings
1.26 crook 8345:
1.27 crook 8346: Forth commonly uses two different methods for representing character
8347: strings:
1.26 crook 8348:
8349: @itemize @bullet
8350: @item
8351: @cindex address of counted string
1.45 crook 8352: @cindex counted string
1.29 crook 8353: As a @dfn{counted string}, represented by a @i{c-addr}. The char
8354: addressed by @i{c-addr} contains a character-count, @i{n}, of the
8355: string and the string occupies the subsequent @i{n} char addresses in
1.26 crook 8356: memory.
8357: @item
1.29 crook 8358: As cell pair on the stack; @i{c-addr u}, where @i{u} is the length
8359: of the string in characters, and @i{c-addr} is the address of the
1.26 crook 8360: first byte of the string.
8361: @end itemize
8362:
8363: ANS Forth encourages the use of the second format when representing
8364: strings on the stack, whilst conceeding that the counted string format
8365: remains useful as a way of storing strings in memory.
8366:
1.44 crook 8367:
1.26 crook 8368: doc-count
8369:
1.44 crook 8370:
1.49 anton 8371: For words that move, copy and search for strings see @ref{Memory
8372: Blocks}. For words that display characters and strings see
8373: @ref{Displaying characters and strings}.
1.26 crook 8374:
8375: @node Displaying characters and strings, Input, String Formats, Other I/O
8376: @subsection Displaying characters and strings
1.27 crook 8377: @cindex characters - compiling and displaying
8378: @cindex character strings - compiling and displaying
1.26 crook 8379:
8380: This section starts with a glossary of Forth words and ends with a set
8381: of examples.
8382:
1.44 crook 8383:
1.26 crook 8384: doc-bl
8385: doc-space
8386: doc-spaces
8387: doc-emit
8388: doc-toupper
8389: doc-."
8390: doc-.(
8391: doc-type
1.44 crook 8392: doc-typewhite
1.26 crook 8393: doc-cr
1.27 crook 8394: @cindex cursor control
1.26 crook 8395: doc-at-xy
8396: doc-page
8397: doc-s"
8398: doc-c"
8399: doc-char
8400: doc-[char]
8401: doc-sliteral
8402:
1.44 crook 8403:
8404: @noindent
1.26 crook 8405: As an example, consider the following text, stored in a file @file{test.fs}:
1.5 anton 8406:
8407: @example
1.26 crook 8408: .( text-1)
8409: : my-word
8410: ." text-2" cr
8411: .( text-3)
8412: ;
8413:
8414: ." text-4"
8415:
8416: : my-char
8417: [char] ALPHABET emit
8418: char emit
8419: ;
1.5 anton 8420: @end example
8421:
1.26 crook 8422: When you load this code into Gforth, the following output is generated:
1.5 anton 8423:
1.26 crook 8424: @example
1.30 anton 8425: @kbd{include test.fs @key{RET}} text-1text-3text-4 ok
1.26 crook 8426: @end example
1.5 anton 8427:
1.26 crook 8428: @itemize @bullet
8429: @item
8430: Messages @code{text-1} and @code{text-3} are displayed because @code{.(}
8431: is an immediate word; it behaves in the same way whether it is used inside
8432: or outside a colon definition.
8433: @item
8434: Message @code{text-4} is displayed because of Gforth's added interpretation
8435: semantics for @code{."}.
8436: @item
1.29 crook 8437: Message @code{text-2} is @i{not} displayed, because the text interpreter
1.26 crook 8438: performs the compilation semantics for @code{."} within the definition of
8439: @code{my-word}.
8440: @end itemize
1.5 anton 8441:
1.26 crook 8442: Here are some examples of executing @code{my-word} and @code{my-char}:
1.5 anton 8443:
1.26 crook 8444: @example
1.30 anton 8445: @kbd{my-word @key{RET}} text-2
1.26 crook 8446: ok
1.30 anton 8447: @kbd{my-char fred @key{RET}} Af ok
8448: @kbd{my-char jim @key{RET}} Aj ok
1.26 crook 8449: @end example
1.5 anton 8450:
8451: @itemize @bullet
8452: @item
1.26 crook 8453: Message @code{text-2} is displayed because of the run-time behaviour of
8454: @code{."}.
8455: @item
8456: @code{[char]} compiles the ``A'' from ``ALPHABET'' and puts its display code
8457: on the stack at run-time. @code{emit} always displays the character
8458: when @code{my-char} is executed.
8459: @item
8460: @code{char} parses a string at run-time and the second @code{emit} displays
8461: the first character of the string.
1.5 anton 8462: @item
1.26 crook 8463: If you type @code{see my-char} you can see that @code{[char]} discarded
8464: the text ``LPHABET'' and only compiled the display code for ``A'' into the
8465: definition of @code{my-char}.
1.5 anton 8466: @end itemize
8467:
8468:
8469:
1.48 anton 8470: @node Input, , Displaying characters and strings, Other I/O
1.26 crook 8471: @subsection Input
8472: @cindex input
1.28 crook 8473: @cindex I/O - see input
8474: @cindex parsing a string
1.5 anton 8475:
1.49 anton 8476: For ways of storing character strings in memory see @ref{String Formats}.
1.5 anton 8477:
1.27 crook 8478: @comment TODO examples for >number >float accept key key? pad parse word refill
1.29 crook 8479: @comment then index them
1.27 crook 8480:
1.44 crook 8481:
1.27 crook 8482: doc-key
8483: doc-key?
1.45 crook 8484: doc-ekey
8485: doc-ekey?
8486: doc-ekey>char
1.26 crook 8487: doc->number
8488: doc->float
8489: doc-accept
1.27 crook 8490: doc-pad
8491: doc-parse
8492: doc-word
8493: doc-sword
1.44 crook 8494: doc-(name)
1.27 crook 8495: doc-refill
8496: @comment obsolescent words..
8497: doc-convert
1.26 crook 8498: doc-query
8499: doc-expect
1.27 crook 8500: doc-span
1.5 anton 8501:
8502:
1.44 crook 8503:
1.5 anton 8504: @c -------------------------------------------------------------
1.26 crook 8505: @node Programming Tools, Assembler and Code Words, Other I/O, Words
8506: @section Programming Tools
8507: @cindex programming tools
1.12 anton 8508:
8509: @menu
1.26 crook 8510: * Debugging:: Simple and quick.
8511: * Assertions:: Making your programs self-checking.
1.46 pazsan 8512: * Singlestep Debugger:: Executing your program word by word.
1.5 anton 8513: @end menu
8514:
1.26 crook 8515: @node Debugging, Assertions, Programming Tools, Programming Tools
8516: @subsection Debugging
8517: @cindex debugging
1.5 anton 8518:
1.26 crook 8519: Languages with a slow edit/compile/link/test development loop tend to
8520: require sophisticated tracing/stepping debuggers to facilate
8521: productive debugging.
1.5 anton 8522:
1.26 crook 8523: A much better (faster) way in fast-compiling languages is to add
8524: printing code at well-selected places, let the program run, look at
8525: the output, see where things went wrong, add more printing code, etc.,
8526: until the bug is found.
1.5 anton 8527:
1.26 crook 8528: The simple debugging aids provided in @file{debugs.fs}
8529: are meant to support this style of debugging. In addition, there are
8530: words for non-destructively inspecting the stack and memory:
1.5 anton 8531:
1.44 crook 8532:
1.26 crook 8533: doc-.s
8534: doc-f.s
1.5 anton 8535:
1.44 crook 8536:
1.29 crook 8537: There is a word @code{.r} but it does @i{not} display the return
1.26 crook 8538: stack! It is used for formatted numeric output.
1.5 anton 8539:
1.44 crook 8540:
1.26 crook 8541: doc-depth
8542: doc-fdepth
8543: doc-clearstack
8544: doc-?
8545: doc-dump
1.5 anton 8546:
1.44 crook 8547:
1.26 crook 8548: The word @code{~~} prints debugging information (by default the source
8549: location and the stack contents). It is easy to insert. If you use Emacs
8550: it is also easy to remove (@kbd{C-x ~} in the Emacs Forth mode to
8551: query-replace them with nothing). The deferred words
8552: @code{printdebugdata} and @code{printdebugline} control the output of
8553: @code{~~}. The default source location output format works well with
8554: Emacs' compilation mode, so you can step through the program at the
8555: source level using @kbd{C-x `} (the advantage over a stepping debugger
8556: is that you can step in any direction and you know where the crash has
8557: happened or where the strange data has occurred).
1.5 anton 8558:
1.26 crook 8559: The default actions of @code{~~} clobber the contents of the pictured
8560: numeric output string, so you should not use @code{~~}, e.g., between
8561: @code{<#} and @code{#>}.
1.5 anton 8562:
1.44 crook 8563:
1.26 crook 8564: doc-~~
8565: doc-printdebugdata
8566: doc-printdebugline
1.5 anton 8567:
1.26 crook 8568: doc-see
8569: doc-marker
1.5 anton 8570:
1.44 crook 8571:
1.26 crook 8572: Here's an example of using @code{marker} at the start of a source file
8573: that you are debugging; it ensures that you only ever have one copy of
8574: the file's definitions compiled at any time:
1.5 anton 8575:
1.26 crook 8576: @example
8577: [IFDEF] my-code
8578: my-code
8579: [ENDIF]
1.5 anton 8580:
1.26 crook 8581: marker my-code
1.28 crook 8582: init-included-files
1.5 anton 8583:
1.26 crook 8584: \ .. definitions start here
8585: \ .
8586: \ .
8587: \ end
8588: @end example
1.5 anton 8589:
8590:
8591:
1.26 crook 8592: @node Assertions, Singlestep Debugger, Debugging, Programming Tools
8593: @subsection Assertions
8594: @cindex assertions
1.5 anton 8595:
1.26 crook 8596: It is a good idea to make your programs self-checking, especially if you
8597: make an assumption that may become invalid during maintenance (for
8598: example, that a certain field of a data structure is never zero). Gforth
1.29 crook 8599: supports @dfn{assertions} for this purpose. They are used like this:
1.23 crook 8600:
1.26 crook 8601: @example
1.29 crook 8602: assert( @i{flag} )
1.26 crook 8603: @end example
1.23 crook 8604:
1.26 crook 8605: The code between @code{assert(} and @code{)} should compute a flag, that
8606: should be true if everything is alright and false otherwise. It should
8607: not change anything else on the stack. The overall stack effect of the
8608: assertion is @code{( -- )}. E.g.
1.23 crook 8609:
1.26 crook 8610: @example
8611: assert( 1 1 + 2 = ) \ what we learn in school
8612: assert( dup 0<> ) \ assert that the top of stack is not zero
8613: assert( false ) \ this code should not be reached
8614: @end example
1.23 crook 8615:
1.26 crook 8616: The need for assertions is different at different times. During
8617: debugging, we want more checking, in production we sometimes care more
8618: for speed. Therefore, assertions can be turned off, i.e., the assertion
8619: becomes a comment. Depending on the importance of an assertion and the
8620: time it takes to check it, you may want to turn off some assertions and
8621: keep others turned on. Gforth provides several levels of assertions for
8622: this purpose:
1.23 crook 8623:
1.44 crook 8624:
1.26 crook 8625: doc-assert0(
8626: doc-assert1(
8627: doc-assert2(
8628: doc-assert3(
8629: doc-assert(
8630: doc-)
1.23 crook 8631:
1.44 crook 8632:
1.26 crook 8633: The variable @code{assert-level} specifies the highest assertions that
8634: are turned on. I.e., at the default @code{assert-level} of one,
8635: @code{assert0(} and @code{assert1(} assertions perform checking, while
8636: @code{assert2(} and @code{assert3(} assertions are treated as comments.
8637:
8638: The value of @code{assert-level} is evaluated at compile-time, not at
8639: run-time. Therefore you cannot turn assertions on or off at run-time;
8640: you have to set the @code{assert-level} appropriately before compiling a
8641: piece of code. You can compile different pieces of code at different
8642: @code{assert-level}s (e.g., a trusted library at level 1 and
8643: newly-written code at level 3).
1.23 crook 8644:
1.44 crook 8645:
1.26 crook 8646: doc-assert-level
1.23 crook 8647:
1.44 crook 8648:
1.26 crook 8649: If an assertion fails, a message compatible with Emacs' compilation mode
8650: is produced and the execution is aborted (currently with @code{ABORT"}.
8651: If there is interest, we will introduce a special throw code. But if you
8652: intend to @code{catch} a specific condition, using @code{throw} is
8653: probably more appropriate than an assertion).
1.23 crook 8654:
1.26 crook 8655: Definitions in ANS Forth for these assertion words are provided
8656: in @file{compat/assert.fs}.
1.23 crook 8657:
8658:
1.48 anton 8659: @node Singlestep Debugger, , Assertions, Programming Tools
1.26 crook 8660: @subsection Singlestep Debugger
8661: @cindex singlestep Debugger
8662: @cindex debugging Singlestep
1.23 crook 8663:
1.26 crook 8664: When you create a new word there's often the need to check whether it
8665: behaves correctly or not. You can do this by typing @code{dbg
8666: badword}. A debug session might look like this:
1.23 crook 8667:
1.26 crook 8668: @example
8669: : badword 0 DO i . LOOP ; ok
8670: 2 dbg badword
8671: : badword
8672: Scanning code...
1.23 crook 8673:
1.26 crook 8674: Nesting debugger ready!
1.23 crook 8675:
1.26 crook 8676: 400D4738 8049BC4 0 -> [ 2 ] 00002 00000
8677: 400D4740 8049F68 DO -> [ 0 ]
8678: 400D4744 804A0C8 i -> [ 1 ] 00000
8679: 400D4748 400C5E60 . -> 0 [ 0 ]
8680: 400D474C 8049D0C LOOP -> [ 0 ]
8681: 400D4744 804A0C8 i -> [ 1 ] 00001
8682: 400D4748 400C5E60 . -> 1 [ 0 ]
8683: 400D474C 8049D0C LOOP -> [ 0 ]
8684: 400D4758 804B384 ; -> ok
8685: @end example
1.23 crook 8686:
1.26 crook 8687: Each line displayed is one step. You always have to hit return to
8688: execute the next word that is displayed. If you don't want to execute
8689: the next word in a whole, you have to type @kbd{n} for @code{nest}. Here is
8690: an overview what keys are available:
1.23 crook 8691:
1.26 crook 8692: @table @i
1.23 crook 8693:
1.30 anton 8694: @item @key{RET}
1.26 crook 8695: Next; Execute the next word.
1.23 crook 8696:
1.26 crook 8697: @item n
8698: Nest; Single step through next word.
1.5 anton 8699:
1.26 crook 8700: @item u
8701: Unnest; Stop debugging and execute rest of word. If we got to this word
8702: with nest, continue debugging with the calling word.
1.5 anton 8703:
1.26 crook 8704: @item d
8705: Done; Stop debugging and execute rest.
1.5 anton 8706:
1.26 crook 8707: @item s
8708: Stop; Abort immediately.
1.5 anton 8709:
1.26 crook 8710: @end table
1.5 anton 8711:
1.26 crook 8712: Debugging large application with this mechanism is very difficult, because
8713: you have to nest very deeply into the program before the interesting part
8714: begins. This takes a lot of time.
1.5 anton 8715:
1.26 crook 8716: To do it more directly put a @code{BREAK:} command into your source code.
8717: When program execution reaches @code{BREAK:} the single step debugger is
8718: invoked and you have all the features described above.
1.23 crook 8719:
1.26 crook 8720: If you have more than one part to debug it is useful to know where the
8721: program has stopped at the moment. You can do this by the
8722: @code{BREAK" string"} command. This behaves like @code{BREAK:} except that
8723: string is typed out when the ``breakpoint'' is reached.
8724:
1.44 crook 8725:
1.26 crook 8726: doc-dbg
1.45 crook 8727: doc-break:
8728: doc-break"
1.26 crook 8729:
8730:
1.44 crook 8731:
1.26 crook 8732: @c -------------------------------------------------------------
8733: @node Assembler and Code Words, Threading Words, Programming Tools, Words
8734: @section Assembler and Code Words
8735: @cindex assembler
8736: @cindex code words
1.5 anton 8737:
1.52 anton 8738: @menu
1.53 anton 8739: * Code and ;code::
8740: * Common Assembler:: Assembler Syntax
1.52 anton 8741: * Common Disassembler::
8742: * 386 Assembler:: Deviations and special cases
8743: * Alpha Assembler:: Deviations and special cases
8744: * MIPS assembler:: Deviations and special cases
1.53 anton 8745: * Other assemblers:: How to write them
1.52 anton 8746: @end menu
8747:
1.53 anton 8748: @node Code and ;code, Common Assembler, Assembler and Code Words, Assembler and Code Words
8749: @subsection @code{Code} and @code{;code}
1.52 anton 8750:
1.26 crook 8751: Gforth provides some words for defining primitives (words written in
1.29 crook 8752: machine code), and for defining the machine-code equivalent of
1.26 crook 8753: @code{DOES>}-based defining words. However, the machine-independent
8754: nature of Gforth poses a few problems: First of all, Gforth runs on
8755: several architectures, so it can provide no standard assembler. What's
8756: worse is that the register allocation not only depends on the processor,
8757: but also on the @code{gcc} version and options used.
1.5 anton 8758:
1.29 crook 8759: The words that Gforth offers encapsulate some system dependences (e.g.,
8760: the header structure), so a system-independent assembler may be used in
1.26 crook 8761: Gforth. If you do not have an assembler, you can compile machine code
1.29 crook 8762: directly with @code{,} and @code{c,}@footnote{This isn't portable,
8763: because these words emit stuff in @i{data} space; it works because
8764: Gforth has unified code/data spaces. Assembler isn't likely to be
8765: portable anyway.}.
1.5 anton 8766:
1.44 crook 8767:
1.26 crook 8768: doc-assembler
1.45 crook 8769: doc-init-asm
1.26 crook 8770: doc-code
8771: doc-end-code
8772: doc-;code
8773: doc-flush-icache
1.5 anton 8774:
1.44 crook 8775:
1.26 crook 8776: If @code{flush-icache} does not work correctly, @code{code} words
8777: etc. will not work (reliably), either.
1.5 anton 8778:
1.29 crook 8779: The typical usage of these @code{code} words can be shown most easily by
8780: analogy to the equivalent high-level defining words:
8781:
8782: @example
1.53 anton 8783: : foo code foo
8784: <high-level Forth words> <assembler>
8785: ; end-code
8786:
8787: : bar : bar
8788: <high-level Forth words> <high-level Forth words>
8789: CREATE CREATE
8790: <high-level Forth words> <high-level Forth words>
8791: DOES> ;code
8792: <high-level Forth words> <assembler>
8793: ; end-code
1.29 crook 8794: @end example
8795:
1.26 crook 8796: @code{flush-icache} is always present. The other words are rarely used
8797: and reside in @code{code.fs}, which is usually not loaded. You can load
8798: it with @code{require code.fs}.
1.5 anton 8799:
1.26 crook 8800: @cindex registers of the inner interpreter
8801: In the assembly code you will want to refer to the inner interpreter's
8802: registers (e.g., the data stack pointer) and you may want to use other
8803: registers for temporary storage. Unfortunately, the register allocation
8804: is installation-dependent.
1.5 anton 8805:
1.26 crook 8806: The easiest solution is to use explicit register declarations
8807: (@pxref{Explicit Reg Vars, , Variables in Specified Registers, gcc.info,
8808: GNU C Manual}) for all of the inner interpreter's registers: You have to
8809: compile Gforth with @code{-DFORCE_REG} (configure option
8810: @code{--enable-force-reg}) and the appropriate declarations must be
8811: present in the @code{machine.h} file (see @code{mips.h} for an example;
8812: you can find a full list of all declarable register symbols with
8813: @code{grep register engine.c}). If you give explicit registers to all
8814: variables that are declared at the beginning of @code{engine()}, you
8815: should be able to use the other caller-saved registers for temporary
8816: storage. Alternatively, you can use the @code{gcc} option
8817: @code{-ffixed-REG} (@pxref{Code Gen Options, , Options for Code
8818: Generation Conventions, gcc.info, GNU C Manual}) to reserve a register
8819: (however, this restriction on register allocation may slow Gforth
8820: significantly).
1.5 anton 8821:
1.26 crook 8822: If this solution is not viable (e.g., because @code{gcc} does not allow
8823: you to explicitly declare all the registers you need), you have to find
8824: out by looking at the code where the inner interpreter's registers
8825: reside and which registers can be used for temporary storage. You can
8826: get an assembly listing of the engine's code with @code{make engine.s}.
1.5 anton 8827:
1.26 crook 8828: In any case, it is good practice to abstract your assembly code from the
8829: actual register allocation. E.g., if the data stack pointer resides in
8830: register @code{$17}, create an alias for this register called @code{sp},
8831: and use that in your assembly code.
1.5 anton 8832:
1.26 crook 8833: @cindex code words, portable
8834: Another option for implementing normal and defining words efficiently
8835: is to add the desired functionality to the source of Gforth. For normal
8836: words you just have to edit @file{primitives} (@pxref{Automatic
8837: Generation}). Defining words (equivalent to @code{;CODE} words, for fast
8838: defined words) may require changes in @file{engine.c}, @file{kernel.fs},
8839: @file{prims2x.fs}, and possibly @file{cross.fs}.
1.5 anton 8840:
1.53 anton 8841: @node Common Assembler, Common Disassembler, Code and ;code, Assembler and Code Words
8842: @subsection Common Assembler
8843:
8844: The assemblers in Gforth generally use a postfix syntax, i.e., the
8845: instruction name follows the operands.
8846:
8847: The operands are passed in the usual order (the same that is used in the
8848: manual of the architecture). Since they all are Forth words, they have
8849: to be separated by spaces; you can also use Forth words to compute the
8850: operands.
8851:
8852: The instruction names usually end with a @code{,}. This makes it easier
8853: to visually separate instructions if you put several of them on one
8854: line; it also avoids shadowing other Forth words (e.g., @code{and}).
8855:
1.55 anton 8856: Registers are usually specified by number; e.g., (decimal) @code{11}
8857: specifies registers R11 and F11 on the Alpha architecture (which one,
8858: depends on the instruction). The usual names are also available, e.g.,
8859: @code{s2} for R11 on Alpha.
8860:
1.53 anton 8861: Control flow is specified similar to normal Forth code (@pxref{Arbitrary
8862: control structures}), with @code{if,}, @code{ahead,}, @code{then,},
8863: @code{begin,}, @code{until,}, @code{again,}, @code{cs-roll},
8864: @code{cs-pick}, @code{else,}, @code{while,}, and @code{repeat,}. The
8865: conditions are specified in a way specific to each assembler.
8866:
1.57 anton 8867: Note that the register assignments of the Gforth engine can change
8868: between Gforth versions, or even between different compilations of the
8869: same Gforth version (e.g., if you use a different GCC version). So if
8870: you want to refer to Gforth's registers (e.g., the stack pointer or
8871: TOS), I recommend defining your own words for refering to these
8872: registers, and using them later on; then you can easily adapt to a
8873: changed register assignment. The stability of the register assignment
8874: is usually better if you build Gforth with @code{--enable-force-reg}.
8875:
8876: In particular, the resturn stack pointer and the instruction pointer are
8877: in memory in @code{gforth}, and usually in registers in
8878: @code{gforth-fast}. The most common use of these registers is to
8879: dispatch to the next word (the @code{next} routine). A portable way to
8880: do this is to jump to @code{' noop >code-address} (of course, this is
8881: less efficient than integrating the @code{next} code and scheduling it
8882: well).
8883:
1.52 anton 8884: @node Common Disassembler, 386 Assembler, Common Assembler, Assembler and Code Words
8885: @subsection Common Disassembler
8886:
8887: You can disassemble a @code{code} word with @code{see}
8888: (@pxref{Debugging}). You can disassemble a section of memory with
8889:
8890: doc-disasm
8891:
8892: The disassembler generally produces output that can be fed into the
8893: assembler (i.e., same syntax, etc.). It also includes additional
1.53 anton 8894: information in comments. In particular, the address of the instruction
8895: is given in a comment before the instruction.
8896:
8897: @code{See} may display more or less than the actual code of the word,
8898: because the recognition of the end of the code is unreliable. You can
8899: use @code{disasm} if it did not display enough. It may display more, if
8900: the code word is not immediately followed by a named word. If you have
8901: something else there, you can follow the word with @code{align last @ ,}
8902: to ensure that the end is recognized.
1.52 anton 8903:
8904: @node 386 Assembler, Alpha Assembler, Common Disassembler, Assembler and Code Words
8905: @subsection 386 Assembler
8906:
1.64 pazsan 8907: The 386 assembler included in Gforth was written by Bernd Paysan, it's
8908: available under GPL, and originally part of bigFORTH.
8909:
8910: The 386 disassembler included in Gforth was written by Andrew McKewan
8911: and is in the public domain.
1.57 anton 8912:
8913: The disassembler displays code in prefix Intel syntax.
8914:
1.64 pazsan 8915: The assembler uses a postfix syntax with reversed parameters.
8916:
8917: The assembler includes all instruction of the Athlon, i.e. 486 core
8918: instructions, Pentium and PPro extensions, floating point, MMX, 3Dnow!,
8919: but not ISSE. It's an integrated 16- and 32-bit assembler. Default is 32
8920: bit, you can switch to 16 bit with .86 and back to 32 bit with .386.
8921:
8922: There are several prefixes to switch between different operation sizes,
8923: @code{.b} for byte accesses, @code{.w} for word accesses, @code{.d} for
8924: double-word accesses. Addressing modes can be switched with @code{.wa}
8925: for 16 bit addresses, and @code{.da} for 32 bit addresses. You don't
8926: need a prefix for byte register names (@code{AL} et al).
8927:
8928: For floating point operations, the prefixes are @code{.fs} (IEEE
8929: single), @code{.fl} (IEEE double), @code{.fx} (extended), @code{.fw}
8930: (word), @code{.fd} (double-word), and @code{.fq} (quad-word).
8931:
8932: The MMX opcodes don't have size prefixes, they are spelled out like in
8933: the Intel assembler. Instead of move from and to memory, there are
8934: PLDQ/PLDD and PSTQ/PSTD.
8935:
8936: The registers lack the 'e' prefix; even in 32 bit mode, eax is called
8937: ax. Immediate values are indicated by postfixing them with @code{#},
8938: e.g., @code{3 #}. Here are some examples of addressing modes:
1.57 anton 8939:
8940: @example
1.65 anton 8941: 3 # \ immediate
8942: ax \ register
8943: 100 di d) \ 100[edi]
8944: 4 bx cx di) \ 4[ebx][ecx]
8945: di ax *4 i) \ [edi][eax*4]
8946: 20 ax *4 i#) \ 20[eax*4]
1.57 anton 8947: @end example
8948:
8949: Some example of instructions are:
8950:
8951: @example
1.64 pazsan 8952: ax bx mov \ move ebx,eax
8953: 3 # ax mov \ mov eax,3
8954: 100 di ) ax mov \ mov eax,100[edi]
8955: 4 bx cx di) ax mov \ mov eax,4[ebx][ecx]
8956: .w ax bx mov \ mov bx,ax
1.57 anton 8957: @end example
8958:
1.64 pazsan 8959: The following forms are supported for binary instructions:
1.57 anton 8960:
8961: @example
8962: <reg> <reg> <inst>
8963: <n> # <reg> <inst>
8964: <mem> <reg> <inst>
8965: <reg> <mem> <inst>
8966: @end example
8967:
8968: Immediate to memory is not supported. The shift/rotate syntax is:
8969:
8970: @example
1.64 pazsan 8971: <reg/mem> 1 # shl \ shortens to shift without immediate
8972: <reg/mem> 4 # shl
8973: <reg/mem> cl shl
1.57 anton 8974: @end example
8975:
1.64 pazsan 8976: Precede string instructions (@code{movs} etc.) with @code{.b} to get
1.57 anton 8977: the byte version.
8978:
1.65 anton 8979: The control structure words @code{IF} @code{UNTIL} etc. must be preceded
8980: by one of these conditions: @code{vs vc u< u>= 0= 0<> u<= u> 0< 0>= ps
8981: pc < >= <= >}. (Note that most of these words shadow some Forth words
8982: when @code{assembler} is in front of @code{forth} in the search path,
8983: e.g., in @code{code} words). Currently the control structure words use
8984: one stack item, so you have to use @code{roll} instead of @code{cs-roll}
8985: to shuffle them (you can also use @code{swap} etc.).
8986:
8987: Here is an example of a @code{code} word (assumes that the stack pointer
8988: is in esi and the TOS is in ebx):
8989:
8990: @example
8991: code my+ ( n1 n2 -- n )
8992: 4 si D) bx add
8993: 4 # si add
8994: Next
8995: end-code
8996: @end example
1.52 anton 8997:
8998: @node Alpha Assembler, MIPS assembler, 386 Assembler, Assembler and Code Words
8999: @subsection Alpha Assembler
9000:
1.55 anton 9001: The Alpha assembler and disassembler were originally written by Bernd
9002: Thallner.
9003:
9004: The register names @code{a0}--@code{a5} are not available to avoid
9005: shadowing hex numbers.
9006:
9007: Immediate forms of arithmetic instructions are distinguished by a
9008: @code{#} just before the @code{,}, e.g., @code{and#,} (note: @code{lda,}
9009: does not count as arithmetic instruction).
9010:
9011: You have to specify all operands to an instruction, even those that
9012: other assemblers consider optional, e.g., the destination register for
9013: @code{br,}, or the destination register and hint for @code{jmp,}.
9014:
9015: You can specify conditions for @code{if,} by removing the first @code{b}
9016: and the trailing @code{,} from a branch with a corresponding name; e.g.,
9017:
9018: @example
9019: 11 fgt if, \ if F11>0e
9020: ...
9021: endif,
1.56 anton 9022: @end example
1.55 anton 9023:
9024: @code{fbgt,} gives @code{fgt}.
1.52 anton 9025:
1.53 anton 9026: @node MIPS assembler, Other assemblers, Alpha Assembler, Assembler and Code Words
1.52 anton 9027: @subsection MIPS assembler
9028:
9029: The MIPS assembler was originally written by Christian Pirker.
9030:
9031: Currently the assembler and disassembler only cover the MIPS-I
9032: architecture (R3000), and don't support FP instructions.
9033:
1.55 anton 9034: The register names @code{$a0}--@code{$a3} are not available to avoid
9035: shadowing hex numbers.
1.52 anton 9036:
9037: Because there is no way to distinguish registers from immediate values,
9038: you have to explicitly use the immediate forms of instructions, i.e.,
9039: @code{addiu,}, not just @code{addu,} (@command{as} does this
9040: implicitly).
9041:
9042: If the architecture manual specifies several formats for the instruction
9043: (e.g., for @code{jalr,}), you usually have to use the one with more
9044: arguments (i.e., two for @code{jalr,}). When in doubt, see
9045: @code{arch/mips/testasm.fs} for an example of correct use.
9046:
1.53 anton 9047: Branches and jumps in the MIPS architecture have a delay slot. You have
9048: to fill it yourself (the simplest way is to use @code{nop,}), the
9049: assembler does not do it for you (unlike @command{as}). Even
9050: @code{if,}, @code{ahead,}, @code{until,}, @code{again,}, @code{while,},
9051: @code{else,} and @code{repeat,} need a delay slot. Since @code{begin,}
9052: and @code{then,} just specify branch targets, they are not affected.
9053:
9054: Note that you must not put branches, jumps, or @code{li,} into the delay
9055: slot: @code{li,} may expand to several instructions, and control flow
9056: instructions may not be put into the branch delay slot in any case.
1.52 anton 9057:
9058: For branches the argument specifying the target is a relative address;
9059: You have to add the address of the delay slot to get the absolute
9060: address.
1.53 anton 9061:
9062: The MIPS architecture also has load delay slots and restrictions on
9063: using @code{mfhi,} and @code{mflo,}; you have to order the instructions
9064: yourself to satisfy these restrictions, the assembler does not do it for
9065: you.
9066:
9067: You can specify the conditions for @code{if,} etc. by taking a
9068: conditional branch and leaving away the @code{b} at the start and the
9069: @code{,} at the end. E.g.,
9070:
9071: @example
9072: 4 5 eq if,
9073: ... \ do something if $4 equals $5
9074: then,
9075: @end example
9076:
9077: @node Other assemblers, , MIPS assembler, Assembler and Code Words
9078: @subsection Other assemblers
9079:
9080: If you want to contribute another assembler/disassembler, please contact
9081: us (@email{bug-gforth@@gnu.org}) to check if we have such an assembler
9082: already. If you are writing them from scratch, please use a similar
9083: syntax style as the one we use (i.e., postfix, commas at the end of the
9084: instruction names, @pxref{Common Assembler}); make the output of the
9085: disassembler be valid input for the assembler, and keep the style
9086: similar to the style we used.
9087:
9088: Hints on implementation: The most important part is to have a good test
9089: suite that contains all instructions. Once you have that, the rest is
9090: easy. For actual coding you can take a look at
9091: @file{arch/mips/disasm.fs} to get some ideas on how to use data for both
9092: the assembler and disassembler, avoiding redundancy and some potential
1.63 anton 9093: bugs. You can also look at that file (and @pxref{Advanced does> usage
9094: example}) to get ideas how to factor a disassembler.
1.5 anton 9095:
1.54 anton 9096: Start with the disassembler, because it's easier to reuse data from the
9097: disassembler for the assembler than the other way round.
9098:
9099: For the assembler, take a look at @file{arch/alpha/asm.fs}, which shows
9100: how simple it can be.
9101:
1.26 crook 9102: @c -------------------------------------------------------------
9103: @node Threading Words, Locals, Assembler and Code Words, Words
9104: @section Threading Words
9105: @cindex threading words
1.5 anton 9106:
1.26 crook 9107: @cindex code address
9108: These words provide access to code addresses and other threading stuff
9109: in Gforth (and, possibly, other interpretive Forths). It more or less
9110: abstracts away the differences between direct and indirect threading
9111: (and, for direct threading, the machine dependences). However, at
9112: present this wordset is still incomplete. It is also pretty low-level;
9113: some day it will hopefully be made unnecessary by an internals wordset
9114: that abstracts implementation details away completely.
1.5 anton 9115:
1.44 crook 9116:
1.26 crook 9117: doc-threading-method
9118: doc->code-address
9119: doc->does-code
9120: doc-code-address!
9121: doc-does-code!
9122: doc-does-handler!
9123: doc-/does-handler
1.5 anton 9124:
1.44 crook 9125:
1.26 crook 9126: The code addresses produced by various defining words are produced by
9127: the following words:
1.5 anton 9128:
1.44 crook 9129:
1.26 crook 9130: doc-docol:
9131: doc-docon:
9132: doc-dovar:
9133: doc-douser:
9134: doc-dodefer:
9135: doc-dofield:
1.5 anton 9136:
1.44 crook 9137:
1.26 crook 9138: You can recognize words defined by a @code{CREATE}...@code{DOES>} word
9139: with @code{>does-code}. If the word was defined in that way, the value
9140: returned is non-zero and identifies the @code{DOES>} used by the
9141: defining word.
9142: @comment TODO should that be ``identifies the xt of the DOES> ??''
1.5 anton 9143:
1.26 crook 9144: @c -------------------------------------------------------------
9145: @node Locals, Structures, Threading Words, Words
9146: @section Locals
9147: @cindex locals
1.5 anton 9148:
1.26 crook 9149: Local variables can make Forth programming more enjoyable and Forth
9150: programs easier to read. Unfortunately, the locals of ANS Forth are
9151: laden with restrictions. Therefore, we provide not only the ANS Forth
9152: locals wordset, but also our own, more powerful locals wordset (we
9153: implemented the ANS Forth locals wordset through our locals wordset).
1.5 anton 9154:
1.66 anton 9155: The ideas in this section have also been published in M. Anton Ertl,
9156: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl94l.ps.gz,
9157: Automatic Scoping of Local Variables}}, EuroForth '94.
1.5 anton 9158:
1.26 crook 9159: @menu
9160: * Gforth locals::
9161: * ANS Forth locals::
9162: @end menu
1.5 anton 9163:
1.26 crook 9164: @node Gforth locals, ANS Forth locals, Locals, Locals
9165: @subsection Gforth locals
9166: @cindex Gforth locals
9167: @cindex locals, Gforth style
1.5 anton 9168:
1.26 crook 9169: Locals can be defined with
1.5 anton 9170:
9171: @example
1.26 crook 9172: @{ local1 local2 ... -- comment @}
9173: @end example
9174: or
9175: @example
9176: @{ local1 local2 ... @}
1.5 anton 9177: @end example
9178:
1.26 crook 9179: E.g.,
1.5 anton 9180: @example
1.26 crook 9181: : max @{ n1 n2 -- n3 @}
9182: n1 n2 > if
9183: n1
9184: else
9185: n2
9186: endif ;
1.5 anton 9187: @end example
9188:
1.26 crook 9189: The similarity of locals definitions with stack comments is intended. A
9190: locals definition often replaces the stack comment of a word. The order
9191: of the locals corresponds to the order in a stack comment and everything
9192: after the @code{--} is really a comment.
1.5 anton 9193:
1.26 crook 9194: This similarity has one disadvantage: It is too easy to confuse locals
9195: declarations with stack comments, causing bugs and making them hard to
9196: find. However, this problem can be avoided by appropriate coding
9197: conventions: Do not use both notations in the same program. If you do,
9198: they should be distinguished using additional means, e.g. by position.
9199:
9200: @cindex types of locals
9201: @cindex locals types
9202: The name of the local may be preceded by a type specifier, e.g.,
9203: @code{F:} for a floating point value:
9204:
9205: @example
9206: : CX* @{ F: Ar F: Ai F: Br F: Bi -- Cr Ci @}
9207: \ complex multiplication
9208: Ar Br f* Ai Bi f* f-
9209: Ar Bi f* Ai Br f* f+ ;
9210: @end example
9211:
9212: @cindex flavours of locals
9213: @cindex locals flavours
9214: @cindex value-flavoured locals
9215: @cindex variable-flavoured locals
9216: Gforth currently supports cells (@code{W:}, @code{W^}), doubles
9217: (@code{D:}, @code{D^}), floats (@code{F:}, @code{F^}) and characters
9218: (@code{C:}, @code{C^}) in two flavours: a value-flavoured local (defined
9219: with @code{W:}, @code{D:} etc.) produces its value and can be changed
9220: with @code{TO}. A variable-flavoured local (defined with @code{W^} etc.)
9221: produces its address (which becomes invalid when the variable's scope is
9222: left). E.g., the standard word @code{emit} can be defined in terms of
9223: @code{type} like this:
1.5 anton 9224:
9225: @example
1.26 crook 9226: : emit @{ C^ char* -- @}
9227: char* 1 type ;
1.5 anton 9228: @end example
9229:
1.26 crook 9230: @cindex default type of locals
9231: @cindex locals, default type
9232: A local without type specifier is a @code{W:} local. Both flavours of
9233: locals are initialized with values from the data or FP stack.
1.5 anton 9234:
1.26 crook 9235: Currently there is no way to define locals with user-defined data
9236: structures, but we are working on it.
1.5 anton 9237:
1.26 crook 9238: Gforth allows defining locals everywhere in a colon definition. This
9239: poses the following questions:
1.5 anton 9240:
1.26 crook 9241: @menu
9242: * Where are locals visible by name?::
9243: * How long do locals live?::
9244: * Programming Style::
9245: * Implementation::
9246: @end menu
1.5 anton 9247:
1.26 crook 9248: @node Where are locals visible by name?, How long do locals live?, Gforth locals, Gforth locals
9249: @subsubsection Where are locals visible by name?
9250: @cindex locals visibility
9251: @cindex visibility of locals
9252: @cindex scope of locals
1.5 anton 9253:
1.26 crook 9254: Basically, the answer is that locals are visible where you would expect
9255: it in block-structured languages, and sometimes a little longer. If you
9256: want to restrict the scope of a local, enclose its definition in
9257: @code{SCOPE}...@code{ENDSCOPE}.
1.5 anton 9258:
1.44 crook 9259:
1.26 crook 9260: doc-scope
9261: doc-endscope
1.5 anton 9262:
1.44 crook 9263:
1.26 crook 9264: These words behave like control structure words, so you can use them
9265: with @code{CS-PICK} and @code{CS-ROLL} to restrict the scope in
9266: arbitrary ways.
1.5 anton 9267:
1.26 crook 9268: If you want a more exact answer to the visibility question, here's the
9269: basic principle: A local is visible in all places that can only be
9270: reached through the definition of the local@footnote{In compiler
9271: construction terminology, all places dominated by the definition of the
9272: local.}. In other words, it is not visible in places that can be reached
9273: without going through the definition of the local. E.g., locals defined
9274: in @code{IF}...@code{ENDIF} are visible until the @code{ENDIF}, locals
9275: defined in @code{BEGIN}...@code{UNTIL} are visible after the
9276: @code{UNTIL} (until, e.g., a subsequent @code{ENDSCOPE}).
1.5 anton 9277:
1.26 crook 9278: The reasoning behind this solution is: We want to have the locals
9279: visible as long as it is meaningful. The user can always make the
9280: visibility shorter by using explicit scoping. In a place that can
9281: only be reached through the definition of a local, the meaning of a
9282: local name is clear. In other places it is not: How is the local
9283: initialized at the control flow path that does not contain the
9284: definition? Which local is meant, if the same name is defined twice in
9285: two independent control flow paths?
1.5 anton 9286:
1.26 crook 9287: This should be enough detail for nearly all users, so you can skip the
9288: rest of this section. If you really must know all the gory details and
9289: options, read on.
1.5 anton 9290:
1.26 crook 9291: In order to implement this rule, the compiler has to know which places
9292: are unreachable. It knows this automatically after @code{AHEAD},
9293: @code{AGAIN}, @code{EXIT} and @code{LEAVE}; in other cases (e.g., after
9294: most @code{THROW}s), you can use the word @code{UNREACHABLE} to tell the
9295: compiler that the control flow never reaches that place. If
9296: @code{UNREACHABLE} is not used where it could, the only consequence is
9297: that the visibility of some locals is more limited than the rule above
9298: says. If @code{UNREACHABLE} is used where it should not (i.e., if you
9299: lie to the compiler), buggy code will be produced.
1.5 anton 9300:
1.44 crook 9301:
1.26 crook 9302: doc-unreachable
1.5 anton 9303:
1.44 crook 9304:
1.26 crook 9305: Another problem with this rule is that at @code{BEGIN}, the compiler
9306: does not know which locals will be visible on the incoming
9307: back-edge. All problems discussed in the following are due to this
9308: ignorance of the compiler (we discuss the problems using @code{BEGIN}
9309: loops as examples; the discussion also applies to @code{?DO} and other
9310: loops). Perhaps the most insidious example is:
1.5 anton 9311: @example
1.26 crook 9312: AHEAD
9313: BEGIN
9314: x
9315: [ 1 CS-ROLL ] THEN
9316: @{ x @}
9317: ...
9318: UNTIL
9319: @end example
1.5 anton 9320:
1.26 crook 9321: This should be legal according to the visibility rule. The use of
9322: @code{x} can only be reached through the definition; but that appears
9323: textually below the use.
1.5 anton 9324:
1.26 crook 9325: From this example it is clear that the visibility rules cannot be fully
9326: implemented without major headaches. Our implementation treats common
9327: cases as advertised and the exceptions are treated in a safe way: The
9328: compiler makes a reasonable guess about the locals visible after a
9329: @code{BEGIN}; if it is too pessimistic, the
9330: user will get a spurious error about the local not being defined; if the
9331: compiler is too optimistic, it will notice this later and issue a
9332: warning. In the case above the compiler would complain about @code{x}
9333: being undefined at its use. You can see from the obscure examples in
9334: this section that it takes quite unusual control structures to get the
9335: compiler into trouble, and even then it will often do fine.
1.5 anton 9336:
1.26 crook 9337: If the @code{BEGIN} is reachable from above, the most optimistic guess
9338: is that all locals visible before the @code{BEGIN} will also be
9339: visible after the @code{BEGIN}. This guess is valid for all loops that
9340: are entered only through the @code{BEGIN}, in particular, for normal
9341: @code{BEGIN}...@code{WHILE}...@code{REPEAT} and
9342: @code{BEGIN}...@code{UNTIL} loops and it is implemented in our
9343: compiler. When the branch to the @code{BEGIN} is finally generated by
9344: @code{AGAIN} or @code{UNTIL}, the compiler checks the guess and
9345: warns the user if it was too optimistic:
9346: @example
9347: IF
9348: @{ x @}
9349: BEGIN
9350: \ x ?
9351: [ 1 cs-roll ] THEN
9352: ...
9353: UNTIL
1.5 anton 9354: @end example
9355:
1.26 crook 9356: Here, @code{x} lives only until the @code{BEGIN}, but the compiler
9357: optimistically assumes that it lives until the @code{THEN}. It notices
9358: this difference when it compiles the @code{UNTIL} and issues a
9359: warning. The user can avoid the warning, and make sure that @code{x}
9360: is not used in the wrong area by using explicit scoping:
9361: @example
9362: IF
9363: SCOPE
9364: @{ x @}
9365: ENDSCOPE
9366: BEGIN
9367: [ 1 cs-roll ] THEN
9368: ...
9369: UNTIL
9370: @end example
1.5 anton 9371:
1.26 crook 9372: Since the guess is optimistic, there will be no spurious error messages
9373: about undefined locals.
1.5 anton 9374:
1.26 crook 9375: If the @code{BEGIN} is not reachable from above (e.g., after
9376: @code{AHEAD} or @code{EXIT}), the compiler cannot even make an
9377: optimistic guess, as the locals visible after the @code{BEGIN} may be
9378: defined later. Therefore, the compiler assumes that no locals are
9379: visible after the @code{BEGIN}. However, the user can use
9380: @code{ASSUME-LIVE} to make the compiler assume that the same locals are
9381: visible at the BEGIN as at the point where the top control-flow stack
9382: item was created.
1.5 anton 9383:
1.44 crook 9384:
1.26 crook 9385: doc-assume-live
1.5 anton 9386:
1.44 crook 9387:
9388: @noindent
1.26 crook 9389: E.g.,
1.5 anton 9390: @example
1.26 crook 9391: @{ x @}
9392: AHEAD
9393: ASSUME-LIVE
9394: BEGIN
9395: x
9396: [ 1 CS-ROLL ] THEN
9397: ...
9398: UNTIL
1.5 anton 9399: @end example
9400:
1.26 crook 9401: Other cases where the locals are defined before the @code{BEGIN} can be
9402: handled by inserting an appropriate @code{CS-ROLL} before the
9403: @code{ASSUME-LIVE} (and changing the control-flow stack manipulation
9404: behind the @code{ASSUME-LIVE}).
1.5 anton 9405:
1.26 crook 9406: Cases where locals are defined after the @code{BEGIN} (but should be
9407: visible immediately after the @code{BEGIN}) can only be handled by
9408: rearranging the loop. E.g., the ``most insidious'' example above can be
9409: arranged into:
1.5 anton 9410: @example
1.26 crook 9411: BEGIN
9412: @{ x @}
9413: ... 0=
9414: WHILE
9415: x
9416: REPEAT
1.5 anton 9417: @end example
9418:
1.26 crook 9419: @node How long do locals live?, Programming Style, Where are locals visible by name?, Gforth locals
9420: @subsubsection How long do locals live?
9421: @cindex locals lifetime
9422: @cindex lifetime of locals
1.5 anton 9423:
1.26 crook 9424: The right answer for the lifetime question would be: A local lives at
9425: least as long as it can be accessed. For a value-flavoured local this
9426: means: until the end of its visibility. However, a variable-flavoured
9427: local could be accessed through its address far beyond its visibility
9428: scope. Ultimately, this would mean that such locals would have to be
9429: garbage collected. Since this entails un-Forth-like implementation
9430: complexities, I adopted the same cowardly solution as some other
9431: languages (e.g., C): The local lives only as long as it is visible;
9432: afterwards its address is invalid (and programs that access it
9433: afterwards are erroneous).
1.5 anton 9434:
1.26 crook 9435: @node Programming Style, Implementation, How long do locals live?, Gforth locals
9436: @subsubsection Programming Style
9437: @cindex locals programming style
9438: @cindex programming style, locals
1.5 anton 9439:
1.26 crook 9440: The freedom to define locals anywhere has the potential to change
9441: programming styles dramatically. In particular, the need to use the
9442: return stack for intermediate storage vanishes. Moreover, all stack
9443: manipulations (except @code{PICK}s and @code{ROLL}s with run-time
9444: determined arguments) can be eliminated: If the stack items are in the
9445: wrong order, just write a locals definition for all of them; then
9446: write the items in the order you want.
1.5 anton 9447:
1.26 crook 9448: This seems a little far-fetched and eliminating stack manipulations is
9449: unlikely to become a conscious programming objective. Still, the number
9450: of stack manipulations will be reduced dramatically if local variables
1.49 anton 9451: are used liberally (e.g., compare @code{max} (@pxref{Gforth locals}) with
1.26 crook 9452: a traditional implementation of @code{max}).
1.5 anton 9453:
1.26 crook 9454: This shows one potential benefit of locals: making Forth programs more
9455: readable. Of course, this benefit will only be realized if the
9456: programmers continue to honour the principle of factoring instead of
9457: using the added latitude to make the words longer.
1.5 anton 9458:
1.26 crook 9459: @cindex single-assignment style for locals
9460: Using @code{TO} can and should be avoided. Without @code{TO},
9461: every value-flavoured local has only a single assignment and many
9462: advantages of functional languages apply to Forth. I.e., programs are
9463: easier to analyse, to optimize and to read: It is clear from the
9464: definition what the local stands for, it does not turn into something
9465: different later.
1.5 anton 9466:
1.26 crook 9467: E.g., a definition using @code{TO} might look like this:
1.5 anton 9468: @example
1.26 crook 9469: : strcmp @{ addr1 u1 addr2 u2 -- n @}
9470: u1 u2 min 0
9471: ?do
9472: addr1 c@@ addr2 c@@ -
9473: ?dup-if
9474: unloop exit
9475: then
9476: addr1 char+ TO addr1
9477: addr2 char+ TO addr2
9478: loop
9479: u1 u2 - ;
1.5 anton 9480: @end example
1.26 crook 9481: Here, @code{TO} is used to update @code{addr1} and @code{addr2} at
9482: every loop iteration. @code{strcmp} is a typical example of the
9483: readability problems of using @code{TO}. When you start reading
9484: @code{strcmp}, you think that @code{addr1} refers to the start of the
9485: string. Only near the end of the loop you realize that it is something
9486: else.
1.5 anton 9487:
1.26 crook 9488: This can be avoided by defining two locals at the start of the loop that
9489: are initialized with the right value for the current iteration.
1.5 anton 9490: @example
1.26 crook 9491: : strcmp @{ addr1 u1 addr2 u2 -- n @}
9492: addr1 addr2
9493: u1 u2 min 0
9494: ?do @{ s1 s2 @}
9495: s1 c@@ s2 c@@ -
9496: ?dup-if
9497: unloop exit
9498: then
9499: s1 char+ s2 char+
9500: loop
9501: 2drop
9502: u1 u2 - ;
1.5 anton 9503: @end example
1.26 crook 9504: Here it is clear from the start that @code{s1} has a different value
9505: in every loop iteration.
1.5 anton 9506:
1.26 crook 9507: @node Implementation, , Programming Style, Gforth locals
9508: @subsubsection Implementation
9509: @cindex locals implementation
9510: @cindex implementation of locals
1.5 anton 9511:
1.26 crook 9512: @cindex locals stack
9513: Gforth uses an extra locals stack. The most compelling reason for
9514: this is that the return stack is not float-aligned; using an extra stack
9515: also eliminates the problems and restrictions of using the return stack
9516: as locals stack. Like the other stacks, the locals stack grows toward
9517: lower addresses. A few primitives allow an efficient implementation:
1.5 anton 9518:
1.44 crook 9519:
1.26 crook 9520: doc-@local#
9521: doc-f@local#
9522: doc-laddr#
9523: doc-lp+!#
9524: doc-lp!
9525: doc->l
9526: doc-f>l
1.5 anton 9527:
1.44 crook 9528:
1.26 crook 9529: In addition to these primitives, some specializations of these
9530: primitives for commonly occurring inline arguments are provided for
9531: efficiency reasons, e.g., @code{@@local0} as specialization of
9532: @code{@@local#} for the inline argument 0. The following compiling words
9533: compile the right specialized version, or the general version, as
9534: appropriate:
1.6 pazsan 9535:
1.44 crook 9536:
1.26 crook 9537: doc-compile-@local
9538: doc-compile-f@local
9539: doc-compile-lp+!
1.12 anton 9540:
1.44 crook 9541:
1.26 crook 9542: Combinations of conditional branches and @code{lp+!#} like
9543: @code{?branch-lp+!#} (the locals pointer is only changed if the branch
9544: is taken) are provided for efficiency and correctness in loops.
1.6 pazsan 9545:
1.26 crook 9546: A special area in the dictionary space is reserved for keeping the
9547: local variable names. @code{@{} switches the dictionary pointer to this
9548: area and @code{@}} switches it back and generates the locals
9549: initializing code. @code{W:} etc.@ are normal defining words. This
9550: special area is cleared at the start of every colon definition.
1.6 pazsan 9551:
1.26 crook 9552: @cindex word list for defining locals
9553: A special feature of Gforth's dictionary is used to implement the
9554: definition of locals without type specifiers: every word list (aka
9555: vocabulary) has its own methods for searching
9556: etc. (@pxref{Word Lists}). For the present purpose we defined a word list
9557: with a special search method: When it is searched for a word, it
9558: actually creates that word using @code{W:}. @code{@{} changes the search
9559: order to first search the word list containing @code{@}}, @code{W:} etc.,
9560: and then the word list for defining locals without type specifiers.
1.12 anton 9561:
1.26 crook 9562: The lifetime rules support a stack discipline within a colon
9563: definition: The lifetime of a local is either nested with other locals
9564: lifetimes or it does not overlap them.
1.6 pazsan 9565:
1.26 crook 9566: At @code{BEGIN}, @code{IF}, and @code{AHEAD} no code for locals stack
9567: pointer manipulation is generated. Between control structure words
9568: locals definitions can push locals onto the locals stack. @code{AGAIN}
9569: is the simplest of the other three control flow words. It has to
9570: restore the locals stack depth of the corresponding @code{BEGIN}
9571: before branching. The code looks like this:
9572: @format
9573: @code{lp+!#} current-locals-size @minus{} dest-locals-size
9574: @code{branch} <begin>
9575: @end format
1.6 pazsan 9576:
1.26 crook 9577: @code{UNTIL} is a little more complicated: If it branches back, it
9578: must adjust the stack just like @code{AGAIN}. But if it falls through,
9579: the locals stack must not be changed. The compiler generates the
9580: following code:
9581: @format
9582: @code{?branch-lp+!#} <begin> current-locals-size @minus{} dest-locals-size
9583: @end format
9584: The locals stack pointer is only adjusted if the branch is taken.
1.6 pazsan 9585:
1.26 crook 9586: @code{THEN} can produce somewhat inefficient code:
9587: @format
9588: @code{lp+!#} current-locals-size @minus{} orig-locals-size
9589: <orig target>:
9590: @code{lp+!#} orig-locals-size @minus{} new-locals-size
9591: @end format
9592: The second @code{lp+!#} adjusts the locals stack pointer from the
1.29 crook 9593: level at the @i{orig} point to the level after the @code{THEN}. The
1.26 crook 9594: first @code{lp+!#} adjusts the locals stack pointer from the current
9595: level to the level at the orig point, so the complete effect is an
9596: adjustment from the current level to the right level after the
9597: @code{THEN}.
1.6 pazsan 9598:
1.26 crook 9599: @cindex locals information on the control-flow stack
9600: @cindex control-flow stack items, locals information
9601: In a conventional Forth implementation a dest control-flow stack entry
9602: is just the target address and an orig entry is just the address to be
9603: patched. Our locals implementation adds a word list to every orig or dest
9604: item. It is the list of locals visible (or assumed visible) at the point
9605: described by the entry. Our implementation also adds a tag to identify
9606: the kind of entry, in particular to differentiate between live and dead
9607: (reachable and unreachable) orig entries.
1.6 pazsan 9608:
1.26 crook 9609: A few unusual operations have to be performed on locals word lists:
1.6 pazsan 9610:
1.44 crook 9611:
1.26 crook 9612: doc-common-list
9613: doc-sub-list?
9614: doc-list-size
1.6 pazsan 9615:
1.44 crook 9616:
1.26 crook 9617: Several features of our locals word list implementation make these
9618: operations easy to implement: The locals word lists are organised as
9619: linked lists; the tails of these lists are shared, if the lists
9620: contain some of the same locals; and the address of a name is greater
9621: than the address of the names behind it in the list.
1.6 pazsan 9622:
1.26 crook 9623: Another important implementation detail is the variable
9624: @code{dead-code}. It is used by @code{BEGIN} and @code{THEN} to
9625: determine if they can be reached directly or only through the branch
9626: that they resolve. @code{dead-code} is set by @code{UNREACHABLE},
9627: @code{AHEAD}, @code{EXIT} etc., and cleared at the start of a colon
9628: definition, by @code{BEGIN} and usually by @code{THEN}.
1.6 pazsan 9629:
1.26 crook 9630: Counted loops are similar to other loops in most respects, but
9631: @code{LEAVE} requires special attention: It performs basically the same
9632: service as @code{AHEAD}, but it does not create a control-flow stack
9633: entry. Therefore the information has to be stored elsewhere;
9634: traditionally, the information was stored in the target fields of the
9635: branches created by the @code{LEAVE}s, by organizing these fields into a
9636: linked list. Unfortunately, this clever trick does not provide enough
9637: space for storing our extended control flow information. Therefore, we
9638: introduce another stack, the leave stack. It contains the control-flow
9639: stack entries for all unresolved @code{LEAVE}s.
1.6 pazsan 9640:
1.26 crook 9641: Local names are kept until the end of the colon definition, even if
9642: they are no longer visible in any control-flow path. In a few cases
9643: this may lead to increased space needs for the locals name area, but
9644: usually less than reclaiming this space would cost in code size.
1.6 pazsan 9645:
9646:
1.26 crook 9647: @node ANS Forth locals, , Gforth locals, Locals
9648: @subsection ANS Forth locals
9649: @cindex locals, ANS Forth style
1.6 pazsan 9650:
1.26 crook 9651: The ANS Forth locals wordset does not define a syntax for locals, but
9652: words that make it possible to define various syntaxes. One of the
9653: possible syntaxes is a subset of the syntax we used in the Gforth locals
9654: wordset, i.e.:
1.6 pazsan 9655:
9656: @example
1.26 crook 9657: @{ local1 local2 ... -- comment @}
1.6 pazsan 9658: @end example
1.23 crook 9659: @noindent
1.26 crook 9660: or
1.6 pazsan 9661: @example
1.26 crook 9662: @{ local1 local2 ... @}
1.6 pazsan 9663: @end example
9664:
1.26 crook 9665: The order of the locals corresponds to the order in a stack comment. The
9666: restrictions are:
1.6 pazsan 9667:
9668: @itemize @bullet
9669: @item
1.26 crook 9670: Locals can only be cell-sized values (no type specifiers are allowed).
1.6 pazsan 9671: @item
1.26 crook 9672: Locals can be defined only outside control structures.
1.6 pazsan 9673: @item
1.26 crook 9674: Locals can interfere with explicit usage of the return stack. For the
9675: exact (and long) rules, see the standard. If you don't use return stack
9676: accessing words in a definition using locals, you will be all right. The
9677: purpose of this rule is to make locals implementation on the return
9678: stack easier.
1.6 pazsan 9679: @item
1.26 crook 9680: The whole definition must be in one line.
9681: @end itemize
1.6 pazsan 9682:
1.44 crook 9683: Locals defined in this way behave like @code{VALUE}s
1.49 anton 9684: (@pxref{Values}). I.e., they are initialized from the stack. Using their
1.26 crook 9685: name produces their value. Their value can be changed using @code{TO}.
1.6 pazsan 9686:
1.26 crook 9687: Since this syntax is supported by Gforth directly, you need not do
9688: anything to use it. If you want to port a program using this syntax to
9689: another ANS Forth system, use @file{compat/anslocal.fs} to implement the
9690: syntax on the other system.
1.6 pazsan 9691:
1.26 crook 9692: Note that a syntax shown in the standard, section A.13 looks
9693: similar, but is quite different in having the order of locals
9694: reversed. Beware!
1.6 pazsan 9695:
1.26 crook 9696: The ANS Forth locals wordset itself consists of a word:
1.6 pazsan 9697:
1.44 crook 9698:
1.26 crook 9699: doc-(local)
1.6 pazsan 9700:
1.44 crook 9701:
1.26 crook 9702: The ANS Forth locals extension wordset defines a syntax using @code{locals|}, but it is so
9703: awful that we strongly recommend not to use it. We have implemented this
9704: syntax to make porting to Gforth easy, but do not document it here. The
9705: problem with this syntax is that the locals are defined in an order
9706: reversed with respect to the standard stack comment notation, making
9707: programs harder to read, and easier to misread and miswrite. The only
9708: merit of this syntax is that it is easy to implement using the ANS Forth
9709: locals wordset.
1.7 pazsan 9710:
9711:
1.26 crook 9712: @c ----------------------------------------------------------
9713: @node Structures, Object-oriented Forth, Locals, Words
9714: @section Structures
9715: @cindex structures
9716: @cindex records
1.7 pazsan 9717:
1.26 crook 9718: This section presents the structure package that comes with Gforth. A
9719: version of the package implemented in ANS Forth is available in
9720: @file{compat/struct.fs}. This package was inspired by a posting on
9721: comp.lang.forth in 1989 (unfortunately I don't remember, by whom;
9722: possibly John Hayes). A version of this section has been published in
9723: ???. Marcel Hendrix provided helpful comments.
1.7 pazsan 9724:
1.26 crook 9725: @menu
9726: * Why explicit structure support?::
9727: * Structure Usage::
9728: * Structure Naming Convention::
9729: * Structure Implementation::
9730: * Structure Glossary::
9731: @end menu
1.7 pazsan 9732:
1.26 crook 9733: @node Why explicit structure support?, Structure Usage, Structures, Structures
9734: @subsection Why explicit structure support?
1.7 pazsan 9735:
1.26 crook 9736: @cindex address arithmetic for structures
9737: @cindex structures using address arithmetic
9738: If we want to use a structure containing several fields, we could simply
9739: reserve memory for it, and access the fields using address arithmetic
1.32 anton 9740: (@pxref{Address arithmetic}). As an example, consider a structure with
1.26 crook 9741: the following fields
1.7 pazsan 9742:
1.26 crook 9743: @table @code
9744: @item a
9745: is a float
9746: @item b
9747: is a cell
9748: @item c
9749: is a float
9750: @end table
1.7 pazsan 9751:
1.26 crook 9752: Given the (float-aligned) base address of the structure we get the
9753: address of the field
1.13 pazsan 9754:
1.26 crook 9755: @table @code
9756: @item a
9757: without doing anything further.
9758: @item b
9759: with @code{float+}
9760: @item c
9761: with @code{float+ cell+ faligned}
9762: @end table
1.13 pazsan 9763:
1.26 crook 9764: It is easy to see that this can become quite tiring.
1.13 pazsan 9765:
1.26 crook 9766: Moreover, it is not very readable, because seeing a
9767: @code{cell+} tells us neither which kind of structure is
9768: accessed nor what field is accessed; we have to somehow infer the kind
9769: of structure, and then look up in the documentation, which field of
9770: that structure corresponds to that offset.
1.13 pazsan 9771:
1.26 crook 9772: Finally, this kind of address arithmetic also causes maintenance
9773: troubles: If you add or delete a field somewhere in the middle of the
9774: structure, you have to find and change all computations for the fields
9775: afterwards.
1.13 pazsan 9776:
1.26 crook 9777: So, instead of using @code{cell+} and friends directly, how
9778: about storing the offsets in constants:
1.13 pazsan 9779:
9780: @example
1.26 crook 9781: 0 constant a-offset
9782: 0 float+ constant b-offset
9783: 0 float+ cell+ faligned c-offset
1.13 pazsan 9784: @end example
9785:
1.26 crook 9786: Now we can get the address of field @code{x} with @code{x-offset
9787: +}. This is much better in all respects. Of course, you still
9788: have to change all later offset definitions if you add a field. You can
9789: fix this by declaring the offsets in the following way:
1.13 pazsan 9790:
9791: @example
1.26 crook 9792: 0 constant a-offset
9793: a-offset float+ constant b-offset
9794: b-offset cell+ faligned constant c-offset
1.13 pazsan 9795: @end example
9796:
1.26 crook 9797: Since we always use the offsets with @code{+}, we could use a defining
9798: word @code{cfield} that includes the @code{+} in the action of the
9799: defined word:
1.8 pazsan 9800:
9801: @example
1.26 crook 9802: : cfield ( n "name" -- )
9803: create ,
9804: does> ( name execution: addr1 -- addr2 )
9805: @@ + ;
1.13 pazsan 9806:
1.26 crook 9807: 0 cfield a
9808: 0 a float+ cfield b
9809: 0 b cell+ faligned cfield c
1.13 pazsan 9810: @end example
9811:
1.26 crook 9812: Instead of @code{x-offset +}, we now simply write @code{x}.
9813:
9814: The structure field words now can be used quite nicely. However,
9815: their definition is still a bit cumbersome: We have to repeat the
9816: name, the information about size and alignment is distributed before
9817: and after the field definitions etc. The structure package presented
9818: here addresses these problems.
9819:
9820: @node Structure Usage, Structure Naming Convention, Why explicit structure support?, Structures
9821: @subsection Structure Usage
9822: @cindex structure usage
1.13 pazsan 9823:
1.26 crook 9824: @cindex @code{field} usage
9825: @cindex @code{struct} usage
9826: @cindex @code{end-struct} usage
9827: You can define a structure for a (data-less) linked list with:
1.13 pazsan 9828: @example
1.26 crook 9829: struct
9830: cell% field list-next
9831: end-struct list%
1.13 pazsan 9832: @end example
9833:
1.26 crook 9834: With the address of the list node on the stack, you can compute the
9835: address of the field that contains the address of the next node with
9836: @code{list-next}. E.g., you can determine the length of a list
9837: with:
1.13 pazsan 9838:
9839: @example
1.26 crook 9840: : list-length ( list -- n )
9841: \ "list" is a pointer to the first element of a linked list
9842: \ "n" is the length of the list
9843: 0 BEGIN ( list1 n1 )
9844: over
9845: WHILE ( list1 n1 )
9846: 1+ swap list-next @@ swap
9847: REPEAT
9848: nip ;
1.13 pazsan 9849: @end example
9850:
1.26 crook 9851: You can reserve memory for a list node in the dictionary with
9852: @code{list% %allot}, which leaves the address of the list node on the
9853: stack. For the equivalent allocation on the heap you can use @code{list%
9854: %alloc} (or, for an @code{allocate}-like stack effect (i.e., with ior),
9855: use @code{list% %allocate}). You can get the the size of a list
9856: node with @code{list% %size} and its alignment with @code{list%
9857: %alignment}.
1.13 pazsan 9858:
1.26 crook 9859: Note that in ANS Forth the body of a @code{create}d word is
9860: @code{aligned} but not necessarily @code{faligned};
9861: therefore, if you do a:
1.13 pazsan 9862: @example
1.26 crook 9863: create @emph{name} foo% %allot
1.8 pazsan 9864: @end example
9865:
1.26 crook 9866: @noindent
9867: then the memory alloted for @code{foo%} is
9868: guaranteed to start at the body of @code{@emph{name}} only if
9869: @code{foo%} contains only character, cell and double fields.
1.20 pazsan 9870:
1.45 crook 9871: @cindex structures containing structures
1.26 crook 9872: You can include a structure @code{foo%} as a field of
9873: another structure, like this:
1.20 pazsan 9874: @example
1.26 crook 9875: struct
9876: ...
9877: foo% field ...
9878: ...
9879: end-struct ...
1.20 pazsan 9880: @end example
9881:
1.26 crook 9882: @cindex structure extension
9883: @cindex extended records
9884: Instead of starting with an empty structure, you can extend an
9885: existing structure. E.g., a plain linked list without data, as defined
9886: above, is hardly useful; You can extend it to a linked list of integers,
9887: like this:@footnote{This feature is also known as @emph{extended
9888: records}. It is the main innovation in the Oberon language; in other
9889: words, adding this feature to Modula-2 led Wirth to create a new
9890: language, write a new compiler etc. Adding this feature to Forth just
9891: required a few lines of code.}
1.20 pazsan 9892:
9893: @example
1.26 crook 9894: list%
9895: cell% field intlist-int
9896: end-struct intlist%
1.20 pazsan 9897: @end example
9898:
1.26 crook 9899: @code{intlist%} is a structure with two fields:
9900: @code{list-next} and @code{intlist-int}.
1.20 pazsan 9901:
1.26 crook 9902: @cindex structures containing arrays
9903: You can specify an array type containing @emph{n} elements of
9904: type @code{foo%} like this:
1.20 pazsan 9905:
9906: @example
1.26 crook 9907: foo% @emph{n} *
1.20 pazsan 9908: @end example
9909:
1.26 crook 9910: You can use this array type in any place where you can use a normal
9911: type, e.g., when defining a @code{field}, or with
9912: @code{%allot}.
1.20 pazsan 9913:
1.26 crook 9914: @cindex first field optimization
9915: The first field is at the base address of a structure and the word
9916: for this field (e.g., @code{list-next}) actually does not change
9917: the address on the stack. You may be tempted to leave it away in the
9918: interest of run-time and space efficiency. This is not necessary,
9919: because the structure package optimizes this case and compiling such
9920: words does not generate any code. So, in the interest of readability
9921: and maintainability you should include the word for the field when
9922: accessing the field.
1.20 pazsan 9923:
1.26 crook 9924: @node Structure Naming Convention, Structure Implementation, Structure Usage, Structures
9925: @subsection Structure Naming Convention
9926: @cindex structure naming convention
1.20 pazsan 9927:
1.26 crook 9928: The field names that come to (my) mind are often quite generic, and,
9929: if used, would cause frequent name clashes. E.g., many structures
9930: probably contain a @code{counter} field. The structure names
9931: that come to (my) mind are often also the logical choice for the names
9932: of words that create such a structure.
1.20 pazsan 9933:
1.26 crook 9934: Therefore, I have adopted the following naming conventions:
1.20 pazsan 9935:
1.26 crook 9936: @itemize @bullet
9937: @cindex field naming convention
9938: @item
9939: The names of fields are of the form
9940: @code{@emph{struct}-@emph{field}}, where
9941: @code{@emph{struct}} is the basic name of the structure, and
9942: @code{@emph{field}} is the basic name of the field. You can
9943: think of field words as converting the (address of the)
9944: structure into the (address of the) field.
1.20 pazsan 9945:
1.26 crook 9946: @cindex structure naming convention
9947: @item
9948: The names of structures are of the form
9949: @code{@emph{struct}%}, where
9950: @code{@emph{struct}} is the basic name of the structure.
9951: @end itemize
1.20 pazsan 9952:
1.26 crook 9953: This naming convention does not work that well for fields of extended
9954: structures; e.g., the integer list structure has a field
9955: @code{intlist-int}, but has @code{list-next}, not
9956: @code{intlist-next}.
1.20 pazsan 9957:
1.26 crook 9958: @node Structure Implementation, Structure Glossary, Structure Naming Convention, Structures
9959: @subsection Structure Implementation
9960: @cindex structure implementation
9961: @cindex implementation of structures
1.20 pazsan 9962:
1.26 crook 9963: The central idea in the implementation is to pass the data about the
9964: structure being built on the stack, not in some global
9965: variable. Everything else falls into place naturally once this design
9966: decision is made.
1.20 pazsan 9967:
1.26 crook 9968: The type description on the stack is of the form @emph{align
9969: size}. Keeping the size on the top-of-stack makes dealing with arrays
9970: very simple.
1.20 pazsan 9971:
1.26 crook 9972: @code{field} is a defining word that uses @code{Create}
9973: and @code{DOES>}. The body of the field contains the offset
9974: of the field, and the normal @code{DOES>} action is simply:
1.20 pazsan 9975:
9976: @example
1.48 anton 9977: @@ +
1.20 pazsan 9978: @end example
9979:
1.23 crook 9980: @noindent
1.26 crook 9981: i.e., add the offset to the address, giving the stack effect
1.29 crook 9982: @i{addr1 -- addr2} for a field.
1.20 pazsan 9983:
1.26 crook 9984: @cindex first field optimization, implementation
9985: This simple structure is slightly complicated by the optimization
9986: for fields with offset 0, which requires a different
9987: @code{DOES>}-part (because we cannot rely on there being
9988: something on the stack if such a field is invoked during
9989: compilation). Therefore, we put the different @code{DOES>}-parts
9990: in separate words, and decide which one to invoke based on the
9991: offset. For a zero offset, the field is basically a noop; it is
9992: immediate, and therefore no code is generated when it is compiled.
1.20 pazsan 9993:
1.26 crook 9994: @node Structure Glossary, , Structure Implementation, Structures
9995: @subsection Structure Glossary
9996: @cindex structure glossary
1.20 pazsan 9997:
1.44 crook 9998:
1.26 crook 9999: doc-%align
10000: doc-%alignment
10001: doc-%alloc
10002: doc-%allocate
10003: doc-%allot
10004: doc-cell%
10005: doc-char%
10006: doc-dfloat%
10007: doc-double%
10008: doc-end-struct
10009: doc-field
10010: doc-float%
10011: doc-naligned
10012: doc-sfloat%
10013: doc-%size
10014: doc-struct
1.23 crook 10015:
1.44 crook 10016:
1.26 crook 10017: @c -------------------------------------------------------------
10018: @node Object-oriented Forth, Passing Commands to the OS, Structures, Words
10019: @section Object-oriented Forth
1.20 pazsan 10020:
1.26 crook 10021: Gforth comes with three packages for object-oriented programming:
10022: @file{objects.fs}, @file{oof.fs}, and @file{mini-oof.fs}; none of them
10023: is preloaded, so you have to @code{include} them before use. The most
10024: important differences between these packages (and others) are discussed
10025: in @ref{Comparison with other object models}. All packages are written
10026: in ANS Forth and can be used with any other ANS Forth.
1.20 pazsan 10027:
1.26 crook 10028: @menu
1.48 anton 10029: * Why object-oriented programming?::
10030: * Object-Oriented Terminology::
10031: * Objects::
10032: * OOF::
10033: * Mini-OOF::
1.26 crook 10034: * Comparison with other object models::
10035: @end menu
1.20 pazsan 10036:
1.48 anton 10037: @c ----------------------------------------------------------------
10038: @node Why object-oriented programming?, Object-Oriented Terminology, Object-oriented Forth, Object-oriented Forth
10039: @subsection Why object-oriented programming?
1.26 crook 10040: @cindex object-oriented programming motivation
10041: @cindex motivation for object-oriented programming
1.23 crook 10042:
1.26 crook 10043: Often we have to deal with several data structures (@emph{objects}),
10044: that have to be treated similarly in some respects, but differently in
10045: others. Graphical objects are the textbook example: circles, triangles,
10046: dinosaurs, icons, and others, and we may want to add more during program
10047: development. We want to apply some operations to any graphical object,
10048: e.g., @code{draw} for displaying it on the screen. However, @code{draw}
10049: has to do something different for every kind of object.
10050: @comment TODO add some other operations eg perimeter, area
10051: @comment and tie in to concrete examples later..
1.23 crook 10052:
1.26 crook 10053: We could implement @code{draw} as a big @code{CASE}
10054: control structure that executes the appropriate code depending on the
10055: kind of object to be drawn. This would be not be very elegant, and,
10056: moreover, we would have to change @code{draw} every time we add
10057: a new kind of graphical object (say, a spaceship).
1.23 crook 10058:
1.26 crook 10059: What we would rather do is: When defining spaceships, we would tell
10060: the system: ``Here's how you @code{draw} a spaceship; you figure
10061: out the rest''.
1.23 crook 10062:
1.26 crook 10063: This is the problem that all systems solve that (rightfully) call
10064: themselves object-oriented; the object-oriented packages presented here
10065: solve this problem (and not much else).
10066: @comment TODO ?list properties of oo systems.. oo vs o-based?
1.23 crook 10067:
1.48 anton 10068: @c ------------------------------------------------------------------------
1.26 crook 10069: @node Object-Oriented Terminology, Objects, Why object-oriented programming?, Object-oriented Forth
1.48 anton 10070: @subsection Object-Oriented Terminology
1.26 crook 10071: @cindex object-oriented terminology
10072: @cindex terminology for object-oriented programming
1.23 crook 10073:
1.26 crook 10074: This section is mainly for reference, so you don't have to understand
10075: all of it right away. The terminology is mainly Smalltalk-inspired. In
10076: short:
1.23 crook 10077:
1.26 crook 10078: @table @emph
10079: @cindex class
10080: @item class
10081: a data structure definition with some extras.
1.23 crook 10082:
1.26 crook 10083: @cindex object
10084: @item object
10085: an instance of the data structure described by the class definition.
1.23 crook 10086:
1.26 crook 10087: @cindex instance variables
10088: @item instance variables
10089: fields of the data structure.
1.23 crook 10090:
1.26 crook 10091: @cindex selector
10092: @cindex method selector
10093: @cindex virtual function
10094: @item selector
10095: (or @emph{method selector}) a word (e.g.,
10096: @code{draw}) that performs an operation on a variety of data
10097: structures (classes). A selector describes @emph{what} operation to
10098: perform. In C++ terminology: a (pure) virtual function.
1.23 crook 10099:
1.26 crook 10100: @cindex method
10101: @item method
10102: the concrete definition that performs the operation
10103: described by the selector for a specific class. A method specifies
10104: @emph{how} the operation is performed for a specific class.
1.23 crook 10105:
1.26 crook 10106: @cindex selector invocation
10107: @cindex message send
10108: @cindex invoking a selector
10109: @item selector invocation
10110: a call of a selector. One argument of the call (the TOS (top-of-stack))
10111: is used for determining which method is used. In Smalltalk terminology:
10112: a message (consisting of the selector and the other arguments) is sent
10113: to the object.
1.1 anton 10114:
1.26 crook 10115: @cindex receiving object
10116: @item receiving object
10117: the object used for determining the method executed by a selector
10118: invocation. In the @file{objects.fs} model, it is the object that is on
10119: the TOS when the selector is invoked. (@emph{Receiving} comes from
10120: the Smalltalk @emph{message} terminology.)
1.1 anton 10121:
1.26 crook 10122: @cindex child class
10123: @cindex parent class
10124: @cindex inheritance
10125: @item child class
10126: a class that has (@emph{inherits}) all properties (instance variables,
10127: selectors, methods) from a @emph{parent class}. In Smalltalk
10128: terminology: The subclass inherits from the superclass. In C++
10129: terminology: The derived class inherits from the base class.
1.1 anton 10130:
1.26 crook 10131: @end table
1.21 crook 10132:
1.26 crook 10133: @c If you wonder about the message sending terminology, it comes from
10134: @c a time when each object had it's own task and objects communicated via
10135: @c message passing; eventually the Smalltalk developers realized that
10136: @c they can do most things through simple (indirect) calls. They kept the
10137: @c terminology.
1.1 anton 10138:
1.48 anton 10139: @c --------------------------------------------------------------
1.26 crook 10140: @node Objects, OOF, Object-Oriented Terminology, Object-oriented Forth
10141: @subsection The @file{objects.fs} model
10142: @cindex objects
10143: @cindex object-oriented programming
1.1 anton 10144:
1.26 crook 10145: @cindex @file{objects.fs}
10146: @cindex @file{oof.fs}
1.1 anton 10147:
1.37 anton 10148: This section describes the @file{objects.fs} package. This material also
1.66 anton 10149: has been published in M. Anton Ertl,
10150: @cite{@uref{http://www.complang.tuwien.ac.at/forth/objects/objects.html,
10151: Yet Another Forth Objects Package}}, Forth Dimensions 19(2), pages
10152: 37--43.
1.26 crook 10153: @c McKewan's and Zsoter's packages
1.1 anton 10154:
1.26 crook 10155: This section assumes that you have read @ref{Structures}.
1.1 anton 10156:
1.26 crook 10157: The techniques on which this model is based have been used to implement
10158: the parser generator, Gray, and have also been used in Gforth for
10159: implementing the various flavours of word lists (hashed or not,
10160: case-sensitive or not, special-purpose word lists for locals etc.).
1.1 anton 10161:
10162:
1.26 crook 10163: @menu
10164: * Properties of the Objects model::
10165: * Basic Objects Usage::
1.37 anton 10166: * The Objects base class::
1.26 crook 10167: * Creating objects::
10168: * Object-Oriented Programming Style::
10169: * Class Binding::
10170: * Method conveniences::
10171: * Classes and Scoping::
1.37 anton 10172: * Dividing classes::
1.26 crook 10173: * Object Interfaces::
10174: * Objects Implementation::
10175: * Objects Glossary::
10176: @end menu
1.1 anton 10177:
1.26 crook 10178: Marcel Hendrix provided helpful comments on this section. Andras Zsoter
10179: and Bernd Paysan helped me with the related works section.
1.1 anton 10180:
1.26 crook 10181: @node Properties of the Objects model, Basic Objects Usage, Objects, Objects
10182: @subsubsection Properties of the @file{objects.fs} model
10183: @cindex @file{objects.fs} properties
1.1 anton 10184:
1.26 crook 10185: @itemize @bullet
10186: @item
10187: It is straightforward to pass objects on the stack. Passing
10188: selectors on the stack is a little less convenient, but possible.
1.1 anton 10189:
1.26 crook 10190: @item
10191: Objects are just data structures in memory, and are referenced by their
10192: address. You can create words for objects with normal defining words
10193: like @code{constant}. Likewise, there is no difference between instance
10194: variables that contain objects and those that contain other data.
1.1 anton 10195:
1.26 crook 10196: @item
10197: Late binding is efficient and easy to use.
1.21 crook 10198:
1.26 crook 10199: @item
10200: It avoids parsing, and thus avoids problems with state-smartness
10201: and reduced extensibility; for convenience there are a few parsing
10202: words, but they have non-parsing counterparts. There are also a few
10203: defining words that parse. This is hard to avoid, because all standard
10204: defining words parse (except @code{:noname}); however, such
10205: words are not as bad as many other parsing words, because they are not
10206: state-smart.
1.21 crook 10207:
1.26 crook 10208: @item
10209: It does not try to incorporate everything. It does a few things and does
10210: them well (IMO). In particular, this model was not designed to support
10211: information hiding (although it has features that may help); you can use
10212: a separate package for achieving this.
1.21 crook 10213:
1.26 crook 10214: @item
10215: It is layered; you don't have to learn and use all features to use this
1.49 anton 10216: model. Only a few features are necessary (@pxref{Basic Objects Usage},
10217: @pxref{The Objects base class}, @pxref{Creating objects}.), the others
1.26 crook 10218: are optional and independent of each other.
1.21 crook 10219:
1.26 crook 10220: @item
10221: An implementation in ANS Forth is available.
1.21 crook 10222:
1.26 crook 10223: @end itemize
1.21 crook 10224:
10225:
1.26 crook 10226: @node Basic Objects Usage, The Objects base class, Properties of the Objects model, Objects
10227: @subsubsection Basic @file{objects.fs} Usage
10228: @cindex basic objects usage
10229: @cindex objects, basic usage
1.21 crook 10230:
1.26 crook 10231: You can define a class for graphical objects like this:
1.21 crook 10232:
1.26 crook 10233: @cindex @code{class} usage
10234: @cindex @code{end-class} usage
10235: @cindex @code{selector} usage
10236: @example
10237: object class \ "object" is the parent class
10238: selector draw ( x y graphical -- )
10239: end-class graphical
10240: @end example
1.21 crook 10241:
1.26 crook 10242: This code defines a class @code{graphical} with an
10243: operation @code{draw}. We can perform the operation
10244: @code{draw} on any @code{graphical} object, e.g.:
1.21 crook 10245:
1.26 crook 10246: @example
10247: 100 100 t-rex draw
10248: @end example
1.21 crook 10249:
1.26 crook 10250: @noindent
10251: where @code{t-rex} is a word (say, a constant) that produces a
10252: graphical object.
1.21 crook 10253:
1.29 crook 10254: @comment TODO add a 2nd operation eg perimeter.. and use for
1.26 crook 10255: @comment a concrete example
1.21 crook 10256:
1.26 crook 10257: @cindex abstract class
10258: How do we create a graphical object? With the present definitions,
10259: we cannot create a useful graphical object. The class
10260: @code{graphical} describes graphical objects in general, but not
10261: any concrete graphical object type (C++ users would call it an
10262: @emph{abstract class}); e.g., there is no method for the selector
10263: @code{draw} in the class @code{graphical}.
1.21 crook 10264:
1.26 crook 10265: For concrete graphical objects, we define child classes of the
10266: class @code{graphical}, e.g.:
1.21 crook 10267:
1.26 crook 10268: @cindex @code{overrides} usage
10269: @cindex @code{field} usage in class definition
10270: @example
10271: graphical class \ "graphical" is the parent class
10272: cell% field circle-radius
1.21 crook 10273:
1.26 crook 10274: :noname ( x y circle -- )
10275: circle-radius @@ draw-circle ;
10276: overrides draw
1.21 crook 10277:
1.26 crook 10278: :noname ( n-radius circle -- )
10279: circle-radius ! ;
10280: overrides construct
1.21 crook 10281:
1.26 crook 10282: end-class circle
1.21 crook 10283: @end example
10284:
1.26 crook 10285: Here we define a class @code{circle} as a child of @code{graphical},
10286: with field @code{circle-radius} (which behaves just like a field
10287: (@pxref{Structures}); it defines (using @code{overrides}) new methods
10288: for the selectors @code{draw} and @code{construct} (@code{construct} is
10289: defined in @code{object}, the parent class of @code{graphical}).
1.21 crook 10290:
1.26 crook 10291: Now we can create a circle on the heap (i.e.,
10292: @code{allocate}d memory) with:
1.21 crook 10293:
1.26 crook 10294: @cindex @code{heap-new} usage
1.21 crook 10295: @example
1.26 crook 10296: 50 circle heap-new constant my-circle
10297: @end example
1.21 crook 10298:
1.26 crook 10299: @noindent
10300: @code{heap-new} invokes @code{construct}, thus
10301: initializing the field @code{circle-radius} with 50. We can draw
10302: this new circle at (100,100) with:
1.21 crook 10303:
1.26 crook 10304: @example
10305: 100 100 my-circle draw
1.21 crook 10306: @end example
10307:
1.26 crook 10308: @cindex selector invocation, restrictions
10309: @cindex class definition, restrictions
10310: Note: You can only invoke a selector if the object on the TOS
10311: (the receiving object) belongs to the class where the selector was
10312: defined or one of its descendents; e.g., you can invoke
10313: @code{draw} only for objects belonging to @code{graphical}
10314: or its descendents (e.g., @code{circle}). Immediately before
10315: @code{end-class}, the search order has to be the same as
10316: immediately after @code{class}.
1.21 crook 10317:
1.26 crook 10318: @node The Objects base class, Creating objects, Basic Objects Usage, Objects
10319: @subsubsection The @file{object.fs} base class
10320: @cindex @code{object} class
1.21 crook 10321:
1.26 crook 10322: When you define a class, you have to specify a parent class. So how do
10323: you start defining classes? There is one class available from the start:
10324: @code{object}. It is ancestor for all classes and so is the
10325: only class that has no parent. It has two selectors: @code{construct}
10326: and @code{print}.
1.21 crook 10327:
1.26 crook 10328: @node Creating objects, Object-Oriented Programming Style, The Objects base class, Objects
10329: @subsubsection Creating objects
10330: @cindex creating objects
10331: @cindex object creation
10332: @cindex object allocation options
1.21 crook 10333:
1.26 crook 10334: @cindex @code{heap-new} discussion
10335: @cindex @code{dict-new} discussion
10336: @cindex @code{construct} discussion
10337: You can create and initialize an object of a class on the heap with
10338: @code{heap-new} ( ... class -- object ) and in the dictionary
10339: (allocation with @code{allot}) with @code{dict-new} (
10340: ... class -- object ). Both words invoke @code{construct}, which
10341: consumes the stack items indicated by "..." above.
1.21 crook 10342:
1.26 crook 10343: @cindex @code{init-object} discussion
10344: @cindex @code{class-inst-size} discussion
10345: If you want to allocate memory for an object yourself, you can get its
10346: alignment and size with @code{class-inst-size 2@@} ( class --
10347: align size ). Once you have memory for an object, you can initialize
10348: it with @code{init-object} ( ... class object -- );
10349: @code{construct} does only a part of the necessary work.
1.21 crook 10350:
1.26 crook 10351: @node Object-Oriented Programming Style, Class Binding, Creating objects, Objects
10352: @subsubsection Object-Oriented Programming Style
10353: @cindex object-oriented programming style
1.47 crook 10354: @cindex programming style, object-oriented
1.21 crook 10355:
1.26 crook 10356: This section is not exhaustive.
1.1 anton 10357:
1.26 crook 10358: @cindex stack effects of selectors
10359: @cindex selectors and stack effects
10360: In general, it is a good idea to ensure that all methods for the
10361: same selector have the same stack effect: when you invoke a selector,
10362: you often have no idea which method will be invoked, so, unless all
10363: methods have the same stack effect, you will not know the stack effect
10364: of the selector invocation.
1.21 crook 10365:
1.26 crook 10366: One exception to this rule is methods for the selector
10367: @code{construct}. We know which method is invoked, because we
10368: specify the class to be constructed at the same place. Actually, I
10369: defined @code{construct} as a selector only to give the users a
10370: convenient way to specify initialization. The way it is used, a
10371: mechanism different from selector invocation would be more natural
10372: (but probably would take more code and more space to explain).
1.21 crook 10373:
1.26 crook 10374: @node Class Binding, Method conveniences, Object-Oriented Programming Style, Objects
10375: @subsubsection Class Binding
10376: @cindex class binding
10377: @cindex early binding
1.21 crook 10378:
1.26 crook 10379: @cindex late binding
10380: Normal selector invocations determine the method at run-time depending
10381: on the class of the receiving object. This run-time selection is called
1.29 crook 10382: @i{late binding}.
1.21 crook 10383:
1.26 crook 10384: Sometimes it's preferable to invoke a different method. For example,
10385: you might want to use the simple method for @code{print}ing
10386: @code{object}s instead of the possibly long-winded @code{print} method
10387: of the receiver class. You can achieve this by replacing the invocation
10388: of @code{print} with:
1.21 crook 10389:
1.26 crook 10390: @cindex @code{[bind]} usage
10391: @example
10392: [bind] object print
1.21 crook 10393: @end example
10394:
1.26 crook 10395: @noindent
10396: in compiled code or:
1.21 crook 10397:
1.26 crook 10398: @cindex @code{bind} usage
1.21 crook 10399: @example
1.26 crook 10400: bind object print
1.21 crook 10401: @end example
10402:
1.26 crook 10403: @cindex class binding, alternative to
10404: @noindent
10405: in interpreted code. Alternatively, you can define the method with a
10406: name (e.g., @code{print-object}), and then invoke it through the
10407: name. Class binding is just a (often more convenient) way to achieve
10408: the same effect; it avoids name clutter and allows you to invoke
10409: methods directly without naming them first.
10410:
10411: @cindex superclass binding
10412: @cindex parent class binding
10413: A frequent use of class binding is this: When we define a method
10414: for a selector, we often want the method to do what the selector does
10415: in the parent class, and a little more. There is a special word for
10416: this purpose: @code{[parent]}; @code{[parent]
10417: @emph{selector}} is equivalent to @code{[bind] @emph{parent
10418: selector}}, where @code{@emph{parent}} is the parent
10419: class of the current class. E.g., a method definition might look like:
1.21 crook 10420:
1.26 crook 10421: @cindex @code{[parent]} usage
1.21 crook 10422: @example
1.26 crook 10423: :noname
10424: dup [parent] foo \ do parent's foo on the receiving object
10425: ... \ do some more
10426: ; overrides foo
1.21 crook 10427: @end example
10428:
1.26 crook 10429: @cindex class binding as optimization
10430: In @cite{Object-oriented programming in ANS Forth} (Forth Dimensions,
10431: March 1997), Andrew McKewan presents class binding as an optimization
10432: technique. I recommend not using it for this purpose unless you are in
10433: an emergency. Late binding is pretty fast with this model anyway, so the
10434: benefit of using class binding is small; the cost of using class binding
10435: where it is not appropriate is reduced maintainability.
1.21 crook 10436:
1.26 crook 10437: While we are at programming style questions: You should bind
10438: selectors only to ancestor classes of the receiving object. E.g., say,
10439: you know that the receiving object is of class @code{foo} or its
10440: descendents; then you should bind only to @code{foo} and its
10441: ancestors.
1.21 crook 10442:
1.26 crook 10443: @node Method conveniences, Classes and Scoping, Class Binding, Objects
10444: @subsubsection Method conveniences
10445: @cindex method conveniences
1.1 anton 10446:
1.26 crook 10447: In a method you usually access the receiving object pretty often. If
10448: you define the method as a plain colon definition (e.g., with
10449: @code{:noname}), you may have to do a lot of stack
10450: gymnastics. To avoid this, you can define the method with @code{m:
10451: ... ;m}. E.g., you could define the method for
10452: @code{draw}ing a @code{circle} with
1.20 pazsan 10453:
1.26 crook 10454: @cindex @code{this} usage
10455: @cindex @code{m:} usage
10456: @cindex @code{;m} usage
10457: @example
10458: m: ( x y circle -- )
10459: ( x y ) this circle-radius @@ draw-circle ;m
10460: @end example
1.20 pazsan 10461:
1.26 crook 10462: @cindex @code{exit} in @code{m: ... ;m}
10463: @cindex @code{exitm} discussion
10464: @cindex @code{catch} in @code{m: ... ;m}
10465: When this method is executed, the receiver object is removed from the
10466: stack; you can access it with @code{this} (admittedly, in this
10467: example the use of @code{m: ... ;m} offers no advantage). Note
10468: that I specify the stack effect for the whole method (i.e. including
10469: the receiver object), not just for the code between @code{m:}
10470: and @code{;m}. You cannot use @code{exit} in
10471: @code{m:...;m}; instead, use
10472: @code{exitm}.@footnote{Moreover, for any word that calls
10473: @code{catch} and was defined before loading
10474: @code{objects.fs}, you have to redefine it like I redefined
10475: @code{catch}: @code{: catch this >r catch r> to-this ;}}
1.20 pazsan 10476:
1.26 crook 10477: @cindex @code{inst-var} usage
10478: You will frequently use sequences of the form @code{this
10479: @emph{field}} (in the example above: @code{this
10480: circle-radius}). If you use the field only in this way, you can
10481: define it with @code{inst-var} and eliminate the
10482: @code{this} before the field name. E.g., the @code{circle}
10483: class above could also be defined with:
1.20 pazsan 10484:
1.26 crook 10485: @example
10486: graphical class
10487: cell% inst-var radius
1.20 pazsan 10488:
1.26 crook 10489: m: ( x y circle -- )
10490: radius @@ draw-circle ;m
10491: overrides draw
1.20 pazsan 10492:
1.26 crook 10493: m: ( n-radius circle -- )
10494: radius ! ;m
10495: overrides construct
1.12 anton 10496:
1.26 crook 10497: end-class circle
10498: @end example
1.12 anton 10499:
1.26 crook 10500: @code{radius} can only be used in @code{circle} and its
10501: descendent classes and inside @code{m:...;m}.
1.12 anton 10502:
1.26 crook 10503: @cindex @code{inst-value} usage
10504: You can also define fields with @code{inst-value}, which is
10505: to @code{inst-var} what @code{value} is to
10506: @code{variable}. You can change the value of such a field with
10507: @code{[to-inst]}. E.g., we could also define the class
10508: @code{circle} like this:
1.12 anton 10509:
1.26 crook 10510: @example
10511: graphical class
10512: inst-value radius
1.12 anton 10513:
1.26 crook 10514: m: ( x y circle -- )
10515: radius draw-circle ;m
10516: overrides draw
1.12 anton 10517:
1.26 crook 10518: m: ( n-radius circle -- )
10519: [to-inst] radius ;m
10520: overrides construct
1.21 crook 10521:
1.26 crook 10522: end-class circle
1.12 anton 10523: @end example
10524:
1.38 anton 10525: Finally, you can define named methods with @code{:m}. One use of this
10526: feature is the definition of words that occur only in one class and are
10527: not intended to be overridden, but which still need method context
10528: (e.g., for accessing @code{inst-var}s). Another use is for methods that
10529: would be bound frequently, if defined anonymously.
10530:
1.12 anton 10531:
1.37 anton 10532: @node Classes and Scoping, Dividing classes, Method conveniences, Objects
1.26 crook 10533: @subsubsection Classes and Scoping
10534: @cindex classes and scoping
10535: @cindex scoping and classes
1.12 anton 10536:
1.26 crook 10537: Inheritance is frequent, unlike structure extension. This exacerbates
10538: the problem with the field name convention (@pxref{Structure Naming
10539: Convention}): One always has to remember in which class the field was
10540: originally defined; changing a part of the class structure would require
10541: changes for renaming in otherwise unaffected code.
1.12 anton 10542:
1.26 crook 10543: @cindex @code{inst-var} visibility
10544: @cindex @code{inst-value} visibility
10545: To solve this problem, I added a scoping mechanism (which was not in my
10546: original charter): A field defined with @code{inst-var} (or
10547: @code{inst-value}) is visible only in the class where it is defined and in
10548: the descendent classes of this class. Using such fields only makes
10549: sense in @code{m:}-defined methods in these classes anyway.
1.12 anton 10550:
1.26 crook 10551: This scoping mechanism allows us to use the unadorned field name,
10552: because name clashes with unrelated words become much less likely.
1.12 anton 10553:
1.26 crook 10554: @cindex @code{protected} discussion
10555: @cindex @code{private} discussion
10556: Once we have this mechanism, we can also use it for controlling the
10557: visibility of other words: All words defined after
10558: @code{protected} are visible only in the current class and its
10559: descendents. @code{public} restores the compilation
10560: (i.e. @code{current}) word list that was in effect before. If you
10561: have several @code{protected}s without an intervening
10562: @code{public} or @code{set-current}, @code{public}
10563: will restore the compilation word list in effect before the first of
10564: these @code{protected}s.
1.12 anton 10565:
1.37 anton 10566: @node Dividing classes, Object Interfaces, Classes and Scoping, Objects
10567: @subsubsection Dividing classes
10568: @cindex Dividing classes
10569: @cindex @code{methods}...@code{end-methods}
10570:
10571: You may want to do the definition of methods separate from the
10572: definition of the class, its selectors, fields, and instance variables,
10573: i.e., separate the implementation from the definition. You can do this
10574: in the following way:
10575:
10576: @example
10577: graphical class
10578: inst-value radius
10579: end-class circle
10580:
10581: ... \ do some other stuff
10582:
10583: circle methods \ now we are ready
10584:
10585: m: ( x y circle -- )
10586: radius draw-circle ;m
10587: overrides draw
10588:
10589: m: ( n-radius circle -- )
10590: [to-inst] radius ;m
10591: overrides construct
10592:
10593: end-methods
10594: @end example
10595:
10596: You can use several @code{methods}...@code{end-methods} sections. The
10597: only things you can do to the class in these sections are: defining
10598: methods, and overriding the class's selectors. You must not define new
10599: selectors or fields.
10600:
10601: Note that you often have to override a selector before using it. In
10602: particular, you usually have to override @code{construct} with a new
10603: method before you can invoke @code{heap-new} and friends. E.g., you
10604: must not create a circle before the @code{overrides construct} sequence
10605: in the example above.
10606:
10607: @node Object Interfaces, Objects Implementation, Dividing classes, Objects
1.26 crook 10608: @subsubsection Object Interfaces
10609: @cindex object interfaces
10610: @cindex interfaces for objects
1.12 anton 10611:
1.26 crook 10612: In this model you can only call selectors defined in the class of the
10613: receiving objects or in one of its ancestors. If you call a selector
10614: with a receiving object that is not in one of these classes, the
10615: result is undefined; if you are lucky, the program crashes
10616: immediately.
1.12 anton 10617:
1.26 crook 10618: @cindex selectors common to hardly-related classes
10619: Now consider the case when you want to have a selector (or several)
10620: available in two classes: You would have to add the selector to a
10621: common ancestor class, in the worst case to @code{object}. You
10622: may not want to do this, e.g., because someone else is responsible for
10623: this ancestor class.
1.12 anton 10624:
1.26 crook 10625: The solution for this problem is interfaces. An interface is a
10626: collection of selectors. If a class implements an interface, the
10627: selectors become available to the class and its descendents. A class
10628: can implement an unlimited number of interfaces. For the problem
10629: discussed above, we would define an interface for the selector(s), and
10630: both classes would implement the interface.
1.12 anton 10631:
1.26 crook 10632: As an example, consider an interface @code{storage} for
10633: writing objects to disk and getting them back, and a class
10634: @code{foo} that implements it. The code would look like this:
1.12 anton 10635:
1.26 crook 10636: @cindex @code{interface} usage
10637: @cindex @code{end-interface} usage
10638: @cindex @code{implementation} usage
10639: @example
10640: interface
10641: selector write ( file object -- )
10642: selector read1 ( file object -- )
10643: end-interface storage
1.12 anton 10644:
1.26 crook 10645: bar class
10646: storage implementation
1.12 anton 10647:
1.26 crook 10648: ... overrides write
1.37 anton 10649: ... overrides read1
1.26 crook 10650: ...
10651: end-class foo
1.12 anton 10652: @end example
10653:
1.26 crook 10654: @noindent
1.29 crook 10655: (I would add a word @code{read} @i{( file -- object )} that uses
1.26 crook 10656: @code{read1} internally, but that's beyond the point illustrated
10657: here.)
1.12 anton 10658:
1.26 crook 10659: Note that you cannot use @code{protected} in an interface; and
10660: of course you cannot define fields.
1.12 anton 10661:
1.26 crook 10662: In the Neon model, all selectors are available for all classes;
10663: therefore it does not need interfaces. The price you pay in this model
10664: is slower late binding, and therefore, added complexity to avoid late
10665: binding.
1.12 anton 10666:
1.26 crook 10667: @node Objects Implementation, Objects Glossary, Object Interfaces, Objects
10668: @subsubsection @file{objects.fs} Implementation
10669: @cindex @file{objects.fs} implementation
1.12 anton 10670:
1.26 crook 10671: @cindex @code{object-map} discussion
10672: An object is a piece of memory, like one of the data structures
10673: described with @code{struct...end-struct}. It has a field
10674: @code{object-map} that points to the method map for the object's
10675: class.
1.12 anton 10676:
1.26 crook 10677: @cindex method map
10678: @cindex virtual function table
10679: The @emph{method map}@footnote{This is Self terminology; in C++
10680: terminology: virtual function table.} is an array that contains the
1.29 crook 10681: execution tokens (@i{xt}s) of the methods for the object's class. Each
1.26 crook 10682: selector contains an offset into a method map.
1.12 anton 10683:
1.26 crook 10684: @cindex @code{selector} implementation, class
10685: @code{selector} is a defining word that uses
10686: @code{CREATE} and @code{DOES>}. The body of the
1.44 crook 10687: selector contains the offset; the @code{DOES>} action for a
1.26 crook 10688: class selector is, basically:
1.21 crook 10689:
1.26 crook 10690: @example
10691: ( object addr ) @@ over object-map @@ + @@ execute
10692: @end example
1.12 anton 10693:
1.26 crook 10694: Since @code{object-map} is the first field of the object, it
10695: does not generate any code. As you can see, calling a selector has a
10696: small, constant cost.
1.12 anton 10697:
1.26 crook 10698: @cindex @code{current-interface} discussion
10699: @cindex class implementation and representation
10700: A class is basically a @code{struct} combined with a method
10701: map. During the class definition the alignment and size of the class
10702: are passed on the stack, just as with @code{struct}s, so
10703: @code{field} can also be used for defining class
10704: fields. However, passing more items on the stack would be
10705: inconvenient, so @code{class} builds a data structure in memory,
10706: which is accessed through the variable
10707: @code{current-interface}. After its definition is complete, the
10708: class is represented on the stack by a pointer (e.g., as parameter for
10709: a child class definition).
1.1 anton 10710:
1.26 crook 10711: A new class starts off with the alignment and size of its parent,
10712: and a copy of the parent's method map. Defining new fields extends the
10713: size and alignment; likewise, defining new selectors extends the
1.29 crook 10714: method map. @code{overrides} just stores a new @i{xt} in the method
1.26 crook 10715: map at the offset given by the selector.
1.20 pazsan 10716:
1.26 crook 10717: @cindex class binding, implementation
1.29 crook 10718: Class binding just gets the @i{xt} at the offset given by the selector
1.26 crook 10719: from the class's method map and @code{compile,}s (in the case of
10720: @code{[bind]}) it.
1.21 crook 10721:
1.26 crook 10722: @cindex @code{this} implementation
10723: @cindex @code{catch} and @code{this}
10724: @cindex @code{this} and @code{catch}
10725: I implemented @code{this} as a @code{value}. At the
10726: start of an @code{m:...;m} method the old @code{this} is
10727: stored to the return stack and restored at the end; and the object on
10728: the TOS is stored @code{TO this}. This technique has one
10729: disadvantage: If the user does not leave the method via
10730: @code{;m}, but via @code{throw} or @code{exit},
10731: @code{this} is not restored (and @code{exit} may
10732: crash). To deal with the @code{throw} problem, I have redefined
10733: @code{catch} to save and restore @code{this}; the same
10734: should be done with any word that can catch an exception. As for
10735: @code{exit}, I simply forbid it (as a replacement, there is
10736: @code{exitm}).
1.21 crook 10737:
1.26 crook 10738: @cindex @code{inst-var} implementation
10739: @code{inst-var} is just the same as @code{field}, with
10740: a different @code{DOES>} action:
10741: @example
10742: @@ this +
10743: @end example
10744: Similar for @code{inst-value}.
1.21 crook 10745:
1.26 crook 10746: @cindex class scoping implementation
10747: Each class also has a word list that contains the words defined with
10748: @code{inst-var} and @code{inst-value}, and its protected
10749: words. It also has a pointer to its parent. @code{class} pushes
10750: the word lists of the class and all its ancestors onto the search order stack,
10751: and @code{end-class} drops them.
1.21 crook 10752:
1.26 crook 10753: @cindex interface implementation
10754: An interface is like a class without fields, parent and protected
10755: words; i.e., it just has a method map. If a class implements an
10756: interface, its method map contains a pointer to the method map of the
10757: interface. The positive offsets in the map are reserved for class
10758: methods, therefore interface map pointers have negative
10759: offsets. Interfaces have offsets that are unique throughout the
10760: system, unlike class selectors, whose offsets are only unique for the
10761: classes where the selector is available (invokable).
1.21 crook 10762:
1.26 crook 10763: This structure means that interface selectors have to perform one
10764: indirection more than class selectors to find their method. Their body
10765: contains the interface map pointer offset in the class method map, and
10766: the method offset in the interface method map. The
10767: @code{does>} action for an interface selector is, basically:
1.21 crook 10768:
10769: @example
1.26 crook 10770: ( object selector-body )
10771: 2dup selector-interface @@ ( object selector-body object interface-offset )
10772: swap object-map @@ + @@ ( object selector-body map )
10773: swap selector-offset @@ + @@ execute
1.21 crook 10774: @end example
10775:
1.26 crook 10776: where @code{object-map} and @code{selector-offset} are
10777: first fields and generate no code.
10778:
10779: As a concrete example, consider the following code:
1.21 crook 10780:
1.26 crook 10781: @example
10782: interface
10783: selector if1sel1
10784: selector if1sel2
10785: end-interface if1
1.21 crook 10786:
1.26 crook 10787: object class
10788: if1 implementation
10789: selector cl1sel1
10790: cell% inst-var cl1iv1
1.21 crook 10791:
1.26 crook 10792: ' m1 overrides construct
10793: ' m2 overrides if1sel1
10794: ' m3 overrides if1sel2
10795: ' m4 overrides cl1sel2
10796: end-class cl1
1.21 crook 10797:
1.26 crook 10798: create obj1 object dict-new drop
10799: create obj2 cl1 dict-new drop
10800: @end example
1.21 crook 10801:
1.26 crook 10802: The data structure created by this code (including the data structure
10803: for @code{object}) is shown in the <a
10804: href="objects-implementation.eps">figure</a>, assuming a cell size of 4.
1.29 crook 10805: @comment TODO add this diagram..
1.21 crook 10806:
1.26 crook 10807: @node Objects Glossary, , Objects Implementation, Objects
10808: @subsubsection @file{objects.fs} Glossary
10809: @cindex @file{objects.fs} Glossary
1.21 crook 10810:
1.44 crook 10811:
1.26 crook 10812: doc---objects-bind
10813: doc---objects-<bind>
10814: doc---objects-bind'
10815: doc---objects-[bind]
10816: doc---objects-class
10817: doc---objects-class->map
10818: doc---objects-class-inst-size
10819: doc---objects-class-override!
10820: doc---objects-construct
10821: doc---objects-current'
10822: doc---objects-[current]
10823: doc---objects-current-interface
10824: doc---objects-dict-new
10825: doc---objects-drop-order
10826: doc---objects-end-class
10827: doc---objects-end-class-noname
10828: doc---objects-end-interface
10829: doc---objects-end-interface-noname
1.37 anton 10830: doc---objects-end-methods
1.26 crook 10831: doc---objects-exitm
10832: doc---objects-heap-new
10833: doc---objects-implementation
10834: doc---objects-init-object
10835: doc---objects-inst-value
10836: doc---objects-inst-var
10837: doc---objects-interface
1.38 anton 10838: doc---objects-m:
10839: doc---objects-:m
1.26 crook 10840: doc---objects-;m
10841: doc---objects-method
1.37 anton 10842: doc---objects-methods
1.26 crook 10843: doc---objects-object
10844: doc---objects-overrides
10845: doc---objects-[parent]
10846: doc---objects-print
10847: doc---objects-protected
10848: doc---objects-public
10849: doc---objects-push-order
10850: doc---objects-selector
10851: doc---objects-this
10852: doc---objects-<to-inst>
10853: doc---objects-[to-inst]
10854: doc---objects-to-this
10855: doc---objects-xt-new
1.21 crook 10856:
1.44 crook 10857:
1.26 crook 10858: @c -------------------------------------------------------------
10859: @node OOF, Mini-OOF, Objects, Object-oriented Forth
10860: @subsection The @file{oof.fs} model
10861: @cindex oof
10862: @cindex object-oriented programming
1.21 crook 10863:
1.26 crook 10864: @cindex @file{objects.fs}
10865: @cindex @file{oof.fs}
1.21 crook 10866:
1.26 crook 10867: This section describes the @file{oof.fs} package.
1.21 crook 10868:
1.26 crook 10869: The package described in this section has been used in bigFORTH since 1991, and
10870: used for two large applications: a chromatographic system used to
10871: create new medicaments, and a graphic user interface library (MINOS).
1.21 crook 10872:
1.26 crook 10873: You can find a description (in German) of @file{oof.fs} in @cite{Object
10874: oriented bigFORTH} by Bernd Paysan, published in @cite{Vierte Dimension}
10875: 10(2), 1994.
1.21 crook 10876:
1.26 crook 10877: @menu
1.67 anton 10878: * Properties of the OOF model::
10879: * Basic OOF Usage::
10880: * The OOF base class::
10881: * Class Declaration::
10882: * Class Implementation::
1.26 crook 10883: @end menu
1.21 crook 10884:
1.26 crook 10885: @node Properties of the OOF model, Basic OOF Usage, OOF, OOF
10886: @subsubsection Properties of the @file{oof.fs} model
10887: @cindex @file{oof.fs} properties
1.21 crook 10888:
1.26 crook 10889: @itemize @bullet
10890: @item
10891: This model combines object oriented programming with information
10892: hiding. It helps you writing large application, where scoping is
10893: necessary, because it provides class-oriented scoping.
1.21 crook 10894:
1.26 crook 10895: @item
10896: Named objects, object pointers, and object arrays can be created,
10897: selector invocation uses the ``object selector'' syntax. Selector invocation
10898: to objects and/or selectors on the stack is a bit less convenient, but
10899: possible.
1.21 crook 10900:
1.26 crook 10901: @item
10902: Selector invocation and instance variable usage of the active object is
10903: straightforward, since both make use of the active object.
1.21 crook 10904:
1.26 crook 10905: @item
10906: Late binding is efficient and easy to use.
1.21 crook 10907:
1.26 crook 10908: @item
10909: State-smart objects parse selectors. However, extensibility is provided
10910: using a (parsing) selector @code{postpone} and a selector @code{'}.
1.21 crook 10911:
10912: @item
1.26 crook 10913: An implementation in ANS Forth is available.
10914:
1.21 crook 10915: @end itemize
10916:
10917:
1.26 crook 10918: @node Basic OOF Usage, The OOF base class, Properties of the OOF model, OOF
10919: @subsubsection Basic @file{oof.fs} Usage
10920: @cindex @file{oof.fs} usage
10921:
10922: This section uses the same example as for @code{objects} (@pxref{Basic Objects Usage}).
1.21 crook 10923:
1.26 crook 10924: You can define a class for graphical objects like this:
1.21 crook 10925:
1.26 crook 10926: @cindex @code{class} usage
10927: @cindex @code{class;} usage
10928: @cindex @code{method} usage
10929: @example
10930: object class graphical \ "object" is the parent class
10931: method draw ( x y graphical -- )
10932: class;
10933: @end example
1.21 crook 10934:
1.26 crook 10935: This code defines a class @code{graphical} with an
10936: operation @code{draw}. We can perform the operation
10937: @code{draw} on any @code{graphical} object, e.g.:
1.21 crook 10938:
1.26 crook 10939: @example
10940: 100 100 t-rex draw
10941: @end example
1.21 crook 10942:
1.26 crook 10943: @noindent
10944: where @code{t-rex} is an object or object pointer, created with e.g.
10945: @code{graphical : t-rex}.
1.21 crook 10946:
1.26 crook 10947: @cindex abstract class
10948: How do we create a graphical object? With the present definitions,
10949: we cannot create a useful graphical object. The class
10950: @code{graphical} describes graphical objects in general, but not
10951: any concrete graphical object type (C++ users would call it an
10952: @emph{abstract class}); e.g., there is no method for the selector
10953: @code{draw} in the class @code{graphical}.
1.21 crook 10954:
1.26 crook 10955: For concrete graphical objects, we define child classes of the
10956: class @code{graphical}, e.g.:
1.21 crook 10957:
10958: @example
1.26 crook 10959: graphical class circle \ "graphical" is the parent class
10960: cell var circle-radius
10961: how:
10962: : draw ( x y -- )
10963: circle-radius @@ draw-circle ;
10964:
10965: : init ( n-radius -- (
10966: circle-radius ! ;
10967: class;
10968: @end example
10969:
10970: Here we define a class @code{circle} as a child of @code{graphical},
10971: with a field @code{circle-radius}; it defines new methods for the
10972: selectors @code{draw} and @code{init} (@code{init} is defined in
10973: @code{object}, the parent class of @code{graphical}).
1.21 crook 10974:
1.26 crook 10975: Now we can create a circle in the dictionary with:
1.21 crook 10976:
1.26 crook 10977: @example
10978: 50 circle : my-circle
1.21 crook 10979: @end example
10980:
1.26 crook 10981: @noindent
10982: @code{:} invokes @code{init}, thus initializing the field
10983: @code{circle-radius} with 50. We can draw this new circle at (100,100)
10984: with:
1.21 crook 10985:
10986: @example
1.26 crook 10987: 100 100 my-circle draw
1.21 crook 10988: @end example
10989:
1.26 crook 10990: @cindex selector invocation, restrictions
10991: @cindex class definition, restrictions
10992: Note: You can only invoke a selector if the receiving object belongs to
10993: the class where the selector was defined or one of its descendents;
10994: e.g., you can invoke @code{draw} only for objects belonging to
10995: @code{graphical} or its descendents (e.g., @code{circle}). The scoping
10996: mechanism will check if you try to invoke a selector that is not
10997: defined in this class hierarchy, so you'll get an error at compilation
10998: time.
10999:
11000:
11001: @node The OOF base class, Class Declaration, Basic OOF Usage, OOF
11002: @subsubsection The @file{oof.fs} base class
11003: @cindex @file{oof.fs} base class
11004:
11005: When you define a class, you have to specify a parent class. So how do
11006: you start defining classes? There is one class available from the start:
11007: @code{object}. You have to use it as ancestor for all classes. It is the
11008: only class that has no parent. Classes are also objects, except that
11009: they don't have instance variables; class manipulation such as
11010: inheritance or changing definitions of a class is handled through
11011: selectors of the class @code{object}.
11012:
11013: @code{object} provides a number of selectors:
11014:
1.21 crook 11015: @itemize @bullet
11016: @item
1.26 crook 11017: @code{class} for subclassing, @code{definitions} to add definitions
11018: later on, and @code{class?} to get type informations (is the class a
11019: subclass of the class passed on the stack?).
1.44 crook 11020:
1.26 crook 11021: doc---object-class
11022: doc---object-definitions
11023: doc---object-class?
11024:
1.44 crook 11025:
1.21 crook 11026: @item
1.26 crook 11027: @code{init} and @code{dispose} as constructor and destructor of the
11028: object. @code{init} is invocated after the object's memory is allocated,
11029: while @code{dispose} also handles deallocation. Thus if you redefine
11030: @code{dispose}, you have to call the parent's dispose with @code{super
11031: dispose}, too.
1.44 crook 11032:
1.26 crook 11033: doc---object-init
11034: doc---object-dispose
11035:
1.44 crook 11036:
1.21 crook 11037: @item
1.26 crook 11038: @code{new}, @code{new[]}, @code{:}, @code{ptr}, @code{asptr}, and
11039: @code{[]} to create named and unnamed objects and object arrays or
11040: object pointers.
1.44 crook 11041:
1.26 crook 11042: doc---object-new
11043: doc---object-new[]
11044: doc---object-:
11045: doc---object-ptr
11046: doc---object-asptr
11047: doc---object-[]
1.21 crook 11048:
1.44 crook 11049:
1.26 crook 11050: @item
11051: @code{::} and @code{super} for explicit scoping. You should use explicit
11052: scoping only for super classes or classes with the same set of instance
11053: variables. Explicitly-scoped selectors use early binding.
1.44 crook 11054:
1.26 crook 11055: doc---object-::
11056: doc---object-super
1.21 crook 11057:
1.44 crook 11058:
1.26 crook 11059: @item
11060: @code{self} to get the address of the object
1.44 crook 11061:
1.26 crook 11062: doc---object-self
1.21 crook 11063:
1.44 crook 11064:
1.21 crook 11065: @item
1.26 crook 11066: @code{bind}, @code{bound}, @code{link}, and @code{is} to assign object
11067: pointers and instance defers.
1.44 crook 11068:
1.26 crook 11069: doc---object-bind
11070: doc---object-bound
11071: doc---object-link
11072: doc---object-is
11073:
1.44 crook 11074:
1.21 crook 11075: @item
1.26 crook 11076: @code{'} to obtain selector tokens, @code{send} to invocate selectors
11077: form the stack, and @code{postpone} to generate selector invocation code.
1.44 crook 11078:
1.26 crook 11079: doc---object-'
11080: doc---object-postpone
11081:
1.44 crook 11082:
1.21 crook 11083: @item
1.26 crook 11084: @code{with} and @code{endwith} to select the active object from the
11085: stack, and enable its scope. Using @code{with} and @code{endwith}
11086: also allows you to create code using selector @code{postpone} without being
11087: trapped by the state-smart objects.
1.44 crook 11088:
1.26 crook 11089: doc---object-with
11090: doc---object-endwith
11091:
1.44 crook 11092:
1.21 crook 11093: @end itemize
11094:
1.26 crook 11095: @node Class Declaration, Class Implementation, The OOF base class, OOF
11096: @subsubsection Class Declaration
11097: @cindex class declaration
11098:
11099: @itemize @bullet
11100: @item
11101: Instance variables
1.44 crook 11102:
1.26 crook 11103: doc---oof-var
1.21 crook 11104:
1.44 crook 11105:
1.26 crook 11106: @item
11107: Object pointers
1.44 crook 11108:
1.26 crook 11109: doc---oof-ptr
11110: doc---oof-asptr
1.21 crook 11111:
1.44 crook 11112:
1.26 crook 11113: @item
11114: Instance defers
1.44 crook 11115:
1.26 crook 11116: doc---oof-defer
1.21 crook 11117:
1.44 crook 11118:
1.26 crook 11119: @item
11120: Method selectors
1.44 crook 11121:
1.26 crook 11122: doc---oof-early
11123: doc---oof-method
1.21 crook 11124:
1.44 crook 11125:
1.26 crook 11126: @item
11127: Class-wide variables
1.44 crook 11128:
1.26 crook 11129: doc---oof-static
1.21 crook 11130:
1.44 crook 11131:
1.26 crook 11132: @item
11133: End declaration
1.44 crook 11134:
1.26 crook 11135: doc---oof-how:
11136: doc---oof-class;
1.21 crook 11137:
1.44 crook 11138:
1.26 crook 11139: @end itemize
1.21 crook 11140:
1.26 crook 11141: @c -------------------------------------------------------------
11142: @node Class Implementation, , Class Declaration, OOF
11143: @subsubsection Class Implementation
11144: @cindex class implementation
1.21 crook 11145:
1.26 crook 11146: @c -------------------------------------------------------------
11147: @node Mini-OOF, Comparison with other object models, OOF, Object-oriented Forth
11148: @subsection The @file{mini-oof.fs} model
11149: @cindex mini-oof
1.1 anton 11150:
1.26 crook 11151: Gforth's third object oriented Forth package is a 12-liner. It uses a
11152: mixture of the @file{object.fs} and the @file{oof.fs} syntax,
11153: and reduces to the bare minimum of features. This is based on a posting
11154: of Bernd Paysan in comp.arch.
1.1 anton 11155:
11156: @menu
1.48 anton 11157: * Basic Mini-OOF Usage::
11158: * Mini-OOF Example::
11159: * Mini-OOF Implementation::
1.1 anton 11160: @end menu
11161:
1.26 crook 11162: @c -------------------------------------------------------------
1.48 anton 11163: @node Basic Mini-OOF Usage, Mini-OOF Example, Mini-OOF, Mini-OOF
1.26 crook 11164: @subsubsection Basic @file{mini-oof.fs} Usage
11165: @cindex mini-oof usage
1.1 anton 11166:
1.28 crook 11167: There is a base class (@code{class}, which allocates one cell for the
11168: object pointer) plus seven other words: to define a method, a variable,
11169: a class; to end a class, to resolve binding, to allocate an object and
11170: to compile a class method.
1.26 crook 11171: @comment TODO better description of the last one
1.1 anton 11172:
1.44 crook 11173:
1.26 crook 11174: doc-object
11175: doc-method
11176: doc-var
11177: doc-class
11178: doc-end-class
11179: doc-defines
11180: doc-new
11181: doc-::
1.1 anton 11182:
1.21 crook 11183:
1.44 crook 11184:
1.26 crook 11185: @c -------------------------------------------------------------
11186: @node Mini-OOF Example, Mini-OOF Implementation, Basic Mini-OOF Usage, Mini-OOF
11187: @subsubsection Mini-OOF Example
11188: @cindex mini-oof example
1.21 crook 11189:
1.26 crook 11190: A short example shows how to use this package. This example, in slightly
11191: extended form, is supplied as @file{moof-exm.fs}
1.29 crook 11192: @comment TODO could flesh this out with some comments from the Forthwrite article
1.21 crook 11193:
1.26 crook 11194: @example
11195: object class
11196: method init
11197: method draw
11198: end-class graphical
11199: @end example
1.21 crook 11200:
1.26 crook 11201: This code defines a class @code{graphical} with an
11202: operation @code{draw}. We can perform the operation
11203: @code{draw} on any @code{graphical} object, e.g.:
1.1 anton 11204:
1.26 crook 11205: @example
11206: 100 100 t-rex draw
11207: @end example
1.1 anton 11208:
1.26 crook 11209: where @code{t-rex} is an object or object pointer, created with e.g.
11210: @code{graphical new Constant t-rex}.
1.1 anton 11211:
1.26 crook 11212: For concrete graphical objects, we define child classes of the
11213: class @code{graphical}, e.g.:
1.21 crook 11214:
11215: @example
1.26 crook 11216: graphical class
11217: cell var circle-radius
11218: end-class circle \ "graphical" is the parent class
1.21 crook 11219:
1.26 crook 11220: :noname ( x y -- )
11221: circle-radius @@ draw-circle ; circle defines draw
11222: :noname ( r -- )
11223: circle-radius ! ; circle defines init
1.21 crook 11224: @end example
11225:
1.26 crook 11226: There is no implicit init method, so we have to define one. The creation
11227: code of the object now has to call init explicitely.
1.21 crook 11228:
1.26 crook 11229: @example
11230: circle new Constant my-circle
11231: 50 my-circle init
11232: @end example
1.21 crook 11233:
1.26 crook 11234: It is also possible to add a function to create named objects with
11235: automatic call of @code{init}, given that all objects have @code{init}
11236: on the same place:
1.1 anton 11237:
11238: @example
1.26 crook 11239: : new: ( .. o "name" -- )
11240: new dup Constant init ;
11241: 80 circle new: large-circle
1.1 anton 11242: @end example
11243:
1.26 crook 11244: We can draw this new circle at (100,100) with:
1.1 anton 11245:
11246: @example
1.26 crook 11247: 100 100 my-circle draw
1.1 anton 11248: @end example
11249:
1.48 anton 11250: @node Mini-OOF Implementation, , Mini-OOF Example, Mini-OOF
1.26 crook 11251: @subsubsection @file{mini-oof.fs} Implementation
1.1 anton 11252:
1.26 crook 11253: Object-oriented systems with late binding typically use a
11254: ``vtable''-approach: the first variable in each object is a pointer to a
11255: table, which contains the methods as function pointers. The vtable
11256: may also contain other information.
1.1 anton 11257:
1.26 crook 11258: So first, let's declare methods:
1.1 anton 11259:
1.26 crook 11260: @example
11261: : method ( m v -- m' v ) Create over , swap cell+ swap
11262: DOES> ( ... o -- ... ) @ over @ + @ execute ;
11263: @end example
1.1 anton 11264:
1.26 crook 11265: During method declaration, the number of methods and instance
11266: variables is on the stack (in address units). @code{method} creates
11267: one method and increments the method number. To execute a method, it
11268: takes the object, fetches the vtable pointer, adds the offset, and
1.29 crook 11269: executes the @i{xt} stored there. Each method takes the object it is
1.26 crook 11270: invoked from as top of stack parameter. The method itself should
11271: consume that object.
1.1 anton 11272:
1.26 crook 11273: Now, we also have to declare instance variables
1.21 crook 11274:
1.26 crook 11275: @example
11276: : var ( m v size -- m v' ) Create over , +
11277: DOES> ( o -- addr ) @ + ;
11278: @end example
1.21 crook 11279:
1.26 crook 11280: As before, a word is created with the current offset. Instance
11281: variables can have different sizes (cells, floats, doubles, chars), so
11282: all we do is take the size and add it to the offset. If your machine
11283: has alignment restrictions, put the proper @code{aligned} or
11284: @code{faligned} before the variable, to adjust the variable
11285: offset. That's why it is on the top of stack.
1.2 jwilke 11286:
1.26 crook 11287: We need a starting point (the base object) and some syntactic sugar:
1.21 crook 11288:
1.26 crook 11289: @example
11290: Create object 1 cells , 2 cells ,
11291: : class ( class -- class methods vars ) dup 2@ ;
11292: @end example
1.21 crook 11293:
1.26 crook 11294: For inheritance, the vtable of the parent object has to be
11295: copied when a new, derived class is declared. This gives all the
11296: methods of the parent class, which can be overridden, though.
1.21 crook 11297:
1.2 jwilke 11298: @example
1.26 crook 11299: : end-class ( class methods vars -- )
11300: Create here >r , dup , 2 cells ?DO ['] noop , 1 cells +LOOP
11301: cell+ dup cell+ r> rot @ 2 cells /string move ;
11302: @end example
11303:
11304: The first line creates the vtable, initialized with
11305: @code{noop}s. The second line is the inheritance mechanism, it
11306: copies the xts from the parent vtable.
1.2 jwilke 11307:
1.26 crook 11308: We still have no way to define new methods, let's do that now:
1.2 jwilke 11309:
1.26 crook 11310: @example
11311: : defines ( xt class -- ) ' >body @ + ! ;
1.2 jwilke 11312: @end example
11313:
1.26 crook 11314: To allocate a new object, we need a word, too:
1.2 jwilke 11315:
1.26 crook 11316: @example
11317: : new ( class -- o ) here over @ allot swap over ! ;
11318: @end example
1.2 jwilke 11319:
1.26 crook 11320: Sometimes derived classes want to access the method of the
11321: parent object. There are two ways to achieve this with Mini-OOF:
11322: first, you could use named words, and second, you could look up the
11323: vtable of the parent object.
1.2 jwilke 11324:
1.26 crook 11325: @example
11326: : :: ( class "name" -- ) ' >body @ + @ compile, ;
11327: @end example
1.2 jwilke 11328:
11329:
1.26 crook 11330: Nothing can be more confusing than a good example, so here is
11331: one. First let's declare a text object (called
11332: @code{button}), that stores text and position:
1.2 jwilke 11333:
1.26 crook 11334: @example
11335: object class
11336: cell var text
11337: cell var len
11338: cell var x
11339: cell var y
11340: method init
11341: method draw
11342: end-class button
11343: @end example
1.2 jwilke 11344:
1.26 crook 11345: @noindent
11346: Now, implement the two methods, @code{draw} and @code{init}:
1.2 jwilke 11347:
1.26 crook 11348: @example
11349: :noname ( o -- )
11350: >r r@ x @ r@ y @ at-xy r@ text @ r> len @ type ;
11351: button defines draw
11352: :noname ( addr u o -- )
11353: >r 0 r@ x ! 0 r@ y ! r@ len ! r> text ! ;
11354: button defines init
11355: @end example
1.2 jwilke 11356:
1.26 crook 11357: @noindent
11358: To demonstrate inheritance, we define a class @code{bold-button}, with no
11359: new data and no new methods:
1.2 jwilke 11360:
1.26 crook 11361: @example
11362: button class
11363: end-class bold-button
1.1 anton 11364:
1.26 crook 11365: : bold 27 emit ." [1m" ;
11366: : normal 27 emit ." [0m" ;
11367: @end example
1.1 anton 11368:
1.26 crook 11369: @noindent
11370: The class @code{bold-button} has a different draw method to
11371: @code{button}, but the new method is defined in terms of the draw method
11372: for @code{button}:
1.1 anton 11373:
1.26 crook 11374: @example
11375: :noname bold [ button :: draw ] normal ; bold-button defines draw
11376: @end example
1.1 anton 11377:
1.26 crook 11378: @noindent
11379: Finally, create two objects and apply methods:
1.1 anton 11380:
1.26 crook 11381: @example
11382: button new Constant foo
11383: s" thin foo" foo init
11384: page
11385: foo draw
11386: bold-button new Constant bar
11387: s" fat bar" bar init
11388: 1 bar y !
11389: bar draw
11390: @end example
1.1 anton 11391:
11392:
1.48 anton 11393: @node Comparison with other object models, , Mini-OOF, Object-oriented Forth
11394: @subsection Comparison with other object models
1.26 crook 11395: @cindex comparison of object models
11396: @cindex object models, comparison
1.1 anton 11397:
1.26 crook 11398: Many object-oriented Forth extensions have been proposed (@cite{A survey
11399: of object-oriented Forths} (SIGPLAN Notices, April 1996) by Bradford
11400: J. Rodriguez and W. F. S. Poehlman lists 17). This section discusses the
11401: relation of the object models described here to two well-known and two
11402: closely-related (by the use of method maps) models.
1.1 anton 11403:
1.26 crook 11404: @cindex Neon model
11405: The most popular model currently seems to be the Neon model (see
11406: @cite{Object-oriented programming in ANS Forth} (Forth Dimensions, March
11407: 1997) by Andrew McKewan) but this model has a number of limitations
11408: @footnote{A longer version of this critique can be
11409: found in @cite{On Standardizing Object-Oriented Forth Extensions} (Forth
11410: Dimensions, May 1997) by Anton Ertl.}:
1.1 anton 11411:
1.26 crook 11412: @itemize @bullet
11413: @item
1.48 anton 11414: It uses a @code{@emph{selector object}} syntax, which makes it unnatural
11415: to pass objects on the stack.
1.1 anton 11416:
1.26 crook 11417: @item
11418: It requires that the selector parses the input stream (at
11419: compile time); this leads to reduced extensibility and to bugs that are+
11420: hard to find.
1.1 anton 11421:
1.26 crook 11422: @item
11423: It allows using every selector to every object;
11424: this eliminates the need for classes, but makes it harder to create
11425: efficient implementations.
11426: @end itemize
1.1 anton 11427:
1.26 crook 11428: @cindex Pountain's object-oriented model
11429: Another well-known publication is @cite{Object-Oriented Forth} (Academic
11430: Press, London, 1987) by Dick Pountain. However, it is not really about
11431: object-oriented programming, because it hardly deals with late
11432: binding. Instead, it focuses on features like information hiding and
11433: overloading that are characteristic of modular languages like Ada (83).
1.1 anton 11434:
1.26 crook 11435: @cindex Zsoter's object-oriented model
1.48 anton 11436: In @cite{Does late binding have to be slow?} (Forth Dimensions 18(1)
11437: 1996, pages 31-35) Andras Zsoter describes a model that makes heavy use
11438: of an active object (like @code{this} in @file{objects.fs}): The active
11439: object is not only used for accessing all fields, but also specifies the
11440: receiving object of every selector invocation; you have to change the
11441: active object explicitly with @code{@{ ... @}}, whereas in
11442: @file{objects.fs} it changes more or less implicitly at @code{m:
11443: ... ;m}. Such a change at the method entry point is unnecessary with the
11444: Zsoter's model, because the receiving object is the active object
11445: already. On the other hand, the explicit change is absolutely necessary
11446: in that model, because otherwise no one could ever change the active
11447: object. An ANS Forth implementation of this model is available at
11448: @uref{http://www.forth.org/fig/oopf.html}.
1.1 anton 11449:
1.26 crook 11450: @cindex @file{oof.fs}, differences to other models
11451: The @file{oof.fs} model combines information hiding and overloading
11452: resolution (by keeping names in various word lists) with object-oriented
11453: programming. It sets the active object implicitly on method entry, but
11454: also allows explicit changing (with @code{>o...o>} or with
11455: @code{with...endwith}). It uses parsing and state-smart objects and
11456: classes for resolving overloading and for early binding: the object or
11457: class parses the selector and determines the method from this. If the
11458: selector is not parsed by an object or class, it performs a call to the
11459: selector for the active object (late binding), like Zsoter's model.
11460: Fields are always accessed through the active object. The big
11461: disadvantage of this model is the parsing and the state-smartness, which
11462: reduces extensibility and increases the opportunities for subtle bugs;
11463: essentially, you are only safe if you never tick or @code{postpone} an
11464: object or class (Bernd disagrees, but I (Anton) am not convinced).
1.1 anton 11465:
1.26 crook 11466: @cindex @file{mini-oof.fs}, differences to other models
1.48 anton 11467: The @file{mini-oof.fs} model is quite similar to a very stripped-down
11468: version of the @file{objects.fs} model, but syntactically it is a
11469: mixture of the @file{objects.fs} and @file{oof.fs} models.
1.1 anton 11470:
1.26 crook 11471: @c -------------------------------------------------------------
1.47 crook 11472: @node Passing Commands to the OS, Keeping track of Time, Object-oriented Forth, Words
1.21 crook 11473: @section Passing Commands to the Operating System
11474: @cindex operating system - passing commands
11475: @cindex shell commands
11476:
11477: Gforth allows you to pass an arbitrary string to the host operating
11478: system shell (if such a thing exists) for execution.
11479:
1.44 crook 11480:
1.21 crook 11481: doc-sh
11482: doc-system
11483: doc-$?
1.23 crook 11484: doc-getenv
1.21 crook 11485:
1.44 crook 11486:
1.26 crook 11487: @c -------------------------------------------------------------
1.47 crook 11488: @node Keeping track of Time, Miscellaneous Words, Passing Commands to the OS, Words
11489: @section Keeping track of Time
11490: @cindex time-related words
11491:
11492: Gforth implements time-related operations by making calls to the C
11493: library function, @code{gettimeofday}.
11494:
11495: doc-ms
11496: doc-time&date
11497:
11498:
11499:
11500: @c -------------------------------------------------------------
11501: @node Miscellaneous Words, , Keeping track of Time, Words
1.21 crook 11502: @section Miscellaneous Words
11503: @cindex miscellaneous words
11504:
1.29 crook 11505: @comment TODO find homes for these
11506:
1.26 crook 11507: These section lists the ANS Forth words that are not documented
1.21 crook 11508: elsewhere in this manual. Ultimately, they all need proper homes.
11509:
11510: doc-[compile]
1.68 ! anton 11511: doc-quit
1.44 crook 11512:
1.26 crook 11513: The following ANS Forth words are not currently supported by Gforth
1.27 crook 11514: (@pxref{ANS conformance}):
1.21 crook 11515:
11516: @code{EDITOR}
11517: @code{EMIT?}
11518: @code{FORGET}
11519:
1.24 anton 11520: @c ******************************************************************
11521: @node Error messages, Tools, Words, Top
11522: @chapter Error messages
11523: @cindex error messages
11524: @cindex backtrace
11525:
11526: A typical Gforth error message looks like this:
11527:
11528: @example
11529: in file included from :-1
11530: in file included from ./yyy.fs:1
11531: ./xxx.fs:4: Invalid memory address
11532: bar
11533: ^^^
1.25 anton 11534: $400E664C @@
11535: $400E6664 foo
1.24 anton 11536: @end example
11537:
11538: The message identifying the error is @code{Invalid memory address}. The
11539: error happened when text-interpreting line 4 of the file
11540: @file{./xxx.fs}. This line is given (it contains @code{bar}), and the
11541: word on the line where the error happened, is pointed out (with
11542: @code{^^^}).
11543:
11544: The file containing the error was included in line 1 of @file{./yyy.fs},
11545: and @file{yyy.fs} was included from a non-file (in this case, by giving
11546: @file{yyy.fs} as command-line parameter to Gforth).
11547:
11548: At the end of the error message you find a return stack dump that can be
11549: interpreted as a backtrace (possibly empty). On top you find the top of
11550: the return stack when the @code{throw} happened, and at the bottom you
11551: find the return stack entry just above the return stack of the topmost
11552: text interpreter.
11553:
11554: To the right of most return stack entries you see a guess for the word
11555: that pushed that return stack entry as its return address. This gives a
11556: backtrace. In our case we see that @code{bar} called @code{foo}, and
11557: @code{foo} called @code{@@} (and @code{@@} had an @emph{Invalid memory
11558: address} exception).
11559:
11560: Note that the backtrace is not perfect: We don't know which return stack
11561: entries are return addresses (so we may get false positives); and in
11562: some cases (e.g., for @code{abort"}) we cannot determine from the return
11563: address the word that pushed the return address, so for some return
11564: addresses you see no names in the return stack dump.
1.25 anton 11565:
11566: @cindex @code{catch} and backtraces
11567: The return stack dump represents the return stack at the time when a
11568: specific @code{throw} was executed. In programs that make use of
11569: @code{catch}, it is not necessarily clear which @code{throw} should be
11570: used for the return stack dump (e.g., consider one @code{throw} that
11571: indicates an error, which is caught, and during recovery another error
1.42 anton 11572: happens; which @code{throw} should be used for the stack dump?). Gforth
1.25 anton 11573: presents the return stack dump for the first @code{throw} after the last
11574: executed (not returned-to) @code{catch}; this works well in the usual
11575: case.
11576:
11577: @cindex @code{gforth-fast} and backtraces
11578: @cindex @code{gforth-fast}, difference from @code{gforth}
11579: @cindex backtraces with @code{gforth-fast}
11580: @cindex return stack dump with @code{gforth-fast}
11581: @code{gforth} is able to do a return stack dump for throws generated
11582: from primitives (e.g., invalid memory address, stack empty etc.);
11583: @code{gforth-fast} is only able to do a return stack dump from a
11584: directly called @code{throw} (including @code{abort} etc.). This is the
1.30 anton 11585: only difference (apart from a speed factor of between 1.15 (K6-2) and
11586: 1.6 (21164A)) between @code{gforth} and @code{gforth-fast}. Given an
11587: exception caused by a primitive in @code{gforth-fast}, you will
11588: typically see no return stack dump at all; however, if the exception is
11589: caught by @code{catch} (e.g., for restoring some state), and then
11590: @code{throw}n again, the return stack dump will be for the first such
11591: @code{throw}.
1.2 jwilke 11592:
1.5 anton 11593: @c ******************************************************************
1.24 anton 11594: @node Tools, ANS conformance, Error messages, Top
1.1 anton 11595: @chapter Tools
11596:
11597: @menu
11598: * ANS Report:: Report the words used, sorted by wordset.
11599: @end menu
11600:
11601: See also @ref{Emacs and Gforth}.
11602:
11603: @node ANS Report, , Tools, Tools
11604: @section @file{ans-report.fs}: Report the words used, sorted by wordset
11605: @cindex @file{ans-report.fs}
11606: @cindex report the words used in your program
11607: @cindex words used in your program
11608:
11609: If you want to label a Forth program as ANS Forth Program, you must
11610: document which wordsets the program uses; for extension wordsets, it is
11611: helpful to list the words the program requires from these wordsets
11612: (because Forth systems are allowed to provide only some words of them).
11613:
11614: The @file{ans-report.fs} tool makes it easy for you to determine which
11615: words from which wordset and which non-ANS words your application
11616: uses. You simply have to include @file{ans-report.fs} before loading the
11617: program you want to check. After loading your program, you can get the
11618: report with @code{print-ans-report}. A typical use is to run this as
11619: batch job like this:
11620: @example
11621: gforth ans-report.fs myprog.fs -e "print-ans-report bye"
11622: @end example
11623:
11624: The output looks like this (for @file{compat/control.fs}):
11625: @example
11626: The program uses the following words
11627: from CORE :
11628: : POSTPONE THEN ; immediate ?dup IF 0=
11629: from BLOCK-EXT :
11630: \
11631: from FILE :
11632: (
11633: @end example
11634:
11635: @subsection Caveats
11636:
11637: Note that @file{ans-report.fs} just checks which words are used, not whether
11638: they are used in an ANS Forth conforming way!
11639:
11640: Some words are defined in several wordsets in the
11641: standard. @file{ans-report.fs} reports them for only one of the
11642: wordsets, and not necessarily the one you expect. It depends on usage
11643: which wordset is the right one to specify. E.g., if you only use the
11644: compilation semantics of @code{S"}, it is a Core word; if you also use
11645: its interpretation semantics, it is a File word.
11646:
11647: @c ******************************************************************
1.65 anton 11648: @node ANS conformance, Standard vs Extensions, Tools, Top
1.1 anton 11649: @chapter ANS conformance
11650: @cindex ANS conformance of Gforth
11651:
11652: To the best of our knowledge, Gforth is an
11653:
11654: ANS Forth System
11655: @itemize @bullet
11656: @item providing the Core Extensions word set
11657: @item providing the Block word set
11658: @item providing the Block Extensions word set
11659: @item providing the Double-Number word set
11660: @item providing the Double-Number Extensions word set
11661: @item providing the Exception word set
11662: @item providing the Exception Extensions word set
11663: @item providing the Facility word set
1.40 anton 11664: @item providing @code{EKEY}, @code{EKEY>CHAR}, @code{EKEY?}, @code{MS} and @code{TIME&DATE} from the Facility Extensions word set
1.1 anton 11665: @item providing the File Access word set
11666: @item providing the File Access Extensions word set
11667: @item providing the Floating-Point word set
11668: @item providing the Floating-Point Extensions word set
11669: @item providing the Locals word set
11670: @item providing the Locals Extensions word set
11671: @item providing the Memory-Allocation word set
11672: @item providing the Memory-Allocation Extensions word set (that one's easy)
11673: @item providing the Programming-Tools word set
11674: @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
11675: @item providing the Search-Order word set
11676: @item providing the Search-Order Extensions word set
11677: @item providing the String word set
11678: @item providing the String Extensions word set (another easy one)
11679: @end itemize
11680:
11681: @cindex system documentation
11682: In addition, ANS Forth systems are required to document certain
11683: implementation choices. This chapter tries to meet these
11684: requirements. In many cases it gives a way to ask the system for the
11685: information instead of providing the information directly, in
11686: particular, if the information depends on the processor, the operating
11687: system or the installation options chosen, or if they are likely to
11688: change during the maintenance of Gforth.
11689:
11690: @comment The framework for the rest has been taken from pfe.
11691:
11692: @menu
11693: * The Core Words::
11694: * The optional Block word set::
11695: * The optional Double Number word set::
11696: * The optional Exception word set::
11697: * The optional Facility word set::
11698: * The optional File-Access word set::
11699: * The optional Floating-Point word set::
11700: * The optional Locals word set::
11701: * The optional Memory-Allocation word set::
11702: * The optional Programming-Tools word set::
11703: * The optional Search-Order word set::
11704: @end menu
11705:
11706:
11707: @c =====================================================================
11708: @node The Core Words, The optional Block word set, ANS conformance, ANS conformance
11709: @comment node-name, next, previous, up
11710: @section The Core Words
11711: @c =====================================================================
11712: @cindex core words, system documentation
11713: @cindex system documentation, core words
11714:
11715: @menu
11716: * core-idef:: Implementation Defined Options
11717: * core-ambcond:: Ambiguous Conditions
11718: * core-other:: Other System Documentation
11719: @end menu
11720:
11721: @c ---------------------------------------------------------------------
11722: @node core-idef, core-ambcond, The Core Words, The Core Words
11723: @subsection Implementation Defined Options
11724: @c ---------------------------------------------------------------------
11725: @cindex core words, implementation-defined options
11726: @cindex implementation-defined options, core words
11727:
11728:
11729: @table @i
11730: @item (Cell) aligned addresses:
11731: @cindex cell-aligned addresses
11732: @cindex aligned addresses
11733: processor-dependent. Gforth's alignment words perform natural alignment
11734: (e.g., an address aligned for a datum of size 8 is divisible by
11735: 8). Unaligned accesses usually result in a @code{-23 THROW}.
11736:
11737: @item @code{EMIT} and non-graphic characters:
11738: @cindex @code{EMIT} and non-graphic characters
11739: @cindex non-graphic characters and @code{EMIT}
11740: The character is output using the C library function (actually, macro)
11741: @code{putc}.
11742:
11743: @item character editing of @code{ACCEPT} and @code{EXPECT}:
11744: @cindex character editing of @code{ACCEPT} and @code{EXPECT}
11745: @cindex editing in @code{ACCEPT} and @code{EXPECT}
11746: @cindex @code{ACCEPT}, editing
11747: @cindex @code{EXPECT}, editing
11748: This is modeled on the GNU readline library (@pxref{Readline
11749: Interaction, , Command Line Editing, readline, The GNU Readline
11750: Library}) with Emacs-like key bindings. @kbd{Tab} deviates a little by
11751: producing a full word completion every time you type it (instead of
1.28 crook 11752: producing the common prefix of all completions). @xref{Command-line editing}.
1.1 anton 11753:
11754: @item character set:
11755: @cindex character set
11756: The character set of your computer and display device. Gforth is
11757: 8-bit-clean (but some other component in your system may make trouble).
11758:
11759: @item Character-aligned address requirements:
11760: @cindex character-aligned address requirements
11761: installation-dependent. Currently a character is represented by a C
11762: @code{unsigned char}; in the future we might switch to @code{wchar_t}
11763: (Comments on that requested).
11764:
11765: @item character-set extensions and matching of names:
11766: @cindex character-set extensions and matching of names
1.26 crook 11767: @cindex case-sensitivity for name lookup
11768: @cindex name lookup, case-sensitivity
11769: @cindex locale and case-sensitivity
1.21 crook 11770: Any character except the ASCII NUL character can be used in a
1.1 anton 11771: name. Matching is case-insensitive (except in @code{TABLE}s). The
1.47 crook 11772: matching is performed using the C library function @code{strncasecmp}, whose
1.1 anton 11773: function is probably influenced by the locale. E.g., the @code{C} locale
11774: does not know about accents and umlauts, so they are matched
11775: case-sensitively in that locale. For portability reasons it is best to
11776: write programs such that they work in the @code{C} locale. Then one can
11777: use libraries written by a Polish programmer (who might use words
11778: containing ISO Latin-2 encoded characters) and by a French programmer
11779: (ISO Latin-1) in the same program (of course, @code{WORDS} will produce
11780: funny results for some of the words (which ones, depends on the font you
11781: are using)). Also, the locale you prefer may not be available in other
11782: operating systems. Hopefully, Unicode will solve these problems one day.
11783:
11784: @item conditions under which control characters match a space delimiter:
11785: @cindex space delimiters
11786: @cindex control characters as delimiters
11787: If @code{WORD} is called with the space character as a delimiter, all
11788: white-space characters (as identified by the C macro @code{isspace()})
11789: are delimiters. @code{PARSE}, on the other hand, treats space like other
1.44 crook 11790: delimiters. @code{SWORD} treats space like @code{WORD}, but behaves
1.1 anton 11791: like @code{PARSE} otherwise. @code{(NAME)}, which is used by the outer
11792: interpreter (aka text interpreter) by default, treats all white-space
11793: characters as delimiters.
11794:
1.26 crook 11795: @item format of the control-flow stack:
11796: @cindex control-flow stack, format
11797: The data stack is used as control-flow stack. The size of a control-flow
1.1 anton 11798: stack item in cells is given by the constant @code{cs-item-size}. At the
11799: time of this writing, an item consists of a (pointer to a) locals list
11800: (third), an address in the code (second), and a tag for identifying the
11801: item (TOS). The following tags are used: @code{defstart},
11802: @code{live-orig}, @code{dead-orig}, @code{dest}, @code{do-dest},
11803: @code{scopestart}.
11804:
11805: @item conversion of digits > 35
11806: @cindex digits > 35
11807: The characters @code{[\]^_'} are the digits with the decimal value
11808: 36@minus{}41. There is no way to input many of the larger digits.
11809:
11810: @item display after input terminates in @code{ACCEPT} and @code{EXPECT}:
11811: @cindex @code{EXPECT}, display after end of input
11812: @cindex @code{ACCEPT}, display after end of input
11813: The cursor is moved to the end of the entered string. If the input is
11814: terminated using the @kbd{Return} key, a space is typed.
11815:
11816: @item exception abort sequence of @code{ABORT"}:
11817: @cindex exception abort sequence of @code{ABORT"}
11818: @cindex @code{ABORT"}, exception abort sequence
11819: The error string is stored into the variable @code{"error} and a
11820: @code{-2 throw} is performed.
11821:
11822: @item input line terminator:
11823: @cindex input line terminator
11824: @cindex line terminator on input
1.26 crook 11825: @cindex newline character on input
1.1 anton 11826: For interactive input, @kbd{C-m} (CR) and @kbd{C-j} (LF) terminate
11827: lines. One of these characters is typically produced when you type the
11828: @kbd{Enter} or @kbd{Return} key.
11829:
11830: @item maximum size of a counted string:
11831: @cindex maximum size of a counted string
11832: @cindex counted string, maximum size
11833: @code{s" /counted-string" environment? drop .}. Currently 255 characters
11834: on all ports, but this may change.
11835:
11836: @item maximum size of a parsed string:
11837: @cindex maximum size of a parsed string
11838: @cindex parsed string, maximum size
11839: Given by the constant @code{/line}. Currently 255 characters.
11840:
11841: @item maximum size of a definition name, in characters:
11842: @cindex maximum size of a definition name, in characters
11843: @cindex name, maximum length
11844: 31
11845:
11846: @item maximum string length for @code{ENVIRONMENT?}, in characters:
11847: @cindex maximum string length for @code{ENVIRONMENT?}, in characters
11848: @cindex @code{ENVIRONMENT?} string length, maximum
11849: 31
11850:
11851: @item method of selecting the user input device:
11852: @cindex user input device, method of selecting
11853: The user input device is the standard input. There is currently no way to
11854: change it from within Gforth. However, the input can typically be
11855: redirected in the command line that starts Gforth.
11856:
11857: @item method of selecting the user output device:
11858: @cindex user output device, method of selecting
11859: @code{EMIT} and @code{TYPE} output to the file-id stored in the value
1.10 anton 11860: @code{outfile-id} (@code{stdout} by default). Gforth uses unbuffered
11861: output when the user output device is a terminal, otherwise the output
11862: is buffered.
1.1 anton 11863:
11864: @item methods of dictionary compilation:
11865: What are we expected to document here?
11866:
11867: @item number of bits in one address unit:
11868: @cindex number of bits in one address unit
11869: @cindex address unit, size in bits
11870: @code{s" address-units-bits" environment? drop .}. 8 in all current
11871: ports.
11872:
11873: @item number representation and arithmetic:
11874: @cindex number representation and arithmetic
11875: Processor-dependent. Binary two's complement on all current ports.
11876:
11877: @item ranges for integer types:
11878: @cindex ranges for integer types
11879: @cindex integer types, ranges
11880: Installation-dependent. Make environmental queries for @code{MAX-N},
11881: @code{MAX-U}, @code{MAX-D} and @code{MAX-UD}. The lower bounds for
11882: unsigned (and positive) types is 0. The lower bound for signed types on
11883: two's complement and one's complement machines machines can be computed
11884: by adding 1 to the upper bound.
11885:
11886: @item read-only data space regions:
11887: @cindex read-only data space regions
11888: @cindex data-space, read-only regions
11889: The whole Forth data space is writable.
11890:
11891: @item size of buffer at @code{WORD}:
11892: @cindex size of buffer at @code{WORD}
11893: @cindex @code{WORD} buffer size
11894: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
11895: shared with the pictured numeric output string. If overwriting
11896: @code{PAD} is acceptable, it is as large as the remaining dictionary
11897: space, although only as much can be sensibly used as fits in a counted
11898: string.
11899:
11900: @item size of one cell in address units:
11901: @cindex cell size
11902: @code{1 cells .}.
11903:
11904: @item size of one character in address units:
11905: @cindex char size
11906: @code{1 chars .}. 1 on all current ports.
11907:
11908: @item size of the keyboard terminal buffer:
11909: @cindex size of the keyboard terminal buffer
11910: @cindex terminal buffer, size
11911: Varies. You can determine the size at a specific time using @code{lp@@
11912: tib - .}. It is shared with the locals stack and TIBs of files that
11913: include the current file. You can change the amount of space for TIBs
11914: and locals stack at Gforth startup with the command line option
11915: @code{-l}.
11916:
11917: @item size of the pictured numeric output buffer:
11918: @cindex size of the pictured numeric output buffer
11919: @cindex pictured numeric output buffer, size
11920: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
11921: shared with @code{WORD}.
11922:
11923: @item size of the scratch area returned by @code{PAD}:
11924: @cindex size of the scratch area returned by @code{PAD}
11925: @cindex @code{PAD} size
11926: The remainder of dictionary space. @code{unused pad here - - .}.
11927:
11928: @item system case-sensitivity characteristics:
11929: @cindex case-sensitivity characteristics
1.26 crook 11930: Dictionary searches are case-insensitive (except in
1.1 anton 11931: @code{TABLE}s). However, as explained above under @i{character-set
11932: extensions}, the matching for non-ASCII characters is determined by the
11933: locale you are using. In the default @code{C} locale all non-ASCII
11934: characters are matched case-sensitively.
11935:
11936: @item system prompt:
11937: @cindex system prompt
11938: @cindex prompt
11939: @code{ ok} in interpret state, @code{ compiled} in compile state.
11940:
11941: @item division rounding:
11942: @cindex division rounding
11943: installation dependent. @code{s" floored" environment? drop .}. We leave
11944: the choice to @code{gcc} (what to use for @code{/}) and to you (whether
11945: to use @code{fm/mod}, @code{sm/rem} or simply @code{/}).
11946:
11947: @item values of @code{STATE} when true:
11948: @cindex @code{STATE} values
11949: -1.
11950:
11951: @item values returned after arithmetic overflow:
11952: On two's complement machines, arithmetic is performed modulo
11953: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
11954: arithmetic (with appropriate mapping for signed types). Division by zero
11955: typically results in a @code{-55 throw} (Floating-point unidentified
11956: fault), although a @code{-10 throw} (divide by zero) would be more
11957: appropriate.
11958:
11959: @item whether the current definition can be found after @t{DOES>}:
11960: @cindex @t{DOES>}, visibility of current definition
11961: No.
11962:
11963: @end table
11964:
11965: @c ---------------------------------------------------------------------
11966: @node core-ambcond, core-other, core-idef, The Core Words
11967: @subsection Ambiguous conditions
11968: @c ---------------------------------------------------------------------
11969: @cindex core words, ambiguous conditions
11970: @cindex ambiguous conditions, core words
11971:
11972: @table @i
11973:
11974: @item a name is neither a word nor a number:
11975: @cindex name not found
1.26 crook 11976: @cindex undefined word
1.1 anton 11977: @code{-13 throw} (Undefined word). Actually, @code{-13 bounce}, which
11978: preserves the data and FP stack, so you don't lose more work than
11979: necessary.
11980:
11981: @item a definition name exceeds the maximum length allowed:
1.26 crook 11982: @cindex word name too long
1.1 anton 11983: @code{-19 throw} (Word name too long)
11984:
11985: @item addressing a region not inside the various data spaces of the forth system:
11986: @cindex Invalid memory address
1.32 anton 11987: The stacks, code space and header space are accessible. Machine code space is
1.1 anton 11988: typically readable. Accessing other addresses gives results dependent on
11989: the operating system. On decent systems: @code{-9 throw} (Invalid memory
11990: address).
11991:
11992: @item argument type incompatible with parameter:
1.26 crook 11993: @cindex argument type mismatch
1.1 anton 11994: This is usually not caught. Some words perform checks, e.g., the control
11995: flow words, and issue a @code{ABORT"} or @code{-12 THROW} (Argument type
11996: mismatch).
11997:
11998: @item attempting to obtain the execution token of a word with undefined execution semantics:
11999: @cindex Interpreting a compile-only word, for @code{'} etc.
12000: @cindex execution token of words with undefined execution semantics
12001: @code{-14 throw} (Interpreting a compile-only word). In some cases, you
12002: get an execution token for @code{compile-only-error} (which performs a
12003: @code{-14 throw} when executed).
12004:
12005: @item dividing by zero:
12006: @cindex dividing by zero
12007: @cindex floating point unidentified fault, integer division
1.24 anton 12008: On better platforms, this produces a @code{-10 throw} (Division by
12009: zero); on other systems, this typically results in a @code{-55 throw}
12010: (Floating-point unidentified fault).
1.1 anton 12011:
12012: @item insufficient data stack or return stack space:
12013: @cindex insufficient data stack or return stack space
12014: @cindex stack overflow
1.26 crook 12015: @cindex address alignment exception, stack overflow
1.1 anton 12016: @cindex Invalid memory address, stack overflow
12017: Depending on the operating system, the installation, and the invocation
12018: of Gforth, this is either checked by the memory management hardware, or
1.24 anton 12019: it is not checked. If it is checked, you typically get a @code{-3 throw}
12020: (Stack overflow), @code{-5 throw} (Return stack overflow), or @code{-9
12021: throw} (Invalid memory address) (depending on the platform and how you
12022: achieved the overflow) as soon as the overflow happens. If it is not
12023: checked, overflows typically result in mysterious illegal memory
12024: accesses, producing @code{-9 throw} (Invalid memory address) or
12025: @code{-23 throw} (Address alignment exception); they might also destroy
12026: the internal data structure of @code{ALLOCATE} and friends, resulting in
12027: various errors in these words.
1.1 anton 12028:
12029: @item insufficient space for loop control parameters:
12030: @cindex insufficient space for loop control parameters
12031: like other return stack overflows.
12032:
12033: @item insufficient space in the dictionary:
12034: @cindex insufficient space in the dictionary
12035: @cindex dictionary overflow
1.12 anton 12036: If you try to allot (either directly with @code{allot}, or indirectly
12037: with @code{,}, @code{create} etc.) more memory than available in the
12038: dictionary, you get a @code{-8 throw} (Dictionary overflow). If you try
12039: to access memory beyond the end of the dictionary, the results are
12040: similar to stack overflows.
1.1 anton 12041:
12042: @item interpreting a word with undefined interpretation semantics:
12043: @cindex interpreting a word with undefined interpretation semantics
12044: @cindex Interpreting a compile-only word
12045: For some words, we have defined interpretation semantics. For the
12046: others: @code{-14 throw} (Interpreting a compile-only word).
12047:
12048: @item modifying the contents of the input buffer or a string literal:
12049: @cindex modifying the contents of the input buffer or a string literal
12050: These are located in writable memory and can be modified.
12051:
12052: @item overflow of the pictured numeric output string:
12053: @cindex overflow of the pictured numeric output string
12054: @cindex pictured numeric output string, overflow
1.24 anton 12055: @code{-17 throw} (Pictured numeric ouput string overflow).
1.1 anton 12056:
12057: @item parsed string overflow:
12058: @cindex parsed string overflow
12059: @code{PARSE} cannot overflow. @code{WORD} does not check for overflow.
12060:
12061: @item producing a result out of range:
12062: @cindex result out of range
12063: On two's complement machines, arithmetic is performed modulo
12064: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
12065: arithmetic (with appropriate mapping for signed types). Division by zero
1.24 anton 12066: typically results in a @code{-10 throw} (divide by zero) or @code{-55
12067: throw} (floating point unidentified fault). @code{convert} and
12068: @code{>number} currently overflow silently.
1.1 anton 12069:
12070: @item reading from an empty data or return stack:
12071: @cindex stack empty
12072: @cindex stack underflow
1.24 anton 12073: @cindex return stack underflow
1.1 anton 12074: The data stack is checked by the outer (aka text) interpreter after
12075: every word executed. If it has underflowed, a @code{-4 throw} (Stack
12076: underflow) is performed. Apart from that, stacks may be checked or not,
1.24 anton 12077: depending on operating system, installation, and invocation. If they are
12078: caught by a check, they typically result in @code{-4 throw} (Stack
12079: underflow), @code{-6 throw} (Return stack underflow) or @code{-9 throw}
12080: (Invalid memory address), depending on the platform and which stack
12081: underflows and by how much. Note that even if the system uses checking
12082: (through the MMU), your program may have to underflow by a significant
12083: number of stack items to trigger the reaction (the reason for this is
12084: that the MMU, and therefore the checking, works with a page-size
12085: granularity). If there is no checking, the symptoms resulting from an
12086: underflow are similar to those from an overflow. Unbalanced return
12087: stack errors result in a variaty of symptoms, including @code{-9 throw}
12088: (Invalid memory address) and Illegal Instruction (typically @code{-260
12089: throw}).
1.1 anton 12090:
12091: @item unexpected end of the input buffer, resulting in an attempt to use a zero-length string as a name:
12092: @cindex unexpected end of the input buffer
12093: @cindex zero-length string as a name
12094: @cindex Attempt to use zero-length string as a name
12095: @code{Create} and its descendants perform a @code{-16 throw} (Attempt to
12096: use zero-length string as a name). Words like @code{'} probably will not
12097: find what they search. Note that it is possible to create zero-length
12098: names with @code{nextname} (should it not?).
12099:
12100: @item @code{>IN} greater than input buffer:
12101: @cindex @code{>IN} greater than input buffer
12102: The next invocation of a parsing word returns a string with length 0.
12103:
12104: @item @code{RECURSE} appears after @code{DOES>}:
12105: @cindex @code{RECURSE} appears after @code{DOES>}
12106: Compiles a recursive call to the defining word, not to the defined word.
12107:
12108: @item argument input source different than current input source for @code{RESTORE-INPUT}:
12109: @cindex argument input source different than current input source for @code{RESTORE-INPUT}
1.26 crook 12110: @cindex argument type mismatch, @code{RESTORE-INPUT}
1.1 anton 12111: @cindex @code{RESTORE-INPUT}, Argument type mismatch
12112: @code{-12 THROW}. Note that, once an input file is closed (e.g., because
12113: the end of the file was reached), its source-id may be
12114: reused. Therefore, restoring an input source specification referencing a
12115: closed file may lead to unpredictable results instead of a @code{-12
12116: THROW}.
12117:
12118: In the future, Gforth may be able to restore input source specifications
12119: from other than the current input source.
12120:
12121: @item data space containing definitions gets de-allocated:
12122: @cindex data space containing definitions gets de-allocated
12123: Deallocation with @code{allot} is not checked. This typically results in
12124: memory access faults or execution of illegal instructions.
12125:
12126: @item data space read/write with incorrect alignment:
12127: @cindex data space read/write with incorrect alignment
12128: @cindex alignment faults
1.26 crook 12129: @cindex address alignment exception
1.1 anton 12130: Processor-dependent. Typically results in a @code{-23 throw} (Address
1.12 anton 12131: alignment exception). Under Linux-Intel on a 486 or later processor with
1.1 anton 12132: alignment turned on, incorrect alignment results in a @code{-9 throw}
12133: (Invalid memory address). There are reportedly some processors with
1.12 anton 12134: alignment restrictions that do not report violations.
1.1 anton 12135:
12136: @item data space pointer not properly aligned, @code{,}, @code{C,}:
12137: @cindex data space pointer not properly aligned, @code{,}, @code{C,}
12138: Like other alignment errors.
12139:
12140: @item less than u+2 stack items (@code{PICK} and @code{ROLL}):
12141: Like other stack underflows.
12142:
12143: @item loop control parameters not available:
12144: @cindex loop control parameters not available
12145: Not checked. The counted loop words simply assume that the top of return
12146: stack items are loop control parameters and behave accordingly.
12147:
12148: @item most recent definition does not have a name (@code{IMMEDIATE}):
12149: @cindex most recent definition does not have a name (@code{IMMEDIATE})
12150: @cindex last word was headerless
12151: @code{abort" last word was headerless"}.
12152:
12153: @item name not defined by @code{VALUE} used by @code{TO}:
12154: @cindex name not defined by @code{VALUE} used by @code{TO}
12155: @cindex @code{TO} on non-@code{VALUE}s
12156: @cindex Invalid name argument, @code{TO}
12157: @code{-32 throw} (Invalid name argument) (unless name is a local or was
12158: defined by @code{CONSTANT}; in the latter case it just changes the constant).
12159:
12160: @item name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}):
12161: @cindex name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]})
1.26 crook 12162: @cindex undefined word, @code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}
1.1 anton 12163: @code{-13 throw} (Undefined word)
12164:
12165: @item parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN}):
12166: @cindex parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN})
12167: Gforth behaves as if they were of the same type. I.e., you can predict
12168: the behaviour by interpreting all parameters as, e.g., signed.
12169:
12170: @item @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}:
12171: @cindex @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}
12172: Assume @code{: X POSTPONE TO ; IMMEDIATE}. @code{X} performs the
12173: compilation semantics of @code{TO}.
12174:
12175: @item String longer than a counted string returned by @code{WORD}:
1.26 crook 12176: @cindex string longer than a counted string returned by @code{WORD}
1.1 anton 12177: @cindex @code{WORD}, string overflow
12178: Not checked. The string will be ok, but the count will, of course,
12179: contain only the least significant bits of the length.
12180:
12181: @item u greater than or equal to the number of bits in a cell (@code{LSHIFT}, @code{RSHIFT}):
12182: @cindex @code{LSHIFT}, large shift counts
12183: @cindex @code{RSHIFT}, large shift counts
12184: Processor-dependent. Typical behaviours are returning 0 and using only
12185: the low bits of the shift count.
12186:
12187: @item word not defined via @code{CREATE}:
12188: @cindex @code{>BODY} of non-@code{CREATE}d words
12189: @code{>BODY} produces the PFA of the word no matter how it was defined.
12190:
12191: @cindex @code{DOES>} of non-@code{CREATE}d words
12192: @code{DOES>} changes the execution semantics of the last defined word no
12193: matter how it was defined. E.g., @code{CONSTANT DOES>} is equivalent to
12194: @code{CREATE , DOES>}.
12195:
12196: @item words improperly used outside @code{<#} and @code{#>}:
12197: Not checked. As usual, you can expect memory faults.
12198:
12199: @end table
12200:
12201:
12202: @c ---------------------------------------------------------------------
12203: @node core-other, , core-ambcond, The Core Words
12204: @subsection Other system documentation
12205: @c ---------------------------------------------------------------------
12206: @cindex other system documentation, core words
12207: @cindex core words, other system documentation
12208:
12209: @table @i
12210: @item nonstandard words using @code{PAD}:
12211: @cindex @code{PAD} use by nonstandard words
12212: None.
12213:
12214: @item operator's terminal facilities available:
12215: @cindex operator's terminal facilities available
12216: After processing the command line, Gforth goes into interactive mode,
12217: and you can give commands to Gforth interactively. The actual facilities
12218: available depend on how you invoke Gforth.
12219:
12220: @item program data space available:
12221: @cindex program data space available
12222: @cindex data space available
12223: @code{UNUSED .} gives the remaining dictionary space. The total
12224: dictionary space can be specified with the @code{-m} switch
12225: (@pxref{Invoking Gforth}) when Gforth starts up.
12226:
12227: @item return stack space available:
12228: @cindex return stack space available
12229: You can compute the total return stack space in cells with
12230: @code{s" RETURN-STACK-CELLS" environment? drop .}. You can specify it at
12231: startup time with the @code{-r} switch (@pxref{Invoking Gforth}).
12232:
12233: @item stack space available:
12234: @cindex stack space available
12235: You can compute the total data stack space in cells with
12236: @code{s" STACK-CELLS" environment? drop .}. You can specify it at
12237: startup time with the @code{-d} switch (@pxref{Invoking Gforth}).
12238:
12239: @item system dictionary space required, in address units:
12240: @cindex system dictionary space required, in address units
12241: Type @code{here forthstart - .} after startup. At the time of this
12242: writing, this gives 80080 (bytes) on a 32-bit system.
12243: @end table
12244:
12245:
12246: @c =====================================================================
12247: @node The optional Block word set, The optional Double Number word set, The Core Words, ANS conformance
12248: @section The optional Block word set
12249: @c =====================================================================
12250: @cindex system documentation, block words
12251: @cindex block words, system documentation
12252:
12253: @menu
12254: * block-idef:: Implementation Defined Options
12255: * block-ambcond:: Ambiguous Conditions
12256: * block-other:: Other System Documentation
12257: @end menu
12258:
12259:
12260: @c ---------------------------------------------------------------------
12261: @node block-idef, block-ambcond, The optional Block word set, The optional Block word set
12262: @subsection Implementation Defined Options
12263: @c ---------------------------------------------------------------------
12264: @cindex implementation-defined options, block words
12265: @cindex block words, implementation-defined options
12266:
12267: @table @i
12268: @item the format for display by @code{LIST}:
12269: @cindex @code{LIST} display format
12270: First the screen number is displayed, then 16 lines of 64 characters,
12271: each line preceded by the line number.
12272:
12273: @item the length of a line affected by @code{\}:
12274: @cindex length of a line affected by @code{\}
12275: @cindex @code{\}, line length in blocks
12276: 64 characters.
12277: @end table
12278:
12279:
12280: @c ---------------------------------------------------------------------
12281: @node block-ambcond, block-other, block-idef, The optional Block word set
12282: @subsection Ambiguous conditions
12283: @c ---------------------------------------------------------------------
12284: @cindex block words, ambiguous conditions
12285: @cindex ambiguous conditions, block words
12286:
12287: @table @i
12288: @item correct block read was not possible:
12289: @cindex block read not possible
12290: Typically results in a @code{throw} of some OS-derived value (between
12291: -512 and -2048). If the blocks file was just not long enough, blanks are
12292: supplied for the missing portion.
12293:
12294: @item I/O exception in block transfer:
12295: @cindex I/O exception in block transfer
12296: @cindex block transfer, I/O exception
12297: Typically results in a @code{throw} of some OS-derived value (between
12298: -512 and -2048).
12299:
12300: @item invalid block number:
12301: @cindex invalid block number
12302: @cindex block number invalid
12303: @code{-35 throw} (Invalid block number)
12304:
12305: @item a program directly alters the contents of @code{BLK}:
12306: @cindex @code{BLK}, altering @code{BLK}
12307: The input stream is switched to that other block, at the same
12308: position. If the storing to @code{BLK} happens when interpreting
12309: non-block input, the system will get quite confused when the block ends.
12310:
12311: @item no current block buffer for @code{UPDATE}:
12312: @cindex @code{UPDATE}, no current block buffer
12313: @code{UPDATE} has no effect.
12314:
12315: @end table
12316:
12317: @c ---------------------------------------------------------------------
12318: @node block-other, , block-ambcond, The optional Block word set
12319: @subsection Other system documentation
12320: @c ---------------------------------------------------------------------
12321: @cindex other system documentation, block words
12322: @cindex block words, other system documentation
12323:
12324: @table @i
12325: @item any restrictions a multiprogramming system places on the use of buffer addresses:
12326: No restrictions (yet).
12327:
12328: @item the number of blocks available for source and data:
12329: depends on your disk space.
12330:
12331: @end table
12332:
12333:
12334: @c =====================================================================
12335: @node The optional Double Number word set, The optional Exception word set, The optional Block word set, ANS conformance
12336: @section The optional Double Number word set
12337: @c =====================================================================
12338: @cindex system documentation, double words
12339: @cindex double words, system documentation
12340:
12341: @menu
12342: * double-ambcond:: Ambiguous Conditions
12343: @end menu
12344:
12345:
12346: @c ---------------------------------------------------------------------
12347: @node double-ambcond, , The optional Double Number word set, The optional Double Number word set
12348: @subsection Ambiguous conditions
12349: @c ---------------------------------------------------------------------
12350: @cindex double words, ambiguous conditions
12351: @cindex ambiguous conditions, double words
12352:
12353: @table @i
1.29 crook 12354: @item @i{d} outside of range of @i{n} in @code{D>S}:
12355: @cindex @code{D>S}, @i{d} out of range of @i{n}
12356: The least significant cell of @i{d} is produced.
1.1 anton 12357:
12358: @end table
12359:
12360:
12361: @c =====================================================================
12362: @node The optional Exception word set, The optional Facility word set, The optional Double Number word set, ANS conformance
12363: @section The optional Exception word set
12364: @c =====================================================================
12365: @cindex system documentation, exception words
12366: @cindex exception words, system documentation
12367:
12368: @menu
12369: * exception-idef:: Implementation Defined Options
12370: @end menu
12371:
12372:
12373: @c ---------------------------------------------------------------------
12374: @node exception-idef, , The optional Exception word set, The optional Exception word set
12375: @subsection Implementation Defined Options
12376: @c ---------------------------------------------------------------------
12377: @cindex implementation-defined options, exception words
12378: @cindex exception words, implementation-defined options
12379:
12380: @table @i
12381: @item @code{THROW}-codes used in the system:
12382: @cindex @code{THROW}-codes used in the system
12383: The codes -256@minus{}-511 are used for reporting signals. The mapping
1.29 crook 12384: from OS signal numbers to throw codes is -256@minus{}@i{signal}. The
1.1 anton 12385: codes -512@minus{}-2047 are used for OS errors (for file and memory
12386: allocation operations). The mapping from OS error numbers to throw codes
12387: is -512@minus{}@code{errno}. One side effect of this mapping is that
12388: undefined OS errors produce a message with a strange number; e.g.,
12389: @code{-1000 THROW} results in @code{Unknown error 488} on my system.
12390: @end table
12391:
12392: @c =====================================================================
12393: @node The optional Facility word set, The optional File-Access word set, The optional Exception word set, ANS conformance
12394: @section The optional Facility word set
12395: @c =====================================================================
12396: @cindex system documentation, facility words
12397: @cindex facility words, system documentation
12398:
12399: @menu
12400: * facility-idef:: Implementation Defined Options
12401: * facility-ambcond:: Ambiguous Conditions
12402: @end menu
12403:
12404:
12405: @c ---------------------------------------------------------------------
12406: @node facility-idef, facility-ambcond, The optional Facility word set, The optional Facility word set
12407: @subsection Implementation Defined Options
12408: @c ---------------------------------------------------------------------
12409: @cindex implementation-defined options, facility words
12410: @cindex facility words, implementation-defined options
12411:
12412: @table @i
12413: @item encoding of keyboard events (@code{EKEY}):
12414: @cindex keyboard events, encoding in @code{EKEY}
12415: @cindex @code{EKEY}, encoding of keyboard events
1.40 anton 12416: Keys corresponding to ASCII characters are encoded as ASCII characters.
1.41 anton 12417: Other keys are encoded with the constants @code{k-left}, @code{k-right},
12418: @code{k-up}, @code{k-down}, @code{k-home}, @code{k-end}, @code{k1},
12419: @code{k2}, @code{k3}, @code{k4}, @code{k5}, @code{k6}, @code{k7},
12420: @code{k8}, @code{k9}, @code{k10}, @code{k11}, @code{k12}.
1.40 anton 12421:
1.1 anton 12422:
12423: @item duration of a system clock tick:
12424: @cindex duration of a system clock tick
12425: @cindex clock tick duration
12426: System dependent. With respect to @code{MS}, the time is specified in
12427: microseconds. How well the OS and the hardware implement this, is
12428: another question.
12429:
12430: @item repeatability to be expected from the execution of @code{MS}:
12431: @cindex repeatability to be expected from the execution of @code{MS}
12432: @cindex @code{MS}, repeatability to be expected
12433: System dependent. On Unix, a lot depends on load. If the system is
12434: lightly loaded, and the delay is short enough that Gforth does not get
12435: swapped out, the performance should be acceptable. Under MS-DOS and
12436: other single-tasking systems, it should be good.
12437:
12438: @end table
12439:
12440:
12441: @c ---------------------------------------------------------------------
12442: @node facility-ambcond, , facility-idef, The optional Facility word set
12443: @subsection Ambiguous conditions
12444: @c ---------------------------------------------------------------------
12445: @cindex facility words, ambiguous conditions
12446: @cindex ambiguous conditions, facility words
12447:
12448: @table @i
12449: @item @code{AT-XY} can't be performed on user output device:
12450: @cindex @code{AT-XY} can't be performed on user output device
12451: Largely terminal dependent. No range checks are done on the arguments.
12452: No errors are reported. You may see some garbage appearing, you may see
12453: simply nothing happen.
12454:
12455: @end table
12456:
12457:
12458: @c =====================================================================
12459: @node The optional File-Access word set, The optional Floating-Point word set, The optional Facility word set, ANS conformance
12460: @section The optional File-Access word set
12461: @c =====================================================================
12462: @cindex system documentation, file words
12463: @cindex file words, system documentation
12464:
12465: @menu
12466: * file-idef:: Implementation Defined Options
12467: * file-ambcond:: Ambiguous Conditions
12468: @end menu
12469:
12470: @c ---------------------------------------------------------------------
12471: @node file-idef, file-ambcond, The optional File-Access word set, The optional File-Access word set
12472: @subsection Implementation Defined Options
12473: @c ---------------------------------------------------------------------
12474: @cindex implementation-defined options, file words
12475: @cindex file words, implementation-defined options
12476:
12477: @table @i
12478: @item file access methods used:
12479: @cindex file access methods used
12480: @code{R/O}, @code{R/W} and @code{BIN} work as you would
12481: expect. @code{W/O} translates into the C file opening mode @code{w} (or
12482: @code{wb}): The file is cleared, if it exists, and created, if it does
12483: not (with both @code{open-file} and @code{create-file}). Under Unix
12484: @code{create-file} creates a file with 666 permissions modified by your
12485: umask.
12486:
12487: @item file exceptions:
12488: @cindex file exceptions
12489: The file words do not raise exceptions (except, perhaps, memory access
12490: faults when you pass illegal addresses or file-ids).
12491:
12492: @item file line terminator:
12493: @cindex file line terminator
12494: System-dependent. Gforth uses C's newline character as line
12495: terminator. What the actual character code(s) of this are is
12496: system-dependent.
12497:
12498: @item file name format:
12499: @cindex file name format
12500: System dependent. Gforth just uses the file name format of your OS.
12501:
12502: @item information returned by @code{FILE-STATUS}:
12503: @cindex @code{FILE-STATUS}, returned information
12504: @code{FILE-STATUS} returns the most powerful file access mode allowed
12505: for the file: Either @code{R/O}, @code{W/O} or @code{R/W}. If the file
12506: cannot be accessed, @code{R/O BIN} is returned. @code{BIN} is applicable
12507: along with the returned mode.
12508:
12509: @item input file state after an exception when including source:
12510: @cindex exception when including source
12511: All files that are left via the exception are closed.
12512:
1.29 crook 12513: @item @i{ior} values and meaning:
12514: @cindex @i{ior} values and meaning
1.68 ! anton 12515: @cindex @i{wior} values and meaning
1.29 crook 12516: The @i{ior}s returned by the file and memory allocation words are
1.1 anton 12517: intended as throw codes. They typically are in the range
12518: -512@minus{}-2047 of OS errors. The mapping from OS error numbers to
1.29 crook 12519: @i{ior}s is -512@minus{}@i{errno}.
1.1 anton 12520:
12521: @item maximum depth of file input nesting:
12522: @cindex maximum depth of file input nesting
12523: @cindex file input nesting, maximum depth
12524: limited by the amount of return stack, locals/TIB stack, and the number
12525: of open files available. This should not give you troubles.
12526:
12527: @item maximum size of input line:
12528: @cindex maximum size of input line
12529: @cindex input line size, maximum
12530: @code{/line}. Currently 255.
12531:
12532: @item methods of mapping block ranges to files:
12533: @cindex mapping block ranges to files
12534: @cindex files containing blocks
12535: @cindex blocks in files
12536: By default, blocks are accessed in the file @file{blocks.fb} in the
12537: current working directory. The file can be switched with @code{USE}.
12538:
12539: @item number of string buffers provided by @code{S"}:
12540: @cindex @code{S"}, number of string buffers
12541: 1
12542:
12543: @item size of string buffer used by @code{S"}:
12544: @cindex @code{S"}, size of string buffer
12545: @code{/line}. currently 255.
12546:
12547: @end table
12548:
12549: @c ---------------------------------------------------------------------
12550: @node file-ambcond, , file-idef, The optional File-Access word set
12551: @subsection Ambiguous conditions
12552: @c ---------------------------------------------------------------------
12553: @cindex file words, ambiguous conditions
12554: @cindex ambiguous conditions, file words
12555:
12556: @table @i
12557: @item attempting to position a file outside its boundaries:
12558: @cindex @code{REPOSITION-FILE}, outside the file's boundaries
12559: @code{REPOSITION-FILE} is performed as usual: Afterwards,
12560: @code{FILE-POSITION} returns the value given to @code{REPOSITION-FILE}.
12561:
12562: @item attempting to read from file positions not yet written:
12563: @cindex reading from file positions not yet written
12564: End-of-file, i.e., zero characters are read and no error is reported.
12565:
1.29 crook 12566: @item @i{file-id} is invalid (@code{INCLUDE-FILE}):
12567: @cindex @code{INCLUDE-FILE}, @i{file-id} is invalid
1.1 anton 12568: An appropriate exception may be thrown, but a memory fault or other
12569: problem is more probable.
12570:
1.29 crook 12571: @item I/O exception reading or closing @i{file-id} (@code{INCLUDE-FILE}, @code{INCLUDED}):
12572: @cindex @code{INCLUDE-FILE}, I/O exception reading or closing @i{file-id}
12573: @cindex @code{INCLUDED}, I/O exception reading or closing @i{file-id}
12574: The @i{ior} produced by the operation, that discovered the problem, is
1.1 anton 12575: thrown.
12576:
12577: @item named file cannot be opened (@code{INCLUDED}):
12578: @cindex @code{INCLUDED}, named file cannot be opened
1.29 crook 12579: The @i{ior} produced by @code{open-file} is thrown.
1.1 anton 12580:
12581: @item requesting an unmapped block number:
12582: @cindex unmapped block numbers
12583: There are no unmapped legal block numbers. On some operating systems,
12584: writing a block with a large number may overflow the file system and
12585: have an error message as consequence.
12586:
12587: @item using @code{source-id} when @code{blk} is non-zero:
12588: @cindex @code{SOURCE-ID}, behaviour when @code{BLK} is non-zero
12589: @code{source-id} performs its function. Typically it will give the id of
12590: the source which loaded the block. (Better ideas?)
12591:
12592: @end table
12593:
12594:
12595: @c =====================================================================
12596: @node The optional Floating-Point word set, The optional Locals word set, The optional File-Access word set, ANS conformance
12597: @section The optional Floating-Point word set
12598: @c =====================================================================
12599: @cindex system documentation, floating-point words
12600: @cindex floating-point words, system documentation
12601:
12602: @menu
12603: * floating-idef:: Implementation Defined Options
12604: * floating-ambcond:: Ambiguous Conditions
12605: @end menu
12606:
12607:
12608: @c ---------------------------------------------------------------------
12609: @node floating-idef, floating-ambcond, The optional Floating-Point word set, The optional Floating-Point word set
12610: @subsection Implementation Defined Options
12611: @c ---------------------------------------------------------------------
12612: @cindex implementation-defined options, floating-point words
12613: @cindex floating-point words, implementation-defined options
12614:
12615: @table @i
12616: @item format and range of floating point numbers:
12617: @cindex format and range of floating point numbers
12618: @cindex floating point numbers, format and range
12619: System-dependent; the @code{double} type of C.
12620:
1.29 crook 12621: @item results of @code{REPRESENT} when @i{float} is out of range:
12622: @cindex @code{REPRESENT}, results when @i{float} is out of range
1.1 anton 12623: System dependent; @code{REPRESENT} is implemented using the C library
12624: function @code{ecvt()} and inherits its behaviour in this respect.
12625:
12626: @item rounding or truncation of floating-point numbers:
12627: @cindex rounding of floating-point numbers
12628: @cindex truncation of floating-point numbers
12629: @cindex floating-point numbers, rounding or truncation
12630: System dependent; the rounding behaviour is inherited from the hosting C
12631: compiler. IEEE-FP-based (i.e., most) systems by default round to
12632: nearest, and break ties by rounding to even (i.e., such that the last
12633: bit of the mantissa is 0).
12634:
12635: @item size of floating-point stack:
12636: @cindex floating-point stack size
12637: @code{s" FLOATING-STACK" environment? drop .} gives the total size of
12638: the floating-point stack (in floats). You can specify this on startup
12639: with the command-line option @code{-f} (@pxref{Invoking Gforth}).
12640:
12641: @item width of floating-point stack:
12642: @cindex floating-point stack width
12643: @code{1 floats}.
12644:
12645: @end table
12646:
12647:
12648: @c ---------------------------------------------------------------------
12649: @node floating-ambcond, , floating-idef, The optional Floating-Point word set
12650: @subsection Ambiguous conditions
12651: @c ---------------------------------------------------------------------
12652: @cindex floating-point words, ambiguous conditions
12653: @cindex ambiguous conditions, floating-point words
12654:
12655: @table @i
12656: @item @code{df@@} or @code{df!} used with an address that is not double-float aligned:
12657: @cindex @code{df@@} or @code{df!} used with an address that is not double-float aligned
12658: System-dependent. Typically results in a @code{-23 THROW} like other
12659: alignment violations.
12660:
12661: @item @code{f@@} or @code{f!} used with an address that is not float aligned:
12662: @cindex @code{f@@} used with an address that is not float aligned
12663: @cindex @code{f!} used with an address that is not float aligned
12664: System-dependent. Typically results in a @code{-23 THROW} like other
12665: alignment violations.
12666:
12667: @item floating-point result out of range:
12668: @cindex floating-point result out of range
12669: System-dependent. Can result in a @code{-55 THROW} (Floating-point
12670: unidentified fault), or can produce a special value representing, e.g.,
12671: Infinity.
12672:
12673: @item @code{sf@@} or @code{sf!} used with an address that is not single-float aligned:
12674: @cindex @code{sf@@} or @code{sf!} used with an address that is not single-float aligned
12675: System-dependent. Typically results in an alignment fault like other
12676: alignment violations.
12677:
1.35 anton 12678: @item @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.}):
12679: @cindex @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.})
1.1 anton 12680: The floating-point number is converted into decimal nonetheless.
12681:
12682: @item Both arguments are equal to zero (@code{FATAN2}):
12683: @cindex @code{FATAN2}, both arguments are equal to zero
12684: System-dependent. @code{FATAN2} is implemented using the C library
12685: function @code{atan2()}.
12686:
1.29 crook 12687: @item Using @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero:
12688: @cindex @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero
12689: System-dependent. Anyway, typically the cos of @i{r1} will not be zero
1.1 anton 12690: because of small errors and the tan will be a very large (or very small)
12691: but finite number.
12692:
1.29 crook 12693: @item @i{d} cannot be presented precisely as a float in @code{D>F}:
12694: @cindex @code{D>F}, @i{d} cannot be presented precisely as a float
1.1 anton 12695: The result is rounded to the nearest float.
12696:
12697: @item dividing by zero:
12698: @cindex dividing by zero, floating-point
12699: @cindex floating-point dividing by zero
12700: @cindex floating-point unidentified fault, FP divide-by-zero
12701: @code{-55 throw} (Floating-point unidentified fault)
12702:
12703: @item exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@}):
12704: @cindex exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@})
12705: System dependent. On IEEE-FP based systems the number is converted into
12706: an infinity.
12707:
1.29 crook 12708: @item @i{float}<1 (@code{FACOSH}):
12709: @cindex @code{FACOSH}, @i{float}<1
1.1 anton 12710: @cindex floating-point unidentified fault, @code{FACOSH}
12711: @code{-55 throw} (Floating-point unidentified fault)
12712:
1.29 crook 12713: @item @i{float}=<-1 (@code{FLNP1}):
12714: @cindex @code{FLNP1}, @i{float}=<-1
1.1 anton 12715: @cindex floating-point unidentified fault, @code{FLNP1}
12716: @code{-55 throw} (Floating-point unidentified fault). On IEEE-FP systems
1.29 crook 12717: negative infinity is typically produced for @i{float}=-1.
1.1 anton 12718:
1.29 crook 12719: @item @i{float}=<0 (@code{FLN}, @code{FLOG}):
12720: @cindex @code{FLN}, @i{float}=<0
12721: @cindex @code{FLOG}, @i{float}=<0
1.1 anton 12722: @cindex floating-point unidentified fault, @code{FLN} or @code{FLOG}
12723: @code{-55 throw} (Floating-point unidentified fault). On IEEE-FP systems
1.29 crook 12724: negative infinity is typically produced for @i{float}=0.
1.1 anton 12725:
1.29 crook 12726: @item @i{float}<0 (@code{FASINH}, @code{FSQRT}):
12727: @cindex @code{FASINH}, @i{float}<0
12728: @cindex @code{FSQRT}, @i{float}<0
1.1 anton 12729: @cindex floating-point unidentified fault, @code{FASINH} or @code{FSQRT}
12730: @code{-55 throw} (Floating-point unidentified fault). @code{fasinh}
12731: produces values for these inputs on my Linux box (Bug in the C library?)
12732:
1.29 crook 12733: @item |@i{float}|>1 (@code{FACOS}, @code{FASIN}, @code{FATANH}):
12734: @cindex @code{FACOS}, |@i{float}|>1
12735: @cindex @code{FASIN}, |@i{float}|>1
12736: @cindex @code{FATANH}, |@i{float}|>1
1.1 anton 12737: @cindex floating-point unidentified fault, @code{FACOS}, @code{FASIN} or @code{FATANH}
12738: @code{-55 throw} (Floating-point unidentified fault).
12739:
1.29 crook 12740: @item integer part of float cannot be represented by @i{d} in @code{F>D}:
12741: @cindex @code{F>D}, integer part of float cannot be represented by @i{d}
1.1 anton 12742: @cindex floating-point unidentified fault, @code{F>D}
12743: @code{-55 throw} (Floating-point unidentified fault).
12744:
12745: @item string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.}):
12746: @cindex string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.})
12747: This does not happen.
12748: @end table
12749:
12750: @c =====================================================================
12751: @node The optional Locals word set, The optional Memory-Allocation word set, The optional Floating-Point word set, ANS conformance
12752: @section The optional Locals word set
12753: @c =====================================================================
12754: @cindex system documentation, locals words
12755: @cindex locals words, system documentation
12756:
12757: @menu
12758: * locals-idef:: Implementation Defined Options
12759: * locals-ambcond:: Ambiguous Conditions
12760: @end menu
12761:
12762:
12763: @c ---------------------------------------------------------------------
12764: @node locals-idef, locals-ambcond, The optional Locals word set, The optional Locals word set
12765: @subsection Implementation Defined Options
12766: @c ---------------------------------------------------------------------
12767: @cindex implementation-defined options, locals words
12768: @cindex locals words, implementation-defined options
12769:
12770: @table @i
12771: @item maximum number of locals in a definition:
12772: @cindex maximum number of locals in a definition
12773: @cindex locals, maximum number in a definition
12774: @code{s" #locals" environment? drop .}. Currently 15. This is a lower
12775: bound, e.g., on a 32-bit machine there can be 41 locals of up to 8
12776: characters. The number of locals in a definition is bounded by the size
12777: of locals-buffer, which contains the names of the locals.
12778:
12779: @end table
12780:
12781:
12782: @c ---------------------------------------------------------------------
12783: @node locals-ambcond, , locals-idef, The optional Locals word set
12784: @subsection Ambiguous conditions
12785: @c ---------------------------------------------------------------------
12786: @cindex locals words, ambiguous conditions
12787: @cindex ambiguous conditions, locals words
12788:
12789: @table @i
12790: @item executing a named local in interpretation state:
12791: @cindex local in interpretation state
12792: @cindex Interpreting a compile-only word, for a local
12793: Locals have no interpretation semantics. If you try to perform the
12794: interpretation semantics, you will get a @code{-14 throw} somewhere
12795: (Interpreting a compile-only word). If you perform the compilation
12796: semantics, the locals access will be compiled (irrespective of state).
12797:
1.29 crook 12798: @item @i{name} not defined by @code{VALUE} or @code{(LOCAL)} (@code{TO}):
1.1 anton 12799: @cindex name not defined by @code{VALUE} or @code{(LOCAL)} used by @code{TO}
12800: @cindex @code{TO} on non-@code{VALUE}s and non-locals
12801: @cindex Invalid name argument, @code{TO}
12802: @code{-32 throw} (Invalid name argument)
12803:
12804: @end table
12805:
12806:
12807: @c =====================================================================
12808: @node The optional Memory-Allocation word set, The optional Programming-Tools word set, The optional Locals word set, ANS conformance
12809: @section The optional Memory-Allocation word set
12810: @c =====================================================================
12811: @cindex system documentation, memory-allocation words
12812: @cindex memory-allocation words, system documentation
12813:
12814: @menu
12815: * memory-idef:: Implementation Defined Options
12816: @end menu
12817:
12818:
12819: @c ---------------------------------------------------------------------
12820: @node memory-idef, , The optional Memory-Allocation word set, The optional Memory-Allocation word set
12821: @subsection Implementation Defined Options
12822: @c ---------------------------------------------------------------------
12823: @cindex implementation-defined options, memory-allocation words
12824: @cindex memory-allocation words, implementation-defined options
12825:
12826: @table @i
1.29 crook 12827: @item values and meaning of @i{ior}:
12828: @cindex @i{ior} values and meaning
12829: The @i{ior}s returned by the file and memory allocation words are
1.1 anton 12830: intended as throw codes. They typically are in the range
12831: -512@minus{}-2047 of OS errors. The mapping from OS error numbers to
1.29 crook 12832: @i{ior}s is -512@minus{}@i{errno}.
1.1 anton 12833:
12834: @end table
12835:
12836: @c =====================================================================
12837: @node The optional Programming-Tools word set, The optional Search-Order word set, The optional Memory-Allocation word set, ANS conformance
12838: @section The optional Programming-Tools word set
12839: @c =====================================================================
12840: @cindex system documentation, programming-tools words
12841: @cindex programming-tools words, system documentation
12842:
12843: @menu
12844: * programming-idef:: Implementation Defined Options
12845: * programming-ambcond:: Ambiguous Conditions
12846: @end menu
12847:
12848:
12849: @c ---------------------------------------------------------------------
12850: @node programming-idef, programming-ambcond, The optional Programming-Tools word set, The optional Programming-Tools word set
12851: @subsection Implementation Defined Options
12852: @c ---------------------------------------------------------------------
12853: @cindex implementation-defined options, programming-tools words
12854: @cindex programming-tools words, implementation-defined options
12855:
12856: @table @i
12857: @item ending sequence for input following @code{;CODE} and @code{CODE}:
12858: @cindex @code{;CODE} ending sequence
12859: @cindex @code{CODE} ending sequence
12860: @code{END-CODE}
12861:
12862: @item manner of processing input following @code{;CODE} and @code{CODE}:
12863: @cindex @code{;CODE}, processing input
12864: @cindex @code{CODE}, processing input
12865: The @code{ASSEMBLER} vocabulary is pushed on the search order stack, and
12866: the input is processed by the text interpreter, (starting) in interpret
12867: state.
12868:
12869: @item search order capability for @code{EDITOR} and @code{ASSEMBLER}:
12870: @cindex @code{ASSEMBLER}, search order capability
12871: The ANS Forth search order word set.
12872:
12873: @item source and format of display by @code{SEE}:
12874: @cindex @code{SEE}, source and format of output
12875: The source for @code{see} is the intermediate code used by the inner
12876: interpreter. The current @code{see} tries to output Forth source code
12877: as well as possible.
12878:
12879: @end table
12880:
12881: @c ---------------------------------------------------------------------
12882: @node programming-ambcond, , programming-idef, The optional Programming-Tools word set
12883: @subsection Ambiguous conditions
12884: @c ---------------------------------------------------------------------
12885: @cindex programming-tools words, ambiguous conditions
12886: @cindex ambiguous conditions, programming-tools words
12887:
12888: @table @i
12889:
1.21 crook 12890: @item deleting the compilation word list (@code{FORGET}):
12891: @cindex @code{FORGET}, deleting the compilation word list
1.1 anton 12892: Not implemented (yet).
12893:
1.29 crook 12894: @item fewer than @i{u}+1 items on the control-flow stack (@code{CS-PICK}, @code{CS-ROLL}):
12895: @cindex @code{CS-PICK}, fewer than @i{u}+1 items on the control flow-stack
12896: @cindex @code{CS-ROLL}, fewer than @i{u}+1 items on the control flow-stack
1.1 anton 12897: @cindex control-flow stack underflow
12898: This typically results in an @code{abort"} with a descriptive error
12899: message (may change into a @code{-22 throw} (Control structure mismatch)
12900: in the future). You may also get a memory access error. If you are
12901: unlucky, this ambiguous condition is not caught.
12902:
1.29 crook 12903: @item @i{name} can't be found (@code{FORGET}):
12904: @cindex @code{FORGET}, @i{name} can't be found
1.1 anton 12905: Not implemented (yet).
12906:
1.29 crook 12907: @item @i{name} not defined via @code{CREATE}:
12908: @cindex @code{;CODE}, @i{name} not defined via @code{CREATE}
1.1 anton 12909: @code{;CODE} behaves like @code{DOES>} in this respect, i.e., it changes
12910: the execution semantics of the last defined word no matter how it was
12911: defined.
12912:
12913: @item @code{POSTPONE} applied to @code{[IF]}:
12914: @cindex @code{POSTPONE} applied to @code{[IF]}
12915: @cindex @code{[IF]} and @code{POSTPONE}
12916: After defining @code{: X POSTPONE [IF] ; IMMEDIATE}. @code{X} is
12917: equivalent to @code{[IF]}.
12918:
12919: @item reaching the end of the input source before matching @code{[ELSE]} or @code{[THEN]}:
12920: @cindex @code{[IF]}, end of the input source before matching @code{[ELSE]} or @code{[THEN]}
12921: Continue in the same state of conditional compilation in the next outer
12922: input source. Currently there is no warning to the user about this.
12923:
12924: @item removing a needed definition (@code{FORGET}):
12925: @cindex @code{FORGET}, removing a needed definition
12926: Not implemented (yet).
12927:
12928: @end table
12929:
12930:
12931: @c =====================================================================
12932: @node The optional Search-Order word set, , The optional Programming-Tools word set, ANS conformance
12933: @section The optional Search-Order word set
12934: @c =====================================================================
12935: @cindex system documentation, search-order words
12936: @cindex search-order words, system documentation
12937:
12938: @menu
12939: * search-idef:: Implementation Defined Options
12940: * search-ambcond:: Ambiguous Conditions
12941: @end menu
12942:
12943:
12944: @c ---------------------------------------------------------------------
12945: @node search-idef, search-ambcond, The optional Search-Order word set, The optional Search-Order word set
12946: @subsection Implementation Defined Options
12947: @c ---------------------------------------------------------------------
12948: @cindex implementation-defined options, search-order words
12949: @cindex search-order words, implementation-defined options
12950:
12951: @table @i
12952: @item maximum number of word lists in search order:
12953: @cindex maximum number of word lists in search order
12954: @cindex search order, maximum depth
12955: @code{s" wordlists" environment? drop .}. Currently 16.
12956:
12957: @item minimum search order:
12958: @cindex minimum search order
12959: @cindex search order, minimum
12960: @code{root root}.
12961:
12962: @end table
12963:
12964: @c ---------------------------------------------------------------------
12965: @node search-ambcond, , search-idef, The optional Search-Order word set
12966: @subsection Ambiguous conditions
12967: @c ---------------------------------------------------------------------
12968: @cindex search-order words, ambiguous conditions
12969: @cindex ambiguous conditions, search-order words
12970:
12971: @table @i
1.21 crook 12972: @item changing the compilation word list (during compilation):
12973: @cindex changing the compilation word list (during compilation)
12974: @cindex compilation word list, change before definition ends
12975: The word is entered into the word list that was the compilation word list
1.1 anton 12976: at the start of the definition. Any changes to the name field (e.g.,
12977: @code{immediate}) or the code field (e.g., when executing @code{DOES>})
12978: are applied to the latest defined word (as reported by @code{last} or
1.21 crook 12979: @code{lastxt}), if possible, irrespective of the compilation word list.
1.1 anton 12980:
12981: @item search order empty (@code{previous}):
12982: @cindex @code{previous}, search order empty
1.26 crook 12983: @cindex vocstack empty, @code{previous}
1.1 anton 12984: @code{abort" Vocstack empty"}.
12985:
12986: @item too many word lists in search order (@code{also}):
12987: @cindex @code{also}, too many word lists in search order
1.26 crook 12988: @cindex vocstack full, @code{also}
1.1 anton 12989: @code{abort" Vocstack full"}.
12990:
12991: @end table
12992:
12993: @c ***************************************************************
1.65 anton 12994: @node Standard vs Extensions, Model, ANS conformance, Top
12995: @chapter Should I use Gforth extensions?
12996: @cindex Gforth extensions
12997:
12998: As you read through the rest of this manual, you will see documentation
12999: for @i{Standard} words, and documentation for some appealing Gforth
13000: @i{extensions}. You might ask yourself the question: @i{``Should I
13001: restrict myself to the standard, or should I use the extensions?''}
13002:
13003: The answer depends on the goals you have for the program you are working
13004: on:
13005:
13006: @itemize @bullet
13007:
13008: @item Is it just for yourself or do you want to share it with others?
13009:
13010: @item
13011: If you want to share it, do the others all use Gforth?
13012:
13013: @item
13014: If it is just for yourself, do you want to restrict yourself to Gforth?
13015:
13016: @end itemize
13017:
13018: If restricting the program to Gforth is ok, then there is no reason not
13019: to use extensions. It is still a good idea to keep to the standard
13020: where it is easy, in case you want to reuse these parts in another
13021: program that you want to be portable.
13022:
13023: If you want to be able to port the program to other Forth systems, there
13024: are the following points to consider:
13025:
13026: @itemize @bullet
13027:
13028: @item
13029: Most Forth systems that are being maintained support the ANS Forth
13030: standard. So if your program complies with the standard, it will be
13031: portable among many systems.
13032:
13033: @item
13034: A number of the Gforth extensions can be implemented in ANS Forth using
13035: public-domain files provided in the @file{compat/} directory. These are
13036: mentioned in the text in passing. There is no reason not to use these
13037: extensions, your program will still be ANS Forth compliant; just include
13038: the appropriate compat files with your program.
13039:
13040: @item
13041: The tool @file{ans-report.fs} (@pxref{ANS Report}) makes it easy to
13042: analyse your program and determine what non-Standard words it relies
13043: upon. However, it does not check whether you use standard words in a
13044: non-standard way.
13045:
13046: @item
13047: Some techniques are not standardized by ANS Forth, and are hard or
13048: impossible to implement in a standard way, but can be implemented in
13049: most Forth systems easily, and usually in similar ways (e.g., accessing
13050: word headers). Forth has a rich historical precedent for programmers
13051: taking advantage of implementation-dependent features of their tools
13052: (for example, relying on a knowledge of the dictionary
13053: structure). Sometimes these techniques are necessary to extract every
13054: last bit of performance from the hardware, sometimes they are just a
13055: programming shorthand.
13056:
13057: @item
13058: Does using a Gforth extension save more work than the porting this part
13059: to other Forth systems (if any) will cost?
13060:
13061: @item
13062: Is the additional functionality worth the reduction in portability and
13063: the additional porting problems?
13064:
13065: @end itemize
13066:
13067: In order to perform these consideratios, you need to know what's
13068: standard and what's not. This manual generally states if something is
13069: non-standard, but the authoritative source is the standard document.
13070: Appendix A of the Standard (@var{Rationale}) provides a valuable insight
13071: into the thought processes of the technical committee.
13072:
13073: Note also that portability between Forth systems is not the only
13074: portability issue; there is also the issue of portability between
13075: different platforms (processor/OS combinations).
13076:
13077: @c ***************************************************************
13078: @node Model, Integrating Gforth, Standard vs Extensions, Top
1.1 anton 13079: @chapter Model
13080:
13081: This chapter has yet to be written. It will contain information, on
13082: which internal structures you can rely.
13083:
13084: @c ***************************************************************
13085: @node Integrating Gforth, Emacs and Gforth, Model, Top
13086: @chapter Integrating Gforth into C programs
13087:
13088: This is not yet implemented.
13089:
13090: Several people like to use Forth as scripting language for applications
13091: that are otherwise written in C, C++, or some other language.
13092:
13093: The Forth system ATLAST provides facilities for embedding it into
13094: applications; unfortunately it has several disadvantages: most
13095: importantly, it is not based on ANS Forth, and it is apparently dead
13096: (i.e., not developed further and not supported). The facilities
1.21 crook 13097: provided by Gforth in this area are inspired by ATLAST's facilities, so
1.1 anton 13098: making the switch should not be hard.
13099:
13100: We also tried to design the interface such that it can easily be
13101: implemented by other Forth systems, so that we may one day arrive at a
13102: standardized interface. Such a standard interface would allow you to
13103: replace the Forth system without having to rewrite C code.
13104:
13105: You embed the Gforth interpreter by linking with the library
13106: @code{libgforth.a} (give the compiler the option @code{-lgforth}). All
13107: global symbols in this library that belong to the interface, have the
13108: prefix @code{forth_}. (Global symbols that are used internally have the
13109: prefix @code{gforth_}).
13110:
13111: You can include the declarations of Forth types and the functions and
13112: variables of the interface with @code{#include <forth.h>}.
13113:
13114: Types.
13115:
13116: Variables.
13117:
13118: Data and FP Stack pointer. Area sizes.
13119:
13120: functions.
13121:
13122: forth_init(imagefile)
13123: forth_evaluate(string) exceptions?
13124: forth_goto(address) (or forth_execute(xt)?)
13125: forth_continue() (a corountining mechanism)
13126:
13127: Adding primitives.
13128:
13129: No checking.
13130:
13131: Signals?
13132:
13133: Accessing the Stacks
13134:
1.26 crook 13135: @c ******************************************************************
1.1 anton 13136: @node Emacs and Gforth, Image Files, Integrating Gforth, Top
13137: @chapter Emacs and Gforth
13138: @cindex Emacs and Gforth
13139:
13140: @cindex @file{gforth.el}
13141: @cindex @file{forth.el}
13142: @cindex Rydqvist, Goran
13143: @cindex comment editing commands
13144: @cindex @code{\}, editing with Emacs
13145: @cindex debug tracer editing commands
13146: @cindex @code{~~}, removal with Emacs
13147: @cindex Forth mode in Emacs
13148: Gforth comes with @file{gforth.el}, an improved version of
13149: @file{forth.el} by Goran Rydqvist (included in the TILE package). The
1.26 crook 13150: improvements are:
13151:
13152: @itemize @bullet
13153: @item
13154: A better (but still not perfect) handling of indentation.
13155: @item
13156: Comment paragraph filling (@kbd{M-q})
13157: @item
13158: Commenting (@kbd{C-x \}) and uncommenting (@kbd{C-u C-x \}) of regions
13159: @item
13160: Removal of debugging tracers (@kbd{C-x ~}, @pxref{Debugging}).
1.41 anton 13161: @item
13162: Support of the @code{info-lookup} feature for looking up the
13163: documentation of a word.
1.26 crook 13164: @end itemize
13165:
13166: I left the stuff I do not use alone, even though some of it only makes
13167: sense for TILE. To get a description of these features, enter Forth mode
13168: and type @kbd{C-h m}.
1.1 anton 13169:
13170: @cindex source location of error or debugging output in Emacs
13171: @cindex error output, finding the source location in Emacs
13172: @cindex debugging output, finding the source location in Emacs
13173: In addition, Gforth supports Emacs quite well: The source code locations
13174: given in error messages, debugging output (from @code{~~}) and failed
13175: assertion messages are in the right format for Emacs' compilation mode
13176: (@pxref{Compilation, , Running Compilations under Emacs, emacs, Emacs
13177: Manual}) so the source location corresponding to an error or other
13178: message is only a few keystrokes away (@kbd{C-x `} for the next error,
13179: @kbd{C-c C-c} for the error under the cursor).
13180:
13181: @cindex @file{TAGS} file
13182: @cindex @file{etags.fs}
13183: @cindex viewing the source of a word in Emacs
1.43 anton 13184: @cindex @code{require}, placement in files
13185: @cindex @code{include}, placement in files
13186: Also, if you @code{require} @file{etags.fs}, a new @file{TAGS} file will
1.26 crook 13187: be produced (@pxref{Tags, , Tags Tables, emacs, Emacs Manual}) that
1.1 anton 13188: contains the definitions of all words defined afterwards. You can then
13189: find the source for a word using @kbd{M-.}. Note that emacs can use
13190: several tags files at the same time (e.g., one for the Gforth sources
13191: and one for your program, @pxref{Select Tags Table,,Selecting a Tags
13192: Table,emacs, Emacs Manual}). The TAGS file for the preloaded words is
13193: @file{$(datadir)/gforth/$(VERSION)/TAGS} (e.g.,
1.43 anton 13194: @file{/usr/local/share/gforth/0.2.0/TAGS}). To get the best behaviour
13195: with @file{etags.fs}, you should avoid putting definitions both before
13196: and after @code{require} etc., otherwise you will see the same file
13197: visited several times by commands like @code{tags-search}.
1.1 anton 13198:
1.41 anton 13199: @cindex viewing the documentation of a word in Emacs
13200: @cindex context-sensitive help
13201: Moreover, for words documented in this manual, you can look up the
13202: glossary entry quickly by using @kbd{C-h TAB}
13203: (@code{info-lookup-symbol}, see @pxref{Documentation, ,Documentation
13204: Commands, emacs, Emacs Manual}). This feature requires Emacs 20.3 or
1.42 anton 13205: later and does not work for words containing @code{:}.
1.41 anton 13206:
13207:
1.1 anton 13208: @cindex @file{.emacs}
13209: To get all these benefits, add the following lines to your @file{.emacs}
13210: file:
13211:
13212: @example
13213: (autoload 'forth-mode "gforth.el")
13214: (setq auto-mode-alist (cons '("\\.fs\\'" . forth-mode) auto-mode-alist))
13215: @end example
13216:
1.26 crook 13217: @c ******************************************************************
1.1 anton 13218: @node Image Files, Engine, Emacs and Gforth, Top
13219: @chapter Image Files
1.26 crook 13220: @cindex image file
13221: @cindex @file{.fi} files
1.1 anton 13222: @cindex precompiled Forth code
13223: @cindex dictionary in persistent form
13224: @cindex persistent form of dictionary
13225:
13226: An image file is a file containing an image of the Forth dictionary,
13227: i.e., compiled Forth code and data residing in the dictionary. By
13228: convention, we use the extension @code{.fi} for image files.
13229:
13230: @menu
1.18 anton 13231: * Image Licensing Issues:: Distribution terms for images.
13232: * Image File Background:: Why have image files?
1.67 anton 13233: * Non-Relocatable Image Files:: don't always work.
1.18 anton 13234: * Data-Relocatable Image Files:: are better.
1.67 anton 13235: * Fully Relocatable Image Files:: better yet.
1.18 anton 13236: * Stack and Dictionary Sizes:: Setting the default sizes for an image.
1.29 crook 13237: * Running Image Files:: @code{gforth -i @i{file}} or @i{file}.
1.18 anton 13238: * Modifying the Startup Sequence:: and turnkey applications.
1.1 anton 13239: @end menu
13240:
1.18 anton 13241: @node Image Licensing Issues, Image File Background, Image Files, Image Files
13242: @section Image Licensing Issues
13243: @cindex license for images
13244: @cindex image license
13245:
13246: An image created with @code{gforthmi} (@pxref{gforthmi}) or
13247: @code{savesystem} (@pxref{Non-Relocatable Image Files}) includes the
13248: original image; i.e., according to copyright law it is a derived work of
13249: the original image.
13250:
13251: Since Gforth is distributed under the GNU GPL, the newly created image
13252: falls under the GNU GPL, too. In particular, this means that if you
13253: distribute the image, you have to make all of the sources for the image
13254: available, including those you wrote. For details see @ref{License, ,
13255: GNU General Public License (Section 3)}.
13256:
13257: If you create an image with @code{cross} (@pxref{cross.fs}), the image
13258: contains only code compiled from the sources you gave it; if none of
13259: these sources is under the GPL, the terms discussed above do not apply
13260: to the image. However, if your image needs an engine (a gforth binary)
13261: that is under the GPL, you should make sure that you distribute both in
13262: a way that is at most a @emph{mere aggregation}, if you don't want the
13263: terms of the GPL to apply to the image.
13264:
13265: @node Image File Background, Non-Relocatable Image Files, Image Licensing Issues, Image Files
1.1 anton 13266: @section Image File Background
13267: @cindex image file background
13268:
13269: Our Forth system consists not only of primitives, but also of
13270: definitions written in Forth. Since the Forth compiler itself belongs to
13271: those definitions, it is not possible to start the system with the
13272: primitives and the Forth source alone. Therefore we provide the Forth
1.26 crook 13273: code as an image file in nearly executable form. When Gforth starts up,
13274: a C routine loads the image file into memory, optionally relocates the
13275: addresses, then sets up the memory (stacks etc.) according to
13276: information in the image file, and (finally) starts executing Forth
13277: code.
1.1 anton 13278:
13279: The image file variants represent different compromises between the
13280: goals of making it easy to generate image files and making them
13281: portable.
13282:
13283: @cindex relocation at run-time
1.26 crook 13284: Win32Forth 3.4 and Mitch Bradley's @code{cforth} use relocation at
1.1 anton 13285: run-time. This avoids many of the complications discussed below (image
13286: files are data relocatable without further ado), but costs performance
13287: (one addition per memory access).
13288:
13289: @cindex relocation at load-time
1.26 crook 13290: By contrast, the Gforth loader performs relocation at image load time. The
13291: loader also has to replace tokens that represent primitive calls with the
1.1 anton 13292: appropriate code-field addresses (or code addresses in the case of
13293: direct threading).
13294:
13295: There are three kinds of image files, with different degrees of
13296: relocatability: non-relocatable, data-relocatable, and fully relocatable
13297: image files.
13298:
13299: @cindex image file loader
13300: @cindex relocating loader
13301: @cindex loader for image files
13302: These image file variants have several restrictions in common; they are
13303: caused by the design of the image file loader:
13304:
13305: @itemize @bullet
13306: @item
13307: There is only one segment; in particular, this means, that an image file
13308: cannot represent @code{ALLOCATE}d memory chunks (and pointers to
1.26 crook 13309: them). The contents of the stacks are not represented, either.
1.1 anton 13310:
13311: @item
13312: The only kinds of relocation supported are: adding the same offset to
13313: all cells that represent data addresses; and replacing special tokens
13314: with code addresses or with pieces of machine code.
13315:
13316: If any complex computations involving addresses are performed, the
13317: results cannot be represented in the image file. Several applications that
13318: use such computations come to mind:
13319: @itemize @minus
13320: @item
13321: Hashing addresses (or data structures which contain addresses) for table
13322: lookup. If you use Gforth's @code{table}s or @code{wordlist}s for this
13323: purpose, you will have no problem, because the hash tables are
13324: recomputed automatically when the system is started. If you use your own
13325: hash tables, you will have to do something similar.
13326:
13327: @item
13328: There's a cute implementation of doubly-linked lists that uses
13329: @code{XOR}ed addresses. You could represent such lists as singly-linked
13330: in the image file, and restore the doubly-linked representation on
13331: startup.@footnote{In my opinion, though, you should think thrice before
13332: using a doubly-linked list (whatever implementation).}
13333:
13334: @item
13335: The code addresses of run-time routines like @code{docol:} cannot be
13336: represented in the image file (because their tokens would be replaced by
13337: machine code in direct threaded implementations). As a workaround,
13338: compute these addresses at run-time with @code{>code-address} from the
13339: executions tokens of appropriate words (see the definitions of
13340: @code{docol:} and friends in @file{kernel.fs}).
13341:
13342: @item
13343: On many architectures addresses are represented in machine code in some
13344: shifted or mangled form. You cannot put @code{CODE} words that contain
13345: absolute addresses in this form in a relocatable image file. Workarounds
13346: are representing the address in some relative form (e.g., relative to
13347: the CFA, which is present in some register), or loading the address from
13348: a place where it is stored in a non-mangled form.
13349: @end itemize
13350: @end itemize
13351:
13352: @node Non-Relocatable Image Files, Data-Relocatable Image Files, Image File Background, Image Files
13353: @section Non-Relocatable Image Files
13354: @cindex non-relocatable image files
1.26 crook 13355: @cindex image file, non-relocatable
1.1 anton 13356:
13357: These files are simple memory dumps of the dictionary. They are specific
13358: to the executable (i.e., @file{gforth} file) they were created
13359: with. What's worse, they are specific to the place on which the
13360: dictionary resided when the image was created. Now, there is no
13361: guarantee that the dictionary will reside at the same place the next
13362: time you start Gforth, so there's no guarantee that a non-relocatable
13363: image will work the next time (Gforth will complain instead of crashing,
13364: though).
13365:
13366: You can create a non-relocatable image file with
13367:
1.44 crook 13368:
1.1 anton 13369: doc-savesystem
13370:
1.44 crook 13371:
1.1 anton 13372: @node Data-Relocatable Image Files, Fully Relocatable Image Files, Non-Relocatable Image Files, Image Files
13373: @section Data-Relocatable Image Files
13374: @cindex data-relocatable image files
1.26 crook 13375: @cindex image file, data-relocatable
1.1 anton 13376:
13377: These files contain relocatable data addresses, but fixed code addresses
13378: (instead of tokens). They are specific to the executable (i.e.,
13379: @file{gforth} file) they were created with. For direct threading on some
13380: architectures (e.g., the i386), data-relocatable images do not work. You
13381: get a data-relocatable image, if you use @file{gforthmi} with a
13382: Gforth binary that is not doubly indirect threaded (@pxref{Fully
13383: Relocatable Image Files}).
13384:
13385: @node Fully Relocatable Image Files, Stack and Dictionary Sizes, Data-Relocatable Image Files, Image Files
13386: @section Fully Relocatable Image Files
13387: @cindex fully relocatable image files
1.26 crook 13388: @cindex image file, fully relocatable
1.1 anton 13389:
13390: @cindex @file{kern*.fi}, relocatability
13391: @cindex @file{gforth.fi}, relocatability
13392: These image files have relocatable data addresses, and tokens for code
13393: addresses. They can be used with different binaries (e.g., with and
13394: without debugging) on the same machine, and even across machines with
13395: the same data formats (byte order, cell size, floating point
13396: format). However, they are usually specific to the version of Gforth
13397: they were created with. The files @file{gforth.fi} and @file{kernl*.fi}
13398: are fully relocatable.
13399:
13400: There are two ways to create a fully relocatable image file:
13401:
13402: @menu
1.29 crook 13403: * gforthmi:: The normal way
1.1 anton 13404: * cross.fs:: The hard way
13405: @end menu
13406:
13407: @node gforthmi, cross.fs, Fully Relocatable Image Files, Fully Relocatable Image Files
13408: @subsection @file{gforthmi}
13409: @cindex @file{comp-i.fs}
13410: @cindex @file{gforthmi}
13411:
13412: You will usually use @file{gforthmi}. If you want to create an
1.29 crook 13413: image @i{file} that contains everything you would load by invoking
13414: Gforth with @code{gforth @i{options}}, you simply say:
1.1 anton 13415: @example
1.29 crook 13416: gforthmi @i{file} @i{options}
1.1 anton 13417: @end example
13418:
13419: E.g., if you want to create an image @file{asm.fi} that has the file
13420: @file{asm.fs} loaded in addition to the usual stuff, you could do it
13421: like this:
13422:
13423: @example
13424: gforthmi asm.fi asm.fs
13425: @end example
13426:
1.27 crook 13427: @file{gforthmi} is implemented as a sh script and works like this: It
13428: produces two non-relocatable images for different addresses and then
13429: compares them. Its output reflects this: first you see the output (if
1.62 crook 13430: any) of the two Gforth invocations that produce the non-relocatable image
1.27 crook 13431: files, then you see the output of the comparing program: It displays the
13432: offset used for data addresses and the offset used for code addresses;
1.1 anton 13433: moreover, for each cell that cannot be represented correctly in the
1.44 crook 13434: image files, it displays a line like this:
1.1 anton 13435:
13436: @example
13437: 78DC BFFFFA50 BFFFFA40
13438: @end example
13439:
13440: This means that at offset $78dc from @code{forthstart}, one input image
13441: contains $bffffa50, and the other contains $bffffa40. Since these cells
13442: cannot be represented correctly in the output image, you should examine
13443: these places in the dictionary and verify that these cells are dead
13444: (i.e., not read before they are written).
1.39 anton 13445:
13446: @cindex --application, @code{gforthmi} option
13447: If you insert the option @code{--application} in front of the image file
13448: name, you will get an image that uses the @code{--appl-image} option
13449: instead of the @code{--image-file} option (@pxref{Invoking
13450: Gforth}). When you execute such an image on Unix (by typing the image
13451: name as command), the Gforth engine will pass all options to the image
13452: instead of trying to interpret them as engine options.
1.1 anton 13453:
1.27 crook 13454: If you type @file{gforthmi} with no arguments, it prints some usage
13455: instructions.
13456:
1.1 anton 13457: @cindex @code{savesystem} during @file{gforthmi}
13458: @cindex @code{bye} during @file{gforthmi}
13459: @cindex doubly indirect threaded code
1.44 crook 13460: @cindex environment variables
13461: @cindex @code{GFORTHD} -- environment variable
13462: @cindex @code{GFORTH} -- environment variable
1.1 anton 13463: @cindex @code{gforth-ditc}
1.29 crook 13464: There are a few wrinkles: After processing the passed @i{options}, the
1.1 anton 13465: words @code{savesystem} and @code{bye} must be visible. A special doubly
13466: indirect threaded version of the @file{gforth} executable is used for
1.62 crook 13467: creating the non-relocatable images; you can pass the exact filename of
1.1 anton 13468: this executable through the environment variable @code{GFORTHD}
13469: (default: @file{gforth-ditc}); if you pass a version that is not doubly
13470: indirect threaded, you will not get a fully relocatable image, but a
1.27 crook 13471: data-relocatable image (because there is no code address offset). The
13472: normal @file{gforth} executable is used for creating the relocatable
13473: image; you can pass the exact filename of this executable through the
13474: environment variable @code{GFORTH}.
1.1 anton 13475:
13476: @node cross.fs, , gforthmi, Fully Relocatable Image Files
13477: @subsection @file{cross.fs}
13478: @cindex @file{cross.fs}
13479: @cindex cross-compiler
13480: @cindex metacompiler
1.47 crook 13481: @cindex target compiler
1.1 anton 13482:
13483: You can also use @code{cross}, a batch compiler that accepts a Forth-like
1.47 crook 13484: programming language (@pxref{Cross Compiler}).
1.1 anton 13485:
1.47 crook 13486: @code{cross} allows you to create image files for machines with
1.1 anton 13487: different data sizes and data formats than the one used for generating
13488: the image file. You can also use it to create an application image that
13489: does not contain a Forth compiler. These features are bought with
13490: restrictions and inconveniences in programming. E.g., addresses have to
13491: be stored in memory with special words (@code{A!}, @code{A,}, etc.) in
13492: order to make the code relocatable.
13493:
13494:
13495: @node Stack and Dictionary Sizes, Running Image Files, Fully Relocatable Image Files, Image Files
13496: @section Stack and Dictionary Sizes
13497: @cindex image file, stack and dictionary sizes
13498: @cindex dictionary size default
13499: @cindex stack size default
13500:
13501: If you invoke Gforth with a command line flag for the size
13502: (@pxref{Invoking Gforth}), the size you specify is stored in the
13503: dictionary. If you save the dictionary with @code{savesystem} or create
13504: an image with @file{gforthmi}, this size will become the default
13505: for the resulting image file. E.g., the following will create a
1.21 crook 13506: fully relocatable version of @file{gforth.fi} with a 1MB dictionary:
1.1 anton 13507:
13508: @example
13509: gforthmi gforth.fi -m 1M
13510: @end example
13511:
13512: In other words, if you want to set the default size for the dictionary
13513: and the stacks of an image, just invoke @file{gforthmi} with the
13514: appropriate options when creating the image.
13515:
13516: @cindex stack size, cache-friendly
13517: Note: For cache-friendly behaviour (i.e., good performance), you should
13518: make the sizes of the stacks modulo, say, 2K, somewhat different. E.g.,
13519: the default stack sizes are: data: 16k (mod 2k=0); fp: 15.5k (mod
13520: 2k=1.5k); return: 15k(mod 2k=1k); locals: 14.5k (mod 2k=0.5k).
13521:
13522: @node Running Image Files, Modifying the Startup Sequence, Stack and Dictionary Sizes, Image Files
13523: @section Running Image Files
13524: @cindex running image files
13525: @cindex invoking image files
13526: @cindex image file invocation
13527:
13528: @cindex -i, invoke image file
13529: @cindex --image file, invoke image file
1.29 crook 13530: You can invoke Gforth with an image file @i{image} instead of the
1.1 anton 13531: default @file{gforth.fi} with the @code{-i} flag (@pxref{Invoking Gforth}):
13532: @example
1.29 crook 13533: gforth -i @i{image}
1.1 anton 13534: @end example
13535:
13536: @cindex executable image file
1.26 crook 13537: @cindex image file, executable
1.1 anton 13538: If your operating system supports starting scripts with a line of the
13539: form @code{#! ...}, you just have to type the image file name to start
13540: Gforth with this image file (note that the file extension @code{.fi} is
1.29 crook 13541: just a convention). I.e., to run Gforth with the image file @i{image},
13542: you can just type @i{image} instead of @code{gforth -i @i{image}}.
1.27 crook 13543: This works because every @code{.fi} file starts with a line of this
13544: format:
13545:
13546: @example
13547: #! /usr/local/bin/gforth-0.4.0 -i
13548: @end example
13549:
13550: The file and pathname for the Gforth engine specified on this line is
13551: the specific Gforth executable that it was built against; i.e. the value
13552: of the environment variable @code{GFORTH} at the time that
13553: @file{gforthmi} was executed.
1.1 anton 13554:
1.27 crook 13555: You can make use of the same shell capability to make a Forth source
13556: file into an executable. For example, if you place this text in a file:
1.26 crook 13557:
13558: @example
13559: #! /usr/local/bin/gforth
13560:
13561: ." Hello, world" CR
13562: bye
13563: @end example
13564:
13565: @noindent
1.27 crook 13566: and then make the file executable (chmod +x in Unix), you can run it
1.26 crook 13567: directly from the command line. The sequence @code{#!} is used in two
13568: ways; firstly, it is recognised as a ``magic sequence'' by the operating
1.29 crook 13569: system@footnote{The Unix kernel actually recognises two types of files:
13570: executable files and files of data, where the data is processed by an
13571: interpreter that is specified on the ``interpreter line'' -- the first
13572: line of the file, starting with the sequence #!. There may be a small
13573: limit (e.g., 32) on the number of characters that may be specified on
13574: the interpreter line.} secondly it is treated as a comment character by
13575: Gforth. Because of the second usage, a space is required between
13576: @code{#!} and the path to the executable.
1.27 crook 13577:
13578: The disadvantage of this latter technique, compared with using
13579: @file{gforthmi}, is that it is slower; the Forth source code is compiled
13580: on-the-fly, each time the program is invoked.
13581:
1.26 crook 13582:
1.1 anton 13583: doc-#!
13584:
1.44 crook 13585:
1.1 anton 13586: @node Modifying the Startup Sequence, , Running Image Files, Image Files
13587: @section Modifying the Startup Sequence
13588: @cindex startup sequence for image file
13589: @cindex image file initialization sequence
13590: @cindex initialization sequence of image file
13591:
13592: You can add your own initialization to the startup sequence through the
1.26 crook 13593: deferred word @code{'cold}. @code{'cold} is invoked just before the
13594: image-specific command line processing (by default, loading files and
13595: evaluating (@code{-e}) strings) starts.
1.1 anton 13596:
13597: A sequence for adding your initialization usually looks like this:
13598:
13599: @example
13600: :noname
13601: Defers 'cold \ do other initialization stuff (e.g., rehashing wordlists)
13602: ... \ your stuff
13603: ; IS 'cold
13604: @end example
13605:
13606: @cindex turnkey image files
1.26 crook 13607: @cindex image file, turnkey applications
1.1 anton 13608: You can make a turnkey image by letting @code{'cold} execute a word
13609: (your turnkey application) that never returns; instead, it exits Gforth
13610: via @code{bye} or @code{throw}.
13611:
13612: @cindex command-line arguments, access
13613: @cindex arguments on the command line, access
13614: You can access the (image-specific) command-line arguments through the
1.26 crook 13615: variables @code{argc} and @code{argv}. @code{arg} provides convenient
1.1 anton 13616: access to @code{argv}.
13617:
1.26 crook 13618: If @code{'cold} exits normally, Gforth processes the command-line
13619: arguments as files to be loaded and strings to be evaluated. Therefore,
13620: @code{'cold} should remove the arguments it has used in this case.
13621:
1.44 crook 13622:
13623:
1.26 crook 13624: doc-'cold
1.1 anton 13625: doc-argc
13626: doc-argv
13627: doc-arg
13628:
13629:
1.44 crook 13630:
1.1 anton 13631: @c ******************************************************************
1.13 pazsan 13632: @node Engine, Binding to System Library, Image Files, Top
1.1 anton 13633: @chapter Engine
13634: @cindex engine
13635: @cindex virtual machine
13636:
1.26 crook 13637: Reading this chapter is not necessary for programming with Gforth. It
1.1 anton 13638: may be helpful for finding your way in the Gforth sources.
13639:
1.66 anton 13640: The ideas in this section have also been published in Bernd Paysan,
13641: @cite{ANS fig/GNU/??? Forth} (in German), Forth-Tagung '93 and M. Anton
13642: Ertl, @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl93.ps.Z, A
13643: Portable Forth Engine}}, EuroForth '93.
1.1 anton 13644:
13645: @menu
13646: * Portability::
13647: * Threading::
13648: * Primitives::
13649: * Performance::
13650: @end menu
13651:
13652: @node Portability, Threading, Engine, Engine
13653: @section Portability
13654: @cindex engine portability
13655:
1.26 crook 13656: An important goal of the Gforth Project is availability across a wide
13657: range of personal machines. fig-Forth, and, to a lesser extent, F83,
13658: achieved this goal by manually coding the engine in assembly language
13659: for several then-popular processors. This approach is very
13660: labor-intensive and the results are short-lived due to progress in
13661: computer architecture.
1.1 anton 13662:
13663: @cindex C, using C for the engine
13664: Others have avoided this problem by coding in C, e.g., Mitch Bradley
13665: (cforth), Mikael Patel (TILE) and Dirk Zoller (pfe). This approach is
13666: particularly popular for UNIX-based Forths due to the large variety of
13667: architectures of UNIX machines. Unfortunately an implementation in C
13668: does not mix well with the goals of efficiency and with using
13669: traditional techniques: Indirect or direct threading cannot be expressed
13670: in C, and switch threading, the fastest technique available in C, is
13671: significantly slower. Another problem with C is that it is very
13672: cumbersome to express double integer arithmetic.
13673:
13674: @cindex GNU C for the engine
13675: @cindex long long
13676: Fortunately, there is a portable language that does not have these
13677: limitations: GNU C, the version of C processed by the GNU C compiler
13678: (@pxref{C Extensions, , Extensions to the C Language Family, gcc.info,
13679: GNU C Manual}). Its labels as values feature (@pxref{Labels as Values, ,
13680: Labels as Values, gcc.info, GNU C Manual}) makes direct and indirect
13681: threading possible, its @code{long long} type (@pxref{Long Long, ,
13682: Double-Word Integers, gcc.info, GNU C Manual}) corresponds to Forth's
13683: double numbers@footnote{Unfortunately, long longs are not implemented
13684: properly on all machines (e.g., on alpha-osf1, long longs are only 64
13685: bits, the same size as longs (and pointers), but they should be twice as
1.4 anton 13686: long according to @pxref{Long Long, , Double-Word Integers, gcc.info, GNU
1.1 anton 13687: C Manual}). So, we had to implement doubles in C after all. Still, on
13688: most machines we can use long longs and achieve better performance than
13689: with the emulation package.}. GNU C is available for free on all
13690: important (and many unimportant) UNIX machines, VMS, 80386s running
13691: MS-DOS, the Amiga, and the Atari ST, so a Forth written in GNU C can run
13692: on all these machines.
13693:
13694: Writing in a portable language has the reputation of producing code that
13695: is slower than assembly. For our Forth engine we repeatedly looked at
13696: the code produced by the compiler and eliminated most compiler-induced
13697: inefficiencies by appropriate changes in the source code.
13698:
13699: @cindex explicit register declarations
13700: @cindex --enable-force-reg, configuration flag
13701: @cindex -DFORCE_REG
13702: However, register allocation cannot be portably influenced by the
13703: programmer, leading to some inefficiencies on register-starved
13704: machines. We use explicit register declarations (@pxref{Explicit Reg
13705: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) to
13706: improve the speed on some machines. They are turned on by using the
13707: configuration flag @code{--enable-force-reg} (@code{gcc} switch
13708: @code{-DFORCE_REG}). Unfortunately, this feature not only depends on the
13709: machine, but also on the compiler version: On some machines some
13710: compiler versions produce incorrect code when certain explicit register
13711: declarations are used. So by default @code{-DFORCE_REG} is not used.
13712:
13713: @node Threading, Primitives, Portability, Engine
13714: @section Threading
13715: @cindex inner interpreter implementation
13716: @cindex threaded code implementation
13717:
13718: @cindex labels as values
13719: GNU C's labels as values extension (available since @code{gcc-2.0},
13720: @pxref{Labels as Values, , Labels as Values, gcc.info, GNU C Manual})
1.29 crook 13721: makes it possible to take the address of @i{label} by writing
13722: @code{&&@i{label}}. This address can then be used in a statement like
13723: @code{goto *@i{address}}. I.e., @code{goto *&&x} is the same as
1.1 anton 13724: @code{goto x}.
13725:
1.26 crook 13726: @cindex @code{NEXT}, indirect threaded
1.1 anton 13727: @cindex indirect threaded inner interpreter
13728: @cindex inner interpreter, indirect threaded
1.26 crook 13729: With this feature an indirect threaded @code{NEXT} looks like:
1.1 anton 13730: @example
13731: cfa = *ip++;
13732: ca = *cfa;
13733: goto *ca;
13734: @end example
13735: @cindex instruction pointer
13736: For those unfamiliar with the names: @code{ip} is the Forth instruction
13737: pointer; the @code{cfa} (code-field address) corresponds to ANS Forths
13738: execution token and points to the code field of the next word to be
13739: executed; The @code{ca} (code address) fetched from there points to some
13740: executable code, e.g., a primitive or the colon definition handler
13741: @code{docol}.
13742:
1.26 crook 13743: @cindex @code{NEXT}, direct threaded
1.1 anton 13744: @cindex direct threaded inner interpreter
13745: @cindex inner interpreter, direct threaded
13746: Direct threading is even simpler:
13747: @example
13748: ca = *ip++;
13749: goto *ca;
13750: @end example
13751:
13752: Of course we have packaged the whole thing neatly in macros called
1.26 crook 13753: @code{NEXT} and @code{NEXT1} (the part of @code{NEXT} after fetching the cfa).
1.1 anton 13754:
13755: @menu
13756: * Scheduling::
13757: * Direct or Indirect Threaded?::
13758: * DOES>::
13759: @end menu
13760:
13761: @node Scheduling, Direct or Indirect Threaded?, Threading, Threading
13762: @subsection Scheduling
13763: @cindex inner interpreter optimization
13764:
13765: There is a little complication: Pipelined and superscalar processors,
13766: i.e., RISC and some modern CISC machines can process independent
13767: instructions while waiting for the results of an instruction. The
13768: compiler usually reorders (schedules) the instructions in a way that
13769: achieves good usage of these delay slots. However, on our first tries
13770: the compiler did not do well on scheduling primitives. E.g., for
13771: @code{+} implemented as
13772: @example
13773: n=sp[0]+sp[1];
13774: sp++;
13775: sp[0]=n;
13776: NEXT;
13777: @end example
1.26 crook 13778: the @code{NEXT} comes strictly after the other code, i.e., there is nearly no
1.1 anton 13779: scheduling. After a little thought the problem becomes clear: The
1.21 crook 13780: compiler cannot know that @code{sp} and @code{ip} point to different
13781: addresses (and the version of @code{gcc} we used would not know it even
13782: if it was possible), so it could not move the load of the cfa above the
13783: store to the TOS. Indeed the pointers could be the same, if code on or
13784: very near the top of stack were executed. In the interest of speed we
13785: chose to forbid this probably unused ``feature'' and helped the compiler
1.26 crook 13786: in scheduling: @code{NEXT} is divided into the loading part (@code{NEXT_P1})
1.21 crook 13787: and the goto part (@code{NEXT_P2}). @code{+} now looks like:
1.1 anton 13788: @example
13789: n=sp[0]+sp[1];
13790: sp++;
13791: NEXT_P1;
13792: sp[0]=n;
13793: NEXT_P2;
13794: @end example
13795: This can be scheduled optimally by the compiler.
13796:
13797: This division can be turned off with the switch @code{-DCISC_NEXT}. This
13798: switch is on by default on machines that do not profit from scheduling
13799: (e.g., the 80386), in order to preserve registers.
13800:
13801: @node Direct or Indirect Threaded?, DOES>, Scheduling, Threading
13802: @subsection Direct or Indirect Threaded?
13803: @cindex threading, direct or indirect?
13804:
13805: @cindex -DDIRECT_THREADED
13806: Both! After packaging the nasty details in macro definitions we
13807: realized that we could switch between direct and indirect threading by
13808: simply setting a compilation flag (@code{-DDIRECT_THREADED}) and
13809: defining a few machine-specific macros for the direct-threading case.
13810: On the Forth level we also offer access words that hide the
13811: differences between the threading methods (@pxref{Threading Words}).
13812:
13813: Indirect threading is implemented completely machine-independently.
13814: Direct threading needs routines for creating jumps to the executable
1.21 crook 13815: code (e.g. to @code{docol} or @code{dodoes}). These routines are inherently
13816: machine-dependent, but they do not amount to many source lines. Therefore,
13817: even porting direct threading to a new machine requires little effort.
1.1 anton 13818:
13819: @cindex --enable-indirect-threaded, configuration flag
13820: @cindex --enable-direct-threaded, configuration flag
13821: The default threading method is machine-dependent. You can enforce a
13822: specific threading method when building Gforth with the configuration
13823: flag @code{--enable-direct-threaded} or
13824: @code{--enable-indirect-threaded}. Note that direct threading is not
13825: supported on all machines.
13826:
13827: @node DOES>, , Direct or Indirect Threaded?, Threading
13828: @subsection DOES>
13829: @cindex @code{DOES>} implementation
13830:
1.26 crook 13831: @cindex @code{dodoes} routine
13832: @cindex @code{DOES>}-code
1.1 anton 13833: One of the most complex parts of a Forth engine is @code{dodoes}, i.e.,
13834: the chunk of code executed by every word defined by a
13835: @code{CREATE}...@code{DOES>} pair. The main problem here is: How to find
13836: the Forth code to be executed, i.e. the code after the
1.26 crook 13837: @code{DOES>} (the @code{DOES>}-code)? There are two solutions:
1.1 anton 13838:
1.21 crook 13839: In fig-Forth the code field points directly to the @code{dodoes} and the
1.45 crook 13840: @code{DOES>}-code address is stored in the cell after the code address (i.e. at
1.29 crook 13841: @code{@i{CFA} cell+}). It may seem that this solution is illegal in
1.1 anton 13842: the Forth-79 and all later standards, because in fig-Forth this address
13843: lies in the body (which is illegal in these standards). However, by
13844: making the code field larger for all words this solution becomes legal
13845: again. We use this approach for the indirect threaded version and for
13846: direct threading on some machines. Leaving a cell unused in most words
13847: is a bit wasteful, but on the machines we are targeting this is hardly a
13848: problem. The other reason for having a code field size of two cells is
13849: to avoid having different image files for direct and indirect threaded
13850: systems (direct threaded systems require two-cell code fields on many
13851: machines).
13852:
1.26 crook 13853: @cindex @code{DOES>}-handler
1.1 anton 13854: The other approach is that the code field points or jumps to the cell
1.26 crook 13855: after @code{DOES>}. In this variant there is a jump to @code{dodoes} at
13856: this address (the @code{DOES>}-handler). @code{dodoes} can then get the
13857: @code{DOES>}-code address by computing the code address, i.e., the address of
1.45 crook 13858: the jump to @code{dodoes}, and add the length of that jump field. A variant of
1.1 anton 13859: this is to have a call to @code{dodoes} after the @code{DOES>}; then the
13860: return address (which can be found in the return register on RISCs) is
1.26 crook 13861: the @code{DOES>}-code address. Since the two cells available in the code field
1.1 anton 13862: are used up by the jump to the code address in direct threading on many
13863: architectures, we use this approach for direct threading on these
13864: architectures. We did not want to add another cell to the code field.
13865:
13866: @node Primitives, Performance, Threading, Engine
13867: @section Primitives
13868: @cindex primitives, implementation
13869: @cindex virtual machine instructions, implementation
13870:
13871: @menu
13872: * Automatic Generation::
13873: * TOS Optimization::
13874: * Produced code::
13875: @end menu
13876:
13877: @node Automatic Generation, TOS Optimization, Primitives, Primitives
13878: @subsection Automatic Generation
13879: @cindex primitives, automatic generation
13880:
13881: @cindex @file{prims2x.fs}
13882: Since the primitives are implemented in a portable language, there is no
13883: longer any need to minimize the number of primitives. On the contrary,
13884: having many primitives has an advantage: speed. In order to reduce the
13885: number of errors in primitives and to make programming them easier, we
13886: provide a tool, the primitive generator (@file{prims2x.fs}), that
13887: automatically generates most (and sometimes all) of the C code for a
13888: primitive from the stack effect notation. The source for a primitive
13889: has the following form:
13890:
13891: @cindex primitive source format
13892: @format
1.58 anton 13893: @i{Forth-name} ( @i{stack-effect} ) @i{category} [@i{pronounc.}]
1.29 crook 13894: [@code{""}@i{glossary entry}@code{""}]
13895: @i{C code}
1.1 anton 13896: [@code{:}
1.29 crook 13897: @i{Forth code}]
1.1 anton 13898: @end format
13899:
13900: The items in brackets are optional. The category and glossary fields
13901: are there for generating the documentation, the Forth code is there
13902: for manual implementations on machines without GNU C. E.g., the source
13903: for the primitive @code{+} is:
13904: @example
1.58 anton 13905: + ( n1 n2 -- n ) core plus
1.1 anton 13906: n = n1+n2;
13907: @end example
13908:
13909: This looks like a specification, but in fact @code{n = n1+n2} is C
13910: code. Our primitive generation tool extracts a lot of information from
13911: the stack effect notations@footnote{We use a one-stack notation, even
13912: though we have separate data and floating-point stacks; The separate
13913: notation can be generated easily from the unified notation.}: The number
13914: of items popped from and pushed on the stack, their type, and by what
13915: name they are referred to in the C code. It then generates a C code
13916: prelude and postlude for each primitive. The final C code for @code{+}
13917: looks like this:
13918:
13919: @example
1.46 pazsan 13920: I_plus: /* + ( n1 n2 -- n ) */ /* label, stack effect */
1.1 anton 13921: /* */ /* documentation */
13922: @{
13923: DEF_CA /* definition of variable ca (indirect threading) */
13924: Cell n1; /* definitions of variables */
13925: Cell n2;
13926: Cell n;
13927: n1 = (Cell) sp[1]; /* input */
13928: n2 = (Cell) TOS;
13929: sp += 1; /* stack adjustment */
13930: NAME("+") /* debugging output (with -DDEBUG) */
13931: @{
13932: n = n1+n2; /* C code taken from the source */
13933: @}
13934: NEXT_P1; /* NEXT part 1 */
13935: TOS = (Cell)n; /* output */
13936: NEXT_P2; /* NEXT part 2 */
13937: @}
13938: @end example
13939:
13940: This looks long and inefficient, but the GNU C compiler optimizes quite
13941: well and produces optimal code for @code{+} on, e.g., the R3000 and the
13942: HP RISC machines: Defining the @code{n}s does not produce any code, and
13943: using them as intermediate storage also adds no cost.
13944:
1.26 crook 13945: There are also other optimizations that are not illustrated by this
13946: example: assignments between simple variables are usually for free (copy
1.1 anton 13947: propagation). If one of the stack items is not used by the primitive
13948: (e.g. in @code{drop}), the compiler eliminates the load from the stack
13949: (dead code elimination). On the other hand, there are some things that
13950: the compiler does not do, therefore they are performed by
13951: @file{prims2x.fs}: The compiler does not optimize code away that stores
13952: a stack item to the place where it just came from (e.g., @code{over}).
13953:
13954: While programming a primitive is usually easy, there are a few cases
13955: where the programmer has to take the actions of the generator into
13956: account, most notably @code{?dup}, but also words that do not (always)
1.26 crook 13957: fall through to @code{NEXT}.
1.1 anton 13958:
13959: @node TOS Optimization, Produced code, Automatic Generation, Primitives
13960: @subsection TOS Optimization
13961: @cindex TOS optimization for primitives
13962: @cindex primitives, keeping the TOS in a register
13963:
13964: An important optimization for stack machine emulators, e.g., Forth
13965: engines, is keeping one or more of the top stack items in
1.29 crook 13966: registers. If a word has the stack effect @i{in1}...@i{inx} @code{--}
13967: @i{out1}...@i{outy}, keeping the top @i{n} items in registers
1.1 anton 13968: @itemize @bullet
13969: @item
1.29 crook 13970: is better than keeping @i{n-1} items, if @i{x>=n} and @i{y>=n},
1.1 anton 13971: due to fewer loads from and stores to the stack.
1.29 crook 13972: @item is slower than keeping @i{n-1} items, if @i{x<>y} and @i{x<n} and
13973: @i{y<n}, due to additional moves between registers.
1.1 anton 13974: @end itemize
13975:
13976: @cindex -DUSE_TOS
13977: @cindex -DUSE_NO_TOS
13978: In particular, keeping one item in a register is never a disadvantage,
13979: if there are enough registers. Keeping two items in registers is a
13980: disadvantage for frequent words like @code{?branch}, constants,
13981: variables, literals and @code{i}. Therefore our generator only produces
13982: code that keeps zero or one items in registers. The generated C code
13983: covers both cases; the selection between these alternatives is made at
13984: C-compile time using the switch @code{-DUSE_TOS}. @code{TOS} in the C
13985: code for @code{+} is just a simple variable name in the one-item case,
13986: otherwise it is a macro that expands into @code{sp[0]}. Note that the
13987: GNU C compiler tries to keep simple variables like @code{TOS} in
13988: registers, and it usually succeeds, if there are enough registers.
13989:
13990: @cindex -DUSE_FTOS
13991: @cindex -DUSE_NO_FTOS
13992: The primitive generator performs the TOS optimization for the
13993: floating-point stack, too (@code{-DUSE_FTOS}). For floating-point
13994: operations the benefit of this optimization is even larger:
13995: floating-point operations take quite long on most processors, but can be
13996: performed in parallel with other operations as long as their results are
13997: not used. If the FP-TOS is kept in a register, this works. If
13998: it is kept on the stack, i.e., in memory, the store into memory has to
13999: wait for the result of the floating-point operation, lengthening the
14000: execution time of the primitive considerably.
14001:
14002: The TOS optimization makes the automatic generation of primitives a
14003: bit more complicated. Just replacing all occurrences of @code{sp[0]} by
14004: @code{TOS} is not sufficient. There are some special cases to
14005: consider:
14006: @itemize @bullet
14007: @item In the case of @code{dup ( w -- w w )} the generator must not
14008: eliminate the store to the original location of the item on the stack,
14009: if the TOS optimization is turned on.
14010: @item Primitives with stack effects of the form @code{--}
1.29 crook 14011: @i{out1}...@i{outy} must store the TOS to the stack at the start.
14012: Likewise, primitives with the stack effect @i{in1}...@i{inx} @code{--}
1.1 anton 14013: must load the TOS from the stack at the end. But for the null stack
14014: effect @code{--} no stores or loads should be generated.
14015: @end itemize
14016:
14017: @node Produced code, , TOS Optimization, Primitives
14018: @subsection Produced code
14019: @cindex primitives, assembly code listing
14020:
14021: @cindex @file{engine.s}
14022: To see what assembly code is produced for the primitives on your machine
14023: with your compiler and your flag settings, type @code{make engine.s} and
14024: look at the resulting file @file{engine.s}.
14025:
14026: @node Performance, , Primitives, Engine
14027: @section Performance
14028: @cindex performance of some Forth interpreters
14029: @cindex engine performance
14030: @cindex benchmarking Forth systems
14031: @cindex Gforth performance
14032:
14033: On RISCs the Gforth engine is very close to optimal; i.e., it is usually
14034: impossible to write a significantly faster engine.
14035:
14036: On register-starved machines like the 386 architecture processors
14037: improvements are possible, because @code{gcc} does not utilize the
14038: registers as well as a human, even with explicit register declarations;
14039: e.g., Bernd Beuster wrote a Forth system fragment in assembly language
14040: and hand-tuned it for the 486; this system is 1.19 times faster on the
14041: Sieve benchmark on a 486DX2/66 than Gforth compiled with
1.40 anton 14042: @code{gcc-2.6.3} with @code{-DFORCE_REG}. The situation has improved
14043: with gcc-2.95 and gforth-0.4.9; now the most important virtual machine
14044: registers fit in real registers (and we can even afford to use the TOS
14045: optimization), resulting in a speedup of 1.14 on the sieve over the
14046: earlier results.
1.1 anton 14047:
14048: @cindex Win32Forth performance
14049: @cindex NT Forth performance
14050: @cindex eforth performance
14051: @cindex ThisForth performance
14052: @cindex PFE performance
14053: @cindex TILE performance
1.40 anton 14054: The potential advantage of assembly language implementations
1.1 anton 14055: is not necessarily realized in complete Forth systems: We compared
1.40 anton 14056: Gforth-0.4.9 (direct threaded, compiled with @code{gcc-2.95.1} and
1.1 anton 14057: @code{-DFORCE_REG}) with Win32Forth 1.2093, LMI's NT Forth (Beta, May
14058: 1994) and Eforth (with and without peephole (aka pinhole) optimization
14059: of the threaded code); all these systems were written in assembly
14060: language. We also compared Gforth with three systems written in C:
14061: PFE-0.9.14 (compiled with @code{gcc-2.6.3} with the default
14062: configuration for Linux: @code{-O2 -fomit-frame-pointer -DUSE_REGS
1.21 crook 14063: -DUNROLL_NEXT}), ThisForth Beta (compiled with @code{gcc-2.6.3 -O3
14064: -fomit-frame-pointer}; ThisForth employs peephole optimization of the
1.1 anton 14065: threaded code) and TILE (compiled with @code{make opt}). We benchmarked
14066: Gforth, PFE, ThisForth and TILE on a 486DX2/66 under Linux. Kenneth
14067: O'Heskin kindly provided the results for Win32Forth and NT Forth on a
14068: 486DX2/66 with similar memory performance under Windows NT. Marcel
14069: Hendrix ported Eforth to Linux, then extended it to run the benchmarks,
14070: added the peephole optimizer, ran the benchmarks and reported the
14071: results.
1.40 anton 14072:
1.1 anton 14073: We used four small benchmarks: the ubiquitous Sieve; bubble-sorting and
14074: matrix multiplication come from the Stanford integer benchmarks and have
14075: been translated into Forth by Martin Fraeman; we used the versions
14076: included in the TILE Forth package, but with bigger data set sizes; and
14077: a recursive Fibonacci number computation for benchmarking calling
14078: performance. The following table shows the time taken for the benchmarks
14079: scaled by the time taken by Gforth (in other words, it shows the speedup
14080: factor that Gforth achieved over the other systems).
14081:
14082: @example
1.40 anton 14083: relative Win32- NT eforth This-
1.1 anton 14084: time Gforth Forth Forth eforth +opt PFE Forth TILE
1.40 anton 14085: sieve 1.00 1.58 1.30 1.58 0.97 1.80 3.63 9.79
14086: bubble 1.00 1.55 1.67 1.75 1.04 1.78 4.59
14087: matmul 1.00 1.67 1.53 1.66 0.84 1.79 4.63
14088: fib 1.00 1.75 1.53 1.40 0.99 1.99 3.43 4.93
1.1 anton 14089: @end example
14090:
1.26 crook 14091: You may be quite surprised by the good performance of Gforth when
14092: compared with systems written in assembly language. One important reason
14093: for the disappointing performance of these other systems is probably
14094: that they are not written optimally for the 486 (e.g., they use the
14095: @code{lods} instruction). In addition, Win32Forth uses a comfortable,
14096: but costly method for relocating the Forth image: like @code{cforth}, it
14097: computes the actual addresses at run time, resulting in two address
14098: computations per @code{NEXT} (@pxref{Image File Background}).
14099:
1.40 anton 14100: Only Eforth with the peephole optimizer performs comparable to
14101: Gforth. The speedups achieved with peephole optimization of threaded
14102: code are quite remarkable. Adding a peephole optimizer to Gforth should
14103: cause similar speedups.
1.1 anton 14104:
14105: The speedup of Gforth over PFE, ThisForth and TILE can be easily
14106: explained with the self-imposed restriction of the latter systems to
14107: standard C, which makes efficient threading impossible (however, the
1.4 anton 14108: measured implementation of PFE uses a GNU C extension: @pxref{Global Reg
1.1 anton 14109: Vars, , Defining Global Register Variables, gcc.info, GNU C Manual}).
14110: Moreover, current C compilers have a hard time optimizing other aspects
14111: of the ThisForth and the TILE source.
14112:
1.26 crook 14113: The performance of Gforth on 386 architecture processors varies widely
14114: with the version of @code{gcc} used. E.g., @code{gcc-2.5.8} failed to
14115: allocate any of the virtual machine registers into real machine
14116: registers by itself and would not work correctly with explicit register
1.40 anton 14117: declarations, giving a 1.5 times slower engine (on a 486DX2/66 running
1.26 crook 14118: the Sieve) than the one measured above.
1.1 anton 14119:
1.26 crook 14120: Note that there have been several releases of Win32Forth since the
14121: release presented here, so the results presented above may have little
1.40 anton 14122: predictive value for the performance of Win32Forth today (results for
14123: the current release on an i486DX2/66 are welcome).
1.1 anton 14124:
14125: @cindex @file{Benchres}
1.66 anton 14126: In
14127: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl&maierhofer95.ps.gz,
14128: Translating Forth to Efficient C}} by M. Anton Ertl and Martin
1.1 anton 14129: Maierhofer (presented at EuroForth '95), an indirect threaded version of
1.66 anton 14130: Gforth is compared with Win32Forth, NT Forth, PFE, ThisForth, and
14131: several native code systems; that version of Gforth is slower on a 486
14132: than the direct threaded version used here. You can find a newer version
14133: of these measurements at
1.47 crook 14134: @uref{http://www.complang.tuwien.ac.at/forth/performance.html}. You can
1.1 anton 14135: find numbers for Gforth on various machines in @file{Benchres}.
14136:
1.26 crook 14137: @c ******************************************************************
1.13 pazsan 14138: @node Binding to System Library, Cross Compiler, Engine, Top
1.14 pazsan 14139: @chapter Binding to System Library
1.13 pazsan 14140:
14141: @node Cross Compiler, Bugs, Binding to System Library, Top
1.14 pazsan 14142: @chapter Cross Compiler
1.47 crook 14143: @cindex @file{cross.fs}
14144: @cindex cross-compiler
14145: @cindex metacompiler
14146: @cindex target compiler
1.13 pazsan 14147:
1.46 pazsan 14148: The cross compiler is used to bootstrap a Forth kernel. Since Gforth is
14149: mostly written in Forth, including crucial parts like the outer
14150: interpreter and compiler, it needs compiled Forth code to get
14151: started. The cross compiler allows to create new images for other
14152: architectures, even running under another Forth system.
1.13 pazsan 14153:
14154: @menu
1.67 anton 14155: * Using the Cross Compiler::
14156: * How the Cross Compiler Works::
1.13 pazsan 14157: @end menu
14158:
1.21 crook 14159: @node Using the Cross Compiler, How the Cross Compiler Works, Cross Compiler, Cross Compiler
1.14 pazsan 14160: @section Using the Cross Compiler
1.46 pazsan 14161:
14162: The cross compiler uses a language that resembles Forth, but isn't. The
14163: main difference is that you can execute Forth code after definition,
14164: while you usually can't execute the code compiled by cross, because the
14165: code you are compiling is typically for a different computer than the
14166: one you are compiling on.
14167:
14168: The Makefile is already set up to allow you to create kernels for new
14169: architectures with a simple make command. The generic kernels using the
14170: GCC compiled virtual machine are created in the normal build process
14171: with @code{make}. To create a embedded Gforth executable for e.g. the
14172: 8086 processor (running on a DOS machine), type
14173:
14174: @example
14175: make kernl-8086.fi
14176: @end example
14177:
14178: This will use the machine description from the @file{arch/8086}
14179: directory to create a new kernel. A machine file may look like that:
14180:
14181: @example
14182: \ Parameter for target systems 06oct92py
14183:
14184: 4 Constant cell \ cell size in bytes
14185: 2 Constant cell<< \ cell shift to bytes
14186: 5 Constant cell>bit \ cell shift to bits
14187: 8 Constant bits/char \ bits per character
14188: 8 Constant bits/byte \ bits per byte [default: 8]
14189: 8 Constant float \ bytes per float
14190: 8 Constant /maxalign \ maximum alignment in bytes
14191: false Constant bigendian \ byte order
14192: ( true=big, false=little )
14193:
14194: include machpc.fs \ feature list
14195: @end example
14196:
14197: This part is obligatory for the cross compiler itself, the feature list
14198: is used by the kernel to conditionally compile some features in and out,
14199: depending on whether the target supports these features.
14200:
14201: There are some optional features, if you define your own primitives,
14202: have an assembler, or need special, nonstandard preparation to make the
14203: boot process work. @code{asm-include} include an assembler,
14204: @code{prims-include} includes primitives, and @code{>boot} prepares for
14205: booting.
14206:
14207: @example
14208: : asm-include ." Include assembler" cr
14209: s" arch/8086/asm.fs" included ;
14210:
14211: : prims-include ." Include primitives" cr
14212: s" arch/8086/prim.fs" included ;
14213:
14214: : >boot ." Prepare booting" cr
14215: s" ' boot >body into-forth 1+ !" evaluate ;
14216: @end example
14217:
14218: These words are used as sort of macro during the cross compilation in
14219: the file @file{kernel/main.fs}. Instead of using this macros, it would
14220: be possible --- but more complicated --- to write a new kernel project
14221: file, too.
14222:
14223: @file{kernel/main.fs} expects the machine description file name on the
14224: stack; the cross compiler itself (@file{cross.fs}) assumes that either
14225: @code{mach-file} leaves a counted string on the stack, or
14226: @code{machine-file} leaves an address, count pair of the filename on the
14227: stack.
14228:
14229: The feature list is typically controlled using @code{SetValue}, generic
14230: files that are used by several projects can use @code{DefaultValue}
14231: instead. Both functions work like @code{Value}, when the value isn't
14232: defined, but @code{SetValue} works like @code{to} if the value is
14233: defined, and @code{DefaultValue} doesn't set anything, if the value is
14234: defined.
14235:
14236: @example
14237: \ generic mach file for pc gforth 03sep97jaw
14238:
14239: true DefaultValue NIL \ relocating
14240:
14241: >ENVIRON
14242:
14243: true DefaultValue file \ controls the presence of the
14244: \ file access wordset
14245: true DefaultValue OS \ flag to indicate a operating system
14246:
14247: true DefaultValue prims \ true: primitives are c-code
14248:
14249: true DefaultValue floating \ floating point wordset is present
14250:
14251: true DefaultValue glocals \ gforth locals are present
14252: \ will be loaded
14253: true DefaultValue dcomps \ double number comparisons
14254:
14255: true DefaultValue hash \ hashing primitives are loaded/present
14256:
14257: true DefaultValue xconds \ used together with glocals,
14258: \ special conditionals supporting gforths'
14259: \ local variables
14260: true DefaultValue header \ save a header information
14261:
14262: true DefaultValue backtrace \ enables backtrace code
14263:
14264: false DefaultValue ec
14265: false DefaultValue crlf
14266:
14267: cell 2 = [IF] &32 [ELSE] &256 [THEN] KB DefaultValue kernel-size
14268:
14269: &16 KB DefaultValue stack-size
14270: &15 KB &512 + DefaultValue fstack-size
14271: &15 KB DefaultValue rstack-size
14272: &14 KB &512 + DefaultValue lstack-size
14273: @end example
1.13 pazsan 14274:
1.48 anton 14275: @node How the Cross Compiler Works, , Using the Cross Compiler, Cross Compiler
1.14 pazsan 14276: @section How the Cross Compiler Works
1.13 pazsan 14277:
14278: @node Bugs, Origin, Cross Compiler, Top
1.21 crook 14279: @appendix Bugs
1.1 anton 14280: @cindex bug reporting
14281:
1.21 crook 14282: Known bugs are described in the file @file{BUGS} in the Gforth distribution.
1.1 anton 14283:
14284: If you find a bug, please send a bug report to
1.33 anton 14285: @email{bug-gforth@@gnu.org}. A bug report should include this
1.21 crook 14286: information:
14287:
14288: @itemize @bullet
14289: @item
14290: The Gforth version used (it is announced at the start of an
14291: interactive Gforth session).
14292: @item
14293: The machine and operating system (on Unix
14294: systems @code{uname -a} will report this information).
14295: @item
14296: The installation options (send the file @file{config.status}).
14297: @item
14298: A complete list of changes (if any) you (or your installer) have made to the
14299: Gforth sources.
14300: @item
14301: A program (or a sequence of keyboard commands) that reproduces the bug.
14302: @item
14303: A description of what you think constitutes the buggy behaviour.
14304: @end itemize
1.1 anton 14305:
14306: For a thorough guide on reporting bugs read @ref{Bug Reporting, , How
14307: to Report Bugs, gcc.info, GNU C Manual}.
14308:
14309:
1.21 crook 14310: @node Origin, Forth-related information, Bugs, Top
14311: @appendix Authors and Ancestors of Gforth
1.1 anton 14312:
14313: @section Authors and Contributors
14314: @cindex authors of Gforth
14315: @cindex contributors to Gforth
14316:
14317: The Gforth project was started in mid-1992 by Bernd Paysan and Anton
14318: Ertl. The third major author was Jens Wilke. Lennart Benschop (who was
14319: one of Gforth's first users, in mid-1993) and Stuart Ramsden inspired us
14320: with their continuous feedback. Lennart Benshop contributed
14321: @file{glosgen.fs}, while Stuart Ramsden has been working on automatic
14322: support for calling C libraries. Helpful comments also came from Paul
14323: Kleinrubatscher, Christian Pirker, Dirk Zoller, Marcel Hendrix, John
1.58 anton 14324: Wavrik, Barrie Stott, Marc de Groot, Jorge Acerada, Bruce Hoyt, and
14325: Robert Epprecht. Since the release of Gforth-0.2.1 there were also
14326: helpful comments from many others; thank you all, sorry for not listing
14327: you here (but digging through my mailbox to extract your names is on my
14328: to-do list). Since the release of Gforth-0.4.0 Neal Crook worked on the
14329: manual.
1.1 anton 14330:
14331: Gforth also owes a lot to the authors of the tools we used (GCC, CVS,
14332: and autoconf, among others), and to the creators of the Internet: Gforth
1.21 crook 14333: was developed across the Internet, and its authors did not meet
1.20 pazsan 14334: physically for the first 4 years of development.
1.1 anton 14335:
14336: @section Pedigree
1.26 crook 14337: @cindex pedigree of Gforth
1.1 anton 14338:
1.20 pazsan 14339: Gforth descends from bigFORTH (1993) and fig-Forth. Gforth and PFE (by
1.1 anton 14340: Dirk Zoller) will cross-fertilize each other. Of course, a significant
14341: part of the design of Gforth was prescribed by ANS Forth.
14342:
1.20 pazsan 14343: Bernd Paysan wrote bigFORTH, a descendent from TurboForth, an unreleased
1.1 anton 14344: 32 bit native code version of VolksForth for the Atari ST, written
14345: mostly by Dietrich Weineck.
14346:
14347: VolksForth descends from F83. It was written by Klaus Schleisiek, Bernd
14348: Pennemann, Georg Rehfeld and Dietrich Weineck for the C64 (called
14349: UltraForth there) in the mid-80s and ported to the Atari ST in 1986.
14350:
14351: Henry Laxen and Mike Perry wrote F83 as a model implementation of the
14352: Forth-83 standard. !! Pedigree? When?
14353:
14354: A team led by Bill Ragsdale implemented fig-Forth on many processors in
14355: 1979. Robert Selzer and Bill Ragsdale developed the original
14356: implementation of fig-Forth for the 6502 based on microForth.
14357:
14358: The principal architect of microForth was Dean Sanderson. microForth was
14359: FORTH, Inc.'s first off-the-shelf product. It was developed in 1976 for
14360: the 1802, and subsequently implemented on the 8080, the 6800 and the
14361: Z80.
14362:
14363: All earlier Forth systems were custom-made, usually by Charles Moore,
14364: who discovered (as he puts it) Forth during the late 60s. The first full
14365: Forth existed in 1971.
14366:
14367: A part of the information in this section comes from @cite{The Evolution
14368: of Forth} by Elizabeth D. Rather, Donald R. Colburn and Charles
14369: H. Moore, presented at the HOPL-II conference and preprinted in SIGPLAN
14370: Notices 28(3), 1993. You can find more historical and genealogical
14371: information about Forth there.
14372:
1.21 crook 14373: @node Forth-related information, Word Index, Origin, Top
14374: @appendix Other Forth-related information
14375: @cindex Forth-related information
14376:
14377: @menu
1.67 anton 14378: * Internet resources::
14379: * Books::
14380: * The Forth Interest Group::
14381: * Conferences::
1.21 crook 14382: @end menu
14383:
14384:
14385: @node Internet resources, Books, Forth-related information, Forth-related information
14386: @section Internet resources
1.26 crook 14387: @cindex internet resources
1.21 crook 14388:
14389: @cindex comp.lang.forth
14390: @cindex frequently asked questions
1.45 crook 14391: There is an active news group (comp.lang.forth) discussing Forth and
1.21 crook 14392: Forth-related issues. A frequently-asked-questions (FAQ) list
1.45 crook 14393: is posted to the news group regularly, and archived at these sites:
1.21 crook 14394:
14395: @itemize @bullet
14396: @item
1.47 crook 14397: @uref{ftp://rtfm.mit.edu/pub/usenet-by-group/comp.lang.forth/}
1.21 crook 14398: @item
1.47 crook 14399: @uref{ftp://ftp.forth.org/pub/Forth/FAQ/}
1.21 crook 14400: @end itemize
14401:
14402: The FAQ list should be considered mandatory reading before posting to
1.45 crook 14403: the news group.
1.21 crook 14404:
14405: Here are some other web sites holding Forth-related material:
14406:
14407: @itemize @bullet
14408: @item
1.47 crook 14409: @uref{http://www.taygeta.com/forth.html} -- Skip Carter's Forth pages.
1.21 crook 14410: @item
1.47 crook 14411: @uref{http://www.jwdt.com/~paysan/gforth.html} -- the Gforth home page.
1.21 crook 14412: @item
1.47 crook 14413: @uref{http://www.minerva.com/uathena.htm} -- home of ANS Forth Standard.
1.21 crook 14414: @item
1.47 crook 14415: @uref{http://dec.bournemouth.ac.uk/forth/index.html} -- the Forth
1.21 crook 14416: Research page, including links to the Journal of Forth Application and
14417: Research (JFAR) and a searchable Forth bibliography.
14418: @end itemize
14419:
14420:
14421: @node Books, The Forth Interest Group, Internet resources, Forth-related information
14422: @section Books
1.26 crook 14423: @cindex books on Forth
1.21 crook 14424:
14425: As the Standard is relatively new, there are not many books out yet. It
14426: is not recommended to learn Forth by using Gforth and a book that is not
14427: written for ANS Forth, as you will not know your mistakes from the
14428: deviations of the book. However, books based on the Forth-83 standard
14429: should be ok, because ANS Forth is primarily an extension of Forth-83.
1.44 crook 14430: Refer to the Forth FAQ for details of Forth-related books.
1.21 crook 14431:
14432: @cindex standard document for ANS Forth
14433: @cindex ANS Forth document
14434: The definite reference if you want to write ANS Forth programs is, of
1.26 crook 14435: course, the ANS Forth document. It is available in printed form from the
1.21 crook 14436: National Standards Institute Sales Department (Tel.: USA (212) 642-4900;
14437: Fax.: USA (212) 302-1286) as document @cite{X3.215-1994} for about
14438: $200. You can also get it from Global Engineering Documents (Tel.: USA
14439: (800) 854-7179; Fax.: (303) 843-9880) for about $300.
14440:
14441: @cite{dpANS6}, the last draft of the standard, which was then submitted
14442: to ANSI for publication is available electronically and for free in some
14443: MS Word format, and it has been converted to HTML
1.47 crook 14444: (@uref{http://www.taygeta.com/forth/dpans.html}; this HTML version also
1.44 crook 14445: includes the answers to Requests for Interpretation (RFIs). Some
14446: pointers to these versions can be found through
1.47 crook 14447: @*@uref{http://www.complang.tuwien.ac.at/projects/forth.html}.
1.44 crook 14448:
1.21 crook 14449:
14450: @node The Forth Interest Group, Conferences, Books, Forth-related information
14451: @section The Forth Interest Group
14452: @cindex Forth interest group (FIG)
14453:
14454: The Forth Interest Group (FIG) is a world-wide, non-profit,
1.26 crook 14455: member-supported organisation. It publishes a regular magazine,
14456: @var{FORTH Dimensions}, and offers other benefits of membership. You can
14457: contact the FIG through their office email address:
14458: @email{office@@forth.org} or by visiting their web site at
1.47 crook 14459: @uref{http://www.forth.org/}. This web site also includes links to FIG
1.26 crook 14460: chapters in other countries and American cities
1.47 crook 14461: (@uref{http://www.forth.org/chapters.html}).
1.21 crook 14462:
1.48 anton 14463: @node Conferences, , The Forth Interest Group, Forth-related information
1.21 crook 14464: @section Conferences
14465: @cindex Conferences
14466:
14467: There are several regular conferences related to Forth. They are all
1.26 crook 14468: well-publicised in @var{FORTH Dimensions} and on the comp.lang.forth
1.45 crook 14469: news group:
1.21 crook 14470:
14471: @itemize @bullet
14472: @item
14473: FORML -- the Forth modification laboratory convenes every year near
14474: Monterey, California.
14475: @item
14476: The Rochester Forth Conference -- an annual conference traditionally
14477: held in Rochester, New York.
14478: @item
14479: EuroForth -- this European conference takes place annually.
14480: @end itemize
14481:
14482:
1.41 anton 14483: @node Word Index, Name Index, Forth-related information, Top
1.1 anton 14484: @unnumbered Word Index
14485:
1.26 crook 14486: This index is a list of Forth words that have ``glossary'' entries
14487: within this manual. Each word is listed with its stack effect and
14488: wordset.
1.1 anton 14489:
14490: @printindex fn
14491:
1.41 anton 14492: @node Name Index, Concept Index, Word Index, Top
14493: @unnumbered Name Index
14494:
14495: This index is a list of Forth words that have ``glossary'' entries
14496: within this manual.
14497:
14498: @printindex ky
14499:
14500: @node Concept Index, , Name Index, Top
1.1 anton 14501: @unnumbered Concept and Word Index
14502:
1.26 crook 14503: Not all entries listed in this index are present verbatim in the
14504: text. This index also duplicates, in abbreviated form, all of the words
14505: listed in the Word Index (only the names are listed for the words here).
1.1 anton 14506:
14507: @printindex cp
14508:
14509: @contents
14510: @bye
14511:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>