Annotation of gforth/doc/gforth.ds, revision 1.77
1.1 anton 1: \input texinfo @c -*-texinfo-*-
2: @comment The source is gforth.ds, from which gforth.texi is generated
1.28 crook 3:
1.21 crook 4: @comment TODO: nac29jan99 - a list of things to add in the next edit:
1.28 crook 5: @comment 1. x-ref all ambiguous or implementation-defined features?
6: @comment 2. Describe the use of Auser Avariable AConstant A, etc.
7: @comment 3. words in miscellaneous section need a home.
8: @comment 4. search for TODO for other minor and major works required.
9: @comment 5. [rats] change all @var to @i in Forth source so that info
10: @comment file looks decent.
1.36 anton 11: @c Not an improvement IMO - anton
12: @c and anyway, this should be taken up
13: @c with Karl Berry (the texinfo guy) - anton
1.29 crook 14: @comment .. would be useful to have a word that identified all deferred words
15: @comment should semantics stuff in intro be moved to another section
16:
1.66 anton 17: @c POSTPONE, COMPILE, [COMPILE], LITERAL should have their own section
1.28 crook 18:
1.1 anton 19: @comment %**start of header (This is for running Texinfo on a region.)
20: @setfilename gforth.info
21: @settitle Gforth Manual
22: @dircategory GNU programming tools
23: @direntry
24: * Gforth: (gforth). A fast interpreter for the Forth language.
25: @end direntry
1.49 anton 26: @c The Texinfo manual also recommends doing this, but for Gforth it may
27: @c not make much sense
28: @c @dircategory Individual utilities
29: @c @direntry
30: @c * Gforth: (gforth)Invoking Gforth. gforth, gforth-fast, gforthmi
31: @c @end direntry
32:
1.1 anton 33: @comment @setchapternewpage odd
1.29 crook 34: @comment TODO this gets left in by HTML converter
1.12 anton 35: @macro progstyle {}
36: Programming style note:
1.3 anton 37: @end macro
1.48 anton 38:
39: @macro assignment {}
40: @table @i
41: @item Assignment:
42: @end macro
43: @macro endassignment {}
44: @end table
45: @end macro
46:
1.1 anton 47: @comment %**end of header (This is for running Texinfo on a region.)
48:
1.29 crook 49:
50: @comment ----------------------------------------------------------
51: @comment macros for beautifying glossary entries
52: @comment if these are used, need to strip them out for HTML converter
53: @comment else they get repeated verbatim in HTML output.
54: @comment .. not working yet.
55:
56: @macro GLOSS-START {}
57: @iftex
58: @ninerm
59: @end iftex
60: @end macro
61:
62: @macro GLOSS-END {}
63: @iftex
64: @rm
65: @end iftex
66: @end macro
67:
68: @comment ----------------------------------------------------------
69:
70:
1.10 anton 71: @include version.texi
72:
1.49 anton 73: @ifnottex
1.11 anton 74: This file documents Gforth @value{VERSION}
1.1 anton 75:
1.62 crook 76: Copyright @copyright{} 1995--2000 Free Software Foundation, Inc.
1.1 anton 77:
78: Permission is granted to make and distribute verbatim copies of
79: this manual provided the copyright notice and this permission notice
80: are preserved on all copies.
81:
82: @ignore
83: Permission is granted to process this file through TeX and print the
84: results, provided the printed document carries a copying permission
85: notice identical to this one except for the removal of this paragraph
86: (this paragraph not being relevant to the printed manual).
87:
88: @end ignore
89: Permission is granted to copy and distribute modified versions of this
90: manual under the conditions for verbatim copying, provided also that the
91: sections entitled "Distribution" and "General Public License" are
92: included exactly as in the original, and provided that the entire
93: resulting derived work is distributed under the terms of a permission
94: notice identical to this one.
95:
96: Permission is granted to copy and distribute translations of this manual
97: into another language, under the above conditions for modified versions,
98: except that the sections entitled "Distribution" and "General Public
99: License" may be included in a translation approved by the author instead
100: of in the original English.
1.49 anton 101: @end ifnottex
1.1 anton 102:
103: @finalout
104: @titlepage
105: @sp 10
106: @center @titlefont{Gforth Manual}
107: @sp 2
1.11 anton 108: @center for version @value{VERSION}
1.1 anton 109: @sp 2
1.34 anton 110: @center Neal Crook
1.1 anton 111: @center Anton Ertl
1.6 pazsan 112: @center Bernd Paysan
1.5 anton 113: @center Jens Wilke
1.1 anton 114: @sp 3
1.47 crook 115: @center This manual is permanently under construction and was last updated on 15-Mar-2000
1.1 anton 116:
117: @comment The following two commands start the copyright page.
118: @page
119: @vskip 0pt plus 1filll
1.62 crook 120: Copyright @copyright{} 1995--2000 Free Software Foundation, Inc.
1.1 anton 121:
122: @comment !! Published by ... or You can get a copy of this manual ...
123:
124: Permission is granted to make and distribute verbatim copies of
125: this manual provided the copyright notice and this permission notice
126: are preserved on all copies.
127:
128: Permission is granted to copy and distribute modified versions of this
129: manual under the conditions for verbatim copying, provided also that the
130: sections entitled "Distribution" and "General Public License" are
131: included exactly as in the original, and provided that the entire
132: resulting derived work is distributed under the terms of a permission
133: notice identical to this one.
134:
135: Permission is granted to copy and distribute translations of this manual
136: into another language, under the above conditions for modified versions,
137: except that the sections entitled "Distribution" and "General Public
138: License" may be included in a translation approved by the author instead
139: of in the original English.
140: @end titlepage
141:
142: @node Top, License, (dir), (dir)
1.49 anton 143: @ifnottex
1.1 anton 144: Gforth is a free implementation of ANS Forth available on many
1.11 anton 145: personal machines. This manual corresponds to version @value{VERSION}.
1.49 anton 146: @end ifnottex
1.1 anton 147:
148: @menu
1.21 crook 149: * License:: The GPL
1.26 crook 150: * Goals:: About the Gforth Project
1.29 crook 151: * Gforth Environment:: Starting (and exiting) Gforth
1.48 anton 152: * Tutorial:: Hands-on Forth Tutorial
1.21 crook 153: * Introduction:: An introduction to ANS Forth
1.1 anton 154: * Words:: Forth words available in Gforth
1.24 anton 155: * Error messages:: How to interpret them
1.1 anton 156: * Tools:: Programming tools
157: * ANS conformance:: Implementation-defined options etc.
1.65 anton 158: * Standard vs Extensions:: Should I use extensions?
1.1 anton 159: * Model:: The abstract machine of Gforth
160: * Integrating Gforth:: Forth as scripting language for applications
161: * Emacs and Gforth:: The Gforth Mode
162: * Image Files:: @code{.fi} files contain compiled code
163: * Engine:: The inner interpreter and the primitives
1.24 anton 164: * Binding to System Library::
1.13 pazsan 165: * Cross Compiler:: The Cross Compiler
1.1 anton 166: * Bugs:: How to report them
167: * Origin:: Authors and ancestors of Gforth
1.21 crook 168: * Forth-related information:: Books and places to look on the WWW
1.1 anton 169: * Word Index:: An item for each Forth word
1.41 anton 170: * Name Index:: Forth words, only names listed
1.1 anton 171: * Concept Index:: A menu covering many topics
1.12 anton 172:
1.77 ! anton 173: @detailmenu
! 174: --- The Detailed Node Listing ---
1.12 anton 175:
1.29 crook 176: Gforth Environment
177:
1.32 anton 178: * Invoking Gforth:: Getting in
179: * Leaving Gforth:: Getting out
180: * Command-line editing::
1.48 anton 181: * Environment variables:: that affect how Gforth starts up
1.32 anton 182: * Gforth Files:: What gets installed and where
1.48 anton 183: * Startup speed:: When 35ms is not fast enough ...
184:
185: Forth Tutorial
186:
187: * Starting Gforth Tutorial::
188: * Syntax Tutorial::
189: * Crash Course Tutorial::
190: * Stack Tutorial::
191: * Arithmetics Tutorial::
192: * Stack Manipulation Tutorial::
193: * Using files for Forth code Tutorial::
194: * Comments Tutorial::
195: * Colon Definitions Tutorial::
196: * Decompilation Tutorial::
197: * Stack-Effect Comments Tutorial::
198: * Types Tutorial::
199: * Factoring Tutorial::
200: * Designing the stack effect Tutorial::
201: * Local Variables Tutorial::
202: * Conditional execution Tutorial::
203: * Flags and Comparisons Tutorial::
204: * General Loops Tutorial::
205: * Counted loops Tutorial::
206: * Recursion Tutorial::
207: * Leaving definitions or loops Tutorial::
208: * Return Stack Tutorial::
209: * Memory Tutorial::
210: * Characters and Strings Tutorial::
211: * Alignment Tutorial::
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.65 anton 247: * The Text Interpreter::
248: * Word Lists::
249: * Environmental Queries::
1.12 anton 250: * Files::
251: * Blocks::
252: * Other I/O::
253: * Programming Tools::
254: * Assembler and Code Words::
255: * Threading Words::
1.26 crook 256: * Locals::
257: * Structures::
258: * Object-oriented Forth::
1.65 anton 259: * Passing Commands to the OS::
260: * Keeping track of Time::
261: * Miscellaneous Words::
1.12 anton 262:
263: Arithmetic
264:
265: * Single precision::
1.67 anton 266: * Double precision:: Double-cell integer arithmetic
1.12 anton 267: * Bitwise operations::
1.67 anton 268: * Numeric comparison::
1.32 anton 269: * Mixed precision:: Operations with single and double-cell integers
1.12 anton 270: * Floating Point::
271:
272: Stack Manipulation
273:
274: * Data stack::
275: * Floating point stack::
276: * Return stack::
277: * Locals stack::
278: * Stack pointer manipulation::
279:
280: Memory
281:
1.32 anton 282: * Memory model::
283: * Dictionary allocation::
284: * Heap Allocation::
285: * Memory Access::
286: * Address arithmetic::
287: * Memory Blocks::
1.12 anton 288:
289: Control Structures
290:
1.41 anton 291: * Selection:: IF ... ELSE ... ENDIF
292: * Simple Loops:: BEGIN ...
1.32 anton 293: * Counted Loops:: DO
1.67 anton 294: * Arbitrary control structures::
295: * Calls and returns::
1.12 anton 296: * Exception Handling::
297:
298: Defining Words
299:
1.67 anton 300: * CREATE::
1.44 crook 301: * Variables:: Variables and user variables
1.67 anton 302: * Constants::
1.44 crook 303: * Values:: Initialised variables
1.67 anton 304: * Colon Definitions::
1.44 crook 305: * Anonymous Definitions:: Definitions without names
1.71 anton 306: * Supplying names:: Passing definition names as strings
1.67 anton 307: * User-defined Defining Words::
1.44 crook 308: * Deferred words:: Allow forward references
1.67 anton 309: * Aliases::
1.47 crook 310:
1.63 anton 311: User-defined Defining Words
312:
313: * CREATE..DOES> applications::
314: * CREATE..DOES> details::
315: * Advanced does> usage example::
316:
1.47 crook 317: Interpretation and Compilation Semantics
318:
1.67 anton 319: * Combined words::
1.12 anton 320:
1.71 anton 321: Tokens for Words
322:
323: * Execution token:: represents execution/interpretation semantics
324: * Compilation token:: represents compilation semantics
325: * Name token:: represents named words
326:
1.21 crook 327: The Text Interpreter
328:
1.67 anton 329: * Input Sources::
330: * Number Conversion::
331: * Interpret/Compile states::
332: * Literals::
333: * Interpreter Directives::
1.21 crook 334:
1.26 crook 335: Word Lists
336:
1.75 anton 337: * Vocabularies::
1.67 anton 338: * Why use word lists?::
1.75 anton 339: * Word list example::
1.26 crook 340:
341: Files
342:
1.48 anton 343: * Forth source files::
344: * General files::
345: * Search Paths::
346:
347: Search Paths
348:
1.75 anton 349: * Source Search Paths::
1.26 crook 350: * General Search Paths::
351:
352: Other I/O
353:
1.32 anton 354: * Simple numeric output:: Predefined formats
355: * Formatted numeric output:: Formatted (pictured) output
356: * String Formats:: How Forth stores strings in memory
1.67 anton 357: * Displaying characters and strings:: Other stuff
1.32 anton 358: * Input:: Input
1.26 crook 359:
360: Programming Tools
361:
1.77 ! anton 362: * Examining::
! 363: * Forgetting words::
1.26 crook 364: * Debugging:: Simple and quick.
365: * Assertions:: Making your programs self-checking.
1.46 pazsan 366: * Singlestep Debugger:: Executing your program word by word.
1.26 crook 367:
1.63 anton 368: Assembler and Code Words
369:
370: * Code and ;code::
371: * Common Assembler:: Assembler Syntax
372: * Common Disassembler::
373: * 386 Assembler:: Deviations and special cases
374: * Alpha Assembler:: Deviations and special cases
375: * MIPS assembler:: Deviations and special cases
376: * Other assemblers:: How to write them
377:
1.26 crook 378: Locals
379:
380: * Gforth locals::
381: * ANS Forth locals::
382:
383: Gforth locals
384:
385: * Where are locals visible by name?::
386: * How long do locals live?::
387: * Programming Style::
388: * Implementation::
389:
1.12 anton 390: Structures
391:
392: * Why explicit structure support?::
393: * Structure Usage::
394: * Structure Naming Convention::
395: * Structure Implementation::
396: * Structure Glossary::
397:
398: Object-oriented Forth
399:
1.48 anton 400: * Why object-oriented programming?::
401: * Object-Oriented Terminology::
402: * Objects::
403: * OOF::
404: * Mini-OOF::
1.23 crook 405: * Comparison with other object models::
1.12 anton 406:
1.24 anton 407: The @file{objects.fs} model
1.12 anton 408:
409: * Properties of the Objects model::
410: * Basic Objects Usage::
1.41 anton 411: * The Objects base class::
1.12 anton 412: * Creating objects::
413: * Object-Oriented Programming Style::
414: * Class Binding::
415: * Method conveniences::
416: * Classes and Scoping::
1.41 anton 417: * Dividing classes::
1.12 anton 418: * Object Interfaces::
419: * Objects Implementation::
420: * Objects Glossary::
421:
1.24 anton 422: The @file{oof.fs} model
1.12 anton 423:
1.67 anton 424: * Properties of the OOF model::
425: * Basic OOF Usage::
426: * The OOF base class::
427: * Class Declaration::
428: * Class Implementation::
1.12 anton 429:
1.24 anton 430: The @file{mini-oof.fs} model
1.23 crook 431:
1.48 anton 432: * Basic Mini-OOF Usage::
433: * Mini-OOF Example::
434: * Mini-OOF Implementation::
1.23 crook 435:
1.12 anton 436: Tools
437:
438: * ANS Report:: Report the words used, sorted by wordset.
439:
440: ANS conformance
441:
442: * The Core Words::
443: * The optional Block word set::
444: * The optional Double Number word set::
445: * The optional Exception word set::
446: * The optional Facility word set::
447: * The optional File-Access word set::
448: * The optional Floating-Point word set::
449: * The optional Locals word set::
450: * The optional Memory-Allocation word set::
451: * The optional Programming-Tools word set::
452: * The optional Search-Order word set::
453:
454: The Core Words
455:
456: * core-idef:: Implementation Defined Options
457: * core-ambcond:: Ambiguous Conditions
458: * core-other:: Other System Documentation
459:
460: The optional Block word set
461:
462: * block-idef:: Implementation Defined Options
463: * block-ambcond:: Ambiguous Conditions
464: * block-other:: Other System Documentation
465:
466: The optional Double Number word set
467:
468: * double-ambcond:: Ambiguous Conditions
469:
470: The optional Exception word set
471:
472: * exception-idef:: Implementation Defined Options
473:
474: The optional Facility word set
475:
476: * facility-idef:: Implementation Defined Options
477: * facility-ambcond:: Ambiguous Conditions
478:
479: The optional File-Access word set
480:
481: * file-idef:: Implementation Defined Options
482: * file-ambcond:: Ambiguous Conditions
483:
484: The optional Floating-Point word set
485:
486: * floating-idef:: Implementation Defined Options
487: * floating-ambcond:: Ambiguous Conditions
488:
489: The optional Locals word set
490:
491: * locals-idef:: Implementation Defined Options
492: * locals-ambcond:: Ambiguous Conditions
493:
494: The optional Memory-Allocation word set
495:
496: * memory-idef:: Implementation Defined Options
497:
498: The optional Programming-Tools word set
499:
500: * programming-idef:: Implementation Defined Options
501: * programming-ambcond:: Ambiguous Conditions
502:
503: The optional Search-Order word set
504:
505: * search-idef:: Implementation Defined Options
506: * search-ambcond:: Ambiguous Conditions
507:
508: Image Files
509:
1.24 anton 510: * Image Licensing Issues:: Distribution terms for images.
511: * Image File Background:: Why have image files?
1.67 anton 512: * Non-Relocatable Image Files:: don't always work.
1.24 anton 513: * Data-Relocatable Image Files:: are better.
1.67 anton 514: * Fully Relocatable Image Files:: better yet.
1.24 anton 515: * Stack and Dictionary Sizes:: Setting the default sizes for an image.
1.32 anton 516: * Running Image Files:: @code{gforth -i @i{file}} or @i{file}.
1.24 anton 517: * Modifying the Startup Sequence:: and turnkey applications.
1.12 anton 518:
519: Fully Relocatable Image Files
520:
1.27 crook 521: * gforthmi:: The normal way
1.12 anton 522: * cross.fs:: The hard way
523:
524: Engine
525:
526: * Portability::
527: * Threading::
528: * Primitives::
529: * Performance::
530:
531: Threading
532:
533: * Scheduling::
534: * Direct or Indirect Threaded?::
535: * DOES>::
536:
537: Primitives
538:
539: * Automatic Generation::
540: * TOS Optimization::
541: * Produced code::
1.13 pazsan 542:
543: Cross Compiler
544:
1.67 anton 545: * Using the Cross Compiler::
546: * How the Cross Compiler Works::
1.13 pazsan 547:
1.24 anton 548: Other Forth-related information
1.21 crook 549:
1.67 anton 550: * Internet resources::
551: * Books::
552: * The Forth Interest Group::
553: * Conferences::
1.21 crook 554:
1.24 anton 555: @end detailmenu
1.1 anton 556: @end menu
557:
1.26 crook 558: @node License, Goals, Top, Top
1.1 anton 559: @unnumbered GNU GENERAL PUBLIC LICENSE
560: @center Version 2, June 1991
561:
562: @display
563: Copyright @copyright{} 1989, 1991 Free Software Foundation, Inc.
564: 675 Mass Ave, Cambridge, MA 02139, USA
565:
566: Everyone is permitted to copy and distribute verbatim copies
567: of this license document, but changing it is not allowed.
568: @end display
569:
570: @unnumberedsec Preamble
571:
572: The licenses for most software are designed to take away your
573: freedom to share and change it. By contrast, the GNU General Public
574: License is intended to guarantee your freedom to share and change free
575: software---to make sure the software is free for all its users. This
576: General Public License applies to most of the Free Software
577: Foundation's software and to any other program whose authors commit to
578: using it. (Some other Free Software Foundation software is covered by
579: the GNU Library General Public License instead.) You can apply it to
580: your programs, too.
581:
582: When we speak of free software, we are referring to freedom, not
583: price. Our General Public Licenses are designed to make sure that you
584: have the freedom to distribute copies of free software (and charge for
585: this service if you wish), that you receive source code or can get it
586: if you want it, that you can change the software or use pieces of it
587: in new free programs; and that you know you can do these things.
588:
589: To protect your rights, we need to make restrictions that forbid
590: anyone to deny you these rights or to ask you to surrender the rights.
591: These restrictions translate to certain responsibilities for you if you
592: distribute copies of the software, or if you modify it.
593:
594: For example, if you distribute copies of such a program, whether
595: gratis or for a fee, you must give the recipients all the rights that
596: you have. You must make sure that they, too, receive or can get the
597: source code. And you must show them these terms so they know their
598: rights.
599:
600: We protect your rights with two steps: (1) copyright the software, and
601: (2) offer you this license which gives you legal permission to copy,
602: distribute and/or modify the software.
603:
604: Also, for each author's protection and ours, we want to make certain
605: that everyone understands that there is no warranty for this free
606: software. If the software is modified by someone else and passed on, we
607: want its recipients to know that what they have is not the original, so
608: that any problems introduced by others will not reflect on the original
609: authors' reputations.
610:
611: Finally, any free program is threatened constantly by software
612: patents. We wish to avoid the danger that redistributors of a free
613: program will individually obtain patent licenses, in effect making the
614: program proprietary. To prevent this, we have made it clear that any
615: patent must be licensed for everyone's free use or not licensed at all.
616:
617: The precise terms and conditions for copying, distribution and
618: modification follow.
619:
620: @iftex
621: @unnumberedsec TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
622: @end iftex
1.49 anton 623: @ifnottex
1.1 anton 624: @center TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
1.49 anton 625: @end ifnottex
1.1 anton 626:
627: @enumerate 0
628: @item
629: This License applies to any program or other work which contains
630: a notice placed by the copyright holder saying it may be distributed
631: under the terms of this General Public License. The ``Program'', below,
632: refers to any such program or work, and a ``work based on the Program''
633: means either the Program or any derivative work under copyright law:
634: that is to say, a work containing the Program or a portion of it,
635: either verbatim or with modifications and/or translated into another
636: language. (Hereinafter, translation is included without limitation in
637: the term ``modification''.) Each licensee is addressed as ``you''.
638:
639: Activities other than copying, distribution and modification are not
640: covered by this License; they are outside its scope. The act of
641: running the Program is not restricted, and the output from the Program
642: is covered only if its contents constitute a work based on the
643: Program (independent of having been made by running the Program).
644: Whether that is true depends on what the Program does.
645:
646: @item
647: You may copy and distribute verbatim copies of the Program's
648: source code as you receive it, in any medium, provided that you
649: conspicuously and appropriately publish on each copy an appropriate
650: copyright notice and disclaimer of warranty; keep intact all the
651: notices that refer to this License and to the absence of any warranty;
652: and give any other recipients of the Program a copy of this License
653: along with the Program.
654:
655: You may charge a fee for the physical act of transferring a copy, and
656: you may at your option offer warranty protection in exchange for a fee.
657:
658: @item
659: You may modify your copy or copies of the Program or any portion
660: of it, thus forming a work based on the Program, and copy and
661: distribute such modifications or work under the terms of Section 1
662: above, provided that you also meet all of these conditions:
663:
664: @enumerate a
665: @item
666: You must cause the modified files to carry prominent notices
667: stating that you changed the files and the date of any change.
668:
669: @item
670: You must cause any work that you distribute or publish, that in
671: whole or in part contains or is derived from the Program or any
672: part thereof, to be licensed as a whole at no charge to all third
673: parties under the terms of this License.
674:
675: @item
676: If the modified program normally reads commands interactively
677: when run, you must cause it, when started running for such
678: interactive use in the most ordinary way, to print or display an
679: announcement including an appropriate copyright notice and a
680: notice that there is no warranty (or else, saying that you provide
681: a warranty) and that users may redistribute the program under
682: these conditions, and telling the user how to view a copy of this
683: License. (Exception: if the Program itself is interactive but
684: does not normally print such an announcement, your work based on
685: the Program is not required to print an announcement.)
686: @end enumerate
687:
688: These requirements apply to the modified work as a whole. If
689: identifiable sections of that work are not derived from the Program,
690: and can be reasonably considered independent and separate works in
691: themselves, then this License, and its terms, do not apply to those
692: sections when you distribute them as separate works. But when you
693: distribute the same sections as part of a whole which is a work based
694: on the Program, the distribution of the whole must be on the terms of
695: this License, whose permissions for other licensees extend to the
696: entire whole, and thus to each and every part regardless of who wrote it.
697:
698: Thus, it is not the intent of this section to claim rights or contest
699: your rights to work written entirely by you; rather, the intent is to
700: exercise the right to control the distribution of derivative or
701: collective works based on the Program.
702:
703: In addition, mere aggregation of another work not based on the Program
704: with the Program (or with a work based on the Program) on a volume of
705: a storage or distribution medium does not bring the other work under
706: the scope of this License.
707:
708: @item
709: You may copy and distribute the Program (or a work based on it,
710: under Section 2) in object code or executable form under the terms of
711: Sections 1 and 2 above provided that you also do one of the following:
712:
713: @enumerate a
714: @item
715: Accompany it with the complete corresponding machine-readable
716: source code, which must be distributed under the terms of Sections
717: 1 and 2 above on a medium customarily used for software interchange; or,
718:
719: @item
720: Accompany it with a written offer, valid for at least three
721: years, to give any third party, for a charge no more than your
722: cost of physically performing source distribution, a complete
723: machine-readable copy of the corresponding source code, to be
724: distributed under the terms of Sections 1 and 2 above on a medium
725: customarily used for software interchange; or,
726:
727: @item
728: Accompany it with the information you received as to the offer
729: to distribute corresponding source code. (This alternative is
730: allowed only for noncommercial distribution and only if you
731: received the program in object code or executable form with such
732: an offer, in accord with Subsection b above.)
733: @end enumerate
734:
735: The source code for a work means the preferred form of the work for
736: making modifications to it. For an executable work, complete source
737: code means all the source code for all modules it contains, plus any
738: associated interface definition files, plus the scripts used to
739: control compilation and installation of the executable. However, as a
740: special exception, the source code distributed need not include
741: anything that is normally distributed (in either source or binary
742: form) with the major components (compiler, kernel, and so on) of the
743: operating system on which the executable runs, unless that component
744: itself accompanies the executable.
745:
746: If distribution of executable or object code is made by offering
747: access to copy from a designated place, then offering equivalent
748: access to copy the source code from the same place counts as
749: distribution of the source code, even though third parties are not
750: compelled to copy the source along with the object code.
751:
752: @item
753: You may not copy, modify, sublicense, or distribute the Program
754: except as expressly provided under this License. Any attempt
755: otherwise to copy, modify, sublicense or distribute the Program is
756: void, and will automatically terminate your rights under this License.
757: However, parties who have received copies, or rights, from you under
758: this License will not have their licenses terminated so long as such
759: parties remain in full compliance.
760:
761: @item
762: You are not required to accept this License, since you have not
763: signed it. However, nothing else grants you permission to modify or
764: distribute the Program or its derivative works. These actions are
765: prohibited by law if you do not accept this License. Therefore, by
766: modifying or distributing the Program (or any work based on the
767: Program), you indicate your acceptance of this License to do so, and
768: all its terms and conditions for copying, distributing or modifying
769: the Program or works based on it.
770:
771: @item
772: Each time you redistribute the Program (or any work based on the
773: Program), the recipient automatically receives a license from the
774: original licensor to copy, distribute or modify the Program subject to
775: these terms and conditions. You may not impose any further
776: restrictions on the recipients' exercise of the rights granted herein.
777: You are not responsible for enforcing compliance by third parties to
778: this License.
779:
780: @item
781: If, as a consequence of a court judgment or allegation of patent
782: infringement or for any other reason (not limited to patent issues),
783: conditions are imposed on you (whether by court order, agreement or
784: otherwise) that contradict the conditions of this License, they do not
785: excuse you from the conditions of this License. If you cannot
786: distribute so as to satisfy simultaneously your obligations under this
787: License and any other pertinent obligations, then as a consequence you
788: may not distribute the Program at all. For example, if a patent
789: license would not permit royalty-free redistribution of the Program by
790: all those who receive copies directly or indirectly through you, then
791: the only way you could satisfy both it and this License would be to
792: refrain entirely from distribution of the Program.
793:
794: If any portion of this section is held invalid or unenforceable under
795: any particular circumstance, the balance of the section is intended to
796: apply and the section as a whole is intended to apply in other
797: circumstances.
798:
799: It is not the purpose of this section to induce you to infringe any
800: patents or other property right claims or to contest validity of any
801: such claims; this section has the sole purpose of protecting the
802: integrity of the free software distribution system, which is
803: implemented by public license practices. Many people have made
804: generous contributions to the wide range of software distributed
805: through that system in reliance on consistent application of that
806: system; it is up to the author/donor to decide if he or she is willing
807: to distribute software through any other system and a licensee cannot
808: impose that choice.
809:
810: This section is intended to make thoroughly clear what is believed to
811: be a consequence of the rest of this License.
812:
813: @item
814: If the distribution and/or use of the Program is restricted in
815: certain countries either by patents or by copyrighted interfaces, the
816: original copyright holder who places the Program under this License
817: may add an explicit geographical distribution limitation excluding
818: those countries, so that distribution is permitted only in or among
819: countries not thus excluded. In such case, this License incorporates
820: the limitation as if written in the body of this License.
821:
822: @item
823: The Free Software Foundation may publish revised and/or new versions
824: of the General Public License from time to time. Such new versions will
825: be similar in spirit to the present version, but may differ in detail to
826: address new problems or concerns.
827:
828: Each version is given a distinguishing version number. If the Program
829: specifies a version number of this License which applies to it and ``any
830: later version'', you have the option of following the terms and conditions
831: either of that version or of any later version published by the Free
832: Software Foundation. If the Program does not specify a version number of
833: this License, you may choose any version ever published by the Free Software
834: Foundation.
835:
836: @item
837: If you wish to incorporate parts of the Program into other free
838: programs whose distribution conditions are different, write to the author
839: to ask for permission. For software which is copyrighted by the Free
840: Software Foundation, write to the Free Software Foundation; we sometimes
841: make exceptions for this. Our decision will be guided by the two goals
842: of preserving the free status of all derivatives of our free software and
843: of promoting the sharing and reuse of software generally.
844:
845: @iftex
846: @heading NO WARRANTY
847: @end iftex
1.49 anton 848: @ifnottex
1.1 anton 849: @center NO WARRANTY
1.49 anton 850: @end ifnottex
1.1 anton 851:
852: @item
853: BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
854: FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
855: OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
856: PROVIDE THE PROGRAM ``AS IS'' WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
857: OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
858: MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
859: TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
860: PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
861: REPAIR OR CORRECTION.
862:
863: @item
864: IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
865: WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
866: REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
867: INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
868: OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
869: TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
870: YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
871: PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
872: POSSIBILITY OF SUCH DAMAGES.
873: @end enumerate
874:
875: @iftex
876: @heading END OF TERMS AND CONDITIONS
877: @end iftex
1.49 anton 878: @ifnottex
1.1 anton 879: @center END OF TERMS AND CONDITIONS
1.49 anton 880: @end ifnottex
1.1 anton 881:
882: @page
883: @unnumberedsec How to Apply These Terms to Your New Programs
884:
885: If you develop a new program, and you want it to be of the greatest
886: possible use to the public, the best way to achieve this is to make it
887: free software which everyone can redistribute and change under these terms.
888:
889: To do so, attach the following notices to the program. It is safest
890: to attach them to the start of each source file to most effectively
891: convey the exclusion of warranty; and each file should have at least
892: the ``copyright'' line and a pointer to where the full notice is found.
893:
894: @smallexample
895: @var{one line to give the program's name and a brief idea of what it does.}
896: Copyright (C) 19@var{yy} @var{name of author}
897:
898: This program is free software; you can redistribute it and/or modify
899: it under the terms of the GNU General Public License as published by
900: the Free Software Foundation; either version 2 of the License, or
901: (at your option) any later version.
902:
903: This program is distributed in the hope that it will be useful,
904: but WITHOUT ANY WARRANTY; without even the implied warranty of
905: MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
906: GNU General Public License for more details.
907:
908: You should have received a copy of the GNU General Public License
909: along with this program; if not, write to the Free Software
910: Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
911: @end smallexample
912:
913: Also add information on how to contact you by electronic and paper mail.
914:
915: If the program is interactive, make it output a short notice like this
916: when it starts in an interactive mode:
917:
918: @smallexample
919: Gnomovision version 69, Copyright (C) 19@var{yy} @var{name of author}
920: Gnomovision comes with ABSOLUTELY NO WARRANTY; for details
921: type `show w'.
922: This is free software, and you are welcome to redistribute it
923: under certain conditions; type `show c' for details.
924: @end smallexample
925:
926: The hypothetical commands @samp{show w} and @samp{show c} should show
927: the appropriate parts of the General Public License. Of course, the
928: commands you use may be called something other than @samp{show w} and
929: @samp{show c}; they could even be mouse-clicks or menu items---whatever
930: suits your program.
931:
932: You should also get your employer (if you work as a programmer) or your
933: school, if any, to sign a ``copyright disclaimer'' for the program, if
934: necessary. Here is a sample; alter the names:
935:
936: @smallexample
937: Yoyodyne, Inc., hereby disclaims all copyright interest in the program
938: `Gnomovision' (which makes passes at compilers) written by James Hacker.
939:
940: @var{signature of Ty Coon}, 1 April 1989
941: Ty Coon, President of Vice
942: @end smallexample
943:
944: This General Public License does not permit incorporating your program into
945: proprietary programs. If your program is a subroutine library, you may
946: consider it more useful to permit linking proprietary applications with the
947: library. If this is what you want to do, use the GNU Library General
948: Public License instead of this License.
949:
950: @iftex
951: @unnumbered Preface
952: @cindex Preface
1.21 crook 953: This manual documents Gforth. Some introductory material is provided for
954: readers who are unfamiliar with Forth or who are migrating to Gforth
955: from other Forth compilers. However, this manual is primarily a
956: reference manual.
1.1 anton 957: @end iftex
958:
1.28 crook 959: @comment TODO much more blurb here.
1.26 crook 960:
961: @c ******************************************************************
1.29 crook 962: @node Goals, Gforth Environment, License, Top
1.26 crook 963: @comment node-name, next, previous, up
964: @chapter Goals of Gforth
965: @cindex goals of the Gforth project
966: The goal of the Gforth Project is to develop a standard model for
967: ANS Forth. This can be split into several subgoals:
968:
969: @itemize @bullet
970: @item
971: Gforth should conform to the ANS Forth Standard.
972: @item
973: It should be a model, i.e. it should define all the
974: implementation-dependent things.
975: @item
976: It should become standard, i.e. widely accepted and used. This goal
977: is the most difficult one.
978: @end itemize
979:
980: To achieve these goals Gforth should be
981: @itemize @bullet
982: @item
983: Similar to previous models (fig-Forth, F83)
984: @item
985: Powerful. It should provide for all the things that are considered
986: necessary today and even some that are not yet considered necessary.
987: @item
988: Efficient. It should not get the reputation of being exceptionally
989: slow.
990: @item
991: Free.
992: @item
993: Available on many machines/easy to port.
994: @end itemize
995:
996: Have we achieved these goals? Gforth conforms to the ANS Forth
997: standard. It may be considered a model, but we have not yet documented
998: which parts of the model are stable and which parts we are likely to
999: change. It certainly has not yet become a de facto standard, but it
1000: appears to be quite popular. It has some similarities to and some
1001: differences from previous models. It has some powerful features, but not
1002: yet everything that we envisioned. We certainly have achieved our
1.65 anton 1003: execution speed goals (@pxref{Performance})@footnote{However, in 1998
1004: the bar was raised when the major commercial Forth vendors switched to
1005: native code compilers.}. It is free and available on many machines.
1.29 crook 1006:
1.26 crook 1007: @c ******************************************************************
1.48 anton 1008: @node Gforth Environment, Tutorial, Goals, Top
1.29 crook 1009: @chapter Gforth Environment
1010: @cindex Gforth environment
1.21 crook 1011:
1.45 crook 1012: Note: ultimately, the Gforth man page will be auto-generated from the
1.29 crook 1013: material in this chapter.
1.21 crook 1014:
1015: @menu
1.29 crook 1016: * Invoking Gforth:: Getting in
1017: * Leaving Gforth:: Getting out
1018: * Command-line editing::
1.48 anton 1019: * Environment variables:: that affect how Gforth starts up
1.29 crook 1020: * Gforth Files:: What gets installed and where
1.48 anton 1021: * Startup speed:: When 35ms is not fast enough ...
1.21 crook 1022: @end menu
1023:
1.49 anton 1024: For related information about the creation of images see @ref{Image Files}.
1.29 crook 1025:
1.21 crook 1026: @comment ----------------------------------------------
1.48 anton 1027: @node Invoking Gforth, Leaving Gforth, Gforth Environment, Gforth Environment
1.29 crook 1028: @section Invoking Gforth
1029: @cindex invoking Gforth
1030: @cindex running Gforth
1031: @cindex command-line options
1032: @cindex options on the command line
1033: @cindex flags on the command line
1.21 crook 1034:
1.30 anton 1035: Gforth is made up of two parts; an executable ``engine'' (named
1036: @file{gforth} or @file{gforth-fast}) and an image file. To start it, you
1037: will usually just say @code{gforth} -- this automatically loads the
1038: default image file @file{gforth.fi}. In many other cases the default
1039: Gforth image will be invoked like this:
1.21 crook 1040: @example
1.30 anton 1041: gforth [file | -e forth-code] ...
1.21 crook 1042: @end example
1.29 crook 1043: @noindent
1044: This interprets the contents of the files and the Forth code in the order they
1045: are given.
1.21 crook 1046:
1.30 anton 1047: In addition to the @file{gforth} engine, there is also an engine called
1048: @file{gforth-fast}, which is faster, but gives less informative error
1049: messages (@pxref{Error messages}).
1050:
1.29 crook 1051: In general, the command line looks like this:
1.21 crook 1052:
1053: @example
1.30 anton 1054: gforth[-fast] [engine options] [image options]
1.21 crook 1055: @end example
1056:
1.30 anton 1057: The engine options must come before the rest of the command
1.29 crook 1058: line. They are:
1.26 crook 1059:
1.29 crook 1060: @table @code
1061: @cindex -i, command-line option
1062: @cindex --image-file, command-line option
1063: @item --image-file @i{file}
1064: @itemx -i @i{file}
1065: Loads the Forth image @i{file} instead of the default
1066: @file{gforth.fi} (@pxref{Image Files}).
1.21 crook 1067:
1.39 anton 1068: @cindex --appl-image, command-line option
1069: @item --appl-image @i{file}
1070: Loads the image @i{file} and leaves all further command-line arguments
1.65 anton 1071: to the image (instead of processing them as engine options). This is
1072: useful for building executable application images on Unix, built with
1.39 anton 1073: @code{gforthmi --application ...}.
1074:
1.29 crook 1075: @cindex --path, command-line option
1076: @cindex -p, command-line option
1077: @item --path @i{path}
1078: @itemx -p @i{path}
1079: Uses @i{path} for searching the image file and Forth source code files
1080: instead of the default in the environment variable @code{GFORTHPATH} or
1081: the path specified at installation time (e.g.,
1082: @file{/usr/local/share/gforth/0.2.0:.}). A path is given as a list of
1083: directories, separated by @samp{:} (on Unix) or @samp{;} (on other OSs).
1.21 crook 1084:
1.29 crook 1085: @cindex --dictionary-size, command-line option
1086: @cindex -m, command-line option
1087: @cindex @i{size} parameters for command-line options
1088: @cindex size of the dictionary and the stacks
1089: @item --dictionary-size @i{size}
1090: @itemx -m @i{size}
1091: Allocate @i{size} space for the Forth dictionary space instead of
1092: using the default specified in the image (typically 256K). The
1093: @i{size} specification for this and subsequent options consists of
1094: an integer and a unit (e.g.,
1095: @code{4M}). The unit can be one of @code{b} (bytes), @code{e} (element
1096: size, in this case Cells), @code{k} (kilobytes), @code{M} (Megabytes),
1097: @code{G} (Gigabytes), and @code{T} (Terabytes). If no unit is specified,
1098: @code{e} is used.
1.21 crook 1099:
1.29 crook 1100: @cindex --data-stack-size, command-line option
1101: @cindex -d, command-line option
1102: @item --data-stack-size @i{size}
1103: @itemx -d @i{size}
1104: Allocate @i{size} space for the data stack instead of using the
1105: default specified in the image (typically 16K).
1.21 crook 1106:
1.29 crook 1107: @cindex --return-stack-size, command-line option
1108: @cindex -r, command-line option
1109: @item --return-stack-size @i{size}
1110: @itemx -r @i{size}
1111: Allocate @i{size} space for the return stack instead of using the
1112: default specified in the image (typically 15K).
1.21 crook 1113:
1.29 crook 1114: @cindex --fp-stack-size, command-line option
1115: @cindex -f, command-line option
1116: @item --fp-stack-size @i{size}
1117: @itemx -f @i{size}
1118: Allocate @i{size} space for the floating point stack instead of
1119: using the default specified in the image (typically 15.5K). In this case
1120: the unit specifier @code{e} refers to floating point numbers.
1.21 crook 1121:
1.48 anton 1122: @cindex --locals-stack-size, command-line option
1123: @cindex -l, command-line option
1124: @item --locals-stack-size @i{size}
1125: @itemx -l @i{size}
1126: Allocate @i{size} space for the locals stack instead of using the
1127: default specified in the image (typically 14.5K).
1128:
1129: @cindex -h, command-line option
1130: @cindex --help, command-line option
1131: @item --help
1132: @itemx -h
1133: Print a message about the command-line options
1134:
1135: @cindex -v, command-line option
1136: @cindex --version, command-line option
1137: @item --version
1138: @itemx -v
1139: Print version and exit
1140:
1141: @cindex --debug, command-line option
1142: @item --debug
1143: Print some information useful for debugging on startup.
1144:
1145: @cindex --offset-image, command-line option
1146: @item --offset-image
1147: Start the dictionary at a slightly different position than would be used
1148: otherwise (useful for creating data-relocatable images,
1149: @pxref{Data-Relocatable Image Files}).
1150:
1151: @cindex --no-offset-im, command-line option
1152: @item --no-offset-im
1153: Start the dictionary at the normal position.
1154:
1155: @cindex --clear-dictionary, command-line option
1156: @item --clear-dictionary
1157: Initialize all bytes in the dictionary to 0 before loading the image
1158: (@pxref{Data-Relocatable Image Files}).
1159:
1160: @cindex --die-on-signal, command-line-option
1161: @item --die-on-signal
1162: Normally Gforth handles most signals (e.g., the user interrupt SIGINT,
1163: or the segmentation violation SIGSEGV) by translating it into a Forth
1164: @code{THROW}. With this option, Gforth exits if it receives such a
1165: signal. This option is useful when the engine and/or the image might be
1166: severely broken (such that it causes another signal before recovering
1167: from the first); this option avoids endless loops in such cases.
1168: @end table
1169:
1170: @cindex loading files at startup
1171: @cindex executing code on startup
1172: @cindex batch processing with Gforth
1173: As explained above, the image-specific command-line arguments for the
1174: default image @file{gforth.fi} consist of a sequence of filenames and
1175: @code{-e @var{forth-code}} options that are interpreted in the sequence
1176: in which they are given. The @code{-e @var{forth-code}} or
1177: @code{--evaluate @var{forth-code}} option evaluates the Forth
1178: code. This option takes only one argument; if you want to evaluate more
1179: Forth words, you have to quote them or use @code{-e} several times. To exit
1180: after processing the command line (instead of entering interactive mode)
1181: append @code{-e bye} to the command line.
1182:
1183: @cindex versions, invoking other versions of Gforth
1184: If you have several versions of Gforth installed, @code{gforth} will
1185: invoke the version that was installed last. @code{gforth-@i{version}}
1186: invokes a specific version. If your environment contains the variable
1187: @code{GFORTHPATH}, you may want to override it by using the
1188: @code{--path} option.
1189:
1190: Not yet implemented:
1191: On startup the system first executes the system initialization file
1192: (unless the option @code{--no-init-file} is given; note that the system
1193: resulting from using this option may not be ANS Forth conformant). Then
1194: the user initialization file @file{.gforth.fs} is executed, unless the
1.62 crook 1195: option @code{--no-rc} is given; this file is searched for in @file{.},
1.48 anton 1196: then in @file{~}, then in the normal path (see above).
1197:
1198:
1199:
1200: @comment ----------------------------------------------
1201: @node Leaving Gforth, Command-line editing, Invoking Gforth, Gforth Environment
1202: @section Leaving Gforth
1203: @cindex Gforth - leaving
1204: @cindex leaving Gforth
1205:
1206: You can leave Gforth by typing @code{bye} or @kbd{Ctrl-d} (at the start
1207: of a line) or (if you invoked Gforth with the @code{--die-on-signal}
1208: option) @kbd{Ctrl-c}. When you leave Gforth, all of your definitions and
1.49 anton 1209: data are discarded. For ways of saving the state of the system before
1210: leaving Gforth see @ref{Image Files}.
1.48 anton 1211:
1212: doc-bye
1213:
1214:
1215: @comment ----------------------------------------------
1.65 anton 1216: @node Command-line editing, Environment variables, Leaving Gforth, Gforth Environment
1.48 anton 1217: @section Command-line editing
1218: @cindex command-line editing
1219:
1220: Gforth maintains a history file that records every line that you type to
1221: the text interpreter. This file is preserved between sessions, and is
1222: used to provide a command-line recall facility; if you type @kbd{Ctrl-P}
1223: repeatedly you can recall successively older commands from this (or
1224: previous) session(s). The full list of command-line editing facilities is:
1225:
1226: @itemize @bullet
1227: @item
1228: @kbd{Ctrl-p} (``previous'') (or up-arrow) to recall successively older
1229: commands from the history buffer.
1230: @item
1231: @kbd{Ctrl-n} (``next'') (or down-arrow) to recall successively newer commands
1232: from the history buffer.
1233: @item
1234: @kbd{Ctrl-f} (or right-arrow) to move the cursor right, non-destructively.
1235: @item
1236: @kbd{Ctrl-b} (or left-arrow) to move the cursor left, non-destructively.
1237: @item
1238: @kbd{Ctrl-h} (backspace) to delete the character to the left of the cursor,
1239: closing up the line.
1240: @item
1241: @kbd{Ctrl-k} to delete (``kill'') from the cursor to the end of the line.
1242: @item
1243: @kbd{Ctrl-a} to move the cursor to the start of the line.
1244: @item
1245: @kbd{Ctrl-e} to move the cursor to the end of the line.
1246: @item
1247: @key{RET} (@kbd{Ctrl-m}) or @key{LFD} (@kbd{Ctrl-j}) to submit the current
1248: line.
1249: @item
1250: @key{TAB} to step through all possible full-word completions of the word
1251: currently being typed.
1252: @item
1.65 anton 1253: @kbd{Ctrl-d} on an empty line line to terminate Gforth (gracefully,
1254: using @code{bye}).
1255: @item
1256: @kbd{Ctrl-x} (or @code{Ctrl-d} on a non-empty line) to delete the
1257: character under the cursor.
1.48 anton 1258: @end itemize
1259:
1260: When editing, displayable characters are inserted to the left of the
1261: cursor position; the line is always in ``insert'' (as opposed to
1262: ``overstrike'') mode.
1263:
1264: @cindex history file
1265: @cindex @file{.gforth-history}
1266: On Unix systems, the history file is @file{~/.gforth-history} by
1267: default@footnote{i.e. it is stored in the user's home directory.}. You
1268: can find out the name and location of your history file using:
1269:
1270: @example
1271: history-file type \ Unix-class systems
1272:
1273: history-file type \ Other systems
1274: history-dir type
1275: @end example
1276:
1277: If you enter long definitions by hand, you can use a text editor to
1278: paste them out of the history file into a Forth source file for reuse at
1279: a later time.
1280:
1281: Gforth never trims the size of the history file, so you should do this
1282: periodically, if necessary.
1283:
1284: @comment this is all defined in history.fs
1285: @comment NAC TODO the ctrl-D behaviour can either do a bye or a beep.. how is that option
1286: @comment chosen?
1287:
1288:
1289: @comment ----------------------------------------------
1.65 anton 1290: @node Environment variables, Gforth Files, Command-line editing, Gforth Environment
1.48 anton 1291: @section Environment variables
1292: @cindex environment variables
1293:
1294: Gforth uses these environment variables:
1295:
1296: @itemize @bullet
1297: @item
1298: @cindex @code{GFORTHHIST} -- environment variable
1299: @code{GFORTHHIST} -- (Unix systems only) specifies the directory in which to
1300: open/create the history file, @file{.gforth-history}. Default:
1301: @code{$HOME}.
1302:
1303: @item
1304: @cindex @code{GFORTHPATH} -- environment variable
1305: @code{GFORTHPATH} -- specifies the path used when searching for the gforth image file and
1306: for Forth source-code files.
1307:
1308: @item
1309: @cindex @code{GFORTH} -- environment variable
1.49 anton 1310: @code{GFORTH} -- used by @file{gforthmi}, @xref{gforthmi}.
1.48 anton 1311:
1312: @item
1313: @cindex @code{GFORTHD} -- environment variable
1.62 crook 1314: @code{GFORTHD} -- used by @file{gforthmi}, @xref{gforthmi}.
1.48 anton 1315:
1316: @item
1317: @cindex @code{TMP}, @code{TEMP} - environment variable
1318: @code{TMP}, @code{TEMP} - (non-Unix systems only) used as a potential
1319: location for the history file.
1320: @end itemize
1321:
1322: @comment also POSIXELY_CORRECT LINES COLUMNS HOME but no interest in
1323: @comment mentioning these.
1324:
1325: All the Gforth environment variables default to sensible values if they
1326: are not set.
1327:
1328:
1329: @comment ----------------------------------------------
1330: @node Gforth Files, Startup speed, Environment variables, Gforth Environment
1331: @section Gforth files
1332: @cindex Gforth files
1333:
1334: When you install Gforth on a Unix system, it installs files in these
1335: locations by default:
1336:
1337: @itemize @bullet
1338: @item
1339: @file{/usr/local/bin/gforth}
1340: @item
1341: @file{/usr/local/bin/gforthmi}
1342: @item
1343: @file{/usr/local/man/man1/gforth.1} - man page.
1344: @item
1345: @file{/usr/local/info} - the Info version of this manual.
1346: @item
1347: @file{/usr/local/lib/gforth/<version>/...} - Gforth @file{.fi} files.
1348: @item
1349: @file{/usr/local/share/gforth/<version>/TAGS} - Emacs TAGS file.
1350: @item
1351: @file{/usr/local/share/gforth/<version>/...} - Gforth source files.
1352: @item
1353: @file{.../emacs/site-lisp/gforth.el} - Emacs gforth mode.
1354: @end itemize
1355:
1356: You can select different places for installation by using
1357: @code{configure} options (listed with @code{configure --help}).
1358:
1359: @comment ----------------------------------------------
1360: @node Startup speed, , Gforth Files, Gforth Environment
1361: @section Startup speed
1362: @cindex Startup speed
1363: @cindex speed, startup
1364:
1365: If Gforth is used for CGI scripts or in shell scripts, its startup
1366: speed may become a problem. On a 300MHz 21064a under Linux-2.2.13 with
1367: glibc-2.0.7, @code{gforth -e bye} takes about 24.6ms user and 11.3ms
1368: system time.
1369:
1370: If startup speed is a problem, you may consider the following ways to
1371: improve it; or you may consider ways to reduce the number of startups
1.62 crook 1372: (for example, by using Fast-CGI).
1.48 anton 1373:
1374: The first step to improve startup speed is to statically link Gforth, by
1375: building it with @code{XLDFLAGS=-static}. This requires more memory for
1376: the code and will therefore slow down the first invocation, but
1377: subsequent invocations avoid the dynamic linking overhead. Another
1378: disadvantage is that Gforth won't profit from library upgrades. As a
1379: result, @code{gforth-static -e bye} takes about 17.1ms user and
1380: 8.2ms system time.
1381:
1382: The next step to improve startup speed is to use a non-relocatable image
1.65 anton 1383: (@pxref{Non-Relocatable Image Files}). You can create this image with
1.48 anton 1384: @code{gforth -e "savesystem gforthnr.fi bye"} and later use it with
1385: @code{gforth -i gforthnr.fi ...}. This avoids the relocation overhead
1386: and a part of the copy-on-write overhead. The disadvantage is that the
1.62 crook 1387: non-relocatable image does not work if the OS gives Gforth a different
1.48 anton 1388: address for the dictionary, for whatever reason; so you better provide a
1389: fallback on a relocatable image. @code{gforth-static -i gforthnr.fi -e
1390: bye} takes about 15.3ms user and 7.5ms system time.
1391:
1392: The final step is to disable dictionary hashing in Gforth. Gforth
1393: builds the hash table on startup, which takes much of the startup
1394: overhead. You can do this by commenting out the @code{include hash.fs}
1395: in @file{startup.fs} and everything that requires @file{hash.fs} (at the
1396: moment @file{table.fs} and @file{ekey.fs}) and then doing @code{make}.
1397: The disadvantages are that functionality like @code{table} and
1398: @code{ekey} is missing and that text interpretation (e.g., compiling)
1399: now takes much longer. So, you should only use this method if there is
1400: no significant text interpretation to perform (the script should be
1.62 crook 1401: compiled into the image, amongst other things). @code{gforth-static -i
1.48 anton 1402: gforthnrnh.fi -e bye} takes about 2.1ms user and 6.1ms system time.
1403:
1404: @c ******************************************************************
1405: @node Tutorial, Introduction, Gforth Environment, Top
1406: @chapter Forth Tutorial
1407: @cindex Tutorial
1408: @cindex Forth Tutorial
1409:
1.67 anton 1410: @c Topics from nac's Introduction that could be mentioned:
1411: @c press <ret> after each line
1412: @c Prompt
1413: @c numbers vs. words in dictionary on text interpretation
1414: @c what happens on redefinition
1415: @c parsing words (in particular, defining words)
1416:
1.62 crook 1417: This tutorial can be used with any ANS-compliant Forth; any
1418: Gforth-specific features are marked as such and you can skip them if you
1419: work with another Forth. This tutorial does not explain all features of
1420: Forth, just enough to get you started and give you some ideas about the
1421: facilities available in Forth. Read the rest of the manual and the
1422: standard when you are through this.
1.48 anton 1423:
1424: The intended way to use this tutorial is that you work through it while
1425: sitting in front of the console, take a look at the examples and predict
1426: what they will do, then try them out; if the outcome is not as expected,
1427: find out why (e.g., by trying out variations of the example), so you
1428: understand what's going on. There are also some assignments that you
1429: should solve.
1430:
1431: This tutorial assumes that you have programmed before and know what,
1432: e.g., a loop is.
1433:
1434: @c !! explain compat library
1435:
1436: @menu
1437: * Starting Gforth Tutorial::
1438: * Syntax Tutorial::
1439: * Crash Course Tutorial::
1440: * Stack Tutorial::
1441: * Arithmetics Tutorial::
1442: * Stack Manipulation Tutorial::
1443: * Using files for Forth code Tutorial::
1444: * Comments Tutorial::
1445: * Colon Definitions Tutorial::
1446: * Decompilation Tutorial::
1447: * Stack-Effect Comments Tutorial::
1448: * Types Tutorial::
1449: * Factoring Tutorial::
1450: * Designing the stack effect Tutorial::
1451: * Local Variables Tutorial::
1452: * Conditional execution Tutorial::
1453: * Flags and Comparisons Tutorial::
1454: * General Loops Tutorial::
1455: * Counted loops Tutorial::
1456: * Recursion Tutorial::
1457: * Leaving definitions or loops Tutorial::
1458: * Return Stack Tutorial::
1459: * Memory Tutorial::
1460: * Characters and Strings Tutorial::
1461: * Alignment Tutorial::
1462: * Interpretation and Compilation Semantics and Immediacy Tutorial::
1463: * Execution Tokens Tutorial::
1464: * Exceptions Tutorial::
1465: * Defining Words Tutorial::
1466: * Arrays and Records Tutorial::
1467: * POSTPONE Tutorial::
1468: * Literal Tutorial::
1469: * Advanced macros Tutorial::
1470: * Compilation Tokens Tutorial::
1471: * Wordlists and Search Order Tutorial::
1472: @end menu
1473:
1474: @node Starting Gforth Tutorial, Syntax Tutorial, Tutorial, Tutorial
1475: @section Starting Gforth
1.66 anton 1476: @cindex starting Gforth tutorial
1.48 anton 1477: You can start Gforth by typing its name:
1478:
1479: @example
1480: gforth
1481: @end example
1482:
1483: That puts you into interactive mode; you can leave Gforth by typing
1484: @code{bye}. While in Gforth, you can edit the command line and access
1485: the command line history with cursor keys, similar to bash.
1486:
1487:
1488: @node Syntax Tutorial, Crash Course Tutorial, Starting Gforth Tutorial, Tutorial
1489: @section Syntax
1.66 anton 1490: @cindex syntax tutorial
1.48 anton 1491:
1492: A @dfn{word} is a sequence of arbitrary characters (expcept white
1493: space). Words are separated by white space. E.g., each of the
1494: following lines contains exactly one word:
1495:
1496: @example
1497: word
1498: !@@#$%^&*()
1499: 1234567890
1500: 5!a
1501: @end example
1502:
1503: A frequent beginner's error is to leave away necessary white space,
1504: resulting in an error like @samp{Undefined word}; so if you see such an
1505: error, check if you have put spaces wherever necessary.
1506:
1507: @example
1508: ." hello, world" \ correct
1509: ."hello, world" \ gives an "Undefined word" error
1510: @end example
1511:
1.65 anton 1512: Gforth and most other Forth systems ignore differences in case (they are
1.48 anton 1513: case-insensitive), i.e., @samp{word} is the same as @samp{Word}. If
1514: your system is case-sensitive, you may have to type all the examples
1515: given here in upper case.
1516:
1517:
1518: @node Crash Course Tutorial, Stack Tutorial, Syntax Tutorial, Tutorial
1519: @section Crash Course
1520:
1521: Type
1522:
1523: @example
1524: 0 0 !
1525: here execute
1526: ' catch >body 20 erase abort
1527: ' (quit) >body 20 erase
1528: @end example
1529:
1530: The last two examples are guaranteed to destroy parts of Gforth (and
1531: most other systems), so you better leave Gforth afterwards (if it has
1532: not finished by itself). On some systems you may have to kill gforth
1533: from outside (e.g., in Unix with @code{kill}).
1534:
1535: Now that you know how to produce crashes (and that there's not much to
1536: them), let's learn how to produce meaningful programs.
1537:
1538:
1539: @node Stack Tutorial, Arithmetics Tutorial, Crash Course Tutorial, Tutorial
1540: @section Stack
1.66 anton 1541: @cindex stack tutorial
1.48 anton 1542:
1543: The most obvious feature of Forth is the stack. When you type in a
1544: number, it is pushed on the stack. You can display the content of the
1545: stack with @code{.s}.
1546:
1547: @example
1548: 1 2 .s
1549: 3 .s
1550: @end example
1551:
1552: @code{.s} displays the top-of-stack to the right, i.e., the numbers
1553: appear in @code{.s} output as they appeared in the input.
1554:
1555: You can print the top of stack element with @code{.}.
1556:
1557: @example
1558: 1 2 3 . . .
1559: @end example
1560:
1561: In general, words consume their stack arguments (@code{.s} is an
1562: exception).
1563:
1564: @assignment
1565: What does the stack contain after @code{5 6 7 .}?
1566: @endassignment
1567:
1568:
1569: @node Arithmetics Tutorial, Stack Manipulation Tutorial, Stack Tutorial, Tutorial
1570: @section Arithmetics
1.66 anton 1571: @cindex arithmetics tutorial
1.48 anton 1572:
1573: The words @code{+}, @code{-}, @code{*}, @code{/}, and @code{mod} always
1574: operate on the top two stack items:
1575:
1576: @example
1.67 anton 1577: 2 2 .s
1578: + .s
1579: .
1.48 anton 1580: 2 1 - .
1581: 7 3 mod .
1582: @end example
1583:
1584: The operands of @code{-}, @code{/}, and @code{mod} are in the same order
1585: as in the corresponding infix expression (this is generally the case in
1586: Forth).
1587:
1588: Parentheses are superfluous (and not available), because the order of
1589: the words unambiguously determines the order of evaluation and the
1590: operands:
1591:
1592: @example
1593: 3 4 + 5 * .
1594: 3 4 5 * + .
1595: @end example
1596:
1597: @assignment
1598: What are the infix expressions corresponding to the Forth code above?
1599: Write @code{6-7*8+9} in Forth notation@footnote{This notation is also
1600: known as Postfix or RPN (Reverse Polish Notation).}.
1601: @endassignment
1602:
1603: To change the sign, use @code{negate}:
1604:
1605: @example
1606: 2 negate .
1607: @end example
1608:
1609: @assignment
1610: Convert -(-3)*4-5 to Forth.
1611: @endassignment
1612:
1613: @code{/mod} performs both @code{/} and @code{mod}.
1614:
1615: @example
1616: 7 3 /mod . .
1617: @end example
1618:
1.66 anton 1619: Reference: @ref{Arithmetic}.
1620:
1621:
1.48 anton 1622: @node Stack Manipulation Tutorial, Using files for Forth code Tutorial, Arithmetics Tutorial, Tutorial
1623: @section Stack Manipulation
1.66 anton 1624: @cindex stack manipulation tutorial
1.48 anton 1625:
1626: Stack manipulation words rearrange the data on the stack.
1627:
1628: @example
1629: 1 .s drop .s
1630: 1 .s dup .s drop drop .s
1631: 1 2 .s over .s drop drop drop
1632: 1 2 .s swap .s drop drop
1633: 1 2 3 .s rot .s drop drop drop
1634: @end example
1635:
1636: These are the most important stack manipulation words. There are also
1637: variants that manipulate twice as many stack items:
1638:
1639: @example
1640: 1 2 3 4 .s 2swap .s 2drop 2drop
1641: @end example
1642:
1643: Two more stack manipulation words are:
1644:
1645: @example
1646: 1 2 .s nip .s drop
1647: 1 2 .s tuck .s 2drop drop
1648: @end example
1649:
1650: @assignment
1651: Replace @code{nip} and @code{tuck} with combinations of other stack
1652: manipulation words.
1653:
1654: @example
1655: Given: How do you get:
1656: 1 2 3 3 2 1
1657: 1 2 3 1 2 3 2
1658: 1 2 3 1 2 3 3
1659: 1 2 3 1 3 3
1660: 1 2 3 2 1 3
1661: 1 2 3 4 4 3 2 1
1662: 1 2 3 1 2 3 1 2 3
1663: 1 2 3 4 1 2 3 4 1 2
1664: 1 2 3
1665: 1 2 3 1 2 3 4
1666: 1 2 3 1 3
1667: @end example
1668: @endassignment
1669:
1670: @example
1671: 5 dup * .
1672: @end example
1673:
1674: @assignment
1675: Write 17^3 and 17^4 in Forth, without writing @code{17} more than once.
1676: Write a piece of Forth code that expects two numbers on the stack
1677: (@var{a} and @var{b}, with @var{b} on top) and computes
1678: @code{(a-b)(a+1)}.
1679: @endassignment
1680:
1.66 anton 1681: Reference: @ref{Stack Manipulation}.
1682:
1683:
1.48 anton 1684: @node Using files for Forth code Tutorial, Comments Tutorial, Stack Manipulation Tutorial, Tutorial
1685: @section Using files for Forth code
1.66 anton 1686: @cindex loading Forth code, tutorial
1687: @cindex files containing Forth code, tutorial
1.48 anton 1688:
1689: While working at the Forth command line is convenient for one-line
1690: examples and short one-off code, you probably want to store your source
1691: code in files for convenient editing and persistence. You can use your
1692: favourite editor (Gforth includes Emacs support, @pxref{Emacs and
1693: Gforth}) to create @var{file} and use
1694:
1695: @example
1696: s" @var{file}" included
1697: @end example
1698:
1699: to load it into your Forth system. The file name extension I use for
1700: Forth files is @samp{.fs}.
1701:
1702: You can easily start Gforth with some files loaded like this:
1703:
1704: @example
1705: gforth @var{file1} @var{file2}
1706: @end example
1707:
1708: If an error occurs during loading these files, Gforth terminates,
1709: whereas an error during @code{INCLUDED} within Gforth usually gives you
1710: a Gforth command line. Starting the Forth system every time gives you a
1711: clean start every time, without interference from the results of earlier
1712: tries.
1713:
1714: I often put all the tests in a file, then load the code and run the
1715: tests with
1716:
1717: @example
1718: gforth @var{code} @var{tests} -e bye
1719: @end example
1720:
1721: (often by performing this command with @kbd{C-x C-e} in Emacs). The
1722: @code{-e bye} ensures that Gforth terminates afterwards so that I can
1723: restart this command without ado.
1724:
1725: The advantage of this approach is that the tests can be repeated easily
1726: every time the program ist changed, making it easy to catch bugs
1727: introduced by the change.
1728:
1.66 anton 1729: Reference: @ref{Forth source files}.
1730:
1.48 anton 1731:
1732: @node Comments Tutorial, Colon Definitions Tutorial, Using files for Forth code Tutorial, Tutorial
1733: @section Comments
1.66 anton 1734: @cindex comments tutorial
1.48 anton 1735:
1736: @example
1737: \ That's a comment; it ends at the end of the line
1738: ( Another comment; it ends here: ) .s
1739: @end example
1740:
1741: @code{\} and @code{(} are ordinary Forth words and therefore have to be
1742: separated with white space from the following text.
1743:
1744: @example
1745: \This gives an "Undefined word" error
1746: @end example
1747:
1748: The first @code{)} ends a comment started with @code{(}, so you cannot
1749: nest @code{(}-comments; and you cannot comment out text containing a
1750: @code{)} with @code{( ... )}@footnote{therefore it's a good idea to
1751: avoid @code{)} in word names.}.
1752:
1753: I use @code{\}-comments for descriptive text and for commenting out code
1754: of one or more line; I use @code{(}-comments for describing the stack
1755: effect, the stack contents, or for commenting out sub-line pieces of
1756: code.
1757:
1758: The Emacs mode @file{gforth.el} (@pxref{Emacs and Gforth}) supports
1759: these uses by commenting out a region with @kbd{C-x \}, uncommenting a
1760: region with @kbd{C-u C-x \}, and filling a @code{\}-commented region
1761: with @kbd{M-q}.
1762:
1.66 anton 1763: Reference: @ref{Comments}.
1764:
1.48 anton 1765:
1766: @node Colon Definitions Tutorial, Decompilation Tutorial, Comments Tutorial, Tutorial
1767: @section Colon Definitions
1.66 anton 1768: @cindex colon definitions, tutorial
1769: @cindex definitions, tutorial
1770: @cindex procedures, tutorial
1771: @cindex functions, tutorial
1.48 anton 1772:
1773: are similar to procedures and functions in other programming languages.
1774:
1775: @example
1776: : squared ( n -- n^2 )
1777: dup * ;
1778: 5 squared .
1779: 7 squared .
1780: @end example
1781:
1782: @code{:} starts the colon definition; its name is @code{squared}. The
1783: following comment describes its stack effect. The words @code{dup *}
1784: are not executed, but compiled into the definition. @code{;} ends the
1785: colon definition.
1786:
1787: The newly-defined word can be used like any other word, including using
1788: it in other definitions:
1789:
1790: @example
1791: : cubed ( n -- n^3 )
1792: dup squared * ;
1793: -5 cubed .
1794: : fourth-power ( n -- n^4 )
1795: squared squared ;
1796: 3 fourth-power .
1797: @end example
1798:
1799: @assignment
1800: Write colon definitions for @code{nip}, @code{tuck}, @code{negate}, and
1801: @code{/mod} in terms of other Forth words, and check if they work (hint:
1802: test your tests on the originals first). Don't let the
1803: @samp{redefined}-Messages spook you, they are just warnings.
1804: @endassignment
1805:
1.66 anton 1806: Reference: @ref{Colon Definitions}.
1807:
1.48 anton 1808:
1809: @node Decompilation Tutorial, Stack-Effect Comments Tutorial, Colon Definitions Tutorial, Tutorial
1810: @section Decompilation
1.66 anton 1811: @cindex decompilation tutorial
1812: @cindex see tutorial
1.48 anton 1813:
1814: You can decompile colon definitions with @code{see}:
1815:
1816: @example
1817: see squared
1818: see cubed
1819: @end example
1820:
1821: In Gforth @code{see} shows you a reconstruction of the source code from
1822: the executable code. Informations that were present in the source, but
1823: not in the executable code, are lost (e.g., comments).
1824:
1.65 anton 1825: You can also decompile the predefined words:
1826:
1827: @example
1828: see .
1829: see +
1830: @end example
1831:
1832:
1.48 anton 1833: @node Stack-Effect Comments Tutorial, Types Tutorial, Decompilation Tutorial, Tutorial
1834: @section Stack-Effect Comments
1.66 anton 1835: @cindex stack-effect comments, tutorial
1836: @cindex --, tutorial
1.48 anton 1837: By convention the comment after the name of a definition describes the
1838: stack effect: The part in from of the @samp{--} describes the state of
1839: the stack before the execution of the definition, i.e., the parameters
1840: that are passed into the colon definition; the part behind the @samp{--}
1841: is the state of the stack after the execution of the definition, i.e.,
1842: the results of the definition. The stack comment only shows the top
1843: stack items that the definition accesses and/or changes.
1844:
1845: You should put a correct stack effect on every definition, even if it is
1846: just @code{( -- )}. You should also add some descriptive comment to
1847: more complicated words (I usually do this in the lines following
1848: @code{:}). If you don't do this, your code becomes unreadable (because
1849: you have to work through every definition before you can undertsand
1850: any).
1851:
1852: @assignment
1853: The stack effect of @code{swap} can be written like this: @code{x1 x2 --
1854: x2 x1}. Describe the stack effect of @code{-}, @code{drop}, @code{dup},
1855: @code{over}, @code{rot}, @code{nip}, and @code{tuck}. Hint: When you
1.65 anton 1856: are done, you can compare your stack effects to those in this manual
1.48 anton 1857: (@pxref{Word Index}).
1858: @endassignment
1859:
1860: Sometimes programmers put comments at various places in colon
1861: definitions that describe the contents of the stack at that place (stack
1862: comments); i.e., they are like the first part of a stack-effect
1863: comment. E.g.,
1864:
1865: @example
1866: : cubed ( n -- n^3 )
1867: dup squared ( n n^2 ) * ;
1868: @end example
1869:
1870: In this case the stack comment is pretty superfluous, because the word
1871: is simple enough. If you think it would be a good idea to add such a
1872: comment to increase readability, you should also consider factoring the
1873: word into several simpler words (@pxref{Factoring Tutorial,,
1.60 anton 1874: Factoring}), which typically eliminates the need for the stack comment;
1.48 anton 1875: however, if you decide not to refactor it, then having such a comment is
1876: better than not having it.
1877:
1878: The names of the stack items in stack-effect and stack comments in the
1879: standard, in this manual, and in many programs specify the type through
1880: a type prefix, similar to Fortran and Hungarian notation. The most
1881: frequent prefixes are:
1882:
1883: @table @code
1884: @item n
1885: signed integer
1886: @item u
1887: unsigned integer
1888: @item c
1889: character
1890: @item f
1891: Boolean flags, i.e. @code{false} or @code{true}.
1892: @item a-addr,a-
1893: Cell-aligned address
1894: @item c-addr,c-
1895: Char-aligned address (note that a Char may have two bytes in Windows NT)
1896: @item xt
1897: Execution token, same size as Cell
1898: @item w,x
1899: Cell, can contain an integer or an address. It usually takes 32, 64 or
1900: 16 bits (depending on your platform and Forth system). A cell is more
1901: commonly known as machine word, but the term @emph{word} already means
1902: something different in Forth.
1903: @item d
1904: signed double-cell integer
1905: @item ud
1906: unsigned double-cell integer
1907: @item r
1908: Float (on the FP stack)
1909: @end table
1910:
1911: You can find a more complete list in @ref{Notation}.
1912:
1913: @assignment
1914: Write stack-effect comments for all definitions you have written up to
1915: now.
1916: @endassignment
1917:
1918:
1919: @node Types Tutorial, Factoring Tutorial, Stack-Effect Comments Tutorial, Tutorial
1920: @section Types
1.66 anton 1921: @cindex types tutorial
1.48 anton 1922:
1923: In Forth the names of the operations are not overloaded; so similar
1924: operations on different types need different names; e.g., @code{+} adds
1925: integers, and you have to use @code{f+} to add floating-point numbers.
1926: The following prefixes are often used for related operations on
1927: different types:
1928:
1929: @table @code
1930: @item (none)
1931: signed integer
1932: @item u
1933: unsigned integer
1934: @item c
1935: character
1936: @item d
1937: signed double-cell integer
1938: @item ud, du
1939: unsigned double-cell integer
1940: @item 2
1941: two cells (not-necessarily double-cell numbers)
1942: @item m, um
1943: mixed single-cell and double-cell operations
1944: @item f
1945: floating-point (note that in stack comments @samp{f} represents flags,
1.66 anton 1946: and @samp{r} represents FP numbers).
1.48 anton 1947: @end table
1948:
1949: If there are no differences between the signed and the unsigned variant
1950: (e.g., for @code{+}), there is only the prefix-less variant.
1951:
1952: Forth does not perform type checking, neither at compile time, nor at
1953: run time. If you use the wrong oeration, the data are interpreted
1954: incorrectly:
1955:
1956: @example
1957: -1 u.
1958: @end example
1959:
1960: If you have only experience with type-checked languages until now, and
1961: have heard how important type-checking is, don't panic! In my
1962: experience (and that of other Forthers), type errors in Forth code are
1963: usually easy to find (once you get used to it), the increased vigilance
1964: of the programmer tends to catch some harder errors in addition to most
1965: type errors, and you never have to work around the type system, so in
1966: most situations the lack of type-checking seems to be a win (projects to
1967: add type checking to Forth have not caught on).
1968:
1969:
1970: @node Factoring Tutorial, Designing the stack effect Tutorial, Types Tutorial, Tutorial
1971: @section Factoring
1.66 anton 1972: @cindex factoring tutorial
1.48 anton 1973:
1974: If you try to write longer definitions, you will soon find it hard to
1975: keep track of the stack contents. Therefore, good Forth programmers
1976: tend to write only short definitions (e.g., three lines). The art of
1977: finding meaningful short definitions is known as factoring (as in
1978: factoring polynomials).
1979:
1980: Well-factored programs offer additional advantages: smaller, more
1981: general words, are easier to test and debug and can be reused more and
1982: better than larger, specialized words.
1983:
1984: So, if you run into difficulties with stack management, when writing
1985: code, try to define meaningful factors for the word, and define the word
1986: in terms of those. Even if a factor contains only two words, it is
1987: often helpful.
1988:
1.65 anton 1989: Good factoring is not easy, and it takes some practice to get the knack
1990: for it; but even experienced Forth programmers often don't find the
1991: right solution right away, but only when rewriting the program. So, if
1992: you don't come up with a good solution immediately, keep trying, don't
1993: despair.
1.48 anton 1994:
1995: @c example !!
1996:
1997:
1998: @node Designing the stack effect Tutorial, Local Variables Tutorial, Factoring Tutorial, Tutorial
1999: @section Designing the stack effect
1.66 anton 2000: @cindex Stack effect design, tutorial
2001: @cindex design of stack effects, tutorial
1.48 anton 2002:
2003: In other languages you can use an arbitrary order of parameters for a
1.65 anton 2004: function; and since there is only one result, you don't have to deal with
1.48 anton 2005: the order of results, either.
2006:
2007: In Forth (and other stack-based languages, e.g., Postscript) the
2008: parameter and result order of a definition is important and should be
2009: designed well. The general guideline is to design the stack effect such
2010: that the word is simple to use in most cases, even if that complicates
2011: the implementation of the word. Some concrete rules are:
2012:
2013: @itemize @bullet
2014:
2015: @item
2016: Words consume all of their parameters (e.g., @code{.}).
2017:
2018: @item
2019: If there is a convention on the order of parameters (e.g., from
2020: mathematics or another programming language), stick with it (e.g.,
2021: @code{-}).
2022:
2023: @item
2024: If one parameter usually requires only a short computation (e.g., it is
2025: a constant), pass it on the top of the stack. Conversely, parameters
2026: that usually require a long sequence of code to compute should be passed
2027: as the bottom (i.e., first) parameter. This makes the code easier to
2028: read, because reader does not need to keep track of the bottom item
2029: through a long sequence of code (or, alternatively, through stack
1.49 anton 2030: manipulations). E.g., @code{!} (store, @pxref{Memory}) expects the
1.48 anton 2031: address on top of the stack because it is usually simpler to compute
2032: than the stored value (often the address is just a variable).
2033:
2034: @item
2035: Similarly, results that are usually consumed quickly should be returned
2036: on the top of stack, whereas a result that is often used in long
2037: computations should be passed as bottom result. E.g., the file words
2038: like @code{open-file} return the error code on the top of stack, because
2039: it is usually consumed quickly by @code{throw}; moreover, the error code
2040: has to be checked before doing anything with the other results.
2041:
2042: @end itemize
2043:
2044: These rules are just general guidelines, don't lose sight of the overall
2045: goal to make the words easy to use. E.g., if the convention rule
2046: conflicts with the computation-length rule, you might decide in favour
2047: of the convention if the word will be used rarely, and in favour of the
2048: computation-length rule if the word will be used frequently (because
2049: with frequent use the cost of breaking the computation-length rule would
2050: be quite high, and frequent use makes it easier to remember an
2051: unconventional order).
2052:
2053: @c example !! structure package
2054:
1.65 anton 2055:
1.48 anton 2056: @node Local Variables Tutorial, Conditional execution Tutorial, Designing the stack effect Tutorial, Tutorial
2057: @section Local Variables
1.66 anton 2058: @cindex local variables, tutorial
1.48 anton 2059:
2060: You can define local variables (@emph{locals}) in a colon definition:
2061:
2062: @example
2063: : swap @{ a b -- b a @}
2064: b a ;
2065: 1 2 swap .s 2drop
2066: @end example
2067:
2068: (If your Forth system does not support this syntax, include
2069: @file{compat/anslocals.fs} first).
2070:
2071: In this example @code{@{ a b -- b a @}} is the locals definition; it
2072: takes two cells from the stack, puts the top of stack in @code{b} and
2073: the next stack element in @code{a}. @code{--} starts a comment ending
2074: with @code{@}}. After the locals definition, using the name of the
2075: local will push its value on the stack. You can leave the comment
2076: part (@code{-- b a}) away:
2077:
2078: @example
2079: : swap ( x1 x2 -- x2 x1 )
2080: @{ a b @} b a ;
2081: @end example
2082:
2083: In Gforth you can have several locals definitions, anywhere in a colon
2084: definition; in contrast, in a standard program you can have only one
2085: locals definition per colon definition, and that locals definition must
2086: be outside any controll structure.
2087:
2088: With locals you can write slightly longer definitions without running
2089: into stack trouble. However, I recommend trying to write colon
2090: definitions without locals for exercise purposes to help you gain the
2091: essential factoring skills.
2092:
2093: @assignment
2094: Rewrite your definitions until now with locals
2095: @endassignment
2096:
1.66 anton 2097: Reference: @ref{Locals}.
2098:
1.48 anton 2099:
2100: @node Conditional execution Tutorial, Flags and Comparisons Tutorial, Local Variables Tutorial, Tutorial
2101: @section Conditional execution
1.66 anton 2102: @cindex conditionals, tutorial
2103: @cindex if, tutorial
1.48 anton 2104:
2105: In Forth you can use control structures only inside colon definitions.
2106: An @code{if}-structure looks like this:
2107:
2108: @example
2109: : abs ( n1 -- +n2 )
2110: dup 0 < if
2111: negate
2112: endif ;
2113: 5 abs .
2114: -5 abs .
2115: @end example
2116:
2117: @code{if} takes a flag from the stack. If the flag is non-zero (true),
2118: the following code is performed, otherwise execution continues after the
1.51 pazsan 2119: @code{endif} (or @code{else}). @code{<} compares the top two stack
1.48 anton 2120: elements and prioduces a flag:
2121:
2122: @example
2123: 1 2 < .
2124: 2 1 < .
2125: 1 1 < .
2126: @end example
2127:
2128: Actually the standard name for @code{endif} is @code{then}. This
2129: tutorial presents the examples using @code{endif}, because this is often
2130: less confusing for people familiar with other programming languages
2131: where @code{then} has a different meaning. If your system does not have
2132: @code{endif}, define it with
2133:
2134: @example
2135: : endif postpone then ; immediate
2136: @end example
2137:
2138: You can optionally use an @code{else}-part:
2139:
2140: @example
2141: : min ( n1 n2 -- n )
2142: 2dup < if
2143: drop
2144: else
2145: nip
2146: endif ;
2147: 2 3 min .
2148: 3 2 min .
2149: @end example
2150:
2151: @assignment
2152: Write @code{min} without @code{else}-part (hint: what's the definition
2153: of @code{nip}?).
2154: @endassignment
2155:
1.66 anton 2156: Reference: @ref{Selection}.
2157:
1.48 anton 2158:
2159: @node Flags and Comparisons Tutorial, General Loops Tutorial, Conditional execution Tutorial, Tutorial
2160: @section Flags and Comparisons
1.66 anton 2161: @cindex flags tutorial
2162: @cindex comparison tutorial
1.48 anton 2163:
2164: In a false-flag all bits are clear (0 when interpreted as integer). In
2165: a canonical true-flag all bits are set (-1 as a twos-complement signed
2166: integer); in many contexts (e.g., @code{if}) any non-zero value is
2167: treated as true flag.
2168:
2169: @example
2170: false .
2171: true .
2172: true hex u. decimal
2173: @end example
2174:
2175: Comparison words produce canonical flags:
2176:
2177: @example
2178: 1 1 = .
2179: 1 0= .
2180: 0 1 < .
2181: 0 0 < .
2182: -1 1 u< . \ type error, u< interprets -1 as large unsigned number
2183: -1 1 < .
2184: @end example
2185:
1.66 anton 2186: Gforth supports all combinations of the prefixes @code{0 u d d0 du f f0}
2187: (or none) and the comparisons @code{= <> < > <= >=}. Only a part of
2188: these combinations are standard (for details see the standard,
2189: @ref{Numeric comparison}, @ref{Floating Point} or @ref{Word Index}).
1.48 anton 2190:
2191: You can use @code{and or xor invert} can be used as operations on
2192: canonical flags. Actually they are bitwise operations:
2193:
2194: @example
2195: 1 2 and .
2196: 1 2 or .
2197: 1 3 xor .
2198: 1 invert .
2199: @end example
2200:
2201: You can convert a zero/non-zero flag into a canonical flag with
2202: @code{0<>} (and complement it on the way with @code{0=}).
2203:
2204: @example
2205: 1 0= .
2206: 1 0<> .
2207: @end example
2208:
1.65 anton 2209: You can use the all-bits-set feature of canonical flags and the bitwise
1.48 anton 2210: operation of the Boolean operations to avoid @code{if}s:
2211:
2212: @example
2213: : foo ( n1 -- n2 )
2214: 0= if
2215: 14
2216: else
2217: 0
2218: endif ;
2219: 0 foo .
2220: 1 foo .
2221:
2222: : foo ( n1 -- n2 )
2223: 0= 14 and ;
2224: 0 foo .
2225: 1 foo .
2226: @end example
2227:
2228: @assignment
2229: Write @code{min} without @code{if}.
2230: @endassignment
2231:
1.66 anton 2232: For reference, see @ref{Boolean Flags}, @ref{Numeric comparison}, and
2233: @ref{Bitwise operations}.
2234:
1.48 anton 2235:
2236: @node General Loops Tutorial, Counted loops Tutorial, Flags and Comparisons Tutorial, Tutorial
2237: @section General Loops
1.66 anton 2238: @cindex loops, indefinite, tutorial
1.48 anton 2239:
2240: The endless loop is the most simple one:
2241:
2242: @example
2243: : endless ( -- )
2244: 0 begin
2245: dup . 1+
2246: again ;
2247: endless
2248: @end example
2249:
2250: Terminate this loop by pressing @kbd{Ctrl-C} (in Gforth). @code{begin}
2251: does nothing at run-time, @code{again} jumps back to @code{begin}.
2252:
2253: A loop with one exit at any place looks like this:
2254:
2255: @example
2256: : log2 ( +n1 -- n2 )
2257: \ logarithmus dualis of n1>0, rounded down to the next integer
2258: assert( dup 0> )
2259: 2/ 0 begin
2260: over 0> while
2261: 1+ swap 2/ swap
2262: repeat
2263: nip ;
2264: 7 log2 .
2265: 8 log2 .
2266: @end example
2267:
2268: At run-time @code{while} consumes a flag; if it is 0, execution
1.51 pazsan 2269: continues behind the @code{repeat}; if the flag is non-zero, execution
1.48 anton 2270: continues behind the @code{while}. @code{Repeat} jumps back to
2271: @code{begin}, just like @code{again}.
2272:
2273: In Forth there are many combinations/abbreviations, like @code{1+}.
2274: However, @code{2/} is not one of them; it shifts it's argument right by
2275: one bit (arithmetic shift right):
2276:
2277: @example
2278: -5 2 / .
2279: -5 2/ .
2280: @end example
2281:
2282: @code{assert(} is no standard word, but you can get it on systems other
2283: then Gforth by including @file{compat/assert.fs}. You can see what it
2284: does by trying
2285:
2286: @example
2287: 0 log2 .
2288: @end example
2289:
2290: Here's a loop with an exit at the end:
2291:
2292: @example
2293: : log2 ( +n1 -- n2 )
2294: \ logarithmus dualis of n1>0, rounded down to the next integer
2295: assert( dup 0 > )
2296: -1 begin
2297: 1+ swap 2/ swap
2298: over 0 <=
2299: until
2300: nip ;
2301: @end example
2302:
2303: @code{Until} consumes a flag; if it is non-zero, execution continues at
2304: the @code{begin}, otherwise after the @code{until}.
2305:
2306: @assignment
2307: Write a definition for computing the greatest common divisor.
2308: @endassignment
2309:
1.66 anton 2310: Reference: @ref{Simple Loops}.
2311:
1.48 anton 2312:
2313: @node Counted loops Tutorial, Recursion Tutorial, General Loops Tutorial, Tutorial
2314: @section Counted loops
1.66 anton 2315: @cindex loops, counted, tutorial
1.48 anton 2316:
2317: @example
2318: : ^ ( n1 u -- n )
2319: \ n = the uth power of u1
2320: 1 swap 0 u+do
2321: over *
2322: loop
2323: nip ;
2324: 3 2 ^ .
2325: 4 3 ^ .
2326: @end example
2327:
2328: @code{U+do} (from @file{compat/loops.fs}, if your Forth system doesn't
2329: have it) takes two numbers of the stack @code{( u3 u4 -- )}, and then
2330: performs the code between @code{u+do} and @code{loop} for @code{u3-u4}
2331: times (or not at all, if @code{u3-u4<0}).
2332:
2333: You can see the stack effect design rules at work in the stack effect of
2334: the loop start words: Since the start value of the loop is more
2335: frequently constant than the end value, the start value is passed on
2336: the top-of-stack.
2337:
2338: You can access the counter of a counted loop with @code{i}:
2339:
2340: @example
2341: : fac ( u -- u! )
2342: 1 swap 1+ 1 u+do
2343: i *
2344: loop ;
2345: 5 fac .
2346: 7 fac .
2347: @end example
2348:
2349: There is also @code{+do}, which expects signed numbers (important for
2350: deciding whether to enter the loop).
2351:
2352: @assignment
2353: Write a definition for computing the nth Fibonacci number.
2354: @endassignment
2355:
1.65 anton 2356: You can also use increments other than 1:
2357:
2358: @example
2359: : up2 ( n1 n2 -- )
2360: +do
2361: i .
2362: 2 +loop ;
2363: 10 0 up2
2364:
2365: : down2 ( n1 n2 -- )
2366: -do
2367: i .
2368: 2 -loop ;
2369: 0 10 down2
2370: @end example
1.48 anton 2371:
1.66 anton 2372: Reference: @ref{Counted Loops}.
2373:
1.48 anton 2374:
2375: @node Recursion Tutorial, Leaving definitions or loops Tutorial, Counted loops Tutorial, Tutorial
2376: @section Recursion
1.66 anton 2377: @cindex recursion tutorial
1.48 anton 2378:
2379: Usually the name of a definition is not visible in the definition; but
2380: earlier definitions are usually visible:
2381:
2382: @example
2383: 1 0 / . \ "Floating-point unidentified fault" in Gforth on most platforms
2384: : / ( n1 n2 -- n )
2385: dup 0= if
2386: -10 throw \ report division by zero
2387: endif
2388: / \ old version
2389: ;
2390: 1 0 /
2391: @end example
2392:
2393: For recursive definitions you can use @code{recursive} (non-standard) or
2394: @code{recurse}:
2395:
2396: @example
2397: : fac1 ( n -- n! ) recursive
2398: dup 0> if
2399: dup 1- fac1 *
2400: else
2401: drop 1
2402: endif ;
2403: 7 fac1 .
2404:
2405: : fac2 ( n -- n! )
2406: dup 0> if
2407: dup 1- recurse *
2408: else
2409: drop 1
2410: endif ;
2411: 8 fac2 .
2412: @end example
2413:
2414: @assignment
2415: Write a recursive definition for computing the nth Fibonacci number.
2416: @endassignment
2417:
1.66 anton 2418: Reference (including indirect recursion): @xref{Calls and returns}.
2419:
1.48 anton 2420:
2421: @node Leaving definitions or loops Tutorial, Return Stack Tutorial, Recursion Tutorial, Tutorial
2422: @section Leaving definitions or loops
1.66 anton 2423: @cindex leaving definitions, tutorial
2424: @cindex leaving loops, tutorial
1.48 anton 2425:
2426: @code{EXIT} exits the current definition right away. For every counted
2427: loop that is left in this way, an @code{UNLOOP} has to be performed
2428: before the @code{EXIT}:
2429:
2430: @c !! real examples
2431: @example
2432: : ...
2433: ... u+do
2434: ... if
2435: ... unloop exit
2436: endif
2437: ...
2438: loop
2439: ... ;
2440: @end example
2441:
2442: @code{LEAVE} leaves the innermost counted loop right away:
2443:
2444: @example
2445: : ...
2446: ... u+do
2447: ... if
2448: ... leave
2449: endif
2450: ...
2451: loop
2452: ... ;
2453: @end example
2454:
1.65 anton 2455: @c !! example
1.48 anton 2456:
1.66 anton 2457: Reference: @ref{Calls and returns}, @ref{Counted Loops}.
2458:
2459:
1.48 anton 2460: @node Return Stack Tutorial, Memory Tutorial, Leaving definitions or loops Tutorial, Tutorial
2461: @section Return Stack
1.66 anton 2462: @cindex return stack tutorial
1.48 anton 2463:
2464: In addition to the data stack Forth also has a second stack, the return
2465: stack; most Forth systems store the return addresses of procedure calls
2466: there (thus its name). Programmers can also use this stack:
2467:
2468: @example
2469: : foo ( n1 n2 -- )
2470: .s
2471: >r .s
1.50 anton 2472: r@@ .
1.48 anton 2473: >r .s
1.50 anton 2474: r@@ .
1.48 anton 2475: r> .
1.50 anton 2476: r@@ .
1.48 anton 2477: r> . ;
2478: 1 2 foo
2479: @end example
2480:
2481: @code{>r} takes an element from the data stack and pushes it onto the
2482: return stack; conversely, @code{r>} moves an elementm from the return to
2483: the data stack; @code{r@@} pushes a copy of the top of the return stack
2484: on the return stack.
2485:
2486: Forth programmers usually use the return stack for storing data
2487: temporarily, if using the data stack alone would be too complex, and
2488: factoring and locals are not an option:
2489:
2490: @example
2491: : 2swap ( x1 x2 x3 x4 -- x3 x4 x1 x2 )
2492: rot >r rot r> ;
2493: @end example
2494:
2495: The return address of the definition and the loop control parameters of
2496: counted loops usually reside on the return stack, so you have to take
2497: all items, that you have pushed on the return stack in a colon
2498: definition or counted loop, from the return stack before the definition
2499: or loop ends. You cannot access items that you pushed on the return
2500: stack outside some definition or loop within the definition of loop.
2501:
2502: If you miscount the return stack items, this usually ends in a crash:
2503:
2504: @example
2505: : crash ( n -- )
2506: >r ;
2507: 5 crash
2508: @end example
2509:
2510: You cannot mix using locals and using the return stack (according to the
2511: standard; Gforth has no problem). However, they solve the same
2512: problems, so this shouldn't be an issue.
2513:
2514: @assignment
2515: Can you rewrite any of the definitions you wrote until now in a better
2516: way using the return stack?
2517: @endassignment
2518:
1.66 anton 2519: Reference: @ref{Return stack}.
2520:
1.48 anton 2521:
2522: @node Memory Tutorial, Characters and Strings Tutorial, Return Stack Tutorial, Tutorial
2523: @section Memory
1.66 anton 2524: @cindex memory access/allocation tutorial
1.48 anton 2525:
2526: You can create a global variable @code{v} with
2527:
2528: @example
2529: variable v ( -- addr )
2530: @end example
2531:
2532: @code{v} pushes the address of a cell in memory on the stack. This cell
2533: was reserved by @code{variable}. You can use @code{!} (store) to store
2534: values into this cell and @code{@@} (fetch) to load the value from the
2535: stack into memory:
2536:
2537: @example
2538: v .
2539: 5 v ! .s
1.50 anton 2540: v @@ .
1.48 anton 2541: @end example
2542:
1.65 anton 2543: You can see a raw dump of memory with @code{dump}:
2544:
2545: @example
2546: v 1 cells .s dump
2547: @end example
2548:
2549: @code{Cells ( n1 -- n2 )} gives you the number of bytes (or, more
2550: generally, address units (aus)) that @code{n1 cells} occupy. You can
2551: also reserve more memory:
1.48 anton 2552:
2553: @example
2554: create v2 20 cells allot
1.65 anton 2555: v2 20 cells dump
1.48 anton 2556: @end example
2557:
1.65 anton 2558: creates a word @code{v2} and reserves 20 uninitialized cells; the
2559: address pushed by @code{v2} points to the start of these 20 cells. You
2560: can use address arithmetic to access these cells:
1.48 anton 2561:
2562: @example
2563: 3 v2 5 cells + !
1.65 anton 2564: v2 20 cells dump
1.48 anton 2565: @end example
2566:
2567: You can reserve and initialize memory with @code{,}:
2568:
2569: @example
2570: create v3
2571: 5 , 4 , 3 , 2 , 1 ,
1.50 anton 2572: v3 @@ .
2573: v3 cell+ @@ .
2574: v3 2 cells + @@ .
1.65 anton 2575: v3 5 cells dump
1.48 anton 2576: @end example
2577:
2578: @assignment
2579: Write a definition @code{vsum ( addr u -- n )} that computes the sum of
2580: @code{u} cells, with the first of these cells at @code{addr}, the next
2581: one at @code{addr cell+} etc.
2582: @endassignment
2583:
2584: You can also reserve memory without creating a new word:
2585:
2586: @example
1.60 anton 2587: here 10 cells allot .
2588: here .
1.48 anton 2589: @end example
2590:
2591: @code{Here} pushes the start address of the memory area. You should
2592: store it somewhere, or you will have a hard time finding the memory area
2593: again.
2594:
2595: @code{Allot} manages dictionary memory. The dictionary memory contains
2596: the system's data structures for words etc. on Gforth and most other
2597: Forth systems. It is managed like a stack: You can free the memory that
2598: you have just @code{allot}ed with
2599:
2600: @example
2601: -10 cells allot
1.60 anton 2602: here .
1.48 anton 2603: @end example
2604:
2605: Note that you cannot do this if you have created a new word in the
2606: meantime (because then your @code{allot}ed memory is no longer on the
2607: top of the dictionary ``stack'').
2608:
2609: Alternatively, you can use @code{allocate} and @code{free} which allow
2610: freeing memory in any order:
2611:
2612: @example
2613: 10 cells allocate throw .s
2614: 20 cells allocate throw .s
2615: swap
2616: free throw
2617: free throw
2618: @end example
2619:
2620: The @code{throw}s deal with errors (e.g., out of memory).
2621:
1.65 anton 2622: And there is also a
2623: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
2624: garbage collector}, which eliminates the need to @code{free} memory
2625: explicitly.
1.48 anton 2626:
1.66 anton 2627: Reference: @ref{Memory}.
2628:
1.48 anton 2629:
2630: @node Characters and Strings Tutorial, Alignment Tutorial, Memory Tutorial, Tutorial
2631: @section Characters and Strings
1.66 anton 2632: @cindex strings tutorial
2633: @cindex characters tutorial
1.48 anton 2634:
2635: On the stack characters take up a cell, like numbers. In memory they
2636: have their own size (one 8-bit byte on most systems), and therefore
2637: require their own words for memory access:
2638:
2639: @example
2640: create v4
2641: 104 c, 97 c, 108 c, 108 c, 111 c,
1.50 anton 2642: v4 4 chars + c@@ .
1.65 anton 2643: v4 5 chars dump
1.48 anton 2644: @end example
2645:
2646: The preferred representation of strings on the stack is @code{addr
2647: u-count}, where @code{addr} is the address of the first character and
2648: @code{u-count} is the number of characters in the string.
2649:
2650: @example
2651: v4 5 type
2652: @end example
2653:
2654: You get a string constant with
2655:
2656: @example
2657: s" hello, world" .s
2658: type
2659: @end example
2660:
2661: Make sure you have a space between @code{s"} and the string; @code{s"}
2662: is a normal Forth word and must be delimited with white space (try what
2663: happens when you remove the space).
2664:
2665: However, this interpretive use of @code{s"} is quite restricted: the
2666: string exists only until the next call of @code{s"} (some Forth systems
2667: keep more than one of these strings, but usually they still have a
1.62 crook 2668: limited lifetime).
1.48 anton 2669:
2670: @example
2671: s" hello," s" world" .s
2672: type
2673: type
2674: @end example
2675:
1.62 crook 2676: You can also use @code{s"} in a definition, and the resulting
2677: strings then live forever (well, for as long as the definition):
1.48 anton 2678:
2679: @example
2680: : foo s" hello," s" world" ;
2681: foo .s
2682: type
2683: type
2684: @end example
2685:
2686: @assignment
2687: @code{Emit ( c -- )} types @code{c} as character (not a number).
2688: Implement @code{type ( addr u -- )}.
2689: @endassignment
2690:
1.66 anton 2691: Reference: @ref{Memory Blocks}.
2692:
2693:
1.48 anton 2694: @node Alignment Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Characters and Strings Tutorial, Tutorial
2695: @section Alignment
1.66 anton 2696: @cindex alignment tutorial
2697: @cindex memory alignment tutorial
1.48 anton 2698:
2699: On many processors cells have to be aligned in memory, if you want to
2700: access them with @code{@@} and @code{!} (and even if the processor does
1.62 crook 2701: not require alignment, access to aligned cells is faster).
1.48 anton 2702:
2703: @code{Create} aligns @code{here} (i.e., the place where the next
2704: allocation will occur, and that the @code{create}d word points to).
2705: Likewise, the memory produced by @code{allocate} starts at an aligned
2706: address. Adding a number of @code{cells} to an aligned address produces
2707: another aligned address.
2708:
2709: However, address arithmetic involving @code{char+} and @code{chars} can
2710: create an address that is not cell-aligned. @code{Aligned ( addr --
2711: a-addr )} produces the next aligned address:
2712:
2713: @example
1.50 anton 2714: v3 char+ aligned .s @@ .
2715: v3 char+ .s @@ .
1.48 anton 2716: @end example
2717:
2718: Similarly, @code{align} advances @code{here} to the next aligned
2719: address:
2720:
2721: @example
2722: create v5 97 c,
2723: here .
2724: align here .
2725: 1000 ,
2726: @end example
2727:
2728: Note that you should use aligned addresses even if your processor does
2729: not require them, if you want your program to be portable.
2730:
1.66 anton 2731: Reference: @ref{Address arithmetic}.
2732:
1.48 anton 2733:
2734: @node Interpretation and Compilation Semantics and Immediacy Tutorial, Execution Tokens Tutorial, Alignment Tutorial, Tutorial
2735: @section Interpretation and Compilation Semantics and Immediacy
1.66 anton 2736: @cindex semantics tutorial
2737: @cindex interpretation semantics tutorial
2738: @cindex compilation semantics tutorial
2739: @cindex immediate, tutorial
1.48 anton 2740:
2741: When a word is compiled, it behaves differently from being interpreted.
2742: E.g., consider @code{+}:
2743:
2744: @example
2745: 1 2 + .
2746: : foo + ;
2747: @end example
2748:
2749: These two behaviours are known as compilation and interpretation
2750: semantics. For normal words (e.g., @code{+}), the compilation semantics
2751: is to append the interpretation semantics to the currently defined word
2752: (@code{foo} in the example above). I.e., when @code{foo} is executed
2753: later, the interpretation semantics of @code{+} (i.e., adding two
2754: numbers) will be performed.
2755:
2756: However, there are words with non-default compilation semantics, e.g.,
2757: the control-flow words like @code{if}. You can use @code{immediate} to
2758: change the compilation semantics of the last defined word to be equal to
2759: the interpretation semantics:
2760:
2761: @example
2762: : [FOO] ( -- )
2763: 5 . ; immediate
2764:
2765: [FOO]
2766: : bar ( -- )
2767: [FOO] ;
2768: bar
2769: see bar
2770: @end example
2771:
2772: Two conventions to mark words with non-default compilation semnatics are
2773: names with brackets (more frequently used) and to write them all in
2774: upper case (less frequently used).
2775:
2776: In Gforth (and many other systems) you can also remove the
2777: interpretation semantics with @code{compile-only} (the compilation
2778: semantics is derived from the original interpretation semantics):
2779:
2780: @example
2781: : flip ( -- )
2782: 6 . ; compile-only \ but not immediate
2783: flip
2784:
2785: : flop ( -- )
2786: flip ;
2787: flop
2788: @end example
2789:
2790: In this example the interpretation semantics of @code{flop} is equal to
2791: the original interpretation semantics of @code{flip}.
2792:
2793: The text interpreter has two states: in interpret state, it performs the
2794: interpretation semantics of words it encounters; in compile state, it
2795: performs the compilation semantics of these words.
2796:
2797: Among other things, @code{:} switches into compile state, and @code{;}
2798: switches back to interpret state. They contain the factors @code{]}
2799: (switch to compile state) and @code{[} (switch to interpret state), that
2800: do nothing but switch the state.
2801:
2802: @example
2803: : xxx ( -- )
2804: [ 5 . ]
2805: ;
2806:
2807: xxx
2808: see xxx
2809: @end example
2810:
2811: These brackets are also the source of the naming convention mentioned
2812: above.
2813:
1.66 anton 2814: Reference: @ref{Interpretation and Compilation Semantics}.
2815:
1.48 anton 2816:
2817: @node Execution Tokens Tutorial, Exceptions Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Tutorial
2818: @section Execution Tokens
1.66 anton 2819: @cindex execution tokens tutorial
2820: @cindex XT tutorial
1.48 anton 2821:
2822: @code{' word} gives you the execution token (XT) of a word. The XT is a
2823: cell representing the interpretation semantics of a word. You can
2824: execute this semantics with @code{execute}:
2825:
2826: @example
2827: ' + .s
2828: 1 2 rot execute .
2829: @end example
2830:
2831: The XT is similar to a function pointer in C. However, parameter
2832: passing through the stack makes it a little more flexible:
2833:
2834: @example
2835: : map-array ( ... addr u xt -- ... )
1.50 anton 2836: \ executes xt ( ... x -- ... ) for every element of the array starting
2837: \ at addr and containing u elements
1.48 anton 2838: @{ xt @}
2839: cells over + swap ?do
1.50 anton 2840: i @@ xt execute
1.48 anton 2841: 1 cells +loop ;
2842:
2843: create a 3 , 4 , 2 , -1 , 4 ,
2844: a 5 ' . map-array .s
2845: 0 a 5 ' + map-array .
2846: s" max-n" environment? drop .s
2847: a 5 ' min map-array .
2848: @end example
2849:
2850: You can use map-array with the XTs of words that consume one element
2851: more than they produce. In theory you can also use it with other XTs,
2852: but the stack effect then depends on the size of the array, which is
2853: hard to understand.
2854:
1.51 pazsan 2855: Since XTs are cell-sized, you can store them in memory and manipulate
2856: them on the stack like other cells. You can also compile the XT into a
1.48 anton 2857: word with @code{compile,}:
2858:
2859: @example
2860: : foo1 ( n1 n2 -- n )
2861: [ ' + compile, ] ;
2862: see foo
2863: @end example
2864:
2865: This is non-standard, because @code{compile,} has no compilation
2866: semantics in the standard, but it works in good Forth systems. For the
2867: broken ones, use
2868:
2869: @example
2870: : [compile,] compile, ; immediate
2871:
2872: : foo1 ( n1 n2 -- n )
2873: [ ' + ] [compile,] ;
2874: see foo
2875: @end example
2876:
2877: @code{'} is a word with default compilation semantics; it parses the
2878: next word when its interpretation semantics are executed, not during
2879: compilation:
2880:
2881: @example
2882: : foo ( -- xt )
2883: ' ;
2884: see foo
2885: : bar ( ... "word" -- ... )
2886: ' execute ;
2887: see bar
1.60 anton 2888: 1 2 bar + .
1.48 anton 2889: @end example
2890:
2891: You often want to parse a word during compilation and compile its XT so
2892: it will be pushed on the stack at run-time. @code{[']} does this:
2893:
2894: @example
2895: : xt-+ ( -- xt )
2896: ['] + ;
2897: see xt-+
2898: 1 2 xt-+ execute .
2899: @end example
2900:
2901: Many programmers tend to see @code{'} and the word it parses as one
2902: unit, and expect it to behave like @code{[']} when compiled, and are
2903: confused by the actual behaviour. If you are, just remember that the
2904: Forth system just takes @code{'} as one unit and has no idea that it is
2905: a parsing word (attempts to convenience programmers in this issue have
2906: usually resulted in even worse pitfalls, see
1.66 anton 2907: @uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,
2908: @code{State}-smartness---Why it is evil and How to Exorcise it}).
1.48 anton 2909:
2910: Note that the state of the interpreter does not come into play when
1.51 pazsan 2911: creating and executing XTs. I.e., even when you execute @code{'} in
1.48 anton 2912: compile state, it still gives you the interpretation semantics. And
2913: whatever that state is, @code{execute} performs the semantics
1.66 anton 2914: represented by the XT (i.e., for XTs produced with @code{'} the
2915: interpretation semantics).
2916:
2917: Reference: @ref{Tokens for Words}.
1.48 anton 2918:
2919:
2920: @node Exceptions Tutorial, Defining Words Tutorial, Execution Tokens Tutorial, Tutorial
2921: @section Exceptions
1.66 anton 2922: @cindex exceptions tutorial
1.48 anton 2923:
2924: @code{throw ( n -- )} causes an exception unless n is zero.
2925:
2926: @example
2927: 100 throw .s
2928: 0 throw .s
2929: @end example
2930:
2931: @code{catch ( ... xt -- ... n )} behaves similar to @code{execute}, but
2932: it catches exceptions and pushes the number of the exception on the
2933: stack (or 0, if the xt executed without exception). If there was an
2934: exception, the stacks have the same depth as when entering @code{catch}:
2935:
2936: @example
2937: .s
2938: 3 0 ' / catch .s
2939: 3 2 ' / catch .s
2940: @end example
2941:
2942: @assignment
2943: Try the same with @code{execute} instead of @code{catch}.
2944: @endassignment
2945:
2946: @code{Throw} always jumps to the dynamically next enclosing
2947: @code{catch}, even if it has to leave several call levels to achieve
2948: this:
2949:
2950: @example
2951: : foo 100 throw ;
2952: : foo1 foo ." after foo" ;
1.51 pazsan 2953: : bar ['] foo1 catch ;
1.60 anton 2954: bar .
1.48 anton 2955: @end example
2956:
2957: It is often important to restore a value upon leaving a definition, even
2958: if the definition is left through an exception. You can ensure this
2959: like this:
2960:
2961: @example
2962: : ...
2963: save-x
1.51 pazsan 2964: ['] word-changing-x catch ( ... n )
1.48 anton 2965: restore-x
2966: ( ... n ) throw ;
2967: @end example
2968:
1.55 anton 2969: Gforth provides an alternative syntax in addition to @code{catch}:
1.48 anton 2970: @code{try ... recover ... endtry}. If the code between @code{try} and
2971: @code{recover} has an exception, the stack depths are restored, the
2972: exception number is pushed on the stack, and the code between
2973: @code{recover} and @code{endtry} is performed. E.g., the definition for
2974: @code{catch} is
2975:
2976: @example
2977: : catch ( x1 .. xn xt -- y1 .. ym 0 / z1 .. zn error ) \ exception
2978: try
2979: execute 0
2980: recover
2981: nip
2982: endtry ;
2983: @end example
2984:
2985: The equivalent to the restoration code above is
2986:
2987: @example
2988: : ...
2989: save-x
2990: try
2991: word-changing-x
2992: end-try
2993: restore-x
2994: throw ;
2995: @end example
2996:
2997: As you can see, the @code{recover} part is optional.
2998:
1.66 anton 2999: Reference: @ref{Exception Handling}.
3000:
1.48 anton 3001:
3002: @node Defining Words Tutorial, Arrays and Records Tutorial, Exceptions Tutorial, Tutorial
3003: @section Defining Words
1.66 anton 3004: @cindex defining words tutorial
3005: @cindex does> tutorial
3006: @cindex create...does> tutorial
3007:
3008: @c before semantics?
1.48 anton 3009:
3010: @code{:}, @code{create}, and @code{variable} are definition words: They
3011: define other words. @code{Constant} is another definition word:
3012:
3013: @example
3014: 5 constant foo
3015: foo .
3016: @end example
3017:
3018: You can also use the prefixes @code{2} (double-cell) and @code{f}
3019: (floating point) with @code{variable} and @code{constant}.
3020:
3021: You can also define your own defining words. E.g.:
3022:
3023: @example
3024: : variable ( "name" -- )
3025: create 0 , ;
3026: @end example
3027:
3028: You can also define defining words that create words that do something
3029: other than just producing their address:
3030:
3031: @example
3032: : constant ( n "name" -- )
3033: create ,
3034: does> ( -- n )
1.50 anton 3035: ( addr ) @@ ;
1.48 anton 3036:
3037: 5 constant foo
3038: foo .
3039: @end example
3040:
3041: The definition of @code{constant} above ends at the @code{does>}; i.e.,
3042: @code{does>} replaces @code{;}, but it also does something else: It
3043: changes the last defined word such that it pushes the address of the
3044: body of the word and then performs the code after the @code{does>}
3045: whenever it is called.
3046:
3047: In the example above, @code{constant} uses @code{,} to store 5 into the
3048: body of @code{foo}. When @code{foo} executes, it pushes the address of
3049: the body onto the stack, then (in the code after the @code{does>})
3050: fetches the 5 from there.
3051:
3052: The stack comment near the @code{does>} reflects the stack effect of the
3053: defined word, not the stack effect of the code after the @code{does>}
3054: (the difference is that the code expects the address of the body that
3055: the stack comment does not show).
3056:
3057: You can use these definition words to do factoring in cases that involve
3058: (other) definition words. E.g., a field offset is always added to an
3059: address. Instead of defining
3060:
3061: @example
3062: 2 cells constant offset-field1
3063: @end example
3064:
3065: and using this like
3066:
3067: @example
3068: ( addr ) offset-field1 +
3069: @end example
3070:
3071: you can define a definition word
3072:
3073: @example
3074: : simple-field ( n "name" -- )
3075: create ,
3076: does> ( n1 -- n1+n )
1.50 anton 3077: ( addr ) @@ + ;
1.48 anton 3078: @end example
1.21 crook 3079:
1.48 anton 3080: Definition and use of field offsets now look like this:
1.21 crook 3081:
1.48 anton 3082: @example
3083: 2 cells simple-field field1
1.60 anton 3084: create mystruct 4 cells allot
3085: mystruct .s field1 .s drop
1.48 anton 3086: @end example
1.21 crook 3087:
1.48 anton 3088: If you want to do something with the word without performing the code
3089: after the @code{does>}, you can access the body of a @code{create}d word
3090: with @code{>body ( xt -- addr )}:
1.21 crook 3091:
1.48 anton 3092: @example
3093: : value ( n "name" -- )
3094: create ,
3095: does> ( -- n1 )
1.50 anton 3096: @@ ;
1.48 anton 3097: : to ( n "name" -- )
3098: ' >body ! ;
1.21 crook 3099:
1.48 anton 3100: 5 value foo
3101: foo .
3102: 7 to foo
3103: foo .
3104: @end example
1.21 crook 3105:
1.48 anton 3106: @assignment
3107: Define @code{defer ( "name" -- )}, which creates a word that stores an
3108: XT (at the start the XT of @code{abort}), and upon execution
3109: @code{execute}s the XT. Define @code{is ( xt "name" -- )} that stores
3110: @code{xt} into @code{name}, a word defined with @code{defer}. Indirect
3111: recursion is one application of @code{defer}.
3112: @endassignment
1.29 crook 3113:
1.66 anton 3114: Reference: @ref{User-defined Defining Words}.
3115:
3116:
1.48 anton 3117: @node Arrays and Records Tutorial, POSTPONE Tutorial, Defining Words Tutorial, Tutorial
3118: @section Arrays and Records
1.66 anton 3119: @cindex arrays tutorial
3120: @cindex records tutorial
3121: @cindex structs tutorial
1.29 crook 3122:
1.48 anton 3123: Forth has no standard words for defining data structures such as arrays
3124: and records (structs in C terminology), but you can build them yourself
3125: based on address arithmetic. You can also define words for defining
3126: arrays and records (@pxref{Defining Words Tutorial,, Defining Words}).
1.29 crook 3127:
1.48 anton 3128: One of the first projects a Forth newcomer sets out upon when learning
3129: about defining words is an array defining word (possibly for
3130: n-dimensional arrays). Go ahead and do it, I did it, too; you will
3131: learn something from it. However, don't be disappointed when you later
3132: learn that you have little use for these words (inappropriate use would
3133: be even worse). I have not yet found a set of useful array words yet;
3134: the needs are just too diverse, and named, global arrays (the result of
3135: naive use of defining words) are often not flexible enough (e.g.,
1.66 anton 3136: consider how to pass them as parameters). Another such project is a set
3137: of words to help dealing with strings.
1.29 crook 3138:
1.48 anton 3139: On the other hand, there is a useful set of record words, and it has
3140: been defined in @file{compat/struct.fs}; these words are predefined in
3141: Gforth. They are explained in depth elsewhere in this manual (see
3142: @pxref{Structures}). The @code{simple-field} example above is
3143: simplified variant of fields in this package.
1.21 crook 3144:
3145:
1.48 anton 3146: @node POSTPONE Tutorial, Literal Tutorial, Arrays and Records Tutorial, Tutorial
3147: @section @code{POSTPONE}
1.66 anton 3148: @cindex postpone tutorial
1.21 crook 3149:
1.48 anton 3150: You can compile the compilation semantics (instead of compiling the
3151: interpretation semantics) of a word with @code{POSTPONE}:
1.21 crook 3152:
1.48 anton 3153: @example
3154: : MY-+ ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
1.51 pazsan 3155: POSTPONE + ; immediate
1.48 anton 3156: : foo ( n1 n2 -- n )
3157: MY-+ ;
3158: 1 2 foo .
3159: see foo
3160: @end example
1.21 crook 3161:
1.48 anton 3162: During the definition of @code{foo} the text interpreter performs the
3163: compilation semantics of @code{MY-+}, which performs the compilation
3164: semantics of @code{+}, i.e., it compiles @code{+} into @code{foo}.
3165:
3166: This example also displays separate stack comments for the compilation
3167: semantics and for the stack effect of the compiled code. For words with
3168: default compilation semantics these stack effects are usually not
3169: displayed; the stack effect of the compilation semantics is always
3170: @code{( -- )} for these words, the stack effect for the compiled code is
3171: the stack effect of the interpretation semantics.
3172:
3173: Note that the state of the interpreter does not come into play when
3174: performing the compilation semantics in this way. You can also perform
3175: it interpretively, e.g.:
3176:
3177: @example
3178: : foo2 ( n1 n2 -- n )
3179: [ MY-+ ] ;
3180: 1 2 foo .
3181: see foo
3182: @end example
1.21 crook 3183:
1.48 anton 3184: However, there are some broken Forth systems where this does not always
1.62 crook 3185: work, and therefore this practice was been declared non-standard in
1.48 anton 3186: 1999.
3187: @c !! repair.fs
3188:
3189: Here is another example for using @code{POSTPONE}:
1.44 crook 3190:
1.48 anton 3191: @example
3192: : MY-- ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
3193: POSTPONE negate POSTPONE + ; immediate compile-only
3194: : bar ( n1 n2 -- n )
3195: MY-- ;
3196: 2 1 bar .
3197: see bar
3198: @end example
1.21 crook 3199:
1.48 anton 3200: You can define @code{ENDIF} in this way:
1.21 crook 3201:
1.48 anton 3202: @example
3203: : ENDIF ( Compilation: orig -- )
3204: POSTPONE then ; immediate
3205: @end example
1.21 crook 3206:
1.48 anton 3207: @assignment
3208: Write @code{MY-2DUP} that has compilation semantics equivalent to
3209: @code{2dup}, but compiles @code{over over}.
3210: @endassignment
1.29 crook 3211:
1.66 anton 3212: @c !! @xref{Macros} for reference
3213:
3214:
1.48 anton 3215: @node Literal Tutorial, Advanced macros Tutorial, POSTPONE Tutorial, Tutorial
3216: @section @code{Literal}
1.66 anton 3217: @cindex literal tutorial
1.29 crook 3218:
1.48 anton 3219: You cannot @code{POSTPONE} numbers:
1.21 crook 3220:
1.48 anton 3221: @example
3222: : [FOO] POSTPONE 500 ; immediate
1.21 crook 3223: @end example
3224:
1.48 anton 3225: Instead, you can use @code{LITERAL (compilation: n --; run-time: -- n )}:
1.29 crook 3226:
1.48 anton 3227: @example
3228: : [FOO] ( compilation: --; run-time: -- n )
3229: 500 POSTPONE literal ; immediate
1.29 crook 3230:
1.60 anton 3231: : flip [FOO] ;
1.48 anton 3232: flip .
3233: see flip
3234: @end example
1.29 crook 3235:
1.48 anton 3236: @code{LITERAL} consumes a number at compile-time (when it's compilation
3237: semantics are executed) and pushes it at run-time (when the code it
3238: compiled is executed). A frequent use of @code{LITERAL} is to compile a
3239: number computed at compile time into the current word:
1.29 crook 3240:
1.48 anton 3241: @example
3242: : bar ( -- n )
3243: [ 2 2 + ] literal ;
3244: see bar
3245: @end example
1.29 crook 3246:
1.48 anton 3247: @assignment
3248: Write @code{]L} which allows writing the example above as @code{: bar (
3249: -- n ) [ 2 2 + ]L ;}
3250: @endassignment
3251:
1.66 anton 3252: @c !! @xref{Macros} for reference
3253:
1.48 anton 3254:
3255: @node Advanced macros Tutorial, Compilation Tokens Tutorial, Literal Tutorial, Tutorial
3256: @section Advanced macros
1.66 anton 3257: @cindex macros, advanced tutorial
3258: @cindex run-time code generation, tutorial
1.48 anton 3259:
1.66 anton 3260: Reconsider @code{map-array} from @ref{Execution Tokens Tutorial,,
3261: Execution Tokens}. It frequently performs @code{execute}, a relatively
3262: expensive operation in some Forth implementations. You can use
1.48 anton 3263: @code{compile,} and @code{POSTPONE} to eliminate these @code{execute}s
3264: and produce a word that contains the word to be performed directly:
3265:
3266: @c use ]] ... [[
3267: @example
3268: : compile-map-array ( compilation: xt -- ; run-time: ... addr u -- ... )
3269: \ at run-time, execute xt ( ... x -- ... ) for each element of the
3270: \ array beginning at addr and containing u elements
3271: @{ xt @}
3272: POSTPONE cells POSTPONE over POSTPONE + POSTPONE swap POSTPONE ?do
1.50 anton 3273: POSTPONE i POSTPONE @@ xt compile,
1.48 anton 3274: 1 cells POSTPONE literal POSTPONE +loop ;
3275:
3276: : sum-array ( addr u -- n )
3277: 0 rot rot [ ' + compile-map-array ] ;
3278: see sum-array
3279: a 5 sum-array .
3280: @end example
3281:
3282: You can use the full power of Forth for generating the code; here's an
3283: example where the code is generated in a loop:
3284:
3285: @example
3286: : compile-vmul-step ( compilation: n --; run-time: n1 addr1 -- n2 addr2 )
3287: \ n2=n1+(addr1)*n, addr2=addr1+cell
1.50 anton 3288: POSTPONE tuck POSTPONE @@
1.48 anton 3289: POSTPONE literal POSTPONE * POSTPONE +
3290: POSTPONE swap POSTPONE cell+ ;
3291:
3292: : compile-vmul ( compilation: addr1 u -- ; run-time: addr2 -- n )
1.51 pazsan 3293: \ n=v1*v2 (inner product), where the v_i are represented as addr_i u
1.48 anton 3294: 0 postpone literal postpone swap
3295: [ ' compile-vmul-step compile-map-array ]
3296: postpone drop ;
3297: see compile-vmul
3298:
3299: : a-vmul ( addr -- n )
1.51 pazsan 3300: \ n=a*v, where v is a vector that's as long as a and starts at addr
1.48 anton 3301: [ a 5 compile-vmul ] ;
3302: see a-vmul
3303: a a-vmul .
3304: @end example
3305:
3306: This example uses @code{compile-map-array} to show off, but you could
1.66 anton 3307: also use @code{map-array} instead (try it now!).
1.48 anton 3308:
3309: You can use this technique for efficient multiplication of large
3310: matrices. In matrix multiplication, you multiply every line of one
3311: matrix with every column of the other matrix. You can generate the code
3312: for one line once, and use it for every column. The only downside of
3313: this technique is that it is cumbersome to recover the memory consumed
3314: by the generated code when you are done (and in more complicated cases
3315: it is not possible portably).
3316:
1.66 anton 3317: @c !! @xref{Macros} for reference
3318:
3319:
1.48 anton 3320: @node Compilation Tokens Tutorial, Wordlists and Search Order Tutorial, Advanced macros Tutorial, Tutorial
3321: @section Compilation Tokens
1.66 anton 3322: @cindex compilation tokens, tutorial
3323: @cindex CT, tutorial
1.48 anton 3324:
3325: This section is Gforth-specific. You can skip it.
3326:
3327: @code{' word compile,} compiles the interpretation semantics. For words
3328: with default compilation semantics this is the same as performing the
3329: compilation semantics. To represent the compilation semantics of other
3330: words (e.g., words like @code{if} that have no interpretation
3331: semantics), Gforth has the concept of a compilation token (CT,
3332: consisting of two cells), and words @code{comp'} and @code{[comp']}.
3333: You can perform the compilation semantics represented by a CT with
3334: @code{execute}:
1.29 crook 3335:
1.48 anton 3336: @example
3337: : foo2 ( n1 n2 -- n )
3338: [ comp' + execute ] ;
3339: see foo
3340: @end example
1.29 crook 3341:
1.48 anton 3342: You can compile the compilation semantics represented by a CT with
3343: @code{postpone,}:
1.30 anton 3344:
1.48 anton 3345: @example
3346: : foo3 ( -- )
3347: [ comp' + postpone, ] ;
3348: see foo3
3349: @end example
1.30 anton 3350:
1.51 pazsan 3351: @code{[ comp' word postpone, ]} is equivalent to @code{POSTPONE word}.
1.48 anton 3352: @code{comp'} is particularly useful for words that have no
3353: interpretation semantics:
1.29 crook 3354:
1.30 anton 3355: @example
1.48 anton 3356: ' if
1.60 anton 3357: comp' if .s 2drop
1.30 anton 3358: @end example
3359:
1.66 anton 3360: Reference: @ref{Tokens for Words}.
3361:
1.29 crook 3362:
1.48 anton 3363: @node Wordlists and Search Order Tutorial, , Compilation Tokens Tutorial, Tutorial
3364: @section Wordlists and Search Order
1.66 anton 3365: @cindex wordlists tutorial
3366: @cindex search order, tutorial
1.48 anton 3367:
3368: The dictionary is not just a memory area that allows you to allocate
3369: memory with @code{allot}, it also contains the Forth words, arranged in
3370: several wordlists. When searching for a word in a wordlist,
3371: conceptually you start searching at the youngest and proceed towards
3372: older words (in reality most systems nowadays use hash-tables); i.e., if
3373: you define a word with the same name as an older word, the new word
3374: shadows the older word.
3375:
3376: Which wordlists are searched in which order is determined by the search
3377: order. You can display the search order with @code{order}. It displays
3378: first the search order, starting with the wordlist searched first, then
3379: it displays the wordlist that will contain newly defined words.
1.21 crook 3380:
1.48 anton 3381: You can create a new, empty wordlist with @code{wordlist ( -- wid )}:
1.21 crook 3382:
1.48 anton 3383: @example
3384: wordlist constant mywords
3385: @end example
1.21 crook 3386:
1.48 anton 3387: @code{Set-current ( wid -- )} sets the wordlist that will contain newly
3388: defined words (the @emph{current} wordlist):
1.21 crook 3389:
1.48 anton 3390: @example
3391: mywords set-current
3392: order
3393: @end example
1.26 crook 3394:
1.48 anton 3395: Gforth does not display a name for the wordlist in @code{mywords}
3396: because this wordlist was created anonymously with @code{wordlist}.
1.21 crook 3397:
1.48 anton 3398: You can get the current wordlist with @code{get-current ( -- wid)}. If
3399: you want to put something into a specific wordlist without overall
3400: effect on the current wordlist, this typically looks like this:
1.21 crook 3401:
1.48 anton 3402: @example
3403: get-current mywords set-current ( wid )
3404: create someword
3405: ( wid ) set-current
3406: @end example
1.21 crook 3407:
1.48 anton 3408: You can write the search order with @code{set-order ( wid1 .. widn n --
3409: )} and read it with @code{get-order ( -- wid1 .. widn n )}. The first
3410: searched wordlist is topmost.
1.21 crook 3411:
1.48 anton 3412: @example
3413: get-order mywords swap 1+ set-order
3414: order
3415: @end example
1.21 crook 3416:
1.48 anton 3417: Yes, the order of wordlists in the output of @code{order} is reversed
3418: from stack comments and the output of @code{.s} and thus unintuitive.
1.21 crook 3419:
1.48 anton 3420: @assignment
3421: Define @code{>order ( wid -- )} with adds @code{wid} as first searched
3422: wordlist to the search order. Define @code{previous ( -- )}, which
3423: removes the first searched wordlist from the search order. Experiment
3424: with boundary conditions (you will see some crashes or situations that
3425: are hard or impossible to leave).
3426: @endassignment
1.21 crook 3427:
1.48 anton 3428: The search order is a powerful foundation for providing features similar
3429: to Modula-2 modules and C++ namespaces. However, trying to modularize
3430: programs in this way has disadvantages for debugging and reuse/factoring
3431: that overcome the advantages in my experience (I don't do huge projects,
1.55 anton 3432: though). These disadvantages are not so clear in other
1.48 anton 3433: languages/programming environments, because these langauges are not so
3434: strong in debugging and reuse.
1.21 crook 3435:
1.66 anton 3436: @c !! example
3437:
3438: Reference: @ref{Word Lists}.
1.21 crook 3439:
1.29 crook 3440: @c ******************************************************************
1.48 anton 3441: @node Introduction, Words, Tutorial, Top
1.29 crook 3442: @comment node-name, next, previous, up
3443: @chapter An Introduction to ANS Forth
3444: @cindex Forth - an introduction
1.21 crook 3445:
1.29 crook 3446: The primary purpose of this manual is to document Gforth. However, since
3447: Forth is not a widely-known language and there is a lack of up-to-date
3448: teaching material, it seems worthwhile to provide some introductory
1.49 anton 3449: material. For other sources of Forth-related
3450: information, see @ref{Forth-related information}.
1.21 crook 3451:
1.29 crook 3452: The examples in this section should work on any ANS Forth; the
3453: output shown was produced using Gforth. Each example attempts to
3454: reproduce the exact output that Gforth produces. If you try out the
3455: examples (and you should), what you should type is shown @kbd{like this}
3456: and Gforth's response is shown @code{like this}. The single exception is
1.30 anton 3457: that, where the example shows @key{RET} it means that you should
1.29 crook 3458: press the ``carriage return'' key. Unfortunately, some output formats for
3459: this manual cannot show the difference between @kbd{this} and
3460: @code{this} which will make trying out the examples harder (but not
3461: impossible).
1.21 crook 3462:
1.29 crook 3463: Forth is an unusual language. It provides an interactive development
3464: environment which includes both an interpreter and compiler. Forth
3465: programming style encourages you to break a problem down into many
3466: @cindex factoring
3467: small fragments (@dfn{factoring}), and then to develop and test each
3468: fragment interactively. Forth advocates assert that breaking the
3469: edit-compile-test cycle used by conventional programming languages can
3470: lead to great productivity improvements.
1.21 crook 3471:
1.29 crook 3472: @menu
1.67 anton 3473: * Introducing the Text Interpreter::
3474: * Stacks and Postfix notation::
3475: * Your first definition::
3476: * How does that work?::
3477: * Forth is written in Forth::
3478: * Review - elements of a Forth system::
3479: * Where to go next::
3480: * Exercises::
1.29 crook 3481: @end menu
1.21 crook 3482:
1.29 crook 3483: @comment ----------------------------------------------
3484: @node Introducing the Text Interpreter, Stacks and Postfix notation, Introduction, Introduction
3485: @section Introducing the Text Interpreter
3486: @cindex text interpreter
3487: @cindex outer interpreter
1.21 crook 3488:
1.30 anton 3489: @c IMO this is too detailed and the pace is too slow for
3490: @c an introduction. If you know German, take a look at
3491: @c http://www.complang.tuwien.ac.at/anton/lvas/skriptum-stack.html
3492: @c to see how I do it - anton
3493:
1.44 crook 3494: @c nac-> Where I have accepted your comments 100% and modified the text
3495: @c accordingly, I have deleted your comments. Elsewhere I have added a
3496: @c response like this to attempt to rationalise what I have done. Of
3497: @c course, this is a very clumsy mechanism for something that would be
3498: @c done far more efficiently over a beer. Please delete any dialogue
3499: @c you consider closed.
3500:
1.29 crook 3501: When you invoke the Forth image, you will see a startup banner printed
3502: and nothing else (if you have Gforth installed on your system, try
1.30 anton 3503: invoking it now, by typing @kbd{gforth@key{RET}}). Forth is now running
1.29 crook 3504: its command line interpreter, which is called the @dfn{Text Interpreter}
3505: (also known as the @dfn{Outer Interpreter}). (You will learn a lot
1.49 anton 3506: about the text interpreter as you read through this chapter, for more
3507: detail @pxref{The Text Interpreter}).
1.21 crook 3508:
1.29 crook 3509: Although it's not obvious, Forth is actually waiting for your
1.30 anton 3510: input. Type a number and press the @key{RET} key:
1.21 crook 3511:
1.26 crook 3512: @example
1.30 anton 3513: @kbd{45@key{RET}} ok
1.26 crook 3514: @end example
1.21 crook 3515:
1.29 crook 3516: Rather than give you a prompt to invite you to input something, the text
3517: interpreter prints a status message @i{after} it has processed a line
3518: of input. The status message in this case (``@code{ ok}'' followed by
3519: carriage-return) indicates that the text interpreter was able to process
3520: all of your input successfully. Now type something illegal:
3521:
3522: @example
1.30 anton 3523: @kbd{qwer341@key{RET}}
1.29 crook 3524: :1: Undefined word
3525: qwer341
3526: ^^^^^^^
3527: $400D2BA8 Bounce
3528: $400DBDA8 no.extensions
3529: @end example
1.23 crook 3530:
1.29 crook 3531: The exact text, other than the ``Undefined word'' may differ slightly on
3532: your system, but the effect is the same; when the text interpreter
3533: detects an error, it discards any remaining text on a line, resets
1.49 anton 3534: certain internal state and prints an error message. For a detailed description of error messages see @ref{Error
3535: messages}.
1.23 crook 3536:
1.29 crook 3537: The text interpreter waits for you to press carriage-return, and then
3538: processes your input line. Starting at the beginning of the line, it
3539: breaks the line into groups of characters separated by spaces. For each
3540: group of characters in turn, it makes two attempts to do something:
1.23 crook 3541:
1.29 crook 3542: @itemize @bullet
3543: @item
1.44 crook 3544: @cindex name dictionary
1.29 crook 3545: It tries to treat it as a command. It does this by searching a @dfn{name
3546: dictionary}. If the group of characters matches an entry in the name
3547: dictionary, the name dictionary provides the text interpreter with
3548: information that allows the text interpreter perform some actions. In
3549: Forth jargon, we say that the group
3550: @cindex word
3551: @cindex definition
3552: @cindex execution token
3553: @cindex xt
3554: of characters names a @dfn{word}, that the dictionary search returns an
3555: @dfn{execution token (xt)} corresponding to the @dfn{definition} of the
3556: word, and that the text interpreter executes the xt. Often, the terms
3557: @dfn{word} and @dfn{definition} are used interchangeably.
3558: @item
3559: If the text interpreter fails to find a match in the name dictionary, it
3560: tries to treat the group of characters as a number in the current number
3561: base (when you start up Forth, the current number base is base 10). If
3562: the group of characters legitimately represents a number, the text
3563: interpreter pushes the number onto a stack (we'll learn more about that
3564: in the next section).
3565: @end itemize
1.23 crook 3566:
1.29 crook 3567: If the text interpreter is unable to do either of these things with any
3568: group of characters, it discards the group of characters and the rest of
3569: the line, then prints an error message. If the text interpreter reaches
3570: the end of the line without error, it prints the status message ``@code{ ok}''
3571: followed by carriage-return.
1.21 crook 3572:
1.29 crook 3573: This is the simplest command we can give to the text interpreter:
1.23 crook 3574:
3575: @example
1.30 anton 3576: @key{RET} ok
1.23 crook 3577: @end example
1.21 crook 3578:
1.29 crook 3579: The text interpreter did everything we asked it to do (nothing) without
3580: an error, so it said that everything is ``@code{ ok}''. Try a slightly longer
3581: command:
1.21 crook 3582:
1.23 crook 3583: @example
1.30 anton 3584: @kbd{12 dup fred dup@key{RET}}
1.29 crook 3585: :1: Undefined word
3586: 12 dup fred dup
3587: ^^^^
3588: $400D2BA8 Bounce
3589: $400DBDA8 no.extensions
1.23 crook 3590: @end example
1.21 crook 3591:
1.29 crook 3592: When you press the carriage-return key, the text interpreter starts to
3593: work its way along the line:
1.21 crook 3594:
1.29 crook 3595: @itemize @bullet
3596: @item
3597: When it gets to the space after the @code{2}, it takes the group of
3598: characters @code{12} and looks them up in the name
3599: dictionary@footnote{We can't tell if it found them or not, but assume
3600: for now that it did not}. There is no match for this group of characters
3601: in the name dictionary, so it tries to treat them as a number. It is
3602: able to do this successfully, so it puts the number, 12, ``on the stack''
3603: (whatever that means).
3604: @item
3605: The text interpreter resumes scanning the line and gets the next group
3606: of characters, @code{dup}. It looks it up in the name dictionary and
3607: (you'll have to take my word for this) finds it, and executes the word
3608: @code{dup} (whatever that means).
3609: @item
3610: Once again, the text interpreter resumes scanning the line and gets the
3611: group of characters @code{fred}. It looks them up in the name
3612: dictionary, but can't find them. It tries to treat them as a number, but
3613: they don't represent any legal number.
3614: @end itemize
1.21 crook 3615:
1.29 crook 3616: At this point, the text interpreter gives up and prints an error
3617: message. The error message shows exactly how far the text interpreter
3618: got in processing the line. In particular, it shows that the text
3619: interpreter made no attempt to do anything with the final character
3620: group, @code{dup}, even though we have good reason to believe that the
3621: text interpreter would have no problem looking that word up and
3622: executing it a second time.
1.21 crook 3623:
3624:
1.29 crook 3625: @comment ----------------------------------------------
3626: @node Stacks and Postfix notation, Your first definition, Introducing the Text Interpreter, Introduction
3627: @section Stacks, postfix notation and parameter passing
3628: @cindex text interpreter
3629: @cindex outer interpreter
1.21 crook 3630:
1.29 crook 3631: In procedural programming languages (like C and Pascal), the
3632: building-block of programs is the @dfn{function} or @dfn{procedure}. These
3633: functions or procedures are called with @dfn{explicit parameters}. For
3634: example, in C we might write:
1.21 crook 3635:
1.23 crook 3636: @example
1.29 crook 3637: total = total + new_volume(length,height,depth);
1.23 crook 3638: @end example
1.21 crook 3639:
1.23 crook 3640: @noindent
1.29 crook 3641: where new_volume is a function-call to another piece of code, and total,
3642: length, height and depth are all variables. length, height and depth are
3643: parameters to the function-call.
1.21 crook 3644:
1.29 crook 3645: In Forth, the equivalent of the function or procedure is the
3646: @dfn{definition} and parameters are implicitly passed between
3647: definitions using a shared stack that is visible to the
3648: programmer. Although Forth does support variables, the existence of the
3649: stack means that they are used far less often than in most other
3650: programming languages. When the text interpreter encounters a number, it
3651: will place (@dfn{push}) it on the stack. There are several stacks (the
1.30 anton 3652: actual number is implementation-dependent ...) and the particular stack
1.29 crook 3653: used for any operation is implied unambiguously by the operation being
3654: performed. The stack used for all integer operations is called the @dfn{data
3655: stack} and, since this is the stack used most commonly, references to
3656: ``the data stack'' are often abbreviated to ``the stack''.
1.21 crook 3657:
1.29 crook 3658: The stacks have a last-in, first-out (LIFO) organisation. If you type:
1.21 crook 3659:
1.23 crook 3660: @example
1.30 anton 3661: @kbd{1 2 3@key{RET}} ok
1.23 crook 3662: @end example
1.21 crook 3663:
1.29 crook 3664: Then this instructs the text interpreter to placed three numbers on the
3665: (data) stack. An analogy for the behaviour of the stack is to take a
3666: pack of playing cards and deal out the ace (1), 2 and 3 into a pile on
3667: the table. The 3 was the last card onto the pile (``last-in'') and if
3668: you take a card off the pile then, unless you're prepared to fiddle a
3669: bit, the card that you take off will be the 3 (``first-out''). The
3670: number that will be first-out of the stack is called the @dfn{top of
3671: stack}, which
3672: @cindex TOS definition
3673: is often abbreviated to @dfn{TOS}.
1.21 crook 3674:
1.29 crook 3675: To understand how parameters are passed in Forth, consider the
3676: behaviour of the definition @code{+} (pronounced ``plus''). You will not
3677: be surprised to learn that this definition performs addition. More
3678: precisely, it adds two number together and produces a result. Where does
3679: it get the two numbers from? It takes the top two numbers off the
3680: stack. Where does it place the result? On the stack. You can act-out the
3681: behaviour of @code{+} with your playing cards like this:
1.21 crook 3682:
3683: @itemize @bullet
3684: @item
1.29 crook 3685: Pick up two cards from the stack on the table
1.21 crook 3686: @item
1.29 crook 3687: Stare at them intently and ask yourself ``what @i{is} the sum of these two
3688: numbers''
1.21 crook 3689: @item
1.29 crook 3690: Decide that the answer is 5
1.21 crook 3691: @item
1.29 crook 3692: Shuffle the two cards back into the pack and find a 5
1.21 crook 3693: @item
1.29 crook 3694: Put a 5 on the remaining ace that's on the table.
1.21 crook 3695: @end itemize
3696:
1.29 crook 3697: If you don't have a pack of cards handy but you do have Forth running,
3698: you can use the definition @code{.s} to show the current state of the stack,
3699: without affecting the stack. Type:
1.21 crook 3700:
3701: @example
1.30 anton 3702: @kbd{clearstack 1 2 3@key{RET}} ok
3703: @kbd{.s@key{RET}} <3> 1 2 3 ok
1.23 crook 3704: @end example
3705:
1.29 crook 3706: The text interpreter looks up the word @code{clearstack} and executes
3707: it; it tidies up the stack and removes any entries that may have been
3708: left on it by earlier examples. The text interpreter pushes each of the
3709: three numbers in turn onto the stack. Finally, the text interpreter
3710: looks up the word @code{.s} and executes it. The effect of executing
3711: @code{.s} is to print the ``<3>'' (the total number of items on the stack)
3712: followed by a list of all the items on the stack; the item on the far
3713: right-hand side is the TOS.
1.21 crook 3714:
1.29 crook 3715: You can now type:
1.21 crook 3716:
1.29 crook 3717: @example
1.30 anton 3718: @kbd{+ .s@key{RET}} <2> 1 5 ok
1.29 crook 3719: @end example
1.21 crook 3720:
1.29 crook 3721: @noindent
3722: which is correct; there are now 2 items on the stack and the result of
3723: the addition is 5.
1.23 crook 3724:
1.29 crook 3725: If you're playing with cards, try doing a second addition: pick up the
3726: two cards, work out that their sum is 6, shuffle them into the pack,
3727: look for a 6 and place that on the table. You now have just one item on
3728: the stack. What happens if you try to do a third addition? Pick up the
3729: first card, pick up the second card -- ah! There is no second card. This
3730: is called a @dfn{stack underflow} and consitutes an error. If you try to
3731: do the same thing with Forth it will report an error (probably a Stack
3732: Underflow or an Invalid Memory Address error).
1.23 crook 3733:
1.29 crook 3734: The opposite situation to a stack underflow is a @dfn{stack overflow},
3735: which simply accepts that there is a finite amount of storage space
3736: reserved for the stack. To stretch the playing card analogy, if you had
3737: enough packs of cards and you piled the cards up on the table, you would
3738: eventually be unable to add another card; you'd hit the ceiling. Gforth
3739: allows you to set the maximum size of the stacks. In general, the only
3740: time that you will get a stack overflow is because a definition has a
3741: bug in it and is generating data on the stack uncontrollably.
1.23 crook 3742:
1.29 crook 3743: There's one final use for the playing card analogy. If you model your
3744: stack using a pack of playing cards, the maximum number of items on
3745: your stack will be 52 (I assume you didn't use the Joker). The maximum
3746: @i{value} of any item on the stack is 13 (the King). In fact, the only
3747: possible numbers are positive integer numbers 1 through 13; you can't
3748: have (for example) 0 or 27 or 3.52 or -2. If you change the way you
3749: think about some of the cards, you can accommodate different
3750: numbers. For example, you could think of the Jack as representing 0,
3751: the Queen as representing -1 and the King as representing -2. Your
1.45 crook 3752: @i{range} remains unchanged (you can still only represent a total of 13
1.29 crook 3753: numbers) but the numbers that you can represent are -2 through 10.
1.28 crook 3754:
1.29 crook 3755: In that analogy, the limit was the amount of information that a single
3756: stack entry could hold, and Forth has a similar limit. In Forth, the
3757: size of a stack entry is called a @dfn{cell}. The actual size of a cell is
3758: implementation dependent and affects the maximum value that a stack
3759: entry can hold. A Standard Forth provides a cell size of at least
3760: 16-bits, and most desktop systems use a cell size of 32-bits.
1.21 crook 3761:
1.29 crook 3762: Forth does not do any type checking for you, so you are free to
3763: manipulate and combine stack items in any way you wish. A convenient way
3764: of treating stack items is as 2's complement signed integers, and that
3765: is what Standard words like @code{+} do. Therefore you can type:
1.21 crook 3766:
1.29 crook 3767: @example
1.30 anton 3768: @kbd{-5 12 + .s@key{RET}} <1> 7 ok
1.29 crook 3769: @end example
1.21 crook 3770:
1.29 crook 3771: If you use numbers and definitions like @code{+} in order to turn Forth
3772: into a great big pocket calculator, you will realise that it's rather
3773: different from a normal calculator. Rather than typing 2 + 3 = you had
3774: to type 2 3 + (ignore the fact that you had to use @code{.s} to see the
3775: result). The terminology used to describe this difference is to say that
3776: your calculator uses @dfn{Infix Notation} (parameters and operators are
3777: mixed) whilst Forth uses @dfn{Postfix Notation} (parameters and
3778: operators are separate), also called @dfn{Reverse Polish Notation}.
1.21 crook 3779:
1.29 crook 3780: Whilst postfix notation might look confusing to begin with, it has
3781: several important advantages:
1.21 crook 3782:
1.23 crook 3783: @itemize @bullet
3784: @item
1.29 crook 3785: it is unambiguous
1.23 crook 3786: @item
1.29 crook 3787: it is more concise
1.23 crook 3788: @item
1.29 crook 3789: it fits naturally with a stack-based system
1.23 crook 3790: @end itemize
1.21 crook 3791:
1.29 crook 3792: To examine these claims in more detail, consider these sums:
1.21 crook 3793:
1.29 crook 3794: @example
3795: 6 + 5 * 4 =
3796: 4 * 5 + 6 =
3797: @end example
1.21 crook 3798:
1.29 crook 3799: If you're just learning maths or your maths is very rusty, you will
3800: probably come up with the answer 44 for the first and 26 for the
3801: second. If you are a bit of a whizz at maths you will remember the
3802: @i{convention} that multiplication takes precendence over addition, and
3803: you'd come up with the answer 26 both times. To explain the answer 26
3804: to someone who got the answer 44, you'd probably rewrite the first sum
3805: like this:
1.21 crook 3806:
1.29 crook 3807: @example
3808: 6 + (5 * 4) =
3809: @end example
1.21 crook 3810:
1.29 crook 3811: If what you really wanted was to perform the addition before the
3812: multiplication, you would have to use parentheses to force it.
1.21 crook 3813:
1.29 crook 3814: If you did the first two sums on a pocket calculator you would probably
3815: get the right answers, unless you were very cautious and entered them using
3816: these keystroke sequences:
1.21 crook 3817:
1.29 crook 3818: 6 + 5 = * 4 =
3819: 4 * 5 = + 6 =
1.21 crook 3820:
1.29 crook 3821: Postfix notation is unambiguous because the order that the operators
3822: are applied is always explicit; that also means that parentheses are
3823: never required. The operators are @i{active} (the act of quoting the
3824: operator makes the operation occur) which removes the need for ``=''.
1.28 crook 3825:
1.29 crook 3826: The sum 6 + 5 * 4 can be written (in postfix notation) in two
3827: equivalent ways:
1.26 crook 3828:
3829: @example
1.29 crook 3830: 6 5 4 * + or:
3831: 5 4 * 6 +
1.26 crook 3832: @end example
1.23 crook 3833:
1.29 crook 3834: An important thing that you should notice about this notation is that
3835: the @i{order} of the numbers does not change; if you want to subtract
3836: 2 from 10 you type @code{10 2 -}.
1.1 anton 3837:
1.29 crook 3838: The reason that Forth uses postfix notation is very simple to explain: it
3839: makes the implementation extremely simple, and it follows naturally from
3840: using the stack as a mechanism for passing parameters. Another way of
3841: thinking about this is to realise that all Forth definitions are
3842: @i{active}; they execute as they are encountered by the text
3843: interpreter. The result of this is that the syntax of Forth is trivially
3844: simple.
1.1 anton 3845:
3846:
3847:
1.29 crook 3848: @comment ----------------------------------------------
3849: @node Your first definition, How does that work?, Stacks and Postfix notation, Introduction
3850: @section Your first Forth definition
3851: @cindex first definition
1.1 anton 3852:
1.29 crook 3853: Until now, the examples we've seen have been trivial; we've just been
3854: using Forth as a bigger-than-pocket calculator. Also, each calculation
3855: we've shown has been a ``one-off'' -- to repeat it we'd need to type it in
3856: again@footnote{That's not quite true. If you press the up-arrow key on
3857: your keyboard you should be able to scroll back to any earlier command,
3858: edit it and re-enter it.} In this section we'll see how to add new
3859: words to Forth's vocabulary.
1.1 anton 3860:
1.29 crook 3861: The easiest way to create a new word is to use a @dfn{colon
3862: definition}. We'll define a few and try them out before worrying too
3863: much about how they work. Try typing in these examples; be careful to
3864: copy the spaces accurately:
1.1 anton 3865:
1.29 crook 3866: @example
3867: : add-two 2 + . ;
3868: : greet ." Hello and welcome" ;
3869: : demo 5 add-two ;
3870: @end example
1.1 anton 3871:
1.29 crook 3872: @noindent
3873: Now try them out:
1.1 anton 3874:
1.29 crook 3875: @example
1.30 anton 3876: @kbd{greet@key{RET}} Hello and welcome ok
3877: @kbd{greet greet@key{RET}} Hello and welcomeHello and welcome ok
3878: @kbd{4 add-two@key{RET}} 6 ok
3879: @kbd{demo@key{RET}} 7 ok
3880: @kbd{9 greet demo add-two@key{RET}} Hello and welcome7 11 ok
1.29 crook 3881: @end example
1.1 anton 3882:
1.29 crook 3883: The first new thing that we've introduced here is the pair of words
3884: @code{:} and @code{;}. These are used to start and terminate a new
3885: definition, respectively. The first word after the @code{:} is the name
3886: for the new definition.
1.1 anton 3887:
1.29 crook 3888: As you can see from the examples, a definition is built up of words that
3889: have already been defined; Forth makes no distinction between
3890: definitions that existed when you started the system up, and those that
3891: you define yourself.
1.1 anton 3892:
1.29 crook 3893: The examples also introduce the words @code{.} (dot), @code{."}
3894: (dot-quote) and @code{dup} (dewp). Dot takes the value from the top of
3895: the stack and displays it. It's like @code{.s} except that it only
3896: displays the top item of the stack and it is destructive; after it has
3897: executed, the number is no longer on the stack. There is always one
3898: space printed after the number, and no spaces before it. Dot-quote
3899: defines a string (a sequence of characters) that will be printed when
3900: the word is executed. The string can contain any printable characters
3901: except @code{"}. A @code{"} has a special function; it is not a Forth
3902: word but it acts as a delimiter (the way that delimiters work is
3903: described in the next section). Finally, @code{dup} duplicates the value
3904: at the top of the stack. Try typing @code{5 dup .s} to see what it does.
1.1 anton 3905:
1.29 crook 3906: We already know that the text interpreter searches through the
3907: dictionary to locate names. If you've followed the examples earlier, you
3908: will already have a definition called @code{add-two}. Lets try modifying
3909: it by typing in a new definition:
1.1 anton 3910:
1.29 crook 3911: @example
1.30 anton 3912: @kbd{: add-two dup . ." + 2 =" 2 + . ;@key{RET}} redefined add-two ok
1.29 crook 3913: @end example
1.5 anton 3914:
1.29 crook 3915: Forth recognised that we were defining a word that already exists, and
3916: printed a message to warn us of that fact. Let's try out the new
3917: definition:
1.5 anton 3918:
1.29 crook 3919: @example
1.30 anton 3920: @kbd{9 add-two@key{RET}} 9 + 2 =11 ok
1.29 crook 3921: @end example
1.1 anton 3922:
1.29 crook 3923: @noindent
3924: All that we've actually done here, though, is to create a new
3925: definition, with a particular name. The fact that there was already a
3926: definition with the same name did not make any difference to the way
3927: that the new definition was created (except that Forth printed a warning
3928: message). The old definition of add-two still exists (try @code{demo}
3929: again to see that this is true). Any new definition will use the new
3930: definition of @code{add-two}, but old definitions continue to use the
3931: version that already existed at the time that they were @code{compiled}.
1.1 anton 3932:
1.29 crook 3933: Before you go on to the next section, try defining and redefining some
3934: words of your own.
1.1 anton 3935:
1.29 crook 3936: @comment ----------------------------------------------
3937: @node How does that work?, Forth is written in Forth, Your first definition, Introduction
3938: @section How does that work?
3939: @cindex parsing words
1.1 anton 3940:
1.30 anton 3941: @c That's pretty deep (IMO way too deep) for an introduction. - anton
3942:
3943: @c Is it a good idea to talk about the interpretation semantics of a
3944: @c number? We don't have an xt to go along with it. - anton
3945:
3946: @c Now that I have eliminated execution semantics, I wonder if it would not
3947: @c be better to keep them (or add run-time semantics), to make it easier to
3948: @c explain what compilation semantics usually does. - anton
3949:
1.44 crook 3950: @c nac-> I removed the term ``default compilation sematics'' from the
3951: @c introductory chapter. Removing ``execution semantics'' was making
3952: @c everything simpler to explain, then I think the use of this term made
3953: @c everything more complex again. I replaced it with ``default
3954: @c semantics'' (which is used elsewhere in the manual) by which I mean
3955: @c ``a definition that has neither the immediate nor the compile-only
3956: @c flag set''. I reworded big chunks of the ``how does that work''
3957: @c section (and, unusually for me, I think I even made it shorter!). See
3958: @c what you think -- I know I have not addressed your primary concern
3959: @c that it is too heavy-going for an introduction. From what I understood
3960: @c of your course notes it looks as though they might be a good framework.
3961: @c Things that I've tried to capture here are some things that came as a
3962: @c great revelation here when I first understood them. Also, I like the
3963: @c fact that a very simple code example shows up almost all of the issues
3964: @c that you need to understand to see how Forth works. That's unique and
3965: @c worthwhile to emphasise.
3966:
1.29 crook 3967: Now we're going to take another look at the definition of @code{add-two}
3968: from the previous section. From our knowledge of the way that the text
3969: interpreter works, we would have expected this result when we tried to
3970: define @code{add-two}:
1.21 crook 3971:
1.29 crook 3972: @example
1.44 crook 3973: @kbd{: add-two 2 + . ;@key{RET}}
1.29 crook 3974: ^^^^^^^
3975: Error: Undefined word
3976: @end example
1.28 crook 3977:
1.29 crook 3978: The reason that this didn't happen is bound up in the way that @code{:}
3979: works. The word @code{:} does two special things. The first special
3980: thing that it does prevents the text interpreter from ever seeing the
3981: characters @code{add-two}. The text interpreter uses a variable called
3982: @cindex modifying >IN
1.44 crook 3983: @code{>IN} (pronounced ``to-in'') to keep track of where it is in the
1.29 crook 3984: input line. When it encounters the word @code{:} it behaves in exactly
3985: the same way as it does for any other word; it looks it up in the name
3986: dictionary, finds its xt and executes it. When @code{:} executes, it
3987: looks at the input buffer, finds the word @code{add-two} and advances the
3988: value of @code{>IN} to point past it. It then does some other stuff
3989: associated with creating the new definition (including creating an entry
3990: for @code{add-two} in the name dictionary). When the execution of @code{:}
3991: completes, control returns to the text interpreter, which is oblivious
3992: to the fact that it has been tricked into ignoring part of the input
3993: line.
1.21 crook 3994:
1.29 crook 3995: @cindex parsing words
3996: Words like @code{:} -- words that advance the value of @code{>IN} and so
3997: prevent the text interpreter from acting on the whole of the input line
3998: -- are called @dfn{parsing words}.
1.21 crook 3999:
1.29 crook 4000: @cindex @code{state} - effect on the text interpreter
4001: @cindex text interpreter - effect of state
4002: The second special thing that @code{:} does is change the value of a
4003: variable called @code{state}, which affects the way that the text
4004: interpreter behaves. When Gforth starts up, @code{state} has the value
4005: 0, and the text interpreter is said to be @dfn{interpreting}. During a
4006: colon definition (started with @code{:}), @code{state} is set to -1 and
1.44 crook 4007: the text interpreter is said to be @dfn{compiling}.
4008:
4009: In this example, the text interpreter is compiling when it processes the
4010: string ``@code{2 + . ;}''. It still breaks the string down into
4011: character sequences in the same way. However, instead of pushing the
4012: number @code{2} onto the stack, it lays down (@dfn{compiles}) some magic
4013: into the definition of @code{add-two} that will make the number @code{2} get
4014: pushed onto the stack when @code{add-two} is @dfn{executed}. Similarly,
4015: the behaviours of @code{+} and @code{.} are also compiled into the
4016: definition.
4017:
4018: One category of words don't get compiled. These so-called @dfn{immediate
4019: words} get executed (performed @i{now}) regardless of whether the text
4020: interpreter is interpreting or compiling. The word @code{;} is an
4021: immediate word. Rather than being compiled into the definition, it
4022: executes. Its effect is to terminate the current definition, which
4023: includes changing the value of @code{state} back to 0.
4024:
4025: When you execute @code{add-two}, it has a @dfn{run-time effect} that is
4026: exactly the same as if you had typed @code{2 + . @key{RET}} outside of a
4027: definition.
1.28 crook 4028:
1.30 anton 4029: In Forth, every word or number can be described in terms of two
1.29 crook 4030: properties:
1.28 crook 4031:
4032: @itemize @bullet
4033: @item
1.29 crook 4034: @cindex interpretation semantics
1.44 crook 4035: Its @dfn{interpretation semantics} describe how it will behave when the
4036: text interpreter encounters it in @dfn{interpret} state. The
4037: interpretation semantics of a word are represented by an @dfn{execution
4038: token}.
1.28 crook 4039: @item
1.29 crook 4040: @cindex compilation semantics
1.44 crook 4041: Its @dfn{compilation semantics} describe how it will behave when the
4042: text interpreter encounters it in @dfn{compile} state. The compilation
4043: semantics of a word are represented in an implementation-dependent way;
4044: Gforth uses a @dfn{compilation token}.
1.29 crook 4045: @end itemize
4046:
4047: @noindent
4048: Numbers are always treated in a fixed way:
4049:
4050: @itemize @bullet
1.28 crook 4051: @item
1.44 crook 4052: When the number is @dfn{interpreted}, its behaviour is to push the
4053: number onto the stack.
1.28 crook 4054: @item
1.30 anton 4055: When the number is @dfn{compiled}, a piece of code is appended to the
4056: current definition that pushes the number when it runs. (In other words,
4057: the compilation semantics of a number are to postpone its interpretation
4058: semantics until the run-time of the definition that it is being compiled
4059: into.)
1.29 crook 4060: @end itemize
4061:
1.44 crook 4062: Words don't behave in such a regular way, but most have @i{default
4063: semantics} which means that they behave like this:
1.29 crook 4064:
4065: @itemize @bullet
1.28 crook 4066: @item
1.30 anton 4067: The @dfn{interpretation semantics} of the word are to do something useful.
4068: @item
1.29 crook 4069: The @dfn{compilation semantics} of the word are to append its
1.30 anton 4070: @dfn{interpretation semantics} to the current definition (so that its
4071: run-time behaviour is to do something useful).
1.28 crook 4072: @end itemize
4073:
1.30 anton 4074: @cindex immediate words
1.44 crook 4075: The actual behaviour of any particular word can be controlled by using
4076: the words @code{immediate} and @code{compile-only} when the word is
4077: defined. These words set flags in the name dictionary entry of the most
4078: recently defined word, and these flags are retrieved by the text
4079: interpreter when it finds the word in the name dictionary.
4080:
4081: A word that is marked as @dfn{immediate} has compilation semantics that
4082: are identical to its interpretation semantics. In other words, it
4083: behaves like this:
1.29 crook 4084:
4085: @itemize @bullet
4086: @item
1.30 anton 4087: The @dfn{interpretation semantics} of the word are to do something useful.
1.29 crook 4088: @item
1.30 anton 4089: The @dfn{compilation semantics} of the word are to do something useful
4090: (and actually the same thing); i.e., it is executed during compilation.
1.29 crook 4091: @end itemize
1.28 crook 4092:
1.44 crook 4093: Marking a word as @dfn{compile-only} prohibits the text interpreter from
4094: performing the interpretation semantics of the word directly; an attempt
4095: to do so will generate an error. It is never necessary to use
4096: @code{compile-only} (and it is not even part of ANS Forth, though it is
4097: provided by many implementations) but it is good etiquette to apply it
4098: to a word that will not behave correctly (and might have unexpected
4099: side-effects) in interpret state. For example, it is only legal to use
4100: the conditional word @code{IF} within a definition. If you forget this
4101: and try to use it elsewhere, the fact that (in Gforth) it is marked as
4102: @code{compile-only} allows the text interpreter to generate a helpful
4103: error message rather than subjecting you to the consequences of your
4104: folly.
4105:
1.29 crook 4106: This example shows the difference between an immediate and a
4107: non-immediate word:
1.28 crook 4108:
1.29 crook 4109: @example
4110: : show-state state @@ . ;
4111: : show-state-now show-state ; immediate
4112: : word1 show-state ;
4113: : word2 show-state-now ;
1.28 crook 4114: @end example
1.23 crook 4115:
1.29 crook 4116: The word @code{immediate} after the definition of @code{show-state-now}
4117: makes that word an immediate word. These definitions introduce a new
4118: word: @code{@@} (pronounced ``fetch''). This word fetches the value of a
4119: variable, and leaves it on the stack. Therefore, the behaviour of
4120: @code{show-state} is to print a number that represents the current value
4121: of @code{state}.
1.28 crook 4122:
1.29 crook 4123: When you execute @code{word1}, it prints the number 0, indicating that
4124: the system is interpreting. When the text interpreter compiled the
4125: definition of @code{word1}, it encountered @code{show-state} whose
1.30 anton 4126: compilation semantics are to append its interpretation semantics to the
1.29 crook 4127: current definition. When you execute @code{word1}, it performs the
1.30 anton 4128: interpretation semantics of @code{show-state}. At the time that @code{word1}
1.29 crook 4129: (and therefore @code{show-state}) are executed, the system is
4130: interpreting.
1.28 crook 4131:
1.30 anton 4132: When you pressed @key{RET} after entering the definition of @code{word2},
1.29 crook 4133: you should have seen the number -1 printed, followed by ``@code{
4134: ok}''. When the text interpreter compiled the definition of
4135: @code{word2}, it encountered @code{show-state-now}, an immediate word,
1.30 anton 4136: whose compilation semantics are therefore to perform its interpretation
1.29 crook 4137: semantics. It is executed straight away (even before the text
4138: interpreter has moved on to process another group of characters; the
4139: @code{;} in this example). The effect of executing it are to display the
4140: value of @code{state} @i{at the time that the definition of}
4141: @code{word2} @i{is being defined}. Printing -1 demonstrates that the
4142: system is compiling at this time. If you execute @code{word2} it does
4143: nothing at all.
1.28 crook 4144:
1.29 crook 4145: @cindex @code{."}, how it works
4146: Before leaving the subject of immediate words, consider the behaviour of
4147: @code{."} in the definition of @code{greet}, in the previous
4148: section. This word is both a parsing word and an immediate word. Notice
4149: that there is a space between @code{."} and the start of the text
4150: @code{Hello and welcome}, but that there is no space between the last
4151: letter of @code{welcome} and the @code{"} character. The reason for this
4152: is that @code{."} is a Forth word; it must have a space after it so that
4153: the text interpreter can identify it. The @code{"} is not a Forth word;
4154: it is a @dfn{delimiter}. The examples earlier show that, when the string
4155: is displayed, there is neither a space before the @code{H} nor after the
4156: @code{e}. Since @code{."} is an immediate word, it executes at the time
4157: that @code{greet} is defined. When it executes, its behaviour is to
4158: search forward in the input line looking for the delimiter. When it
4159: finds the delimiter, it updates @code{>IN} to point past the
4160: delimiter. It also compiles some magic code into the definition of
4161: @code{greet}; the xt of a run-time routine that prints a text string. It
4162: compiles the string @code{Hello and welcome} into memory so that it is
4163: available to be printed later. When the text interpreter gains control,
4164: the next word it finds in the input stream is @code{;} and so it
4165: terminates the definition of @code{greet}.
1.28 crook 4166:
4167:
4168: @comment ----------------------------------------------
1.29 crook 4169: @node Forth is written in Forth, Review - elements of a Forth system, How does that work?, Introduction
4170: @section Forth is written in Forth
4171: @cindex structure of Forth programs
4172:
4173: When you start up a Forth compiler, a large number of definitions
4174: already exist. In Forth, you develop a new application using bottom-up
4175: programming techniques to create new definitions that are defined in
4176: terms of existing definitions. As you create each definition you can
4177: test and debug it interactively.
4178:
4179: If you have tried out the examples in this section, you will probably
4180: have typed them in by hand; when you leave Gforth, your definitions will
4181: be lost. You can avoid this by using a text editor to enter Forth source
4182: code into a file, and then loading code from the file using
1.49 anton 4183: @code{include} (@pxref{Forth source files}). A Forth source file is
1.29 crook 4184: processed by the text interpreter, just as though you had typed it in by
4185: hand@footnote{Actually, there are some subtle differences -- see
4186: @ref{The Text Interpreter}.}.
4187:
4188: Gforth also supports the traditional Forth alternative to using text
1.49 anton 4189: files for program entry (@pxref{Blocks}).
1.28 crook 4190:
1.29 crook 4191: In common with many, if not most, Forth compilers, most of Gforth is
4192: actually written in Forth. All of the @file{.fs} files in the
4193: installation directory@footnote{For example,
1.30 anton 4194: @file{/usr/local/share/gforth...}} are Forth source files, which you can
1.29 crook 4195: study to see examples of Forth programming.
1.28 crook 4196:
1.29 crook 4197: Gforth maintains a history file that records every line that you type to
4198: the text interpreter. This file is preserved between sessions, and is
4199: used to provide a command-line recall facility. If you enter long
4200: definitions by hand, you can use a text editor to paste them out of the
4201: history file into a Forth source file for reuse at a later time
1.49 anton 4202: (for more information @pxref{Command-line editing}).
1.28 crook 4203:
4204:
4205: @comment ----------------------------------------------
1.29 crook 4206: @node Review - elements of a Forth system, Where to go next, Forth is written in Forth, Introduction
4207: @section Review - elements of a Forth system
4208: @cindex elements of a Forth system
1.28 crook 4209:
1.29 crook 4210: To summarise this chapter:
1.28 crook 4211:
4212: @itemize @bullet
4213: @item
1.29 crook 4214: Forth programs use @dfn{factoring} to break a problem down into small
4215: fragments called @dfn{words} or @dfn{definitions}.
4216: @item
4217: Forth program development is an interactive process.
4218: @item
4219: The main command loop that accepts input, and controls both
4220: interpretation and compilation, is called the @dfn{text interpreter}
4221: (also known as the @dfn{outer interpreter}).
4222: @item
4223: Forth has a very simple syntax, consisting of words and numbers
4224: separated by spaces or carriage-return characters. Any additional syntax
4225: is imposed by @dfn{parsing words}.
4226: @item
4227: Forth uses a stack to pass parameters between words. As a result, it
4228: uses postfix notation.
4229: @item
4230: To use a word that has previously been defined, the text interpreter
4231: searches for the word in the @dfn{name dictionary}.
4232: @item
1.30 anton 4233: Words have @dfn{interpretation semantics} and @dfn{compilation semantics}.
1.28 crook 4234: @item
1.29 crook 4235: The text interpreter uses the value of @code{state} to select between
4236: the use of the @dfn{interpretation semantics} and the @dfn{compilation
4237: semantics} of a word that it encounters.
1.28 crook 4238: @item
1.30 anton 4239: The relationship between the @dfn{interpretation semantics} and
4240: @dfn{compilation semantics} for a word
1.29 crook 4241: depend upon the way in which the word was defined (for example, whether
4242: it is an @dfn{immediate} word).
1.28 crook 4243: @item
1.29 crook 4244: Forth definitions can be implemented in Forth (called @dfn{high-level
4245: definitions}) or in some other way (usually a lower-level language and
4246: as a result often called @dfn{low-level definitions}, @dfn{code
4247: definitions} or @dfn{primitives}).
1.28 crook 4248: @item
1.29 crook 4249: Many Forth systems are implemented mainly in Forth.
1.28 crook 4250: @end itemize
4251:
4252:
1.29 crook 4253: @comment ----------------------------------------------
1.48 anton 4254: @node Where to go next, Exercises, Review - elements of a Forth system, Introduction
1.29 crook 4255: @section Where To Go Next
4256: @cindex where to go next
1.28 crook 4257:
1.29 crook 4258: Amazing as it may seem, if you have read (and understood) this far, you
4259: know almost all the fundamentals about the inner workings of a Forth
4260: system. You certainly know enough to be able to read and understand the
4261: rest of this manual and the ANS Forth document, to learn more about the
4262: facilities that Forth in general and Gforth in particular provide. Even
4263: scarier, you know almost enough to implement your own Forth system.
1.30 anton 4264: However, that's not a good idea just yet... better to try writing some
1.29 crook 4265: programs in Gforth.
1.28 crook 4266:
1.29 crook 4267: Forth has such a rich vocabulary that it can be hard to know where to
4268: start in learning it. This section suggests a few sets of words that are
4269: enough to write small but useful programs. Use the word index in this
4270: document to learn more about each word, then try it out and try to write
4271: small definitions using it. Start by experimenting with these words:
1.28 crook 4272:
4273: @itemize @bullet
4274: @item
1.29 crook 4275: Arithmetic: @code{+ - * / /MOD */ ABS INVERT}
4276: @item
4277: Comparison: @code{MIN MAX =}
4278: @item
4279: Logic: @code{AND OR XOR NOT}
4280: @item
4281: Stack manipulation: @code{DUP DROP SWAP OVER}
1.28 crook 4282: @item
1.29 crook 4283: Loops and decisions: @code{IF ELSE ENDIF ?DO I LOOP}
1.28 crook 4284: @item
1.29 crook 4285: Input/Output: @code{. ." EMIT CR KEY}
1.28 crook 4286: @item
1.29 crook 4287: Defining words: @code{: ; CREATE}
1.28 crook 4288: @item
1.29 crook 4289: Memory allocation words: @code{ALLOT ,}
1.28 crook 4290: @item
1.29 crook 4291: Tools: @code{SEE WORDS .S MARKER}
4292: @end itemize
4293:
4294: When you have mastered those, go on to:
4295:
4296: @itemize @bullet
1.28 crook 4297: @item
1.29 crook 4298: More defining words: @code{VARIABLE CONSTANT VALUE TO CREATE DOES>}
1.28 crook 4299: @item
1.29 crook 4300: Memory access: @code{@@ !}
1.28 crook 4301: @end itemize
1.23 crook 4302:
1.29 crook 4303: When you have mastered these, there's nothing for it but to read through
4304: the whole of this manual and find out what you've missed.
4305:
4306: @comment ----------------------------------------------
1.48 anton 4307: @node Exercises, , Where to go next, Introduction
1.29 crook 4308: @section Exercises
4309: @cindex exercises
4310:
4311: TODO: provide a set of programming excercises linked into the stuff done
4312: already and into other sections of the manual. Provide solutions to all
4313: the exercises in a .fs file in the distribution.
4314:
4315: @c Get some inspiration from Starting Forth and Kelly&Spies.
4316:
4317: @c excercises:
4318: @c 1. take inches and convert to feet and inches.
4319: @c 2. take temperature and convert from fahrenheight to celcius;
4320: @c may need to care about symmetric vs floored??
4321: @c 3. take input line and do character substitution
4322: @c to encipher or decipher
4323: @c 4. as above but work on a file for in and out
4324: @c 5. take input line and convert to pig-latin
4325: @c
4326: @c thing of sets of things to exercise then come up with
4327: @c problems that need those things.
4328:
4329:
1.26 crook 4330: @c ******************************************************************
1.29 crook 4331: @node Words, Error messages, Introduction, Top
1.1 anton 4332: @chapter Forth Words
1.26 crook 4333: @cindex words
1.1 anton 4334:
4335: @menu
4336: * Notation::
1.65 anton 4337: * Case insensitivity::
4338: * Comments::
4339: * Boolean Flags::
1.1 anton 4340: * Arithmetic::
4341: * Stack Manipulation::
1.5 anton 4342: * Memory::
1.1 anton 4343: * Control Structures::
4344: * Defining Words::
1.65 anton 4345: * Interpretation and Compilation Semantics::
1.47 crook 4346: * Tokens for Words::
1.65 anton 4347: * The Text Interpreter::
4348: * Word Lists::
4349: * Environmental Queries::
1.12 anton 4350: * Files::
4351: * Blocks::
4352: * Other I/O::
4353: * Programming Tools::
4354: * Assembler and Code Words::
4355: * Threading Words::
1.26 crook 4356: * Locals::
4357: * Structures::
4358: * Object-oriented Forth::
1.65 anton 4359: * Passing Commands to the OS::
4360: * Keeping track of Time::
4361: * Miscellaneous Words::
1.1 anton 4362: @end menu
4363:
1.65 anton 4364: @node Notation, Case insensitivity, Words, Words
1.1 anton 4365: @section Notation
4366: @cindex notation of glossary entries
4367: @cindex format of glossary entries
4368: @cindex glossary notation format
4369: @cindex word glossary entry format
4370:
4371: The Forth words are described in this section in the glossary notation
1.67 anton 4372: that has become a de-facto standard for Forth texts:
1.1 anton 4373:
4374: @format
1.29 crook 4375: @i{word} @i{Stack effect} @i{wordset} @i{pronunciation}
1.1 anton 4376: @end format
1.29 crook 4377: @i{Description}
1.1 anton 4378:
4379: @table @var
4380: @item word
1.28 crook 4381: The name of the word.
1.1 anton 4382:
4383: @item Stack effect
4384: @cindex stack effect
1.29 crook 4385: The stack effect is written in the notation @code{@i{before} --
4386: @i{after}}, where @i{before} and @i{after} describe the top of
1.1 anton 4387: stack entries before and after the execution of the word. The rest of
4388: the stack is not touched by the word. The top of stack is rightmost,
4389: i.e., a stack sequence is written as it is typed in. Note that Gforth
4390: uses a separate floating point stack, but a unified stack
1.29 crook 4391: notation. Also, return stack effects are not shown in @i{stack
4392: effect}, but in @i{Description}. The name of a stack item describes
1.1 anton 4393: the type and/or the function of the item. See below for a discussion of
4394: the types.
4395:
4396: All words have two stack effects: A compile-time stack effect and a
4397: run-time stack effect. The compile-time stack-effect of most words is
1.29 crook 4398: @i{ -- }. If the compile-time stack-effect of a word deviates from
1.1 anton 4399: this standard behaviour, or the word does other unusual things at
4400: compile time, both stack effects are shown; otherwise only the run-time
4401: stack effect is shown.
4402:
4403: @cindex pronounciation of words
4404: @item pronunciation
4405: How the word is pronounced.
4406:
4407: @cindex wordset
1.67 anton 4408: @cindex environment wordset
1.1 anton 4409: @item wordset
1.21 crook 4410: The ANS Forth standard is divided into several word sets. A standard
4411: system need not support all of them. Therefore, in theory, the fewer
4412: word sets your program uses the more portable it will be. However, we
4413: suspect that most ANS Forth systems on personal machines will feature
1.26 crook 4414: all word sets. Words that are not defined in ANS Forth have
1.21 crook 4415: @code{gforth} or @code{gforth-internal} as word set. @code{gforth}
1.1 anton 4416: describes words that will work in future releases of Gforth;
4417: @code{gforth-internal} words are more volatile. Environmental query
4418: strings are also displayed like words; you can recognize them by the
1.21 crook 4419: @code{environment} in the word set field.
1.1 anton 4420:
4421: @item Description
4422: A description of the behaviour of the word.
4423: @end table
4424:
4425: @cindex types of stack items
4426: @cindex stack item types
4427: The type of a stack item is specified by the character(s) the name
4428: starts with:
4429:
4430: @table @code
4431: @item f
4432: @cindex @code{f}, stack item type
4433: Boolean flags, i.e. @code{false} or @code{true}.
4434: @item c
4435: @cindex @code{c}, stack item type
4436: Char
4437: @item w
4438: @cindex @code{w}, stack item type
4439: Cell, can contain an integer or an address
4440: @item n
4441: @cindex @code{n}, stack item type
4442: signed integer
4443: @item u
4444: @cindex @code{u}, stack item type
4445: unsigned integer
4446: @item d
4447: @cindex @code{d}, stack item type
4448: double sized signed integer
4449: @item ud
4450: @cindex @code{ud}, stack item type
4451: double sized unsigned integer
4452: @item r
4453: @cindex @code{r}, stack item type
4454: Float (on the FP stack)
1.21 crook 4455: @item a-
1.1 anton 4456: @cindex @code{a_}, stack item type
4457: Cell-aligned address
1.21 crook 4458: @item c-
1.1 anton 4459: @cindex @code{c_}, stack item type
4460: Char-aligned address (note that a Char may have two bytes in Windows NT)
1.21 crook 4461: @item f-
1.1 anton 4462: @cindex @code{f_}, stack item type
4463: Float-aligned address
1.21 crook 4464: @item df-
1.1 anton 4465: @cindex @code{df_}, stack item type
4466: Address aligned for IEEE double precision float
1.21 crook 4467: @item sf-
1.1 anton 4468: @cindex @code{sf_}, stack item type
4469: Address aligned for IEEE single precision float
4470: @item xt
4471: @cindex @code{xt}, stack item type
4472: Execution token, same size as Cell
4473: @item wid
4474: @cindex @code{wid}, stack item type
1.21 crook 4475: Word list ID, same size as Cell
1.68 anton 4476: @item ior, wior
4477: @cindex ior type description
4478: @cindex wior type description
4479: I/O result code, cell-sized. In Gforth, you can @code{throw} iors.
1.1 anton 4480: @item f83name
4481: @cindex @code{f83name}, stack item type
4482: Pointer to a name structure
4483: @item "
4484: @cindex @code{"}, stack item type
1.12 anton 4485: string in the input stream (not on the stack). The terminating character
4486: is a blank by default. If it is not a blank, it is shown in @code{<>}
1.1 anton 4487: quotes.
4488: @end table
4489:
1.65 anton 4490: @comment ----------------------------------------------
4491: @node Case insensitivity, Comments, Notation, Words
4492: @section Case insensitivity
4493: @cindex case sensitivity
4494: @cindex upper and lower case
4495:
4496: Gforth is case-insensitive; you can enter definitions and invoke
4497: Standard words using upper, lower or mixed case (however,
4498: @pxref{core-idef, Implementation-defined options, Implementation-defined
4499: options}).
4500:
4501: ANS Forth only @i{requires} implementations to recognise Standard words
4502: when they are typed entirely in upper case. Therefore, a Standard
4503: program must use upper case for all Standard words. You can use whatever
4504: case you like for words that you define, but in a Standard program you
4505: have to use the words in the same case that you defined them.
4506:
4507: Gforth supports case sensitivity through @code{table}s (case-sensitive
4508: wordlists, @pxref{Word Lists}).
4509:
4510: Two people have asked how to convert Gforth to be case-sensitive; while
4511: we think this is a bad idea, you can change all wordlists into tables
4512: like this:
4513:
4514: @example
4515: ' table-find forth-wordlist wordlist-map @ !
4516: @end example
4517:
4518: Note that you now have to type the predefined words in the same case
4519: that we defined them, which are varying. You may want to convert them
4520: to your favourite case before doing this operation (I won't explain how,
4521: because if you are even contemplating doing this, you'd better have
4522: enough knowledge of Forth systems to know this already).
4523:
4524: @node Comments, Boolean Flags, Case insensitivity, Words
1.21 crook 4525: @section Comments
1.26 crook 4526: @cindex comments
1.21 crook 4527:
1.29 crook 4528: Forth supports two styles of comment; the traditional @i{in-line} comment,
4529: @code{(} and its modern cousin, the @i{comment to end of line}; @code{\}.
1.21 crook 4530:
1.44 crook 4531:
1.23 crook 4532: doc-(
1.21 crook 4533: doc-\
1.23 crook 4534: doc-\G
1.21 crook 4535:
1.44 crook 4536:
1.21 crook 4537: @node Boolean Flags, Arithmetic, Comments, Words
4538: @section Boolean Flags
1.26 crook 4539: @cindex Boolean flags
1.21 crook 4540:
4541: A Boolean flag is cell-sized. A cell with all bits clear represents the
4542: flag @code{false} and a flag with all bits set represents the flag
1.26 crook 4543: @code{true}. Words that check a flag (for example, @code{IF}) will treat
1.29 crook 4544: a cell that has @i{any} bit set as @code{true}.
1.67 anton 4545: @c on and off to Memory?
4546: @c true and false to "Bitwise operations" or "Numeric comparison"?
1.44 crook 4547:
1.21 crook 4548: doc-true
4549: doc-false
1.29 crook 4550: doc-on
4551: doc-off
1.21 crook 4552:
1.44 crook 4553:
1.21 crook 4554: @node Arithmetic, Stack Manipulation, Boolean Flags, Words
1.1 anton 4555: @section Arithmetic
4556: @cindex arithmetic words
4557:
4558: @cindex division with potentially negative operands
4559: Forth arithmetic is not checked, i.e., you will not hear about integer
4560: overflow on addition or multiplication, you may hear about division by
4561: zero if you are lucky. The operator is written after the operands, but
4562: the operands are still in the original order. I.e., the infix @code{2-1}
4563: corresponds to @code{2 1 -}. Forth offers a variety of division
4564: operators. If you perform division with potentially negative operands,
4565: you do not want to use @code{/} or @code{/mod} with its undefined
4566: behaviour, but rather @code{fm/mod} or @code{sm/mod} (probably the
4567: former, @pxref{Mixed precision}).
1.26 crook 4568: @comment TODO discuss the different division forms and the std approach
1.1 anton 4569:
4570: @menu
4571: * Single precision::
1.67 anton 4572: * Double precision:: Double-cell integer arithmetic
1.1 anton 4573: * Bitwise operations::
1.67 anton 4574: * Numeric comparison::
1.29 crook 4575: * Mixed precision:: Operations with single and double-cell integers
1.1 anton 4576: * Floating Point::
4577: @end menu
4578:
1.67 anton 4579: @node Single precision, Double precision, Arithmetic, Arithmetic
1.1 anton 4580: @subsection Single precision
4581: @cindex single precision arithmetic words
4582:
1.67 anton 4583: @c !! cell undefined
4584:
4585: By default, numbers in Forth are single-precision integers that are one
1.26 crook 4586: cell in size. They can be signed or unsigned, depending upon how you
1.49 anton 4587: treat them. For the rules used by the text interpreter for recognising
4588: single-precision integers see @ref{Number Conversion}.
1.21 crook 4589:
1.67 anton 4590: These words are all defined for signed operands, but some of them also
4591: work for unsigned numbers: @code{+}, @code{1+}, @code{-}, @code{1-},
4592: @code{*}.
1.44 crook 4593:
1.1 anton 4594: doc-+
1.21 crook 4595: doc-1+
1.1 anton 4596: doc--
1.21 crook 4597: doc-1-
1.1 anton 4598: doc-*
4599: doc-/
4600: doc-mod
4601: doc-/mod
4602: doc-negate
4603: doc-abs
4604: doc-min
4605: doc-max
1.27 crook 4606: doc-floored
1.1 anton 4607:
1.44 crook 4608:
1.67 anton 4609: @node Double precision, Bitwise operations, Single precision, Arithmetic
1.21 crook 4610: @subsection Double precision
4611: @cindex double precision arithmetic words
4612:
1.49 anton 4613: For the rules used by the text interpreter for
4614: recognising double-precision integers, see @ref{Number Conversion}.
1.21 crook 4615:
4616: A double precision number is represented by a cell pair, with the most
1.67 anton 4617: significant cell at the TOS. It is trivial to convert an unsigned single
4618: to a double: simply push a @code{0} onto the TOS. Since numbers are
4619: represented by Gforth using 2's complement arithmetic, converting a
4620: signed single to a (signed) double requires sign-extension across the
4621: most significant cell. This can be achieved using @code{s>d}. The moral
4622: of the story is that you cannot convert a number without knowing whether
4623: it represents an unsigned or a signed number.
1.21 crook 4624:
1.67 anton 4625: These words are all defined for signed operands, but some of them also
4626: work for unsigned numbers: @code{d+}, @code{d-}.
1.44 crook 4627:
1.21 crook 4628: doc-s>d
1.67 anton 4629: doc-d>s
1.21 crook 4630: doc-d+
4631: doc-d-
4632: doc-dnegate
4633: doc-dabs
4634: doc-dmin
4635: doc-dmax
4636:
1.44 crook 4637:
1.67 anton 4638: @node Bitwise operations, Numeric comparison, Double precision, Arithmetic
4639: @subsection Bitwise operations
4640: @cindex bitwise operation words
4641:
4642:
4643: doc-and
4644: doc-or
4645: doc-xor
4646: doc-invert
4647: doc-lshift
4648: doc-rshift
4649: doc-2*
4650: doc-d2*
4651: doc-2/
4652: doc-d2/
4653:
4654:
4655: @node Numeric comparison, Mixed precision, Bitwise operations, Arithmetic
1.21 crook 4656: @subsection Numeric comparison
4657: @cindex numeric comparison words
4658:
1.67 anton 4659: Note that the words that compare for equality (@code{= <> 0= 0<> d= d<>
4660: d0= d0<>}) work for for both signed and unsigned numbers.
1.44 crook 4661:
1.28 crook 4662: doc-<
4663: doc-<=
4664: doc-<>
4665: doc-=
4666: doc->
4667: doc->=
4668:
1.21 crook 4669: doc-0<
1.23 crook 4670: doc-0<=
1.21 crook 4671: doc-0<>
4672: doc-0=
1.23 crook 4673: doc-0>
4674: doc-0>=
1.28 crook 4675:
4676: doc-u<
4677: doc-u<=
1.44 crook 4678: @c u<> and u= exist but are the same as <> and =
1.31 anton 4679: @c doc-u<>
4680: @c doc-u=
1.28 crook 4681: doc-u>
4682: doc-u>=
4683:
4684: doc-within
4685:
4686: doc-d<
4687: doc-d<=
4688: doc-d<>
4689: doc-d=
4690: doc-d>
4691: doc-d>=
1.23 crook 4692:
1.21 crook 4693: doc-d0<
1.23 crook 4694: doc-d0<=
4695: doc-d0<>
1.21 crook 4696: doc-d0=
1.23 crook 4697: doc-d0>
4698: doc-d0>=
4699:
1.21 crook 4700: doc-du<
1.28 crook 4701: doc-du<=
1.44 crook 4702: @c du<> and du= exist but are the same as d<> and d=
1.31 anton 4703: @c doc-du<>
4704: @c doc-du=
1.28 crook 4705: doc-du>
4706: doc-du>=
1.1 anton 4707:
1.44 crook 4708:
1.21 crook 4709: @node Mixed precision, Floating Point, Numeric comparison, Arithmetic
1.1 anton 4710: @subsection Mixed precision
4711: @cindex mixed precision arithmetic words
4712:
1.44 crook 4713:
1.1 anton 4714: doc-m+
4715: doc-*/
4716: doc-*/mod
4717: doc-m*
4718: doc-um*
4719: doc-m*/
4720: doc-um/mod
4721: doc-fm/mod
4722: doc-sm/rem
4723:
1.44 crook 4724:
1.21 crook 4725: @node Floating Point, , Mixed precision, Arithmetic
1.1 anton 4726: @subsection Floating Point
4727: @cindex floating point arithmetic words
4728:
1.49 anton 4729: For the rules used by the text interpreter for
4730: recognising floating-point numbers see @ref{Number Conversion}.
1.1 anton 4731:
1.67 anton 4732: Gforth has a separate floating point stack, but the documentation uses
4733: the unified notation.@footnote{It's easy to generate the separate
4734: notation from that by just separating the floating-point numbers out:
4735: e.g. @code{( n r1 u r2 -- r3 )} becomes @code{( n u -- ) ( F: r1 r2 --
4736: r3 )}.}
1.1 anton 4737:
4738: @cindex floating-point arithmetic, pitfalls
4739: Floating point numbers have a number of unpleasant surprises for the
4740: unwary (e.g., floating point addition is not associative) and even a few
4741: for the wary. You should not use them unless you know what you are doing
4742: or you don't care that the results you get are totally bogus. If you
4743: want to learn about the problems of floating point numbers (and how to
1.66 anton 4744: avoid them), you might start with @cite{David Goldberg,
4745: @uref{http://www.validgh.com/goldberg/paper.ps,What Every Computer
4746: Scientist Should Know About Floating-Point Arithmetic}, ACM Computing
4747: Surveys 23(1):5@minus{}48, March 1991}.
1.1 anton 4748:
1.44 crook 4749:
1.21 crook 4750: doc-d>f
4751: doc-f>d
1.1 anton 4752: doc-f+
4753: doc-f-
4754: doc-f*
4755: doc-f/
4756: doc-fnegate
4757: doc-fabs
4758: doc-fmax
4759: doc-fmin
4760: doc-floor
4761: doc-fround
4762: doc-f**
4763: doc-fsqrt
4764: doc-fexp
4765: doc-fexpm1
4766: doc-fln
4767: doc-flnp1
4768: doc-flog
4769: doc-falog
1.32 anton 4770: doc-f2*
4771: doc-f2/
4772: doc-1/f
4773: doc-precision
4774: doc-set-precision
4775:
4776: @cindex angles in trigonometric operations
4777: @cindex trigonometric operations
4778: Angles in floating point operations are given in radians (a full circle
4779: has 2 pi radians).
4780:
1.1 anton 4781: doc-fsin
4782: doc-fcos
4783: doc-fsincos
4784: doc-ftan
4785: doc-fasin
4786: doc-facos
4787: doc-fatan
4788: doc-fatan2
4789: doc-fsinh
4790: doc-fcosh
4791: doc-ftanh
4792: doc-fasinh
4793: doc-facosh
4794: doc-fatanh
1.21 crook 4795: doc-pi
1.28 crook 4796:
1.32 anton 4797: @cindex equality of floats
4798: @cindex floating-point comparisons
1.31 anton 4799: One particular problem with floating-point arithmetic is that comparison
4800: for equality often fails when you would expect it to succeed. For this
4801: reason approximate equality is often preferred (but you still have to
1.67 anton 4802: know what you are doing). Also note that IEEE NaNs may compare
1.68 anton 4803: differently from what you might expect. The comparison words are:
1.31 anton 4804:
4805: doc-f~rel
4806: doc-f~abs
1.68 anton 4807: doc-f~
1.31 anton 4808: doc-f=
4809: doc-f<>
4810:
4811: doc-f<
4812: doc-f<=
4813: doc-f>
4814: doc-f>=
4815:
1.21 crook 4816: doc-f0<
1.28 crook 4817: doc-f0<=
4818: doc-f0<>
1.21 crook 4819: doc-f0=
1.28 crook 4820: doc-f0>
4821: doc-f0>=
4822:
1.1 anton 4823:
4824: @node Stack Manipulation, Memory, Arithmetic, Words
4825: @section Stack Manipulation
4826: @cindex stack manipulation words
4827:
4828: @cindex floating-point stack in the standard
1.21 crook 4829: Gforth maintains a number of separate stacks:
4830:
1.29 crook 4831: @cindex data stack
4832: @cindex parameter stack
1.21 crook 4833: @itemize @bullet
4834: @item
1.29 crook 4835: A data stack (also known as the @dfn{parameter stack}) -- for
4836: characters, cells, addresses, and double cells.
1.21 crook 4837:
1.29 crook 4838: @cindex floating-point stack
1.21 crook 4839: @item
1.44 crook 4840: A floating point stack -- for holding floating point (FP) numbers.
1.21 crook 4841:
1.29 crook 4842: @cindex return stack
1.21 crook 4843: @item
1.44 crook 4844: A return stack -- for holding the return addresses of colon
1.32 anton 4845: definitions and other (non-FP) data.
1.21 crook 4846:
1.29 crook 4847: @cindex locals stack
1.21 crook 4848: @item
1.44 crook 4849: A locals stack -- for holding local variables.
1.21 crook 4850: @end itemize
4851:
1.1 anton 4852: @menu
4853: * Data stack::
4854: * Floating point stack::
4855: * Return stack::
4856: * Locals stack::
4857: * Stack pointer manipulation::
4858: @end menu
4859:
4860: @node Data stack, Floating point stack, Stack Manipulation, Stack Manipulation
4861: @subsection Data stack
4862: @cindex data stack manipulation words
4863: @cindex stack manipulations words, data stack
4864:
1.44 crook 4865:
1.1 anton 4866: doc-drop
4867: doc-nip
4868: doc-dup
4869: doc-over
4870: doc-tuck
4871: doc-swap
1.21 crook 4872: doc-pick
1.1 anton 4873: doc-rot
4874: doc--rot
4875: doc-?dup
4876: doc-roll
4877: doc-2drop
4878: doc-2nip
4879: doc-2dup
4880: doc-2over
4881: doc-2tuck
4882: doc-2swap
4883: doc-2rot
4884:
1.44 crook 4885:
1.1 anton 4886: @node Floating point stack, Return stack, Data stack, Stack Manipulation
4887: @subsection Floating point stack
4888: @cindex floating-point stack manipulation words
4889: @cindex stack manipulation words, floating-point stack
4890:
1.32 anton 4891: Whilst every sane Forth has a separate floating-point stack, it is not
4892: strictly required; an ANS Forth system could theoretically keep
4893: floating-point numbers on the data stack. As an additional difficulty,
4894: you don't know how many cells a floating-point number takes. It is
4895: reportedly possible to write words in a way that they work also for a
4896: unified stack model, but we do not recommend trying it. Instead, just
4897: say that your program has an environmental dependency on a separate
4898: floating-point stack.
4899:
4900: doc-floating-stack
4901:
1.1 anton 4902: doc-fdrop
4903: doc-fnip
4904: doc-fdup
4905: doc-fover
4906: doc-ftuck
4907: doc-fswap
1.21 crook 4908: doc-fpick
1.1 anton 4909: doc-frot
4910:
1.44 crook 4911:
1.1 anton 4912: @node Return stack, Locals stack, Floating point stack, Stack Manipulation
4913: @subsection Return stack
4914: @cindex return stack manipulation words
4915: @cindex stack manipulation words, return stack
4916:
1.32 anton 4917: @cindex return stack and locals
4918: @cindex locals and return stack
4919: A Forth system is allowed to keep local variables on the
4920: return stack. This is reasonable, as local variables usually eliminate
4921: the need to use the return stack explicitly. So, if you want to produce
4922: a standard compliant program and you are using local variables in a
4923: word, forget about return stack manipulations in that word (refer to the
4924: standard document for the exact rules).
4925:
1.1 anton 4926: doc->r
4927: doc-r>
4928: doc-r@
4929: doc-rdrop
4930: doc-2>r
4931: doc-2r>
4932: doc-2r@
4933: doc-2rdrop
4934:
1.44 crook 4935:
1.1 anton 4936: @node Locals stack, Stack pointer manipulation, Return stack, Stack Manipulation
4937: @subsection Locals stack
4938:
1.47 crook 4939: Gforth uses an extra locals stack. It is described, along with the
4940: reasons for its existence, in @ref{Implementation,Implementation of locals}.
1.21 crook 4941:
1.1 anton 4942: @node Stack pointer manipulation, , Locals stack, Stack Manipulation
4943: @subsection Stack pointer manipulation
4944: @cindex stack pointer manipulation words
4945:
1.44 crook 4946: @c removed s0 r0 l0 -- they are obsolete aliases for sp0 rp0 lp0
1.21 crook 4947: doc-sp0
1.1 anton 4948: doc-sp@
4949: doc-sp!
1.21 crook 4950: doc-fp0
1.1 anton 4951: doc-fp@
4952: doc-fp!
1.21 crook 4953: doc-rp0
1.1 anton 4954: doc-rp@
4955: doc-rp!
1.21 crook 4956: doc-lp0
1.1 anton 4957: doc-lp@
4958: doc-lp!
4959:
1.44 crook 4960:
1.1 anton 4961: @node Memory, Control Structures, Stack Manipulation, Words
4962: @section Memory
1.26 crook 4963: @cindex memory words
1.1 anton 4964:
1.32 anton 4965: @menu
4966: * Memory model::
4967: * Dictionary allocation::
4968: * Heap Allocation::
4969: * Memory Access::
4970: * Address arithmetic::
4971: * Memory Blocks::
4972: @end menu
4973:
1.67 anton 4974: In addition to the standard Forth memory allocation words, there is also
4975: a @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
4976: garbage collector}.
4977:
1.32 anton 4978: @node Memory model, Dictionary allocation, Memory, Memory
4979: @subsection ANS Forth and Gforth memory models
4980:
4981: @c The ANS Forth description is a mess (e.g., is the heap part of
4982: @c the dictionary?), so let's not stick to closely with it.
4983:
1.67 anton 4984: ANS Forth considers a Forth system as consisting of several address
4985: spaces, of which only @dfn{data space} is managed and accessible with
4986: the memory words. Memory not necessarily in data space includes the
4987: stacks, the code (called code space) and the headers (called name
4988: space). In Gforth everything is in data space, but the code for the
4989: primitives is usually read-only.
1.32 anton 4990:
4991: Data space is divided into a number of areas: The (data space portion of
4992: the) dictionary@footnote{Sometimes, the term @dfn{dictionary} is used to
4993: refer to the search data structure embodied in word lists and headers,
4994: because it is used for looking up names, just as you would in a
4995: conventional dictionary.}, the heap, and a number of system-allocated
4996: buffers.
4997:
1.68 anton 4998: @cindex address arithmetic restrictions, ANS vs. Gforth
4999: @cindex contiguous regions, ANS vs. Gforth
1.32 anton 5000: In ANS Forth data space is also divided into contiguous regions. You
5001: can only use address arithmetic within a contiguous region, not between
5002: them. Usually each allocation gives you one contiguous region, but the
1.33 anton 5003: dictionary allocation words have additional rules (@pxref{Dictionary
1.32 anton 5004: allocation}).
5005:
5006: Gforth provides one big address space, and address arithmetic can be
5007: performed between any addresses. However, in the dictionary headers or
5008: code are interleaved with data, so almost the only contiguous data space
5009: regions there are those described by ANS Forth as contiguous; but you
5010: can be sure that the dictionary is allocated towards increasing
5011: addresses even between contiguous regions. The memory order of
5012: allocations in the heap is platform-dependent (and possibly different
5013: from one run to the next).
5014:
1.27 crook 5015:
1.32 anton 5016: @node Dictionary allocation, Heap Allocation, Memory model, Memory
5017: @subsection Dictionary allocation
1.27 crook 5018: @cindex reserving data space
5019: @cindex data space - reserving some
5020:
1.32 anton 5021: Dictionary allocation is a stack-oriented allocation scheme, i.e., if
5022: you want to deallocate X, you also deallocate everything
5023: allocated after X.
5024:
1.68 anton 5025: @cindex contiguous regions in dictionary allocation
1.32 anton 5026: The allocations using the words below are contiguous and grow the region
5027: towards increasing addresses. Other words that allocate dictionary
5028: memory of any kind (i.e., defining words including @code{:noname}) end
5029: the contiguous region and start a new one.
5030:
5031: In ANS Forth only @code{create}d words are guaranteed to produce an
5032: address that is the start of the following contiguous region. In
5033: particular, the cell allocated by @code{variable} is not guaranteed to
5034: be contiguous with following @code{allot}ed memory.
5035:
5036: You can deallocate memory by using @code{allot} with a negative argument
5037: (with some restrictions, see @code{allot}). For larger deallocations use
5038: @code{marker}.
1.27 crook 5039:
1.29 crook 5040:
1.27 crook 5041: doc-here
5042: doc-unused
5043: doc-allot
5044: doc-c,
1.29 crook 5045: doc-f,
1.27 crook 5046: doc-,
5047: doc-2,
5048:
1.32 anton 5049: Memory accesses have to be aligned (@pxref{Address arithmetic}). So of
5050: course you should allocate memory in an aligned way, too. I.e., before
5051: allocating allocating a cell, @code{here} must be cell-aligned, etc.
5052: The words below align @code{here} if it is not already. Basically it is
5053: only already aligned for a type, if the last allocation was a multiple
5054: of the size of this type and if @code{here} was aligned for this type
5055: before.
5056:
5057: After freshly @code{create}ing a word, @code{here} is @code{align}ed in
5058: ANS Forth (@code{maxalign}ed in Gforth).
5059:
5060: doc-align
5061: doc-falign
5062: doc-sfalign
5063: doc-dfalign
5064: doc-maxalign
5065: doc-cfalign
5066:
5067:
5068: @node Heap Allocation, Memory Access, Dictionary allocation, Memory
5069: @subsection Heap allocation
5070: @cindex heap allocation
5071: @cindex dynamic allocation of memory
5072: @cindex memory-allocation word set
5073:
1.68 anton 5074: @cindex contiguous regions and heap allocation
1.32 anton 5075: Heap allocation supports deallocation of allocated memory in any
5076: order. Dictionary allocation is not affected by it (i.e., it does not
5077: end a contiguous region). In Gforth, these words are implemented using
5078: the standard C library calls malloc(), free() and resize().
5079:
1.68 anton 5080: The memory region produced by one invocation of @code{allocate} or
5081: @code{resize} is internally contiguous. There is no contiguity between
5082: such a region and any other region (including others allocated from the
5083: heap).
5084:
1.32 anton 5085: doc-allocate
5086: doc-free
5087: doc-resize
5088:
1.27 crook 5089:
1.32 anton 5090: @node Memory Access, Address arithmetic, Heap Allocation, Memory
1.1 anton 5091: @subsection Memory Access
5092: @cindex memory access words
5093:
5094: doc-@
5095: doc-!
5096: doc-+!
5097: doc-c@
5098: doc-c!
5099: doc-2@
5100: doc-2!
5101: doc-f@
5102: doc-f!
5103: doc-sf@
5104: doc-sf!
5105: doc-df@
5106: doc-df!
5107:
1.68 anton 5108:
1.32 anton 5109: @node Address arithmetic, Memory Blocks, Memory Access, Memory
5110: @subsection Address arithmetic
1.1 anton 5111: @cindex address arithmetic words
5112:
1.67 anton 5113: Address arithmetic is the foundation on which you can build data
5114: structures like arrays, records (@pxref{Structures}) and objects
5115: (@pxref{Object-oriented Forth}).
1.32 anton 5116:
1.68 anton 5117: @cindex address unit
5118: @cindex au (address unit)
1.1 anton 5119: ANS Forth does not specify the sizes of the data types. Instead, it
5120: offers a number of words for computing sizes and doing address
1.29 crook 5121: arithmetic. Address arithmetic is performed in terms of address units
5122: (aus); on most systems the address unit is one byte. Note that a
5123: character may have more than one au, so @code{chars} is no noop (on
1.68 anton 5124: platforms where it is a noop, it compiles to nothing).
1.1 anton 5125:
1.67 anton 5126: The basic address arithmetic words are @code{+} and @code{-}. E.g., if
5127: you have the address of a cell, perform @code{1 cells +}, and you will
5128: have the address of the next cell.
5129:
1.68 anton 5130: @cindex contiguous regions and address arithmetic
1.67 anton 5131: In ANS Forth you can perform address arithmetic only within a contiguous
5132: region, i.e., if you have an address into one region, you can only add
5133: and subtract such that the result is still within the region; you can
5134: only subtract or compare addresses from within the same contiguous
5135: region. Reasons: several contiguous regions can be arranged in memory
5136: in any way; on segmented systems addresses may have unusual
5137: representations, such that address arithmetic only works within a
5138: region. Gforth provides a few more guarantees (linear address space,
5139: dictionary grows upwards), but in general I have found it easy to stay
5140: within contiguous regions (exception: computing and comparing to the
5141: address just beyond the end of an array).
5142:
1.1 anton 5143: @cindex alignment of addresses for types
5144: ANS Forth also defines words for aligning addresses for specific
5145: types. Many computers require that accesses to specific data types
5146: must only occur at specific addresses; e.g., that cells may only be
5147: accessed at addresses divisible by 4. Even if a machine allows unaligned
5148: accesses, it can usually perform aligned accesses faster.
5149:
5150: For the performance-conscious: alignment operations are usually only
5151: necessary during the definition of a data structure, not during the
5152: (more frequent) accesses to it.
5153:
5154: ANS Forth defines no words for character-aligning addresses. This is not
5155: an oversight, but reflects the fact that addresses that are not
5156: char-aligned have no use in the standard and therefore will not be
5157: created.
5158:
5159: @cindex @code{CREATE} and alignment
1.29 crook 5160: ANS Forth guarantees that addresses returned by @code{CREATE}d words
1.1 anton 5161: are cell-aligned; in addition, Gforth guarantees that these addresses
5162: are aligned for all purposes.
5163:
1.26 crook 5164: Note that the ANS Forth word @code{char} has nothing to do with address
5165: arithmetic.
1.1 anton 5166:
1.44 crook 5167:
1.1 anton 5168: doc-chars
5169: doc-char+
5170: doc-cells
5171: doc-cell+
5172: doc-cell
5173: doc-aligned
5174: doc-floats
5175: doc-float+
5176: doc-float
5177: doc-faligned
5178: doc-sfloats
5179: doc-sfloat+
5180: doc-sfaligned
5181: doc-dfloats
5182: doc-dfloat+
5183: doc-dfaligned
5184: doc-maxaligned
5185: doc-cfaligned
5186: doc-address-unit-bits
5187:
1.44 crook 5188:
1.32 anton 5189: @node Memory Blocks, , Address arithmetic, Memory
1.1 anton 5190: @subsection Memory Blocks
5191: @cindex memory block words
1.27 crook 5192: @cindex character strings - moving and copying
5193:
1.49 anton 5194: Memory blocks often represent character strings; For ways of storing
5195: character strings in memory see @ref{String Formats}. For other
5196: string-processing words see @ref{Displaying characters and strings}.
1.1 anton 5197:
1.67 anton 5198: A few of these words work on address unit blocks. In that case, you
5199: usually have to insert @code{CHARS} before the word when working on
5200: character strings. Most words work on character blocks, and expect a
5201: char-aligned address.
5202:
5203: When copying characters between overlapping memory regions, use
5204: @code{chars move} or choose carefully between @code{cmove} and
5205: @code{cmove>}.
1.44 crook 5206:
1.1 anton 5207: doc-move
5208: doc-erase
5209: doc-cmove
5210: doc-cmove>
5211: doc-fill
5212: doc-blank
1.21 crook 5213: doc-compare
5214: doc-search
1.27 crook 5215: doc--trailing
5216: doc-/string
5217:
1.44 crook 5218:
1.27 crook 5219: @comment TODO examples
5220:
1.1 anton 5221:
1.26 crook 5222: @node Control Structures, Defining Words, Memory, Words
1.1 anton 5223: @section Control Structures
5224: @cindex control structures
5225:
1.33 anton 5226: Control structures in Forth cannot be used interpretively, only in a
5227: colon definition@footnote{To be precise, they have no interpretation
5228: semantics (@pxref{Interpretation and Compilation Semantics}).}. We do
5229: not like this limitation, but have not seen a satisfying way around it
5230: yet, although many schemes have been proposed.
1.1 anton 5231:
5232: @menu
1.33 anton 5233: * Selection:: IF ... ELSE ... ENDIF
5234: * Simple Loops:: BEGIN ...
1.29 crook 5235: * Counted Loops:: DO
1.67 anton 5236: * Arbitrary control structures::
5237: * Calls and returns::
1.1 anton 5238: * Exception Handling::
5239: @end menu
5240:
5241: @node Selection, Simple Loops, Control Structures, Control Structures
5242: @subsection Selection
5243: @cindex selection control structures
5244: @cindex control structures for selection
5245:
5246: @cindex @code{IF} control structure
5247: @example
1.29 crook 5248: @i{flag}
1.1 anton 5249: IF
1.29 crook 5250: @i{code}
1.1 anton 5251: ENDIF
5252: @end example
1.21 crook 5253: @noindent
1.33 anton 5254:
1.44 crook 5255: If @i{flag} is non-zero (as far as @code{IF} etc. are concerned, a cell
5256: with any bit set represents truth) @i{code} is executed.
1.33 anton 5257:
1.1 anton 5258: @example
1.29 crook 5259: @i{flag}
1.1 anton 5260: IF
1.29 crook 5261: @i{code1}
1.1 anton 5262: ELSE
1.29 crook 5263: @i{code2}
1.1 anton 5264: ENDIF
5265: @end example
5266:
1.44 crook 5267: If @var{flag} is true, @i{code1} is executed, otherwise @i{code2} is
5268: executed.
1.33 anton 5269:
1.1 anton 5270: You can use @code{THEN} instead of @code{ENDIF}. Indeed, @code{THEN} is
5271: standard, and @code{ENDIF} is not, although it is quite popular. We
5272: recommend using @code{ENDIF}, because it is less confusing for people
5273: who also know other languages (and is not prone to reinforcing negative
5274: prejudices against Forth in these people). Adding @code{ENDIF} to a
5275: system that only supplies @code{THEN} is simple:
5276: @example
1.21 crook 5277: : ENDIF POSTPONE THEN ; immediate
1.1 anton 5278: @end example
5279:
5280: [According to @cite{Webster's New Encyclopedic Dictionary}, @dfn{then
5281: (adv.)} has the following meanings:
5282: @quotation
5283: ... 2b: following next after in order ... 3d: as a necessary consequence
5284: (if you were there, then you saw them).
5285: @end quotation
5286: Forth's @code{THEN} has the meaning 2b, whereas @code{THEN} in Pascal
5287: and many other programming languages has the meaning 3d.]
5288:
1.21 crook 5289: Gforth also provides the words @code{?DUP-IF} and @code{?DUP-0=-IF}, so
1.1 anton 5290: you can avoid using @code{?dup}. Using these alternatives is also more
1.26 crook 5291: efficient than using @code{?dup}. Definitions in ANS Forth
1.1 anton 5292: for @code{ENDIF}, @code{?DUP-IF} and @code{?DUP-0=-IF} are provided in
5293: @file{compat/control.fs}.
5294:
5295: @cindex @code{CASE} control structure
5296: @example
1.29 crook 5297: @i{n}
1.1 anton 5298: CASE
1.29 crook 5299: @i{n1} OF @i{code1} ENDOF
5300: @i{n2} OF @i{code2} ENDOF
1.1 anton 5301: @dots{}
1.68 anton 5302: ( n ) @i{default-code} ( n )
1.1 anton 5303: ENDCASE
5304: @end example
5305:
1.68 anton 5306: Executes the first @i{codei}, where the @i{ni} is equal to @i{n}. If no
5307: @i{ni} matches, the optional @i{default-code} is executed. The optional
5308: default case can be added by simply writing the code after the last
5309: @code{ENDOF}. It may use @i{n}, which is on top of the stack, but must
5310: not consume it.
1.1 anton 5311:
1.69 anton 5312: @progstyle
5313: To keep the code understandable, you should ensure that on all paths
5314: through a selection construct the stack is changed in the same way
5315: (wrt. number and types of stack items consumed and pushed).
5316:
1.1 anton 5317: @node Simple Loops, Counted Loops, Selection, Control Structures
5318: @subsection Simple Loops
5319: @cindex simple loops
5320: @cindex loops without count
5321:
5322: @cindex @code{WHILE} loop
5323: @example
5324: BEGIN
1.29 crook 5325: @i{code1}
5326: @i{flag}
1.1 anton 5327: WHILE
1.29 crook 5328: @i{code2}
1.1 anton 5329: REPEAT
5330: @end example
5331:
1.29 crook 5332: @i{code1} is executed and @i{flag} is computed. If it is true,
5333: @i{code2} is executed and the loop is restarted; If @i{flag} is
1.1 anton 5334: false, execution continues after the @code{REPEAT}.
5335:
5336: @cindex @code{UNTIL} loop
5337: @example
5338: BEGIN
1.29 crook 5339: @i{code}
5340: @i{flag}
1.1 anton 5341: UNTIL
5342: @end example
5343:
1.29 crook 5344: @i{code} is executed. The loop is restarted if @code{flag} is false.
1.1 anton 5345:
1.69 anton 5346: @progstyle
5347: To keep the code understandable, a complete iteration of the loop should
5348: not change the number and types of the items on the stacks.
5349:
1.1 anton 5350: @cindex endless loop
5351: @cindex loops, endless
5352: @example
5353: BEGIN
1.29 crook 5354: @i{code}
1.1 anton 5355: AGAIN
5356: @end example
5357:
5358: This is an endless loop.
5359:
5360: @node Counted Loops, Arbitrary control structures, Simple Loops, Control Structures
5361: @subsection Counted Loops
5362: @cindex counted loops
5363: @cindex loops, counted
5364: @cindex @code{DO} loops
5365:
5366: The basic counted loop is:
5367: @example
1.29 crook 5368: @i{limit} @i{start}
1.1 anton 5369: ?DO
1.29 crook 5370: @i{body}
1.1 anton 5371: LOOP
5372: @end example
5373:
1.29 crook 5374: This performs one iteration for every integer, starting from @i{start}
5375: and up to, but excluding @i{limit}. The counter, or @i{index}, can be
1.21 crook 5376: accessed with @code{i}. For example, the loop:
1.1 anton 5377: @example
5378: 10 0 ?DO
5379: i .
5380: LOOP
5381: @end example
1.21 crook 5382: @noindent
5383: prints @code{0 1 2 3 4 5 6 7 8 9}
5384:
1.1 anton 5385: The index of the innermost loop can be accessed with @code{i}, the index
5386: of the next loop with @code{j}, and the index of the third loop with
5387: @code{k}.
5388:
1.44 crook 5389:
1.1 anton 5390: doc-i
5391: doc-j
5392: doc-k
5393:
1.44 crook 5394:
1.1 anton 5395: The loop control data are kept on the return stack, so there are some
1.21 crook 5396: restrictions on mixing return stack accesses and counted loop words. In
5397: particuler, if you put values on the return stack outside the loop, you
5398: cannot read them inside the loop@footnote{well, not in a way that is
5399: portable.}. If you put values on the return stack within a loop, you
5400: have to remove them before the end of the loop and before accessing the
5401: index of the loop.
1.1 anton 5402:
5403: There are several variations on the counted loop:
5404:
1.21 crook 5405: @itemize @bullet
5406: @item
5407: @code{LEAVE} leaves the innermost counted loop immediately; execution
5408: continues after the associated @code{LOOP} or @code{NEXT}. For example:
5409:
5410: @example
5411: 10 0 ?DO i DUP . 3 = IF LEAVE THEN LOOP
5412: @end example
5413: prints @code{0 1 2 3}
5414:
1.1 anton 5415:
1.21 crook 5416: @item
5417: @code{UNLOOP} prepares for an abnormal loop exit, e.g., via
5418: @code{EXIT}. @code{UNLOOP} removes the loop control parameters from the
5419: return stack so @code{EXIT} can get to its return address. For example:
5420:
5421: @example
5422: : demo 10 0 ?DO i DUP . 3 = IF UNLOOP EXIT THEN LOOP ." Done" ;
5423: @end example
5424: prints @code{0 1 2 3}
5425:
5426:
5427: @item
1.29 crook 5428: If @i{start} is greater than @i{limit}, a @code{?DO} loop is entered
1.1 anton 5429: (and @code{LOOP} iterates until they become equal by wrap-around
5430: arithmetic). This behaviour is usually not what you want. Therefore,
5431: Gforth offers @code{+DO} and @code{U+DO} (as replacements for
1.29 crook 5432: @code{?DO}), which do not enter the loop if @i{start} is greater than
5433: @i{limit}; @code{+DO} is for signed loop parameters, @code{U+DO} for
1.1 anton 5434: unsigned loop parameters.
5435:
1.21 crook 5436: @item
5437: @code{?DO} can be replaced by @code{DO}. @code{DO} always enters
5438: the loop, independent of the loop parameters. Do not use @code{DO}, even
5439: if you know that the loop is entered in any case. Such knowledge tends
5440: to become invalid during maintenance of a program, and then the
5441: @code{DO} will make trouble.
5442:
5443: @item
1.29 crook 5444: @code{LOOP} can be replaced with @code{@i{n} +LOOP}; this updates the
5445: index by @i{n} instead of by 1. The loop is terminated when the border
5446: between @i{limit-1} and @i{limit} is crossed. E.g.:
1.1 anton 5447:
1.21 crook 5448: @example
5449: 4 0 +DO i . 2 +LOOP
5450: @end example
5451: @noindent
5452: prints @code{0 2}
5453:
5454: @example
5455: 4 1 +DO i . 2 +LOOP
5456: @end example
5457: @noindent
5458: prints @code{1 3}
1.1 anton 5459:
1.68 anton 5460: @item
1.1 anton 5461: @cindex negative increment for counted loops
5462: @cindex counted loops with negative increment
1.29 crook 5463: The behaviour of @code{@i{n} +LOOP} is peculiar when @i{n} is negative:
1.1 anton 5464:
1.21 crook 5465: @example
5466: -1 0 ?DO i . -1 +LOOP
5467: @end example
5468: @noindent
5469: prints @code{0 -1}
1.1 anton 5470:
1.21 crook 5471: @example
5472: 0 0 ?DO i . -1 +LOOP
5473: @end example
5474: prints nothing.
1.1 anton 5475:
1.29 crook 5476: Therefore we recommend avoiding @code{@i{n} +LOOP} with negative
5477: @i{n}. One alternative is @code{@i{u} -LOOP}, which reduces the
5478: index by @i{u} each iteration. The loop is terminated when the border
5479: between @i{limit+1} and @i{limit} is crossed. Gforth also provides
1.1 anton 5480: @code{-DO} and @code{U-DO} for down-counting loops. E.g.:
5481:
1.21 crook 5482: @example
5483: -2 0 -DO i . 1 -LOOP
5484: @end example
5485: @noindent
5486: prints @code{0 -1}
1.1 anton 5487:
1.21 crook 5488: @example
5489: -1 0 -DO i . 1 -LOOP
5490: @end example
5491: @noindent
5492: prints @code{0}
5493:
5494: @example
5495: 0 0 -DO i . 1 -LOOP
5496: @end example
5497: @noindent
5498: prints nothing.
1.1 anton 5499:
1.21 crook 5500: @end itemize
1.1 anton 5501:
5502: Unfortunately, @code{+DO}, @code{U+DO}, @code{-DO}, @code{U-DO} and
1.26 crook 5503: @code{-LOOP} are not defined in ANS Forth. However, an implementation
5504: for these words that uses only standard words is provided in
5505: @file{compat/loops.fs}.
1.1 anton 5506:
5507:
5508: @cindex @code{FOR} loops
1.26 crook 5509: Another counted loop is:
1.1 anton 5510: @example
1.29 crook 5511: @i{n}
1.1 anton 5512: FOR
1.29 crook 5513: @i{body}
1.1 anton 5514: NEXT
5515: @end example
5516: This is the preferred loop of native code compiler writers who are too
1.26 crook 5517: lazy to optimize @code{?DO} loops properly. This loop structure is not
1.29 crook 5518: defined in ANS Forth. In Gforth, this loop iterates @i{n+1} times;
5519: @code{i} produces values starting with @i{n} and ending with 0. Other
1.26 crook 5520: Forth systems may behave differently, even if they support @code{FOR}
5521: loops. To avoid problems, don't use @code{FOR} loops.
1.1 anton 5522:
5523: @node Arbitrary control structures, Calls and returns, Counted Loops, Control Structures
5524: @subsection Arbitrary control structures
5525: @cindex control structures, user-defined
5526:
5527: @cindex control-flow stack
5528: ANS Forth permits and supports using control structures in a non-nested
5529: way. Information about incomplete control structures is stored on the
5530: control-flow stack. This stack may be implemented on the Forth data
5531: stack, and this is what we have done in Gforth.
5532:
5533: @cindex @code{orig}, control-flow stack item
5534: @cindex @code{dest}, control-flow stack item
5535: An @i{orig} entry represents an unresolved forward branch, a @i{dest}
5536: entry represents a backward branch target. A few words are the basis for
5537: building any control structure possible (except control structures that
5538: need storage, like calls, coroutines, and backtracking).
5539:
1.44 crook 5540:
1.1 anton 5541: doc-if
5542: doc-ahead
5543: doc-then
5544: doc-begin
5545: doc-until
5546: doc-again
5547: doc-cs-pick
5548: doc-cs-roll
5549:
1.44 crook 5550:
1.21 crook 5551: The Standard words @code{CS-PICK} and @code{CS-ROLL} allow you to
5552: manipulate the control-flow stack in a portable way. Without them, you
5553: would need to know how many stack items are occupied by a control-flow
5554: entry (many systems use one cell. In Gforth they currently take three,
5555: but this may change in the future).
5556:
1.1 anton 5557: Some standard control structure words are built from these words:
5558:
1.44 crook 5559:
1.1 anton 5560: doc-else
5561: doc-while
5562: doc-repeat
5563:
1.44 crook 5564:
5565: @noindent
1.1 anton 5566: Gforth adds some more control-structure words:
5567:
1.44 crook 5568:
1.1 anton 5569: doc-endif
5570: doc-?dup-if
5571: doc-?dup-0=-if
5572:
1.44 crook 5573:
5574: @noindent
1.1 anton 5575: Counted loop words constitute a separate group of words:
5576:
1.44 crook 5577:
1.1 anton 5578: doc-?do
5579: doc-+do
5580: doc-u+do
5581: doc--do
5582: doc-u-do
5583: doc-do
5584: doc-for
5585: doc-loop
5586: doc-+loop
5587: doc--loop
5588: doc-next
5589: doc-leave
5590: doc-?leave
5591: doc-unloop
5592: doc-done
5593:
1.44 crook 5594:
1.21 crook 5595: The standard does not allow using @code{CS-PICK} and @code{CS-ROLL} on
5596: @i{do-sys}. Gforth allows it, but it's your job to ensure that for
1.1 anton 5597: every @code{?DO} etc. there is exactly one @code{UNLOOP} on any path
5598: through the definition (@code{LOOP} etc. compile an @code{UNLOOP} on the
5599: fall-through path). Also, you have to ensure that all @code{LEAVE}s are
5600: resolved (by using one of the loop-ending words or @code{DONE}).
5601:
1.44 crook 5602: @noindent
1.26 crook 5603: Another group of control structure words are:
1.1 anton 5604:
1.44 crook 5605:
1.1 anton 5606: doc-case
5607: doc-endcase
5608: doc-of
5609: doc-endof
5610:
1.44 crook 5611:
1.21 crook 5612: @i{case-sys} and @i{of-sys} cannot be processed using @code{CS-PICK} and
5613: @code{CS-ROLL}.
1.1 anton 5614:
5615: @subsubsection Programming Style
1.47 crook 5616: @cindex control structures programming style
5617: @cindex programming style, arbitrary control structures
1.1 anton 5618:
5619: In order to ensure readability we recommend that you do not create
5620: arbitrary control structures directly, but define new control structure
5621: words for the control structure you want and use these words in your
1.26 crook 5622: program. For example, instead of writing:
1.1 anton 5623:
5624: @example
1.26 crook 5625: BEGIN
1.1 anton 5626: ...
1.26 crook 5627: IF [ 1 CS-ROLL ]
1.1 anton 5628: ...
1.26 crook 5629: AGAIN THEN
1.1 anton 5630: @end example
5631:
1.21 crook 5632: @noindent
1.1 anton 5633: we recommend defining control structure words, e.g.,
5634:
5635: @example
1.26 crook 5636: : WHILE ( DEST -- ORIG DEST )
5637: POSTPONE IF
5638: 1 CS-ROLL ; immediate
5639:
5640: : REPEAT ( orig dest -- )
5641: POSTPONE AGAIN
5642: POSTPONE THEN ; immediate
1.1 anton 5643: @end example
5644:
1.21 crook 5645: @noindent
1.1 anton 5646: and then using these to create the control structure:
5647:
5648: @example
1.26 crook 5649: BEGIN
1.1 anton 5650: ...
1.26 crook 5651: WHILE
1.1 anton 5652: ...
1.26 crook 5653: REPEAT
1.1 anton 5654: @end example
5655:
5656: That's much easier to read, isn't it? Of course, @code{REPEAT} and
5657: @code{WHILE} are predefined, so in this example it would not be
5658: necessary to define them.
5659:
5660: @node Calls and returns, Exception Handling, Arbitrary control structures, Control Structures
5661: @subsection Calls and returns
5662: @cindex calling a definition
5663: @cindex returning from a definition
5664:
1.3 anton 5665: @cindex recursive definitions
5666: A definition can be called simply be writing the name of the definition
1.26 crook 5667: to be called. Normally a definition is invisible during its own
1.3 anton 5668: definition. If you want to write a directly recursive definition, you
1.26 crook 5669: can use @code{recursive} to make the current definition visible, or
5670: @code{recurse} to call the current definition directly.
1.3 anton 5671:
1.44 crook 5672:
1.3 anton 5673: doc-recursive
5674: doc-recurse
5675:
1.44 crook 5676:
1.21 crook 5677: @comment TODO add example of the two recursion methods
1.12 anton 5678: @quotation
5679: @progstyle
5680: I prefer using @code{recursive} to @code{recurse}, because calling the
5681: definition by name is more descriptive (if the name is well-chosen) than
5682: the somewhat cryptic @code{recurse}. E.g., in a quicksort
5683: implementation, it is much better to read (and think) ``now sort the
5684: partitions'' than to read ``now do a recursive call''.
5685: @end quotation
1.3 anton 5686:
1.29 crook 5687: For mutual recursion, use @code{Defer}red words, like this:
1.3 anton 5688:
5689: @example
1.28 crook 5690: Defer foo
1.3 anton 5691:
5692: : bar ( ... -- ... )
5693: ... foo ... ;
5694:
5695: :noname ( ... -- ... )
5696: ... bar ... ;
5697: IS foo
5698: @end example
5699:
1.44 crook 5700: Deferred words are discussed in more detail in @ref{Deferred words}.
1.33 anton 5701:
1.26 crook 5702: The current definition returns control to the calling definition when
1.33 anton 5703: the end of the definition is reached or @code{EXIT} is encountered.
1.1 anton 5704:
5705: doc-exit
5706: doc-;s
5707:
1.44 crook 5708:
1.1 anton 5709: @node Exception Handling, , Calls and returns, Control Structures
5710: @subsection Exception Handling
1.26 crook 5711: @cindex exceptions
1.1 anton 5712:
1.68 anton 5713: @c quit is a very bad idea for error handling,
5714: @c because it does not translate into a THROW
5715: @c it also does not belong into this chapter
5716:
5717: If a word detects an error condition that it cannot handle, it can
5718: @code{throw} an exception. In the simplest case, this will terminate
5719: your program, and report an appropriate error.
1.21 crook 5720:
1.68 anton 5721: doc-throw
1.1 anton 5722:
1.69 anton 5723: @code{Throw} consumes a cell-sized error number on the stack. There are
5724: some predefined error numbers in ANS Forth (see @file{errors.fs}). In
5725: Gforth (and most other systems) you can use the iors produced by various
5726: words as error numbers (e.g., a typical use of @code{allocate} is
5727: @code{allocate throw}). Gforth also provides the word @code{exception}
5728: to define your own error numbers (with decent error reporting); an ANS
5729: Forth version of this word (but without the error messages) is available
5730: in @code{compat/except.fs}. And finally, you can use your own error
1.68 anton 5731: numbers (anything outside the range -4095..0), but won't get nice error
5732: messages, only numbers. For example, try:
5733:
5734: @example
1.69 anton 5735: -10 throw \ ANS defined
5736: -267 throw \ system defined
5737: s" my error" exception throw \ user defined
5738: 7 throw \ arbitrary number
1.68 anton 5739: @end example
5740:
5741: doc---exception-exception
1.1 anton 5742:
1.69 anton 5743: A common idiom to @code{THROW} a specific error if a flag is true is
5744: this:
5745:
5746: @example
5747: @code{( flag ) 0<> @i{errno} and throw}
5748: @end example
5749:
5750: Your program can provide exception handlers to catch exceptions. An
5751: exception handler can be used to correct the problem, or to clean up
5752: some data structures and just throw the exception to the next exception
5753: handler. Note that @code{throw} jumps to the dynamically innermost
5754: exception handler. The system's exception handler is outermost, and just
5755: prints an error and restarts command-line interpretation (or, in batch
5756: mode (i.e., while processing the shell command line), leaves Gforth).
1.1 anton 5757:
1.68 anton 5758: The ANS Forth way to catch exceptions is @code{catch}:
1.1 anton 5759:
1.68 anton 5760: doc-catch
5761:
5762: The most common use of exception handlers is to clean up the state when
5763: an error happens. E.g.,
1.1 anton 5764:
1.26 crook 5765: @example
1.68 anton 5766: base @ >r hex \ actually the hex should be inside foo, or we h
5767: ['] foo catch ( nerror|0 )
5768: r> base !
1.69 anton 5769: ( nerror|0 ) throw \ pass it on
1.26 crook 5770: @end example
1.1 anton 5771:
1.69 anton 5772: A use of @code{catch} for handling the error @code{myerror} might look
5773: like this:
1.44 crook 5774:
1.68 anton 5775: @example
1.69 anton 5776: ['] foo catch
5777: CASE
5778: myerror OF ... ( do something about it ) ENDOF
5779: dup throw \ default: pass other errors on, do nothing on non-errors
5780: ENDCASE
1.68 anton 5781: @end example
1.44 crook 5782:
1.68 anton 5783: Having to wrap the code into a separate word is often cumbersome,
5784: therefore Gforth provides an alternative syntax:
1.1 anton 5785:
5786: @example
1.69 anton 5787: TRY
1.68 anton 5788: @i{code1}
1.69 anton 5789: RECOVER \ optional
1.68 anton 5790: @i{code2} \ optional
1.69 anton 5791: ENDTRY
1.1 anton 5792: @end example
5793:
1.68 anton 5794: This performs @i{Code1}. If @i{code1} completes normally, execution
5795: continues after the @code{endtry}. If @i{Code1} throws, the stacks are
5796: reset to the state during @code{try}, the throw value is pushed on the
5797: data stack, and execution constinues at @i{code2}, and finally falls
5798: through the @code{endtry} into the following code. If there is no
5799: @code{recover} clause, this works like an empty recover clause.
1.26 crook 5800:
1.68 anton 5801: doc-try
5802: doc-recover
5803: doc-endtry
1.26 crook 5804:
1.69 anton 5805: The cleanup example from above in this syntax:
1.26 crook 5806:
1.68 anton 5807: @example
1.69 anton 5808: base @ >r TRY
1.68 anton 5809: hex foo \ now the hex is placed correctly
1.69 anton 5810: 0 \ value for throw
5811: ENDTRY
1.68 anton 5812: r> base ! throw
1.1 anton 5813: @end example
5814:
1.69 anton 5815: And here's the error handling example:
1.1 anton 5816:
1.68 anton 5817: @example
1.69 anton 5818: TRY
1.68 anton 5819: foo
1.69 anton 5820: RECOVER
5821: CASE
5822: myerror OF ... ( do something about it ) ENDOF
5823: throw \ pass other errors on
5824: ENDCASE
5825: ENDTRY
1.68 anton 5826: @end example
1.1 anton 5827:
1.69 anton 5828: @progstyle
5829: As usual, you should ensure that the stack depth is statically known at
5830: the end: either after the @code{throw} for passing on errors, or after
5831: the @code{ENDTRY} (or, if you use @code{catch}, after the end of the
5832: selection construct for handling the error).
5833:
1.68 anton 5834: There are two alternatives to @code{throw}: @code{Abort"} is conditional
5835: and you can provide an error message. @code{Abort} just produces an
5836: ``Aborted'' error.
1.1 anton 5837:
1.68 anton 5838: The problem with these words is that exception handlers cannot
5839: differentiate between different @code{abort"}s; they just look like
5840: @code{-2 throw} to them (the error message cannot be accessed by
5841: standard programs). Similar @code{abort} looks like @code{-1 throw} to
5842: exception handlers.
1.44 crook 5843:
1.68 anton 5844: doc-abort"
1.26 crook 5845: doc-abort
1.29 crook 5846:
5847:
1.44 crook 5848:
1.29 crook 5849: @c -------------------------------------------------------------
1.47 crook 5850: @node Defining Words, Interpretation and Compilation Semantics, Control Structures, Words
1.29 crook 5851: @section Defining Words
5852: @cindex defining words
5853:
1.47 crook 5854: Defining words are used to extend Forth by creating new entries in the dictionary.
5855:
1.29 crook 5856: @menu
1.67 anton 5857: * CREATE::
1.44 crook 5858: * Variables:: Variables and user variables
1.67 anton 5859: * Constants::
1.44 crook 5860: * Values:: Initialised variables
1.67 anton 5861: * Colon Definitions::
1.44 crook 5862: * Anonymous Definitions:: Definitions without names
1.69 anton 5863: * Supplying names:: Passing definition names as strings
1.67 anton 5864: * User-defined Defining Words::
1.44 crook 5865: * Deferred words:: Allow forward references
1.67 anton 5866: * Aliases::
1.29 crook 5867: @end menu
5868:
1.44 crook 5869: @node CREATE, Variables, Defining Words, Defining Words
5870: @subsection @code{CREATE}
1.29 crook 5871: @cindex simple defining words
5872: @cindex defining words, simple
5873:
5874: Defining words are used to create new entries in the dictionary. The
5875: simplest defining word is @code{CREATE}. @code{CREATE} is used like
5876: this:
5877:
5878: @example
5879: CREATE new-word1
5880: @end example
5881:
1.69 anton 5882: @code{CREATE} is a parsing word, i.e., it takes an argument from the
5883: input stream (@code{new-word1} in our example). It generates a
5884: dictionary entry for @code{new-word1}. When @code{new-word1} is
5885: executed, all that it does is leave an address on the stack. The address
5886: represents the value of the data space pointer (@code{HERE}) at the time
5887: that @code{new-word1} was defined. Therefore, @code{CREATE} is a way of
5888: associating a name with the address of a region of memory.
1.29 crook 5889:
1.34 anton 5890: doc-create
5891:
1.69 anton 5892: Note that in ANS Forth guarantees only for @code{create} that its body
5893: is in dictionary data space (i.e., where @code{here}, @code{allot}
5894: etc. work, @pxref{Dictionary allocation}). Also, in ANS Forth only
5895: @code{create}d words can be modified with @code{does>}
5896: (@pxref{User-defined Defining Words}). And in ANS Forth @code{>body}
5897: can only be applied to @code{create}d words.
5898:
1.29 crook 5899: By extending this example to reserve some memory in data space, we end
1.69 anton 5900: up with something like a @i{variable}. Here are two different ways to do
5901: it:
1.29 crook 5902:
5903: @example
5904: CREATE new-word2 1 cells allot \ reserve 1 cell - initial value undefined
5905: CREATE new-word3 4 , \ reserve 1 cell and initialise it (to 4)
5906: @end example
5907:
5908: The variable can be examined and modified using @code{@@} (``fetch'') and
5909: @code{!} (``store'') like this:
5910:
5911: @example
5912: new-word2 @@ . \ get address, fetch from it and display
5913: 1234 new-word2 ! \ new value, get address, store to it
5914: @end example
5915:
1.44 crook 5916: @cindex arrays
5917: A similar mechanism can be used to create arrays. For example, an
5918: 80-character text input buffer:
1.29 crook 5919:
5920: @example
1.44 crook 5921: CREATE text-buf 80 chars allot
5922:
5923: text-buf 0 chars c@@ \ the 1st character (offset 0)
5924: text-buf 3 chars c@@ \ the 4th character (offset 3)
5925: @end example
1.29 crook 5926:
1.44 crook 5927: You can build arbitrarily complex data structures by allocating
1.49 anton 5928: appropriate areas of memory. For further discussions of this, and to
1.66 anton 5929: learn about some Gforth tools that make it easier,
1.49 anton 5930: @xref{Structures}.
1.44 crook 5931:
5932:
5933: @node Variables, Constants, CREATE, Defining Words
5934: @subsection Variables
5935: @cindex variables
5936:
5937: The previous section showed how a sequence of commands could be used to
5938: generate a variable. As a final refinement, the whole code sequence can
5939: be wrapped up in a defining word (pre-empting the subject of the next
5940: section), making it easier to create new variables:
5941:
5942: @example
5943: : myvariableX ( "name" -- a-addr ) CREATE 1 cells allot ;
5944: : myvariable0 ( "name" -- a-addr ) CREATE 0 , ;
5945:
5946: myvariableX foo \ variable foo starts off with an unknown value
5947: myvariable0 joe \ whilst joe is initialised to 0
1.29 crook 5948:
5949: 45 3 * foo ! \ set foo to 135
5950: 1234 joe ! \ set joe to 1234
5951: 3 joe +! \ increment joe by 3.. to 1237
5952: @end example
5953:
5954: Not surprisingly, there is no need to define @code{myvariable}, since
1.44 crook 5955: Forth already has a definition @code{Variable}. ANS Forth does not
1.69 anton 5956: guarantee that a @code{Variable} is initialised when it is created
5957: (i.e., it may behave like @code{myvariableX}). In contrast, Gforth's
5958: @code{Variable} initialises the variable to 0 (i.e., it behaves exactly
5959: like @code{myvariable0}). Forth also provides @code{2Variable} and
1.47 crook 5960: @code{fvariable} for double and floating-point variables, respectively
1.69 anton 5961: -- they are initialised to 0. and 0e in Gforth. If you use a @code{Variable} to
1.47 crook 5962: store a boolean, you can use @code{on} and @code{off} to toggle its
5963: state.
1.29 crook 5964:
1.34 anton 5965: doc-variable
5966: doc-2variable
5967: doc-fvariable
5968:
1.29 crook 5969: @cindex user variables
5970: @cindex user space
5971: The defining word @code{User} behaves in the same way as @code{Variable}.
5972: The difference is that it reserves space in @i{user (data) space} rather
5973: than normal data space. In a Forth system that has a multi-tasker, each
5974: task has its own set of user variables.
5975:
1.34 anton 5976: doc-user
1.67 anton 5977: @c doc-udp
5978: @c doc-uallot
1.34 anton 5979:
1.29 crook 5980: @comment TODO is that stuff about user variables strictly correct? Is it
5981: @comment just terminal tasks that have user variables?
5982: @comment should document tasker.fs (with some examples) elsewhere
5983: @comment in this manual, then expand on user space and user variables.
5984:
1.44 crook 5985: @node Constants, Values, Variables, Defining Words
5986: @subsection Constants
5987: @cindex constants
5988:
5989: @code{Constant} allows you to declare a fixed value and refer to it by
5990: name. For example:
1.29 crook 5991:
5992: @example
5993: 12 Constant INCHES-PER-FOOT
5994: 3E+08 fconstant SPEED-O-LIGHT
5995: @end example
5996:
5997: A @code{Variable} can be both read and written, so its run-time
5998: behaviour is to supply an address through which its current value can be
5999: manipulated. In contrast, the value of a @code{Constant} cannot be
6000: changed once it has been declared@footnote{Well, often it can be -- but
6001: not in a Standard, portable way. It's safer to use a @code{Value} (read
6002: on).} so it's not necessary to supply the address -- it is more
6003: efficient to return the value of the constant directly. That's exactly
6004: what happens; the run-time effect of a constant is to put its value on
1.49 anton 6005: the top of the stack (You can find one
6006: way of implementing @code{Constant} in @ref{User-defined Defining Words}).
1.29 crook 6007:
1.69 anton 6008: Forth also provides @code{2Constant} and @code{fconstant} for defining
1.29 crook 6009: double and floating-point constants, respectively.
6010:
1.34 anton 6011: doc-constant
6012: doc-2constant
6013: doc-fconstant
6014:
6015: @c that's too deep, and it's not necessarily true for all ANS Forths. - anton
1.44 crook 6016: @c nac-> How could that not be true in an ANS Forth? You can't define a
6017: @c constant, use it and then delete the definition of the constant..
1.69 anton 6018:
6019: @c anton->An ANS Forth system can compile a constant to a literal; On
6020: @c decompilation you would see only the number, just as if it had been used
6021: @c in the first place. The word will stay, of course, but it will only be
6022: @c used by the text interpreter (no run-time duties, except when it is
6023: @c POSTPONEd or somesuch).
6024:
6025: @c nac:
1.44 crook 6026: @c I agree that it's rather deep, but IMO it is an important difference
6027: @c relative to other programming languages.. often it's annoying: it
6028: @c certainly changes my programming style relative to C.
6029:
1.69 anton 6030: @c anton: In what way?
6031:
1.29 crook 6032: Constants in Forth behave differently from their equivalents in other
6033: programming languages. In other languages, a constant (such as an EQU in
6034: assembler or a #define in C) only exists at compile-time; in the
6035: executable program the constant has been translated into an absolute
6036: number and, unless you are using a symbolic debugger, it's impossible to
6037: know what abstract thing that number represents. In Forth a constant has
1.44 crook 6038: an entry in the header space and remains there after the code that uses
6039: it has been defined. In fact, it must remain in the dictionary since it
6040: has run-time duties to perform. For example:
1.29 crook 6041:
6042: @example
6043: 12 Constant INCHES-PER-FOOT
6044: : FEET-TO-INCHES ( n1 -- n2 ) INCHES-PER-FOOT * ;
6045: @end example
6046:
6047: @cindex in-lining of constants
6048: When @code{FEET-TO-INCHES} is executed, it will in turn execute the xt
6049: associated with the constant @code{INCHES-PER-FOOT}. If you use
6050: @code{see} to decompile the definition of @code{FEET-TO-INCHES}, you can
6051: see that it makes a call to @code{INCHES-PER-FOOT}. Some Forth compilers
6052: attempt to optimise constants by in-lining them where they are used. You
6053: can force Gforth to in-line a constant like this:
6054:
6055: @example
6056: : FEET-TO-INCHES ( n1 -- n2 ) [ INCHES-PER-FOOT ] LITERAL * ;
6057: @end example
6058:
6059: If you use @code{see} to decompile @i{this} version of
6060: @code{FEET-TO-INCHES}, you can see that @code{INCHES-PER-FOOT} is no
1.49 anton 6061: longer present. To understand how this works, read
6062: @ref{Interpret/Compile states}, and @ref{Literals}.
1.29 crook 6063:
6064: In-lining constants in this way might improve execution time
6065: fractionally, and can ensure that a constant is now only referenced at
6066: compile-time. However, the definition of the constant still remains in
6067: the dictionary. Some Forth compilers provide a mechanism for controlling
6068: a second dictionary for holding transient words such that this second
6069: dictionary can be deleted later in order to recover memory
6070: space. However, there is no standard way of doing this.
6071:
6072:
1.44 crook 6073: @node Values, Colon Definitions, Constants, Defining Words
6074: @subsection Values
6075: @cindex values
1.34 anton 6076:
1.69 anton 6077: A @code{Value} behaves like a @code{Constant}, but it can be changed.
6078: @code{TO} is a parsing word that changes a @code{Values}. In Gforth
6079: (not in ANS Forth) you can access (and change) a @code{value} also with
6080: @code{>body}.
6081:
6082: Here are some
6083: examples:
1.29 crook 6084:
6085: @example
1.69 anton 6086: 12 Value APPLES \ Define APPLES with an initial value of 12
6087: 34 TO APPLES \ Change the value of APPLES. TO is a parsing word
6088: 1 ' APPLES >body +! \ Increment APPLES. Non-standard usage.
6089: APPLES \ puts 35 on the top of the stack.
1.29 crook 6090: @end example
6091:
1.44 crook 6092: doc-value
6093: doc-to
1.29 crook 6094:
1.35 anton 6095:
1.69 anton 6096:
1.44 crook 6097: @node Colon Definitions, Anonymous Definitions, Values, Defining Words
6098: @subsection Colon Definitions
6099: @cindex colon definitions
1.35 anton 6100:
6101: @example
1.44 crook 6102: : name ( ... -- ... )
6103: word1 word2 word3 ;
1.29 crook 6104: @end example
6105:
1.44 crook 6106: @noindent
6107: Creates a word called @code{name} that, upon execution, executes
6108: @code{word1 word2 word3}. @code{name} is a @dfn{(colon) definition}.
1.29 crook 6109:
1.49 anton 6110: The explanation above is somewhat superficial. For simple examples of
6111: colon definitions see @ref{Your first definition}. For an in-depth
1.66 anton 6112: discussion of some of the issues involved, @xref{Interpretation and
1.49 anton 6113: Compilation Semantics}.
1.29 crook 6114:
1.44 crook 6115: doc-:
6116: doc-;
1.1 anton 6117:
1.34 anton 6118:
1.69 anton 6119: @node Anonymous Definitions, Supplying names, Colon Definitions, Defining Words
1.44 crook 6120: @subsection Anonymous Definitions
6121: @cindex colon definitions
6122: @cindex defining words without name
1.34 anton 6123:
1.44 crook 6124: Sometimes you want to define an @dfn{anonymous word}; a word without a
6125: name. You can do this with:
1.1 anton 6126:
1.44 crook 6127: doc-:noname
1.1 anton 6128:
1.44 crook 6129: This leaves the execution token for the word on the stack after the
6130: closing @code{;}. Here's an example in which a deferred word is
6131: initialised with an @code{xt} from an anonymous colon definition:
1.1 anton 6132:
1.29 crook 6133: @example
1.44 crook 6134: Defer deferred
6135: :noname ( ... -- ... )
6136: ... ;
6137: IS deferred
1.29 crook 6138: @end example
1.26 crook 6139:
1.44 crook 6140: @noindent
6141: Gforth provides an alternative way of doing this, using two separate
6142: words:
1.27 crook 6143:
1.44 crook 6144: doc-noname
6145: @cindex execution token of last defined word
6146: doc-lastxt
1.1 anton 6147:
1.44 crook 6148: @noindent
6149: The previous example can be rewritten using @code{noname} and
6150: @code{lastxt}:
1.1 anton 6151:
1.26 crook 6152: @example
1.44 crook 6153: Defer deferred
6154: noname : ( ... -- ... )
6155: ... ;
6156: lastxt IS deferred
1.26 crook 6157: @end example
1.1 anton 6158:
1.29 crook 6159: @noindent
1.44 crook 6160: @code{noname} works with any defining word, not just @code{:}.
6161:
6162: @code{lastxt} also works when the last word was not defined as
1.71 anton 6163: @code{noname}. It does not work for combined words, though. It also has
6164: the useful property that is is valid as soon as the header for a
6165: definition has been built. Thus:
1.44 crook 6166:
6167: @example
6168: lastxt . : foo [ lastxt . ] ; ' foo .
6169: @end example
1.1 anton 6170:
1.44 crook 6171: @noindent
6172: prints 3 numbers; the last two are the same.
1.26 crook 6173:
1.69 anton 6174: @node Supplying names, User-defined Defining Words, Anonymous Definitions, Defining Words
6175: @subsection Supplying the name of a defined word
6176: @cindex names for defined words
6177: @cindex defining words, name given in a string
6178:
6179: By default, a defining word takes the name for the defined word from the
6180: input stream. Sometimes you want to supply the name from a string. You
6181: can do this with:
6182:
6183: doc-nextname
6184:
6185: For example:
6186:
6187: @example
6188: s" foo" nextname create
6189: @end example
6190:
6191: @noindent
6192: is equivalent to:
6193:
6194: @example
6195: create foo
6196: @end example
6197:
6198: @noindent
6199: @code{nextname} works with any defining word.
6200:
1.1 anton 6201:
1.69 anton 6202: @node User-defined Defining Words, Deferred words, Supplying names, Defining Words
1.26 crook 6203: @subsection User-defined Defining Words
6204: @cindex user-defined defining words
6205: @cindex defining words, user-defined
1.1 anton 6206:
1.29 crook 6207: You can create a new defining word by wrapping defining-time code around
6208: an existing defining word and putting the sequence in a colon
1.69 anton 6209: definition.
6210:
6211: @c anton: This example is very complex and leads in a quite different
6212: @c direction from the CREATE-DOES> stuff that follows. It should probably
6213: @c be done elsewhere, or as a subsubsection of this subsection (or as a
6214: @c subsection of Defining Words)
6215:
6216: For example, suppose that you have a word @code{stats} that
1.29 crook 6217: gathers statistics about colon definitions given the @i{xt} of the
6218: definition, and you want every colon definition in your application to
6219: make a call to @code{stats}. You can define and use a new version of
6220: @code{:} like this:
6221:
6222: @example
6223: : stats ( xt -- ) DUP ." (Gathering statistics for " . ." )"
6224: ... ; \ other code
6225:
6226: : my: : lastxt postpone literal ['] stats compile, ;
6227:
6228: my: foo + - ;
6229: @end example
6230:
6231: When @code{foo} is defined using @code{my:} these steps occur:
6232:
6233: @itemize @bullet
6234: @item
6235: @code{my:} is executed.
6236: @item
6237: The @code{:} within the definition (the one between @code{my:} and
6238: @code{lastxt}) is executed, and does just what it always does; it parses
6239: the input stream for a name, builds a dictionary header for the name
6240: @code{foo} and switches @code{state} from interpret to compile.
6241: @item
6242: The word @code{lastxt} is executed. It puts the @i{xt} for the word that is
6243: being defined -- @code{foo} -- onto the stack.
6244: @item
6245: The code that was produced by @code{postpone literal} is executed; this
6246: causes the value on the stack to be compiled as a literal in the code
6247: area of @code{foo}.
6248: @item
6249: The code @code{['] stats} compiles a literal into the definition of
6250: @code{my:}. When @code{compile,} is executed, that literal -- the
6251: execution token for @code{stats} -- is layed down in the code area of
6252: @code{foo} , following the literal@footnote{Strictly speaking, the
6253: mechanism that @code{compile,} uses to convert an @i{xt} into something
6254: in the code area is implementation-dependent. A threaded implementation
6255: might spit out the execution token directly whilst another
6256: implementation might spit out a native code sequence.}.
6257: @item
6258: At this point, the execution of @code{my:} is complete, and control
6259: returns to the text interpreter. The text interpreter is in compile
6260: state, so subsequent text @code{+ -} is compiled into the definition of
6261: @code{foo} and the @code{;} terminates the definition as always.
6262: @end itemize
6263:
6264: You can use @code{see} to decompile a word that was defined using
6265: @code{my:} and see how it is different from a normal @code{:}
6266: definition. For example:
6267:
6268: @example
6269: : bar + - ; \ like foo but using : rather than my:
6270: see bar
6271: : bar
6272: + - ;
6273: see foo
6274: : foo
6275: 107645672 stats + - ;
6276:
6277: \ use ' stats . to show that 107645672 is the xt for stats
6278: @end example
6279:
6280: You can use techniques like this to make new defining words in terms of
6281: @i{any} existing defining word.
1.1 anton 6282:
6283:
1.29 crook 6284: @cindex defining defining words
1.26 crook 6285: @cindex @code{CREATE} ... @code{DOES>}
6286: If you want the words defined with your defining words to behave
6287: differently from words defined with standard defining words, you can
6288: write your defining word like this:
1.1 anton 6289:
6290: @example
1.26 crook 6291: : def-word ( "name" -- )
1.29 crook 6292: CREATE @i{code1}
1.26 crook 6293: DOES> ( ... -- ... )
1.29 crook 6294: @i{code2} ;
1.26 crook 6295:
6296: def-word name
1.1 anton 6297: @end example
6298:
1.29 crook 6299: @cindex child words
6300: This fragment defines a @dfn{defining word} @code{def-word} and then
6301: executes it. When @code{def-word} executes, it @code{CREATE}s a new
6302: word, @code{name}, and executes the code @i{code1}. The code @i{code2}
6303: is not executed at this time. The word @code{name} is sometimes called a
6304: @dfn{child} of @code{def-word}.
6305:
6306: When you execute @code{name}, the address of the body of @code{name} is
6307: put on the data stack and @i{code2} is executed (the address of the body
6308: of @code{name} is the address @code{HERE} returns immediately after the
1.69 anton 6309: @code{CREATE}, i.e., the address a @code{create}d word returns by
6310: default).
6311:
6312: @c anton:
6313: @c www.dictionary.com says:
6314: @c at·a·vism: 1.The reappearance of a characteristic in an organism after
6315: @c several generations of absence, usually caused by the chance
6316: @c recombination of genes. 2.An individual or a part that exhibits
6317: @c atavism. Also called throwback. 3.The return of a trait or recurrence
6318: @c of previous behavior after a period of absence.
6319: @c
6320: @c Doesn't seem to fit.
1.29 crook 6321:
1.69 anton 6322: @c @cindex atavism in child words
1.33 anton 6323: You can use @code{def-word} to define a set of child words that behave
1.69 anton 6324: similarly; they all have a common run-time behaviour determined by
6325: @i{code2}. Typically, the @i{code1} sequence builds a data area in the
6326: body of the child word. The structure of the data is common to all
6327: children of @code{def-word}, but the data values are specific -- and
6328: private -- to each child word. When a child word is executed, the
6329: address of its private data area is passed as a parameter on TOS to be
6330: used and manipulated@footnote{It is legitimate both to read and write to
6331: this data area.} by @i{code2}.
1.29 crook 6332:
6333: The two fragments of code that make up the defining words act (are
6334: executed) at two completely separate times:
1.1 anton 6335:
1.29 crook 6336: @itemize @bullet
6337: @item
6338: At @i{define time}, the defining word executes @i{code1} to generate a
6339: child word
6340: @item
6341: At @i{child execution time}, when a child word is invoked, @i{code2}
6342: is executed, using parameters (data) that are private and specific to
6343: the child word.
6344: @end itemize
6345:
1.44 crook 6346: Another way of understanding the behaviour of @code{def-word} and
6347: @code{name} is to say that, if you make the following definitions:
1.33 anton 6348: @example
6349: : def-word1 ( "name" -- )
6350: CREATE @i{code1} ;
6351:
6352: : action1 ( ... -- ... )
6353: @i{code2} ;
6354:
6355: def-word1 name1
6356: @end example
6357:
1.44 crook 6358: @noindent
6359: Then using @code{name1 action1} is equivalent to using @code{name}.
1.1 anton 6360:
1.29 crook 6361: The classic example is that you can define @code{CONSTANT} in this way:
1.26 crook 6362:
1.1 anton 6363: @example
1.29 crook 6364: : CONSTANT ( w "name" -- )
6365: CREATE ,
1.26 crook 6366: DOES> ( -- w )
6367: @@ ;
1.1 anton 6368: @end example
6369:
1.29 crook 6370: @comment There is a beautiful description of how this works and what
6371: @comment it does in the Forthwrite 100th edition.. as well as an elegant
6372: @comment commentary on the Counting Fruits problem.
6373:
6374: When you create a constant with @code{5 CONSTANT five}, a set of
6375: define-time actions take place; first a new word @code{five} is created,
6376: then the value 5 is laid down in the body of @code{five} with
1.44 crook 6377: @code{,}. When @code{five} is executed, the address of the body is put on
1.29 crook 6378: the stack, and @code{@@} retrieves the value 5. The word @code{five} has
6379: no code of its own; it simply contains a data field and a pointer to the
6380: code that follows @code{DOES>} in its defining word. That makes words
6381: created in this way very compact.
6382:
6383: The final example in this section is intended to remind you that space
6384: reserved in @code{CREATE}d words is @i{data} space and therefore can be
6385: both read and written by a Standard program@footnote{Exercise: use this
6386: example as a starting point for your own implementation of @code{Value}
6387: and @code{TO} -- if you get stuck, investigate the behaviour of @code{'} and
6388: @code{[']}.}:
6389:
6390: @example
6391: : foo ( "name" -- )
6392: CREATE -1 ,
6393: DOES> ( -- )
1.33 anton 6394: @@ . ;
1.29 crook 6395:
6396: foo first-word
6397: foo second-word
6398:
6399: 123 ' first-word >BODY !
6400: @end example
6401:
6402: If @code{first-word} had been a @code{CREATE}d word, we could simply
6403: have executed it to get the address of its data field. However, since it
6404: was defined to have @code{DOES>} actions, its execution semantics are to
6405: perform those @code{DOES>} actions. To get the address of its data field
6406: it's necessary to use @code{'} to get its xt, then @code{>BODY} to
6407: translate the xt into the address of the data field. When you execute
6408: @code{first-word}, it will display @code{123}. When you execute
6409: @code{second-word} it will display @code{-1}.
1.26 crook 6410:
6411: @cindex stack effect of @code{DOES>}-parts
6412: @cindex @code{DOES>}-parts, stack effect
1.29 crook 6413: In the examples above the stack comment after the @code{DOES>} specifies
1.26 crook 6414: the stack effect of the defined words, not the stack effect of the
6415: following code (the following code expects the address of the body on
6416: the top of stack, which is not reflected in the stack comment). This is
6417: the convention that I use and recommend (it clashes a bit with using
6418: locals declarations for stack effect specification, though).
1.1 anton 6419:
1.53 anton 6420: @menu
6421: * CREATE..DOES> applications::
6422: * CREATE..DOES> details::
1.63 anton 6423: * Advanced does> usage example::
1.53 anton 6424: @end menu
6425:
6426: @node CREATE..DOES> applications, CREATE..DOES> details, User-defined Defining Words, User-defined Defining Words
1.26 crook 6427: @subsubsection Applications of @code{CREATE..DOES>}
6428: @cindex @code{CREATE} ... @code{DOES>}, applications
1.1 anton 6429:
1.26 crook 6430: You may wonder how to use this feature. Here are some usage patterns:
1.1 anton 6431:
1.26 crook 6432: @cindex factoring similar colon definitions
6433: When you see a sequence of code occurring several times, and you can
6434: identify a meaning, you will factor it out as a colon definition. When
6435: you see similar colon definitions, you can factor them using
6436: @code{CREATE..DOES>}. E.g., an assembler usually defines several words
6437: that look very similar:
1.1 anton 6438: @example
1.26 crook 6439: : ori, ( reg-target reg-source n -- )
6440: 0 asm-reg-reg-imm ;
6441: : andi, ( reg-target reg-source n -- )
6442: 1 asm-reg-reg-imm ;
1.1 anton 6443: @end example
6444:
1.26 crook 6445: @noindent
6446: This could be factored with:
6447: @example
6448: : reg-reg-imm ( op-code -- )
6449: CREATE ,
6450: DOES> ( reg-target reg-source n -- )
6451: @@ asm-reg-reg-imm ;
6452:
6453: 0 reg-reg-imm ori,
6454: 1 reg-reg-imm andi,
6455: @end example
1.1 anton 6456:
1.26 crook 6457: @cindex currying
6458: Another view of @code{CREATE..DOES>} is to consider it as a crude way to
6459: supply a part of the parameters for a word (known as @dfn{currying} in
6460: the functional language community). E.g., @code{+} needs two
6461: parameters. Creating versions of @code{+} with one parameter fixed can
6462: be done like this:
1.1 anton 6463: @example
1.26 crook 6464: : curry+ ( n1 -- )
6465: CREATE ,
6466: DOES> ( n2 -- n1+n2 )
6467: @@ + ;
6468:
6469: 3 curry+ 3+
6470: -2 curry+ 2-
1.1 anton 6471: @end example
6472:
1.63 anton 6473: @node CREATE..DOES> details, Advanced does> usage example, CREATE..DOES> applications, User-defined Defining Words
1.26 crook 6474: @subsubsection The gory details of @code{CREATE..DOES>}
6475: @cindex @code{CREATE} ... @code{DOES>}, details
1.1 anton 6476:
1.26 crook 6477: doc-does>
1.1 anton 6478:
1.26 crook 6479: @cindex @code{DOES>} in a separate definition
6480: This means that you need not use @code{CREATE} and @code{DOES>} in the
6481: same definition; you can put the @code{DOES>}-part in a separate
1.29 crook 6482: definition. This allows us to, e.g., select among different @code{DOES>}-parts:
1.26 crook 6483: @example
6484: : does1
6485: DOES> ( ... -- ... )
1.44 crook 6486: ... ;
6487:
6488: : does2
6489: DOES> ( ... -- ... )
6490: ... ;
6491:
6492: : def-word ( ... -- ... )
6493: create ...
6494: IF
6495: does1
6496: ELSE
6497: does2
6498: ENDIF ;
6499: @end example
6500:
6501: In this example, the selection of whether to use @code{does1} or
1.69 anton 6502: @code{does2} is made at definition-time; at the time that the child word is
1.44 crook 6503: @code{CREATE}d.
6504:
6505: @cindex @code{DOES>} in interpretation state
6506: In a standard program you can apply a @code{DOES>}-part only if the last
6507: word was defined with @code{CREATE}. In Gforth, the @code{DOES>}-part
6508: will override the behaviour of the last word defined in any case. In a
6509: standard program, you can use @code{DOES>} only in a colon
6510: definition. In Gforth, you can also use it in interpretation state, in a
6511: kind of one-shot mode; for example:
6512: @example
6513: CREATE name ( ... -- ... )
6514: @i{initialization}
6515: DOES>
6516: @i{code} ;
6517: @end example
6518:
6519: @noindent
6520: is equivalent to the standard:
6521: @example
6522: :noname
6523: DOES>
6524: @i{code} ;
6525: CREATE name EXECUTE ( ... -- ... )
6526: @i{initialization}
6527: @end example
6528:
1.53 anton 6529: doc->body
6530:
1.63 anton 6531: @node Advanced does> usage example, , CREATE..DOES> details, User-defined Defining Words
6532: @subsubsection Advanced does> usage example
6533:
6534: The MIPS disassembler (@file{arch/mips/disasm.fs}) contains many words
6535: for disassembling instructions, that follow a very repetetive scheme:
6536:
6537: @example
6538: :noname @var{disasm-operands} s" @var{inst-name}" type ;
6539: @var{entry-num} cells @var{table} + !
6540: @end example
6541:
6542: Of course, this inspires the idea to factor out the commonalities to
6543: allow a definition like
6544:
6545: @example
6546: @var{disasm-operands} @var{entry-num} @var{table} define-inst @var{inst-name}
6547: @end example
6548:
6549: The parameters @var{disasm-operands} and @var{table} are usually
1.69 anton 6550: correlated. Moreover, before I wrote the disassembler, there already
6551: existed code that defines instructions like this:
1.63 anton 6552:
6553: @example
6554: @var{entry-num} @var{inst-format} @var{inst-name}
6555: @end example
6556:
6557: This code comes from the assembler and resides in
6558: @file{arch/mips/insts.fs}.
6559:
6560: So I had to define the @var{inst-format} words that performed the scheme
6561: above when executed. At first I chose to use run-time code-generation:
6562:
6563: @example
6564: : @var{inst-format} ( entry-num "name" -- ; compiled code: addr w -- )
6565: :noname Postpone @var{disasm-operands}
6566: name Postpone sliteral Postpone type Postpone ;
6567: swap cells @var{table} + ! ;
6568: @end example
6569:
6570: Note that this supplies the other two parameters of the scheme above.
1.44 crook 6571:
1.63 anton 6572: An alternative would have been to write this using
6573: @code{create}/@code{does>}:
6574:
6575: @example
6576: : @var{inst-format} ( entry-num "name" -- )
6577: here name string, ( entry-num c-addr ) \ parse and save "name"
6578: noname create , ( entry-num )
6579: lastxt swap cells @var{table} + !
6580: does> ( addr w -- )
6581: \ disassemble instruction w at addr
6582: @@ >r
6583: @var{disasm-operands}
6584: r> count type ;
6585: @end example
6586:
6587: Somehow the first solution is simpler, mainly because it's simpler to
6588: shift a string from definition-time to use-time with @code{sliteral}
6589: than with @code{string,} and friends.
6590:
6591: I wrote a lot of words following this scheme and soon thought about
6592: factoring out the commonalities among them. Note that this uses a
6593: two-level defining word, i.e., a word that defines ordinary defining
6594: words.
6595:
6596: This time a solution involving @code{postpone} and friends seemed more
6597: difficult (try it as an exercise), so I decided to use a
6598: @code{create}/@code{does>} word; since I was already at it, I also used
6599: @code{create}/@code{does>} for the lower level (try using
6600: @code{postpone} etc. as an exercise), resulting in the following
6601: definition:
6602:
6603: @example
6604: : define-format ( disasm-xt table-xt -- )
6605: \ define an instruction format that uses disasm-xt for
6606: \ disassembling and enters the defined instructions into table
6607: \ table-xt
6608: create 2,
6609: does> ( u "inst" -- )
6610: \ defines an anonymous word for disassembling instruction inst,
6611: \ and enters it as u-th entry into table-xt
6612: 2@@ swap here name string, ( u table-xt disasm-xt c-addr ) \ remember string
6613: noname create 2, \ define anonymous word
6614: execute lastxt swap ! \ enter xt of defined word into table-xt
6615: does> ( addr w -- )
6616: \ disassemble instruction w at addr
6617: 2@@ >r ( addr w disasm-xt R: c-addr )
6618: execute ( R: c-addr ) \ disassemble operands
6619: r> count type ; \ print name
6620: @end example
6621:
6622: Note that the tables here (in contrast to above) do the @code{cells +}
6623: by themselves (that's why you have to pass an xt). This word is used in
6624: the following way:
6625:
6626: @example
6627: ' @var{disasm-operands} ' @var{table} define-format @var{inst-format}
6628: @end example
6629:
1.71 anton 6630: As shown above, the defined instruction format is then used like this:
6631:
6632: @example
6633: @var{entry-num} @var{inst-format} @var{inst-name}
6634: @end example
6635:
1.63 anton 6636: In terms of currying, this kind of two-level defining word provides the
6637: parameters in three stages: first @var{disasm-operands} and @var{table},
6638: then @var{entry-num} and @var{inst-name}, finally @code{addr w}, i.e.,
6639: the instruction to be disassembled.
6640:
6641: Of course this did not quite fit all the instruction format names used
6642: in @file{insts.fs}, so I had to define a few wrappers that conditioned
6643: the parameters into the right form.
6644:
6645: If you have trouble following this section, don't worry. First, this is
6646: involved and takes time (and probably some playing around) to
6647: understand; second, this is the first two-level
6648: @code{create}/@code{does>} word I have written in seventeen years of
6649: Forth; and if I did not have @file{insts.fs} to start with, I may well
6650: have elected to use just a one-level defining word (with some repeating
6651: of parameters when using the defining word). So it is not necessary to
6652: understand this, but it may improve your understanding of Forth.
1.44 crook 6653:
6654:
6655: @node Deferred words, Aliases, User-defined Defining Words, Defining Words
6656: @subsection Deferred words
6657: @cindex deferred words
6658:
6659: The defining word @code{Defer} allows you to define a word by name
6660: without defining its behaviour; the definition of its behaviour is
6661: deferred. Here are two situation where this can be useful:
6662:
6663: @itemize @bullet
6664: @item
6665: Where you want to allow the behaviour of a word to be altered later, and
6666: for all precompiled references to the word to change when its behaviour
6667: is changed.
6668: @item
6669: For mutual recursion; @xref{Calls and returns}.
6670: @end itemize
6671:
6672: In the following example, @code{foo} always invokes the version of
6673: @code{greet} that prints ``@code{Good morning}'' whilst @code{bar}
6674: always invokes the version that prints ``@code{Hello}''. There is no way
6675: of getting @code{foo} to use the later version without re-ordering the
6676: source code and recompiling it.
6677:
6678: @example
6679: : greet ." Good morning" ;
6680: : foo ... greet ... ;
6681: : greet ." Hello" ;
6682: : bar ... greet ... ;
6683: @end example
6684:
6685: This problem can be solved by defining @code{greet} as a @code{Defer}red
6686: word. The behaviour of a @code{Defer}red word can be defined and
6687: redefined at any time by using @code{IS} to associate the xt of a
6688: previously-defined word with it. The previous example becomes:
6689:
6690: @example
1.69 anton 6691: Defer greet ( -- )
1.44 crook 6692: : foo ... greet ... ;
6693: : bar ... greet ... ;
1.69 anton 6694: : greet1 ( -- ) ." Good morning" ;
6695: : greet2 ( -- ) ." Hello" ;
1.44 crook 6696: ' greet2 <IS> greet \ make greet behave like greet2
6697: @end example
6698:
1.69 anton 6699: @progstyle
6700: You should write a stack comment for every deferred word, and put only
6701: XTs into deferred words that conform to this stack effect. Otherwise
6702: it's too difficult to use the deferred word.
6703:
1.44 crook 6704: A deferred word can be used to improve the statistics-gathering example
6705: from @ref{User-defined Defining Words}; rather than edit the
6706: application's source code to change every @code{:} to a @code{my:}, do
6707: this:
6708:
6709: @example
6710: : real: : ; \ retain access to the original
6711: defer : \ redefine as a deferred word
1.69 anton 6712: ' my: <IS> : \ use special version of :
1.44 crook 6713: \
6714: \ load application here
6715: \
1.69 anton 6716: ' real: <IS> : \ go back to the original
1.44 crook 6717: @end example
6718:
6719:
6720: One thing to note is that @code{<IS>} consumes its name when it is
6721: executed. If you want to specify the name at compile time, use
6722: @code{[IS]}:
6723:
6724: @example
6725: : set-greet ( xt -- )
6726: [IS] greet ;
6727:
6728: ' greet1 set-greet
6729: @end example
6730:
1.69 anton 6731: A deferred word can only inherit execution semantics from the xt
6732: (because that is all that an xt can represent -- for more discussion of
6733: this @pxref{Tokens for Words}); by default it will have default
6734: interpretation and compilation semantics deriving from this execution
6735: semantics. However, you can change the interpretation and compilation
6736: semantics of the deferred word in the usual ways:
1.44 crook 6737:
6738: @example
6739: : bar .... ; compile-only
6740: Defer fred immediate
6741: Defer jim
6742:
6743: ' bar <IS> jim \ jim has default semantics
6744: ' bar <IS> fred \ fred is immediate
6745: @end example
6746:
6747: doc-defer
6748: doc-<is>
6749: doc-[is]
6750: doc-is
6751: @comment TODO document these: what's defers [is]
6752: doc-what's
6753: doc-defers
6754:
6755: @c Use @code{words-deferred} to see a list of deferred words.
6756:
6757: Definitions in ANS Forth for @code{defer}, @code{<is>} and @code{[is]}
6758: are provided in @file{compat/defer.fs}.
6759:
6760:
1.69 anton 6761: @node Aliases, , Deferred words, Defining Words
1.44 crook 6762: @subsection Aliases
6763: @cindex aliases
1.1 anton 6764:
1.44 crook 6765: The defining word @code{Alias} allows you to define a word by name that
6766: has the same behaviour as some other word. Here are two situation where
6767: this can be useful:
1.1 anton 6768:
1.44 crook 6769: @itemize @bullet
6770: @item
6771: When you want access to a word's definition from a different word list
6772: (for an example of this, see the definition of the @code{Root} word list
6773: in the Gforth source).
6774: @item
6775: When you want to create a synonym; a definition that can be known by
6776: either of two names (for example, @code{THEN} and @code{ENDIF} are
6777: aliases).
6778: @end itemize
1.1 anton 6779:
1.69 anton 6780: Like deferred words, an alias has default compilation and interpretation
6781: semantics at the beginning (not the modifications of the other word),
6782: but you can change them in the usual ways (@code{immediate},
6783: @code{compile-only}). For example:
1.1 anton 6784:
6785: @example
1.44 crook 6786: : foo ... ; immediate
6787:
6788: ' foo Alias bar \ bar is not an immediate word
6789: ' foo Alias fooby immediate \ fooby is an immediate word
1.1 anton 6790: @end example
6791:
1.44 crook 6792: Words that are aliases have the same xt, different headers in the
6793: dictionary, and consequently different name tokens (@pxref{Tokens for
6794: Words}) and possibly different immediate flags. An alias can only have
6795: default or immediate compilation semantics; you can define aliases for
6796: combined words with @code{interpret/compile:} -- see @ref{Combined words}.
1.1 anton 6797:
1.44 crook 6798: doc-alias
1.1 anton 6799:
6800:
1.47 crook 6801: @node Interpretation and Compilation Semantics, Tokens for Words, Defining Words, Words
6802: @section Interpretation and Compilation Semantics
1.26 crook 6803: @cindex semantics, interpretation and compilation
1.1 anton 6804:
1.71 anton 6805: @c !! state and ' are used without explanation
6806: @c example for immediate/compile-only? or is the tutorial enough
6807:
1.26 crook 6808: @cindex interpretation semantics
1.71 anton 6809: The @dfn{interpretation semantics} of a (named) word are what the text
1.26 crook 6810: interpreter does when it encounters the word in interpret state. It also
6811: appears in some other contexts, e.g., the execution token returned by
1.71 anton 6812: @code{' @i{word}} identifies the interpretation semantics of @i{word}
6813: (in other words, @code{' @i{word} execute} is equivalent to
1.29 crook 6814: interpret-state text interpretation of @code{@i{word}}).
1.1 anton 6815:
1.26 crook 6816: @cindex compilation semantics
1.71 anton 6817: The @dfn{compilation semantics} of a (named) word are what the text
6818: interpreter does when it encounters the word in compile state. It also
6819: appears in other contexts, e.g, @code{POSTPONE @i{word}}
6820: compiles@footnote{In standard terminology, ``appends to the current
6821: definition''.} the compilation semantics of @i{word}.
1.1 anton 6822:
1.26 crook 6823: @cindex execution semantics
6824: The standard also talks about @dfn{execution semantics}. They are used
6825: only for defining the interpretation and compilation semantics of many
6826: words. By default, the interpretation semantics of a word are to
6827: @code{execute} its execution semantics, and the compilation semantics of
6828: a word are to @code{compile,} its execution semantics.@footnote{In
6829: standard terminology: The default interpretation semantics are its
6830: execution semantics; the default compilation semantics are to append its
6831: execution semantics to the execution semantics of the current
6832: definition.}
6833:
1.71 anton 6834: Unnamed words (@pxref{Anonymous Definitions}) cannot be encountered by
6835: the text interpreter, ticked, or @code{postpone}d, so they have no
6836: interpretation or compilation semantics. Their behaviour is represented
6837: by their XT (@pxref{Tokens for Words}), and we call it execution
6838: semantics, too.
6839:
1.26 crook 6840: @comment TODO expand, make it co-operate with new sections on text interpreter.
6841:
6842: @cindex immediate words
6843: @cindex compile-only words
6844: You can change the semantics of the most-recently defined word:
6845:
1.44 crook 6846:
1.26 crook 6847: doc-immediate
6848: doc-compile-only
6849: doc-restrict
6850:
1.44 crook 6851:
1.26 crook 6852: Note that ticking (@code{'}) a compile-only word gives an error
6853: (``Interpreting a compile-only word'').
1.1 anton 6854:
1.47 crook 6855: @menu
1.67 anton 6856: * Combined words::
1.47 crook 6857: @end menu
1.44 crook 6858:
1.71 anton 6859:
1.48 anton 6860: @node Combined words, , Interpretation and Compilation Semantics, Interpretation and Compilation Semantics
1.44 crook 6861: @subsection Combined Words
6862: @cindex combined words
6863:
6864: Gforth allows you to define @dfn{combined words} -- words that have an
6865: arbitrary combination of interpretation and compilation semantics.
6866:
1.26 crook 6867: doc-interpret/compile:
1.1 anton 6868:
1.26 crook 6869: This feature was introduced for implementing @code{TO} and @code{S"}. I
6870: recommend that you do not define such words, as cute as they may be:
6871: they make it hard to get at both parts of the word in some contexts.
6872: E.g., assume you want to get an execution token for the compilation
6873: part. Instead, define two words, one that embodies the interpretation
6874: part, and one that embodies the compilation part. Once you have done
6875: that, you can define a combined word with @code{interpret/compile:} for
6876: the convenience of your users.
1.1 anton 6877:
1.26 crook 6878: You might try to use this feature to provide an optimizing
6879: implementation of the default compilation semantics of a word. For
6880: example, by defining:
1.1 anton 6881: @example
1.26 crook 6882: :noname
6883: foo bar ;
6884: :noname
6885: POSTPONE foo POSTPONE bar ;
1.29 crook 6886: interpret/compile: opti-foobar
1.1 anton 6887: @end example
1.26 crook 6888:
1.23 crook 6889: @noindent
1.26 crook 6890: as an optimizing version of:
6891:
1.1 anton 6892: @example
1.26 crook 6893: : foobar
6894: foo bar ;
1.1 anton 6895: @end example
6896:
1.26 crook 6897: Unfortunately, this does not work correctly with @code{[compile]},
6898: because @code{[compile]} assumes that the compilation semantics of all
6899: @code{interpret/compile:} words are non-default. I.e., @code{[compile]
1.29 crook 6900: opti-foobar} would compile compilation semantics, whereas
6901: @code{[compile] foobar} would compile interpretation semantics.
1.1 anton 6902:
1.26 crook 6903: @cindex state-smart words (are a bad idea)
1.29 crook 6904: Some people try to use @dfn{state-smart} words to emulate the feature provided
1.26 crook 6905: by @code{interpret/compile:} (words are state-smart if they check
6906: @code{STATE} during execution). E.g., they would try to code
6907: @code{foobar} like this:
1.1 anton 6908:
1.26 crook 6909: @example
6910: : foobar
6911: STATE @@
6912: IF ( compilation state )
6913: POSTPONE foo POSTPONE bar
6914: ELSE
6915: foo bar
6916: ENDIF ; immediate
6917: @end example
1.1 anton 6918:
1.26 crook 6919: Although this works if @code{foobar} is only processed by the text
6920: interpreter, it does not work in other contexts (like @code{'} or
6921: @code{POSTPONE}). E.g., @code{' foobar} will produce an execution token
6922: for a state-smart word, not for the interpretation semantics of the
6923: original @code{foobar}; when you execute this execution token (directly
6924: with @code{EXECUTE} or indirectly through @code{COMPILE,}) in compile
6925: state, the result will not be what you expected (i.e., it will not
6926: perform @code{foo bar}). State-smart words are a bad idea. Simply don't
6927: write them@footnote{For a more detailed discussion of this topic, see
1.66 anton 6928: M. Anton Ertl,
6929: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,@code{State}-smartness---Why
6930: it is Evil and How to Exorcise it}}, EuroForth '98.}!
1.1 anton 6931:
1.26 crook 6932: @cindex defining words with arbitrary semantics combinations
6933: It is also possible to write defining words that define words with
6934: arbitrary combinations of interpretation and compilation semantics. In
6935: general, they look like this:
1.1 anton 6936:
1.26 crook 6937: @example
6938: : def-word
6939: create-interpret/compile
1.29 crook 6940: @i{code1}
1.26 crook 6941: interpretation>
1.29 crook 6942: @i{code2}
1.26 crook 6943: <interpretation
6944: compilation>
1.29 crook 6945: @i{code3}
1.26 crook 6946: <compilation ;
6947: @end example
1.1 anton 6948:
1.29 crook 6949: For a @i{word} defined with @code{def-word}, the interpretation
6950: semantics are to push the address of the body of @i{word} and perform
6951: @i{code2}, and the compilation semantics are to push the address of
6952: the body of @i{word} and perform @i{code3}. E.g., @code{constant}
1.26 crook 6953: can also be defined like this (except that the defined constants don't
6954: behave correctly when @code{[compile]}d):
1.1 anton 6955:
1.26 crook 6956: @example
6957: : constant ( n "name" -- )
6958: create-interpret/compile
6959: ,
6960: interpretation> ( -- n )
6961: @@
6962: <interpretation
6963: compilation> ( compilation. -- ; run-time. -- n )
6964: @@ postpone literal
6965: <compilation ;
6966: @end example
1.1 anton 6967:
1.44 crook 6968:
1.26 crook 6969: doc-create-interpret/compile
6970: doc-interpretation>
6971: doc-<interpretation
6972: doc-compilation>
6973: doc-<compilation
1.1 anton 6974:
1.44 crook 6975:
1.29 crook 6976: Words defined with @code{interpret/compile:} and
1.26 crook 6977: @code{create-interpret/compile} have an extended header structure that
6978: differs from other words; however, unless you try to access them with
6979: plain address arithmetic, you should not notice this. Words for
6980: accessing the header structure usually know how to deal with this; e.g.,
1.29 crook 6981: @code{'} @i{word} @code{>body} also gives you the body of a word created
6982: with @code{create-interpret/compile}.
1.1 anton 6983:
1.44 crook 6984:
1.27 crook 6985: doc-postpone
1.44 crook 6986:
1.29 crook 6987: @comment TODO -- expand glossary text for POSTPONE
1.27 crook 6988:
1.47 crook 6989:
6990: @c -------------------------------------------------------------
6991: @node Tokens for Words, The Text Interpreter, Interpretation and Compilation Semantics, Words
6992: @section Tokens for Words
6993: @cindex tokens for words
6994:
6995: This section describes the creation and use of tokens that represent
6996: words.
6997:
1.71 anton 6998: @menu
6999: * Execution token:: represents execution/interpretation semantics
7000: * Compilation token:: represents compilation semantics
7001: * Name token:: represents named words
7002: @end menu
1.47 crook 7003:
1.71 anton 7004: @node Execution token, Compilation token, Tokens for Words, Tokens for Words
7005: @subsection Execution token
1.47 crook 7006:
7007: @cindex xt
7008: @cindex execution token
1.71 anton 7009: An @dfn{execution token} (@i{XT}) represents some behaviour of a word.
7010: You can use @code{execute} to invoke this behaviour.
1.47 crook 7011:
1.71 anton 7012: @cindex tick (')
7013: You can use @code{'} to get an execution token that represents the
7014: interpretation semantics of a named word:
1.47 crook 7015:
7016: @example
1.71 anton 7017: 5 ' .
7018: execute
7019: @end example
1.47 crook 7020:
1.71 anton 7021: doc-'
7022:
7023: @code{'} parses at run-time; there is also a word @code{[']} that parses
7024: when it is compiled, and compiles the resulting XT:
7025:
7026: @example
7027: : foo ['] . execute ;
7028: 5 foo
7029: : bar ' execute ; \ by contrast,
7030: 5 bar . \ ' parses "." when bar executes
7031: @end example
7032:
7033: doc-[']
7034:
7035: If you want the execution token of @i{word}, write @code{['] @i{word}}
7036: in compiled code and @code{' @i{word}} in interpreted code. Gforth's
7037: @code{'} and @code{[']} behave somewhat unusually by complaining about
7038: compile-only words (because these words have no interpretation
7039: semantics). You might get what you want by using @code{COMP' @i{word}
7040: DROP} or @code{[COMP'] @i{word} DROP} (for details @pxref{Compilation
7041: token}).
7042:
7043: Another way to get an XT is @code{:noname} or @code{lastxt}
7044: (@pxref{Anonymous Definitions}). For anonymous words this gives an xt
7045: for the only behaviour the word has (the execution semantics). For
7046: named words, @code{lastxt} produces an XT for the same behaviour it
7047: would produce if the word was defined anonymously.
7048:
7049: @example
7050: :noname ." hello" ;
7051: execute
1.47 crook 7052: @end example
7053:
1.71 anton 7054: An XT occupies one cell and can be manipulated like any other cell.
7055:
1.47 crook 7056: @cindex code field address
7057: @cindex CFA
1.71 anton 7058: In ANS Forth the XT is just an abstract data type (i.e., defined by the
7059: operations that produce or consume it). For old hands: In Gforth, the
7060: XT is implemented as a code field address (CFA).
7061:
7062: @c !! discuss "compile," some more (or in Macros).
7063:
7064: doc-execute
7065: doc-perform
7066: doc-compile,
7067:
7068: @node Compilation token, Name token, Execution token, Tokens for Words
7069: @subsection Compilation token
1.47 crook 7070:
7071: @cindex compilation token
1.71 anton 7072: @cindex CT (compilation token)
7073: Gforth represents the compilation semantics of a named word by a
1.47 crook 7074: @dfn{compilation token} consisting of two cells: @i{w xt}. The top cell
7075: @i{xt} is an execution token. The compilation semantics represented by
7076: the compilation token can be performed with @code{execute}, which
7077: consumes the whole compilation token, with an additional stack effect
7078: determined by the represented compilation semantics.
7079:
7080: At present, the @i{w} part of a compilation token is an execution token,
7081: and the @i{xt} part represents either @code{execute} or
7082: @code{compile,}@footnote{Depending upon the compilation semantics of the
7083: word. If the word has default compilation semantics, the @i{xt} will
7084: represent @code{compile,}. Otherwise (e.g., for immediate words), the
7085: @i{xt} will represent @code{execute}.}. However, don't rely on that
7086: knowledge, unless necessary; future versions of Gforth may introduce
7087: unusual compilation tokens (e.g., a compilation token that represents
7088: the compilation semantics of a literal).
7089:
1.71 anton 7090: You can perform the compilation semantics represented by the compilation
7091: token with @code{execute}. You can compile the compilation semantics
7092: with @code{postpone,}. I.e., @code{COMP' @i{word} postpone,} is
7093: equivalent to @code{postpone @i{word}}.
7094:
7095: doc-[comp']
7096: doc-comp'
7097: doc-postpone,
7098:
7099: @node Name token, , Compilation token, Tokens for Words
7100: @subsection Name token
1.47 crook 7101:
7102: @cindex name token
7103: @cindex name field address
7104: @cindex NFA
1.71 anton 7105: Gforth represents named words by the @dfn{name token}, (@i{nt}). In
1.47 crook 7106: Gforth, the abstract data type @emph{name token} is implemented as a
7107: name field address (NFA).
7108:
7109: doc-find-name
7110: doc-name>int
7111: doc-name?int
7112: doc-name>comp
7113: doc-name>string
7114:
7115:
1.26 crook 7116: @c ----------------------------------------------------------
1.47 crook 7117: @node The Text Interpreter, Word Lists, Tokens for Words, Words
1.26 crook 7118: @section The Text Interpreter
7119: @cindex interpreter - outer
7120: @cindex text interpreter
7121: @cindex outer interpreter
1.1 anton 7122:
1.34 anton 7123: @c Should we really describe all these ugly details? IMO the text
7124: @c interpreter should be much cleaner, but that may not be possible within
7125: @c ANS Forth. - anton
1.44 crook 7126: @c nac-> I wanted to explain how it works to show how you can exploit
7127: @c it in your own programs. When I was writing a cross-compiler, figuring out
7128: @c some of these gory details was very helpful to me. None of the textbooks
7129: @c I've seen cover it, and the most modern Forth textbook -- Forth Inc's,
7130: @c seems to positively avoid going into too much detail for some of
7131: @c the internals.
1.34 anton 7132:
1.71 anton 7133: @c anton: ok. I wonder, though, if this is the right place; for some stuff
7134: @c it is; for the ugly details, I would prefer another place. I wonder
7135: @c whether we should have a chapter before "Words" that describes some
7136: @c basic concepts referred to in words, and a chapter after "Words" that
7137: @c describes implementation details.
7138:
1.29 crook 7139: The text interpreter@footnote{This is an expanded version of the
7140: material in @ref{Introducing the Text Interpreter}.} is an endless loop
1.34 anton 7141: that processes input from the current input device. It is also called
7142: the outer interpreter, in contrast to the inner interpreter
7143: (@pxref{Engine}) which executes the compiled Forth code on interpretive
7144: implementations.
1.27 crook 7145:
1.29 crook 7146: @cindex interpret state
7147: @cindex compile state
7148: The text interpreter operates in one of two states: @dfn{interpret
7149: state} and @dfn{compile state}. The current state is defined by the
1.71 anton 7150: aptly-named variable @code{state}.
1.29 crook 7151:
7152: This section starts by describing how the text interpreter behaves when
7153: it is in interpret state, processing input from the user input device --
7154: the keyboard. This is the mode that a Forth system is in after it starts
7155: up.
7156:
7157: @cindex input buffer
7158: @cindex terminal input buffer
7159: The text interpreter works from an area of memory called the @dfn{input
7160: buffer}@footnote{When the text interpreter is processing input from the
7161: keyboard, this area of memory is called the @dfn{terminal input buffer}
7162: (TIB) and is addressed by the (obsolescent) words @code{TIB} and
7163: @code{#TIB}.}, which stores your keyboard input when you press the
1.30 anton 7164: @key{RET} key. Starting at the beginning of the input buffer, it skips
1.29 crook 7165: leading spaces (called @dfn{delimiters}) then parses a string (a
7166: sequence of non-space characters) until it reaches either a space
7167: character or the end of the buffer. Having parsed a string, it makes two
7168: attempts to process it:
1.27 crook 7169:
1.29 crook 7170: @cindex dictionary
1.27 crook 7171: @itemize @bullet
7172: @item
1.29 crook 7173: It looks for the string in a @dfn{dictionary} of definitions. If the
7174: string is found, the string names a @dfn{definition} (also known as a
7175: @dfn{word}) and the dictionary search returns information that allows
7176: the text interpreter to perform the word's @dfn{interpretation
7177: semantics}. In most cases, this simply means that the word will be
7178: executed.
1.27 crook 7179: @item
7180: If the string is not found in the dictionary, the text interpreter
1.29 crook 7181: attempts to treat it as a number, using the rules described in
7182: @ref{Number Conversion}. If the string represents a legal number in the
7183: current radix, the number is pushed onto a parameter stack (the data
7184: stack for integers, the floating-point stack for floating-point
7185: numbers).
7186: @end itemize
7187:
7188: If both attempts fail, or if the word is found in the dictionary but has
7189: no interpretation semantics@footnote{This happens if the word was
7190: defined as @code{COMPILE-ONLY}.} the text interpreter discards the
7191: remainder of the input buffer, issues an error message and waits for
7192: more input. If one of the attempts succeeds, the text interpreter
7193: repeats the parsing process until the whole of the input buffer has been
7194: processed, at which point it prints the status message ``@code{ ok}''
7195: and waits for more input.
7196:
1.71 anton 7197: @c anton: this should be in the input stream subsection (or below it)
7198:
1.29 crook 7199: @cindex parse area
7200: The text interpreter keeps track of its position in the input buffer by
7201: updating a variable called @code{>IN} (pronounced ``to-in''). The value
7202: of @code{>IN} starts out as 0, indicating an offset of 0 from the start
7203: of the input buffer. The region from offset @code{>IN @@} to the end of
7204: the input buffer is called the @dfn{parse area}@footnote{In other words,
7205: the text interpreter processes the contents of the input buffer by
7206: parsing strings from the parse area until the parse area is empty.}.
7207: This example shows how @code{>IN} changes as the text interpreter parses
7208: the input buffer:
7209:
7210: @example
7211: : remaining >IN @@ SOURCE 2 PICK - -ROT + SWAP
7212: CR ." ->" TYPE ." <-" ; IMMEDIATE
7213:
7214: 1 2 3 remaining + remaining .
7215:
7216: : foo 1 2 3 remaining SWAP remaining ;
7217: @end example
7218:
7219: @noindent
7220: The result is:
7221:
7222: @example
7223: ->+ remaining .<-
7224: ->.<-5 ok
7225:
7226: ->SWAP remaining ;-<
7227: ->;<- ok
7228: @end example
7229:
7230: @cindex parsing words
7231: The value of @code{>IN} can also be modified by a word in the input
7232: buffer that is executed by the text interpreter. This means that a word
7233: can ``trick'' the text interpreter into either skipping a section of the
7234: input buffer@footnote{This is how parsing words work.} or into parsing a
7235: section twice. For example:
1.27 crook 7236:
1.29 crook 7237: @example
1.71 anton 7238: : lat ." <<foo>>" ;
7239: : flat ." <<bar>>" >IN DUP @@ 3 - SWAP ! ;
1.29 crook 7240: @end example
7241:
7242: @noindent
7243: When @code{flat} is executed, this output is produced@footnote{Exercise
7244: for the reader: what would happen if the @code{3} were replaced with
7245: @code{4}?}:
7246:
7247: @example
1.71 anton 7248: <<bar>><<foo>>
1.29 crook 7249: @end example
7250:
1.71 anton 7251: This technique can be used to work around some of the interoperability
7252: problems of parsing words. Of course, it's better to avoid parsing
7253: words where possible.
7254:
1.29 crook 7255: @noindent
7256: Two important notes about the behaviour of the text interpreter:
1.27 crook 7257:
7258: @itemize @bullet
7259: @item
7260: It processes each input string to completion before parsing additional
1.29 crook 7261: characters from the input buffer.
7262: @item
7263: It treats the input buffer as a read-only region (and so must your code).
7264: @end itemize
7265:
7266: @noindent
7267: When the text interpreter is in compile state, its behaviour changes in
7268: these ways:
7269:
7270: @itemize @bullet
7271: @item
7272: If a parsed string is found in the dictionary, the text interpreter will
7273: perform the word's @dfn{compilation semantics}. In most cases, this
7274: simply means that the execution semantics of the word will be appended
7275: to the current definition.
1.27 crook 7276: @item
1.29 crook 7277: When a number is encountered, it is compiled into the current definition
7278: (as a literal) rather than being pushed onto a parameter stack.
7279: @item
7280: If an error occurs, @code{state} is modified to put the text interpreter
7281: back into interpret state.
7282: @item
7283: Each time a line is entered from the keyboard, Gforth prints
7284: ``@code{ compiled}'' rather than `` @code{ok}''.
7285: @end itemize
7286:
7287: @cindex text interpreter - input sources
7288: When the text interpreter is using an input device other than the
7289: keyboard, its behaviour changes in these ways:
7290:
7291: @itemize @bullet
7292: @item
7293: When the parse area is empty, the text interpreter attempts to refill
7294: the input buffer from the input source. When the input source is
1.71 anton 7295: exhausted, the input source is set back to the previous input source.
1.29 crook 7296: @item
7297: It doesn't print out ``@code{ ok}'' or ``@code{ compiled}'' messages each
7298: time the parse area is emptied.
7299: @item
7300: If an error occurs, the input source is set back to the user input
7301: device.
1.27 crook 7302: @end itemize
1.21 crook 7303:
1.49 anton 7304: You can read about this in more detail in @ref{Input Sources}.
1.44 crook 7305:
1.26 crook 7306: doc->in
1.27 crook 7307: doc-source
7308:
1.26 crook 7309: doc-tib
7310: doc-#tib
1.1 anton 7311:
1.44 crook 7312:
1.26 crook 7313: @menu
1.67 anton 7314: * Input Sources::
7315: * Number Conversion::
7316: * Interpret/Compile states::
7317: * Literals::
7318: * Interpreter Directives::
1.26 crook 7319: @end menu
1.1 anton 7320:
1.29 crook 7321: @node Input Sources, Number Conversion, The Text Interpreter, The Text Interpreter
7322: @subsection Input Sources
7323: @cindex input sources
7324: @cindex text interpreter - input sources
7325:
1.44 crook 7326: By default, the text interpreter processes input from the user input
1.29 crook 7327: device (the keyboard) when Forth starts up. The text interpreter can
7328: process input from any of these sources:
7329:
7330: @itemize @bullet
7331: @item
7332: The user input device -- the keyboard.
7333: @item
7334: A file, using the words described in @ref{Forth source files}.
7335: @item
7336: A block, using the words described in @ref{Blocks}.
7337: @item
7338: A text string, using @code{evaluate}.
7339: @end itemize
7340:
7341: A program can identify the current input device from the values of
7342: @code{source-id} and @code{blk}.
7343:
1.44 crook 7344:
1.29 crook 7345: doc-source-id
7346: doc-blk
7347:
7348: doc-save-input
7349: doc-restore-input
7350:
7351: doc-evaluate
1.1 anton 7352:
1.29 crook 7353:
1.44 crook 7354:
1.29 crook 7355: @node Number Conversion, Interpret/Compile states, Input Sources, The Text Interpreter
1.26 crook 7356: @subsection Number Conversion
7357: @cindex number conversion
7358: @cindex double-cell numbers, input format
7359: @cindex input format for double-cell numbers
7360: @cindex single-cell numbers, input format
7361: @cindex input format for single-cell numbers
7362: @cindex floating-point numbers, input format
7363: @cindex input format for floating-point numbers
1.1 anton 7364:
1.29 crook 7365: This section describes the rules that the text interpreter uses when it
7366: tries to convert a string into a number.
1.1 anton 7367:
1.26 crook 7368: Let <digit> represent any character that is a legal digit in the current
1.29 crook 7369: number base@footnote{For example, 0-9 when the number base is decimal or
7370: 0-9, A-F when the number base is hexadecimal.}.
1.1 anton 7371:
1.26 crook 7372: Let <decimal digit> represent any character in the range 0-9.
1.1 anton 7373:
1.29 crook 7374: Let @{@i{a b}@} represent the @i{optional} presence of any of the characters
7375: in the braces (@i{a} or @i{b} or neither).
1.1 anton 7376:
1.26 crook 7377: Let * represent any number of instances of the previous character
7378: (including none).
1.1 anton 7379:
1.26 crook 7380: Let any other character represent itself.
1.1 anton 7381:
1.29 crook 7382: @noindent
1.26 crook 7383: Now, the conversion rules are:
1.21 crook 7384:
1.26 crook 7385: @itemize @bullet
7386: @item
7387: A string of the form <digit><digit>* is treated as a single-precision
1.29 crook 7388: (cell-sized) positive integer. Examples are 0 123 6784532 32343212343456 42
1.26 crook 7389: @item
7390: A string of the form -<digit><digit>* is treated as a single-precision
1.29 crook 7391: (cell-sized) negative integer, and is represented using 2's-complement
1.26 crook 7392: arithmetic. Examples are -45 -5681 -0
7393: @item
7394: A string of the form <digit><digit>*.<digit>* is treated as a double-precision
1.29 crook 7395: (double-cell-sized) positive integer. Examples are 3465. 3.465 34.65
7396: (all three of these represent the same number).
1.26 crook 7397: @item
7398: A string of the form -<digit><digit>*.<digit>* is treated as a
1.29 crook 7399: double-precision (double-cell-sized) negative integer, and is
1.26 crook 7400: represented using 2's-complement arithmetic. Examples are -3465. -3.465
1.29 crook 7401: -34.65 (all three of these represent the same number).
1.26 crook 7402: @item
1.29 crook 7403: A string of the form @{+ -@}<decimal digit>@{.@}<decimal digit>*@{e
7404: E@}@{+ -@}<decimal digit><decimal digit>* is treated as a floating-point
1.35 anton 7405: number. Examples are 1e 1e0 1.e 1.e0 +1e+0 (which all represent the same
1.29 crook 7406: number) +12.E-4
1.26 crook 7407: @end itemize
1.1 anton 7408:
1.26 crook 7409: By default, the number base used for integer number conversion is given
1.35 anton 7410: by the contents of the variable @code{base}. Note that a lot of
7411: confusion can result from unexpected values of @code{base}. If you
7412: change @code{base} anywhere, make sure to save the old value and restore
7413: it afterwards. In general I recommend keeping @code{base} decimal, and
7414: using the prefixes described below for the popular non-decimal bases.
1.1 anton 7415:
1.29 crook 7416: doc-dpl
1.26 crook 7417: doc-base
7418: doc-hex
7419: doc-decimal
1.1 anton 7420:
1.44 crook 7421:
1.26 crook 7422: @cindex '-prefix for character strings
7423: @cindex &-prefix for decimal numbers
7424: @cindex %-prefix for binary numbers
7425: @cindex $-prefix for hexadecimal numbers
1.35 anton 7426: Gforth allows you to override the value of @code{base} by using a
1.29 crook 7427: prefix@footnote{Some Forth implementations provide a similar scheme by
7428: implementing @code{$} etc. as parsing words that process the subsequent
7429: number in the input stream and push it onto the stack. For example, see
7430: @cite{Number Conversion and Literals}, by Wil Baden; Forth Dimensions
7431: 20(3) pages 26--27. In such implementations, unlike in Gforth, a space
7432: is required between the prefix and the number.} before the first digit
7433: of an (integer) number. Four prefixes are supported:
1.1 anton 7434:
1.26 crook 7435: @itemize @bullet
7436: @item
1.35 anton 7437: @code{&} -- decimal
1.26 crook 7438: @item
1.35 anton 7439: @code{%} -- binary
1.26 crook 7440: @item
1.35 anton 7441: @code{$} -- hexadecimal
1.26 crook 7442: @item
1.35 anton 7443: @code{'} -- base @code{max-char+1}
1.26 crook 7444: @end itemize
1.1 anton 7445:
1.26 crook 7446: Here are some examples, with the equivalent decimal number shown after
7447: in braces:
1.1 anton 7448:
1.26 crook 7449: -$41 (-65), %1001101 (205), %1001.0001 (145 - a double-precision number),
7450: 'AB (16706; ascii A is 65, ascii B is 66, number is 65*256 + 66),
7451: 'ab (24930; ascii a is 97, ascii B is 98, number is 97*256 + 98),
7452: &905 (905), $abc (2478), $ABC (2478).
1.1 anton 7453:
1.26 crook 7454: @cindex number conversion - traps for the unwary
1.29 crook 7455: @noindent
1.26 crook 7456: Number conversion has a number of traps for the unwary:
1.1 anton 7457:
1.26 crook 7458: @itemize @bullet
7459: @item
7460: You cannot determine the current number base using the code sequence
1.35 anton 7461: @code{base @@ .} -- the number base is always 10 in the current number
7462: base. Instead, use something like @code{base @@ dec.}
1.26 crook 7463: @item
7464: If the number base is set to a value greater than 14 (for example,
7465: hexadecimal), the number 123E4 is ambiguous; the conversion rules allow
7466: it to be intepreted as either a single-precision integer or a
7467: floating-point number (Gforth treats it as an integer). The ambiguity
7468: can be resolved by explicitly stating the sign of the mantissa and/or
7469: exponent: 123E+4 or +123E4 -- if the number base is decimal, no
7470: ambiguity arises; either representation will be treated as a
7471: floating-point number.
7472: @item
1.29 crook 7473: There is a word @code{bin} but it does @i{not} set the number base!
1.26 crook 7474: It is used to specify file types.
7475: @item
1.72 anton 7476: ANS Forth requires the @code{.} of a double-precision number to be the
7477: final character in the string. Gforth allows the @code{.} to be
7478: anywhere after the first digit.
1.26 crook 7479: @item
7480: The number conversion process does not check for overflow.
7481: @item
1.72 anton 7482: In an ANS Forth program @code{base} is required to be decimal when
7483: converting floating-point numbers. In Gforth, number conversion to
7484: floating-point numbers always uses base &10, irrespective of the value
7485: of @code{base}.
1.26 crook 7486: @end itemize
1.1 anton 7487:
1.49 anton 7488: You can read numbers into your programs with the words described in
7489: @ref{Input}.
1.1 anton 7490:
1.26 crook 7491: @node Interpret/Compile states, Literals, Number Conversion, The Text Interpreter
7492: @subsection Interpret/Compile states
7493: @cindex Interpret/Compile states
1.1 anton 7494:
1.29 crook 7495: A standard program is not permitted to change @code{state}
7496: explicitly. However, it can change @code{state} implicitly, using the
7497: words @code{[} and @code{]}. When @code{[} is executed it switches
7498: @code{state} to interpret state, and therefore the text interpreter
7499: starts interpreting. When @code{]} is executed it switches @code{state}
7500: to compile state and therefore the text interpreter starts
1.44 crook 7501: compiling. The most common usage for these words is for switching into
7502: interpret state and back from within a colon definition; this technique
1.49 anton 7503: can be used to compile a literal (for an example, @pxref{Literals}) or
7504: for conditional compilation (for an example, @pxref{Interpreter
7505: Directives}).
1.44 crook 7506:
1.35 anton 7507:
7508: @c This is a bad example: It's non-standard, and it's not necessary.
7509: @c However, I can't think of a good example for switching into compile
7510: @c state when there is no current word (@code{state}-smart words are not a
7511: @c good reason). So maybe we should use an example for switching into
7512: @c interpret @code{state} in a colon def. - anton
1.44 crook 7513: @c nac-> I agree. I started out by putting in the example, then realised
7514: @c that it was non-ANS, so wrote more words around it. I hope this
7515: @c re-written version is acceptable to you. I do want to keep the example
7516: @c as it is helpful for showing what is and what is not portable, particularly
7517: @c where it outlaws a style in common use.
7518:
1.72 anton 7519: @c anton: it's more important to show what's portable. After we have done
7520: @c that, we can also show what's not. In any case, I intend to write a
7521: @c section Macros (or so) which will also deal with [ ].
1.35 anton 7522:
1.44 crook 7523: @code{[} and @code{]} also give you the ability to switch into compile
7524: state and back, but we cannot think of any useful Standard application
7525: for this ability. Pre-ANS Forth textbooks have examples like this:
1.29 crook 7526:
7527: @example
7528: : AA ." this is A" ;
7529: : BB ." this is B" ;
7530: : CC ." this is C" ;
7531:
1.44 crook 7532: create table ] aa bb cc [
7533:
1.29 crook 7534: : go ( n -- ) \ n is offset into table.. 0 for 1st entry
7535: cells table + @ execute ;
7536: @end example
7537:
1.44 crook 7538: This example builds a jump table; @code{0 go} will display ``@code{this
7539: is A}''. Using @code{[} and @code{]} in this example is equivalent to
7540: defining @code{table} like this:
1.29 crook 7541:
7542: @example
1.44 crook 7543: create table ' aa COMPILE, ' bb COMPILE, ' cc COMPILE,
1.29 crook 7544: @end example
7545:
1.44 crook 7546: The problem with this code is that the definition of @code{table} is not
7547: portable -- it @i{compile}s execution tokens into code space. Whilst it
7548: @i{may} work on systems where code space and data space co-incide, the
1.29 crook 7549: Standard only allows data space to be assigned for a @code{CREATE}d
7550: word. In addition, the Standard only allows @code{@@} to access data
7551: space, whilst this example is using it to access code space. The only
7552: portable, Standard way to build this table is to build it in data space,
7553: like this:
7554:
7555: @example
7556: create table ' aa , ' bb , ' cc ,
7557: @end example
7558:
1.26 crook 7559: doc-state
7560: doc-[
7561: doc-]
1.1 anton 7562:
1.44 crook 7563:
1.26 crook 7564: @node Literals, Interpreter Directives, Interpret/Compile states, The Text Interpreter
7565: @subsection Literals
7566: @cindex Literals
1.21 crook 7567:
1.29 crook 7568: Often, you want to use a number within a colon definition. When you do
7569: this, the text interpreter automatically compiles the number as a
7570: @i{literal}. A literal is a number whose run-time effect is to be pushed
7571: onto the stack. If you had to do some maths to generate the number, you
7572: might write it like this:
7573:
7574: @example
7575: : HOUR-TO-SEC ( n1 -- n2 )
7576: 60 * \ to minutes
7577: 60 * ; \ to seconds
7578: @end example
7579:
7580: It is very clear what this definition is doing, but it's inefficient
7581: since it is performing 2 multiples at run-time. An alternative would be
7582: to write:
7583:
7584: @example
7585: : HOUR-TO-SEC ( n1 -- n2 )
7586: 3600 * ; \ to seconds
7587: @end example
7588:
7589: Which does the same thing, and has the advantage of using a single
7590: multiply. Ideally, we'd like the efficiency of the second with the
7591: readability of the first.
7592:
7593: @code{Literal} allows us to achieve that. It takes a number from the
7594: stack and lays it down in the current definition just as though the
7595: number had been typed directly into the definition. Our first attempt
7596: might look like this:
7597:
7598: @example
7599: 60 \ mins per hour
7600: 60 * \ seconds per minute
7601: : HOUR-TO-SEC ( n1 -- n2 )
7602: Literal * ; \ to seconds
7603: @end example
7604:
7605: But this produces the error message @code{unstructured}. What happened?
7606: The stack notation for @code{:} is (@i{ -- colon-sys}) and the size of
7607: @i{colon-sys} is implementation-defined. In other words, once we start a
7608: colon definition we can't portably access anything that was on the stack
7609: before the definition began@footnote{@cite{Two Problems in ANS Forth},
7610: by Thomas Worthington; Forth Dimensions 20(2) pages 32--34 describes
7611: some situations where you might want to access stack items above
7612: colon-sys, and provides a solution to the problem.}. The correct way of
7613: solving this problem in this instance is to use @code{[ ]} like this:
7614:
7615: @example
7616: : HOUR-TO-SEC ( n1 -- n2 )
7617: [ 60 \ minutes per hour
7618: 60 * ] \ seconds per minute
7619: LITERAL * ; \ to seconds
7620: @end example
1.23 crook 7621:
1.44 crook 7622:
1.26 crook 7623: doc-literal
7624: doc-]L
7625: doc-2literal
7626: doc-fliteral
1.1 anton 7627:
1.44 crook 7628:
1.48 anton 7629: @node Interpreter Directives, , Literals, The Text Interpreter
1.26 crook 7630: @subsection Interpreter Directives
7631: @cindex interpreter directives
1.72 anton 7632: @cindex conditional compilation
1.1 anton 7633:
1.29 crook 7634: These words are usually used in interpret state; typically to control
7635: which parts of a source file are processed by the text
1.26 crook 7636: interpreter. There are only a few ANS Forth Standard words, but Gforth
7637: supplements these with a rich set of immediate control structure words
7638: to compensate for the fact that the non-immediate versions can only be
1.29 crook 7639: used in compile state (@pxref{Control Structures}). Typical usages:
7640:
7641: @example
1.72 anton 7642: FALSE Constant HAVE-ASSEMBLER
1.29 crook 7643: .
7644: .
1.72 anton 7645: HAVE-ASSEMBLER [IF]
1.29 crook 7646: : ASSEMBLER-FEATURE
7647: ...
7648: ;
7649: [ENDIF]
7650: .
7651: .
7652: : SEE
7653: ... \ general-purpose SEE code
1.72 anton 7654: [ HAVE-ASSEMBLER [IF] ]
1.29 crook 7655: ... \ assembler-specific SEE code
7656: [ [ENDIF] ]
7657: ;
7658: @end example
1.1 anton 7659:
1.44 crook 7660:
1.26 crook 7661: doc-[IF]
7662: doc-[ELSE]
7663: doc-[THEN]
7664: doc-[ENDIF]
1.1 anton 7665:
1.26 crook 7666: doc-[IFDEF]
7667: doc-[IFUNDEF]
1.1 anton 7668:
1.26 crook 7669: doc-[?DO]
7670: doc-[DO]
7671: doc-[FOR]
7672: doc-[LOOP]
7673: doc-[+LOOP]
7674: doc-[NEXT]
1.1 anton 7675:
1.26 crook 7676: doc-[BEGIN]
7677: doc-[UNTIL]
7678: doc-[AGAIN]
7679: doc-[WHILE]
7680: doc-[REPEAT]
1.1 anton 7681:
1.27 crook 7682:
1.26 crook 7683: @c -------------------------------------------------------------
1.47 crook 7684: @node Word Lists, Environmental Queries, The Text Interpreter, Words
1.26 crook 7685: @section Word Lists
7686: @cindex word lists
1.32 anton 7687: @cindex header space
1.1 anton 7688:
1.36 anton 7689: A wordlist is a list of named words; you can add new words and look up
7690: words by name (and you can remove words in a restricted way with
7691: markers). Every named (and @code{reveal}ed) word is in one wordlist.
7692:
7693: @cindex search order stack
7694: The text interpreter searches the wordlists present in the search order
7695: (a stack of wordlists), from the top to the bottom. Within each
7696: wordlist, the search starts conceptually at the newest word; i.e., if
7697: two words in a wordlist have the same name, the newer word is found.
1.1 anton 7698:
1.26 crook 7699: @cindex compilation word list
1.36 anton 7700: New words are added to the @dfn{compilation wordlist} (aka current
7701: wordlist).
1.1 anton 7702:
1.36 anton 7703: @cindex wid
7704: A word list is identified by a cell-sized word list identifier (@i{wid})
7705: in much the same way as a file is identified by a file handle. The
7706: numerical value of the wid has no (portable) meaning, and might change
7707: from session to session.
1.1 anton 7708:
1.29 crook 7709: The ANS Forth ``Search order'' word set is intended to provide a set of
7710: low-level tools that allow various different schemes to be
1.74 anton 7711: implemented. Gforth also provides @code{vocabulary}, a traditional Forth
1.26 crook 7712: word. @file{compat/vocabulary.fs} provides an implementation in ANS
1.45 crook 7713: Forth.
1.1 anton 7714:
1.27 crook 7715: @comment TODO: locals section refers to here, saying that every word list (aka
7716: @comment vocabulary) has its own methods for searching etc. Need to document that.
1.1 anton 7717:
1.45 crook 7718: @comment TODO: document markers, reveal, tables, mappedwordlist
7719:
7720: @comment the gforthman- prefix is used to pick out the true definition of a
1.27 crook 7721: @comment word from the source files, rather than some alias.
1.44 crook 7722:
1.26 crook 7723: doc-forth-wordlist
7724: doc-definitions
7725: doc-get-current
7726: doc-set-current
7727: doc-get-order
1.45 crook 7728: doc---gforthman-set-order
1.26 crook 7729: doc-wordlist
1.30 anton 7730: doc-table
1.36 anton 7731: doc-push-order
7732: doc-previous
1.26 crook 7733: doc-also
1.45 crook 7734: doc---gforthman-forth
1.26 crook 7735: doc-only
1.45 crook 7736: doc---gforthman-order
1.15 anton 7737:
1.26 crook 7738: doc-find
7739: doc-search-wordlist
1.15 anton 7740:
1.26 crook 7741: doc-words
7742: doc-vlist
1.44 crook 7743: @c doc-words-deferred
1.1 anton 7744:
1.74 anton 7745: @c doc-mappedwordlist @c map-structure undefined, implemantation-specific
1.26 crook 7746: doc-root
7747: doc-vocabulary
7748: doc-seal
7749: doc-vocs
7750: doc-current
7751: doc-context
1.1 anton 7752:
1.44 crook 7753:
1.26 crook 7754: @menu
1.75 anton 7755: * Vocabularies::
1.67 anton 7756: * Why use word lists?::
1.75 anton 7757: * Word list example::
1.26 crook 7758: @end menu
7759:
1.75 anton 7760: @node Vocabularies, Why use word lists?, Word Lists, Word Lists
7761: @subsection Vocabularies
7762: @cindex Vocabularies, detailed explanation
7763:
7764: Here is an example of creating and using a new wordlist using ANS
7765: Forth words:
7766:
7767: @example
7768: wordlist constant my-new-words-wordlist
7769: : my-new-words get-order nip my-new-words-wordlist swap set-order ;
7770:
7771: \ add it to the search order
7772: also my-new-words
7773:
7774: \ alternatively, add it to the search order and make it
7775: \ the compilation word list
7776: also my-new-words definitions
7777: \ type "order" to see the problem
7778: @end example
7779:
7780: The problem with this example is that @code{order} has no way to
7781: associate the name @code{my-new-words} with the wid of the word list (in
7782: Gforth, @code{order} and @code{vocs} will display @code{???} for a wid
7783: that has no associated name). There is no Standard way of associating a
7784: name with a wid.
7785:
7786: In Gforth, this example can be re-coded using @code{vocabulary}, which
7787: associates a name with a wid:
7788:
7789: @example
7790: vocabulary my-new-words
7791:
7792: \ add it to the search order
7793: also my-new-words
7794:
7795: \ alternatively, add it to the search order and make it
7796: \ the compilation word list
7797: my-new-words definitions
7798: \ type "order" to see that the problem is solved
7799: @end example
7800:
7801:
7802: @node Why use word lists?, Word list example, Vocabularies, Word Lists
1.26 crook 7803: @subsection Why use word lists?
7804: @cindex word lists - why use them?
7805:
1.74 anton 7806: Here are some reasons why people use wordlists:
1.26 crook 7807:
7808: @itemize @bullet
1.74 anton 7809:
7810: @c anton: Gforth's hashing implementation makes the search speed
7811: @c independent from the number of words. But it is linear with the number
7812: @c of wordlists that have to be searched, so in effect using more wordlists
7813: @c actually slows down compilation.
7814:
7815: @c @item
7816: @c To improve compilation speed by reducing the number of header space
7817: @c entries that must be searched. This is achieved by creating a new
7818: @c word list that contains all of the definitions that are used in the
7819: @c definition of a Forth system but which would not usually be used by
7820: @c programs running on that system. That word list would be on the search
7821: @c list when the Forth system was compiled but would be removed from the
7822: @c search list for normal operation. This can be a useful technique for
7823: @c low-performance systems (for example, 8-bit processors in embedded
7824: @c systems) but is unlikely to be necessary in high-performance desktop
7825: @c systems.
7826:
1.26 crook 7827: @item
7828: To prevent a set of words from being used outside the context in which
7829: they are valid. Two classic examples of this are an integrated editor
7830: (all of the edit commands are defined in a separate word list; the
7831: search order is set to the editor word list when the editor is invoked;
7832: the old search order is restored when the editor is terminated) and an
7833: integrated assembler (the op-codes for the machine are defined in a
7834: separate word list which is used when a @code{CODE} word is defined).
1.74 anton 7835:
7836: @item
7837: To organize the words of an application or library into a user-visible
7838: set (in @code{forth-wordlist} or some other common wordlist) and a set
7839: of helper words used just for the implementation (hidden in a separate
1.75 anton 7840: wordlist). This keeps @code{words}' output smaller, separates
7841: implementation and interface, and reduces the chance of name conflicts
7842: within the common wordlist.
1.74 anton 7843:
1.26 crook 7844: @item
7845: To prevent a name-space clash between multiple definitions with the same
7846: name. For example, when building a cross-compiler you might have a word
7847: @code{IF} that generates conditional code for your target system. By
7848: placing this definition in a different word list you can control whether
7849: the host system's @code{IF} or the target system's @code{IF} get used in
7850: any particular context by controlling the order of the word lists on the
7851: search order stack.
1.74 anton 7852:
1.26 crook 7853: @end itemize
1.1 anton 7854:
1.74 anton 7855: The downsides of using wordlists are:
7856:
7857: @itemize
7858:
7859: @item
7860: Debugging becomes more cumbersome.
7861:
7862: @item
7863: Name conflicts worked around with wordlists are still there, and you
7864: have to arrange the search order carefully to get the desired results;
7865: if you forget to do that, you get hard-to-find errors (as in any case
7866: where you read the code differently from the compiler; @code{see} can
1.75 anton 7867: help seeing which of several possible words the name resolves to in such
7868: cases). @code{See} displays just the name of the words, not what
7869: wordlist they belong to, so it might be misleading. Using unique names
7870: is a better approach to avoid name conflicts.
1.74 anton 7871:
7872: @item
7873: You have to explicitly undo any changes to the search order. In many
7874: cases it would be more convenient if this happened implicitly. Gforth
7875: currently does not provide such a feature, but it may do so in the
7876: future.
7877: @end itemize
7878:
7879:
1.75 anton 7880: @node Word list example, , Why use word lists?, Word Lists
7881: @subsection Word list example
7882: @cindex word lists - example
1.1 anton 7883:
1.74 anton 7884: The following example is from the
7885: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
7886: garbage collector} and uses wordlists to separate public words from
7887: helper words:
7888:
7889: @example
7890: get-current ( wid )
7891: vocabulary garbage-collector also garbage-collector definitions
7892: ... \ define helper words
7893: ( wid ) set-current \ restore original (i.e., public) compilation wordlist
7894: ... \ define the public (i.e., API) words
7895: \ they can refer to the helper words
7896: previous \ restore original search order (helper words become invisible)
7897: @end example
7898:
1.26 crook 7899: @c -------------------------------------------------------------
7900: @node Environmental Queries, Files, Word Lists, Words
7901: @section Environmental Queries
7902: @cindex environmental queries
1.21 crook 7903:
1.26 crook 7904: ANS Forth introduced the idea of ``environmental queries'' as a way
7905: for a program running on a system to determine certain characteristics of the system.
7906: The Standard specifies a number of strings that might be recognised by a system.
1.21 crook 7907:
1.32 anton 7908: The Standard requires that the header space used for environmental queries
7909: be distinct from the header space used for definitions.
1.21 crook 7910:
1.26 crook 7911: Typically, environmental queries are supported by creating a set of
1.29 crook 7912: definitions in a word list that is @i{only} used during environmental
1.26 crook 7913: queries; that is what Gforth does. There is no Standard way of adding
7914: definitions to the set of recognised environmental queries, but any
7915: implementation that supports the loading of optional word sets must have
7916: some mechanism for doing this (after loading the word set, the
7917: associated environmental query string must return @code{true}). In
7918: Gforth, the word list used to honour environmental queries can be
7919: manipulated just like any other word list.
1.21 crook 7920:
1.44 crook 7921:
1.26 crook 7922: doc-environment?
7923: doc-environment-wordlist
1.21 crook 7924:
1.26 crook 7925: doc-gforth
7926: doc-os-class
1.21 crook 7927:
1.44 crook 7928:
1.26 crook 7929: Note that, whilst the documentation for (e.g.) @code{gforth} shows it
7930: returning two items on the stack, querying it using @code{environment?}
7931: will return an additional item; the @code{true} flag that shows that the
7932: string was recognised.
1.21 crook 7933:
1.26 crook 7934: @comment TODO Document the standard strings or note where they are documented herein
1.21 crook 7935:
1.26 crook 7936: Here are some examples of using environmental queries:
1.21 crook 7937:
1.26 crook 7938: @example
7939: s" address-unit-bits" environment? 0=
7940: [IF]
7941: cr .( environmental attribute address-units-bits unknown... ) cr
1.75 anton 7942: [ELSE]
7943: drop \ ensure balanced stack effect
1.26 crook 7944: [THEN]
1.21 crook 7945:
1.75 anton 7946: \ this might occur in the prelude of a standard program that uses THROW
7947: s" exception" environment? [IF]
7948: 0= [IF]
7949: : throw abort" exception thrown" ;
7950: [THEN]
7951: [ELSE] \ we don't know, so make sure
7952: : throw abort" exception thrown" ;
7953: [THEN]
1.21 crook 7954:
1.26 crook 7955: s" gforth" environment? [IF] .( Gforth version ) TYPE
7956: [ELSE] .( Not Gforth..) [THEN]
1.75 anton 7957:
7958: \ a program using v*
7959: s" gforth" environment? [IF]
7960: s" 0.5.0" compare 0< [IF] \ v* is a primitive since 0.5.0
7961: : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
7962: >r swap 2swap swap 0e r> 0 ?DO
7963: dup f@ over + 2swap dup f@ f* f+ over + 2swap
7964: LOOP
7965: 2drop 2drop ;
7966: [THEN]
7967: [ELSE] \
7968: : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
7969: ...
7970: [THEN]
1.26 crook 7971: @end example
1.21 crook 7972:
1.26 crook 7973: Here is an example of adding a definition to the environment word list:
1.21 crook 7974:
1.26 crook 7975: @example
7976: get-current environment-wordlist set-current
7977: true constant block
7978: true constant block-ext
7979: set-current
7980: @end example
1.21 crook 7981:
1.26 crook 7982: You can see what definitions are in the environment word list like this:
1.21 crook 7983:
1.26 crook 7984: @example
1.75 anton 7985: environment-wordlist push-order words previous
1.26 crook 7986: @end example
1.21 crook 7987:
7988:
1.26 crook 7989: @c -------------------------------------------------------------
7990: @node Files, Blocks, Environmental Queries, Words
7991: @section Files
1.28 crook 7992: @cindex files
7993: @cindex I/O - file-handling
1.21 crook 7994:
1.26 crook 7995: Gforth provides facilities for accessing files that are stored in the
7996: host operating system's file-system. Files that are processed by Gforth
7997: can be divided into two categories:
1.21 crook 7998:
1.23 crook 7999: @itemize @bullet
8000: @item
1.29 crook 8001: Files that are processed by the Text Interpreter (@dfn{Forth source files}).
1.23 crook 8002: @item
1.29 crook 8003: Files that are processed by some other program (@dfn{general files}).
1.26 crook 8004: @end itemize
8005:
8006: @menu
1.48 anton 8007: * Forth source files::
8008: * General files::
8009: * Search Paths::
1.26 crook 8010: @end menu
8011:
8012: @c -------------------------------------------------------------
8013: @node Forth source files, General files, Files, Files
8014: @subsection Forth source files
8015: @cindex including files
8016: @cindex Forth source files
1.21 crook 8017:
1.26 crook 8018: The simplest way to interpret the contents of a file is to use one of
8019: these two formats:
1.21 crook 8020:
1.26 crook 8021: @example
8022: include mysource.fs
8023: s" mysource.fs" included
8024: @end example
1.21 crook 8025:
1.75 anton 8026: You usually want to include a file only if it is not included already
1.26 crook 8027: (by, say, another source file). In that case, you can use one of these
1.45 crook 8028: three formats:
1.21 crook 8029:
1.26 crook 8030: @example
8031: require mysource.fs
8032: needs mysource.fs
8033: s" mysource.fs" required
8034: @end example
1.21 crook 8035:
1.26 crook 8036: @cindex stack effect of included files
8037: @cindex including files, stack effect
1.45 crook 8038: It is good practice to write your source files such that interpreting them
8039: does not change the stack. Source files designed in this way can be used with
1.26 crook 8040: @code{required} and friends without complications. For example:
1.21 crook 8041:
1.26 crook 8042: @example
1.75 anton 8043: 1024 require foo.fs drop
1.26 crook 8044: @end example
1.21 crook 8045:
1.75 anton 8046: Here you want to pass the argument 1024 (e.g., a buffer size) to
8047: @file{foo.fs}. Interpreting @file{foo.fs} has the stack effect ( n -- n
8048: ), which allows its use with @code{require}. Of course with such
8049: parameters to required files, you have to ensure that the first
8050: @code{require} fits for all uses (i.e., @code{require} it early in the
8051: master load file).
1.44 crook 8052:
1.26 crook 8053: doc-include-file
8054: doc-included
1.28 crook 8055: doc-included?
1.26 crook 8056: doc-include
8057: doc-required
8058: doc-require
8059: doc-needs
1.75 anton 8060: @c doc-init-included-files @c internal
8061: @c doc-loadfilename @c internal word
8062: doc-sourcefilename
8063: doc-sourceline#
1.44 crook 8064:
1.26 crook 8065: A definition in ANS Forth for @code{required} is provided in
8066: @file{compat/required.fs}.
1.21 crook 8067:
1.26 crook 8068: @c -------------------------------------------------------------
8069: @node General files, Search Paths, Forth source files, Files
8070: @subsection General files
8071: @cindex general files
8072: @cindex file-handling
1.21 crook 8073:
1.75 anton 8074: Files are opened/created by name and type. The following file access
8075: methods (FAMs) are recognised:
1.44 crook 8076:
1.75 anton 8077: @cindex fam (file access method)
1.26 crook 8078: doc-r/o
8079: doc-r/w
8080: doc-w/o
8081: doc-bin
1.1 anton 8082:
1.44 crook 8083:
1.26 crook 8084: When a file is opened/created, it returns a file identifier,
1.29 crook 8085: @i{wfileid} that is used for all other file commands. All file
8086: commands also return a status value, @i{wior}, that is 0 for a
1.26 crook 8087: successful operation and an implementation-defined non-zero value in the
8088: case of an error.
1.21 crook 8089:
1.44 crook 8090:
1.26 crook 8091: doc-open-file
8092: doc-create-file
1.21 crook 8093:
1.26 crook 8094: doc-close-file
8095: doc-delete-file
8096: doc-rename-file
8097: doc-read-file
8098: doc-read-line
8099: doc-write-file
8100: doc-write-line
8101: doc-emit-file
8102: doc-flush-file
1.21 crook 8103:
1.26 crook 8104: doc-file-status
8105: doc-file-position
8106: doc-reposition-file
8107: doc-file-size
8108: doc-resize-file
1.21 crook 8109:
1.44 crook 8110:
1.26 crook 8111: @c ---------------------------------------------------------
1.48 anton 8112: @node Search Paths, , General files, Files
1.26 crook 8113: @subsection Search Paths
8114: @cindex path for @code{included}
8115: @cindex file search path
8116: @cindex @code{include} search path
8117: @cindex search path for files
1.21 crook 8118:
1.26 crook 8119: If you specify an absolute filename (i.e., a filename starting with
8120: @file{/} or @file{~}, or with @file{:} in the second position (as in
8121: @samp{C:...})) for @code{included} and friends, that file is included
8122: just as you would expect.
1.21 crook 8123:
1.75 anton 8124: If the filename starts with @file{./}, this refers to the directory that
8125: the present file was @code{included} from. This allows files to include
8126: other files relative to their own position (irrespective of the current
8127: working directory or the absolute position). This feature is essential
8128: for libraries consisting of several files, where a file may include
8129: other files from the library. It corresponds to @code{#include "..."}
8130: in C. If the current input source is not a file, @file{.} refers to the
8131: directory of the innermost file being included, or, if there is no file
8132: being included, to the current working directory.
8133:
8134: For relative filenames (not starting with @file{./}), Gforth uses a
8135: search path similar to Forth's search order (@pxref{Word Lists}). It
8136: tries to find the given filename in the directories present in the path,
8137: and includes the first one it finds. There are separate search paths for
8138: Forth source files and general files. If the search path contains the
8139: directory @file{.}, this refers to the directory of the current file, or
8140: the working directory, as if the file had been specified with @file{./}.
1.21 crook 8141:
1.26 crook 8142: Use @file{~+} to refer to the current working directory (as in the
8143: @code{bash}).
1.1 anton 8144:
1.75 anton 8145: @c anton: fold the following subsubsections into this subsection?
1.1 anton 8146:
1.48 anton 8147: @menu
1.75 anton 8148: * Source Search Paths::
1.48 anton 8149: * General Search Paths::
8150: @end menu
8151:
1.26 crook 8152: @c ---------------------------------------------------------
1.75 anton 8153: @node Source Search Paths, General Search Paths, Search Paths, Search Paths
8154: @subsubsection Source Search Paths
8155: @cindex search path control, source files
1.5 anton 8156:
1.26 crook 8157: The search path is initialized when you start Gforth (@pxref{Invoking
1.75 anton 8158: Gforth}). You can display it and change it using @code{fpath} in
8159: combination with the general path handling words.
1.5 anton 8160:
1.75 anton 8161: doc-fpath
8162: @c the functionality of the following words is easily available through
8163: @c fpath and the general path words. The may go away.
8164: @c doc-.fpath
8165: @c doc-fpath+
8166: @c doc-fpath=
8167: @c doc-open-fpath-file
1.44 crook 8168:
8169: @noindent
1.26 crook 8170: Here is an example of using @code{fpath} and @code{require}:
1.5 anton 8171:
1.26 crook 8172: @example
1.75 anton 8173: fpath path= /usr/lib/forth/|./
1.26 crook 8174: require timer.fs
8175: @end example
1.5 anton 8176:
1.75 anton 8177:
1.26 crook 8178: @c ---------------------------------------------------------
1.75 anton 8179: @node General Search Paths, , Source Search Paths, Search Paths
1.26 crook 8180: @subsubsection General Search Paths
1.75 anton 8181: @cindex search path control, source files
1.5 anton 8182:
1.26 crook 8183: Your application may need to search files in several directories, like
8184: @code{included} does. To facilitate this, Gforth allows you to define
8185: and use your own search paths, by providing generic equivalents of the
8186: Forth search path words:
1.5 anton 8187:
1.75 anton 8188: doc-open-path-file
8189: doc-path-allot
8190: doc-clear-path
8191: doc-also-path
1.26 crook 8192: doc-.path
8193: doc-path+
8194: doc-path=
1.5 anton 8195:
1.75 anton 8196: @c anton: better define a word for it, say "path-allot ( ucount -- path-addr )
1.44 crook 8197:
1.75 anton 8198: Here's an example of creating an empty search path:
8199: @c
1.26 crook 8200: @example
1.75 anton 8201: create mypath 500 path-allot \ maximum length 500 chars (is checked)
1.26 crook 8202: @end example
1.5 anton 8203:
1.26 crook 8204: @c -------------------------------------------------------------
8205: @node Blocks, Other I/O, Files, Words
8206: @section Blocks
1.28 crook 8207: @cindex I/O - blocks
8208: @cindex blocks
8209:
8210: When you run Gforth on a modern desk-top computer, it runs under the
8211: control of an operating system which provides certain services. One of
8212: these services is @var{file services}, which allows Forth source code
8213: and data to be stored in files and read into Gforth (@pxref{Files}).
8214:
8215: Traditionally, Forth has been an important programming language on
8216: systems where it has interfaced directly to the underlying hardware with
8217: no intervening operating system. Forth provides a mechanism, called
1.29 crook 8218: @dfn{blocks}, for accessing mass storage on such systems.
1.28 crook 8219:
8220: A block is a 1024-byte data area, which can be used to hold data or
8221: Forth source code. No structure is imposed on the contents of the
8222: block. A block is identified by its number; blocks are numbered
8223: contiguously from 1 to an implementation-defined maximum.
8224:
8225: A typical system that used blocks but no operating system might use a
8226: single floppy-disk drive for mass storage, with the disks formatted to
8227: provide 256-byte sectors. Blocks would be implemented by assigning the
8228: first four sectors of the disk to block 1, the second four sectors to
8229: block 2 and so on, up to the limit of the capacity of the disk. The disk
8230: would not contain any file system information, just the set of blocks.
8231:
1.29 crook 8232: @cindex blocks file
1.28 crook 8233: On systems that do provide file services, blocks are typically
1.29 crook 8234: implemented by storing a sequence of blocks within a single @dfn{blocks
1.28 crook 8235: file}. The size of the blocks file will be an exact multiple of 1024
8236: bytes, corresponding to the number of blocks it contains. This is the
8237: mechanism that Gforth uses.
8238:
1.29 crook 8239: @cindex @file{blocks.fb}
1.75 anton 8240: Only one blocks file can be open at a time. If you use block words without
1.28 crook 8241: having specified a blocks file, Gforth defaults to the blocks file
8242: @file{blocks.fb}. Gforth uses the Forth search path when attempting to
1.75 anton 8243: locate a blocks file (@pxref{Source Search Paths}).
1.28 crook 8244:
1.29 crook 8245: @cindex block buffers
1.28 crook 8246: When you read and write blocks under program control, Gforth uses a
1.29 crook 8247: number of @dfn{block buffers} as intermediate storage. These buffers are
1.28 crook 8248: not used when you use @code{load} to interpret the contents of a block.
8249:
1.75 anton 8250: The behaviour of the block buffers is analagous to that of a cache.
8251: Each block buffer has three states:
1.28 crook 8252:
8253: @itemize @bullet
8254: @item
8255: Unassigned
8256: @item
8257: Assigned-clean
8258: @item
8259: Assigned-dirty
8260: @end itemize
8261:
1.29 crook 8262: Initially, all block buffers are @i{unassigned}. In order to access a
1.28 crook 8263: block, the block (specified by its block number) must be assigned to a
8264: block buffer.
8265:
8266: The assignment of a block to a block buffer is performed by @code{block}
8267: or @code{buffer}. Use @code{block} when you wish to modify the existing
8268: contents of a block. Use @code{buffer} when you don't care about the
8269: existing contents of the block@footnote{The ANS Forth definition of
1.35 anton 8270: @code{buffer} is intended not to cause disk I/O; if the data associated
1.28 crook 8271: with the particular block is already stored in a block buffer due to an
8272: earlier @code{block} command, @code{buffer} will return that block
8273: buffer and the existing contents of the block will be
8274: available. Otherwise, @code{buffer} will simply assign a new, empty
1.29 crook 8275: block buffer for the block.}.
1.28 crook 8276:
1.47 crook 8277: Once a block has been assigned to a block buffer using @code{block} or
1.75 anton 8278: @code{buffer}, that block buffer becomes the @i{current block
8279: buffer}. Data may only be manipulated (read or written) within the
8280: current block buffer.
1.47 crook 8281:
8282: When the contents of the current block buffer has been modified it is
1.48 anton 8283: necessary, @emph{before calling @code{block} or @code{buffer} again}, to
1.75 anton 8284: either abandon the changes (by doing nothing) or mark the block as
8285: changed (assigned-dirty), using @code{update}. Using @code{update} does
8286: not change the blocks file; it simply changes a block buffer's state to
8287: @i{assigned-dirty}. The block will be written implicitly when it's
8288: buffer is needed for another block, or explicitly by @code{flush} or
8289: @code{save-buffers}.
8290:
8291: word @code{Flush} writes all @i{assigned-dirty} blocks back to the
8292: blocks file on disk. Leaving Gforth with @code{bye} also performs a
8293: @code{flush}.
1.28 crook 8294:
1.29 crook 8295: In Gforth, @code{block} and @code{buffer} use a @i{direct-mapped}
1.28 crook 8296: algorithm to assign a block buffer to a block. That means that any
8297: particular block can only be assigned to one specific block buffer,
1.29 crook 8298: called (for the particular operation) the @i{victim buffer}. If the
1.47 crook 8299: victim buffer is @i{unassigned} or @i{assigned-clean} it is allocated to
8300: the new block immediately. If it is @i{assigned-dirty} its current
8301: contents are written back to the blocks file on disk before it is
1.28 crook 8302: allocated to the new block.
8303:
8304: Although no structure is imposed on the contents of a block, it is
8305: traditional to display the contents as 16 lines each of 64 characters. A
8306: block provides a single, continuous stream of input (for example, it
8307: acts as a single parse area) -- there are no end-of-line characters
8308: within a block, and no end-of-file character at the end of a
8309: block. There are two consequences of this:
1.26 crook 8310:
1.28 crook 8311: @itemize @bullet
8312: @item
8313: The last character of one line wraps straight into the first character
8314: of the following line
8315: @item
8316: The word @code{\} -- comment to end of line -- requires special
8317: treatment; in the context of a block it causes all characters until the
8318: end of the current 64-character ``line'' to be ignored.
8319: @end itemize
8320:
8321: In Gforth, when you use @code{block} with a non-existent block number,
1.45 crook 8322: the current blocks file will be extended to the appropriate size and the
1.28 crook 8323: block buffer will be initialised with spaces.
8324:
1.47 crook 8325: Gforth includes a simple block editor (type @code{use blocked.fb 0 list}
8326: for details) but doesn't encourage the use of blocks; the mechanism is
8327: only provided for backward compatibility -- ANS Forth requires blocks to
8328: be available when files are.
1.28 crook 8329:
8330: Common techniques that are used when working with blocks include:
8331:
8332: @itemize @bullet
8333: @item
8334: A screen editor that allows you to edit blocks without leaving the Forth
8335: environment.
8336: @item
8337: Shadow screens; where every code block has an associated block
8338: containing comments (for example: code in odd block numbers, comments in
8339: even block numbers). Typically, the block editor provides a convenient
8340: mechanism to toggle between code and comments.
8341: @item
8342: Load blocks; a single block (typically block 1) contains a number of
8343: @code{thru} commands which @code{load} the whole of the application.
8344: @end itemize
1.26 crook 8345:
1.29 crook 8346: See Frank Sergeant's Pygmy Forth to see just how well blocks can be
8347: integrated into a Forth programming environment.
1.26 crook 8348:
8349: @comment TODO what about errors on open-blocks?
1.44 crook 8350:
1.26 crook 8351: doc-open-blocks
8352: doc-use
1.75 anton 8353: doc-block-offset
1.26 crook 8354: doc-get-block-fid
8355: doc-block-position
1.28 crook 8356:
1.75 anton 8357: doc-list
1.28 crook 8358: doc-scr
8359:
1.45 crook 8360: doc---gforthman-block
1.28 crook 8361: doc-buffer
8362:
1.75 anton 8363: doc-empty-buffers
8364: doc-empty-buffer
1.26 crook 8365: doc-update
1.28 crook 8366: doc-updated?
1.26 crook 8367: doc-save-buffers
1.75 anton 8368: doc-save-buffer
1.26 crook 8369: doc-flush
1.28 crook 8370:
1.26 crook 8371: doc-load
8372: doc-thru
8373: doc-+load
8374: doc-+thru
1.45 crook 8375: doc---gforthman--->
1.26 crook 8376: doc-block-included
8377:
1.44 crook 8378:
1.26 crook 8379: @c -------------------------------------------------------------
8380: @node Other I/O, Programming Tools, Blocks, Words
8381: @section Other I/O
1.28 crook 8382: @cindex I/O - keyboard and display
1.26 crook 8383:
8384: @menu
8385: * Simple numeric output:: Predefined formats
8386: * Formatted numeric output:: Formatted (pictured) output
8387: * String Formats:: How Forth stores strings in memory
1.67 anton 8388: * Displaying characters and strings:: Other stuff
1.26 crook 8389: * Input:: Input
8390: @end menu
8391:
8392: @node Simple numeric output, Formatted numeric output, Other I/O, Other I/O
8393: @subsection Simple numeric output
1.28 crook 8394: @cindex numeric output - simple/free-format
1.5 anton 8395:
1.26 crook 8396: The simplest output functions are those that display numbers from the
8397: data or floating-point stacks. Floating-point output is always displayed
8398: using base 10. Numbers displayed from the data stack use the value stored
8399: in @code{base}.
1.5 anton 8400:
1.44 crook 8401:
1.26 crook 8402: doc-.
8403: doc-dec.
8404: doc-hex.
8405: doc-u.
8406: doc-.r
8407: doc-u.r
8408: doc-d.
8409: doc-ud.
8410: doc-d.r
8411: doc-ud.r
8412: doc-f.
8413: doc-fe.
8414: doc-fs.
1.5 anton 8415:
1.44 crook 8416:
1.26 crook 8417: Examples of printing the number 1234.5678E23 in the different floating-point output
8418: formats are shown below:
1.5 anton 8419:
8420: @example
1.26 crook 8421: f. 123456779999999000000000000.
8422: fe. 123.456779999999E24
8423: fs. 1.23456779999999E26
1.5 anton 8424: @end example
8425:
8426:
1.26 crook 8427: @node Formatted numeric output, String Formats, Simple numeric output, Other I/O
8428: @subsection Formatted numeric output
1.28 crook 8429: @cindex formatted numeric output
1.26 crook 8430: @cindex pictured numeric output
1.28 crook 8431: @cindex numeric output - formatted
1.26 crook 8432:
1.29 crook 8433: Forth traditionally uses a technique called @dfn{pictured numeric
1.26 crook 8434: output} for formatted printing of integers. In this technique, digits
8435: are extracted from the number (using the current output radix defined by
8436: @code{base}), converted to ASCII codes and appended to a string that is
8437: built in a scratch-pad area of memory (@pxref{core-idef,
8438: Implementation-defined options, Implementation-defined
8439: options}). Arbitrary characters can be appended to the string during the
8440: extraction process. The completed string is specified by an address
8441: and length and can be manipulated (@code{TYPE}ed, copied, modified)
8442: under program control.
1.5 anton 8443:
1.75 anton 8444: All of the integer output words described in the previous section
8445: (@pxref{Simple numeric output}) are implemented in Gforth using pictured
8446: numeric output.
1.5 anton 8447:
1.47 crook 8448: Three important things to remember about pictured numeric output:
1.5 anton 8449:
1.26 crook 8450: @itemize @bullet
8451: @item
1.28 crook 8452: It always operates on double-precision numbers; to display a
1.49 anton 8453: single-precision number, convert it first (for ways of doing this
8454: @pxref{Double precision}).
1.26 crook 8455: @item
1.28 crook 8456: It always treats the double-precision number as though it were
8457: unsigned. The examples below show ways of printing signed numbers.
1.26 crook 8458: @item
8459: The string is built up from right to left; least significant digit first.
8460: @end itemize
1.5 anton 8461:
1.44 crook 8462:
1.26 crook 8463: doc-<#
1.47 crook 8464: doc-<<#
1.26 crook 8465: doc-#
8466: doc-#s
8467: doc-hold
8468: doc-sign
8469: doc-#>
1.47 crook 8470: doc-#>>
1.5 anton 8471:
1.26 crook 8472: doc-represent
1.5 anton 8473:
1.44 crook 8474:
8475: @noindent
1.26 crook 8476: Here are some examples of using pictured numeric output:
1.5 anton 8477:
8478: @example
1.26 crook 8479: : my-u. ( u -- )
8480: \ Simplest use of pns.. behaves like Standard u.
8481: 0 \ convert to unsigned double
1.75 anton 8482: <<# \ start conversion
1.26 crook 8483: #s \ convert all digits
8484: #> \ complete conversion
1.75 anton 8485: TYPE SPACE \ display, with trailing space
8486: #>> ; \ release hold area
1.5 anton 8487:
1.26 crook 8488: : cents-only ( u -- )
8489: 0 \ convert to unsigned double
1.75 anton 8490: <<# \ start conversion
1.26 crook 8491: # # \ convert two least-significant digits
8492: #> \ complete conversion, discard other digits
1.75 anton 8493: TYPE SPACE \ display, with trailing space
8494: #>> ; \ release hold area
1.5 anton 8495:
1.26 crook 8496: : dollars-and-cents ( u -- )
8497: 0 \ convert to unsigned double
1.75 anton 8498: <<# \ start conversion
1.26 crook 8499: # # \ convert two least-significant digits
8500: [char] . hold \ insert decimal point
8501: #s \ convert remaining digits
8502: [char] $ hold \ append currency symbol
8503: #> \ complete conversion
1.75 anton 8504: TYPE SPACE \ display, with trailing space
8505: #>> ; \ release hold area
1.5 anton 8506:
1.26 crook 8507: : my-. ( n -- )
8508: \ handling negatives.. behaves like Standard .
8509: s>d \ convert to signed double
8510: swap over dabs \ leave sign byte followed by unsigned double
1.75 anton 8511: <<# \ start conversion
1.26 crook 8512: #s \ convert all digits
8513: rot sign \ get at sign byte, append "-" if needed
8514: #> \ complete conversion
1.75 anton 8515: TYPE SPACE \ display, with trailing space
8516: #>> ; \ release hold area
1.5 anton 8517:
1.26 crook 8518: : account. ( n -- )
1.75 anton 8519: \ accountants don't like minus signs, they use parentheses
1.26 crook 8520: \ for negative numbers
8521: s>d \ convert to signed double
8522: swap over dabs \ leave sign byte followed by unsigned double
1.75 anton 8523: <<# \ start conversion
1.26 crook 8524: 2 pick \ get copy of sign byte
8525: 0< IF [char] ) hold THEN \ right-most character of output
8526: #s \ convert all digits
8527: rot \ get at sign byte
8528: 0< IF [char] ( hold THEN
8529: #> \ complete conversion
1.75 anton 8530: TYPE SPACE \ display, with trailing space
8531: #>> ; \ release hold area
8532:
1.5 anton 8533: @end example
8534:
1.26 crook 8535: Here are some examples of using these words:
1.5 anton 8536:
8537: @example
1.26 crook 8538: 1 my-u. 1
8539: hex -1 my-u. decimal FFFFFFFF
8540: 1 cents-only 01
8541: 1234 cents-only 34
8542: 2 dollars-and-cents $0.02
8543: 1234 dollars-and-cents $12.34
8544: 123 my-. 123
8545: -123 my. -123
8546: 123 account. 123
8547: -456 account. (456)
1.5 anton 8548: @end example
8549:
8550:
1.26 crook 8551: @node String Formats, Displaying characters and strings, Formatted numeric output, Other I/O
8552: @subsection String Formats
1.27 crook 8553: @cindex strings - see character strings
8554: @cindex character strings - formats
1.28 crook 8555: @cindex I/O - see character strings
1.75 anton 8556: @cindex counted strings
8557:
8558: @c anton: this does not really belong here; maybe the memory section,
8559: @c or the principles chapter
1.26 crook 8560:
1.27 crook 8561: Forth commonly uses two different methods for representing character
8562: strings:
1.26 crook 8563:
8564: @itemize @bullet
8565: @item
8566: @cindex address of counted string
1.45 crook 8567: @cindex counted string
1.29 crook 8568: As a @dfn{counted string}, represented by a @i{c-addr}. The char
8569: addressed by @i{c-addr} contains a character-count, @i{n}, of the
8570: string and the string occupies the subsequent @i{n} char addresses in
1.26 crook 8571: memory.
8572: @item
1.29 crook 8573: As cell pair on the stack; @i{c-addr u}, where @i{u} is the length
8574: of the string in characters, and @i{c-addr} is the address of the
1.26 crook 8575: first byte of the string.
8576: @end itemize
8577:
8578: ANS Forth encourages the use of the second format when representing
1.75 anton 8579: strings.
1.26 crook 8580:
1.44 crook 8581:
1.26 crook 8582: doc-count
8583:
1.44 crook 8584:
1.49 anton 8585: For words that move, copy and search for strings see @ref{Memory
8586: Blocks}. For words that display characters and strings see
8587: @ref{Displaying characters and strings}.
1.26 crook 8588:
8589: @node Displaying characters and strings, Input, String Formats, Other I/O
8590: @subsection Displaying characters and strings
1.27 crook 8591: @cindex characters - compiling and displaying
8592: @cindex character strings - compiling and displaying
1.26 crook 8593:
8594: This section starts with a glossary of Forth words and ends with a set
8595: of examples.
8596:
1.44 crook 8597:
1.26 crook 8598: doc-bl
8599: doc-space
8600: doc-spaces
8601: doc-emit
8602: doc-toupper
8603: doc-."
8604: doc-.(
8605: doc-type
1.44 crook 8606: doc-typewhite
1.26 crook 8607: doc-cr
1.27 crook 8608: @cindex cursor control
1.26 crook 8609: doc-at-xy
8610: doc-page
8611: doc-s"
8612: doc-c"
8613: doc-char
8614: doc-[char]
8615: doc-sliteral
8616:
1.44 crook 8617:
8618: @noindent
1.26 crook 8619: As an example, consider the following text, stored in a file @file{test.fs}:
1.5 anton 8620:
8621: @example
1.26 crook 8622: .( text-1)
8623: : my-word
8624: ." text-2" cr
8625: .( text-3)
8626: ;
8627:
8628: ." text-4"
8629:
8630: : my-char
8631: [char] ALPHABET emit
8632: char emit
8633: ;
1.5 anton 8634: @end example
8635:
1.26 crook 8636: When you load this code into Gforth, the following output is generated:
1.5 anton 8637:
1.26 crook 8638: @example
1.30 anton 8639: @kbd{include test.fs @key{RET}} text-1text-3text-4 ok
1.26 crook 8640: @end example
1.5 anton 8641:
1.26 crook 8642: @itemize @bullet
8643: @item
8644: Messages @code{text-1} and @code{text-3} are displayed because @code{.(}
8645: is an immediate word; it behaves in the same way whether it is used inside
8646: or outside a colon definition.
8647: @item
8648: Message @code{text-4} is displayed because of Gforth's added interpretation
8649: semantics for @code{."}.
8650: @item
1.29 crook 8651: Message @code{text-2} is @i{not} displayed, because the text interpreter
1.26 crook 8652: performs the compilation semantics for @code{."} within the definition of
8653: @code{my-word}.
8654: @end itemize
1.5 anton 8655:
1.26 crook 8656: Here are some examples of executing @code{my-word} and @code{my-char}:
1.5 anton 8657:
1.26 crook 8658: @example
1.30 anton 8659: @kbd{my-word @key{RET}} text-2
1.26 crook 8660: ok
1.30 anton 8661: @kbd{my-char fred @key{RET}} Af ok
8662: @kbd{my-char jim @key{RET}} Aj ok
1.26 crook 8663: @end example
1.5 anton 8664:
8665: @itemize @bullet
8666: @item
1.26 crook 8667: Message @code{text-2} is displayed because of the run-time behaviour of
8668: @code{."}.
8669: @item
8670: @code{[char]} compiles the ``A'' from ``ALPHABET'' and puts its display code
8671: on the stack at run-time. @code{emit} always displays the character
8672: when @code{my-char} is executed.
8673: @item
8674: @code{char} parses a string at run-time and the second @code{emit} displays
8675: the first character of the string.
1.5 anton 8676: @item
1.26 crook 8677: If you type @code{see my-char} you can see that @code{[char]} discarded
8678: the text ``LPHABET'' and only compiled the display code for ``A'' into the
8679: definition of @code{my-char}.
1.5 anton 8680: @end itemize
8681:
8682:
8683:
1.48 anton 8684: @node Input, , Displaying characters and strings, Other I/O
1.26 crook 8685: @subsection Input
8686: @cindex input
1.28 crook 8687: @cindex I/O - see input
8688: @cindex parsing a string
1.5 anton 8689:
1.49 anton 8690: For ways of storing character strings in memory see @ref{String Formats}.
1.5 anton 8691:
1.27 crook 8692: @comment TODO examples for >number >float accept key key? pad parse word refill
1.29 crook 8693: @comment then index them
1.27 crook 8694:
1.44 crook 8695:
1.27 crook 8696: doc-key
8697: doc-key?
1.45 crook 8698: doc-ekey
8699: doc-ekey?
8700: doc-ekey>char
1.26 crook 8701: doc->number
8702: doc->float
8703: doc-accept
1.27 crook 8704: doc-pad
1.75 anton 8705: @c anton: these belong in the input stream section
1.27 crook 8706: doc-parse
8707: doc-word
8708: doc-sword
1.75 anton 8709: doc-name
1.27 crook 8710: doc-refill
8711: @comment obsolescent words..
8712: doc-convert
1.26 crook 8713: doc-query
8714: doc-expect
1.27 crook 8715: doc-span
1.5 anton 8716:
8717:
1.44 crook 8718:
1.5 anton 8719: @c -------------------------------------------------------------
1.26 crook 8720: @node Programming Tools, Assembler and Code Words, Other I/O, Words
8721: @section Programming Tools
8722: @cindex programming tools
1.12 anton 8723:
8724: @menu
1.77 ! anton 8725: * Examining::
! 8726: * Forgetting words::
1.26 crook 8727: * Debugging:: Simple and quick.
8728: * Assertions:: Making your programs self-checking.
1.46 pazsan 8729: * Singlestep Debugger:: Executing your program word by word.
1.5 anton 8730: @end menu
8731:
1.77 ! anton 8732: @node Examining, Forgetting words, Programming Tools, Programming Tools
! 8733: @subsection Examining data and code
! 8734: @cindex examining data and code
! 8735: @cindex data examination
! 8736: @cindex code examination
1.5 anton 8737:
1.77 ! anton 8738: The following words inspect the stack non-destructively:
1.44 crook 8739:
1.26 crook 8740: doc-.s
8741: doc-f.s
1.5 anton 8742:
1.77 ! anton 8743: There is a word @code{.r} but it does @i{not} display the return stack!
! 8744: It is used for formatted numeric output (@pxref{Simple numeric output}).
1.44 crook 8745:
1.26 crook 8746: doc-depth
8747: doc-fdepth
8748: doc-clearstack
1.77 ! anton 8749:
! 8750: The following words inspect memory.
! 8751:
1.26 crook 8752: doc-?
8753: doc-dump
1.5 anton 8754:
1.77 ! anton 8755: And finally, @code{see} allows to inspect code:
1.44 crook 8756:
1.77 ! anton 8757: doc-see
! 8758: doc-xt-see
1.5 anton 8759:
1.77 ! anton 8760: @node Forgetting words, Debugging, Examining, Programming Tools
! 8761: @subsection Forgetting words
! 8762: @cindex words, forgetting
! 8763: @cindex forgeting words
1.5 anton 8764:
1.77 ! anton 8765: @c anton: other, maybe better places for this subsection: Defining Words;
! 8766: @c Dictionary allocation. At least a reference should be there.
1.44 crook 8767:
1.77 ! anton 8768: Forth allows you to forget words (and everything that was alloted in the
! 8769: dictonary after them) in a LIFO manner.
1.5 anton 8770:
1.26 crook 8771: doc-marker
1.5 anton 8772:
1.77 ! anton 8773: The most common use of this feature is during progam development: when
! 8774: you change a source file, forget all the words it defined and load it
! 8775: again (since you also forget everything defined after the source file
! 8776: was loaded, you have to reload that, too). Note that effects like
! 8777: storing to variables and destroyed system words are not undone when you
! 8778: forget words. With a system like Gforth, that is fast enough at
! 8779: starting up and compiling, I find it more convenient to exit and restart
! 8780: Gforth, as this gives me a clean slate.
1.44 crook 8781:
1.26 crook 8782: Here's an example of using @code{marker} at the start of a source file
8783: that you are debugging; it ensures that you only ever have one copy of
8784: the file's definitions compiled at any time:
1.5 anton 8785:
1.26 crook 8786: @example
8787: [IFDEF] my-code
8788: my-code
8789: [ENDIF]
1.5 anton 8790:
1.26 crook 8791: marker my-code
1.28 crook 8792: init-included-files
1.5 anton 8793:
1.26 crook 8794: \ .. definitions start here
8795: \ .
8796: \ .
8797: \ end
8798: @end example
1.5 anton 8799:
8800:
1.77 ! anton 8801: @node Debugging, Assertions, Forgetting words, Programming Tools
! 8802: @subsection Debugging
! 8803: @cindex debugging
! 8804:
! 8805: Languages with a slow edit/compile/link/test development loop tend to
! 8806: require sophisticated tracing/stepping debuggers to facilate debugging.
! 8807:
! 8808: A much better (faster) way in fast-compiling languages is to add
! 8809: printing code at well-selected places, let the program run, look at
! 8810: the output, see where things went wrong, add more printing code, etc.,
! 8811: until the bug is found.
! 8812:
! 8813: The simple debugging aids provided in @file{debugs.fs}
! 8814: are meant to support this style of debugging.
! 8815:
! 8816: The word @code{~~} prints debugging information (by default the source
! 8817: location and the stack contents). It is easy to insert. If you use Emacs
! 8818: it is also easy to remove (@kbd{C-x ~} in the Emacs Forth mode to
! 8819: query-replace them with nothing). The deferred words
! 8820: @code{printdebugdata} and @code{printdebugline} control the output of
! 8821: @code{~~}. The default source location output format works well with
! 8822: Emacs' compilation mode, so you can step through the program at the
! 8823: source level using @kbd{C-x `} (the advantage over a stepping debugger
! 8824: is that you can step in any direction and you know where the crash has
! 8825: happened or where the strange data has occurred).
! 8826:
! 8827: doc-~~
! 8828: doc-printdebugdata
! 8829: doc-printdebugline
1.5 anton 8830:
1.26 crook 8831: @node Assertions, Singlestep Debugger, Debugging, Programming Tools
8832: @subsection Assertions
8833: @cindex assertions
1.5 anton 8834:
1.26 crook 8835: It is a good idea to make your programs self-checking, especially if you
8836: make an assumption that may become invalid during maintenance (for
8837: example, that a certain field of a data structure is never zero). Gforth
1.29 crook 8838: supports @dfn{assertions} for this purpose. They are used like this:
1.23 crook 8839:
1.26 crook 8840: @example
1.29 crook 8841: assert( @i{flag} )
1.26 crook 8842: @end example
1.23 crook 8843:
1.26 crook 8844: The code between @code{assert(} and @code{)} should compute a flag, that
8845: should be true if everything is alright and false otherwise. It should
8846: not change anything else on the stack. The overall stack effect of the
8847: assertion is @code{( -- )}. E.g.
1.23 crook 8848:
1.26 crook 8849: @example
8850: assert( 1 1 + 2 = ) \ what we learn in school
8851: assert( dup 0<> ) \ assert that the top of stack is not zero
8852: assert( false ) \ this code should not be reached
8853: @end example
1.23 crook 8854:
1.26 crook 8855: The need for assertions is different at different times. During
8856: debugging, we want more checking, in production we sometimes care more
8857: for speed. Therefore, assertions can be turned off, i.e., the assertion
8858: becomes a comment. Depending on the importance of an assertion and the
8859: time it takes to check it, you may want to turn off some assertions and
8860: keep others turned on. Gforth provides several levels of assertions for
8861: this purpose:
1.23 crook 8862:
1.44 crook 8863:
1.26 crook 8864: doc-assert0(
8865: doc-assert1(
8866: doc-assert2(
8867: doc-assert3(
8868: doc-assert(
8869: doc-)
1.23 crook 8870:
1.44 crook 8871:
1.26 crook 8872: The variable @code{assert-level} specifies the highest assertions that
8873: are turned on. I.e., at the default @code{assert-level} of one,
8874: @code{assert0(} and @code{assert1(} assertions perform checking, while
8875: @code{assert2(} and @code{assert3(} assertions are treated as comments.
8876:
8877: The value of @code{assert-level} is evaluated at compile-time, not at
8878: run-time. Therefore you cannot turn assertions on or off at run-time;
8879: you have to set the @code{assert-level} appropriately before compiling a
8880: piece of code. You can compile different pieces of code at different
8881: @code{assert-level}s (e.g., a trusted library at level 1 and
8882: newly-written code at level 3).
1.23 crook 8883:
1.44 crook 8884:
1.26 crook 8885: doc-assert-level
1.23 crook 8886:
1.44 crook 8887:
1.26 crook 8888: If an assertion fails, a message compatible with Emacs' compilation mode
8889: is produced and the execution is aborted (currently with @code{ABORT"}.
8890: If there is interest, we will introduce a special throw code. But if you
8891: intend to @code{catch} a specific condition, using @code{throw} is
8892: probably more appropriate than an assertion).
1.23 crook 8893:
1.26 crook 8894: Definitions in ANS Forth for these assertion words are provided
8895: in @file{compat/assert.fs}.
1.23 crook 8896:
8897:
1.48 anton 8898: @node Singlestep Debugger, , Assertions, Programming Tools
1.26 crook 8899: @subsection Singlestep Debugger
8900: @cindex singlestep Debugger
8901: @cindex debugging Singlestep
1.23 crook 8902:
1.26 crook 8903: When you create a new word there's often the need to check whether it
8904: behaves correctly or not. You can do this by typing @code{dbg
8905: badword}. A debug session might look like this:
1.23 crook 8906:
1.26 crook 8907: @example
8908: : badword 0 DO i . LOOP ; ok
8909: 2 dbg badword
8910: : badword
8911: Scanning code...
1.23 crook 8912:
1.26 crook 8913: Nesting debugger ready!
1.23 crook 8914:
1.26 crook 8915: 400D4738 8049BC4 0 -> [ 2 ] 00002 00000
8916: 400D4740 8049F68 DO -> [ 0 ]
8917: 400D4744 804A0C8 i -> [ 1 ] 00000
8918: 400D4748 400C5E60 . -> 0 [ 0 ]
8919: 400D474C 8049D0C LOOP -> [ 0 ]
8920: 400D4744 804A0C8 i -> [ 1 ] 00001
8921: 400D4748 400C5E60 . -> 1 [ 0 ]
8922: 400D474C 8049D0C LOOP -> [ 0 ]
8923: 400D4758 804B384 ; -> ok
8924: @end example
1.23 crook 8925:
1.26 crook 8926: Each line displayed is one step. You always have to hit return to
8927: execute the next word that is displayed. If you don't want to execute
8928: the next word in a whole, you have to type @kbd{n} for @code{nest}. Here is
8929: an overview what keys are available:
1.23 crook 8930:
1.26 crook 8931: @table @i
1.23 crook 8932:
1.30 anton 8933: @item @key{RET}
1.26 crook 8934: Next; Execute the next word.
1.23 crook 8935:
1.26 crook 8936: @item n
8937: Nest; Single step through next word.
1.5 anton 8938:
1.26 crook 8939: @item u
8940: Unnest; Stop debugging and execute rest of word. If we got to this word
8941: with nest, continue debugging with the calling word.
1.5 anton 8942:
1.26 crook 8943: @item d
8944: Done; Stop debugging and execute rest.
1.5 anton 8945:
1.26 crook 8946: @item s
8947: Stop; Abort immediately.
1.5 anton 8948:
1.26 crook 8949: @end table
1.5 anton 8950:
1.26 crook 8951: Debugging large application with this mechanism is very difficult, because
8952: you have to nest very deeply into the program before the interesting part
8953: begins. This takes a lot of time.
1.5 anton 8954:
1.26 crook 8955: To do it more directly put a @code{BREAK:} command into your source code.
8956: When program execution reaches @code{BREAK:} the single step debugger is
8957: invoked and you have all the features described above.
1.23 crook 8958:
1.26 crook 8959: If you have more than one part to debug it is useful to know where the
8960: program has stopped at the moment. You can do this by the
8961: @code{BREAK" string"} command. This behaves like @code{BREAK:} except that
8962: string is typed out when the ``breakpoint'' is reached.
8963:
1.44 crook 8964:
1.26 crook 8965: doc-dbg
1.45 crook 8966: doc-break:
8967: doc-break"
1.26 crook 8968:
8969:
1.44 crook 8970:
1.26 crook 8971: @c -------------------------------------------------------------
8972: @node Assembler and Code Words, Threading Words, Programming Tools, Words
8973: @section Assembler and Code Words
8974: @cindex assembler
8975: @cindex code words
1.5 anton 8976:
1.52 anton 8977: @menu
1.53 anton 8978: * Code and ;code::
8979: * Common Assembler:: Assembler Syntax
1.52 anton 8980: * Common Disassembler::
8981: * 386 Assembler:: Deviations and special cases
8982: * Alpha Assembler:: Deviations and special cases
8983: * MIPS assembler:: Deviations and special cases
1.53 anton 8984: * Other assemblers:: How to write them
1.52 anton 8985: @end menu
8986:
1.53 anton 8987: @node Code and ;code, Common Assembler, Assembler and Code Words, Assembler and Code Words
8988: @subsection @code{Code} and @code{;code}
1.52 anton 8989:
1.26 crook 8990: Gforth provides some words for defining primitives (words written in
1.29 crook 8991: machine code), and for defining the machine-code equivalent of
1.26 crook 8992: @code{DOES>}-based defining words. However, the machine-independent
8993: nature of Gforth poses a few problems: First of all, Gforth runs on
8994: several architectures, so it can provide no standard assembler. What's
8995: worse is that the register allocation not only depends on the processor,
8996: but also on the @code{gcc} version and options used.
1.5 anton 8997:
1.29 crook 8998: The words that Gforth offers encapsulate some system dependences (e.g.,
8999: the header structure), so a system-independent assembler may be used in
1.26 crook 9000: Gforth. If you do not have an assembler, you can compile machine code
1.29 crook 9001: directly with @code{,} and @code{c,}@footnote{This isn't portable,
9002: because these words emit stuff in @i{data} space; it works because
9003: Gforth has unified code/data spaces. Assembler isn't likely to be
9004: portable anyway.}.
1.5 anton 9005:
1.44 crook 9006:
1.26 crook 9007: doc-assembler
1.45 crook 9008: doc-init-asm
1.26 crook 9009: doc-code
9010: doc-end-code
9011: doc-;code
9012: doc-flush-icache
1.5 anton 9013:
1.44 crook 9014:
1.26 crook 9015: If @code{flush-icache} does not work correctly, @code{code} words
9016: etc. will not work (reliably), either.
1.5 anton 9017:
1.29 crook 9018: The typical usage of these @code{code} words can be shown most easily by
9019: analogy to the equivalent high-level defining words:
9020:
9021: @example
1.53 anton 9022: : foo code foo
9023: <high-level Forth words> <assembler>
9024: ; end-code
9025:
9026: : bar : bar
9027: <high-level Forth words> <high-level Forth words>
9028: CREATE CREATE
9029: <high-level Forth words> <high-level Forth words>
9030: DOES> ;code
9031: <high-level Forth words> <assembler>
9032: ; end-code
1.29 crook 9033: @end example
9034:
1.77 ! anton 9035: @c anton: the following stuff is also in "Common Assembler", in less detail.
1.5 anton 9036:
1.26 crook 9037: @cindex registers of the inner interpreter
9038: In the assembly code you will want to refer to the inner interpreter's
9039: registers (e.g., the data stack pointer) and you may want to use other
9040: registers for temporary storage. Unfortunately, the register allocation
9041: is installation-dependent.
1.5 anton 9042:
1.77 ! anton 9043: In particular, @code{ip} (Forth instruction pointer) and @code{rp}
! 9044: (return stack pointer) are in different places in @code{gforth} and
! 9045: @code{gforth-fast}. This means that you cannot write a @code{NEXT}
! 9046: routine that works on both versions; so for doing @code{NEXT}, I
! 9047: recomment jumping to @code{' noop >code-address}, which contains nothing
! 9048: but a @code{NEXT}.
! 9049:
! 9050: For general accesses to the inner interpreter's registers, the easiest
! 9051: solution is to use explicit register declarations (@pxref{Explicit Reg
! 9052: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) for
! 9053: all of the inner interpreter's registers: You have to compile Gforth
! 9054: with @code{-DFORCE_REG} (configure option @code{--enable-force-reg}) and
! 9055: the appropriate declarations must be present in the @code{machine.h}
! 9056: file (see @code{mips.h} for an example; you can find a full list of all
! 9057: declarable register symbols with @code{grep register engine.c}). If you
! 9058: give explicit registers to all variables that are declared at the
! 9059: beginning of @code{engine()}, you should be able to use the other
! 9060: caller-saved registers for temporary storage. Alternatively, you can use
! 9061: the @code{gcc} option @code{-ffixed-REG} (@pxref{Code Gen Options, ,
! 9062: Options for Code Generation Conventions, gcc.info, GNU C Manual}) to
! 9063: reserve a register (however, this restriction on register allocation may
! 9064: slow Gforth significantly).
1.5 anton 9065:
1.26 crook 9066: If this solution is not viable (e.g., because @code{gcc} does not allow
9067: you to explicitly declare all the registers you need), you have to find
9068: out by looking at the code where the inner interpreter's registers
9069: reside and which registers can be used for temporary storage. You can
9070: get an assembly listing of the engine's code with @code{make engine.s}.
1.5 anton 9071:
1.26 crook 9072: In any case, it is good practice to abstract your assembly code from the
9073: actual register allocation. E.g., if the data stack pointer resides in
9074: register @code{$17}, create an alias for this register called @code{sp},
9075: and use that in your assembly code.
1.5 anton 9076:
1.26 crook 9077: @cindex code words, portable
9078: Another option for implementing normal and defining words efficiently
9079: is to add the desired functionality to the source of Gforth. For normal
9080: words you just have to edit @file{primitives} (@pxref{Automatic
9081: Generation}). Defining words (equivalent to @code{;CODE} words, for fast
9082: defined words) may require changes in @file{engine.c}, @file{kernel.fs},
9083: @file{prims2x.fs}, and possibly @file{cross.fs}.
1.5 anton 9084:
1.53 anton 9085: @node Common Assembler, Common Disassembler, Code and ;code, Assembler and Code Words
9086: @subsection Common Assembler
9087:
9088: The assemblers in Gforth generally use a postfix syntax, i.e., the
9089: instruction name follows the operands.
9090:
9091: The operands are passed in the usual order (the same that is used in the
9092: manual of the architecture). Since they all are Forth words, they have
9093: to be separated by spaces; you can also use Forth words to compute the
9094: operands.
9095:
9096: The instruction names usually end with a @code{,}. This makes it easier
9097: to visually separate instructions if you put several of them on one
9098: line; it also avoids shadowing other Forth words (e.g., @code{and}).
9099:
1.55 anton 9100: Registers are usually specified by number; e.g., (decimal) @code{11}
9101: specifies registers R11 and F11 on the Alpha architecture (which one,
9102: depends on the instruction). The usual names are also available, e.g.,
9103: @code{s2} for R11 on Alpha.
9104:
1.53 anton 9105: Control flow is specified similar to normal Forth code (@pxref{Arbitrary
9106: control structures}), with @code{if,}, @code{ahead,}, @code{then,},
9107: @code{begin,}, @code{until,}, @code{again,}, @code{cs-roll},
9108: @code{cs-pick}, @code{else,}, @code{while,}, and @code{repeat,}. The
9109: conditions are specified in a way specific to each assembler.
9110:
1.57 anton 9111: Note that the register assignments of the Gforth engine can change
9112: between Gforth versions, or even between different compilations of the
9113: same Gforth version (e.g., if you use a different GCC version). So if
9114: you want to refer to Gforth's registers (e.g., the stack pointer or
9115: TOS), I recommend defining your own words for refering to these
9116: registers, and using them later on; then you can easily adapt to a
9117: changed register assignment. The stability of the register assignment
9118: is usually better if you build Gforth with @code{--enable-force-reg}.
9119:
1.77 ! anton 9120: In particular, the return stack pointer and the instruction pointer are
1.57 anton 9121: in memory in @code{gforth}, and usually in registers in
9122: @code{gforth-fast}. The most common use of these registers is to
9123: dispatch to the next word (the @code{next} routine). A portable way to
9124: do this is to jump to @code{' noop >code-address} (of course, this is
9125: less efficient than integrating the @code{next} code and scheduling it
9126: well).
9127:
1.52 anton 9128: @node Common Disassembler, 386 Assembler, Common Assembler, Assembler and Code Words
9129: @subsection Common Disassembler
9130:
9131: You can disassemble a @code{code} word with @code{see}
9132: (@pxref{Debugging}). You can disassemble a section of memory with
9133:
9134: doc-disasm
9135:
9136: The disassembler generally produces output that can be fed into the
9137: assembler (i.e., same syntax, etc.). It also includes additional
1.53 anton 9138: information in comments. In particular, the address of the instruction
9139: is given in a comment before the instruction.
9140:
9141: @code{See} may display more or less than the actual code of the word,
9142: because the recognition of the end of the code is unreliable. You can
9143: use @code{disasm} if it did not display enough. It may display more, if
9144: the code word is not immediately followed by a named word. If you have
9145: something else there, you can follow the word with @code{align last @ ,}
9146: to ensure that the end is recognized.
1.52 anton 9147:
9148: @node 386 Assembler, Alpha Assembler, Common Disassembler, Assembler and Code Words
9149: @subsection 386 Assembler
9150:
1.64 pazsan 9151: The 386 assembler included in Gforth was written by Bernd Paysan, it's
9152: available under GPL, and originally part of bigFORTH.
9153:
9154: The 386 disassembler included in Gforth was written by Andrew McKewan
9155: and is in the public domain.
1.57 anton 9156:
9157: The disassembler displays code in prefix Intel syntax.
9158:
1.64 pazsan 9159: The assembler uses a postfix syntax with reversed parameters.
9160:
9161: The assembler includes all instruction of the Athlon, i.e. 486 core
9162: instructions, Pentium and PPro extensions, floating point, MMX, 3Dnow!,
9163: but not ISSE. It's an integrated 16- and 32-bit assembler. Default is 32
9164: bit, you can switch to 16 bit with .86 and back to 32 bit with .386.
9165:
9166: There are several prefixes to switch between different operation sizes,
9167: @code{.b} for byte accesses, @code{.w} for word accesses, @code{.d} for
9168: double-word accesses. Addressing modes can be switched with @code{.wa}
9169: for 16 bit addresses, and @code{.da} for 32 bit addresses. You don't
9170: need a prefix for byte register names (@code{AL} et al).
9171:
9172: For floating point operations, the prefixes are @code{.fs} (IEEE
9173: single), @code{.fl} (IEEE double), @code{.fx} (extended), @code{.fw}
9174: (word), @code{.fd} (double-word), and @code{.fq} (quad-word).
9175:
9176: The MMX opcodes don't have size prefixes, they are spelled out like in
9177: the Intel assembler. Instead of move from and to memory, there are
9178: PLDQ/PLDD and PSTQ/PSTD.
9179:
9180: The registers lack the 'e' prefix; even in 32 bit mode, eax is called
9181: ax. Immediate values are indicated by postfixing them with @code{#},
9182: e.g., @code{3 #}. Here are some examples of addressing modes:
1.57 anton 9183:
9184: @example
1.65 anton 9185: 3 # \ immediate
9186: ax \ register
9187: 100 di d) \ 100[edi]
9188: 4 bx cx di) \ 4[ebx][ecx]
9189: di ax *4 i) \ [edi][eax*4]
9190: 20 ax *4 i#) \ 20[eax*4]
1.57 anton 9191: @end example
9192:
9193: Some example of instructions are:
9194:
9195: @example
1.64 pazsan 9196: ax bx mov \ move ebx,eax
9197: 3 # ax mov \ mov eax,3
9198: 100 di ) ax mov \ mov eax,100[edi]
9199: 4 bx cx di) ax mov \ mov eax,4[ebx][ecx]
9200: .w ax bx mov \ mov bx,ax
1.57 anton 9201: @end example
9202:
1.64 pazsan 9203: The following forms are supported for binary instructions:
1.57 anton 9204:
9205: @example
9206: <reg> <reg> <inst>
9207: <n> # <reg> <inst>
9208: <mem> <reg> <inst>
9209: <reg> <mem> <inst>
9210: @end example
9211:
9212: Immediate to memory is not supported. The shift/rotate syntax is:
9213:
9214: @example
1.64 pazsan 9215: <reg/mem> 1 # shl \ shortens to shift without immediate
9216: <reg/mem> 4 # shl
9217: <reg/mem> cl shl
1.57 anton 9218: @end example
9219:
1.64 pazsan 9220: Precede string instructions (@code{movs} etc.) with @code{.b} to get
1.57 anton 9221: the byte version.
9222:
1.65 anton 9223: The control structure words @code{IF} @code{UNTIL} etc. must be preceded
9224: by one of these conditions: @code{vs vc u< u>= 0= 0<> u<= u> 0< 0>= ps
9225: pc < >= <= >}. (Note that most of these words shadow some Forth words
9226: when @code{assembler} is in front of @code{forth} in the search path,
9227: e.g., in @code{code} words). Currently the control structure words use
9228: one stack item, so you have to use @code{roll} instead of @code{cs-roll}
9229: to shuffle them (you can also use @code{swap} etc.).
9230:
9231: Here is an example of a @code{code} word (assumes that the stack pointer
9232: is in esi and the TOS is in ebx):
9233:
9234: @example
9235: code my+ ( n1 n2 -- n )
9236: 4 si D) bx add
9237: 4 # si add
9238: Next
9239: end-code
9240: @end example
1.52 anton 9241:
9242: @node Alpha Assembler, MIPS assembler, 386 Assembler, Assembler and Code Words
9243: @subsection Alpha Assembler
9244:
1.55 anton 9245: The Alpha assembler and disassembler were originally written by Bernd
9246: Thallner.
9247:
9248: The register names @code{a0}--@code{a5} are not available to avoid
9249: shadowing hex numbers.
9250:
9251: Immediate forms of arithmetic instructions are distinguished by a
9252: @code{#} just before the @code{,}, e.g., @code{and#,} (note: @code{lda,}
9253: does not count as arithmetic instruction).
9254:
9255: You have to specify all operands to an instruction, even those that
9256: other assemblers consider optional, e.g., the destination register for
9257: @code{br,}, or the destination register and hint for @code{jmp,}.
9258:
9259: You can specify conditions for @code{if,} by removing the first @code{b}
9260: and the trailing @code{,} from a branch with a corresponding name; e.g.,
9261:
9262: @example
9263: 11 fgt if, \ if F11>0e
9264: ...
9265: endif,
1.56 anton 9266: @end example
1.55 anton 9267:
9268: @code{fbgt,} gives @code{fgt}.
1.52 anton 9269:
1.53 anton 9270: @node MIPS assembler, Other assemblers, Alpha Assembler, Assembler and Code Words
1.52 anton 9271: @subsection MIPS assembler
9272:
9273: The MIPS assembler was originally written by Christian Pirker.
9274:
9275: Currently the assembler and disassembler only cover the MIPS-I
9276: architecture (R3000), and don't support FP instructions.
9277:
1.55 anton 9278: The register names @code{$a0}--@code{$a3} are not available to avoid
9279: shadowing hex numbers.
1.52 anton 9280:
9281: Because there is no way to distinguish registers from immediate values,
9282: you have to explicitly use the immediate forms of instructions, i.e.,
9283: @code{addiu,}, not just @code{addu,} (@command{as} does this
9284: implicitly).
9285:
9286: If the architecture manual specifies several formats for the instruction
9287: (e.g., for @code{jalr,}), you usually have to use the one with more
9288: arguments (i.e., two for @code{jalr,}). When in doubt, see
9289: @code{arch/mips/testasm.fs} for an example of correct use.
9290:
1.53 anton 9291: Branches and jumps in the MIPS architecture have a delay slot. You have
9292: to fill it yourself (the simplest way is to use @code{nop,}), the
9293: assembler does not do it for you (unlike @command{as}). Even
9294: @code{if,}, @code{ahead,}, @code{until,}, @code{again,}, @code{while,},
9295: @code{else,} and @code{repeat,} need a delay slot. Since @code{begin,}
9296: and @code{then,} just specify branch targets, they are not affected.
9297:
9298: Note that you must not put branches, jumps, or @code{li,} into the delay
9299: slot: @code{li,} may expand to several instructions, and control flow
9300: instructions may not be put into the branch delay slot in any case.
1.52 anton 9301:
9302: For branches the argument specifying the target is a relative address;
9303: You have to add the address of the delay slot to get the absolute
9304: address.
1.53 anton 9305:
9306: The MIPS architecture also has load delay slots and restrictions on
9307: using @code{mfhi,} and @code{mflo,}; you have to order the instructions
9308: yourself to satisfy these restrictions, the assembler does not do it for
9309: you.
9310:
9311: You can specify the conditions for @code{if,} etc. by taking a
9312: conditional branch and leaving away the @code{b} at the start and the
9313: @code{,} at the end. E.g.,
9314:
9315: @example
9316: 4 5 eq if,
9317: ... \ do something if $4 equals $5
9318: then,
9319: @end example
9320:
9321: @node Other assemblers, , MIPS assembler, Assembler and Code Words
9322: @subsection Other assemblers
9323:
9324: If you want to contribute another assembler/disassembler, please contact
9325: us (@email{bug-gforth@@gnu.org}) to check if we have such an assembler
9326: already. If you are writing them from scratch, please use a similar
9327: syntax style as the one we use (i.e., postfix, commas at the end of the
9328: instruction names, @pxref{Common Assembler}); make the output of the
9329: disassembler be valid input for the assembler, and keep the style
9330: similar to the style we used.
9331:
9332: Hints on implementation: The most important part is to have a good test
9333: suite that contains all instructions. Once you have that, the rest is
9334: easy. For actual coding you can take a look at
9335: @file{arch/mips/disasm.fs} to get some ideas on how to use data for both
9336: the assembler and disassembler, avoiding redundancy and some potential
1.63 anton 9337: bugs. You can also look at that file (and @pxref{Advanced does> usage
9338: example}) to get ideas how to factor a disassembler.
1.5 anton 9339:
1.54 anton 9340: Start with the disassembler, because it's easier to reuse data from the
9341: disassembler for the assembler than the other way round.
9342:
9343: For the assembler, take a look at @file{arch/alpha/asm.fs}, which shows
9344: how simple it can be.
9345:
1.26 crook 9346: @c -------------------------------------------------------------
9347: @node Threading Words, Locals, Assembler and Code Words, Words
9348: @section Threading Words
9349: @cindex threading words
1.5 anton 9350:
1.26 crook 9351: @cindex code address
9352: These words provide access to code addresses and other threading stuff
9353: in Gforth (and, possibly, other interpretive Forths). It more or less
9354: abstracts away the differences between direct and indirect threading
9355: (and, for direct threading, the machine dependences). However, at
9356: present this wordset is still incomplete. It is also pretty low-level;
9357: some day it will hopefully be made unnecessary by an internals wordset
9358: that abstracts implementation details away completely.
1.5 anton 9359:
1.44 crook 9360:
1.26 crook 9361: doc-threading-method
9362: doc->code-address
9363: doc->does-code
9364: doc-code-address!
9365: doc-does-code!
9366: doc-does-handler!
9367: doc-/does-handler
1.5 anton 9368:
1.44 crook 9369:
1.26 crook 9370: The code addresses produced by various defining words are produced by
9371: the following words:
1.5 anton 9372:
1.44 crook 9373:
1.26 crook 9374: doc-docol:
9375: doc-docon:
9376: doc-dovar:
9377: doc-douser:
9378: doc-dodefer:
9379: doc-dofield:
1.5 anton 9380:
1.44 crook 9381:
1.26 crook 9382: You can recognize words defined by a @code{CREATE}...@code{DOES>} word
9383: with @code{>does-code}. If the word was defined in that way, the value
9384: returned is non-zero and identifies the @code{DOES>} used by the
9385: defining word.
9386: @comment TODO should that be ``identifies the xt of the DOES> ??''
1.5 anton 9387:
1.26 crook 9388: @c -------------------------------------------------------------
9389: @node Locals, Structures, Threading Words, Words
9390: @section Locals
9391: @cindex locals
1.5 anton 9392:
1.26 crook 9393: Local variables can make Forth programming more enjoyable and Forth
9394: programs easier to read. Unfortunately, the locals of ANS Forth are
9395: laden with restrictions. Therefore, we provide not only the ANS Forth
9396: locals wordset, but also our own, more powerful locals wordset (we
9397: implemented the ANS Forth locals wordset through our locals wordset).
1.5 anton 9398:
1.66 anton 9399: The ideas in this section have also been published in M. Anton Ertl,
9400: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl94l.ps.gz,
9401: Automatic Scoping of Local Variables}}, EuroForth '94.
1.5 anton 9402:
1.26 crook 9403: @menu
9404: * Gforth locals::
9405: * ANS Forth locals::
9406: @end menu
1.5 anton 9407:
1.26 crook 9408: @node Gforth locals, ANS Forth locals, Locals, Locals
9409: @subsection Gforth locals
9410: @cindex Gforth locals
9411: @cindex locals, Gforth style
1.5 anton 9412:
1.26 crook 9413: Locals can be defined with
1.5 anton 9414:
9415: @example
1.26 crook 9416: @{ local1 local2 ... -- comment @}
9417: @end example
9418: or
9419: @example
9420: @{ local1 local2 ... @}
1.5 anton 9421: @end example
9422:
1.26 crook 9423: E.g.,
1.5 anton 9424: @example
1.26 crook 9425: : max @{ n1 n2 -- n3 @}
9426: n1 n2 > if
9427: n1
9428: else
9429: n2
9430: endif ;
1.5 anton 9431: @end example
9432:
1.26 crook 9433: The similarity of locals definitions with stack comments is intended. A
9434: locals definition often replaces the stack comment of a word. The order
9435: of the locals corresponds to the order in a stack comment and everything
9436: after the @code{--} is really a comment.
1.5 anton 9437:
1.26 crook 9438: This similarity has one disadvantage: It is too easy to confuse locals
9439: declarations with stack comments, causing bugs and making them hard to
9440: find. However, this problem can be avoided by appropriate coding
9441: conventions: Do not use both notations in the same program. If you do,
9442: they should be distinguished using additional means, e.g. by position.
9443:
9444: @cindex types of locals
9445: @cindex locals types
9446: The name of the local may be preceded by a type specifier, e.g.,
9447: @code{F:} for a floating point value:
9448:
9449: @example
9450: : CX* @{ F: Ar F: Ai F: Br F: Bi -- Cr Ci @}
9451: \ complex multiplication
9452: Ar Br f* Ai Bi f* f-
9453: Ar Bi f* Ai Br f* f+ ;
9454: @end example
9455:
9456: @cindex flavours of locals
9457: @cindex locals flavours
9458: @cindex value-flavoured locals
9459: @cindex variable-flavoured locals
9460: Gforth currently supports cells (@code{W:}, @code{W^}), doubles
9461: (@code{D:}, @code{D^}), floats (@code{F:}, @code{F^}) and characters
9462: (@code{C:}, @code{C^}) in two flavours: a value-flavoured local (defined
9463: with @code{W:}, @code{D:} etc.) produces its value and can be changed
9464: with @code{TO}. A variable-flavoured local (defined with @code{W^} etc.)
9465: produces its address (which becomes invalid when the variable's scope is
9466: left). E.g., the standard word @code{emit} can be defined in terms of
9467: @code{type} like this:
1.5 anton 9468:
9469: @example
1.26 crook 9470: : emit @{ C^ char* -- @}
9471: char* 1 type ;
1.5 anton 9472: @end example
9473:
1.26 crook 9474: @cindex default type of locals
9475: @cindex locals, default type
9476: A local without type specifier is a @code{W:} local. Both flavours of
9477: locals are initialized with values from the data or FP stack.
1.5 anton 9478:
1.26 crook 9479: Currently there is no way to define locals with user-defined data
9480: structures, but we are working on it.
1.5 anton 9481:
1.26 crook 9482: Gforth allows defining locals everywhere in a colon definition. This
9483: poses the following questions:
1.5 anton 9484:
1.26 crook 9485: @menu
9486: * Where are locals visible by name?::
9487: * How long do locals live?::
9488: * Programming Style::
9489: * Implementation::
9490: @end menu
1.5 anton 9491:
1.26 crook 9492: @node Where are locals visible by name?, How long do locals live?, Gforth locals, Gforth locals
9493: @subsubsection Where are locals visible by name?
9494: @cindex locals visibility
9495: @cindex visibility of locals
9496: @cindex scope of locals
1.5 anton 9497:
1.26 crook 9498: Basically, the answer is that locals are visible where you would expect
9499: it in block-structured languages, and sometimes a little longer. If you
9500: want to restrict the scope of a local, enclose its definition in
9501: @code{SCOPE}...@code{ENDSCOPE}.
1.5 anton 9502:
1.44 crook 9503:
1.26 crook 9504: doc-scope
9505: doc-endscope
1.5 anton 9506:
1.44 crook 9507:
1.26 crook 9508: These words behave like control structure words, so you can use them
9509: with @code{CS-PICK} and @code{CS-ROLL} to restrict the scope in
9510: arbitrary ways.
1.5 anton 9511:
1.26 crook 9512: If you want a more exact answer to the visibility question, here's the
9513: basic principle: A local is visible in all places that can only be
9514: reached through the definition of the local@footnote{In compiler
9515: construction terminology, all places dominated by the definition of the
9516: local.}. In other words, it is not visible in places that can be reached
9517: without going through the definition of the local. E.g., locals defined
9518: in @code{IF}...@code{ENDIF} are visible until the @code{ENDIF}, locals
9519: defined in @code{BEGIN}...@code{UNTIL} are visible after the
9520: @code{UNTIL} (until, e.g., a subsequent @code{ENDSCOPE}).
1.5 anton 9521:
1.26 crook 9522: The reasoning behind this solution is: We want to have the locals
9523: visible as long as it is meaningful. The user can always make the
9524: visibility shorter by using explicit scoping. In a place that can
9525: only be reached through the definition of a local, the meaning of a
9526: local name is clear. In other places it is not: How is the local
9527: initialized at the control flow path that does not contain the
9528: definition? Which local is meant, if the same name is defined twice in
9529: two independent control flow paths?
1.5 anton 9530:
1.26 crook 9531: This should be enough detail for nearly all users, so you can skip the
9532: rest of this section. If you really must know all the gory details and
9533: options, read on.
1.5 anton 9534:
1.26 crook 9535: In order to implement this rule, the compiler has to know which places
9536: are unreachable. It knows this automatically after @code{AHEAD},
9537: @code{AGAIN}, @code{EXIT} and @code{LEAVE}; in other cases (e.g., after
9538: most @code{THROW}s), you can use the word @code{UNREACHABLE} to tell the
9539: compiler that the control flow never reaches that place. If
9540: @code{UNREACHABLE} is not used where it could, the only consequence is
9541: that the visibility of some locals is more limited than the rule above
9542: says. If @code{UNREACHABLE} is used where it should not (i.e., if you
9543: lie to the compiler), buggy code will be produced.
1.5 anton 9544:
1.44 crook 9545:
1.26 crook 9546: doc-unreachable
1.5 anton 9547:
1.44 crook 9548:
1.26 crook 9549: Another problem with this rule is that at @code{BEGIN}, the compiler
9550: does not know which locals will be visible on the incoming
9551: back-edge. All problems discussed in the following are due to this
9552: ignorance of the compiler (we discuss the problems using @code{BEGIN}
9553: loops as examples; the discussion also applies to @code{?DO} and other
9554: loops). Perhaps the most insidious example is:
1.5 anton 9555: @example
1.26 crook 9556: AHEAD
9557: BEGIN
9558: x
9559: [ 1 CS-ROLL ] THEN
9560: @{ x @}
9561: ...
9562: UNTIL
9563: @end example
1.5 anton 9564:
1.26 crook 9565: This should be legal according to the visibility rule. The use of
9566: @code{x} can only be reached through the definition; but that appears
9567: textually below the use.
1.5 anton 9568:
1.26 crook 9569: From this example it is clear that the visibility rules cannot be fully
9570: implemented without major headaches. Our implementation treats common
9571: cases as advertised and the exceptions are treated in a safe way: The
9572: compiler makes a reasonable guess about the locals visible after a
9573: @code{BEGIN}; if it is too pessimistic, the
9574: user will get a spurious error about the local not being defined; if the
9575: compiler is too optimistic, it will notice this later and issue a
9576: warning. In the case above the compiler would complain about @code{x}
9577: being undefined at its use. You can see from the obscure examples in
9578: this section that it takes quite unusual control structures to get the
9579: compiler into trouble, and even then it will often do fine.
1.5 anton 9580:
1.26 crook 9581: If the @code{BEGIN} is reachable from above, the most optimistic guess
9582: is that all locals visible before the @code{BEGIN} will also be
9583: visible after the @code{BEGIN}. This guess is valid for all loops that
9584: are entered only through the @code{BEGIN}, in particular, for normal
9585: @code{BEGIN}...@code{WHILE}...@code{REPEAT} and
9586: @code{BEGIN}...@code{UNTIL} loops and it is implemented in our
9587: compiler. When the branch to the @code{BEGIN} is finally generated by
9588: @code{AGAIN} or @code{UNTIL}, the compiler checks the guess and
9589: warns the user if it was too optimistic:
9590: @example
9591: IF
9592: @{ x @}
9593: BEGIN
9594: \ x ?
9595: [ 1 cs-roll ] THEN
9596: ...
9597: UNTIL
1.5 anton 9598: @end example
9599:
1.26 crook 9600: Here, @code{x} lives only until the @code{BEGIN}, but the compiler
9601: optimistically assumes that it lives until the @code{THEN}. It notices
9602: this difference when it compiles the @code{UNTIL} and issues a
9603: warning. The user can avoid the warning, and make sure that @code{x}
9604: is not used in the wrong area by using explicit scoping:
9605: @example
9606: IF
9607: SCOPE
9608: @{ x @}
9609: ENDSCOPE
9610: BEGIN
9611: [ 1 cs-roll ] THEN
9612: ...
9613: UNTIL
9614: @end example
1.5 anton 9615:
1.26 crook 9616: Since the guess is optimistic, there will be no spurious error messages
9617: about undefined locals.
1.5 anton 9618:
1.26 crook 9619: If the @code{BEGIN} is not reachable from above (e.g., after
9620: @code{AHEAD} or @code{EXIT}), the compiler cannot even make an
9621: optimistic guess, as the locals visible after the @code{BEGIN} may be
9622: defined later. Therefore, the compiler assumes that no locals are
9623: visible after the @code{BEGIN}. However, the user can use
9624: @code{ASSUME-LIVE} to make the compiler assume that the same locals are
9625: visible at the BEGIN as at the point where the top control-flow stack
9626: item was created.
1.5 anton 9627:
1.44 crook 9628:
1.26 crook 9629: doc-assume-live
1.5 anton 9630:
1.44 crook 9631:
9632: @noindent
1.26 crook 9633: E.g.,
1.5 anton 9634: @example
1.26 crook 9635: @{ x @}
9636: AHEAD
9637: ASSUME-LIVE
9638: BEGIN
9639: x
9640: [ 1 CS-ROLL ] THEN
9641: ...
9642: UNTIL
1.5 anton 9643: @end example
9644:
1.26 crook 9645: Other cases where the locals are defined before the @code{BEGIN} can be
9646: handled by inserting an appropriate @code{CS-ROLL} before the
9647: @code{ASSUME-LIVE} (and changing the control-flow stack manipulation
9648: behind the @code{ASSUME-LIVE}).
1.5 anton 9649:
1.26 crook 9650: Cases where locals are defined after the @code{BEGIN} (but should be
9651: visible immediately after the @code{BEGIN}) can only be handled by
9652: rearranging the loop. E.g., the ``most insidious'' example above can be
9653: arranged into:
1.5 anton 9654: @example
1.26 crook 9655: BEGIN
9656: @{ x @}
9657: ... 0=
9658: WHILE
9659: x
9660: REPEAT
1.5 anton 9661: @end example
9662:
1.26 crook 9663: @node How long do locals live?, Programming Style, Where are locals visible by name?, Gforth locals
9664: @subsubsection How long do locals live?
9665: @cindex locals lifetime
9666: @cindex lifetime of locals
1.5 anton 9667:
1.26 crook 9668: The right answer for the lifetime question would be: A local lives at
9669: least as long as it can be accessed. For a value-flavoured local this
9670: means: until the end of its visibility. However, a variable-flavoured
9671: local could be accessed through its address far beyond its visibility
9672: scope. Ultimately, this would mean that such locals would have to be
9673: garbage collected. Since this entails un-Forth-like implementation
9674: complexities, I adopted the same cowardly solution as some other
9675: languages (e.g., C): The local lives only as long as it is visible;
9676: afterwards its address is invalid (and programs that access it
9677: afterwards are erroneous).
1.5 anton 9678:
1.26 crook 9679: @node Programming Style, Implementation, How long do locals live?, Gforth locals
9680: @subsubsection Programming Style
9681: @cindex locals programming style
9682: @cindex programming style, locals
1.5 anton 9683:
1.26 crook 9684: The freedom to define locals anywhere has the potential to change
9685: programming styles dramatically. In particular, the need to use the
9686: return stack for intermediate storage vanishes. Moreover, all stack
9687: manipulations (except @code{PICK}s and @code{ROLL}s with run-time
9688: determined arguments) can be eliminated: If the stack items are in the
9689: wrong order, just write a locals definition for all of them; then
9690: write the items in the order you want.
1.5 anton 9691:
1.26 crook 9692: This seems a little far-fetched and eliminating stack manipulations is
9693: unlikely to become a conscious programming objective. Still, the number
9694: of stack manipulations will be reduced dramatically if local variables
1.49 anton 9695: are used liberally (e.g., compare @code{max} (@pxref{Gforth locals}) with
1.26 crook 9696: a traditional implementation of @code{max}).
1.5 anton 9697:
1.26 crook 9698: This shows one potential benefit of locals: making Forth programs more
9699: readable. Of course, this benefit will only be realized if the
9700: programmers continue to honour the principle of factoring instead of
9701: using the added latitude to make the words longer.
1.5 anton 9702:
1.26 crook 9703: @cindex single-assignment style for locals
9704: Using @code{TO} can and should be avoided. Without @code{TO},
9705: every value-flavoured local has only a single assignment and many
9706: advantages of functional languages apply to Forth. I.e., programs are
9707: easier to analyse, to optimize and to read: It is clear from the
9708: definition what the local stands for, it does not turn into something
9709: different later.
1.5 anton 9710:
1.26 crook 9711: E.g., a definition using @code{TO} might look like this:
1.5 anton 9712: @example
1.26 crook 9713: : strcmp @{ addr1 u1 addr2 u2 -- n @}
9714: u1 u2 min 0
9715: ?do
9716: addr1 c@@ addr2 c@@ -
9717: ?dup-if
9718: unloop exit
9719: then
9720: addr1 char+ TO addr1
9721: addr2 char+ TO addr2
9722: loop
9723: u1 u2 - ;
1.5 anton 9724: @end example
1.26 crook 9725: Here, @code{TO} is used to update @code{addr1} and @code{addr2} at
9726: every loop iteration. @code{strcmp} is a typical example of the
9727: readability problems of using @code{TO}. When you start reading
9728: @code{strcmp}, you think that @code{addr1} refers to the start of the
9729: string. Only near the end of the loop you realize that it is something
9730: else.
1.5 anton 9731:
1.26 crook 9732: This can be avoided by defining two locals at the start of the loop that
9733: are initialized with the right value for the current iteration.
1.5 anton 9734: @example
1.26 crook 9735: : strcmp @{ addr1 u1 addr2 u2 -- n @}
9736: addr1 addr2
9737: u1 u2 min 0
9738: ?do @{ s1 s2 @}
9739: s1 c@@ s2 c@@ -
9740: ?dup-if
9741: unloop exit
9742: then
9743: s1 char+ s2 char+
9744: loop
9745: 2drop
9746: u1 u2 - ;
1.5 anton 9747: @end example
1.26 crook 9748: Here it is clear from the start that @code{s1} has a different value
9749: in every loop iteration.
1.5 anton 9750:
1.26 crook 9751: @node Implementation, , Programming Style, Gforth locals
9752: @subsubsection Implementation
9753: @cindex locals implementation
9754: @cindex implementation of locals
1.5 anton 9755:
1.26 crook 9756: @cindex locals stack
9757: Gforth uses an extra locals stack. The most compelling reason for
9758: this is that the return stack is not float-aligned; using an extra stack
9759: also eliminates the problems and restrictions of using the return stack
9760: as locals stack. Like the other stacks, the locals stack grows toward
9761: lower addresses. A few primitives allow an efficient implementation:
1.5 anton 9762:
1.44 crook 9763:
1.26 crook 9764: doc-@local#
9765: doc-f@local#
9766: doc-laddr#
9767: doc-lp+!#
9768: doc-lp!
9769: doc->l
9770: doc-f>l
1.5 anton 9771:
1.44 crook 9772:
1.26 crook 9773: In addition to these primitives, some specializations of these
9774: primitives for commonly occurring inline arguments are provided for
9775: efficiency reasons, e.g., @code{@@local0} as specialization of
9776: @code{@@local#} for the inline argument 0. The following compiling words
9777: compile the right specialized version, or the general version, as
9778: appropriate:
1.6 pazsan 9779:
1.44 crook 9780:
1.26 crook 9781: doc-compile-@local
9782: doc-compile-f@local
9783: doc-compile-lp+!
1.12 anton 9784:
1.44 crook 9785:
1.26 crook 9786: Combinations of conditional branches and @code{lp+!#} like
9787: @code{?branch-lp+!#} (the locals pointer is only changed if the branch
9788: is taken) are provided for efficiency and correctness in loops.
1.6 pazsan 9789:
1.26 crook 9790: A special area in the dictionary space is reserved for keeping the
9791: local variable names. @code{@{} switches the dictionary pointer to this
9792: area and @code{@}} switches it back and generates the locals
9793: initializing code. @code{W:} etc.@ are normal defining words. This
9794: special area is cleared at the start of every colon definition.
1.6 pazsan 9795:
1.26 crook 9796: @cindex word list for defining locals
9797: A special feature of Gforth's dictionary is used to implement the
9798: definition of locals without type specifiers: every word list (aka
9799: vocabulary) has its own methods for searching
9800: etc. (@pxref{Word Lists}). For the present purpose we defined a word list
9801: with a special search method: When it is searched for a word, it
9802: actually creates that word using @code{W:}. @code{@{} changes the search
9803: order to first search the word list containing @code{@}}, @code{W:} etc.,
9804: and then the word list for defining locals without type specifiers.
1.12 anton 9805:
1.26 crook 9806: The lifetime rules support a stack discipline within a colon
9807: definition: The lifetime of a local is either nested with other locals
9808: lifetimes or it does not overlap them.
1.6 pazsan 9809:
1.26 crook 9810: At @code{BEGIN}, @code{IF}, and @code{AHEAD} no code for locals stack
9811: pointer manipulation is generated. Between control structure words
9812: locals definitions can push locals onto the locals stack. @code{AGAIN}
9813: is the simplest of the other three control flow words. It has to
9814: restore the locals stack depth of the corresponding @code{BEGIN}
9815: before branching. The code looks like this:
9816: @format
9817: @code{lp+!#} current-locals-size @minus{} dest-locals-size
9818: @code{branch} <begin>
9819: @end format
1.6 pazsan 9820:
1.26 crook 9821: @code{UNTIL} is a little more complicated: If it branches back, it
9822: must adjust the stack just like @code{AGAIN}. But if it falls through,
9823: the locals stack must not be changed. The compiler generates the
9824: following code:
9825: @format
9826: @code{?branch-lp+!#} <begin> current-locals-size @minus{} dest-locals-size
9827: @end format
9828: The locals stack pointer is only adjusted if the branch is taken.
1.6 pazsan 9829:
1.26 crook 9830: @code{THEN} can produce somewhat inefficient code:
9831: @format
9832: @code{lp+!#} current-locals-size @minus{} orig-locals-size
9833: <orig target>:
9834: @code{lp+!#} orig-locals-size @minus{} new-locals-size
9835: @end format
9836: The second @code{lp+!#} adjusts the locals stack pointer from the
1.29 crook 9837: level at the @i{orig} point to the level after the @code{THEN}. The
1.26 crook 9838: first @code{lp+!#} adjusts the locals stack pointer from the current
9839: level to the level at the orig point, so the complete effect is an
9840: adjustment from the current level to the right level after the
9841: @code{THEN}.
1.6 pazsan 9842:
1.26 crook 9843: @cindex locals information on the control-flow stack
9844: @cindex control-flow stack items, locals information
9845: In a conventional Forth implementation a dest control-flow stack entry
9846: is just the target address and an orig entry is just the address to be
9847: patched. Our locals implementation adds a word list to every orig or dest
9848: item. It is the list of locals visible (or assumed visible) at the point
9849: described by the entry. Our implementation also adds a tag to identify
9850: the kind of entry, in particular to differentiate between live and dead
9851: (reachable and unreachable) orig entries.
1.6 pazsan 9852:
1.26 crook 9853: A few unusual operations have to be performed on locals word lists:
1.6 pazsan 9854:
1.44 crook 9855:
1.26 crook 9856: doc-common-list
9857: doc-sub-list?
9858: doc-list-size
1.6 pazsan 9859:
1.44 crook 9860:
1.26 crook 9861: Several features of our locals word list implementation make these
9862: operations easy to implement: The locals word lists are organised as
9863: linked lists; the tails of these lists are shared, if the lists
9864: contain some of the same locals; and the address of a name is greater
9865: than the address of the names behind it in the list.
1.6 pazsan 9866:
1.26 crook 9867: Another important implementation detail is the variable
9868: @code{dead-code}. It is used by @code{BEGIN} and @code{THEN} to
9869: determine if they can be reached directly or only through the branch
9870: that they resolve. @code{dead-code} is set by @code{UNREACHABLE},
9871: @code{AHEAD}, @code{EXIT} etc., and cleared at the start of a colon
9872: definition, by @code{BEGIN} and usually by @code{THEN}.
1.6 pazsan 9873:
1.26 crook 9874: Counted loops are similar to other loops in most respects, but
9875: @code{LEAVE} requires special attention: It performs basically the same
9876: service as @code{AHEAD}, but it does not create a control-flow stack
9877: entry. Therefore the information has to be stored elsewhere;
9878: traditionally, the information was stored in the target fields of the
9879: branches created by the @code{LEAVE}s, by organizing these fields into a
9880: linked list. Unfortunately, this clever trick does not provide enough
9881: space for storing our extended control flow information. Therefore, we
9882: introduce another stack, the leave stack. It contains the control-flow
9883: stack entries for all unresolved @code{LEAVE}s.
1.6 pazsan 9884:
1.26 crook 9885: Local names are kept until the end of the colon definition, even if
9886: they are no longer visible in any control-flow path. In a few cases
9887: this may lead to increased space needs for the locals name area, but
9888: usually less than reclaiming this space would cost in code size.
1.6 pazsan 9889:
9890:
1.26 crook 9891: @node ANS Forth locals, , Gforth locals, Locals
9892: @subsection ANS Forth locals
9893: @cindex locals, ANS Forth style
1.6 pazsan 9894:
1.26 crook 9895: The ANS Forth locals wordset does not define a syntax for locals, but
9896: words that make it possible to define various syntaxes. One of the
9897: possible syntaxes is a subset of the syntax we used in the Gforth locals
9898: wordset, i.e.:
1.6 pazsan 9899:
9900: @example
1.26 crook 9901: @{ local1 local2 ... -- comment @}
1.6 pazsan 9902: @end example
1.23 crook 9903: @noindent
1.26 crook 9904: or
1.6 pazsan 9905: @example
1.26 crook 9906: @{ local1 local2 ... @}
1.6 pazsan 9907: @end example
9908:
1.26 crook 9909: The order of the locals corresponds to the order in a stack comment. The
9910: restrictions are:
1.6 pazsan 9911:
9912: @itemize @bullet
9913: @item
1.26 crook 9914: Locals can only be cell-sized values (no type specifiers are allowed).
1.6 pazsan 9915: @item
1.26 crook 9916: Locals can be defined only outside control structures.
1.6 pazsan 9917: @item
1.26 crook 9918: Locals can interfere with explicit usage of the return stack. For the
9919: exact (and long) rules, see the standard. If you don't use return stack
9920: accessing words in a definition using locals, you will be all right. The
9921: purpose of this rule is to make locals implementation on the return
9922: stack easier.
1.6 pazsan 9923: @item
1.26 crook 9924: The whole definition must be in one line.
9925: @end itemize
1.6 pazsan 9926:
1.44 crook 9927: Locals defined in this way behave like @code{VALUE}s
1.49 anton 9928: (@pxref{Values}). I.e., they are initialized from the stack. Using their
1.26 crook 9929: name produces their value. Their value can be changed using @code{TO}.
1.6 pazsan 9930:
1.26 crook 9931: Since this syntax is supported by Gforth directly, you need not do
9932: anything to use it. If you want to port a program using this syntax to
9933: another ANS Forth system, use @file{compat/anslocal.fs} to implement the
9934: syntax on the other system.
1.6 pazsan 9935:
1.26 crook 9936: Note that a syntax shown in the standard, section A.13 looks
9937: similar, but is quite different in having the order of locals
9938: reversed. Beware!
1.6 pazsan 9939:
1.26 crook 9940: The ANS Forth locals wordset itself consists of a word:
1.6 pazsan 9941:
1.44 crook 9942:
1.26 crook 9943: doc-(local)
1.6 pazsan 9944:
1.44 crook 9945:
1.26 crook 9946: The ANS Forth locals extension wordset defines a syntax using @code{locals|}, but it is so
9947: awful that we strongly recommend not to use it. We have implemented this
9948: syntax to make porting to Gforth easy, but do not document it here. The
9949: problem with this syntax is that the locals are defined in an order
9950: reversed with respect to the standard stack comment notation, making
9951: programs harder to read, and easier to misread and miswrite. The only
9952: merit of this syntax is that it is easy to implement using the ANS Forth
9953: locals wordset.
1.7 pazsan 9954:
9955:
1.26 crook 9956: @c ----------------------------------------------------------
9957: @node Structures, Object-oriented Forth, Locals, Words
9958: @section Structures
9959: @cindex structures
9960: @cindex records
1.7 pazsan 9961:
1.26 crook 9962: This section presents the structure package that comes with Gforth. A
9963: version of the package implemented in ANS Forth is available in
9964: @file{compat/struct.fs}. This package was inspired by a posting on
9965: comp.lang.forth in 1989 (unfortunately I don't remember, by whom;
9966: possibly John Hayes). A version of this section has been published in
9967: ???. Marcel Hendrix provided helpful comments.
1.7 pazsan 9968:
1.26 crook 9969: @menu
9970: * Why explicit structure support?::
9971: * Structure Usage::
9972: * Structure Naming Convention::
9973: * Structure Implementation::
9974: * Structure Glossary::
9975: @end menu
1.7 pazsan 9976:
1.26 crook 9977: @node Why explicit structure support?, Structure Usage, Structures, Structures
9978: @subsection Why explicit structure support?
1.7 pazsan 9979:
1.26 crook 9980: @cindex address arithmetic for structures
9981: @cindex structures using address arithmetic
9982: If we want to use a structure containing several fields, we could simply
9983: reserve memory for it, and access the fields using address arithmetic
1.32 anton 9984: (@pxref{Address arithmetic}). As an example, consider a structure with
1.26 crook 9985: the following fields
1.7 pazsan 9986:
1.26 crook 9987: @table @code
9988: @item a
9989: is a float
9990: @item b
9991: is a cell
9992: @item c
9993: is a float
9994: @end table
1.7 pazsan 9995:
1.26 crook 9996: Given the (float-aligned) base address of the structure we get the
9997: address of the field
1.13 pazsan 9998:
1.26 crook 9999: @table @code
10000: @item a
10001: without doing anything further.
10002: @item b
10003: with @code{float+}
10004: @item c
10005: with @code{float+ cell+ faligned}
10006: @end table
1.13 pazsan 10007:
1.26 crook 10008: It is easy to see that this can become quite tiring.
1.13 pazsan 10009:
1.26 crook 10010: Moreover, it is not very readable, because seeing a
10011: @code{cell+} tells us neither which kind of structure is
10012: accessed nor what field is accessed; we have to somehow infer the kind
10013: of structure, and then look up in the documentation, which field of
10014: that structure corresponds to that offset.
1.13 pazsan 10015:
1.26 crook 10016: Finally, this kind of address arithmetic also causes maintenance
10017: troubles: If you add or delete a field somewhere in the middle of the
10018: structure, you have to find and change all computations for the fields
10019: afterwards.
1.13 pazsan 10020:
1.26 crook 10021: So, instead of using @code{cell+} and friends directly, how
10022: about storing the offsets in constants:
1.13 pazsan 10023:
10024: @example
1.26 crook 10025: 0 constant a-offset
10026: 0 float+ constant b-offset
10027: 0 float+ cell+ faligned c-offset
1.13 pazsan 10028: @end example
10029:
1.26 crook 10030: Now we can get the address of field @code{x} with @code{x-offset
10031: +}. This is much better in all respects. Of course, you still
10032: have to change all later offset definitions if you add a field. You can
10033: fix this by declaring the offsets in the following way:
1.13 pazsan 10034:
10035: @example
1.26 crook 10036: 0 constant a-offset
10037: a-offset float+ constant b-offset
10038: b-offset cell+ faligned constant c-offset
1.13 pazsan 10039: @end example
10040:
1.26 crook 10041: Since we always use the offsets with @code{+}, we could use a defining
10042: word @code{cfield} that includes the @code{+} in the action of the
10043: defined word:
1.8 pazsan 10044:
10045: @example
1.26 crook 10046: : cfield ( n "name" -- )
10047: create ,
10048: does> ( name execution: addr1 -- addr2 )
10049: @@ + ;
1.13 pazsan 10050:
1.26 crook 10051: 0 cfield a
10052: 0 a float+ cfield b
10053: 0 b cell+ faligned cfield c
1.13 pazsan 10054: @end example
10055:
1.26 crook 10056: Instead of @code{x-offset +}, we now simply write @code{x}.
10057:
10058: The structure field words now can be used quite nicely. However,
10059: their definition is still a bit cumbersome: We have to repeat the
10060: name, the information about size and alignment is distributed before
10061: and after the field definitions etc. The structure package presented
10062: here addresses these problems.
10063:
10064: @node Structure Usage, Structure Naming Convention, Why explicit structure support?, Structures
10065: @subsection Structure Usage
10066: @cindex structure usage
1.13 pazsan 10067:
1.26 crook 10068: @cindex @code{field} usage
10069: @cindex @code{struct} usage
10070: @cindex @code{end-struct} usage
10071: You can define a structure for a (data-less) linked list with:
1.13 pazsan 10072: @example
1.26 crook 10073: struct
10074: cell% field list-next
10075: end-struct list%
1.13 pazsan 10076: @end example
10077:
1.26 crook 10078: With the address of the list node on the stack, you can compute the
10079: address of the field that contains the address of the next node with
10080: @code{list-next}. E.g., you can determine the length of a list
10081: with:
1.13 pazsan 10082:
10083: @example
1.26 crook 10084: : list-length ( list -- n )
10085: \ "list" is a pointer to the first element of a linked list
10086: \ "n" is the length of the list
10087: 0 BEGIN ( list1 n1 )
10088: over
10089: WHILE ( list1 n1 )
10090: 1+ swap list-next @@ swap
10091: REPEAT
10092: nip ;
1.13 pazsan 10093: @end example
10094:
1.26 crook 10095: You can reserve memory for a list node in the dictionary with
10096: @code{list% %allot}, which leaves the address of the list node on the
10097: stack. For the equivalent allocation on the heap you can use @code{list%
10098: %alloc} (or, for an @code{allocate}-like stack effect (i.e., with ior),
10099: use @code{list% %allocate}). You can get the the size of a list
10100: node with @code{list% %size} and its alignment with @code{list%
10101: %alignment}.
1.13 pazsan 10102:
1.26 crook 10103: Note that in ANS Forth the body of a @code{create}d word is
10104: @code{aligned} but not necessarily @code{faligned};
10105: therefore, if you do a:
1.13 pazsan 10106: @example
1.26 crook 10107: create @emph{name} foo% %allot
1.8 pazsan 10108: @end example
10109:
1.26 crook 10110: @noindent
10111: then the memory alloted for @code{foo%} is
10112: guaranteed to start at the body of @code{@emph{name}} only if
10113: @code{foo%} contains only character, cell and double fields.
1.20 pazsan 10114:
1.45 crook 10115: @cindex structures containing structures
1.26 crook 10116: You can include a structure @code{foo%} as a field of
10117: another structure, like this:
1.20 pazsan 10118: @example
1.26 crook 10119: struct
10120: ...
10121: foo% field ...
10122: ...
10123: end-struct ...
1.20 pazsan 10124: @end example
10125:
1.26 crook 10126: @cindex structure extension
10127: @cindex extended records
10128: Instead of starting with an empty structure, you can extend an
10129: existing structure. E.g., a plain linked list without data, as defined
10130: above, is hardly useful; You can extend it to a linked list of integers,
10131: like this:@footnote{This feature is also known as @emph{extended
10132: records}. It is the main innovation in the Oberon language; in other
10133: words, adding this feature to Modula-2 led Wirth to create a new
10134: language, write a new compiler etc. Adding this feature to Forth just
10135: required a few lines of code.}
1.20 pazsan 10136:
10137: @example
1.26 crook 10138: list%
10139: cell% field intlist-int
10140: end-struct intlist%
1.20 pazsan 10141: @end example
10142:
1.26 crook 10143: @code{intlist%} is a structure with two fields:
10144: @code{list-next} and @code{intlist-int}.
1.20 pazsan 10145:
1.26 crook 10146: @cindex structures containing arrays
10147: You can specify an array type containing @emph{n} elements of
10148: type @code{foo%} like this:
1.20 pazsan 10149:
10150: @example
1.26 crook 10151: foo% @emph{n} *
1.20 pazsan 10152: @end example
10153:
1.26 crook 10154: You can use this array type in any place where you can use a normal
10155: type, e.g., when defining a @code{field}, or with
10156: @code{%allot}.
1.20 pazsan 10157:
1.26 crook 10158: @cindex first field optimization
10159: The first field is at the base address of a structure and the word
10160: for this field (e.g., @code{list-next}) actually does not change
10161: the address on the stack. You may be tempted to leave it away in the
10162: interest of run-time and space efficiency. This is not necessary,
10163: because the structure package optimizes this case and compiling such
10164: words does not generate any code. So, in the interest of readability
10165: and maintainability you should include the word for the field when
10166: accessing the field.
1.20 pazsan 10167:
1.26 crook 10168: @node Structure Naming Convention, Structure Implementation, Structure Usage, Structures
10169: @subsection Structure Naming Convention
10170: @cindex structure naming convention
1.20 pazsan 10171:
1.26 crook 10172: The field names that come to (my) mind are often quite generic, and,
10173: if used, would cause frequent name clashes. E.g., many structures
10174: probably contain a @code{counter} field. The structure names
10175: that come to (my) mind are often also the logical choice for the names
10176: of words that create such a structure.
1.20 pazsan 10177:
1.26 crook 10178: Therefore, I have adopted the following naming conventions:
1.20 pazsan 10179:
1.26 crook 10180: @itemize @bullet
10181: @cindex field naming convention
10182: @item
10183: The names of fields are of the form
10184: @code{@emph{struct}-@emph{field}}, where
10185: @code{@emph{struct}} is the basic name of the structure, and
10186: @code{@emph{field}} is the basic name of the field. You can
10187: think of field words as converting the (address of the)
10188: structure into the (address of the) field.
1.20 pazsan 10189:
1.26 crook 10190: @cindex structure naming convention
10191: @item
10192: The names of structures are of the form
10193: @code{@emph{struct}%}, where
10194: @code{@emph{struct}} is the basic name of the structure.
10195: @end itemize
1.20 pazsan 10196:
1.26 crook 10197: This naming convention does not work that well for fields of extended
10198: structures; e.g., the integer list structure has a field
10199: @code{intlist-int}, but has @code{list-next}, not
10200: @code{intlist-next}.
1.20 pazsan 10201:
1.26 crook 10202: @node Structure Implementation, Structure Glossary, Structure Naming Convention, Structures
10203: @subsection Structure Implementation
10204: @cindex structure implementation
10205: @cindex implementation of structures
1.20 pazsan 10206:
1.26 crook 10207: The central idea in the implementation is to pass the data about the
10208: structure being built on the stack, not in some global
10209: variable. Everything else falls into place naturally once this design
10210: decision is made.
1.20 pazsan 10211:
1.26 crook 10212: The type description on the stack is of the form @emph{align
10213: size}. Keeping the size on the top-of-stack makes dealing with arrays
10214: very simple.
1.20 pazsan 10215:
1.26 crook 10216: @code{field} is a defining word that uses @code{Create}
10217: and @code{DOES>}. The body of the field contains the offset
10218: of the field, and the normal @code{DOES>} action is simply:
1.20 pazsan 10219:
10220: @example
1.48 anton 10221: @@ +
1.20 pazsan 10222: @end example
10223:
1.23 crook 10224: @noindent
1.26 crook 10225: i.e., add the offset to the address, giving the stack effect
1.29 crook 10226: @i{addr1 -- addr2} for a field.
1.20 pazsan 10227:
1.26 crook 10228: @cindex first field optimization, implementation
10229: This simple structure is slightly complicated by the optimization
10230: for fields with offset 0, which requires a different
10231: @code{DOES>}-part (because we cannot rely on there being
10232: something on the stack if such a field is invoked during
10233: compilation). Therefore, we put the different @code{DOES>}-parts
10234: in separate words, and decide which one to invoke based on the
10235: offset. For a zero offset, the field is basically a noop; it is
10236: immediate, and therefore no code is generated when it is compiled.
1.20 pazsan 10237:
1.26 crook 10238: @node Structure Glossary, , Structure Implementation, Structures
10239: @subsection Structure Glossary
10240: @cindex structure glossary
1.20 pazsan 10241:
1.44 crook 10242:
1.26 crook 10243: doc-%align
10244: doc-%alignment
10245: doc-%alloc
10246: doc-%allocate
10247: doc-%allot
10248: doc-cell%
10249: doc-char%
10250: doc-dfloat%
10251: doc-double%
10252: doc-end-struct
10253: doc-field
10254: doc-float%
10255: doc-naligned
10256: doc-sfloat%
10257: doc-%size
10258: doc-struct
1.23 crook 10259:
1.44 crook 10260:
1.26 crook 10261: @c -------------------------------------------------------------
10262: @node Object-oriented Forth, Passing Commands to the OS, Structures, Words
10263: @section Object-oriented Forth
1.20 pazsan 10264:
1.26 crook 10265: Gforth comes with three packages for object-oriented programming:
10266: @file{objects.fs}, @file{oof.fs}, and @file{mini-oof.fs}; none of them
10267: is preloaded, so you have to @code{include} them before use. The most
10268: important differences between these packages (and others) are discussed
10269: in @ref{Comparison with other object models}. All packages are written
10270: in ANS Forth and can be used with any other ANS Forth.
1.20 pazsan 10271:
1.26 crook 10272: @menu
1.48 anton 10273: * Why object-oriented programming?::
10274: * Object-Oriented Terminology::
10275: * Objects::
10276: * OOF::
10277: * Mini-OOF::
1.26 crook 10278: * Comparison with other object models::
10279: @end menu
1.20 pazsan 10280:
1.48 anton 10281: @c ----------------------------------------------------------------
10282: @node Why object-oriented programming?, Object-Oriented Terminology, Object-oriented Forth, Object-oriented Forth
10283: @subsection Why object-oriented programming?
1.26 crook 10284: @cindex object-oriented programming motivation
10285: @cindex motivation for object-oriented programming
1.23 crook 10286:
1.26 crook 10287: Often we have to deal with several data structures (@emph{objects}),
10288: that have to be treated similarly in some respects, but differently in
10289: others. Graphical objects are the textbook example: circles, triangles,
10290: dinosaurs, icons, and others, and we may want to add more during program
10291: development. We want to apply some operations to any graphical object,
10292: e.g., @code{draw} for displaying it on the screen. However, @code{draw}
10293: has to do something different for every kind of object.
10294: @comment TODO add some other operations eg perimeter, area
10295: @comment and tie in to concrete examples later..
1.23 crook 10296:
1.26 crook 10297: We could implement @code{draw} as a big @code{CASE}
10298: control structure that executes the appropriate code depending on the
10299: kind of object to be drawn. This would be not be very elegant, and,
10300: moreover, we would have to change @code{draw} every time we add
10301: a new kind of graphical object (say, a spaceship).
1.23 crook 10302:
1.26 crook 10303: What we would rather do is: When defining spaceships, we would tell
10304: the system: ``Here's how you @code{draw} a spaceship; you figure
10305: out the rest''.
1.23 crook 10306:
1.26 crook 10307: This is the problem that all systems solve that (rightfully) call
10308: themselves object-oriented; the object-oriented packages presented here
10309: solve this problem (and not much else).
10310: @comment TODO ?list properties of oo systems.. oo vs o-based?
1.23 crook 10311:
1.48 anton 10312: @c ------------------------------------------------------------------------
1.26 crook 10313: @node Object-Oriented Terminology, Objects, Why object-oriented programming?, Object-oriented Forth
1.48 anton 10314: @subsection Object-Oriented Terminology
1.26 crook 10315: @cindex object-oriented terminology
10316: @cindex terminology for object-oriented programming
1.23 crook 10317:
1.26 crook 10318: This section is mainly for reference, so you don't have to understand
10319: all of it right away. The terminology is mainly Smalltalk-inspired. In
10320: short:
1.23 crook 10321:
1.26 crook 10322: @table @emph
10323: @cindex class
10324: @item class
10325: a data structure definition with some extras.
1.23 crook 10326:
1.26 crook 10327: @cindex object
10328: @item object
10329: an instance of the data structure described by the class definition.
1.23 crook 10330:
1.26 crook 10331: @cindex instance variables
10332: @item instance variables
10333: fields of the data structure.
1.23 crook 10334:
1.26 crook 10335: @cindex selector
10336: @cindex method selector
10337: @cindex virtual function
10338: @item selector
10339: (or @emph{method selector}) a word (e.g.,
10340: @code{draw}) that performs an operation on a variety of data
10341: structures (classes). A selector describes @emph{what} operation to
10342: perform. In C++ terminology: a (pure) virtual function.
1.23 crook 10343:
1.26 crook 10344: @cindex method
10345: @item method
10346: the concrete definition that performs the operation
10347: described by the selector for a specific class. A method specifies
10348: @emph{how} the operation is performed for a specific class.
1.23 crook 10349:
1.26 crook 10350: @cindex selector invocation
10351: @cindex message send
10352: @cindex invoking a selector
10353: @item selector invocation
10354: a call of a selector. One argument of the call (the TOS (top-of-stack))
10355: is used for determining which method is used. In Smalltalk terminology:
10356: a message (consisting of the selector and the other arguments) is sent
10357: to the object.
1.1 anton 10358:
1.26 crook 10359: @cindex receiving object
10360: @item receiving object
10361: the object used for determining the method executed by a selector
10362: invocation. In the @file{objects.fs} model, it is the object that is on
10363: the TOS when the selector is invoked. (@emph{Receiving} comes from
10364: the Smalltalk @emph{message} terminology.)
1.1 anton 10365:
1.26 crook 10366: @cindex child class
10367: @cindex parent class
10368: @cindex inheritance
10369: @item child class
10370: a class that has (@emph{inherits}) all properties (instance variables,
10371: selectors, methods) from a @emph{parent class}. In Smalltalk
10372: terminology: The subclass inherits from the superclass. In C++
10373: terminology: The derived class inherits from the base class.
1.1 anton 10374:
1.26 crook 10375: @end table
1.21 crook 10376:
1.26 crook 10377: @c If you wonder about the message sending terminology, it comes from
10378: @c a time when each object had it's own task and objects communicated via
10379: @c message passing; eventually the Smalltalk developers realized that
10380: @c they can do most things through simple (indirect) calls. They kept the
10381: @c terminology.
1.1 anton 10382:
1.48 anton 10383: @c --------------------------------------------------------------
1.26 crook 10384: @node Objects, OOF, Object-Oriented Terminology, Object-oriented Forth
10385: @subsection The @file{objects.fs} model
10386: @cindex objects
10387: @cindex object-oriented programming
1.1 anton 10388:
1.26 crook 10389: @cindex @file{objects.fs}
10390: @cindex @file{oof.fs}
1.1 anton 10391:
1.37 anton 10392: This section describes the @file{objects.fs} package. This material also
1.66 anton 10393: has been published in M. Anton Ertl,
10394: @cite{@uref{http://www.complang.tuwien.ac.at/forth/objects/objects.html,
10395: Yet Another Forth Objects Package}}, Forth Dimensions 19(2), pages
10396: 37--43.
1.26 crook 10397: @c McKewan's and Zsoter's packages
1.1 anton 10398:
1.26 crook 10399: This section assumes that you have read @ref{Structures}.
1.1 anton 10400:
1.26 crook 10401: The techniques on which this model is based have been used to implement
10402: the parser generator, Gray, and have also been used in Gforth for
10403: implementing the various flavours of word lists (hashed or not,
10404: case-sensitive or not, special-purpose word lists for locals etc.).
1.1 anton 10405:
10406:
1.26 crook 10407: @menu
10408: * Properties of the Objects model::
10409: * Basic Objects Usage::
1.37 anton 10410: * The Objects base class::
1.26 crook 10411: * Creating objects::
10412: * Object-Oriented Programming Style::
10413: * Class Binding::
10414: * Method conveniences::
10415: * Classes and Scoping::
1.37 anton 10416: * Dividing classes::
1.26 crook 10417: * Object Interfaces::
10418: * Objects Implementation::
10419: * Objects Glossary::
10420: @end menu
1.1 anton 10421:
1.26 crook 10422: Marcel Hendrix provided helpful comments on this section. Andras Zsoter
10423: and Bernd Paysan helped me with the related works section.
1.1 anton 10424:
1.26 crook 10425: @node Properties of the Objects model, Basic Objects Usage, Objects, Objects
10426: @subsubsection Properties of the @file{objects.fs} model
10427: @cindex @file{objects.fs} properties
1.1 anton 10428:
1.26 crook 10429: @itemize @bullet
10430: @item
10431: It is straightforward to pass objects on the stack. Passing
10432: selectors on the stack is a little less convenient, but possible.
1.1 anton 10433:
1.26 crook 10434: @item
10435: Objects are just data structures in memory, and are referenced by their
10436: address. You can create words for objects with normal defining words
10437: like @code{constant}. Likewise, there is no difference between instance
10438: variables that contain objects and those that contain other data.
1.1 anton 10439:
1.26 crook 10440: @item
10441: Late binding is efficient and easy to use.
1.21 crook 10442:
1.26 crook 10443: @item
10444: It avoids parsing, and thus avoids problems with state-smartness
10445: and reduced extensibility; for convenience there are a few parsing
10446: words, but they have non-parsing counterparts. There are also a few
10447: defining words that parse. This is hard to avoid, because all standard
10448: defining words parse (except @code{:noname}); however, such
10449: words are not as bad as many other parsing words, because they are not
10450: state-smart.
1.21 crook 10451:
1.26 crook 10452: @item
10453: It does not try to incorporate everything. It does a few things and does
10454: them well (IMO). In particular, this model was not designed to support
10455: information hiding (although it has features that may help); you can use
10456: a separate package for achieving this.
1.21 crook 10457:
1.26 crook 10458: @item
10459: It is layered; you don't have to learn and use all features to use this
1.49 anton 10460: model. Only a few features are necessary (@pxref{Basic Objects Usage},
10461: @pxref{The Objects base class}, @pxref{Creating objects}.), the others
1.26 crook 10462: are optional and independent of each other.
1.21 crook 10463:
1.26 crook 10464: @item
10465: An implementation in ANS Forth is available.
1.21 crook 10466:
1.26 crook 10467: @end itemize
1.21 crook 10468:
10469:
1.26 crook 10470: @node Basic Objects Usage, The Objects base class, Properties of the Objects model, Objects
10471: @subsubsection Basic @file{objects.fs} Usage
10472: @cindex basic objects usage
10473: @cindex objects, basic usage
1.21 crook 10474:
1.26 crook 10475: You can define a class for graphical objects like this:
1.21 crook 10476:
1.26 crook 10477: @cindex @code{class} usage
10478: @cindex @code{end-class} usage
10479: @cindex @code{selector} usage
10480: @example
10481: object class \ "object" is the parent class
10482: selector draw ( x y graphical -- )
10483: end-class graphical
10484: @end example
1.21 crook 10485:
1.26 crook 10486: This code defines a class @code{graphical} with an
10487: operation @code{draw}. We can perform the operation
10488: @code{draw} on any @code{graphical} object, e.g.:
1.21 crook 10489:
1.26 crook 10490: @example
10491: 100 100 t-rex draw
10492: @end example
1.21 crook 10493:
1.26 crook 10494: @noindent
10495: where @code{t-rex} is a word (say, a constant) that produces a
10496: graphical object.
1.21 crook 10497:
1.29 crook 10498: @comment TODO add a 2nd operation eg perimeter.. and use for
1.26 crook 10499: @comment a concrete example
1.21 crook 10500:
1.26 crook 10501: @cindex abstract class
10502: How do we create a graphical object? With the present definitions,
10503: we cannot create a useful graphical object. The class
10504: @code{graphical} describes graphical objects in general, but not
10505: any concrete graphical object type (C++ users would call it an
10506: @emph{abstract class}); e.g., there is no method for the selector
10507: @code{draw} in the class @code{graphical}.
1.21 crook 10508:
1.26 crook 10509: For concrete graphical objects, we define child classes of the
10510: class @code{graphical}, e.g.:
1.21 crook 10511:
1.26 crook 10512: @cindex @code{overrides} usage
10513: @cindex @code{field} usage in class definition
10514: @example
10515: graphical class \ "graphical" is the parent class
10516: cell% field circle-radius
1.21 crook 10517:
1.26 crook 10518: :noname ( x y circle -- )
10519: circle-radius @@ draw-circle ;
10520: overrides draw
1.21 crook 10521:
1.26 crook 10522: :noname ( n-radius circle -- )
10523: circle-radius ! ;
10524: overrides construct
1.21 crook 10525:
1.26 crook 10526: end-class circle
1.21 crook 10527: @end example
10528:
1.26 crook 10529: Here we define a class @code{circle} as a child of @code{graphical},
10530: with field @code{circle-radius} (which behaves just like a field
10531: (@pxref{Structures}); it defines (using @code{overrides}) new methods
10532: for the selectors @code{draw} and @code{construct} (@code{construct} is
10533: defined in @code{object}, the parent class of @code{graphical}).
1.21 crook 10534:
1.26 crook 10535: Now we can create a circle on the heap (i.e.,
10536: @code{allocate}d memory) with:
1.21 crook 10537:
1.26 crook 10538: @cindex @code{heap-new} usage
1.21 crook 10539: @example
1.26 crook 10540: 50 circle heap-new constant my-circle
10541: @end example
1.21 crook 10542:
1.26 crook 10543: @noindent
10544: @code{heap-new} invokes @code{construct}, thus
10545: initializing the field @code{circle-radius} with 50. We can draw
10546: this new circle at (100,100) with:
1.21 crook 10547:
1.26 crook 10548: @example
10549: 100 100 my-circle draw
1.21 crook 10550: @end example
10551:
1.26 crook 10552: @cindex selector invocation, restrictions
10553: @cindex class definition, restrictions
10554: Note: You can only invoke a selector if the object on the TOS
10555: (the receiving object) belongs to the class where the selector was
10556: defined or one of its descendents; e.g., you can invoke
10557: @code{draw} only for objects belonging to @code{graphical}
10558: or its descendents (e.g., @code{circle}). Immediately before
10559: @code{end-class}, the search order has to be the same as
10560: immediately after @code{class}.
1.21 crook 10561:
1.26 crook 10562: @node The Objects base class, Creating objects, Basic Objects Usage, Objects
10563: @subsubsection The @file{object.fs} base class
10564: @cindex @code{object} class
1.21 crook 10565:
1.26 crook 10566: When you define a class, you have to specify a parent class. So how do
10567: you start defining classes? There is one class available from the start:
10568: @code{object}. It is ancestor for all classes and so is the
10569: only class that has no parent. It has two selectors: @code{construct}
10570: and @code{print}.
1.21 crook 10571:
1.26 crook 10572: @node Creating objects, Object-Oriented Programming Style, The Objects base class, Objects
10573: @subsubsection Creating objects
10574: @cindex creating objects
10575: @cindex object creation
10576: @cindex object allocation options
1.21 crook 10577:
1.26 crook 10578: @cindex @code{heap-new} discussion
10579: @cindex @code{dict-new} discussion
10580: @cindex @code{construct} discussion
10581: You can create and initialize an object of a class on the heap with
10582: @code{heap-new} ( ... class -- object ) and in the dictionary
10583: (allocation with @code{allot}) with @code{dict-new} (
10584: ... class -- object ). Both words invoke @code{construct}, which
10585: consumes the stack items indicated by "..." above.
1.21 crook 10586:
1.26 crook 10587: @cindex @code{init-object} discussion
10588: @cindex @code{class-inst-size} discussion
10589: If you want to allocate memory for an object yourself, you can get its
10590: alignment and size with @code{class-inst-size 2@@} ( class --
10591: align size ). Once you have memory for an object, you can initialize
10592: it with @code{init-object} ( ... class object -- );
10593: @code{construct} does only a part of the necessary work.
1.21 crook 10594:
1.26 crook 10595: @node Object-Oriented Programming Style, Class Binding, Creating objects, Objects
10596: @subsubsection Object-Oriented Programming Style
10597: @cindex object-oriented programming style
1.47 crook 10598: @cindex programming style, object-oriented
1.21 crook 10599:
1.26 crook 10600: This section is not exhaustive.
1.1 anton 10601:
1.26 crook 10602: @cindex stack effects of selectors
10603: @cindex selectors and stack effects
10604: In general, it is a good idea to ensure that all methods for the
10605: same selector have the same stack effect: when you invoke a selector,
10606: you often have no idea which method will be invoked, so, unless all
10607: methods have the same stack effect, you will not know the stack effect
10608: of the selector invocation.
1.21 crook 10609:
1.26 crook 10610: One exception to this rule is methods for the selector
10611: @code{construct}. We know which method is invoked, because we
10612: specify the class to be constructed at the same place. Actually, I
10613: defined @code{construct} as a selector only to give the users a
10614: convenient way to specify initialization. The way it is used, a
10615: mechanism different from selector invocation would be more natural
10616: (but probably would take more code and more space to explain).
1.21 crook 10617:
1.26 crook 10618: @node Class Binding, Method conveniences, Object-Oriented Programming Style, Objects
10619: @subsubsection Class Binding
10620: @cindex class binding
10621: @cindex early binding
1.21 crook 10622:
1.26 crook 10623: @cindex late binding
10624: Normal selector invocations determine the method at run-time depending
10625: on the class of the receiving object. This run-time selection is called
1.29 crook 10626: @i{late binding}.
1.21 crook 10627:
1.26 crook 10628: Sometimes it's preferable to invoke a different method. For example,
10629: you might want to use the simple method for @code{print}ing
10630: @code{object}s instead of the possibly long-winded @code{print} method
10631: of the receiver class. You can achieve this by replacing the invocation
10632: of @code{print} with:
1.21 crook 10633:
1.26 crook 10634: @cindex @code{[bind]} usage
10635: @example
10636: [bind] object print
1.21 crook 10637: @end example
10638:
1.26 crook 10639: @noindent
10640: in compiled code or:
1.21 crook 10641:
1.26 crook 10642: @cindex @code{bind} usage
1.21 crook 10643: @example
1.26 crook 10644: bind object print
1.21 crook 10645: @end example
10646:
1.26 crook 10647: @cindex class binding, alternative to
10648: @noindent
10649: in interpreted code. Alternatively, you can define the method with a
10650: name (e.g., @code{print-object}), and then invoke it through the
10651: name. Class binding is just a (often more convenient) way to achieve
10652: the same effect; it avoids name clutter and allows you to invoke
10653: methods directly without naming them first.
10654:
10655: @cindex superclass binding
10656: @cindex parent class binding
10657: A frequent use of class binding is this: When we define a method
10658: for a selector, we often want the method to do what the selector does
10659: in the parent class, and a little more. There is a special word for
10660: this purpose: @code{[parent]}; @code{[parent]
10661: @emph{selector}} is equivalent to @code{[bind] @emph{parent
10662: selector}}, where @code{@emph{parent}} is the parent
10663: class of the current class. E.g., a method definition might look like:
1.21 crook 10664:
1.26 crook 10665: @cindex @code{[parent]} usage
1.21 crook 10666: @example
1.26 crook 10667: :noname
10668: dup [parent] foo \ do parent's foo on the receiving object
10669: ... \ do some more
10670: ; overrides foo
1.21 crook 10671: @end example
10672:
1.26 crook 10673: @cindex class binding as optimization
10674: In @cite{Object-oriented programming in ANS Forth} (Forth Dimensions,
10675: March 1997), Andrew McKewan presents class binding as an optimization
10676: technique. I recommend not using it for this purpose unless you are in
10677: an emergency. Late binding is pretty fast with this model anyway, so the
10678: benefit of using class binding is small; the cost of using class binding
10679: where it is not appropriate is reduced maintainability.
1.21 crook 10680:
1.26 crook 10681: While we are at programming style questions: You should bind
10682: selectors only to ancestor classes of the receiving object. E.g., say,
10683: you know that the receiving object is of class @code{foo} or its
10684: descendents; then you should bind only to @code{foo} and its
10685: ancestors.
1.21 crook 10686:
1.26 crook 10687: @node Method conveniences, Classes and Scoping, Class Binding, Objects
10688: @subsubsection Method conveniences
10689: @cindex method conveniences
1.1 anton 10690:
1.26 crook 10691: In a method you usually access the receiving object pretty often. If
10692: you define the method as a plain colon definition (e.g., with
10693: @code{:noname}), you may have to do a lot of stack
10694: gymnastics. To avoid this, you can define the method with @code{m:
10695: ... ;m}. E.g., you could define the method for
10696: @code{draw}ing a @code{circle} with
1.20 pazsan 10697:
1.26 crook 10698: @cindex @code{this} usage
10699: @cindex @code{m:} usage
10700: @cindex @code{;m} usage
10701: @example
10702: m: ( x y circle -- )
10703: ( x y ) this circle-radius @@ draw-circle ;m
10704: @end example
1.20 pazsan 10705:
1.26 crook 10706: @cindex @code{exit} in @code{m: ... ;m}
10707: @cindex @code{exitm} discussion
10708: @cindex @code{catch} in @code{m: ... ;m}
10709: When this method is executed, the receiver object is removed from the
10710: stack; you can access it with @code{this} (admittedly, in this
10711: example the use of @code{m: ... ;m} offers no advantage). Note
10712: that I specify the stack effect for the whole method (i.e. including
10713: the receiver object), not just for the code between @code{m:}
10714: and @code{;m}. You cannot use @code{exit} in
10715: @code{m:...;m}; instead, use
10716: @code{exitm}.@footnote{Moreover, for any word that calls
10717: @code{catch} and was defined before loading
10718: @code{objects.fs}, you have to redefine it like I redefined
10719: @code{catch}: @code{: catch this >r catch r> to-this ;}}
1.20 pazsan 10720:
1.26 crook 10721: @cindex @code{inst-var} usage
10722: You will frequently use sequences of the form @code{this
10723: @emph{field}} (in the example above: @code{this
10724: circle-radius}). If you use the field only in this way, you can
10725: define it with @code{inst-var} and eliminate the
10726: @code{this} before the field name. E.g., the @code{circle}
10727: class above could also be defined with:
1.20 pazsan 10728:
1.26 crook 10729: @example
10730: graphical class
10731: cell% inst-var radius
1.20 pazsan 10732:
1.26 crook 10733: m: ( x y circle -- )
10734: radius @@ draw-circle ;m
10735: overrides draw
1.20 pazsan 10736:
1.26 crook 10737: m: ( n-radius circle -- )
10738: radius ! ;m
10739: overrides construct
1.12 anton 10740:
1.26 crook 10741: end-class circle
10742: @end example
1.12 anton 10743:
1.26 crook 10744: @code{radius} can only be used in @code{circle} and its
10745: descendent classes and inside @code{m:...;m}.
1.12 anton 10746:
1.26 crook 10747: @cindex @code{inst-value} usage
10748: You can also define fields with @code{inst-value}, which is
10749: to @code{inst-var} what @code{value} is to
10750: @code{variable}. You can change the value of such a field with
10751: @code{[to-inst]}. E.g., we could also define the class
10752: @code{circle} like this:
1.12 anton 10753:
1.26 crook 10754: @example
10755: graphical class
10756: inst-value radius
1.12 anton 10757:
1.26 crook 10758: m: ( x y circle -- )
10759: radius draw-circle ;m
10760: overrides draw
1.12 anton 10761:
1.26 crook 10762: m: ( n-radius circle -- )
10763: [to-inst] radius ;m
10764: overrides construct
1.21 crook 10765:
1.26 crook 10766: end-class circle
1.12 anton 10767: @end example
10768:
1.38 anton 10769: Finally, you can define named methods with @code{:m}. One use of this
10770: feature is the definition of words that occur only in one class and are
10771: not intended to be overridden, but which still need method context
10772: (e.g., for accessing @code{inst-var}s). Another use is for methods that
10773: would be bound frequently, if defined anonymously.
10774:
1.12 anton 10775:
1.37 anton 10776: @node Classes and Scoping, Dividing classes, Method conveniences, Objects
1.26 crook 10777: @subsubsection Classes and Scoping
10778: @cindex classes and scoping
10779: @cindex scoping and classes
1.12 anton 10780:
1.26 crook 10781: Inheritance is frequent, unlike structure extension. This exacerbates
10782: the problem with the field name convention (@pxref{Structure Naming
10783: Convention}): One always has to remember in which class the field was
10784: originally defined; changing a part of the class structure would require
10785: changes for renaming in otherwise unaffected code.
1.12 anton 10786:
1.26 crook 10787: @cindex @code{inst-var} visibility
10788: @cindex @code{inst-value} visibility
10789: To solve this problem, I added a scoping mechanism (which was not in my
10790: original charter): A field defined with @code{inst-var} (or
10791: @code{inst-value}) is visible only in the class where it is defined and in
10792: the descendent classes of this class. Using such fields only makes
10793: sense in @code{m:}-defined methods in these classes anyway.
1.12 anton 10794:
1.26 crook 10795: This scoping mechanism allows us to use the unadorned field name,
10796: because name clashes with unrelated words become much less likely.
1.12 anton 10797:
1.26 crook 10798: @cindex @code{protected} discussion
10799: @cindex @code{private} discussion
10800: Once we have this mechanism, we can also use it for controlling the
10801: visibility of other words: All words defined after
10802: @code{protected} are visible only in the current class and its
10803: descendents. @code{public} restores the compilation
10804: (i.e. @code{current}) word list that was in effect before. If you
10805: have several @code{protected}s without an intervening
10806: @code{public} or @code{set-current}, @code{public}
10807: will restore the compilation word list in effect before the first of
10808: these @code{protected}s.
1.12 anton 10809:
1.37 anton 10810: @node Dividing classes, Object Interfaces, Classes and Scoping, Objects
10811: @subsubsection Dividing classes
10812: @cindex Dividing classes
10813: @cindex @code{methods}...@code{end-methods}
10814:
10815: You may want to do the definition of methods separate from the
10816: definition of the class, its selectors, fields, and instance variables,
10817: i.e., separate the implementation from the definition. You can do this
10818: in the following way:
10819:
10820: @example
10821: graphical class
10822: inst-value radius
10823: end-class circle
10824:
10825: ... \ do some other stuff
10826:
10827: circle methods \ now we are ready
10828:
10829: m: ( x y circle -- )
10830: radius draw-circle ;m
10831: overrides draw
10832:
10833: m: ( n-radius circle -- )
10834: [to-inst] radius ;m
10835: overrides construct
10836:
10837: end-methods
10838: @end example
10839:
10840: You can use several @code{methods}...@code{end-methods} sections. The
10841: only things you can do to the class in these sections are: defining
10842: methods, and overriding the class's selectors. You must not define new
10843: selectors or fields.
10844:
10845: Note that you often have to override a selector before using it. In
10846: particular, you usually have to override @code{construct} with a new
10847: method before you can invoke @code{heap-new} and friends. E.g., you
10848: must not create a circle before the @code{overrides construct} sequence
10849: in the example above.
10850:
10851: @node Object Interfaces, Objects Implementation, Dividing classes, Objects
1.26 crook 10852: @subsubsection Object Interfaces
10853: @cindex object interfaces
10854: @cindex interfaces for objects
1.12 anton 10855:
1.26 crook 10856: In this model you can only call selectors defined in the class of the
10857: receiving objects or in one of its ancestors. If you call a selector
10858: with a receiving object that is not in one of these classes, the
10859: result is undefined; if you are lucky, the program crashes
10860: immediately.
1.12 anton 10861:
1.26 crook 10862: @cindex selectors common to hardly-related classes
10863: Now consider the case when you want to have a selector (or several)
10864: available in two classes: You would have to add the selector to a
10865: common ancestor class, in the worst case to @code{object}. You
10866: may not want to do this, e.g., because someone else is responsible for
10867: this ancestor class.
1.12 anton 10868:
1.26 crook 10869: The solution for this problem is interfaces. An interface is a
10870: collection of selectors. If a class implements an interface, the
10871: selectors become available to the class and its descendents. A class
10872: can implement an unlimited number of interfaces. For the problem
10873: discussed above, we would define an interface for the selector(s), and
10874: both classes would implement the interface.
1.12 anton 10875:
1.26 crook 10876: As an example, consider an interface @code{storage} for
10877: writing objects to disk and getting them back, and a class
10878: @code{foo} that implements it. The code would look like this:
1.12 anton 10879:
1.26 crook 10880: @cindex @code{interface} usage
10881: @cindex @code{end-interface} usage
10882: @cindex @code{implementation} usage
10883: @example
10884: interface
10885: selector write ( file object -- )
10886: selector read1 ( file object -- )
10887: end-interface storage
1.12 anton 10888:
1.26 crook 10889: bar class
10890: storage implementation
1.12 anton 10891:
1.26 crook 10892: ... overrides write
1.37 anton 10893: ... overrides read1
1.26 crook 10894: ...
10895: end-class foo
1.12 anton 10896: @end example
10897:
1.26 crook 10898: @noindent
1.29 crook 10899: (I would add a word @code{read} @i{( file -- object )} that uses
1.26 crook 10900: @code{read1} internally, but that's beyond the point illustrated
10901: here.)
1.12 anton 10902:
1.26 crook 10903: Note that you cannot use @code{protected} in an interface; and
10904: of course you cannot define fields.
1.12 anton 10905:
1.26 crook 10906: In the Neon model, all selectors are available for all classes;
10907: therefore it does not need interfaces. The price you pay in this model
10908: is slower late binding, and therefore, added complexity to avoid late
10909: binding.
1.12 anton 10910:
1.26 crook 10911: @node Objects Implementation, Objects Glossary, Object Interfaces, Objects
10912: @subsubsection @file{objects.fs} Implementation
10913: @cindex @file{objects.fs} implementation
1.12 anton 10914:
1.26 crook 10915: @cindex @code{object-map} discussion
10916: An object is a piece of memory, like one of the data structures
10917: described with @code{struct...end-struct}. It has a field
10918: @code{object-map} that points to the method map for the object's
10919: class.
1.12 anton 10920:
1.26 crook 10921: @cindex method map
10922: @cindex virtual function table
10923: The @emph{method map}@footnote{This is Self terminology; in C++
10924: terminology: virtual function table.} is an array that contains the
1.29 crook 10925: execution tokens (@i{xt}s) of the methods for the object's class. Each
1.26 crook 10926: selector contains an offset into a method map.
1.12 anton 10927:
1.26 crook 10928: @cindex @code{selector} implementation, class
10929: @code{selector} is a defining word that uses
10930: @code{CREATE} and @code{DOES>}. The body of the
1.44 crook 10931: selector contains the offset; the @code{DOES>} action for a
1.26 crook 10932: class selector is, basically:
1.21 crook 10933:
1.26 crook 10934: @example
10935: ( object addr ) @@ over object-map @@ + @@ execute
10936: @end example
1.12 anton 10937:
1.26 crook 10938: Since @code{object-map} is the first field of the object, it
10939: does not generate any code. As you can see, calling a selector has a
10940: small, constant cost.
1.12 anton 10941:
1.26 crook 10942: @cindex @code{current-interface} discussion
10943: @cindex class implementation and representation
10944: A class is basically a @code{struct} combined with a method
10945: map. During the class definition the alignment and size of the class
10946: are passed on the stack, just as with @code{struct}s, so
10947: @code{field} can also be used for defining class
10948: fields. However, passing more items on the stack would be
10949: inconvenient, so @code{class} builds a data structure in memory,
10950: which is accessed through the variable
10951: @code{current-interface}. After its definition is complete, the
10952: class is represented on the stack by a pointer (e.g., as parameter for
10953: a child class definition).
1.1 anton 10954:
1.26 crook 10955: A new class starts off with the alignment and size of its parent,
10956: and a copy of the parent's method map. Defining new fields extends the
10957: size and alignment; likewise, defining new selectors extends the
1.29 crook 10958: method map. @code{overrides} just stores a new @i{xt} in the method
1.26 crook 10959: map at the offset given by the selector.
1.20 pazsan 10960:
1.26 crook 10961: @cindex class binding, implementation
1.29 crook 10962: Class binding just gets the @i{xt} at the offset given by the selector
1.26 crook 10963: from the class's method map and @code{compile,}s (in the case of
10964: @code{[bind]}) it.
1.21 crook 10965:
1.26 crook 10966: @cindex @code{this} implementation
10967: @cindex @code{catch} and @code{this}
10968: @cindex @code{this} and @code{catch}
10969: I implemented @code{this} as a @code{value}. At the
10970: start of an @code{m:...;m} method the old @code{this} is
10971: stored to the return stack and restored at the end; and the object on
10972: the TOS is stored @code{TO this}. This technique has one
10973: disadvantage: If the user does not leave the method via
10974: @code{;m}, but via @code{throw} or @code{exit},
10975: @code{this} is not restored (and @code{exit} may
10976: crash). To deal with the @code{throw} problem, I have redefined
10977: @code{catch} to save and restore @code{this}; the same
10978: should be done with any word that can catch an exception. As for
10979: @code{exit}, I simply forbid it (as a replacement, there is
10980: @code{exitm}).
1.21 crook 10981:
1.26 crook 10982: @cindex @code{inst-var} implementation
10983: @code{inst-var} is just the same as @code{field}, with
10984: a different @code{DOES>} action:
10985: @example
10986: @@ this +
10987: @end example
10988: Similar for @code{inst-value}.
1.21 crook 10989:
1.26 crook 10990: @cindex class scoping implementation
10991: Each class also has a word list that contains the words defined with
10992: @code{inst-var} and @code{inst-value}, and its protected
10993: words. It also has a pointer to its parent. @code{class} pushes
10994: the word lists of the class and all its ancestors onto the search order stack,
10995: and @code{end-class} drops them.
1.21 crook 10996:
1.26 crook 10997: @cindex interface implementation
10998: An interface is like a class without fields, parent and protected
10999: words; i.e., it just has a method map. If a class implements an
11000: interface, its method map contains a pointer to the method map of the
11001: interface. The positive offsets in the map are reserved for class
11002: methods, therefore interface map pointers have negative
11003: offsets. Interfaces have offsets that are unique throughout the
11004: system, unlike class selectors, whose offsets are only unique for the
11005: classes where the selector is available (invokable).
1.21 crook 11006:
1.26 crook 11007: This structure means that interface selectors have to perform one
11008: indirection more than class selectors to find their method. Their body
11009: contains the interface map pointer offset in the class method map, and
11010: the method offset in the interface method map. The
11011: @code{does>} action for an interface selector is, basically:
1.21 crook 11012:
11013: @example
1.26 crook 11014: ( object selector-body )
11015: 2dup selector-interface @@ ( object selector-body object interface-offset )
11016: swap object-map @@ + @@ ( object selector-body map )
11017: swap selector-offset @@ + @@ execute
1.21 crook 11018: @end example
11019:
1.26 crook 11020: where @code{object-map} and @code{selector-offset} are
11021: first fields and generate no code.
11022:
11023: As a concrete example, consider the following code:
1.21 crook 11024:
1.26 crook 11025: @example
11026: interface
11027: selector if1sel1
11028: selector if1sel2
11029: end-interface if1
1.21 crook 11030:
1.26 crook 11031: object class
11032: if1 implementation
11033: selector cl1sel1
11034: cell% inst-var cl1iv1
1.21 crook 11035:
1.26 crook 11036: ' m1 overrides construct
11037: ' m2 overrides if1sel1
11038: ' m3 overrides if1sel2
11039: ' m4 overrides cl1sel2
11040: end-class cl1
1.21 crook 11041:
1.26 crook 11042: create obj1 object dict-new drop
11043: create obj2 cl1 dict-new drop
11044: @end example
1.21 crook 11045:
1.26 crook 11046: The data structure created by this code (including the data structure
11047: for @code{object}) is shown in the <a
11048: href="objects-implementation.eps">figure</a>, assuming a cell size of 4.
1.29 crook 11049: @comment TODO add this diagram..
1.21 crook 11050:
1.26 crook 11051: @node Objects Glossary, , Objects Implementation, Objects
11052: @subsubsection @file{objects.fs} Glossary
11053: @cindex @file{objects.fs} Glossary
1.21 crook 11054:
1.44 crook 11055:
1.26 crook 11056: doc---objects-bind
11057: doc---objects-<bind>
11058: doc---objects-bind'
11059: doc---objects-[bind]
11060: doc---objects-class
11061: doc---objects-class->map
11062: doc---objects-class-inst-size
11063: doc---objects-class-override!
11064: doc---objects-construct
11065: doc---objects-current'
11066: doc---objects-[current]
11067: doc---objects-current-interface
11068: doc---objects-dict-new
11069: doc---objects-drop-order
11070: doc---objects-end-class
11071: doc---objects-end-class-noname
11072: doc---objects-end-interface
11073: doc---objects-end-interface-noname
1.37 anton 11074: doc---objects-end-methods
1.26 crook 11075: doc---objects-exitm
11076: doc---objects-heap-new
11077: doc---objects-implementation
11078: doc---objects-init-object
11079: doc---objects-inst-value
11080: doc---objects-inst-var
11081: doc---objects-interface
1.38 anton 11082: doc---objects-m:
11083: doc---objects-:m
1.26 crook 11084: doc---objects-;m
11085: doc---objects-method
1.37 anton 11086: doc---objects-methods
1.26 crook 11087: doc---objects-object
11088: doc---objects-overrides
11089: doc---objects-[parent]
11090: doc---objects-print
11091: doc---objects-protected
11092: doc---objects-public
11093: doc---objects-push-order
11094: doc---objects-selector
11095: doc---objects-this
11096: doc---objects-<to-inst>
11097: doc---objects-[to-inst]
11098: doc---objects-to-this
11099: doc---objects-xt-new
1.21 crook 11100:
1.44 crook 11101:
1.26 crook 11102: @c -------------------------------------------------------------
11103: @node OOF, Mini-OOF, Objects, Object-oriented Forth
11104: @subsection The @file{oof.fs} model
11105: @cindex oof
11106: @cindex object-oriented programming
1.21 crook 11107:
1.26 crook 11108: @cindex @file{objects.fs}
11109: @cindex @file{oof.fs}
1.21 crook 11110:
1.26 crook 11111: This section describes the @file{oof.fs} package.
1.21 crook 11112:
1.26 crook 11113: The package described in this section has been used in bigFORTH since 1991, and
11114: used for two large applications: a chromatographic system used to
11115: create new medicaments, and a graphic user interface library (MINOS).
1.21 crook 11116:
1.26 crook 11117: You can find a description (in German) of @file{oof.fs} in @cite{Object
11118: oriented bigFORTH} by Bernd Paysan, published in @cite{Vierte Dimension}
11119: 10(2), 1994.
1.21 crook 11120:
1.26 crook 11121: @menu
1.67 anton 11122: * Properties of the OOF model::
11123: * Basic OOF Usage::
11124: * The OOF base class::
11125: * Class Declaration::
11126: * Class Implementation::
1.26 crook 11127: @end menu
1.21 crook 11128:
1.26 crook 11129: @node Properties of the OOF model, Basic OOF Usage, OOF, OOF
11130: @subsubsection Properties of the @file{oof.fs} model
11131: @cindex @file{oof.fs} properties
1.21 crook 11132:
1.26 crook 11133: @itemize @bullet
11134: @item
11135: This model combines object oriented programming with information
11136: hiding. It helps you writing large application, where scoping is
11137: necessary, because it provides class-oriented scoping.
1.21 crook 11138:
1.26 crook 11139: @item
11140: Named objects, object pointers, and object arrays can be created,
11141: selector invocation uses the ``object selector'' syntax. Selector invocation
11142: to objects and/or selectors on the stack is a bit less convenient, but
11143: possible.
1.21 crook 11144:
1.26 crook 11145: @item
11146: Selector invocation and instance variable usage of the active object is
11147: straightforward, since both make use of the active object.
1.21 crook 11148:
1.26 crook 11149: @item
11150: Late binding is efficient and easy to use.
1.21 crook 11151:
1.26 crook 11152: @item
11153: State-smart objects parse selectors. However, extensibility is provided
11154: using a (parsing) selector @code{postpone} and a selector @code{'}.
1.21 crook 11155:
11156: @item
1.26 crook 11157: An implementation in ANS Forth is available.
11158:
1.21 crook 11159: @end itemize
11160:
11161:
1.26 crook 11162: @node Basic OOF Usage, The OOF base class, Properties of the OOF model, OOF
11163: @subsubsection Basic @file{oof.fs} Usage
11164: @cindex @file{oof.fs} usage
11165:
11166: This section uses the same example as for @code{objects} (@pxref{Basic Objects Usage}).
1.21 crook 11167:
1.26 crook 11168: You can define a class for graphical objects like this:
1.21 crook 11169:
1.26 crook 11170: @cindex @code{class} usage
11171: @cindex @code{class;} usage
11172: @cindex @code{method} usage
11173: @example
11174: object class graphical \ "object" is the parent class
11175: method draw ( x y graphical -- )
11176: class;
11177: @end example
1.21 crook 11178:
1.26 crook 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.21 crook 11182:
1.26 crook 11183: @example
11184: 100 100 t-rex draw
11185: @end example
1.21 crook 11186:
1.26 crook 11187: @noindent
11188: where @code{t-rex} is an object or object pointer, created with e.g.
11189: @code{graphical : t-rex}.
1.21 crook 11190:
1.26 crook 11191: @cindex abstract class
11192: How do we create a graphical object? With the present definitions,
11193: we cannot create a useful graphical object. The class
11194: @code{graphical} describes graphical objects in general, but not
11195: any concrete graphical object type (C++ users would call it an
11196: @emph{abstract class}); e.g., there is no method for the selector
11197: @code{draw} in the class @code{graphical}.
1.21 crook 11198:
1.26 crook 11199: For concrete graphical objects, we define child classes of the
11200: class @code{graphical}, e.g.:
1.21 crook 11201:
11202: @example
1.26 crook 11203: graphical class circle \ "graphical" is the parent class
11204: cell var circle-radius
11205: how:
11206: : draw ( x y -- )
11207: circle-radius @@ draw-circle ;
11208:
11209: : init ( n-radius -- (
11210: circle-radius ! ;
11211: class;
11212: @end example
11213:
11214: Here we define a class @code{circle} as a child of @code{graphical},
11215: with a field @code{circle-radius}; it defines new methods for the
11216: selectors @code{draw} and @code{init} (@code{init} is defined in
11217: @code{object}, the parent class of @code{graphical}).
1.21 crook 11218:
1.26 crook 11219: Now we can create a circle in the dictionary with:
1.21 crook 11220:
1.26 crook 11221: @example
11222: 50 circle : my-circle
1.21 crook 11223: @end example
11224:
1.26 crook 11225: @noindent
11226: @code{:} invokes @code{init}, thus initializing the field
11227: @code{circle-radius} with 50. We can draw this new circle at (100,100)
11228: with:
1.21 crook 11229:
11230: @example
1.26 crook 11231: 100 100 my-circle draw
1.21 crook 11232: @end example
11233:
1.26 crook 11234: @cindex selector invocation, restrictions
11235: @cindex class definition, restrictions
11236: Note: You can only invoke a selector if the receiving object belongs to
11237: the class where the selector was defined or one of its descendents;
11238: e.g., you can invoke @code{draw} only for objects belonging to
11239: @code{graphical} or its descendents (e.g., @code{circle}). The scoping
11240: mechanism will check if you try to invoke a selector that is not
11241: defined in this class hierarchy, so you'll get an error at compilation
11242: time.
11243:
11244:
11245: @node The OOF base class, Class Declaration, Basic OOF Usage, OOF
11246: @subsubsection The @file{oof.fs} base class
11247: @cindex @file{oof.fs} base class
11248:
11249: When you define a class, you have to specify a parent class. So how do
11250: you start defining classes? There is one class available from the start:
11251: @code{object}. You have to use it as ancestor for all classes. It is the
11252: only class that has no parent. Classes are also objects, except that
11253: they don't have instance variables; class manipulation such as
11254: inheritance or changing definitions of a class is handled through
11255: selectors of the class @code{object}.
11256:
11257: @code{object} provides a number of selectors:
11258:
1.21 crook 11259: @itemize @bullet
11260: @item
1.26 crook 11261: @code{class} for subclassing, @code{definitions} to add definitions
11262: later on, and @code{class?} to get type informations (is the class a
11263: subclass of the class passed on the stack?).
1.44 crook 11264:
1.26 crook 11265: doc---object-class
11266: doc---object-definitions
11267: doc---object-class?
11268:
1.44 crook 11269:
1.21 crook 11270: @item
1.26 crook 11271: @code{init} and @code{dispose} as constructor and destructor of the
11272: object. @code{init} is invocated after the object's memory is allocated,
11273: while @code{dispose} also handles deallocation. Thus if you redefine
11274: @code{dispose}, you have to call the parent's dispose with @code{super
11275: dispose}, too.
1.44 crook 11276:
1.26 crook 11277: doc---object-init
11278: doc---object-dispose
11279:
1.44 crook 11280:
1.21 crook 11281: @item
1.26 crook 11282: @code{new}, @code{new[]}, @code{:}, @code{ptr}, @code{asptr}, and
11283: @code{[]} to create named and unnamed objects and object arrays or
11284: object pointers.
1.44 crook 11285:
1.26 crook 11286: doc---object-new
11287: doc---object-new[]
11288: doc---object-:
11289: doc---object-ptr
11290: doc---object-asptr
11291: doc---object-[]
1.21 crook 11292:
1.44 crook 11293:
1.26 crook 11294: @item
11295: @code{::} and @code{super} for explicit scoping. You should use explicit
11296: scoping only for super classes or classes with the same set of instance
11297: variables. Explicitly-scoped selectors use early binding.
1.44 crook 11298:
1.26 crook 11299: doc---object-::
11300: doc---object-super
1.21 crook 11301:
1.44 crook 11302:
1.26 crook 11303: @item
11304: @code{self} to get the address of the object
1.44 crook 11305:
1.26 crook 11306: doc---object-self
1.21 crook 11307:
1.44 crook 11308:
1.21 crook 11309: @item
1.26 crook 11310: @code{bind}, @code{bound}, @code{link}, and @code{is} to assign object
11311: pointers and instance defers.
1.44 crook 11312:
1.26 crook 11313: doc---object-bind
11314: doc---object-bound
11315: doc---object-link
11316: doc---object-is
11317:
1.44 crook 11318:
1.21 crook 11319: @item
1.26 crook 11320: @code{'} to obtain selector tokens, @code{send} to invocate selectors
11321: form the stack, and @code{postpone} to generate selector invocation code.
1.44 crook 11322:
1.26 crook 11323: doc---object-'
11324: doc---object-postpone
11325:
1.44 crook 11326:
1.21 crook 11327: @item
1.26 crook 11328: @code{with} and @code{endwith} to select the active object from the
11329: stack, and enable its scope. Using @code{with} and @code{endwith}
11330: also allows you to create code using selector @code{postpone} without being
11331: trapped by the state-smart objects.
1.44 crook 11332:
1.26 crook 11333: doc---object-with
11334: doc---object-endwith
11335:
1.44 crook 11336:
1.21 crook 11337: @end itemize
11338:
1.26 crook 11339: @node Class Declaration, Class Implementation, The OOF base class, OOF
11340: @subsubsection Class Declaration
11341: @cindex class declaration
11342:
11343: @itemize @bullet
11344: @item
11345: Instance variables
1.44 crook 11346:
1.26 crook 11347: doc---oof-var
1.21 crook 11348:
1.44 crook 11349:
1.26 crook 11350: @item
11351: Object pointers
1.44 crook 11352:
1.26 crook 11353: doc---oof-ptr
11354: doc---oof-asptr
1.21 crook 11355:
1.44 crook 11356:
1.26 crook 11357: @item
11358: Instance defers
1.44 crook 11359:
1.26 crook 11360: doc---oof-defer
1.21 crook 11361:
1.44 crook 11362:
1.26 crook 11363: @item
11364: Method selectors
1.44 crook 11365:
1.26 crook 11366: doc---oof-early
11367: doc---oof-method
1.21 crook 11368:
1.44 crook 11369:
1.26 crook 11370: @item
11371: Class-wide variables
1.44 crook 11372:
1.26 crook 11373: doc---oof-static
1.21 crook 11374:
1.44 crook 11375:
1.26 crook 11376: @item
11377: End declaration
1.44 crook 11378:
1.26 crook 11379: doc---oof-how:
11380: doc---oof-class;
1.21 crook 11381:
1.44 crook 11382:
1.26 crook 11383: @end itemize
1.21 crook 11384:
1.26 crook 11385: @c -------------------------------------------------------------
11386: @node Class Implementation, , Class Declaration, OOF
11387: @subsubsection Class Implementation
11388: @cindex class implementation
1.21 crook 11389:
1.26 crook 11390: @c -------------------------------------------------------------
11391: @node Mini-OOF, Comparison with other object models, OOF, Object-oriented Forth
11392: @subsection The @file{mini-oof.fs} model
11393: @cindex mini-oof
1.1 anton 11394:
1.26 crook 11395: Gforth's third object oriented Forth package is a 12-liner. It uses a
11396: mixture of the @file{object.fs} and the @file{oof.fs} syntax,
11397: and reduces to the bare minimum of features. This is based on a posting
1.70 pazsan 11398: of Bernd Paysan in comp.lang.forth.
1.1 anton 11399:
11400: @menu
1.48 anton 11401: * Basic Mini-OOF Usage::
11402: * Mini-OOF Example::
11403: * Mini-OOF Implementation::
1.1 anton 11404: @end menu
11405:
1.26 crook 11406: @c -------------------------------------------------------------
1.48 anton 11407: @node Basic Mini-OOF Usage, Mini-OOF Example, Mini-OOF, Mini-OOF
1.26 crook 11408: @subsubsection Basic @file{mini-oof.fs} Usage
11409: @cindex mini-oof usage
1.1 anton 11410:
1.28 crook 11411: There is a base class (@code{class}, which allocates one cell for the
11412: object pointer) plus seven other words: to define a method, a variable,
11413: a class; to end a class, to resolve binding, to allocate an object and
11414: to compile a class method.
1.26 crook 11415: @comment TODO better description of the last one
1.1 anton 11416:
1.44 crook 11417:
1.26 crook 11418: doc-object
11419: doc-method
11420: doc-var
11421: doc-class
11422: doc-end-class
11423: doc-defines
11424: doc-new
11425: doc-::
1.1 anton 11426:
1.21 crook 11427:
1.44 crook 11428:
1.26 crook 11429: @c -------------------------------------------------------------
11430: @node Mini-OOF Example, Mini-OOF Implementation, Basic Mini-OOF Usage, Mini-OOF
11431: @subsubsection Mini-OOF Example
11432: @cindex mini-oof example
1.21 crook 11433:
1.26 crook 11434: A short example shows how to use this package. This example, in slightly
11435: extended form, is supplied as @file{moof-exm.fs}
1.29 crook 11436: @comment TODO could flesh this out with some comments from the Forthwrite article
1.21 crook 11437:
1.26 crook 11438: @example
11439: object class
11440: method init
11441: method draw
11442: end-class graphical
11443: @end example
1.21 crook 11444:
1.26 crook 11445: This code defines a class @code{graphical} with an
11446: operation @code{draw}. We can perform the operation
11447: @code{draw} on any @code{graphical} object, e.g.:
1.1 anton 11448:
1.26 crook 11449: @example
11450: 100 100 t-rex draw
11451: @end example
1.1 anton 11452:
1.26 crook 11453: where @code{t-rex} is an object or object pointer, created with e.g.
11454: @code{graphical new Constant t-rex}.
1.1 anton 11455:
1.26 crook 11456: For concrete graphical objects, we define child classes of the
11457: class @code{graphical}, e.g.:
1.21 crook 11458:
11459: @example
1.26 crook 11460: graphical class
11461: cell var circle-radius
11462: end-class circle \ "graphical" is the parent class
1.21 crook 11463:
1.26 crook 11464: :noname ( x y -- )
11465: circle-radius @@ draw-circle ; circle defines draw
11466: :noname ( r -- )
11467: circle-radius ! ; circle defines init
1.21 crook 11468: @end example
11469:
1.26 crook 11470: There is no implicit init method, so we have to define one. The creation
11471: code of the object now has to call init explicitely.
1.21 crook 11472:
1.26 crook 11473: @example
11474: circle new Constant my-circle
11475: 50 my-circle init
11476: @end example
1.21 crook 11477:
1.26 crook 11478: It is also possible to add a function to create named objects with
11479: automatic call of @code{init}, given that all objects have @code{init}
11480: on the same place:
1.1 anton 11481:
11482: @example
1.26 crook 11483: : new: ( .. o "name" -- )
11484: new dup Constant init ;
11485: 80 circle new: large-circle
1.1 anton 11486: @end example
11487:
1.26 crook 11488: We can draw this new circle at (100,100) with:
1.1 anton 11489:
11490: @example
1.26 crook 11491: 100 100 my-circle draw
1.1 anton 11492: @end example
11493:
1.48 anton 11494: @node Mini-OOF Implementation, , Mini-OOF Example, Mini-OOF
1.26 crook 11495: @subsubsection @file{mini-oof.fs} Implementation
1.1 anton 11496:
1.26 crook 11497: Object-oriented systems with late binding typically use a
11498: ``vtable''-approach: the first variable in each object is a pointer to a
11499: table, which contains the methods as function pointers. The vtable
11500: may also contain other information.
1.1 anton 11501:
1.26 crook 11502: So first, let's declare methods:
1.1 anton 11503:
1.26 crook 11504: @example
11505: : method ( m v -- m' v ) Create over , swap cell+ swap
1.73 anton 11506: DOES> ( ... o -- ... ) @@ over @@ + @@ execute ;
1.26 crook 11507: @end example
1.1 anton 11508:
1.26 crook 11509: During method declaration, the number of methods and instance
11510: variables is on the stack (in address units). @code{method} creates
11511: one method and increments the method number. To execute a method, it
11512: takes the object, fetches the vtable pointer, adds the offset, and
1.29 crook 11513: executes the @i{xt} stored there. Each method takes the object it is
1.26 crook 11514: invoked from as top of stack parameter. The method itself should
11515: consume that object.
1.1 anton 11516:
1.26 crook 11517: Now, we also have to declare instance variables
1.21 crook 11518:
1.26 crook 11519: @example
11520: : var ( m v size -- m v' ) Create over , +
1.73 anton 11521: DOES> ( o -- addr ) @@ + ;
1.26 crook 11522: @end example
1.21 crook 11523:
1.26 crook 11524: As before, a word is created with the current offset. Instance
11525: variables can have different sizes (cells, floats, doubles, chars), so
11526: all we do is take the size and add it to the offset. If your machine
11527: has alignment restrictions, put the proper @code{aligned} or
11528: @code{faligned} before the variable, to adjust the variable
11529: offset. That's why it is on the top of stack.
1.2 jwilke 11530:
1.26 crook 11531: We need a starting point (the base object) and some syntactic sugar:
1.21 crook 11532:
1.26 crook 11533: @example
11534: Create object 1 cells , 2 cells ,
1.73 anton 11535: : class ( class -- class methods vars ) dup 2@@ ;
1.26 crook 11536: @end example
1.21 crook 11537:
1.26 crook 11538: For inheritance, the vtable of the parent object has to be
11539: copied when a new, derived class is declared. This gives all the
11540: methods of the parent class, which can be overridden, though.
1.21 crook 11541:
1.2 jwilke 11542: @example
1.26 crook 11543: : end-class ( class methods vars -- )
11544: Create here >r , dup , 2 cells ?DO ['] noop , 1 cells +LOOP
1.73 anton 11545: cell+ dup cell+ r> rot @@ 2 cells /string move ;
1.26 crook 11546: @end example
11547:
11548: The first line creates the vtable, initialized with
11549: @code{noop}s. The second line is the inheritance mechanism, it
11550: copies the xts from the parent vtable.
1.2 jwilke 11551:
1.26 crook 11552: We still have no way to define new methods, let's do that now:
1.2 jwilke 11553:
1.26 crook 11554: @example
1.73 anton 11555: : defines ( xt class -- ) ' >body @@ + ! ;
1.2 jwilke 11556: @end example
11557:
1.26 crook 11558: To allocate a new object, we need a word, too:
1.2 jwilke 11559:
1.26 crook 11560: @example
1.73 anton 11561: : new ( class -- o ) here over @@ allot swap over ! ;
1.26 crook 11562: @end example
1.2 jwilke 11563:
1.26 crook 11564: Sometimes derived classes want to access the method of the
11565: parent object. There are two ways to achieve this with Mini-OOF:
11566: first, you could use named words, and second, you could look up the
11567: vtable of the parent object.
1.2 jwilke 11568:
1.26 crook 11569: @example
1.73 anton 11570: : :: ( class "name" -- ) ' >body @@ + @@ compile, ;
1.26 crook 11571: @end example
1.2 jwilke 11572:
11573:
1.26 crook 11574: Nothing can be more confusing than a good example, so here is
11575: one. First let's declare a text object (called
11576: @code{button}), that stores text and position:
1.2 jwilke 11577:
1.26 crook 11578: @example
11579: object class
11580: cell var text
11581: cell var len
11582: cell var x
11583: cell var y
11584: method init
11585: method draw
11586: end-class button
11587: @end example
1.2 jwilke 11588:
1.26 crook 11589: @noindent
11590: Now, implement the two methods, @code{draw} and @code{init}:
1.2 jwilke 11591:
1.26 crook 11592: @example
11593: :noname ( o -- )
1.73 anton 11594: >r r@@ x @@ r@@ y @@ at-xy r@@ text @@ r> len @@ type ;
1.26 crook 11595: button defines draw
11596: :noname ( addr u o -- )
1.73 anton 11597: >r 0 r@@ x ! 0 r@@ y ! r@@ len ! r> text ! ;
1.26 crook 11598: button defines init
11599: @end example
1.2 jwilke 11600:
1.26 crook 11601: @noindent
11602: To demonstrate inheritance, we define a class @code{bold-button}, with no
11603: new data and no new methods:
1.2 jwilke 11604:
1.26 crook 11605: @example
11606: button class
11607: end-class bold-button
1.1 anton 11608:
1.26 crook 11609: : bold 27 emit ." [1m" ;
11610: : normal 27 emit ." [0m" ;
11611: @end example
1.1 anton 11612:
1.26 crook 11613: @noindent
11614: The class @code{bold-button} has a different draw method to
11615: @code{button}, but the new method is defined in terms of the draw method
11616: for @code{button}:
1.1 anton 11617:
1.26 crook 11618: @example
11619: :noname bold [ button :: draw ] normal ; bold-button defines draw
11620: @end example
1.1 anton 11621:
1.26 crook 11622: @noindent
11623: Finally, create two objects and apply methods:
1.1 anton 11624:
1.26 crook 11625: @example
11626: button new Constant foo
11627: s" thin foo" foo init
11628: page
11629: foo draw
11630: bold-button new Constant bar
11631: s" fat bar" bar init
11632: 1 bar y !
11633: bar draw
11634: @end example
1.1 anton 11635:
11636:
1.48 anton 11637: @node Comparison with other object models, , Mini-OOF, Object-oriented Forth
11638: @subsection Comparison with other object models
1.26 crook 11639: @cindex comparison of object models
11640: @cindex object models, comparison
1.1 anton 11641:
1.26 crook 11642: Many object-oriented Forth extensions have been proposed (@cite{A survey
11643: of object-oriented Forths} (SIGPLAN Notices, April 1996) by Bradford
11644: J. Rodriguez and W. F. S. Poehlman lists 17). This section discusses the
11645: relation of the object models described here to two well-known and two
11646: closely-related (by the use of method maps) models.
1.1 anton 11647:
1.26 crook 11648: @cindex Neon model
11649: The most popular model currently seems to be the Neon model (see
11650: @cite{Object-oriented programming in ANS Forth} (Forth Dimensions, March
11651: 1997) by Andrew McKewan) but this model has a number of limitations
11652: @footnote{A longer version of this critique can be
11653: found in @cite{On Standardizing Object-Oriented Forth Extensions} (Forth
11654: Dimensions, May 1997) by Anton Ertl.}:
1.1 anton 11655:
1.26 crook 11656: @itemize @bullet
11657: @item
1.48 anton 11658: It uses a @code{@emph{selector object}} syntax, which makes it unnatural
11659: to pass objects on the stack.
1.1 anton 11660:
1.26 crook 11661: @item
11662: It requires that the selector parses the input stream (at
11663: compile time); this leads to reduced extensibility and to bugs that are+
11664: hard to find.
1.1 anton 11665:
1.26 crook 11666: @item
11667: It allows using every selector to every object;
11668: this eliminates the need for classes, but makes it harder to create
11669: efficient implementations.
11670: @end itemize
1.1 anton 11671:
1.26 crook 11672: @cindex Pountain's object-oriented model
11673: Another well-known publication is @cite{Object-Oriented Forth} (Academic
11674: Press, London, 1987) by Dick Pountain. However, it is not really about
11675: object-oriented programming, because it hardly deals with late
11676: binding. Instead, it focuses on features like information hiding and
11677: overloading that are characteristic of modular languages like Ada (83).
1.1 anton 11678:
1.26 crook 11679: @cindex Zsoter's object-oriented model
1.48 anton 11680: In @cite{Does late binding have to be slow?} (Forth Dimensions 18(1)
11681: 1996, pages 31-35) Andras Zsoter describes a model that makes heavy use
11682: of an active object (like @code{this} in @file{objects.fs}): The active
11683: object is not only used for accessing all fields, but also specifies the
11684: receiving object of every selector invocation; you have to change the
11685: active object explicitly with @code{@{ ... @}}, whereas in
11686: @file{objects.fs} it changes more or less implicitly at @code{m:
11687: ... ;m}. Such a change at the method entry point is unnecessary with the
11688: Zsoter's model, because the receiving object is the active object
11689: already. On the other hand, the explicit change is absolutely necessary
11690: in that model, because otherwise no one could ever change the active
11691: object. An ANS Forth implementation of this model is available at
11692: @uref{http://www.forth.org/fig/oopf.html}.
1.1 anton 11693:
1.26 crook 11694: @cindex @file{oof.fs}, differences to other models
11695: The @file{oof.fs} model combines information hiding and overloading
11696: resolution (by keeping names in various word lists) with object-oriented
11697: programming. It sets the active object implicitly on method entry, but
11698: also allows explicit changing (with @code{>o...o>} or with
11699: @code{with...endwith}). It uses parsing and state-smart objects and
11700: classes for resolving overloading and for early binding: the object or
11701: class parses the selector and determines the method from this. If the
11702: selector is not parsed by an object or class, it performs a call to the
11703: selector for the active object (late binding), like Zsoter's model.
11704: Fields are always accessed through the active object. The big
11705: disadvantage of this model is the parsing and the state-smartness, which
11706: reduces extensibility and increases the opportunities for subtle bugs;
11707: essentially, you are only safe if you never tick or @code{postpone} an
11708: object or class (Bernd disagrees, but I (Anton) am not convinced).
1.1 anton 11709:
1.26 crook 11710: @cindex @file{mini-oof.fs}, differences to other models
1.48 anton 11711: The @file{mini-oof.fs} model is quite similar to a very stripped-down
11712: version of the @file{objects.fs} model, but syntactically it is a
11713: mixture of the @file{objects.fs} and @file{oof.fs} models.
1.1 anton 11714:
1.26 crook 11715: @c -------------------------------------------------------------
1.47 crook 11716: @node Passing Commands to the OS, Keeping track of Time, Object-oriented Forth, Words
1.21 crook 11717: @section Passing Commands to the Operating System
11718: @cindex operating system - passing commands
11719: @cindex shell commands
11720:
11721: Gforth allows you to pass an arbitrary string to the host operating
11722: system shell (if such a thing exists) for execution.
11723:
1.44 crook 11724:
1.21 crook 11725: doc-sh
11726: doc-system
11727: doc-$?
1.23 crook 11728: doc-getenv
1.21 crook 11729:
1.44 crook 11730:
1.26 crook 11731: @c -------------------------------------------------------------
1.47 crook 11732: @node Keeping track of Time, Miscellaneous Words, Passing Commands to the OS, Words
11733: @section Keeping track of Time
11734: @cindex time-related words
11735:
11736: Gforth implements time-related operations by making calls to the C
11737: library function, @code{gettimeofday}.
11738:
11739: doc-ms
11740: doc-time&date
11741:
11742:
11743:
11744: @c -------------------------------------------------------------
11745: @node Miscellaneous Words, , Keeping track of Time, Words
1.21 crook 11746: @section Miscellaneous Words
11747: @cindex miscellaneous words
11748:
1.29 crook 11749: @comment TODO find homes for these
11750:
1.26 crook 11751: These section lists the ANS Forth words that are not documented
1.21 crook 11752: elsewhere in this manual. Ultimately, they all need proper homes.
11753:
11754: doc-[compile]
1.68 anton 11755: doc-quit
1.44 crook 11756:
1.26 crook 11757: The following ANS Forth words are not currently supported by Gforth
1.27 crook 11758: (@pxref{ANS conformance}):
1.21 crook 11759:
11760: @code{EDITOR}
11761: @code{EMIT?}
11762: @code{FORGET}
11763:
1.24 anton 11764: @c ******************************************************************
11765: @node Error messages, Tools, Words, Top
11766: @chapter Error messages
11767: @cindex error messages
11768: @cindex backtrace
11769:
11770: A typical Gforth error message looks like this:
11771:
11772: @example
11773: in file included from :-1
11774: in file included from ./yyy.fs:1
11775: ./xxx.fs:4: Invalid memory address
11776: bar
11777: ^^^
1.25 anton 11778: $400E664C @@
11779: $400E6664 foo
1.24 anton 11780: @end example
11781:
11782: The message identifying the error is @code{Invalid memory address}. The
11783: error happened when text-interpreting line 4 of the file
11784: @file{./xxx.fs}. This line is given (it contains @code{bar}), and the
11785: word on the line where the error happened, is pointed out (with
11786: @code{^^^}).
11787:
11788: The file containing the error was included in line 1 of @file{./yyy.fs},
11789: and @file{yyy.fs} was included from a non-file (in this case, by giving
11790: @file{yyy.fs} as command-line parameter to Gforth).
11791:
11792: At the end of the error message you find a return stack dump that can be
11793: interpreted as a backtrace (possibly empty). On top you find the top of
11794: the return stack when the @code{throw} happened, and at the bottom you
11795: find the return stack entry just above the return stack of the topmost
11796: text interpreter.
11797:
11798: To the right of most return stack entries you see a guess for the word
11799: that pushed that return stack entry as its return address. This gives a
11800: backtrace. In our case we see that @code{bar} called @code{foo}, and
11801: @code{foo} called @code{@@} (and @code{@@} had an @emph{Invalid memory
11802: address} exception).
11803:
11804: Note that the backtrace is not perfect: We don't know which return stack
11805: entries are return addresses (so we may get false positives); and in
11806: some cases (e.g., for @code{abort"}) we cannot determine from the return
11807: address the word that pushed the return address, so for some return
11808: addresses you see no names in the return stack dump.
1.25 anton 11809:
11810: @cindex @code{catch} and backtraces
11811: The return stack dump represents the return stack at the time when a
11812: specific @code{throw} was executed. In programs that make use of
11813: @code{catch}, it is not necessarily clear which @code{throw} should be
11814: used for the return stack dump (e.g., consider one @code{throw} that
11815: indicates an error, which is caught, and during recovery another error
1.42 anton 11816: happens; which @code{throw} should be used for the stack dump?). Gforth
1.25 anton 11817: presents the return stack dump for the first @code{throw} after the last
11818: executed (not returned-to) @code{catch}; this works well in the usual
11819: case.
11820:
11821: @cindex @code{gforth-fast} and backtraces
11822: @cindex @code{gforth-fast}, difference from @code{gforth}
11823: @cindex backtraces with @code{gforth-fast}
11824: @cindex return stack dump with @code{gforth-fast}
11825: @code{gforth} is able to do a return stack dump for throws generated
11826: from primitives (e.g., invalid memory address, stack empty etc.);
11827: @code{gforth-fast} is only able to do a return stack dump from a
11828: directly called @code{throw} (including @code{abort} etc.). This is the
1.30 anton 11829: only difference (apart from a speed factor of between 1.15 (K6-2) and
11830: 1.6 (21164A)) between @code{gforth} and @code{gforth-fast}. Given an
11831: exception caused by a primitive in @code{gforth-fast}, you will
11832: typically see no return stack dump at all; however, if the exception is
11833: caught by @code{catch} (e.g., for restoring some state), and then
11834: @code{throw}n again, the return stack dump will be for the first such
11835: @code{throw}.
1.2 jwilke 11836:
1.5 anton 11837: @c ******************************************************************
1.24 anton 11838: @node Tools, ANS conformance, Error messages, Top
1.1 anton 11839: @chapter Tools
11840:
11841: @menu
11842: * ANS Report:: Report the words used, sorted by wordset.
11843: @end menu
11844:
11845: See also @ref{Emacs and Gforth}.
11846:
11847: @node ANS Report, , Tools, Tools
11848: @section @file{ans-report.fs}: Report the words used, sorted by wordset
11849: @cindex @file{ans-report.fs}
11850: @cindex report the words used in your program
11851: @cindex words used in your program
11852:
11853: If you want to label a Forth program as ANS Forth Program, you must
11854: document which wordsets the program uses; for extension wordsets, it is
11855: helpful to list the words the program requires from these wordsets
11856: (because Forth systems are allowed to provide only some words of them).
11857:
11858: The @file{ans-report.fs} tool makes it easy for you to determine which
11859: words from which wordset and which non-ANS words your application
11860: uses. You simply have to include @file{ans-report.fs} before loading the
11861: program you want to check. After loading your program, you can get the
11862: report with @code{print-ans-report}. A typical use is to run this as
11863: batch job like this:
11864: @example
11865: gforth ans-report.fs myprog.fs -e "print-ans-report bye"
11866: @end example
11867:
11868: The output looks like this (for @file{compat/control.fs}):
11869: @example
11870: The program uses the following words
11871: from CORE :
11872: : POSTPONE THEN ; immediate ?dup IF 0=
11873: from BLOCK-EXT :
11874: \
11875: from FILE :
11876: (
11877: @end example
11878:
11879: @subsection Caveats
11880:
11881: Note that @file{ans-report.fs} just checks which words are used, not whether
11882: they are used in an ANS Forth conforming way!
11883:
11884: Some words are defined in several wordsets in the
11885: standard. @file{ans-report.fs} reports them for only one of the
11886: wordsets, and not necessarily the one you expect. It depends on usage
11887: which wordset is the right one to specify. E.g., if you only use the
11888: compilation semantics of @code{S"}, it is a Core word; if you also use
11889: its interpretation semantics, it is a File word.
11890:
11891: @c ******************************************************************
1.65 anton 11892: @node ANS conformance, Standard vs Extensions, Tools, Top
1.1 anton 11893: @chapter ANS conformance
11894: @cindex ANS conformance of Gforth
11895:
11896: To the best of our knowledge, Gforth is an
11897:
11898: ANS Forth System
11899: @itemize @bullet
11900: @item providing the Core Extensions word set
11901: @item providing the Block word set
11902: @item providing the Block Extensions word set
11903: @item providing the Double-Number word set
11904: @item providing the Double-Number Extensions word set
11905: @item providing the Exception word set
11906: @item providing the Exception Extensions word set
11907: @item providing the Facility word set
1.40 anton 11908: @item providing @code{EKEY}, @code{EKEY>CHAR}, @code{EKEY?}, @code{MS} and @code{TIME&DATE} from the Facility Extensions word set
1.1 anton 11909: @item providing the File Access word set
11910: @item providing the File Access Extensions word set
11911: @item providing the Floating-Point word set
11912: @item providing the Floating-Point Extensions word set
11913: @item providing the Locals word set
11914: @item providing the Locals Extensions word set
11915: @item providing the Memory-Allocation word set
11916: @item providing the Memory-Allocation Extensions word set (that one's easy)
11917: @item providing the Programming-Tools word set
11918: @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
11919: @item providing the Search-Order word set
11920: @item providing the Search-Order Extensions word set
11921: @item providing the String word set
11922: @item providing the String Extensions word set (another easy one)
11923: @end itemize
11924:
11925: @cindex system documentation
11926: In addition, ANS Forth systems are required to document certain
11927: implementation choices. This chapter tries to meet these
11928: requirements. In many cases it gives a way to ask the system for the
11929: information instead of providing the information directly, in
11930: particular, if the information depends on the processor, the operating
11931: system or the installation options chosen, or if they are likely to
11932: change during the maintenance of Gforth.
11933:
11934: @comment The framework for the rest has been taken from pfe.
11935:
11936: @menu
11937: * The Core Words::
11938: * The optional Block word set::
11939: * The optional Double Number word set::
11940: * The optional Exception word set::
11941: * The optional Facility word set::
11942: * The optional File-Access word set::
11943: * The optional Floating-Point word set::
11944: * The optional Locals word set::
11945: * The optional Memory-Allocation word set::
11946: * The optional Programming-Tools word set::
11947: * The optional Search-Order word set::
11948: @end menu
11949:
11950:
11951: @c =====================================================================
11952: @node The Core Words, The optional Block word set, ANS conformance, ANS conformance
11953: @comment node-name, next, previous, up
11954: @section The Core Words
11955: @c =====================================================================
11956: @cindex core words, system documentation
11957: @cindex system documentation, core words
11958:
11959: @menu
11960: * core-idef:: Implementation Defined Options
11961: * core-ambcond:: Ambiguous Conditions
11962: * core-other:: Other System Documentation
11963: @end menu
11964:
11965: @c ---------------------------------------------------------------------
11966: @node core-idef, core-ambcond, The Core Words, The Core Words
11967: @subsection Implementation Defined Options
11968: @c ---------------------------------------------------------------------
11969: @cindex core words, implementation-defined options
11970: @cindex implementation-defined options, core words
11971:
11972:
11973: @table @i
11974: @item (Cell) aligned addresses:
11975: @cindex cell-aligned addresses
11976: @cindex aligned addresses
11977: processor-dependent. Gforth's alignment words perform natural alignment
11978: (e.g., an address aligned for a datum of size 8 is divisible by
11979: 8). Unaligned accesses usually result in a @code{-23 THROW}.
11980:
11981: @item @code{EMIT} and non-graphic characters:
11982: @cindex @code{EMIT} and non-graphic characters
11983: @cindex non-graphic characters and @code{EMIT}
11984: The character is output using the C library function (actually, macro)
11985: @code{putc}.
11986:
11987: @item character editing of @code{ACCEPT} and @code{EXPECT}:
11988: @cindex character editing of @code{ACCEPT} and @code{EXPECT}
11989: @cindex editing in @code{ACCEPT} and @code{EXPECT}
11990: @cindex @code{ACCEPT}, editing
11991: @cindex @code{EXPECT}, editing
11992: This is modeled on the GNU readline library (@pxref{Readline
11993: Interaction, , Command Line Editing, readline, The GNU Readline
11994: Library}) with Emacs-like key bindings. @kbd{Tab} deviates a little by
11995: producing a full word completion every time you type it (instead of
1.28 crook 11996: producing the common prefix of all completions). @xref{Command-line editing}.
1.1 anton 11997:
11998: @item character set:
11999: @cindex character set
12000: The character set of your computer and display device. Gforth is
12001: 8-bit-clean (but some other component in your system may make trouble).
12002:
12003: @item Character-aligned address requirements:
12004: @cindex character-aligned address requirements
12005: installation-dependent. Currently a character is represented by a C
12006: @code{unsigned char}; in the future we might switch to @code{wchar_t}
12007: (Comments on that requested).
12008:
12009: @item character-set extensions and matching of names:
12010: @cindex character-set extensions and matching of names
1.26 crook 12011: @cindex case-sensitivity for name lookup
12012: @cindex name lookup, case-sensitivity
12013: @cindex locale and case-sensitivity
1.21 crook 12014: Any character except the ASCII NUL character can be used in a
1.1 anton 12015: name. Matching is case-insensitive (except in @code{TABLE}s). The
1.47 crook 12016: matching is performed using the C library function @code{strncasecmp}, whose
1.1 anton 12017: function is probably influenced by the locale. E.g., the @code{C} locale
12018: does not know about accents and umlauts, so they are matched
12019: case-sensitively in that locale. For portability reasons it is best to
12020: write programs such that they work in the @code{C} locale. Then one can
12021: use libraries written by a Polish programmer (who might use words
12022: containing ISO Latin-2 encoded characters) and by a French programmer
12023: (ISO Latin-1) in the same program (of course, @code{WORDS} will produce
12024: funny results for some of the words (which ones, depends on the font you
12025: are using)). Also, the locale you prefer may not be available in other
12026: operating systems. Hopefully, Unicode will solve these problems one day.
12027:
12028: @item conditions under which control characters match a space delimiter:
12029: @cindex space delimiters
12030: @cindex control characters as delimiters
12031: If @code{WORD} is called with the space character as a delimiter, all
12032: white-space characters (as identified by the C macro @code{isspace()})
12033: are delimiters. @code{PARSE}, on the other hand, treats space like other
1.44 crook 12034: delimiters. @code{SWORD} treats space like @code{WORD}, but behaves
1.1 anton 12035: like @code{PARSE} otherwise. @code{(NAME)}, which is used by the outer
12036: interpreter (aka text interpreter) by default, treats all white-space
12037: characters as delimiters.
12038:
1.26 crook 12039: @item format of the control-flow stack:
12040: @cindex control-flow stack, format
12041: The data stack is used as control-flow stack. The size of a control-flow
1.1 anton 12042: stack item in cells is given by the constant @code{cs-item-size}. At the
12043: time of this writing, an item consists of a (pointer to a) locals list
12044: (third), an address in the code (second), and a tag for identifying the
12045: item (TOS). The following tags are used: @code{defstart},
12046: @code{live-orig}, @code{dead-orig}, @code{dest}, @code{do-dest},
12047: @code{scopestart}.
12048:
12049: @item conversion of digits > 35
12050: @cindex digits > 35
12051: The characters @code{[\]^_'} are the digits with the decimal value
12052: 36@minus{}41. There is no way to input many of the larger digits.
12053:
12054: @item display after input terminates in @code{ACCEPT} and @code{EXPECT}:
12055: @cindex @code{EXPECT}, display after end of input
12056: @cindex @code{ACCEPT}, display after end of input
12057: The cursor is moved to the end of the entered string. If the input is
12058: terminated using the @kbd{Return} key, a space is typed.
12059:
12060: @item exception abort sequence of @code{ABORT"}:
12061: @cindex exception abort sequence of @code{ABORT"}
12062: @cindex @code{ABORT"}, exception abort sequence
12063: The error string is stored into the variable @code{"error} and a
12064: @code{-2 throw} is performed.
12065:
12066: @item input line terminator:
12067: @cindex input line terminator
12068: @cindex line terminator on input
1.26 crook 12069: @cindex newline character on input
1.1 anton 12070: For interactive input, @kbd{C-m} (CR) and @kbd{C-j} (LF) terminate
12071: lines. One of these characters is typically produced when you type the
12072: @kbd{Enter} or @kbd{Return} key.
12073:
12074: @item maximum size of a counted string:
12075: @cindex maximum size of a counted string
12076: @cindex counted string, maximum size
12077: @code{s" /counted-string" environment? drop .}. Currently 255 characters
12078: on all ports, but this may change.
12079:
12080: @item maximum size of a parsed string:
12081: @cindex maximum size of a parsed string
12082: @cindex parsed string, maximum size
12083: Given by the constant @code{/line}. Currently 255 characters.
12084:
12085: @item maximum size of a definition name, in characters:
12086: @cindex maximum size of a definition name, in characters
12087: @cindex name, maximum length
12088: 31
12089:
12090: @item maximum string length for @code{ENVIRONMENT?}, in characters:
12091: @cindex maximum string length for @code{ENVIRONMENT?}, in characters
12092: @cindex @code{ENVIRONMENT?} string length, maximum
12093: 31
12094:
12095: @item method of selecting the user input device:
12096: @cindex user input device, method of selecting
12097: The user input device is the standard input. There is currently no way to
12098: change it from within Gforth. However, the input can typically be
12099: redirected in the command line that starts Gforth.
12100:
12101: @item method of selecting the user output device:
12102: @cindex user output device, method of selecting
12103: @code{EMIT} and @code{TYPE} output to the file-id stored in the value
1.10 anton 12104: @code{outfile-id} (@code{stdout} by default). Gforth uses unbuffered
12105: output when the user output device is a terminal, otherwise the output
12106: is buffered.
1.1 anton 12107:
12108: @item methods of dictionary compilation:
12109: What are we expected to document here?
12110:
12111: @item number of bits in one address unit:
12112: @cindex number of bits in one address unit
12113: @cindex address unit, size in bits
12114: @code{s" address-units-bits" environment? drop .}. 8 in all current
12115: ports.
12116:
12117: @item number representation and arithmetic:
12118: @cindex number representation and arithmetic
12119: Processor-dependent. Binary two's complement on all current ports.
12120:
12121: @item ranges for integer types:
12122: @cindex ranges for integer types
12123: @cindex integer types, ranges
12124: Installation-dependent. Make environmental queries for @code{MAX-N},
12125: @code{MAX-U}, @code{MAX-D} and @code{MAX-UD}. The lower bounds for
12126: unsigned (and positive) types is 0. The lower bound for signed types on
12127: two's complement and one's complement machines machines can be computed
12128: by adding 1 to the upper bound.
12129:
12130: @item read-only data space regions:
12131: @cindex read-only data space regions
12132: @cindex data-space, read-only regions
12133: The whole Forth data space is writable.
12134:
12135: @item size of buffer at @code{WORD}:
12136: @cindex size of buffer at @code{WORD}
12137: @cindex @code{WORD} buffer size
12138: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
12139: shared with the pictured numeric output string. If overwriting
12140: @code{PAD} is acceptable, it is as large as the remaining dictionary
12141: space, although only as much can be sensibly used as fits in a counted
12142: string.
12143:
12144: @item size of one cell in address units:
12145: @cindex cell size
12146: @code{1 cells .}.
12147:
12148: @item size of one character in address units:
12149: @cindex char size
12150: @code{1 chars .}. 1 on all current ports.
12151:
12152: @item size of the keyboard terminal buffer:
12153: @cindex size of the keyboard terminal buffer
12154: @cindex terminal buffer, size
12155: Varies. You can determine the size at a specific time using @code{lp@@
12156: tib - .}. It is shared with the locals stack and TIBs of files that
12157: include the current file. You can change the amount of space for TIBs
12158: and locals stack at Gforth startup with the command line option
12159: @code{-l}.
12160:
12161: @item size of the pictured numeric output buffer:
12162: @cindex size of the pictured numeric output buffer
12163: @cindex pictured numeric output buffer, size
12164: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
12165: shared with @code{WORD}.
12166:
12167: @item size of the scratch area returned by @code{PAD}:
12168: @cindex size of the scratch area returned by @code{PAD}
12169: @cindex @code{PAD} size
12170: The remainder of dictionary space. @code{unused pad here - - .}.
12171:
12172: @item system case-sensitivity characteristics:
12173: @cindex case-sensitivity characteristics
1.26 crook 12174: Dictionary searches are case-insensitive (except in
1.1 anton 12175: @code{TABLE}s). However, as explained above under @i{character-set
12176: extensions}, the matching for non-ASCII characters is determined by the
12177: locale you are using. In the default @code{C} locale all non-ASCII
12178: characters are matched case-sensitively.
12179:
12180: @item system prompt:
12181: @cindex system prompt
12182: @cindex prompt
12183: @code{ ok} in interpret state, @code{ compiled} in compile state.
12184:
12185: @item division rounding:
12186: @cindex division rounding
12187: installation dependent. @code{s" floored" environment? drop .}. We leave
12188: the choice to @code{gcc} (what to use for @code{/}) and to you (whether
12189: to use @code{fm/mod}, @code{sm/rem} or simply @code{/}).
12190:
12191: @item values of @code{STATE} when true:
12192: @cindex @code{STATE} values
12193: -1.
12194:
12195: @item values returned after arithmetic overflow:
12196: On two's complement machines, arithmetic is performed modulo
12197: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
12198: arithmetic (with appropriate mapping for signed types). Division by zero
12199: typically results in a @code{-55 throw} (Floating-point unidentified
12200: fault), although a @code{-10 throw} (divide by zero) would be more
12201: appropriate.
12202:
12203: @item whether the current definition can be found after @t{DOES>}:
12204: @cindex @t{DOES>}, visibility of current definition
12205: No.
12206:
12207: @end table
12208:
12209: @c ---------------------------------------------------------------------
12210: @node core-ambcond, core-other, core-idef, The Core Words
12211: @subsection Ambiguous conditions
12212: @c ---------------------------------------------------------------------
12213: @cindex core words, ambiguous conditions
12214: @cindex ambiguous conditions, core words
12215:
12216: @table @i
12217:
12218: @item a name is neither a word nor a number:
12219: @cindex name not found
1.26 crook 12220: @cindex undefined word
1.1 anton 12221: @code{-13 throw} (Undefined word). Actually, @code{-13 bounce}, which
12222: preserves the data and FP stack, so you don't lose more work than
12223: necessary.
12224:
12225: @item a definition name exceeds the maximum length allowed:
1.26 crook 12226: @cindex word name too long
1.1 anton 12227: @code{-19 throw} (Word name too long)
12228:
12229: @item addressing a region not inside the various data spaces of the forth system:
12230: @cindex Invalid memory address
1.32 anton 12231: The stacks, code space and header space are accessible. Machine code space is
1.1 anton 12232: typically readable. Accessing other addresses gives results dependent on
12233: the operating system. On decent systems: @code{-9 throw} (Invalid memory
12234: address).
12235:
12236: @item argument type incompatible with parameter:
1.26 crook 12237: @cindex argument type mismatch
1.1 anton 12238: This is usually not caught. Some words perform checks, e.g., the control
12239: flow words, and issue a @code{ABORT"} or @code{-12 THROW} (Argument type
12240: mismatch).
12241:
12242: @item attempting to obtain the execution token of a word with undefined execution semantics:
12243: @cindex Interpreting a compile-only word, for @code{'} etc.
12244: @cindex execution token of words with undefined execution semantics
12245: @code{-14 throw} (Interpreting a compile-only word). In some cases, you
12246: get an execution token for @code{compile-only-error} (which performs a
12247: @code{-14 throw} when executed).
12248:
12249: @item dividing by zero:
12250: @cindex dividing by zero
12251: @cindex floating point unidentified fault, integer division
1.24 anton 12252: On better platforms, this produces a @code{-10 throw} (Division by
12253: zero); on other systems, this typically results in a @code{-55 throw}
12254: (Floating-point unidentified fault).
1.1 anton 12255:
12256: @item insufficient data stack or return stack space:
12257: @cindex insufficient data stack or return stack space
12258: @cindex stack overflow
1.26 crook 12259: @cindex address alignment exception, stack overflow
1.1 anton 12260: @cindex Invalid memory address, stack overflow
12261: Depending on the operating system, the installation, and the invocation
12262: of Gforth, this is either checked by the memory management hardware, or
1.24 anton 12263: it is not checked. If it is checked, you typically get a @code{-3 throw}
12264: (Stack overflow), @code{-5 throw} (Return stack overflow), or @code{-9
12265: throw} (Invalid memory address) (depending on the platform and how you
12266: achieved the overflow) as soon as the overflow happens. If it is not
12267: checked, overflows typically result in mysterious illegal memory
12268: accesses, producing @code{-9 throw} (Invalid memory address) or
12269: @code{-23 throw} (Address alignment exception); they might also destroy
12270: the internal data structure of @code{ALLOCATE} and friends, resulting in
12271: various errors in these words.
1.1 anton 12272:
12273: @item insufficient space for loop control parameters:
12274: @cindex insufficient space for loop control parameters
12275: like other return stack overflows.
12276:
12277: @item insufficient space in the dictionary:
12278: @cindex insufficient space in the dictionary
12279: @cindex dictionary overflow
1.12 anton 12280: If you try to allot (either directly with @code{allot}, or indirectly
12281: with @code{,}, @code{create} etc.) more memory than available in the
12282: dictionary, you get a @code{-8 throw} (Dictionary overflow). If you try
12283: to access memory beyond the end of the dictionary, the results are
12284: similar to stack overflows.
1.1 anton 12285:
12286: @item interpreting a word with undefined interpretation semantics:
12287: @cindex interpreting a word with undefined interpretation semantics
12288: @cindex Interpreting a compile-only word
12289: For some words, we have defined interpretation semantics. For the
12290: others: @code{-14 throw} (Interpreting a compile-only word).
12291:
12292: @item modifying the contents of the input buffer or a string literal:
12293: @cindex modifying the contents of the input buffer or a string literal
12294: These are located in writable memory and can be modified.
12295:
12296: @item overflow of the pictured numeric output string:
12297: @cindex overflow of the pictured numeric output string
12298: @cindex pictured numeric output string, overflow
1.24 anton 12299: @code{-17 throw} (Pictured numeric ouput string overflow).
1.1 anton 12300:
12301: @item parsed string overflow:
12302: @cindex parsed string overflow
12303: @code{PARSE} cannot overflow. @code{WORD} does not check for overflow.
12304:
12305: @item producing a result out of range:
12306: @cindex result out of range
12307: On two's complement machines, arithmetic is performed modulo
12308: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
12309: arithmetic (with appropriate mapping for signed types). Division by zero
1.24 anton 12310: typically results in a @code{-10 throw} (divide by zero) or @code{-55
12311: throw} (floating point unidentified fault). @code{convert} and
12312: @code{>number} currently overflow silently.
1.1 anton 12313:
12314: @item reading from an empty data or return stack:
12315: @cindex stack empty
12316: @cindex stack underflow
1.24 anton 12317: @cindex return stack underflow
1.1 anton 12318: The data stack is checked by the outer (aka text) interpreter after
12319: every word executed. If it has underflowed, a @code{-4 throw} (Stack
12320: underflow) is performed. Apart from that, stacks may be checked or not,
1.24 anton 12321: depending on operating system, installation, and invocation. If they are
12322: caught by a check, they typically result in @code{-4 throw} (Stack
12323: underflow), @code{-6 throw} (Return stack underflow) or @code{-9 throw}
12324: (Invalid memory address), depending on the platform and which stack
12325: underflows and by how much. Note that even if the system uses checking
12326: (through the MMU), your program may have to underflow by a significant
12327: number of stack items to trigger the reaction (the reason for this is
12328: that the MMU, and therefore the checking, works with a page-size
12329: granularity). If there is no checking, the symptoms resulting from an
12330: underflow are similar to those from an overflow. Unbalanced return
12331: stack errors result in a variaty of symptoms, including @code{-9 throw}
12332: (Invalid memory address) and Illegal Instruction (typically @code{-260
12333: throw}).
1.1 anton 12334:
12335: @item unexpected end of the input buffer, resulting in an attempt to use a zero-length string as a name:
12336: @cindex unexpected end of the input buffer
12337: @cindex zero-length string as a name
12338: @cindex Attempt to use zero-length string as a name
12339: @code{Create} and its descendants perform a @code{-16 throw} (Attempt to
12340: use zero-length string as a name). Words like @code{'} probably will not
12341: find what they search. Note that it is possible to create zero-length
12342: names with @code{nextname} (should it not?).
12343:
12344: @item @code{>IN} greater than input buffer:
12345: @cindex @code{>IN} greater than input buffer
12346: The next invocation of a parsing word returns a string with length 0.
12347:
12348: @item @code{RECURSE} appears after @code{DOES>}:
12349: @cindex @code{RECURSE} appears after @code{DOES>}
12350: Compiles a recursive call to the defining word, not to the defined word.
12351:
12352: @item argument input source different than current input source for @code{RESTORE-INPUT}:
12353: @cindex argument input source different than current input source for @code{RESTORE-INPUT}
1.26 crook 12354: @cindex argument type mismatch, @code{RESTORE-INPUT}
1.1 anton 12355: @cindex @code{RESTORE-INPUT}, Argument type mismatch
12356: @code{-12 THROW}. Note that, once an input file is closed (e.g., because
12357: the end of the file was reached), its source-id may be
12358: reused. Therefore, restoring an input source specification referencing a
12359: closed file may lead to unpredictable results instead of a @code{-12
12360: THROW}.
12361:
12362: In the future, Gforth may be able to restore input source specifications
12363: from other than the current input source.
12364:
12365: @item data space containing definitions gets de-allocated:
12366: @cindex data space containing definitions gets de-allocated
12367: Deallocation with @code{allot} is not checked. This typically results in
12368: memory access faults or execution of illegal instructions.
12369:
12370: @item data space read/write with incorrect alignment:
12371: @cindex data space read/write with incorrect alignment
12372: @cindex alignment faults
1.26 crook 12373: @cindex address alignment exception
1.1 anton 12374: Processor-dependent. Typically results in a @code{-23 throw} (Address
1.12 anton 12375: alignment exception). Under Linux-Intel on a 486 or later processor with
1.1 anton 12376: alignment turned on, incorrect alignment results in a @code{-9 throw}
12377: (Invalid memory address). There are reportedly some processors with
1.12 anton 12378: alignment restrictions that do not report violations.
1.1 anton 12379:
12380: @item data space pointer not properly aligned, @code{,}, @code{C,}:
12381: @cindex data space pointer not properly aligned, @code{,}, @code{C,}
12382: Like other alignment errors.
12383:
12384: @item less than u+2 stack items (@code{PICK} and @code{ROLL}):
12385: Like other stack underflows.
12386:
12387: @item loop control parameters not available:
12388: @cindex loop control parameters not available
12389: Not checked. The counted loop words simply assume that the top of return
12390: stack items are loop control parameters and behave accordingly.
12391:
12392: @item most recent definition does not have a name (@code{IMMEDIATE}):
12393: @cindex most recent definition does not have a name (@code{IMMEDIATE})
12394: @cindex last word was headerless
12395: @code{abort" last word was headerless"}.
12396:
12397: @item name not defined by @code{VALUE} used by @code{TO}:
12398: @cindex name not defined by @code{VALUE} used by @code{TO}
12399: @cindex @code{TO} on non-@code{VALUE}s
12400: @cindex Invalid name argument, @code{TO}
12401: @code{-32 throw} (Invalid name argument) (unless name is a local or was
12402: defined by @code{CONSTANT}; in the latter case it just changes the constant).
12403:
12404: @item name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}):
12405: @cindex name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]})
1.26 crook 12406: @cindex undefined word, @code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}
1.1 anton 12407: @code{-13 throw} (Undefined word)
12408:
12409: @item parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN}):
12410: @cindex parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN})
12411: Gforth behaves as if they were of the same type. I.e., you can predict
12412: the behaviour by interpreting all parameters as, e.g., signed.
12413:
12414: @item @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}:
12415: @cindex @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}
12416: Assume @code{: X POSTPONE TO ; IMMEDIATE}. @code{X} performs the
12417: compilation semantics of @code{TO}.
12418:
12419: @item String longer than a counted string returned by @code{WORD}:
1.26 crook 12420: @cindex string longer than a counted string returned by @code{WORD}
1.1 anton 12421: @cindex @code{WORD}, string overflow
12422: Not checked. The string will be ok, but the count will, of course,
12423: contain only the least significant bits of the length.
12424:
12425: @item u greater than or equal to the number of bits in a cell (@code{LSHIFT}, @code{RSHIFT}):
12426: @cindex @code{LSHIFT}, large shift counts
12427: @cindex @code{RSHIFT}, large shift counts
12428: Processor-dependent. Typical behaviours are returning 0 and using only
12429: the low bits of the shift count.
12430:
12431: @item word not defined via @code{CREATE}:
12432: @cindex @code{>BODY} of non-@code{CREATE}d words
12433: @code{>BODY} produces the PFA of the word no matter how it was defined.
12434:
12435: @cindex @code{DOES>} of non-@code{CREATE}d words
12436: @code{DOES>} changes the execution semantics of the last defined word no
12437: matter how it was defined. E.g., @code{CONSTANT DOES>} is equivalent to
12438: @code{CREATE , DOES>}.
12439:
12440: @item words improperly used outside @code{<#} and @code{#>}:
12441: Not checked. As usual, you can expect memory faults.
12442:
12443: @end table
12444:
12445:
12446: @c ---------------------------------------------------------------------
12447: @node core-other, , core-ambcond, The Core Words
12448: @subsection Other system documentation
12449: @c ---------------------------------------------------------------------
12450: @cindex other system documentation, core words
12451: @cindex core words, other system documentation
12452:
12453: @table @i
12454: @item nonstandard words using @code{PAD}:
12455: @cindex @code{PAD} use by nonstandard words
12456: None.
12457:
12458: @item operator's terminal facilities available:
12459: @cindex operator's terminal facilities available
12460: After processing the command line, Gforth goes into interactive mode,
12461: and you can give commands to Gforth interactively. The actual facilities
12462: available depend on how you invoke Gforth.
12463:
12464: @item program data space available:
12465: @cindex program data space available
12466: @cindex data space available
12467: @code{UNUSED .} gives the remaining dictionary space. The total
12468: dictionary space can be specified with the @code{-m} switch
12469: (@pxref{Invoking Gforth}) when Gforth starts up.
12470:
12471: @item return stack space available:
12472: @cindex return stack space available
12473: You can compute the total return stack space in cells with
12474: @code{s" RETURN-STACK-CELLS" environment? drop .}. You can specify it at
12475: startup time with the @code{-r} switch (@pxref{Invoking Gforth}).
12476:
12477: @item stack space available:
12478: @cindex stack space available
12479: You can compute the total data stack space in cells with
12480: @code{s" STACK-CELLS" environment? drop .}. You can specify it at
12481: startup time with the @code{-d} switch (@pxref{Invoking Gforth}).
12482:
12483: @item system dictionary space required, in address units:
12484: @cindex system dictionary space required, in address units
12485: Type @code{here forthstart - .} after startup. At the time of this
12486: writing, this gives 80080 (bytes) on a 32-bit system.
12487: @end table
12488:
12489:
12490: @c =====================================================================
12491: @node The optional Block word set, The optional Double Number word set, The Core Words, ANS conformance
12492: @section The optional Block word set
12493: @c =====================================================================
12494: @cindex system documentation, block words
12495: @cindex block words, system documentation
12496:
12497: @menu
12498: * block-idef:: Implementation Defined Options
12499: * block-ambcond:: Ambiguous Conditions
12500: * block-other:: Other System Documentation
12501: @end menu
12502:
12503:
12504: @c ---------------------------------------------------------------------
12505: @node block-idef, block-ambcond, The optional Block word set, The optional Block word set
12506: @subsection Implementation Defined Options
12507: @c ---------------------------------------------------------------------
12508: @cindex implementation-defined options, block words
12509: @cindex block words, implementation-defined options
12510:
12511: @table @i
12512: @item the format for display by @code{LIST}:
12513: @cindex @code{LIST} display format
12514: First the screen number is displayed, then 16 lines of 64 characters,
12515: each line preceded by the line number.
12516:
12517: @item the length of a line affected by @code{\}:
12518: @cindex length of a line affected by @code{\}
12519: @cindex @code{\}, line length in blocks
12520: 64 characters.
12521: @end table
12522:
12523:
12524: @c ---------------------------------------------------------------------
12525: @node block-ambcond, block-other, block-idef, The optional Block word set
12526: @subsection Ambiguous conditions
12527: @c ---------------------------------------------------------------------
12528: @cindex block words, ambiguous conditions
12529: @cindex ambiguous conditions, block words
12530:
12531: @table @i
12532: @item correct block read was not possible:
12533: @cindex block read not possible
12534: Typically results in a @code{throw} of some OS-derived value (between
12535: -512 and -2048). If the blocks file was just not long enough, blanks are
12536: supplied for the missing portion.
12537:
12538: @item I/O exception in block transfer:
12539: @cindex I/O exception in block transfer
12540: @cindex block transfer, I/O exception
12541: Typically results in a @code{throw} of some OS-derived value (between
12542: -512 and -2048).
12543:
12544: @item invalid block number:
12545: @cindex invalid block number
12546: @cindex block number invalid
12547: @code{-35 throw} (Invalid block number)
12548:
12549: @item a program directly alters the contents of @code{BLK}:
12550: @cindex @code{BLK}, altering @code{BLK}
12551: The input stream is switched to that other block, at the same
12552: position. If the storing to @code{BLK} happens when interpreting
12553: non-block input, the system will get quite confused when the block ends.
12554:
12555: @item no current block buffer for @code{UPDATE}:
12556: @cindex @code{UPDATE}, no current block buffer
12557: @code{UPDATE} has no effect.
12558:
12559: @end table
12560:
12561: @c ---------------------------------------------------------------------
12562: @node block-other, , block-ambcond, The optional Block word set
12563: @subsection Other system documentation
12564: @c ---------------------------------------------------------------------
12565: @cindex other system documentation, block words
12566: @cindex block words, other system documentation
12567:
12568: @table @i
12569: @item any restrictions a multiprogramming system places on the use of buffer addresses:
12570: No restrictions (yet).
12571:
12572: @item the number of blocks available for source and data:
12573: depends on your disk space.
12574:
12575: @end table
12576:
12577:
12578: @c =====================================================================
12579: @node The optional Double Number word set, The optional Exception word set, The optional Block word set, ANS conformance
12580: @section The optional Double Number word set
12581: @c =====================================================================
12582: @cindex system documentation, double words
12583: @cindex double words, system documentation
12584:
12585: @menu
12586: * double-ambcond:: Ambiguous Conditions
12587: @end menu
12588:
12589:
12590: @c ---------------------------------------------------------------------
12591: @node double-ambcond, , The optional Double Number word set, The optional Double Number word set
12592: @subsection Ambiguous conditions
12593: @c ---------------------------------------------------------------------
12594: @cindex double words, ambiguous conditions
12595: @cindex ambiguous conditions, double words
12596:
12597: @table @i
1.29 crook 12598: @item @i{d} outside of range of @i{n} in @code{D>S}:
12599: @cindex @code{D>S}, @i{d} out of range of @i{n}
12600: The least significant cell of @i{d} is produced.
1.1 anton 12601:
12602: @end table
12603:
12604:
12605: @c =====================================================================
12606: @node The optional Exception word set, The optional Facility word set, The optional Double Number word set, ANS conformance
12607: @section The optional Exception word set
12608: @c =====================================================================
12609: @cindex system documentation, exception words
12610: @cindex exception words, system documentation
12611:
12612: @menu
12613: * exception-idef:: Implementation Defined Options
12614: @end menu
12615:
12616:
12617: @c ---------------------------------------------------------------------
12618: @node exception-idef, , The optional Exception word set, The optional Exception word set
12619: @subsection Implementation Defined Options
12620: @c ---------------------------------------------------------------------
12621: @cindex implementation-defined options, exception words
12622: @cindex exception words, implementation-defined options
12623:
12624: @table @i
12625: @item @code{THROW}-codes used in the system:
12626: @cindex @code{THROW}-codes used in the system
12627: The codes -256@minus{}-511 are used for reporting signals. The mapping
1.29 crook 12628: from OS signal numbers to throw codes is -256@minus{}@i{signal}. The
1.1 anton 12629: codes -512@minus{}-2047 are used for OS errors (for file and memory
12630: allocation operations). The mapping from OS error numbers to throw codes
12631: is -512@minus{}@code{errno}. One side effect of this mapping is that
12632: undefined OS errors produce a message with a strange number; e.g.,
12633: @code{-1000 THROW} results in @code{Unknown error 488} on my system.
12634: @end table
12635:
12636: @c =====================================================================
12637: @node The optional Facility word set, The optional File-Access word set, The optional Exception word set, ANS conformance
12638: @section The optional Facility word set
12639: @c =====================================================================
12640: @cindex system documentation, facility words
12641: @cindex facility words, system documentation
12642:
12643: @menu
12644: * facility-idef:: Implementation Defined Options
12645: * facility-ambcond:: Ambiguous Conditions
12646: @end menu
12647:
12648:
12649: @c ---------------------------------------------------------------------
12650: @node facility-idef, facility-ambcond, The optional Facility word set, The optional Facility word set
12651: @subsection Implementation Defined Options
12652: @c ---------------------------------------------------------------------
12653: @cindex implementation-defined options, facility words
12654: @cindex facility words, implementation-defined options
12655:
12656: @table @i
12657: @item encoding of keyboard events (@code{EKEY}):
12658: @cindex keyboard events, encoding in @code{EKEY}
12659: @cindex @code{EKEY}, encoding of keyboard events
1.40 anton 12660: Keys corresponding to ASCII characters are encoded as ASCII characters.
1.41 anton 12661: Other keys are encoded with the constants @code{k-left}, @code{k-right},
12662: @code{k-up}, @code{k-down}, @code{k-home}, @code{k-end}, @code{k1},
12663: @code{k2}, @code{k3}, @code{k4}, @code{k5}, @code{k6}, @code{k7},
12664: @code{k8}, @code{k9}, @code{k10}, @code{k11}, @code{k12}.
1.40 anton 12665:
1.1 anton 12666:
12667: @item duration of a system clock tick:
12668: @cindex duration of a system clock tick
12669: @cindex clock tick duration
12670: System dependent. With respect to @code{MS}, the time is specified in
12671: microseconds. How well the OS and the hardware implement this, is
12672: another question.
12673:
12674: @item repeatability to be expected from the execution of @code{MS}:
12675: @cindex repeatability to be expected from the execution of @code{MS}
12676: @cindex @code{MS}, repeatability to be expected
12677: System dependent. On Unix, a lot depends on load. If the system is
12678: lightly loaded, and the delay is short enough that Gforth does not get
12679: swapped out, the performance should be acceptable. Under MS-DOS and
12680: other single-tasking systems, it should be good.
12681:
12682: @end table
12683:
12684:
12685: @c ---------------------------------------------------------------------
12686: @node facility-ambcond, , facility-idef, The optional Facility word set
12687: @subsection Ambiguous conditions
12688: @c ---------------------------------------------------------------------
12689: @cindex facility words, ambiguous conditions
12690: @cindex ambiguous conditions, facility words
12691:
12692: @table @i
12693: @item @code{AT-XY} can't be performed on user output device:
12694: @cindex @code{AT-XY} can't be performed on user output device
12695: Largely terminal dependent. No range checks are done on the arguments.
12696: No errors are reported. You may see some garbage appearing, you may see
12697: simply nothing happen.
12698:
12699: @end table
12700:
12701:
12702: @c =====================================================================
12703: @node The optional File-Access word set, The optional Floating-Point word set, The optional Facility word set, ANS conformance
12704: @section The optional File-Access word set
12705: @c =====================================================================
12706: @cindex system documentation, file words
12707: @cindex file words, system documentation
12708:
12709: @menu
12710: * file-idef:: Implementation Defined Options
12711: * file-ambcond:: Ambiguous Conditions
12712: @end menu
12713:
12714: @c ---------------------------------------------------------------------
12715: @node file-idef, file-ambcond, The optional File-Access word set, The optional File-Access word set
12716: @subsection Implementation Defined Options
12717: @c ---------------------------------------------------------------------
12718: @cindex implementation-defined options, file words
12719: @cindex file words, implementation-defined options
12720:
12721: @table @i
12722: @item file access methods used:
12723: @cindex file access methods used
12724: @code{R/O}, @code{R/W} and @code{BIN} work as you would
12725: expect. @code{W/O} translates into the C file opening mode @code{w} (or
12726: @code{wb}): The file is cleared, if it exists, and created, if it does
12727: not (with both @code{open-file} and @code{create-file}). Under Unix
12728: @code{create-file} creates a file with 666 permissions modified by your
12729: umask.
12730:
12731: @item file exceptions:
12732: @cindex file exceptions
12733: The file words do not raise exceptions (except, perhaps, memory access
12734: faults when you pass illegal addresses or file-ids).
12735:
12736: @item file line terminator:
12737: @cindex file line terminator
12738: System-dependent. Gforth uses C's newline character as line
12739: terminator. What the actual character code(s) of this are is
12740: system-dependent.
12741:
12742: @item file name format:
12743: @cindex file name format
12744: System dependent. Gforth just uses the file name format of your OS.
12745:
12746: @item information returned by @code{FILE-STATUS}:
12747: @cindex @code{FILE-STATUS}, returned information
12748: @code{FILE-STATUS} returns the most powerful file access mode allowed
12749: for the file: Either @code{R/O}, @code{W/O} or @code{R/W}. If the file
12750: cannot be accessed, @code{R/O BIN} is returned. @code{BIN} is applicable
12751: along with the returned mode.
12752:
12753: @item input file state after an exception when including source:
12754: @cindex exception when including source
12755: All files that are left via the exception are closed.
12756:
1.29 crook 12757: @item @i{ior} values and meaning:
12758: @cindex @i{ior} values and meaning
1.68 anton 12759: @cindex @i{wior} values and meaning
1.29 crook 12760: The @i{ior}s returned by the file and memory allocation words are
1.1 anton 12761: intended as throw codes. They typically are in the range
12762: -512@minus{}-2047 of OS errors. The mapping from OS error numbers to
1.29 crook 12763: @i{ior}s is -512@minus{}@i{errno}.
1.1 anton 12764:
12765: @item maximum depth of file input nesting:
12766: @cindex maximum depth of file input nesting
12767: @cindex file input nesting, maximum depth
12768: limited by the amount of return stack, locals/TIB stack, and the number
12769: of open files available. This should not give you troubles.
12770:
12771: @item maximum size of input line:
12772: @cindex maximum size of input line
12773: @cindex input line size, maximum
12774: @code{/line}. Currently 255.
12775:
12776: @item methods of mapping block ranges to files:
12777: @cindex mapping block ranges to files
12778: @cindex files containing blocks
12779: @cindex blocks in files
12780: By default, blocks are accessed in the file @file{blocks.fb} in the
12781: current working directory. The file can be switched with @code{USE}.
12782:
12783: @item number of string buffers provided by @code{S"}:
12784: @cindex @code{S"}, number of string buffers
12785: 1
12786:
12787: @item size of string buffer used by @code{S"}:
12788: @cindex @code{S"}, size of string buffer
12789: @code{/line}. currently 255.
12790:
12791: @end table
12792:
12793: @c ---------------------------------------------------------------------
12794: @node file-ambcond, , file-idef, The optional File-Access word set
12795: @subsection Ambiguous conditions
12796: @c ---------------------------------------------------------------------
12797: @cindex file words, ambiguous conditions
12798: @cindex ambiguous conditions, file words
12799:
12800: @table @i
12801: @item attempting to position a file outside its boundaries:
12802: @cindex @code{REPOSITION-FILE}, outside the file's boundaries
12803: @code{REPOSITION-FILE} is performed as usual: Afterwards,
12804: @code{FILE-POSITION} returns the value given to @code{REPOSITION-FILE}.
12805:
12806: @item attempting to read from file positions not yet written:
12807: @cindex reading from file positions not yet written
12808: End-of-file, i.e., zero characters are read and no error is reported.
12809:
1.29 crook 12810: @item @i{file-id} is invalid (@code{INCLUDE-FILE}):
12811: @cindex @code{INCLUDE-FILE}, @i{file-id} is invalid
1.1 anton 12812: An appropriate exception may be thrown, but a memory fault or other
12813: problem is more probable.
12814:
1.29 crook 12815: @item I/O exception reading or closing @i{file-id} (@code{INCLUDE-FILE}, @code{INCLUDED}):
12816: @cindex @code{INCLUDE-FILE}, I/O exception reading or closing @i{file-id}
12817: @cindex @code{INCLUDED}, I/O exception reading or closing @i{file-id}
12818: The @i{ior} produced by the operation, that discovered the problem, is
1.1 anton 12819: thrown.
12820:
12821: @item named file cannot be opened (@code{INCLUDED}):
12822: @cindex @code{INCLUDED}, named file cannot be opened
1.29 crook 12823: The @i{ior} produced by @code{open-file} is thrown.
1.1 anton 12824:
12825: @item requesting an unmapped block number:
12826: @cindex unmapped block numbers
12827: There are no unmapped legal block numbers. On some operating systems,
12828: writing a block with a large number may overflow the file system and
12829: have an error message as consequence.
12830:
12831: @item using @code{source-id} when @code{blk} is non-zero:
12832: @cindex @code{SOURCE-ID}, behaviour when @code{BLK} is non-zero
12833: @code{source-id} performs its function. Typically it will give the id of
12834: the source which loaded the block. (Better ideas?)
12835:
12836: @end table
12837:
12838:
12839: @c =====================================================================
12840: @node The optional Floating-Point word set, The optional Locals word set, The optional File-Access word set, ANS conformance
12841: @section The optional Floating-Point word set
12842: @c =====================================================================
12843: @cindex system documentation, floating-point words
12844: @cindex floating-point words, system documentation
12845:
12846: @menu
12847: * floating-idef:: Implementation Defined Options
12848: * floating-ambcond:: Ambiguous Conditions
12849: @end menu
12850:
12851:
12852: @c ---------------------------------------------------------------------
12853: @node floating-idef, floating-ambcond, The optional Floating-Point word set, The optional Floating-Point word set
12854: @subsection Implementation Defined Options
12855: @c ---------------------------------------------------------------------
12856: @cindex implementation-defined options, floating-point words
12857: @cindex floating-point words, implementation-defined options
12858:
12859: @table @i
12860: @item format and range of floating point numbers:
12861: @cindex format and range of floating point numbers
12862: @cindex floating point numbers, format and range
12863: System-dependent; the @code{double} type of C.
12864:
1.29 crook 12865: @item results of @code{REPRESENT} when @i{float} is out of range:
12866: @cindex @code{REPRESENT}, results when @i{float} is out of range
1.1 anton 12867: System dependent; @code{REPRESENT} is implemented using the C library
12868: function @code{ecvt()} and inherits its behaviour in this respect.
12869:
12870: @item rounding or truncation of floating-point numbers:
12871: @cindex rounding of floating-point numbers
12872: @cindex truncation of floating-point numbers
12873: @cindex floating-point numbers, rounding or truncation
12874: System dependent; the rounding behaviour is inherited from the hosting C
12875: compiler. IEEE-FP-based (i.e., most) systems by default round to
12876: nearest, and break ties by rounding to even (i.e., such that the last
12877: bit of the mantissa is 0).
12878:
12879: @item size of floating-point stack:
12880: @cindex floating-point stack size
12881: @code{s" FLOATING-STACK" environment? drop .} gives the total size of
12882: the floating-point stack (in floats). You can specify this on startup
12883: with the command-line option @code{-f} (@pxref{Invoking Gforth}).
12884:
12885: @item width of floating-point stack:
12886: @cindex floating-point stack width
12887: @code{1 floats}.
12888:
12889: @end table
12890:
12891:
12892: @c ---------------------------------------------------------------------
12893: @node floating-ambcond, , floating-idef, The optional Floating-Point word set
12894: @subsection Ambiguous conditions
12895: @c ---------------------------------------------------------------------
12896: @cindex floating-point words, ambiguous conditions
12897: @cindex ambiguous conditions, floating-point words
12898:
12899: @table @i
12900: @item @code{df@@} or @code{df!} used with an address that is not double-float aligned:
12901: @cindex @code{df@@} or @code{df!} used with an address that is not double-float aligned
12902: System-dependent. Typically results in a @code{-23 THROW} like other
12903: alignment violations.
12904:
12905: @item @code{f@@} or @code{f!} used with an address that is not float aligned:
12906: @cindex @code{f@@} used with an address that is not float aligned
12907: @cindex @code{f!} used with an address that is not float aligned
12908: System-dependent. Typically results in a @code{-23 THROW} like other
12909: alignment violations.
12910:
12911: @item floating-point result out of range:
12912: @cindex floating-point result out of range
12913: System-dependent. Can result in a @code{-55 THROW} (Floating-point
12914: unidentified fault), or can produce a special value representing, e.g.,
12915: Infinity.
12916:
12917: @item @code{sf@@} or @code{sf!} used with an address that is not single-float aligned:
12918: @cindex @code{sf@@} or @code{sf!} used with an address that is not single-float aligned
12919: System-dependent. Typically results in an alignment fault like other
12920: alignment violations.
12921:
1.35 anton 12922: @item @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.}):
12923: @cindex @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.})
1.1 anton 12924: The floating-point number is converted into decimal nonetheless.
12925:
12926: @item Both arguments are equal to zero (@code{FATAN2}):
12927: @cindex @code{FATAN2}, both arguments are equal to zero
12928: System-dependent. @code{FATAN2} is implemented using the C library
12929: function @code{atan2()}.
12930:
1.29 crook 12931: @item Using @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero:
12932: @cindex @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero
12933: System-dependent. Anyway, typically the cos of @i{r1} will not be zero
1.1 anton 12934: because of small errors and the tan will be a very large (or very small)
12935: but finite number.
12936:
1.29 crook 12937: @item @i{d} cannot be presented precisely as a float in @code{D>F}:
12938: @cindex @code{D>F}, @i{d} cannot be presented precisely as a float
1.1 anton 12939: The result is rounded to the nearest float.
12940:
12941: @item dividing by zero:
12942: @cindex dividing by zero, floating-point
12943: @cindex floating-point dividing by zero
12944: @cindex floating-point unidentified fault, FP divide-by-zero
12945: @code{-55 throw} (Floating-point unidentified fault)
12946:
12947: @item exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@}):
12948: @cindex exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@})
12949: System dependent. On IEEE-FP based systems the number is converted into
12950: an infinity.
12951:
1.29 crook 12952: @item @i{float}<1 (@code{FACOSH}):
12953: @cindex @code{FACOSH}, @i{float}<1
1.1 anton 12954: @cindex floating-point unidentified fault, @code{FACOSH}
12955: @code{-55 throw} (Floating-point unidentified fault)
12956:
1.29 crook 12957: @item @i{float}=<-1 (@code{FLNP1}):
12958: @cindex @code{FLNP1}, @i{float}=<-1
1.1 anton 12959: @cindex floating-point unidentified fault, @code{FLNP1}
12960: @code{-55 throw} (Floating-point unidentified fault). On IEEE-FP systems
1.29 crook 12961: negative infinity is typically produced for @i{float}=-1.
1.1 anton 12962:
1.29 crook 12963: @item @i{float}=<0 (@code{FLN}, @code{FLOG}):
12964: @cindex @code{FLN}, @i{float}=<0
12965: @cindex @code{FLOG}, @i{float}=<0
1.1 anton 12966: @cindex floating-point unidentified fault, @code{FLN} or @code{FLOG}
12967: @code{-55 throw} (Floating-point unidentified fault). On IEEE-FP systems
1.29 crook 12968: negative infinity is typically produced for @i{float}=0.
1.1 anton 12969:
1.29 crook 12970: @item @i{float}<0 (@code{FASINH}, @code{FSQRT}):
12971: @cindex @code{FASINH}, @i{float}<0
12972: @cindex @code{FSQRT}, @i{float}<0
1.1 anton 12973: @cindex floating-point unidentified fault, @code{FASINH} or @code{FSQRT}
12974: @code{-55 throw} (Floating-point unidentified fault). @code{fasinh}
12975: produces values for these inputs on my Linux box (Bug in the C library?)
12976:
1.29 crook 12977: @item |@i{float}|>1 (@code{FACOS}, @code{FASIN}, @code{FATANH}):
12978: @cindex @code{FACOS}, |@i{float}|>1
12979: @cindex @code{FASIN}, |@i{float}|>1
12980: @cindex @code{FATANH}, |@i{float}|>1
1.1 anton 12981: @cindex floating-point unidentified fault, @code{FACOS}, @code{FASIN} or @code{FATANH}
12982: @code{-55 throw} (Floating-point unidentified fault).
12983:
1.29 crook 12984: @item integer part of float cannot be represented by @i{d} in @code{F>D}:
12985: @cindex @code{F>D}, integer part of float cannot be represented by @i{d}
1.1 anton 12986: @cindex floating-point unidentified fault, @code{F>D}
12987: @code{-55 throw} (Floating-point unidentified fault).
12988:
12989: @item string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.}):
12990: @cindex string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.})
12991: This does not happen.
12992: @end table
12993:
12994: @c =====================================================================
12995: @node The optional Locals word set, The optional Memory-Allocation word set, The optional Floating-Point word set, ANS conformance
12996: @section The optional Locals word set
12997: @c =====================================================================
12998: @cindex system documentation, locals words
12999: @cindex locals words, system documentation
13000:
13001: @menu
13002: * locals-idef:: Implementation Defined Options
13003: * locals-ambcond:: Ambiguous Conditions
13004: @end menu
13005:
13006:
13007: @c ---------------------------------------------------------------------
13008: @node locals-idef, locals-ambcond, The optional Locals word set, The optional Locals word set
13009: @subsection Implementation Defined Options
13010: @c ---------------------------------------------------------------------
13011: @cindex implementation-defined options, locals words
13012: @cindex locals words, implementation-defined options
13013:
13014: @table @i
13015: @item maximum number of locals in a definition:
13016: @cindex maximum number of locals in a definition
13017: @cindex locals, maximum number in a definition
13018: @code{s" #locals" environment? drop .}. Currently 15. This is a lower
13019: bound, e.g., on a 32-bit machine there can be 41 locals of up to 8
13020: characters. The number of locals in a definition is bounded by the size
13021: of locals-buffer, which contains the names of the locals.
13022:
13023: @end table
13024:
13025:
13026: @c ---------------------------------------------------------------------
13027: @node locals-ambcond, , locals-idef, The optional Locals word set
13028: @subsection Ambiguous conditions
13029: @c ---------------------------------------------------------------------
13030: @cindex locals words, ambiguous conditions
13031: @cindex ambiguous conditions, locals words
13032:
13033: @table @i
13034: @item executing a named local in interpretation state:
13035: @cindex local in interpretation state
13036: @cindex Interpreting a compile-only word, for a local
13037: Locals have no interpretation semantics. If you try to perform the
13038: interpretation semantics, you will get a @code{-14 throw} somewhere
13039: (Interpreting a compile-only word). If you perform the compilation
13040: semantics, the locals access will be compiled (irrespective of state).
13041:
1.29 crook 13042: @item @i{name} not defined by @code{VALUE} or @code{(LOCAL)} (@code{TO}):
1.1 anton 13043: @cindex name not defined by @code{VALUE} or @code{(LOCAL)} used by @code{TO}
13044: @cindex @code{TO} on non-@code{VALUE}s and non-locals
13045: @cindex Invalid name argument, @code{TO}
13046: @code{-32 throw} (Invalid name argument)
13047:
13048: @end table
13049:
13050:
13051: @c =====================================================================
13052: @node The optional Memory-Allocation word set, The optional Programming-Tools word set, The optional Locals word set, ANS conformance
13053: @section The optional Memory-Allocation word set
13054: @c =====================================================================
13055: @cindex system documentation, memory-allocation words
13056: @cindex memory-allocation words, system documentation
13057:
13058: @menu
13059: * memory-idef:: Implementation Defined Options
13060: @end menu
13061:
13062:
13063: @c ---------------------------------------------------------------------
13064: @node memory-idef, , The optional Memory-Allocation word set, The optional Memory-Allocation word set
13065: @subsection Implementation Defined Options
13066: @c ---------------------------------------------------------------------
13067: @cindex implementation-defined options, memory-allocation words
13068: @cindex memory-allocation words, implementation-defined options
13069:
13070: @table @i
1.29 crook 13071: @item values and meaning of @i{ior}:
13072: @cindex @i{ior} values and meaning
13073: The @i{ior}s returned by the file and memory allocation words are
1.1 anton 13074: intended as throw codes. They typically are in the range
13075: -512@minus{}-2047 of OS errors. The mapping from OS error numbers to
1.29 crook 13076: @i{ior}s is -512@minus{}@i{errno}.
1.1 anton 13077:
13078: @end table
13079:
13080: @c =====================================================================
13081: @node The optional Programming-Tools word set, The optional Search-Order word set, The optional Memory-Allocation word set, ANS conformance
13082: @section The optional Programming-Tools word set
13083: @c =====================================================================
13084: @cindex system documentation, programming-tools words
13085: @cindex programming-tools words, system documentation
13086:
13087: @menu
13088: * programming-idef:: Implementation Defined Options
13089: * programming-ambcond:: Ambiguous Conditions
13090: @end menu
13091:
13092:
13093: @c ---------------------------------------------------------------------
13094: @node programming-idef, programming-ambcond, The optional Programming-Tools word set, The optional Programming-Tools word set
13095: @subsection Implementation Defined Options
13096: @c ---------------------------------------------------------------------
13097: @cindex implementation-defined options, programming-tools words
13098: @cindex programming-tools words, implementation-defined options
13099:
13100: @table @i
13101: @item ending sequence for input following @code{;CODE} and @code{CODE}:
13102: @cindex @code{;CODE} ending sequence
13103: @cindex @code{CODE} ending sequence
13104: @code{END-CODE}
13105:
13106: @item manner of processing input following @code{;CODE} and @code{CODE}:
13107: @cindex @code{;CODE}, processing input
13108: @cindex @code{CODE}, processing input
13109: The @code{ASSEMBLER} vocabulary is pushed on the search order stack, and
13110: the input is processed by the text interpreter, (starting) in interpret
13111: state.
13112:
13113: @item search order capability for @code{EDITOR} and @code{ASSEMBLER}:
13114: @cindex @code{ASSEMBLER}, search order capability
13115: The ANS Forth search order word set.
13116:
13117: @item source and format of display by @code{SEE}:
13118: @cindex @code{SEE}, source and format of output
13119: The source for @code{see} is the intermediate code used by the inner
13120: interpreter. The current @code{see} tries to output Forth source code
13121: as well as possible.
13122:
13123: @end table
13124:
13125: @c ---------------------------------------------------------------------
13126: @node programming-ambcond, , programming-idef, The optional Programming-Tools word set
13127: @subsection Ambiguous conditions
13128: @c ---------------------------------------------------------------------
13129: @cindex programming-tools words, ambiguous conditions
13130: @cindex ambiguous conditions, programming-tools words
13131:
13132: @table @i
13133:
1.21 crook 13134: @item deleting the compilation word list (@code{FORGET}):
13135: @cindex @code{FORGET}, deleting the compilation word list
1.1 anton 13136: Not implemented (yet).
13137:
1.29 crook 13138: @item fewer than @i{u}+1 items on the control-flow stack (@code{CS-PICK}, @code{CS-ROLL}):
13139: @cindex @code{CS-PICK}, fewer than @i{u}+1 items on the control flow-stack
13140: @cindex @code{CS-ROLL}, fewer than @i{u}+1 items on the control flow-stack
1.1 anton 13141: @cindex control-flow stack underflow
13142: This typically results in an @code{abort"} with a descriptive error
13143: message (may change into a @code{-22 throw} (Control structure mismatch)
13144: in the future). You may also get a memory access error. If you are
13145: unlucky, this ambiguous condition is not caught.
13146:
1.29 crook 13147: @item @i{name} can't be found (@code{FORGET}):
13148: @cindex @code{FORGET}, @i{name} can't be found
1.1 anton 13149: Not implemented (yet).
13150:
1.29 crook 13151: @item @i{name} not defined via @code{CREATE}:
13152: @cindex @code{;CODE}, @i{name} not defined via @code{CREATE}
1.1 anton 13153: @code{;CODE} behaves like @code{DOES>} in this respect, i.e., it changes
13154: the execution semantics of the last defined word no matter how it was
13155: defined.
13156:
13157: @item @code{POSTPONE} applied to @code{[IF]}:
13158: @cindex @code{POSTPONE} applied to @code{[IF]}
13159: @cindex @code{[IF]} and @code{POSTPONE}
13160: After defining @code{: X POSTPONE [IF] ; IMMEDIATE}. @code{X} is
13161: equivalent to @code{[IF]}.
13162:
13163: @item reaching the end of the input source before matching @code{[ELSE]} or @code{[THEN]}:
13164: @cindex @code{[IF]}, end of the input source before matching @code{[ELSE]} or @code{[THEN]}
13165: Continue in the same state of conditional compilation in the next outer
13166: input source. Currently there is no warning to the user about this.
13167:
13168: @item removing a needed definition (@code{FORGET}):
13169: @cindex @code{FORGET}, removing a needed definition
13170: Not implemented (yet).
13171:
13172: @end table
13173:
13174:
13175: @c =====================================================================
13176: @node The optional Search-Order word set, , The optional Programming-Tools word set, ANS conformance
13177: @section The optional Search-Order word set
13178: @c =====================================================================
13179: @cindex system documentation, search-order words
13180: @cindex search-order words, system documentation
13181:
13182: @menu
13183: * search-idef:: Implementation Defined Options
13184: * search-ambcond:: Ambiguous Conditions
13185: @end menu
13186:
13187:
13188: @c ---------------------------------------------------------------------
13189: @node search-idef, search-ambcond, The optional Search-Order word set, The optional Search-Order word set
13190: @subsection Implementation Defined Options
13191: @c ---------------------------------------------------------------------
13192: @cindex implementation-defined options, search-order words
13193: @cindex search-order words, implementation-defined options
13194:
13195: @table @i
13196: @item maximum number of word lists in search order:
13197: @cindex maximum number of word lists in search order
13198: @cindex search order, maximum depth
13199: @code{s" wordlists" environment? drop .}. Currently 16.
13200:
13201: @item minimum search order:
13202: @cindex minimum search order
13203: @cindex search order, minimum
13204: @code{root root}.
13205:
13206: @end table
13207:
13208: @c ---------------------------------------------------------------------
13209: @node search-ambcond, , search-idef, The optional Search-Order word set
13210: @subsection Ambiguous conditions
13211: @c ---------------------------------------------------------------------
13212: @cindex search-order words, ambiguous conditions
13213: @cindex ambiguous conditions, search-order words
13214:
13215: @table @i
1.21 crook 13216: @item changing the compilation word list (during compilation):
13217: @cindex changing the compilation word list (during compilation)
13218: @cindex compilation word list, change before definition ends
13219: The word is entered into the word list that was the compilation word list
1.1 anton 13220: at the start of the definition. Any changes to the name field (e.g.,
13221: @code{immediate}) or the code field (e.g., when executing @code{DOES>})
13222: are applied to the latest defined word (as reported by @code{last} or
1.21 crook 13223: @code{lastxt}), if possible, irrespective of the compilation word list.
1.1 anton 13224:
13225: @item search order empty (@code{previous}):
13226: @cindex @code{previous}, search order empty
1.26 crook 13227: @cindex vocstack empty, @code{previous}
1.1 anton 13228: @code{abort" Vocstack empty"}.
13229:
13230: @item too many word lists in search order (@code{also}):
13231: @cindex @code{also}, too many word lists in search order
1.26 crook 13232: @cindex vocstack full, @code{also}
1.1 anton 13233: @code{abort" Vocstack full"}.
13234:
13235: @end table
13236:
13237: @c ***************************************************************
1.65 anton 13238: @node Standard vs Extensions, Model, ANS conformance, Top
13239: @chapter Should I use Gforth extensions?
13240: @cindex Gforth extensions
13241:
13242: As you read through the rest of this manual, you will see documentation
13243: for @i{Standard} words, and documentation for some appealing Gforth
13244: @i{extensions}. You might ask yourself the question: @i{``Should I
13245: restrict myself to the standard, or should I use the extensions?''}
13246:
13247: The answer depends on the goals you have for the program you are working
13248: on:
13249:
13250: @itemize @bullet
13251:
13252: @item Is it just for yourself or do you want to share it with others?
13253:
13254: @item
13255: If you want to share it, do the others all use Gforth?
13256:
13257: @item
13258: If it is just for yourself, do you want to restrict yourself to Gforth?
13259:
13260: @end itemize
13261:
13262: If restricting the program to Gforth is ok, then there is no reason not
13263: to use extensions. It is still a good idea to keep to the standard
13264: where it is easy, in case you want to reuse these parts in another
13265: program that you want to be portable.
13266:
13267: If you want to be able to port the program to other Forth systems, there
13268: are the following points to consider:
13269:
13270: @itemize @bullet
13271:
13272: @item
13273: Most Forth systems that are being maintained support the ANS Forth
13274: standard. So if your program complies with the standard, it will be
13275: portable among many systems.
13276:
13277: @item
13278: A number of the Gforth extensions can be implemented in ANS Forth using
13279: public-domain files provided in the @file{compat/} directory. These are
13280: mentioned in the text in passing. There is no reason not to use these
13281: extensions, your program will still be ANS Forth compliant; just include
13282: the appropriate compat files with your program.
13283:
13284: @item
13285: The tool @file{ans-report.fs} (@pxref{ANS Report}) makes it easy to
13286: analyse your program and determine what non-Standard words it relies
13287: upon. However, it does not check whether you use standard words in a
13288: non-standard way.
13289:
13290: @item
13291: Some techniques are not standardized by ANS Forth, and are hard or
13292: impossible to implement in a standard way, but can be implemented in
13293: most Forth systems easily, and usually in similar ways (e.g., accessing
13294: word headers). Forth has a rich historical precedent for programmers
13295: taking advantage of implementation-dependent features of their tools
13296: (for example, relying on a knowledge of the dictionary
13297: structure). Sometimes these techniques are necessary to extract every
13298: last bit of performance from the hardware, sometimes they are just a
13299: programming shorthand.
13300:
13301: @item
13302: Does using a Gforth extension save more work than the porting this part
13303: to other Forth systems (if any) will cost?
13304:
13305: @item
13306: Is the additional functionality worth the reduction in portability and
13307: the additional porting problems?
13308:
13309: @end itemize
13310:
13311: In order to perform these consideratios, you need to know what's
13312: standard and what's not. This manual generally states if something is
13313: non-standard, but the authoritative source is the standard document.
13314: Appendix A of the Standard (@var{Rationale}) provides a valuable insight
13315: into the thought processes of the technical committee.
13316:
13317: Note also that portability between Forth systems is not the only
13318: portability issue; there is also the issue of portability between
13319: different platforms (processor/OS combinations).
13320:
13321: @c ***************************************************************
13322: @node Model, Integrating Gforth, Standard vs Extensions, Top
1.1 anton 13323: @chapter Model
13324:
13325: This chapter has yet to be written. It will contain information, on
13326: which internal structures you can rely.
13327:
13328: @c ***************************************************************
13329: @node Integrating Gforth, Emacs and Gforth, Model, Top
13330: @chapter Integrating Gforth into C programs
13331:
13332: This is not yet implemented.
13333:
13334: Several people like to use Forth as scripting language for applications
13335: that are otherwise written in C, C++, or some other language.
13336:
13337: The Forth system ATLAST provides facilities for embedding it into
13338: applications; unfortunately it has several disadvantages: most
13339: importantly, it is not based on ANS Forth, and it is apparently dead
13340: (i.e., not developed further and not supported). The facilities
1.21 crook 13341: provided by Gforth in this area are inspired by ATLAST's facilities, so
1.1 anton 13342: making the switch should not be hard.
13343:
13344: We also tried to design the interface such that it can easily be
13345: implemented by other Forth systems, so that we may one day arrive at a
13346: standardized interface. Such a standard interface would allow you to
13347: replace the Forth system without having to rewrite C code.
13348:
13349: You embed the Gforth interpreter by linking with the library
13350: @code{libgforth.a} (give the compiler the option @code{-lgforth}). All
13351: global symbols in this library that belong to the interface, have the
13352: prefix @code{forth_}. (Global symbols that are used internally have the
13353: prefix @code{gforth_}).
13354:
13355: You can include the declarations of Forth types and the functions and
13356: variables of the interface with @code{#include <forth.h>}.
13357:
13358: Types.
13359:
13360: Variables.
13361:
13362: Data and FP Stack pointer. Area sizes.
13363:
13364: functions.
13365:
13366: forth_init(imagefile)
13367: forth_evaluate(string) exceptions?
13368: forth_goto(address) (or forth_execute(xt)?)
13369: forth_continue() (a corountining mechanism)
13370:
13371: Adding primitives.
13372:
13373: No checking.
13374:
13375: Signals?
13376:
13377: Accessing the Stacks
13378:
1.26 crook 13379: @c ******************************************************************
1.1 anton 13380: @node Emacs and Gforth, Image Files, Integrating Gforth, Top
13381: @chapter Emacs and Gforth
13382: @cindex Emacs and Gforth
13383:
13384: @cindex @file{gforth.el}
13385: @cindex @file{forth.el}
13386: @cindex Rydqvist, Goran
13387: @cindex comment editing commands
13388: @cindex @code{\}, editing with Emacs
13389: @cindex debug tracer editing commands
13390: @cindex @code{~~}, removal with Emacs
13391: @cindex Forth mode in Emacs
13392: Gforth comes with @file{gforth.el}, an improved version of
13393: @file{forth.el} by Goran Rydqvist (included in the TILE package). The
1.26 crook 13394: improvements are:
13395:
13396: @itemize @bullet
13397: @item
13398: A better (but still not perfect) handling of indentation.
13399: @item
13400: Comment paragraph filling (@kbd{M-q})
13401: @item
13402: Commenting (@kbd{C-x \}) and uncommenting (@kbd{C-u C-x \}) of regions
13403: @item
13404: Removal of debugging tracers (@kbd{C-x ~}, @pxref{Debugging}).
1.41 anton 13405: @item
13406: Support of the @code{info-lookup} feature for looking up the
13407: documentation of a word.
1.26 crook 13408: @end itemize
13409:
13410: I left the stuff I do not use alone, even though some of it only makes
13411: sense for TILE. To get a description of these features, enter Forth mode
13412: and type @kbd{C-h m}.
1.1 anton 13413:
13414: @cindex source location of error or debugging output in Emacs
13415: @cindex error output, finding the source location in Emacs
13416: @cindex debugging output, finding the source location in Emacs
13417: In addition, Gforth supports Emacs quite well: The source code locations
13418: given in error messages, debugging output (from @code{~~}) and failed
13419: assertion messages are in the right format for Emacs' compilation mode
13420: (@pxref{Compilation, , Running Compilations under Emacs, emacs, Emacs
13421: Manual}) so the source location corresponding to an error or other
13422: message is only a few keystrokes away (@kbd{C-x `} for the next error,
13423: @kbd{C-c C-c} for the error under the cursor).
13424:
13425: @cindex @file{TAGS} file
13426: @cindex @file{etags.fs}
13427: @cindex viewing the source of a word in Emacs
1.43 anton 13428: @cindex @code{require}, placement in files
13429: @cindex @code{include}, placement in files
13430: Also, if you @code{require} @file{etags.fs}, a new @file{TAGS} file will
1.26 crook 13431: be produced (@pxref{Tags, , Tags Tables, emacs, Emacs Manual}) that
1.1 anton 13432: contains the definitions of all words defined afterwards. You can then
13433: find the source for a word using @kbd{M-.}. Note that emacs can use
13434: several tags files at the same time (e.g., one for the Gforth sources
13435: and one for your program, @pxref{Select Tags Table,,Selecting a Tags
13436: Table,emacs, Emacs Manual}). The TAGS file for the preloaded words is
13437: @file{$(datadir)/gforth/$(VERSION)/TAGS} (e.g.,
1.43 anton 13438: @file{/usr/local/share/gforth/0.2.0/TAGS}). To get the best behaviour
13439: with @file{etags.fs}, you should avoid putting definitions both before
13440: and after @code{require} etc., otherwise you will see the same file
13441: visited several times by commands like @code{tags-search}.
1.1 anton 13442:
1.41 anton 13443: @cindex viewing the documentation of a word in Emacs
13444: @cindex context-sensitive help
13445: Moreover, for words documented in this manual, you can look up the
13446: glossary entry quickly by using @kbd{C-h TAB}
13447: (@code{info-lookup-symbol}, see @pxref{Documentation, ,Documentation
13448: Commands, emacs, Emacs Manual}). This feature requires Emacs 20.3 or
1.42 anton 13449: later and does not work for words containing @code{:}.
1.41 anton 13450:
13451:
1.1 anton 13452: @cindex @file{.emacs}
13453: To get all these benefits, add the following lines to your @file{.emacs}
13454: file:
13455:
13456: @example
13457: (autoload 'forth-mode "gforth.el")
13458: (setq auto-mode-alist (cons '("\\.fs\\'" . forth-mode) auto-mode-alist))
13459: @end example
13460:
1.26 crook 13461: @c ******************************************************************
1.1 anton 13462: @node Image Files, Engine, Emacs and Gforth, Top
13463: @chapter Image Files
1.26 crook 13464: @cindex image file
13465: @cindex @file{.fi} files
1.1 anton 13466: @cindex precompiled Forth code
13467: @cindex dictionary in persistent form
13468: @cindex persistent form of dictionary
13469:
13470: An image file is a file containing an image of the Forth dictionary,
13471: i.e., compiled Forth code and data residing in the dictionary. By
13472: convention, we use the extension @code{.fi} for image files.
13473:
13474: @menu
1.18 anton 13475: * Image Licensing Issues:: Distribution terms for images.
13476: * Image File Background:: Why have image files?
1.67 anton 13477: * Non-Relocatable Image Files:: don't always work.
1.18 anton 13478: * Data-Relocatable Image Files:: are better.
1.67 anton 13479: * Fully Relocatable Image Files:: better yet.
1.18 anton 13480: * Stack and Dictionary Sizes:: Setting the default sizes for an image.
1.29 crook 13481: * Running Image Files:: @code{gforth -i @i{file}} or @i{file}.
1.18 anton 13482: * Modifying the Startup Sequence:: and turnkey applications.
1.1 anton 13483: @end menu
13484:
1.18 anton 13485: @node Image Licensing Issues, Image File Background, Image Files, Image Files
13486: @section Image Licensing Issues
13487: @cindex license for images
13488: @cindex image license
13489:
13490: An image created with @code{gforthmi} (@pxref{gforthmi}) or
13491: @code{savesystem} (@pxref{Non-Relocatable Image Files}) includes the
13492: original image; i.e., according to copyright law it is a derived work of
13493: the original image.
13494:
13495: Since Gforth is distributed under the GNU GPL, the newly created image
13496: falls under the GNU GPL, too. In particular, this means that if you
13497: distribute the image, you have to make all of the sources for the image
13498: available, including those you wrote. For details see @ref{License, ,
13499: GNU General Public License (Section 3)}.
13500:
13501: If you create an image with @code{cross} (@pxref{cross.fs}), the image
13502: contains only code compiled from the sources you gave it; if none of
13503: these sources is under the GPL, the terms discussed above do not apply
13504: to the image. However, if your image needs an engine (a gforth binary)
13505: that is under the GPL, you should make sure that you distribute both in
13506: a way that is at most a @emph{mere aggregation}, if you don't want the
13507: terms of the GPL to apply to the image.
13508:
13509: @node Image File Background, Non-Relocatable Image Files, Image Licensing Issues, Image Files
1.1 anton 13510: @section Image File Background
13511: @cindex image file background
13512:
13513: Our Forth system consists not only of primitives, but also of
13514: definitions written in Forth. Since the Forth compiler itself belongs to
13515: those definitions, it is not possible to start the system with the
13516: primitives and the Forth source alone. Therefore we provide the Forth
1.26 crook 13517: code as an image file in nearly executable form. When Gforth starts up,
13518: a C routine loads the image file into memory, optionally relocates the
13519: addresses, then sets up the memory (stacks etc.) according to
13520: information in the image file, and (finally) starts executing Forth
13521: code.
1.1 anton 13522:
13523: The image file variants represent different compromises between the
13524: goals of making it easy to generate image files and making them
13525: portable.
13526:
13527: @cindex relocation at run-time
1.26 crook 13528: Win32Forth 3.4 and Mitch Bradley's @code{cforth} use relocation at
1.1 anton 13529: run-time. This avoids many of the complications discussed below (image
13530: files are data relocatable without further ado), but costs performance
13531: (one addition per memory access).
13532:
13533: @cindex relocation at load-time
1.26 crook 13534: By contrast, the Gforth loader performs relocation at image load time. The
13535: loader also has to replace tokens that represent primitive calls with the
1.1 anton 13536: appropriate code-field addresses (or code addresses in the case of
13537: direct threading).
13538:
13539: There are three kinds of image files, with different degrees of
13540: relocatability: non-relocatable, data-relocatable, and fully relocatable
13541: image files.
13542:
13543: @cindex image file loader
13544: @cindex relocating loader
13545: @cindex loader for image files
13546: These image file variants have several restrictions in common; they are
13547: caused by the design of the image file loader:
13548:
13549: @itemize @bullet
13550: @item
13551: There is only one segment; in particular, this means, that an image file
13552: cannot represent @code{ALLOCATE}d memory chunks (and pointers to
1.26 crook 13553: them). The contents of the stacks are not represented, either.
1.1 anton 13554:
13555: @item
13556: The only kinds of relocation supported are: adding the same offset to
13557: all cells that represent data addresses; and replacing special tokens
13558: with code addresses or with pieces of machine code.
13559:
13560: If any complex computations involving addresses are performed, the
13561: results cannot be represented in the image file. Several applications that
13562: use such computations come to mind:
13563: @itemize @minus
13564: @item
13565: Hashing addresses (or data structures which contain addresses) for table
13566: lookup. If you use Gforth's @code{table}s or @code{wordlist}s for this
13567: purpose, you will have no problem, because the hash tables are
13568: recomputed automatically when the system is started. If you use your own
13569: hash tables, you will have to do something similar.
13570:
13571: @item
13572: There's a cute implementation of doubly-linked lists that uses
13573: @code{XOR}ed addresses. You could represent such lists as singly-linked
13574: in the image file, and restore the doubly-linked representation on
13575: startup.@footnote{In my opinion, though, you should think thrice before
13576: using a doubly-linked list (whatever implementation).}
13577:
13578: @item
13579: The code addresses of run-time routines like @code{docol:} cannot be
13580: represented in the image file (because their tokens would be replaced by
13581: machine code in direct threaded implementations). As a workaround,
13582: compute these addresses at run-time with @code{>code-address} from the
13583: executions tokens of appropriate words (see the definitions of
13584: @code{docol:} and friends in @file{kernel.fs}).
13585:
13586: @item
13587: On many architectures addresses are represented in machine code in some
13588: shifted or mangled form. You cannot put @code{CODE} words that contain
13589: absolute addresses in this form in a relocatable image file. Workarounds
13590: are representing the address in some relative form (e.g., relative to
13591: the CFA, which is present in some register), or loading the address from
13592: a place where it is stored in a non-mangled form.
13593: @end itemize
13594: @end itemize
13595:
13596: @node Non-Relocatable Image Files, Data-Relocatable Image Files, Image File Background, Image Files
13597: @section Non-Relocatable Image Files
13598: @cindex non-relocatable image files
1.26 crook 13599: @cindex image file, non-relocatable
1.1 anton 13600:
13601: These files are simple memory dumps of the dictionary. They are specific
13602: to the executable (i.e., @file{gforth} file) they were created
13603: with. What's worse, they are specific to the place on which the
13604: dictionary resided when the image was created. Now, there is no
13605: guarantee that the dictionary will reside at the same place the next
13606: time you start Gforth, so there's no guarantee that a non-relocatable
13607: image will work the next time (Gforth will complain instead of crashing,
13608: though).
13609:
13610: You can create a non-relocatable image file with
13611:
1.44 crook 13612:
1.1 anton 13613: doc-savesystem
13614:
1.44 crook 13615:
1.1 anton 13616: @node Data-Relocatable Image Files, Fully Relocatable Image Files, Non-Relocatable Image Files, Image Files
13617: @section Data-Relocatable Image Files
13618: @cindex data-relocatable image files
1.26 crook 13619: @cindex image file, data-relocatable
1.1 anton 13620:
13621: These files contain relocatable data addresses, but fixed code addresses
13622: (instead of tokens). They are specific to the executable (i.e.,
13623: @file{gforth} file) they were created with. For direct threading on some
13624: architectures (e.g., the i386), data-relocatable images do not work. You
13625: get a data-relocatable image, if you use @file{gforthmi} with a
13626: Gforth binary that is not doubly indirect threaded (@pxref{Fully
13627: Relocatable Image Files}).
13628:
13629: @node Fully Relocatable Image Files, Stack and Dictionary Sizes, Data-Relocatable Image Files, Image Files
13630: @section Fully Relocatable Image Files
13631: @cindex fully relocatable image files
1.26 crook 13632: @cindex image file, fully relocatable
1.1 anton 13633:
13634: @cindex @file{kern*.fi}, relocatability
13635: @cindex @file{gforth.fi}, relocatability
13636: These image files have relocatable data addresses, and tokens for code
13637: addresses. They can be used with different binaries (e.g., with and
13638: without debugging) on the same machine, and even across machines with
13639: the same data formats (byte order, cell size, floating point
13640: format). However, they are usually specific to the version of Gforth
13641: they were created with. The files @file{gforth.fi} and @file{kernl*.fi}
13642: are fully relocatable.
13643:
13644: There are two ways to create a fully relocatable image file:
13645:
13646: @menu
1.29 crook 13647: * gforthmi:: The normal way
1.1 anton 13648: * cross.fs:: The hard way
13649: @end menu
13650:
13651: @node gforthmi, cross.fs, Fully Relocatable Image Files, Fully Relocatable Image Files
13652: @subsection @file{gforthmi}
13653: @cindex @file{comp-i.fs}
13654: @cindex @file{gforthmi}
13655:
13656: You will usually use @file{gforthmi}. If you want to create an
1.29 crook 13657: image @i{file} that contains everything you would load by invoking
13658: Gforth with @code{gforth @i{options}}, you simply say:
1.1 anton 13659: @example
1.29 crook 13660: gforthmi @i{file} @i{options}
1.1 anton 13661: @end example
13662:
13663: E.g., if you want to create an image @file{asm.fi} that has the file
13664: @file{asm.fs} loaded in addition to the usual stuff, you could do it
13665: like this:
13666:
13667: @example
13668: gforthmi asm.fi asm.fs
13669: @end example
13670:
1.27 crook 13671: @file{gforthmi} is implemented as a sh script and works like this: It
13672: produces two non-relocatable images for different addresses and then
13673: compares them. Its output reflects this: first you see the output (if
1.62 crook 13674: any) of the two Gforth invocations that produce the non-relocatable image
1.27 crook 13675: files, then you see the output of the comparing program: It displays the
13676: offset used for data addresses and the offset used for code addresses;
1.1 anton 13677: moreover, for each cell that cannot be represented correctly in the
1.44 crook 13678: image files, it displays a line like this:
1.1 anton 13679:
13680: @example
13681: 78DC BFFFFA50 BFFFFA40
13682: @end example
13683:
13684: This means that at offset $78dc from @code{forthstart}, one input image
13685: contains $bffffa50, and the other contains $bffffa40. Since these cells
13686: cannot be represented correctly in the output image, you should examine
13687: these places in the dictionary and verify that these cells are dead
13688: (i.e., not read before they are written).
1.39 anton 13689:
13690: @cindex --application, @code{gforthmi} option
13691: If you insert the option @code{--application} in front of the image file
13692: name, you will get an image that uses the @code{--appl-image} option
13693: instead of the @code{--image-file} option (@pxref{Invoking
13694: Gforth}). When you execute such an image on Unix (by typing the image
13695: name as command), the Gforth engine will pass all options to the image
13696: instead of trying to interpret them as engine options.
1.1 anton 13697:
1.27 crook 13698: If you type @file{gforthmi} with no arguments, it prints some usage
13699: instructions.
13700:
1.1 anton 13701: @cindex @code{savesystem} during @file{gforthmi}
13702: @cindex @code{bye} during @file{gforthmi}
13703: @cindex doubly indirect threaded code
1.44 crook 13704: @cindex environment variables
13705: @cindex @code{GFORTHD} -- environment variable
13706: @cindex @code{GFORTH} -- environment variable
1.1 anton 13707: @cindex @code{gforth-ditc}
1.29 crook 13708: There are a few wrinkles: After processing the passed @i{options}, the
1.1 anton 13709: words @code{savesystem} and @code{bye} must be visible. A special doubly
13710: indirect threaded version of the @file{gforth} executable is used for
1.62 crook 13711: creating the non-relocatable images; you can pass the exact filename of
1.1 anton 13712: this executable through the environment variable @code{GFORTHD}
13713: (default: @file{gforth-ditc}); if you pass a version that is not doubly
13714: indirect threaded, you will not get a fully relocatable image, but a
1.27 crook 13715: data-relocatable image (because there is no code address offset). The
13716: normal @file{gforth} executable is used for creating the relocatable
13717: image; you can pass the exact filename of this executable through the
13718: environment variable @code{GFORTH}.
1.1 anton 13719:
13720: @node cross.fs, , gforthmi, Fully Relocatable Image Files
13721: @subsection @file{cross.fs}
13722: @cindex @file{cross.fs}
13723: @cindex cross-compiler
13724: @cindex metacompiler
1.47 crook 13725: @cindex target compiler
1.1 anton 13726:
13727: You can also use @code{cross}, a batch compiler that accepts a Forth-like
1.47 crook 13728: programming language (@pxref{Cross Compiler}).
1.1 anton 13729:
1.47 crook 13730: @code{cross} allows you to create image files for machines with
1.1 anton 13731: different data sizes and data formats than the one used for generating
13732: the image file. You can also use it to create an application image that
13733: does not contain a Forth compiler. These features are bought with
13734: restrictions and inconveniences in programming. E.g., addresses have to
13735: be stored in memory with special words (@code{A!}, @code{A,}, etc.) in
13736: order to make the code relocatable.
13737:
13738:
13739: @node Stack and Dictionary Sizes, Running Image Files, Fully Relocatable Image Files, Image Files
13740: @section Stack and Dictionary Sizes
13741: @cindex image file, stack and dictionary sizes
13742: @cindex dictionary size default
13743: @cindex stack size default
13744:
13745: If you invoke Gforth with a command line flag for the size
13746: (@pxref{Invoking Gforth}), the size you specify is stored in the
13747: dictionary. If you save the dictionary with @code{savesystem} or create
13748: an image with @file{gforthmi}, this size will become the default
13749: for the resulting image file. E.g., the following will create a
1.21 crook 13750: fully relocatable version of @file{gforth.fi} with a 1MB dictionary:
1.1 anton 13751:
13752: @example
13753: gforthmi gforth.fi -m 1M
13754: @end example
13755:
13756: In other words, if you want to set the default size for the dictionary
13757: and the stacks of an image, just invoke @file{gforthmi} with the
13758: appropriate options when creating the image.
13759:
13760: @cindex stack size, cache-friendly
13761: Note: For cache-friendly behaviour (i.e., good performance), you should
13762: make the sizes of the stacks modulo, say, 2K, somewhat different. E.g.,
13763: the default stack sizes are: data: 16k (mod 2k=0); fp: 15.5k (mod
13764: 2k=1.5k); return: 15k(mod 2k=1k); locals: 14.5k (mod 2k=0.5k).
13765:
13766: @node Running Image Files, Modifying the Startup Sequence, Stack and Dictionary Sizes, Image Files
13767: @section Running Image Files
13768: @cindex running image files
13769: @cindex invoking image files
13770: @cindex image file invocation
13771:
13772: @cindex -i, invoke image file
13773: @cindex --image file, invoke image file
1.29 crook 13774: You can invoke Gforth with an image file @i{image} instead of the
1.1 anton 13775: default @file{gforth.fi} with the @code{-i} flag (@pxref{Invoking Gforth}):
13776: @example
1.29 crook 13777: gforth -i @i{image}
1.1 anton 13778: @end example
13779:
13780: @cindex executable image file
1.26 crook 13781: @cindex image file, executable
1.1 anton 13782: If your operating system supports starting scripts with a line of the
13783: form @code{#! ...}, you just have to type the image file name to start
13784: Gforth with this image file (note that the file extension @code{.fi} is
1.29 crook 13785: just a convention). I.e., to run Gforth with the image file @i{image},
13786: you can just type @i{image} instead of @code{gforth -i @i{image}}.
1.27 crook 13787: This works because every @code{.fi} file starts with a line of this
13788: format:
13789:
13790: @example
13791: #! /usr/local/bin/gforth-0.4.0 -i
13792: @end example
13793:
13794: The file and pathname for the Gforth engine specified on this line is
13795: the specific Gforth executable that it was built against; i.e. the value
13796: of the environment variable @code{GFORTH} at the time that
13797: @file{gforthmi} was executed.
1.1 anton 13798:
1.27 crook 13799: You can make use of the same shell capability to make a Forth source
13800: file into an executable. For example, if you place this text in a file:
1.26 crook 13801:
13802: @example
13803: #! /usr/local/bin/gforth
13804:
13805: ." Hello, world" CR
13806: bye
13807: @end example
13808:
13809: @noindent
1.27 crook 13810: and then make the file executable (chmod +x in Unix), you can run it
1.26 crook 13811: directly from the command line. The sequence @code{#!} is used in two
13812: ways; firstly, it is recognised as a ``magic sequence'' by the operating
1.29 crook 13813: system@footnote{The Unix kernel actually recognises two types of files:
13814: executable files and files of data, where the data is processed by an
13815: interpreter that is specified on the ``interpreter line'' -- the first
13816: line of the file, starting with the sequence #!. There may be a small
13817: limit (e.g., 32) on the number of characters that may be specified on
13818: the interpreter line.} secondly it is treated as a comment character by
13819: Gforth. Because of the second usage, a space is required between
13820: @code{#!} and the path to the executable.
1.27 crook 13821:
13822: The disadvantage of this latter technique, compared with using
13823: @file{gforthmi}, is that it is slower; the Forth source code is compiled
13824: on-the-fly, each time the program is invoked.
13825:
1.26 crook 13826:
1.1 anton 13827: doc-#!
13828:
1.44 crook 13829:
1.1 anton 13830: @node Modifying the Startup Sequence, , Running Image Files, Image Files
13831: @section Modifying the Startup Sequence
13832: @cindex startup sequence for image file
13833: @cindex image file initialization sequence
13834: @cindex initialization sequence of image file
13835:
13836: You can add your own initialization to the startup sequence through the
1.26 crook 13837: deferred word @code{'cold}. @code{'cold} is invoked just before the
13838: image-specific command line processing (by default, loading files and
13839: evaluating (@code{-e}) strings) starts.
1.1 anton 13840:
13841: A sequence for adding your initialization usually looks like this:
13842:
13843: @example
13844: :noname
13845: Defers 'cold \ do other initialization stuff (e.g., rehashing wordlists)
13846: ... \ your stuff
13847: ; IS 'cold
13848: @end example
13849:
13850: @cindex turnkey image files
1.26 crook 13851: @cindex image file, turnkey applications
1.1 anton 13852: You can make a turnkey image by letting @code{'cold} execute a word
13853: (your turnkey application) that never returns; instead, it exits Gforth
13854: via @code{bye} or @code{throw}.
13855:
13856: @cindex command-line arguments, access
13857: @cindex arguments on the command line, access
13858: You can access the (image-specific) command-line arguments through the
1.26 crook 13859: variables @code{argc} and @code{argv}. @code{arg} provides convenient
1.1 anton 13860: access to @code{argv}.
13861:
1.26 crook 13862: If @code{'cold} exits normally, Gforth processes the command-line
13863: arguments as files to be loaded and strings to be evaluated. Therefore,
13864: @code{'cold} should remove the arguments it has used in this case.
13865:
1.44 crook 13866:
13867:
1.26 crook 13868: doc-'cold
1.1 anton 13869: doc-argc
13870: doc-argv
13871: doc-arg
13872:
13873:
1.44 crook 13874:
1.1 anton 13875: @c ******************************************************************
1.13 pazsan 13876: @node Engine, Binding to System Library, Image Files, Top
1.1 anton 13877: @chapter Engine
13878: @cindex engine
13879: @cindex virtual machine
13880:
1.26 crook 13881: Reading this chapter is not necessary for programming with Gforth. It
1.1 anton 13882: may be helpful for finding your way in the Gforth sources.
13883:
1.66 anton 13884: The ideas in this section have also been published in Bernd Paysan,
13885: @cite{ANS fig/GNU/??? Forth} (in German), Forth-Tagung '93 and M. Anton
13886: Ertl, @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl93.ps.Z, A
13887: Portable Forth Engine}}, EuroForth '93.
1.1 anton 13888:
13889: @menu
13890: * Portability::
13891: * Threading::
13892: * Primitives::
13893: * Performance::
13894: @end menu
13895:
13896: @node Portability, Threading, Engine, Engine
13897: @section Portability
13898: @cindex engine portability
13899:
1.26 crook 13900: An important goal of the Gforth Project is availability across a wide
13901: range of personal machines. fig-Forth, and, to a lesser extent, F83,
13902: achieved this goal by manually coding the engine in assembly language
13903: for several then-popular processors. This approach is very
13904: labor-intensive and the results are short-lived due to progress in
13905: computer architecture.
1.1 anton 13906:
13907: @cindex C, using C for the engine
13908: Others have avoided this problem by coding in C, e.g., Mitch Bradley
13909: (cforth), Mikael Patel (TILE) and Dirk Zoller (pfe). This approach is
13910: particularly popular for UNIX-based Forths due to the large variety of
13911: architectures of UNIX machines. Unfortunately an implementation in C
13912: does not mix well with the goals of efficiency and with using
13913: traditional techniques: Indirect or direct threading cannot be expressed
13914: in C, and switch threading, the fastest technique available in C, is
13915: significantly slower. Another problem with C is that it is very
13916: cumbersome to express double integer arithmetic.
13917:
13918: @cindex GNU C for the engine
13919: @cindex long long
13920: Fortunately, there is a portable language that does not have these
13921: limitations: GNU C, the version of C processed by the GNU C compiler
13922: (@pxref{C Extensions, , Extensions to the C Language Family, gcc.info,
13923: GNU C Manual}). Its labels as values feature (@pxref{Labels as Values, ,
13924: Labels as Values, gcc.info, GNU C Manual}) makes direct and indirect
13925: threading possible, its @code{long long} type (@pxref{Long Long, ,
13926: Double-Word Integers, gcc.info, GNU C Manual}) corresponds to Forth's
13927: double numbers@footnote{Unfortunately, long longs are not implemented
13928: properly on all machines (e.g., on alpha-osf1, long longs are only 64
13929: bits, the same size as longs (and pointers), but they should be twice as
1.4 anton 13930: long according to @pxref{Long Long, , Double-Word Integers, gcc.info, GNU
1.1 anton 13931: C Manual}). So, we had to implement doubles in C after all. Still, on
13932: most machines we can use long longs and achieve better performance than
13933: with the emulation package.}. GNU C is available for free on all
13934: important (and many unimportant) UNIX machines, VMS, 80386s running
13935: MS-DOS, the Amiga, and the Atari ST, so a Forth written in GNU C can run
13936: on all these machines.
13937:
13938: Writing in a portable language has the reputation of producing code that
13939: is slower than assembly. For our Forth engine we repeatedly looked at
13940: the code produced by the compiler and eliminated most compiler-induced
13941: inefficiencies by appropriate changes in the source code.
13942:
13943: @cindex explicit register declarations
13944: @cindex --enable-force-reg, configuration flag
13945: @cindex -DFORCE_REG
13946: However, register allocation cannot be portably influenced by the
13947: programmer, leading to some inefficiencies on register-starved
13948: machines. We use explicit register declarations (@pxref{Explicit Reg
13949: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) to
13950: improve the speed on some machines. They are turned on by using the
13951: configuration flag @code{--enable-force-reg} (@code{gcc} switch
13952: @code{-DFORCE_REG}). Unfortunately, this feature not only depends on the
13953: machine, but also on the compiler version: On some machines some
13954: compiler versions produce incorrect code when certain explicit register
13955: declarations are used. So by default @code{-DFORCE_REG} is not used.
13956:
13957: @node Threading, Primitives, Portability, Engine
13958: @section Threading
13959: @cindex inner interpreter implementation
13960: @cindex threaded code implementation
13961:
13962: @cindex labels as values
13963: GNU C's labels as values extension (available since @code{gcc-2.0},
13964: @pxref{Labels as Values, , Labels as Values, gcc.info, GNU C Manual})
1.29 crook 13965: makes it possible to take the address of @i{label} by writing
13966: @code{&&@i{label}}. This address can then be used in a statement like
13967: @code{goto *@i{address}}. I.e., @code{goto *&&x} is the same as
1.1 anton 13968: @code{goto x}.
13969:
1.26 crook 13970: @cindex @code{NEXT}, indirect threaded
1.1 anton 13971: @cindex indirect threaded inner interpreter
13972: @cindex inner interpreter, indirect threaded
1.26 crook 13973: With this feature an indirect threaded @code{NEXT} looks like:
1.1 anton 13974: @example
13975: cfa = *ip++;
13976: ca = *cfa;
13977: goto *ca;
13978: @end example
13979: @cindex instruction pointer
13980: For those unfamiliar with the names: @code{ip} is the Forth instruction
13981: pointer; the @code{cfa} (code-field address) corresponds to ANS Forths
13982: execution token and points to the code field of the next word to be
13983: executed; The @code{ca} (code address) fetched from there points to some
13984: executable code, e.g., a primitive or the colon definition handler
13985: @code{docol}.
13986:
1.26 crook 13987: @cindex @code{NEXT}, direct threaded
1.1 anton 13988: @cindex direct threaded inner interpreter
13989: @cindex inner interpreter, direct threaded
13990: Direct threading is even simpler:
13991: @example
13992: ca = *ip++;
13993: goto *ca;
13994: @end example
13995:
13996: Of course we have packaged the whole thing neatly in macros called
1.26 crook 13997: @code{NEXT} and @code{NEXT1} (the part of @code{NEXT} after fetching the cfa).
1.1 anton 13998:
13999: @menu
14000: * Scheduling::
14001: * Direct or Indirect Threaded?::
14002: * DOES>::
14003: @end menu
14004:
14005: @node Scheduling, Direct or Indirect Threaded?, Threading, Threading
14006: @subsection Scheduling
14007: @cindex inner interpreter optimization
14008:
14009: There is a little complication: Pipelined and superscalar processors,
14010: i.e., RISC and some modern CISC machines can process independent
14011: instructions while waiting for the results of an instruction. The
14012: compiler usually reorders (schedules) the instructions in a way that
14013: achieves good usage of these delay slots. However, on our first tries
14014: the compiler did not do well on scheduling primitives. E.g., for
14015: @code{+} implemented as
14016: @example
14017: n=sp[0]+sp[1];
14018: sp++;
14019: sp[0]=n;
14020: NEXT;
14021: @end example
1.26 crook 14022: the @code{NEXT} comes strictly after the other code, i.e., there is nearly no
1.1 anton 14023: scheduling. After a little thought the problem becomes clear: The
1.21 crook 14024: compiler cannot know that @code{sp} and @code{ip} point to different
14025: addresses (and the version of @code{gcc} we used would not know it even
14026: if it was possible), so it could not move the load of the cfa above the
14027: store to the TOS. Indeed the pointers could be the same, if code on or
14028: very near the top of stack were executed. In the interest of speed we
14029: chose to forbid this probably unused ``feature'' and helped the compiler
1.26 crook 14030: in scheduling: @code{NEXT} is divided into the loading part (@code{NEXT_P1})
1.21 crook 14031: and the goto part (@code{NEXT_P2}). @code{+} now looks like:
1.1 anton 14032: @example
14033: n=sp[0]+sp[1];
14034: sp++;
14035: NEXT_P1;
14036: sp[0]=n;
14037: NEXT_P2;
14038: @end example
14039: This can be scheduled optimally by the compiler.
14040:
14041: This division can be turned off with the switch @code{-DCISC_NEXT}. This
14042: switch is on by default on machines that do not profit from scheduling
14043: (e.g., the 80386), in order to preserve registers.
14044:
14045: @node Direct or Indirect Threaded?, DOES>, Scheduling, Threading
14046: @subsection Direct or Indirect Threaded?
14047: @cindex threading, direct or indirect?
14048:
14049: @cindex -DDIRECT_THREADED
14050: Both! After packaging the nasty details in macro definitions we
14051: realized that we could switch between direct and indirect threading by
14052: simply setting a compilation flag (@code{-DDIRECT_THREADED}) and
14053: defining a few machine-specific macros for the direct-threading case.
14054: On the Forth level we also offer access words that hide the
14055: differences between the threading methods (@pxref{Threading Words}).
14056:
14057: Indirect threading is implemented completely machine-independently.
14058: Direct threading needs routines for creating jumps to the executable
1.21 crook 14059: code (e.g. to @code{docol} or @code{dodoes}). These routines are inherently
14060: machine-dependent, but they do not amount to many source lines. Therefore,
14061: even porting direct threading to a new machine requires little effort.
1.1 anton 14062:
14063: @cindex --enable-indirect-threaded, configuration flag
14064: @cindex --enable-direct-threaded, configuration flag
14065: The default threading method is machine-dependent. You can enforce a
14066: specific threading method when building Gforth with the configuration
14067: flag @code{--enable-direct-threaded} or
14068: @code{--enable-indirect-threaded}. Note that direct threading is not
14069: supported on all machines.
14070:
14071: @node DOES>, , Direct or Indirect Threaded?, Threading
14072: @subsection DOES>
14073: @cindex @code{DOES>} implementation
14074:
1.26 crook 14075: @cindex @code{dodoes} routine
14076: @cindex @code{DOES>}-code
1.1 anton 14077: One of the most complex parts of a Forth engine is @code{dodoes}, i.e.,
14078: the chunk of code executed by every word defined by a
14079: @code{CREATE}...@code{DOES>} pair. The main problem here is: How to find
14080: the Forth code to be executed, i.e. the code after the
1.26 crook 14081: @code{DOES>} (the @code{DOES>}-code)? There are two solutions:
1.1 anton 14082:
1.21 crook 14083: In fig-Forth the code field points directly to the @code{dodoes} and the
1.45 crook 14084: @code{DOES>}-code address is stored in the cell after the code address (i.e. at
1.29 crook 14085: @code{@i{CFA} cell+}). It may seem that this solution is illegal in
1.1 anton 14086: the Forth-79 and all later standards, because in fig-Forth this address
14087: lies in the body (which is illegal in these standards). However, by
14088: making the code field larger for all words this solution becomes legal
14089: again. We use this approach for the indirect threaded version and for
14090: direct threading on some machines. Leaving a cell unused in most words
14091: is a bit wasteful, but on the machines we are targeting this is hardly a
14092: problem. The other reason for having a code field size of two cells is
14093: to avoid having different image files for direct and indirect threaded
14094: systems (direct threaded systems require two-cell code fields on many
14095: machines).
14096:
1.26 crook 14097: @cindex @code{DOES>}-handler
1.1 anton 14098: The other approach is that the code field points or jumps to the cell
1.26 crook 14099: after @code{DOES>}. In this variant there is a jump to @code{dodoes} at
14100: this address (the @code{DOES>}-handler). @code{dodoes} can then get the
14101: @code{DOES>}-code address by computing the code address, i.e., the address of
1.45 crook 14102: the jump to @code{dodoes}, and add the length of that jump field. A variant of
1.1 anton 14103: this is to have a call to @code{dodoes} after the @code{DOES>}; then the
14104: return address (which can be found in the return register on RISCs) is
1.26 crook 14105: the @code{DOES>}-code address. Since the two cells available in the code field
1.1 anton 14106: are used up by the jump to the code address in direct threading on many
14107: architectures, we use this approach for direct threading on these
14108: architectures. We did not want to add another cell to the code field.
14109:
14110: @node Primitives, Performance, Threading, Engine
14111: @section Primitives
14112: @cindex primitives, implementation
14113: @cindex virtual machine instructions, implementation
14114:
14115: @menu
14116: * Automatic Generation::
14117: * TOS Optimization::
14118: * Produced code::
14119: @end menu
14120:
14121: @node Automatic Generation, TOS Optimization, Primitives, Primitives
14122: @subsection Automatic Generation
14123: @cindex primitives, automatic generation
14124:
14125: @cindex @file{prims2x.fs}
14126: Since the primitives are implemented in a portable language, there is no
14127: longer any need to minimize the number of primitives. On the contrary,
14128: having many primitives has an advantage: speed. In order to reduce the
14129: number of errors in primitives and to make programming them easier, we
14130: provide a tool, the primitive generator (@file{prims2x.fs}), that
14131: automatically generates most (and sometimes all) of the C code for a
14132: primitive from the stack effect notation. The source for a primitive
14133: has the following form:
14134:
14135: @cindex primitive source format
14136: @format
1.58 anton 14137: @i{Forth-name} ( @i{stack-effect} ) @i{category} [@i{pronounc.}]
1.29 crook 14138: [@code{""}@i{glossary entry}@code{""}]
14139: @i{C code}
1.1 anton 14140: [@code{:}
1.29 crook 14141: @i{Forth code}]
1.1 anton 14142: @end format
14143:
14144: The items in brackets are optional. The category and glossary fields
14145: are there for generating the documentation, the Forth code is there
14146: for manual implementations on machines without GNU C. E.g., the source
14147: for the primitive @code{+} is:
14148: @example
1.58 anton 14149: + ( n1 n2 -- n ) core plus
1.1 anton 14150: n = n1+n2;
14151: @end example
14152:
14153: This looks like a specification, but in fact @code{n = n1+n2} is C
14154: code. Our primitive generation tool extracts a lot of information from
14155: the stack effect notations@footnote{We use a one-stack notation, even
14156: though we have separate data and floating-point stacks; The separate
14157: notation can be generated easily from the unified notation.}: The number
14158: of items popped from and pushed on the stack, their type, and by what
14159: name they are referred to in the C code. It then generates a C code
14160: prelude and postlude for each primitive. The final C code for @code{+}
14161: looks like this:
14162:
14163: @example
1.46 pazsan 14164: I_plus: /* + ( n1 n2 -- n ) */ /* label, stack effect */
1.1 anton 14165: /* */ /* documentation */
14166: @{
14167: DEF_CA /* definition of variable ca (indirect threading) */
14168: Cell n1; /* definitions of variables */
14169: Cell n2;
14170: Cell n;
14171: n1 = (Cell) sp[1]; /* input */
14172: n2 = (Cell) TOS;
14173: sp += 1; /* stack adjustment */
14174: NAME("+") /* debugging output (with -DDEBUG) */
14175: @{
14176: n = n1+n2; /* C code taken from the source */
14177: @}
14178: NEXT_P1; /* NEXT part 1 */
14179: TOS = (Cell)n; /* output */
14180: NEXT_P2; /* NEXT part 2 */
14181: @}
14182: @end example
14183:
14184: This looks long and inefficient, but the GNU C compiler optimizes quite
14185: well and produces optimal code for @code{+} on, e.g., the R3000 and the
14186: HP RISC machines: Defining the @code{n}s does not produce any code, and
14187: using them as intermediate storage also adds no cost.
14188:
1.26 crook 14189: There are also other optimizations that are not illustrated by this
14190: example: assignments between simple variables are usually for free (copy
1.1 anton 14191: propagation). If one of the stack items is not used by the primitive
14192: (e.g. in @code{drop}), the compiler eliminates the load from the stack
14193: (dead code elimination). On the other hand, there are some things that
14194: the compiler does not do, therefore they are performed by
14195: @file{prims2x.fs}: The compiler does not optimize code away that stores
14196: a stack item to the place where it just came from (e.g., @code{over}).
14197:
14198: While programming a primitive is usually easy, there are a few cases
14199: where the programmer has to take the actions of the generator into
14200: account, most notably @code{?dup}, but also words that do not (always)
1.26 crook 14201: fall through to @code{NEXT}.
1.1 anton 14202:
14203: @node TOS Optimization, Produced code, Automatic Generation, Primitives
14204: @subsection TOS Optimization
14205: @cindex TOS optimization for primitives
14206: @cindex primitives, keeping the TOS in a register
14207:
14208: An important optimization for stack machine emulators, e.g., Forth
14209: engines, is keeping one or more of the top stack items in
1.29 crook 14210: registers. If a word has the stack effect @i{in1}...@i{inx} @code{--}
14211: @i{out1}...@i{outy}, keeping the top @i{n} items in registers
1.1 anton 14212: @itemize @bullet
14213: @item
1.29 crook 14214: is better than keeping @i{n-1} items, if @i{x>=n} and @i{y>=n},
1.1 anton 14215: due to fewer loads from and stores to the stack.
1.29 crook 14216: @item is slower than keeping @i{n-1} items, if @i{x<>y} and @i{x<n} and
14217: @i{y<n}, due to additional moves between registers.
1.1 anton 14218: @end itemize
14219:
14220: @cindex -DUSE_TOS
14221: @cindex -DUSE_NO_TOS
14222: In particular, keeping one item in a register is never a disadvantage,
14223: if there are enough registers. Keeping two items in registers is a
14224: disadvantage for frequent words like @code{?branch}, constants,
14225: variables, literals and @code{i}. Therefore our generator only produces
14226: code that keeps zero or one items in registers. The generated C code
14227: covers both cases; the selection between these alternatives is made at
14228: C-compile time using the switch @code{-DUSE_TOS}. @code{TOS} in the C
14229: code for @code{+} is just a simple variable name in the one-item case,
14230: otherwise it is a macro that expands into @code{sp[0]}. Note that the
14231: GNU C compiler tries to keep simple variables like @code{TOS} in
14232: registers, and it usually succeeds, if there are enough registers.
14233:
14234: @cindex -DUSE_FTOS
14235: @cindex -DUSE_NO_FTOS
14236: The primitive generator performs the TOS optimization for the
14237: floating-point stack, too (@code{-DUSE_FTOS}). For floating-point
14238: operations the benefit of this optimization is even larger:
14239: floating-point operations take quite long on most processors, but can be
14240: performed in parallel with other operations as long as their results are
14241: not used. If the FP-TOS is kept in a register, this works. If
14242: it is kept on the stack, i.e., in memory, the store into memory has to
14243: wait for the result of the floating-point operation, lengthening the
14244: execution time of the primitive considerably.
14245:
14246: The TOS optimization makes the automatic generation of primitives a
14247: bit more complicated. Just replacing all occurrences of @code{sp[0]} by
14248: @code{TOS} is not sufficient. There are some special cases to
14249: consider:
14250: @itemize @bullet
14251: @item In the case of @code{dup ( w -- w w )} the generator must not
14252: eliminate the store to the original location of the item on the stack,
14253: if the TOS optimization is turned on.
14254: @item Primitives with stack effects of the form @code{--}
1.29 crook 14255: @i{out1}...@i{outy} must store the TOS to the stack at the start.
14256: Likewise, primitives with the stack effect @i{in1}...@i{inx} @code{--}
1.1 anton 14257: must load the TOS from the stack at the end. But for the null stack
14258: effect @code{--} no stores or loads should be generated.
14259: @end itemize
14260:
14261: @node Produced code, , TOS Optimization, Primitives
14262: @subsection Produced code
14263: @cindex primitives, assembly code listing
14264:
14265: @cindex @file{engine.s}
14266: To see what assembly code is produced for the primitives on your machine
14267: with your compiler and your flag settings, type @code{make engine.s} and
14268: look at the resulting file @file{engine.s}.
14269:
14270: @node Performance, , Primitives, Engine
14271: @section Performance
14272: @cindex performance of some Forth interpreters
14273: @cindex engine performance
14274: @cindex benchmarking Forth systems
14275: @cindex Gforth performance
14276:
14277: On RISCs the Gforth engine is very close to optimal; i.e., it is usually
14278: impossible to write a significantly faster engine.
14279:
14280: On register-starved machines like the 386 architecture processors
14281: improvements are possible, because @code{gcc} does not utilize the
14282: registers as well as a human, even with explicit register declarations;
14283: e.g., Bernd Beuster wrote a Forth system fragment in assembly language
14284: and hand-tuned it for the 486; this system is 1.19 times faster on the
14285: Sieve benchmark on a 486DX2/66 than Gforth compiled with
1.40 anton 14286: @code{gcc-2.6.3} with @code{-DFORCE_REG}. The situation has improved
14287: with gcc-2.95 and gforth-0.4.9; now the most important virtual machine
14288: registers fit in real registers (and we can even afford to use the TOS
14289: optimization), resulting in a speedup of 1.14 on the sieve over the
14290: earlier results.
1.1 anton 14291:
14292: @cindex Win32Forth performance
14293: @cindex NT Forth performance
14294: @cindex eforth performance
14295: @cindex ThisForth performance
14296: @cindex PFE performance
14297: @cindex TILE performance
1.40 anton 14298: The potential advantage of assembly language implementations
1.1 anton 14299: is not necessarily realized in complete Forth systems: We compared
1.40 anton 14300: Gforth-0.4.9 (direct threaded, compiled with @code{gcc-2.95.1} and
1.1 anton 14301: @code{-DFORCE_REG}) with Win32Forth 1.2093, LMI's NT Forth (Beta, May
14302: 1994) and Eforth (with and without peephole (aka pinhole) optimization
14303: of the threaded code); all these systems were written in assembly
14304: language. We also compared Gforth with three systems written in C:
14305: PFE-0.9.14 (compiled with @code{gcc-2.6.3} with the default
14306: configuration for Linux: @code{-O2 -fomit-frame-pointer -DUSE_REGS
1.21 crook 14307: -DUNROLL_NEXT}), ThisForth Beta (compiled with @code{gcc-2.6.3 -O3
14308: -fomit-frame-pointer}; ThisForth employs peephole optimization of the
1.1 anton 14309: threaded code) and TILE (compiled with @code{make opt}). We benchmarked
14310: Gforth, PFE, ThisForth and TILE on a 486DX2/66 under Linux. Kenneth
14311: O'Heskin kindly provided the results for Win32Forth and NT Forth on a
14312: 486DX2/66 with similar memory performance under Windows NT. Marcel
14313: Hendrix ported Eforth to Linux, then extended it to run the benchmarks,
14314: added the peephole optimizer, ran the benchmarks and reported the
14315: results.
1.40 anton 14316:
1.1 anton 14317: We used four small benchmarks: the ubiquitous Sieve; bubble-sorting and
14318: matrix multiplication come from the Stanford integer benchmarks and have
14319: been translated into Forth by Martin Fraeman; we used the versions
14320: included in the TILE Forth package, but with bigger data set sizes; and
14321: a recursive Fibonacci number computation for benchmarking calling
14322: performance. The following table shows the time taken for the benchmarks
14323: scaled by the time taken by Gforth (in other words, it shows the speedup
14324: factor that Gforth achieved over the other systems).
14325:
14326: @example
1.40 anton 14327: relative Win32- NT eforth This-
1.1 anton 14328: time Gforth Forth Forth eforth +opt PFE Forth TILE
1.40 anton 14329: sieve 1.00 1.58 1.30 1.58 0.97 1.80 3.63 9.79
14330: bubble 1.00 1.55 1.67 1.75 1.04 1.78 4.59
14331: matmul 1.00 1.67 1.53 1.66 0.84 1.79 4.63
14332: fib 1.00 1.75 1.53 1.40 0.99 1.99 3.43 4.93
1.1 anton 14333: @end example
14334:
1.26 crook 14335: You may be quite surprised by the good performance of Gforth when
14336: compared with systems written in assembly language. One important reason
14337: for the disappointing performance of these other systems is probably
14338: that they are not written optimally for the 486 (e.g., they use the
14339: @code{lods} instruction). In addition, Win32Forth uses a comfortable,
14340: but costly method for relocating the Forth image: like @code{cforth}, it
14341: computes the actual addresses at run time, resulting in two address
14342: computations per @code{NEXT} (@pxref{Image File Background}).
14343:
1.40 anton 14344: Only Eforth with the peephole optimizer performs comparable to
14345: Gforth. The speedups achieved with peephole optimization of threaded
14346: code are quite remarkable. Adding a peephole optimizer to Gforth should
14347: cause similar speedups.
1.1 anton 14348:
14349: The speedup of Gforth over PFE, ThisForth and TILE can be easily
14350: explained with the self-imposed restriction of the latter systems to
14351: standard C, which makes efficient threading impossible (however, the
1.4 anton 14352: measured implementation of PFE uses a GNU C extension: @pxref{Global Reg
1.1 anton 14353: Vars, , Defining Global Register Variables, gcc.info, GNU C Manual}).
14354: Moreover, current C compilers have a hard time optimizing other aspects
14355: of the ThisForth and the TILE source.
14356:
1.26 crook 14357: The performance of Gforth on 386 architecture processors varies widely
14358: with the version of @code{gcc} used. E.g., @code{gcc-2.5.8} failed to
14359: allocate any of the virtual machine registers into real machine
14360: registers by itself and would not work correctly with explicit register
1.40 anton 14361: declarations, giving a 1.5 times slower engine (on a 486DX2/66 running
1.26 crook 14362: the Sieve) than the one measured above.
1.1 anton 14363:
1.26 crook 14364: Note that there have been several releases of Win32Forth since the
14365: release presented here, so the results presented above may have little
1.40 anton 14366: predictive value for the performance of Win32Forth today (results for
14367: the current release on an i486DX2/66 are welcome).
1.1 anton 14368:
14369: @cindex @file{Benchres}
1.66 anton 14370: In
14371: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl&maierhofer95.ps.gz,
14372: Translating Forth to Efficient C}} by M. Anton Ertl and Martin
1.1 anton 14373: Maierhofer (presented at EuroForth '95), an indirect threaded version of
1.66 anton 14374: Gforth is compared with Win32Forth, NT Forth, PFE, ThisForth, and
14375: several native code systems; that version of Gforth is slower on a 486
14376: than the direct threaded version used here. You can find a newer version
14377: of these measurements at
1.47 crook 14378: @uref{http://www.complang.tuwien.ac.at/forth/performance.html}. You can
1.1 anton 14379: find numbers for Gforth on various machines in @file{Benchres}.
14380:
1.26 crook 14381: @c ******************************************************************
1.13 pazsan 14382: @node Binding to System Library, Cross Compiler, Engine, Top
1.14 pazsan 14383: @chapter Binding to System Library
1.13 pazsan 14384:
14385: @node Cross Compiler, Bugs, Binding to System Library, Top
1.14 pazsan 14386: @chapter Cross Compiler
1.47 crook 14387: @cindex @file{cross.fs}
14388: @cindex cross-compiler
14389: @cindex metacompiler
14390: @cindex target compiler
1.13 pazsan 14391:
1.46 pazsan 14392: The cross compiler is used to bootstrap a Forth kernel. Since Gforth is
14393: mostly written in Forth, including crucial parts like the outer
14394: interpreter and compiler, it needs compiled Forth code to get
14395: started. The cross compiler allows to create new images for other
14396: architectures, even running under another Forth system.
1.13 pazsan 14397:
14398: @menu
1.67 anton 14399: * Using the Cross Compiler::
14400: * How the Cross Compiler Works::
1.13 pazsan 14401: @end menu
14402:
1.21 crook 14403: @node Using the Cross Compiler, How the Cross Compiler Works, Cross Compiler, Cross Compiler
1.14 pazsan 14404: @section Using the Cross Compiler
1.46 pazsan 14405:
14406: The cross compiler uses a language that resembles Forth, but isn't. The
14407: main difference is that you can execute Forth code after definition,
14408: while you usually can't execute the code compiled by cross, because the
14409: code you are compiling is typically for a different computer than the
14410: one you are compiling on.
14411:
14412: The Makefile is already set up to allow you to create kernels for new
14413: architectures with a simple make command. The generic kernels using the
14414: GCC compiled virtual machine are created in the normal build process
14415: with @code{make}. To create a embedded Gforth executable for e.g. the
14416: 8086 processor (running on a DOS machine), type
14417:
14418: @example
14419: make kernl-8086.fi
14420: @end example
14421:
14422: This will use the machine description from the @file{arch/8086}
14423: directory to create a new kernel. A machine file may look like that:
14424:
14425: @example
14426: \ Parameter for target systems 06oct92py
14427:
14428: 4 Constant cell \ cell size in bytes
14429: 2 Constant cell<< \ cell shift to bytes
14430: 5 Constant cell>bit \ cell shift to bits
14431: 8 Constant bits/char \ bits per character
14432: 8 Constant bits/byte \ bits per byte [default: 8]
14433: 8 Constant float \ bytes per float
14434: 8 Constant /maxalign \ maximum alignment in bytes
14435: false Constant bigendian \ byte order
14436: ( true=big, false=little )
14437:
14438: include machpc.fs \ feature list
14439: @end example
14440:
14441: This part is obligatory for the cross compiler itself, the feature list
14442: is used by the kernel to conditionally compile some features in and out,
14443: depending on whether the target supports these features.
14444:
14445: There are some optional features, if you define your own primitives,
14446: have an assembler, or need special, nonstandard preparation to make the
14447: boot process work. @code{asm-include} include an assembler,
14448: @code{prims-include} includes primitives, and @code{>boot} prepares for
14449: booting.
14450:
14451: @example
14452: : asm-include ." Include assembler" cr
14453: s" arch/8086/asm.fs" included ;
14454:
14455: : prims-include ." Include primitives" cr
14456: s" arch/8086/prim.fs" included ;
14457:
14458: : >boot ." Prepare booting" cr
14459: s" ' boot >body into-forth 1+ !" evaluate ;
14460: @end example
14461:
14462: These words are used as sort of macro during the cross compilation in
14463: the file @file{kernel/main.fs}. Instead of using this macros, it would
14464: be possible --- but more complicated --- to write a new kernel project
14465: file, too.
14466:
14467: @file{kernel/main.fs} expects the machine description file name on the
14468: stack; the cross compiler itself (@file{cross.fs}) assumes that either
14469: @code{mach-file} leaves a counted string on the stack, or
14470: @code{machine-file} leaves an address, count pair of the filename on the
14471: stack.
14472:
14473: The feature list is typically controlled using @code{SetValue}, generic
14474: files that are used by several projects can use @code{DefaultValue}
14475: instead. Both functions work like @code{Value}, when the value isn't
14476: defined, but @code{SetValue} works like @code{to} if the value is
14477: defined, and @code{DefaultValue} doesn't set anything, if the value is
14478: defined.
14479:
14480: @example
14481: \ generic mach file for pc gforth 03sep97jaw
14482:
14483: true DefaultValue NIL \ relocating
14484:
14485: >ENVIRON
14486:
14487: true DefaultValue file \ controls the presence of the
14488: \ file access wordset
14489: true DefaultValue OS \ flag to indicate a operating system
14490:
14491: true DefaultValue prims \ true: primitives are c-code
14492:
14493: true DefaultValue floating \ floating point wordset is present
14494:
14495: true DefaultValue glocals \ gforth locals are present
14496: \ will be loaded
14497: true DefaultValue dcomps \ double number comparisons
14498:
14499: true DefaultValue hash \ hashing primitives are loaded/present
14500:
14501: true DefaultValue xconds \ used together with glocals,
14502: \ special conditionals supporting gforths'
14503: \ local variables
14504: true DefaultValue header \ save a header information
14505:
14506: true DefaultValue backtrace \ enables backtrace code
14507:
14508: false DefaultValue ec
14509: false DefaultValue crlf
14510:
14511: cell 2 = [IF] &32 [ELSE] &256 [THEN] KB DefaultValue kernel-size
14512:
14513: &16 KB DefaultValue stack-size
14514: &15 KB &512 + DefaultValue fstack-size
14515: &15 KB DefaultValue rstack-size
14516: &14 KB &512 + DefaultValue lstack-size
14517: @end example
1.13 pazsan 14518:
1.48 anton 14519: @node How the Cross Compiler Works, , Using the Cross Compiler, Cross Compiler
1.14 pazsan 14520: @section How the Cross Compiler Works
1.13 pazsan 14521:
14522: @node Bugs, Origin, Cross Compiler, Top
1.21 crook 14523: @appendix Bugs
1.1 anton 14524: @cindex bug reporting
14525:
1.21 crook 14526: Known bugs are described in the file @file{BUGS} in the Gforth distribution.
1.1 anton 14527:
14528: If you find a bug, please send a bug report to
1.33 anton 14529: @email{bug-gforth@@gnu.org}. A bug report should include this
1.21 crook 14530: information:
14531:
14532: @itemize @bullet
14533: @item
14534: The Gforth version used (it is announced at the start of an
14535: interactive Gforth session).
14536: @item
14537: The machine and operating system (on Unix
14538: systems @code{uname -a} will report this information).
14539: @item
14540: The installation options (send the file @file{config.status}).
14541: @item
14542: A complete list of changes (if any) you (or your installer) have made to the
14543: Gforth sources.
14544: @item
14545: A program (or a sequence of keyboard commands) that reproduces the bug.
14546: @item
14547: A description of what you think constitutes the buggy behaviour.
14548: @end itemize
1.1 anton 14549:
14550: For a thorough guide on reporting bugs read @ref{Bug Reporting, , How
14551: to Report Bugs, gcc.info, GNU C Manual}.
14552:
14553:
1.21 crook 14554: @node Origin, Forth-related information, Bugs, Top
14555: @appendix Authors and Ancestors of Gforth
1.1 anton 14556:
14557: @section Authors and Contributors
14558: @cindex authors of Gforth
14559: @cindex contributors to Gforth
14560:
14561: The Gforth project was started in mid-1992 by Bernd Paysan and Anton
14562: Ertl. The third major author was Jens Wilke. Lennart Benschop (who was
14563: one of Gforth's first users, in mid-1993) and Stuart Ramsden inspired us
14564: with their continuous feedback. Lennart Benshop contributed
14565: @file{glosgen.fs}, while Stuart Ramsden has been working on automatic
14566: support for calling C libraries. Helpful comments also came from Paul
14567: Kleinrubatscher, Christian Pirker, Dirk Zoller, Marcel Hendrix, John
1.58 anton 14568: Wavrik, Barrie Stott, Marc de Groot, Jorge Acerada, Bruce Hoyt, and
14569: Robert Epprecht. Since the release of Gforth-0.2.1 there were also
14570: helpful comments from many others; thank you all, sorry for not listing
14571: you here (but digging through my mailbox to extract your names is on my
14572: to-do list). Since the release of Gforth-0.4.0 Neal Crook worked on the
14573: manual.
1.1 anton 14574:
14575: Gforth also owes a lot to the authors of the tools we used (GCC, CVS,
14576: and autoconf, among others), and to the creators of the Internet: Gforth
1.21 crook 14577: was developed across the Internet, and its authors did not meet
1.20 pazsan 14578: physically for the first 4 years of development.
1.1 anton 14579:
14580: @section Pedigree
1.26 crook 14581: @cindex pedigree of Gforth
1.1 anton 14582:
1.20 pazsan 14583: Gforth descends from bigFORTH (1993) and fig-Forth. Gforth and PFE (by
1.1 anton 14584: Dirk Zoller) will cross-fertilize each other. Of course, a significant
14585: part of the design of Gforth was prescribed by ANS Forth.
14586:
1.20 pazsan 14587: Bernd Paysan wrote bigFORTH, a descendent from TurboForth, an unreleased
1.1 anton 14588: 32 bit native code version of VolksForth for the Atari ST, written
14589: mostly by Dietrich Weineck.
14590:
14591: VolksForth descends from F83. It was written by Klaus Schleisiek, Bernd
14592: Pennemann, Georg Rehfeld and Dietrich Weineck for the C64 (called
14593: UltraForth there) in the mid-80s and ported to the Atari ST in 1986.
14594:
14595: Henry Laxen and Mike Perry wrote F83 as a model implementation of the
14596: Forth-83 standard. !! Pedigree? When?
14597:
14598: A team led by Bill Ragsdale implemented fig-Forth on many processors in
14599: 1979. Robert Selzer and Bill Ragsdale developed the original
14600: implementation of fig-Forth for the 6502 based on microForth.
14601:
14602: The principal architect of microForth was Dean Sanderson. microForth was
14603: FORTH, Inc.'s first off-the-shelf product. It was developed in 1976 for
14604: the 1802, and subsequently implemented on the 8080, the 6800 and the
14605: Z80.
14606:
14607: All earlier Forth systems were custom-made, usually by Charles Moore,
14608: who discovered (as he puts it) Forth during the late 60s. The first full
14609: Forth existed in 1971.
14610:
14611: A part of the information in this section comes from @cite{The Evolution
14612: of Forth} by Elizabeth D. Rather, Donald R. Colburn and Charles
14613: H. Moore, presented at the HOPL-II conference and preprinted in SIGPLAN
14614: Notices 28(3), 1993. You can find more historical and genealogical
14615: information about Forth there.
14616:
1.21 crook 14617: @node Forth-related information, Word Index, Origin, Top
14618: @appendix Other Forth-related information
14619: @cindex Forth-related information
14620:
14621: @menu
1.67 anton 14622: * Internet resources::
14623: * Books::
14624: * The Forth Interest Group::
14625: * Conferences::
1.21 crook 14626: @end menu
14627:
14628:
14629: @node Internet resources, Books, Forth-related information, Forth-related information
14630: @section Internet resources
1.26 crook 14631: @cindex internet resources
1.21 crook 14632:
14633: @cindex comp.lang.forth
14634: @cindex frequently asked questions
1.45 crook 14635: There is an active news group (comp.lang.forth) discussing Forth and
1.21 crook 14636: Forth-related issues. A frequently-asked-questions (FAQ) list
1.45 crook 14637: is posted to the news group regularly, and archived at these sites:
1.21 crook 14638:
14639: @itemize @bullet
14640: @item
1.47 crook 14641: @uref{ftp://rtfm.mit.edu/pub/usenet-by-group/comp.lang.forth/}
1.21 crook 14642: @item
1.47 crook 14643: @uref{ftp://ftp.forth.org/pub/Forth/FAQ/}
1.21 crook 14644: @end itemize
14645:
14646: The FAQ list should be considered mandatory reading before posting to
1.45 crook 14647: the news group.
1.21 crook 14648:
14649: Here are some other web sites holding Forth-related material:
14650:
14651: @itemize @bullet
14652: @item
1.47 crook 14653: @uref{http://www.taygeta.com/forth.html} -- Skip Carter's Forth pages.
1.21 crook 14654: @item
1.47 crook 14655: @uref{http://www.jwdt.com/~paysan/gforth.html} -- the Gforth home page.
1.21 crook 14656: @item
1.47 crook 14657: @uref{http://www.minerva.com/uathena.htm} -- home of ANS Forth Standard.
1.21 crook 14658: @item
1.47 crook 14659: @uref{http://dec.bournemouth.ac.uk/forth/index.html} -- the Forth
1.21 crook 14660: Research page, including links to the Journal of Forth Application and
14661: Research (JFAR) and a searchable Forth bibliography.
14662: @end itemize
14663:
14664:
14665: @node Books, The Forth Interest Group, Internet resources, Forth-related information
14666: @section Books
1.26 crook 14667: @cindex books on Forth
1.21 crook 14668:
14669: As the Standard is relatively new, there are not many books out yet. It
14670: is not recommended to learn Forth by using Gforth and a book that is not
14671: written for ANS Forth, as you will not know your mistakes from the
14672: deviations of the book. However, books based on the Forth-83 standard
14673: should be ok, because ANS Forth is primarily an extension of Forth-83.
1.44 crook 14674: Refer to the Forth FAQ for details of Forth-related books.
1.21 crook 14675:
14676: @cindex standard document for ANS Forth
14677: @cindex ANS Forth document
14678: The definite reference if you want to write ANS Forth programs is, of
1.26 crook 14679: course, the ANS Forth document. It is available in printed form from the
1.21 crook 14680: National Standards Institute Sales Department (Tel.: USA (212) 642-4900;
14681: Fax.: USA (212) 302-1286) as document @cite{X3.215-1994} for about
14682: $200. You can also get it from Global Engineering Documents (Tel.: USA
14683: (800) 854-7179; Fax.: (303) 843-9880) for about $300.
14684:
14685: @cite{dpANS6}, the last draft of the standard, which was then submitted
14686: to ANSI for publication is available electronically and for free in some
14687: MS Word format, and it has been converted to HTML
1.47 crook 14688: (@uref{http://www.taygeta.com/forth/dpans.html}; this HTML version also
1.44 crook 14689: includes the answers to Requests for Interpretation (RFIs). Some
14690: pointers to these versions can be found through
1.47 crook 14691: @*@uref{http://www.complang.tuwien.ac.at/projects/forth.html}.
1.44 crook 14692:
1.21 crook 14693:
14694: @node The Forth Interest Group, Conferences, Books, Forth-related information
14695: @section The Forth Interest Group
14696: @cindex Forth interest group (FIG)
14697:
14698: The Forth Interest Group (FIG) is a world-wide, non-profit,
1.26 crook 14699: member-supported organisation. It publishes a regular magazine,
14700: @var{FORTH Dimensions}, and offers other benefits of membership. You can
14701: contact the FIG through their office email address:
14702: @email{office@@forth.org} or by visiting their web site at
1.47 crook 14703: @uref{http://www.forth.org/}. This web site also includes links to FIG
1.26 crook 14704: chapters in other countries and American cities
1.47 crook 14705: (@uref{http://www.forth.org/chapters.html}).
1.21 crook 14706:
1.48 anton 14707: @node Conferences, , The Forth Interest Group, Forth-related information
1.21 crook 14708: @section Conferences
14709: @cindex Conferences
14710:
14711: There are several regular conferences related to Forth. They are all
1.26 crook 14712: well-publicised in @var{FORTH Dimensions} and on the comp.lang.forth
1.45 crook 14713: news group:
1.21 crook 14714:
14715: @itemize @bullet
14716: @item
14717: FORML -- the Forth modification laboratory convenes every year near
14718: Monterey, California.
14719: @item
14720: The Rochester Forth Conference -- an annual conference traditionally
14721: held in Rochester, New York.
14722: @item
14723: EuroForth -- this European conference takes place annually.
14724: @end itemize
14725:
14726:
1.41 anton 14727: @node Word Index, Name Index, Forth-related information, Top
1.1 anton 14728: @unnumbered Word Index
14729:
1.26 crook 14730: This index is a list of Forth words that have ``glossary'' entries
14731: within this manual. Each word is listed with its stack effect and
14732: wordset.
1.1 anton 14733:
14734: @printindex fn
14735:
1.41 anton 14736: @node Name Index, Concept Index, Word Index, Top
14737: @unnumbered Name Index
14738:
14739: This index is a list of Forth words that have ``glossary'' entries
14740: within this manual.
14741:
14742: @printindex ky
14743:
14744: @node Concept Index, , Name Index, Top
1.1 anton 14745: @unnumbered Concept and Word Index
14746:
1.26 crook 14747: Not all entries listed in this index are present verbatim in the
14748: text. This index also duplicates, in abbreviated form, all of the words
14749: listed in the Word Index (only the names are listed for the words here).
1.1 anton 14750:
14751: @printindex cp
14752:
14753: @contents
14754: @bye
14755:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>