Annotation of gforth/doc/gforth.ds, revision 1.109
1.1 anton 1: \input texinfo @c -*-texinfo-*-
2: @comment The source is gforth.ds, from which gforth.texi is generated
1.28 crook 3:
1.21 crook 4: @comment TODO: nac29jan99 - a list of things to add in the next edit:
1.28 crook 5: @comment 1. x-ref all ambiguous or implementation-defined features?
6: @comment 2. Describe the use of Auser Avariable AConstant A, etc.
7: @comment 3. words in miscellaneous section need a home.
8: @comment 4. search for TODO for other minor and major works required.
9: @comment 5. [rats] change all @var to @i in Forth source so that info
10: @comment file looks decent.
1.36 anton 11: @c Not an improvement IMO - anton
12: @c and anyway, this should be taken up
13: @c with Karl Berry (the texinfo guy) - anton
1.29 crook 14: @comment .. would be useful to have a word that identified all deferred words
15: @comment should semantics stuff in intro be moved to another section
16:
1.66 anton 17: @c POSTPONE, COMPILE, [COMPILE], LITERAL should have their own section
1.28 crook 18:
1.1 anton 19: @comment %**start of header (This is for running Texinfo on a region.)
20: @setfilename gforth.info
21: @settitle Gforth Manual
1.108 anton 22: @dircategory Software development
1.1 anton 23: @direntry
24: * Gforth: (gforth). A fast interpreter for the Forth language.
25: @end direntry
1.49 anton 26: @c The Texinfo manual also recommends doing this, but for Gforth it may
27: @c not make much sense
28: @c @dircategory Individual utilities
29: @c @direntry
30: @c * Gforth: (gforth)Invoking Gforth. gforth, gforth-fast, gforthmi
31: @c @end direntry
32:
1.1 anton 33: @comment @setchapternewpage odd
1.29 crook 34: @comment TODO this gets left in by HTML converter
1.12 anton 35: @macro progstyle {}
36: Programming style note:
1.3 anton 37: @end macro
1.48 anton 38:
39: @macro assignment {}
40: @table @i
41: @item Assignment:
42: @end macro
43: @macro endassignment {}
44: @end table
45: @end macro
46:
1.1 anton 47: @comment %**end of header (This is for running Texinfo on a region.)
48:
1.29 crook 49:
50: @comment ----------------------------------------------------------
51: @comment macros for beautifying glossary entries
52: @comment if these are used, need to strip them out for HTML converter
53: @comment else they get repeated verbatim in HTML output.
54: @comment .. not working yet.
55:
56: @macro GLOSS-START {}
57: @iftex
58: @ninerm
59: @end iftex
60: @end macro
61:
62: @macro GLOSS-END {}
63: @iftex
64: @rm
65: @end iftex
66: @end macro
67:
68: @comment ----------------------------------------------------------
69:
70:
1.10 anton 71: @include version.texi
72:
1.49 anton 73: @ifnottex
1.11 anton 74: This file documents Gforth @value{VERSION}
1.1 anton 75:
1.108 anton 76: Copyright @copyright{} 1995, 1996, 1997, 1998, 2000, 2003 Free Software Foundation, Inc.
1.1 anton 77:
78: Permission is granted to make and distribute verbatim copies of
79: this manual provided the copyright notice and this permission notice
80: are preserved on all copies.
81:
82: @ignore
83: Permission is granted to process this file through TeX and print the
84: results, provided the printed document carries a copying permission
85: notice identical to this one except for the removal of this paragraph
86: (this paragraph not being relevant to the printed manual).
87:
88: @end ignore
89: Permission is granted to copy and distribute modified versions of this
90: manual under the conditions for verbatim copying, provided also that the
91: sections entitled "Distribution" and "General Public License" are
92: included exactly as in the original, and provided that the entire
93: resulting derived work is distributed under the terms of a permission
94: notice identical to this one.
95:
96: Permission is granted to copy and distribute translations of this manual
97: into another language, under the above conditions for modified versions,
98: except that the sections entitled "Distribution" and "General Public
99: License" may be included in a translation approved by the author instead
100: of in the original English.
1.49 anton 101: @end ifnottex
1.1 anton 102:
103: @finalout
104: @titlepage
105: @sp 10
106: @center @titlefont{Gforth Manual}
107: @sp 2
1.11 anton 108: @center for version @value{VERSION}
1.1 anton 109: @sp 2
1.34 anton 110: @center Neal Crook
1.1 anton 111: @center Anton Ertl
1.6 pazsan 112: @center Bernd Paysan
1.5 anton 113: @center Jens Wilke
1.1 anton 114: @sp 3
1.47 crook 115: @center This manual is permanently under construction and was last updated on 15-Mar-2000
1.1 anton 116:
117: @comment The following two commands start the copyright page.
118: @page
119: @vskip 0pt plus 1filll
1.108 anton 120: Copyright @copyright{} 1995, 1996, 1997, 1998, 2000, 2003 Free Software Foundation, Inc.
1.1 anton 121:
122: @comment !! Published by ... or You can get a copy of this manual ...
123:
124: Permission is granted to make and distribute verbatim copies of
125: this manual provided the copyright notice and this permission notice
126: are preserved on all copies.
127:
128: Permission is granted to copy and distribute modified versions of this
129: manual under the conditions for verbatim copying, provided also that the
130: sections entitled "Distribution" and "General Public License" are
131: included exactly as in the original, and provided that the entire
132: resulting derived work is distributed under the terms of a permission
133: notice identical to this one.
134:
135: Permission is granted to copy and distribute translations of this manual
136: into another language, under the above conditions for modified versions,
137: except that the sections entitled "Distribution" and "General Public
138: License" may be included in a translation approved by the author instead
139: of in the original English.
140: @end titlepage
141:
142: @node Top, License, (dir), (dir)
1.49 anton 143: @ifnottex
1.1 anton 144: Gforth is a free implementation of ANS Forth available on many
1.11 anton 145: personal machines. This manual corresponds to version @value{VERSION}.
1.49 anton 146: @end ifnottex
1.1 anton 147:
148: @menu
1.21 crook 149: * License:: The GPL
1.26 crook 150: * Goals:: About the Gforth Project
1.29 crook 151: * Gforth Environment:: Starting (and exiting) Gforth
1.48 anton 152: * Tutorial:: Hands-on Forth Tutorial
1.21 crook 153: * Introduction:: An introduction to ANS Forth
1.1 anton 154: * Words:: Forth words available in Gforth
1.24 anton 155: * Error messages:: How to interpret them
1.1 anton 156: * Tools:: Programming tools
157: * ANS conformance:: Implementation-defined options etc.
1.65 anton 158: * Standard vs Extensions:: Should I use extensions?
1.1 anton 159: * Model:: The abstract machine of Gforth
160: * Integrating Gforth:: Forth as scripting language for applications
161: * Emacs and Gforth:: The Gforth Mode
162: * Image Files:: @code{.fi} files contain compiled code
163: * Engine:: The inner interpreter and the primitives
1.24 anton 164: * Binding to System Library::
1.13 pazsan 165: * Cross Compiler:: The Cross Compiler
1.1 anton 166: * Bugs:: How to report them
167: * Origin:: Authors and ancestors of Gforth
1.21 crook 168: * Forth-related information:: Books and places to look on the WWW
1.1 anton 169: * Word Index:: An item for each Forth word
170: * Concept Index:: A menu covering many topics
1.12 anton 171:
1.91 anton 172: @detailmenu
173: --- The Detailed Node Listing ---
1.12 anton 174:
1.29 crook 175: Gforth Environment
176:
1.32 anton 177: * Invoking Gforth:: Getting in
178: * Leaving Gforth:: Getting out
179: * Command-line editing::
1.48 anton 180: * Environment variables:: that affect how Gforth starts up
1.32 anton 181: * Gforth Files:: What gets installed and where
1.48 anton 182: * Startup speed:: When 35ms is not fast enough ...
183:
184: Forth Tutorial
185:
186: * Starting Gforth Tutorial::
187: * Syntax Tutorial::
188: * Crash Course Tutorial::
189: * Stack Tutorial::
190: * Arithmetics Tutorial::
191: * Stack Manipulation Tutorial::
192: * Using files for Forth code Tutorial::
193: * Comments Tutorial::
194: * Colon Definitions Tutorial::
195: * Decompilation Tutorial::
196: * Stack-Effect Comments Tutorial::
197: * Types Tutorial::
198: * Factoring Tutorial::
199: * Designing the stack effect Tutorial::
200: * Local Variables Tutorial::
201: * Conditional execution Tutorial::
202: * Flags and Comparisons Tutorial::
203: * General Loops Tutorial::
204: * Counted loops Tutorial::
205: * Recursion Tutorial::
206: * Leaving definitions or loops Tutorial::
207: * Return Stack Tutorial::
208: * Memory Tutorial::
209: * Characters and Strings Tutorial::
210: * Alignment Tutorial::
1.87 anton 211: * Files Tutorial::
1.48 anton 212: * Interpretation and Compilation Semantics and Immediacy Tutorial::
213: * Execution Tokens Tutorial::
214: * Exceptions Tutorial::
215: * Defining Words Tutorial::
216: * Arrays and Records Tutorial::
217: * POSTPONE Tutorial::
218: * Literal Tutorial::
219: * Advanced macros Tutorial::
220: * Compilation Tokens Tutorial::
221: * Wordlists and Search Order Tutorial::
1.29 crook 222:
1.24 anton 223: An Introduction to ANS Forth
224:
1.67 anton 225: * Introducing the Text Interpreter::
226: * Stacks and Postfix notation::
227: * Your first definition::
228: * How does that work?::
229: * Forth is written in Forth::
230: * Review - elements of a Forth system::
231: * Where to go next::
232: * Exercises::
1.24 anton 233:
1.12 anton 234: Forth Words
235:
236: * Notation::
1.65 anton 237: * Case insensitivity::
238: * Comments::
239: * Boolean Flags::
1.12 anton 240: * Arithmetic::
241: * Stack Manipulation::
242: * Memory::
243: * Control Structures::
244: * Defining Words::
1.65 anton 245: * Interpretation and Compilation Semantics::
1.47 crook 246: * Tokens for Words::
1.81 anton 247: * Compiling words::
1.65 anton 248: * The Text Interpreter::
249: * Word Lists::
250: * Environmental Queries::
1.12 anton 251: * Files::
252: * Blocks::
253: * Other I/O::
1.78 anton 254: * Locals::
255: * Structures::
256: * Object-oriented Forth::
1.12 anton 257: * Programming Tools::
258: * Assembler and Code Words::
259: * Threading Words::
1.65 anton 260: * Passing Commands to the OS::
261: * Keeping track of Time::
262: * Miscellaneous Words::
1.12 anton 263:
264: Arithmetic
265:
266: * Single precision::
1.67 anton 267: * Double precision:: Double-cell integer arithmetic
1.12 anton 268: * Bitwise operations::
1.67 anton 269: * Numeric comparison::
1.32 anton 270: * Mixed precision:: Operations with single and double-cell integers
1.12 anton 271: * Floating Point::
272:
273: Stack Manipulation
274:
275: * Data stack::
276: * Floating point stack::
277: * Return stack::
278: * Locals stack::
279: * Stack pointer manipulation::
280:
281: Memory
282:
1.32 anton 283: * Memory model::
284: * Dictionary allocation::
285: * Heap Allocation::
286: * Memory Access::
287: * Address arithmetic::
288: * Memory Blocks::
1.12 anton 289:
290: Control Structures
291:
1.41 anton 292: * Selection:: IF ... ELSE ... ENDIF
293: * Simple Loops:: BEGIN ...
1.32 anton 294: * Counted Loops:: DO
1.67 anton 295: * Arbitrary control structures::
296: * Calls and returns::
1.12 anton 297: * Exception Handling::
298:
299: Defining Words
300:
1.67 anton 301: * CREATE::
1.44 crook 302: * Variables:: Variables and user variables
1.67 anton 303: * Constants::
1.44 crook 304: * Values:: Initialised variables
1.67 anton 305: * Colon Definitions::
1.44 crook 306: * Anonymous Definitions:: Definitions without names
1.71 anton 307: * Supplying names:: Passing definition names as strings
1.67 anton 308: * User-defined Defining Words::
1.44 crook 309: * Deferred words:: Allow forward references
1.67 anton 310: * Aliases::
1.47 crook 311:
1.63 anton 312: User-defined Defining Words
313:
314: * CREATE..DOES> applications::
315: * CREATE..DOES> details::
316: * Advanced does> usage example::
1.91 anton 317: * @code{Const-does>}::
1.63 anton 318:
1.47 crook 319: Interpretation and Compilation Semantics
320:
1.67 anton 321: * Combined words::
1.12 anton 322:
1.71 anton 323: Tokens for Words
324:
325: * Execution token:: represents execution/interpretation semantics
326: * Compilation token:: represents compilation semantics
327: * Name token:: represents named words
328:
1.82 anton 329: Compiling words
330:
331: * Literals:: Compiling data values
332: * Macros:: Compiling words
333:
1.21 crook 334: The Text Interpreter
335:
1.67 anton 336: * Input Sources::
337: * Number Conversion::
338: * Interpret/Compile states::
339: * Interpreter Directives::
1.21 crook 340:
1.26 crook 341: Word Lists
342:
1.75 anton 343: * Vocabularies::
1.67 anton 344: * Why use word lists?::
1.75 anton 345: * Word list example::
1.26 crook 346:
347: Files
348:
1.48 anton 349: * Forth source files::
350: * General files::
351: * Search Paths::
352:
353: Search Paths
354:
1.75 anton 355: * Source Search Paths::
1.26 crook 356: * General Search Paths::
357:
358: Other I/O
359:
1.32 anton 360: * Simple numeric output:: Predefined formats
361: * Formatted numeric output:: Formatted (pictured) output
362: * String Formats:: How Forth stores strings in memory
1.67 anton 363: * Displaying characters and strings:: Other stuff
1.32 anton 364: * Input:: Input
1.26 crook 365:
366: Locals
367:
368: * Gforth locals::
369: * ANS Forth locals::
370:
371: Gforth locals
372:
373: * Where are locals visible by name?::
374: * How long do locals live?::
1.78 anton 375: * Locals programming style::
376: * Locals implementation::
1.26 crook 377:
1.12 anton 378: Structures
379:
380: * Why explicit structure support?::
381: * Structure Usage::
382: * Structure Naming Convention::
383: * Structure Implementation::
384: * Structure Glossary::
385:
386: Object-oriented Forth
387:
1.48 anton 388: * Why object-oriented programming?::
389: * Object-Oriented Terminology::
390: * Objects::
391: * OOF::
392: * Mini-OOF::
1.23 crook 393: * Comparison with other object models::
1.12 anton 394:
1.24 anton 395: The @file{objects.fs} model
1.12 anton 396:
397: * Properties of the Objects model::
398: * Basic Objects Usage::
1.41 anton 399: * The Objects base class::
1.12 anton 400: * Creating objects::
401: * Object-Oriented Programming Style::
402: * Class Binding::
403: * Method conveniences::
404: * Classes and Scoping::
1.41 anton 405: * Dividing classes::
1.12 anton 406: * Object Interfaces::
407: * Objects Implementation::
408: * Objects Glossary::
409:
1.24 anton 410: The @file{oof.fs} model
1.12 anton 411:
1.67 anton 412: * Properties of the OOF model::
413: * Basic OOF Usage::
414: * The OOF base class::
415: * Class Declaration::
416: * Class Implementation::
1.12 anton 417:
1.24 anton 418: The @file{mini-oof.fs} model
1.23 crook 419:
1.48 anton 420: * Basic Mini-OOF Usage::
421: * Mini-OOF Example::
422: * Mini-OOF Implementation::
1.23 crook 423:
1.78 anton 424: Programming Tools
425:
426: * Examining::
427: * Forgetting words::
428: * Debugging:: Simple and quick.
429: * Assertions:: Making your programs self-checking.
430: * Singlestep Debugger:: Executing your program word by word.
431:
432: Assembler and Code Words
433:
434: * Code and ;code::
435: * Common Assembler:: Assembler Syntax
436: * Common Disassembler::
437: * 386 Assembler:: Deviations and special cases
438: * Alpha Assembler:: Deviations and special cases
439: * MIPS assembler:: Deviations and special cases
440: * Other assemblers:: How to write them
441:
1.12 anton 442: Tools
443:
444: * ANS Report:: Report the words used, sorted by wordset.
445:
446: ANS conformance
447:
448: * The Core Words::
449: * The optional Block word set::
450: * The optional Double Number word set::
451: * The optional Exception word set::
452: * The optional Facility word set::
453: * The optional File-Access word set::
454: * The optional Floating-Point word set::
455: * The optional Locals word set::
456: * The optional Memory-Allocation word set::
457: * The optional Programming-Tools word set::
458: * The optional Search-Order word set::
459:
460: The Core Words
461:
462: * core-idef:: Implementation Defined Options
463: * core-ambcond:: Ambiguous Conditions
464: * core-other:: Other System Documentation
465:
466: The optional Block word set
467:
468: * block-idef:: Implementation Defined Options
469: * block-ambcond:: Ambiguous Conditions
470: * block-other:: Other System Documentation
471:
472: The optional Double Number word set
473:
474: * double-ambcond:: Ambiguous Conditions
475:
476: The optional Exception word set
477:
478: * exception-idef:: Implementation Defined Options
479:
480: The optional Facility word set
481:
482: * facility-idef:: Implementation Defined Options
483: * facility-ambcond:: Ambiguous Conditions
484:
485: The optional File-Access word set
486:
487: * file-idef:: Implementation Defined Options
488: * file-ambcond:: Ambiguous Conditions
489:
490: The optional Floating-Point word set
491:
492: * floating-idef:: Implementation Defined Options
493: * floating-ambcond:: Ambiguous Conditions
494:
495: The optional Locals word set
496:
497: * locals-idef:: Implementation Defined Options
498: * locals-ambcond:: Ambiguous Conditions
499:
500: The optional Memory-Allocation word set
501:
502: * memory-idef:: Implementation Defined Options
503:
504: The optional Programming-Tools word set
505:
506: * programming-idef:: Implementation Defined Options
507: * programming-ambcond:: Ambiguous Conditions
508:
509: The optional Search-Order word set
510:
511: * search-idef:: Implementation Defined Options
512: * search-ambcond:: Ambiguous Conditions
513:
1.109 ! anton 514: Emacs and Gforth
! 515:
! 516: * Installing gforth.el:: Making Emacs aware of Forth.
! 517: * Emacs Tags:: Viewing the source of a word in Emacs.
! 518: * Hilighting:: Making Forth code look prettier.
! 519: * Auto-Indentation:: Customizing auto-indentation.
! 520: * Blocks Files:: Reading and writing blocks files.
! 521:
1.12 anton 522: Image Files
523:
1.24 anton 524: * Image Licensing Issues:: Distribution terms for images.
525: * Image File Background:: Why have image files?
1.67 anton 526: * Non-Relocatable Image Files:: don't always work.
1.24 anton 527: * Data-Relocatable Image Files:: are better.
1.67 anton 528: * Fully Relocatable Image Files:: better yet.
1.24 anton 529: * Stack and Dictionary Sizes:: Setting the default sizes for an image.
1.32 anton 530: * Running Image Files:: @code{gforth -i @i{file}} or @i{file}.
1.24 anton 531: * Modifying the Startup Sequence:: and turnkey applications.
1.12 anton 532:
533: Fully Relocatable Image Files
534:
1.27 crook 535: * gforthmi:: The normal way
1.12 anton 536: * cross.fs:: The hard way
537:
538: Engine
539:
540: * Portability::
541: * Threading::
542: * Primitives::
543: * Performance::
544:
545: Threading
546:
547: * Scheduling::
548: * Direct or Indirect Threaded?::
1.109 ! anton 549: * Dynamic Superinstructions::
1.12 anton 550: * DOES>::
551:
552: Primitives
553:
554: * Automatic Generation::
555: * TOS Optimization::
556: * Produced code::
1.13 pazsan 557:
558: Cross Compiler
559:
1.67 anton 560: * Using the Cross Compiler::
561: * How the Cross Compiler Works::
1.13 pazsan 562:
1.24 anton 563: @end detailmenu
1.1 anton 564: @end menu
565:
1.26 crook 566: @node License, Goals, Top, Top
1.1 anton 567: @unnumbered GNU GENERAL PUBLIC LICENSE
568: @center Version 2, June 1991
569:
570: @display
571: Copyright @copyright{} 1989, 1991 Free Software Foundation, Inc.
1.88 anton 572: 59 Temple Place, Suite 330, Boston, MA 02111, USA
1.1 anton 573:
574: Everyone is permitted to copy and distribute verbatim copies
575: of this license document, but changing it is not allowed.
576: @end display
577:
578: @unnumberedsec Preamble
579:
580: The licenses for most software are designed to take away your
581: freedom to share and change it. By contrast, the GNU General Public
582: License is intended to guarantee your freedom to share and change free
583: software---to make sure the software is free for all its users. This
584: General Public License applies to most of the Free Software
585: Foundation's software and to any other program whose authors commit to
586: using it. (Some other Free Software Foundation software is covered by
587: the GNU Library General Public License instead.) You can apply it to
588: your programs, too.
589:
590: When we speak of free software, we are referring to freedom, not
591: price. Our General Public Licenses are designed to make sure that you
592: have the freedom to distribute copies of free software (and charge for
593: this service if you wish), that you receive source code or can get it
594: if you want it, that you can change the software or use pieces of it
595: in new free programs; and that you know you can do these things.
596:
597: To protect your rights, we need to make restrictions that forbid
598: anyone to deny you these rights or to ask you to surrender the rights.
599: These restrictions translate to certain responsibilities for you if you
600: distribute copies of the software, or if you modify it.
601:
602: For example, if you distribute copies of such a program, whether
603: gratis or for a fee, you must give the recipients all the rights that
604: you have. You must make sure that they, too, receive or can get the
605: source code. And you must show them these terms so they know their
606: rights.
607:
608: We protect your rights with two steps: (1) copyright the software, and
609: (2) offer you this license which gives you legal permission to copy,
610: distribute and/or modify the software.
611:
612: Also, for each author's protection and ours, we want to make certain
613: that everyone understands that there is no warranty for this free
614: software. If the software is modified by someone else and passed on, we
615: want its recipients to know that what they have is not the original, so
616: that any problems introduced by others will not reflect on the original
617: authors' reputations.
618:
619: Finally, any free program is threatened constantly by software
620: patents. We wish to avoid the danger that redistributors of a free
621: program will individually obtain patent licenses, in effect making the
622: program proprietary. To prevent this, we have made it clear that any
623: patent must be licensed for everyone's free use or not licensed at all.
624:
625: The precise terms and conditions for copying, distribution and
626: modification follow.
627:
628: @iftex
629: @unnumberedsec TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
630: @end iftex
1.49 anton 631: @ifnottex
1.1 anton 632: @center TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
1.49 anton 633: @end ifnottex
1.1 anton 634:
635: @enumerate 0
636: @item
637: This License applies to any program or other work which contains
638: a notice placed by the copyright holder saying it may be distributed
639: under the terms of this General Public License. The ``Program'', below,
640: refers to any such program or work, and a ``work based on the Program''
641: means either the Program or any derivative work under copyright law:
642: that is to say, a work containing the Program or a portion of it,
643: either verbatim or with modifications and/or translated into another
644: language. (Hereinafter, translation is included without limitation in
645: the term ``modification''.) Each licensee is addressed as ``you''.
646:
647: Activities other than copying, distribution and modification are not
648: covered by this License; they are outside its scope. The act of
649: running the Program is not restricted, and the output from the Program
650: is covered only if its contents constitute a work based on the
651: Program (independent of having been made by running the Program).
652: Whether that is true depends on what the Program does.
653:
654: @item
655: You may copy and distribute verbatim copies of the Program's
656: source code as you receive it, in any medium, provided that you
657: conspicuously and appropriately publish on each copy an appropriate
658: copyright notice and disclaimer of warranty; keep intact all the
659: notices that refer to this License and to the absence of any warranty;
660: and give any other recipients of the Program a copy of this License
661: along with the Program.
662:
663: You may charge a fee for the physical act of transferring a copy, and
664: you may at your option offer warranty protection in exchange for a fee.
665:
666: @item
667: You may modify your copy or copies of the Program or any portion
668: of it, thus forming a work based on the Program, and copy and
669: distribute such modifications or work under the terms of Section 1
670: above, provided that you also meet all of these conditions:
671:
672: @enumerate a
673: @item
674: You must cause the modified files to carry prominent notices
675: stating that you changed the files and the date of any change.
676:
677: @item
678: You must cause any work that you distribute or publish, that in
679: whole or in part contains or is derived from the Program or any
680: part thereof, to be licensed as a whole at no charge to all third
681: parties under the terms of this License.
682:
683: @item
684: If the modified program normally reads commands interactively
685: when run, you must cause it, when started running for such
686: interactive use in the most ordinary way, to print or display an
687: announcement including an appropriate copyright notice and a
688: notice that there is no warranty (or else, saying that you provide
689: a warranty) and that users may redistribute the program under
690: these conditions, and telling the user how to view a copy of this
691: License. (Exception: if the Program itself is interactive but
692: does not normally print such an announcement, your work based on
693: the Program is not required to print an announcement.)
694: @end enumerate
695:
696: These requirements apply to the modified work as a whole. If
697: identifiable sections of that work are not derived from the Program,
698: and can be reasonably considered independent and separate works in
699: themselves, then this License, and its terms, do not apply to those
700: sections when you distribute them as separate works. But when you
701: distribute the same sections as part of a whole which is a work based
702: on the Program, the distribution of the whole must be on the terms of
703: this License, whose permissions for other licensees extend to the
704: entire whole, and thus to each and every part regardless of who wrote it.
705:
706: Thus, it is not the intent of this section to claim rights or contest
707: your rights to work written entirely by you; rather, the intent is to
708: exercise the right to control the distribution of derivative or
709: collective works based on the Program.
710:
711: In addition, mere aggregation of another work not based on the Program
712: with the Program (or with a work based on the Program) on a volume of
713: a storage or distribution medium does not bring the other work under
714: the scope of this License.
715:
716: @item
717: You may copy and distribute the Program (or a work based on it,
718: under Section 2) in object code or executable form under the terms of
719: Sections 1 and 2 above provided that you also do one of the following:
720:
721: @enumerate a
722: @item
723: Accompany it with the complete corresponding machine-readable
724: source code, which must be distributed under the terms of Sections
725: 1 and 2 above on a medium customarily used for software interchange; or,
726:
727: @item
728: Accompany it with a written offer, valid for at least three
729: years, to give any third party, for a charge no more than your
730: cost of physically performing source distribution, a complete
731: machine-readable copy of the corresponding source code, to be
732: distributed under the terms of Sections 1 and 2 above on a medium
733: customarily used for software interchange; or,
734:
735: @item
736: Accompany it with the information you received as to the offer
737: to distribute corresponding source code. (This alternative is
738: allowed only for noncommercial distribution and only if you
739: received the program in object code or executable form with such
740: an offer, in accord with Subsection b above.)
741: @end enumerate
742:
743: The source code for a work means the preferred form of the work for
744: making modifications to it. For an executable work, complete source
745: code means all the source code for all modules it contains, plus any
746: associated interface definition files, plus the scripts used to
747: control compilation and installation of the executable. However, as a
748: special exception, the source code distributed need not include
749: anything that is normally distributed (in either source or binary
750: form) with the major components (compiler, kernel, and so on) of the
751: operating system on which the executable runs, unless that component
752: itself accompanies the executable.
753:
754: If distribution of executable or object code is made by offering
755: access to copy from a designated place, then offering equivalent
756: access to copy the source code from the same place counts as
757: distribution of the source code, even though third parties are not
758: compelled to copy the source along with the object code.
759:
760: @item
761: You may not copy, modify, sublicense, or distribute the Program
762: except as expressly provided under this License. Any attempt
763: otherwise to copy, modify, sublicense or distribute the Program is
764: void, and will automatically terminate your rights under this License.
765: However, parties who have received copies, or rights, from you under
766: this License will not have their licenses terminated so long as such
767: parties remain in full compliance.
768:
769: @item
770: You are not required to accept this License, since you have not
771: signed it. However, nothing else grants you permission to modify or
772: distribute the Program or its derivative works. These actions are
773: prohibited by law if you do not accept this License. Therefore, by
774: modifying or distributing the Program (or any work based on the
775: Program), you indicate your acceptance of this License to do so, and
776: all its terms and conditions for copying, distributing or modifying
777: the Program or works based on it.
778:
779: @item
780: Each time you redistribute the Program (or any work based on the
781: Program), the recipient automatically receives a license from the
782: original licensor to copy, distribute or modify the Program subject to
783: these terms and conditions. You may not impose any further
784: restrictions on the recipients' exercise of the rights granted herein.
785: You are not responsible for enforcing compliance by third parties to
786: this License.
787:
788: @item
789: If, as a consequence of a court judgment or allegation of patent
790: infringement or for any other reason (not limited to patent issues),
791: conditions are imposed on you (whether by court order, agreement or
792: otherwise) that contradict the conditions of this License, they do not
793: excuse you from the conditions of this License. If you cannot
794: distribute so as to satisfy simultaneously your obligations under this
795: License and any other pertinent obligations, then as a consequence you
796: may not distribute the Program at all. For example, if a patent
797: license would not permit royalty-free redistribution of the Program by
798: all those who receive copies directly or indirectly through you, then
799: the only way you could satisfy both it and this License would be to
800: refrain entirely from distribution of the Program.
801:
802: If any portion of this section is held invalid or unenforceable under
803: any particular circumstance, the balance of the section is intended to
804: apply and the section as a whole is intended to apply in other
805: circumstances.
806:
807: It is not the purpose of this section to induce you to infringe any
808: patents or other property right claims or to contest validity of any
809: such claims; this section has the sole purpose of protecting the
810: integrity of the free software distribution system, which is
811: implemented by public license practices. Many people have made
812: generous contributions to the wide range of software distributed
813: through that system in reliance on consistent application of that
814: system; it is up to the author/donor to decide if he or she is willing
815: to distribute software through any other system and a licensee cannot
816: impose that choice.
817:
818: This section is intended to make thoroughly clear what is believed to
819: be a consequence of the rest of this License.
820:
821: @item
822: If the distribution and/or use of the Program is restricted in
823: certain countries either by patents or by copyrighted interfaces, the
824: original copyright holder who places the Program under this License
825: may add an explicit geographical distribution limitation excluding
826: those countries, so that distribution is permitted only in or among
827: countries not thus excluded. In such case, this License incorporates
828: the limitation as if written in the body of this License.
829:
830: @item
831: The Free Software Foundation may publish revised and/or new versions
832: of the General Public License from time to time. Such new versions will
833: be similar in spirit to the present version, but may differ in detail to
834: address new problems or concerns.
835:
836: Each version is given a distinguishing version number. If the Program
837: specifies a version number of this License which applies to it and ``any
838: later version'', you have the option of following the terms and conditions
839: either of that version or of any later version published by the Free
840: Software Foundation. If the Program does not specify a version number of
841: this License, you may choose any version ever published by the Free Software
842: Foundation.
843:
844: @item
845: If you wish to incorporate parts of the Program into other free
846: programs whose distribution conditions are different, write to the author
847: to ask for permission. For software which is copyrighted by the Free
848: Software Foundation, write to the Free Software Foundation; we sometimes
849: make exceptions for this. Our decision will be guided by the two goals
850: of preserving the free status of all derivatives of our free software and
851: of promoting the sharing and reuse of software generally.
852:
853: @iftex
854: @heading NO WARRANTY
855: @end iftex
1.49 anton 856: @ifnottex
1.1 anton 857: @center NO WARRANTY
1.49 anton 858: @end ifnottex
1.1 anton 859:
860: @item
861: BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
862: FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
863: OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
864: PROVIDE THE PROGRAM ``AS IS'' WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
865: OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
866: MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
867: TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
868: PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
869: REPAIR OR CORRECTION.
870:
871: @item
872: IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
873: WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
874: REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
875: INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
876: OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
877: TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
878: YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
879: PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
880: POSSIBILITY OF SUCH DAMAGES.
881: @end enumerate
882:
883: @iftex
884: @heading END OF TERMS AND CONDITIONS
885: @end iftex
1.49 anton 886: @ifnottex
1.1 anton 887: @center END OF TERMS AND CONDITIONS
1.49 anton 888: @end ifnottex
1.1 anton 889:
890: @page
891: @unnumberedsec How to Apply These Terms to Your New Programs
892:
893: If you develop a new program, and you want it to be of the greatest
894: possible use to the public, the best way to achieve this is to make it
895: free software which everyone can redistribute and change under these terms.
896:
897: To do so, attach the following notices to the program. It is safest
898: to attach them to the start of each source file to most effectively
899: convey the exclusion of warranty; and each file should have at least
900: the ``copyright'' line and a pointer to where the full notice is found.
901:
902: @smallexample
903: @var{one line to give the program's name and a brief idea of what it does.}
904: Copyright (C) 19@var{yy} @var{name of author}
905:
906: This program is free software; you can redistribute it and/or modify
907: it under the terms of the GNU General Public License as published by
908: the Free Software Foundation; either version 2 of the License, or
909: (at your option) any later version.
910:
911: This program is distributed in the hope that it will be useful,
912: but WITHOUT ANY WARRANTY; without even the implied warranty of
913: MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
914: GNU General Public License for more details.
915:
916: You should have received a copy of the GNU General Public License
917: along with this program; if not, write to the Free Software
1.88 anton 918: Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
1.1 anton 919: @end smallexample
920:
921: Also add information on how to contact you by electronic and paper mail.
922:
923: If the program is interactive, make it output a short notice like this
924: when it starts in an interactive mode:
925:
926: @smallexample
927: Gnomovision version 69, Copyright (C) 19@var{yy} @var{name of author}
928: Gnomovision comes with ABSOLUTELY NO WARRANTY; for details
929: type `show w'.
930: This is free software, and you are welcome to redistribute it
931: under certain conditions; type `show c' for details.
932: @end smallexample
933:
934: The hypothetical commands @samp{show w} and @samp{show c} should show
935: the appropriate parts of the General Public License. Of course, the
936: commands you use may be called something other than @samp{show w} and
937: @samp{show c}; they could even be mouse-clicks or menu items---whatever
938: suits your program.
939:
940: You should also get your employer (if you work as a programmer) or your
941: school, if any, to sign a ``copyright disclaimer'' for the program, if
942: necessary. Here is a sample; alter the names:
943:
944: @smallexample
945: Yoyodyne, Inc., hereby disclaims all copyright interest in the program
946: `Gnomovision' (which makes passes at compilers) written by James Hacker.
947:
948: @var{signature of Ty Coon}, 1 April 1989
949: Ty Coon, President of Vice
950: @end smallexample
951:
952: This General Public License does not permit incorporating your program into
953: proprietary programs. If your program is a subroutine library, you may
954: consider it more useful to permit linking proprietary applications with the
955: library. If this is what you want to do, use the GNU Library General
956: Public License instead of this License.
957:
958: @iftex
959: @unnumbered Preface
960: @cindex Preface
1.21 crook 961: This manual documents Gforth. Some introductory material is provided for
962: readers who are unfamiliar with Forth or who are migrating to Gforth
963: from other Forth compilers. However, this manual is primarily a
964: reference manual.
1.1 anton 965: @end iftex
966:
1.28 crook 967: @comment TODO much more blurb here.
1.26 crook 968:
969: @c ******************************************************************
1.29 crook 970: @node Goals, Gforth Environment, License, Top
1.26 crook 971: @comment node-name, next, previous, up
972: @chapter Goals of Gforth
973: @cindex goals of the Gforth project
974: The goal of the Gforth Project is to develop a standard model for
975: ANS Forth. This can be split into several subgoals:
976:
977: @itemize @bullet
978: @item
979: Gforth should conform to the ANS Forth Standard.
980: @item
981: It should be a model, i.e. it should define all the
982: implementation-dependent things.
983: @item
984: It should become standard, i.e. widely accepted and used. This goal
985: is the most difficult one.
986: @end itemize
987:
988: To achieve these goals Gforth should be
989: @itemize @bullet
990: @item
991: Similar to previous models (fig-Forth, F83)
992: @item
993: Powerful. It should provide for all the things that are considered
994: necessary today and even some that are not yet considered necessary.
995: @item
996: Efficient. It should not get the reputation of being exceptionally
997: slow.
998: @item
999: Free.
1000: @item
1001: Available on many machines/easy to port.
1002: @end itemize
1003:
1004: Have we achieved these goals? Gforth conforms to the ANS Forth
1005: standard. It may be considered a model, but we have not yet documented
1006: which parts of the model are stable and which parts we are likely to
1007: change. It certainly has not yet become a de facto standard, but it
1008: appears to be quite popular. It has some similarities to and some
1009: differences from previous models. It has some powerful features, but not
1010: yet everything that we envisioned. We certainly have achieved our
1.65 anton 1011: execution speed goals (@pxref{Performance})@footnote{However, in 1998
1012: the bar was raised when the major commercial Forth vendors switched to
1013: native code compilers.}. It is free and available on many machines.
1.29 crook 1014:
1.26 crook 1015: @c ******************************************************************
1.48 anton 1016: @node Gforth Environment, Tutorial, Goals, Top
1.29 crook 1017: @chapter Gforth Environment
1018: @cindex Gforth environment
1.21 crook 1019:
1.45 crook 1020: Note: ultimately, the Gforth man page will be auto-generated from the
1.29 crook 1021: material in this chapter.
1.21 crook 1022:
1023: @menu
1.29 crook 1024: * Invoking Gforth:: Getting in
1025: * Leaving Gforth:: Getting out
1026: * Command-line editing::
1.48 anton 1027: * Environment variables:: that affect how Gforth starts up
1.29 crook 1028: * Gforth Files:: What gets installed and where
1.48 anton 1029: * Startup speed:: When 35ms is not fast enough ...
1.21 crook 1030: @end menu
1031:
1.49 anton 1032: For related information about the creation of images see @ref{Image Files}.
1.29 crook 1033:
1.21 crook 1034: @comment ----------------------------------------------
1.48 anton 1035: @node Invoking Gforth, Leaving Gforth, Gforth Environment, Gforth Environment
1.29 crook 1036: @section Invoking Gforth
1037: @cindex invoking Gforth
1038: @cindex running Gforth
1039: @cindex command-line options
1040: @cindex options on the command line
1041: @cindex flags on the command line
1.21 crook 1042:
1.30 anton 1043: Gforth is made up of two parts; an executable ``engine'' (named
1.109 ! anton 1044: @command{gforth} or @command{gforth-fast}) and an image file. To start it, you
1.30 anton 1045: will usually just say @code{gforth} -- this automatically loads the
1046: default image file @file{gforth.fi}. In many other cases the default
1047: Gforth image will be invoked like this:
1.21 crook 1048: @example
1.30 anton 1049: gforth [file | -e forth-code] ...
1.21 crook 1050: @end example
1.29 crook 1051: @noindent
1052: This interprets the contents of the files and the Forth code in the order they
1053: are given.
1.21 crook 1054:
1.109 ! anton 1055: In addition to the @command{gforth} engine, there is also an engine
! 1056: called @command{gforth-fast}, which is faster, but gives less
! 1057: informative error messages (@pxref{Error messages}) and may catch some
! 1058: stack underflows later or not at all. You should use it for debugged,
! 1059: performance-critical programs.
! 1060:
! 1061: Moreover, there is an engine called @command{gforth-itc}, which is
! 1062: useful in some backwards-compatibility situations (@pxref{Direct or
! 1063: Indirect Threaded?}).
1.30 anton 1064:
1.29 crook 1065: In general, the command line looks like this:
1.21 crook 1066:
1067: @example
1.30 anton 1068: gforth[-fast] [engine options] [image options]
1.21 crook 1069: @end example
1070:
1.30 anton 1071: The engine options must come before the rest of the command
1.29 crook 1072: line. They are:
1.26 crook 1073:
1.29 crook 1074: @table @code
1075: @cindex -i, command-line option
1076: @cindex --image-file, command-line option
1077: @item --image-file @i{file}
1078: @itemx -i @i{file}
1079: Loads the Forth image @i{file} instead of the default
1080: @file{gforth.fi} (@pxref{Image Files}).
1.21 crook 1081:
1.39 anton 1082: @cindex --appl-image, command-line option
1083: @item --appl-image @i{file}
1084: Loads the image @i{file} and leaves all further command-line arguments
1.65 anton 1085: to the image (instead of processing them as engine options). This is
1086: useful for building executable application images on Unix, built with
1.39 anton 1087: @code{gforthmi --application ...}.
1088:
1.29 crook 1089: @cindex --path, command-line option
1090: @cindex -p, command-line option
1091: @item --path @i{path}
1092: @itemx -p @i{path}
1093: Uses @i{path} for searching the image file and Forth source code files
1094: instead of the default in the environment variable @code{GFORTHPATH} or
1095: the path specified at installation time (e.g.,
1096: @file{/usr/local/share/gforth/0.2.0:.}). A path is given as a list of
1097: directories, separated by @samp{:} (on Unix) or @samp{;} (on other OSs).
1.21 crook 1098:
1.29 crook 1099: @cindex --dictionary-size, command-line option
1100: @cindex -m, command-line option
1101: @cindex @i{size} parameters for command-line options
1102: @cindex size of the dictionary and the stacks
1103: @item --dictionary-size @i{size}
1104: @itemx -m @i{size}
1105: Allocate @i{size} space for the Forth dictionary space instead of
1106: using the default specified in the image (typically 256K). The
1107: @i{size} specification for this and subsequent options consists of
1108: an integer and a unit (e.g.,
1109: @code{4M}). The unit can be one of @code{b} (bytes), @code{e} (element
1110: size, in this case Cells), @code{k} (kilobytes), @code{M} (Megabytes),
1111: @code{G} (Gigabytes), and @code{T} (Terabytes). If no unit is specified,
1112: @code{e} is used.
1.21 crook 1113:
1.29 crook 1114: @cindex --data-stack-size, command-line option
1115: @cindex -d, command-line option
1116: @item --data-stack-size @i{size}
1117: @itemx -d @i{size}
1118: Allocate @i{size} space for the data stack instead of using the
1119: default specified in the image (typically 16K).
1.21 crook 1120:
1.29 crook 1121: @cindex --return-stack-size, command-line option
1122: @cindex -r, command-line option
1123: @item --return-stack-size @i{size}
1124: @itemx -r @i{size}
1125: Allocate @i{size} space for the return stack instead of using the
1126: default specified in the image (typically 15K).
1.21 crook 1127:
1.29 crook 1128: @cindex --fp-stack-size, command-line option
1129: @cindex -f, command-line option
1130: @item --fp-stack-size @i{size}
1131: @itemx -f @i{size}
1132: Allocate @i{size} space for the floating point stack instead of
1133: using the default specified in the image (typically 15.5K). In this case
1134: the unit specifier @code{e} refers to floating point numbers.
1.21 crook 1135:
1.48 anton 1136: @cindex --locals-stack-size, command-line option
1137: @cindex -l, command-line option
1138: @item --locals-stack-size @i{size}
1139: @itemx -l @i{size}
1140: Allocate @i{size} space for the locals stack instead of using the
1141: default specified in the image (typically 14.5K).
1142:
1143: @cindex -h, command-line option
1144: @cindex --help, command-line option
1145: @item --help
1146: @itemx -h
1147: Print a message about the command-line options
1148:
1149: @cindex -v, command-line option
1150: @cindex --version, command-line option
1151: @item --version
1152: @itemx -v
1153: Print version and exit
1154:
1155: @cindex --debug, command-line option
1156: @item --debug
1157: Print some information useful for debugging on startup.
1158:
1159: @cindex --offset-image, command-line option
1160: @item --offset-image
1161: Start the dictionary at a slightly different position than would be used
1162: otherwise (useful for creating data-relocatable images,
1163: @pxref{Data-Relocatable Image Files}).
1164:
1165: @cindex --no-offset-im, command-line option
1166: @item --no-offset-im
1167: Start the dictionary at the normal position.
1168:
1169: @cindex --clear-dictionary, command-line option
1170: @item --clear-dictionary
1171: Initialize all bytes in the dictionary to 0 before loading the image
1172: (@pxref{Data-Relocatable Image Files}).
1173:
1174: @cindex --die-on-signal, command-line-option
1175: @item --die-on-signal
1176: Normally Gforth handles most signals (e.g., the user interrupt SIGINT,
1177: or the segmentation violation SIGSEGV) by translating it into a Forth
1178: @code{THROW}. With this option, Gforth exits if it receives such a
1179: signal. This option is useful when the engine and/or the image might be
1180: severely broken (such that it causes another signal before recovering
1181: from the first); this option avoids endless loops in such cases.
1.109 ! anton 1182:
! 1183: @item --no-dynamic
! 1184: @item --dynamic
! 1185: Disable or enable dynamic superinstructions with replication
! 1186: (@pxref{Dynamic Superinstructions}).
! 1187:
! 1188: @item --no-super
! 1189: Disable dynamic superinstructions, use just dynamic replication
! 1190: (@pxref{Dynamic Superinstructions}).
! 1191:
1.48 anton 1192: @end table
1193:
1194: @cindex loading files at startup
1195: @cindex executing code on startup
1196: @cindex batch processing with Gforth
1197: As explained above, the image-specific command-line arguments for the
1198: default image @file{gforth.fi} consist of a sequence of filenames and
1199: @code{-e @var{forth-code}} options that are interpreted in the sequence
1200: in which they are given. The @code{-e @var{forth-code}} or
1201: @code{--evaluate @var{forth-code}} option evaluates the Forth
1202: code. This option takes only one argument; if you want to evaluate more
1203: Forth words, you have to quote them or use @code{-e} several times. To exit
1204: after processing the command line (instead of entering interactive mode)
1205: append @code{-e bye} to the command line.
1206:
1207: @cindex versions, invoking other versions of Gforth
1208: If you have several versions of Gforth installed, @code{gforth} will
1209: invoke the version that was installed last. @code{gforth-@i{version}}
1210: invokes a specific version. If your environment contains the variable
1211: @code{GFORTHPATH}, you may want to override it by using the
1212: @code{--path} option.
1213:
1214: Not yet implemented:
1215: On startup the system first executes the system initialization file
1216: (unless the option @code{--no-init-file} is given; note that the system
1217: resulting from using this option may not be ANS Forth conformant). Then
1218: the user initialization file @file{.gforth.fs} is executed, unless the
1.62 crook 1219: option @code{--no-rc} is given; this file is searched for in @file{.},
1.48 anton 1220: then in @file{~}, then in the normal path (see above).
1221:
1222:
1223:
1224: @comment ----------------------------------------------
1225: @node Leaving Gforth, Command-line editing, Invoking Gforth, Gforth Environment
1226: @section Leaving Gforth
1227: @cindex Gforth - leaving
1228: @cindex leaving Gforth
1229:
1230: You can leave Gforth by typing @code{bye} or @kbd{Ctrl-d} (at the start
1231: of a line) or (if you invoked Gforth with the @code{--die-on-signal}
1232: option) @kbd{Ctrl-c}. When you leave Gforth, all of your definitions and
1.49 anton 1233: data are discarded. For ways of saving the state of the system before
1234: leaving Gforth see @ref{Image Files}.
1.48 anton 1235:
1236: doc-bye
1237:
1238:
1239: @comment ----------------------------------------------
1.65 anton 1240: @node Command-line editing, Environment variables, Leaving Gforth, Gforth Environment
1.48 anton 1241: @section Command-line editing
1242: @cindex command-line editing
1243:
1244: Gforth maintains a history file that records every line that you type to
1245: the text interpreter. This file is preserved between sessions, and is
1246: used to provide a command-line recall facility; if you type @kbd{Ctrl-P}
1247: repeatedly you can recall successively older commands from this (or
1248: previous) session(s). The full list of command-line editing facilities is:
1249:
1250: @itemize @bullet
1251: @item
1252: @kbd{Ctrl-p} (``previous'') (or up-arrow) to recall successively older
1253: commands from the history buffer.
1254: @item
1255: @kbd{Ctrl-n} (``next'') (or down-arrow) to recall successively newer commands
1256: from the history buffer.
1257: @item
1258: @kbd{Ctrl-f} (or right-arrow) to move the cursor right, non-destructively.
1259: @item
1260: @kbd{Ctrl-b} (or left-arrow) to move the cursor left, non-destructively.
1261: @item
1262: @kbd{Ctrl-h} (backspace) to delete the character to the left of the cursor,
1263: closing up the line.
1264: @item
1265: @kbd{Ctrl-k} to delete (``kill'') from the cursor to the end of the line.
1266: @item
1267: @kbd{Ctrl-a} to move the cursor to the start of the line.
1268: @item
1269: @kbd{Ctrl-e} to move the cursor to the end of the line.
1270: @item
1271: @key{RET} (@kbd{Ctrl-m}) or @key{LFD} (@kbd{Ctrl-j}) to submit the current
1272: line.
1273: @item
1274: @key{TAB} to step through all possible full-word completions of the word
1275: currently being typed.
1276: @item
1.65 anton 1277: @kbd{Ctrl-d} on an empty line line to terminate Gforth (gracefully,
1278: using @code{bye}).
1279: @item
1280: @kbd{Ctrl-x} (or @code{Ctrl-d} on a non-empty line) to delete the
1281: character under the cursor.
1.48 anton 1282: @end itemize
1283:
1284: When editing, displayable characters are inserted to the left of the
1285: cursor position; the line is always in ``insert'' (as opposed to
1286: ``overstrike'') mode.
1287:
1288: @cindex history file
1289: @cindex @file{.gforth-history}
1290: On Unix systems, the history file is @file{~/.gforth-history} by
1291: default@footnote{i.e. it is stored in the user's home directory.}. You
1292: can find out the name and location of your history file using:
1293:
1294: @example
1295: history-file type \ Unix-class systems
1296:
1297: history-file type \ Other systems
1298: history-dir type
1299: @end example
1300:
1301: If you enter long definitions by hand, you can use a text editor to
1302: paste them out of the history file into a Forth source file for reuse at
1303: a later time.
1304:
1305: Gforth never trims the size of the history file, so you should do this
1306: periodically, if necessary.
1307:
1308: @comment this is all defined in history.fs
1309: @comment NAC TODO the ctrl-D behaviour can either do a bye or a beep.. how is that option
1310: @comment chosen?
1311:
1312:
1313: @comment ----------------------------------------------
1.65 anton 1314: @node Environment variables, Gforth Files, Command-line editing, Gforth Environment
1.48 anton 1315: @section Environment variables
1316: @cindex environment variables
1317:
1318: Gforth uses these environment variables:
1319:
1320: @itemize @bullet
1321: @item
1322: @cindex @code{GFORTHHIST} -- environment variable
1323: @code{GFORTHHIST} -- (Unix systems only) specifies the directory in which to
1324: open/create the history file, @file{.gforth-history}. Default:
1325: @code{$HOME}.
1326:
1327: @item
1328: @cindex @code{GFORTHPATH} -- environment variable
1329: @code{GFORTHPATH} -- specifies the path used when searching for the gforth image file and
1330: for Forth source-code files.
1331:
1332: @item
1333: @cindex @code{GFORTH} -- environment variable
1.49 anton 1334: @code{GFORTH} -- used by @file{gforthmi}, @xref{gforthmi}.
1.48 anton 1335:
1336: @item
1337: @cindex @code{GFORTHD} -- environment variable
1.62 crook 1338: @code{GFORTHD} -- used by @file{gforthmi}, @xref{gforthmi}.
1.48 anton 1339:
1340: @item
1341: @cindex @code{TMP}, @code{TEMP} - environment variable
1342: @code{TMP}, @code{TEMP} - (non-Unix systems only) used as a potential
1343: location for the history file.
1344: @end itemize
1345:
1346: @comment also POSIXELY_CORRECT LINES COLUMNS HOME but no interest in
1347: @comment mentioning these.
1348:
1349: All the Gforth environment variables default to sensible values if they
1350: are not set.
1351:
1352:
1353: @comment ----------------------------------------------
1354: @node Gforth Files, Startup speed, Environment variables, Gforth Environment
1355: @section Gforth files
1356: @cindex Gforth files
1357:
1358: When you install Gforth on a Unix system, it installs files in these
1359: locations by default:
1360:
1361: @itemize @bullet
1362: @item
1363: @file{/usr/local/bin/gforth}
1364: @item
1365: @file{/usr/local/bin/gforthmi}
1366: @item
1367: @file{/usr/local/man/man1/gforth.1} - man page.
1368: @item
1369: @file{/usr/local/info} - the Info version of this manual.
1370: @item
1371: @file{/usr/local/lib/gforth/<version>/...} - Gforth @file{.fi} files.
1372: @item
1373: @file{/usr/local/share/gforth/<version>/TAGS} - Emacs TAGS file.
1374: @item
1375: @file{/usr/local/share/gforth/<version>/...} - Gforth source files.
1376: @item
1377: @file{.../emacs/site-lisp/gforth.el} - Emacs gforth mode.
1378: @end itemize
1379:
1380: You can select different places for installation by using
1381: @code{configure} options (listed with @code{configure --help}).
1382:
1383: @comment ----------------------------------------------
1384: @node Startup speed, , Gforth Files, Gforth Environment
1385: @section Startup speed
1386: @cindex Startup speed
1387: @cindex speed, startup
1388:
1389: If Gforth is used for CGI scripts or in shell scripts, its startup
1390: speed may become a problem. On a 300MHz 21064a under Linux-2.2.13 with
1391: glibc-2.0.7, @code{gforth -e bye} takes about 24.6ms user and 11.3ms
1392: system time.
1393:
1394: If startup speed is a problem, you may consider the following ways to
1395: improve it; or you may consider ways to reduce the number of startups
1.62 crook 1396: (for example, by using Fast-CGI).
1.48 anton 1397:
1398: The first step to improve startup speed is to statically link Gforth, by
1399: building it with @code{XLDFLAGS=-static}. This requires more memory for
1400: the code and will therefore slow down the first invocation, but
1401: subsequent invocations avoid the dynamic linking overhead. Another
1402: disadvantage is that Gforth won't profit from library upgrades. As a
1403: result, @code{gforth-static -e bye} takes about 17.1ms user and
1404: 8.2ms system time.
1405:
1406: The next step to improve startup speed is to use a non-relocatable image
1.65 anton 1407: (@pxref{Non-Relocatable Image Files}). You can create this image with
1.48 anton 1408: @code{gforth -e "savesystem gforthnr.fi bye"} and later use it with
1409: @code{gforth -i gforthnr.fi ...}. This avoids the relocation overhead
1410: and a part of the copy-on-write overhead. The disadvantage is that the
1.62 crook 1411: non-relocatable image does not work if the OS gives Gforth a different
1.48 anton 1412: address for the dictionary, for whatever reason; so you better provide a
1413: fallback on a relocatable image. @code{gforth-static -i gforthnr.fi -e
1414: bye} takes about 15.3ms user and 7.5ms system time.
1415:
1416: The final step is to disable dictionary hashing in Gforth. Gforth
1417: builds the hash table on startup, which takes much of the startup
1418: overhead. You can do this by commenting out the @code{include hash.fs}
1419: in @file{startup.fs} and everything that requires @file{hash.fs} (at the
1420: moment @file{table.fs} and @file{ekey.fs}) and then doing @code{make}.
1421: The disadvantages are that functionality like @code{table} and
1422: @code{ekey} is missing and that text interpretation (e.g., compiling)
1423: now takes much longer. So, you should only use this method if there is
1424: no significant text interpretation to perform (the script should be
1.62 crook 1425: compiled into the image, amongst other things). @code{gforth-static -i
1.48 anton 1426: gforthnrnh.fi -e bye} takes about 2.1ms user and 6.1ms system time.
1427:
1428: @c ******************************************************************
1429: @node Tutorial, Introduction, Gforth Environment, Top
1430: @chapter Forth Tutorial
1431: @cindex Tutorial
1432: @cindex Forth Tutorial
1433:
1.67 anton 1434: @c Topics from nac's Introduction that could be mentioned:
1435: @c press <ret> after each line
1436: @c Prompt
1437: @c numbers vs. words in dictionary on text interpretation
1438: @c what happens on redefinition
1439: @c parsing words (in particular, defining words)
1440:
1.83 anton 1441: The difference of this chapter from the Introduction
1442: (@pxref{Introduction}) is that this tutorial is more fast-paced, should
1443: be used while sitting in front of a computer, and covers much more
1444: material, but does not explain how the Forth system works.
1445:
1.62 crook 1446: This tutorial can be used with any ANS-compliant Forth; any
1447: Gforth-specific features are marked as such and you can skip them if you
1448: work with another Forth. This tutorial does not explain all features of
1449: Forth, just enough to get you started and give you some ideas about the
1450: facilities available in Forth. Read the rest of the manual and the
1451: standard when you are through this.
1.48 anton 1452:
1453: The intended way to use this tutorial is that you work through it while
1454: sitting in front of the console, take a look at the examples and predict
1455: what they will do, then try them out; if the outcome is not as expected,
1456: find out why (e.g., by trying out variations of the example), so you
1457: understand what's going on. There are also some assignments that you
1458: should solve.
1459:
1460: This tutorial assumes that you have programmed before and know what,
1461: e.g., a loop is.
1462:
1463: @c !! explain compat library
1464:
1465: @menu
1466: * Starting Gforth Tutorial::
1467: * Syntax Tutorial::
1468: * Crash Course Tutorial::
1469: * Stack Tutorial::
1470: * Arithmetics Tutorial::
1471: * Stack Manipulation Tutorial::
1472: * Using files for Forth code Tutorial::
1473: * Comments Tutorial::
1474: * Colon Definitions Tutorial::
1475: * Decompilation Tutorial::
1476: * Stack-Effect Comments Tutorial::
1477: * Types Tutorial::
1478: * Factoring Tutorial::
1479: * Designing the stack effect Tutorial::
1480: * Local Variables Tutorial::
1481: * Conditional execution Tutorial::
1482: * Flags and Comparisons Tutorial::
1483: * General Loops Tutorial::
1484: * Counted loops Tutorial::
1485: * Recursion Tutorial::
1486: * Leaving definitions or loops Tutorial::
1487: * Return Stack Tutorial::
1488: * Memory Tutorial::
1489: * Characters and Strings Tutorial::
1490: * Alignment Tutorial::
1.87 anton 1491: * Files Tutorial::
1.48 anton 1492: * Interpretation and Compilation Semantics and Immediacy Tutorial::
1493: * Execution Tokens Tutorial::
1494: * Exceptions Tutorial::
1495: * Defining Words Tutorial::
1496: * Arrays and Records Tutorial::
1497: * POSTPONE Tutorial::
1498: * Literal Tutorial::
1499: * Advanced macros Tutorial::
1500: * Compilation Tokens Tutorial::
1501: * Wordlists and Search Order Tutorial::
1502: @end menu
1503:
1504: @node Starting Gforth Tutorial, Syntax Tutorial, Tutorial, Tutorial
1505: @section Starting Gforth
1.66 anton 1506: @cindex starting Gforth tutorial
1.48 anton 1507: You can start Gforth by typing its name:
1508:
1509: @example
1510: gforth
1511: @end example
1512:
1513: That puts you into interactive mode; you can leave Gforth by typing
1514: @code{bye}. While in Gforth, you can edit the command line and access
1515: the command line history with cursor keys, similar to bash.
1516:
1517:
1518: @node Syntax Tutorial, Crash Course Tutorial, Starting Gforth Tutorial, Tutorial
1519: @section Syntax
1.66 anton 1520: @cindex syntax tutorial
1.48 anton 1521:
1522: A @dfn{word} is a sequence of arbitrary characters (expcept white
1523: space). Words are separated by white space. E.g., each of the
1524: following lines contains exactly one word:
1525:
1526: @example
1527: word
1528: !@@#$%^&*()
1529: 1234567890
1530: 5!a
1531: @end example
1532:
1533: A frequent beginner's error is to leave away necessary white space,
1534: resulting in an error like @samp{Undefined word}; so if you see such an
1535: error, check if you have put spaces wherever necessary.
1536:
1537: @example
1538: ." hello, world" \ correct
1539: ."hello, world" \ gives an "Undefined word" error
1540: @end example
1541:
1.65 anton 1542: Gforth and most other Forth systems ignore differences in case (they are
1.48 anton 1543: case-insensitive), i.e., @samp{word} is the same as @samp{Word}. If
1544: your system is case-sensitive, you may have to type all the examples
1545: given here in upper case.
1546:
1547:
1548: @node Crash Course Tutorial, Stack Tutorial, Syntax Tutorial, Tutorial
1549: @section Crash Course
1550:
1551: Type
1552:
1553: @example
1554: 0 0 !
1555: here execute
1556: ' catch >body 20 erase abort
1557: ' (quit) >body 20 erase
1558: @end example
1559:
1560: The last two examples are guaranteed to destroy parts of Gforth (and
1561: most other systems), so you better leave Gforth afterwards (if it has
1562: not finished by itself). On some systems you may have to kill gforth
1563: from outside (e.g., in Unix with @code{kill}).
1564:
1565: Now that you know how to produce crashes (and that there's not much to
1566: them), let's learn how to produce meaningful programs.
1567:
1568:
1569: @node Stack Tutorial, Arithmetics Tutorial, Crash Course Tutorial, Tutorial
1570: @section Stack
1.66 anton 1571: @cindex stack tutorial
1.48 anton 1572:
1573: The most obvious feature of Forth is the stack. When you type in a
1574: number, it is pushed on the stack. You can display the content of the
1575: stack with @code{.s}.
1576:
1577: @example
1578: 1 2 .s
1579: 3 .s
1580: @end example
1581:
1582: @code{.s} displays the top-of-stack to the right, i.e., the numbers
1583: appear in @code{.s} output as they appeared in the input.
1584:
1585: You can print the top of stack element with @code{.}.
1586:
1587: @example
1588: 1 2 3 . . .
1589: @end example
1590:
1591: In general, words consume their stack arguments (@code{.s} is an
1592: exception).
1593:
1594: @assignment
1595: What does the stack contain after @code{5 6 7 .}?
1596: @endassignment
1597:
1598:
1599: @node Arithmetics Tutorial, Stack Manipulation Tutorial, Stack Tutorial, Tutorial
1600: @section Arithmetics
1.66 anton 1601: @cindex arithmetics tutorial
1.48 anton 1602:
1603: The words @code{+}, @code{-}, @code{*}, @code{/}, and @code{mod} always
1604: operate on the top two stack items:
1605:
1606: @example
1.67 anton 1607: 2 2 .s
1608: + .s
1609: .
1.48 anton 1610: 2 1 - .
1611: 7 3 mod .
1612: @end example
1613:
1614: The operands of @code{-}, @code{/}, and @code{mod} are in the same order
1615: as in the corresponding infix expression (this is generally the case in
1616: Forth).
1617:
1618: Parentheses are superfluous (and not available), because the order of
1619: the words unambiguously determines the order of evaluation and the
1620: operands:
1621:
1622: @example
1623: 3 4 + 5 * .
1624: 3 4 5 * + .
1625: @end example
1626:
1627: @assignment
1628: What are the infix expressions corresponding to the Forth code above?
1629: Write @code{6-7*8+9} in Forth notation@footnote{This notation is also
1630: known as Postfix or RPN (Reverse Polish Notation).}.
1631: @endassignment
1632:
1633: To change the sign, use @code{negate}:
1634:
1635: @example
1636: 2 negate .
1637: @end example
1638:
1639: @assignment
1640: Convert -(-3)*4-5 to Forth.
1641: @endassignment
1642:
1643: @code{/mod} performs both @code{/} and @code{mod}.
1644:
1645: @example
1646: 7 3 /mod . .
1647: @end example
1648:
1.66 anton 1649: Reference: @ref{Arithmetic}.
1650:
1651:
1.48 anton 1652: @node Stack Manipulation Tutorial, Using files for Forth code Tutorial, Arithmetics Tutorial, Tutorial
1653: @section Stack Manipulation
1.66 anton 1654: @cindex stack manipulation tutorial
1.48 anton 1655:
1656: Stack manipulation words rearrange the data on the stack.
1657:
1658: @example
1659: 1 .s drop .s
1660: 1 .s dup .s drop drop .s
1661: 1 2 .s over .s drop drop drop
1662: 1 2 .s swap .s drop drop
1663: 1 2 3 .s rot .s drop drop drop
1664: @end example
1665:
1666: These are the most important stack manipulation words. There are also
1667: variants that manipulate twice as many stack items:
1668:
1669: @example
1670: 1 2 3 4 .s 2swap .s 2drop 2drop
1671: @end example
1672:
1673: Two more stack manipulation words are:
1674:
1675: @example
1676: 1 2 .s nip .s drop
1677: 1 2 .s tuck .s 2drop drop
1678: @end example
1679:
1680: @assignment
1681: Replace @code{nip} and @code{tuck} with combinations of other stack
1682: manipulation words.
1683:
1684: @example
1685: Given: How do you get:
1686: 1 2 3 3 2 1
1687: 1 2 3 1 2 3 2
1688: 1 2 3 1 2 3 3
1689: 1 2 3 1 3 3
1690: 1 2 3 2 1 3
1691: 1 2 3 4 4 3 2 1
1692: 1 2 3 1 2 3 1 2 3
1693: 1 2 3 4 1 2 3 4 1 2
1694: 1 2 3
1695: 1 2 3 1 2 3 4
1696: 1 2 3 1 3
1697: @end example
1698: @endassignment
1699:
1700: @example
1701: 5 dup * .
1702: @end example
1703:
1704: @assignment
1705: Write 17^3 and 17^4 in Forth, without writing @code{17} more than once.
1706: Write a piece of Forth code that expects two numbers on the stack
1707: (@var{a} and @var{b}, with @var{b} on top) and computes
1708: @code{(a-b)(a+1)}.
1709: @endassignment
1710:
1.66 anton 1711: Reference: @ref{Stack Manipulation}.
1712:
1713:
1.48 anton 1714: @node Using files for Forth code Tutorial, Comments Tutorial, Stack Manipulation Tutorial, Tutorial
1715: @section Using files for Forth code
1.66 anton 1716: @cindex loading Forth code, tutorial
1717: @cindex files containing Forth code, tutorial
1.48 anton 1718:
1719: While working at the Forth command line is convenient for one-line
1720: examples and short one-off code, you probably want to store your source
1721: code in files for convenient editing and persistence. You can use your
1722: favourite editor (Gforth includes Emacs support, @pxref{Emacs and
1.102 anton 1723: Gforth}) to create @var{file.fs} and use
1.48 anton 1724:
1725: @example
1.102 anton 1726: s" @var{file.fs}" included
1.48 anton 1727: @end example
1728:
1729: to load it into your Forth system. The file name extension I use for
1730: Forth files is @samp{.fs}.
1731:
1732: You can easily start Gforth with some files loaded like this:
1733:
1734: @example
1.102 anton 1735: gforth @var{file1.fs} @var{file2.fs}
1.48 anton 1736: @end example
1737:
1738: If an error occurs during loading these files, Gforth terminates,
1739: whereas an error during @code{INCLUDED} within Gforth usually gives you
1740: a Gforth command line. Starting the Forth system every time gives you a
1741: clean start every time, without interference from the results of earlier
1742: tries.
1743:
1744: I often put all the tests in a file, then load the code and run the
1745: tests with
1746:
1747: @example
1.102 anton 1748: gforth @var{code.fs} @var{tests.fs} -e bye
1.48 anton 1749: @end example
1750:
1751: (often by performing this command with @kbd{C-x C-e} in Emacs). The
1752: @code{-e bye} ensures that Gforth terminates afterwards so that I can
1753: restart this command without ado.
1754:
1755: The advantage of this approach is that the tests can be repeated easily
1756: every time the program ist changed, making it easy to catch bugs
1757: introduced by the change.
1758:
1.66 anton 1759: Reference: @ref{Forth source files}.
1760:
1.48 anton 1761:
1762: @node Comments Tutorial, Colon Definitions Tutorial, Using files for Forth code Tutorial, Tutorial
1763: @section Comments
1.66 anton 1764: @cindex comments tutorial
1.48 anton 1765:
1766: @example
1767: \ That's a comment; it ends at the end of the line
1768: ( Another comment; it ends here: ) .s
1769: @end example
1770:
1771: @code{\} and @code{(} are ordinary Forth words and therefore have to be
1772: separated with white space from the following text.
1773:
1774: @example
1775: \This gives an "Undefined word" error
1776: @end example
1777:
1778: The first @code{)} ends a comment started with @code{(}, so you cannot
1779: nest @code{(}-comments; and you cannot comment out text containing a
1780: @code{)} with @code{( ... )}@footnote{therefore it's a good idea to
1781: avoid @code{)} in word names.}.
1782:
1783: I use @code{\}-comments for descriptive text and for commenting out code
1784: of one or more line; I use @code{(}-comments for describing the stack
1785: effect, the stack contents, or for commenting out sub-line pieces of
1786: code.
1787:
1788: The Emacs mode @file{gforth.el} (@pxref{Emacs and Gforth}) supports
1789: these uses by commenting out a region with @kbd{C-x \}, uncommenting a
1790: region with @kbd{C-u C-x \}, and filling a @code{\}-commented region
1791: with @kbd{M-q}.
1792:
1.66 anton 1793: Reference: @ref{Comments}.
1794:
1.48 anton 1795:
1796: @node Colon Definitions Tutorial, Decompilation Tutorial, Comments Tutorial, Tutorial
1797: @section Colon Definitions
1.66 anton 1798: @cindex colon definitions, tutorial
1799: @cindex definitions, tutorial
1800: @cindex procedures, tutorial
1801: @cindex functions, tutorial
1.48 anton 1802:
1803: are similar to procedures and functions in other programming languages.
1804:
1805: @example
1806: : squared ( n -- n^2 )
1807: dup * ;
1808: 5 squared .
1809: 7 squared .
1810: @end example
1811:
1812: @code{:} starts the colon definition; its name is @code{squared}. The
1813: following comment describes its stack effect. The words @code{dup *}
1814: are not executed, but compiled into the definition. @code{;} ends the
1815: colon definition.
1816:
1817: The newly-defined word can be used like any other word, including using
1818: it in other definitions:
1819:
1820: @example
1821: : cubed ( n -- n^3 )
1822: dup squared * ;
1823: -5 cubed .
1824: : fourth-power ( n -- n^4 )
1825: squared squared ;
1826: 3 fourth-power .
1827: @end example
1828:
1829: @assignment
1830: Write colon definitions for @code{nip}, @code{tuck}, @code{negate}, and
1831: @code{/mod} in terms of other Forth words, and check if they work (hint:
1832: test your tests on the originals first). Don't let the
1833: @samp{redefined}-Messages spook you, they are just warnings.
1834: @endassignment
1835:
1.66 anton 1836: Reference: @ref{Colon Definitions}.
1837:
1.48 anton 1838:
1839: @node Decompilation Tutorial, Stack-Effect Comments Tutorial, Colon Definitions Tutorial, Tutorial
1840: @section Decompilation
1.66 anton 1841: @cindex decompilation tutorial
1842: @cindex see tutorial
1.48 anton 1843:
1844: You can decompile colon definitions with @code{see}:
1845:
1846: @example
1847: see squared
1848: see cubed
1849: @end example
1850:
1851: In Gforth @code{see} shows you a reconstruction of the source code from
1852: the executable code. Informations that were present in the source, but
1853: not in the executable code, are lost (e.g., comments).
1854:
1.65 anton 1855: You can also decompile the predefined words:
1856:
1857: @example
1858: see .
1859: see +
1860: @end example
1861:
1862:
1.48 anton 1863: @node Stack-Effect Comments Tutorial, Types Tutorial, Decompilation Tutorial, Tutorial
1864: @section Stack-Effect Comments
1.66 anton 1865: @cindex stack-effect comments, tutorial
1866: @cindex --, tutorial
1.48 anton 1867: By convention the comment after the name of a definition describes the
1868: stack effect: The part in from of the @samp{--} describes the state of
1869: the stack before the execution of the definition, i.e., the parameters
1870: that are passed into the colon definition; the part behind the @samp{--}
1871: is the state of the stack after the execution of the definition, i.e.,
1872: the results of the definition. The stack comment only shows the top
1873: stack items that the definition accesses and/or changes.
1874:
1875: You should put a correct stack effect on every definition, even if it is
1876: just @code{( -- )}. You should also add some descriptive comment to
1877: more complicated words (I usually do this in the lines following
1878: @code{:}). If you don't do this, your code becomes unreadable (because
1879: you have to work through every definition before you can undertsand
1880: any).
1881:
1882: @assignment
1883: The stack effect of @code{swap} can be written like this: @code{x1 x2 --
1884: x2 x1}. Describe the stack effect of @code{-}, @code{drop}, @code{dup},
1885: @code{over}, @code{rot}, @code{nip}, and @code{tuck}. Hint: When you
1.65 anton 1886: are done, you can compare your stack effects to those in this manual
1.48 anton 1887: (@pxref{Word Index}).
1888: @endassignment
1889:
1890: Sometimes programmers put comments at various places in colon
1891: definitions that describe the contents of the stack at that place (stack
1892: comments); i.e., they are like the first part of a stack-effect
1893: comment. E.g.,
1894:
1895: @example
1896: : cubed ( n -- n^3 )
1897: dup squared ( n n^2 ) * ;
1898: @end example
1899:
1900: In this case the stack comment is pretty superfluous, because the word
1901: is simple enough. If you think it would be a good idea to add such a
1902: comment to increase readability, you should also consider factoring the
1903: word into several simpler words (@pxref{Factoring Tutorial,,
1.60 anton 1904: Factoring}), which typically eliminates the need for the stack comment;
1.48 anton 1905: however, if you decide not to refactor it, then having such a comment is
1906: better than not having it.
1907:
1908: The names of the stack items in stack-effect and stack comments in the
1909: standard, in this manual, and in many programs specify the type through
1910: a type prefix, similar to Fortran and Hungarian notation. The most
1911: frequent prefixes are:
1912:
1913: @table @code
1914: @item n
1915: signed integer
1916: @item u
1917: unsigned integer
1918: @item c
1919: character
1920: @item f
1921: Boolean flags, i.e. @code{false} or @code{true}.
1922: @item a-addr,a-
1923: Cell-aligned address
1924: @item c-addr,c-
1925: Char-aligned address (note that a Char may have two bytes in Windows NT)
1926: @item xt
1927: Execution token, same size as Cell
1928: @item w,x
1929: Cell, can contain an integer or an address. It usually takes 32, 64 or
1930: 16 bits (depending on your platform and Forth system). A cell is more
1931: commonly known as machine word, but the term @emph{word} already means
1932: something different in Forth.
1933: @item d
1934: signed double-cell integer
1935: @item ud
1936: unsigned double-cell integer
1937: @item r
1938: Float (on the FP stack)
1939: @end table
1940:
1941: You can find a more complete list in @ref{Notation}.
1942:
1943: @assignment
1944: Write stack-effect comments for all definitions you have written up to
1945: now.
1946: @endassignment
1947:
1948:
1949: @node Types Tutorial, Factoring Tutorial, Stack-Effect Comments Tutorial, Tutorial
1950: @section Types
1.66 anton 1951: @cindex types tutorial
1.48 anton 1952:
1953: In Forth the names of the operations are not overloaded; so similar
1954: operations on different types need different names; e.g., @code{+} adds
1955: integers, and you have to use @code{f+} to add floating-point numbers.
1956: The following prefixes are often used for related operations on
1957: different types:
1958:
1959: @table @code
1960: @item (none)
1961: signed integer
1962: @item u
1963: unsigned integer
1964: @item c
1965: character
1966: @item d
1967: signed double-cell integer
1968: @item ud, du
1969: unsigned double-cell integer
1970: @item 2
1971: two cells (not-necessarily double-cell numbers)
1972: @item m, um
1973: mixed single-cell and double-cell operations
1974: @item f
1975: floating-point (note that in stack comments @samp{f} represents flags,
1.66 anton 1976: and @samp{r} represents FP numbers).
1.48 anton 1977: @end table
1978:
1979: If there are no differences between the signed and the unsigned variant
1980: (e.g., for @code{+}), there is only the prefix-less variant.
1981:
1982: Forth does not perform type checking, neither at compile time, nor at
1983: run time. If you use the wrong oeration, the data are interpreted
1984: incorrectly:
1985:
1986: @example
1987: -1 u.
1988: @end example
1989:
1990: If you have only experience with type-checked languages until now, and
1991: have heard how important type-checking is, don't panic! In my
1992: experience (and that of other Forthers), type errors in Forth code are
1993: usually easy to find (once you get used to it), the increased vigilance
1994: of the programmer tends to catch some harder errors in addition to most
1995: type errors, and you never have to work around the type system, so in
1996: most situations the lack of type-checking seems to be a win (projects to
1997: add type checking to Forth have not caught on).
1998:
1999:
2000: @node Factoring Tutorial, Designing the stack effect Tutorial, Types Tutorial, Tutorial
2001: @section Factoring
1.66 anton 2002: @cindex factoring tutorial
1.48 anton 2003:
2004: If you try to write longer definitions, you will soon find it hard to
2005: keep track of the stack contents. Therefore, good Forth programmers
2006: tend to write only short definitions (e.g., three lines). The art of
2007: finding meaningful short definitions is known as factoring (as in
2008: factoring polynomials).
2009:
2010: Well-factored programs offer additional advantages: smaller, more
2011: general words, are easier to test and debug and can be reused more and
2012: better than larger, specialized words.
2013:
2014: So, if you run into difficulties with stack management, when writing
2015: code, try to define meaningful factors for the word, and define the word
2016: in terms of those. Even if a factor contains only two words, it is
2017: often helpful.
2018:
1.65 anton 2019: Good factoring is not easy, and it takes some practice to get the knack
2020: for it; but even experienced Forth programmers often don't find the
2021: right solution right away, but only when rewriting the program. So, if
2022: you don't come up with a good solution immediately, keep trying, don't
2023: despair.
1.48 anton 2024:
2025: @c example !!
2026:
2027:
2028: @node Designing the stack effect Tutorial, Local Variables Tutorial, Factoring Tutorial, Tutorial
2029: @section Designing the stack effect
1.66 anton 2030: @cindex Stack effect design, tutorial
2031: @cindex design of stack effects, tutorial
1.48 anton 2032:
2033: In other languages you can use an arbitrary order of parameters for a
1.65 anton 2034: function; and since there is only one result, you don't have to deal with
1.48 anton 2035: the order of results, either.
2036:
2037: In Forth (and other stack-based languages, e.g., Postscript) the
2038: parameter and result order of a definition is important and should be
2039: designed well. The general guideline is to design the stack effect such
2040: that the word is simple to use in most cases, even if that complicates
2041: the implementation of the word. Some concrete rules are:
2042:
2043: @itemize @bullet
2044:
2045: @item
2046: Words consume all of their parameters (e.g., @code{.}).
2047:
2048: @item
2049: If there is a convention on the order of parameters (e.g., from
2050: mathematics or another programming language), stick with it (e.g.,
2051: @code{-}).
2052:
2053: @item
2054: If one parameter usually requires only a short computation (e.g., it is
2055: a constant), pass it on the top of the stack. Conversely, parameters
2056: that usually require a long sequence of code to compute should be passed
2057: as the bottom (i.e., first) parameter. This makes the code easier to
2058: read, because reader does not need to keep track of the bottom item
2059: through a long sequence of code (or, alternatively, through stack
1.49 anton 2060: manipulations). E.g., @code{!} (store, @pxref{Memory}) expects the
1.48 anton 2061: address on top of the stack because it is usually simpler to compute
2062: than the stored value (often the address is just a variable).
2063:
2064: @item
2065: Similarly, results that are usually consumed quickly should be returned
2066: on the top of stack, whereas a result that is often used in long
2067: computations should be passed as bottom result. E.g., the file words
2068: like @code{open-file} return the error code on the top of stack, because
2069: it is usually consumed quickly by @code{throw}; moreover, the error code
2070: has to be checked before doing anything with the other results.
2071:
2072: @end itemize
2073:
2074: These rules are just general guidelines, don't lose sight of the overall
2075: goal to make the words easy to use. E.g., if the convention rule
2076: conflicts with the computation-length rule, you might decide in favour
2077: of the convention if the word will be used rarely, and in favour of the
2078: computation-length rule if the word will be used frequently (because
2079: with frequent use the cost of breaking the computation-length rule would
2080: be quite high, and frequent use makes it easier to remember an
2081: unconventional order).
2082:
2083: @c example !! structure package
2084:
1.65 anton 2085:
1.48 anton 2086: @node Local Variables Tutorial, Conditional execution Tutorial, Designing the stack effect Tutorial, Tutorial
2087: @section Local Variables
1.66 anton 2088: @cindex local variables, tutorial
1.48 anton 2089:
2090: You can define local variables (@emph{locals}) in a colon definition:
2091:
2092: @example
2093: : swap @{ a b -- b a @}
2094: b a ;
2095: 1 2 swap .s 2drop
2096: @end example
2097:
2098: (If your Forth system does not support this syntax, include
2099: @file{compat/anslocals.fs} first).
2100:
2101: In this example @code{@{ a b -- b a @}} is the locals definition; it
2102: takes two cells from the stack, puts the top of stack in @code{b} and
2103: the next stack element in @code{a}. @code{--} starts a comment ending
2104: with @code{@}}. After the locals definition, using the name of the
2105: local will push its value on the stack. You can leave the comment
2106: part (@code{-- b a}) away:
2107:
2108: @example
2109: : swap ( x1 x2 -- x2 x1 )
2110: @{ a b @} b a ;
2111: @end example
2112:
2113: In Gforth you can have several locals definitions, anywhere in a colon
2114: definition; in contrast, in a standard program you can have only one
2115: locals definition per colon definition, and that locals definition must
2116: be outside any controll structure.
2117:
2118: With locals you can write slightly longer definitions without running
2119: into stack trouble. However, I recommend trying to write colon
2120: definitions without locals for exercise purposes to help you gain the
2121: essential factoring skills.
2122:
2123: @assignment
2124: Rewrite your definitions until now with locals
2125: @endassignment
2126:
1.66 anton 2127: Reference: @ref{Locals}.
2128:
1.48 anton 2129:
2130: @node Conditional execution Tutorial, Flags and Comparisons Tutorial, Local Variables Tutorial, Tutorial
2131: @section Conditional execution
1.66 anton 2132: @cindex conditionals, tutorial
2133: @cindex if, tutorial
1.48 anton 2134:
2135: In Forth you can use control structures only inside colon definitions.
2136: An @code{if}-structure looks like this:
2137:
2138: @example
2139: : abs ( n1 -- +n2 )
2140: dup 0 < if
2141: negate
2142: endif ;
2143: 5 abs .
2144: -5 abs .
2145: @end example
2146:
2147: @code{if} takes a flag from the stack. If the flag is non-zero (true),
2148: the following code is performed, otherwise execution continues after the
1.51 pazsan 2149: @code{endif} (or @code{else}). @code{<} compares the top two stack
1.48 anton 2150: elements and prioduces a flag:
2151:
2152: @example
2153: 1 2 < .
2154: 2 1 < .
2155: 1 1 < .
2156: @end example
2157:
2158: Actually the standard name for @code{endif} is @code{then}. This
2159: tutorial presents the examples using @code{endif}, because this is often
2160: less confusing for people familiar with other programming languages
2161: where @code{then} has a different meaning. If your system does not have
2162: @code{endif}, define it with
2163:
2164: @example
2165: : endif postpone then ; immediate
2166: @end example
2167:
2168: You can optionally use an @code{else}-part:
2169:
2170: @example
2171: : min ( n1 n2 -- n )
2172: 2dup < if
2173: drop
2174: else
2175: nip
2176: endif ;
2177: 2 3 min .
2178: 3 2 min .
2179: @end example
2180:
2181: @assignment
2182: Write @code{min} without @code{else}-part (hint: what's the definition
2183: of @code{nip}?).
2184: @endassignment
2185:
1.66 anton 2186: Reference: @ref{Selection}.
2187:
1.48 anton 2188:
2189: @node Flags and Comparisons Tutorial, General Loops Tutorial, Conditional execution Tutorial, Tutorial
2190: @section Flags and Comparisons
1.66 anton 2191: @cindex flags tutorial
2192: @cindex comparison tutorial
1.48 anton 2193:
2194: In a false-flag all bits are clear (0 when interpreted as integer). In
2195: a canonical true-flag all bits are set (-1 as a twos-complement signed
2196: integer); in many contexts (e.g., @code{if}) any non-zero value is
2197: treated as true flag.
2198:
2199: @example
2200: false .
2201: true .
2202: true hex u. decimal
2203: @end example
2204:
2205: Comparison words produce canonical flags:
2206:
2207: @example
2208: 1 1 = .
2209: 1 0= .
2210: 0 1 < .
2211: 0 0 < .
2212: -1 1 u< . \ type error, u< interprets -1 as large unsigned number
2213: -1 1 < .
2214: @end example
2215:
1.66 anton 2216: Gforth supports all combinations of the prefixes @code{0 u d d0 du f f0}
2217: (or none) and the comparisons @code{= <> < > <= >=}. Only a part of
2218: these combinations are standard (for details see the standard,
2219: @ref{Numeric comparison}, @ref{Floating Point} or @ref{Word Index}).
1.48 anton 2220:
2221: You can use @code{and or xor invert} can be used as operations on
2222: canonical flags. Actually they are bitwise operations:
2223:
2224: @example
2225: 1 2 and .
2226: 1 2 or .
2227: 1 3 xor .
2228: 1 invert .
2229: @end example
2230:
2231: You can convert a zero/non-zero flag into a canonical flag with
2232: @code{0<>} (and complement it on the way with @code{0=}).
2233:
2234: @example
2235: 1 0= .
2236: 1 0<> .
2237: @end example
2238:
1.65 anton 2239: You can use the all-bits-set feature of canonical flags and the bitwise
1.48 anton 2240: operation of the Boolean operations to avoid @code{if}s:
2241:
2242: @example
2243: : foo ( n1 -- n2 )
2244: 0= if
2245: 14
2246: else
2247: 0
2248: endif ;
2249: 0 foo .
2250: 1 foo .
2251:
2252: : foo ( n1 -- n2 )
2253: 0= 14 and ;
2254: 0 foo .
2255: 1 foo .
2256: @end example
2257:
2258: @assignment
2259: Write @code{min} without @code{if}.
2260: @endassignment
2261:
1.66 anton 2262: For reference, see @ref{Boolean Flags}, @ref{Numeric comparison}, and
2263: @ref{Bitwise operations}.
2264:
1.48 anton 2265:
2266: @node General Loops Tutorial, Counted loops Tutorial, Flags and Comparisons Tutorial, Tutorial
2267: @section General Loops
1.66 anton 2268: @cindex loops, indefinite, tutorial
1.48 anton 2269:
2270: The endless loop is the most simple one:
2271:
2272: @example
2273: : endless ( -- )
2274: 0 begin
2275: dup . 1+
2276: again ;
2277: endless
2278: @end example
2279:
2280: Terminate this loop by pressing @kbd{Ctrl-C} (in Gforth). @code{begin}
2281: does nothing at run-time, @code{again} jumps back to @code{begin}.
2282:
2283: A loop with one exit at any place looks like this:
2284:
2285: @example
2286: : log2 ( +n1 -- n2 )
2287: \ logarithmus dualis of n1>0, rounded down to the next integer
2288: assert( dup 0> )
2289: 2/ 0 begin
2290: over 0> while
2291: 1+ swap 2/ swap
2292: repeat
2293: nip ;
2294: 7 log2 .
2295: 8 log2 .
2296: @end example
2297:
2298: At run-time @code{while} consumes a flag; if it is 0, execution
1.51 pazsan 2299: continues behind the @code{repeat}; if the flag is non-zero, execution
1.48 anton 2300: continues behind the @code{while}. @code{Repeat} jumps back to
2301: @code{begin}, just like @code{again}.
2302:
2303: In Forth there are many combinations/abbreviations, like @code{1+}.
1.90 anton 2304: However, @code{2/} is not one of them; it shifts its argument right by
1.48 anton 2305: one bit (arithmetic shift right):
2306:
2307: @example
2308: -5 2 / .
2309: -5 2/ .
2310: @end example
2311:
2312: @code{assert(} is no standard word, but you can get it on systems other
2313: then Gforth by including @file{compat/assert.fs}. You can see what it
2314: does by trying
2315:
2316: @example
2317: 0 log2 .
2318: @end example
2319:
2320: Here's a loop with an exit at the end:
2321:
2322: @example
2323: : log2 ( +n1 -- n2 )
2324: \ logarithmus dualis of n1>0, rounded down to the next integer
2325: assert( dup 0 > )
2326: -1 begin
2327: 1+ swap 2/ swap
2328: over 0 <=
2329: until
2330: nip ;
2331: @end example
2332:
2333: @code{Until} consumes a flag; if it is non-zero, execution continues at
2334: the @code{begin}, otherwise after the @code{until}.
2335:
2336: @assignment
2337: Write a definition for computing the greatest common divisor.
2338: @endassignment
2339:
1.66 anton 2340: Reference: @ref{Simple Loops}.
2341:
1.48 anton 2342:
2343: @node Counted loops Tutorial, Recursion Tutorial, General Loops Tutorial, Tutorial
2344: @section Counted loops
1.66 anton 2345: @cindex loops, counted, tutorial
1.48 anton 2346:
2347: @example
2348: : ^ ( n1 u -- n )
2349: \ n = the uth power of u1
2350: 1 swap 0 u+do
2351: over *
2352: loop
2353: nip ;
2354: 3 2 ^ .
2355: 4 3 ^ .
2356: @end example
2357:
2358: @code{U+do} (from @file{compat/loops.fs}, if your Forth system doesn't
2359: have it) takes two numbers of the stack @code{( u3 u4 -- )}, and then
2360: performs the code between @code{u+do} and @code{loop} for @code{u3-u4}
2361: times (or not at all, if @code{u3-u4<0}).
2362:
2363: You can see the stack effect design rules at work in the stack effect of
2364: the loop start words: Since the start value of the loop is more
2365: frequently constant than the end value, the start value is passed on
2366: the top-of-stack.
2367:
2368: You can access the counter of a counted loop with @code{i}:
2369:
2370: @example
2371: : fac ( u -- u! )
2372: 1 swap 1+ 1 u+do
2373: i *
2374: loop ;
2375: 5 fac .
2376: 7 fac .
2377: @end example
2378:
2379: There is also @code{+do}, which expects signed numbers (important for
2380: deciding whether to enter the loop).
2381:
2382: @assignment
2383: Write a definition for computing the nth Fibonacci number.
2384: @endassignment
2385:
1.65 anton 2386: You can also use increments other than 1:
2387:
2388: @example
2389: : up2 ( n1 n2 -- )
2390: +do
2391: i .
2392: 2 +loop ;
2393: 10 0 up2
2394:
2395: : down2 ( n1 n2 -- )
2396: -do
2397: i .
2398: 2 -loop ;
2399: 0 10 down2
2400: @end example
1.48 anton 2401:
1.66 anton 2402: Reference: @ref{Counted Loops}.
2403:
1.48 anton 2404:
2405: @node Recursion Tutorial, Leaving definitions or loops Tutorial, Counted loops Tutorial, Tutorial
2406: @section Recursion
1.66 anton 2407: @cindex recursion tutorial
1.48 anton 2408:
2409: Usually the name of a definition is not visible in the definition; but
2410: earlier definitions are usually visible:
2411:
2412: @example
2413: 1 0 / . \ "Floating-point unidentified fault" in Gforth on most platforms
2414: : / ( n1 n2 -- n )
2415: dup 0= if
2416: -10 throw \ report division by zero
2417: endif
2418: / \ old version
2419: ;
2420: 1 0 /
2421: @end example
2422:
2423: For recursive definitions you can use @code{recursive} (non-standard) or
2424: @code{recurse}:
2425:
2426: @example
2427: : fac1 ( n -- n! ) recursive
2428: dup 0> if
2429: dup 1- fac1 *
2430: else
2431: drop 1
2432: endif ;
2433: 7 fac1 .
2434:
2435: : fac2 ( n -- n! )
2436: dup 0> if
2437: dup 1- recurse *
2438: else
2439: drop 1
2440: endif ;
2441: 8 fac2 .
2442: @end example
2443:
2444: @assignment
2445: Write a recursive definition for computing the nth Fibonacci number.
2446: @endassignment
2447:
1.66 anton 2448: Reference (including indirect recursion): @xref{Calls and returns}.
2449:
1.48 anton 2450:
2451: @node Leaving definitions or loops Tutorial, Return Stack Tutorial, Recursion Tutorial, Tutorial
2452: @section Leaving definitions or loops
1.66 anton 2453: @cindex leaving definitions, tutorial
2454: @cindex leaving loops, tutorial
1.48 anton 2455:
2456: @code{EXIT} exits the current definition right away. For every counted
2457: loop that is left in this way, an @code{UNLOOP} has to be performed
2458: before the @code{EXIT}:
2459:
2460: @c !! real examples
2461: @example
2462: : ...
2463: ... u+do
2464: ... if
2465: ... unloop exit
2466: endif
2467: ...
2468: loop
2469: ... ;
2470: @end example
2471:
2472: @code{LEAVE} leaves the innermost counted loop right away:
2473:
2474: @example
2475: : ...
2476: ... u+do
2477: ... if
2478: ... leave
2479: endif
2480: ...
2481: loop
2482: ... ;
2483: @end example
2484:
1.65 anton 2485: @c !! example
1.48 anton 2486:
1.66 anton 2487: Reference: @ref{Calls and returns}, @ref{Counted Loops}.
2488:
2489:
1.48 anton 2490: @node Return Stack Tutorial, Memory Tutorial, Leaving definitions or loops Tutorial, Tutorial
2491: @section Return Stack
1.66 anton 2492: @cindex return stack tutorial
1.48 anton 2493:
2494: In addition to the data stack Forth also has a second stack, the return
2495: stack; most Forth systems store the return addresses of procedure calls
2496: there (thus its name). Programmers can also use this stack:
2497:
2498: @example
2499: : foo ( n1 n2 -- )
2500: .s
2501: >r .s
1.50 anton 2502: r@@ .
1.48 anton 2503: >r .s
1.50 anton 2504: r@@ .
1.48 anton 2505: r> .
1.50 anton 2506: r@@ .
1.48 anton 2507: r> . ;
2508: 1 2 foo
2509: @end example
2510:
2511: @code{>r} takes an element from the data stack and pushes it onto the
2512: return stack; conversely, @code{r>} moves an elementm from the return to
2513: the data stack; @code{r@@} pushes a copy of the top of the return stack
2514: on the return stack.
2515:
2516: Forth programmers usually use the return stack for storing data
2517: temporarily, if using the data stack alone would be too complex, and
2518: factoring and locals are not an option:
2519:
2520: @example
2521: : 2swap ( x1 x2 x3 x4 -- x3 x4 x1 x2 )
2522: rot >r rot r> ;
2523: @end example
2524:
2525: The return address of the definition and the loop control parameters of
2526: counted loops usually reside on the return stack, so you have to take
2527: all items, that you have pushed on the return stack in a colon
2528: definition or counted loop, from the return stack before the definition
2529: or loop ends. You cannot access items that you pushed on the return
2530: stack outside some definition or loop within the definition of loop.
2531:
2532: If you miscount the return stack items, this usually ends in a crash:
2533:
2534: @example
2535: : crash ( n -- )
2536: >r ;
2537: 5 crash
2538: @end example
2539:
2540: You cannot mix using locals and using the return stack (according to the
2541: standard; Gforth has no problem). However, they solve the same
2542: problems, so this shouldn't be an issue.
2543:
2544: @assignment
2545: Can you rewrite any of the definitions you wrote until now in a better
2546: way using the return stack?
2547: @endassignment
2548:
1.66 anton 2549: Reference: @ref{Return stack}.
2550:
1.48 anton 2551:
2552: @node Memory Tutorial, Characters and Strings Tutorial, Return Stack Tutorial, Tutorial
2553: @section Memory
1.66 anton 2554: @cindex memory access/allocation tutorial
1.48 anton 2555:
2556: You can create a global variable @code{v} with
2557:
2558: @example
2559: variable v ( -- addr )
2560: @end example
2561:
2562: @code{v} pushes the address of a cell in memory on the stack. This cell
2563: was reserved by @code{variable}. You can use @code{!} (store) to store
2564: values into this cell and @code{@@} (fetch) to load the value from the
2565: stack into memory:
2566:
2567: @example
2568: v .
2569: 5 v ! .s
1.50 anton 2570: v @@ .
1.48 anton 2571: @end example
2572:
1.65 anton 2573: You can see a raw dump of memory with @code{dump}:
2574:
2575: @example
2576: v 1 cells .s dump
2577: @end example
2578:
2579: @code{Cells ( n1 -- n2 )} gives you the number of bytes (or, more
2580: generally, address units (aus)) that @code{n1 cells} occupy. You can
2581: also reserve more memory:
1.48 anton 2582:
2583: @example
2584: create v2 20 cells allot
1.65 anton 2585: v2 20 cells dump
1.48 anton 2586: @end example
2587:
1.65 anton 2588: creates a word @code{v2} and reserves 20 uninitialized cells; the
2589: address pushed by @code{v2} points to the start of these 20 cells. You
2590: can use address arithmetic to access these cells:
1.48 anton 2591:
2592: @example
2593: 3 v2 5 cells + !
1.65 anton 2594: v2 20 cells dump
1.48 anton 2595: @end example
2596:
2597: You can reserve and initialize memory with @code{,}:
2598:
2599: @example
2600: create v3
2601: 5 , 4 , 3 , 2 , 1 ,
1.50 anton 2602: v3 @@ .
2603: v3 cell+ @@ .
2604: v3 2 cells + @@ .
1.65 anton 2605: v3 5 cells dump
1.48 anton 2606: @end example
2607:
2608: @assignment
2609: Write a definition @code{vsum ( addr u -- n )} that computes the sum of
2610: @code{u} cells, with the first of these cells at @code{addr}, the next
2611: one at @code{addr cell+} etc.
2612: @endassignment
2613:
2614: You can also reserve memory without creating a new word:
2615:
2616: @example
1.60 anton 2617: here 10 cells allot .
2618: here .
1.48 anton 2619: @end example
2620:
2621: @code{Here} pushes the start address of the memory area. You should
2622: store it somewhere, or you will have a hard time finding the memory area
2623: again.
2624:
2625: @code{Allot} manages dictionary memory. The dictionary memory contains
2626: the system's data structures for words etc. on Gforth and most other
2627: Forth systems. It is managed like a stack: You can free the memory that
2628: you have just @code{allot}ed with
2629:
2630: @example
2631: -10 cells allot
1.60 anton 2632: here .
1.48 anton 2633: @end example
2634:
2635: Note that you cannot do this if you have created a new word in the
2636: meantime (because then your @code{allot}ed memory is no longer on the
2637: top of the dictionary ``stack'').
2638:
2639: Alternatively, you can use @code{allocate} and @code{free} which allow
2640: freeing memory in any order:
2641:
2642: @example
2643: 10 cells allocate throw .s
2644: 20 cells allocate throw .s
2645: swap
2646: free throw
2647: free throw
2648: @end example
2649:
2650: The @code{throw}s deal with errors (e.g., out of memory).
2651:
1.65 anton 2652: And there is also a
2653: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
2654: garbage collector}, which eliminates the need to @code{free} memory
2655: explicitly.
1.48 anton 2656:
1.66 anton 2657: Reference: @ref{Memory}.
2658:
1.48 anton 2659:
2660: @node Characters and Strings Tutorial, Alignment Tutorial, Memory Tutorial, Tutorial
2661: @section Characters and Strings
1.66 anton 2662: @cindex strings tutorial
2663: @cindex characters tutorial
1.48 anton 2664:
2665: On the stack characters take up a cell, like numbers. In memory they
2666: have their own size (one 8-bit byte on most systems), and therefore
2667: require their own words for memory access:
2668:
2669: @example
2670: create v4
2671: 104 c, 97 c, 108 c, 108 c, 111 c,
1.50 anton 2672: v4 4 chars + c@@ .
1.65 anton 2673: v4 5 chars dump
1.48 anton 2674: @end example
2675:
2676: The preferred representation of strings on the stack is @code{addr
2677: u-count}, where @code{addr} is the address of the first character and
2678: @code{u-count} is the number of characters in the string.
2679:
2680: @example
2681: v4 5 type
2682: @end example
2683:
2684: You get a string constant with
2685:
2686: @example
2687: s" hello, world" .s
2688: type
2689: @end example
2690:
2691: Make sure you have a space between @code{s"} and the string; @code{s"}
2692: is a normal Forth word and must be delimited with white space (try what
2693: happens when you remove the space).
2694:
2695: However, this interpretive use of @code{s"} is quite restricted: the
2696: string exists only until the next call of @code{s"} (some Forth systems
2697: keep more than one of these strings, but usually they still have a
1.62 crook 2698: limited lifetime).
1.48 anton 2699:
2700: @example
2701: s" hello," s" world" .s
2702: type
2703: type
2704: @end example
2705:
1.62 crook 2706: You can also use @code{s"} in a definition, and the resulting
2707: strings then live forever (well, for as long as the definition):
1.48 anton 2708:
2709: @example
2710: : foo s" hello," s" world" ;
2711: foo .s
2712: type
2713: type
2714: @end example
2715:
2716: @assignment
2717: @code{Emit ( c -- )} types @code{c} as character (not a number).
2718: Implement @code{type ( addr u -- )}.
2719: @endassignment
2720:
1.66 anton 2721: Reference: @ref{Memory Blocks}.
2722:
2723:
1.84 pazsan 2724: @node Alignment Tutorial, Files Tutorial, Characters and Strings Tutorial, Tutorial
1.48 anton 2725: @section Alignment
1.66 anton 2726: @cindex alignment tutorial
2727: @cindex memory alignment tutorial
1.48 anton 2728:
2729: On many processors cells have to be aligned in memory, if you want to
2730: access them with @code{@@} and @code{!} (and even if the processor does
1.62 crook 2731: not require alignment, access to aligned cells is faster).
1.48 anton 2732:
2733: @code{Create} aligns @code{here} (i.e., the place where the next
2734: allocation will occur, and that the @code{create}d word points to).
2735: Likewise, the memory produced by @code{allocate} starts at an aligned
2736: address. Adding a number of @code{cells} to an aligned address produces
2737: another aligned address.
2738:
2739: However, address arithmetic involving @code{char+} and @code{chars} can
2740: create an address that is not cell-aligned. @code{Aligned ( addr --
2741: a-addr )} produces the next aligned address:
2742:
2743: @example
1.50 anton 2744: v3 char+ aligned .s @@ .
2745: v3 char+ .s @@ .
1.48 anton 2746: @end example
2747:
2748: Similarly, @code{align} advances @code{here} to the next aligned
2749: address:
2750:
2751: @example
2752: create v5 97 c,
2753: here .
2754: align here .
2755: 1000 ,
2756: @end example
2757:
2758: Note that you should use aligned addresses even if your processor does
2759: not require them, if you want your program to be portable.
2760:
1.66 anton 2761: Reference: @ref{Address arithmetic}.
2762:
1.48 anton 2763:
1.84 pazsan 2764: @node Files Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Alignment Tutorial, Tutorial
2765: @section Files
2766: @cindex files tutorial
2767:
2768: This section gives a short introduction into how to use files inside
2769: Forth. It's broken up into five easy steps:
2770:
2771: @enumerate 1
2772: @item Opened an ASCII text file for input
2773: @item Opened a file for output
2774: @item Read input file until string matched (or some other condition matched)
2775: @item Wrote some lines from input ( modified or not) to output
2776: @item Closed the files.
2777: @end enumerate
2778:
2779: @subsection Open file for input
2780:
2781: @example
2782: s" foo.in" r/o open-file throw Value fd-in
2783: @end example
2784:
2785: @subsection Create file for output
2786:
2787: @example
2788: s" foo.out" w/o create-file throw Value fd-out
2789: @end example
2790:
2791: The available file modes are r/o for read-only access, r/w for
2792: read-write access, and w/o for write-only access. You could open both
2793: files with r/w, too, if you like. All file words return error codes; for
2794: most applications, it's best to pass there error codes with @code{throw}
2795: to the outer error handler.
2796:
2797: If you want words for opening and assigning, define them as follows:
2798:
2799: @example
2800: 0 Value fd-in
2801: 0 Value fd-out
2802: : open-input ( addr u -- ) r/o open-file throw to fd-in ;
2803: : open-output ( addr u -- ) w/o create-file throw to fd-out ;
2804: @end example
2805:
2806: Usage example:
2807:
2808: @example
2809: s" foo.in" open-input
2810: s" foo.out" open-output
2811: @end example
2812:
2813: @subsection Scan file for a particular line
2814:
2815: @example
2816: 256 Constant max-line
2817: Create line-buffer max-line 2 + allot
2818:
2819: : scan-file ( addr u -- )
2820: begin
2821: line-buffer max-line fd-in read-line throw
2822: while
2823: >r 2dup line-buffer r> compare 0=
2824: until
2825: else
2826: drop
2827: then
2828: 2drop ;
2829: @end example
2830:
2831: @code{read-line ( addr u1 fd -- u2 flag ior )} reads up to u1 bytes into
1.94 anton 2832: the buffer at addr, and returns the number of bytes read, a flag that is
2833: false when the end of file is reached, and an error code.
1.84 pazsan 2834:
2835: @code{compare ( addr1 u1 addr2 u2 -- n )} compares two strings and
2836: returns zero if both strings are equal. It returns a positive number if
2837: the first string is lexically greater, a negative if the second string
2838: is lexically greater.
2839:
2840: We haven't seen this loop here; it has two exits. Since the @code{while}
2841: exits with the number of bytes read on the stack, we have to clean up
2842: that separately; that's after the @code{else}.
2843:
2844: Usage example:
2845:
2846: @example
2847: s" The text I search is here" scan-file
2848: @end example
2849:
2850: @subsection Copy input to output
2851:
2852: @example
2853: : copy-file ( -- )
2854: begin
2855: line-buffer max-line fd-in read-line throw
2856: while
2857: line-buffer swap fd-out write-file throw
2858: repeat ;
2859: @end example
2860:
2861: @subsection Close files
2862:
2863: @example
2864: fd-in close-file throw
2865: fd-out close-file throw
2866: @end example
2867:
2868: Likewise, you can put that into definitions, too:
2869:
2870: @example
2871: : close-input ( -- ) fd-in close-file throw ;
2872: : close-output ( -- ) fd-out close-file throw ;
2873: @end example
2874:
2875: @assignment
2876: How could you modify @code{copy-file} so that it copies until a second line is
2877: matched? Can you write a program that extracts a section of a text file,
2878: given the line that starts and the line that terminates that section?
2879: @endassignment
2880:
2881: @node Interpretation and Compilation Semantics and Immediacy Tutorial, Execution Tokens Tutorial, Files Tutorial, Tutorial
1.48 anton 2882: @section Interpretation and Compilation Semantics and Immediacy
1.66 anton 2883: @cindex semantics tutorial
2884: @cindex interpretation semantics tutorial
2885: @cindex compilation semantics tutorial
2886: @cindex immediate, tutorial
1.48 anton 2887:
2888: When a word is compiled, it behaves differently from being interpreted.
2889: E.g., consider @code{+}:
2890:
2891: @example
2892: 1 2 + .
2893: : foo + ;
2894: @end example
2895:
2896: These two behaviours are known as compilation and interpretation
2897: semantics. For normal words (e.g., @code{+}), the compilation semantics
2898: is to append the interpretation semantics to the currently defined word
2899: (@code{foo} in the example above). I.e., when @code{foo} is executed
2900: later, the interpretation semantics of @code{+} (i.e., adding two
2901: numbers) will be performed.
2902:
2903: However, there are words with non-default compilation semantics, e.g.,
2904: the control-flow words like @code{if}. You can use @code{immediate} to
2905: change the compilation semantics of the last defined word to be equal to
2906: the interpretation semantics:
2907:
2908: @example
2909: : [FOO] ( -- )
2910: 5 . ; immediate
2911:
2912: [FOO]
2913: : bar ( -- )
2914: [FOO] ;
2915: bar
2916: see bar
2917: @end example
2918:
2919: Two conventions to mark words with non-default compilation semnatics are
2920: names with brackets (more frequently used) and to write them all in
2921: upper case (less frequently used).
2922:
2923: In Gforth (and many other systems) you can also remove the
2924: interpretation semantics with @code{compile-only} (the compilation
2925: semantics is derived from the original interpretation semantics):
2926:
2927: @example
2928: : flip ( -- )
2929: 6 . ; compile-only \ but not immediate
2930: flip
2931:
2932: : flop ( -- )
2933: flip ;
2934: flop
2935: @end example
2936:
2937: In this example the interpretation semantics of @code{flop} is equal to
2938: the original interpretation semantics of @code{flip}.
2939:
2940: The text interpreter has two states: in interpret state, it performs the
2941: interpretation semantics of words it encounters; in compile state, it
2942: performs the compilation semantics of these words.
2943:
2944: Among other things, @code{:} switches into compile state, and @code{;}
2945: switches back to interpret state. They contain the factors @code{]}
2946: (switch to compile state) and @code{[} (switch to interpret state), that
2947: do nothing but switch the state.
2948:
2949: @example
2950: : xxx ( -- )
2951: [ 5 . ]
2952: ;
2953:
2954: xxx
2955: see xxx
2956: @end example
2957:
2958: These brackets are also the source of the naming convention mentioned
2959: above.
2960:
1.66 anton 2961: Reference: @ref{Interpretation and Compilation Semantics}.
2962:
1.48 anton 2963:
2964: @node Execution Tokens Tutorial, Exceptions Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Tutorial
2965: @section Execution Tokens
1.66 anton 2966: @cindex execution tokens tutorial
2967: @cindex XT tutorial
1.48 anton 2968:
2969: @code{' word} gives you the execution token (XT) of a word. The XT is a
2970: cell representing the interpretation semantics of a word. You can
2971: execute this semantics with @code{execute}:
2972:
2973: @example
2974: ' + .s
2975: 1 2 rot execute .
2976: @end example
2977:
2978: The XT is similar to a function pointer in C. However, parameter
2979: passing through the stack makes it a little more flexible:
2980:
2981: @example
2982: : map-array ( ... addr u xt -- ... )
1.50 anton 2983: \ executes xt ( ... x -- ... ) for every element of the array starting
2984: \ at addr and containing u elements
1.48 anton 2985: @{ xt @}
2986: cells over + swap ?do
1.50 anton 2987: i @@ xt execute
1.48 anton 2988: 1 cells +loop ;
2989:
2990: create a 3 , 4 , 2 , -1 , 4 ,
2991: a 5 ' . map-array .s
2992: 0 a 5 ' + map-array .
2993: s" max-n" environment? drop .s
2994: a 5 ' min map-array .
2995: @end example
2996:
2997: You can use map-array with the XTs of words that consume one element
2998: more than they produce. In theory you can also use it with other XTs,
2999: but the stack effect then depends on the size of the array, which is
3000: hard to understand.
3001:
1.51 pazsan 3002: Since XTs are cell-sized, you can store them in memory and manipulate
3003: them on the stack like other cells. You can also compile the XT into a
1.48 anton 3004: word with @code{compile,}:
3005:
3006: @example
3007: : foo1 ( n1 n2 -- n )
3008: [ ' + compile, ] ;
3009: see foo
3010: @end example
3011:
3012: This is non-standard, because @code{compile,} has no compilation
3013: semantics in the standard, but it works in good Forth systems. For the
3014: broken ones, use
3015:
3016: @example
3017: : [compile,] compile, ; immediate
3018:
3019: : foo1 ( n1 n2 -- n )
3020: [ ' + ] [compile,] ;
3021: see foo
3022: @end example
3023:
3024: @code{'} is a word with default compilation semantics; it parses the
3025: next word when its interpretation semantics are executed, not during
3026: compilation:
3027:
3028: @example
3029: : foo ( -- xt )
3030: ' ;
3031: see foo
3032: : bar ( ... "word" -- ... )
3033: ' execute ;
3034: see bar
1.60 anton 3035: 1 2 bar + .
1.48 anton 3036: @end example
3037:
3038: You often want to parse a word during compilation and compile its XT so
3039: it will be pushed on the stack at run-time. @code{[']} does this:
3040:
3041: @example
3042: : xt-+ ( -- xt )
3043: ['] + ;
3044: see xt-+
3045: 1 2 xt-+ execute .
3046: @end example
3047:
3048: Many programmers tend to see @code{'} and the word it parses as one
3049: unit, and expect it to behave like @code{[']} when compiled, and are
3050: confused by the actual behaviour. If you are, just remember that the
3051: Forth system just takes @code{'} as one unit and has no idea that it is
3052: a parsing word (attempts to convenience programmers in this issue have
3053: usually resulted in even worse pitfalls, see
1.66 anton 3054: @uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,
3055: @code{State}-smartness---Why it is evil and How to Exorcise it}).
1.48 anton 3056:
3057: Note that the state of the interpreter does not come into play when
1.51 pazsan 3058: creating and executing XTs. I.e., even when you execute @code{'} in
1.48 anton 3059: compile state, it still gives you the interpretation semantics. And
3060: whatever that state is, @code{execute} performs the semantics
1.66 anton 3061: represented by the XT (i.e., for XTs produced with @code{'} the
3062: interpretation semantics).
3063:
3064: Reference: @ref{Tokens for Words}.
1.48 anton 3065:
3066:
3067: @node Exceptions Tutorial, Defining Words Tutorial, Execution Tokens Tutorial, Tutorial
3068: @section Exceptions
1.66 anton 3069: @cindex exceptions tutorial
1.48 anton 3070:
3071: @code{throw ( n -- )} causes an exception unless n is zero.
3072:
3073: @example
3074: 100 throw .s
3075: 0 throw .s
3076: @end example
3077:
3078: @code{catch ( ... xt -- ... n )} behaves similar to @code{execute}, but
3079: it catches exceptions and pushes the number of the exception on the
3080: stack (or 0, if the xt executed without exception). If there was an
3081: exception, the stacks have the same depth as when entering @code{catch}:
3082:
3083: @example
3084: .s
3085: 3 0 ' / catch .s
3086: 3 2 ' / catch .s
3087: @end example
3088:
3089: @assignment
3090: Try the same with @code{execute} instead of @code{catch}.
3091: @endassignment
3092:
3093: @code{Throw} always jumps to the dynamically next enclosing
3094: @code{catch}, even if it has to leave several call levels to achieve
3095: this:
3096:
3097: @example
3098: : foo 100 throw ;
3099: : foo1 foo ." after foo" ;
1.51 pazsan 3100: : bar ['] foo1 catch ;
1.60 anton 3101: bar .
1.48 anton 3102: @end example
3103:
3104: It is often important to restore a value upon leaving a definition, even
3105: if the definition is left through an exception. You can ensure this
3106: like this:
3107:
3108: @example
3109: : ...
3110: save-x
1.51 pazsan 3111: ['] word-changing-x catch ( ... n )
1.48 anton 3112: restore-x
3113: ( ... n ) throw ;
3114: @end example
3115:
1.55 anton 3116: Gforth provides an alternative syntax in addition to @code{catch}:
1.48 anton 3117: @code{try ... recover ... endtry}. If the code between @code{try} and
3118: @code{recover} has an exception, the stack depths are restored, the
3119: exception number is pushed on the stack, and the code between
3120: @code{recover} and @code{endtry} is performed. E.g., the definition for
3121: @code{catch} is
3122:
3123: @example
3124: : catch ( x1 .. xn xt -- y1 .. ym 0 / z1 .. zn error ) \ exception
3125: try
3126: execute 0
3127: recover
3128: nip
3129: endtry ;
3130: @end example
3131:
3132: The equivalent to the restoration code above is
3133:
3134: @example
3135: : ...
3136: save-x
3137: try
1.92 anton 3138: word-changing-x 0
3139: recover endtry
1.48 anton 3140: restore-x
3141: throw ;
3142: @end example
3143:
1.92 anton 3144: This works if @code{word-changing-x} does not change the stack depth,
3145: otherwise you should add some code between @code{recover} and
3146: @code{endtry} to balance the stack.
1.48 anton 3147:
1.66 anton 3148: Reference: @ref{Exception Handling}.
3149:
1.48 anton 3150:
3151: @node Defining Words Tutorial, Arrays and Records Tutorial, Exceptions Tutorial, Tutorial
3152: @section Defining Words
1.66 anton 3153: @cindex defining words tutorial
3154: @cindex does> tutorial
3155: @cindex create...does> tutorial
3156:
3157: @c before semantics?
1.48 anton 3158:
3159: @code{:}, @code{create}, and @code{variable} are definition words: They
3160: define other words. @code{Constant} is another definition word:
3161:
3162: @example
3163: 5 constant foo
3164: foo .
3165: @end example
3166:
3167: You can also use the prefixes @code{2} (double-cell) and @code{f}
3168: (floating point) with @code{variable} and @code{constant}.
3169:
3170: You can also define your own defining words. E.g.:
3171:
3172: @example
3173: : variable ( "name" -- )
3174: create 0 , ;
3175: @end example
3176:
3177: You can also define defining words that create words that do something
3178: other than just producing their address:
3179:
3180: @example
3181: : constant ( n "name" -- )
3182: create ,
3183: does> ( -- n )
1.50 anton 3184: ( addr ) @@ ;
1.48 anton 3185:
3186: 5 constant foo
3187: foo .
3188: @end example
3189:
3190: The definition of @code{constant} above ends at the @code{does>}; i.e.,
3191: @code{does>} replaces @code{;}, but it also does something else: It
3192: changes the last defined word such that it pushes the address of the
3193: body of the word and then performs the code after the @code{does>}
3194: whenever it is called.
3195:
3196: In the example above, @code{constant} uses @code{,} to store 5 into the
3197: body of @code{foo}. When @code{foo} executes, it pushes the address of
3198: the body onto the stack, then (in the code after the @code{does>})
3199: fetches the 5 from there.
3200:
3201: The stack comment near the @code{does>} reflects the stack effect of the
3202: defined word, not the stack effect of the code after the @code{does>}
3203: (the difference is that the code expects the address of the body that
3204: the stack comment does not show).
3205:
3206: You can use these definition words to do factoring in cases that involve
3207: (other) definition words. E.g., a field offset is always added to an
3208: address. Instead of defining
3209:
3210: @example
3211: 2 cells constant offset-field1
3212: @end example
3213:
3214: and using this like
3215:
3216: @example
3217: ( addr ) offset-field1 +
3218: @end example
3219:
3220: you can define a definition word
3221:
3222: @example
3223: : simple-field ( n "name" -- )
3224: create ,
3225: does> ( n1 -- n1+n )
1.50 anton 3226: ( addr ) @@ + ;
1.48 anton 3227: @end example
1.21 crook 3228:
1.48 anton 3229: Definition and use of field offsets now look like this:
1.21 crook 3230:
1.48 anton 3231: @example
3232: 2 cells simple-field field1
1.60 anton 3233: create mystruct 4 cells allot
3234: mystruct .s field1 .s drop
1.48 anton 3235: @end example
1.21 crook 3236:
1.48 anton 3237: If you want to do something with the word without performing the code
3238: after the @code{does>}, you can access the body of a @code{create}d word
3239: with @code{>body ( xt -- addr )}:
1.21 crook 3240:
1.48 anton 3241: @example
3242: : value ( n "name" -- )
3243: create ,
3244: does> ( -- n1 )
1.50 anton 3245: @@ ;
1.48 anton 3246: : to ( n "name" -- )
3247: ' >body ! ;
1.21 crook 3248:
1.48 anton 3249: 5 value foo
3250: foo .
3251: 7 to foo
3252: foo .
3253: @end example
1.21 crook 3254:
1.48 anton 3255: @assignment
3256: Define @code{defer ( "name" -- )}, which creates a word that stores an
3257: XT (at the start the XT of @code{abort}), and upon execution
3258: @code{execute}s the XT. Define @code{is ( xt "name" -- )} that stores
3259: @code{xt} into @code{name}, a word defined with @code{defer}. Indirect
3260: recursion is one application of @code{defer}.
3261: @endassignment
1.29 crook 3262:
1.66 anton 3263: Reference: @ref{User-defined Defining Words}.
3264:
3265:
1.48 anton 3266: @node Arrays and Records Tutorial, POSTPONE Tutorial, Defining Words Tutorial, Tutorial
3267: @section Arrays and Records
1.66 anton 3268: @cindex arrays tutorial
3269: @cindex records tutorial
3270: @cindex structs tutorial
1.29 crook 3271:
1.48 anton 3272: Forth has no standard words for defining data structures such as arrays
3273: and records (structs in C terminology), but you can build them yourself
3274: based on address arithmetic. You can also define words for defining
3275: arrays and records (@pxref{Defining Words Tutorial,, Defining Words}).
1.29 crook 3276:
1.48 anton 3277: One of the first projects a Forth newcomer sets out upon when learning
3278: about defining words is an array defining word (possibly for
3279: n-dimensional arrays). Go ahead and do it, I did it, too; you will
3280: learn something from it. However, don't be disappointed when you later
3281: learn that you have little use for these words (inappropriate use would
3282: be even worse). I have not yet found a set of useful array words yet;
3283: the needs are just too diverse, and named, global arrays (the result of
3284: naive use of defining words) are often not flexible enough (e.g.,
1.66 anton 3285: consider how to pass them as parameters). Another such project is a set
3286: of words to help dealing with strings.
1.29 crook 3287:
1.48 anton 3288: On the other hand, there is a useful set of record words, and it has
3289: been defined in @file{compat/struct.fs}; these words are predefined in
3290: Gforth. They are explained in depth elsewhere in this manual (see
3291: @pxref{Structures}). The @code{simple-field} example above is
3292: simplified variant of fields in this package.
1.21 crook 3293:
3294:
1.48 anton 3295: @node POSTPONE Tutorial, Literal Tutorial, Arrays and Records Tutorial, Tutorial
3296: @section @code{POSTPONE}
1.66 anton 3297: @cindex postpone tutorial
1.21 crook 3298:
1.48 anton 3299: You can compile the compilation semantics (instead of compiling the
3300: interpretation semantics) of a word with @code{POSTPONE}:
1.21 crook 3301:
1.48 anton 3302: @example
3303: : MY-+ ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
1.51 pazsan 3304: POSTPONE + ; immediate
1.48 anton 3305: : foo ( n1 n2 -- n )
3306: MY-+ ;
3307: 1 2 foo .
3308: see foo
3309: @end example
1.21 crook 3310:
1.48 anton 3311: During the definition of @code{foo} the text interpreter performs the
3312: compilation semantics of @code{MY-+}, which performs the compilation
3313: semantics of @code{+}, i.e., it compiles @code{+} into @code{foo}.
3314:
3315: This example also displays separate stack comments for the compilation
3316: semantics and for the stack effect of the compiled code. For words with
3317: default compilation semantics these stack effects are usually not
3318: displayed; the stack effect of the compilation semantics is always
3319: @code{( -- )} for these words, the stack effect for the compiled code is
3320: the stack effect of the interpretation semantics.
3321:
3322: Note that the state of the interpreter does not come into play when
3323: performing the compilation semantics in this way. You can also perform
3324: it interpretively, e.g.:
3325:
3326: @example
3327: : foo2 ( n1 n2 -- n )
3328: [ MY-+ ] ;
3329: 1 2 foo .
3330: see foo
3331: @end example
1.21 crook 3332:
1.48 anton 3333: However, there are some broken Forth systems where this does not always
1.62 crook 3334: work, and therefore this practice was been declared non-standard in
1.48 anton 3335: 1999.
3336: @c !! repair.fs
3337:
3338: Here is another example for using @code{POSTPONE}:
1.44 crook 3339:
1.48 anton 3340: @example
3341: : MY-- ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
3342: POSTPONE negate POSTPONE + ; immediate compile-only
3343: : bar ( n1 n2 -- n )
3344: MY-- ;
3345: 2 1 bar .
3346: see bar
3347: @end example
1.21 crook 3348:
1.48 anton 3349: You can define @code{ENDIF} in this way:
1.21 crook 3350:
1.48 anton 3351: @example
3352: : ENDIF ( Compilation: orig -- )
3353: POSTPONE then ; immediate
3354: @end example
1.21 crook 3355:
1.48 anton 3356: @assignment
3357: Write @code{MY-2DUP} that has compilation semantics equivalent to
3358: @code{2dup}, but compiles @code{over over}.
3359: @endassignment
1.29 crook 3360:
1.66 anton 3361: @c !! @xref{Macros} for reference
3362:
3363:
1.48 anton 3364: @node Literal Tutorial, Advanced macros Tutorial, POSTPONE Tutorial, Tutorial
3365: @section @code{Literal}
1.66 anton 3366: @cindex literal tutorial
1.29 crook 3367:
1.48 anton 3368: You cannot @code{POSTPONE} numbers:
1.21 crook 3369:
1.48 anton 3370: @example
3371: : [FOO] POSTPONE 500 ; immediate
1.21 crook 3372: @end example
3373:
1.48 anton 3374: Instead, you can use @code{LITERAL (compilation: n --; run-time: -- n )}:
1.29 crook 3375:
1.48 anton 3376: @example
3377: : [FOO] ( compilation: --; run-time: -- n )
3378: 500 POSTPONE literal ; immediate
1.29 crook 3379:
1.60 anton 3380: : flip [FOO] ;
1.48 anton 3381: flip .
3382: see flip
3383: @end example
1.29 crook 3384:
1.48 anton 3385: @code{LITERAL} consumes a number at compile-time (when it's compilation
3386: semantics are executed) and pushes it at run-time (when the code it
3387: compiled is executed). A frequent use of @code{LITERAL} is to compile a
3388: number computed at compile time into the current word:
1.29 crook 3389:
1.48 anton 3390: @example
3391: : bar ( -- n )
3392: [ 2 2 + ] literal ;
3393: see bar
3394: @end example
1.29 crook 3395:
1.48 anton 3396: @assignment
3397: Write @code{]L} which allows writing the example above as @code{: bar (
3398: -- n ) [ 2 2 + ]L ;}
3399: @endassignment
3400:
1.66 anton 3401: @c !! @xref{Macros} for reference
3402:
1.48 anton 3403:
3404: @node Advanced macros Tutorial, Compilation Tokens Tutorial, Literal Tutorial, Tutorial
3405: @section Advanced macros
1.66 anton 3406: @cindex macros, advanced tutorial
3407: @cindex run-time code generation, tutorial
1.48 anton 3408:
1.66 anton 3409: Reconsider @code{map-array} from @ref{Execution Tokens Tutorial,,
3410: Execution Tokens}. It frequently performs @code{execute}, a relatively
3411: expensive operation in some Forth implementations. You can use
1.48 anton 3412: @code{compile,} and @code{POSTPONE} to eliminate these @code{execute}s
3413: and produce a word that contains the word to be performed directly:
3414:
3415: @c use ]] ... [[
3416: @example
3417: : compile-map-array ( compilation: xt -- ; run-time: ... addr u -- ... )
3418: \ at run-time, execute xt ( ... x -- ... ) for each element of the
3419: \ array beginning at addr and containing u elements
3420: @{ xt @}
3421: POSTPONE cells POSTPONE over POSTPONE + POSTPONE swap POSTPONE ?do
1.50 anton 3422: POSTPONE i POSTPONE @@ xt compile,
1.48 anton 3423: 1 cells POSTPONE literal POSTPONE +loop ;
3424:
3425: : sum-array ( addr u -- n )
3426: 0 rot rot [ ' + compile-map-array ] ;
3427: see sum-array
3428: a 5 sum-array .
3429: @end example
3430:
3431: You can use the full power of Forth for generating the code; here's an
3432: example where the code is generated in a loop:
3433:
3434: @example
3435: : compile-vmul-step ( compilation: n --; run-time: n1 addr1 -- n2 addr2 )
3436: \ n2=n1+(addr1)*n, addr2=addr1+cell
1.50 anton 3437: POSTPONE tuck POSTPONE @@
1.48 anton 3438: POSTPONE literal POSTPONE * POSTPONE +
3439: POSTPONE swap POSTPONE cell+ ;
3440:
3441: : compile-vmul ( compilation: addr1 u -- ; run-time: addr2 -- n )
1.51 pazsan 3442: \ n=v1*v2 (inner product), where the v_i are represented as addr_i u
1.48 anton 3443: 0 postpone literal postpone swap
3444: [ ' compile-vmul-step compile-map-array ]
3445: postpone drop ;
3446: see compile-vmul
3447:
3448: : a-vmul ( addr -- n )
1.51 pazsan 3449: \ n=a*v, where v is a vector that's as long as a and starts at addr
1.48 anton 3450: [ a 5 compile-vmul ] ;
3451: see a-vmul
3452: a a-vmul .
3453: @end example
3454:
3455: This example uses @code{compile-map-array} to show off, but you could
1.66 anton 3456: also use @code{map-array} instead (try it now!).
1.48 anton 3457:
3458: You can use this technique for efficient multiplication of large
3459: matrices. In matrix multiplication, you multiply every line of one
3460: matrix with every column of the other matrix. You can generate the code
3461: for one line once, and use it for every column. The only downside of
3462: this technique is that it is cumbersome to recover the memory consumed
3463: by the generated code when you are done (and in more complicated cases
3464: it is not possible portably).
3465:
1.66 anton 3466: @c !! @xref{Macros} for reference
3467:
3468:
1.48 anton 3469: @node Compilation Tokens Tutorial, Wordlists and Search Order Tutorial, Advanced macros Tutorial, Tutorial
3470: @section Compilation Tokens
1.66 anton 3471: @cindex compilation tokens, tutorial
3472: @cindex CT, tutorial
1.48 anton 3473:
3474: This section is Gforth-specific. You can skip it.
3475:
3476: @code{' word compile,} compiles the interpretation semantics. For words
3477: with default compilation semantics this is the same as performing the
3478: compilation semantics. To represent the compilation semantics of other
3479: words (e.g., words like @code{if} that have no interpretation
3480: semantics), Gforth has the concept of a compilation token (CT,
3481: consisting of two cells), and words @code{comp'} and @code{[comp']}.
3482: You can perform the compilation semantics represented by a CT with
3483: @code{execute}:
1.29 crook 3484:
1.48 anton 3485: @example
3486: : foo2 ( n1 n2 -- n )
3487: [ comp' + execute ] ;
3488: see foo
3489: @end example
1.29 crook 3490:
1.48 anton 3491: You can compile the compilation semantics represented by a CT with
3492: @code{postpone,}:
1.30 anton 3493:
1.48 anton 3494: @example
3495: : foo3 ( -- )
3496: [ comp' + postpone, ] ;
3497: see foo3
3498: @end example
1.30 anton 3499:
1.51 pazsan 3500: @code{[ comp' word postpone, ]} is equivalent to @code{POSTPONE word}.
1.48 anton 3501: @code{comp'} is particularly useful for words that have no
3502: interpretation semantics:
1.29 crook 3503:
1.30 anton 3504: @example
1.48 anton 3505: ' if
1.60 anton 3506: comp' if .s 2drop
1.30 anton 3507: @end example
3508:
1.66 anton 3509: Reference: @ref{Tokens for Words}.
3510:
1.29 crook 3511:
1.48 anton 3512: @node Wordlists and Search Order Tutorial, , Compilation Tokens Tutorial, Tutorial
3513: @section Wordlists and Search Order
1.66 anton 3514: @cindex wordlists tutorial
3515: @cindex search order, tutorial
1.48 anton 3516:
3517: The dictionary is not just a memory area that allows you to allocate
3518: memory with @code{allot}, it also contains the Forth words, arranged in
3519: several wordlists. When searching for a word in a wordlist,
3520: conceptually you start searching at the youngest and proceed towards
3521: older words (in reality most systems nowadays use hash-tables); i.e., if
3522: you define a word with the same name as an older word, the new word
3523: shadows the older word.
3524:
3525: Which wordlists are searched in which order is determined by the search
3526: order. You can display the search order with @code{order}. It displays
3527: first the search order, starting with the wordlist searched first, then
3528: it displays the wordlist that will contain newly defined words.
1.21 crook 3529:
1.48 anton 3530: You can create a new, empty wordlist with @code{wordlist ( -- wid )}:
1.21 crook 3531:
1.48 anton 3532: @example
3533: wordlist constant mywords
3534: @end example
1.21 crook 3535:
1.48 anton 3536: @code{Set-current ( wid -- )} sets the wordlist that will contain newly
3537: defined words (the @emph{current} wordlist):
1.21 crook 3538:
1.48 anton 3539: @example
3540: mywords set-current
3541: order
3542: @end example
1.26 crook 3543:
1.48 anton 3544: Gforth does not display a name for the wordlist in @code{mywords}
3545: because this wordlist was created anonymously with @code{wordlist}.
1.21 crook 3546:
1.48 anton 3547: You can get the current wordlist with @code{get-current ( -- wid)}. If
3548: you want to put something into a specific wordlist without overall
3549: effect on the current wordlist, this typically looks like this:
1.21 crook 3550:
1.48 anton 3551: @example
3552: get-current mywords set-current ( wid )
3553: create someword
3554: ( wid ) set-current
3555: @end example
1.21 crook 3556:
1.48 anton 3557: You can write the search order with @code{set-order ( wid1 .. widn n --
3558: )} and read it with @code{get-order ( -- wid1 .. widn n )}. The first
3559: searched wordlist is topmost.
1.21 crook 3560:
1.48 anton 3561: @example
3562: get-order mywords swap 1+ set-order
3563: order
3564: @end example
1.21 crook 3565:
1.48 anton 3566: Yes, the order of wordlists in the output of @code{order} is reversed
3567: from stack comments and the output of @code{.s} and thus unintuitive.
1.21 crook 3568:
1.48 anton 3569: @assignment
3570: Define @code{>order ( wid -- )} with adds @code{wid} as first searched
3571: wordlist to the search order. Define @code{previous ( -- )}, which
3572: removes the first searched wordlist from the search order. Experiment
3573: with boundary conditions (you will see some crashes or situations that
3574: are hard or impossible to leave).
3575: @endassignment
1.21 crook 3576:
1.48 anton 3577: The search order is a powerful foundation for providing features similar
3578: to Modula-2 modules and C++ namespaces. However, trying to modularize
3579: programs in this way has disadvantages for debugging and reuse/factoring
3580: that overcome the advantages in my experience (I don't do huge projects,
1.55 anton 3581: though). These disadvantages are not so clear in other
1.82 anton 3582: languages/programming environments, because these languages are not so
1.48 anton 3583: strong in debugging and reuse.
1.21 crook 3584:
1.66 anton 3585: @c !! example
3586:
3587: Reference: @ref{Word Lists}.
1.21 crook 3588:
1.29 crook 3589: @c ******************************************************************
1.48 anton 3590: @node Introduction, Words, Tutorial, Top
1.29 crook 3591: @comment node-name, next, previous, up
3592: @chapter An Introduction to ANS Forth
3593: @cindex Forth - an introduction
1.21 crook 3594:
1.83 anton 3595: The difference of this chapter from the Tutorial (@pxref{Tutorial}) is
3596: that it is slower-paced in its examples, but uses them to dive deep into
3597: explaining Forth internals (not covered by the Tutorial). Apart from
3598: that, this chapter covers far less material. It is suitable for reading
3599: without using a computer.
3600:
1.29 crook 3601: The primary purpose of this manual is to document Gforth. However, since
3602: Forth is not a widely-known language and there is a lack of up-to-date
3603: teaching material, it seems worthwhile to provide some introductory
1.49 anton 3604: material. For other sources of Forth-related
3605: information, see @ref{Forth-related information}.
1.21 crook 3606:
1.29 crook 3607: The examples in this section should work on any ANS Forth; the
3608: output shown was produced using Gforth. Each example attempts to
3609: reproduce the exact output that Gforth produces. If you try out the
3610: examples (and you should), what you should type is shown @kbd{like this}
3611: and Gforth's response is shown @code{like this}. The single exception is
1.30 anton 3612: that, where the example shows @key{RET} it means that you should
1.29 crook 3613: press the ``carriage return'' key. Unfortunately, some output formats for
3614: this manual cannot show the difference between @kbd{this} and
3615: @code{this} which will make trying out the examples harder (but not
3616: impossible).
1.21 crook 3617:
1.29 crook 3618: Forth is an unusual language. It provides an interactive development
3619: environment which includes both an interpreter and compiler. Forth
3620: programming style encourages you to break a problem down into many
3621: @cindex factoring
3622: small fragments (@dfn{factoring}), and then to develop and test each
3623: fragment interactively. Forth advocates assert that breaking the
3624: edit-compile-test cycle used by conventional programming languages can
3625: lead to great productivity improvements.
1.21 crook 3626:
1.29 crook 3627: @menu
1.67 anton 3628: * Introducing the Text Interpreter::
3629: * Stacks and Postfix notation::
3630: * Your first definition::
3631: * How does that work?::
3632: * Forth is written in Forth::
3633: * Review - elements of a Forth system::
3634: * Where to go next::
3635: * Exercises::
1.29 crook 3636: @end menu
1.21 crook 3637:
1.29 crook 3638: @comment ----------------------------------------------
3639: @node Introducing the Text Interpreter, Stacks and Postfix notation, Introduction, Introduction
3640: @section Introducing the Text Interpreter
3641: @cindex text interpreter
3642: @cindex outer interpreter
1.21 crook 3643:
1.30 anton 3644: @c IMO this is too detailed and the pace is too slow for
3645: @c an introduction. If you know German, take a look at
3646: @c http://www.complang.tuwien.ac.at/anton/lvas/skriptum-stack.html
3647: @c to see how I do it - anton
3648:
1.44 crook 3649: @c nac-> Where I have accepted your comments 100% and modified the text
3650: @c accordingly, I have deleted your comments. Elsewhere I have added a
3651: @c response like this to attempt to rationalise what I have done. Of
3652: @c course, this is a very clumsy mechanism for something that would be
3653: @c done far more efficiently over a beer. Please delete any dialogue
3654: @c you consider closed.
3655:
1.29 crook 3656: When you invoke the Forth image, you will see a startup banner printed
3657: and nothing else (if you have Gforth installed on your system, try
1.30 anton 3658: invoking it now, by typing @kbd{gforth@key{RET}}). Forth is now running
1.29 crook 3659: its command line interpreter, which is called the @dfn{Text Interpreter}
3660: (also known as the @dfn{Outer Interpreter}). (You will learn a lot
1.49 anton 3661: about the text interpreter as you read through this chapter, for more
3662: detail @pxref{The Text Interpreter}).
1.21 crook 3663:
1.29 crook 3664: Although it's not obvious, Forth is actually waiting for your
1.30 anton 3665: input. Type a number and press the @key{RET} key:
1.21 crook 3666:
1.26 crook 3667: @example
1.30 anton 3668: @kbd{45@key{RET}} ok
1.26 crook 3669: @end example
1.21 crook 3670:
1.29 crook 3671: Rather than give you a prompt to invite you to input something, the text
3672: interpreter prints a status message @i{after} it has processed a line
3673: of input. The status message in this case (``@code{ ok}'' followed by
3674: carriage-return) indicates that the text interpreter was able to process
3675: all of your input successfully. Now type something illegal:
3676:
3677: @example
1.30 anton 3678: @kbd{qwer341@key{RET}}
1.29 crook 3679: :1: Undefined word
3680: qwer341
3681: ^^^^^^^
3682: $400D2BA8 Bounce
3683: $400DBDA8 no.extensions
3684: @end example
1.23 crook 3685:
1.29 crook 3686: The exact text, other than the ``Undefined word'' may differ slightly on
3687: your system, but the effect is the same; when the text interpreter
3688: detects an error, it discards any remaining text on a line, resets
1.49 anton 3689: certain internal state and prints an error message. For a detailed description of error messages see @ref{Error
3690: messages}.
1.23 crook 3691:
1.29 crook 3692: The text interpreter waits for you to press carriage-return, and then
3693: processes your input line. Starting at the beginning of the line, it
3694: breaks the line into groups of characters separated by spaces. For each
3695: group of characters in turn, it makes two attempts to do something:
1.23 crook 3696:
1.29 crook 3697: @itemize @bullet
3698: @item
1.44 crook 3699: @cindex name dictionary
1.29 crook 3700: It tries to treat it as a command. It does this by searching a @dfn{name
3701: dictionary}. If the group of characters matches an entry in the name
3702: dictionary, the name dictionary provides the text interpreter with
3703: information that allows the text interpreter perform some actions. In
3704: Forth jargon, we say that the group
3705: @cindex word
3706: @cindex definition
3707: @cindex execution token
3708: @cindex xt
3709: of characters names a @dfn{word}, that the dictionary search returns an
3710: @dfn{execution token (xt)} corresponding to the @dfn{definition} of the
3711: word, and that the text interpreter executes the xt. Often, the terms
3712: @dfn{word} and @dfn{definition} are used interchangeably.
3713: @item
3714: If the text interpreter fails to find a match in the name dictionary, it
3715: tries to treat the group of characters as a number in the current number
3716: base (when you start up Forth, the current number base is base 10). If
3717: the group of characters legitimately represents a number, the text
3718: interpreter pushes the number onto a stack (we'll learn more about that
3719: in the next section).
3720: @end itemize
1.23 crook 3721:
1.29 crook 3722: If the text interpreter is unable to do either of these things with any
3723: group of characters, it discards the group of characters and the rest of
3724: the line, then prints an error message. If the text interpreter reaches
3725: the end of the line without error, it prints the status message ``@code{ ok}''
3726: followed by carriage-return.
1.21 crook 3727:
1.29 crook 3728: This is the simplest command we can give to the text interpreter:
1.23 crook 3729:
3730: @example
1.30 anton 3731: @key{RET} ok
1.23 crook 3732: @end example
1.21 crook 3733:
1.29 crook 3734: The text interpreter did everything we asked it to do (nothing) without
3735: an error, so it said that everything is ``@code{ ok}''. Try a slightly longer
3736: command:
1.21 crook 3737:
1.23 crook 3738: @example
1.30 anton 3739: @kbd{12 dup fred dup@key{RET}}
1.29 crook 3740: :1: Undefined word
3741: 12 dup fred dup
3742: ^^^^
3743: $400D2BA8 Bounce
3744: $400DBDA8 no.extensions
1.23 crook 3745: @end example
1.21 crook 3746:
1.29 crook 3747: When you press the carriage-return key, the text interpreter starts to
3748: work its way along the line:
1.21 crook 3749:
1.29 crook 3750: @itemize @bullet
3751: @item
3752: When it gets to the space after the @code{2}, it takes the group of
3753: characters @code{12} and looks them up in the name
3754: dictionary@footnote{We can't tell if it found them or not, but assume
3755: for now that it did not}. There is no match for this group of characters
3756: in the name dictionary, so it tries to treat them as a number. It is
3757: able to do this successfully, so it puts the number, 12, ``on the stack''
3758: (whatever that means).
3759: @item
3760: The text interpreter resumes scanning the line and gets the next group
3761: of characters, @code{dup}. It looks it up in the name dictionary and
3762: (you'll have to take my word for this) finds it, and executes the word
3763: @code{dup} (whatever that means).
3764: @item
3765: Once again, the text interpreter resumes scanning the line and gets the
3766: group of characters @code{fred}. It looks them up in the name
3767: dictionary, but can't find them. It tries to treat them as a number, but
3768: they don't represent any legal number.
3769: @end itemize
1.21 crook 3770:
1.29 crook 3771: At this point, the text interpreter gives up and prints an error
3772: message. The error message shows exactly how far the text interpreter
3773: got in processing the line. In particular, it shows that the text
3774: interpreter made no attempt to do anything with the final character
3775: group, @code{dup}, even though we have good reason to believe that the
3776: text interpreter would have no problem looking that word up and
3777: executing it a second time.
1.21 crook 3778:
3779:
1.29 crook 3780: @comment ----------------------------------------------
3781: @node Stacks and Postfix notation, Your first definition, Introducing the Text Interpreter, Introduction
3782: @section Stacks, postfix notation and parameter passing
3783: @cindex text interpreter
3784: @cindex outer interpreter
1.21 crook 3785:
1.29 crook 3786: In procedural programming languages (like C and Pascal), the
3787: building-block of programs is the @dfn{function} or @dfn{procedure}. These
3788: functions or procedures are called with @dfn{explicit parameters}. For
3789: example, in C we might write:
1.21 crook 3790:
1.23 crook 3791: @example
1.29 crook 3792: total = total + new_volume(length,height,depth);
1.23 crook 3793: @end example
1.21 crook 3794:
1.23 crook 3795: @noindent
1.29 crook 3796: where new_volume is a function-call to another piece of code, and total,
3797: length, height and depth are all variables. length, height and depth are
3798: parameters to the function-call.
1.21 crook 3799:
1.29 crook 3800: In Forth, the equivalent of the function or procedure is the
3801: @dfn{definition} and parameters are implicitly passed between
3802: definitions using a shared stack that is visible to the
3803: programmer. Although Forth does support variables, the existence of the
3804: stack means that they are used far less often than in most other
3805: programming languages. When the text interpreter encounters a number, it
3806: will place (@dfn{push}) it on the stack. There are several stacks (the
1.30 anton 3807: actual number is implementation-dependent ...) and the particular stack
1.29 crook 3808: used for any operation is implied unambiguously by the operation being
3809: performed. The stack used for all integer operations is called the @dfn{data
3810: stack} and, since this is the stack used most commonly, references to
3811: ``the data stack'' are often abbreviated to ``the stack''.
1.21 crook 3812:
1.29 crook 3813: The stacks have a last-in, first-out (LIFO) organisation. If you type:
1.21 crook 3814:
1.23 crook 3815: @example
1.30 anton 3816: @kbd{1 2 3@key{RET}} ok
1.23 crook 3817: @end example
1.21 crook 3818:
1.29 crook 3819: Then this instructs the text interpreter to placed three numbers on the
3820: (data) stack. An analogy for the behaviour of the stack is to take a
3821: pack of playing cards and deal out the ace (1), 2 and 3 into a pile on
3822: the table. The 3 was the last card onto the pile (``last-in'') and if
3823: you take a card off the pile then, unless you're prepared to fiddle a
3824: bit, the card that you take off will be the 3 (``first-out''). The
3825: number that will be first-out of the stack is called the @dfn{top of
3826: stack}, which
3827: @cindex TOS definition
3828: is often abbreviated to @dfn{TOS}.
1.21 crook 3829:
1.29 crook 3830: To understand how parameters are passed in Forth, consider the
3831: behaviour of the definition @code{+} (pronounced ``plus''). You will not
3832: be surprised to learn that this definition performs addition. More
3833: precisely, it adds two number together and produces a result. Where does
3834: it get the two numbers from? It takes the top two numbers off the
3835: stack. Where does it place the result? On the stack. You can act-out the
3836: behaviour of @code{+} with your playing cards like this:
1.21 crook 3837:
3838: @itemize @bullet
3839: @item
1.29 crook 3840: Pick up two cards from the stack on the table
1.21 crook 3841: @item
1.29 crook 3842: Stare at them intently and ask yourself ``what @i{is} the sum of these two
3843: numbers''
1.21 crook 3844: @item
1.29 crook 3845: Decide that the answer is 5
1.21 crook 3846: @item
1.29 crook 3847: Shuffle the two cards back into the pack and find a 5
1.21 crook 3848: @item
1.29 crook 3849: Put a 5 on the remaining ace that's on the table.
1.21 crook 3850: @end itemize
3851:
1.29 crook 3852: If you don't have a pack of cards handy but you do have Forth running,
3853: you can use the definition @code{.s} to show the current state of the stack,
3854: without affecting the stack. Type:
1.21 crook 3855:
3856: @example
1.30 anton 3857: @kbd{clearstack 1 2 3@key{RET}} ok
3858: @kbd{.s@key{RET}} <3> 1 2 3 ok
1.23 crook 3859: @end example
3860:
1.29 crook 3861: The text interpreter looks up the word @code{clearstack} and executes
3862: it; it tidies up the stack and removes any entries that may have been
3863: left on it by earlier examples. The text interpreter pushes each of the
3864: three numbers in turn onto the stack. Finally, the text interpreter
3865: looks up the word @code{.s} and executes it. The effect of executing
3866: @code{.s} is to print the ``<3>'' (the total number of items on the stack)
3867: followed by a list of all the items on the stack; the item on the far
3868: right-hand side is the TOS.
1.21 crook 3869:
1.29 crook 3870: You can now type:
1.21 crook 3871:
1.29 crook 3872: @example
1.30 anton 3873: @kbd{+ .s@key{RET}} <2> 1 5 ok
1.29 crook 3874: @end example
1.21 crook 3875:
1.29 crook 3876: @noindent
3877: which is correct; there are now 2 items on the stack and the result of
3878: the addition is 5.
1.23 crook 3879:
1.29 crook 3880: If you're playing with cards, try doing a second addition: pick up the
3881: two cards, work out that their sum is 6, shuffle them into the pack,
3882: look for a 6 and place that on the table. You now have just one item on
3883: the stack. What happens if you try to do a third addition? Pick up the
3884: first card, pick up the second card -- ah! There is no second card. This
3885: is called a @dfn{stack underflow} and consitutes an error. If you try to
1.95 anton 3886: do the same thing with Forth it often reports an error (probably a Stack
1.29 crook 3887: Underflow or an Invalid Memory Address error).
1.23 crook 3888:
1.29 crook 3889: The opposite situation to a stack underflow is a @dfn{stack overflow},
3890: which simply accepts that there is a finite amount of storage space
3891: reserved for the stack. To stretch the playing card analogy, if you had
3892: enough packs of cards and you piled the cards up on the table, you would
3893: eventually be unable to add another card; you'd hit the ceiling. Gforth
3894: allows you to set the maximum size of the stacks. In general, the only
3895: time that you will get a stack overflow is because a definition has a
3896: bug in it and is generating data on the stack uncontrollably.
1.23 crook 3897:
1.29 crook 3898: There's one final use for the playing card analogy. If you model your
3899: stack using a pack of playing cards, the maximum number of items on
3900: your stack will be 52 (I assume you didn't use the Joker). The maximum
3901: @i{value} of any item on the stack is 13 (the King). In fact, the only
3902: possible numbers are positive integer numbers 1 through 13; you can't
3903: have (for example) 0 or 27 or 3.52 or -2. If you change the way you
3904: think about some of the cards, you can accommodate different
3905: numbers. For example, you could think of the Jack as representing 0,
3906: the Queen as representing -1 and the King as representing -2. Your
1.45 crook 3907: @i{range} remains unchanged (you can still only represent a total of 13
1.29 crook 3908: numbers) but the numbers that you can represent are -2 through 10.
1.28 crook 3909:
1.29 crook 3910: In that analogy, the limit was the amount of information that a single
3911: stack entry could hold, and Forth has a similar limit. In Forth, the
3912: size of a stack entry is called a @dfn{cell}. The actual size of a cell is
3913: implementation dependent and affects the maximum value that a stack
3914: entry can hold. A Standard Forth provides a cell size of at least
3915: 16-bits, and most desktop systems use a cell size of 32-bits.
1.21 crook 3916:
1.29 crook 3917: Forth does not do any type checking for you, so you are free to
3918: manipulate and combine stack items in any way you wish. A convenient way
3919: of treating stack items is as 2's complement signed integers, and that
3920: is what Standard words like @code{+} do. Therefore you can type:
1.21 crook 3921:
1.29 crook 3922: @example
1.30 anton 3923: @kbd{-5 12 + .s@key{RET}} <1> 7 ok
1.29 crook 3924: @end example
1.21 crook 3925:
1.29 crook 3926: If you use numbers and definitions like @code{+} in order to turn Forth
3927: into a great big pocket calculator, you will realise that it's rather
3928: different from a normal calculator. Rather than typing 2 + 3 = you had
3929: to type 2 3 + (ignore the fact that you had to use @code{.s} to see the
3930: result). The terminology used to describe this difference is to say that
3931: your calculator uses @dfn{Infix Notation} (parameters and operators are
3932: mixed) whilst Forth uses @dfn{Postfix Notation} (parameters and
3933: operators are separate), also called @dfn{Reverse Polish Notation}.
1.21 crook 3934:
1.29 crook 3935: Whilst postfix notation might look confusing to begin with, it has
3936: several important advantages:
1.21 crook 3937:
1.23 crook 3938: @itemize @bullet
3939: @item
1.29 crook 3940: it is unambiguous
1.23 crook 3941: @item
1.29 crook 3942: it is more concise
1.23 crook 3943: @item
1.29 crook 3944: it fits naturally with a stack-based system
1.23 crook 3945: @end itemize
1.21 crook 3946:
1.29 crook 3947: To examine these claims in more detail, consider these sums:
1.21 crook 3948:
1.29 crook 3949: @example
3950: 6 + 5 * 4 =
3951: 4 * 5 + 6 =
3952: @end example
1.21 crook 3953:
1.29 crook 3954: If you're just learning maths or your maths is very rusty, you will
3955: probably come up with the answer 44 for the first and 26 for the
3956: second. If you are a bit of a whizz at maths you will remember the
3957: @i{convention} that multiplication takes precendence over addition, and
3958: you'd come up with the answer 26 both times. To explain the answer 26
3959: to someone who got the answer 44, you'd probably rewrite the first sum
3960: like this:
1.21 crook 3961:
1.29 crook 3962: @example
3963: 6 + (5 * 4) =
3964: @end example
1.21 crook 3965:
1.29 crook 3966: If what you really wanted was to perform the addition before the
3967: multiplication, you would have to use parentheses to force it.
1.21 crook 3968:
1.29 crook 3969: If you did the first two sums on a pocket calculator you would probably
3970: get the right answers, unless you were very cautious and entered them using
3971: these keystroke sequences:
1.21 crook 3972:
1.29 crook 3973: 6 + 5 = * 4 =
3974: 4 * 5 = + 6 =
1.21 crook 3975:
1.29 crook 3976: Postfix notation is unambiguous because the order that the operators
3977: are applied is always explicit; that also means that parentheses are
3978: never required. The operators are @i{active} (the act of quoting the
3979: operator makes the operation occur) which removes the need for ``=''.
1.28 crook 3980:
1.29 crook 3981: The sum 6 + 5 * 4 can be written (in postfix notation) in two
3982: equivalent ways:
1.26 crook 3983:
3984: @example
1.29 crook 3985: 6 5 4 * + or:
3986: 5 4 * 6 +
1.26 crook 3987: @end example
1.23 crook 3988:
1.29 crook 3989: An important thing that you should notice about this notation is that
3990: the @i{order} of the numbers does not change; if you want to subtract
3991: 2 from 10 you type @code{10 2 -}.
1.1 anton 3992:
1.29 crook 3993: The reason that Forth uses postfix notation is very simple to explain: it
3994: makes the implementation extremely simple, and it follows naturally from
3995: using the stack as a mechanism for passing parameters. Another way of
3996: thinking about this is to realise that all Forth definitions are
3997: @i{active}; they execute as they are encountered by the text
3998: interpreter. The result of this is that the syntax of Forth is trivially
3999: simple.
1.1 anton 4000:
4001:
4002:
1.29 crook 4003: @comment ----------------------------------------------
4004: @node Your first definition, How does that work?, Stacks and Postfix notation, Introduction
4005: @section Your first Forth definition
4006: @cindex first definition
1.1 anton 4007:
1.29 crook 4008: Until now, the examples we've seen have been trivial; we've just been
4009: using Forth as a bigger-than-pocket calculator. Also, each calculation
4010: we've shown has been a ``one-off'' -- to repeat it we'd need to type it in
4011: again@footnote{That's not quite true. If you press the up-arrow key on
4012: your keyboard you should be able to scroll back to any earlier command,
4013: edit it and re-enter it.} In this section we'll see how to add new
4014: words to Forth's vocabulary.
1.1 anton 4015:
1.29 crook 4016: The easiest way to create a new word is to use a @dfn{colon
4017: definition}. We'll define a few and try them out before worrying too
4018: much about how they work. Try typing in these examples; be careful to
4019: copy the spaces accurately:
1.1 anton 4020:
1.29 crook 4021: @example
4022: : add-two 2 + . ;
4023: : greet ." Hello and welcome" ;
4024: : demo 5 add-two ;
4025: @end example
1.1 anton 4026:
1.29 crook 4027: @noindent
4028: Now try them out:
1.1 anton 4029:
1.29 crook 4030: @example
1.30 anton 4031: @kbd{greet@key{RET}} Hello and welcome ok
4032: @kbd{greet greet@key{RET}} Hello and welcomeHello and welcome ok
4033: @kbd{4 add-two@key{RET}} 6 ok
4034: @kbd{demo@key{RET}} 7 ok
4035: @kbd{9 greet demo add-two@key{RET}} Hello and welcome7 11 ok
1.29 crook 4036: @end example
1.1 anton 4037:
1.29 crook 4038: The first new thing that we've introduced here is the pair of words
4039: @code{:} and @code{;}. These are used to start and terminate a new
4040: definition, respectively. The first word after the @code{:} is the name
4041: for the new definition.
1.1 anton 4042:
1.29 crook 4043: As you can see from the examples, a definition is built up of words that
4044: have already been defined; Forth makes no distinction between
4045: definitions that existed when you started the system up, and those that
4046: you define yourself.
1.1 anton 4047:
1.29 crook 4048: The examples also introduce the words @code{.} (dot), @code{."}
4049: (dot-quote) and @code{dup} (dewp). Dot takes the value from the top of
4050: the stack and displays it. It's like @code{.s} except that it only
4051: displays the top item of the stack and it is destructive; after it has
4052: executed, the number is no longer on the stack. There is always one
4053: space printed after the number, and no spaces before it. Dot-quote
4054: defines a string (a sequence of characters) that will be printed when
4055: the word is executed. The string can contain any printable characters
4056: except @code{"}. A @code{"} has a special function; it is not a Forth
4057: word but it acts as a delimiter (the way that delimiters work is
4058: described in the next section). Finally, @code{dup} duplicates the value
4059: at the top of the stack. Try typing @code{5 dup .s} to see what it does.
1.1 anton 4060:
1.29 crook 4061: We already know that the text interpreter searches through the
4062: dictionary to locate names. If you've followed the examples earlier, you
4063: will already have a definition called @code{add-two}. Lets try modifying
4064: it by typing in a new definition:
1.1 anton 4065:
1.29 crook 4066: @example
1.30 anton 4067: @kbd{: add-two dup . ." + 2 =" 2 + . ;@key{RET}} redefined add-two ok
1.29 crook 4068: @end example
1.5 anton 4069:
1.29 crook 4070: Forth recognised that we were defining a word that already exists, and
4071: printed a message to warn us of that fact. Let's try out the new
4072: definition:
1.5 anton 4073:
1.29 crook 4074: @example
1.30 anton 4075: @kbd{9 add-two@key{RET}} 9 + 2 =11 ok
1.29 crook 4076: @end example
1.1 anton 4077:
1.29 crook 4078: @noindent
4079: All that we've actually done here, though, is to create a new
4080: definition, with a particular name. The fact that there was already a
4081: definition with the same name did not make any difference to the way
4082: that the new definition was created (except that Forth printed a warning
4083: message). The old definition of add-two still exists (try @code{demo}
4084: again to see that this is true). Any new definition will use the new
4085: definition of @code{add-two}, but old definitions continue to use the
4086: version that already existed at the time that they were @code{compiled}.
1.1 anton 4087:
1.29 crook 4088: Before you go on to the next section, try defining and redefining some
4089: words of your own.
1.1 anton 4090:
1.29 crook 4091: @comment ----------------------------------------------
4092: @node How does that work?, Forth is written in Forth, Your first definition, Introduction
4093: @section How does that work?
4094: @cindex parsing words
1.1 anton 4095:
1.30 anton 4096: @c That's pretty deep (IMO way too deep) for an introduction. - anton
4097:
4098: @c Is it a good idea to talk about the interpretation semantics of a
4099: @c number? We don't have an xt to go along with it. - anton
4100:
4101: @c Now that I have eliminated execution semantics, I wonder if it would not
4102: @c be better to keep them (or add run-time semantics), to make it easier to
4103: @c explain what compilation semantics usually does. - anton
4104:
1.44 crook 4105: @c nac-> I removed the term ``default compilation sematics'' from the
4106: @c introductory chapter. Removing ``execution semantics'' was making
4107: @c everything simpler to explain, then I think the use of this term made
4108: @c everything more complex again. I replaced it with ``default
4109: @c semantics'' (which is used elsewhere in the manual) by which I mean
4110: @c ``a definition that has neither the immediate nor the compile-only
1.83 anton 4111: @c flag set''.
4112:
4113: @c anton: I have eliminated default semantics (except in one place where it
4114: @c means "default interpretation and compilation semantics"), because it
4115: @c makes no sense in the presence of combined words. I reverted to
4116: @c "execution semantics" where necessary.
4117:
4118: @c nac-> I reworded big chunks of the ``how does that work''
1.44 crook 4119: @c section (and, unusually for me, I think I even made it shorter!). See
4120: @c what you think -- I know I have not addressed your primary concern
4121: @c that it is too heavy-going for an introduction. From what I understood
4122: @c of your course notes it looks as though they might be a good framework.
4123: @c Things that I've tried to capture here are some things that came as a
4124: @c great revelation here when I first understood them. Also, I like the
4125: @c fact that a very simple code example shows up almost all of the issues
4126: @c that you need to understand to see how Forth works. That's unique and
4127: @c worthwhile to emphasise.
4128:
1.83 anton 4129: @c anton: I think it's a good idea to present the details, especially those
4130: @c that you found to be a revelation, and probably the tutorial tries to be
4131: @c too superficial and does not get some of the things across that make
4132: @c Forth special. I do believe that most of the time these things should
4133: @c be discussed at the end of a section or in separate sections instead of
4134: @c in the middle of a section (e.g., the stuff you added in "User-defined
4135: @c defining words" leads in a completely different direction from the rest
4136: @c of the section).
4137:
1.29 crook 4138: Now we're going to take another look at the definition of @code{add-two}
4139: from the previous section. From our knowledge of the way that the text
4140: interpreter works, we would have expected this result when we tried to
4141: define @code{add-two}:
1.21 crook 4142:
1.29 crook 4143: @example
1.44 crook 4144: @kbd{: add-two 2 + . ;@key{RET}}
1.29 crook 4145: ^^^^^^^
4146: Error: Undefined word
4147: @end example
1.28 crook 4148:
1.29 crook 4149: The reason that this didn't happen is bound up in the way that @code{:}
4150: works. The word @code{:} does two special things. The first special
4151: thing that it does prevents the text interpreter from ever seeing the
4152: characters @code{add-two}. The text interpreter uses a variable called
4153: @cindex modifying >IN
1.44 crook 4154: @code{>IN} (pronounced ``to-in'') to keep track of where it is in the
1.29 crook 4155: input line. When it encounters the word @code{:} it behaves in exactly
4156: the same way as it does for any other word; it looks it up in the name
4157: dictionary, finds its xt and executes it. When @code{:} executes, it
4158: looks at the input buffer, finds the word @code{add-two} and advances the
4159: value of @code{>IN} to point past it. It then does some other stuff
4160: associated with creating the new definition (including creating an entry
4161: for @code{add-two} in the name dictionary). When the execution of @code{:}
4162: completes, control returns to the text interpreter, which is oblivious
4163: to the fact that it has been tricked into ignoring part of the input
4164: line.
1.21 crook 4165:
1.29 crook 4166: @cindex parsing words
4167: Words like @code{:} -- words that advance the value of @code{>IN} and so
4168: prevent the text interpreter from acting on the whole of the input line
4169: -- are called @dfn{parsing words}.
1.21 crook 4170:
1.29 crook 4171: @cindex @code{state} - effect on the text interpreter
4172: @cindex text interpreter - effect of state
4173: The second special thing that @code{:} does is change the value of a
4174: variable called @code{state}, which affects the way that the text
4175: interpreter behaves. When Gforth starts up, @code{state} has the value
4176: 0, and the text interpreter is said to be @dfn{interpreting}. During a
4177: colon definition (started with @code{:}), @code{state} is set to -1 and
1.44 crook 4178: the text interpreter is said to be @dfn{compiling}.
4179:
4180: In this example, the text interpreter is compiling when it processes the
4181: string ``@code{2 + . ;}''. It still breaks the string down into
4182: character sequences in the same way. However, instead of pushing the
4183: number @code{2} onto the stack, it lays down (@dfn{compiles}) some magic
4184: into the definition of @code{add-two} that will make the number @code{2} get
4185: pushed onto the stack when @code{add-two} is @dfn{executed}. Similarly,
4186: the behaviours of @code{+} and @code{.} are also compiled into the
4187: definition.
4188:
4189: One category of words don't get compiled. These so-called @dfn{immediate
4190: words} get executed (performed @i{now}) regardless of whether the text
4191: interpreter is interpreting or compiling. The word @code{;} is an
4192: immediate word. Rather than being compiled into the definition, it
4193: executes. Its effect is to terminate the current definition, which
4194: includes changing the value of @code{state} back to 0.
4195:
4196: When you execute @code{add-two}, it has a @dfn{run-time effect} that is
4197: exactly the same as if you had typed @code{2 + . @key{RET}} outside of a
4198: definition.
1.28 crook 4199:
1.30 anton 4200: In Forth, every word or number can be described in terms of two
1.29 crook 4201: properties:
1.28 crook 4202:
4203: @itemize @bullet
4204: @item
1.29 crook 4205: @cindex interpretation semantics
1.44 crook 4206: Its @dfn{interpretation semantics} describe how it will behave when the
4207: text interpreter encounters it in @dfn{interpret} state. The
4208: interpretation semantics of a word are represented by an @dfn{execution
4209: token}.
1.28 crook 4210: @item
1.29 crook 4211: @cindex compilation semantics
1.44 crook 4212: Its @dfn{compilation semantics} describe how it will behave when the
4213: text interpreter encounters it in @dfn{compile} state. The compilation
4214: semantics of a word are represented in an implementation-dependent way;
4215: Gforth uses a @dfn{compilation token}.
1.29 crook 4216: @end itemize
4217:
4218: @noindent
4219: Numbers are always treated in a fixed way:
4220:
4221: @itemize @bullet
1.28 crook 4222: @item
1.44 crook 4223: When the number is @dfn{interpreted}, its behaviour is to push the
4224: number onto the stack.
1.28 crook 4225: @item
1.30 anton 4226: When the number is @dfn{compiled}, a piece of code is appended to the
4227: current definition that pushes the number when it runs. (In other words,
4228: the compilation semantics of a number are to postpone its interpretation
4229: semantics until the run-time of the definition that it is being compiled
4230: into.)
1.29 crook 4231: @end itemize
4232:
1.44 crook 4233: Words don't behave in such a regular way, but most have @i{default
4234: semantics} which means that they behave like this:
1.29 crook 4235:
4236: @itemize @bullet
1.28 crook 4237: @item
1.30 anton 4238: The @dfn{interpretation semantics} of the word are to do something useful.
4239: @item
1.29 crook 4240: The @dfn{compilation semantics} of the word are to append its
1.30 anton 4241: @dfn{interpretation semantics} to the current definition (so that its
4242: run-time behaviour is to do something useful).
1.28 crook 4243: @end itemize
4244:
1.30 anton 4245: @cindex immediate words
1.44 crook 4246: The actual behaviour of any particular word can be controlled by using
4247: the words @code{immediate} and @code{compile-only} when the word is
4248: defined. These words set flags in the name dictionary entry of the most
4249: recently defined word, and these flags are retrieved by the text
4250: interpreter when it finds the word in the name dictionary.
4251:
4252: A word that is marked as @dfn{immediate} has compilation semantics that
4253: are identical to its interpretation semantics. In other words, it
4254: behaves like this:
1.29 crook 4255:
4256: @itemize @bullet
4257: @item
1.30 anton 4258: The @dfn{interpretation semantics} of the word are to do something useful.
1.29 crook 4259: @item
1.30 anton 4260: The @dfn{compilation semantics} of the word are to do something useful
4261: (and actually the same thing); i.e., it is executed during compilation.
1.29 crook 4262: @end itemize
1.28 crook 4263:
1.44 crook 4264: Marking a word as @dfn{compile-only} prohibits the text interpreter from
4265: performing the interpretation semantics of the word directly; an attempt
4266: to do so will generate an error. It is never necessary to use
4267: @code{compile-only} (and it is not even part of ANS Forth, though it is
4268: provided by many implementations) but it is good etiquette to apply it
4269: to a word that will not behave correctly (and might have unexpected
4270: side-effects) in interpret state. For example, it is only legal to use
4271: the conditional word @code{IF} within a definition. If you forget this
4272: and try to use it elsewhere, the fact that (in Gforth) it is marked as
4273: @code{compile-only} allows the text interpreter to generate a helpful
4274: error message rather than subjecting you to the consequences of your
4275: folly.
4276:
1.29 crook 4277: This example shows the difference between an immediate and a
4278: non-immediate word:
1.28 crook 4279:
1.29 crook 4280: @example
4281: : show-state state @@ . ;
4282: : show-state-now show-state ; immediate
4283: : word1 show-state ;
4284: : word2 show-state-now ;
1.28 crook 4285: @end example
1.23 crook 4286:
1.29 crook 4287: The word @code{immediate} after the definition of @code{show-state-now}
4288: makes that word an immediate word. These definitions introduce a new
4289: word: @code{@@} (pronounced ``fetch''). This word fetches the value of a
4290: variable, and leaves it on the stack. Therefore, the behaviour of
4291: @code{show-state} is to print a number that represents the current value
4292: of @code{state}.
1.28 crook 4293:
1.29 crook 4294: When you execute @code{word1}, it prints the number 0, indicating that
4295: the system is interpreting. When the text interpreter compiled the
4296: definition of @code{word1}, it encountered @code{show-state} whose
1.30 anton 4297: compilation semantics are to append its interpretation semantics to the
1.29 crook 4298: current definition. When you execute @code{word1}, it performs the
1.30 anton 4299: interpretation semantics of @code{show-state}. At the time that @code{word1}
1.29 crook 4300: (and therefore @code{show-state}) are executed, the system is
4301: interpreting.
1.28 crook 4302:
1.30 anton 4303: When you pressed @key{RET} after entering the definition of @code{word2},
1.29 crook 4304: you should have seen the number -1 printed, followed by ``@code{
4305: ok}''. When the text interpreter compiled the definition of
4306: @code{word2}, it encountered @code{show-state-now}, an immediate word,
1.30 anton 4307: whose compilation semantics are therefore to perform its interpretation
1.29 crook 4308: semantics. It is executed straight away (even before the text
4309: interpreter has moved on to process another group of characters; the
4310: @code{;} in this example). The effect of executing it are to display the
4311: value of @code{state} @i{at the time that the definition of}
4312: @code{word2} @i{is being defined}. Printing -1 demonstrates that the
4313: system is compiling at this time. If you execute @code{word2} it does
4314: nothing at all.
1.28 crook 4315:
1.29 crook 4316: @cindex @code{."}, how it works
4317: Before leaving the subject of immediate words, consider the behaviour of
4318: @code{."} in the definition of @code{greet}, in the previous
4319: section. This word is both a parsing word and an immediate word. Notice
4320: that there is a space between @code{."} and the start of the text
4321: @code{Hello and welcome}, but that there is no space between the last
4322: letter of @code{welcome} and the @code{"} character. The reason for this
4323: is that @code{."} is a Forth word; it must have a space after it so that
4324: the text interpreter can identify it. The @code{"} is not a Forth word;
4325: it is a @dfn{delimiter}. The examples earlier show that, when the string
4326: is displayed, there is neither a space before the @code{H} nor after the
4327: @code{e}. Since @code{."} is an immediate word, it executes at the time
4328: that @code{greet} is defined. When it executes, its behaviour is to
4329: search forward in the input line looking for the delimiter. When it
4330: finds the delimiter, it updates @code{>IN} to point past the
4331: delimiter. It also compiles some magic code into the definition of
4332: @code{greet}; the xt of a run-time routine that prints a text string. It
4333: compiles the string @code{Hello and welcome} into memory so that it is
4334: available to be printed later. When the text interpreter gains control,
4335: the next word it finds in the input stream is @code{;} and so it
4336: terminates the definition of @code{greet}.
1.28 crook 4337:
4338:
4339: @comment ----------------------------------------------
1.29 crook 4340: @node Forth is written in Forth, Review - elements of a Forth system, How does that work?, Introduction
4341: @section Forth is written in Forth
4342: @cindex structure of Forth programs
4343:
4344: When you start up a Forth compiler, a large number of definitions
4345: already exist. In Forth, you develop a new application using bottom-up
4346: programming techniques to create new definitions that are defined in
4347: terms of existing definitions. As you create each definition you can
4348: test and debug it interactively.
4349:
4350: If you have tried out the examples in this section, you will probably
4351: have typed them in by hand; when you leave Gforth, your definitions will
4352: be lost. You can avoid this by using a text editor to enter Forth source
4353: code into a file, and then loading code from the file using
1.49 anton 4354: @code{include} (@pxref{Forth source files}). A Forth source file is
1.29 crook 4355: processed by the text interpreter, just as though you had typed it in by
4356: hand@footnote{Actually, there are some subtle differences -- see
4357: @ref{The Text Interpreter}.}.
4358:
4359: Gforth also supports the traditional Forth alternative to using text
1.49 anton 4360: files for program entry (@pxref{Blocks}).
1.28 crook 4361:
1.29 crook 4362: In common with many, if not most, Forth compilers, most of Gforth is
4363: actually written in Forth. All of the @file{.fs} files in the
4364: installation directory@footnote{For example,
1.30 anton 4365: @file{/usr/local/share/gforth...}} are Forth source files, which you can
1.29 crook 4366: study to see examples of Forth programming.
1.28 crook 4367:
1.29 crook 4368: Gforth maintains a history file that records every line that you type to
4369: the text interpreter. This file is preserved between sessions, and is
4370: used to provide a command-line recall facility. If you enter long
4371: definitions by hand, you can use a text editor to paste them out of the
4372: history file into a Forth source file for reuse at a later time
1.49 anton 4373: (for more information @pxref{Command-line editing}).
1.28 crook 4374:
4375:
4376: @comment ----------------------------------------------
1.29 crook 4377: @node Review - elements of a Forth system, Where to go next, Forth is written in Forth, Introduction
4378: @section Review - elements of a Forth system
4379: @cindex elements of a Forth system
1.28 crook 4380:
1.29 crook 4381: To summarise this chapter:
1.28 crook 4382:
4383: @itemize @bullet
4384: @item
1.29 crook 4385: Forth programs use @dfn{factoring} to break a problem down into small
4386: fragments called @dfn{words} or @dfn{definitions}.
4387: @item
4388: Forth program development is an interactive process.
4389: @item
4390: The main command loop that accepts input, and controls both
4391: interpretation and compilation, is called the @dfn{text interpreter}
4392: (also known as the @dfn{outer interpreter}).
4393: @item
4394: Forth has a very simple syntax, consisting of words and numbers
4395: separated by spaces or carriage-return characters. Any additional syntax
4396: is imposed by @dfn{parsing words}.
4397: @item
4398: Forth uses a stack to pass parameters between words. As a result, it
4399: uses postfix notation.
4400: @item
4401: To use a word that has previously been defined, the text interpreter
4402: searches for the word in the @dfn{name dictionary}.
4403: @item
1.30 anton 4404: Words have @dfn{interpretation semantics} and @dfn{compilation semantics}.
1.28 crook 4405: @item
1.29 crook 4406: The text interpreter uses the value of @code{state} to select between
4407: the use of the @dfn{interpretation semantics} and the @dfn{compilation
4408: semantics} of a word that it encounters.
1.28 crook 4409: @item
1.30 anton 4410: The relationship between the @dfn{interpretation semantics} and
4411: @dfn{compilation semantics} for a word
1.29 crook 4412: depend upon the way in which the word was defined (for example, whether
4413: it is an @dfn{immediate} word).
1.28 crook 4414: @item
1.29 crook 4415: Forth definitions can be implemented in Forth (called @dfn{high-level
4416: definitions}) or in some other way (usually a lower-level language and
4417: as a result often called @dfn{low-level definitions}, @dfn{code
4418: definitions} or @dfn{primitives}).
1.28 crook 4419: @item
1.29 crook 4420: Many Forth systems are implemented mainly in Forth.
1.28 crook 4421: @end itemize
4422:
4423:
1.29 crook 4424: @comment ----------------------------------------------
1.48 anton 4425: @node Where to go next, Exercises, Review - elements of a Forth system, Introduction
1.29 crook 4426: @section Where To Go Next
4427: @cindex where to go next
1.28 crook 4428:
1.29 crook 4429: Amazing as it may seem, if you have read (and understood) this far, you
4430: know almost all the fundamentals about the inner workings of a Forth
4431: system. You certainly know enough to be able to read and understand the
4432: rest of this manual and the ANS Forth document, to learn more about the
4433: facilities that Forth in general and Gforth in particular provide. Even
4434: scarier, you know almost enough to implement your own Forth system.
1.30 anton 4435: However, that's not a good idea just yet... better to try writing some
1.29 crook 4436: programs in Gforth.
1.28 crook 4437:
1.29 crook 4438: Forth has such a rich vocabulary that it can be hard to know where to
4439: start in learning it. This section suggests a few sets of words that are
4440: enough to write small but useful programs. Use the word index in this
4441: document to learn more about each word, then try it out and try to write
4442: small definitions using it. Start by experimenting with these words:
1.28 crook 4443:
4444: @itemize @bullet
4445: @item
1.29 crook 4446: Arithmetic: @code{+ - * / /MOD */ ABS INVERT}
4447: @item
4448: Comparison: @code{MIN MAX =}
4449: @item
4450: Logic: @code{AND OR XOR NOT}
4451: @item
4452: Stack manipulation: @code{DUP DROP SWAP OVER}
1.28 crook 4453: @item
1.29 crook 4454: Loops and decisions: @code{IF ELSE ENDIF ?DO I LOOP}
1.28 crook 4455: @item
1.29 crook 4456: Input/Output: @code{. ." EMIT CR KEY}
1.28 crook 4457: @item
1.29 crook 4458: Defining words: @code{: ; CREATE}
1.28 crook 4459: @item
1.29 crook 4460: Memory allocation words: @code{ALLOT ,}
1.28 crook 4461: @item
1.29 crook 4462: Tools: @code{SEE WORDS .S MARKER}
4463: @end itemize
4464:
4465: When you have mastered those, go on to:
4466:
4467: @itemize @bullet
1.28 crook 4468: @item
1.29 crook 4469: More defining words: @code{VARIABLE CONSTANT VALUE TO CREATE DOES>}
1.28 crook 4470: @item
1.29 crook 4471: Memory access: @code{@@ !}
1.28 crook 4472: @end itemize
1.23 crook 4473:
1.29 crook 4474: When you have mastered these, there's nothing for it but to read through
4475: the whole of this manual and find out what you've missed.
4476:
4477: @comment ----------------------------------------------
1.48 anton 4478: @node Exercises, , Where to go next, Introduction
1.29 crook 4479: @section Exercises
4480: @cindex exercises
4481:
4482: TODO: provide a set of programming excercises linked into the stuff done
4483: already and into other sections of the manual. Provide solutions to all
4484: the exercises in a .fs file in the distribution.
4485:
4486: @c Get some inspiration from Starting Forth and Kelly&Spies.
4487:
4488: @c excercises:
4489: @c 1. take inches and convert to feet and inches.
4490: @c 2. take temperature and convert from fahrenheight to celcius;
4491: @c may need to care about symmetric vs floored??
4492: @c 3. take input line and do character substitution
4493: @c to encipher or decipher
4494: @c 4. as above but work on a file for in and out
4495: @c 5. take input line and convert to pig-latin
4496: @c
4497: @c thing of sets of things to exercise then come up with
4498: @c problems that need those things.
4499:
4500:
1.26 crook 4501: @c ******************************************************************
1.29 crook 4502: @node Words, Error messages, Introduction, Top
1.1 anton 4503: @chapter Forth Words
1.26 crook 4504: @cindex words
1.1 anton 4505:
4506: @menu
4507: * Notation::
1.65 anton 4508: * Case insensitivity::
4509: * Comments::
4510: * Boolean Flags::
1.1 anton 4511: * Arithmetic::
4512: * Stack Manipulation::
1.5 anton 4513: * Memory::
1.1 anton 4514: * Control Structures::
4515: * Defining Words::
1.65 anton 4516: * Interpretation and Compilation Semantics::
1.47 crook 4517: * Tokens for Words::
1.81 anton 4518: * Compiling words::
1.65 anton 4519: * The Text Interpreter::
4520: * Word Lists::
4521: * Environmental Queries::
1.12 anton 4522: * Files::
4523: * Blocks::
4524: * Other I/O::
1.78 anton 4525: * Locals::
4526: * Structures::
4527: * Object-oriented Forth::
1.12 anton 4528: * Programming Tools::
4529: * Assembler and Code Words::
4530: * Threading Words::
1.65 anton 4531: * Passing Commands to the OS::
4532: * Keeping track of Time::
4533: * Miscellaneous Words::
1.1 anton 4534: @end menu
4535:
1.65 anton 4536: @node Notation, Case insensitivity, Words, Words
1.1 anton 4537: @section Notation
4538: @cindex notation of glossary entries
4539: @cindex format of glossary entries
4540: @cindex glossary notation format
4541: @cindex word glossary entry format
4542:
4543: The Forth words are described in this section in the glossary notation
1.67 anton 4544: that has become a de-facto standard for Forth texts:
1.1 anton 4545:
4546: @format
1.29 crook 4547: @i{word} @i{Stack effect} @i{wordset} @i{pronunciation}
1.1 anton 4548: @end format
1.29 crook 4549: @i{Description}
1.1 anton 4550:
4551: @table @var
4552: @item word
1.28 crook 4553: The name of the word.
1.1 anton 4554:
4555: @item Stack effect
4556: @cindex stack effect
1.29 crook 4557: The stack effect is written in the notation @code{@i{before} --
4558: @i{after}}, where @i{before} and @i{after} describe the top of
1.1 anton 4559: stack entries before and after the execution of the word. The rest of
4560: the stack is not touched by the word. The top of stack is rightmost,
4561: i.e., a stack sequence is written as it is typed in. Note that Gforth
4562: uses a separate floating point stack, but a unified stack
1.29 crook 4563: notation. Also, return stack effects are not shown in @i{stack
4564: effect}, but in @i{Description}. The name of a stack item describes
1.1 anton 4565: the type and/or the function of the item. See below for a discussion of
4566: the types.
4567:
4568: All words have two stack effects: A compile-time stack effect and a
4569: run-time stack effect. The compile-time stack-effect of most words is
1.29 crook 4570: @i{ -- }. If the compile-time stack-effect of a word deviates from
1.1 anton 4571: this standard behaviour, or the word does other unusual things at
4572: compile time, both stack effects are shown; otherwise only the run-time
4573: stack effect is shown.
4574:
4575: @cindex pronounciation of words
4576: @item pronunciation
4577: How the word is pronounced.
4578:
4579: @cindex wordset
1.67 anton 4580: @cindex environment wordset
1.1 anton 4581: @item wordset
1.21 crook 4582: The ANS Forth standard is divided into several word sets. A standard
4583: system need not support all of them. Therefore, in theory, the fewer
4584: word sets your program uses the more portable it will be. However, we
4585: suspect that most ANS Forth systems on personal machines will feature
1.26 crook 4586: all word sets. Words that are not defined in ANS Forth have
1.21 crook 4587: @code{gforth} or @code{gforth-internal} as word set. @code{gforth}
1.1 anton 4588: describes words that will work in future releases of Gforth;
4589: @code{gforth-internal} words are more volatile. Environmental query
4590: strings are also displayed like words; you can recognize them by the
1.21 crook 4591: @code{environment} in the word set field.
1.1 anton 4592:
4593: @item Description
4594: A description of the behaviour of the word.
4595: @end table
4596:
4597: @cindex types of stack items
4598: @cindex stack item types
4599: The type of a stack item is specified by the character(s) the name
4600: starts with:
4601:
4602: @table @code
4603: @item f
4604: @cindex @code{f}, stack item type
4605: Boolean flags, i.e. @code{false} or @code{true}.
4606: @item c
4607: @cindex @code{c}, stack item type
4608: Char
4609: @item w
4610: @cindex @code{w}, stack item type
4611: Cell, can contain an integer or an address
4612: @item n
4613: @cindex @code{n}, stack item type
4614: signed integer
4615: @item u
4616: @cindex @code{u}, stack item type
4617: unsigned integer
4618: @item d
4619: @cindex @code{d}, stack item type
4620: double sized signed integer
4621: @item ud
4622: @cindex @code{ud}, stack item type
4623: double sized unsigned integer
4624: @item r
4625: @cindex @code{r}, stack item type
4626: Float (on the FP stack)
1.21 crook 4627: @item a-
1.1 anton 4628: @cindex @code{a_}, stack item type
4629: Cell-aligned address
1.21 crook 4630: @item c-
1.1 anton 4631: @cindex @code{c_}, stack item type
4632: Char-aligned address (note that a Char may have two bytes in Windows NT)
1.21 crook 4633: @item f-
1.1 anton 4634: @cindex @code{f_}, stack item type
4635: Float-aligned address
1.21 crook 4636: @item df-
1.1 anton 4637: @cindex @code{df_}, stack item type
4638: Address aligned for IEEE double precision float
1.21 crook 4639: @item sf-
1.1 anton 4640: @cindex @code{sf_}, stack item type
4641: Address aligned for IEEE single precision float
4642: @item xt
4643: @cindex @code{xt}, stack item type
4644: Execution token, same size as Cell
4645: @item wid
4646: @cindex @code{wid}, stack item type
1.21 crook 4647: Word list ID, same size as Cell
1.68 anton 4648: @item ior, wior
4649: @cindex ior type description
4650: @cindex wior type description
4651: I/O result code, cell-sized. In Gforth, you can @code{throw} iors.
1.1 anton 4652: @item f83name
4653: @cindex @code{f83name}, stack item type
4654: Pointer to a name structure
4655: @item "
4656: @cindex @code{"}, stack item type
1.12 anton 4657: string in the input stream (not on the stack). The terminating character
4658: is a blank by default. If it is not a blank, it is shown in @code{<>}
1.1 anton 4659: quotes.
4660: @end table
4661:
1.65 anton 4662: @comment ----------------------------------------------
4663: @node Case insensitivity, Comments, Notation, Words
4664: @section Case insensitivity
4665: @cindex case sensitivity
4666: @cindex upper and lower case
4667:
4668: Gforth is case-insensitive; you can enter definitions and invoke
4669: Standard words using upper, lower or mixed case (however,
4670: @pxref{core-idef, Implementation-defined options, Implementation-defined
4671: options}).
4672:
4673: ANS Forth only @i{requires} implementations to recognise Standard words
4674: when they are typed entirely in upper case. Therefore, a Standard
4675: program must use upper case for all Standard words. You can use whatever
4676: case you like for words that you define, but in a Standard program you
4677: have to use the words in the same case that you defined them.
4678:
4679: Gforth supports case sensitivity through @code{table}s (case-sensitive
4680: wordlists, @pxref{Word Lists}).
4681:
4682: Two people have asked how to convert Gforth to be case-sensitive; while
4683: we think this is a bad idea, you can change all wordlists into tables
4684: like this:
4685:
4686: @example
4687: ' table-find forth-wordlist wordlist-map @ !
4688: @end example
4689:
4690: Note that you now have to type the predefined words in the same case
4691: that we defined them, which are varying. You may want to convert them
4692: to your favourite case before doing this operation (I won't explain how,
4693: because if you are even contemplating doing this, you'd better have
4694: enough knowledge of Forth systems to know this already).
4695:
4696: @node Comments, Boolean Flags, Case insensitivity, Words
1.21 crook 4697: @section Comments
1.26 crook 4698: @cindex comments
1.21 crook 4699:
1.29 crook 4700: Forth supports two styles of comment; the traditional @i{in-line} comment,
4701: @code{(} and its modern cousin, the @i{comment to end of line}; @code{\}.
1.21 crook 4702:
1.44 crook 4703:
1.23 crook 4704: doc-(
1.21 crook 4705: doc-\
1.23 crook 4706: doc-\G
1.21 crook 4707:
1.44 crook 4708:
1.21 crook 4709: @node Boolean Flags, Arithmetic, Comments, Words
4710: @section Boolean Flags
1.26 crook 4711: @cindex Boolean flags
1.21 crook 4712:
4713: A Boolean flag is cell-sized. A cell with all bits clear represents the
4714: flag @code{false} and a flag with all bits set represents the flag
1.26 crook 4715: @code{true}. Words that check a flag (for example, @code{IF}) will treat
1.29 crook 4716: a cell that has @i{any} bit set as @code{true}.
1.67 anton 4717: @c on and off to Memory?
4718: @c true and false to "Bitwise operations" or "Numeric comparison"?
1.44 crook 4719:
1.21 crook 4720: doc-true
4721: doc-false
1.29 crook 4722: doc-on
4723: doc-off
1.21 crook 4724:
1.44 crook 4725:
1.21 crook 4726: @node Arithmetic, Stack Manipulation, Boolean Flags, Words
1.1 anton 4727: @section Arithmetic
4728: @cindex arithmetic words
4729:
4730: @cindex division with potentially negative operands
4731: Forth arithmetic is not checked, i.e., you will not hear about integer
4732: overflow on addition or multiplication, you may hear about division by
4733: zero if you are lucky. The operator is written after the operands, but
4734: the operands are still in the original order. I.e., the infix @code{2-1}
4735: corresponds to @code{2 1 -}. Forth offers a variety of division
4736: operators. If you perform division with potentially negative operands,
4737: you do not want to use @code{/} or @code{/mod} with its undefined
4738: behaviour, but rather @code{fm/mod} or @code{sm/mod} (probably the
4739: former, @pxref{Mixed precision}).
1.26 crook 4740: @comment TODO discuss the different division forms and the std approach
1.1 anton 4741:
4742: @menu
4743: * Single precision::
1.67 anton 4744: * Double precision:: Double-cell integer arithmetic
1.1 anton 4745: * Bitwise operations::
1.67 anton 4746: * Numeric comparison::
1.29 crook 4747: * Mixed precision:: Operations with single and double-cell integers
1.1 anton 4748: * Floating Point::
4749: @end menu
4750:
1.67 anton 4751: @node Single precision, Double precision, Arithmetic, Arithmetic
1.1 anton 4752: @subsection Single precision
4753: @cindex single precision arithmetic words
4754:
1.67 anton 4755: @c !! cell undefined
4756:
4757: By default, numbers in Forth are single-precision integers that are one
1.26 crook 4758: cell in size. They can be signed or unsigned, depending upon how you
1.49 anton 4759: treat them. For the rules used by the text interpreter for recognising
4760: single-precision integers see @ref{Number Conversion}.
1.21 crook 4761:
1.67 anton 4762: These words are all defined for signed operands, but some of them also
4763: work for unsigned numbers: @code{+}, @code{1+}, @code{-}, @code{1-},
4764: @code{*}.
1.44 crook 4765:
1.1 anton 4766: doc-+
1.21 crook 4767: doc-1+
1.1 anton 4768: doc--
1.21 crook 4769: doc-1-
1.1 anton 4770: doc-*
4771: doc-/
4772: doc-mod
4773: doc-/mod
4774: doc-negate
4775: doc-abs
4776: doc-min
4777: doc-max
1.27 crook 4778: doc-floored
1.1 anton 4779:
1.44 crook 4780:
1.67 anton 4781: @node Double precision, Bitwise operations, Single precision, Arithmetic
1.21 crook 4782: @subsection Double precision
4783: @cindex double precision arithmetic words
4784:
1.49 anton 4785: For the rules used by the text interpreter for
4786: recognising double-precision integers, see @ref{Number Conversion}.
1.21 crook 4787:
4788: A double precision number is represented by a cell pair, with the most
1.67 anton 4789: significant cell at the TOS. It is trivial to convert an unsigned single
4790: to a double: simply push a @code{0} onto the TOS. Since numbers are
4791: represented by Gforth using 2's complement arithmetic, converting a
4792: signed single to a (signed) double requires sign-extension across the
4793: most significant cell. This can be achieved using @code{s>d}. The moral
4794: of the story is that you cannot convert a number without knowing whether
4795: it represents an unsigned or a signed number.
1.21 crook 4796:
1.67 anton 4797: These words are all defined for signed operands, but some of them also
4798: work for unsigned numbers: @code{d+}, @code{d-}.
1.44 crook 4799:
1.21 crook 4800: doc-s>d
1.67 anton 4801: doc-d>s
1.21 crook 4802: doc-d+
4803: doc-d-
4804: doc-dnegate
4805: doc-dabs
4806: doc-dmin
4807: doc-dmax
4808:
1.44 crook 4809:
1.67 anton 4810: @node Bitwise operations, Numeric comparison, Double precision, Arithmetic
4811: @subsection Bitwise operations
4812: @cindex bitwise operation words
4813:
4814:
4815: doc-and
4816: doc-or
4817: doc-xor
4818: doc-invert
4819: doc-lshift
4820: doc-rshift
4821: doc-2*
4822: doc-d2*
4823: doc-2/
4824: doc-d2/
4825:
4826:
4827: @node Numeric comparison, Mixed precision, Bitwise operations, Arithmetic
1.21 crook 4828: @subsection Numeric comparison
4829: @cindex numeric comparison words
4830:
1.67 anton 4831: Note that the words that compare for equality (@code{= <> 0= 0<> d= d<>
4832: d0= d0<>}) work for for both signed and unsigned numbers.
1.44 crook 4833:
1.28 crook 4834: doc-<
4835: doc-<=
4836: doc-<>
4837: doc-=
4838: doc->
4839: doc->=
4840:
1.21 crook 4841: doc-0<
1.23 crook 4842: doc-0<=
1.21 crook 4843: doc-0<>
4844: doc-0=
1.23 crook 4845: doc-0>
4846: doc-0>=
1.28 crook 4847:
4848: doc-u<
4849: doc-u<=
1.44 crook 4850: @c u<> and u= exist but are the same as <> and =
1.31 anton 4851: @c doc-u<>
4852: @c doc-u=
1.28 crook 4853: doc-u>
4854: doc-u>=
4855:
4856: doc-within
4857:
4858: doc-d<
4859: doc-d<=
4860: doc-d<>
4861: doc-d=
4862: doc-d>
4863: doc-d>=
1.23 crook 4864:
1.21 crook 4865: doc-d0<
1.23 crook 4866: doc-d0<=
4867: doc-d0<>
1.21 crook 4868: doc-d0=
1.23 crook 4869: doc-d0>
4870: doc-d0>=
4871:
1.21 crook 4872: doc-du<
1.28 crook 4873: doc-du<=
1.44 crook 4874: @c du<> and du= exist but are the same as d<> and d=
1.31 anton 4875: @c doc-du<>
4876: @c doc-du=
1.28 crook 4877: doc-du>
4878: doc-du>=
1.1 anton 4879:
1.44 crook 4880:
1.21 crook 4881: @node Mixed precision, Floating Point, Numeric comparison, Arithmetic
1.1 anton 4882: @subsection Mixed precision
4883: @cindex mixed precision arithmetic words
4884:
1.44 crook 4885:
1.1 anton 4886: doc-m+
4887: doc-*/
4888: doc-*/mod
4889: doc-m*
4890: doc-um*
4891: doc-m*/
4892: doc-um/mod
4893: doc-fm/mod
4894: doc-sm/rem
4895:
1.44 crook 4896:
1.21 crook 4897: @node Floating Point, , Mixed precision, Arithmetic
1.1 anton 4898: @subsection Floating Point
4899: @cindex floating point arithmetic words
4900:
1.49 anton 4901: For the rules used by the text interpreter for
4902: recognising floating-point numbers see @ref{Number Conversion}.
1.1 anton 4903:
1.67 anton 4904: Gforth has a separate floating point stack, but the documentation uses
4905: the unified notation.@footnote{It's easy to generate the separate
4906: notation from that by just separating the floating-point numbers out:
4907: e.g. @code{( n r1 u r2 -- r3 )} becomes @code{( n u -- ) ( F: r1 r2 --
4908: r3 )}.}
1.1 anton 4909:
4910: @cindex floating-point arithmetic, pitfalls
4911: Floating point numbers have a number of unpleasant surprises for the
4912: unwary (e.g., floating point addition is not associative) and even a few
4913: for the wary. You should not use them unless you know what you are doing
4914: or you don't care that the results you get are totally bogus. If you
4915: want to learn about the problems of floating point numbers (and how to
1.66 anton 4916: avoid them), you might start with @cite{David Goldberg,
4917: @uref{http://www.validgh.com/goldberg/paper.ps,What Every Computer
4918: Scientist Should Know About Floating-Point Arithmetic}, ACM Computing
4919: Surveys 23(1):5@minus{}48, March 1991}.
1.1 anton 4920:
1.44 crook 4921:
1.21 crook 4922: doc-d>f
4923: doc-f>d
1.1 anton 4924: doc-f+
4925: doc-f-
4926: doc-f*
4927: doc-f/
4928: doc-fnegate
4929: doc-fabs
4930: doc-fmax
4931: doc-fmin
4932: doc-floor
4933: doc-fround
4934: doc-f**
4935: doc-fsqrt
4936: doc-fexp
4937: doc-fexpm1
4938: doc-fln
4939: doc-flnp1
4940: doc-flog
4941: doc-falog
1.32 anton 4942: doc-f2*
4943: doc-f2/
4944: doc-1/f
4945: doc-precision
4946: doc-set-precision
4947:
4948: @cindex angles in trigonometric operations
4949: @cindex trigonometric operations
4950: Angles in floating point operations are given in radians (a full circle
4951: has 2 pi radians).
4952:
1.1 anton 4953: doc-fsin
4954: doc-fcos
4955: doc-fsincos
4956: doc-ftan
4957: doc-fasin
4958: doc-facos
4959: doc-fatan
4960: doc-fatan2
4961: doc-fsinh
4962: doc-fcosh
4963: doc-ftanh
4964: doc-fasinh
4965: doc-facosh
4966: doc-fatanh
1.21 crook 4967: doc-pi
1.28 crook 4968:
1.32 anton 4969: @cindex equality of floats
4970: @cindex floating-point comparisons
1.31 anton 4971: One particular problem with floating-point arithmetic is that comparison
4972: for equality often fails when you would expect it to succeed. For this
4973: reason approximate equality is often preferred (but you still have to
1.67 anton 4974: know what you are doing). Also note that IEEE NaNs may compare
1.68 anton 4975: differently from what you might expect. The comparison words are:
1.31 anton 4976:
4977: doc-f~rel
4978: doc-f~abs
1.68 anton 4979: doc-f~
1.31 anton 4980: doc-f=
4981: doc-f<>
4982:
4983: doc-f<
4984: doc-f<=
4985: doc-f>
4986: doc-f>=
4987:
1.21 crook 4988: doc-f0<
1.28 crook 4989: doc-f0<=
4990: doc-f0<>
1.21 crook 4991: doc-f0=
1.28 crook 4992: doc-f0>
4993: doc-f0>=
4994:
1.1 anton 4995:
4996: @node Stack Manipulation, Memory, Arithmetic, Words
4997: @section Stack Manipulation
4998: @cindex stack manipulation words
4999:
5000: @cindex floating-point stack in the standard
1.21 crook 5001: Gforth maintains a number of separate stacks:
5002:
1.29 crook 5003: @cindex data stack
5004: @cindex parameter stack
1.21 crook 5005: @itemize @bullet
5006: @item
1.29 crook 5007: A data stack (also known as the @dfn{parameter stack}) -- for
5008: characters, cells, addresses, and double cells.
1.21 crook 5009:
1.29 crook 5010: @cindex floating-point stack
1.21 crook 5011: @item
1.44 crook 5012: A floating point stack -- for holding floating point (FP) numbers.
1.21 crook 5013:
1.29 crook 5014: @cindex return stack
1.21 crook 5015: @item
1.44 crook 5016: A return stack -- for holding the return addresses of colon
1.32 anton 5017: definitions and other (non-FP) data.
1.21 crook 5018:
1.29 crook 5019: @cindex locals stack
1.21 crook 5020: @item
1.44 crook 5021: A locals stack -- for holding local variables.
1.21 crook 5022: @end itemize
5023:
1.1 anton 5024: @menu
5025: * Data stack::
5026: * Floating point stack::
5027: * Return stack::
5028: * Locals stack::
5029: * Stack pointer manipulation::
5030: @end menu
5031:
5032: @node Data stack, Floating point stack, Stack Manipulation, Stack Manipulation
5033: @subsection Data stack
5034: @cindex data stack manipulation words
5035: @cindex stack manipulations words, data stack
5036:
1.44 crook 5037:
1.1 anton 5038: doc-drop
5039: doc-nip
5040: doc-dup
5041: doc-over
5042: doc-tuck
5043: doc-swap
1.21 crook 5044: doc-pick
1.1 anton 5045: doc-rot
5046: doc--rot
5047: doc-?dup
5048: doc-roll
5049: doc-2drop
5050: doc-2nip
5051: doc-2dup
5052: doc-2over
5053: doc-2tuck
5054: doc-2swap
5055: doc-2rot
5056:
1.44 crook 5057:
1.1 anton 5058: @node Floating point stack, Return stack, Data stack, Stack Manipulation
5059: @subsection Floating point stack
5060: @cindex floating-point stack manipulation words
5061: @cindex stack manipulation words, floating-point stack
5062:
1.32 anton 5063: Whilst every sane Forth has a separate floating-point stack, it is not
5064: strictly required; an ANS Forth system could theoretically keep
5065: floating-point numbers on the data stack. As an additional difficulty,
5066: you don't know how many cells a floating-point number takes. It is
5067: reportedly possible to write words in a way that they work also for a
5068: unified stack model, but we do not recommend trying it. Instead, just
5069: say that your program has an environmental dependency on a separate
5070: floating-point stack.
5071:
5072: doc-floating-stack
5073:
1.1 anton 5074: doc-fdrop
5075: doc-fnip
5076: doc-fdup
5077: doc-fover
5078: doc-ftuck
5079: doc-fswap
1.21 crook 5080: doc-fpick
1.1 anton 5081: doc-frot
5082:
1.44 crook 5083:
1.1 anton 5084: @node Return stack, Locals stack, Floating point stack, Stack Manipulation
5085: @subsection Return stack
5086: @cindex return stack manipulation words
5087: @cindex stack manipulation words, return stack
5088:
1.32 anton 5089: @cindex return stack and locals
5090: @cindex locals and return stack
5091: A Forth system is allowed to keep local variables on the
5092: return stack. This is reasonable, as local variables usually eliminate
5093: the need to use the return stack explicitly. So, if you want to produce
5094: a standard compliant program and you are using local variables in a
5095: word, forget about return stack manipulations in that word (refer to the
5096: standard document for the exact rules).
5097:
1.1 anton 5098: doc->r
5099: doc-r>
5100: doc-r@
5101: doc-rdrop
5102: doc-2>r
5103: doc-2r>
5104: doc-2r@
5105: doc-2rdrop
5106:
1.44 crook 5107:
1.1 anton 5108: @node Locals stack, Stack pointer manipulation, Return stack, Stack Manipulation
5109: @subsection Locals stack
5110:
1.78 anton 5111: Gforth uses an extra locals stack. It is described, along with the
5112: reasons for its existence, in @ref{Locals implementation}.
1.21 crook 5113:
1.1 anton 5114: @node Stack pointer manipulation, , Locals stack, Stack Manipulation
5115: @subsection Stack pointer manipulation
5116: @cindex stack pointer manipulation words
5117:
1.44 crook 5118: @c removed s0 r0 l0 -- they are obsolete aliases for sp0 rp0 lp0
1.21 crook 5119: doc-sp0
1.1 anton 5120: doc-sp@
5121: doc-sp!
1.21 crook 5122: doc-fp0
1.1 anton 5123: doc-fp@
5124: doc-fp!
1.21 crook 5125: doc-rp0
1.1 anton 5126: doc-rp@
5127: doc-rp!
1.21 crook 5128: doc-lp0
1.1 anton 5129: doc-lp@
5130: doc-lp!
5131:
1.44 crook 5132:
1.1 anton 5133: @node Memory, Control Structures, Stack Manipulation, Words
5134: @section Memory
1.26 crook 5135: @cindex memory words
1.1 anton 5136:
1.32 anton 5137: @menu
5138: * Memory model::
5139: * Dictionary allocation::
5140: * Heap Allocation::
5141: * Memory Access::
5142: * Address arithmetic::
5143: * Memory Blocks::
5144: @end menu
5145:
1.67 anton 5146: In addition to the standard Forth memory allocation words, there is also
5147: a @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
5148: garbage collector}.
5149:
1.32 anton 5150: @node Memory model, Dictionary allocation, Memory, Memory
5151: @subsection ANS Forth and Gforth memory models
5152:
5153: @c The ANS Forth description is a mess (e.g., is the heap part of
5154: @c the dictionary?), so let's not stick to closely with it.
5155:
1.67 anton 5156: ANS Forth considers a Forth system as consisting of several address
5157: spaces, of which only @dfn{data space} is managed and accessible with
5158: the memory words. Memory not necessarily in data space includes the
5159: stacks, the code (called code space) and the headers (called name
5160: space). In Gforth everything is in data space, but the code for the
5161: primitives is usually read-only.
1.32 anton 5162:
5163: Data space is divided into a number of areas: The (data space portion of
5164: the) dictionary@footnote{Sometimes, the term @dfn{dictionary} is used to
5165: refer to the search data structure embodied in word lists and headers,
5166: because it is used for looking up names, just as you would in a
5167: conventional dictionary.}, the heap, and a number of system-allocated
5168: buffers.
5169:
1.68 anton 5170: @cindex address arithmetic restrictions, ANS vs. Gforth
5171: @cindex contiguous regions, ANS vs. Gforth
1.32 anton 5172: In ANS Forth data space is also divided into contiguous regions. You
5173: can only use address arithmetic within a contiguous region, not between
5174: them. Usually each allocation gives you one contiguous region, but the
1.33 anton 5175: dictionary allocation words have additional rules (@pxref{Dictionary
1.32 anton 5176: allocation}).
5177:
5178: Gforth provides one big address space, and address arithmetic can be
5179: performed between any addresses. However, in the dictionary headers or
5180: code are interleaved with data, so almost the only contiguous data space
5181: regions there are those described by ANS Forth as contiguous; but you
5182: can be sure that the dictionary is allocated towards increasing
5183: addresses even between contiguous regions. The memory order of
5184: allocations in the heap is platform-dependent (and possibly different
5185: from one run to the next).
5186:
1.27 crook 5187:
1.32 anton 5188: @node Dictionary allocation, Heap Allocation, Memory model, Memory
5189: @subsection Dictionary allocation
1.27 crook 5190: @cindex reserving data space
5191: @cindex data space - reserving some
5192:
1.32 anton 5193: Dictionary allocation is a stack-oriented allocation scheme, i.e., if
5194: you want to deallocate X, you also deallocate everything
5195: allocated after X.
5196:
1.68 anton 5197: @cindex contiguous regions in dictionary allocation
1.32 anton 5198: The allocations using the words below are contiguous and grow the region
5199: towards increasing addresses. Other words that allocate dictionary
5200: memory of any kind (i.e., defining words including @code{:noname}) end
5201: the contiguous region and start a new one.
5202:
5203: In ANS Forth only @code{create}d words are guaranteed to produce an
5204: address that is the start of the following contiguous region. In
5205: particular, the cell allocated by @code{variable} is not guaranteed to
5206: be contiguous with following @code{allot}ed memory.
5207:
5208: You can deallocate memory by using @code{allot} with a negative argument
5209: (with some restrictions, see @code{allot}). For larger deallocations use
5210: @code{marker}.
1.27 crook 5211:
1.29 crook 5212:
1.27 crook 5213: doc-here
5214: doc-unused
5215: doc-allot
5216: doc-c,
1.29 crook 5217: doc-f,
1.27 crook 5218: doc-,
5219: doc-2,
5220:
1.32 anton 5221: Memory accesses have to be aligned (@pxref{Address arithmetic}). So of
5222: course you should allocate memory in an aligned way, too. I.e., before
5223: allocating allocating a cell, @code{here} must be cell-aligned, etc.
5224: The words below align @code{here} if it is not already. Basically it is
5225: only already aligned for a type, if the last allocation was a multiple
5226: of the size of this type and if @code{here} was aligned for this type
5227: before.
5228:
5229: After freshly @code{create}ing a word, @code{here} is @code{align}ed in
5230: ANS Forth (@code{maxalign}ed in Gforth).
5231:
5232: doc-align
5233: doc-falign
5234: doc-sfalign
5235: doc-dfalign
5236: doc-maxalign
5237: doc-cfalign
5238:
5239:
5240: @node Heap Allocation, Memory Access, Dictionary allocation, Memory
5241: @subsection Heap allocation
5242: @cindex heap allocation
5243: @cindex dynamic allocation of memory
5244: @cindex memory-allocation word set
5245:
1.68 anton 5246: @cindex contiguous regions and heap allocation
1.32 anton 5247: Heap allocation supports deallocation of allocated memory in any
5248: order. Dictionary allocation is not affected by it (i.e., it does not
5249: end a contiguous region). In Gforth, these words are implemented using
5250: the standard C library calls malloc(), free() and resize().
5251:
1.68 anton 5252: The memory region produced by one invocation of @code{allocate} or
5253: @code{resize} is internally contiguous. There is no contiguity between
5254: such a region and any other region (including others allocated from the
5255: heap).
5256:
1.32 anton 5257: doc-allocate
5258: doc-free
5259: doc-resize
5260:
1.27 crook 5261:
1.32 anton 5262: @node Memory Access, Address arithmetic, Heap Allocation, Memory
1.1 anton 5263: @subsection Memory Access
5264: @cindex memory access words
5265:
5266: doc-@
5267: doc-!
5268: doc-+!
5269: doc-c@
5270: doc-c!
5271: doc-2@
5272: doc-2!
5273: doc-f@
5274: doc-f!
5275: doc-sf@
5276: doc-sf!
5277: doc-df@
5278: doc-df!
5279:
1.68 anton 5280:
1.32 anton 5281: @node Address arithmetic, Memory Blocks, Memory Access, Memory
5282: @subsection Address arithmetic
1.1 anton 5283: @cindex address arithmetic words
5284:
1.67 anton 5285: Address arithmetic is the foundation on which you can build data
5286: structures like arrays, records (@pxref{Structures}) and objects
5287: (@pxref{Object-oriented Forth}).
1.32 anton 5288:
1.68 anton 5289: @cindex address unit
5290: @cindex au (address unit)
1.1 anton 5291: ANS Forth does not specify the sizes of the data types. Instead, it
5292: offers a number of words for computing sizes and doing address
1.29 crook 5293: arithmetic. Address arithmetic is performed in terms of address units
5294: (aus); on most systems the address unit is one byte. Note that a
5295: character may have more than one au, so @code{chars} is no noop (on
1.68 anton 5296: platforms where it is a noop, it compiles to nothing).
1.1 anton 5297:
1.67 anton 5298: The basic address arithmetic words are @code{+} and @code{-}. E.g., if
5299: you have the address of a cell, perform @code{1 cells +}, and you will
5300: have the address of the next cell.
5301:
1.68 anton 5302: @cindex contiguous regions and address arithmetic
1.67 anton 5303: In ANS Forth you can perform address arithmetic only within a contiguous
5304: region, i.e., if you have an address into one region, you can only add
5305: and subtract such that the result is still within the region; you can
5306: only subtract or compare addresses from within the same contiguous
5307: region. Reasons: several contiguous regions can be arranged in memory
5308: in any way; on segmented systems addresses may have unusual
5309: representations, such that address arithmetic only works within a
5310: region. Gforth provides a few more guarantees (linear address space,
5311: dictionary grows upwards), but in general I have found it easy to stay
5312: within contiguous regions (exception: computing and comparing to the
5313: address just beyond the end of an array).
5314:
1.1 anton 5315: @cindex alignment of addresses for types
5316: ANS Forth also defines words for aligning addresses for specific
5317: types. Many computers require that accesses to specific data types
5318: must only occur at specific addresses; e.g., that cells may only be
5319: accessed at addresses divisible by 4. Even if a machine allows unaligned
5320: accesses, it can usually perform aligned accesses faster.
5321:
5322: For the performance-conscious: alignment operations are usually only
5323: necessary during the definition of a data structure, not during the
5324: (more frequent) accesses to it.
5325:
5326: ANS Forth defines no words for character-aligning addresses. This is not
5327: an oversight, but reflects the fact that addresses that are not
5328: char-aligned have no use in the standard and therefore will not be
5329: created.
5330:
5331: @cindex @code{CREATE} and alignment
1.29 crook 5332: ANS Forth guarantees that addresses returned by @code{CREATE}d words
1.1 anton 5333: are cell-aligned; in addition, Gforth guarantees that these addresses
5334: are aligned for all purposes.
5335:
1.26 crook 5336: Note that the ANS Forth word @code{char} has nothing to do with address
5337: arithmetic.
1.1 anton 5338:
1.44 crook 5339:
1.1 anton 5340: doc-chars
5341: doc-char+
5342: doc-cells
5343: doc-cell+
5344: doc-cell
5345: doc-aligned
5346: doc-floats
5347: doc-float+
5348: doc-float
5349: doc-faligned
5350: doc-sfloats
5351: doc-sfloat+
5352: doc-sfaligned
5353: doc-dfloats
5354: doc-dfloat+
5355: doc-dfaligned
5356: doc-maxaligned
5357: doc-cfaligned
5358: doc-address-unit-bits
5359:
1.44 crook 5360:
1.32 anton 5361: @node Memory Blocks, , Address arithmetic, Memory
1.1 anton 5362: @subsection Memory Blocks
5363: @cindex memory block words
1.27 crook 5364: @cindex character strings - moving and copying
5365:
1.49 anton 5366: Memory blocks often represent character strings; For ways of storing
5367: character strings in memory see @ref{String Formats}. For other
5368: string-processing words see @ref{Displaying characters and strings}.
1.1 anton 5369:
1.67 anton 5370: A few of these words work on address unit blocks. In that case, you
5371: usually have to insert @code{CHARS} before the word when working on
5372: character strings. Most words work on character blocks, and expect a
5373: char-aligned address.
5374:
5375: When copying characters between overlapping memory regions, use
5376: @code{chars move} or choose carefully between @code{cmove} and
5377: @code{cmove>}.
1.44 crook 5378:
1.1 anton 5379: doc-move
5380: doc-erase
5381: doc-cmove
5382: doc-cmove>
5383: doc-fill
5384: doc-blank
1.21 crook 5385: doc-compare
5386: doc-search
1.27 crook 5387: doc--trailing
5388: doc-/string
1.82 anton 5389: doc-bounds
1.44 crook 5390:
1.27 crook 5391: @comment TODO examples
5392:
1.1 anton 5393:
1.26 crook 5394: @node Control Structures, Defining Words, Memory, Words
1.1 anton 5395: @section Control Structures
5396: @cindex control structures
5397:
1.33 anton 5398: Control structures in Forth cannot be used interpretively, only in a
5399: colon definition@footnote{To be precise, they have no interpretation
5400: semantics (@pxref{Interpretation and Compilation Semantics}).}. We do
5401: not like this limitation, but have not seen a satisfying way around it
5402: yet, although many schemes have been proposed.
1.1 anton 5403:
5404: @menu
1.33 anton 5405: * Selection:: IF ... ELSE ... ENDIF
5406: * Simple Loops:: BEGIN ...
1.29 crook 5407: * Counted Loops:: DO
1.67 anton 5408: * Arbitrary control structures::
5409: * Calls and returns::
1.1 anton 5410: * Exception Handling::
5411: @end menu
5412:
5413: @node Selection, Simple Loops, Control Structures, Control Structures
5414: @subsection Selection
5415: @cindex selection control structures
5416: @cindex control structures for selection
5417:
5418: @cindex @code{IF} control structure
5419: @example
1.29 crook 5420: @i{flag}
1.1 anton 5421: IF
1.29 crook 5422: @i{code}
1.1 anton 5423: ENDIF
5424: @end example
1.21 crook 5425: @noindent
1.33 anton 5426:
1.44 crook 5427: If @i{flag} is non-zero (as far as @code{IF} etc. are concerned, a cell
5428: with any bit set represents truth) @i{code} is executed.
1.33 anton 5429:
1.1 anton 5430: @example
1.29 crook 5431: @i{flag}
1.1 anton 5432: IF
1.29 crook 5433: @i{code1}
1.1 anton 5434: ELSE
1.29 crook 5435: @i{code2}
1.1 anton 5436: ENDIF
5437: @end example
5438:
1.44 crook 5439: If @var{flag} is true, @i{code1} is executed, otherwise @i{code2} is
5440: executed.
1.33 anton 5441:
1.1 anton 5442: You can use @code{THEN} instead of @code{ENDIF}. Indeed, @code{THEN} is
5443: standard, and @code{ENDIF} is not, although it is quite popular. We
5444: recommend using @code{ENDIF}, because it is less confusing for people
5445: who also know other languages (and is not prone to reinforcing negative
5446: prejudices against Forth in these people). Adding @code{ENDIF} to a
5447: system that only supplies @code{THEN} is simple:
5448: @example
1.82 anton 5449: : ENDIF POSTPONE then ; immediate
1.1 anton 5450: @end example
5451:
5452: [According to @cite{Webster's New Encyclopedic Dictionary}, @dfn{then
5453: (adv.)} has the following meanings:
5454: @quotation
5455: ... 2b: following next after in order ... 3d: as a necessary consequence
5456: (if you were there, then you saw them).
5457: @end quotation
5458: Forth's @code{THEN} has the meaning 2b, whereas @code{THEN} in Pascal
5459: and many other programming languages has the meaning 3d.]
5460:
1.21 crook 5461: Gforth also provides the words @code{?DUP-IF} and @code{?DUP-0=-IF}, so
1.1 anton 5462: you can avoid using @code{?dup}. Using these alternatives is also more
1.26 crook 5463: efficient than using @code{?dup}. Definitions in ANS Forth
1.1 anton 5464: for @code{ENDIF}, @code{?DUP-IF} and @code{?DUP-0=-IF} are provided in
5465: @file{compat/control.fs}.
5466:
5467: @cindex @code{CASE} control structure
5468: @example
1.29 crook 5469: @i{n}
1.1 anton 5470: CASE
1.29 crook 5471: @i{n1} OF @i{code1} ENDOF
5472: @i{n2} OF @i{code2} ENDOF
1.1 anton 5473: @dots{}
1.68 anton 5474: ( n ) @i{default-code} ( n )
1.1 anton 5475: ENDCASE
5476: @end example
5477:
1.68 anton 5478: Executes the first @i{codei}, where the @i{ni} is equal to @i{n}. If no
5479: @i{ni} matches, the optional @i{default-code} is executed. The optional
5480: default case can be added by simply writing the code after the last
5481: @code{ENDOF}. It may use @i{n}, which is on top of the stack, but must
5482: not consume it.
1.1 anton 5483:
1.69 anton 5484: @progstyle
5485: To keep the code understandable, you should ensure that on all paths
5486: through a selection construct the stack is changed in the same way
5487: (wrt. number and types of stack items consumed and pushed).
5488:
1.1 anton 5489: @node Simple Loops, Counted Loops, Selection, Control Structures
5490: @subsection Simple Loops
5491: @cindex simple loops
5492: @cindex loops without count
5493:
5494: @cindex @code{WHILE} loop
5495: @example
5496: BEGIN
1.29 crook 5497: @i{code1}
5498: @i{flag}
1.1 anton 5499: WHILE
1.29 crook 5500: @i{code2}
1.1 anton 5501: REPEAT
5502: @end example
5503:
1.29 crook 5504: @i{code1} is executed and @i{flag} is computed. If it is true,
5505: @i{code2} is executed and the loop is restarted; If @i{flag} is
1.1 anton 5506: false, execution continues after the @code{REPEAT}.
5507:
5508: @cindex @code{UNTIL} loop
5509: @example
5510: BEGIN
1.29 crook 5511: @i{code}
5512: @i{flag}
1.1 anton 5513: UNTIL
5514: @end example
5515:
1.29 crook 5516: @i{code} is executed. The loop is restarted if @code{flag} is false.
1.1 anton 5517:
1.69 anton 5518: @progstyle
5519: To keep the code understandable, a complete iteration of the loop should
5520: not change the number and types of the items on the stacks.
5521:
1.1 anton 5522: @cindex endless loop
5523: @cindex loops, endless
5524: @example
5525: BEGIN
1.29 crook 5526: @i{code}
1.1 anton 5527: AGAIN
5528: @end example
5529:
5530: This is an endless loop.
5531:
5532: @node Counted Loops, Arbitrary control structures, Simple Loops, Control Structures
5533: @subsection Counted Loops
5534: @cindex counted loops
5535: @cindex loops, counted
5536: @cindex @code{DO} loops
5537:
5538: The basic counted loop is:
5539: @example
1.29 crook 5540: @i{limit} @i{start}
1.1 anton 5541: ?DO
1.29 crook 5542: @i{body}
1.1 anton 5543: LOOP
5544: @end example
5545:
1.29 crook 5546: This performs one iteration for every integer, starting from @i{start}
5547: and up to, but excluding @i{limit}. The counter, or @i{index}, can be
1.21 crook 5548: accessed with @code{i}. For example, the loop:
1.1 anton 5549: @example
5550: 10 0 ?DO
5551: i .
5552: LOOP
5553: @end example
1.21 crook 5554: @noindent
5555: prints @code{0 1 2 3 4 5 6 7 8 9}
5556:
1.1 anton 5557: The index of the innermost loop can be accessed with @code{i}, the index
5558: of the next loop with @code{j}, and the index of the third loop with
5559: @code{k}.
5560:
1.44 crook 5561:
1.1 anton 5562: doc-i
5563: doc-j
5564: doc-k
5565:
1.44 crook 5566:
1.1 anton 5567: The loop control data are kept on the return stack, so there are some
1.21 crook 5568: restrictions on mixing return stack accesses and counted loop words. In
5569: particuler, if you put values on the return stack outside the loop, you
5570: cannot read them inside the loop@footnote{well, not in a way that is
5571: portable.}. If you put values on the return stack within a loop, you
5572: have to remove them before the end of the loop and before accessing the
5573: index of the loop.
1.1 anton 5574:
5575: There are several variations on the counted loop:
5576:
1.21 crook 5577: @itemize @bullet
5578: @item
5579: @code{LEAVE} leaves the innermost counted loop immediately; execution
5580: continues after the associated @code{LOOP} or @code{NEXT}. For example:
5581:
5582: @example
5583: 10 0 ?DO i DUP . 3 = IF LEAVE THEN LOOP
5584: @end example
5585: prints @code{0 1 2 3}
5586:
1.1 anton 5587:
1.21 crook 5588: @item
5589: @code{UNLOOP} prepares for an abnormal loop exit, e.g., via
5590: @code{EXIT}. @code{UNLOOP} removes the loop control parameters from the
5591: return stack so @code{EXIT} can get to its return address. For example:
5592:
5593: @example
5594: : demo 10 0 ?DO i DUP . 3 = IF UNLOOP EXIT THEN LOOP ." Done" ;
5595: @end example
5596: prints @code{0 1 2 3}
5597:
5598:
5599: @item
1.29 crook 5600: If @i{start} is greater than @i{limit}, a @code{?DO} loop is entered
1.1 anton 5601: (and @code{LOOP} iterates until they become equal by wrap-around
5602: arithmetic). This behaviour is usually not what you want. Therefore,
5603: Gforth offers @code{+DO} and @code{U+DO} (as replacements for
1.29 crook 5604: @code{?DO}), which do not enter the loop if @i{start} is greater than
5605: @i{limit}; @code{+DO} is for signed loop parameters, @code{U+DO} for
1.1 anton 5606: unsigned loop parameters.
5607:
1.21 crook 5608: @item
5609: @code{?DO} can be replaced by @code{DO}. @code{DO} always enters
5610: the loop, independent of the loop parameters. Do not use @code{DO}, even
5611: if you know that the loop is entered in any case. Such knowledge tends
5612: to become invalid during maintenance of a program, and then the
5613: @code{DO} will make trouble.
5614:
5615: @item
1.29 crook 5616: @code{LOOP} can be replaced with @code{@i{n} +LOOP}; this updates the
5617: index by @i{n} instead of by 1. The loop is terminated when the border
5618: between @i{limit-1} and @i{limit} is crossed. E.g.:
1.1 anton 5619:
1.21 crook 5620: @example
5621: 4 0 +DO i . 2 +LOOP
5622: @end example
5623: @noindent
5624: prints @code{0 2}
5625:
5626: @example
5627: 4 1 +DO i . 2 +LOOP
5628: @end example
5629: @noindent
5630: prints @code{1 3}
1.1 anton 5631:
1.68 anton 5632: @item
1.1 anton 5633: @cindex negative increment for counted loops
5634: @cindex counted loops with negative increment
1.29 crook 5635: The behaviour of @code{@i{n} +LOOP} is peculiar when @i{n} is negative:
1.1 anton 5636:
1.21 crook 5637: @example
5638: -1 0 ?DO i . -1 +LOOP
5639: @end example
5640: @noindent
5641: prints @code{0 -1}
1.1 anton 5642:
1.21 crook 5643: @example
5644: 0 0 ?DO i . -1 +LOOP
5645: @end example
5646: prints nothing.
1.1 anton 5647:
1.29 crook 5648: Therefore we recommend avoiding @code{@i{n} +LOOP} with negative
5649: @i{n}. One alternative is @code{@i{u} -LOOP}, which reduces the
5650: index by @i{u} each iteration. The loop is terminated when the border
5651: between @i{limit+1} and @i{limit} is crossed. Gforth also provides
1.1 anton 5652: @code{-DO} and @code{U-DO} for down-counting loops. E.g.:
5653:
1.21 crook 5654: @example
5655: -2 0 -DO i . 1 -LOOP
5656: @end example
5657: @noindent
5658: prints @code{0 -1}
1.1 anton 5659:
1.21 crook 5660: @example
5661: -1 0 -DO i . 1 -LOOP
5662: @end example
5663: @noindent
5664: prints @code{0}
5665:
5666: @example
5667: 0 0 -DO i . 1 -LOOP
5668: @end example
5669: @noindent
5670: prints nothing.
1.1 anton 5671:
1.21 crook 5672: @end itemize
1.1 anton 5673:
5674: Unfortunately, @code{+DO}, @code{U+DO}, @code{-DO}, @code{U-DO} and
1.26 crook 5675: @code{-LOOP} are not defined in ANS Forth. However, an implementation
5676: for these words that uses only standard words is provided in
5677: @file{compat/loops.fs}.
1.1 anton 5678:
5679:
5680: @cindex @code{FOR} loops
1.26 crook 5681: Another counted loop is:
1.1 anton 5682: @example
1.29 crook 5683: @i{n}
1.1 anton 5684: FOR
1.29 crook 5685: @i{body}
1.1 anton 5686: NEXT
5687: @end example
5688: This is the preferred loop of native code compiler writers who are too
1.26 crook 5689: lazy to optimize @code{?DO} loops properly. This loop structure is not
1.29 crook 5690: defined in ANS Forth. In Gforth, this loop iterates @i{n+1} times;
5691: @code{i} produces values starting with @i{n} and ending with 0. Other
1.26 crook 5692: Forth systems may behave differently, even if they support @code{FOR}
5693: loops. To avoid problems, don't use @code{FOR} loops.
1.1 anton 5694:
5695: @node Arbitrary control structures, Calls and returns, Counted Loops, Control Structures
5696: @subsection Arbitrary control structures
5697: @cindex control structures, user-defined
5698:
5699: @cindex control-flow stack
5700: ANS Forth permits and supports using control structures in a non-nested
5701: way. Information about incomplete control structures is stored on the
5702: control-flow stack. This stack may be implemented on the Forth data
5703: stack, and this is what we have done in Gforth.
5704:
5705: @cindex @code{orig}, control-flow stack item
5706: @cindex @code{dest}, control-flow stack item
5707: An @i{orig} entry represents an unresolved forward branch, a @i{dest}
5708: entry represents a backward branch target. A few words are the basis for
5709: building any control structure possible (except control structures that
5710: need storage, like calls, coroutines, and backtracking).
5711:
1.44 crook 5712:
1.1 anton 5713: doc-if
5714: doc-ahead
5715: doc-then
5716: doc-begin
5717: doc-until
5718: doc-again
5719: doc-cs-pick
5720: doc-cs-roll
5721:
1.44 crook 5722:
1.21 crook 5723: The Standard words @code{CS-PICK} and @code{CS-ROLL} allow you to
5724: manipulate the control-flow stack in a portable way. Without them, you
5725: would need to know how many stack items are occupied by a control-flow
5726: entry (many systems use one cell. In Gforth they currently take three,
5727: but this may change in the future).
5728:
1.1 anton 5729: Some standard control structure words are built from these words:
5730:
1.44 crook 5731:
1.1 anton 5732: doc-else
5733: doc-while
5734: doc-repeat
5735:
1.44 crook 5736:
5737: @noindent
1.1 anton 5738: Gforth adds some more control-structure words:
5739:
1.44 crook 5740:
1.1 anton 5741: doc-endif
5742: doc-?dup-if
5743: doc-?dup-0=-if
5744:
1.44 crook 5745:
5746: @noindent
1.1 anton 5747: Counted loop words constitute a separate group of words:
5748:
1.44 crook 5749:
1.1 anton 5750: doc-?do
5751: doc-+do
5752: doc-u+do
5753: doc--do
5754: doc-u-do
5755: doc-do
5756: doc-for
5757: doc-loop
5758: doc-+loop
5759: doc--loop
5760: doc-next
5761: doc-leave
5762: doc-?leave
5763: doc-unloop
5764: doc-done
5765:
1.44 crook 5766:
1.21 crook 5767: The standard does not allow using @code{CS-PICK} and @code{CS-ROLL} on
5768: @i{do-sys}. Gforth allows it, but it's your job to ensure that for
1.1 anton 5769: every @code{?DO} etc. there is exactly one @code{UNLOOP} on any path
5770: through the definition (@code{LOOP} etc. compile an @code{UNLOOP} on the
5771: fall-through path). Also, you have to ensure that all @code{LEAVE}s are
5772: resolved (by using one of the loop-ending words or @code{DONE}).
5773:
1.44 crook 5774: @noindent
1.26 crook 5775: Another group of control structure words are:
1.1 anton 5776:
1.44 crook 5777:
1.1 anton 5778: doc-case
5779: doc-endcase
5780: doc-of
5781: doc-endof
5782:
1.44 crook 5783:
1.21 crook 5784: @i{case-sys} and @i{of-sys} cannot be processed using @code{CS-PICK} and
5785: @code{CS-ROLL}.
1.1 anton 5786:
5787: @subsubsection Programming Style
1.47 crook 5788: @cindex control structures programming style
5789: @cindex programming style, arbitrary control structures
1.1 anton 5790:
5791: In order to ensure readability we recommend that you do not create
5792: arbitrary control structures directly, but define new control structure
5793: words for the control structure you want and use these words in your
1.26 crook 5794: program. For example, instead of writing:
1.1 anton 5795:
5796: @example
1.26 crook 5797: BEGIN
1.1 anton 5798: ...
1.26 crook 5799: IF [ 1 CS-ROLL ]
1.1 anton 5800: ...
1.26 crook 5801: AGAIN THEN
1.1 anton 5802: @end example
5803:
1.21 crook 5804: @noindent
1.1 anton 5805: we recommend defining control structure words, e.g.,
5806:
5807: @example
1.26 crook 5808: : WHILE ( DEST -- ORIG DEST )
5809: POSTPONE IF
5810: 1 CS-ROLL ; immediate
5811:
5812: : REPEAT ( orig dest -- )
5813: POSTPONE AGAIN
5814: POSTPONE THEN ; immediate
1.1 anton 5815: @end example
5816:
1.21 crook 5817: @noindent
1.1 anton 5818: and then using these to create the control structure:
5819:
5820: @example
1.26 crook 5821: BEGIN
1.1 anton 5822: ...
1.26 crook 5823: WHILE
1.1 anton 5824: ...
1.26 crook 5825: REPEAT
1.1 anton 5826: @end example
5827:
5828: That's much easier to read, isn't it? Of course, @code{REPEAT} and
5829: @code{WHILE} are predefined, so in this example it would not be
5830: necessary to define them.
5831:
5832: @node Calls and returns, Exception Handling, Arbitrary control structures, Control Structures
5833: @subsection Calls and returns
5834: @cindex calling a definition
5835: @cindex returning from a definition
5836:
1.3 anton 5837: @cindex recursive definitions
5838: A definition can be called simply be writing the name of the definition
1.26 crook 5839: to be called. Normally a definition is invisible during its own
1.3 anton 5840: definition. If you want to write a directly recursive definition, you
1.26 crook 5841: can use @code{recursive} to make the current definition visible, or
5842: @code{recurse} to call the current definition directly.
1.3 anton 5843:
1.44 crook 5844:
1.3 anton 5845: doc-recursive
5846: doc-recurse
5847:
1.44 crook 5848:
1.21 crook 5849: @comment TODO add example of the two recursion methods
1.12 anton 5850: @quotation
5851: @progstyle
5852: I prefer using @code{recursive} to @code{recurse}, because calling the
5853: definition by name is more descriptive (if the name is well-chosen) than
5854: the somewhat cryptic @code{recurse}. E.g., in a quicksort
5855: implementation, it is much better to read (and think) ``now sort the
5856: partitions'' than to read ``now do a recursive call''.
5857: @end quotation
1.3 anton 5858:
1.29 crook 5859: For mutual recursion, use @code{Defer}red words, like this:
1.3 anton 5860:
5861: @example
1.28 crook 5862: Defer foo
1.3 anton 5863:
5864: : bar ( ... -- ... )
5865: ... foo ... ;
5866:
5867: :noname ( ... -- ... )
5868: ... bar ... ;
5869: IS foo
5870: @end example
5871:
1.44 crook 5872: Deferred words are discussed in more detail in @ref{Deferred words}.
1.33 anton 5873:
1.26 crook 5874: The current definition returns control to the calling definition when
1.33 anton 5875: the end of the definition is reached or @code{EXIT} is encountered.
1.1 anton 5876:
5877: doc-exit
5878: doc-;s
5879:
1.44 crook 5880:
1.1 anton 5881: @node Exception Handling, , Calls and returns, Control Structures
5882: @subsection Exception Handling
1.26 crook 5883: @cindex exceptions
1.1 anton 5884:
1.68 anton 5885: @c quit is a very bad idea for error handling,
5886: @c because it does not translate into a THROW
5887: @c it also does not belong into this chapter
5888:
5889: If a word detects an error condition that it cannot handle, it can
5890: @code{throw} an exception. In the simplest case, this will terminate
5891: your program, and report an appropriate error.
1.21 crook 5892:
1.68 anton 5893: doc-throw
1.1 anton 5894:
1.69 anton 5895: @code{Throw} consumes a cell-sized error number on the stack. There are
5896: some predefined error numbers in ANS Forth (see @file{errors.fs}). In
5897: Gforth (and most other systems) you can use the iors produced by various
5898: words as error numbers (e.g., a typical use of @code{allocate} is
5899: @code{allocate throw}). Gforth also provides the word @code{exception}
5900: to define your own error numbers (with decent error reporting); an ANS
5901: Forth version of this word (but without the error messages) is available
5902: in @code{compat/except.fs}. And finally, you can use your own error
1.68 anton 5903: numbers (anything outside the range -4095..0), but won't get nice error
5904: messages, only numbers. For example, try:
5905:
5906: @example
1.69 anton 5907: -10 throw \ ANS defined
5908: -267 throw \ system defined
5909: s" my error" exception throw \ user defined
5910: 7 throw \ arbitrary number
1.68 anton 5911: @end example
5912:
5913: doc---exception-exception
1.1 anton 5914:
1.69 anton 5915: A common idiom to @code{THROW} a specific error if a flag is true is
5916: this:
5917:
5918: @example
5919: @code{( flag ) 0<> @i{errno} and throw}
5920: @end example
5921:
5922: Your program can provide exception handlers to catch exceptions. An
5923: exception handler can be used to correct the problem, or to clean up
5924: some data structures and just throw the exception to the next exception
5925: handler. Note that @code{throw} jumps to the dynamically innermost
5926: exception handler. The system's exception handler is outermost, and just
5927: prints an error and restarts command-line interpretation (or, in batch
5928: mode (i.e., while processing the shell command line), leaves Gforth).
1.1 anton 5929:
1.68 anton 5930: The ANS Forth way to catch exceptions is @code{catch}:
1.1 anton 5931:
1.68 anton 5932: doc-catch
5933:
5934: The most common use of exception handlers is to clean up the state when
5935: an error happens. E.g.,
1.1 anton 5936:
1.26 crook 5937: @example
1.68 anton 5938: base @ >r hex \ actually the hex should be inside foo, or we h
5939: ['] foo catch ( nerror|0 )
5940: r> base !
1.69 anton 5941: ( nerror|0 ) throw \ pass it on
1.26 crook 5942: @end example
1.1 anton 5943:
1.69 anton 5944: A use of @code{catch} for handling the error @code{myerror} might look
5945: like this:
1.44 crook 5946:
1.68 anton 5947: @example
1.69 anton 5948: ['] foo catch
5949: CASE
5950: myerror OF ... ( do something about it ) ENDOF
5951: dup throw \ default: pass other errors on, do nothing on non-errors
5952: ENDCASE
1.68 anton 5953: @end example
1.44 crook 5954:
1.68 anton 5955: Having to wrap the code into a separate word is often cumbersome,
5956: therefore Gforth provides an alternative syntax:
1.1 anton 5957:
5958: @example
1.69 anton 5959: TRY
1.68 anton 5960: @i{code1}
1.69 anton 5961: RECOVER \ optional
1.68 anton 5962: @i{code2} \ optional
1.69 anton 5963: ENDTRY
1.1 anton 5964: @end example
5965:
1.68 anton 5966: This performs @i{Code1}. If @i{code1} completes normally, execution
5967: continues after the @code{endtry}. If @i{Code1} throws, the stacks are
5968: reset to the state during @code{try}, the throw value is pushed on the
5969: data stack, and execution constinues at @i{code2}, and finally falls
1.92 anton 5970: through the @code{endtry} into the following code.
1.26 crook 5971:
1.68 anton 5972: doc-try
5973: doc-recover
5974: doc-endtry
1.26 crook 5975:
1.69 anton 5976: The cleanup example from above in this syntax:
1.26 crook 5977:
1.68 anton 5978: @example
1.69 anton 5979: base @ >r TRY
1.68 anton 5980: hex foo \ now the hex is placed correctly
1.69 anton 5981: 0 \ value for throw
1.92 anton 5982: RECOVER ENDTRY
1.68 anton 5983: r> base ! throw
1.1 anton 5984: @end example
5985:
1.69 anton 5986: And here's the error handling example:
1.1 anton 5987:
1.68 anton 5988: @example
1.69 anton 5989: TRY
1.68 anton 5990: foo
1.69 anton 5991: RECOVER
5992: CASE
5993: myerror OF ... ( do something about it ) ENDOF
5994: throw \ pass other errors on
5995: ENDCASE
5996: ENDTRY
1.68 anton 5997: @end example
1.1 anton 5998:
1.69 anton 5999: @progstyle
6000: As usual, you should ensure that the stack depth is statically known at
6001: the end: either after the @code{throw} for passing on errors, or after
6002: the @code{ENDTRY} (or, if you use @code{catch}, after the end of the
6003: selection construct for handling the error).
6004:
1.68 anton 6005: There are two alternatives to @code{throw}: @code{Abort"} is conditional
6006: and you can provide an error message. @code{Abort} just produces an
6007: ``Aborted'' error.
1.1 anton 6008:
1.68 anton 6009: The problem with these words is that exception handlers cannot
6010: differentiate between different @code{abort"}s; they just look like
6011: @code{-2 throw} to them (the error message cannot be accessed by
6012: standard programs). Similar @code{abort} looks like @code{-1 throw} to
6013: exception handlers.
1.44 crook 6014:
1.68 anton 6015: doc-abort"
1.26 crook 6016: doc-abort
1.29 crook 6017:
6018:
1.44 crook 6019:
1.29 crook 6020: @c -------------------------------------------------------------
1.47 crook 6021: @node Defining Words, Interpretation and Compilation Semantics, Control Structures, Words
1.29 crook 6022: @section Defining Words
6023: @cindex defining words
6024:
1.47 crook 6025: Defining words are used to extend Forth by creating new entries in the dictionary.
6026:
1.29 crook 6027: @menu
1.67 anton 6028: * CREATE::
1.44 crook 6029: * Variables:: Variables and user variables
1.67 anton 6030: * Constants::
1.44 crook 6031: * Values:: Initialised variables
1.67 anton 6032: * Colon Definitions::
1.44 crook 6033: * Anonymous Definitions:: Definitions without names
1.69 anton 6034: * Supplying names:: Passing definition names as strings
1.67 anton 6035: * User-defined Defining Words::
1.44 crook 6036: * Deferred words:: Allow forward references
1.67 anton 6037: * Aliases::
1.29 crook 6038: @end menu
6039:
1.44 crook 6040: @node CREATE, Variables, Defining Words, Defining Words
6041: @subsection @code{CREATE}
1.29 crook 6042: @cindex simple defining words
6043: @cindex defining words, simple
6044:
6045: Defining words are used to create new entries in the dictionary. The
6046: simplest defining word is @code{CREATE}. @code{CREATE} is used like
6047: this:
6048:
6049: @example
6050: CREATE new-word1
6051: @end example
6052:
1.69 anton 6053: @code{CREATE} is a parsing word, i.e., it takes an argument from the
6054: input stream (@code{new-word1} in our example). It generates a
6055: dictionary entry for @code{new-word1}. When @code{new-word1} is
6056: executed, all that it does is leave an address on the stack. The address
6057: represents the value of the data space pointer (@code{HERE}) at the time
6058: that @code{new-word1} was defined. Therefore, @code{CREATE} is a way of
6059: associating a name with the address of a region of memory.
1.29 crook 6060:
1.34 anton 6061: doc-create
6062:
1.69 anton 6063: Note that in ANS Forth guarantees only for @code{create} that its body
6064: is in dictionary data space (i.e., where @code{here}, @code{allot}
6065: etc. work, @pxref{Dictionary allocation}). Also, in ANS Forth only
6066: @code{create}d words can be modified with @code{does>}
6067: (@pxref{User-defined Defining Words}). And in ANS Forth @code{>body}
6068: can only be applied to @code{create}d words.
6069:
1.29 crook 6070: By extending this example to reserve some memory in data space, we end
1.69 anton 6071: up with something like a @i{variable}. Here are two different ways to do
6072: it:
1.29 crook 6073:
6074: @example
6075: CREATE new-word2 1 cells allot \ reserve 1 cell - initial value undefined
6076: CREATE new-word3 4 , \ reserve 1 cell and initialise it (to 4)
6077: @end example
6078:
6079: The variable can be examined and modified using @code{@@} (``fetch'') and
6080: @code{!} (``store'') like this:
6081:
6082: @example
6083: new-word2 @@ . \ get address, fetch from it and display
6084: 1234 new-word2 ! \ new value, get address, store to it
6085: @end example
6086:
1.44 crook 6087: @cindex arrays
6088: A similar mechanism can be used to create arrays. For example, an
6089: 80-character text input buffer:
1.29 crook 6090:
6091: @example
1.44 crook 6092: CREATE text-buf 80 chars allot
6093:
6094: text-buf 0 chars c@@ \ the 1st character (offset 0)
6095: text-buf 3 chars c@@ \ the 4th character (offset 3)
6096: @end example
1.29 crook 6097:
1.44 crook 6098: You can build arbitrarily complex data structures by allocating
1.49 anton 6099: appropriate areas of memory. For further discussions of this, and to
1.66 anton 6100: learn about some Gforth tools that make it easier,
1.49 anton 6101: @xref{Structures}.
1.44 crook 6102:
6103:
6104: @node Variables, Constants, CREATE, Defining Words
6105: @subsection Variables
6106: @cindex variables
6107:
6108: The previous section showed how a sequence of commands could be used to
6109: generate a variable. As a final refinement, the whole code sequence can
6110: be wrapped up in a defining word (pre-empting the subject of the next
6111: section), making it easier to create new variables:
6112:
6113: @example
6114: : myvariableX ( "name" -- a-addr ) CREATE 1 cells allot ;
6115: : myvariable0 ( "name" -- a-addr ) CREATE 0 , ;
6116:
6117: myvariableX foo \ variable foo starts off with an unknown value
6118: myvariable0 joe \ whilst joe is initialised to 0
1.29 crook 6119:
6120: 45 3 * foo ! \ set foo to 135
6121: 1234 joe ! \ set joe to 1234
6122: 3 joe +! \ increment joe by 3.. to 1237
6123: @end example
6124:
6125: Not surprisingly, there is no need to define @code{myvariable}, since
1.44 crook 6126: Forth already has a definition @code{Variable}. ANS Forth does not
1.69 anton 6127: guarantee that a @code{Variable} is initialised when it is created
6128: (i.e., it may behave like @code{myvariableX}). In contrast, Gforth's
6129: @code{Variable} initialises the variable to 0 (i.e., it behaves exactly
6130: like @code{myvariable0}). Forth also provides @code{2Variable} and
1.47 crook 6131: @code{fvariable} for double and floating-point variables, respectively
1.69 anton 6132: -- they are initialised to 0. and 0e in Gforth. If you use a @code{Variable} to
1.47 crook 6133: store a boolean, you can use @code{on} and @code{off} to toggle its
6134: state.
1.29 crook 6135:
1.34 anton 6136: doc-variable
6137: doc-2variable
6138: doc-fvariable
6139:
1.29 crook 6140: @cindex user variables
6141: @cindex user space
6142: The defining word @code{User} behaves in the same way as @code{Variable}.
6143: The difference is that it reserves space in @i{user (data) space} rather
6144: than normal data space. In a Forth system that has a multi-tasker, each
6145: task has its own set of user variables.
6146:
1.34 anton 6147: doc-user
1.67 anton 6148: @c doc-udp
6149: @c doc-uallot
1.34 anton 6150:
1.29 crook 6151: @comment TODO is that stuff about user variables strictly correct? Is it
6152: @comment just terminal tasks that have user variables?
6153: @comment should document tasker.fs (with some examples) elsewhere
6154: @comment in this manual, then expand on user space and user variables.
6155:
1.44 crook 6156: @node Constants, Values, Variables, Defining Words
6157: @subsection Constants
6158: @cindex constants
6159:
6160: @code{Constant} allows you to declare a fixed value and refer to it by
6161: name. For example:
1.29 crook 6162:
6163: @example
6164: 12 Constant INCHES-PER-FOOT
6165: 3E+08 fconstant SPEED-O-LIGHT
6166: @end example
6167:
6168: A @code{Variable} can be both read and written, so its run-time
6169: behaviour is to supply an address through which its current value can be
6170: manipulated. In contrast, the value of a @code{Constant} cannot be
6171: changed once it has been declared@footnote{Well, often it can be -- but
6172: not in a Standard, portable way. It's safer to use a @code{Value} (read
6173: on).} so it's not necessary to supply the address -- it is more
6174: efficient to return the value of the constant directly. That's exactly
6175: what happens; the run-time effect of a constant is to put its value on
1.49 anton 6176: the top of the stack (You can find one
6177: way of implementing @code{Constant} in @ref{User-defined Defining Words}).
1.29 crook 6178:
1.69 anton 6179: Forth also provides @code{2Constant} and @code{fconstant} for defining
1.29 crook 6180: double and floating-point constants, respectively.
6181:
1.34 anton 6182: doc-constant
6183: doc-2constant
6184: doc-fconstant
6185:
6186: @c that's too deep, and it's not necessarily true for all ANS Forths. - anton
1.44 crook 6187: @c nac-> How could that not be true in an ANS Forth? You can't define a
6188: @c constant, use it and then delete the definition of the constant..
1.69 anton 6189:
6190: @c anton->An ANS Forth system can compile a constant to a literal; On
6191: @c decompilation you would see only the number, just as if it had been used
6192: @c in the first place. The word will stay, of course, but it will only be
6193: @c used by the text interpreter (no run-time duties, except when it is
6194: @c POSTPONEd or somesuch).
6195:
6196: @c nac:
1.44 crook 6197: @c I agree that it's rather deep, but IMO it is an important difference
6198: @c relative to other programming languages.. often it's annoying: it
6199: @c certainly changes my programming style relative to C.
6200:
1.69 anton 6201: @c anton: In what way?
6202:
1.29 crook 6203: Constants in Forth behave differently from their equivalents in other
6204: programming languages. In other languages, a constant (such as an EQU in
6205: assembler or a #define in C) only exists at compile-time; in the
6206: executable program the constant has been translated into an absolute
6207: number and, unless you are using a symbolic debugger, it's impossible to
6208: know what abstract thing that number represents. In Forth a constant has
1.44 crook 6209: an entry in the header space and remains there after the code that uses
6210: it has been defined. In fact, it must remain in the dictionary since it
6211: has run-time duties to perform. For example:
1.29 crook 6212:
6213: @example
6214: 12 Constant INCHES-PER-FOOT
6215: : FEET-TO-INCHES ( n1 -- n2 ) INCHES-PER-FOOT * ;
6216: @end example
6217:
6218: @cindex in-lining of constants
6219: When @code{FEET-TO-INCHES} is executed, it will in turn execute the xt
6220: associated with the constant @code{INCHES-PER-FOOT}. If you use
6221: @code{see} to decompile the definition of @code{FEET-TO-INCHES}, you can
6222: see that it makes a call to @code{INCHES-PER-FOOT}. Some Forth compilers
6223: attempt to optimise constants by in-lining them where they are used. You
6224: can force Gforth to in-line a constant like this:
6225:
6226: @example
6227: : FEET-TO-INCHES ( n1 -- n2 ) [ INCHES-PER-FOOT ] LITERAL * ;
6228: @end example
6229:
6230: If you use @code{see} to decompile @i{this} version of
6231: @code{FEET-TO-INCHES}, you can see that @code{INCHES-PER-FOOT} is no
1.49 anton 6232: longer present. To understand how this works, read
6233: @ref{Interpret/Compile states}, and @ref{Literals}.
1.29 crook 6234:
6235: In-lining constants in this way might improve execution time
6236: fractionally, and can ensure that a constant is now only referenced at
6237: compile-time. However, the definition of the constant still remains in
6238: the dictionary. Some Forth compilers provide a mechanism for controlling
6239: a second dictionary for holding transient words such that this second
6240: dictionary can be deleted later in order to recover memory
6241: space. However, there is no standard way of doing this.
6242:
6243:
1.44 crook 6244: @node Values, Colon Definitions, Constants, Defining Words
6245: @subsection Values
6246: @cindex values
1.34 anton 6247:
1.69 anton 6248: A @code{Value} behaves like a @code{Constant}, but it can be changed.
6249: @code{TO} is a parsing word that changes a @code{Values}. In Gforth
6250: (not in ANS Forth) you can access (and change) a @code{value} also with
6251: @code{>body}.
6252:
6253: Here are some
6254: examples:
1.29 crook 6255:
6256: @example
1.69 anton 6257: 12 Value APPLES \ Define APPLES with an initial value of 12
6258: 34 TO APPLES \ Change the value of APPLES. TO is a parsing word
6259: 1 ' APPLES >body +! \ Increment APPLES. Non-standard usage.
6260: APPLES \ puts 35 on the top of the stack.
1.29 crook 6261: @end example
6262:
1.44 crook 6263: doc-value
6264: doc-to
1.29 crook 6265:
1.35 anton 6266:
1.69 anton 6267:
1.44 crook 6268: @node Colon Definitions, Anonymous Definitions, Values, Defining Words
6269: @subsection Colon Definitions
6270: @cindex colon definitions
1.35 anton 6271:
6272: @example
1.44 crook 6273: : name ( ... -- ... )
6274: word1 word2 word3 ;
1.29 crook 6275: @end example
6276:
1.44 crook 6277: @noindent
6278: Creates a word called @code{name} that, upon execution, executes
6279: @code{word1 word2 word3}. @code{name} is a @dfn{(colon) definition}.
1.29 crook 6280:
1.49 anton 6281: The explanation above is somewhat superficial. For simple examples of
6282: colon definitions see @ref{Your first definition}. For an in-depth
1.66 anton 6283: discussion of some of the issues involved, @xref{Interpretation and
1.49 anton 6284: Compilation Semantics}.
1.29 crook 6285:
1.44 crook 6286: doc-:
6287: doc-;
1.1 anton 6288:
1.34 anton 6289:
1.69 anton 6290: @node Anonymous Definitions, Supplying names, Colon Definitions, Defining Words
1.44 crook 6291: @subsection Anonymous Definitions
6292: @cindex colon definitions
6293: @cindex defining words without name
1.34 anton 6294:
1.44 crook 6295: Sometimes you want to define an @dfn{anonymous word}; a word without a
6296: name. You can do this with:
1.1 anton 6297:
1.44 crook 6298: doc-:noname
1.1 anton 6299:
1.44 crook 6300: This leaves the execution token for the word on the stack after the
6301: closing @code{;}. Here's an example in which a deferred word is
6302: initialised with an @code{xt} from an anonymous colon definition:
1.1 anton 6303:
1.29 crook 6304: @example
1.44 crook 6305: Defer deferred
6306: :noname ( ... -- ... )
6307: ... ;
6308: IS deferred
1.29 crook 6309: @end example
1.26 crook 6310:
1.44 crook 6311: @noindent
6312: Gforth provides an alternative way of doing this, using two separate
6313: words:
1.27 crook 6314:
1.44 crook 6315: doc-noname
6316: @cindex execution token of last defined word
6317: doc-lastxt
1.1 anton 6318:
1.44 crook 6319: @noindent
6320: The previous example can be rewritten using @code{noname} and
6321: @code{lastxt}:
1.1 anton 6322:
1.26 crook 6323: @example
1.44 crook 6324: Defer deferred
6325: noname : ( ... -- ... )
6326: ... ;
6327: lastxt IS deferred
1.26 crook 6328: @end example
1.1 anton 6329:
1.29 crook 6330: @noindent
1.44 crook 6331: @code{noname} works with any defining word, not just @code{:}.
6332:
6333: @code{lastxt} also works when the last word was not defined as
1.71 anton 6334: @code{noname}. It does not work for combined words, though. It also has
6335: the useful property that is is valid as soon as the header for a
6336: definition has been built. Thus:
1.44 crook 6337:
6338: @example
6339: lastxt . : foo [ lastxt . ] ; ' foo .
6340: @end example
1.1 anton 6341:
1.44 crook 6342: @noindent
6343: prints 3 numbers; the last two are the same.
1.26 crook 6344:
1.69 anton 6345: @node Supplying names, User-defined Defining Words, Anonymous Definitions, Defining Words
6346: @subsection Supplying the name of a defined word
6347: @cindex names for defined words
6348: @cindex defining words, name given in a string
6349:
6350: By default, a defining word takes the name for the defined word from the
6351: input stream. Sometimes you want to supply the name from a string. You
6352: can do this with:
6353:
6354: doc-nextname
6355:
6356: For example:
6357:
6358: @example
6359: s" foo" nextname create
6360: @end example
6361:
6362: @noindent
6363: is equivalent to:
6364:
6365: @example
6366: create foo
6367: @end example
6368:
6369: @noindent
6370: @code{nextname} works with any defining word.
6371:
1.1 anton 6372:
1.69 anton 6373: @node User-defined Defining Words, Deferred words, Supplying names, Defining Words
1.26 crook 6374: @subsection User-defined Defining Words
6375: @cindex user-defined defining words
6376: @cindex defining words, user-defined
1.1 anton 6377:
1.29 crook 6378: You can create a new defining word by wrapping defining-time code around
6379: an existing defining word and putting the sequence in a colon
1.69 anton 6380: definition.
6381:
6382: @c anton: This example is very complex and leads in a quite different
6383: @c direction from the CREATE-DOES> stuff that follows. It should probably
6384: @c be done elsewhere, or as a subsubsection of this subsection (or as a
6385: @c subsection of Defining Words)
6386:
6387: For example, suppose that you have a word @code{stats} that
1.29 crook 6388: gathers statistics about colon definitions given the @i{xt} of the
6389: definition, and you want every colon definition in your application to
6390: make a call to @code{stats}. You can define and use a new version of
6391: @code{:} like this:
6392:
6393: @example
6394: : stats ( xt -- ) DUP ." (Gathering statistics for " . ." )"
6395: ... ; \ other code
6396:
6397: : my: : lastxt postpone literal ['] stats compile, ;
6398:
6399: my: foo + - ;
6400: @end example
6401:
6402: When @code{foo} is defined using @code{my:} these steps occur:
6403:
6404: @itemize @bullet
6405: @item
6406: @code{my:} is executed.
6407: @item
6408: The @code{:} within the definition (the one between @code{my:} and
6409: @code{lastxt}) is executed, and does just what it always does; it parses
6410: the input stream for a name, builds a dictionary header for the name
6411: @code{foo} and switches @code{state} from interpret to compile.
6412: @item
6413: The word @code{lastxt} is executed. It puts the @i{xt} for the word that is
6414: being defined -- @code{foo} -- onto the stack.
6415: @item
6416: The code that was produced by @code{postpone literal} is executed; this
6417: causes the value on the stack to be compiled as a literal in the code
6418: area of @code{foo}.
6419: @item
6420: The code @code{['] stats} compiles a literal into the definition of
6421: @code{my:}. When @code{compile,} is executed, that literal -- the
6422: execution token for @code{stats} -- is layed down in the code area of
6423: @code{foo} , following the literal@footnote{Strictly speaking, the
6424: mechanism that @code{compile,} uses to convert an @i{xt} into something
6425: in the code area is implementation-dependent. A threaded implementation
6426: might spit out the execution token directly whilst another
6427: implementation might spit out a native code sequence.}.
6428: @item
6429: At this point, the execution of @code{my:} is complete, and control
6430: returns to the text interpreter. The text interpreter is in compile
6431: state, so subsequent text @code{+ -} is compiled into the definition of
6432: @code{foo} and the @code{;} terminates the definition as always.
6433: @end itemize
6434:
6435: You can use @code{see} to decompile a word that was defined using
6436: @code{my:} and see how it is different from a normal @code{:}
6437: definition. For example:
6438:
6439: @example
6440: : bar + - ; \ like foo but using : rather than my:
6441: see bar
6442: : bar
6443: + - ;
6444: see foo
6445: : foo
6446: 107645672 stats + - ;
6447:
6448: \ use ' stats . to show that 107645672 is the xt for stats
6449: @end example
6450:
6451: You can use techniques like this to make new defining words in terms of
6452: @i{any} existing defining word.
1.1 anton 6453:
6454:
1.29 crook 6455: @cindex defining defining words
1.26 crook 6456: @cindex @code{CREATE} ... @code{DOES>}
6457: If you want the words defined with your defining words to behave
6458: differently from words defined with standard defining words, you can
6459: write your defining word like this:
1.1 anton 6460:
6461: @example
1.26 crook 6462: : def-word ( "name" -- )
1.29 crook 6463: CREATE @i{code1}
1.26 crook 6464: DOES> ( ... -- ... )
1.29 crook 6465: @i{code2} ;
1.26 crook 6466:
6467: def-word name
1.1 anton 6468: @end example
6469:
1.29 crook 6470: @cindex child words
6471: This fragment defines a @dfn{defining word} @code{def-word} and then
6472: executes it. When @code{def-word} executes, it @code{CREATE}s a new
6473: word, @code{name}, and executes the code @i{code1}. The code @i{code2}
6474: is not executed at this time. The word @code{name} is sometimes called a
6475: @dfn{child} of @code{def-word}.
6476:
6477: When you execute @code{name}, the address of the body of @code{name} is
6478: put on the data stack and @i{code2} is executed (the address of the body
6479: of @code{name} is the address @code{HERE} returns immediately after the
1.69 anton 6480: @code{CREATE}, i.e., the address a @code{create}d word returns by
6481: default).
6482:
6483: @c anton:
6484: @c www.dictionary.com says:
6485: @c at·a·vism: 1.The reappearance of a characteristic in an organism after
6486: @c several generations of absence, usually caused by the chance
6487: @c recombination of genes. 2.An individual or a part that exhibits
6488: @c atavism. Also called throwback. 3.The return of a trait or recurrence
6489: @c of previous behavior after a period of absence.
6490: @c
6491: @c Doesn't seem to fit.
1.29 crook 6492:
1.69 anton 6493: @c @cindex atavism in child words
1.33 anton 6494: You can use @code{def-word} to define a set of child words that behave
1.69 anton 6495: similarly; they all have a common run-time behaviour determined by
6496: @i{code2}. Typically, the @i{code1} sequence builds a data area in the
6497: body of the child word. The structure of the data is common to all
6498: children of @code{def-word}, but the data values are specific -- and
6499: private -- to each child word. When a child word is executed, the
6500: address of its private data area is passed as a parameter on TOS to be
6501: used and manipulated@footnote{It is legitimate both to read and write to
6502: this data area.} by @i{code2}.
1.29 crook 6503:
6504: The two fragments of code that make up the defining words act (are
6505: executed) at two completely separate times:
1.1 anton 6506:
1.29 crook 6507: @itemize @bullet
6508: @item
6509: At @i{define time}, the defining word executes @i{code1} to generate a
6510: child word
6511: @item
6512: At @i{child execution time}, when a child word is invoked, @i{code2}
6513: is executed, using parameters (data) that are private and specific to
6514: the child word.
6515: @end itemize
6516:
1.44 crook 6517: Another way of understanding the behaviour of @code{def-word} and
6518: @code{name} is to say that, if you make the following definitions:
1.33 anton 6519: @example
6520: : def-word1 ( "name" -- )
6521: CREATE @i{code1} ;
6522:
6523: : action1 ( ... -- ... )
6524: @i{code2} ;
6525:
6526: def-word1 name1
6527: @end example
6528:
1.44 crook 6529: @noindent
6530: Then using @code{name1 action1} is equivalent to using @code{name}.
1.1 anton 6531:
1.29 crook 6532: The classic example is that you can define @code{CONSTANT} in this way:
1.26 crook 6533:
1.1 anton 6534: @example
1.29 crook 6535: : CONSTANT ( w "name" -- )
6536: CREATE ,
1.26 crook 6537: DOES> ( -- w )
6538: @@ ;
1.1 anton 6539: @end example
6540:
1.29 crook 6541: @comment There is a beautiful description of how this works and what
6542: @comment it does in the Forthwrite 100th edition.. as well as an elegant
6543: @comment commentary on the Counting Fruits problem.
6544:
6545: When you create a constant with @code{5 CONSTANT five}, a set of
6546: define-time actions take place; first a new word @code{five} is created,
6547: then the value 5 is laid down in the body of @code{five} with
1.44 crook 6548: @code{,}. When @code{five} is executed, the address of the body is put on
1.29 crook 6549: the stack, and @code{@@} retrieves the value 5. The word @code{five} has
6550: no code of its own; it simply contains a data field and a pointer to the
6551: code that follows @code{DOES>} in its defining word. That makes words
6552: created in this way very compact.
6553:
6554: The final example in this section is intended to remind you that space
6555: reserved in @code{CREATE}d words is @i{data} space and therefore can be
6556: both read and written by a Standard program@footnote{Exercise: use this
6557: example as a starting point for your own implementation of @code{Value}
6558: and @code{TO} -- if you get stuck, investigate the behaviour of @code{'} and
6559: @code{[']}.}:
6560:
6561: @example
6562: : foo ( "name" -- )
6563: CREATE -1 ,
6564: DOES> ( -- )
1.33 anton 6565: @@ . ;
1.29 crook 6566:
6567: foo first-word
6568: foo second-word
6569:
6570: 123 ' first-word >BODY !
6571: @end example
6572:
6573: If @code{first-word} had been a @code{CREATE}d word, we could simply
6574: have executed it to get the address of its data field. However, since it
6575: was defined to have @code{DOES>} actions, its execution semantics are to
6576: perform those @code{DOES>} actions. To get the address of its data field
6577: it's necessary to use @code{'} to get its xt, then @code{>BODY} to
6578: translate the xt into the address of the data field. When you execute
6579: @code{first-word}, it will display @code{123}. When you execute
6580: @code{second-word} it will display @code{-1}.
1.26 crook 6581:
6582: @cindex stack effect of @code{DOES>}-parts
6583: @cindex @code{DOES>}-parts, stack effect
1.29 crook 6584: In the examples above the stack comment after the @code{DOES>} specifies
1.26 crook 6585: the stack effect of the defined words, not the stack effect of the
6586: following code (the following code expects the address of the body on
6587: the top of stack, which is not reflected in the stack comment). This is
6588: the convention that I use and recommend (it clashes a bit with using
6589: locals declarations for stack effect specification, though).
1.1 anton 6590:
1.53 anton 6591: @menu
6592: * CREATE..DOES> applications::
6593: * CREATE..DOES> details::
1.63 anton 6594: * Advanced does> usage example::
1.91 anton 6595: * @code{Const-does>}::
1.53 anton 6596: @end menu
6597:
6598: @node CREATE..DOES> applications, CREATE..DOES> details, User-defined Defining Words, User-defined Defining Words
1.26 crook 6599: @subsubsection Applications of @code{CREATE..DOES>}
6600: @cindex @code{CREATE} ... @code{DOES>}, applications
1.1 anton 6601:
1.26 crook 6602: You may wonder how to use this feature. Here are some usage patterns:
1.1 anton 6603:
1.26 crook 6604: @cindex factoring similar colon definitions
6605: When you see a sequence of code occurring several times, and you can
6606: identify a meaning, you will factor it out as a colon definition. When
6607: you see similar colon definitions, you can factor them using
6608: @code{CREATE..DOES>}. E.g., an assembler usually defines several words
6609: that look very similar:
1.1 anton 6610: @example
1.26 crook 6611: : ori, ( reg-target reg-source n -- )
6612: 0 asm-reg-reg-imm ;
6613: : andi, ( reg-target reg-source n -- )
6614: 1 asm-reg-reg-imm ;
1.1 anton 6615: @end example
6616:
1.26 crook 6617: @noindent
6618: This could be factored with:
6619: @example
6620: : reg-reg-imm ( op-code -- )
6621: CREATE ,
6622: DOES> ( reg-target reg-source n -- )
6623: @@ asm-reg-reg-imm ;
6624:
6625: 0 reg-reg-imm ori,
6626: 1 reg-reg-imm andi,
6627: @end example
1.1 anton 6628:
1.26 crook 6629: @cindex currying
6630: Another view of @code{CREATE..DOES>} is to consider it as a crude way to
6631: supply a part of the parameters for a word (known as @dfn{currying} in
6632: the functional language community). E.g., @code{+} needs two
6633: parameters. Creating versions of @code{+} with one parameter fixed can
6634: be done like this:
1.82 anton 6635:
1.1 anton 6636: @example
1.82 anton 6637: : curry+ ( n1 "name" -- )
1.26 crook 6638: CREATE ,
6639: DOES> ( n2 -- n1+n2 )
6640: @@ + ;
6641:
6642: 3 curry+ 3+
6643: -2 curry+ 2-
1.1 anton 6644: @end example
6645:
1.91 anton 6646:
1.63 anton 6647: @node CREATE..DOES> details, Advanced does> usage example, CREATE..DOES> applications, User-defined Defining Words
1.26 crook 6648: @subsubsection The gory details of @code{CREATE..DOES>}
6649: @cindex @code{CREATE} ... @code{DOES>}, details
1.1 anton 6650:
1.26 crook 6651: doc-does>
1.1 anton 6652:
1.26 crook 6653: @cindex @code{DOES>} in a separate definition
6654: This means that you need not use @code{CREATE} and @code{DOES>} in the
6655: same definition; you can put the @code{DOES>}-part in a separate
1.29 crook 6656: definition. This allows us to, e.g., select among different @code{DOES>}-parts:
1.26 crook 6657: @example
6658: : does1
6659: DOES> ( ... -- ... )
1.44 crook 6660: ... ;
6661:
6662: : does2
6663: DOES> ( ... -- ... )
6664: ... ;
6665:
6666: : def-word ( ... -- ... )
6667: create ...
6668: IF
6669: does1
6670: ELSE
6671: does2
6672: ENDIF ;
6673: @end example
6674:
6675: In this example, the selection of whether to use @code{does1} or
1.69 anton 6676: @code{does2} is made at definition-time; at the time that the child word is
1.44 crook 6677: @code{CREATE}d.
6678:
6679: @cindex @code{DOES>} in interpretation state
6680: In a standard program you can apply a @code{DOES>}-part only if the last
6681: word was defined with @code{CREATE}. In Gforth, the @code{DOES>}-part
6682: will override the behaviour of the last word defined in any case. In a
6683: standard program, you can use @code{DOES>} only in a colon
6684: definition. In Gforth, you can also use it in interpretation state, in a
6685: kind of one-shot mode; for example:
6686: @example
6687: CREATE name ( ... -- ... )
6688: @i{initialization}
6689: DOES>
6690: @i{code} ;
6691: @end example
6692:
6693: @noindent
6694: is equivalent to the standard:
6695: @example
6696: :noname
6697: DOES>
6698: @i{code} ;
6699: CREATE name EXECUTE ( ... -- ... )
6700: @i{initialization}
6701: @end example
6702:
1.53 anton 6703: doc->body
6704:
1.91 anton 6705: @node Advanced does> usage example, @code{Const-does>}, CREATE..DOES> details, User-defined Defining Words
1.63 anton 6706: @subsubsection Advanced does> usage example
6707:
6708: The MIPS disassembler (@file{arch/mips/disasm.fs}) contains many words
6709: for disassembling instructions, that follow a very repetetive scheme:
6710:
6711: @example
6712: :noname @var{disasm-operands} s" @var{inst-name}" type ;
6713: @var{entry-num} cells @var{table} + !
6714: @end example
6715:
6716: Of course, this inspires the idea to factor out the commonalities to
6717: allow a definition like
6718:
6719: @example
6720: @var{disasm-operands} @var{entry-num} @var{table} define-inst @var{inst-name}
6721: @end example
6722:
6723: The parameters @var{disasm-operands} and @var{table} are usually
1.69 anton 6724: correlated. Moreover, before I wrote the disassembler, there already
6725: existed code that defines instructions like this:
1.63 anton 6726:
6727: @example
6728: @var{entry-num} @var{inst-format} @var{inst-name}
6729: @end example
6730:
6731: This code comes from the assembler and resides in
6732: @file{arch/mips/insts.fs}.
6733:
6734: So I had to define the @var{inst-format} words that performed the scheme
6735: above when executed. At first I chose to use run-time code-generation:
6736:
6737: @example
6738: : @var{inst-format} ( entry-num "name" -- ; compiled code: addr w -- )
6739: :noname Postpone @var{disasm-operands}
6740: name Postpone sliteral Postpone type Postpone ;
6741: swap cells @var{table} + ! ;
6742: @end example
6743:
6744: Note that this supplies the other two parameters of the scheme above.
1.44 crook 6745:
1.63 anton 6746: An alternative would have been to write this using
6747: @code{create}/@code{does>}:
6748:
6749: @example
6750: : @var{inst-format} ( entry-num "name" -- )
6751: here name string, ( entry-num c-addr ) \ parse and save "name"
6752: noname create , ( entry-num )
6753: lastxt swap cells @var{table} + !
6754: does> ( addr w -- )
6755: \ disassemble instruction w at addr
6756: @@ >r
6757: @var{disasm-operands}
6758: r> count type ;
6759: @end example
6760:
6761: Somehow the first solution is simpler, mainly because it's simpler to
6762: shift a string from definition-time to use-time with @code{sliteral}
6763: than with @code{string,} and friends.
6764:
6765: I wrote a lot of words following this scheme and soon thought about
6766: factoring out the commonalities among them. Note that this uses a
6767: two-level defining word, i.e., a word that defines ordinary defining
6768: words.
6769:
6770: This time a solution involving @code{postpone} and friends seemed more
6771: difficult (try it as an exercise), so I decided to use a
6772: @code{create}/@code{does>} word; since I was already at it, I also used
6773: @code{create}/@code{does>} for the lower level (try using
6774: @code{postpone} etc. as an exercise), resulting in the following
6775: definition:
6776:
6777: @example
6778: : define-format ( disasm-xt table-xt -- )
6779: \ define an instruction format that uses disasm-xt for
6780: \ disassembling and enters the defined instructions into table
6781: \ table-xt
6782: create 2,
6783: does> ( u "inst" -- )
6784: \ defines an anonymous word for disassembling instruction inst,
6785: \ and enters it as u-th entry into table-xt
6786: 2@@ swap here name string, ( u table-xt disasm-xt c-addr ) \ remember string
6787: noname create 2, \ define anonymous word
6788: execute lastxt swap ! \ enter xt of defined word into table-xt
6789: does> ( addr w -- )
6790: \ disassemble instruction w at addr
6791: 2@@ >r ( addr w disasm-xt R: c-addr )
6792: execute ( R: c-addr ) \ disassemble operands
6793: r> count type ; \ print name
6794: @end example
6795:
6796: Note that the tables here (in contrast to above) do the @code{cells +}
6797: by themselves (that's why you have to pass an xt). This word is used in
6798: the following way:
6799:
6800: @example
6801: ' @var{disasm-operands} ' @var{table} define-format @var{inst-format}
6802: @end example
6803:
1.71 anton 6804: As shown above, the defined instruction format is then used like this:
6805:
6806: @example
6807: @var{entry-num} @var{inst-format} @var{inst-name}
6808: @end example
6809:
1.63 anton 6810: In terms of currying, this kind of two-level defining word provides the
6811: parameters in three stages: first @var{disasm-operands} and @var{table},
6812: then @var{entry-num} and @var{inst-name}, finally @code{addr w}, i.e.,
6813: the instruction to be disassembled.
6814:
6815: Of course this did not quite fit all the instruction format names used
6816: in @file{insts.fs}, so I had to define a few wrappers that conditioned
6817: the parameters into the right form.
6818:
6819: If you have trouble following this section, don't worry. First, this is
6820: involved and takes time (and probably some playing around) to
6821: understand; second, this is the first two-level
6822: @code{create}/@code{does>} word I have written in seventeen years of
6823: Forth; and if I did not have @file{insts.fs} to start with, I may well
6824: have elected to use just a one-level defining word (with some repeating
6825: of parameters when using the defining word). So it is not necessary to
6826: understand this, but it may improve your understanding of Forth.
1.44 crook 6827:
6828:
1.91 anton 6829: @node @code{Const-does>}, , Advanced does> usage example, User-defined Defining Words
6830: @subsubsection @code{Const-does>}
6831:
6832: A frequent use of @code{create}...@code{does>} is for transferring some
6833: values from definition-time to run-time. Gforth supports this use with
6834:
6835: doc-const-does>
6836:
6837: A typical use of this word is:
6838:
6839: @example
6840: : curry+ ( n1 "name" -- )
6841: 1 0 CONST-DOES> ( n2 -- n1+n2 )
6842: + ;
6843:
6844: 3 curry+ 3+
6845: @end example
6846:
6847: Here the @code{1 0} means that 1 cell and 0 floats are transferred from
6848: definition to run-time.
6849:
6850: The advantages of using @code{const-does>} are:
6851:
6852: @itemize
6853:
6854: @item
6855: You don't have to deal with storing and retrieving the values, i.e.,
6856: your program becomes more writable and readable.
6857:
6858: @item
6859: When using @code{does>}, you have to introduce a @code{@@} that cannot
6860: be optimized away (because you could change the data using
6861: @code{>body}...@code{!}); @code{const-does>} avoids this problem.
6862:
6863: @end itemize
6864:
6865: An ANS Forth implementation of @code{const-does>} is available in
6866: @file{compat/const-does.fs}.
6867:
6868:
1.44 crook 6869: @node Deferred words, Aliases, User-defined Defining Words, Defining Words
6870: @subsection Deferred words
6871: @cindex deferred words
6872:
6873: The defining word @code{Defer} allows you to define a word by name
6874: without defining its behaviour; the definition of its behaviour is
6875: deferred. Here are two situation where this can be useful:
6876:
6877: @itemize @bullet
6878: @item
6879: Where you want to allow the behaviour of a word to be altered later, and
6880: for all precompiled references to the word to change when its behaviour
6881: is changed.
6882: @item
6883: For mutual recursion; @xref{Calls and returns}.
6884: @end itemize
6885:
6886: In the following example, @code{foo} always invokes the version of
6887: @code{greet} that prints ``@code{Good morning}'' whilst @code{bar}
6888: always invokes the version that prints ``@code{Hello}''. There is no way
6889: of getting @code{foo} to use the later version without re-ordering the
6890: source code and recompiling it.
6891:
6892: @example
6893: : greet ." Good morning" ;
6894: : foo ... greet ... ;
6895: : greet ." Hello" ;
6896: : bar ... greet ... ;
6897: @end example
6898:
6899: This problem can be solved by defining @code{greet} as a @code{Defer}red
6900: word. The behaviour of a @code{Defer}red word can be defined and
6901: redefined at any time by using @code{IS} to associate the xt of a
6902: previously-defined word with it. The previous example becomes:
6903:
6904: @example
1.69 anton 6905: Defer greet ( -- )
1.44 crook 6906: : foo ... greet ... ;
6907: : bar ... greet ... ;
1.69 anton 6908: : greet1 ( -- ) ." Good morning" ;
6909: : greet2 ( -- ) ." Hello" ;
1.44 crook 6910: ' greet2 <IS> greet \ make greet behave like greet2
6911: @end example
6912:
1.69 anton 6913: @progstyle
6914: You should write a stack comment for every deferred word, and put only
6915: XTs into deferred words that conform to this stack effect. Otherwise
6916: it's too difficult to use the deferred word.
6917:
1.44 crook 6918: A deferred word can be used to improve the statistics-gathering example
6919: from @ref{User-defined Defining Words}; rather than edit the
6920: application's source code to change every @code{:} to a @code{my:}, do
6921: this:
6922:
6923: @example
6924: : real: : ; \ retain access to the original
6925: defer : \ redefine as a deferred word
1.69 anton 6926: ' my: <IS> : \ use special version of :
1.44 crook 6927: \
6928: \ load application here
6929: \
1.69 anton 6930: ' real: <IS> : \ go back to the original
1.44 crook 6931: @end example
6932:
6933:
6934: One thing to note is that @code{<IS>} consumes its name when it is
6935: executed. If you want to specify the name at compile time, use
6936: @code{[IS]}:
6937:
6938: @example
6939: : set-greet ( xt -- )
6940: [IS] greet ;
6941:
6942: ' greet1 set-greet
6943: @end example
6944:
1.69 anton 6945: A deferred word can only inherit execution semantics from the xt
6946: (because that is all that an xt can represent -- for more discussion of
6947: this @pxref{Tokens for Words}); by default it will have default
6948: interpretation and compilation semantics deriving from this execution
6949: semantics. However, you can change the interpretation and compilation
6950: semantics of the deferred word in the usual ways:
1.44 crook 6951:
6952: @example
6953: : bar .... ; compile-only
6954: Defer fred immediate
6955: Defer jim
6956:
6957: ' bar <IS> jim \ jim has default semantics
6958: ' bar <IS> fred \ fred is immediate
6959: @end example
6960:
6961: doc-defer
6962: doc-<is>
6963: doc-[is]
6964: doc-is
6965: @comment TODO document these: what's defers [is]
6966: doc-what's
6967: doc-defers
6968:
6969: @c Use @code{words-deferred} to see a list of deferred words.
6970:
6971: Definitions in ANS Forth for @code{defer}, @code{<is>} and @code{[is]}
6972: are provided in @file{compat/defer.fs}.
6973:
6974:
1.69 anton 6975: @node Aliases, , Deferred words, Defining Words
1.44 crook 6976: @subsection Aliases
6977: @cindex aliases
1.1 anton 6978:
1.44 crook 6979: The defining word @code{Alias} allows you to define a word by name that
6980: has the same behaviour as some other word. Here are two situation where
6981: this can be useful:
1.1 anton 6982:
1.44 crook 6983: @itemize @bullet
6984: @item
6985: When you want access to a word's definition from a different word list
6986: (for an example of this, see the definition of the @code{Root} word list
6987: in the Gforth source).
6988: @item
6989: When you want to create a synonym; a definition that can be known by
6990: either of two names (for example, @code{THEN} and @code{ENDIF} are
6991: aliases).
6992: @end itemize
1.1 anton 6993:
1.69 anton 6994: Like deferred words, an alias has default compilation and interpretation
6995: semantics at the beginning (not the modifications of the other word),
6996: but you can change them in the usual ways (@code{immediate},
6997: @code{compile-only}). For example:
1.1 anton 6998:
6999: @example
1.44 crook 7000: : foo ... ; immediate
7001:
7002: ' foo Alias bar \ bar is not an immediate word
7003: ' foo Alias fooby immediate \ fooby is an immediate word
1.1 anton 7004: @end example
7005:
1.44 crook 7006: Words that are aliases have the same xt, different headers in the
7007: dictionary, and consequently different name tokens (@pxref{Tokens for
7008: Words}) and possibly different immediate flags. An alias can only have
7009: default or immediate compilation semantics; you can define aliases for
7010: combined words with @code{interpret/compile:} -- see @ref{Combined words}.
1.1 anton 7011:
1.44 crook 7012: doc-alias
1.1 anton 7013:
7014:
1.47 crook 7015: @node Interpretation and Compilation Semantics, Tokens for Words, Defining Words, Words
7016: @section Interpretation and Compilation Semantics
1.26 crook 7017: @cindex semantics, interpretation and compilation
1.1 anton 7018:
1.71 anton 7019: @c !! state and ' are used without explanation
7020: @c example for immediate/compile-only? or is the tutorial enough
7021:
1.26 crook 7022: @cindex interpretation semantics
1.71 anton 7023: The @dfn{interpretation semantics} of a (named) word are what the text
1.26 crook 7024: interpreter does when it encounters the word in interpret state. It also
7025: appears in some other contexts, e.g., the execution token returned by
1.71 anton 7026: @code{' @i{word}} identifies the interpretation semantics of @i{word}
7027: (in other words, @code{' @i{word} execute} is equivalent to
1.29 crook 7028: interpret-state text interpretation of @code{@i{word}}).
1.1 anton 7029:
1.26 crook 7030: @cindex compilation semantics
1.71 anton 7031: The @dfn{compilation semantics} of a (named) word are what the text
7032: interpreter does when it encounters the word in compile state. It also
7033: appears in other contexts, e.g, @code{POSTPONE @i{word}}
7034: compiles@footnote{In standard terminology, ``appends to the current
7035: definition''.} the compilation semantics of @i{word}.
1.1 anton 7036:
1.26 crook 7037: @cindex execution semantics
7038: The standard also talks about @dfn{execution semantics}. They are used
7039: only for defining the interpretation and compilation semantics of many
7040: words. By default, the interpretation semantics of a word are to
7041: @code{execute} its execution semantics, and the compilation semantics of
7042: a word are to @code{compile,} its execution semantics.@footnote{In
7043: standard terminology: The default interpretation semantics are its
7044: execution semantics; the default compilation semantics are to append its
7045: execution semantics to the execution semantics of the current
7046: definition.}
7047:
1.71 anton 7048: Unnamed words (@pxref{Anonymous Definitions}) cannot be encountered by
7049: the text interpreter, ticked, or @code{postpone}d, so they have no
7050: interpretation or compilation semantics. Their behaviour is represented
7051: by their XT (@pxref{Tokens for Words}), and we call it execution
7052: semantics, too.
7053:
1.26 crook 7054: @comment TODO expand, make it co-operate with new sections on text interpreter.
7055:
7056: @cindex immediate words
7057: @cindex compile-only words
7058: You can change the semantics of the most-recently defined word:
7059:
1.44 crook 7060:
1.26 crook 7061: doc-immediate
7062: doc-compile-only
7063: doc-restrict
7064:
1.82 anton 7065: By convention, words with non-default compilation semantics (e.g.,
7066: immediate words) often have names surrounded with brackets (e.g.,
7067: @code{[']}, @pxref{Execution token}).
1.44 crook 7068:
1.26 crook 7069: Note that ticking (@code{'}) a compile-only word gives an error
7070: (``Interpreting a compile-only word'').
1.1 anton 7071:
1.47 crook 7072: @menu
1.67 anton 7073: * Combined words::
1.47 crook 7074: @end menu
1.44 crook 7075:
1.71 anton 7076:
1.48 anton 7077: @node Combined words, , Interpretation and Compilation Semantics, Interpretation and Compilation Semantics
1.44 crook 7078: @subsection Combined Words
7079: @cindex combined words
7080:
7081: Gforth allows you to define @dfn{combined words} -- words that have an
7082: arbitrary combination of interpretation and compilation semantics.
7083:
1.26 crook 7084: doc-interpret/compile:
1.1 anton 7085:
1.26 crook 7086: This feature was introduced for implementing @code{TO} and @code{S"}. I
7087: recommend that you do not define such words, as cute as they may be:
7088: they make it hard to get at both parts of the word in some contexts.
7089: E.g., assume you want to get an execution token for the compilation
7090: part. Instead, define two words, one that embodies the interpretation
7091: part, and one that embodies the compilation part. Once you have done
7092: that, you can define a combined word with @code{interpret/compile:} for
7093: the convenience of your users.
1.1 anton 7094:
1.26 crook 7095: You might try to use this feature to provide an optimizing
7096: implementation of the default compilation semantics of a word. For
7097: example, by defining:
1.1 anton 7098: @example
1.26 crook 7099: :noname
7100: foo bar ;
7101: :noname
7102: POSTPONE foo POSTPONE bar ;
1.29 crook 7103: interpret/compile: opti-foobar
1.1 anton 7104: @end example
1.26 crook 7105:
1.23 crook 7106: @noindent
1.26 crook 7107: as an optimizing version of:
7108:
1.1 anton 7109: @example
1.26 crook 7110: : foobar
7111: foo bar ;
1.1 anton 7112: @end example
7113:
1.26 crook 7114: Unfortunately, this does not work correctly with @code{[compile]},
7115: because @code{[compile]} assumes that the compilation semantics of all
7116: @code{interpret/compile:} words are non-default. I.e., @code{[compile]
1.29 crook 7117: opti-foobar} would compile compilation semantics, whereas
7118: @code{[compile] foobar} would compile interpretation semantics.
1.1 anton 7119:
1.26 crook 7120: @cindex state-smart words (are a bad idea)
1.82 anton 7121: @anchor{state-smartness}
1.29 crook 7122: Some people try to use @dfn{state-smart} words to emulate the feature provided
1.26 crook 7123: by @code{interpret/compile:} (words are state-smart if they check
7124: @code{STATE} during execution). E.g., they would try to code
7125: @code{foobar} like this:
1.1 anton 7126:
1.26 crook 7127: @example
7128: : foobar
7129: STATE @@
7130: IF ( compilation state )
7131: POSTPONE foo POSTPONE bar
7132: ELSE
7133: foo bar
7134: ENDIF ; immediate
7135: @end example
1.1 anton 7136:
1.26 crook 7137: Although this works if @code{foobar} is only processed by the text
7138: interpreter, it does not work in other contexts (like @code{'} or
7139: @code{POSTPONE}). E.g., @code{' foobar} will produce an execution token
7140: for a state-smart word, not for the interpretation semantics of the
7141: original @code{foobar}; when you execute this execution token (directly
7142: with @code{EXECUTE} or indirectly through @code{COMPILE,}) in compile
7143: state, the result will not be what you expected (i.e., it will not
7144: perform @code{foo bar}). State-smart words are a bad idea. Simply don't
7145: write them@footnote{For a more detailed discussion of this topic, see
1.66 anton 7146: M. Anton Ertl,
7147: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,@code{State}-smartness---Why
7148: it is Evil and How to Exorcise it}}, EuroForth '98.}!
1.1 anton 7149:
1.26 crook 7150: @cindex defining words with arbitrary semantics combinations
7151: It is also possible to write defining words that define words with
7152: arbitrary combinations of interpretation and compilation semantics. In
7153: general, they look like this:
1.1 anton 7154:
1.26 crook 7155: @example
7156: : def-word
7157: create-interpret/compile
1.29 crook 7158: @i{code1}
1.26 crook 7159: interpretation>
1.29 crook 7160: @i{code2}
1.26 crook 7161: <interpretation
7162: compilation>
1.29 crook 7163: @i{code3}
1.26 crook 7164: <compilation ;
7165: @end example
1.1 anton 7166:
1.29 crook 7167: For a @i{word} defined with @code{def-word}, the interpretation
7168: semantics are to push the address of the body of @i{word} and perform
7169: @i{code2}, and the compilation semantics are to push the address of
7170: the body of @i{word} and perform @i{code3}. E.g., @code{constant}
1.26 crook 7171: can also be defined like this (except that the defined constants don't
7172: behave correctly when @code{[compile]}d):
1.1 anton 7173:
1.26 crook 7174: @example
7175: : constant ( n "name" -- )
7176: create-interpret/compile
7177: ,
7178: interpretation> ( -- n )
7179: @@
7180: <interpretation
7181: compilation> ( compilation. -- ; run-time. -- n )
7182: @@ postpone literal
7183: <compilation ;
7184: @end example
1.1 anton 7185:
1.44 crook 7186:
1.26 crook 7187: doc-create-interpret/compile
7188: doc-interpretation>
7189: doc-<interpretation
7190: doc-compilation>
7191: doc-<compilation
1.1 anton 7192:
1.44 crook 7193:
1.29 crook 7194: Words defined with @code{interpret/compile:} and
1.26 crook 7195: @code{create-interpret/compile} have an extended header structure that
7196: differs from other words; however, unless you try to access them with
7197: plain address arithmetic, you should not notice this. Words for
7198: accessing the header structure usually know how to deal with this; e.g.,
1.29 crook 7199: @code{'} @i{word} @code{>body} also gives you the body of a word created
7200: with @code{create-interpret/compile}.
1.1 anton 7201:
1.44 crook 7202:
1.47 crook 7203: @c -------------------------------------------------------------
1.81 anton 7204: @node Tokens for Words, Compiling words, Interpretation and Compilation Semantics, Words
1.47 crook 7205: @section Tokens for Words
7206: @cindex tokens for words
7207:
7208: This section describes the creation and use of tokens that represent
7209: words.
7210:
1.71 anton 7211: @menu
7212: * Execution token:: represents execution/interpretation semantics
7213: * Compilation token:: represents compilation semantics
7214: * Name token:: represents named words
7215: @end menu
1.47 crook 7216:
1.71 anton 7217: @node Execution token, Compilation token, Tokens for Words, Tokens for Words
7218: @subsection Execution token
1.47 crook 7219:
7220: @cindex xt
7221: @cindex execution token
1.71 anton 7222: An @dfn{execution token} (@i{XT}) represents some behaviour of a word.
7223: You can use @code{execute} to invoke this behaviour.
1.47 crook 7224:
1.71 anton 7225: @cindex tick (')
7226: You can use @code{'} to get an execution token that represents the
7227: interpretation semantics of a named word:
1.47 crook 7228:
7229: @example
1.97 anton 7230: 5 ' . ( n xt )
7231: execute ( ) \ execute the xt (i.e., ".")
1.71 anton 7232: @end example
1.47 crook 7233:
1.71 anton 7234: doc-'
7235:
7236: @code{'} parses at run-time; there is also a word @code{[']} that parses
7237: when it is compiled, and compiles the resulting XT:
7238:
7239: @example
7240: : foo ['] . execute ;
7241: 5 foo
7242: : bar ' execute ; \ by contrast,
7243: 5 bar . \ ' parses "." when bar executes
7244: @end example
7245:
7246: doc-[']
7247:
7248: If you want the execution token of @i{word}, write @code{['] @i{word}}
7249: in compiled code and @code{' @i{word}} in interpreted code. Gforth's
7250: @code{'} and @code{[']} behave somewhat unusually by complaining about
7251: compile-only words (because these words have no interpretation
7252: semantics). You might get what you want by using @code{COMP' @i{word}
7253: DROP} or @code{[COMP'] @i{word} DROP} (for details @pxref{Compilation
7254: token}).
7255:
7256: Another way to get an XT is @code{:noname} or @code{lastxt}
7257: (@pxref{Anonymous Definitions}). For anonymous words this gives an xt
7258: for the only behaviour the word has (the execution semantics). For
7259: named words, @code{lastxt} produces an XT for the same behaviour it
7260: would produce if the word was defined anonymously.
7261:
7262: @example
7263: :noname ." hello" ;
7264: execute
1.47 crook 7265: @end example
7266:
1.71 anton 7267: An XT occupies one cell and can be manipulated like any other cell.
7268:
1.47 crook 7269: @cindex code field address
7270: @cindex CFA
1.71 anton 7271: In ANS Forth the XT is just an abstract data type (i.e., defined by the
7272: operations that produce or consume it). For old hands: In Gforth, the
7273: XT is implemented as a code field address (CFA).
7274:
7275: doc-execute
7276: doc-perform
7277:
7278: @node Compilation token, Name token, Execution token, Tokens for Words
7279: @subsection Compilation token
1.47 crook 7280:
7281: @cindex compilation token
1.71 anton 7282: @cindex CT (compilation token)
7283: Gforth represents the compilation semantics of a named word by a
1.47 crook 7284: @dfn{compilation token} consisting of two cells: @i{w xt}. The top cell
7285: @i{xt} is an execution token. The compilation semantics represented by
7286: the compilation token can be performed with @code{execute}, which
7287: consumes the whole compilation token, with an additional stack effect
7288: determined by the represented compilation semantics.
7289:
7290: At present, the @i{w} part of a compilation token is an execution token,
7291: and the @i{xt} part represents either @code{execute} or
7292: @code{compile,}@footnote{Depending upon the compilation semantics of the
7293: word. If the word has default compilation semantics, the @i{xt} will
7294: represent @code{compile,}. Otherwise (e.g., for immediate words), the
7295: @i{xt} will represent @code{execute}.}. However, don't rely on that
7296: knowledge, unless necessary; future versions of Gforth may introduce
7297: unusual compilation tokens (e.g., a compilation token that represents
7298: the compilation semantics of a literal).
7299:
1.71 anton 7300: You can perform the compilation semantics represented by the compilation
7301: token with @code{execute}. You can compile the compilation semantics
7302: with @code{postpone,}. I.e., @code{COMP' @i{word} postpone,} is
7303: equivalent to @code{postpone @i{word}}.
7304:
7305: doc-[comp']
7306: doc-comp'
7307: doc-postpone,
7308:
7309: @node Name token, , Compilation token, Tokens for Words
7310: @subsection Name token
1.47 crook 7311:
7312: @cindex name token
7313: @cindex name field address
7314: @cindex NFA
1.71 anton 7315: Gforth represents named words by the @dfn{name token}, (@i{nt}). In
1.47 crook 7316: Gforth, the abstract data type @emph{name token} is implemented as a
7317: name field address (NFA).
7318:
7319: doc-find-name
7320: doc-name>int
7321: doc-name?int
7322: doc-name>comp
7323: doc-name>string
1.109 ! anton 7324: doc-id.
! 7325: doc-.name
! 7326: doc-.id
1.47 crook 7327:
1.81 anton 7328: @c ----------------------------------------------------------
7329: @node Compiling words, The Text Interpreter, Tokens for Words, Words
7330: @section Compiling words
7331: @cindex compiling words
7332: @cindex macros
7333:
7334: In contrast to most other languages, Forth has no strict boundary
1.82 anton 7335: between compilation and run-time. E.g., you can run arbitrary code
7336: between defining words (or for computing data used by defining words
7337: like @code{constant}). Moreover, @code{Immediate} (@pxref{Interpretation
7338: and Compilation Semantics} and @code{[}...@code{]} (see below) allow
7339: running arbitrary code while compiling a colon definition (exception:
7340: you must not allot dictionary space).
7341:
7342: @menu
7343: * Literals:: Compiling data values
7344: * Macros:: Compiling words
7345: @end menu
7346:
7347: @node Literals, Macros, Compiling words, Compiling words
7348: @subsection Literals
7349: @cindex Literals
7350:
7351: The simplest and most frequent example is to compute a literal during
7352: compilation. E.g., the following definition prints an array of strings,
7353: one string per line:
7354:
7355: @example
7356: : .strings ( addr u -- ) \ gforth
7357: 2* cells bounds U+DO
7358: cr i 2@@ type
7359: 2 cells +LOOP ;
7360: @end example
1.81 anton 7361:
1.82 anton 7362: With a simple-minded compiler like Gforth's, this computes @code{2
7363: cells} on every loop iteration. You can compute this value once and for
7364: all at compile time and compile it into the definition like this:
7365:
7366: @example
7367: : .strings ( addr u -- ) \ gforth
7368: 2* cells bounds U+DO
7369: cr i 2@@ type
7370: [ 2 cells ] literal +LOOP ;
7371: @end example
7372:
7373: @code{[} switches the text interpreter to interpret state (you will get
7374: an @code{ok} prompt if you type this example interactively and insert a
7375: newline between @code{[} and @code{]}), so it performs the
7376: interpretation semantics of @code{2 cells}; this computes a number.
7377: @code{]} switches the text interpreter back into compile state. It then
7378: performs @code{Literal}'s compilation semantics, which are to compile
7379: this number into the current word. You can decompile the word with
7380: @code{see .strings} to see the effect on the compiled code.
1.81 anton 7381:
1.82 anton 7382: You can also optimize the @code{2* cells} into @code{[ 2 cells ] literal
7383: *} in this way.
1.81 anton 7384:
1.82 anton 7385: doc-[
7386: doc-]
1.81 anton 7387: doc-literal
7388: doc-]L
1.82 anton 7389:
7390: There are also words for compiling other data types than single cells as
7391: literals:
7392:
1.81 anton 7393: doc-2literal
7394: doc-fliteral
1.82 anton 7395: doc-sliteral
7396:
7397: @cindex colon-sys, passing data across @code{:}
7398: @cindex @code{:}, passing data across
7399: You might be tempted to pass data from outside a colon definition to the
7400: inside on the data stack. This does not work, because @code{:} puhes a
7401: colon-sys, making stuff below unaccessible. E.g., this does not work:
7402:
7403: @example
7404: 5 : foo literal ; \ error: "unstructured"
7405: @end example
7406:
7407: Instead, you have to pass the value in some other way, e.g., through a
7408: variable:
7409:
7410: @example
7411: variable temp
7412: 5 temp !
7413: : foo [ temp @@ ] literal ;
7414: @end example
7415:
7416:
7417: @node Macros, , Literals, Compiling words
7418: @subsection Macros
7419: @cindex Macros
7420: @cindex compiling compilation semantics
7421:
7422: @code{Literal} and friends compile data values into the current
7423: definition. You can also write words that compile other words into the
7424: current definition. E.g.,
7425:
7426: @example
7427: : compile-+ ( -- ) \ compiled code: ( n1 n2 -- n )
7428: POSTPONE + ;
7429:
7430: : foo ( n1 n2 -- n )
7431: [ compile-+ ] ;
7432: 1 2 foo .
7433: @end example
7434:
7435: This is equivalent to @code{: foo + ;} (@code{see foo} to check this).
7436: What happens in this example? @code{Postpone} compiles the compilation
7437: semantics of @code{+} into @code{compile-+}; later the text interpreter
7438: executes @code{compile-+} and thus the compilation semantics of +, which
7439: compile (the execution semantics of) @code{+} into
7440: @code{foo}.@footnote{A recent RFI answer requires that compiling words
7441: should only be executed in compile state, so this example is not
7442: guaranteed to work on all standard systems, but on any decent system it
7443: will work.}
7444:
7445: doc-postpone
7446: doc-[compile]
7447:
7448: Compiling words like @code{compile-+} are usually immediate (or similar)
7449: so you do not have to switch to interpret state to execute them;
7450: mopifying the last example accordingly produces:
7451:
7452: @example
7453: : [compile-+] ( compilation: --; interpretation: -- )
7454: \ compiled code: ( n1 n2 -- n )
7455: POSTPONE + ; immediate
7456:
7457: : foo ( n1 n2 -- n )
7458: [compile-+] ;
7459: 1 2 foo .
7460: @end example
7461:
7462: Immediate compiling words are similar to macros in other languages (in
7463: particular, Lisp). The important differences to macros in, e.g., C are:
7464:
7465: @itemize @bullet
7466:
7467: @item
7468: You use the same language for defining and processing macros, not a
7469: separate preprocessing language and processor.
7470:
7471: @item
7472: Consequently, the full power of Forth is available in macro definitions.
7473: E.g., you can perform arbitrarily complex computations, or generate
7474: different code conditionally or in a loop (e.g., @pxref{Advanced macros
7475: Tutorial}). This power is very useful when writing a parser generators
7476: or other code-generating software.
7477:
7478: @item
7479: Macros defined using @code{postpone} etc. deal with the language at a
7480: higher level than strings; name binding happens at macro definition
7481: time, so you can avoid the pitfalls of name collisions that can happen
7482: in C macros. Of course, Forth is a liberal language and also allows to
7483: shoot yourself in the foot with text-interpreted macros like
7484:
7485: @example
7486: : [compile-+] s" +" evaluate ; immediate
7487: @end example
7488:
7489: Apart from binding the name at macro use time, using @code{evaluate}
7490: also makes your definition @code{state}-smart (@pxref{state-smartness}).
7491: @end itemize
7492:
7493: You may want the macro to compile a number into a word. The word to do
7494: it is @code{literal}, but you have to @code{postpone} it, so its
7495: compilation semantics take effect when the macro is executed, not when
7496: it is compiled:
7497:
7498: @example
7499: : [compile-5] ( -- ) \ compiled code: ( -- n )
7500: 5 POSTPONE literal ; immediate
7501:
7502: : foo [compile-5] ;
7503: foo .
7504: @end example
7505:
7506: You may want to pass parameters to a macro, that the macro should
7507: compile into the current definition. If the parameter is a number, then
7508: you can use @code{postpone literal} (similar for other values).
7509:
7510: If you want to pass a word that is to be compiled, the usual way is to
7511: pass an execution token and @code{compile,} it:
7512:
7513: @example
7514: : twice1 ( xt -- ) \ compiled code: ... -- ...
7515: dup compile, compile, ;
7516:
7517: : 2+ ( n1 -- n2 )
7518: [ ' 1+ twice1 ] ;
7519: @end example
7520:
7521: doc-compile,
7522:
7523: An alternative available in Gforth, that allows you to pass compile-only
7524: words as parameters is to use the compilation token (@pxref{Compilation
7525: token}). The same example in this technique:
7526:
7527: @example
7528: : twice ( ... ct -- ... ) \ compiled code: ... -- ...
7529: 2dup 2>r execute 2r> execute ;
7530:
7531: : 2+ ( n1 -- n2 )
7532: [ comp' 1+ twice ] ;
7533: @end example
7534:
7535: In the example above @code{2>r} and @code{2r>} ensure that @code{twice}
7536: works even if the executed compilation semantics has an effect on the
7537: data stack.
7538:
7539: You can also define complete definitions with these words; this provides
7540: an alternative to using @code{does>} (@pxref{User-defined Defining
7541: Words}). E.g., instead of
7542:
7543: @example
7544: : curry+ ( n1 "name" -- )
7545: CREATE ,
7546: DOES> ( n2 -- n1+n2 )
7547: @@ + ;
7548: @end example
7549:
7550: you could define
7551:
7552: @example
7553: : curry+ ( n1 "name" -- )
7554: \ name execution: ( n2 -- n1+n2 )
7555: >r : r> POSTPONE literal POSTPONE + POSTPONE ; ;
1.81 anton 7556:
1.82 anton 7557: -3 curry+ 3-
7558: see 3-
7559: @end example
1.81 anton 7560:
1.82 anton 7561: The sequence @code{>r : r>} is necessary, because @code{:} puts a
7562: colon-sys on the data stack that makes everything below it unaccessible.
1.81 anton 7563:
1.82 anton 7564: This way of writing defining words is sometimes more, sometimes less
7565: convenient than using @code{does>} (@pxref{Advanced does> usage
7566: example}). One advantage of this method is that it can be optimized
7567: better, because the compiler knows that the value compiled with
7568: @code{literal} is fixed, whereas the data associated with a
7569: @code{create}d word can be changed.
1.47 crook 7570:
1.26 crook 7571: @c ----------------------------------------------------------
1.81 anton 7572: @node The Text Interpreter, Word Lists, Compiling words, Words
1.26 crook 7573: @section The Text Interpreter
7574: @cindex interpreter - outer
7575: @cindex text interpreter
7576: @cindex outer interpreter
1.1 anton 7577:
1.34 anton 7578: @c Should we really describe all these ugly details? IMO the text
7579: @c interpreter should be much cleaner, but that may not be possible within
7580: @c ANS Forth. - anton
1.44 crook 7581: @c nac-> I wanted to explain how it works to show how you can exploit
7582: @c it in your own programs. When I was writing a cross-compiler, figuring out
7583: @c some of these gory details was very helpful to me. None of the textbooks
7584: @c I've seen cover it, and the most modern Forth textbook -- Forth Inc's,
7585: @c seems to positively avoid going into too much detail for some of
7586: @c the internals.
1.34 anton 7587:
1.71 anton 7588: @c anton: ok. I wonder, though, if this is the right place; for some stuff
7589: @c it is; for the ugly details, I would prefer another place. I wonder
7590: @c whether we should have a chapter before "Words" that describes some
7591: @c basic concepts referred to in words, and a chapter after "Words" that
7592: @c describes implementation details.
7593:
1.29 crook 7594: The text interpreter@footnote{This is an expanded version of the
7595: material in @ref{Introducing the Text Interpreter}.} is an endless loop
1.34 anton 7596: that processes input from the current input device. It is also called
7597: the outer interpreter, in contrast to the inner interpreter
7598: (@pxref{Engine}) which executes the compiled Forth code on interpretive
7599: implementations.
1.27 crook 7600:
1.29 crook 7601: @cindex interpret state
7602: @cindex compile state
7603: The text interpreter operates in one of two states: @dfn{interpret
7604: state} and @dfn{compile state}. The current state is defined by the
1.71 anton 7605: aptly-named variable @code{state}.
1.29 crook 7606:
7607: This section starts by describing how the text interpreter behaves when
7608: it is in interpret state, processing input from the user input device --
7609: the keyboard. This is the mode that a Forth system is in after it starts
7610: up.
7611:
7612: @cindex input buffer
7613: @cindex terminal input buffer
7614: The text interpreter works from an area of memory called the @dfn{input
7615: buffer}@footnote{When the text interpreter is processing input from the
7616: keyboard, this area of memory is called the @dfn{terminal input buffer}
7617: (TIB) and is addressed by the (obsolescent) words @code{TIB} and
7618: @code{#TIB}.}, which stores your keyboard input when you press the
1.30 anton 7619: @key{RET} key. Starting at the beginning of the input buffer, it skips
1.29 crook 7620: leading spaces (called @dfn{delimiters}) then parses a string (a
7621: sequence of non-space characters) until it reaches either a space
7622: character or the end of the buffer. Having parsed a string, it makes two
7623: attempts to process it:
1.27 crook 7624:
1.29 crook 7625: @cindex dictionary
1.27 crook 7626: @itemize @bullet
7627: @item
1.29 crook 7628: It looks for the string in a @dfn{dictionary} of definitions. If the
7629: string is found, the string names a @dfn{definition} (also known as a
7630: @dfn{word}) and the dictionary search returns information that allows
7631: the text interpreter to perform the word's @dfn{interpretation
7632: semantics}. In most cases, this simply means that the word will be
7633: executed.
1.27 crook 7634: @item
7635: If the string is not found in the dictionary, the text interpreter
1.29 crook 7636: attempts to treat it as a number, using the rules described in
7637: @ref{Number Conversion}. If the string represents a legal number in the
7638: current radix, the number is pushed onto a parameter stack (the data
7639: stack for integers, the floating-point stack for floating-point
7640: numbers).
7641: @end itemize
7642:
7643: If both attempts fail, or if the word is found in the dictionary but has
7644: no interpretation semantics@footnote{This happens if the word was
7645: defined as @code{COMPILE-ONLY}.} the text interpreter discards the
7646: remainder of the input buffer, issues an error message and waits for
7647: more input. If one of the attempts succeeds, the text interpreter
7648: repeats the parsing process until the whole of the input buffer has been
7649: processed, at which point it prints the status message ``@code{ ok}''
7650: and waits for more input.
7651:
1.71 anton 7652: @c anton: this should be in the input stream subsection (or below it)
7653:
1.29 crook 7654: @cindex parse area
7655: The text interpreter keeps track of its position in the input buffer by
7656: updating a variable called @code{>IN} (pronounced ``to-in''). The value
7657: of @code{>IN} starts out as 0, indicating an offset of 0 from the start
7658: of the input buffer. The region from offset @code{>IN @@} to the end of
7659: the input buffer is called the @dfn{parse area}@footnote{In other words,
7660: the text interpreter processes the contents of the input buffer by
7661: parsing strings from the parse area until the parse area is empty.}.
7662: This example shows how @code{>IN} changes as the text interpreter parses
7663: the input buffer:
7664:
7665: @example
7666: : remaining >IN @@ SOURCE 2 PICK - -ROT + SWAP
7667: CR ." ->" TYPE ." <-" ; IMMEDIATE
7668:
7669: 1 2 3 remaining + remaining .
7670:
7671: : foo 1 2 3 remaining SWAP remaining ;
7672: @end example
7673:
7674: @noindent
7675: The result is:
7676:
7677: @example
7678: ->+ remaining .<-
7679: ->.<-5 ok
7680:
7681: ->SWAP remaining ;-<
7682: ->;<- ok
7683: @end example
7684:
7685: @cindex parsing words
7686: The value of @code{>IN} can also be modified by a word in the input
7687: buffer that is executed by the text interpreter. This means that a word
7688: can ``trick'' the text interpreter into either skipping a section of the
7689: input buffer@footnote{This is how parsing words work.} or into parsing a
7690: section twice. For example:
1.27 crook 7691:
1.29 crook 7692: @example
1.71 anton 7693: : lat ." <<foo>>" ;
7694: : flat ." <<bar>>" >IN DUP @@ 3 - SWAP ! ;
1.29 crook 7695: @end example
7696:
7697: @noindent
7698: When @code{flat} is executed, this output is produced@footnote{Exercise
7699: for the reader: what would happen if the @code{3} were replaced with
7700: @code{4}?}:
7701:
7702: @example
1.71 anton 7703: <<bar>><<foo>>
1.29 crook 7704: @end example
7705:
1.71 anton 7706: This technique can be used to work around some of the interoperability
7707: problems of parsing words. Of course, it's better to avoid parsing
7708: words where possible.
7709:
1.29 crook 7710: @noindent
7711: Two important notes about the behaviour of the text interpreter:
1.27 crook 7712:
7713: @itemize @bullet
7714: @item
7715: It processes each input string to completion before parsing additional
1.29 crook 7716: characters from the input buffer.
7717: @item
7718: It treats the input buffer as a read-only region (and so must your code).
7719: @end itemize
7720:
7721: @noindent
7722: When the text interpreter is in compile state, its behaviour changes in
7723: these ways:
7724:
7725: @itemize @bullet
7726: @item
7727: If a parsed string is found in the dictionary, the text interpreter will
7728: perform the word's @dfn{compilation semantics}. In most cases, this
7729: simply means that the execution semantics of the word will be appended
7730: to the current definition.
1.27 crook 7731: @item
1.29 crook 7732: When a number is encountered, it is compiled into the current definition
7733: (as a literal) rather than being pushed onto a parameter stack.
7734: @item
7735: If an error occurs, @code{state} is modified to put the text interpreter
7736: back into interpret state.
7737: @item
7738: Each time a line is entered from the keyboard, Gforth prints
7739: ``@code{ compiled}'' rather than `` @code{ok}''.
7740: @end itemize
7741:
7742: @cindex text interpreter - input sources
7743: When the text interpreter is using an input device other than the
7744: keyboard, its behaviour changes in these ways:
7745:
7746: @itemize @bullet
7747: @item
7748: When the parse area is empty, the text interpreter attempts to refill
7749: the input buffer from the input source. When the input source is
1.71 anton 7750: exhausted, the input source is set back to the previous input source.
1.29 crook 7751: @item
7752: It doesn't print out ``@code{ ok}'' or ``@code{ compiled}'' messages each
7753: time the parse area is emptied.
7754: @item
7755: If an error occurs, the input source is set back to the user input
7756: device.
1.27 crook 7757: @end itemize
1.21 crook 7758:
1.49 anton 7759: You can read about this in more detail in @ref{Input Sources}.
1.44 crook 7760:
1.26 crook 7761: doc->in
1.27 crook 7762: doc-source
7763:
1.26 crook 7764: doc-tib
7765: doc-#tib
1.1 anton 7766:
1.44 crook 7767:
1.26 crook 7768: @menu
1.67 anton 7769: * Input Sources::
7770: * Number Conversion::
7771: * Interpret/Compile states::
7772: * Interpreter Directives::
1.26 crook 7773: @end menu
1.1 anton 7774:
1.29 crook 7775: @node Input Sources, Number Conversion, The Text Interpreter, The Text Interpreter
7776: @subsection Input Sources
7777: @cindex input sources
7778: @cindex text interpreter - input sources
7779:
1.44 crook 7780: By default, the text interpreter processes input from the user input
1.29 crook 7781: device (the keyboard) when Forth starts up. The text interpreter can
7782: process input from any of these sources:
7783:
7784: @itemize @bullet
7785: @item
7786: The user input device -- the keyboard.
7787: @item
7788: A file, using the words described in @ref{Forth source files}.
7789: @item
7790: A block, using the words described in @ref{Blocks}.
7791: @item
7792: A text string, using @code{evaluate}.
7793: @end itemize
7794:
7795: A program can identify the current input device from the values of
7796: @code{source-id} and @code{blk}.
7797:
1.44 crook 7798:
1.29 crook 7799: doc-source-id
7800: doc-blk
7801:
7802: doc-save-input
7803: doc-restore-input
7804:
7805: doc-evaluate
1.1 anton 7806:
1.29 crook 7807:
1.44 crook 7808:
1.29 crook 7809: @node Number Conversion, Interpret/Compile states, Input Sources, The Text Interpreter
1.26 crook 7810: @subsection Number Conversion
7811: @cindex number conversion
7812: @cindex double-cell numbers, input format
7813: @cindex input format for double-cell numbers
7814: @cindex single-cell numbers, input format
7815: @cindex input format for single-cell numbers
7816: @cindex floating-point numbers, input format
7817: @cindex input format for floating-point numbers
1.1 anton 7818:
1.29 crook 7819: This section describes the rules that the text interpreter uses when it
7820: tries to convert a string into a number.
1.1 anton 7821:
1.26 crook 7822: Let <digit> represent any character that is a legal digit in the current
1.29 crook 7823: number base@footnote{For example, 0-9 when the number base is decimal or
7824: 0-9, A-F when the number base is hexadecimal.}.
1.1 anton 7825:
1.26 crook 7826: Let <decimal digit> represent any character in the range 0-9.
1.1 anton 7827:
1.29 crook 7828: Let @{@i{a b}@} represent the @i{optional} presence of any of the characters
7829: in the braces (@i{a} or @i{b} or neither).
1.1 anton 7830:
1.26 crook 7831: Let * represent any number of instances of the previous character
7832: (including none).
1.1 anton 7833:
1.26 crook 7834: Let any other character represent itself.
1.1 anton 7835:
1.29 crook 7836: @noindent
1.26 crook 7837: Now, the conversion rules are:
1.21 crook 7838:
1.26 crook 7839: @itemize @bullet
7840: @item
7841: A string of the form <digit><digit>* is treated as a single-precision
1.29 crook 7842: (cell-sized) positive integer. Examples are 0 123 6784532 32343212343456 42
1.26 crook 7843: @item
7844: A string of the form -<digit><digit>* is treated as a single-precision
1.29 crook 7845: (cell-sized) negative integer, and is represented using 2's-complement
1.26 crook 7846: arithmetic. Examples are -45 -5681 -0
7847: @item
7848: A string of the form <digit><digit>*.<digit>* is treated as a double-precision
1.29 crook 7849: (double-cell-sized) positive integer. Examples are 3465. 3.465 34.65
7850: (all three of these represent the same number).
1.26 crook 7851: @item
7852: A string of the form -<digit><digit>*.<digit>* is treated as a
1.29 crook 7853: double-precision (double-cell-sized) negative integer, and is
1.26 crook 7854: represented using 2's-complement arithmetic. Examples are -3465. -3.465
1.29 crook 7855: -34.65 (all three of these represent the same number).
1.26 crook 7856: @item
1.29 crook 7857: A string of the form @{+ -@}<decimal digit>@{.@}<decimal digit>*@{e
7858: E@}@{+ -@}<decimal digit><decimal digit>* is treated as a floating-point
1.35 anton 7859: number. Examples are 1e 1e0 1.e 1.e0 +1e+0 (which all represent the same
1.29 crook 7860: number) +12.E-4
1.26 crook 7861: @end itemize
1.1 anton 7862:
1.26 crook 7863: By default, the number base used for integer number conversion is given
1.35 anton 7864: by the contents of the variable @code{base}. Note that a lot of
7865: confusion can result from unexpected values of @code{base}. If you
7866: change @code{base} anywhere, make sure to save the old value and restore
7867: it afterwards. In general I recommend keeping @code{base} decimal, and
7868: using the prefixes described below for the popular non-decimal bases.
1.1 anton 7869:
1.29 crook 7870: doc-dpl
1.26 crook 7871: doc-base
7872: doc-hex
7873: doc-decimal
1.1 anton 7874:
1.44 crook 7875:
1.26 crook 7876: @cindex '-prefix for character strings
7877: @cindex &-prefix for decimal numbers
7878: @cindex %-prefix for binary numbers
7879: @cindex $-prefix for hexadecimal numbers
1.35 anton 7880: Gforth allows you to override the value of @code{base} by using a
1.29 crook 7881: prefix@footnote{Some Forth implementations provide a similar scheme by
7882: implementing @code{$} etc. as parsing words that process the subsequent
7883: number in the input stream and push it onto the stack. For example, see
7884: @cite{Number Conversion and Literals}, by Wil Baden; Forth Dimensions
7885: 20(3) pages 26--27. In such implementations, unlike in Gforth, a space
7886: is required between the prefix and the number.} before the first digit
7887: of an (integer) number. Four prefixes are supported:
1.1 anton 7888:
1.26 crook 7889: @itemize @bullet
7890: @item
1.35 anton 7891: @code{&} -- decimal
1.26 crook 7892: @item
1.35 anton 7893: @code{%} -- binary
1.26 crook 7894: @item
1.35 anton 7895: @code{$} -- hexadecimal
1.26 crook 7896: @item
1.35 anton 7897: @code{'} -- base @code{max-char+1}
1.26 crook 7898: @end itemize
1.1 anton 7899:
1.26 crook 7900: Here are some examples, with the equivalent decimal number shown after
7901: in braces:
1.1 anton 7902:
1.26 crook 7903: -$41 (-65), %1001101 (205), %1001.0001 (145 - a double-precision number),
7904: 'AB (16706; ascii A is 65, ascii B is 66, number is 65*256 + 66),
7905: 'ab (24930; ascii a is 97, ascii B is 98, number is 97*256 + 98),
7906: &905 (905), $abc (2478), $ABC (2478).
1.1 anton 7907:
1.26 crook 7908: @cindex number conversion - traps for the unwary
1.29 crook 7909: @noindent
1.26 crook 7910: Number conversion has a number of traps for the unwary:
1.1 anton 7911:
1.26 crook 7912: @itemize @bullet
7913: @item
7914: You cannot determine the current number base using the code sequence
1.35 anton 7915: @code{base @@ .} -- the number base is always 10 in the current number
7916: base. Instead, use something like @code{base @@ dec.}
1.26 crook 7917: @item
7918: If the number base is set to a value greater than 14 (for example,
7919: hexadecimal), the number 123E4 is ambiguous; the conversion rules allow
7920: it to be intepreted as either a single-precision integer or a
7921: floating-point number (Gforth treats it as an integer). The ambiguity
7922: can be resolved by explicitly stating the sign of the mantissa and/or
7923: exponent: 123E+4 or +123E4 -- if the number base is decimal, no
7924: ambiguity arises; either representation will be treated as a
7925: floating-point number.
7926: @item
1.29 crook 7927: There is a word @code{bin} but it does @i{not} set the number base!
1.26 crook 7928: It is used to specify file types.
7929: @item
1.72 anton 7930: ANS Forth requires the @code{.} of a double-precision number to be the
7931: final character in the string. Gforth allows the @code{.} to be
7932: anywhere after the first digit.
1.26 crook 7933: @item
7934: The number conversion process does not check for overflow.
7935: @item
1.72 anton 7936: In an ANS Forth program @code{base} is required to be decimal when
7937: converting floating-point numbers. In Gforth, number conversion to
7938: floating-point numbers always uses base &10, irrespective of the value
7939: of @code{base}.
1.26 crook 7940: @end itemize
1.1 anton 7941:
1.49 anton 7942: You can read numbers into your programs with the words described in
7943: @ref{Input}.
1.1 anton 7944:
1.82 anton 7945: @node Interpret/Compile states, Interpreter Directives, Number Conversion, The Text Interpreter
1.26 crook 7946: @subsection Interpret/Compile states
7947: @cindex Interpret/Compile states
1.1 anton 7948:
1.29 crook 7949: A standard program is not permitted to change @code{state}
7950: explicitly. However, it can change @code{state} implicitly, using the
7951: words @code{[} and @code{]}. When @code{[} is executed it switches
7952: @code{state} to interpret state, and therefore the text interpreter
7953: starts interpreting. When @code{]} is executed it switches @code{state}
7954: to compile state and therefore the text interpreter starts
1.44 crook 7955: compiling. The most common usage for these words is for switching into
7956: interpret state and back from within a colon definition; this technique
1.49 anton 7957: can be used to compile a literal (for an example, @pxref{Literals}) or
7958: for conditional compilation (for an example, @pxref{Interpreter
7959: Directives}).
1.44 crook 7960:
1.35 anton 7961:
7962: @c This is a bad example: It's non-standard, and it's not necessary.
7963: @c However, I can't think of a good example for switching into compile
7964: @c state when there is no current word (@code{state}-smart words are not a
7965: @c good reason). So maybe we should use an example for switching into
7966: @c interpret @code{state} in a colon def. - anton
1.44 crook 7967: @c nac-> I agree. I started out by putting in the example, then realised
7968: @c that it was non-ANS, so wrote more words around it. I hope this
7969: @c re-written version is acceptable to you. I do want to keep the example
7970: @c as it is helpful for showing what is and what is not portable, particularly
7971: @c where it outlaws a style in common use.
7972:
1.72 anton 7973: @c anton: it's more important to show what's portable. After we have done
1.83 anton 7974: @c that, we can also show what's not. In any case, I have written a
7975: @c section Compiling Words which also deals with [ ].
1.35 anton 7976:
1.95 anton 7977: @c !! The following example does not work in Gforth 0.5.9 or later.
1.29 crook 7978:
1.95 anton 7979: @c @code{[} and @code{]} also give you the ability to switch into compile
7980: @c state and back, but we cannot think of any useful Standard application
7981: @c for this ability. Pre-ANS Forth textbooks have examples like this:
7982:
7983: @c @example
7984: @c : AA ." this is A" ;
7985: @c : BB ." this is B" ;
7986: @c : CC ." this is C" ;
7987:
7988: @c create table ] aa bb cc [
7989:
7990: @c : go ( n -- ) \ n is offset into table.. 0 for 1st entry
7991: @c cells table + @@ execute ;
7992: @c @end example
7993:
7994: @c This example builds a jump table; @code{0 go} will display ``@code{this
7995: @c is A}''. Using @code{[} and @code{]} in this example is equivalent to
7996: @c defining @code{table} like this:
7997:
7998: @c @example
7999: @c create table ' aa COMPILE, ' bb COMPILE, ' cc COMPILE,
8000: @c @end example
8001:
8002: @c The problem with this code is that the definition of @code{table} is not
8003: @c portable -- it @i{compile}s execution tokens into code space. Whilst it
8004: @c @i{may} work on systems where code space and data space co-incide, the
8005: @c Standard only allows data space to be assigned for a @code{CREATE}d
8006: @c word. In addition, the Standard only allows @code{@@} to access data
8007: @c space, whilst this example is using it to access code space. The only
8008: @c portable, Standard way to build this table is to build it in data space,
8009: @c like this:
8010:
8011: @c @example
8012: @c create table ' aa , ' bb , ' cc ,
8013: @c @end example
1.29 crook 8014:
1.95 anton 8015: @c doc-state
1.44 crook 8016:
1.29 crook 8017:
1.82 anton 8018: @node Interpreter Directives, , Interpret/Compile states, The Text Interpreter
1.26 crook 8019: @subsection Interpreter Directives
8020: @cindex interpreter directives
1.72 anton 8021: @cindex conditional compilation
1.1 anton 8022:
1.29 crook 8023: These words are usually used in interpret state; typically to control
8024: which parts of a source file are processed by the text
1.26 crook 8025: interpreter. There are only a few ANS Forth Standard words, but Gforth
8026: supplements these with a rich set of immediate control structure words
8027: to compensate for the fact that the non-immediate versions can only be
1.29 crook 8028: used in compile state (@pxref{Control Structures}). Typical usages:
8029:
8030: @example
1.72 anton 8031: FALSE Constant HAVE-ASSEMBLER
1.29 crook 8032: .
8033: .
1.72 anton 8034: HAVE-ASSEMBLER [IF]
1.29 crook 8035: : ASSEMBLER-FEATURE
8036: ...
8037: ;
8038: [ENDIF]
8039: .
8040: .
8041: : SEE
8042: ... \ general-purpose SEE code
1.72 anton 8043: [ HAVE-ASSEMBLER [IF] ]
1.29 crook 8044: ... \ assembler-specific SEE code
8045: [ [ENDIF] ]
8046: ;
8047: @end example
1.1 anton 8048:
1.44 crook 8049:
1.26 crook 8050: doc-[IF]
8051: doc-[ELSE]
8052: doc-[THEN]
8053: doc-[ENDIF]
1.1 anton 8054:
1.26 crook 8055: doc-[IFDEF]
8056: doc-[IFUNDEF]
1.1 anton 8057:
1.26 crook 8058: doc-[?DO]
8059: doc-[DO]
8060: doc-[FOR]
8061: doc-[LOOP]
8062: doc-[+LOOP]
8063: doc-[NEXT]
1.1 anton 8064:
1.26 crook 8065: doc-[BEGIN]
8066: doc-[UNTIL]
8067: doc-[AGAIN]
8068: doc-[WHILE]
8069: doc-[REPEAT]
1.1 anton 8070:
1.27 crook 8071:
1.26 crook 8072: @c -------------------------------------------------------------
1.47 crook 8073: @node Word Lists, Environmental Queries, The Text Interpreter, Words
1.26 crook 8074: @section Word Lists
8075: @cindex word lists
1.32 anton 8076: @cindex header space
1.1 anton 8077:
1.36 anton 8078: A wordlist is a list of named words; you can add new words and look up
8079: words by name (and you can remove words in a restricted way with
8080: markers). Every named (and @code{reveal}ed) word is in one wordlist.
8081:
8082: @cindex search order stack
8083: The text interpreter searches the wordlists present in the search order
8084: (a stack of wordlists), from the top to the bottom. Within each
8085: wordlist, the search starts conceptually at the newest word; i.e., if
8086: two words in a wordlist have the same name, the newer word is found.
1.1 anton 8087:
1.26 crook 8088: @cindex compilation word list
1.36 anton 8089: New words are added to the @dfn{compilation wordlist} (aka current
8090: wordlist).
1.1 anton 8091:
1.36 anton 8092: @cindex wid
8093: A word list is identified by a cell-sized word list identifier (@i{wid})
8094: in much the same way as a file is identified by a file handle. The
8095: numerical value of the wid has no (portable) meaning, and might change
8096: from session to session.
1.1 anton 8097:
1.29 crook 8098: The ANS Forth ``Search order'' word set is intended to provide a set of
8099: low-level tools that allow various different schemes to be
1.74 anton 8100: implemented. Gforth also provides @code{vocabulary}, a traditional Forth
1.26 crook 8101: word. @file{compat/vocabulary.fs} provides an implementation in ANS
1.45 crook 8102: Forth.
1.1 anton 8103:
1.27 crook 8104: @comment TODO: locals section refers to here, saying that every word list (aka
8105: @comment vocabulary) has its own methods for searching etc. Need to document that.
1.78 anton 8106: @c anton: but better in a separate subsection on wordlist internals
1.1 anton 8107:
1.45 crook 8108: @comment TODO: document markers, reveal, tables, mappedwordlist
8109:
8110: @comment the gforthman- prefix is used to pick out the true definition of a
1.27 crook 8111: @comment word from the source files, rather than some alias.
1.44 crook 8112:
1.26 crook 8113: doc-forth-wordlist
8114: doc-definitions
8115: doc-get-current
8116: doc-set-current
8117: doc-get-order
1.45 crook 8118: doc---gforthman-set-order
1.26 crook 8119: doc-wordlist
1.30 anton 8120: doc-table
1.79 anton 8121: doc->order
1.36 anton 8122: doc-previous
1.26 crook 8123: doc-also
1.45 crook 8124: doc---gforthman-forth
1.26 crook 8125: doc-only
1.45 crook 8126: doc---gforthman-order
1.15 anton 8127:
1.26 crook 8128: doc-find
8129: doc-search-wordlist
1.15 anton 8130:
1.26 crook 8131: doc-words
8132: doc-vlist
1.44 crook 8133: @c doc-words-deferred
1.1 anton 8134:
1.74 anton 8135: @c doc-mappedwordlist @c map-structure undefined, implemantation-specific
1.26 crook 8136: doc-root
8137: doc-vocabulary
8138: doc-seal
8139: doc-vocs
8140: doc-current
8141: doc-context
1.1 anton 8142:
1.44 crook 8143:
1.26 crook 8144: @menu
1.75 anton 8145: * Vocabularies::
1.67 anton 8146: * Why use word lists?::
1.75 anton 8147: * Word list example::
1.26 crook 8148: @end menu
8149:
1.75 anton 8150: @node Vocabularies, Why use word lists?, Word Lists, Word Lists
8151: @subsection Vocabularies
8152: @cindex Vocabularies, detailed explanation
8153:
8154: Here is an example of creating and using a new wordlist using ANS
8155: Forth words:
8156:
8157: @example
8158: wordlist constant my-new-words-wordlist
8159: : my-new-words get-order nip my-new-words-wordlist swap set-order ;
8160:
8161: \ add it to the search order
8162: also my-new-words
8163:
8164: \ alternatively, add it to the search order and make it
8165: \ the compilation word list
8166: also my-new-words definitions
8167: \ type "order" to see the problem
8168: @end example
8169:
8170: The problem with this example is that @code{order} has no way to
8171: associate the name @code{my-new-words} with the wid of the word list (in
8172: Gforth, @code{order} and @code{vocs} will display @code{???} for a wid
8173: that has no associated name). There is no Standard way of associating a
8174: name with a wid.
8175:
8176: In Gforth, this example can be re-coded using @code{vocabulary}, which
8177: associates a name with a wid:
8178:
8179: @example
8180: vocabulary my-new-words
8181:
8182: \ add it to the search order
8183: also my-new-words
8184:
8185: \ alternatively, add it to the search order and make it
8186: \ the compilation word list
8187: my-new-words definitions
8188: \ type "order" to see that the problem is solved
8189: @end example
8190:
8191:
8192: @node Why use word lists?, Word list example, Vocabularies, Word Lists
1.26 crook 8193: @subsection Why use word lists?
8194: @cindex word lists - why use them?
8195:
1.74 anton 8196: Here are some reasons why people use wordlists:
1.26 crook 8197:
8198: @itemize @bullet
1.74 anton 8199:
8200: @c anton: Gforth's hashing implementation makes the search speed
8201: @c independent from the number of words. But it is linear with the number
8202: @c of wordlists that have to be searched, so in effect using more wordlists
8203: @c actually slows down compilation.
8204:
8205: @c @item
8206: @c To improve compilation speed by reducing the number of header space
8207: @c entries that must be searched. This is achieved by creating a new
8208: @c word list that contains all of the definitions that are used in the
8209: @c definition of a Forth system but which would not usually be used by
8210: @c programs running on that system. That word list would be on the search
8211: @c list when the Forth system was compiled but would be removed from the
8212: @c search list for normal operation. This can be a useful technique for
8213: @c low-performance systems (for example, 8-bit processors in embedded
8214: @c systems) but is unlikely to be necessary in high-performance desktop
8215: @c systems.
8216:
1.26 crook 8217: @item
8218: To prevent a set of words from being used outside the context in which
8219: they are valid. Two classic examples of this are an integrated editor
8220: (all of the edit commands are defined in a separate word list; the
8221: search order is set to the editor word list when the editor is invoked;
8222: the old search order is restored when the editor is terminated) and an
8223: integrated assembler (the op-codes for the machine are defined in a
8224: separate word list which is used when a @code{CODE} word is defined).
1.74 anton 8225:
8226: @item
8227: To organize the words of an application or library into a user-visible
8228: set (in @code{forth-wordlist} or some other common wordlist) and a set
8229: of helper words used just for the implementation (hidden in a separate
1.75 anton 8230: wordlist). This keeps @code{words}' output smaller, separates
8231: implementation and interface, and reduces the chance of name conflicts
8232: within the common wordlist.
1.74 anton 8233:
1.26 crook 8234: @item
8235: To prevent a name-space clash between multiple definitions with the same
8236: name. For example, when building a cross-compiler you might have a word
8237: @code{IF} that generates conditional code for your target system. By
8238: placing this definition in a different word list you can control whether
8239: the host system's @code{IF} or the target system's @code{IF} get used in
8240: any particular context by controlling the order of the word lists on the
8241: search order stack.
1.74 anton 8242:
1.26 crook 8243: @end itemize
1.1 anton 8244:
1.74 anton 8245: The downsides of using wordlists are:
8246:
8247: @itemize
8248:
8249: @item
8250: Debugging becomes more cumbersome.
8251:
8252: @item
8253: Name conflicts worked around with wordlists are still there, and you
8254: have to arrange the search order carefully to get the desired results;
8255: if you forget to do that, you get hard-to-find errors (as in any case
8256: where you read the code differently from the compiler; @code{see} can
1.75 anton 8257: help seeing which of several possible words the name resolves to in such
8258: cases). @code{See} displays just the name of the words, not what
8259: wordlist they belong to, so it might be misleading. Using unique names
8260: is a better approach to avoid name conflicts.
1.74 anton 8261:
8262: @item
8263: You have to explicitly undo any changes to the search order. In many
8264: cases it would be more convenient if this happened implicitly. Gforth
8265: currently does not provide such a feature, but it may do so in the
8266: future.
8267: @end itemize
8268:
8269:
1.75 anton 8270: @node Word list example, , Why use word lists?, Word Lists
8271: @subsection Word list example
8272: @cindex word lists - example
1.1 anton 8273:
1.74 anton 8274: The following example is from the
8275: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
8276: garbage collector} and uses wordlists to separate public words from
8277: helper words:
8278:
8279: @example
8280: get-current ( wid )
8281: vocabulary garbage-collector also garbage-collector definitions
8282: ... \ define helper words
8283: ( wid ) set-current \ restore original (i.e., public) compilation wordlist
8284: ... \ define the public (i.e., API) words
8285: \ they can refer to the helper words
8286: previous \ restore original search order (helper words become invisible)
8287: @end example
8288:
1.26 crook 8289: @c -------------------------------------------------------------
8290: @node Environmental Queries, Files, Word Lists, Words
8291: @section Environmental Queries
8292: @cindex environmental queries
1.21 crook 8293:
1.26 crook 8294: ANS Forth introduced the idea of ``environmental queries'' as a way
8295: for a program running on a system to determine certain characteristics of the system.
8296: The Standard specifies a number of strings that might be recognised by a system.
1.21 crook 8297:
1.32 anton 8298: The Standard requires that the header space used for environmental queries
8299: be distinct from the header space used for definitions.
1.21 crook 8300:
1.26 crook 8301: Typically, environmental queries are supported by creating a set of
1.29 crook 8302: definitions in a word list that is @i{only} used during environmental
1.26 crook 8303: queries; that is what Gforth does. There is no Standard way of adding
8304: definitions to the set of recognised environmental queries, but any
8305: implementation that supports the loading of optional word sets must have
8306: some mechanism for doing this (after loading the word set, the
8307: associated environmental query string must return @code{true}). In
8308: Gforth, the word list used to honour environmental queries can be
8309: manipulated just like any other word list.
1.21 crook 8310:
1.44 crook 8311:
1.26 crook 8312: doc-environment?
8313: doc-environment-wordlist
1.21 crook 8314:
1.26 crook 8315: doc-gforth
8316: doc-os-class
1.21 crook 8317:
1.44 crook 8318:
1.26 crook 8319: Note that, whilst the documentation for (e.g.) @code{gforth} shows it
8320: returning two items on the stack, querying it using @code{environment?}
8321: will return an additional item; the @code{true} flag that shows that the
8322: string was recognised.
1.21 crook 8323:
1.26 crook 8324: @comment TODO Document the standard strings or note where they are documented herein
1.21 crook 8325:
1.26 crook 8326: Here are some examples of using environmental queries:
1.21 crook 8327:
1.26 crook 8328: @example
8329: s" address-unit-bits" environment? 0=
8330: [IF]
8331: cr .( environmental attribute address-units-bits unknown... ) cr
1.75 anton 8332: [ELSE]
8333: drop \ ensure balanced stack effect
1.26 crook 8334: [THEN]
1.21 crook 8335:
1.75 anton 8336: \ this might occur in the prelude of a standard program that uses THROW
8337: s" exception" environment? [IF]
8338: 0= [IF]
8339: : throw abort" exception thrown" ;
8340: [THEN]
8341: [ELSE] \ we don't know, so make sure
8342: : throw abort" exception thrown" ;
8343: [THEN]
1.21 crook 8344:
1.26 crook 8345: s" gforth" environment? [IF] .( Gforth version ) TYPE
8346: [ELSE] .( Not Gforth..) [THEN]
1.75 anton 8347:
8348: \ a program using v*
8349: s" gforth" environment? [IF]
8350: s" 0.5.0" compare 0< [IF] \ v* is a primitive since 0.5.0
8351: : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
8352: >r swap 2swap swap 0e r> 0 ?DO
8353: dup f@ over + 2swap dup f@ f* f+ over + 2swap
8354: LOOP
8355: 2drop 2drop ;
8356: [THEN]
8357: [ELSE] \
8358: : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
8359: ...
8360: [THEN]
1.26 crook 8361: @end example
1.21 crook 8362:
1.26 crook 8363: Here is an example of adding a definition to the environment word list:
1.21 crook 8364:
1.26 crook 8365: @example
8366: get-current environment-wordlist set-current
8367: true constant block
8368: true constant block-ext
8369: set-current
8370: @end example
1.21 crook 8371:
1.26 crook 8372: You can see what definitions are in the environment word list like this:
1.21 crook 8373:
1.26 crook 8374: @example
1.79 anton 8375: environment-wordlist >order words previous
1.26 crook 8376: @end example
1.21 crook 8377:
8378:
1.26 crook 8379: @c -------------------------------------------------------------
8380: @node Files, Blocks, Environmental Queries, Words
8381: @section Files
1.28 crook 8382: @cindex files
8383: @cindex I/O - file-handling
1.21 crook 8384:
1.26 crook 8385: Gforth provides facilities for accessing files that are stored in the
8386: host operating system's file-system. Files that are processed by Gforth
8387: can be divided into two categories:
1.21 crook 8388:
1.23 crook 8389: @itemize @bullet
8390: @item
1.29 crook 8391: Files that are processed by the Text Interpreter (@dfn{Forth source files}).
1.23 crook 8392: @item
1.29 crook 8393: Files that are processed by some other program (@dfn{general files}).
1.26 crook 8394: @end itemize
8395:
8396: @menu
1.48 anton 8397: * Forth source files::
8398: * General files::
8399: * Search Paths::
1.26 crook 8400: @end menu
8401:
8402: @c -------------------------------------------------------------
8403: @node Forth source files, General files, Files, Files
8404: @subsection Forth source files
8405: @cindex including files
8406: @cindex Forth source files
1.21 crook 8407:
1.26 crook 8408: The simplest way to interpret the contents of a file is to use one of
8409: these two formats:
1.21 crook 8410:
1.26 crook 8411: @example
8412: include mysource.fs
8413: s" mysource.fs" included
8414: @end example
1.21 crook 8415:
1.75 anton 8416: You usually want to include a file only if it is not included already
1.26 crook 8417: (by, say, another source file). In that case, you can use one of these
1.45 crook 8418: three formats:
1.21 crook 8419:
1.26 crook 8420: @example
8421: require mysource.fs
8422: needs mysource.fs
8423: s" mysource.fs" required
8424: @end example
1.21 crook 8425:
1.26 crook 8426: @cindex stack effect of included files
8427: @cindex including files, stack effect
1.45 crook 8428: It is good practice to write your source files such that interpreting them
8429: does not change the stack. Source files designed in this way can be used with
1.26 crook 8430: @code{required} and friends without complications. For example:
1.21 crook 8431:
1.26 crook 8432: @example
1.75 anton 8433: 1024 require foo.fs drop
1.26 crook 8434: @end example
1.21 crook 8435:
1.75 anton 8436: Here you want to pass the argument 1024 (e.g., a buffer size) to
8437: @file{foo.fs}. Interpreting @file{foo.fs} has the stack effect ( n -- n
8438: ), which allows its use with @code{require}. Of course with such
8439: parameters to required files, you have to ensure that the first
8440: @code{require} fits for all uses (i.e., @code{require} it early in the
8441: master load file).
1.44 crook 8442:
1.26 crook 8443: doc-include-file
8444: doc-included
1.28 crook 8445: doc-included?
1.26 crook 8446: doc-include
8447: doc-required
8448: doc-require
8449: doc-needs
1.75 anton 8450: @c doc-init-included-files @c internal
8451: doc-sourcefilename
8452: doc-sourceline#
1.44 crook 8453:
1.26 crook 8454: A definition in ANS Forth for @code{required} is provided in
8455: @file{compat/required.fs}.
1.21 crook 8456:
1.26 crook 8457: @c -------------------------------------------------------------
8458: @node General files, Search Paths, Forth source files, Files
8459: @subsection General files
8460: @cindex general files
8461: @cindex file-handling
1.21 crook 8462:
1.75 anton 8463: Files are opened/created by name and type. The following file access
8464: methods (FAMs) are recognised:
1.44 crook 8465:
1.75 anton 8466: @cindex fam (file access method)
1.26 crook 8467: doc-r/o
8468: doc-r/w
8469: doc-w/o
8470: doc-bin
1.1 anton 8471:
1.44 crook 8472:
1.26 crook 8473: When a file is opened/created, it returns a file identifier,
1.29 crook 8474: @i{wfileid} that is used for all other file commands. All file
8475: commands also return a status value, @i{wior}, that is 0 for a
1.26 crook 8476: successful operation and an implementation-defined non-zero value in the
8477: case of an error.
1.21 crook 8478:
1.44 crook 8479:
1.26 crook 8480: doc-open-file
8481: doc-create-file
1.21 crook 8482:
1.26 crook 8483: doc-close-file
8484: doc-delete-file
8485: doc-rename-file
8486: doc-read-file
8487: doc-read-line
8488: doc-write-file
8489: doc-write-line
8490: doc-emit-file
8491: doc-flush-file
1.21 crook 8492:
1.26 crook 8493: doc-file-status
8494: doc-file-position
8495: doc-reposition-file
8496: doc-file-size
8497: doc-resize-file
1.21 crook 8498:
1.93 anton 8499: doc-slurp-file
8500: doc-slurp-fid
1.44 crook 8501:
1.26 crook 8502: @c ---------------------------------------------------------
1.48 anton 8503: @node Search Paths, , General files, Files
1.26 crook 8504: @subsection Search Paths
8505: @cindex path for @code{included}
8506: @cindex file search path
8507: @cindex @code{include} search path
8508: @cindex search path for files
1.21 crook 8509:
1.26 crook 8510: If you specify an absolute filename (i.e., a filename starting with
8511: @file{/} or @file{~}, or with @file{:} in the second position (as in
8512: @samp{C:...})) for @code{included} and friends, that file is included
8513: just as you would expect.
1.21 crook 8514:
1.75 anton 8515: If the filename starts with @file{./}, this refers to the directory that
8516: the present file was @code{included} from. This allows files to include
8517: other files relative to their own position (irrespective of the current
8518: working directory or the absolute position). This feature is essential
8519: for libraries consisting of several files, where a file may include
8520: other files from the library. It corresponds to @code{#include "..."}
8521: in C. If the current input source is not a file, @file{.} refers to the
8522: directory of the innermost file being included, or, if there is no file
8523: being included, to the current working directory.
8524:
8525: For relative filenames (not starting with @file{./}), Gforth uses a
8526: search path similar to Forth's search order (@pxref{Word Lists}). It
8527: tries to find the given filename in the directories present in the path,
8528: and includes the first one it finds. There are separate search paths for
8529: Forth source files and general files. If the search path contains the
8530: directory @file{.}, this refers to the directory of the current file, or
8531: the working directory, as if the file had been specified with @file{./}.
1.21 crook 8532:
1.26 crook 8533: Use @file{~+} to refer to the current working directory (as in the
8534: @code{bash}).
1.1 anton 8535:
1.75 anton 8536: @c anton: fold the following subsubsections into this subsection?
1.1 anton 8537:
1.48 anton 8538: @menu
1.75 anton 8539: * Source Search Paths::
1.48 anton 8540: * General Search Paths::
8541: @end menu
8542:
1.26 crook 8543: @c ---------------------------------------------------------
1.75 anton 8544: @node Source Search Paths, General Search Paths, Search Paths, Search Paths
8545: @subsubsection Source Search Paths
8546: @cindex search path control, source files
1.5 anton 8547:
1.26 crook 8548: The search path is initialized when you start Gforth (@pxref{Invoking
1.75 anton 8549: Gforth}). You can display it and change it using @code{fpath} in
8550: combination with the general path handling words.
1.5 anton 8551:
1.75 anton 8552: doc-fpath
8553: @c the functionality of the following words is easily available through
8554: @c fpath and the general path words. The may go away.
8555: @c doc-.fpath
8556: @c doc-fpath+
8557: @c doc-fpath=
8558: @c doc-open-fpath-file
1.44 crook 8559:
8560: @noindent
1.26 crook 8561: Here is an example of using @code{fpath} and @code{require}:
1.5 anton 8562:
1.26 crook 8563: @example
1.75 anton 8564: fpath path= /usr/lib/forth/|./
1.26 crook 8565: require timer.fs
8566: @end example
1.5 anton 8567:
1.75 anton 8568:
1.26 crook 8569: @c ---------------------------------------------------------
1.75 anton 8570: @node General Search Paths, , Source Search Paths, Search Paths
1.26 crook 8571: @subsubsection General Search Paths
1.75 anton 8572: @cindex search path control, source files
1.5 anton 8573:
1.26 crook 8574: Your application may need to search files in several directories, like
8575: @code{included} does. To facilitate this, Gforth allows you to define
8576: and use your own search paths, by providing generic equivalents of the
8577: Forth search path words:
1.5 anton 8578:
1.75 anton 8579: doc-open-path-file
8580: doc-path-allot
8581: doc-clear-path
8582: doc-also-path
1.26 crook 8583: doc-.path
8584: doc-path+
8585: doc-path=
1.5 anton 8586:
1.75 anton 8587: @c anton: better define a word for it, say "path-allot ( ucount -- path-addr )
1.44 crook 8588:
1.75 anton 8589: Here's an example of creating an empty search path:
8590: @c
1.26 crook 8591: @example
1.75 anton 8592: create mypath 500 path-allot \ maximum length 500 chars (is checked)
1.26 crook 8593: @end example
1.5 anton 8594:
1.26 crook 8595: @c -------------------------------------------------------------
8596: @node Blocks, Other I/O, Files, Words
8597: @section Blocks
1.28 crook 8598: @cindex I/O - blocks
8599: @cindex blocks
8600:
8601: When you run Gforth on a modern desk-top computer, it runs under the
8602: control of an operating system which provides certain services. One of
8603: these services is @var{file services}, which allows Forth source code
8604: and data to be stored in files and read into Gforth (@pxref{Files}).
8605:
8606: Traditionally, Forth has been an important programming language on
8607: systems where it has interfaced directly to the underlying hardware with
8608: no intervening operating system. Forth provides a mechanism, called
1.29 crook 8609: @dfn{blocks}, for accessing mass storage on such systems.
1.28 crook 8610:
8611: A block is a 1024-byte data area, which can be used to hold data or
8612: Forth source code. No structure is imposed on the contents of the
8613: block. A block is identified by its number; blocks are numbered
8614: contiguously from 1 to an implementation-defined maximum.
8615:
8616: A typical system that used blocks but no operating system might use a
8617: single floppy-disk drive for mass storage, with the disks formatted to
8618: provide 256-byte sectors. Blocks would be implemented by assigning the
8619: first four sectors of the disk to block 1, the second four sectors to
8620: block 2 and so on, up to the limit of the capacity of the disk. The disk
8621: would not contain any file system information, just the set of blocks.
8622:
1.29 crook 8623: @cindex blocks file
1.28 crook 8624: On systems that do provide file services, blocks are typically
1.29 crook 8625: implemented by storing a sequence of blocks within a single @dfn{blocks
1.28 crook 8626: file}. The size of the blocks file will be an exact multiple of 1024
8627: bytes, corresponding to the number of blocks it contains. This is the
8628: mechanism that Gforth uses.
8629:
1.29 crook 8630: @cindex @file{blocks.fb}
1.75 anton 8631: Only one blocks file can be open at a time. If you use block words without
1.28 crook 8632: having specified a blocks file, Gforth defaults to the blocks file
8633: @file{blocks.fb}. Gforth uses the Forth search path when attempting to
1.75 anton 8634: locate a blocks file (@pxref{Source Search Paths}).
1.28 crook 8635:
1.29 crook 8636: @cindex block buffers
1.28 crook 8637: When you read and write blocks under program control, Gforth uses a
1.29 crook 8638: number of @dfn{block buffers} as intermediate storage. These buffers are
1.28 crook 8639: not used when you use @code{load} to interpret the contents of a block.
8640:
1.75 anton 8641: The behaviour of the block buffers is analagous to that of a cache.
8642: Each block buffer has three states:
1.28 crook 8643:
8644: @itemize @bullet
8645: @item
8646: Unassigned
8647: @item
8648: Assigned-clean
8649: @item
8650: Assigned-dirty
8651: @end itemize
8652:
1.29 crook 8653: Initially, all block buffers are @i{unassigned}. In order to access a
1.28 crook 8654: block, the block (specified by its block number) must be assigned to a
8655: block buffer.
8656:
8657: The assignment of a block to a block buffer is performed by @code{block}
8658: or @code{buffer}. Use @code{block} when you wish to modify the existing
8659: contents of a block. Use @code{buffer} when you don't care about the
8660: existing contents of the block@footnote{The ANS Forth definition of
1.35 anton 8661: @code{buffer} is intended not to cause disk I/O; if the data associated
1.28 crook 8662: with the particular block is already stored in a block buffer due to an
8663: earlier @code{block} command, @code{buffer} will return that block
8664: buffer and the existing contents of the block will be
8665: available. Otherwise, @code{buffer} will simply assign a new, empty
1.29 crook 8666: block buffer for the block.}.
1.28 crook 8667:
1.47 crook 8668: Once a block has been assigned to a block buffer using @code{block} or
1.75 anton 8669: @code{buffer}, that block buffer becomes the @i{current block
8670: buffer}. Data may only be manipulated (read or written) within the
8671: current block buffer.
1.47 crook 8672:
8673: When the contents of the current block buffer has been modified it is
1.48 anton 8674: necessary, @emph{before calling @code{block} or @code{buffer} again}, to
1.75 anton 8675: either abandon the changes (by doing nothing) or mark the block as
8676: changed (assigned-dirty), using @code{update}. Using @code{update} does
8677: not change the blocks file; it simply changes a block buffer's state to
8678: @i{assigned-dirty}. The block will be written implicitly when it's
8679: buffer is needed for another block, or explicitly by @code{flush} or
8680: @code{save-buffers}.
8681:
8682: word @code{Flush} writes all @i{assigned-dirty} blocks back to the
8683: blocks file on disk. Leaving Gforth with @code{bye} also performs a
8684: @code{flush}.
1.28 crook 8685:
1.29 crook 8686: In Gforth, @code{block} and @code{buffer} use a @i{direct-mapped}
1.28 crook 8687: algorithm to assign a block buffer to a block. That means that any
8688: particular block can only be assigned to one specific block buffer,
1.29 crook 8689: called (for the particular operation) the @i{victim buffer}. If the
1.47 crook 8690: victim buffer is @i{unassigned} or @i{assigned-clean} it is allocated to
8691: the new block immediately. If it is @i{assigned-dirty} its current
8692: contents are written back to the blocks file on disk before it is
1.28 crook 8693: allocated to the new block.
8694:
8695: Although no structure is imposed on the contents of a block, it is
8696: traditional to display the contents as 16 lines each of 64 characters. A
8697: block provides a single, continuous stream of input (for example, it
8698: acts as a single parse area) -- there are no end-of-line characters
8699: within a block, and no end-of-file character at the end of a
8700: block. There are two consequences of this:
1.26 crook 8701:
1.28 crook 8702: @itemize @bullet
8703: @item
8704: The last character of one line wraps straight into the first character
8705: of the following line
8706: @item
8707: The word @code{\} -- comment to end of line -- requires special
8708: treatment; in the context of a block it causes all characters until the
8709: end of the current 64-character ``line'' to be ignored.
8710: @end itemize
8711:
8712: In Gforth, when you use @code{block} with a non-existent block number,
1.45 crook 8713: the current blocks file will be extended to the appropriate size and the
1.28 crook 8714: block buffer will be initialised with spaces.
8715:
1.47 crook 8716: Gforth includes a simple block editor (type @code{use blocked.fb 0 list}
8717: for details) but doesn't encourage the use of blocks; the mechanism is
8718: only provided for backward compatibility -- ANS Forth requires blocks to
8719: be available when files are.
1.28 crook 8720:
8721: Common techniques that are used when working with blocks include:
8722:
8723: @itemize @bullet
8724: @item
8725: A screen editor that allows you to edit blocks without leaving the Forth
8726: environment.
8727: @item
8728: Shadow screens; where every code block has an associated block
8729: containing comments (for example: code in odd block numbers, comments in
8730: even block numbers). Typically, the block editor provides a convenient
8731: mechanism to toggle between code and comments.
8732: @item
8733: Load blocks; a single block (typically block 1) contains a number of
8734: @code{thru} commands which @code{load} the whole of the application.
8735: @end itemize
1.26 crook 8736:
1.29 crook 8737: See Frank Sergeant's Pygmy Forth to see just how well blocks can be
8738: integrated into a Forth programming environment.
1.26 crook 8739:
8740: @comment TODO what about errors on open-blocks?
1.44 crook 8741:
1.26 crook 8742: doc-open-blocks
8743: doc-use
1.75 anton 8744: doc-block-offset
1.26 crook 8745: doc-get-block-fid
8746: doc-block-position
1.28 crook 8747:
1.75 anton 8748: doc-list
1.28 crook 8749: doc-scr
8750:
1.45 crook 8751: doc---gforthman-block
1.28 crook 8752: doc-buffer
8753:
1.75 anton 8754: doc-empty-buffers
8755: doc-empty-buffer
1.26 crook 8756: doc-update
1.28 crook 8757: doc-updated?
1.26 crook 8758: doc-save-buffers
1.75 anton 8759: doc-save-buffer
1.26 crook 8760: doc-flush
1.28 crook 8761:
1.26 crook 8762: doc-load
8763: doc-thru
8764: doc-+load
8765: doc-+thru
1.45 crook 8766: doc---gforthman--->
1.26 crook 8767: doc-block-included
8768:
1.44 crook 8769:
1.26 crook 8770: @c -------------------------------------------------------------
1.78 anton 8771: @node Other I/O, Locals, Blocks, Words
1.26 crook 8772: @section Other I/O
1.28 crook 8773: @cindex I/O - keyboard and display
1.26 crook 8774:
8775: @menu
8776: * Simple numeric output:: Predefined formats
8777: * Formatted numeric output:: Formatted (pictured) output
8778: * String Formats:: How Forth stores strings in memory
1.67 anton 8779: * Displaying characters and strings:: Other stuff
1.26 crook 8780: * Input:: Input
8781: @end menu
8782:
8783: @node Simple numeric output, Formatted numeric output, Other I/O, Other I/O
8784: @subsection Simple numeric output
1.28 crook 8785: @cindex numeric output - simple/free-format
1.5 anton 8786:
1.26 crook 8787: The simplest output functions are those that display numbers from the
8788: data or floating-point stacks. Floating-point output is always displayed
8789: using base 10. Numbers displayed from the data stack use the value stored
8790: in @code{base}.
1.5 anton 8791:
1.44 crook 8792:
1.26 crook 8793: doc-.
8794: doc-dec.
8795: doc-hex.
8796: doc-u.
8797: doc-.r
8798: doc-u.r
8799: doc-d.
8800: doc-ud.
8801: doc-d.r
8802: doc-ud.r
8803: doc-f.
8804: doc-fe.
8805: doc-fs.
1.5 anton 8806:
1.44 crook 8807:
1.26 crook 8808: Examples of printing the number 1234.5678E23 in the different floating-point output
8809: formats are shown below:
1.5 anton 8810:
8811: @example
1.26 crook 8812: f. 123456779999999000000000000.
8813: fe. 123.456779999999E24
8814: fs. 1.23456779999999E26
1.5 anton 8815: @end example
8816:
8817:
1.26 crook 8818: @node Formatted numeric output, String Formats, Simple numeric output, Other I/O
8819: @subsection Formatted numeric output
1.28 crook 8820: @cindex formatted numeric output
1.26 crook 8821: @cindex pictured numeric output
1.28 crook 8822: @cindex numeric output - formatted
1.26 crook 8823:
1.29 crook 8824: Forth traditionally uses a technique called @dfn{pictured numeric
1.26 crook 8825: output} for formatted printing of integers. In this technique, digits
8826: are extracted from the number (using the current output radix defined by
8827: @code{base}), converted to ASCII codes and appended to a string that is
8828: built in a scratch-pad area of memory (@pxref{core-idef,
8829: Implementation-defined options, Implementation-defined
8830: options}). Arbitrary characters can be appended to the string during the
8831: extraction process. The completed string is specified by an address
8832: and length and can be manipulated (@code{TYPE}ed, copied, modified)
8833: under program control.
1.5 anton 8834:
1.75 anton 8835: All of the integer output words described in the previous section
8836: (@pxref{Simple numeric output}) are implemented in Gforth using pictured
8837: numeric output.
1.5 anton 8838:
1.47 crook 8839: Three important things to remember about pictured numeric output:
1.5 anton 8840:
1.26 crook 8841: @itemize @bullet
8842: @item
1.28 crook 8843: It always operates on double-precision numbers; to display a
1.49 anton 8844: single-precision number, convert it first (for ways of doing this
8845: @pxref{Double precision}).
1.26 crook 8846: @item
1.28 crook 8847: It always treats the double-precision number as though it were
8848: unsigned. The examples below show ways of printing signed numbers.
1.26 crook 8849: @item
8850: The string is built up from right to left; least significant digit first.
8851: @end itemize
1.5 anton 8852:
1.44 crook 8853:
1.26 crook 8854: doc-<#
1.47 crook 8855: doc-<<#
1.26 crook 8856: doc-#
8857: doc-#s
8858: doc-hold
8859: doc-sign
8860: doc-#>
1.47 crook 8861: doc-#>>
1.5 anton 8862:
1.26 crook 8863: doc-represent
1.5 anton 8864:
1.44 crook 8865:
8866: @noindent
1.26 crook 8867: Here are some examples of using pictured numeric output:
1.5 anton 8868:
8869: @example
1.26 crook 8870: : my-u. ( u -- )
8871: \ Simplest use of pns.. behaves like Standard u.
8872: 0 \ convert to unsigned double
1.75 anton 8873: <<# \ start conversion
1.26 crook 8874: #s \ convert all digits
8875: #> \ complete conversion
1.75 anton 8876: TYPE SPACE \ display, with trailing space
8877: #>> ; \ release hold area
1.5 anton 8878:
1.26 crook 8879: : cents-only ( u -- )
8880: 0 \ convert to unsigned double
1.75 anton 8881: <<# \ start conversion
1.26 crook 8882: # # \ convert two least-significant digits
8883: #> \ complete conversion, discard other digits
1.75 anton 8884: TYPE SPACE \ display, with trailing space
8885: #>> ; \ release hold area
1.5 anton 8886:
1.26 crook 8887: : dollars-and-cents ( u -- )
8888: 0 \ convert to unsigned double
1.75 anton 8889: <<# \ start conversion
1.26 crook 8890: # # \ convert two least-significant digits
8891: [char] . hold \ insert decimal point
8892: #s \ convert remaining digits
8893: [char] $ hold \ append currency symbol
8894: #> \ complete conversion
1.75 anton 8895: TYPE SPACE \ display, with trailing space
8896: #>> ; \ release hold area
1.5 anton 8897:
1.26 crook 8898: : my-. ( n -- )
8899: \ handling negatives.. behaves like Standard .
8900: s>d \ convert to signed double
8901: swap over dabs \ leave sign byte followed by unsigned double
1.75 anton 8902: <<# \ start conversion
1.26 crook 8903: #s \ convert all digits
8904: rot sign \ get at sign byte, append "-" if needed
8905: #> \ complete conversion
1.75 anton 8906: TYPE SPACE \ display, with trailing space
8907: #>> ; \ release hold area
1.5 anton 8908:
1.26 crook 8909: : account. ( n -- )
1.75 anton 8910: \ accountants don't like minus signs, they use parentheses
1.26 crook 8911: \ for negative numbers
8912: s>d \ convert to signed double
8913: swap over dabs \ leave sign byte followed by unsigned double
1.75 anton 8914: <<# \ start conversion
1.26 crook 8915: 2 pick \ get copy of sign byte
8916: 0< IF [char] ) hold THEN \ right-most character of output
8917: #s \ convert all digits
8918: rot \ get at sign byte
8919: 0< IF [char] ( hold THEN
8920: #> \ complete conversion
1.75 anton 8921: TYPE SPACE \ display, with trailing space
8922: #>> ; \ release hold area
8923:
1.5 anton 8924: @end example
8925:
1.26 crook 8926: Here are some examples of using these words:
1.5 anton 8927:
8928: @example
1.26 crook 8929: 1 my-u. 1
8930: hex -1 my-u. decimal FFFFFFFF
8931: 1 cents-only 01
8932: 1234 cents-only 34
8933: 2 dollars-and-cents $0.02
8934: 1234 dollars-and-cents $12.34
8935: 123 my-. 123
8936: -123 my. -123
8937: 123 account. 123
8938: -456 account. (456)
1.5 anton 8939: @end example
8940:
8941:
1.26 crook 8942: @node String Formats, Displaying characters and strings, Formatted numeric output, Other I/O
8943: @subsection String Formats
1.27 crook 8944: @cindex strings - see character strings
8945: @cindex character strings - formats
1.28 crook 8946: @cindex I/O - see character strings
1.75 anton 8947: @cindex counted strings
8948:
8949: @c anton: this does not really belong here; maybe the memory section,
8950: @c or the principles chapter
1.26 crook 8951:
1.27 crook 8952: Forth commonly uses two different methods for representing character
8953: strings:
1.26 crook 8954:
8955: @itemize @bullet
8956: @item
8957: @cindex address of counted string
1.45 crook 8958: @cindex counted string
1.29 crook 8959: As a @dfn{counted string}, represented by a @i{c-addr}. The char
8960: addressed by @i{c-addr} contains a character-count, @i{n}, of the
8961: string and the string occupies the subsequent @i{n} char addresses in
1.26 crook 8962: memory.
8963: @item
1.29 crook 8964: As cell pair on the stack; @i{c-addr u}, where @i{u} is the length
8965: of the string in characters, and @i{c-addr} is the address of the
1.26 crook 8966: first byte of the string.
8967: @end itemize
8968:
8969: ANS Forth encourages the use of the second format when representing
1.75 anton 8970: strings.
1.26 crook 8971:
1.44 crook 8972:
1.26 crook 8973: doc-count
8974:
1.44 crook 8975:
1.49 anton 8976: For words that move, copy and search for strings see @ref{Memory
8977: Blocks}. For words that display characters and strings see
8978: @ref{Displaying characters and strings}.
1.26 crook 8979:
8980: @node Displaying characters and strings, Input, String Formats, Other I/O
8981: @subsection Displaying characters and strings
1.27 crook 8982: @cindex characters - compiling and displaying
8983: @cindex character strings - compiling and displaying
1.26 crook 8984:
8985: This section starts with a glossary of Forth words and ends with a set
8986: of examples.
8987:
1.44 crook 8988:
1.26 crook 8989: doc-bl
8990: doc-space
8991: doc-spaces
8992: doc-emit
8993: doc-toupper
8994: doc-."
8995: doc-.(
1.98 anton 8996: doc-.\"
1.26 crook 8997: doc-type
1.44 crook 8998: doc-typewhite
1.26 crook 8999: doc-cr
1.27 crook 9000: @cindex cursor control
1.26 crook 9001: doc-at-xy
9002: doc-page
9003: doc-s"
1.98 anton 9004: doc-s\"
1.26 crook 9005: doc-c"
9006: doc-char
9007: doc-[char]
9008:
1.44 crook 9009:
9010: @noindent
1.26 crook 9011: As an example, consider the following text, stored in a file @file{test.fs}:
1.5 anton 9012:
9013: @example
1.26 crook 9014: .( text-1)
9015: : my-word
9016: ." text-2" cr
9017: .( text-3)
9018: ;
9019:
9020: ." text-4"
9021:
9022: : my-char
9023: [char] ALPHABET emit
9024: char emit
9025: ;
1.5 anton 9026: @end example
9027:
1.26 crook 9028: When you load this code into Gforth, the following output is generated:
1.5 anton 9029:
1.26 crook 9030: @example
1.30 anton 9031: @kbd{include test.fs @key{RET}} text-1text-3text-4 ok
1.26 crook 9032: @end example
1.5 anton 9033:
1.26 crook 9034: @itemize @bullet
9035: @item
9036: Messages @code{text-1} and @code{text-3} are displayed because @code{.(}
9037: is an immediate word; it behaves in the same way whether it is used inside
9038: or outside a colon definition.
9039: @item
9040: Message @code{text-4} is displayed because of Gforth's added interpretation
9041: semantics for @code{."}.
9042: @item
1.29 crook 9043: Message @code{text-2} is @i{not} displayed, because the text interpreter
1.26 crook 9044: performs the compilation semantics for @code{."} within the definition of
9045: @code{my-word}.
9046: @end itemize
1.5 anton 9047:
1.26 crook 9048: Here are some examples of executing @code{my-word} and @code{my-char}:
1.5 anton 9049:
1.26 crook 9050: @example
1.30 anton 9051: @kbd{my-word @key{RET}} text-2
1.26 crook 9052: ok
1.30 anton 9053: @kbd{my-char fred @key{RET}} Af ok
9054: @kbd{my-char jim @key{RET}} Aj ok
1.26 crook 9055: @end example
1.5 anton 9056:
9057: @itemize @bullet
9058: @item
1.26 crook 9059: Message @code{text-2} is displayed because of the run-time behaviour of
9060: @code{."}.
9061: @item
9062: @code{[char]} compiles the ``A'' from ``ALPHABET'' and puts its display code
9063: on the stack at run-time. @code{emit} always displays the character
9064: when @code{my-char} is executed.
9065: @item
9066: @code{char} parses a string at run-time and the second @code{emit} displays
9067: the first character of the string.
1.5 anton 9068: @item
1.26 crook 9069: If you type @code{see my-char} you can see that @code{[char]} discarded
9070: the text ``LPHABET'' and only compiled the display code for ``A'' into the
9071: definition of @code{my-char}.
1.5 anton 9072: @end itemize
9073:
9074:
9075:
1.48 anton 9076: @node Input, , Displaying characters and strings, Other I/O
1.26 crook 9077: @subsection Input
9078: @cindex input
1.28 crook 9079: @cindex I/O - see input
9080: @cindex parsing a string
1.5 anton 9081:
1.49 anton 9082: For ways of storing character strings in memory see @ref{String Formats}.
1.5 anton 9083:
1.27 crook 9084: @comment TODO examples for >number >float accept key key? pad parse word refill
1.29 crook 9085: @comment then index them
1.27 crook 9086:
1.44 crook 9087:
1.27 crook 9088: doc-key
9089: doc-key?
1.45 crook 9090: doc-ekey
9091: doc-ekey?
9092: doc-ekey>char
1.26 crook 9093: doc->number
9094: doc->float
9095: doc-accept
1.109 ! anton 9096: doc-edit-line
1.27 crook 9097: doc-pad
1.75 anton 9098: @c anton: these belong in the input stream section
1.27 crook 9099: doc-parse
9100: doc-word
1.98 anton 9101: doc-name
9102: doc-parse-word
9103: doc-\"-parse
1.27 crook 9104: doc-sword
9105: doc-refill
9106: @comment obsolescent words..
9107: doc-convert
1.26 crook 9108: doc-query
9109: doc-expect
1.27 crook 9110: doc-span
1.5 anton 9111:
9112:
1.78 anton 9113: @c -------------------------------------------------------------
9114: @node Locals, Structures, Other I/O, Words
9115: @section Locals
9116: @cindex locals
9117:
9118: Local variables can make Forth programming more enjoyable and Forth
9119: programs easier to read. Unfortunately, the locals of ANS Forth are
9120: laden with restrictions. Therefore, we provide not only the ANS Forth
9121: locals wordset, but also our own, more powerful locals wordset (we
9122: implemented the ANS Forth locals wordset through our locals wordset).
1.44 crook 9123:
1.78 anton 9124: The ideas in this section have also been published in M. Anton Ertl,
9125: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl94l.ps.gz,
9126: Automatic Scoping of Local Variables}}, EuroForth '94.
1.12 anton 9127:
9128: @menu
1.78 anton 9129: * Gforth locals::
9130: * ANS Forth locals::
1.5 anton 9131: @end menu
9132:
1.78 anton 9133: @node Gforth locals, ANS Forth locals, Locals, Locals
9134: @subsection Gforth locals
9135: @cindex Gforth locals
9136: @cindex locals, Gforth style
1.5 anton 9137:
1.78 anton 9138: Locals can be defined with
1.44 crook 9139:
1.78 anton 9140: @example
9141: @{ local1 local2 ... -- comment @}
9142: @end example
9143: or
9144: @example
9145: @{ local1 local2 ... @}
9146: @end example
1.5 anton 9147:
1.78 anton 9148: E.g.,
9149: @example
9150: : max @{ n1 n2 -- n3 @}
9151: n1 n2 > if
9152: n1
9153: else
9154: n2
9155: endif ;
9156: @end example
1.44 crook 9157:
1.78 anton 9158: The similarity of locals definitions with stack comments is intended. A
9159: locals definition often replaces the stack comment of a word. The order
9160: of the locals corresponds to the order in a stack comment and everything
9161: after the @code{--} is really a comment.
1.77 anton 9162:
1.78 anton 9163: This similarity has one disadvantage: It is too easy to confuse locals
9164: declarations with stack comments, causing bugs and making them hard to
9165: find. However, this problem can be avoided by appropriate coding
9166: conventions: Do not use both notations in the same program. If you do,
9167: they should be distinguished using additional means, e.g. by position.
1.77 anton 9168:
1.78 anton 9169: @cindex types of locals
9170: @cindex locals types
9171: The name of the local may be preceded by a type specifier, e.g.,
9172: @code{F:} for a floating point value:
1.5 anton 9173:
1.78 anton 9174: @example
9175: : CX* @{ F: Ar F: Ai F: Br F: Bi -- Cr Ci @}
9176: \ complex multiplication
9177: Ar Br f* Ai Bi f* f-
9178: Ar Bi f* Ai Br f* f+ ;
9179: @end example
1.44 crook 9180:
1.78 anton 9181: @cindex flavours of locals
9182: @cindex locals flavours
9183: @cindex value-flavoured locals
9184: @cindex variable-flavoured locals
9185: Gforth currently supports cells (@code{W:}, @code{W^}), doubles
9186: (@code{D:}, @code{D^}), floats (@code{F:}, @code{F^}) and characters
9187: (@code{C:}, @code{C^}) in two flavours: a value-flavoured local (defined
9188: with @code{W:}, @code{D:} etc.) produces its value and can be changed
9189: with @code{TO}. A variable-flavoured local (defined with @code{W^} etc.)
9190: produces its address (which becomes invalid when the variable's scope is
9191: left). E.g., the standard word @code{emit} can be defined in terms of
9192: @code{type} like this:
1.5 anton 9193:
1.78 anton 9194: @example
9195: : emit @{ C^ char* -- @}
9196: char* 1 type ;
9197: @end example
1.5 anton 9198:
1.78 anton 9199: @cindex default type of locals
9200: @cindex locals, default type
9201: A local without type specifier is a @code{W:} local. Both flavours of
9202: locals are initialized with values from the data or FP stack.
1.44 crook 9203:
1.78 anton 9204: Currently there is no way to define locals with user-defined data
9205: structures, but we are working on it.
1.5 anton 9206:
1.78 anton 9207: Gforth allows defining locals everywhere in a colon definition. This
9208: poses the following questions:
1.5 anton 9209:
1.78 anton 9210: @menu
9211: * Where are locals visible by name?::
9212: * How long do locals live?::
9213: * Locals programming style::
9214: * Locals implementation::
9215: @end menu
1.44 crook 9216:
1.78 anton 9217: @node Where are locals visible by name?, How long do locals live?, Gforth locals, Gforth locals
9218: @subsubsection Where are locals visible by name?
9219: @cindex locals visibility
9220: @cindex visibility of locals
9221: @cindex scope of locals
1.5 anton 9222:
1.78 anton 9223: Basically, the answer is that locals are visible where you would expect
9224: it in block-structured languages, and sometimes a little longer. If you
9225: want to restrict the scope of a local, enclose its definition in
9226: @code{SCOPE}...@code{ENDSCOPE}.
1.5 anton 9227:
9228:
1.78 anton 9229: doc-scope
9230: doc-endscope
1.5 anton 9231:
9232:
1.78 anton 9233: These words behave like control structure words, so you can use them
9234: with @code{CS-PICK} and @code{CS-ROLL} to restrict the scope in
9235: arbitrary ways.
1.77 anton 9236:
1.78 anton 9237: If you want a more exact answer to the visibility question, here's the
9238: basic principle: A local is visible in all places that can only be
9239: reached through the definition of the local@footnote{In compiler
9240: construction terminology, all places dominated by the definition of the
9241: local.}. In other words, it is not visible in places that can be reached
9242: without going through the definition of the local. E.g., locals defined
9243: in @code{IF}...@code{ENDIF} are visible until the @code{ENDIF}, locals
9244: defined in @code{BEGIN}...@code{UNTIL} are visible after the
9245: @code{UNTIL} (until, e.g., a subsequent @code{ENDSCOPE}).
1.77 anton 9246:
1.78 anton 9247: The reasoning behind this solution is: We want to have the locals
9248: visible as long as it is meaningful. The user can always make the
9249: visibility shorter by using explicit scoping. In a place that can
9250: only be reached through the definition of a local, the meaning of a
9251: local name is clear. In other places it is not: How is the local
9252: initialized at the control flow path that does not contain the
9253: definition? Which local is meant, if the same name is defined twice in
9254: two independent control flow paths?
1.77 anton 9255:
1.78 anton 9256: This should be enough detail for nearly all users, so you can skip the
9257: rest of this section. If you really must know all the gory details and
9258: options, read on.
1.77 anton 9259:
1.78 anton 9260: In order to implement this rule, the compiler has to know which places
9261: are unreachable. It knows this automatically after @code{AHEAD},
9262: @code{AGAIN}, @code{EXIT} and @code{LEAVE}; in other cases (e.g., after
9263: most @code{THROW}s), you can use the word @code{UNREACHABLE} to tell the
9264: compiler that the control flow never reaches that place. If
9265: @code{UNREACHABLE} is not used where it could, the only consequence is
9266: that the visibility of some locals is more limited than the rule above
9267: says. If @code{UNREACHABLE} is used where it should not (i.e., if you
9268: lie to the compiler), buggy code will be produced.
1.77 anton 9269:
1.5 anton 9270:
1.78 anton 9271: doc-unreachable
1.5 anton 9272:
1.23 crook 9273:
1.78 anton 9274: Another problem with this rule is that at @code{BEGIN}, the compiler
9275: does not know which locals will be visible on the incoming
9276: back-edge. All problems discussed in the following are due to this
9277: ignorance of the compiler (we discuss the problems using @code{BEGIN}
9278: loops as examples; the discussion also applies to @code{?DO} and other
9279: loops). Perhaps the most insidious example is:
1.26 crook 9280: @example
1.78 anton 9281: AHEAD
9282: BEGIN
9283: x
9284: [ 1 CS-ROLL ] THEN
9285: @{ x @}
9286: ...
9287: UNTIL
1.26 crook 9288: @end example
1.23 crook 9289:
1.78 anton 9290: This should be legal according to the visibility rule. The use of
9291: @code{x} can only be reached through the definition; but that appears
9292: textually below the use.
9293:
9294: From this example it is clear that the visibility rules cannot be fully
9295: implemented without major headaches. Our implementation treats common
9296: cases as advertised and the exceptions are treated in a safe way: The
9297: compiler makes a reasonable guess about the locals visible after a
9298: @code{BEGIN}; if it is too pessimistic, the
9299: user will get a spurious error about the local not being defined; if the
9300: compiler is too optimistic, it will notice this later and issue a
9301: warning. In the case above the compiler would complain about @code{x}
9302: being undefined at its use. You can see from the obscure examples in
9303: this section that it takes quite unusual control structures to get the
9304: compiler into trouble, and even then it will often do fine.
1.23 crook 9305:
1.78 anton 9306: If the @code{BEGIN} is reachable from above, the most optimistic guess
9307: is that all locals visible before the @code{BEGIN} will also be
9308: visible after the @code{BEGIN}. This guess is valid for all loops that
9309: are entered only through the @code{BEGIN}, in particular, for normal
9310: @code{BEGIN}...@code{WHILE}...@code{REPEAT} and
9311: @code{BEGIN}...@code{UNTIL} loops and it is implemented in our
9312: compiler. When the branch to the @code{BEGIN} is finally generated by
9313: @code{AGAIN} or @code{UNTIL}, the compiler checks the guess and
9314: warns the user if it was too optimistic:
1.26 crook 9315: @example
1.78 anton 9316: IF
9317: @{ x @}
9318: BEGIN
9319: \ x ?
9320: [ 1 cs-roll ] THEN
9321: ...
9322: UNTIL
1.26 crook 9323: @end example
1.23 crook 9324:
1.78 anton 9325: Here, @code{x} lives only until the @code{BEGIN}, but the compiler
9326: optimistically assumes that it lives until the @code{THEN}. It notices
9327: this difference when it compiles the @code{UNTIL} and issues a
9328: warning. The user can avoid the warning, and make sure that @code{x}
9329: is not used in the wrong area by using explicit scoping:
9330: @example
9331: IF
9332: SCOPE
9333: @{ x @}
9334: ENDSCOPE
9335: BEGIN
9336: [ 1 cs-roll ] THEN
9337: ...
9338: UNTIL
9339: @end example
1.23 crook 9340:
1.78 anton 9341: Since the guess is optimistic, there will be no spurious error messages
9342: about undefined locals.
1.44 crook 9343:
1.78 anton 9344: If the @code{BEGIN} is not reachable from above (e.g., after
9345: @code{AHEAD} or @code{EXIT}), the compiler cannot even make an
9346: optimistic guess, as the locals visible after the @code{BEGIN} may be
9347: defined later. Therefore, the compiler assumes that no locals are
9348: visible after the @code{BEGIN}. However, the user can use
9349: @code{ASSUME-LIVE} to make the compiler assume that the same locals are
9350: visible at the BEGIN as at the point where the top control-flow stack
9351: item was created.
1.23 crook 9352:
1.44 crook 9353:
1.78 anton 9354: doc-assume-live
1.26 crook 9355:
1.23 crook 9356:
1.78 anton 9357: @noindent
9358: E.g.,
9359: @example
9360: @{ x @}
9361: AHEAD
9362: ASSUME-LIVE
9363: BEGIN
9364: x
9365: [ 1 CS-ROLL ] THEN
9366: ...
9367: UNTIL
9368: @end example
1.44 crook 9369:
1.78 anton 9370: Other cases where the locals are defined before the @code{BEGIN} can be
9371: handled by inserting an appropriate @code{CS-ROLL} before the
9372: @code{ASSUME-LIVE} (and changing the control-flow stack manipulation
9373: behind the @code{ASSUME-LIVE}).
1.23 crook 9374:
1.78 anton 9375: Cases where locals are defined after the @code{BEGIN} (but should be
9376: visible immediately after the @code{BEGIN}) can only be handled by
9377: rearranging the loop. E.g., the ``most insidious'' example above can be
9378: arranged into:
9379: @example
9380: BEGIN
9381: @{ x @}
9382: ... 0=
9383: WHILE
9384: x
9385: REPEAT
9386: @end example
1.44 crook 9387:
1.78 anton 9388: @node How long do locals live?, Locals programming style, Where are locals visible by name?, Gforth locals
9389: @subsubsection How long do locals live?
9390: @cindex locals lifetime
9391: @cindex lifetime of locals
1.23 crook 9392:
1.78 anton 9393: The right answer for the lifetime question would be: A local lives at
9394: least as long as it can be accessed. For a value-flavoured local this
9395: means: until the end of its visibility. However, a variable-flavoured
9396: local could be accessed through its address far beyond its visibility
9397: scope. Ultimately, this would mean that such locals would have to be
9398: garbage collected. Since this entails un-Forth-like implementation
9399: complexities, I adopted the same cowardly solution as some other
9400: languages (e.g., C): The local lives only as long as it is visible;
9401: afterwards its address is invalid (and programs that access it
9402: afterwards are erroneous).
1.23 crook 9403:
1.78 anton 9404: @node Locals programming style, Locals implementation, How long do locals live?, Gforth locals
9405: @subsubsection Locals programming style
9406: @cindex locals programming style
9407: @cindex programming style, locals
1.23 crook 9408:
1.78 anton 9409: The freedom to define locals anywhere has the potential to change
9410: programming styles dramatically. In particular, the need to use the
9411: return stack for intermediate storage vanishes. Moreover, all stack
9412: manipulations (except @code{PICK}s and @code{ROLL}s with run-time
9413: determined arguments) can be eliminated: If the stack items are in the
9414: wrong order, just write a locals definition for all of them; then
9415: write the items in the order you want.
1.23 crook 9416:
1.78 anton 9417: This seems a little far-fetched and eliminating stack manipulations is
9418: unlikely to become a conscious programming objective. Still, the number
9419: of stack manipulations will be reduced dramatically if local variables
9420: are used liberally (e.g., compare @code{max} (@pxref{Gforth locals}) with
9421: a traditional implementation of @code{max}).
1.23 crook 9422:
1.78 anton 9423: This shows one potential benefit of locals: making Forth programs more
9424: readable. Of course, this benefit will only be realized if the
9425: programmers continue to honour the principle of factoring instead of
9426: using the added latitude to make the words longer.
1.23 crook 9427:
1.78 anton 9428: @cindex single-assignment style for locals
9429: Using @code{TO} can and should be avoided. Without @code{TO},
9430: every value-flavoured local has only a single assignment and many
9431: advantages of functional languages apply to Forth. I.e., programs are
9432: easier to analyse, to optimize and to read: It is clear from the
9433: definition what the local stands for, it does not turn into something
9434: different later.
1.23 crook 9435:
1.78 anton 9436: E.g., a definition using @code{TO} might look like this:
9437: @example
9438: : strcmp @{ addr1 u1 addr2 u2 -- n @}
9439: u1 u2 min 0
9440: ?do
9441: addr1 c@@ addr2 c@@ -
9442: ?dup-if
9443: unloop exit
9444: then
9445: addr1 char+ TO addr1
9446: addr2 char+ TO addr2
9447: loop
9448: u1 u2 - ;
1.26 crook 9449: @end example
1.78 anton 9450: Here, @code{TO} is used to update @code{addr1} and @code{addr2} at
9451: every loop iteration. @code{strcmp} is a typical example of the
9452: readability problems of using @code{TO}. When you start reading
9453: @code{strcmp}, you think that @code{addr1} refers to the start of the
9454: string. Only near the end of the loop you realize that it is something
9455: else.
1.23 crook 9456:
1.78 anton 9457: This can be avoided by defining two locals at the start of the loop that
9458: are initialized with the right value for the current iteration.
9459: @example
9460: : strcmp @{ addr1 u1 addr2 u2 -- n @}
9461: addr1 addr2
9462: u1 u2 min 0
9463: ?do @{ s1 s2 @}
9464: s1 c@@ s2 c@@ -
9465: ?dup-if
9466: unloop exit
9467: then
9468: s1 char+ s2 char+
9469: loop
9470: 2drop
9471: u1 u2 - ;
9472: @end example
9473: Here it is clear from the start that @code{s1} has a different value
9474: in every loop iteration.
1.23 crook 9475:
1.78 anton 9476: @node Locals implementation, , Locals programming style, Gforth locals
9477: @subsubsection Locals implementation
9478: @cindex locals implementation
9479: @cindex implementation of locals
1.23 crook 9480:
1.78 anton 9481: @cindex locals stack
9482: Gforth uses an extra locals stack. The most compelling reason for
9483: this is that the return stack is not float-aligned; using an extra stack
9484: also eliminates the problems and restrictions of using the return stack
9485: as locals stack. Like the other stacks, the locals stack grows toward
9486: lower addresses. A few primitives allow an efficient implementation:
9487:
9488:
9489: doc-@local#
9490: doc-f@local#
9491: doc-laddr#
9492: doc-lp+!#
9493: doc-lp!
9494: doc->l
9495: doc-f>l
9496:
9497:
9498: In addition to these primitives, some specializations of these
9499: primitives for commonly occurring inline arguments are provided for
9500: efficiency reasons, e.g., @code{@@local0} as specialization of
9501: @code{@@local#} for the inline argument 0. The following compiling words
9502: compile the right specialized version, or the general version, as
9503: appropriate:
1.23 crook 9504:
1.5 anton 9505:
1.107 dvdkhlng 9506: @c doc-compile-@local
9507: @c doc-compile-f@local
1.78 anton 9508: doc-compile-lp+!
1.5 anton 9509:
9510:
1.78 anton 9511: Combinations of conditional branches and @code{lp+!#} like
9512: @code{?branch-lp+!#} (the locals pointer is only changed if the branch
9513: is taken) are provided for efficiency and correctness in loops.
1.5 anton 9514:
1.78 anton 9515: A special area in the dictionary space is reserved for keeping the
9516: local variable names. @code{@{} switches the dictionary pointer to this
9517: area and @code{@}} switches it back and generates the locals
9518: initializing code. @code{W:} etc.@ are normal defining words. This
9519: special area is cleared at the start of every colon definition.
1.5 anton 9520:
1.78 anton 9521: @cindex word list for defining locals
9522: A special feature of Gforth's dictionary is used to implement the
9523: definition of locals without type specifiers: every word list (aka
9524: vocabulary) has its own methods for searching
9525: etc. (@pxref{Word Lists}). For the present purpose we defined a word list
9526: with a special search method: When it is searched for a word, it
9527: actually creates that word using @code{W:}. @code{@{} changes the search
9528: order to first search the word list containing @code{@}}, @code{W:} etc.,
9529: and then the word list for defining locals without type specifiers.
1.5 anton 9530:
1.78 anton 9531: The lifetime rules support a stack discipline within a colon
9532: definition: The lifetime of a local is either nested with other locals
9533: lifetimes or it does not overlap them.
1.23 crook 9534:
1.78 anton 9535: At @code{BEGIN}, @code{IF}, and @code{AHEAD} no code for locals stack
9536: pointer manipulation is generated. Between control structure words
9537: locals definitions can push locals onto the locals stack. @code{AGAIN}
9538: is the simplest of the other three control flow words. It has to
9539: restore the locals stack depth of the corresponding @code{BEGIN}
9540: before branching. The code looks like this:
9541: @format
9542: @code{lp+!#} current-locals-size @minus{} dest-locals-size
9543: @code{branch} <begin>
9544: @end format
1.26 crook 9545:
1.78 anton 9546: @code{UNTIL} is a little more complicated: If it branches back, it
9547: must adjust the stack just like @code{AGAIN}. But if it falls through,
9548: the locals stack must not be changed. The compiler generates the
9549: following code:
9550: @format
9551: @code{?branch-lp+!#} <begin> current-locals-size @minus{} dest-locals-size
9552: @end format
9553: The locals stack pointer is only adjusted if the branch is taken.
1.44 crook 9554:
1.78 anton 9555: @code{THEN} can produce somewhat inefficient code:
9556: @format
9557: @code{lp+!#} current-locals-size @minus{} orig-locals-size
9558: <orig target>:
9559: @code{lp+!#} orig-locals-size @minus{} new-locals-size
9560: @end format
9561: The second @code{lp+!#} adjusts the locals stack pointer from the
9562: level at the @i{orig} point to the level after the @code{THEN}. The
9563: first @code{lp+!#} adjusts the locals stack pointer from the current
9564: level to the level at the orig point, so the complete effect is an
9565: adjustment from the current level to the right level after the
9566: @code{THEN}.
1.26 crook 9567:
1.78 anton 9568: @cindex locals information on the control-flow stack
9569: @cindex control-flow stack items, locals information
9570: In a conventional Forth implementation a dest control-flow stack entry
9571: is just the target address and an orig entry is just the address to be
9572: patched. Our locals implementation adds a word list to every orig or dest
9573: item. It is the list of locals visible (or assumed visible) at the point
9574: described by the entry. Our implementation also adds a tag to identify
9575: the kind of entry, in particular to differentiate between live and dead
9576: (reachable and unreachable) orig entries.
1.26 crook 9577:
1.78 anton 9578: A few unusual operations have to be performed on locals word lists:
1.44 crook 9579:
1.5 anton 9580:
1.78 anton 9581: doc-common-list
9582: doc-sub-list?
9583: doc-list-size
1.52 anton 9584:
9585:
1.78 anton 9586: Several features of our locals word list implementation make these
9587: operations easy to implement: The locals word lists are organised as
9588: linked lists; the tails of these lists are shared, if the lists
9589: contain some of the same locals; and the address of a name is greater
9590: than the address of the names behind it in the list.
1.5 anton 9591:
1.78 anton 9592: Another important implementation detail is the variable
9593: @code{dead-code}. It is used by @code{BEGIN} and @code{THEN} to
9594: determine if they can be reached directly or only through the branch
9595: that they resolve. @code{dead-code} is set by @code{UNREACHABLE},
9596: @code{AHEAD}, @code{EXIT} etc., and cleared at the start of a colon
9597: definition, by @code{BEGIN} and usually by @code{THEN}.
1.5 anton 9598:
1.78 anton 9599: Counted loops are similar to other loops in most respects, but
9600: @code{LEAVE} requires special attention: It performs basically the same
9601: service as @code{AHEAD}, but it does not create a control-flow stack
9602: entry. Therefore the information has to be stored elsewhere;
9603: traditionally, the information was stored in the target fields of the
9604: branches created by the @code{LEAVE}s, by organizing these fields into a
9605: linked list. Unfortunately, this clever trick does not provide enough
9606: space for storing our extended control flow information. Therefore, we
9607: introduce another stack, the leave stack. It contains the control-flow
9608: stack entries for all unresolved @code{LEAVE}s.
1.44 crook 9609:
1.78 anton 9610: Local names are kept until the end of the colon definition, even if
9611: they are no longer visible in any control-flow path. In a few cases
9612: this may lead to increased space needs for the locals name area, but
9613: usually less than reclaiming this space would cost in code size.
1.5 anton 9614:
1.44 crook 9615:
1.78 anton 9616: @node ANS Forth locals, , Gforth locals, Locals
9617: @subsection ANS Forth locals
9618: @cindex locals, ANS Forth style
1.5 anton 9619:
1.78 anton 9620: The ANS Forth locals wordset does not define a syntax for locals, but
9621: words that make it possible to define various syntaxes. One of the
9622: possible syntaxes is a subset of the syntax we used in the Gforth locals
9623: wordset, i.e.:
1.29 crook 9624:
9625: @example
1.78 anton 9626: @{ local1 local2 ... -- comment @}
9627: @end example
9628: @noindent
9629: or
9630: @example
9631: @{ local1 local2 ... @}
1.29 crook 9632: @end example
9633:
1.78 anton 9634: The order of the locals corresponds to the order in a stack comment. The
9635: restrictions are:
1.5 anton 9636:
1.78 anton 9637: @itemize @bullet
9638: @item
9639: Locals can only be cell-sized values (no type specifiers are allowed).
9640: @item
9641: Locals can be defined only outside control structures.
9642: @item
9643: Locals can interfere with explicit usage of the return stack. For the
9644: exact (and long) rules, see the standard. If you don't use return stack
9645: accessing words in a definition using locals, you will be all right. The
9646: purpose of this rule is to make locals implementation on the return
9647: stack easier.
9648: @item
9649: The whole definition must be in one line.
9650: @end itemize
1.5 anton 9651:
1.78 anton 9652: Locals defined in ANS Forth behave like @code{VALUE}s
9653: (@pxref{Values}). I.e., they are initialized from the stack. Using their
9654: name produces their value. Their value can be changed using @code{TO}.
1.77 anton 9655:
1.78 anton 9656: Since the syntax above is supported by Gforth directly, you need not do
9657: anything to use it. If you want to port a program using this syntax to
9658: another ANS Forth system, use @file{compat/anslocal.fs} to implement the
9659: syntax on the other system.
1.5 anton 9660:
1.78 anton 9661: Note that a syntax shown in the standard, section A.13 looks
9662: similar, but is quite different in having the order of locals
9663: reversed. Beware!
1.5 anton 9664:
1.78 anton 9665: The ANS Forth locals wordset itself consists of one word:
1.5 anton 9666:
1.78 anton 9667: doc-(local)
1.5 anton 9668:
1.78 anton 9669: The ANS Forth locals extension wordset defines a syntax using
9670: @code{locals|}, but it is so awful that we strongly recommend not to use
9671: it. We have implemented this syntax to make porting to Gforth easy, but
9672: do not document it here. The problem with this syntax is that the locals
9673: are defined in an order reversed with respect to the standard stack
9674: comment notation, making programs harder to read, and easier to misread
9675: and miswrite. The only merit of this syntax is that it is easy to
9676: implement using the ANS Forth locals wordset.
1.53 anton 9677:
9678:
1.78 anton 9679: @c ----------------------------------------------------------
9680: @node Structures, Object-oriented Forth, Locals, Words
9681: @section Structures
9682: @cindex structures
9683: @cindex records
1.53 anton 9684:
1.78 anton 9685: This section presents the structure package that comes with Gforth. A
9686: version of the package implemented in ANS Forth is available in
9687: @file{compat/struct.fs}. This package was inspired by a posting on
9688: comp.lang.forth in 1989 (unfortunately I don't remember, by whom;
9689: possibly John Hayes). A version of this section has been published in
9690: M. Anton Ertl,
9691: @uref{http://www.complang.tuwien.ac.at/forth/objects/structs.html, Yet
9692: Another Forth Structures Package}, Forth Dimensions 19(3), pages
9693: 13--16. Marcel Hendrix provided helpful comments.
1.53 anton 9694:
1.78 anton 9695: @menu
9696: * Why explicit structure support?::
9697: * Structure Usage::
9698: * Structure Naming Convention::
9699: * Structure Implementation::
9700: * Structure Glossary::
9701: @end menu
1.55 anton 9702:
1.78 anton 9703: @node Why explicit structure support?, Structure Usage, Structures, Structures
9704: @subsection Why explicit structure support?
1.53 anton 9705:
1.78 anton 9706: @cindex address arithmetic for structures
9707: @cindex structures using address arithmetic
9708: If we want to use a structure containing several fields, we could simply
9709: reserve memory for it, and access the fields using address arithmetic
9710: (@pxref{Address arithmetic}). As an example, consider a structure with
9711: the following fields
1.57 anton 9712:
1.78 anton 9713: @table @code
9714: @item a
9715: is a float
9716: @item b
9717: is a cell
9718: @item c
9719: is a float
9720: @end table
1.57 anton 9721:
1.78 anton 9722: Given the (float-aligned) base address of the structure we get the
9723: address of the field
1.52 anton 9724:
1.78 anton 9725: @table @code
9726: @item a
9727: without doing anything further.
9728: @item b
9729: with @code{float+}
9730: @item c
9731: with @code{float+ cell+ faligned}
9732: @end table
1.52 anton 9733:
1.78 anton 9734: It is easy to see that this can become quite tiring.
1.52 anton 9735:
1.78 anton 9736: Moreover, it is not very readable, because seeing a
9737: @code{cell+} tells us neither which kind of structure is
9738: accessed nor what field is accessed; we have to somehow infer the kind
9739: of structure, and then look up in the documentation, which field of
9740: that structure corresponds to that offset.
1.53 anton 9741:
1.78 anton 9742: Finally, this kind of address arithmetic also causes maintenance
9743: troubles: If you add or delete a field somewhere in the middle of the
9744: structure, you have to find and change all computations for the fields
9745: afterwards.
1.52 anton 9746:
1.78 anton 9747: So, instead of using @code{cell+} and friends directly, how
9748: about storing the offsets in constants:
1.52 anton 9749:
1.78 anton 9750: @example
9751: 0 constant a-offset
9752: 0 float+ constant b-offset
9753: 0 float+ cell+ faligned c-offset
9754: @end example
1.64 pazsan 9755:
1.78 anton 9756: Now we can get the address of field @code{x} with @code{x-offset
9757: +}. This is much better in all respects. Of course, you still
9758: have to change all later offset definitions if you add a field. You can
9759: fix this by declaring the offsets in the following way:
1.57 anton 9760:
1.78 anton 9761: @example
9762: 0 constant a-offset
9763: a-offset float+ constant b-offset
9764: b-offset cell+ faligned constant c-offset
9765: @end example
1.57 anton 9766:
1.78 anton 9767: Since we always use the offsets with @code{+}, we could use a defining
9768: word @code{cfield} that includes the @code{+} in the action of the
9769: defined word:
1.64 pazsan 9770:
1.78 anton 9771: @example
9772: : cfield ( n "name" -- )
9773: create ,
9774: does> ( name execution: addr1 -- addr2 )
9775: @@ + ;
1.64 pazsan 9776:
1.78 anton 9777: 0 cfield a
9778: 0 a float+ cfield b
9779: 0 b cell+ faligned cfield c
9780: @end example
1.64 pazsan 9781:
1.78 anton 9782: Instead of @code{x-offset +}, we now simply write @code{x}.
1.64 pazsan 9783:
1.78 anton 9784: The structure field words now can be used quite nicely. However,
9785: their definition is still a bit cumbersome: We have to repeat the
9786: name, the information about size and alignment is distributed before
9787: and after the field definitions etc. The structure package presented
9788: here addresses these problems.
1.64 pazsan 9789:
1.78 anton 9790: @node Structure Usage, Structure Naming Convention, Why explicit structure support?, Structures
9791: @subsection Structure Usage
9792: @cindex structure usage
1.57 anton 9793:
1.78 anton 9794: @cindex @code{field} usage
9795: @cindex @code{struct} usage
9796: @cindex @code{end-struct} usage
9797: You can define a structure for a (data-less) linked list with:
1.57 anton 9798: @example
1.78 anton 9799: struct
9800: cell% field list-next
9801: end-struct list%
1.57 anton 9802: @end example
9803:
1.78 anton 9804: With the address of the list node on the stack, you can compute the
9805: address of the field that contains the address of the next node with
9806: @code{list-next}. E.g., you can determine the length of a list
9807: with:
1.57 anton 9808:
9809: @example
1.78 anton 9810: : list-length ( list -- n )
9811: \ "list" is a pointer to the first element of a linked list
9812: \ "n" is the length of the list
9813: 0 BEGIN ( list1 n1 )
9814: over
9815: WHILE ( list1 n1 )
9816: 1+ swap list-next @@ swap
9817: REPEAT
9818: nip ;
1.57 anton 9819: @end example
9820:
1.78 anton 9821: You can reserve memory for a list node in the dictionary with
9822: @code{list% %allot}, which leaves the address of the list node on the
9823: stack. For the equivalent allocation on the heap you can use @code{list%
9824: %alloc} (or, for an @code{allocate}-like stack effect (i.e., with ior),
9825: use @code{list% %allocate}). You can get the the size of a list
9826: node with @code{list% %size} and its alignment with @code{list%
9827: %alignment}.
9828:
9829: Note that in ANS Forth the body of a @code{create}d word is
9830: @code{aligned} but not necessarily @code{faligned};
9831: therefore, if you do a:
1.57 anton 9832:
9833: @example
1.78 anton 9834: create @emph{name} foo% %allot drop
1.57 anton 9835: @end example
9836:
1.78 anton 9837: @noindent
9838: then the memory alloted for @code{foo%} is guaranteed to start at the
9839: body of @code{@emph{name}} only if @code{foo%} contains only character,
9840: cell and double fields. Therefore, if your structure contains floats,
9841: better use
1.57 anton 9842:
9843: @example
1.78 anton 9844: foo% %allot constant @emph{name}
1.57 anton 9845: @end example
9846:
1.78 anton 9847: @cindex structures containing structures
9848: You can include a structure @code{foo%} as a field of
9849: another structure, like this:
1.65 anton 9850: @example
1.78 anton 9851: struct
9852: ...
9853: foo% field ...
9854: ...
9855: end-struct ...
1.65 anton 9856: @end example
1.52 anton 9857:
1.78 anton 9858: @cindex structure extension
9859: @cindex extended records
9860: Instead of starting with an empty structure, you can extend an
9861: existing structure. E.g., a plain linked list without data, as defined
9862: above, is hardly useful; You can extend it to a linked list of integers,
9863: like this:@footnote{This feature is also known as @emph{extended
9864: records}. It is the main innovation in the Oberon language; in other
9865: words, adding this feature to Modula-2 led Wirth to create a new
9866: language, write a new compiler etc. Adding this feature to Forth just
9867: required a few lines of code.}
1.52 anton 9868:
1.78 anton 9869: @example
9870: list%
9871: cell% field intlist-int
9872: end-struct intlist%
9873: @end example
1.55 anton 9874:
1.78 anton 9875: @code{intlist%} is a structure with two fields:
9876: @code{list-next} and @code{intlist-int}.
1.55 anton 9877:
1.78 anton 9878: @cindex structures containing arrays
9879: You can specify an array type containing @emph{n} elements of
9880: type @code{foo%} like this:
1.55 anton 9881:
9882: @example
1.78 anton 9883: foo% @emph{n} *
1.56 anton 9884: @end example
1.55 anton 9885:
1.78 anton 9886: You can use this array type in any place where you can use a normal
9887: type, e.g., when defining a @code{field}, or with
9888: @code{%allot}.
9889:
9890: @cindex first field optimization
9891: The first field is at the base address of a structure and the word for
9892: this field (e.g., @code{list-next}) actually does not change the address
9893: on the stack. You may be tempted to leave it away in the interest of
9894: run-time and space efficiency. This is not necessary, because the
9895: structure package optimizes this case: If you compile a first-field
9896: words, no code is generated. So, in the interest of readability and
9897: maintainability you should include the word for the field when accessing
9898: the field.
1.52 anton 9899:
9900:
1.78 anton 9901: @node Structure Naming Convention, Structure Implementation, Structure Usage, Structures
9902: @subsection Structure Naming Convention
9903: @cindex structure naming convention
1.52 anton 9904:
1.78 anton 9905: The field names that come to (my) mind are often quite generic, and,
9906: if used, would cause frequent name clashes. E.g., many structures
9907: probably contain a @code{counter} field. The structure names
9908: that come to (my) mind are often also the logical choice for the names
9909: of words that create such a structure.
1.52 anton 9910:
1.78 anton 9911: Therefore, I have adopted the following naming conventions:
1.52 anton 9912:
1.78 anton 9913: @itemize @bullet
9914: @cindex field naming convention
9915: @item
9916: The names of fields are of the form
9917: @code{@emph{struct}-@emph{field}}, where
9918: @code{@emph{struct}} is the basic name of the structure, and
9919: @code{@emph{field}} is the basic name of the field. You can
9920: think of field words as converting the (address of the)
9921: structure into the (address of the) field.
1.52 anton 9922:
1.78 anton 9923: @cindex structure naming convention
9924: @item
9925: The names of structures are of the form
9926: @code{@emph{struct}%}, where
9927: @code{@emph{struct}} is the basic name of the structure.
9928: @end itemize
1.52 anton 9929:
1.78 anton 9930: This naming convention does not work that well for fields of extended
9931: structures; e.g., the integer list structure has a field
9932: @code{intlist-int}, but has @code{list-next}, not
9933: @code{intlist-next}.
1.53 anton 9934:
1.78 anton 9935: @node Structure Implementation, Structure Glossary, Structure Naming Convention, Structures
9936: @subsection Structure Implementation
9937: @cindex structure implementation
9938: @cindex implementation of structures
1.52 anton 9939:
1.78 anton 9940: The central idea in the implementation is to pass the data about the
9941: structure being built on the stack, not in some global
9942: variable. Everything else falls into place naturally once this design
9943: decision is made.
1.53 anton 9944:
1.78 anton 9945: The type description on the stack is of the form @emph{align
9946: size}. Keeping the size on the top-of-stack makes dealing with arrays
9947: very simple.
1.53 anton 9948:
1.78 anton 9949: @code{field} is a defining word that uses @code{Create}
9950: and @code{DOES>}. The body of the field contains the offset
9951: of the field, and the normal @code{DOES>} action is simply:
1.53 anton 9952:
9953: @example
1.78 anton 9954: @@ +
1.53 anton 9955: @end example
9956:
1.78 anton 9957: @noindent
9958: i.e., add the offset to the address, giving the stack effect
9959: @i{addr1 -- addr2} for a field.
9960:
9961: @cindex first field optimization, implementation
9962: This simple structure is slightly complicated by the optimization
9963: for fields with offset 0, which requires a different
9964: @code{DOES>}-part (because we cannot rely on there being
9965: something on the stack if such a field is invoked during
9966: compilation). Therefore, we put the different @code{DOES>}-parts
9967: in separate words, and decide which one to invoke based on the
9968: offset. For a zero offset, the field is basically a noop; it is
9969: immediate, and therefore no code is generated when it is compiled.
1.53 anton 9970:
1.78 anton 9971: @node Structure Glossary, , Structure Implementation, Structures
9972: @subsection Structure Glossary
9973: @cindex structure glossary
1.53 anton 9974:
1.5 anton 9975:
1.78 anton 9976: doc-%align
9977: doc-%alignment
9978: doc-%alloc
9979: doc-%allocate
9980: doc-%allot
9981: doc-cell%
9982: doc-char%
9983: doc-dfloat%
9984: doc-double%
9985: doc-end-struct
9986: doc-field
9987: doc-float%
9988: doc-naligned
9989: doc-sfloat%
9990: doc-%size
9991: doc-struct
1.54 anton 9992:
9993:
1.26 crook 9994: @c -------------------------------------------------------------
1.78 anton 9995: @node Object-oriented Forth, Programming Tools, Structures, Words
9996: @section Object-oriented Forth
9997:
9998: Gforth comes with three packages for object-oriented programming:
9999: @file{objects.fs}, @file{oof.fs}, and @file{mini-oof.fs}; none of them
10000: is preloaded, so you have to @code{include} them before use. The most
10001: important differences between these packages (and others) are discussed
10002: in @ref{Comparison with other object models}. All packages are written
10003: in ANS Forth and can be used with any other ANS Forth.
1.5 anton 10004:
1.78 anton 10005: @menu
10006: * Why object-oriented programming?::
10007: * Object-Oriented Terminology::
10008: * Objects::
10009: * OOF::
10010: * Mini-OOF::
10011: * Comparison with other object models::
10012: @end menu
1.5 anton 10013:
1.78 anton 10014: @c ----------------------------------------------------------------
10015: @node Why object-oriented programming?, Object-Oriented Terminology, Object-oriented Forth, Object-oriented Forth
10016: @subsection Why object-oriented programming?
10017: @cindex object-oriented programming motivation
10018: @cindex motivation for object-oriented programming
1.44 crook 10019:
1.78 anton 10020: Often we have to deal with several data structures (@emph{objects}),
10021: that have to be treated similarly in some respects, but differently in
10022: others. Graphical objects are the textbook example: circles, triangles,
10023: dinosaurs, icons, and others, and we may want to add more during program
10024: development. We want to apply some operations to any graphical object,
10025: e.g., @code{draw} for displaying it on the screen. However, @code{draw}
10026: has to do something different for every kind of object.
10027: @comment TODO add some other operations eg perimeter, area
10028: @comment and tie in to concrete examples later..
1.5 anton 10029:
1.78 anton 10030: We could implement @code{draw} as a big @code{CASE}
10031: control structure that executes the appropriate code depending on the
10032: kind of object to be drawn. This would be not be very elegant, and,
10033: moreover, we would have to change @code{draw} every time we add
10034: a new kind of graphical object (say, a spaceship).
1.44 crook 10035:
1.78 anton 10036: What we would rather do is: When defining spaceships, we would tell
10037: the system: ``Here's how you @code{draw} a spaceship; you figure
10038: out the rest''.
1.5 anton 10039:
1.78 anton 10040: This is the problem that all systems solve that (rightfully) call
10041: themselves object-oriented; the object-oriented packages presented here
10042: solve this problem (and not much else).
10043: @comment TODO ?list properties of oo systems.. oo vs o-based?
1.44 crook 10044:
1.78 anton 10045: @c ------------------------------------------------------------------------
10046: @node Object-Oriented Terminology, Objects, Why object-oriented programming?, Object-oriented Forth
10047: @subsection Object-Oriented Terminology
10048: @cindex object-oriented terminology
10049: @cindex terminology for object-oriented programming
1.5 anton 10050:
1.78 anton 10051: This section is mainly for reference, so you don't have to understand
10052: all of it right away. The terminology is mainly Smalltalk-inspired. In
10053: short:
1.44 crook 10054:
1.78 anton 10055: @table @emph
10056: @cindex class
10057: @item class
10058: a data structure definition with some extras.
1.5 anton 10059:
1.78 anton 10060: @cindex object
10061: @item object
10062: an instance of the data structure described by the class definition.
1.5 anton 10063:
1.78 anton 10064: @cindex instance variables
10065: @item instance variables
10066: fields of the data structure.
1.5 anton 10067:
1.78 anton 10068: @cindex selector
10069: @cindex method selector
10070: @cindex virtual function
10071: @item selector
10072: (or @emph{method selector}) a word (e.g.,
10073: @code{draw}) that performs an operation on a variety of data
10074: structures (classes). A selector describes @emph{what} operation to
10075: perform. In C++ terminology: a (pure) virtual function.
1.5 anton 10076:
1.78 anton 10077: @cindex method
10078: @item method
10079: the concrete definition that performs the operation
10080: described by the selector for a specific class. A method specifies
10081: @emph{how} the operation is performed for a specific class.
1.5 anton 10082:
1.78 anton 10083: @cindex selector invocation
10084: @cindex message send
10085: @cindex invoking a selector
10086: @item selector invocation
10087: a call of a selector. One argument of the call (the TOS (top-of-stack))
10088: is used for determining which method is used. In Smalltalk terminology:
10089: a message (consisting of the selector and the other arguments) is sent
10090: to the object.
1.5 anton 10091:
1.78 anton 10092: @cindex receiving object
10093: @item receiving object
10094: the object used for determining the method executed by a selector
10095: invocation. In the @file{objects.fs} model, it is the object that is on
10096: the TOS when the selector is invoked. (@emph{Receiving} comes from
10097: the Smalltalk @emph{message} terminology.)
1.5 anton 10098:
1.78 anton 10099: @cindex child class
10100: @cindex parent class
10101: @cindex inheritance
10102: @item child class
10103: a class that has (@emph{inherits}) all properties (instance variables,
10104: selectors, methods) from a @emph{parent class}. In Smalltalk
10105: terminology: The subclass inherits from the superclass. In C++
10106: terminology: The derived class inherits from the base class.
1.5 anton 10107:
1.78 anton 10108: @end table
1.5 anton 10109:
1.78 anton 10110: @c If you wonder about the message sending terminology, it comes from
10111: @c a time when each object had it's own task and objects communicated via
10112: @c message passing; eventually the Smalltalk developers realized that
10113: @c they can do most things through simple (indirect) calls. They kept the
10114: @c terminology.
1.5 anton 10115:
1.78 anton 10116: @c --------------------------------------------------------------
10117: @node Objects, OOF, Object-Oriented Terminology, Object-oriented Forth
10118: @subsection The @file{objects.fs} model
10119: @cindex objects
10120: @cindex object-oriented programming
1.26 crook 10121:
1.78 anton 10122: @cindex @file{objects.fs}
10123: @cindex @file{oof.fs}
1.26 crook 10124:
1.78 anton 10125: This section describes the @file{objects.fs} package. This material also
10126: has been published in M. Anton Ertl,
10127: @cite{@uref{http://www.complang.tuwien.ac.at/forth/objects/objects.html,
10128: Yet Another Forth Objects Package}}, Forth Dimensions 19(2), pages
10129: 37--43.
10130: @c McKewan's and Zsoter's packages
1.26 crook 10131:
1.78 anton 10132: This section assumes that you have read @ref{Structures}.
1.5 anton 10133:
1.78 anton 10134: The techniques on which this model is based have been used to implement
10135: the parser generator, Gray, and have also been used in Gforth for
10136: implementing the various flavours of word lists (hashed or not,
10137: case-sensitive or not, special-purpose word lists for locals etc.).
1.5 anton 10138:
10139:
1.26 crook 10140: @menu
1.78 anton 10141: * Properties of the Objects model::
10142: * Basic Objects Usage::
10143: * The Objects base class::
10144: * Creating objects::
10145: * Object-Oriented Programming Style::
10146: * Class Binding::
10147: * Method conveniences::
10148: * Classes and Scoping::
10149: * Dividing classes::
10150: * Object Interfaces::
10151: * Objects Implementation::
10152: * Objects Glossary::
1.26 crook 10153: @end menu
1.5 anton 10154:
1.78 anton 10155: Marcel Hendrix provided helpful comments on this section.
1.5 anton 10156:
1.78 anton 10157: @node Properties of the Objects model, Basic Objects Usage, Objects, Objects
10158: @subsubsection Properties of the @file{objects.fs} model
10159: @cindex @file{objects.fs} properties
1.5 anton 10160:
1.78 anton 10161: @itemize @bullet
10162: @item
10163: It is straightforward to pass objects on the stack. Passing
10164: selectors on the stack is a little less convenient, but possible.
1.44 crook 10165:
1.78 anton 10166: @item
10167: Objects are just data structures in memory, and are referenced by their
10168: address. You can create words for objects with normal defining words
10169: like @code{constant}. Likewise, there is no difference between instance
10170: variables that contain objects and those that contain other data.
1.5 anton 10171:
1.78 anton 10172: @item
10173: Late binding is efficient and easy to use.
1.44 crook 10174:
1.78 anton 10175: @item
10176: It avoids parsing, and thus avoids problems with state-smartness
10177: and reduced extensibility; for convenience there are a few parsing
10178: words, but they have non-parsing counterparts. There are also a few
10179: defining words that parse. This is hard to avoid, because all standard
10180: defining words parse (except @code{:noname}); however, such
10181: words are not as bad as many other parsing words, because they are not
10182: state-smart.
1.5 anton 10183:
1.78 anton 10184: @item
10185: It does not try to incorporate everything. It does a few things and does
10186: them well (IMO). In particular, this model was not designed to support
10187: information hiding (although it has features that may help); you can use
10188: a separate package for achieving this.
1.5 anton 10189:
1.78 anton 10190: @item
10191: It is layered; you don't have to learn and use all features to use this
10192: model. Only a few features are necessary (@pxref{Basic Objects Usage},
10193: @pxref{The Objects base class}, @pxref{Creating objects}.), the others
10194: are optional and independent of each other.
1.5 anton 10195:
1.78 anton 10196: @item
10197: An implementation in ANS Forth is available.
1.5 anton 10198:
1.78 anton 10199: @end itemize
1.5 anton 10200:
1.44 crook 10201:
1.78 anton 10202: @node Basic Objects Usage, The Objects base class, Properties of the Objects model, Objects
10203: @subsubsection Basic @file{objects.fs} Usage
10204: @cindex basic objects usage
10205: @cindex objects, basic usage
1.5 anton 10206:
1.78 anton 10207: You can define a class for graphical objects like this:
1.44 crook 10208:
1.78 anton 10209: @cindex @code{class} usage
10210: @cindex @code{end-class} usage
10211: @cindex @code{selector} usage
1.5 anton 10212: @example
1.78 anton 10213: object class \ "object" is the parent class
10214: selector draw ( x y graphical -- )
10215: end-class graphical
10216: @end example
10217:
10218: This code defines a class @code{graphical} with an
10219: operation @code{draw}. We can perform the operation
10220: @code{draw} on any @code{graphical} object, e.g.:
10221:
10222: @example
10223: 100 100 t-rex draw
1.26 crook 10224: @end example
1.5 anton 10225:
1.78 anton 10226: @noindent
10227: where @code{t-rex} is a word (say, a constant) that produces a
10228: graphical object.
10229:
10230: @comment TODO add a 2nd operation eg perimeter.. and use for
10231: @comment a concrete example
1.5 anton 10232:
1.78 anton 10233: @cindex abstract class
10234: How do we create a graphical object? With the present definitions,
10235: we cannot create a useful graphical object. The class
10236: @code{graphical} describes graphical objects in general, but not
10237: any concrete graphical object type (C++ users would call it an
10238: @emph{abstract class}); e.g., there is no method for the selector
10239: @code{draw} in the class @code{graphical}.
1.5 anton 10240:
1.78 anton 10241: For concrete graphical objects, we define child classes of the
10242: class @code{graphical}, e.g.:
1.5 anton 10243:
1.78 anton 10244: @cindex @code{overrides} usage
10245: @cindex @code{field} usage in class definition
1.26 crook 10246: @example
1.78 anton 10247: graphical class \ "graphical" is the parent class
10248: cell% field circle-radius
1.5 anton 10249:
1.78 anton 10250: :noname ( x y circle -- )
10251: circle-radius @@ draw-circle ;
10252: overrides draw
1.5 anton 10253:
1.78 anton 10254: :noname ( n-radius circle -- )
10255: circle-radius ! ;
10256: overrides construct
1.5 anton 10257:
1.78 anton 10258: end-class circle
10259: @end example
1.44 crook 10260:
1.78 anton 10261: Here we define a class @code{circle} as a child of @code{graphical},
10262: with field @code{circle-radius} (which behaves just like a field
10263: (@pxref{Structures}); it defines (using @code{overrides}) new methods
10264: for the selectors @code{draw} and @code{construct} (@code{construct} is
10265: defined in @code{object}, the parent class of @code{graphical}).
1.5 anton 10266:
1.78 anton 10267: Now we can create a circle on the heap (i.e.,
10268: @code{allocate}d memory) with:
1.44 crook 10269:
1.78 anton 10270: @cindex @code{heap-new} usage
1.5 anton 10271: @example
1.78 anton 10272: 50 circle heap-new constant my-circle
1.5 anton 10273: @end example
10274:
1.78 anton 10275: @noindent
10276: @code{heap-new} invokes @code{construct}, thus
10277: initializing the field @code{circle-radius} with 50. We can draw
10278: this new circle at (100,100) with:
1.5 anton 10279:
10280: @example
1.78 anton 10281: 100 100 my-circle draw
1.5 anton 10282: @end example
10283:
1.78 anton 10284: @cindex selector invocation, restrictions
10285: @cindex class definition, restrictions
10286: Note: You can only invoke a selector if the object on the TOS
10287: (the receiving object) belongs to the class where the selector was
10288: defined or one of its descendents; e.g., you can invoke
10289: @code{draw} only for objects belonging to @code{graphical}
10290: or its descendents (e.g., @code{circle}). Immediately before
10291: @code{end-class}, the search order has to be the same as
10292: immediately after @code{class}.
10293:
10294: @node The Objects base class, Creating objects, Basic Objects Usage, Objects
10295: @subsubsection The @file{object.fs} base class
10296: @cindex @code{object} class
10297:
10298: When you define a class, you have to specify a parent class. So how do
10299: you start defining classes? There is one class available from the start:
10300: @code{object}. It is ancestor for all classes and so is the
10301: only class that has no parent. It has two selectors: @code{construct}
10302: and @code{print}.
10303:
10304: @node Creating objects, Object-Oriented Programming Style, The Objects base class, Objects
10305: @subsubsection Creating objects
10306: @cindex creating objects
10307: @cindex object creation
10308: @cindex object allocation options
10309:
10310: @cindex @code{heap-new} discussion
10311: @cindex @code{dict-new} discussion
10312: @cindex @code{construct} discussion
10313: You can create and initialize an object of a class on the heap with
10314: @code{heap-new} ( ... class -- object ) and in the dictionary
10315: (allocation with @code{allot}) with @code{dict-new} (
10316: ... class -- object ). Both words invoke @code{construct}, which
10317: consumes the stack items indicated by "..." above.
10318:
10319: @cindex @code{init-object} discussion
10320: @cindex @code{class-inst-size} discussion
10321: If you want to allocate memory for an object yourself, you can get its
10322: alignment and size with @code{class-inst-size 2@@} ( class --
10323: align size ). Once you have memory for an object, you can initialize
10324: it with @code{init-object} ( ... class object -- );
10325: @code{construct} does only a part of the necessary work.
10326:
10327: @node Object-Oriented Programming Style, Class Binding, Creating objects, Objects
10328: @subsubsection Object-Oriented Programming Style
10329: @cindex object-oriented programming style
10330: @cindex programming style, object-oriented
1.5 anton 10331:
1.78 anton 10332: This section is not exhaustive.
1.5 anton 10333:
1.78 anton 10334: @cindex stack effects of selectors
10335: @cindex selectors and stack effects
10336: In general, it is a good idea to ensure that all methods for the
10337: same selector have the same stack effect: when you invoke a selector,
10338: you often have no idea which method will be invoked, so, unless all
10339: methods have the same stack effect, you will not know the stack effect
10340: of the selector invocation.
1.5 anton 10341:
1.78 anton 10342: One exception to this rule is methods for the selector
10343: @code{construct}. We know which method is invoked, because we
10344: specify the class to be constructed at the same place. Actually, I
10345: defined @code{construct} as a selector only to give the users a
10346: convenient way to specify initialization. The way it is used, a
10347: mechanism different from selector invocation would be more natural
10348: (but probably would take more code and more space to explain).
1.5 anton 10349:
1.78 anton 10350: @node Class Binding, Method conveniences, Object-Oriented Programming Style, Objects
10351: @subsubsection Class Binding
10352: @cindex class binding
10353: @cindex early binding
1.5 anton 10354:
1.78 anton 10355: @cindex late binding
10356: Normal selector invocations determine the method at run-time depending
10357: on the class of the receiving object. This run-time selection is called
10358: @i{late binding}.
1.5 anton 10359:
1.78 anton 10360: Sometimes it's preferable to invoke a different method. For example,
10361: you might want to use the simple method for @code{print}ing
10362: @code{object}s instead of the possibly long-winded @code{print} method
10363: of the receiver class. You can achieve this by replacing the invocation
10364: of @code{print} with:
1.5 anton 10365:
1.78 anton 10366: @cindex @code{[bind]} usage
1.5 anton 10367: @example
1.78 anton 10368: [bind] object print
1.5 anton 10369: @end example
10370:
1.78 anton 10371: @noindent
10372: in compiled code or:
10373:
10374: @cindex @code{bind} usage
1.5 anton 10375: @example
1.78 anton 10376: bind object print
1.5 anton 10377: @end example
10378:
1.78 anton 10379: @cindex class binding, alternative to
10380: @noindent
10381: in interpreted code. Alternatively, you can define the method with a
10382: name (e.g., @code{print-object}), and then invoke it through the
10383: name. Class binding is just a (often more convenient) way to achieve
10384: the same effect; it avoids name clutter and allows you to invoke
10385: methods directly without naming them first.
1.5 anton 10386:
1.78 anton 10387: @cindex superclass binding
10388: @cindex parent class binding
10389: A frequent use of class binding is this: When we define a method
10390: for a selector, we often want the method to do what the selector does
10391: in the parent class, and a little more. There is a special word for
10392: this purpose: @code{[parent]}; @code{[parent]
10393: @emph{selector}} is equivalent to @code{[bind] @emph{parent
10394: selector}}, where @code{@emph{parent}} is the parent
10395: class of the current class. E.g., a method definition might look like:
1.44 crook 10396:
1.78 anton 10397: @cindex @code{[parent]} usage
10398: @example
10399: :noname
10400: dup [parent] foo \ do parent's foo on the receiving object
10401: ... \ do some more
10402: ; overrides foo
10403: @end example
1.6 pazsan 10404:
1.78 anton 10405: @cindex class binding as optimization
10406: In @cite{Object-oriented programming in ANS Forth} (Forth Dimensions,
10407: March 1997), Andrew McKewan presents class binding as an optimization
10408: technique. I recommend not using it for this purpose unless you are in
10409: an emergency. Late binding is pretty fast with this model anyway, so the
10410: benefit of using class binding is small; the cost of using class binding
10411: where it is not appropriate is reduced maintainability.
1.44 crook 10412:
1.78 anton 10413: While we are at programming style questions: You should bind
10414: selectors only to ancestor classes of the receiving object. E.g., say,
10415: you know that the receiving object is of class @code{foo} or its
10416: descendents; then you should bind only to @code{foo} and its
10417: ancestors.
1.12 anton 10418:
1.78 anton 10419: @node Method conveniences, Classes and Scoping, Class Binding, Objects
10420: @subsubsection Method conveniences
10421: @cindex method conveniences
1.44 crook 10422:
1.78 anton 10423: In a method you usually access the receiving object pretty often. If
10424: you define the method as a plain colon definition (e.g., with
10425: @code{:noname}), you may have to do a lot of stack
10426: gymnastics. To avoid this, you can define the method with @code{m:
10427: ... ;m}. E.g., you could define the method for
10428: @code{draw}ing a @code{circle} with
1.6 pazsan 10429:
1.78 anton 10430: @cindex @code{this} usage
10431: @cindex @code{m:} usage
10432: @cindex @code{;m} usage
10433: @example
10434: m: ( x y circle -- )
10435: ( x y ) this circle-radius @@ draw-circle ;m
10436: @end example
1.6 pazsan 10437:
1.78 anton 10438: @cindex @code{exit} in @code{m: ... ;m}
10439: @cindex @code{exitm} discussion
10440: @cindex @code{catch} in @code{m: ... ;m}
10441: When this method is executed, the receiver object is removed from the
10442: stack; you can access it with @code{this} (admittedly, in this
10443: example the use of @code{m: ... ;m} offers no advantage). Note
10444: that I specify the stack effect for the whole method (i.e. including
10445: the receiver object), not just for the code between @code{m:}
10446: and @code{;m}. You cannot use @code{exit} in
10447: @code{m:...;m}; instead, use
10448: @code{exitm}.@footnote{Moreover, for any word that calls
10449: @code{catch} and was defined before loading
10450: @code{objects.fs}, you have to redefine it like I redefined
10451: @code{catch}: @code{: catch this >r catch r> to-this ;}}
1.12 anton 10452:
1.78 anton 10453: @cindex @code{inst-var} usage
10454: You will frequently use sequences of the form @code{this
10455: @emph{field}} (in the example above: @code{this
10456: circle-radius}). If you use the field only in this way, you can
10457: define it with @code{inst-var} and eliminate the
10458: @code{this} before the field name. E.g., the @code{circle}
10459: class above could also be defined with:
1.6 pazsan 10460:
1.78 anton 10461: @example
10462: graphical class
10463: cell% inst-var radius
1.6 pazsan 10464:
1.78 anton 10465: m: ( x y circle -- )
10466: radius @@ draw-circle ;m
10467: overrides draw
1.6 pazsan 10468:
1.78 anton 10469: m: ( n-radius circle -- )
10470: radius ! ;m
10471: overrides construct
1.6 pazsan 10472:
1.78 anton 10473: end-class circle
10474: @end example
1.6 pazsan 10475:
1.78 anton 10476: @code{radius} can only be used in @code{circle} and its
10477: descendent classes and inside @code{m:...;m}.
1.6 pazsan 10478:
1.78 anton 10479: @cindex @code{inst-value} usage
10480: You can also define fields with @code{inst-value}, which is
10481: to @code{inst-var} what @code{value} is to
10482: @code{variable}. You can change the value of such a field with
10483: @code{[to-inst]}. E.g., we could also define the class
10484: @code{circle} like this:
1.44 crook 10485:
1.78 anton 10486: @example
10487: graphical class
10488: inst-value radius
1.6 pazsan 10489:
1.78 anton 10490: m: ( x y circle -- )
10491: radius draw-circle ;m
10492: overrides draw
1.44 crook 10493:
1.78 anton 10494: m: ( n-radius circle -- )
10495: [to-inst] radius ;m
10496: overrides construct
1.6 pazsan 10497:
1.78 anton 10498: end-class circle
10499: @end example
1.6 pazsan 10500:
1.78 anton 10501: @c !! :m is easy to confuse with m:. Another name would be better.
1.6 pazsan 10502:
1.78 anton 10503: @c Finally, you can define named methods with @code{:m}. One use of this
10504: @c feature is the definition of words that occur only in one class and are
10505: @c not intended to be overridden, but which still need method context
10506: @c (e.g., for accessing @code{inst-var}s). Another use is for methods that
10507: @c would be bound frequently, if defined anonymously.
1.6 pazsan 10508:
10509:
1.78 anton 10510: @node Classes and Scoping, Dividing classes, Method conveniences, Objects
10511: @subsubsection Classes and Scoping
10512: @cindex classes and scoping
10513: @cindex scoping and classes
1.6 pazsan 10514:
1.78 anton 10515: Inheritance is frequent, unlike structure extension. This exacerbates
10516: the problem with the field name convention (@pxref{Structure Naming
10517: Convention}): One always has to remember in which class the field was
10518: originally defined; changing a part of the class structure would require
10519: changes for renaming in otherwise unaffected code.
1.6 pazsan 10520:
1.78 anton 10521: @cindex @code{inst-var} visibility
10522: @cindex @code{inst-value} visibility
10523: To solve this problem, I added a scoping mechanism (which was not in my
10524: original charter): A field defined with @code{inst-var} (or
10525: @code{inst-value}) is visible only in the class where it is defined and in
10526: the descendent classes of this class. Using such fields only makes
10527: sense in @code{m:}-defined methods in these classes anyway.
1.6 pazsan 10528:
1.78 anton 10529: This scoping mechanism allows us to use the unadorned field name,
10530: because name clashes with unrelated words become much less likely.
1.6 pazsan 10531:
1.78 anton 10532: @cindex @code{protected} discussion
10533: @cindex @code{private} discussion
10534: Once we have this mechanism, we can also use it for controlling the
10535: visibility of other words: All words defined after
10536: @code{protected} are visible only in the current class and its
10537: descendents. @code{public} restores the compilation
10538: (i.e. @code{current}) word list that was in effect before. If you
10539: have several @code{protected}s without an intervening
10540: @code{public} or @code{set-current}, @code{public}
10541: will restore the compilation word list in effect before the first of
10542: these @code{protected}s.
1.6 pazsan 10543:
1.78 anton 10544: @node Dividing classes, Object Interfaces, Classes and Scoping, Objects
10545: @subsubsection Dividing classes
10546: @cindex Dividing classes
10547: @cindex @code{methods}...@code{end-methods}
1.6 pazsan 10548:
1.78 anton 10549: You may want to do the definition of methods separate from the
10550: definition of the class, its selectors, fields, and instance variables,
10551: i.e., separate the implementation from the definition. You can do this
10552: in the following way:
1.6 pazsan 10553:
1.78 anton 10554: @example
10555: graphical class
10556: inst-value radius
10557: end-class circle
1.6 pazsan 10558:
1.78 anton 10559: ... \ do some other stuff
1.6 pazsan 10560:
1.78 anton 10561: circle methods \ now we are ready
1.44 crook 10562:
1.78 anton 10563: m: ( x y circle -- )
10564: radius draw-circle ;m
10565: overrides draw
1.6 pazsan 10566:
1.78 anton 10567: m: ( n-radius circle -- )
10568: [to-inst] radius ;m
10569: overrides construct
1.44 crook 10570:
1.78 anton 10571: end-methods
10572: @end example
1.7 pazsan 10573:
1.78 anton 10574: You can use several @code{methods}...@code{end-methods} sections. The
10575: only things you can do to the class in these sections are: defining
10576: methods, and overriding the class's selectors. You must not define new
10577: selectors or fields.
1.7 pazsan 10578:
1.78 anton 10579: Note that you often have to override a selector before using it. In
10580: particular, you usually have to override @code{construct} with a new
10581: method before you can invoke @code{heap-new} and friends. E.g., you
10582: must not create a circle before the @code{overrides construct} sequence
10583: in the example above.
1.7 pazsan 10584:
1.78 anton 10585: @node Object Interfaces, Objects Implementation, Dividing classes, Objects
10586: @subsubsection Object Interfaces
10587: @cindex object interfaces
10588: @cindex interfaces for objects
1.7 pazsan 10589:
1.78 anton 10590: In this model you can only call selectors defined in the class of the
10591: receiving objects or in one of its ancestors. If you call a selector
10592: with a receiving object that is not in one of these classes, the
10593: result is undefined; if you are lucky, the program crashes
10594: immediately.
1.7 pazsan 10595:
1.78 anton 10596: @cindex selectors common to hardly-related classes
10597: Now consider the case when you want to have a selector (or several)
10598: available in two classes: You would have to add the selector to a
10599: common ancestor class, in the worst case to @code{object}. You
10600: may not want to do this, e.g., because someone else is responsible for
10601: this ancestor class.
1.7 pazsan 10602:
1.78 anton 10603: The solution for this problem is interfaces. An interface is a
10604: collection of selectors. If a class implements an interface, the
10605: selectors become available to the class and its descendents. A class
10606: can implement an unlimited number of interfaces. For the problem
10607: discussed above, we would define an interface for the selector(s), and
10608: both classes would implement the interface.
1.7 pazsan 10609:
1.78 anton 10610: As an example, consider an interface @code{storage} for
10611: writing objects to disk and getting them back, and a class
10612: @code{foo} that implements it. The code would look like this:
1.7 pazsan 10613:
1.78 anton 10614: @cindex @code{interface} usage
10615: @cindex @code{end-interface} usage
10616: @cindex @code{implementation} usage
10617: @example
10618: interface
10619: selector write ( file object -- )
10620: selector read1 ( file object -- )
10621: end-interface storage
1.13 pazsan 10622:
1.78 anton 10623: bar class
10624: storage implementation
1.13 pazsan 10625:
1.78 anton 10626: ... overrides write
10627: ... overrides read1
10628: ...
10629: end-class foo
10630: @end example
1.13 pazsan 10631:
1.78 anton 10632: @noindent
10633: (I would add a word @code{read} @i{( file -- object )} that uses
10634: @code{read1} internally, but that's beyond the point illustrated
10635: here.)
1.13 pazsan 10636:
1.78 anton 10637: Note that you cannot use @code{protected} in an interface; and
10638: of course you cannot define fields.
1.13 pazsan 10639:
1.78 anton 10640: In the Neon model, all selectors are available for all classes;
10641: therefore it does not need interfaces. The price you pay in this model
10642: is slower late binding, and therefore, added complexity to avoid late
10643: binding.
1.13 pazsan 10644:
1.78 anton 10645: @node Objects Implementation, Objects Glossary, Object Interfaces, Objects
10646: @subsubsection @file{objects.fs} Implementation
10647: @cindex @file{objects.fs} implementation
1.13 pazsan 10648:
1.78 anton 10649: @cindex @code{object-map} discussion
10650: An object is a piece of memory, like one of the data structures
10651: described with @code{struct...end-struct}. It has a field
10652: @code{object-map} that points to the method map for the object's
10653: class.
1.13 pazsan 10654:
1.78 anton 10655: @cindex method map
10656: @cindex virtual function table
10657: The @emph{method map}@footnote{This is Self terminology; in C++
10658: terminology: virtual function table.} is an array that contains the
10659: execution tokens (@i{xt}s) of the methods for the object's class. Each
10660: selector contains an offset into a method map.
1.13 pazsan 10661:
1.78 anton 10662: @cindex @code{selector} implementation, class
10663: @code{selector} is a defining word that uses
10664: @code{CREATE} and @code{DOES>}. The body of the
10665: selector contains the offset; the @code{DOES>} action for a
10666: class selector is, basically:
1.8 pazsan 10667:
10668: @example
1.78 anton 10669: ( object addr ) @@ over object-map @@ + @@ execute
1.13 pazsan 10670: @end example
10671:
1.78 anton 10672: Since @code{object-map} is the first field of the object, it
10673: does not generate any code. As you can see, calling a selector has a
10674: small, constant cost.
1.26 crook 10675:
1.78 anton 10676: @cindex @code{current-interface} discussion
10677: @cindex class implementation and representation
10678: A class is basically a @code{struct} combined with a method
10679: map. During the class definition the alignment and size of the class
10680: are passed on the stack, just as with @code{struct}s, so
10681: @code{field} can also be used for defining class
10682: fields. However, passing more items on the stack would be
10683: inconvenient, so @code{class} builds a data structure in memory,
10684: which is accessed through the variable
10685: @code{current-interface}. After its definition is complete, the
10686: class is represented on the stack by a pointer (e.g., as parameter for
10687: a child class definition).
1.26 crook 10688:
1.78 anton 10689: A new class starts off with the alignment and size of its parent,
10690: and a copy of the parent's method map. Defining new fields extends the
10691: size and alignment; likewise, defining new selectors extends the
10692: method map. @code{overrides} just stores a new @i{xt} in the method
10693: map at the offset given by the selector.
1.13 pazsan 10694:
1.78 anton 10695: @cindex class binding, implementation
10696: Class binding just gets the @i{xt} at the offset given by the selector
10697: from the class's method map and @code{compile,}s (in the case of
10698: @code{[bind]}) it.
1.13 pazsan 10699:
1.78 anton 10700: @cindex @code{this} implementation
10701: @cindex @code{catch} and @code{this}
10702: @cindex @code{this} and @code{catch}
10703: I implemented @code{this} as a @code{value}. At the
10704: start of an @code{m:...;m} method the old @code{this} is
10705: stored to the return stack and restored at the end; and the object on
10706: the TOS is stored @code{TO this}. This technique has one
10707: disadvantage: If the user does not leave the method via
10708: @code{;m}, but via @code{throw} or @code{exit},
10709: @code{this} is not restored (and @code{exit} may
10710: crash). To deal with the @code{throw} problem, I have redefined
10711: @code{catch} to save and restore @code{this}; the same
10712: should be done with any word that can catch an exception. As for
10713: @code{exit}, I simply forbid it (as a replacement, there is
10714: @code{exitm}).
1.13 pazsan 10715:
1.78 anton 10716: @cindex @code{inst-var} implementation
10717: @code{inst-var} is just the same as @code{field}, with
10718: a different @code{DOES>} action:
1.13 pazsan 10719: @example
1.78 anton 10720: @@ this +
1.8 pazsan 10721: @end example
1.78 anton 10722: Similar for @code{inst-value}.
1.8 pazsan 10723:
1.78 anton 10724: @cindex class scoping implementation
10725: Each class also has a word list that contains the words defined with
10726: @code{inst-var} and @code{inst-value}, and its protected
10727: words. It also has a pointer to its parent. @code{class} pushes
10728: the word lists of the class and all its ancestors onto the search order stack,
10729: and @code{end-class} drops them.
1.20 pazsan 10730:
1.78 anton 10731: @cindex interface implementation
10732: An interface is like a class without fields, parent and protected
10733: words; i.e., it just has a method map. If a class implements an
10734: interface, its method map contains a pointer to the method map of the
10735: interface. The positive offsets in the map are reserved for class
10736: methods, therefore interface map pointers have negative
10737: offsets. Interfaces have offsets that are unique throughout the
10738: system, unlike class selectors, whose offsets are only unique for the
10739: classes where the selector is available (invokable).
1.20 pazsan 10740:
1.78 anton 10741: This structure means that interface selectors have to perform one
10742: indirection more than class selectors to find their method. Their body
10743: contains the interface map pointer offset in the class method map, and
10744: the method offset in the interface method map. The
10745: @code{does>} action for an interface selector is, basically:
1.20 pazsan 10746:
10747: @example
1.78 anton 10748: ( object selector-body )
10749: 2dup selector-interface @@ ( object selector-body object interface-offset )
10750: swap object-map @@ + @@ ( object selector-body map )
10751: swap selector-offset @@ + @@ execute
1.20 pazsan 10752: @end example
10753:
1.78 anton 10754: where @code{object-map} and @code{selector-offset} are
10755: first fields and generate no code.
1.20 pazsan 10756:
1.78 anton 10757: As a concrete example, consider the following code:
1.20 pazsan 10758:
10759: @example
1.78 anton 10760: interface
10761: selector if1sel1
10762: selector if1sel2
10763: end-interface if1
1.20 pazsan 10764:
1.78 anton 10765: object class
10766: if1 implementation
10767: selector cl1sel1
10768: cell% inst-var cl1iv1
1.20 pazsan 10769:
1.78 anton 10770: ' m1 overrides construct
10771: ' m2 overrides if1sel1
10772: ' m3 overrides if1sel2
10773: ' m4 overrides cl1sel2
10774: end-class cl1
1.20 pazsan 10775:
1.78 anton 10776: create obj1 object dict-new drop
10777: create obj2 cl1 dict-new drop
10778: @end example
1.20 pazsan 10779:
1.78 anton 10780: The data structure created by this code (including the data structure
10781: for @code{object}) is shown in the
10782: @uref{objects-implementation.eps,figure}, assuming a cell size of 4.
10783: @comment TODO add this diagram..
1.20 pazsan 10784:
1.78 anton 10785: @node Objects Glossary, , Objects Implementation, Objects
10786: @subsubsection @file{objects.fs} Glossary
10787: @cindex @file{objects.fs} Glossary
1.20 pazsan 10788:
10789:
1.78 anton 10790: doc---objects-bind
10791: doc---objects-<bind>
10792: doc---objects-bind'
10793: doc---objects-[bind]
10794: doc---objects-class
10795: doc---objects-class->map
10796: doc---objects-class-inst-size
10797: doc---objects-class-override!
1.79 anton 10798: doc---objects-class-previous
10799: doc---objects-class>order
1.78 anton 10800: doc---objects-construct
10801: doc---objects-current'
10802: doc---objects-[current]
10803: doc---objects-current-interface
10804: doc---objects-dict-new
10805: doc---objects-end-class
10806: doc---objects-end-class-noname
10807: doc---objects-end-interface
10808: doc---objects-end-interface-noname
10809: doc---objects-end-methods
10810: doc---objects-exitm
10811: doc---objects-heap-new
10812: doc---objects-implementation
10813: doc---objects-init-object
10814: doc---objects-inst-value
10815: doc---objects-inst-var
10816: doc---objects-interface
10817: doc---objects-m:
10818: doc---objects-:m
10819: doc---objects-;m
10820: doc---objects-method
10821: doc---objects-methods
10822: doc---objects-object
10823: doc---objects-overrides
10824: doc---objects-[parent]
10825: doc---objects-print
10826: doc---objects-protected
10827: doc---objects-public
10828: doc---objects-selector
10829: doc---objects-this
10830: doc---objects-<to-inst>
10831: doc---objects-[to-inst]
10832: doc---objects-to-this
10833: doc---objects-xt-new
1.20 pazsan 10834:
10835:
1.78 anton 10836: @c -------------------------------------------------------------
10837: @node OOF, Mini-OOF, Objects, Object-oriented Forth
10838: @subsection The @file{oof.fs} model
10839: @cindex oof
10840: @cindex object-oriented programming
1.20 pazsan 10841:
1.78 anton 10842: @cindex @file{objects.fs}
10843: @cindex @file{oof.fs}
1.20 pazsan 10844:
1.78 anton 10845: This section describes the @file{oof.fs} package.
1.20 pazsan 10846:
1.78 anton 10847: The package described in this section has been used in bigFORTH since 1991, and
10848: used for two large applications: a chromatographic system used to
10849: create new medicaments, and a graphic user interface library (MINOS).
1.20 pazsan 10850:
1.78 anton 10851: You can find a description (in German) of @file{oof.fs} in @cite{Object
10852: oriented bigFORTH} by Bernd Paysan, published in @cite{Vierte Dimension}
10853: 10(2), 1994.
1.20 pazsan 10854:
1.78 anton 10855: @menu
10856: * Properties of the OOF model::
10857: * Basic OOF Usage::
10858: * The OOF base class::
10859: * Class Declaration::
10860: * Class Implementation::
10861: @end menu
1.20 pazsan 10862:
1.78 anton 10863: @node Properties of the OOF model, Basic OOF Usage, OOF, OOF
10864: @subsubsection Properties of the @file{oof.fs} model
10865: @cindex @file{oof.fs} properties
1.20 pazsan 10866:
1.78 anton 10867: @itemize @bullet
10868: @item
10869: This model combines object oriented programming with information
10870: hiding. It helps you writing large application, where scoping is
10871: necessary, because it provides class-oriented scoping.
1.20 pazsan 10872:
1.78 anton 10873: @item
10874: Named objects, object pointers, and object arrays can be created,
10875: selector invocation uses the ``object selector'' syntax. Selector invocation
10876: to objects and/or selectors on the stack is a bit less convenient, but
10877: possible.
1.44 crook 10878:
1.78 anton 10879: @item
10880: Selector invocation and instance variable usage of the active object is
10881: straightforward, since both make use of the active object.
1.44 crook 10882:
1.78 anton 10883: @item
10884: Late binding is efficient and easy to use.
1.20 pazsan 10885:
1.78 anton 10886: @item
10887: State-smart objects parse selectors. However, extensibility is provided
10888: using a (parsing) selector @code{postpone} and a selector @code{'}.
1.20 pazsan 10889:
1.78 anton 10890: @item
10891: An implementation in ANS Forth is available.
1.20 pazsan 10892:
1.78 anton 10893: @end itemize
1.23 crook 10894:
10895:
1.78 anton 10896: @node Basic OOF Usage, The OOF base class, Properties of the OOF model, OOF
10897: @subsubsection Basic @file{oof.fs} Usage
10898: @cindex @file{oof.fs} usage
1.23 crook 10899:
1.78 anton 10900: This section uses the same example as for @code{objects} (@pxref{Basic Objects Usage}).
1.23 crook 10901:
1.78 anton 10902: You can define a class for graphical objects like this:
1.23 crook 10903:
1.78 anton 10904: @cindex @code{class} usage
10905: @cindex @code{class;} usage
10906: @cindex @code{method} usage
10907: @example
10908: object class graphical \ "object" is the parent class
10909: method draw ( x y graphical -- )
10910: class;
10911: @end example
1.23 crook 10912:
1.78 anton 10913: This code defines a class @code{graphical} with an
10914: operation @code{draw}. We can perform the operation
10915: @code{draw} on any @code{graphical} object, e.g.:
1.23 crook 10916:
1.78 anton 10917: @example
10918: 100 100 t-rex draw
10919: @end example
1.23 crook 10920:
1.78 anton 10921: @noindent
10922: where @code{t-rex} is an object or object pointer, created with e.g.
10923: @code{graphical : t-rex}.
1.23 crook 10924:
1.78 anton 10925: @cindex abstract class
10926: How do we create a graphical object? With the present definitions,
10927: we cannot create a useful graphical object. The class
10928: @code{graphical} describes graphical objects in general, but not
10929: any concrete graphical object type (C++ users would call it an
10930: @emph{abstract class}); e.g., there is no method for the selector
10931: @code{draw} in the class @code{graphical}.
1.23 crook 10932:
1.78 anton 10933: For concrete graphical objects, we define child classes of the
10934: class @code{graphical}, e.g.:
1.23 crook 10935:
1.78 anton 10936: @example
10937: graphical class circle \ "graphical" is the parent class
10938: cell var circle-radius
10939: how:
10940: : draw ( x y -- )
10941: circle-radius @@ draw-circle ;
1.23 crook 10942:
1.78 anton 10943: : init ( n-radius -- (
10944: circle-radius ! ;
10945: class;
10946: @end example
1.1 anton 10947:
1.78 anton 10948: Here we define a class @code{circle} as a child of @code{graphical},
10949: with a field @code{circle-radius}; it defines new methods for the
10950: selectors @code{draw} and @code{init} (@code{init} is defined in
10951: @code{object}, the parent class of @code{graphical}).
1.1 anton 10952:
1.78 anton 10953: Now we can create a circle in the dictionary with:
1.1 anton 10954:
1.78 anton 10955: @example
10956: 50 circle : my-circle
10957: @end example
1.21 crook 10958:
1.78 anton 10959: @noindent
10960: @code{:} invokes @code{init}, thus initializing the field
10961: @code{circle-radius} with 50. We can draw this new circle at (100,100)
10962: with:
1.1 anton 10963:
1.78 anton 10964: @example
10965: 100 100 my-circle draw
10966: @end example
1.1 anton 10967:
1.78 anton 10968: @cindex selector invocation, restrictions
10969: @cindex class definition, restrictions
10970: Note: You can only invoke a selector if the receiving object belongs to
10971: the class where the selector was defined or one of its descendents;
10972: e.g., you can invoke @code{draw} only for objects belonging to
10973: @code{graphical} or its descendents (e.g., @code{circle}). The scoping
10974: mechanism will check if you try to invoke a selector that is not
10975: defined in this class hierarchy, so you'll get an error at compilation
10976: time.
1.1 anton 10977:
10978:
1.78 anton 10979: @node The OOF base class, Class Declaration, Basic OOF Usage, OOF
10980: @subsubsection The @file{oof.fs} base class
10981: @cindex @file{oof.fs} base class
1.1 anton 10982:
1.78 anton 10983: When you define a class, you have to specify a parent class. So how do
10984: you start defining classes? There is one class available from the start:
10985: @code{object}. You have to use it as ancestor for all classes. It is the
10986: only class that has no parent. Classes are also objects, except that
10987: they don't have instance variables; class manipulation such as
10988: inheritance or changing definitions of a class is handled through
10989: selectors of the class @code{object}.
1.1 anton 10990:
1.78 anton 10991: @code{object} provides a number of selectors:
1.1 anton 10992:
1.78 anton 10993: @itemize @bullet
10994: @item
10995: @code{class} for subclassing, @code{definitions} to add definitions
10996: later on, and @code{class?} to get type informations (is the class a
10997: subclass of the class passed on the stack?).
1.1 anton 10998:
1.78 anton 10999: doc---object-class
11000: doc---object-definitions
11001: doc---object-class?
1.1 anton 11002:
11003:
1.26 crook 11004: @item
1.78 anton 11005: @code{init} and @code{dispose} as constructor and destructor of the
11006: object. @code{init} is invocated after the object's memory is allocated,
11007: while @code{dispose} also handles deallocation. Thus if you redefine
11008: @code{dispose}, you have to call the parent's dispose with @code{super
11009: dispose}, too.
11010:
11011: doc---object-init
11012: doc---object-dispose
11013:
1.1 anton 11014:
1.26 crook 11015: @item
1.78 anton 11016: @code{new}, @code{new[]}, @code{:}, @code{ptr}, @code{asptr}, and
11017: @code{[]} to create named and unnamed objects and object arrays or
11018: object pointers.
11019:
11020: doc---object-new
11021: doc---object-new[]
11022: doc---object-:
11023: doc---object-ptr
11024: doc---object-asptr
11025: doc---object-[]
11026:
1.1 anton 11027:
1.26 crook 11028: @item
1.78 anton 11029: @code{::} and @code{super} for explicit scoping. You should use explicit
11030: scoping only for super classes or classes with the same set of instance
11031: variables. Explicitly-scoped selectors use early binding.
1.21 crook 11032:
1.78 anton 11033: doc---object-::
11034: doc---object-super
1.21 crook 11035:
11036:
1.26 crook 11037: @item
1.78 anton 11038: @code{self} to get the address of the object
1.21 crook 11039:
1.78 anton 11040: doc---object-self
1.21 crook 11041:
11042:
1.78 anton 11043: @item
11044: @code{bind}, @code{bound}, @code{link}, and @code{is} to assign object
11045: pointers and instance defers.
1.21 crook 11046:
1.78 anton 11047: doc---object-bind
11048: doc---object-bound
11049: doc---object-link
11050: doc---object-is
1.21 crook 11051:
11052:
1.78 anton 11053: @item
11054: @code{'} to obtain selector tokens, @code{send} to invocate selectors
11055: form the stack, and @code{postpone} to generate selector invocation code.
1.21 crook 11056:
1.78 anton 11057: doc---object-'
11058: doc---object-postpone
1.21 crook 11059:
11060:
1.78 anton 11061: @item
11062: @code{with} and @code{endwith} to select the active object from the
11063: stack, and enable its scope. Using @code{with} and @code{endwith}
11064: also allows you to create code using selector @code{postpone} without being
11065: trapped by the state-smart objects.
1.21 crook 11066:
1.78 anton 11067: doc---object-with
11068: doc---object-endwith
1.21 crook 11069:
11070:
1.78 anton 11071: @end itemize
1.21 crook 11072:
1.78 anton 11073: @node Class Declaration, Class Implementation, The OOF base class, OOF
11074: @subsubsection Class Declaration
11075: @cindex class declaration
1.21 crook 11076:
1.78 anton 11077: @itemize @bullet
11078: @item
11079: Instance variables
1.21 crook 11080:
1.78 anton 11081: doc---oof-var
1.21 crook 11082:
11083:
1.78 anton 11084: @item
11085: Object pointers
1.21 crook 11086:
1.78 anton 11087: doc---oof-ptr
11088: doc---oof-asptr
1.21 crook 11089:
11090:
1.78 anton 11091: @item
11092: Instance defers
1.21 crook 11093:
1.78 anton 11094: doc---oof-defer
1.21 crook 11095:
11096:
1.78 anton 11097: @item
11098: Method selectors
1.21 crook 11099:
1.78 anton 11100: doc---oof-early
11101: doc---oof-method
1.21 crook 11102:
11103:
1.78 anton 11104: @item
11105: Class-wide variables
1.21 crook 11106:
1.78 anton 11107: doc---oof-static
1.21 crook 11108:
11109:
1.78 anton 11110: @item
11111: End declaration
1.1 anton 11112:
1.78 anton 11113: doc---oof-how:
11114: doc---oof-class;
1.21 crook 11115:
11116:
1.78 anton 11117: @end itemize
1.21 crook 11118:
1.78 anton 11119: @c -------------------------------------------------------------
11120: @node Class Implementation, , Class Declaration, OOF
11121: @subsubsection Class Implementation
11122: @cindex class implementation
1.21 crook 11123:
1.78 anton 11124: @c -------------------------------------------------------------
11125: @node Mini-OOF, Comparison with other object models, OOF, Object-oriented Forth
11126: @subsection The @file{mini-oof.fs} model
11127: @cindex mini-oof
1.21 crook 11128:
1.78 anton 11129: Gforth's third object oriented Forth package is a 12-liner. It uses a
1.79 anton 11130: mixture of the @file{objects.fs} and the @file{oof.fs} syntax,
1.78 anton 11131: and reduces to the bare minimum of features. This is based on a posting
11132: of Bernd Paysan in comp.lang.forth.
1.21 crook 11133:
1.78 anton 11134: @menu
11135: * Basic Mini-OOF Usage::
11136: * Mini-OOF Example::
11137: * Mini-OOF Implementation::
11138: @end menu
1.21 crook 11139:
1.78 anton 11140: @c -------------------------------------------------------------
11141: @node Basic Mini-OOF Usage, Mini-OOF Example, Mini-OOF, Mini-OOF
11142: @subsubsection Basic @file{mini-oof.fs} Usage
11143: @cindex mini-oof usage
1.21 crook 11144:
1.78 anton 11145: There is a base class (@code{class}, which allocates one cell for the
11146: object pointer) plus seven other words: to define a method, a variable,
11147: a class; to end a class, to resolve binding, to allocate an object and
11148: to compile a class method.
11149: @comment TODO better description of the last one
1.26 crook 11150:
1.21 crook 11151:
1.78 anton 11152: doc-object
11153: doc-method
11154: doc-var
11155: doc-class
11156: doc-end-class
11157: doc-defines
11158: doc-new
11159: doc-::
1.21 crook 11160:
11161:
11162:
1.78 anton 11163: @c -------------------------------------------------------------
11164: @node Mini-OOF Example, Mini-OOF Implementation, Basic Mini-OOF Usage, Mini-OOF
11165: @subsubsection Mini-OOF Example
11166: @cindex mini-oof example
1.1 anton 11167:
1.78 anton 11168: A short example shows how to use this package. This example, in slightly
11169: extended form, is supplied as @file{moof-exm.fs}
11170: @comment TODO could flesh this out with some comments from the Forthwrite article
1.20 pazsan 11171:
1.26 crook 11172: @example
1.78 anton 11173: object class
11174: method init
11175: method draw
11176: end-class graphical
1.26 crook 11177: @end example
1.20 pazsan 11178:
1.78 anton 11179: This code defines a class @code{graphical} with an
11180: operation @code{draw}. We can perform the operation
11181: @code{draw} on any @code{graphical} object, e.g.:
1.20 pazsan 11182:
1.26 crook 11183: @example
1.78 anton 11184: 100 100 t-rex draw
1.26 crook 11185: @end example
1.12 anton 11186:
1.78 anton 11187: where @code{t-rex} is an object or object pointer, created with e.g.
11188: @code{graphical new Constant t-rex}.
1.12 anton 11189:
1.78 anton 11190: For concrete graphical objects, we define child classes of the
11191: class @code{graphical}, e.g.:
1.12 anton 11192:
1.26 crook 11193: @example
11194: graphical class
1.78 anton 11195: cell var circle-radius
11196: end-class circle \ "graphical" is the parent class
1.12 anton 11197:
1.78 anton 11198: :noname ( x y -- )
11199: circle-radius @@ draw-circle ; circle defines draw
11200: :noname ( r -- )
11201: circle-radius ! ; circle defines init
11202: @end example
1.12 anton 11203:
1.78 anton 11204: There is no implicit init method, so we have to define one. The creation
11205: code of the object now has to call init explicitely.
1.21 crook 11206:
1.78 anton 11207: @example
11208: circle new Constant my-circle
11209: 50 my-circle init
1.12 anton 11210: @end example
11211:
1.78 anton 11212: It is also possible to add a function to create named objects with
11213: automatic call of @code{init}, given that all objects have @code{init}
11214: on the same place:
1.38 anton 11215:
1.78 anton 11216: @example
11217: : new: ( .. o "name" -- )
11218: new dup Constant init ;
11219: 80 circle new: large-circle
11220: @end example
1.12 anton 11221:
1.78 anton 11222: We can draw this new circle at (100,100) with:
1.12 anton 11223:
1.78 anton 11224: @example
11225: 100 100 my-circle draw
11226: @end example
1.12 anton 11227:
1.78 anton 11228: @node Mini-OOF Implementation, , Mini-OOF Example, Mini-OOF
11229: @subsubsection @file{mini-oof.fs} Implementation
1.12 anton 11230:
1.78 anton 11231: Object-oriented systems with late binding typically use a
11232: ``vtable''-approach: the first variable in each object is a pointer to a
11233: table, which contains the methods as function pointers. The vtable
11234: may also contain other information.
1.12 anton 11235:
1.79 anton 11236: So first, let's declare selectors:
1.37 anton 11237:
11238: @example
1.79 anton 11239: : method ( m v "name" -- m' v ) Create over , swap cell+ swap
1.78 anton 11240: DOES> ( ... o -- ... ) @@ over @@ + @@ execute ;
11241: @end example
1.37 anton 11242:
1.79 anton 11243: During selector declaration, the number of selectors and instance
11244: variables is on the stack (in address units). @code{method} creates one
11245: selector and increments the selector number. To execute a selector, it
1.78 anton 11246: takes the object, fetches the vtable pointer, adds the offset, and
1.79 anton 11247: executes the method @i{xt} stored there. Each selector takes the object
11248: it is invoked with as top of stack parameter; it passes the parameters
11249: (including the object) unchanged to the appropriate method which should
1.78 anton 11250: consume that object.
1.37 anton 11251:
1.78 anton 11252: Now, we also have to declare instance variables
1.37 anton 11253:
1.78 anton 11254: @example
1.79 anton 11255: : var ( m v size "name" -- m v' ) Create over , +
1.78 anton 11256: DOES> ( o -- addr ) @@ + ;
1.37 anton 11257: @end example
11258:
1.78 anton 11259: As before, a word is created with the current offset. Instance
11260: variables can have different sizes (cells, floats, doubles, chars), so
11261: all we do is take the size and add it to the offset. If your machine
11262: has alignment restrictions, put the proper @code{aligned} or
11263: @code{faligned} before the variable, to adjust the variable
11264: offset. That's why it is on the top of stack.
1.37 anton 11265:
1.78 anton 11266: We need a starting point (the base object) and some syntactic sugar:
1.37 anton 11267:
1.78 anton 11268: @example
11269: Create object 1 cells , 2 cells ,
1.79 anton 11270: : class ( class -- class selectors vars ) dup 2@@ ;
1.78 anton 11271: @end example
1.12 anton 11272:
1.78 anton 11273: For inheritance, the vtable of the parent object has to be
11274: copied when a new, derived class is declared. This gives all the
11275: methods of the parent class, which can be overridden, though.
1.12 anton 11276:
1.78 anton 11277: @example
1.79 anton 11278: : end-class ( class selectors vars "name" -- )
1.78 anton 11279: Create here >r , dup , 2 cells ?DO ['] noop , 1 cells +LOOP
11280: cell+ dup cell+ r> rot @@ 2 cells /string move ;
11281: @end example
1.12 anton 11282:
1.78 anton 11283: The first line creates the vtable, initialized with
11284: @code{noop}s. The second line is the inheritance mechanism, it
11285: copies the xts from the parent vtable.
1.12 anton 11286:
1.78 anton 11287: We still have no way to define new methods, let's do that now:
1.12 anton 11288:
1.26 crook 11289: @example
1.79 anton 11290: : defines ( xt class "name" -- ) ' >body @@ + ! ;
1.78 anton 11291: @end example
1.12 anton 11292:
1.78 anton 11293: To allocate a new object, we need a word, too:
1.12 anton 11294:
1.78 anton 11295: @example
11296: : new ( class -- o ) here over @@ allot swap over ! ;
1.12 anton 11297: @end example
11298:
1.78 anton 11299: Sometimes derived classes want to access the method of the
11300: parent object. There are two ways to achieve this with Mini-OOF:
11301: first, you could use named words, and second, you could look up the
11302: vtable of the parent object.
1.12 anton 11303:
1.78 anton 11304: @example
11305: : :: ( class "name" -- ) ' >body @@ + @@ compile, ;
11306: @end example
1.12 anton 11307:
11308:
1.78 anton 11309: Nothing can be more confusing than a good example, so here is
11310: one. First let's declare a text object (called
11311: @code{button}), that stores text and position:
1.12 anton 11312:
1.78 anton 11313: @example
11314: object class
11315: cell var text
11316: cell var len
11317: cell var x
11318: cell var y
11319: method init
11320: method draw
11321: end-class button
11322: @end example
1.12 anton 11323:
1.78 anton 11324: @noindent
11325: Now, implement the two methods, @code{draw} and @code{init}:
1.21 crook 11326:
1.26 crook 11327: @example
1.78 anton 11328: :noname ( o -- )
11329: >r r@@ x @@ r@@ y @@ at-xy r@@ text @@ r> len @@ type ;
11330: button defines draw
11331: :noname ( addr u o -- )
11332: >r 0 r@@ x ! 0 r@@ y ! r@@ len ! r> text ! ;
11333: button defines init
1.26 crook 11334: @end example
1.12 anton 11335:
1.78 anton 11336: @noindent
11337: To demonstrate inheritance, we define a class @code{bold-button}, with no
1.79 anton 11338: new data and no new selectors:
1.78 anton 11339:
11340: @example
11341: button class
11342: end-class bold-button
1.12 anton 11343:
1.78 anton 11344: : bold 27 emit ." [1m" ;
11345: : normal 27 emit ." [0m" ;
11346: @end example
1.1 anton 11347:
1.78 anton 11348: @noindent
11349: The class @code{bold-button} has a different draw method to
11350: @code{button}, but the new method is defined in terms of the draw method
11351: for @code{button}:
1.20 pazsan 11352:
1.78 anton 11353: @example
11354: :noname bold [ button :: draw ] normal ; bold-button defines draw
11355: @end example
1.21 crook 11356:
1.78 anton 11357: @noindent
1.79 anton 11358: Finally, create two objects and apply selectors:
1.21 crook 11359:
1.26 crook 11360: @example
1.78 anton 11361: button new Constant foo
11362: s" thin foo" foo init
11363: page
11364: foo draw
11365: bold-button new Constant bar
11366: s" fat bar" bar init
11367: 1 bar y !
11368: bar draw
1.26 crook 11369: @end example
1.21 crook 11370:
11371:
1.78 anton 11372: @node Comparison with other object models, , Mini-OOF, Object-oriented Forth
11373: @subsection Comparison with other object models
11374: @cindex comparison of object models
11375: @cindex object models, comparison
11376:
11377: Many object-oriented Forth extensions have been proposed (@cite{A survey
11378: of object-oriented Forths} (SIGPLAN Notices, April 1996) by Bradford
11379: J. Rodriguez and W. F. S. Poehlman lists 17). This section discusses the
11380: relation of the object models described here to two well-known and two
11381: closely-related (by the use of method maps) models. Andras Zsoter
11382: helped us with this section.
11383:
11384: @cindex Neon model
11385: The most popular model currently seems to be the Neon model (see
11386: @cite{Object-oriented programming in ANS Forth} (Forth Dimensions, March
11387: 1997) by Andrew McKewan) but this model has a number of limitations
11388: @footnote{A longer version of this critique can be
11389: found in @cite{On Standardizing Object-Oriented Forth Extensions} (Forth
11390: Dimensions, May 1997) by Anton Ertl.}:
11391:
11392: @itemize @bullet
11393: @item
11394: It uses a @code{@emph{selector object}} syntax, which makes it unnatural
11395: to pass objects on the stack.
1.21 crook 11396:
1.78 anton 11397: @item
11398: It requires that the selector parses the input stream (at
1.79 anton 11399: compile time); this leads to reduced extensibility and to bugs that are
1.78 anton 11400: hard to find.
1.21 crook 11401:
1.78 anton 11402: @item
1.79 anton 11403: It allows using every selector on every object; this eliminates the
11404: need for interfaces, but makes it harder to create efficient
11405: implementations.
1.78 anton 11406: @end itemize
1.21 crook 11407:
1.78 anton 11408: @cindex Pountain's object-oriented model
11409: Another well-known publication is @cite{Object-Oriented Forth} (Academic
11410: Press, London, 1987) by Dick Pountain. However, it is not really about
11411: object-oriented programming, because it hardly deals with late
11412: binding. Instead, it focuses on features like information hiding and
11413: overloading that are characteristic of modular languages like Ada (83).
1.26 crook 11414:
1.78 anton 11415: @cindex Zsoter's object-oriented model
1.79 anton 11416: In @uref{http://www.forth.org/oopf.html, Does late binding have to be
11417: slow?} (Forth Dimensions 18(1) 1996, pages 31-35) Andras Zsoter
11418: describes a model that makes heavy use of an active object (like
11419: @code{this} in @file{objects.fs}): The active object is not only used
11420: for accessing all fields, but also specifies the receiving object of
11421: every selector invocation; you have to change the active object
11422: explicitly with @code{@{ ... @}}, whereas in @file{objects.fs} it
11423: changes more or less implicitly at @code{m: ... ;m}. Such a change at
11424: the method entry point is unnecessary with Zsoter's model, because the
11425: receiving object is the active object already. On the other hand, the
11426: explicit change is absolutely necessary in that model, because otherwise
11427: no one could ever change the active object. An ANS Forth implementation
11428: of this model is available through
11429: @uref{http://www.forth.org/oopf.html}.
1.21 crook 11430:
1.78 anton 11431: @cindex @file{oof.fs}, differences to other models
11432: The @file{oof.fs} model combines information hiding and overloading
11433: resolution (by keeping names in various word lists) with object-oriented
11434: programming. It sets the active object implicitly on method entry, but
11435: also allows explicit changing (with @code{>o...o>} or with
11436: @code{with...endwith}). It uses parsing and state-smart objects and
11437: classes for resolving overloading and for early binding: the object or
11438: class parses the selector and determines the method from this. If the
11439: selector is not parsed by an object or class, it performs a call to the
11440: selector for the active object (late binding), like Zsoter's model.
11441: Fields are always accessed through the active object. The big
11442: disadvantage of this model is the parsing and the state-smartness, which
11443: reduces extensibility and increases the opportunities for subtle bugs;
11444: essentially, you are only safe if you never tick or @code{postpone} an
11445: object or class (Bernd disagrees, but I (Anton) am not convinced).
1.21 crook 11446:
1.78 anton 11447: @cindex @file{mini-oof.fs}, differences to other models
11448: The @file{mini-oof.fs} model is quite similar to a very stripped-down
11449: version of the @file{objects.fs} model, but syntactically it is a
11450: mixture of the @file{objects.fs} and @file{oof.fs} models.
1.21 crook 11451:
11452:
1.78 anton 11453: @c -------------------------------------------------------------
11454: @node Programming Tools, Assembler and Code Words, Object-oriented Forth, Words
11455: @section Programming Tools
11456: @cindex programming tools
1.21 crook 11457:
1.78 anton 11458: @c !! move this and assembler down below OO stuff.
1.21 crook 11459:
1.78 anton 11460: @menu
11461: * Examining::
11462: * Forgetting words::
11463: * Debugging:: Simple and quick.
11464: * Assertions:: Making your programs self-checking.
11465: * Singlestep Debugger:: Executing your program word by word.
11466: @end menu
1.21 crook 11467:
1.78 anton 11468: @node Examining, Forgetting words, Programming Tools, Programming Tools
11469: @subsection Examining data and code
11470: @cindex examining data and code
11471: @cindex data examination
11472: @cindex code examination
1.44 crook 11473:
1.78 anton 11474: The following words inspect the stack non-destructively:
1.21 crook 11475:
1.78 anton 11476: doc-.s
11477: doc-f.s
1.44 crook 11478:
1.78 anton 11479: There is a word @code{.r} but it does @i{not} display the return stack!
11480: It is used for formatted numeric output (@pxref{Simple numeric output}).
1.21 crook 11481:
1.78 anton 11482: doc-depth
11483: doc-fdepth
11484: doc-clearstack
1.21 crook 11485:
1.78 anton 11486: The following words inspect memory.
1.21 crook 11487:
1.78 anton 11488: doc-?
11489: doc-dump
1.21 crook 11490:
1.78 anton 11491: And finally, @code{see} allows to inspect code:
1.21 crook 11492:
1.78 anton 11493: doc-see
11494: doc-xt-see
1.21 crook 11495:
1.78 anton 11496: @node Forgetting words, Debugging, Examining, Programming Tools
11497: @subsection Forgetting words
11498: @cindex words, forgetting
11499: @cindex forgeting words
1.21 crook 11500:
1.78 anton 11501: @c anton: other, maybe better places for this subsection: Defining Words;
11502: @c Dictionary allocation. At least a reference should be there.
1.21 crook 11503:
1.78 anton 11504: Forth allows you to forget words (and everything that was alloted in the
11505: dictonary after them) in a LIFO manner.
1.21 crook 11506:
1.78 anton 11507: doc-marker
1.21 crook 11508:
1.78 anton 11509: The most common use of this feature is during progam development: when
11510: you change a source file, forget all the words it defined and load it
11511: again (since you also forget everything defined after the source file
11512: was loaded, you have to reload that, too). Note that effects like
11513: storing to variables and destroyed system words are not undone when you
11514: forget words. With a system like Gforth, that is fast enough at
11515: starting up and compiling, I find it more convenient to exit and restart
11516: Gforth, as this gives me a clean slate.
1.21 crook 11517:
1.78 anton 11518: Here's an example of using @code{marker} at the start of a source file
11519: that you are debugging; it ensures that you only ever have one copy of
11520: the file's definitions compiled at any time:
1.21 crook 11521:
1.78 anton 11522: @example
11523: [IFDEF] my-code
11524: my-code
11525: [ENDIF]
1.26 crook 11526:
1.78 anton 11527: marker my-code
11528: init-included-files
1.21 crook 11529:
1.78 anton 11530: \ .. definitions start here
11531: \ .
11532: \ .
11533: \ end
11534: @end example
1.21 crook 11535:
1.26 crook 11536:
1.78 anton 11537: @node Debugging, Assertions, Forgetting words, Programming Tools
11538: @subsection Debugging
11539: @cindex debugging
1.21 crook 11540:
1.78 anton 11541: Languages with a slow edit/compile/link/test development loop tend to
11542: require sophisticated tracing/stepping debuggers to facilate debugging.
1.21 crook 11543:
1.78 anton 11544: A much better (faster) way in fast-compiling languages is to add
11545: printing code at well-selected places, let the program run, look at
11546: the output, see where things went wrong, add more printing code, etc.,
11547: until the bug is found.
1.21 crook 11548:
1.78 anton 11549: The simple debugging aids provided in @file{debugs.fs}
11550: are meant to support this style of debugging.
1.21 crook 11551:
1.78 anton 11552: The word @code{~~} prints debugging information (by default the source
11553: location and the stack contents). It is easy to insert. If you use Emacs
11554: it is also easy to remove (@kbd{C-x ~} in the Emacs Forth mode to
11555: query-replace them with nothing). The deferred words
1.101 anton 11556: @code{printdebugdata} and @code{.debugline} control the output of
1.78 anton 11557: @code{~~}. The default source location output format works well with
11558: Emacs' compilation mode, so you can step through the program at the
11559: source level using @kbd{C-x `} (the advantage over a stepping debugger
11560: is that you can step in any direction and you know where the crash has
11561: happened or where the strange data has occurred).
1.21 crook 11562:
1.78 anton 11563: doc-~~
11564: doc-printdebugdata
1.101 anton 11565: doc-.debugline
1.21 crook 11566:
1.106 anton 11567: @cindex filenames in @code{~~} output
11568: @code{~~} (and assertions) will usually print the wrong file name if a
11569: marker is executed in the same file after their occurance. They will
11570: print @samp{*somewhere*} as file name if a marker is executed in the
11571: same file before their occurance.
11572:
11573:
1.78 anton 11574: @node Assertions, Singlestep Debugger, Debugging, Programming Tools
11575: @subsection Assertions
11576: @cindex assertions
1.21 crook 11577:
1.78 anton 11578: It is a good idea to make your programs self-checking, especially if you
11579: make an assumption that may become invalid during maintenance (for
11580: example, that a certain field of a data structure is never zero). Gforth
11581: supports @dfn{assertions} for this purpose. They are used like this:
1.21 crook 11582:
11583: @example
1.78 anton 11584: assert( @i{flag} )
1.26 crook 11585: @end example
11586:
1.78 anton 11587: The code between @code{assert(} and @code{)} should compute a flag, that
11588: should be true if everything is alright and false otherwise. It should
11589: not change anything else on the stack. The overall stack effect of the
11590: assertion is @code{( -- )}. E.g.
1.21 crook 11591:
1.26 crook 11592: @example
1.78 anton 11593: assert( 1 1 + 2 = ) \ what we learn in school
11594: assert( dup 0<> ) \ assert that the top of stack is not zero
11595: assert( false ) \ this code should not be reached
1.21 crook 11596: @end example
11597:
1.78 anton 11598: The need for assertions is different at different times. During
11599: debugging, we want more checking, in production we sometimes care more
11600: for speed. Therefore, assertions can be turned off, i.e., the assertion
11601: becomes a comment. Depending on the importance of an assertion and the
11602: time it takes to check it, you may want to turn off some assertions and
11603: keep others turned on. Gforth provides several levels of assertions for
11604: this purpose:
11605:
11606:
11607: doc-assert0(
11608: doc-assert1(
11609: doc-assert2(
11610: doc-assert3(
11611: doc-assert(
11612: doc-)
1.21 crook 11613:
11614:
1.78 anton 11615: The variable @code{assert-level} specifies the highest assertions that
11616: are turned on. I.e., at the default @code{assert-level} of one,
11617: @code{assert0(} and @code{assert1(} assertions perform checking, while
11618: @code{assert2(} and @code{assert3(} assertions are treated as comments.
1.26 crook 11619:
1.78 anton 11620: The value of @code{assert-level} is evaluated at compile-time, not at
11621: run-time. Therefore you cannot turn assertions on or off at run-time;
11622: you have to set the @code{assert-level} appropriately before compiling a
11623: piece of code. You can compile different pieces of code at different
11624: @code{assert-level}s (e.g., a trusted library at level 1 and
11625: newly-written code at level 3).
1.26 crook 11626:
11627:
1.78 anton 11628: doc-assert-level
1.26 crook 11629:
11630:
1.78 anton 11631: If an assertion fails, a message compatible with Emacs' compilation mode
11632: is produced and the execution is aborted (currently with @code{ABORT"}.
11633: If there is interest, we will introduce a special throw code. But if you
11634: intend to @code{catch} a specific condition, using @code{throw} is
11635: probably more appropriate than an assertion).
1.106 anton 11636:
11637: @cindex filenames in assertion output
11638: Assertions (and @code{~~}) will usually print the wrong file name if a
11639: marker is executed in the same file after their occurance. They will
11640: print @samp{*somewhere*} as file name if a marker is executed in the
11641: same file before their occurance.
1.44 crook 11642:
1.78 anton 11643: Definitions in ANS Forth for these assertion words are provided
11644: in @file{compat/assert.fs}.
1.26 crook 11645:
1.44 crook 11646:
1.78 anton 11647: @node Singlestep Debugger, , Assertions, Programming Tools
11648: @subsection Singlestep Debugger
11649: @cindex singlestep Debugger
11650: @cindex debugging Singlestep
1.44 crook 11651:
1.78 anton 11652: When you create a new word there's often the need to check whether it
11653: behaves correctly or not. You can do this by typing @code{dbg
11654: badword}. A debug session might look like this:
1.26 crook 11655:
1.78 anton 11656: @example
11657: : badword 0 DO i . LOOP ; ok
11658: 2 dbg badword
11659: : badword
11660: Scanning code...
1.44 crook 11661:
1.78 anton 11662: Nesting debugger ready!
1.44 crook 11663:
1.78 anton 11664: 400D4738 8049BC4 0 -> [ 2 ] 00002 00000
11665: 400D4740 8049F68 DO -> [ 0 ]
11666: 400D4744 804A0C8 i -> [ 1 ] 00000
11667: 400D4748 400C5E60 . -> 0 [ 0 ]
11668: 400D474C 8049D0C LOOP -> [ 0 ]
11669: 400D4744 804A0C8 i -> [ 1 ] 00001
11670: 400D4748 400C5E60 . -> 1 [ 0 ]
11671: 400D474C 8049D0C LOOP -> [ 0 ]
11672: 400D4758 804B384 ; -> ok
11673: @end example
1.21 crook 11674:
1.78 anton 11675: Each line displayed is one step. You always have to hit return to
11676: execute the next word that is displayed. If you don't want to execute
11677: the next word in a whole, you have to type @kbd{n} for @code{nest}. Here is
11678: an overview what keys are available:
1.44 crook 11679:
1.78 anton 11680: @table @i
1.44 crook 11681:
1.78 anton 11682: @item @key{RET}
11683: Next; Execute the next word.
1.21 crook 11684:
1.78 anton 11685: @item n
11686: Nest; Single step through next word.
1.44 crook 11687:
1.78 anton 11688: @item u
11689: Unnest; Stop debugging and execute rest of word. If we got to this word
11690: with nest, continue debugging with the calling word.
1.44 crook 11691:
1.78 anton 11692: @item d
11693: Done; Stop debugging and execute rest.
1.21 crook 11694:
1.78 anton 11695: @item s
11696: Stop; Abort immediately.
1.44 crook 11697:
1.78 anton 11698: @end table
1.44 crook 11699:
1.78 anton 11700: Debugging large application with this mechanism is very difficult, because
11701: you have to nest very deeply into the program before the interesting part
11702: begins. This takes a lot of time.
1.26 crook 11703:
1.78 anton 11704: To do it more directly put a @code{BREAK:} command into your source code.
11705: When program execution reaches @code{BREAK:} the single step debugger is
11706: invoked and you have all the features described above.
1.44 crook 11707:
1.78 anton 11708: If you have more than one part to debug it is useful to know where the
11709: program has stopped at the moment. You can do this by the
11710: @code{BREAK" string"} command. This behaves like @code{BREAK:} except that
11711: string is typed out when the ``breakpoint'' is reached.
1.44 crook 11712:
1.26 crook 11713:
1.78 anton 11714: doc-dbg
11715: doc-break:
11716: doc-break"
1.44 crook 11717:
11718:
1.26 crook 11719:
1.78 anton 11720: @c -------------------------------------------------------------
11721: @node Assembler and Code Words, Threading Words, Programming Tools, Words
11722: @section Assembler and Code Words
11723: @cindex assembler
11724: @cindex code words
1.44 crook 11725:
1.78 anton 11726: @menu
11727: * Code and ;code::
11728: * Common Assembler:: Assembler Syntax
11729: * Common Disassembler::
11730: * 386 Assembler:: Deviations and special cases
11731: * Alpha Assembler:: Deviations and special cases
11732: * MIPS assembler:: Deviations and special cases
11733: * Other assemblers:: How to write them
11734: @end menu
1.21 crook 11735:
1.78 anton 11736: @node Code and ;code, Common Assembler, Assembler and Code Words, Assembler and Code Words
11737: @subsection @code{Code} and @code{;code}
1.26 crook 11738:
1.78 anton 11739: Gforth provides some words for defining primitives (words written in
11740: machine code), and for defining the machine-code equivalent of
11741: @code{DOES>}-based defining words. However, the machine-independent
11742: nature of Gforth poses a few problems: First of all, Gforth runs on
11743: several architectures, so it can provide no standard assembler. What's
11744: worse is that the register allocation not only depends on the processor,
11745: but also on the @code{gcc} version and options used.
1.44 crook 11746:
1.78 anton 11747: The words that Gforth offers encapsulate some system dependences (e.g.,
11748: the header structure), so a system-independent assembler may be used in
11749: Gforth. If you do not have an assembler, you can compile machine code
11750: directly with @code{,} and @code{c,}@footnote{This isn't portable,
11751: because these words emit stuff in @i{data} space; it works because
11752: Gforth has unified code/data spaces. Assembler isn't likely to be
11753: portable anyway.}.
1.21 crook 11754:
1.44 crook 11755:
1.78 anton 11756: doc-assembler
11757: doc-init-asm
11758: doc-code
11759: doc-end-code
11760: doc-;code
11761: doc-flush-icache
1.44 crook 11762:
1.21 crook 11763:
1.78 anton 11764: If @code{flush-icache} does not work correctly, @code{code} words
11765: etc. will not work (reliably), either.
1.44 crook 11766:
1.78 anton 11767: The typical usage of these @code{code} words can be shown most easily by
11768: analogy to the equivalent high-level defining words:
1.44 crook 11769:
1.78 anton 11770: @example
11771: : foo code foo
11772: <high-level Forth words> <assembler>
11773: ; end-code
11774:
11775: : bar : bar
11776: <high-level Forth words> <high-level Forth words>
11777: CREATE CREATE
11778: <high-level Forth words> <high-level Forth words>
11779: DOES> ;code
11780: <high-level Forth words> <assembler>
11781: ; end-code
11782: @end example
1.21 crook 11783:
1.78 anton 11784: @c anton: the following stuff is also in "Common Assembler", in less detail.
1.44 crook 11785:
1.78 anton 11786: @cindex registers of the inner interpreter
11787: In the assembly code you will want to refer to the inner interpreter's
11788: registers (e.g., the data stack pointer) and you may want to use other
11789: registers for temporary storage. Unfortunately, the register allocation
11790: is installation-dependent.
1.44 crook 11791:
1.78 anton 11792: In particular, @code{ip} (Forth instruction pointer) and @code{rp}
1.100 anton 11793: (return stack pointer) may be in different places in @code{gforth} and
11794: @code{gforth-fast}, or different installations. This means that you
11795: cannot write a @code{NEXT} routine that works reliably on both versions
11796: or different installations; so for doing @code{NEXT}, I recommend
11797: jumping to @code{' noop >code-address}, which contains nothing but a
11798: @code{NEXT}.
1.21 crook 11799:
1.78 anton 11800: For general accesses to the inner interpreter's registers, the easiest
11801: solution is to use explicit register declarations (@pxref{Explicit Reg
11802: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) for
11803: all of the inner interpreter's registers: You have to compile Gforth
11804: with @code{-DFORCE_REG} (configure option @code{--enable-force-reg}) and
11805: the appropriate declarations must be present in the @code{machine.h}
11806: file (see @code{mips.h} for an example; you can find a full list of all
11807: declarable register symbols with @code{grep register engine.c}). If you
11808: give explicit registers to all variables that are declared at the
11809: beginning of @code{engine()}, you should be able to use the other
11810: caller-saved registers for temporary storage. Alternatively, you can use
11811: the @code{gcc} option @code{-ffixed-REG} (@pxref{Code Gen Options, ,
11812: Options for Code Generation Conventions, gcc.info, GNU C Manual}) to
11813: reserve a register (however, this restriction on register allocation may
11814: slow Gforth significantly).
1.44 crook 11815:
1.78 anton 11816: If this solution is not viable (e.g., because @code{gcc} does not allow
11817: you to explicitly declare all the registers you need), you have to find
11818: out by looking at the code where the inner interpreter's registers
11819: reside and which registers can be used for temporary storage. You can
11820: get an assembly listing of the engine's code with @code{make engine.s}.
1.44 crook 11821:
1.78 anton 11822: In any case, it is good practice to abstract your assembly code from the
11823: actual register allocation. E.g., if the data stack pointer resides in
11824: register @code{$17}, create an alias for this register called @code{sp},
11825: and use that in your assembly code.
1.21 crook 11826:
1.78 anton 11827: @cindex code words, portable
11828: Another option for implementing normal and defining words efficiently
11829: is to add the desired functionality to the source of Gforth. For normal
11830: words you just have to edit @file{primitives} (@pxref{Automatic
11831: Generation}). Defining words (equivalent to @code{;CODE} words, for fast
11832: defined words) may require changes in @file{engine.c}, @file{kernel.fs},
11833: @file{prims2x.fs}, and possibly @file{cross.fs}.
1.44 crook 11834:
1.78 anton 11835: @node Common Assembler, Common Disassembler, Code and ;code, Assembler and Code Words
11836: @subsection Common Assembler
1.44 crook 11837:
1.78 anton 11838: The assemblers in Gforth generally use a postfix syntax, i.e., the
11839: instruction name follows the operands.
1.21 crook 11840:
1.78 anton 11841: The operands are passed in the usual order (the same that is used in the
11842: manual of the architecture). Since they all are Forth words, they have
11843: to be separated by spaces; you can also use Forth words to compute the
11844: operands.
1.44 crook 11845:
1.78 anton 11846: The instruction names usually end with a @code{,}. This makes it easier
11847: to visually separate instructions if you put several of them on one
11848: line; it also avoids shadowing other Forth words (e.g., @code{and}).
1.21 crook 11849:
1.78 anton 11850: Registers are usually specified by number; e.g., (decimal) @code{11}
11851: specifies registers R11 and F11 on the Alpha architecture (which one,
11852: depends on the instruction). The usual names are also available, e.g.,
11853: @code{s2} for R11 on Alpha.
1.21 crook 11854:
1.78 anton 11855: Control flow is specified similar to normal Forth code (@pxref{Arbitrary
11856: control structures}), with @code{if,}, @code{ahead,}, @code{then,},
11857: @code{begin,}, @code{until,}, @code{again,}, @code{cs-roll},
11858: @code{cs-pick}, @code{else,}, @code{while,}, and @code{repeat,}. The
11859: conditions are specified in a way specific to each assembler.
1.1 anton 11860:
1.78 anton 11861: Note that the register assignments of the Gforth engine can change
11862: between Gforth versions, or even between different compilations of the
11863: same Gforth version (e.g., if you use a different GCC version). So if
11864: you want to refer to Gforth's registers (e.g., the stack pointer or
11865: TOS), I recommend defining your own words for refering to these
11866: registers, and using them later on; then you can easily adapt to a
11867: changed register assignment. The stability of the register assignment
11868: is usually better if you build Gforth with @code{--enable-force-reg}.
1.1 anton 11869:
1.100 anton 11870: The most common use of these registers is to dispatch to the next word
11871: (the @code{next} routine). A portable way to do this is to jump to
11872: @code{' noop >code-address} (of course, this is less efficient than
11873: integrating the @code{next} code and scheduling it well).
1.1 anton 11874:
1.96 anton 11875: Another difference between Gforth version is that the top of stack is
11876: kept in memory in @code{gforth} and, on most platforms, in a register in
11877: @code{gforth-fast}.
11878:
1.78 anton 11879: @node Common Disassembler, 386 Assembler, Common Assembler, Assembler and Code Words
11880: @subsection Common Disassembler
1.1 anton 11881:
1.78 anton 11882: You can disassemble a @code{code} word with @code{see}
11883: (@pxref{Debugging}). You can disassemble a section of memory with
1.1 anton 11884:
1.78 anton 11885: doc-disasm
1.44 crook 11886:
1.78 anton 11887: The disassembler generally produces output that can be fed into the
11888: assembler (i.e., same syntax, etc.). It also includes additional
11889: information in comments. In particular, the address of the instruction
11890: is given in a comment before the instruction.
1.1 anton 11891:
1.78 anton 11892: @code{See} may display more or less than the actual code of the word,
11893: because the recognition of the end of the code is unreliable. You can
11894: use @code{disasm} if it did not display enough. It may display more, if
11895: the code word is not immediately followed by a named word. If you have
11896: something else there, you can follow the word with @code{align last @ ,}
11897: to ensure that the end is recognized.
1.21 crook 11898:
1.78 anton 11899: @node 386 Assembler, Alpha Assembler, Common Disassembler, Assembler and Code Words
11900: @subsection 386 Assembler
1.44 crook 11901:
1.78 anton 11902: The 386 assembler included in Gforth was written by Bernd Paysan, it's
11903: available under GPL, and originally part of bigFORTH.
1.21 crook 11904:
1.78 anton 11905: The 386 disassembler included in Gforth was written by Andrew McKewan
11906: and is in the public domain.
1.21 crook 11907:
1.91 anton 11908: The disassembler displays code in an Intel-like prefix syntax.
1.21 crook 11909:
1.78 anton 11910: The assembler uses a postfix syntax with reversed parameters.
1.1 anton 11911:
1.78 anton 11912: The assembler includes all instruction of the Athlon, i.e. 486 core
11913: instructions, Pentium and PPro extensions, floating point, MMX, 3Dnow!,
11914: but not ISSE. It's an integrated 16- and 32-bit assembler. Default is 32
11915: bit, you can switch to 16 bit with .86 and back to 32 bit with .386.
1.1 anton 11916:
1.78 anton 11917: There are several prefixes to switch between different operation sizes,
11918: @code{.b} for byte accesses, @code{.w} for word accesses, @code{.d} for
11919: double-word accesses. Addressing modes can be switched with @code{.wa}
11920: for 16 bit addresses, and @code{.da} for 32 bit addresses. You don't
11921: need a prefix for byte register names (@code{AL} et al).
1.1 anton 11922:
1.78 anton 11923: For floating point operations, the prefixes are @code{.fs} (IEEE
11924: single), @code{.fl} (IEEE double), @code{.fx} (extended), @code{.fw}
11925: (word), @code{.fd} (double-word), and @code{.fq} (quad-word).
1.21 crook 11926:
1.78 anton 11927: The MMX opcodes don't have size prefixes, they are spelled out like in
11928: the Intel assembler. Instead of move from and to memory, there are
11929: PLDQ/PLDD and PSTQ/PSTD.
1.21 crook 11930:
1.78 anton 11931: The registers lack the 'e' prefix; even in 32 bit mode, eax is called
11932: ax. Immediate values are indicated by postfixing them with @code{#},
1.91 anton 11933: e.g., @code{3 #}. Here are some examples of addressing modes in various
11934: syntaxes:
1.21 crook 11935:
1.26 crook 11936: @example
1.91 anton 11937: Gforth Intel (NASM) AT&T (gas) Name
11938: .w ax ax %ax register (16 bit)
11939: ax eax %eax register (32 bit)
11940: 3 # offset 3 $3 immediate
11941: 1000 #) byte ptr 1000 1000 displacement
11942: bx ) [ebx] (%ebx) base
11943: 100 di d) 100[edi] 100(%edi) base+displacement
11944: 20 ax *4 i#) 20[eax*4] 20(,%eax,4) (index*scale)+displacement
11945: di ax *4 i) [edi][eax*4] (%edi,%eax,4) base+(index*scale)
11946: 4 bx cx di) 4[ebx][ecx] 4(%ebx,%ecx) base+index+displacement
11947: 12 sp ax *2 di) 12[esp][eax*2] 12(%esp,%eax,2) base+(index*scale)+displacement
11948: @end example
11949:
11950: You can use @code{L)} and @code{LI)} instead of @code{D)} and
11951: @code{DI)} to enforce 32-bit displacement fields (useful for
11952: later patching).
1.21 crook 11953:
1.78 anton 11954: Some example of instructions are:
1.1 anton 11955:
11956: @example
1.78 anton 11957: ax bx mov \ move ebx,eax
11958: 3 # ax mov \ mov eax,3
11959: 100 di ) ax mov \ mov eax,100[edi]
11960: 4 bx cx di) ax mov \ mov eax,4[ebx][ecx]
11961: .w ax bx mov \ mov bx,ax
1.1 anton 11962: @end example
11963:
1.78 anton 11964: The following forms are supported for binary instructions:
1.1 anton 11965:
11966: @example
1.78 anton 11967: <reg> <reg> <inst>
11968: <n> # <reg> <inst>
11969: <mem> <reg> <inst>
11970: <reg> <mem> <inst>
1.1 anton 11971: @end example
11972:
1.78 anton 11973: Immediate to memory is not supported. The shift/rotate syntax is:
1.1 anton 11974:
1.26 crook 11975: @example
1.78 anton 11976: <reg/mem> 1 # shl \ shortens to shift without immediate
11977: <reg/mem> 4 # shl
11978: <reg/mem> cl shl
1.26 crook 11979: @end example
1.1 anton 11980:
1.78 anton 11981: Precede string instructions (@code{movs} etc.) with @code{.b} to get
11982: the byte version.
1.1 anton 11983:
1.78 anton 11984: The control structure words @code{IF} @code{UNTIL} etc. must be preceded
11985: by one of these conditions: @code{vs vc u< u>= 0= 0<> u<= u> 0< 0>= ps
11986: pc < >= <= >}. (Note that most of these words shadow some Forth words
11987: when @code{assembler} is in front of @code{forth} in the search path,
11988: e.g., in @code{code} words). Currently the control structure words use
11989: one stack item, so you have to use @code{roll} instead of @code{cs-roll}
11990: to shuffle them (you can also use @code{swap} etc.).
1.21 crook 11991:
1.78 anton 11992: Here is an example of a @code{code} word (assumes that the stack pointer
11993: is in esi and the TOS is in ebx):
1.21 crook 11994:
1.26 crook 11995: @example
1.78 anton 11996: code my+ ( n1 n2 -- n )
11997: 4 si D) bx add
11998: 4 # si add
11999: Next
12000: end-code
1.26 crook 12001: @end example
1.21 crook 12002:
1.78 anton 12003: @node Alpha Assembler, MIPS assembler, 386 Assembler, Assembler and Code Words
12004: @subsection Alpha Assembler
1.21 crook 12005:
1.78 anton 12006: The Alpha assembler and disassembler were originally written by Bernd
12007: Thallner.
1.26 crook 12008:
1.78 anton 12009: The register names @code{a0}--@code{a5} are not available to avoid
12010: shadowing hex numbers.
1.2 jwilke 12011:
1.78 anton 12012: Immediate forms of arithmetic instructions are distinguished by a
12013: @code{#} just before the @code{,}, e.g., @code{and#,} (note: @code{lda,}
12014: does not count as arithmetic instruction).
1.2 jwilke 12015:
1.78 anton 12016: You have to specify all operands to an instruction, even those that
12017: other assemblers consider optional, e.g., the destination register for
12018: @code{br,}, or the destination register and hint for @code{jmp,}.
1.2 jwilke 12019:
1.78 anton 12020: You can specify conditions for @code{if,} by removing the first @code{b}
12021: and the trailing @code{,} from a branch with a corresponding name; e.g.,
1.2 jwilke 12022:
1.26 crook 12023: @example
1.78 anton 12024: 11 fgt if, \ if F11>0e
12025: ...
12026: endif,
1.26 crook 12027: @end example
1.2 jwilke 12028:
1.78 anton 12029: @code{fbgt,} gives @code{fgt}.
12030:
12031: @node MIPS assembler, Other assemblers, Alpha Assembler, Assembler and Code Words
12032: @subsection MIPS assembler
1.2 jwilke 12033:
1.78 anton 12034: The MIPS assembler was originally written by Christian Pirker.
1.2 jwilke 12035:
1.78 anton 12036: Currently the assembler and disassembler only cover the MIPS-I
12037: architecture (R3000), and don't support FP instructions.
1.2 jwilke 12038:
1.78 anton 12039: The register names @code{$a0}--@code{$a3} are not available to avoid
12040: shadowing hex numbers.
1.2 jwilke 12041:
1.78 anton 12042: Because there is no way to distinguish registers from immediate values,
12043: you have to explicitly use the immediate forms of instructions, i.e.,
12044: @code{addiu,}, not just @code{addu,} (@command{as} does this
12045: implicitly).
1.2 jwilke 12046:
1.78 anton 12047: If the architecture manual specifies several formats for the instruction
12048: (e.g., for @code{jalr,}), you usually have to use the one with more
12049: arguments (i.e., two for @code{jalr,}). When in doubt, see
12050: @code{arch/mips/testasm.fs} for an example of correct use.
1.2 jwilke 12051:
1.78 anton 12052: Branches and jumps in the MIPS architecture have a delay slot. You have
12053: to fill it yourself (the simplest way is to use @code{nop,}), the
12054: assembler does not do it for you (unlike @command{as}). Even
12055: @code{if,}, @code{ahead,}, @code{until,}, @code{again,}, @code{while,},
12056: @code{else,} and @code{repeat,} need a delay slot. Since @code{begin,}
12057: and @code{then,} just specify branch targets, they are not affected.
1.2 jwilke 12058:
1.78 anton 12059: Note that you must not put branches, jumps, or @code{li,} into the delay
12060: slot: @code{li,} may expand to several instructions, and control flow
12061: instructions may not be put into the branch delay slot in any case.
1.2 jwilke 12062:
1.78 anton 12063: For branches the argument specifying the target is a relative address;
12064: You have to add the address of the delay slot to get the absolute
12065: address.
1.1 anton 12066:
1.78 anton 12067: The MIPS architecture also has load delay slots and restrictions on
12068: using @code{mfhi,} and @code{mflo,}; you have to order the instructions
12069: yourself to satisfy these restrictions, the assembler does not do it for
12070: you.
1.1 anton 12071:
1.78 anton 12072: You can specify the conditions for @code{if,} etc. by taking a
12073: conditional branch and leaving away the @code{b} at the start and the
12074: @code{,} at the end. E.g.,
1.1 anton 12075:
1.26 crook 12076: @example
1.78 anton 12077: 4 5 eq if,
12078: ... \ do something if $4 equals $5
12079: then,
1.26 crook 12080: @end example
1.1 anton 12081:
1.78 anton 12082: @node Other assemblers, , MIPS assembler, Assembler and Code Words
12083: @subsection Other assemblers
12084:
12085: If you want to contribute another assembler/disassembler, please contact
1.103 anton 12086: us (@email{anton@@mips.complang.tuwien.ac.at}) to check if we have such
12087: an assembler already. If you are writing them from scratch, please use
12088: a similar syntax style as the one we use (i.e., postfix, commas at the
12089: end of the instruction names, @pxref{Common Assembler}); make the output
12090: of the disassembler be valid input for the assembler, and keep the style
1.78 anton 12091: similar to the style we used.
12092:
12093: Hints on implementation: The most important part is to have a good test
12094: suite that contains all instructions. Once you have that, the rest is
12095: easy. For actual coding you can take a look at
12096: @file{arch/mips/disasm.fs} to get some ideas on how to use data for both
12097: the assembler and disassembler, avoiding redundancy and some potential
12098: bugs. You can also look at that file (and @pxref{Advanced does> usage
12099: example}) to get ideas how to factor a disassembler.
12100:
12101: Start with the disassembler, because it's easier to reuse data from the
12102: disassembler for the assembler than the other way round.
1.1 anton 12103:
1.78 anton 12104: For the assembler, take a look at @file{arch/alpha/asm.fs}, which shows
12105: how simple it can be.
1.1 anton 12106:
1.78 anton 12107: @c -------------------------------------------------------------
12108: @node Threading Words, Passing Commands to the OS, Assembler and Code Words, Words
12109: @section Threading Words
12110: @cindex threading words
1.1 anton 12111:
1.78 anton 12112: @cindex code address
12113: These words provide access to code addresses and other threading stuff
12114: in Gforth (and, possibly, other interpretive Forths). It more or less
12115: abstracts away the differences between direct and indirect threading
12116: (and, for direct threading, the machine dependences). However, at
12117: present this wordset is still incomplete. It is also pretty low-level;
12118: some day it will hopefully be made unnecessary by an internals wordset
12119: that abstracts implementation details away completely.
1.1 anton 12120:
1.78 anton 12121: The terminology used here stems from indirect threaded Forth systems; in
12122: such a system, the XT of a word is represented by the CFA (code field
12123: address) of a word; the CFA points to a cell that contains the code
12124: address. The code address is the address of some machine code that
12125: performs the run-time action of invoking the word (e.g., the
12126: @code{dovar:} routine pushes the address of the body of the word (a
12127: variable) on the stack
12128: ).
1.1 anton 12129:
1.78 anton 12130: @cindex code address
12131: @cindex code field address
12132: In an indirect threaded Forth, you can get the code address of @i{name}
12133: with @code{' @i{name} @@}; in Gforth you can get it with @code{' @i{name}
12134: >code-address}, independent of the threading method.
1.1 anton 12135:
1.78 anton 12136: doc-threading-method
12137: doc->code-address
12138: doc-code-address!
1.1 anton 12139:
1.78 anton 12140: @cindex @code{does>}-handler
12141: @cindex @code{does>}-code
12142: For a word defined with @code{DOES>}, the code address usually points to
12143: a jump instruction (the @dfn{does-handler}) that jumps to the dodoes
12144: routine (in Gforth on some platforms, it can also point to the dodoes
12145: routine itself). What you are typically interested in, though, is
12146: whether a word is a @code{DOES>}-defined word, and what Forth code it
12147: executes; @code{>does-code} tells you that.
1.1 anton 12148:
1.78 anton 12149: doc->does-code
1.1 anton 12150:
1.78 anton 12151: To create a @code{DOES>}-defined word with the following basic words,
12152: you have to set up a @code{DOES>}-handler with @code{does-handler!};
12153: @code{/does-handler} aus behind you have to place your executable Forth
12154: code. Finally you have to create a word and modify its behaviour with
12155: @code{does-handler!}.
1.1 anton 12156:
1.78 anton 12157: doc-does-code!
12158: doc-does-handler!
12159: doc-/does-handler
1.1 anton 12160:
1.78 anton 12161: The code addresses produced by various defining words are produced by
12162: the following words:
1.1 anton 12163:
1.78 anton 12164: doc-docol:
12165: doc-docon:
12166: doc-dovar:
12167: doc-douser:
12168: doc-dodefer:
12169: doc-dofield:
1.1 anton 12170:
1.99 anton 12171: @cindex definer
12172: The following two words generalize @code{>code-address},
12173: @code{>does-code}, @code{code-address!}, and @code{does-code!}:
12174:
12175: doc->definer
12176: doc-definer!
12177:
1.26 crook 12178: @c -------------------------------------------------------------
1.78 anton 12179: @node Passing Commands to the OS, Keeping track of Time, Threading Words, Words
1.21 crook 12180: @section Passing Commands to the Operating System
12181: @cindex operating system - passing commands
12182: @cindex shell commands
12183:
12184: Gforth allows you to pass an arbitrary string to the host operating
12185: system shell (if such a thing exists) for execution.
12186:
1.44 crook 12187:
1.21 crook 12188: doc-sh
12189: doc-system
12190: doc-$?
1.23 crook 12191: doc-getenv
1.21 crook 12192:
1.44 crook 12193:
1.26 crook 12194: @c -------------------------------------------------------------
1.47 crook 12195: @node Keeping track of Time, Miscellaneous Words, Passing Commands to the OS, Words
12196: @section Keeping track of Time
12197: @cindex time-related words
12198:
12199: doc-ms
12200: doc-time&date
1.79 anton 12201: doc-utime
12202: doc-cputime
1.47 crook 12203:
12204:
12205: @c -------------------------------------------------------------
12206: @node Miscellaneous Words, , Keeping track of Time, Words
1.21 crook 12207: @section Miscellaneous Words
12208: @cindex miscellaneous words
12209:
1.29 crook 12210: @comment TODO find homes for these
12211:
1.26 crook 12212: These section lists the ANS Forth words that are not documented
1.21 crook 12213: elsewhere in this manual. Ultimately, they all need proper homes.
12214:
1.68 anton 12215: doc-quit
1.44 crook 12216:
1.26 crook 12217: The following ANS Forth words are not currently supported by Gforth
1.27 crook 12218: (@pxref{ANS conformance}):
1.21 crook 12219:
12220: @code{EDITOR}
12221: @code{EMIT?}
12222: @code{FORGET}
12223:
1.24 anton 12224: @c ******************************************************************
12225: @node Error messages, Tools, Words, Top
12226: @chapter Error messages
12227: @cindex error messages
12228: @cindex backtrace
12229:
12230: A typical Gforth error message looks like this:
12231:
12232: @example
1.86 anton 12233: in file included from \evaluated string/:-1
1.24 anton 12234: in file included from ./yyy.fs:1
12235: ./xxx.fs:4: Invalid memory address
12236: bar
12237: ^^^
1.79 anton 12238: Backtrace:
1.25 anton 12239: $400E664C @@
12240: $400E6664 foo
1.24 anton 12241: @end example
12242:
12243: The message identifying the error is @code{Invalid memory address}. The
12244: error happened when text-interpreting line 4 of the file
12245: @file{./xxx.fs}. This line is given (it contains @code{bar}), and the
12246: word on the line where the error happened, is pointed out (with
12247: @code{^^^}).
12248:
12249: The file containing the error was included in line 1 of @file{./yyy.fs},
12250: and @file{yyy.fs} was included from a non-file (in this case, by giving
12251: @file{yyy.fs} as command-line parameter to Gforth).
12252:
12253: At the end of the error message you find a return stack dump that can be
12254: interpreted as a backtrace (possibly empty). On top you find the top of
12255: the return stack when the @code{throw} happened, and at the bottom you
12256: find the return stack entry just above the return stack of the topmost
12257: text interpreter.
12258:
12259: To the right of most return stack entries you see a guess for the word
12260: that pushed that return stack entry as its return address. This gives a
12261: backtrace. In our case we see that @code{bar} called @code{foo}, and
12262: @code{foo} called @code{@@} (and @code{@@} had an @emph{Invalid memory
12263: address} exception).
12264:
12265: Note that the backtrace is not perfect: We don't know which return stack
12266: entries are return addresses (so we may get false positives); and in
12267: some cases (e.g., for @code{abort"}) we cannot determine from the return
12268: address the word that pushed the return address, so for some return
12269: addresses you see no names in the return stack dump.
1.25 anton 12270:
12271: @cindex @code{catch} and backtraces
12272: The return stack dump represents the return stack at the time when a
12273: specific @code{throw} was executed. In programs that make use of
12274: @code{catch}, it is not necessarily clear which @code{throw} should be
12275: used for the return stack dump (e.g., consider one @code{throw} that
12276: indicates an error, which is caught, and during recovery another error
1.42 anton 12277: happens; which @code{throw} should be used for the stack dump?). Gforth
1.25 anton 12278: presents the return stack dump for the first @code{throw} after the last
12279: executed (not returned-to) @code{catch}; this works well in the usual
12280: case.
12281:
12282: @cindex @code{gforth-fast} and backtraces
12283: @cindex @code{gforth-fast}, difference from @code{gforth}
12284: @cindex backtraces with @code{gforth-fast}
12285: @cindex return stack dump with @code{gforth-fast}
1.79 anton 12286: @code{Gforth} is able to do a return stack dump for throws generated
1.25 anton 12287: from primitives (e.g., invalid memory address, stack empty etc.);
12288: @code{gforth-fast} is only able to do a return stack dump from a
1.96 anton 12289: directly called @code{throw} (including @code{abort} etc.). Given an
1.30 anton 12290: exception caused by a primitive in @code{gforth-fast}, you will
12291: typically see no return stack dump at all; however, if the exception is
12292: caught by @code{catch} (e.g., for restoring some state), and then
12293: @code{throw}n again, the return stack dump will be for the first such
12294: @code{throw}.
1.2 jwilke 12295:
1.5 anton 12296: @c ******************************************************************
1.24 anton 12297: @node Tools, ANS conformance, Error messages, Top
1.1 anton 12298: @chapter Tools
12299:
12300: @menu
12301: * ANS Report:: Report the words used, sorted by wordset.
12302: @end menu
12303:
12304: See also @ref{Emacs and Gforth}.
12305:
12306: @node ANS Report, , Tools, Tools
12307: @section @file{ans-report.fs}: Report the words used, sorted by wordset
12308: @cindex @file{ans-report.fs}
12309: @cindex report the words used in your program
12310: @cindex words used in your program
12311:
12312: If you want to label a Forth program as ANS Forth Program, you must
12313: document which wordsets the program uses; for extension wordsets, it is
12314: helpful to list the words the program requires from these wordsets
12315: (because Forth systems are allowed to provide only some words of them).
12316:
12317: The @file{ans-report.fs} tool makes it easy for you to determine which
12318: words from which wordset and which non-ANS words your application
12319: uses. You simply have to include @file{ans-report.fs} before loading the
12320: program you want to check. After loading your program, you can get the
12321: report with @code{print-ans-report}. A typical use is to run this as
12322: batch job like this:
12323: @example
12324: gforth ans-report.fs myprog.fs -e "print-ans-report bye"
12325: @end example
12326:
12327: The output looks like this (for @file{compat/control.fs}):
12328: @example
12329: The program uses the following words
12330: from CORE :
12331: : POSTPONE THEN ; immediate ?dup IF 0=
12332: from BLOCK-EXT :
12333: \
12334: from FILE :
12335: (
12336: @end example
12337:
12338: @subsection Caveats
12339:
12340: Note that @file{ans-report.fs} just checks which words are used, not whether
12341: they are used in an ANS Forth conforming way!
12342:
12343: Some words are defined in several wordsets in the
12344: standard. @file{ans-report.fs} reports them for only one of the
12345: wordsets, and not necessarily the one you expect. It depends on usage
12346: which wordset is the right one to specify. E.g., if you only use the
12347: compilation semantics of @code{S"}, it is a Core word; if you also use
12348: its interpretation semantics, it is a File word.
12349:
12350: @c ******************************************************************
1.65 anton 12351: @node ANS conformance, Standard vs Extensions, Tools, Top
1.1 anton 12352: @chapter ANS conformance
12353: @cindex ANS conformance of Gforth
12354:
12355: To the best of our knowledge, Gforth is an
12356:
12357: ANS Forth System
12358: @itemize @bullet
12359: @item providing the Core Extensions word set
12360: @item providing the Block word set
12361: @item providing the Block Extensions word set
12362: @item providing the Double-Number word set
12363: @item providing the Double-Number Extensions word set
12364: @item providing the Exception word set
12365: @item providing the Exception Extensions word set
12366: @item providing the Facility word set
1.40 anton 12367: @item providing @code{EKEY}, @code{EKEY>CHAR}, @code{EKEY?}, @code{MS} and @code{TIME&DATE} from the Facility Extensions word set
1.1 anton 12368: @item providing the File Access word set
12369: @item providing the File Access Extensions word set
12370: @item providing the Floating-Point word set
12371: @item providing the Floating-Point Extensions word set
12372: @item providing the Locals word set
12373: @item providing the Locals Extensions word set
12374: @item providing the Memory-Allocation word set
12375: @item providing the Memory-Allocation Extensions word set (that one's easy)
12376: @item providing the Programming-Tools word set
12377: @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
12378: @item providing the Search-Order word set
12379: @item providing the Search-Order Extensions word set
12380: @item providing the String word set
12381: @item providing the String Extensions word set (another easy one)
12382: @end itemize
12383:
12384: @cindex system documentation
12385: In addition, ANS Forth systems are required to document certain
12386: implementation choices. This chapter tries to meet these
12387: requirements. In many cases it gives a way to ask the system for the
12388: information instead of providing the information directly, in
12389: particular, if the information depends on the processor, the operating
12390: system or the installation options chosen, or if they are likely to
12391: change during the maintenance of Gforth.
12392:
12393: @comment The framework for the rest has been taken from pfe.
12394:
12395: @menu
12396: * The Core Words::
12397: * The optional Block word set::
12398: * The optional Double Number word set::
12399: * The optional Exception word set::
12400: * The optional Facility word set::
12401: * The optional File-Access word set::
12402: * The optional Floating-Point word set::
12403: * The optional Locals word set::
12404: * The optional Memory-Allocation word set::
12405: * The optional Programming-Tools word set::
12406: * The optional Search-Order word set::
12407: @end menu
12408:
12409:
12410: @c =====================================================================
12411: @node The Core Words, The optional Block word set, ANS conformance, ANS conformance
12412: @comment node-name, next, previous, up
12413: @section The Core Words
12414: @c =====================================================================
12415: @cindex core words, system documentation
12416: @cindex system documentation, core words
12417:
12418: @menu
12419: * core-idef:: Implementation Defined Options
12420: * core-ambcond:: Ambiguous Conditions
12421: * core-other:: Other System Documentation
12422: @end menu
12423:
12424: @c ---------------------------------------------------------------------
12425: @node core-idef, core-ambcond, The Core Words, The Core Words
12426: @subsection Implementation Defined Options
12427: @c ---------------------------------------------------------------------
12428: @cindex core words, implementation-defined options
12429: @cindex implementation-defined options, core words
12430:
12431:
12432: @table @i
12433: @item (Cell) aligned addresses:
12434: @cindex cell-aligned addresses
12435: @cindex aligned addresses
12436: processor-dependent. Gforth's alignment words perform natural alignment
12437: (e.g., an address aligned for a datum of size 8 is divisible by
12438: 8). Unaligned accesses usually result in a @code{-23 THROW}.
12439:
12440: @item @code{EMIT} and non-graphic characters:
12441: @cindex @code{EMIT} and non-graphic characters
12442: @cindex non-graphic characters and @code{EMIT}
12443: The character is output using the C library function (actually, macro)
12444: @code{putc}.
12445:
12446: @item character editing of @code{ACCEPT} and @code{EXPECT}:
12447: @cindex character editing of @code{ACCEPT} and @code{EXPECT}
12448: @cindex editing in @code{ACCEPT} and @code{EXPECT}
12449: @cindex @code{ACCEPT}, editing
12450: @cindex @code{EXPECT}, editing
12451: This is modeled on the GNU readline library (@pxref{Readline
12452: Interaction, , Command Line Editing, readline, The GNU Readline
12453: Library}) with Emacs-like key bindings. @kbd{Tab} deviates a little by
12454: producing a full word completion every time you type it (instead of
1.28 crook 12455: producing the common prefix of all completions). @xref{Command-line editing}.
1.1 anton 12456:
12457: @item character set:
12458: @cindex character set
12459: The character set of your computer and display device. Gforth is
12460: 8-bit-clean (but some other component in your system may make trouble).
12461:
12462: @item Character-aligned address requirements:
12463: @cindex character-aligned address requirements
12464: installation-dependent. Currently a character is represented by a C
12465: @code{unsigned char}; in the future we might switch to @code{wchar_t}
12466: (Comments on that requested).
12467:
12468: @item character-set extensions and matching of names:
12469: @cindex character-set extensions and matching of names
1.26 crook 12470: @cindex case-sensitivity for name lookup
12471: @cindex name lookup, case-sensitivity
12472: @cindex locale and case-sensitivity
1.21 crook 12473: Any character except the ASCII NUL character can be used in a
1.1 anton 12474: name. Matching is case-insensitive (except in @code{TABLE}s). The
1.47 crook 12475: matching is performed using the C library function @code{strncasecmp}, whose
1.1 anton 12476: function is probably influenced by the locale. E.g., the @code{C} locale
12477: does not know about accents and umlauts, so they are matched
12478: case-sensitively in that locale. For portability reasons it is best to
12479: write programs such that they work in the @code{C} locale. Then one can
12480: use libraries written by a Polish programmer (who might use words
12481: containing ISO Latin-2 encoded characters) and by a French programmer
12482: (ISO Latin-1) in the same program (of course, @code{WORDS} will produce
12483: funny results for some of the words (which ones, depends on the font you
12484: are using)). Also, the locale you prefer may not be available in other
12485: operating systems. Hopefully, Unicode will solve these problems one day.
12486:
12487: @item conditions under which control characters match a space delimiter:
12488: @cindex space delimiters
12489: @cindex control characters as delimiters
12490: If @code{WORD} is called with the space character as a delimiter, all
12491: white-space characters (as identified by the C macro @code{isspace()})
12492: are delimiters. @code{PARSE}, on the other hand, treats space like other
1.44 crook 12493: delimiters. @code{SWORD} treats space like @code{WORD}, but behaves
1.79 anton 12494: like @code{PARSE} otherwise. @code{Name}, which is used by the outer
1.1 anton 12495: interpreter (aka text interpreter) by default, treats all white-space
12496: characters as delimiters.
12497:
1.26 crook 12498: @item format of the control-flow stack:
12499: @cindex control-flow stack, format
12500: The data stack is used as control-flow stack. The size of a control-flow
1.1 anton 12501: stack item in cells is given by the constant @code{cs-item-size}. At the
12502: time of this writing, an item consists of a (pointer to a) locals list
12503: (third), an address in the code (second), and a tag for identifying the
12504: item (TOS). The following tags are used: @code{defstart},
12505: @code{live-orig}, @code{dead-orig}, @code{dest}, @code{do-dest},
12506: @code{scopestart}.
12507:
12508: @item conversion of digits > 35
12509: @cindex digits > 35
12510: The characters @code{[\]^_'} are the digits with the decimal value
12511: 36@minus{}41. There is no way to input many of the larger digits.
12512:
12513: @item display after input terminates in @code{ACCEPT} and @code{EXPECT}:
12514: @cindex @code{EXPECT}, display after end of input
12515: @cindex @code{ACCEPT}, display after end of input
12516: The cursor is moved to the end of the entered string. If the input is
12517: terminated using the @kbd{Return} key, a space is typed.
12518:
12519: @item exception abort sequence of @code{ABORT"}:
12520: @cindex exception abort sequence of @code{ABORT"}
12521: @cindex @code{ABORT"}, exception abort sequence
12522: The error string is stored into the variable @code{"error} and a
12523: @code{-2 throw} is performed.
12524:
12525: @item input line terminator:
12526: @cindex input line terminator
12527: @cindex line terminator on input
1.26 crook 12528: @cindex newline character on input
1.1 anton 12529: For interactive input, @kbd{C-m} (CR) and @kbd{C-j} (LF) terminate
12530: lines. One of these characters is typically produced when you type the
12531: @kbd{Enter} or @kbd{Return} key.
12532:
12533: @item maximum size of a counted string:
12534: @cindex maximum size of a counted string
12535: @cindex counted string, maximum size
12536: @code{s" /counted-string" environment? drop .}. Currently 255 characters
1.79 anton 12537: on all platforms, but this may change.
1.1 anton 12538:
12539: @item maximum size of a parsed string:
12540: @cindex maximum size of a parsed string
12541: @cindex parsed string, maximum size
12542: Given by the constant @code{/line}. Currently 255 characters.
12543:
12544: @item maximum size of a definition name, in characters:
12545: @cindex maximum size of a definition name, in characters
12546: @cindex name, maximum length
12547: 31
12548:
12549: @item maximum string length for @code{ENVIRONMENT?}, in characters:
12550: @cindex maximum string length for @code{ENVIRONMENT?}, in characters
12551: @cindex @code{ENVIRONMENT?} string length, maximum
12552: 31
12553:
12554: @item method of selecting the user input device:
12555: @cindex user input device, method of selecting
12556: The user input device is the standard input. There is currently no way to
12557: change it from within Gforth. However, the input can typically be
12558: redirected in the command line that starts Gforth.
12559:
12560: @item method of selecting the user output device:
12561: @cindex user output device, method of selecting
12562: @code{EMIT} and @code{TYPE} output to the file-id stored in the value
1.10 anton 12563: @code{outfile-id} (@code{stdout} by default). Gforth uses unbuffered
12564: output when the user output device is a terminal, otherwise the output
12565: is buffered.
1.1 anton 12566:
12567: @item methods of dictionary compilation:
12568: What are we expected to document here?
12569:
12570: @item number of bits in one address unit:
12571: @cindex number of bits in one address unit
12572: @cindex address unit, size in bits
12573: @code{s" address-units-bits" environment? drop .}. 8 in all current
1.79 anton 12574: platforms.
1.1 anton 12575:
12576: @item number representation and arithmetic:
12577: @cindex number representation and arithmetic
1.79 anton 12578: Processor-dependent. Binary two's complement on all current platforms.
1.1 anton 12579:
12580: @item ranges for integer types:
12581: @cindex ranges for integer types
12582: @cindex integer types, ranges
12583: Installation-dependent. Make environmental queries for @code{MAX-N},
12584: @code{MAX-U}, @code{MAX-D} and @code{MAX-UD}. The lower bounds for
12585: unsigned (and positive) types is 0. The lower bound for signed types on
12586: two's complement and one's complement machines machines can be computed
12587: by adding 1 to the upper bound.
12588:
12589: @item read-only data space regions:
12590: @cindex read-only data space regions
12591: @cindex data-space, read-only regions
12592: The whole Forth data space is writable.
12593:
12594: @item size of buffer at @code{WORD}:
12595: @cindex size of buffer at @code{WORD}
12596: @cindex @code{WORD} buffer size
12597: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
12598: shared with the pictured numeric output string. If overwriting
12599: @code{PAD} is acceptable, it is as large as the remaining dictionary
12600: space, although only as much can be sensibly used as fits in a counted
12601: string.
12602:
12603: @item size of one cell in address units:
12604: @cindex cell size
12605: @code{1 cells .}.
12606:
12607: @item size of one character in address units:
12608: @cindex char size
1.79 anton 12609: @code{1 chars .}. 1 on all current platforms.
1.1 anton 12610:
12611: @item size of the keyboard terminal buffer:
12612: @cindex size of the keyboard terminal buffer
12613: @cindex terminal buffer, size
12614: Varies. You can determine the size at a specific time using @code{lp@@
12615: tib - .}. It is shared with the locals stack and TIBs of files that
12616: include the current file. You can change the amount of space for TIBs
12617: and locals stack at Gforth startup with the command line option
12618: @code{-l}.
12619:
12620: @item size of the pictured numeric output buffer:
12621: @cindex size of the pictured numeric output buffer
12622: @cindex pictured numeric output buffer, size
12623: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
12624: shared with @code{WORD}.
12625:
12626: @item size of the scratch area returned by @code{PAD}:
12627: @cindex size of the scratch area returned by @code{PAD}
12628: @cindex @code{PAD} size
12629: The remainder of dictionary space. @code{unused pad here - - .}.
12630:
12631: @item system case-sensitivity characteristics:
12632: @cindex case-sensitivity characteristics
1.26 crook 12633: Dictionary searches are case-insensitive (except in
1.1 anton 12634: @code{TABLE}s). However, as explained above under @i{character-set
12635: extensions}, the matching for non-ASCII characters is determined by the
12636: locale you are using. In the default @code{C} locale all non-ASCII
12637: characters are matched case-sensitively.
12638:
12639: @item system prompt:
12640: @cindex system prompt
12641: @cindex prompt
12642: @code{ ok} in interpret state, @code{ compiled} in compile state.
12643:
12644: @item division rounding:
12645: @cindex division rounding
12646: installation dependent. @code{s" floored" environment? drop .}. We leave
12647: the choice to @code{gcc} (what to use for @code{/}) and to you (whether
12648: to use @code{fm/mod}, @code{sm/rem} or simply @code{/}).
12649:
12650: @item values of @code{STATE} when true:
12651: @cindex @code{STATE} values
12652: -1.
12653:
12654: @item values returned after arithmetic overflow:
12655: On two's complement machines, arithmetic is performed modulo
12656: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
12657: arithmetic (with appropriate mapping for signed types). Division by zero
12658: typically results in a @code{-55 throw} (Floating-point unidentified
1.80 anton 12659: fault) or @code{-10 throw} (divide by zero).
1.1 anton 12660:
12661: @item whether the current definition can be found after @t{DOES>}:
12662: @cindex @t{DOES>}, visibility of current definition
12663: No.
12664:
12665: @end table
12666:
12667: @c ---------------------------------------------------------------------
12668: @node core-ambcond, core-other, core-idef, The Core Words
12669: @subsection Ambiguous conditions
12670: @c ---------------------------------------------------------------------
12671: @cindex core words, ambiguous conditions
12672: @cindex ambiguous conditions, core words
12673:
12674: @table @i
12675:
12676: @item a name is neither a word nor a number:
12677: @cindex name not found
1.26 crook 12678: @cindex undefined word
1.80 anton 12679: @code{-13 throw} (Undefined word).
1.1 anton 12680:
12681: @item a definition name exceeds the maximum length allowed:
1.26 crook 12682: @cindex word name too long
1.1 anton 12683: @code{-19 throw} (Word name too long)
12684:
12685: @item addressing a region not inside the various data spaces of the forth system:
12686: @cindex Invalid memory address
1.32 anton 12687: The stacks, code space and header space are accessible. Machine code space is
1.1 anton 12688: typically readable. Accessing other addresses gives results dependent on
12689: the operating system. On decent systems: @code{-9 throw} (Invalid memory
12690: address).
12691:
12692: @item argument type incompatible with parameter:
1.26 crook 12693: @cindex argument type mismatch
1.1 anton 12694: This is usually not caught. Some words perform checks, e.g., the control
12695: flow words, and issue a @code{ABORT"} or @code{-12 THROW} (Argument type
12696: mismatch).
12697:
12698: @item attempting to obtain the execution token of a word with undefined execution semantics:
12699: @cindex Interpreting a compile-only word, for @code{'} etc.
12700: @cindex execution token of words with undefined execution semantics
12701: @code{-14 throw} (Interpreting a compile-only word). In some cases, you
12702: get an execution token for @code{compile-only-error} (which performs a
12703: @code{-14 throw} when executed).
12704:
12705: @item dividing by zero:
12706: @cindex dividing by zero
12707: @cindex floating point unidentified fault, integer division
1.80 anton 12708: On some platforms, this produces a @code{-10 throw} (Division by
1.24 anton 12709: zero); on other systems, this typically results in a @code{-55 throw}
12710: (Floating-point unidentified fault).
1.1 anton 12711:
12712: @item insufficient data stack or return stack space:
12713: @cindex insufficient data stack or return stack space
12714: @cindex stack overflow
1.26 crook 12715: @cindex address alignment exception, stack overflow
1.1 anton 12716: @cindex Invalid memory address, stack overflow
12717: Depending on the operating system, the installation, and the invocation
12718: of Gforth, this is either checked by the memory management hardware, or
1.24 anton 12719: it is not checked. If it is checked, you typically get a @code{-3 throw}
12720: (Stack overflow), @code{-5 throw} (Return stack overflow), or @code{-9
12721: throw} (Invalid memory address) (depending on the platform and how you
12722: achieved the overflow) as soon as the overflow happens. If it is not
12723: checked, overflows typically result in mysterious illegal memory
12724: accesses, producing @code{-9 throw} (Invalid memory address) or
12725: @code{-23 throw} (Address alignment exception); they might also destroy
12726: the internal data structure of @code{ALLOCATE} and friends, resulting in
12727: various errors in these words.
1.1 anton 12728:
12729: @item insufficient space for loop control parameters:
12730: @cindex insufficient space for loop control parameters
1.80 anton 12731: Like other return stack overflows.
1.1 anton 12732:
12733: @item insufficient space in the dictionary:
12734: @cindex insufficient space in the dictionary
12735: @cindex dictionary overflow
1.12 anton 12736: If you try to allot (either directly with @code{allot}, or indirectly
12737: with @code{,}, @code{create} etc.) more memory than available in the
12738: dictionary, you get a @code{-8 throw} (Dictionary overflow). If you try
12739: to access memory beyond the end of the dictionary, the results are
12740: similar to stack overflows.
1.1 anton 12741:
12742: @item interpreting a word with undefined interpretation semantics:
12743: @cindex interpreting a word with undefined interpretation semantics
12744: @cindex Interpreting a compile-only word
12745: For some words, we have defined interpretation semantics. For the
12746: others: @code{-14 throw} (Interpreting a compile-only word).
12747:
12748: @item modifying the contents of the input buffer or a string literal:
12749: @cindex modifying the contents of the input buffer or a string literal
12750: These are located in writable memory and can be modified.
12751:
12752: @item overflow of the pictured numeric output string:
12753: @cindex overflow of the pictured numeric output string
12754: @cindex pictured numeric output string, overflow
1.24 anton 12755: @code{-17 throw} (Pictured numeric ouput string overflow).
1.1 anton 12756:
12757: @item parsed string overflow:
12758: @cindex parsed string overflow
12759: @code{PARSE} cannot overflow. @code{WORD} does not check for overflow.
12760:
12761: @item producing a result out of range:
12762: @cindex result out of range
12763: On two's complement machines, arithmetic is performed modulo
12764: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
12765: arithmetic (with appropriate mapping for signed types). Division by zero
1.24 anton 12766: typically results in a @code{-10 throw} (divide by zero) or @code{-55
12767: throw} (floating point unidentified fault). @code{convert} and
12768: @code{>number} currently overflow silently.
1.1 anton 12769:
12770: @item reading from an empty data or return stack:
12771: @cindex stack empty
12772: @cindex stack underflow
1.24 anton 12773: @cindex return stack underflow
1.1 anton 12774: The data stack is checked by the outer (aka text) interpreter after
12775: every word executed. If it has underflowed, a @code{-4 throw} (Stack
12776: underflow) is performed. Apart from that, stacks may be checked or not,
1.24 anton 12777: depending on operating system, installation, and invocation. If they are
12778: caught by a check, they typically result in @code{-4 throw} (Stack
12779: underflow), @code{-6 throw} (Return stack underflow) or @code{-9 throw}
12780: (Invalid memory address), depending on the platform and which stack
12781: underflows and by how much. Note that even if the system uses checking
12782: (through the MMU), your program may have to underflow by a significant
12783: number of stack items to trigger the reaction (the reason for this is
12784: that the MMU, and therefore the checking, works with a page-size
12785: granularity). If there is no checking, the symptoms resulting from an
12786: underflow are similar to those from an overflow. Unbalanced return
1.80 anton 12787: stack errors can result in a variety of symptoms, including @code{-9 throw}
1.24 anton 12788: (Invalid memory address) and Illegal Instruction (typically @code{-260
12789: throw}).
1.1 anton 12790:
12791: @item unexpected end of the input buffer, resulting in an attempt to use a zero-length string as a name:
12792: @cindex unexpected end of the input buffer
12793: @cindex zero-length string as a name
12794: @cindex Attempt to use zero-length string as a name
12795: @code{Create} and its descendants perform a @code{-16 throw} (Attempt to
12796: use zero-length string as a name). Words like @code{'} probably will not
12797: find what they search. Note that it is possible to create zero-length
12798: names with @code{nextname} (should it not?).
12799:
12800: @item @code{>IN} greater than input buffer:
12801: @cindex @code{>IN} greater than input buffer
12802: The next invocation of a parsing word returns a string with length 0.
12803:
12804: @item @code{RECURSE} appears after @code{DOES>}:
12805: @cindex @code{RECURSE} appears after @code{DOES>}
12806: Compiles a recursive call to the defining word, not to the defined word.
12807:
12808: @item argument input source different than current input source for @code{RESTORE-INPUT}:
12809: @cindex argument input source different than current input source for @code{RESTORE-INPUT}
1.26 crook 12810: @cindex argument type mismatch, @code{RESTORE-INPUT}
1.1 anton 12811: @cindex @code{RESTORE-INPUT}, Argument type mismatch
12812: @code{-12 THROW}. Note that, once an input file is closed (e.g., because
12813: the end of the file was reached), its source-id may be
12814: reused. Therefore, restoring an input source specification referencing a
12815: closed file may lead to unpredictable results instead of a @code{-12
12816: THROW}.
12817:
12818: In the future, Gforth may be able to restore input source specifications
12819: from other than the current input source.
12820:
12821: @item data space containing definitions gets de-allocated:
12822: @cindex data space containing definitions gets de-allocated
12823: Deallocation with @code{allot} is not checked. This typically results in
12824: memory access faults or execution of illegal instructions.
12825:
12826: @item data space read/write with incorrect alignment:
12827: @cindex data space read/write with incorrect alignment
12828: @cindex alignment faults
1.26 crook 12829: @cindex address alignment exception
1.1 anton 12830: Processor-dependent. Typically results in a @code{-23 throw} (Address
1.12 anton 12831: alignment exception). Under Linux-Intel on a 486 or later processor with
1.1 anton 12832: alignment turned on, incorrect alignment results in a @code{-9 throw}
12833: (Invalid memory address). There are reportedly some processors with
1.12 anton 12834: alignment restrictions that do not report violations.
1.1 anton 12835:
12836: @item data space pointer not properly aligned, @code{,}, @code{C,}:
12837: @cindex data space pointer not properly aligned, @code{,}, @code{C,}
12838: Like other alignment errors.
12839:
12840: @item less than u+2 stack items (@code{PICK} and @code{ROLL}):
12841: Like other stack underflows.
12842:
12843: @item loop control parameters not available:
12844: @cindex loop control parameters not available
12845: Not checked. The counted loop words simply assume that the top of return
12846: stack items are loop control parameters and behave accordingly.
12847:
12848: @item most recent definition does not have a name (@code{IMMEDIATE}):
12849: @cindex most recent definition does not have a name (@code{IMMEDIATE})
12850: @cindex last word was headerless
12851: @code{abort" last word was headerless"}.
12852:
12853: @item name not defined by @code{VALUE} used by @code{TO}:
12854: @cindex name not defined by @code{VALUE} used by @code{TO}
12855: @cindex @code{TO} on non-@code{VALUE}s
12856: @cindex Invalid name argument, @code{TO}
12857: @code{-32 throw} (Invalid name argument) (unless name is a local or was
12858: defined by @code{CONSTANT}; in the latter case it just changes the constant).
12859:
12860: @item name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}):
12861: @cindex name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]})
1.26 crook 12862: @cindex undefined word, @code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}
1.1 anton 12863: @code{-13 throw} (Undefined word)
12864:
12865: @item parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN}):
12866: @cindex parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN})
12867: Gforth behaves as if they were of the same type. I.e., you can predict
12868: the behaviour by interpreting all parameters as, e.g., signed.
12869:
12870: @item @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}:
12871: @cindex @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}
12872: Assume @code{: X POSTPONE TO ; IMMEDIATE}. @code{X} performs the
12873: compilation semantics of @code{TO}.
12874:
12875: @item String longer than a counted string returned by @code{WORD}:
1.26 crook 12876: @cindex string longer than a counted string returned by @code{WORD}
1.1 anton 12877: @cindex @code{WORD}, string overflow
12878: Not checked. The string will be ok, but the count will, of course,
12879: contain only the least significant bits of the length.
12880:
12881: @item u greater than or equal to the number of bits in a cell (@code{LSHIFT}, @code{RSHIFT}):
12882: @cindex @code{LSHIFT}, large shift counts
12883: @cindex @code{RSHIFT}, large shift counts
12884: Processor-dependent. Typical behaviours are returning 0 and using only
12885: the low bits of the shift count.
12886:
12887: @item word not defined via @code{CREATE}:
12888: @cindex @code{>BODY} of non-@code{CREATE}d words
12889: @code{>BODY} produces the PFA of the word no matter how it was defined.
12890:
12891: @cindex @code{DOES>} of non-@code{CREATE}d words
12892: @code{DOES>} changes the execution semantics of the last defined word no
12893: matter how it was defined. E.g., @code{CONSTANT DOES>} is equivalent to
12894: @code{CREATE , DOES>}.
12895:
12896: @item words improperly used outside @code{<#} and @code{#>}:
12897: Not checked. As usual, you can expect memory faults.
12898:
12899: @end table
12900:
12901:
12902: @c ---------------------------------------------------------------------
12903: @node core-other, , core-ambcond, The Core Words
12904: @subsection Other system documentation
12905: @c ---------------------------------------------------------------------
12906: @cindex other system documentation, core words
12907: @cindex core words, other system documentation
12908:
12909: @table @i
12910: @item nonstandard words using @code{PAD}:
12911: @cindex @code{PAD} use by nonstandard words
12912: None.
12913:
12914: @item operator's terminal facilities available:
12915: @cindex operator's terminal facilities available
1.80 anton 12916: After processing the OS's command line, Gforth goes into interactive mode,
1.1 anton 12917: and you can give commands to Gforth interactively. The actual facilities
12918: available depend on how you invoke Gforth.
12919:
12920: @item program data space available:
12921: @cindex program data space available
12922: @cindex data space available
12923: @code{UNUSED .} gives the remaining dictionary space. The total
12924: dictionary space can be specified with the @code{-m} switch
12925: (@pxref{Invoking Gforth}) when Gforth starts up.
12926:
12927: @item return stack space available:
12928: @cindex return stack space available
12929: You can compute the total return stack space in cells with
12930: @code{s" RETURN-STACK-CELLS" environment? drop .}. You can specify it at
12931: startup time with the @code{-r} switch (@pxref{Invoking Gforth}).
12932:
12933: @item stack space available:
12934: @cindex stack space available
12935: You can compute the total data stack space in cells with
12936: @code{s" STACK-CELLS" environment? drop .}. You can specify it at
12937: startup time with the @code{-d} switch (@pxref{Invoking Gforth}).
12938:
12939: @item system dictionary space required, in address units:
12940: @cindex system dictionary space required, in address units
12941: Type @code{here forthstart - .} after startup. At the time of this
12942: writing, this gives 80080 (bytes) on a 32-bit system.
12943: @end table
12944:
12945:
12946: @c =====================================================================
12947: @node The optional Block word set, The optional Double Number word set, The Core Words, ANS conformance
12948: @section The optional Block word set
12949: @c =====================================================================
12950: @cindex system documentation, block words
12951: @cindex block words, system documentation
12952:
12953: @menu
12954: * block-idef:: Implementation Defined Options
12955: * block-ambcond:: Ambiguous Conditions
12956: * block-other:: Other System Documentation
12957: @end menu
12958:
12959:
12960: @c ---------------------------------------------------------------------
12961: @node block-idef, block-ambcond, The optional Block word set, The optional Block word set
12962: @subsection Implementation Defined Options
12963: @c ---------------------------------------------------------------------
12964: @cindex implementation-defined options, block words
12965: @cindex block words, implementation-defined options
12966:
12967: @table @i
12968: @item the format for display by @code{LIST}:
12969: @cindex @code{LIST} display format
12970: First the screen number is displayed, then 16 lines of 64 characters,
12971: each line preceded by the line number.
12972:
12973: @item the length of a line affected by @code{\}:
12974: @cindex length of a line affected by @code{\}
12975: @cindex @code{\}, line length in blocks
12976: 64 characters.
12977: @end table
12978:
12979:
12980: @c ---------------------------------------------------------------------
12981: @node block-ambcond, block-other, block-idef, The optional Block word set
12982: @subsection Ambiguous conditions
12983: @c ---------------------------------------------------------------------
12984: @cindex block words, ambiguous conditions
12985: @cindex ambiguous conditions, block words
12986:
12987: @table @i
12988: @item correct block read was not possible:
12989: @cindex block read not possible
12990: Typically results in a @code{throw} of some OS-derived value (between
12991: -512 and -2048). If the blocks file was just not long enough, blanks are
12992: supplied for the missing portion.
12993:
12994: @item I/O exception in block transfer:
12995: @cindex I/O exception in block transfer
12996: @cindex block transfer, I/O exception
12997: Typically results in a @code{throw} of some OS-derived value (between
12998: -512 and -2048).
12999:
13000: @item invalid block number:
13001: @cindex invalid block number
13002: @cindex block number invalid
13003: @code{-35 throw} (Invalid block number)
13004:
13005: @item a program directly alters the contents of @code{BLK}:
13006: @cindex @code{BLK}, altering @code{BLK}
13007: The input stream is switched to that other block, at the same
13008: position. If the storing to @code{BLK} happens when interpreting
13009: non-block input, the system will get quite confused when the block ends.
13010:
13011: @item no current block buffer for @code{UPDATE}:
13012: @cindex @code{UPDATE}, no current block buffer
13013: @code{UPDATE} has no effect.
13014:
13015: @end table
13016:
13017: @c ---------------------------------------------------------------------
13018: @node block-other, , block-ambcond, The optional Block word set
13019: @subsection Other system documentation
13020: @c ---------------------------------------------------------------------
13021: @cindex other system documentation, block words
13022: @cindex block words, other system documentation
13023:
13024: @table @i
13025: @item any restrictions a multiprogramming system places on the use of buffer addresses:
13026: No restrictions (yet).
13027:
13028: @item the number of blocks available for source and data:
13029: depends on your disk space.
13030:
13031: @end table
13032:
13033:
13034: @c =====================================================================
13035: @node The optional Double Number word set, The optional Exception word set, The optional Block word set, ANS conformance
13036: @section The optional Double Number word set
13037: @c =====================================================================
13038: @cindex system documentation, double words
13039: @cindex double words, system documentation
13040:
13041: @menu
13042: * double-ambcond:: Ambiguous Conditions
13043: @end menu
13044:
13045:
13046: @c ---------------------------------------------------------------------
13047: @node double-ambcond, , The optional Double Number word set, The optional Double Number word set
13048: @subsection Ambiguous conditions
13049: @c ---------------------------------------------------------------------
13050: @cindex double words, ambiguous conditions
13051: @cindex ambiguous conditions, double words
13052:
13053: @table @i
1.29 crook 13054: @item @i{d} outside of range of @i{n} in @code{D>S}:
13055: @cindex @code{D>S}, @i{d} out of range of @i{n}
13056: The least significant cell of @i{d} is produced.
1.1 anton 13057:
13058: @end table
13059:
13060:
13061: @c =====================================================================
13062: @node The optional Exception word set, The optional Facility word set, The optional Double Number word set, ANS conformance
13063: @section The optional Exception word set
13064: @c =====================================================================
13065: @cindex system documentation, exception words
13066: @cindex exception words, system documentation
13067:
13068: @menu
13069: * exception-idef:: Implementation Defined Options
13070: @end menu
13071:
13072:
13073: @c ---------------------------------------------------------------------
13074: @node exception-idef, , The optional Exception word set, The optional Exception word set
13075: @subsection Implementation Defined Options
13076: @c ---------------------------------------------------------------------
13077: @cindex implementation-defined options, exception words
13078: @cindex exception words, implementation-defined options
13079:
13080: @table @i
13081: @item @code{THROW}-codes used in the system:
13082: @cindex @code{THROW}-codes used in the system
13083: The codes -256@minus{}-511 are used for reporting signals. The mapping
1.29 crook 13084: from OS signal numbers to throw codes is -256@minus{}@i{signal}. The
1.1 anton 13085: codes -512@minus{}-2047 are used for OS errors (for file and memory
13086: allocation operations). The mapping from OS error numbers to throw codes
13087: is -512@minus{}@code{errno}. One side effect of this mapping is that
13088: undefined OS errors produce a message with a strange number; e.g.,
13089: @code{-1000 THROW} results in @code{Unknown error 488} on my system.
13090: @end table
13091:
13092: @c =====================================================================
13093: @node The optional Facility word set, The optional File-Access word set, The optional Exception word set, ANS conformance
13094: @section The optional Facility word set
13095: @c =====================================================================
13096: @cindex system documentation, facility words
13097: @cindex facility words, system documentation
13098:
13099: @menu
13100: * facility-idef:: Implementation Defined Options
13101: * facility-ambcond:: Ambiguous Conditions
13102: @end menu
13103:
13104:
13105: @c ---------------------------------------------------------------------
13106: @node facility-idef, facility-ambcond, The optional Facility word set, The optional Facility word set
13107: @subsection Implementation Defined Options
13108: @c ---------------------------------------------------------------------
13109: @cindex implementation-defined options, facility words
13110: @cindex facility words, implementation-defined options
13111:
13112: @table @i
13113: @item encoding of keyboard events (@code{EKEY}):
13114: @cindex keyboard events, encoding in @code{EKEY}
13115: @cindex @code{EKEY}, encoding of keyboard events
1.40 anton 13116: Keys corresponding to ASCII characters are encoded as ASCII characters.
1.41 anton 13117: Other keys are encoded with the constants @code{k-left}, @code{k-right},
13118: @code{k-up}, @code{k-down}, @code{k-home}, @code{k-end}, @code{k1},
13119: @code{k2}, @code{k3}, @code{k4}, @code{k5}, @code{k6}, @code{k7},
13120: @code{k8}, @code{k9}, @code{k10}, @code{k11}, @code{k12}.
1.40 anton 13121:
1.1 anton 13122:
13123: @item duration of a system clock tick:
13124: @cindex duration of a system clock tick
13125: @cindex clock tick duration
13126: System dependent. With respect to @code{MS}, the time is specified in
13127: microseconds. How well the OS and the hardware implement this, is
13128: another question.
13129:
13130: @item repeatability to be expected from the execution of @code{MS}:
13131: @cindex repeatability to be expected from the execution of @code{MS}
13132: @cindex @code{MS}, repeatability to be expected
13133: System dependent. On Unix, a lot depends on load. If the system is
13134: lightly loaded, and the delay is short enough that Gforth does not get
13135: swapped out, the performance should be acceptable. Under MS-DOS and
13136: other single-tasking systems, it should be good.
13137:
13138: @end table
13139:
13140:
13141: @c ---------------------------------------------------------------------
13142: @node facility-ambcond, , facility-idef, The optional Facility word set
13143: @subsection Ambiguous conditions
13144: @c ---------------------------------------------------------------------
13145: @cindex facility words, ambiguous conditions
13146: @cindex ambiguous conditions, facility words
13147:
13148: @table @i
13149: @item @code{AT-XY} can't be performed on user output device:
13150: @cindex @code{AT-XY} can't be performed on user output device
13151: Largely terminal dependent. No range checks are done on the arguments.
13152: No errors are reported. You may see some garbage appearing, you may see
13153: simply nothing happen.
13154:
13155: @end table
13156:
13157:
13158: @c =====================================================================
13159: @node The optional File-Access word set, The optional Floating-Point word set, The optional Facility word set, ANS conformance
13160: @section The optional File-Access word set
13161: @c =====================================================================
13162: @cindex system documentation, file words
13163: @cindex file words, system documentation
13164:
13165: @menu
13166: * file-idef:: Implementation Defined Options
13167: * file-ambcond:: Ambiguous Conditions
13168: @end menu
13169:
13170: @c ---------------------------------------------------------------------
13171: @node file-idef, file-ambcond, The optional File-Access word set, The optional File-Access word set
13172: @subsection Implementation Defined Options
13173: @c ---------------------------------------------------------------------
13174: @cindex implementation-defined options, file words
13175: @cindex file words, implementation-defined options
13176:
13177: @table @i
13178: @item file access methods used:
13179: @cindex file access methods used
13180: @code{R/O}, @code{R/W} and @code{BIN} work as you would
13181: expect. @code{W/O} translates into the C file opening mode @code{w} (or
13182: @code{wb}): The file is cleared, if it exists, and created, if it does
13183: not (with both @code{open-file} and @code{create-file}). Under Unix
13184: @code{create-file} creates a file with 666 permissions modified by your
13185: umask.
13186:
13187: @item file exceptions:
13188: @cindex file exceptions
13189: The file words do not raise exceptions (except, perhaps, memory access
13190: faults when you pass illegal addresses or file-ids).
13191:
13192: @item file line terminator:
13193: @cindex file line terminator
13194: System-dependent. Gforth uses C's newline character as line
13195: terminator. What the actual character code(s) of this are is
13196: system-dependent.
13197:
13198: @item file name format:
13199: @cindex file name format
13200: System dependent. Gforth just uses the file name format of your OS.
13201:
13202: @item information returned by @code{FILE-STATUS}:
13203: @cindex @code{FILE-STATUS}, returned information
13204: @code{FILE-STATUS} returns the most powerful file access mode allowed
13205: for the file: Either @code{R/O}, @code{W/O} or @code{R/W}. If the file
13206: cannot be accessed, @code{R/O BIN} is returned. @code{BIN} is applicable
13207: along with the returned mode.
13208:
13209: @item input file state after an exception when including source:
13210: @cindex exception when including source
13211: All files that are left via the exception are closed.
13212:
1.29 crook 13213: @item @i{ior} values and meaning:
13214: @cindex @i{ior} values and meaning
1.68 anton 13215: @cindex @i{wior} values and meaning
1.29 crook 13216: The @i{ior}s returned by the file and memory allocation words are
1.1 anton 13217: intended as throw codes. They typically are in the range
13218: -512@minus{}-2047 of OS errors. The mapping from OS error numbers to
1.29 crook 13219: @i{ior}s is -512@minus{}@i{errno}.
1.1 anton 13220:
13221: @item maximum depth of file input nesting:
13222: @cindex maximum depth of file input nesting
13223: @cindex file input nesting, maximum depth
13224: limited by the amount of return stack, locals/TIB stack, and the number
13225: of open files available. This should not give you troubles.
13226:
13227: @item maximum size of input line:
13228: @cindex maximum size of input line
13229: @cindex input line size, maximum
13230: @code{/line}. Currently 255.
13231:
13232: @item methods of mapping block ranges to files:
13233: @cindex mapping block ranges to files
13234: @cindex files containing blocks
13235: @cindex blocks in files
13236: By default, blocks are accessed in the file @file{blocks.fb} in the
13237: current working directory. The file can be switched with @code{USE}.
13238:
13239: @item number of string buffers provided by @code{S"}:
13240: @cindex @code{S"}, number of string buffers
13241: 1
13242:
13243: @item size of string buffer used by @code{S"}:
13244: @cindex @code{S"}, size of string buffer
13245: @code{/line}. currently 255.
13246:
13247: @end table
13248:
13249: @c ---------------------------------------------------------------------
13250: @node file-ambcond, , file-idef, The optional File-Access word set
13251: @subsection Ambiguous conditions
13252: @c ---------------------------------------------------------------------
13253: @cindex file words, ambiguous conditions
13254: @cindex ambiguous conditions, file words
13255:
13256: @table @i
13257: @item attempting to position a file outside its boundaries:
13258: @cindex @code{REPOSITION-FILE}, outside the file's boundaries
13259: @code{REPOSITION-FILE} is performed as usual: Afterwards,
13260: @code{FILE-POSITION} returns the value given to @code{REPOSITION-FILE}.
13261:
13262: @item attempting to read from file positions not yet written:
13263: @cindex reading from file positions not yet written
13264: End-of-file, i.e., zero characters are read and no error is reported.
13265:
1.29 crook 13266: @item @i{file-id} is invalid (@code{INCLUDE-FILE}):
13267: @cindex @code{INCLUDE-FILE}, @i{file-id} is invalid
1.1 anton 13268: An appropriate exception may be thrown, but a memory fault or other
13269: problem is more probable.
13270:
1.29 crook 13271: @item I/O exception reading or closing @i{file-id} (@code{INCLUDE-FILE}, @code{INCLUDED}):
13272: @cindex @code{INCLUDE-FILE}, I/O exception reading or closing @i{file-id}
13273: @cindex @code{INCLUDED}, I/O exception reading or closing @i{file-id}
13274: The @i{ior} produced by the operation, that discovered the problem, is
1.1 anton 13275: thrown.
13276:
13277: @item named file cannot be opened (@code{INCLUDED}):
13278: @cindex @code{INCLUDED}, named file cannot be opened
1.29 crook 13279: The @i{ior} produced by @code{open-file} is thrown.
1.1 anton 13280:
13281: @item requesting an unmapped block number:
13282: @cindex unmapped block numbers
13283: There are no unmapped legal block numbers. On some operating systems,
13284: writing a block with a large number may overflow the file system and
13285: have an error message as consequence.
13286:
13287: @item using @code{source-id} when @code{blk} is non-zero:
13288: @cindex @code{SOURCE-ID}, behaviour when @code{BLK} is non-zero
13289: @code{source-id} performs its function. Typically it will give the id of
13290: the source which loaded the block. (Better ideas?)
13291:
13292: @end table
13293:
13294:
13295: @c =====================================================================
13296: @node The optional Floating-Point word set, The optional Locals word set, The optional File-Access word set, ANS conformance
13297: @section The optional Floating-Point word set
13298: @c =====================================================================
13299: @cindex system documentation, floating-point words
13300: @cindex floating-point words, system documentation
13301:
13302: @menu
13303: * floating-idef:: Implementation Defined Options
13304: * floating-ambcond:: Ambiguous Conditions
13305: @end menu
13306:
13307:
13308: @c ---------------------------------------------------------------------
13309: @node floating-idef, floating-ambcond, The optional Floating-Point word set, The optional Floating-Point word set
13310: @subsection Implementation Defined Options
13311: @c ---------------------------------------------------------------------
13312: @cindex implementation-defined options, floating-point words
13313: @cindex floating-point words, implementation-defined options
13314:
13315: @table @i
13316: @item format and range of floating point numbers:
13317: @cindex format and range of floating point numbers
13318: @cindex floating point numbers, format and range
13319: System-dependent; the @code{double} type of C.
13320:
1.29 crook 13321: @item results of @code{REPRESENT} when @i{float} is out of range:
13322: @cindex @code{REPRESENT}, results when @i{float} is out of range
1.1 anton 13323: System dependent; @code{REPRESENT} is implemented using the C library
13324: function @code{ecvt()} and inherits its behaviour in this respect.
13325:
13326: @item rounding or truncation of floating-point numbers:
13327: @cindex rounding of floating-point numbers
13328: @cindex truncation of floating-point numbers
13329: @cindex floating-point numbers, rounding or truncation
13330: System dependent; the rounding behaviour is inherited from the hosting C
13331: compiler. IEEE-FP-based (i.e., most) systems by default round to
13332: nearest, and break ties by rounding to even (i.e., such that the last
13333: bit of the mantissa is 0).
13334:
13335: @item size of floating-point stack:
13336: @cindex floating-point stack size
13337: @code{s" FLOATING-STACK" environment? drop .} gives the total size of
13338: the floating-point stack (in floats). You can specify this on startup
13339: with the command-line option @code{-f} (@pxref{Invoking Gforth}).
13340:
13341: @item width of floating-point stack:
13342: @cindex floating-point stack width
13343: @code{1 floats}.
13344:
13345: @end table
13346:
13347:
13348: @c ---------------------------------------------------------------------
13349: @node floating-ambcond, , floating-idef, The optional Floating-Point word set
13350: @subsection Ambiguous conditions
13351: @c ---------------------------------------------------------------------
13352: @cindex floating-point words, ambiguous conditions
13353: @cindex ambiguous conditions, floating-point words
13354:
13355: @table @i
13356: @item @code{df@@} or @code{df!} used with an address that is not double-float aligned:
13357: @cindex @code{df@@} or @code{df!} used with an address that is not double-float aligned
13358: System-dependent. Typically results in a @code{-23 THROW} like other
13359: alignment violations.
13360:
13361: @item @code{f@@} or @code{f!} used with an address that is not float aligned:
13362: @cindex @code{f@@} used with an address that is not float aligned
13363: @cindex @code{f!} used with an address that is not float aligned
13364: System-dependent. Typically results in a @code{-23 THROW} like other
13365: alignment violations.
13366:
13367: @item floating-point result out of range:
13368: @cindex floating-point result out of range
1.80 anton 13369: System-dependent. Can result in a @code{-43 throw} (floating point
13370: overflow), @code{-54 throw} (floating point underflow), @code{-41 throw}
13371: (floating point inexact result), @code{-55 THROW} (Floating-point
1.1 anton 13372: unidentified fault), or can produce a special value representing, e.g.,
13373: Infinity.
13374:
13375: @item @code{sf@@} or @code{sf!} used with an address that is not single-float aligned:
13376: @cindex @code{sf@@} or @code{sf!} used with an address that is not single-float aligned
13377: System-dependent. Typically results in an alignment fault like other
13378: alignment violations.
13379:
1.35 anton 13380: @item @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.}):
13381: @cindex @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.})
1.1 anton 13382: The floating-point number is converted into decimal nonetheless.
13383:
13384: @item Both arguments are equal to zero (@code{FATAN2}):
13385: @cindex @code{FATAN2}, both arguments are equal to zero
13386: System-dependent. @code{FATAN2} is implemented using the C library
13387: function @code{atan2()}.
13388:
1.29 crook 13389: @item Using @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero:
13390: @cindex @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero
13391: System-dependent. Anyway, typically the cos of @i{r1} will not be zero
1.1 anton 13392: because of small errors and the tan will be a very large (or very small)
13393: but finite number.
13394:
1.29 crook 13395: @item @i{d} cannot be presented precisely as a float in @code{D>F}:
13396: @cindex @code{D>F}, @i{d} cannot be presented precisely as a float
1.1 anton 13397: The result is rounded to the nearest float.
13398:
13399: @item dividing by zero:
13400: @cindex dividing by zero, floating-point
13401: @cindex floating-point dividing by zero
13402: @cindex floating-point unidentified fault, FP divide-by-zero
1.80 anton 13403: Platform-dependent; can produce an Infinity, NaN, @code{-42 throw}
13404: (floating point divide by zero) or @code{-55 throw} (Floating-point
13405: unidentified fault).
1.1 anton 13406:
13407: @item exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@}):
13408: @cindex exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@})
13409: System dependent. On IEEE-FP based systems the number is converted into
13410: an infinity.
13411:
1.29 crook 13412: @item @i{float}<1 (@code{FACOSH}):
13413: @cindex @code{FACOSH}, @i{float}<1
1.1 anton 13414: @cindex floating-point unidentified fault, @code{FACOSH}
1.80 anton 13415: Platform-dependent; on IEEE-FP systems typically produces a NaN.
1.1 anton 13416:
1.29 crook 13417: @item @i{float}=<-1 (@code{FLNP1}):
13418: @cindex @code{FLNP1}, @i{float}=<-1
1.1 anton 13419: @cindex floating-point unidentified fault, @code{FLNP1}
1.80 anton 13420: Platform-dependent; on IEEE-FP systems typically produces a NaN (or a
13421: negative infinity for @i{float}=-1).
1.1 anton 13422:
1.29 crook 13423: @item @i{float}=<0 (@code{FLN}, @code{FLOG}):
13424: @cindex @code{FLN}, @i{float}=<0
13425: @cindex @code{FLOG}, @i{float}=<0
1.1 anton 13426: @cindex floating-point unidentified fault, @code{FLN} or @code{FLOG}
1.80 anton 13427: Platform-dependent; on IEEE-FP systems typically produces a NaN (or a
13428: negative infinity for @i{float}=0).
1.1 anton 13429:
1.29 crook 13430: @item @i{float}<0 (@code{FASINH}, @code{FSQRT}):
13431: @cindex @code{FASINH}, @i{float}<0
13432: @cindex @code{FSQRT}, @i{float}<0
1.1 anton 13433: @cindex floating-point unidentified fault, @code{FASINH} or @code{FSQRT}
1.80 anton 13434: Platform-dependent; for @code{fsqrt} this typically gives a NaN, for
13435: @code{fasinh} some platforms produce a NaN, others a number (bug in the
13436: C library?).
1.1 anton 13437:
1.29 crook 13438: @item |@i{float}|>1 (@code{FACOS}, @code{FASIN}, @code{FATANH}):
13439: @cindex @code{FACOS}, |@i{float}|>1
13440: @cindex @code{FASIN}, |@i{float}|>1
13441: @cindex @code{FATANH}, |@i{float}|>1
1.1 anton 13442: @cindex floating-point unidentified fault, @code{FACOS}, @code{FASIN} or @code{FATANH}
1.80 anton 13443: Platform-dependent; IEEE-FP systems typically produce a NaN.
1.1 anton 13444:
1.29 crook 13445: @item integer part of float cannot be represented by @i{d} in @code{F>D}:
13446: @cindex @code{F>D}, integer part of float cannot be represented by @i{d}
1.1 anton 13447: @cindex floating-point unidentified fault, @code{F>D}
1.80 anton 13448: Platform-dependent; typically, some double number is produced and no
13449: error is reported.
1.1 anton 13450:
13451: @item string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.}):
13452: @cindex string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.})
1.80 anton 13453: @code{Precision} characters of the numeric output area are used. If
13454: @code{precision} is too high, these words will smash the data or code
13455: close to @code{here}.
1.1 anton 13456: @end table
13457:
13458: @c =====================================================================
13459: @node The optional Locals word set, The optional Memory-Allocation word set, The optional Floating-Point word set, ANS conformance
13460: @section The optional Locals word set
13461: @c =====================================================================
13462: @cindex system documentation, locals words
13463: @cindex locals words, system documentation
13464:
13465: @menu
13466: * locals-idef:: Implementation Defined Options
13467: * locals-ambcond:: Ambiguous Conditions
13468: @end menu
13469:
13470:
13471: @c ---------------------------------------------------------------------
13472: @node locals-idef, locals-ambcond, The optional Locals word set, The optional Locals word set
13473: @subsection Implementation Defined Options
13474: @c ---------------------------------------------------------------------
13475: @cindex implementation-defined options, locals words
13476: @cindex locals words, implementation-defined options
13477:
13478: @table @i
13479: @item maximum number of locals in a definition:
13480: @cindex maximum number of locals in a definition
13481: @cindex locals, maximum number in a definition
13482: @code{s" #locals" environment? drop .}. Currently 15. This is a lower
13483: bound, e.g., on a 32-bit machine there can be 41 locals of up to 8
13484: characters. The number of locals in a definition is bounded by the size
13485: of locals-buffer, which contains the names of the locals.
13486:
13487: @end table
13488:
13489:
13490: @c ---------------------------------------------------------------------
13491: @node locals-ambcond, , locals-idef, The optional Locals word set
13492: @subsection Ambiguous conditions
13493: @c ---------------------------------------------------------------------
13494: @cindex locals words, ambiguous conditions
13495: @cindex ambiguous conditions, locals words
13496:
13497: @table @i
13498: @item executing a named local in interpretation state:
13499: @cindex local in interpretation state
13500: @cindex Interpreting a compile-only word, for a local
13501: Locals have no interpretation semantics. If you try to perform the
13502: interpretation semantics, you will get a @code{-14 throw} somewhere
13503: (Interpreting a compile-only word). If you perform the compilation
13504: semantics, the locals access will be compiled (irrespective of state).
13505:
1.29 crook 13506: @item @i{name} not defined by @code{VALUE} or @code{(LOCAL)} (@code{TO}):
1.1 anton 13507: @cindex name not defined by @code{VALUE} or @code{(LOCAL)} used by @code{TO}
13508: @cindex @code{TO} on non-@code{VALUE}s and non-locals
13509: @cindex Invalid name argument, @code{TO}
13510: @code{-32 throw} (Invalid name argument)
13511:
13512: @end table
13513:
13514:
13515: @c =====================================================================
13516: @node The optional Memory-Allocation word set, The optional Programming-Tools word set, The optional Locals word set, ANS conformance
13517: @section The optional Memory-Allocation word set
13518: @c =====================================================================
13519: @cindex system documentation, memory-allocation words
13520: @cindex memory-allocation words, system documentation
13521:
13522: @menu
13523: * memory-idef:: Implementation Defined Options
13524: @end menu
13525:
13526:
13527: @c ---------------------------------------------------------------------
13528: @node memory-idef, , The optional Memory-Allocation word set, The optional Memory-Allocation word set
13529: @subsection Implementation Defined Options
13530: @c ---------------------------------------------------------------------
13531: @cindex implementation-defined options, memory-allocation words
13532: @cindex memory-allocation words, implementation-defined options
13533:
13534: @table @i
1.29 crook 13535: @item values and meaning of @i{ior}:
13536: @cindex @i{ior} values and meaning
13537: The @i{ior}s returned by the file and memory allocation words are
1.1 anton 13538: intended as throw codes. They typically are in the range
13539: -512@minus{}-2047 of OS errors. The mapping from OS error numbers to
1.29 crook 13540: @i{ior}s is -512@minus{}@i{errno}.
1.1 anton 13541:
13542: @end table
13543:
13544: @c =====================================================================
13545: @node The optional Programming-Tools word set, The optional Search-Order word set, The optional Memory-Allocation word set, ANS conformance
13546: @section The optional Programming-Tools word set
13547: @c =====================================================================
13548: @cindex system documentation, programming-tools words
13549: @cindex programming-tools words, system documentation
13550:
13551: @menu
13552: * programming-idef:: Implementation Defined Options
13553: * programming-ambcond:: Ambiguous Conditions
13554: @end menu
13555:
13556:
13557: @c ---------------------------------------------------------------------
13558: @node programming-idef, programming-ambcond, The optional Programming-Tools word set, The optional Programming-Tools word set
13559: @subsection Implementation Defined Options
13560: @c ---------------------------------------------------------------------
13561: @cindex implementation-defined options, programming-tools words
13562: @cindex programming-tools words, implementation-defined options
13563:
13564: @table @i
13565: @item ending sequence for input following @code{;CODE} and @code{CODE}:
13566: @cindex @code{;CODE} ending sequence
13567: @cindex @code{CODE} ending sequence
13568: @code{END-CODE}
13569:
13570: @item manner of processing input following @code{;CODE} and @code{CODE}:
13571: @cindex @code{;CODE}, processing input
13572: @cindex @code{CODE}, processing input
13573: The @code{ASSEMBLER} vocabulary is pushed on the search order stack, and
13574: the input is processed by the text interpreter, (starting) in interpret
13575: state.
13576:
13577: @item search order capability for @code{EDITOR} and @code{ASSEMBLER}:
13578: @cindex @code{ASSEMBLER}, search order capability
13579: The ANS Forth search order word set.
13580:
13581: @item source and format of display by @code{SEE}:
13582: @cindex @code{SEE}, source and format of output
1.80 anton 13583: The source for @code{see} is the executable code used by the inner
1.1 anton 13584: interpreter. The current @code{see} tries to output Forth source code
1.80 anton 13585: (and on some platforms, assembly code for primitives) as well as
13586: possible.
1.1 anton 13587:
13588: @end table
13589:
13590: @c ---------------------------------------------------------------------
13591: @node programming-ambcond, , programming-idef, The optional Programming-Tools word set
13592: @subsection Ambiguous conditions
13593: @c ---------------------------------------------------------------------
13594: @cindex programming-tools words, ambiguous conditions
13595: @cindex ambiguous conditions, programming-tools words
13596:
13597: @table @i
13598:
1.21 crook 13599: @item deleting the compilation word list (@code{FORGET}):
13600: @cindex @code{FORGET}, deleting the compilation word list
1.1 anton 13601: Not implemented (yet).
13602:
1.29 crook 13603: @item fewer than @i{u}+1 items on the control-flow stack (@code{CS-PICK}, @code{CS-ROLL}):
13604: @cindex @code{CS-PICK}, fewer than @i{u}+1 items on the control flow-stack
13605: @cindex @code{CS-ROLL}, fewer than @i{u}+1 items on the control flow-stack
1.1 anton 13606: @cindex control-flow stack underflow
13607: This typically results in an @code{abort"} with a descriptive error
13608: message (may change into a @code{-22 throw} (Control structure mismatch)
13609: in the future). You may also get a memory access error. If you are
13610: unlucky, this ambiguous condition is not caught.
13611:
1.29 crook 13612: @item @i{name} can't be found (@code{FORGET}):
13613: @cindex @code{FORGET}, @i{name} can't be found
1.1 anton 13614: Not implemented (yet).
13615:
1.29 crook 13616: @item @i{name} not defined via @code{CREATE}:
13617: @cindex @code{;CODE}, @i{name} not defined via @code{CREATE}
1.1 anton 13618: @code{;CODE} behaves like @code{DOES>} in this respect, i.e., it changes
13619: the execution semantics of the last defined word no matter how it was
13620: defined.
13621:
13622: @item @code{POSTPONE} applied to @code{[IF]}:
13623: @cindex @code{POSTPONE} applied to @code{[IF]}
13624: @cindex @code{[IF]} and @code{POSTPONE}
13625: After defining @code{: X POSTPONE [IF] ; IMMEDIATE}. @code{X} is
13626: equivalent to @code{[IF]}.
13627:
13628: @item reaching the end of the input source before matching @code{[ELSE]} or @code{[THEN]}:
13629: @cindex @code{[IF]}, end of the input source before matching @code{[ELSE]} or @code{[THEN]}
13630: Continue in the same state of conditional compilation in the next outer
13631: input source. Currently there is no warning to the user about this.
13632:
13633: @item removing a needed definition (@code{FORGET}):
13634: @cindex @code{FORGET}, removing a needed definition
13635: Not implemented (yet).
13636:
13637: @end table
13638:
13639:
13640: @c =====================================================================
13641: @node The optional Search-Order word set, , The optional Programming-Tools word set, ANS conformance
13642: @section The optional Search-Order word set
13643: @c =====================================================================
13644: @cindex system documentation, search-order words
13645: @cindex search-order words, system documentation
13646:
13647: @menu
13648: * search-idef:: Implementation Defined Options
13649: * search-ambcond:: Ambiguous Conditions
13650: @end menu
13651:
13652:
13653: @c ---------------------------------------------------------------------
13654: @node search-idef, search-ambcond, The optional Search-Order word set, The optional Search-Order word set
13655: @subsection Implementation Defined Options
13656: @c ---------------------------------------------------------------------
13657: @cindex implementation-defined options, search-order words
13658: @cindex search-order words, implementation-defined options
13659:
13660: @table @i
13661: @item maximum number of word lists in search order:
13662: @cindex maximum number of word lists in search order
13663: @cindex search order, maximum depth
13664: @code{s" wordlists" environment? drop .}. Currently 16.
13665:
13666: @item minimum search order:
13667: @cindex minimum search order
13668: @cindex search order, minimum
13669: @code{root root}.
13670:
13671: @end table
13672:
13673: @c ---------------------------------------------------------------------
13674: @node search-ambcond, , search-idef, The optional Search-Order word set
13675: @subsection Ambiguous conditions
13676: @c ---------------------------------------------------------------------
13677: @cindex search-order words, ambiguous conditions
13678: @cindex ambiguous conditions, search-order words
13679:
13680: @table @i
1.21 crook 13681: @item changing the compilation word list (during compilation):
13682: @cindex changing the compilation word list (during compilation)
13683: @cindex compilation word list, change before definition ends
13684: The word is entered into the word list that was the compilation word list
1.1 anton 13685: at the start of the definition. Any changes to the name field (e.g.,
13686: @code{immediate}) or the code field (e.g., when executing @code{DOES>})
13687: are applied to the latest defined word (as reported by @code{last} or
1.21 crook 13688: @code{lastxt}), if possible, irrespective of the compilation word list.
1.1 anton 13689:
13690: @item search order empty (@code{previous}):
13691: @cindex @code{previous}, search order empty
1.26 crook 13692: @cindex vocstack empty, @code{previous}
1.1 anton 13693: @code{abort" Vocstack empty"}.
13694:
13695: @item too many word lists in search order (@code{also}):
13696: @cindex @code{also}, too many word lists in search order
1.26 crook 13697: @cindex vocstack full, @code{also}
1.1 anton 13698: @code{abort" Vocstack full"}.
13699:
13700: @end table
13701:
13702: @c ***************************************************************
1.65 anton 13703: @node Standard vs Extensions, Model, ANS conformance, Top
13704: @chapter Should I use Gforth extensions?
13705: @cindex Gforth extensions
13706:
13707: As you read through the rest of this manual, you will see documentation
13708: for @i{Standard} words, and documentation for some appealing Gforth
13709: @i{extensions}. You might ask yourself the question: @i{``Should I
13710: restrict myself to the standard, or should I use the extensions?''}
13711:
13712: The answer depends on the goals you have for the program you are working
13713: on:
13714:
13715: @itemize @bullet
13716:
13717: @item Is it just for yourself or do you want to share it with others?
13718:
13719: @item
13720: If you want to share it, do the others all use Gforth?
13721:
13722: @item
13723: If it is just for yourself, do you want to restrict yourself to Gforth?
13724:
13725: @end itemize
13726:
13727: If restricting the program to Gforth is ok, then there is no reason not
13728: to use extensions. It is still a good idea to keep to the standard
13729: where it is easy, in case you want to reuse these parts in another
13730: program that you want to be portable.
13731:
13732: If you want to be able to port the program to other Forth systems, there
13733: are the following points to consider:
13734:
13735: @itemize @bullet
13736:
13737: @item
13738: Most Forth systems that are being maintained support the ANS Forth
13739: standard. So if your program complies with the standard, it will be
13740: portable among many systems.
13741:
13742: @item
13743: A number of the Gforth extensions can be implemented in ANS Forth using
13744: public-domain files provided in the @file{compat/} directory. These are
13745: mentioned in the text in passing. There is no reason not to use these
13746: extensions, your program will still be ANS Forth compliant; just include
13747: the appropriate compat files with your program.
13748:
13749: @item
13750: The tool @file{ans-report.fs} (@pxref{ANS Report}) makes it easy to
13751: analyse your program and determine what non-Standard words it relies
13752: upon. However, it does not check whether you use standard words in a
13753: non-standard way.
13754:
13755: @item
13756: Some techniques are not standardized by ANS Forth, and are hard or
13757: impossible to implement in a standard way, but can be implemented in
13758: most Forth systems easily, and usually in similar ways (e.g., accessing
13759: word headers). Forth has a rich historical precedent for programmers
13760: taking advantage of implementation-dependent features of their tools
13761: (for example, relying on a knowledge of the dictionary
13762: structure). Sometimes these techniques are necessary to extract every
13763: last bit of performance from the hardware, sometimes they are just a
13764: programming shorthand.
13765:
13766: @item
13767: Does using a Gforth extension save more work than the porting this part
13768: to other Forth systems (if any) will cost?
13769:
13770: @item
13771: Is the additional functionality worth the reduction in portability and
13772: the additional porting problems?
13773:
13774: @end itemize
13775:
13776: In order to perform these consideratios, you need to know what's
13777: standard and what's not. This manual generally states if something is
1.81 anton 13778: non-standard, but the authoritative source is the
13779: @uref{http://www.taygeta.com/forth/dpans.html,standard document}.
1.65 anton 13780: Appendix A of the Standard (@var{Rationale}) provides a valuable insight
13781: into the thought processes of the technical committee.
13782:
13783: Note also that portability between Forth systems is not the only
13784: portability issue; there is also the issue of portability between
13785: different platforms (processor/OS combinations).
13786:
13787: @c ***************************************************************
13788: @node Model, Integrating Gforth, Standard vs Extensions, Top
1.1 anton 13789: @chapter Model
13790:
13791: This chapter has yet to be written. It will contain information, on
13792: which internal structures you can rely.
13793:
13794: @c ***************************************************************
13795: @node Integrating Gforth, Emacs and Gforth, Model, Top
13796: @chapter Integrating Gforth into C programs
13797:
13798: This is not yet implemented.
13799:
13800: Several people like to use Forth as scripting language for applications
13801: that are otherwise written in C, C++, or some other language.
13802:
13803: The Forth system ATLAST provides facilities for embedding it into
13804: applications; unfortunately it has several disadvantages: most
13805: importantly, it is not based on ANS Forth, and it is apparently dead
13806: (i.e., not developed further and not supported). The facilities
1.21 crook 13807: provided by Gforth in this area are inspired by ATLAST's facilities, so
1.1 anton 13808: making the switch should not be hard.
13809:
13810: We also tried to design the interface such that it can easily be
13811: implemented by other Forth systems, so that we may one day arrive at a
13812: standardized interface. Such a standard interface would allow you to
13813: replace the Forth system without having to rewrite C code.
13814:
13815: You embed the Gforth interpreter by linking with the library
13816: @code{libgforth.a} (give the compiler the option @code{-lgforth}). All
13817: global symbols in this library that belong to the interface, have the
13818: prefix @code{forth_}. (Global symbols that are used internally have the
13819: prefix @code{gforth_}).
13820:
13821: You can include the declarations of Forth types and the functions and
13822: variables of the interface with @code{#include <forth.h>}.
13823:
13824: Types.
13825:
13826: Variables.
13827:
13828: Data and FP Stack pointer. Area sizes.
13829:
13830: functions.
13831:
13832: forth_init(imagefile)
13833: forth_evaluate(string) exceptions?
13834: forth_goto(address) (or forth_execute(xt)?)
13835: forth_continue() (a corountining mechanism)
13836:
13837: Adding primitives.
13838:
13839: No checking.
13840:
13841: Signals?
13842:
13843: Accessing the Stacks
13844:
1.26 crook 13845: @c ******************************************************************
1.1 anton 13846: @node Emacs and Gforth, Image Files, Integrating Gforth, Top
13847: @chapter Emacs and Gforth
13848: @cindex Emacs and Gforth
13849:
13850: @cindex @file{gforth.el}
13851: @cindex @file{forth.el}
13852: @cindex Rydqvist, Goran
1.107 dvdkhlng 13853: @cindex Kuehling, David
1.1 anton 13854: @cindex comment editing commands
13855: @cindex @code{\}, editing with Emacs
13856: @cindex debug tracer editing commands
13857: @cindex @code{~~}, removal with Emacs
13858: @cindex Forth mode in Emacs
1.107 dvdkhlng 13859:
1.1 anton 13860: Gforth comes with @file{gforth.el}, an improved version of
13861: @file{forth.el} by Goran Rydqvist (included in the TILE package). The
1.26 crook 13862: improvements are:
13863:
13864: @itemize @bullet
13865: @item
1.107 dvdkhlng 13866: A better handling of indentation.
13867: @item
13868: A custom hilighting engine for Forth-code.
1.26 crook 13869: @item
13870: Comment paragraph filling (@kbd{M-q})
13871: @item
13872: Commenting (@kbd{C-x \}) and uncommenting (@kbd{C-u C-x \}) of regions
13873: @item
13874: Removal of debugging tracers (@kbd{C-x ~}, @pxref{Debugging}).
1.41 anton 13875: @item
13876: Support of the @code{info-lookup} feature for looking up the
13877: documentation of a word.
1.107 dvdkhlng 13878: @item
13879: Support for reading and writing blocks files.
1.26 crook 13880: @end itemize
13881:
1.107 dvdkhlng 13882: To get a basic description of these features, enter Forth mode and
13883: type @kbd{C-h m}.
1.1 anton 13884:
13885: @cindex source location of error or debugging output in Emacs
13886: @cindex error output, finding the source location in Emacs
13887: @cindex debugging output, finding the source location in Emacs
13888: In addition, Gforth supports Emacs quite well: The source code locations
13889: given in error messages, debugging output (from @code{~~}) and failed
13890: assertion messages are in the right format for Emacs' compilation mode
13891: (@pxref{Compilation, , Running Compilations under Emacs, emacs, Emacs
13892: Manual}) so the source location corresponding to an error or other
13893: message is only a few keystrokes away (@kbd{C-x `} for the next error,
13894: @kbd{C-c C-c} for the error under the cursor).
13895:
1.107 dvdkhlng 13896: @cindex viewing the documentation of a word in Emacs
13897: @cindex context-sensitive help
13898: Moreover, for words documented in this manual, you can look up the
13899: glossary entry quickly by using @kbd{C-h TAB}
13900: (@code{info-lookup-symbol}, @pxref{Documentation, ,Documentation
13901: Commands, emacs, Emacs Manual}). This feature requires Emacs 20.3 or
13902: later and does not work for words containing @code{:}.
13903:
13904: @menu
13905: * Installing gforth.el:: Making Emacs aware of Forth.
13906: * Emacs Tags:: Viewing the source of a word in Emacs.
13907: * Hilighting:: Making Forth code look prettier.
13908: * Auto-Indentation:: Customizing auto-indentation.
13909: * Blocks Files:: Reading and writing blocks files.
13910: @end menu
13911:
13912: @c ----------------------------------
1.109 ! anton 13913: @node Installing gforth.el, Emacs Tags, Emacs and Gforth, Emacs and Gforth
1.107 dvdkhlng 13914: @section Installing gforth.el
13915: @cindex @file{.emacs}
13916: @cindex @file{gforth.el}, installation
13917: To make the features from @file{gforth.el} available in Emacs, add
13918: the following lines to your @file{.emacs} file:
13919:
13920: @example
13921: (autoload 'forth-mode "gforth.el")
13922: (setq auto-mode-alist (cons '("\\.fs\\'" . forth-mode)
13923: auto-mode-alist))
13924: (autoload 'forth-block-mode "gforth.el")
13925: (setq auto-mode-alist (cons '("\\.fb\\'" . forth-block-mode)
13926: auto-mode-alist))
13927: (add-hook 'forth-mode-hook (function (lambda ()
13928: ;; customize variables here:
13929: (setq forth-indent-level 4)
13930: (setq forth-minor-indent-level 2)
13931: (setq forth-hilight-level 3)
13932: ;;; ...
13933: )))
13934: @end example
13935:
13936: @c ----------------------------------
13937: @node Emacs Tags, Hilighting, Installing gforth.el, Emacs and Gforth
13938: @section Emacs Tags
1.1 anton 13939: @cindex @file{TAGS} file
13940: @cindex @file{etags.fs}
13941: @cindex viewing the source of a word in Emacs
1.43 anton 13942: @cindex @code{require}, placement in files
13943: @cindex @code{include}, placement in files
1.107 dvdkhlng 13944: If you @code{require} @file{etags.fs}, a new @file{TAGS} file will be
13945: produced (@pxref{Tags, , Tags Tables, emacs, Emacs Manual}) that
1.1 anton 13946: contains the definitions of all words defined afterwards. You can then
1.107 dvdkhlng 13947: find the source for a word using @kbd{M-.}. Note that Emacs can use
1.1 anton 13948: several tags files at the same time (e.g., one for the Gforth sources
13949: and one for your program, @pxref{Select Tags Table,,Selecting a Tags
13950: Table,emacs, Emacs Manual}). The TAGS file for the preloaded words is
13951: @file{$(datadir)/gforth/$(VERSION)/TAGS} (e.g.,
1.43 anton 13952: @file{/usr/local/share/gforth/0.2.0/TAGS}). To get the best behaviour
13953: with @file{etags.fs}, you should avoid putting definitions both before
13954: and after @code{require} etc., otherwise you will see the same file
13955: visited several times by commands like @code{tags-search}.
1.1 anton 13956:
1.107 dvdkhlng 13957: @c ----------------------------------
13958: @node Hilighting, Auto-Indentation, Emacs Tags, Emacs and Gforth
13959: @section Hilighting
13960: @cindex hilighting Forth code in Emacs
13961: @cindex highlighting Forth code in Emacs
13962: @file{gforth.el} comes with a custom source hilighting engine. When
13963: you open a file in @code{forth-mode}, it will be completely parsed,
13964: assigning faces to keywords, comments, strings etc. While you edit
13965: the file, modified regions get parsed and updated on-the-fly.
13966:
13967: Use the variable `forth-hilight-level' to change the level of
13968: decoration from 0 (no hilighting at all) to 3 (the default). Even if
13969: you set the hilighting level to 0, the parser will still work in the
13970: background, collecting information about whether regions of text are
13971: ``compiled'' or ``interpreted''. Those information are required for
13972: auto-indentation to work properly. Set `forth-disable-parser' to
13973: non-nil if your computer is too slow to handle parsing. This will
13974: have an impact on the smartness of the auto-indentation engine,
13975: though.
13976:
13977: Sometimes Forth sources define new features that should be hilighted,
13978: new control structures, defining-words etc. You can use the variable
13979: `forth-custom-words' to make @code{forth-mode} hilight additional
13980: words and constructs. See the docstring of `forth-words' for details
13981: (in Emacs, type @kbd{C-h v forth-words}).
13982:
13983: `forth-custom-words' is meant to be customized in your
13984: @file{.emacs} file. To customize hilighing in a file-specific manner,
13985: set `forth-local-words' in a local-variables section at the end of
13986: your source file (@pxref{Local Variables in Files,, Variables, emacs, Emacs Manual}).
13987:
13988: Example:
13989: @example
13990: 0 [IF]
13991: Local Variables:
13992: forth-local-words:
13993: ((("t:") definition-starter (font-lock-keyword-face . 1)
13994: "[ \t\n]" t name (font-lock-function-name-face . 3))
13995: ((";t") definition-ender (font-lock-keyword-face . 1)))
13996: End:
13997: [THEN]
13998: @end example
13999:
14000: @c ----------------------------------
14001: @node Auto-Indentation, Blocks Files, Hilighting, Emacs and Gforth
14002: @section Auto-Indentation
14003: @cindex auto-indentation of Forth code in Emacs
14004: @cindex indentation of Forth code in Emacs
14005: @code{forth-mode} automatically tries to indent lines in a smart way,
14006: whenever you type @key{TAB} or break a line with @kbd{C-m}.
14007:
14008: Simple customization can be achieved by setting
14009: `forth-indent-level' and `forth-minor-indent-level' in your
14010: @file{.emacs} file. For historical reasons @file{gforth.el} indents
14011: per default by multiples of 4 columns. To use the more traditional
14012: 3-column indentation, add the following lines to your @file{.emacs}:
14013:
14014: @example
14015: (add-hook 'forth-mode-hook (function (lambda ()
14016: ;; customize variables here:
14017: (setq forth-indent-level 3)
14018: (setq forth-minor-indent-level 1)
14019: )))
14020: @end example
14021:
14022: If you want indentation to recognize non-default words, customize it
14023: by setting `forth-custom-indent-words' in your @file{.emacs}. See the
14024: docstring of `forth-indent-words' for details (in Emacs, type @kbd{C-h
14025: v forth-indent-words}).
14026:
14027: To customize indentation in a file-specific manner, set
14028: `forth-local-indent-words' in a local-variables section at the end of
14029: your source file (@pxref{Local Variables in Files, Variables,,emacs,
14030: Emacs Manual}).
14031:
14032: Example:
14033: @example
14034: 0 [IF]
14035: Local Variables:
14036: forth-local-indent-words:
14037: ((("t:") (0 . 2) (0 . 2))
14038: ((";t") (-2 . 0) (0 . -2)))
14039: End:
14040: [THEN]
14041: @end example
14042:
14043: @c ----------------------------------
1.109 ! anton 14044: @node Blocks Files, , Auto-Indentation, Emacs and Gforth
1.107 dvdkhlng 14045: @section Blocks Files
14046: @cindex blocks files, use with Emacs
14047: @code{forth-mode} Autodetects blocks files by checking whether the
14048: length of the first line exceeds 1023 characters. It then tries to
14049: convert the file into normal text format. When you save the file, it
14050: will be written to disk as normal stream-source file.
14051:
14052: If you want to write blocks files, use @code{forth-blocks-mode}. It
14053: inherits all the features from @code{forth-mode}, plus some additions:
1.41 anton 14054:
1.107 dvdkhlng 14055: @itemize @bullet
14056: @item
14057: Files are written to disk in blocks file format.
14058: @item
14059: Screen numbers are displayed in the mode line (enumerated beginning
14060: with the value of `forth-block-base')
14061: @item
14062: Warnings are displayed when lines exceed 64 characters.
14063: @item
14064: The beginning of the currently edited block is marked with an
14065: overlay-arrow.
14066: @end itemize
1.41 anton 14067:
1.107 dvdkhlng 14068: There are some restrictions you should be aware of. When you open a
14069: blocks file that contains tabulator or newline characters, these
14070: characters will be translated into spaces when the file is written
14071: back to disk. If tabs or newlines are encountered during blocks file
14072: reading, an error is output to the echo area. So have a look at the
14073: `*Messages*' buffer, when Emacs' bell rings during reading.
1.1 anton 14074:
1.107 dvdkhlng 14075: Please consult the docstring of @code{forth-blocks-mode} for more
14076: information by typing @kbd{C-h v forth-blocks-mode}).
1.1 anton 14077:
1.26 crook 14078: @c ******************************************************************
1.1 anton 14079: @node Image Files, Engine, Emacs and Gforth, Top
14080: @chapter Image Files
1.26 crook 14081: @cindex image file
14082: @cindex @file{.fi} files
1.1 anton 14083: @cindex precompiled Forth code
14084: @cindex dictionary in persistent form
14085: @cindex persistent form of dictionary
14086:
14087: An image file is a file containing an image of the Forth dictionary,
14088: i.e., compiled Forth code and data residing in the dictionary. By
14089: convention, we use the extension @code{.fi} for image files.
14090:
14091: @menu
1.18 anton 14092: * Image Licensing Issues:: Distribution terms for images.
14093: * Image File Background:: Why have image files?
1.67 anton 14094: * Non-Relocatable Image Files:: don't always work.
1.18 anton 14095: * Data-Relocatable Image Files:: are better.
1.67 anton 14096: * Fully Relocatable Image Files:: better yet.
1.18 anton 14097: * Stack and Dictionary Sizes:: Setting the default sizes for an image.
1.29 crook 14098: * Running Image Files:: @code{gforth -i @i{file}} or @i{file}.
1.18 anton 14099: * Modifying the Startup Sequence:: and turnkey applications.
1.1 anton 14100: @end menu
14101:
1.18 anton 14102: @node Image Licensing Issues, Image File Background, Image Files, Image Files
14103: @section Image Licensing Issues
14104: @cindex license for images
14105: @cindex image license
14106:
14107: An image created with @code{gforthmi} (@pxref{gforthmi}) or
14108: @code{savesystem} (@pxref{Non-Relocatable Image Files}) includes the
14109: original image; i.e., according to copyright law it is a derived work of
14110: the original image.
14111:
14112: Since Gforth is distributed under the GNU GPL, the newly created image
14113: falls under the GNU GPL, too. In particular, this means that if you
14114: distribute the image, you have to make all of the sources for the image
14115: available, including those you wrote. For details see @ref{License, ,
14116: GNU General Public License (Section 3)}.
14117:
14118: If you create an image with @code{cross} (@pxref{cross.fs}), the image
14119: contains only code compiled from the sources you gave it; if none of
14120: these sources is under the GPL, the terms discussed above do not apply
14121: to the image. However, if your image needs an engine (a gforth binary)
14122: that is under the GPL, you should make sure that you distribute both in
14123: a way that is at most a @emph{mere aggregation}, if you don't want the
14124: terms of the GPL to apply to the image.
14125:
14126: @node Image File Background, Non-Relocatable Image Files, Image Licensing Issues, Image Files
1.1 anton 14127: @section Image File Background
14128: @cindex image file background
14129:
1.80 anton 14130: Gforth consists not only of primitives (in the engine), but also of
1.1 anton 14131: definitions written in Forth. Since the Forth compiler itself belongs to
14132: those definitions, it is not possible to start the system with the
1.80 anton 14133: engine and the Forth source alone. Therefore we provide the Forth
1.26 crook 14134: code as an image file in nearly executable form. When Gforth starts up,
14135: a C routine loads the image file into memory, optionally relocates the
14136: addresses, then sets up the memory (stacks etc.) according to
14137: information in the image file, and (finally) starts executing Forth
14138: code.
1.1 anton 14139:
14140: The image file variants represent different compromises between the
14141: goals of making it easy to generate image files and making them
14142: portable.
14143:
14144: @cindex relocation at run-time
1.26 crook 14145: Win32Forth 3.4 and Mitch Bradley's @code{cforth} use relocation at
1.1 anton 14146: run-time. This avoids many of the complications discussed below (image
14147: files are data relocatable without further ado), but costs performance
14148: (one addition per memory access).
14149:
14150: @cindex relocation at load-time
1.26 crook 14151: By contrast, the Gforth loader performs relocation at image load time. The
14152: loader also has to replace tokens that represent primitive calls with the
1.1 anton 14153: appropriate code-field addresses (or code addresses in the case of
14154: direct threading).
14155:
14156: There are three kinds of image files, with different degrees of
14157: relocatability: non-relocatable, data-relocatable, and fully relocatable
14158: image files.
14159:
14160: @cindex image file loader
14161: @cindex relocating loader
14162: @cindex loader for image files
14163: These image file variants have several restrictions in common; they are
14164: caused by the design of the image file loader:
14165:
14166: @itemize @bullet
14167: @item
14168: There is only one segment; in particular, this means, that an image file
14169: cannot represent @code{ALLOCATE}d memory chunks (and pointers to
1.26 crook 14170: them). The contents of the stacks are not represented, either.
1.1 anton 14171:
14172: @item
14173: The only kinds of relocation supported are: adding the same offset to
14174: all cells that represent data addresses; and replacing special tokens
14175: with code addresses or with pieces of machine code.
14176:
14177: If any complex computations involving addresses are performed, the
14178: results cannot be represented in the image file. Several applications that
14179: use such computations come to mind:
14180: @itemize @minus
14181: @item
14182: Hashing addresses (or data structures which contain addresses) for table
14183: lookup. If you use Gforth's @code{table}s or @code{wordlist}s for this
14184: purpose, you will have no problem, because the hash tables are
14185: recomputed automatically when the system is started. If you use your own
14186: hash tables, you will have to do something similar.
14187:
14188: @item
14189: There's a cute implementation of doubly-linked lists that uses
14190: @code{XOR}ed addresses. You could represent such lists as singly-linked
14191: in the image file, and restore the doubly-linked representation on
14192: startup.@footnote{In my opinion, though, you should think thrice before
14193: using a doubly-linked list (whatever implementation).}
14194:
14195: @item
14196: The code addresses of run-time routines like @code{docol:} cannot be
14197: represented in the image file (because their tokens would be replaced by
14198: machine code in direct threaded implementations). As a workaround,
14199: compute these addresses at run-time with @code{>code-address} from the
14200: executions tokens of appropriate words (see the definitions of
1.80 anton 14201: @code{docol:} and friends in @file{kernel/getdoers.fs}).
1.1 anton 14202:
14203: @item
14204: On many architectures addresses are represented in machine code in some
14205: shifted or mangled form. You cannot put @code{CODE} words that contain
14206: absolute addresses in this form in a relocatable image file. Workarounds
14207: are representing the address in some relative form (e.g., relative to
14208: the CFA, which is present in some register), or loading the address from
14209: a place where it is stored in a non-mangled form.
14210: @end itemize
14211: @end itemize
14212:
14213: @node Non-Relocatable Image Files, Data-Relocatable Image Files, Image File Background, Image Files
14214: @section Non-Relocatable Image Files
14215: @cindex non-relocatable image files
1.26 crook 14216: @cindex image file, non-relocatable
1.1 anton 14217:
14218: These files are simple memory dumps of the dictionary. They are specific
14219: to the executable (i.e., @file{gforth} file) they were created
14220: with. What's worse, they are specific to the place on which the
14221: dictionary resided when the image was created. Now, there is no
14222: guarantee that the dictionary will reside at the same place the next
14223: time you start Gforth, so there's no guarantee that a non-relocatable
14224: image will work the next time (Gforth will complain instead of crashing,
14225: though).
14226:
14227: You can create a non-relocatable image file with
14228:
1.44 crook 14229:
1.1 anton 14230: doc-savesystem
14231:
1.44 crook 14232:
1.1 anton 14233: @node Data-Relocatable Image Files, Fully Relocatable Image Files, Non-Relocatable Image Files, Image Files
14234: @section Data-Relocatable Image Files
14235: @cindex data-relocatable image files
1.26 crook 14236: @cindex image file, data-relocatable
1.1 anton 14237:
14238: These files contain relocatable data addresses, but fixed code addresses
14239: (instead of tokens). They are specific to the executable (i.e.,
14240: @file{gforth} file) they were created with. For direct threading on some
14241: architectures (e.g., the i386), data-relocatable images do not work. You
14242: get a data-relocatable image, if you use @file{gforthmi} with a
14243: Gforth binary that is not doubly indirect threaded (@pxref{Fully
14244: Relocatable Image Files}).
14245:
14246: @node Fully Relocatable Image Files, Stack and Dictionary Sizes, Data-Relocatable Image Files, Image Files
14247: @section Fully Relocatable Image Files
14248: @cindex fully relocatable image files
1.26 crook 14249: @cindex image file, fully relocatable
1.1 anton 14250:
14251: @cindex @file{kern*.fi}, relocatability
14252: @cindex @file{gforth.fi}, relocatability
14253: These image files have relocatable data addresses, and tokens for code
14254: addresses. They can be used with different binaries (e.g., with and
14255: without debugging) on the same machine, and even across machines with
14256: the same data formats (byte order, cell size, floating point
14257: format). However, they are usually specific to the version of Gforth
14258: they were created with. The files @file{gforth.fi} and @file{kernl*.fi}
14259: are fully relocatable.
14260:
14261: There are two ways to create a fully relocatable image file:
14262:
14263: @menu
1.29 crook 14264: * gforthmi:: The normal way
1.1 anton 14265: * cross.fs:: The hard way
14266: @end menu
14267:
14268: @node gforthmi, cross.fs, Fully Relocatable Image Files, Fully Relocatable Image Files
14269: @subsection @file{gforthmi}
14270: @cindex @file{comp-i.fs}
14271: @cindex @file{gforthmi}
14272:
14273: You will usually use @file{gforthmi}. If you want to create an
1.29 crook 14274: image @i{file} that contains everything you would load by invoking
14275: Gforth with @code{gforth @i{options}}, you simply say:
1.1 anton 14276: @example
1.29 crook 14277: gforthmi @i{file} @i{options}
1.1 anton 14278: @end example
14279:
14280: E.g., if you want to create an image @file{asm.fi} that has the file
14281: @file{asm.fs} loaded in addition to the usual stuff, you could do it
14282: like this:
14283:
14284: @example
14285: gforthmi asm.fi asm.fs
14286: @end example
14287:
1.27 crook 14288: @file{gforthmi} is implemented as a sh script and works like this: It
14289: produces two non-relocatable images for different addresses and then
14290: compares them. Its output reflects this: first you see the output (if
1.62 crook 14291: any) of the two Gforth invocations that produce the non-relocatable image
1.27 crook 14292: files, then you see the output of the comparing program: It displays the
14293: offset used for data addresses and the offset used for code addresses;
1.1 anton 14294: moreover, for each cell that cannot be represented correctly in the
1.44 crook 14295: image files, it displays a line like this:
1.1 anton 14296:
14297: @example
14298: 78DC BFFFFA50 BFFFFA40
14299: @end example
14300:
14301: This means that at offset $78dc from @code{forthstart}, one input image
14302: contains $bffffa50, and the other contains $bffffa40. Since these cells
14303: cannot be represented correctly in the output image, you should examine
14304: these places in the dictionary and verify that these cells are dead
14305: (i.e., not read before they are written).
1.39 anton 14306:
14307: @cindex --application, @code{gforthmi} option
14308: If you insert the option @code{--application} in front of the image file
14309: name, you will get an image that uses the @code{--appl-image} option
14310: instead of the @code{--image-file} option (@pxref{Invoking
14311: Gforth}). When you execute such an image on Unix (by typing the image
14312: name as command), the Gforth engine will pass all options to the image
14313: instead of trying to interpret them as engine options.
1.1 anton 14314:
1.27 crook 14315: If you type @file{gforthmi} with no arguments, it prints some usage
14316: instructions.
14317:
1.1 anton 14318: @cindex @code{savesystem} during @file{gforthmi}
14319: @cindex @code{bye} during @file{gforthmi}
14320: @cindex doubly indirect threaded code
1.44 crook 14321: @cindex environment variables
14322: @cindex @code{GFORTHD} -- environment variable
14323: @cindex @code{GFORTH} -- environment variable
1.1 anton 14324: @cindex @code{gforth-ditc}
1.29 crook 14325: There are a few wrinkles: After processing the passed @i{options}, the
1.1 anton 14326: words @code{savesystem} and @code{bye} must be visible. A special doubly
14327: indirect threaded version of the @file{gforth} executable is used for
1.62 crook 14328: creating the non-relocatable images; you can pass the exact filename of
1.1 anton 14329: this executable through the environment variable @code{GFORTHD}
14330: (default: @file{gforth-ditc}); if you pass a version that is not doubly
14331: indirect threaded, you will not get a fully relocatable image, but a
1.27 crook 14332: data-relocatable image (because there is no code address offset). The
14333: normal @file{gforth} executable is used for creating the relocatable
14334: image; you can pass the exact filename of this executable through the
14335: environment variable @code{GFORTH}.
1.1 anton 14336:
14337: @node cross.fs, , gforthmi, Fully Relocatable Image Files
14338: @subsection @file{cross.fs}
14339: @cindex @file{cross.fs}
14340: @cindex cross-compiler
14341: @cindex metacompiler
1.47 crook 14342: @cindex target compiler
1.1 anton 14343:
14344: You can also use @code{cross}, a batch compiler that accepts a Forth-like
1.47 crook 14345: programming language (@pxref{Cross Compiler}).
1.1 anton 14346:
1.47 crook 14347: @code{cross} allows you to create image files for machines with
1.1 anton 14348: different data sizes and data formats than the one used for generating
14349: the image file. You can also use it to create an application image that
14350: does not contain a Forth compiler. These features are bought with
14351: restrictions and inconveniences in programming. E.g., addresses have to
14352: be stored in memory with special words (@code{A!}, @code{A,}, etc.) in
14353: order to make the code relocatable.
14354:
14355:
14356: @node Stack and Dictionary Sizes, Running Image Files, Fully Relocatable Image Files, Image Files
14357: @section Stack and Dictionary Sizes
14358: @cindex image file, stack and dictionary sizes
14359: @cindex dictionary size default
14360: @cindex stack size default
14361:
14362: If you invoke Gforth with a command line flag for the size
14363: (@pxref{Invoking Gforth}), the size you specify is stored in the
14364: dictionary. If you save the dictionary with @code{savesystem} or create
14365: an image with @file{gforthmi}, this size will become the default
14366: for the resulting image file. E.g., the following will create a
1.21 crook 14367: fully relocatable version of @file{gforth.fi} with a 1MB dictionary:
1.1 anton 14368:
14369: @example
14370: gforthmi gforth.fi -m 1M
14371: @end example
14372:
14373: In other words, if you want to set the default size for the dictionary
14374: and the stacks of an image, just invoke @file{gforthmi} with the
14375: appropriate options when creating the image.
14376:
14377: @cindex stack size, cache-friendly
14378: Note: For cache-friendly behaviour (i.e., good performance), you should
14379: make the sizes of the stacks modulo, say, 2K, somewhat different. E.g.,
14380: the default stack sizes are: data: 16k (mod 2k=0); fp: 15.5k (mod
14381: 2k=1.5k); return: 15k(mod 2k=1k); locals: 14.5k (mod 2k=0.5k).
14382:
14383: @node Running Image Files, Modifying the Startup Sequence, Stack and Dictionary Sizes, Image Files
14384: @section Running Image Files
14385: @cindex running image files
14386: @cindex invoking image files
14387: @cindex image file invocation
14388:
14389: @cindex -i, invoke image file
14390: @cindex --image file, invoke image file
1.29 crook 14391: You can invoke Gforth with an image file @i{image} instead of the
1.1 anton 14392: default @file{gforth.fi} with the @code{-i} flag (@pxref{Invoking Gforth}):
14393: @example
1.29 crook 14394: gforth -i @i{image}
1.1 anton 14395: @end example
14396:
14397: @cindex executable image file
1.26 crook 14398: @cindex image file, executable
1.1 anton 14399: If your operating system supports starting scripts with a line of the
14400: form @code{#! ...}, you just have to type the image file name to start
14401: Gforth with this image file (note that the file extension @code{.fi} is
1.29 crook 14402: just a convention). I.e., to run Gforth with the image file @i{image},
14403: you can just type @i{image} instead of @code{gforth -i @i{image}}.
1.27 crook 14404: This works because every @code{.fi} file starts with a line of this
14405: format:
14406:
14407: @example
14408: #! /usr/local/bin/gforth-0.4.0 -i
14409: @end example
14410:
14411: The file and pathname for the Gforth engine specified on this line is
14412: the specific Gforth executable that it was built against; i.e. the value
14413: of the environment variable @code{GFORTH} at the time that
14414: @file{gforthmi} was executed.
1.1 anton 14415:
1.27 crook 14416: You can make use of the same shell capability to make a Forth source
14417: file into an executable. For example, if you place this text in a file:
1.26 crook 14418:
14419: @example
14420: #! /usr/local/bin/gforth
14421:
14422: ." Hello, world" CR
14423: bye
14424: @end example
14425:
14426: @noindent
1.27 crook 14427: and then make the file executable (chmod +x in Unix), you can run it
1.26 crook 14428: directly from the command line. The sequence @code{#!} is used in two
14429: ways; firstly, it is recognised as a ``magic sequence'' by the operating
1.29 crook 14430: system@footnote{The Unix kernel actually recognises two types of files:
14431: executable files and files of data, where the data is processed by an
14432: interpreter that is specified on the ``interpreter line'' -- the first
14433: line of the file, starting with the sequence #!. There may be a small
14434: limit (e.g., 32) on the number of characters that may be specified on
14435: the interpreter line.} secondly it is treated as a comment character by
14436: Gforth. Because of the second usage, a space is required between
1.80 anton 14437: @code{#!} and the path to the executable (moreover, some Unixes
14438: require the sequence @code{#! /}).
1.27 crook 14439:
14440: The disadvantage of this latter technique, compared with using
1.80 anton 14441: @file{gforthmi}, is that it is slightly slower; the Forth source code is
14442: compiled on-the-fly, each time the program is invoked.
1.26 crook 14443:
1.1 anton 14444: doc-#!
14445:
1.44 crook 14446:
1.1 anton 14447: @node Modifying the Startup Sequence, , Running Image Files, Image Files
14448: @section Modifying the Startup Sequence
14449: @cindex startup sequence for image file
14450: @cindex image file initialization sequence
14451: @cindex initialization sequence of image file
14452:
14453: You can add your own initialization to the startup sequence through the
1.26 crook 14454: deferred word @code{'cold}. @code{'cold} is invoked just before the
1.80 anton 14455: image-specific command line processing (i.e., loading files and
1.26 crook 14456: evaluating (@code{-e}) strings) starts.
1.1 anton 14457:
14458: A sequence for adding your initialization usually looks like this:
14459:
14460: @example
14461: :noname
14462: Defers 'cold \ do other initialization stuff (e.g., rehashing wordlists)
14463: ... \ your stuff
14464: ; IS 'cold
14465: @end example
14466:
14467: @cindex turnkey image files
1.26 crook 14468: @cindex image file, turnkey applications
1.1 anton 14469: You can make a turnkey image by letting @code{'cold} execute a word
14470: (your turnkey application) that never returns; instead, it exits Gforth
14471: via @code{bye} or @code{throw}.
14472:
14473: @cindex command-line arguments, access
14474: @cindex arguments on the command line, access
14475: You can access the (image-specific) command-line arguments through the
1.26 crook 14476: variables @code{argc} and @code{argv}. @code{arg} provides convenient
1.1 anton 14477: access to @code{argv}.
14478:
1.26 crook 14479: If @code{'cold} exits normally, Gforth processes the command-line
14480: arguments as files to be loaded and strings to be evaluated. Therefore,
14481: @code{'cold} should remove the arguments it has used in this case.
14482:
1.44 crook 14483:
14484:
1.26 crook 14485: doc-'cold
1.1 anton 14486: doc-argc
14487: doc-argv
14488: doc-arg
14489:
14490:
1.44 crook 14491:
1.1 anton 14492: @c ******************************************************************
1.13 pazsan 14493: @node Engine, Binding to System Library, Image Files, Top
1.1 anton 14494: @chapter Engine
14495: @cindex engine
14496: @cindex virtual machine
14497:
1.26 crook 14498: Reading this chapter is not necessary for programming with Gforth. It
1.1 anton 14499: may be helpful for finding your way in the Gforth sources.
14500:
1.109 ! anton 14501: The ideas in this section have also been published in the following
! 14502: papers: Bernd Paysan, @cite{ANS fig/GNU/??? Forth} (in German),
! 14503: Forth-Tagung '93; M. Anton Ertl,
! 14504: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl93.ps.Z, A
! 14505: Portable Forth Engine}}, EuroForth '93; M. Anton Ertl,
! 14506: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl02.ps.gz,
! 14507: Threaded code variations and optimizations (extended version)}},
! 14508: Forth-Tagung '02.
1.1 anton 14509:
14510: @menu
14511: * Portability::
14512: * Threading::
14513: * Primitives::
14514: * Performance::
14515: @end menu
14516:
14517: @node Portability, Threading, Engine, Engine
14518: @section Portability
14519: @cindex engine portability
14520:
1.26 crook 14521: An important goal of the Gforth Project is availability across a wide
14522: range of personal machines. fig-Forth, and, to a lesser extent, F83,
14523: achieved this goal by manually coding the engine in assembly language
14524: for several then-popular processors. This approach is very
14525: labor-intensive and the results are short-lived due to progress in
14526: computer architecture.
1.1 anton 14527:
14528: @cindex C, using C for the engine
14529: Others have avoided this problem by coding in C, e.g., Mitch Bradley
14530: (cforth), Mikael Patel (TILE) and Dirk Zoller (pfe). This approach is
14531: particularly popular for UNIX-based Forths due to the large variety of
14532: architectures of UNIX machines. Unfortunately an implementation in C
14533: does not mix well with the goals of efficiency and with using
14534: traditional techniques: Indirect or direct threading cannot be expressed
14535: in C, and switch threading, the fastest technique available in C, is
14536: significantly slower. Another problem with C is that it is very
14537: cumbersome to express double integer arithmetic.
14538:
14539: @cindex GNU C for the engine
14540: @cindex long long
14541: Fortunately, there is a portable language that does not have these
14542: limitations: GNU C, the version of C processed by the GNU C compiler
14543: (@pxref{C Extensions, , Extensions to the C Language Family, gcc.info,
14544: GNU C Manual}). Its labels as values feature (@pxref{Labels as Values, ,
14545: Labels as Values, gcc.info, GNU C Manual}) makes direct and indirect
14546: threading possible, its @code{long long} type (@pxref{Long Long, ,
14547: Double-Word Integers, gcc.info, GNU C Manual}) corresponds to Forth's
1.109 ! anton 14548: double numbers on many systems. GNU C is freely available on all
1.1 anton 14549: important (and many unimportant) UNIX machines, VMS, 80386s running
14550: MS-DOS, the Amiga, and the Atari ST, so a Forth written in GNU C can run
14551: on all these machines.
14552:
14553: Writing in a portable language has the reputation of producing code that
14554: is slower than assembly. For our Forth engine we repeatedly looked at
14555: the code produced by the compiler and eliminated most compiler-induced
14556: inefficiencies by appropriate changes in the source code.
14557:
14558: @cindex explicit register declarations
14559: @cindex --enable-force-reg, configuration flag
14560: @cindex -DFORCE_REG
14561: However, register allocation cannot be portably influenced by the
14562: programmer, leading to some inefficiencies on register-starved
14563: machines. We use explicit register declarations (@pxref{Explicit Reg
14564: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) to
14565: improve the speed on some machines. They are turned on by using the
14566: configuration flag @code{--enable-force-reg} (@code{gcc} switch
14567: @code{-DFORCE_REG}). Unfortunately, this feature not only depends on the
14568: machine, but also on the compiler version: On some machines some
14569: compiler versions produce incorrect code when certain explicit register
14570: declarations are used. So by default @code{-DFORCE_REG} is not used.
14571:
14572: @node Threading, Primitives, Portability, Engine
14573: @section Threading
14574: @cindex inner interpreter implementation
14575: @cindex threaded code implementation
14576:
14577: @cindex labels as values
14578: GNU C's labels as values extension (available since @code{gcc-2.0},
14579: @pxref{Labels as Values, , Labels as Values, gcc.info, GNU C Manual})
1.29 crook 14580: makes it possible to take the address of @i{label} by writing
14581: @code{&&@i{label}}. This address can then be used in a statement like
14582: @code{goto *@i{address}}. I.e., @code{goto *&&x} is the same as
1.1 anton 14583: @code{goto x}.
14584:
1.26 crook 14585: @cindex @code{NEXT}, indirect threaded
1.1 anton 14586: @cindex indirect threaded inner interpreter
14587: @cindex inner interpreter, indirect threaded
1.26 crook 14588: With this feature an indirect threaded @code{NEXT} looks like:
1.1 anton 14589: @example
14590: cfa = *ip++;
14591: ca = *cfa;
14592: goto *ca;
14593: @end example
14594: @cindex instruction pointer
14595: For those unfamiliar with the names: @code{ip} is the Forth instruction
14596: pointer; the @code{cfa} (code-field address) corresponds to ANS Forths
14597: execution token and points to the code field of the next word to be
14598: executed; The @code{ca} (code address) fetched from there points to some
14599: executable code, e.g., a primitive or the colon definition handler
14600: @code{docol}.
14601:
1.26 crook 14602: @cindex @code{NEXT}, direct threaded
1.1 anton 14603: @cindex direct threaded inner interpreter
14604: @cindex inner interpreter, direct threaded
14605: Direct threading is even simpler:
14606: @example
14607: ca = *ip++;
14608: goto *ca;
14609: @end example
14610:
14611: Of course we have packaged the whole thing neatly in macros called
1.26 crook 14612: @code{NEXT} and @code{NEXT1} (the part of @code{NEXT} after fetching the cfa).
1.1 anton 14613:
14614: @menu
14615: * Scheduling::
14616: * Direct or Indirect Threaded?::
1.109 ! anton 14617: * Dynamic Superinstructions::
1.1 anton 14618: * DOES>::
14619: @end menu
14620:
14621: @node Scheduling, Direct or Indirect Threaded?, Threading, Threading
14622: @subsection Scheduling
14623: @cindex inner interpreter optimization
14624:
14625: There is a little complication: Pipelined and superscalar processors,
14626: i.e., RISC and some modern CISC machines can process independent
14627: instructions while waiting for the results of an instruction. The
14628: compiler usually reorders (schedules) the instructions in a way that
14629: achieves good usage of these delay slots. However, on our first tries
14630: the compiler did not do well on scheduling primitives. E.g., for
14631: @code{+} implemented as
14632: @example
14633: n=sp[0]+sp[1];
14634: sp++;
14635: sp[0]=n;
14636: NEXT;
14637: @end example
1.81 anton 14638: the @code{NEXT} comes strictly after the other code, i.e., there is
14639: nearly no scheduling. After a little thought the problem becomes clear:
14640: The compiler cannot know that @code{sp} and @code{ip} point to different
1.21 crook 14641: addresses (and the version of @code{gcc} we used would not know it even
14642: if it was possible), so it could not move the load of the cfa above the
14643: store to the TOS. Indeed the pointers could be the same, if code on or
14644: very near the top of stack were executed. In the interest of speed we
14645: chose to forbid this probably unused ``feature'' and helped the compiler
1.81 anton 14646: in scheduling: @code{NEXT} is divided into several parts:
14647: @code{NEXT_P0}, @code{NEXT_P1} and @code{NEXT_P2}). @code{+} now looks
14648: like:
1.1 anton 14649: @example
1.81 anton 14650: NEXT_P0;
1.1 anton 14651: n=sp[0]+sp[1];
14652: sp++;
14653: NEXT_P1;
14654: sp[0]=n;
14655: NEXT_P2;
14656: @end example
14657:
1.81 anton 14658: There are various schemes that distribute the different operations of
14659: NEXT between these parts in several ways; in general, different schemes
14660: perform best on different processors. We use a scheme for most
14661: architectures that performs well for most processors of this
1.109 ! anton 14662: architecture; in the future we may switch to benchmarking and chosing
1.81 anton 14663: the scheme on installation time.
14664:
1.1 anton 14665:
1.109 ! anton 14666: @node Direct or Indirect Threaded?, Dynamic Superinstructions, Scheduling, Threading
1.1 anton 14667: @subsection Direct or Indirect Threaded?
14668: @cindex threading, direct or indirect?
14669:
1.109 ! anton 14670: Threaded forth code consists of references to primitives (simple machine
! 14671: code routines like @code{+}) and to non-primitives (e.g., colon
! 14672: definitions, variables, constants); for a specific class of
! 14673: non-primitives (e.g., variables) there is one code routine (e.g.,
! 14674: @code{dovar}), but each variable needs a separate reference to its data.
! 14675:
! 14676: Traditionally Forth has been implemented as indirect threaded code,
! 14677: because this allows to use only one cell to reference a non-primitive
! 14678: (basically you point to the data, and find the code address there).
! 14679:
! 14680: @cindex primitive-centric threaded code
! 14681: However, threaded code in Gforth (since 0.6.0) uses two cells for
! 14682: non-primitives, one for the code address, and one for the data address;
! 14683: the data pointer is an immediate argument for the virtual machine
! 14684: instruction represented by the code address. We call this
! 14685: @emph{primitive-centric} threaded code, because all code addresses point
! 14686: to simple primitives. E.g., for a variable, the code address is for
! 14687: @code{lit} (also used for integer literals like @code{99}).
! 14688:
! 14689: Primitive-centric threaded code allows us to use (faster) direct
! 14690: threading as dispatch method, completely portably (direct threaded code
! 14691: in Gforth before 0.6.0 required architecture-specific code). It also
! 14692: eliminates the performance problems related to I-cache consistency that
! 14693: 386 implementations have with direct threaded code, and allows
! 14694: additional optimizations.
! 14695:
! 14696: @cindex hybrid direct/indirect threaded code
! 14697: There is a catch, however: the @var{xt} parameter of @code{execute} can
! 14698: occupy only one cell, so how do we pass non-primitives with their code
! 14699: @emph{and} data addresses to them? Our answer is to use indirect
! 14700: threaded dispatch for @code{execute} and other words that use a
! 14701: single-cell xt. So, normal threaded code in colon definitions uses
! 14702: direct threading, and @code{execute} and similar words, which dispatch
! 14703: to xts on the data stack, use indirect threaded code. We call this
! 14704: @emph{hybrid direct/indirect} threaded code.
! 14705:
! 14706: @cindex engines, gforth vs. gforth-fast vs. gforth-itc
! 14707: @cindex gforth engine
! 14708: @cindex gforth-fast engine
! 14709: The engines @command{gforth} and @command{gforth-fast} use hybrid
! 14710: direct/indirect threaded code. This means that with these engines you
! 14711: cannot use @code{,} to compile an xt. Instead, you have to use
! 14712: @code{compile,}.
! 14713:
! 14714: @cindex gforth-itc engine
! 14715: If you want to compile xts with @code{,}, use @command{gforth-itc}. This
! 14716: engine uses plain old indirect threaded code. It still compiles in a
! 14717: primitive-centric style, so you cannot use @code{compile,} instead of
! 14718: @code{,} (e.g., for producing tables of xts with @code{] word1 word2
! 14719: ... [}. If you want to do that, you have to use @command{gforth-itc}
! 14720: and execute @code{' , is compile,}. Your program can check if it is
! 14721: running on a hybrid direct/indirect threaded engine or a pure indirect
! 14722: threaded engine with @code{threading-method} (@pxref{Threading Words}).
! 14723:
! 14724:
! 14725: @node Dynamic Superinstructions, DOES>, Direct or Indirect Threaded?, Threading
! 14726: @subsection Dynamic Superinstructions
! 14727: @cindex Dynamic superinstructions with replication
! 14728: @cindex Superinstructions
! 14729: @cindex Replication
! 14730:
! 14731: The engines @command{gforth} and @command{gforth-fast} use another
! 14732: optimization: Dynamic superinstructions with replication. As an
! 14733: example, consider the following colon definition:
! 14734:
! 14735: @example
! 14736: : squared ( n1 -- n2 )
! 14737: dup * ;
! 14738: @end example
! 14739:
! 14740: Gforth compiles this into the threaded code sequence
! 14741:
! 14742: @example
! 14743: dup
! 14744: *
! 14745: ;s
! 14746: @end example
! 14747:
! 14748: In normal direct threaded code there is a code address occupying one
! 14749: cell for each of these primitives. Each code address points to a
! 14750: machine code routine, and the interpreter jumps to this machine code in
! 14751: order to execute the primitive. The routines for these three
! 14752: primitives are (in @command{gforth-fast} on the 386):
! 14753:
! 14754: @example
! 14755: Code dup
! 14756: ( $804B950 ) add esi , # -4 \ $83 $C6 $FC
! 14757: ( $804B953 ) add ebx , # 4 \ $83 $C3 $4
! 14758: ( $804B956 ) mov dword ptr 4 [esi] , ecx \ $89 $4E $4
! 14759: ( $804B959 ) jmp dword ptr FC [ebx] \ $FF $63 $FC
! 14760: end-code
! 14761: Code *
! 14762: ( $804ACC4 ) mov eax , dword ptr 4 [esi] \ $8B $46 $4
! 14763: ( $804ACC7 ) add esi , # 4 \ $83 $C6 $4
! 14764: ( $804ACCA ) add ebx , # 4 \ $83 $C3 $4
! 14765: ( $804ACCD ) imul ecx , eax \ $F $AF $C8
! 14766: ( $804ACD0 ) jmp dword ptr FC [ebx] \ $FF $63 $FC
! 14767: end-code
! 14768: Code ;s
! 14769: ( $804A693 ) mov eax , dword ptr [edi] \ $8B $7
! 14770: ( $804A695 ) add edi , # 4 \ $83 $C7 $4
! 14771: ( $804A698 ) lea ebx , dword ptr 4 [eax] \ $8D $58 $4
! 14772: ( $804A69B ) jmp dword ptr FC [ebx] \ $FF $63 $FC
! 14773: end-code
! 14774: @end example
! 14775:
! 14776: With dynamic superinstructions and replication the compiler does not
! 14777: just lay down the threaded code, but also copies the machine code
! 14778: fragments, usually without the jump at the end.
! 14779:
! 14780: @example
! 14781: ( $4057D27D ) add esi , # -4 \ $83 $C6 $FC
! 14782: ( $4057D280 ) add ebx , # 4 \ $83 $C3 $4
! 14783: ( $4057D283 ) mov dword ptr 4 [esi] , ecx \ $89 $4E $4
! 14784: ( $4057D286 ) mov eax , dword ptr 4 [esi] \ $8B $46 $4
! 14785: ( $4057D289 ) add esi , # 4 \ $83 $C6 $4
! 14786: ( $4057D28C ) add ebx , # 4 \ $83 $C3 $4
! 14787: ( $4057D28F ) imul ecx , eax \ $F $AF $C8
! 14788: ( $4057D292 ) mov eax , dword ptr [edi] \ $8B $7
! 14789: ( $4057D294 ) add edi , # 4 \ $83 $C7 $4
! 14790: ( $4057D297 ) lea ebx , dword ptr 4 [eax] \ $8D $58 $4
! 14791: ( $4057D29A ) jmp dword ptr FC [ebx] \ $FF $63 $FC
! 14792: @end example
! 14793:
! 14794: Only when a threaded-code control-flow change happens (e.g., in
! 14795: @code{;s}), the jump is appended. This optimization eliminates many of
! 14796: these jumps and makes the rest much more predictable. The speedup
! 14797: depends on the processor and the application; on the Athlon and Pentium
! 14798: III this optimization typically produces a speedup by a factor of 2.
! 14799:
! 14800: The code addresses in the direct-threaded code are set to point to the
! 14801: appropriate points in the copied machine code, in this example like
! 14802: this:
1.1 anton 14803:
1.109 ! anton 14804: @example
! 14805: primitive code address
! 14806: dup $4057D27D
! 14807: * $4057D286
! 14808: ;s $4057D292
! 14809: @end example
! 14810:
! 14811: Thus there can be threaded-code jumps to any place in this piece of
! 14812: code. This also simplifies decompilation quite a bit.
! 14813:
! 14814: @cindex --no-dynamic command-line option
! 14815: @cindex --no-super command-line option
! 14816: You can disable this optimization with @option{--no-dynamic}. You can
! 14817: use the copying without eliminating the jumps (i.e., dynamic
! 14818: replication, but without superinstructions) with @option{--no-super};
! 14819: this gives the branch prediction benefit alone; the effect on
! 14820: performance depends on the CPU.
! 14821:
! 14822: @cindex --dynamic command-line option
! 14823: On some machines this optimization is disabled by default, because it is
! 14824: unsafe on these machines. However, if you feel adventurous, you can
! 14825: enable it with @option{--dynamic}.
! 14826:
! 14827: @node DOES>, , Dynamic Superinstructions, Threading
1.1 anton 14828: @subsection DOES>
14829: @cindex @code{DOES>} implementation
14830:
1.26 crook 14831: @cindex @code{dodoes} routine
14832: @cindex @code{DOES>}-code
1.1 anton 14833: One of the most complex parts of a Forth engine is @code{dodoes}, i.e.,
14834: the chunk of code executed by every word defined by a
1.109 ! anton 14835: @code{CREATE}...@code{DOES>} pair; actually with primitive-centric code,
! 14836: this is only needed if the xt of the word is @code{execute}d. The main
! 14837: problem here is: How to find the Forth code to be executed, i.e. the
! 14838: code after the @code{DOES>} (the @code{DOES>}-code)? There are two
! 14839: solutions:
1.1 anton 14840:
1.21 crook 14841: In fig-Forth the code field points directly to the @code{dodoes} and the
1.109 ! anton 14842: @code{DOES>}-code address is stored in the cell after the code address
! 14843: (i.e. at @code{@i{CFA} cell+}). It may seem that this solution is
! 14844: illegal in the Forth-79 and all later standards, because in fig-Forth
! 14845: this address lies in the body (which is illegal in these
! 14846: standards). However, by making the code field larger for all words this
! 14847: solution becomes legal again. We use this approach. Leaving a cell
! 14848: unused in most words is a bit wasteful, but on the machines we are
! 14849: targeting this is hardly a problem.
! 14850:
1.1 anton 14851:
14852: @node Primitives, Performance, Threading, Engine
14853: @section Primitives
14854: @cindex primitives, implementation
14855: @cindex virtual machine instructions, implementation
14856:
14857: @menu
14858: * Automatic Generation::
14859: * TOS Optimization::
14860: * Produced code::
14861: @end menu
14862:
14863: @node Automatic Generation, TOS Optimization, Primitives, Primitives
14864: @subsection Automatic Generation
14865: @cindex primitives, automatic generation
14866:
14867: @cindex @file{prims2x.fs}
1.109 ! anton 14868:
1.1 anton 14869: Since the primitives are implemented in a portable language, there is no
14870: longer any need to minimize the number of primitives. On the contrary,
14871: having many primitives has an advantage: speed. In order to reduce the
14872: number of errors in primitives and to make programming them easier, we
1.109 ! anton 14873: provide a tool, the primitive generator (@file{prims2x.fs} aka Vmgen,
! 14874: @pxref{Top, Vmgen, Introduction, vmgen, Vmgen}), that automatically
! 14875: generates most (and sometimes all) of the C code for a primitive from
! 14876: the stack effect notation. The source for a primitive has the following
! 14877: form:
1.1 anton 14878:
14879: @cindex primitive source format
14880: @format
1.58 anton 14881: @i{Forth-name} ( @i{stack-effect} ) @i{category} [@i{pronounc.}]
1.29 crook 14882: [@code{""}@i{glossary entry}@code{""}]
14883: @i{C code}
1.1 anton 14884: [@code{:}
1.29 crook 14885: @i{Forth code}]
1.1 anton 14886: @end format
14887:
14888: The items in brackets are optional. The category and glossary fields
14889: are there for generating the documentation, the Forth code is there
14890: for manual implementations on machines without GNU C. E.g., the source
14891: for the primitive @code{+} is:
14892: @example
1.58 anton 14893: + ( n1 n2 -- n ) core plus
1.1 anton 14894: n = n1+n2;
14895: @end example
14896:
14897: This looks like a specification, but in fact @code{n = n1+n2} is C
14898: code. Our primitive generation tool extracts a lot of information from
14899: the stack effect notations@footnote{We use a one-stack notation, even
14900: though we have separate data and floating-point stacks; The separate
14901: notation can be generated easily from the unified notation.}: The number
14902: of items popped from and pushed on the stack, their type, and by what
14903: name they are referred to in the C code. It then generates a C code
14904: prelude and postlude for each primitive. The final C code for @code{+}
14905: looks like this:
14906:
14907: @example
1.46 pazsan 14908: I_plus: /* + ( n1 n2 -- n ) */ /* label, stack effect */
1.1 anton 14909: /* */ /* documentation */
1.81 anton 14910: NAME("+") /* debugging output (with -DDEBUG) */
1.1 anton 14911: @{
14912: DEF_CA /* definition of variable ca (indirect threading) */
14913: Cell n1; /* definitions of variables */
14914: Cell n2;
14915: Cell n;
1.81 anton 14916: NEXT_P0; /* NEXT part 0 */
1.1 anton 14917: n1 = (Cell) sp[1]; /* input */
14918: n2 = (Cell) TOS;
14919: sp += 1; /* stack adjustment */
14920: @{
14921: n = n1+n2; /* C code taken from the source */
14922: @}
14923: NEXT_P1; /* NEXT part 1 */
14924: TOS = (Cell)n; /* output */
14925: NEXT_P2; /* NEXT part 2 */
14926: @}
14927: @end example
14928:
14929: This looks long and inefficient, but the GNU C compiler optimizes quite
14930: well and produces optimal code for @code{+} on, e.g., the R3000 and the
14931: HP RISC machines: Defining the @code{n}s does not produce any code, and
14932: using them as intermediate storage also adds no cost.
14933:
1.26 crook 14934: There are also other optimizations that are not illustrated by this
14935: example: assignments between simple variables are usually for free (copy
1.1 anton 14936: propagation). If one of the stack items is not used by the primitive
14937: (e.g. in @code{drop}), the compiler eliminates the load from the stack
14938: (dead code elimination). On the other hand, there are some things that
14939: the compiler does not do, therefore they are performed by
14940: @file{prims2x.fs}: The compiler does not optimize code away that stores
14941: a stack item to the place where it just came from (e.g., @code{over}).
14942:
14943: While programming a primitive is usually easy, there are a few cases
14944: where the programmer has to take the actions of the generator into
14945: account, most notably @code{?dup}, but also words that do not (always)
1.26 crook 14946: fall through to @code{NEXT}.
1.109 ! anton 14947:
! 14948: For more information
1.1 anton 14949:
14950: @node TOS Optimization, Produced code, Automatic Generation, Primitives
14951: @subsection TOS Optimization
14952: @cindex TOS optimization for primitives
14953: @cindex primitives, keeping the TOS in a register
14954:
14955: An important optimization for stack machine emulators, e.g., Forth
14956: engines, is keeping one or more of the top stack items in
1.29 crook 14957: registers. If a word has the stack effect @i{in1}...@i{inx} @code{--}
14958: @i{out1}...@i{outy}, keeping the top @i{n} items in registers
1.1 anton 14959: @itemize @bullet
14960: @item
1.29 crook 14961: is better than keeping @i{n-1} items, if @i{x>=n} and @i{y>=n},
1.1 anton 14962: due to fewer loads from and stores to the stack.
1.29 crook 14963: @item is slower than keeping @i{n-1} items, if @i{x<>y} and @i{x<n} and
14964: @i{y<n}, due to additional moves between registers.
1.1 anton 14965: @end itemize
14966:
14967: @cindex -DUSE_TOS
14968: @cindex -DUSE_NO_TOS
14969: In particular, keeping one item in a register is never a disadvantage,
14970: if there are enough registers. Keeping two items in registers is a
14971: disadvantage for frequent words like @code{?branch}, constants,
14972: variables, literals and @code{i}. Therefore our generator only produces
14973: code that keeps zero or one items in registers. The generated C code
14974: covers both cases; the selection between these alternatives is made at
14975: C-compile time using the switch @code{-DUSE_TOS}. @code{TOS} in the C
14976: code for @code{+} is just a simple variable name in the one-item case,
14977: otherwise it is a macro that expands into @code{sp[0]}. Note that the
14978: GNU C compiler tries to keep simple variables like @code{TOS} in
14979: registers, and it usually succeeds, if there are enough registers.
14980:
14981: @cindex -DUSE_FTOS
14982: @cindex -DUSE_NO_FTOS
14983: The primitive generator performs the TOS optimization for the
14984: floating-point stack, too (@code{-DUSE_FTOS}). For floating-point
14985: operations the benefit of this optimization is even larger:
14986: floating-point operations take quite long on most processors, but can be
14987: performed in parallel with other operations as long as their results are
14988: not used. If the FP-TOS is kept in a register, this works. If
14989: it is kept on the stack, i.e., in memory, the store into memory has to
14990: wait for the result of the floating-point operation, lengthening the
14991: execution time of the primitive considerably.
14992:
14993: The TOS optimization makes the automatic generation of primitives a
14994: bit more complicated. Just replacing all occurrences of @code{sp[0]} by
14995: @code{TOS} is not sufficient. There are some special cases to
14996: consider:
14997: @itemize @bullet
14998: @item In the case of @code{dup ( w -- w w )} the generator must not
14999: eliminate the store to the original location of the item on the stack,
15000: if the TOS optimization is turned on.
15001: @item Primitives with stack effects of the form @code{--}
1.29 crook 15002: @i{out1}...@i{outy} must store the TOS to the stack at the start.
15003: Likewise, primitives with the stack effect @i{in1}...@i{inx} @code{--}
1.1 anton 15004: must load the TOS from the stack at the end. But for the null stack
15005: effect @code{--} no stores or loads should be generated.
15006: @end itemize
15007:
15008: @node Produced code, , TOS Optimization, Primitives
15009: @subsection Produced code
15010: @cindex primitives, assembly code listing
15011:
15012: @cindex @file{engine.s}
15013: To see what assembly code is produced for the primitives on your machine
15014: with your compiler and your flag settings, type @code{make engine.s} and
1.81 anton 15015: look at the resulting file @file{engine.s}. Alternatively, you can also
15016: disassemble the code of primitives with @code{see} on some architectures.
1.1 anton 15017:
15018: @node Performance, , Primitives, Engine
15019: @section Performance
15020: @cindex performance of some Forth interpreters
15021: @cindex engine performance
15022: @cindex benchmarking Forth systems
15023: @cindex Gforth performance
15024:
15025: On RISCs the Gforth engine is very close to optimal; i.e., it is usually
15026: impossible to write a significantly faster engine.
15027:
15028: On register-starved machines like the 386 architecture processors
15029: improvements are possible, because @code{gcc} does not utilize the
15030: registers as well as a human, even with explicit register declarations;
15031: e.g., Bernd Beuster wrote a Forth system fragment in assembly language
15032: and hand-tuned it for the 486; this system is 1.19 times faster on the
15033: Sieve benchmark on a 486DX2/66 than Gforth compiled with
1.40 anton 15034: @code{gcc-2.6.3} with @code{-DFORCE_REG}. The situation has improved
15035: with gcc-2.95 and gforth-0.4.9; now the most important virtual machine
15036: registers fit in real registers (and we can even afford to use the TOS
15037: optimization), resulting in a speedup of 1.14 on the sieve over the
15038: earlier results.
1.1 anton 15039:
15040: @cindex Win32Forth performance
15041: @cindex NT Forth performance
15042: @cindex eforth performance
15043: @cindex ThisForth performance
15044: @cindex PFE performance
15045: @cindex TILE performance
1.81 anton 15046: The potential advantage of assembly language implementations is not
15047: necessarily realized in complete Forth systems: We compared Gforth-0.4.9
15048: (direct threaded, compiled with @code{gcc-2.95.1} and
15049: @code{-DFORCE_REG}) with Win32Forth 1.2093 (newer versions are
15050: reportedly much faster), LMI's NT Forth (Beta, May 1994) and Eforth
15051: (with and without peephole (aka pinhole) optimization of the threaded
15052: code); all these systems were written in assembly language. We also
15053: compared Gforth with three systems written in C: PFE-0.9.14 (compiled
15054: with @code{gcc-2.6.3} with the default configuration for Linux:
15055: @code{-O2 -fomit-frame-pointer -DUSE_REGS -DUNROLL_NEXT}), ThisForth
15056: Beta (compiled with @code{gcc-2.6.3 -O3 -fomit-frame-pointer}; ThisForth
15057: employs peephole optimization of the threaded code) and TILE (compiled
15058: with @code{make opt}). We benchmarked Gforth, PFE, ThisForth and TILE on
15059: a 486DX2/66 under Linux. Kenneth O'Heskin kindly provided the results
15060: for Win32Forth and NT Forth on a 486DX2/66 with similar memory
15061: performance under Windows NT. Marcel Hendrix ported Eforth to Linux,
15062: then extended it to run the benchmarks, added the peephole optimizer,
15063: ran the benchmarks and reported the results.
1.40 anton 15064:
1.1 anton 15065: We used four small benchmarks: the ubiquitous Sieve; bubble-sorting and
15066: matrix multiplication come from the Stanford integer benchmarks and have
15067: been translated into Forth by Martin Fraeman; we used the versions
15068: included in the TILE Forth package, but with bigger data set sizes; and
15069: a recursive Fibonacci number computation for benchmarking calling
15070: performance. The following table shows the time taken for the benchmarks
15071: scaled by the time taken by Gforth (in other words, it shows the speedup
15072: factor that Gforth achieved over the other systems).
15073:
15074: @example
1.40 anton 15075: relative Win32- NT eforth This-
1.1 anton 15076: time Gforth Forth Forth eforth +opt PFE Forth TILE
1.81 anton 15077: sieve 1.00 1.60 1.32 1.60 0.98 1.82 3.67 9.91
15078: bubble 1.00 1.55 1.66 1.75 1.04 1.78 4.58
15079: matmul 1.00 1.71 1.57 1.69 0.86 1.83 4.74
15080: fib 1.00 1.76 1.54 1.41 1.00 2.01 3.45 4.96
1.1 anton 15081: @end example
15082:
1.26 crook 15083: You may be quite surprised by the good performance of Gforth when
15084: compared with systems written in assembly language. One important reason
15085: for the disappointing performance of these other systems is probably
15086: that they are not written optimally for the 486 (e.g., they use the
15087: @code{lods} instruction). In addition, Win32Forth uses a comfortable,
15088: but costly method for relocating the Forth image: like @code{cforth}, it
15089: computes the actual addresses at run time, resulting in two address
15090: computations per @code{NEXT} (@pxref{Image File Background}).
15091:
1.40 anton 15092: Only Eforth with the peephole optimizer performs comparable to
15093: Gforth. The speedups achieved with peephole optimization of threaded
15094: code are quite remarkable. Adding a peephole optimizer to Gforth should
15095: cause similar speedups.
1.1 anton 15096:
15097: The speedup of Gforth over PFE, ThisForth and TILE can be easily
15098: explained with the self-imposed restriction of the latter systems to
15099: standard C, which makes efficient threading impossible (however, the
1.4 anton 15100: measured implementation of PFE uses a GNU C extension: @pxref{Global Reg
1.1 anton 15101: Vars, , Defining Global Register Variables, gcc.info, GNU C Manual}).
15102: Moreover, current C compilers have a hard time optimizing other aspects
15103: of the ThisForth and the TILE source.
15104:
1.26 crook 15105: The performance of Gforth on 386 architecture processors varies widely
15106: with the version of @code{gcc} used. E.g., @code{gcc-2.5.8} failed to
15107: allocate any of the virtual machine registers into real machine
15108: registers by itself and would not work correctly with explicit register
1.40 anton 15109: declarations, giving a 1.5 times slower engine (on a 486DX2/66 running
1.26 crook 15110: the Sieve) than the one measured above.
1.1 anton 15111:
1.26 crook 15112: Note that there have been several releases of Win32Forth since the
15113: release presented here, so the results presented above may have little
1.40 anton 15114: predictive value for the performance of Win32Forth today (results for
15115: the current release on an i486DX2/66 are welcome).
1.1 anton 15116:
15117: @cindex @file{Benchres}
1.66 anton 15118: In
15119: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl&maierhofer95.ps.gz,
15120: Translating Forth to Efficient C}} by M. Anton Ertl and Martin
1.1 anton 15121: Maierhofer (presented at EuroForth '95), an indirect threaded version of
1.66 anton 15122: Gforth is compared with Win32Forth, NT Forth, PFE, ThisForth, and
15123: several native code systems; that version of Gforth is slower on a 486
15124: than the direct threaded version used here. You can find a newer version
15125: of these measurements at
1.47 crook 15126: @uref{http://www.complang.tuwien.ac.at/forth/performance.html}. You can
1.1 anton 15127: find numbers for Gforth on various machines in @file{Benchres}.
15128:
1.26 crook 15129: @c ******************************************************************
1.13 pazsan 15130: @node Binding to System Library, Cross Compiler, Engine, Top
1.14 pazsan 15131: @chapter Binding to System Library
1.13 pazsan 15132:
15133: @node Cross Compiler, Bugs, Binding to System Library, Top
1.14 pazsan 15134: @chapter Cross Compiler
1.47 crook 15135: @cindex @file{cross.fs}
15136: @cindex cross-compiler
15137: @cindex metacompiler
15138: @cindex target compiler
1.13 pazsan 15139:
1.46 pazsan 15140: The cross compiler is used to bootstrap a Forth kernel. Since Gforth is
15141: mostly written in Forth, including crucial parts like the outer
15142: interpreter and compiler, it needs compiled Forth code to get
15143: started. The cross compiler allows to create new images for other
15144: architectures, even running under another Forth system.
1.13 pazsan 15145:
15146: @menu
1.67 anton 15147: * Using the Cross Compiler::
15148: * How the Cross Compiler Works::
1.13 pazsan 15149: @end menu
15150:
1.21 crook 15151: @node Using the Cross Compiler, How the Cross Compiler Works, Cross Compiler, Cross Compiler
1.14 pazsan 15152: @section Using the Cross Compiler
1.46 pazsan 15153:
15154: The cross compiler uses a language that resembles Forth, but isn't. The
15155: main difference is that you can execute Forth code after definition,
15156: while you usually can't execute the code compiled by cross, because the
15157: code you are compiling is typically for a different computer than the
15158: one you are compiling on.
15159:
1.81 anton 15160: @c anton: This chapter is somewhat different from waht I would expect: I
15161: @c would expect an explanation of the cross language and how to create an
15162: @c application image with it. The section explains some aspects of
15163: @c creating a Gforth kernel.
15164:
1.46 pazsan 15165: The Makefile is already set up to allow you to create kernels for new
15166: architectures with a simple make command. The generic kernels using the
15167: GCC compiled virtual machine are created in the normal build process
15168: with @code{make}. To create a embedded Gforth executable for e.g. the
15169: 8086 processor (running on a DOS machine), type
15170:
15171: @example
15172: make kernl-8086.fi
15173: @end example
15174:
15175: This will use the machine description from the @file{arch/8086}
15176: directory to create a new kernel. A machine file may look like that:
15177:
15178: @example
15179: \ Parameter for target systems 06oct92py
15180:
15181: 4 Constant cell \ cell size in bytes
15182: 2 Constant cell<< \ cell shift to bytes
15183: 5 Constant cell>bit \ cell shift to bits
15184: 8 Constant bits/char \ bits per character
15185: 8 Constant bits/byte \ bits per byte [default: 8]
15186: 8 Constant float \ bytes per float
15187: 8 Constant /maxalign \ maximum alignment in bytes
15188: false Constant bigendian \ byte order
15189: ( true=big, false=little )
15190:
15191: include machpc.fs \ feature list
15192: @end example
15193:
15194: This part is obligatory for the cross compiler itself, the feature list
15195: is used by the kernel to conditionally compile some features in and out,
15196: depending on whether the target supports these features.
15197:
15198: There are some optional features, if you define your own primitives,
15199: have an assembler, or need special, nonstandard preparation to make the
1.81 anton 15200: boot process work. @code{asm-include} includes an assembler,
1.46 pazsan 15201: @code{prims-include} includes primitives, and @code{>boot} prepares for
15202: booting.
15203:
15204: @example
15205: : asm-include ." Include assembler" cr
15206: s" arch/8086/asm.fs" included ;
15207:
15208: : prims-include ." Include primitives" cr
15209: s" arch/8086/prim.fs" included ;
15210:
15211: : >boot ." Prepare booting" cr
15212: s" ' boot >body into-forth 1+ !" evaluate ;
15213: @end example
15214:
15215: These words are used as sort of macro during the cross compilation in
1.81 anton 15216: the file @file{kernel/main.fs}. Instead of using these macros, it would
1.46 pazsan 15217: be possible --- but more complicated --- to write a new kernel project
15218: file, too.
15219:
15220: @file{kernel/main.fs} expects the machine description file name on the
15221: stack; the cross compiler itself (@file{cross.fs}) assumes that either
15222: @code{mach-file} leaves a counted string on the stack, or
15223: @code{machine-file} leaves an address, count pair of the filename on the
15224: stack.
15225:
15226: The feature list is typically controlled using @code{SetValue}, generic
15227: files that are used by several projects can use @code{DefaultValue}
15228: instead. Both functions work like @code{Value}, when the value isn't
15229: defined, but @code{SetValue} works like @code{to} if the value is
15230: defined, and @code{DefaultValue} doesn't set anything, if the value is
15231: defined.
15232:
15233: @example
15234: \ generic mach file for pc gforth 03sep97jaw
15235:
15236: true DefaultValue NIL \ relocating
15237:
15238: >ENVIRON
15239:
15240: true DefaultValue file \ controls the presence of the
15241: \ file access wordset
15242: true DefaultValue OS \ flag to indicate a operating system
15243:
15244: true DefaultValue prims \ true: primitives are c-code
15245:
15246: true DefaultValue floating \ floating point wordset is present
15247:
15248: true DefaultValue glocals \ gforth locals are present
15249: \ will be loaded
15250: true DefaultValue dcomps \ double number comparisons
15251:
15252: true DefaultValue hash \ hashing primitives are loaded/present
15253:
15254: true DefaultValue xconds \ used together with glocals,
15255: \ special conditionals supporting gforths'
15256: \ local variables
15257: true DefaultValue header \ save a header information
15258:
15259: true DefaultValue backtrace \ enables backtrace code
15260:
15261: false DefaultValue ec
15262: false DefaultValue crlf
15263:
15264: cell 2 = [IF] &32 [ELSE] &256 [THEN] KB DefaultValue kernel-size
15265:
15266: &16 KB DefaultValue stack-size
15267: &15 KB &512 + DefaultValue fstack-size
15268: &15 KB DefaultValue rstack-size
15269: &14 KB &512 + DefaultValue lstack-size
15270: @end example
1.13 pazsan 15271:
1.48 anton 15272: @node How the Cross Compiler Works, , Using the Cross Compiler, Cross Compiler
1.14 pazsan 15273: @section How the Cross Compiler Works
1.13 pazsan 15274:
15275: @node Bugs, Origin, Cross Compiler, Top
1.21 crook 15276: @appendix Bugs
1.1 anton 15277: @cindex bug reporting
15278:
1.21 crook 15279: Known bugs are described in the file @file{BUGS} in the Gforth distribution.
1.1 anton 15280:
1.103 anton 15281: If you find a bug, please submit a bug report through
15282: @uref{https://savannah.gnu.org/bugs/?func=addbug&group=gforth}.
1.21 crook 15283:
15284: @itemize @bullet
15285: @item
1.81 anton 15286: A program (or a sequence of keyboard commands) that reproduces the bug.
15287: @item
15288: A description of what you think constitutes the buggy behaviour.
15289: @item
1.21 crook 15290: The Gforth version used (it is announced at the start of an
15291: interactive Gforth session).
15292: @item
15293: The machine and operating system (on Unix
15294: systems @code{uname -a} will report this information).
15295: @item
1.81 anton 15296: The installation options (you can find the configure options at the
15297: start of @file{config.status}) and configuration (@code{configure}
15298: output or @file{config.cache}).
1.21 crook 15299: @item
15300: A complete list of changes (if any) you (or your installer) have made to the
15301: Gforth sources.
15302: @end itemize
1.1 anton 15303:
15304: For a thorough guide on reporting bugs read @ref{Bug Reporting, , How
15305: to Report Bugs, gcc.info, GNU C Manual}.
15306:
15307:
1.21 crook 15308: @node Origin, Forth-related information, Bugs, Top
15309: @appendix Authors and Ancestors of Gforth
1.1 anton 15310:
15311: @section Authors and Contributors
15312: @cindex authors of Gforth
15313: @cindex contributors to Gforth
15314:
15315: The Gforth project was started in mid-1992 by Bernd Paysan and Anton
1.81 anton 15316: Ertl. The third major author was Jens Wilke. Neal Crook contributed a
15317: lot to the manual. Assemblers and disassemblers were contributed by
15318: Andrew McKewan, Christian Pirker, and Bernd Thallner. Lennart Benschop
15319: (who was one of Gforth's first users, in mid-1993) and Stuart Ramsden
15320: inspired us with their continuous feedback. Lennart Benshop contributed
1.1 anton 15321: @file{glosgen.fs}, while Stuart Ramsden has been working on automatic
15322: support for calling C libraries. Helpful comments also came from Paul
15323: Kleinrubatscher, Christian Pirker, Dirk Zoller, Marcel Hendrix, John
1.58 anton 15324: Wavrik, Barrie Stott, Marc de Groot, Jorge Acerada, Bruce Hoyt, and
15325: Robert Epprecht. Since the release of Gforth-0.2.1 there were also
15326: helpful comments from many others; thank you all, sorry for not listing
15327: you here (but digging through my mailbox to extract your names is on my
1.81 anton 15328: to-do list).
1.1 anton 15329:
15330: Gforth also owes a lot to the authors of the tools we used (GCC, CVS,
15331: and autoconf, among others), and to the creators of the Internet: Gforth
1.21 crook 15332: was developed across the Internet, and its authors did not meet
1.20 pazsan 15333: physically for the first 4 years of development.
1.1 anton 15334:
15335: @section Pedigree
1.26 crook 15336: @cindex pedigree of Gforth
1.1 anton 15337:
1.81 anton 15338: Gforth descends from bigFORTH (1993) and fig-Forth. Of course, a
15339: significant part of the design of Gforth was prescribed by ANS Forth.
1.1 anton 15340:
1.20 pazsan 15341: Bernd Paysan wrote bigFORTH, a descendent from TurboForth, an unreleased
1.1 anton 15342: 32 bit native code version of VolksForth for the Atari ST, written
15343: mostly by Dietrich Weineck.
15344:
1.81 anton 15345: VolksForth was written by Klaus Schleisiek, Bernd Pennemann, Georg
15346: Rehfeld and Dietrich Weineck for the C64 (called UltraForth there) in
15347: the mid-80s and ported to the Atari ST in 1986. It descends from F83.
1.1 anton 15348:
15349: Henry Laxen and Mike Perry wrote F83 as a model implementation of the
15350: Forth-83 standard. !! Pedigree? When?
15351:
15352: A team led by Bill Ragsdale implemented fig-Forth on many processors in
15353: 1979. Robert Selzer and Bill Ragsdale developed the original
15354: implementation of fig-Forth for the 6502 based on microForth.
15355:
15356: The principal architect of microForth was Dean Sanderson. microForth was
15357: FORTH, Inc.'s first off-the-shelf product. It was developed in 1976 for
15358: the 1802, and subsequently implemented on the 8080, the 6800 and the
15359: Z80.
15360:
15361: All earlier Forth systems were custom-made, usually by Charles Moore,
15362: who discovered (as he puts it) Forth during the late 60s. The first full
15363: Forth existed in 1971.
15364:
1.81 anton 15365: A part of the information in this section comes from
15366: @cite{@uref{http://www.forth.com/Content/History/History1.htm,The
15367: Evolution of Forth}} by Elizabeth D. Rather, Donald R. Colburn and
15368: Charles H. Moore, presented at the HOPL-II conference and preprinted in
15369: SIGPLAN Notices 28(3), 1993. You can find more historical and
15370: genealogical information about Forth there.
1.1 anton 15371:
1.81 anton 15372: @c ------------------------------------------------------------------
1.21 crook 15373: @node Forth-related information, Word Index, Origin, Top
15374: @appendix Other Forth-related information
15375: @cindex Forth-related information
15376:
1.81 anton 15377: @c anton: I threw most of this stuff out, because it can be found through
15378: @c the FAQ and the FAQ is more likely to be up-to-date.
1.21 crook 15379:
15380: @cindex comp.lang.forth
15381: @cindex frequently asked questions
1.81 anton 15382: There is an active news group (comp.lang.forth) discussing Forth
15383: (including Gforth) and Forth-related issues. Its
15384: @uref{http://www.complang.tuwien.ac.at/forth/faq/faq-general-2.html,FAQs}
15385: (frequently asked questions and their answers) contains a lot of
15386: information on Forth. You should read it before posting to
15387: comp.lang.forth.
1.21 crook 15388:
1.81 anton 15389: The ANS Forth standard is most usable in its
15390: @uref{http://www.taygeta.com/forth/dpans.html, HTML form}.
1.21 crook 15391:
1.81 anton 15392: @c ------------------------------------------------------------------
15393: @node Word Index, Concept Index, Forth-related information, Top
1.1 anton 15394: @unnumbered Word Index
15395:
1.26 crook 15396: This index is a list of Forth words that have ``glossary'' entries
15397: within this manual. Each word is listed with its stack effect and
15398: wordset.
1.1 anton 15399:
15400: @printindex fn
15401:
1.81 anton 15402: @c anton: the name index seems superfluous given the word and concept indices.
15403:
15404: @c @node Name Index, Concept Index, Word Index, Top
15405: @c @unnumbered Name Index
1.41 anton 15406:
1.81 anton 15407: @c This index is a list of Forth words that have ``glossary'' entries
15408: @c within this manual.
1.41 anton 15409:
1.81 anton 15410: @c @printindex ky
1.41 anton 15411:
1.81 anton 15412: @node Concept Index, , Word Index, Top
1.1 anton 15413: @unnumbered Concept and Word Index
15414:
1.26 crook 15415: Not all entries listed in this index are present verbatim in the
15416: text. This index also duplicates, in abbreviated form, all of the words
15417: listed in the Word Index (only the names are listed for the words here).
1.1 anton 15418:
15419: @printindex cp
15420:
15421: @contents
15422: @bye
1.81 anton 15423:
15424:
1.1 anton 15425:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>