Annotation of gforth/doc/gforth.ds, revision 1.85
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
170: * Concept Index:: A menu covering many topics
1.12 anton 171:
1.78 anton 172: @detailmenu --- The Detailed Node Listing ---
1.12 anton 173:
1.29 crook 174: Gforth Environment
175:
1.32 anton 176: * Invoking Gforth:: Getting in
177: * Leaving Gforth:: Getting out
178: * Command-line editing::
1.48 anton 179: * Environment variables:: that affect how Gforth starts up
1.32 anton 180: * Gforth Files:: What gets installed and where
1.48 anton 181: * Startup speed:: When 35ms is not fast enough ...
182:
183: Forth Tutorial
184:
185: * Starting Gforth Tutorial::
186: * Syntax Tutorial::
187: * Crash Course Tutorial::
188: * Stack Tutorial::
189: * Arithmetics Tutorial::
190: * Stack Manipulation Tutorial::
191: * Using files for Forth code Tutorial::
192: * Comments Tutorial::
193: * Colon Definitions Tutorial::
194: * Decompilation Tutorial::
195: * Stack-Effect Comments Tutorial::
196: * Types Tutorial::
197: * Factoring Tutorial::
198: * Designing the stack effect Tutorial::
199: * Local Variables Tutorial::
200: * Conditional execution Tutorial::
201: * Flags and Comparisons Tutorial::
202: * General Loops Tutorial::
203: * Counted loops Tutorial::
204: * Recursion Tutorial::
205: * Leaving definitions or loops Tutorial::
206: * Return Stack Tutorial::
207: * Memory Tutorial::
208: * Characters and Strings Tutorial::
209: * Alignment Tutorial::
210: * Interpretation and Compilation Semantics and Immediacy Tutorial::
211: * Execution Tokens Tutorial::
212: * Exceptions Tutorial::
213: * Defining Words Tutorial::
214: * Arrays and Records Tutorial::
215: * POSTPONE Tutorial::
216: * Literal Tutorial::
217: * Advanced macros Tutorial::
218: * Compilation Tokens Tutorial::
219: * Wordlists and Search Order Tutorial::
1.29 crook 220:
1.24 anton 221: An Introduction to ANS Forth
222:
1.67 anton 223: * Introducing the Text Interpreter::
224: * Stacks and Postfix notation::
225: * Your first definition::
226: * How does that work?::
227: * Forth is written in Forth::
228: * Review - elements of a Forth system::
229: * Where to go next::
230: * Exercises::
1.24 anton 231:
1.12 anton 232: Forth Words
233:
234: * Notation::
1.65 anton 235: * Case insensitivity::
236: * Comments::
237: * Boolean Flags::
1.12 anton 238: * Arithmetic::
239: * Stack Manipulation::
240: * Memory::
241: * Control Structures::
242: * Defining Words::
1.65 anton 243: * Interpretation and Compilation Semantics::
1.47 crook 244: * Tokens for Words::
1.81 anton 245: * Compiling words::
1.65 anton 246: * The Text Interpreter::
247: * Word Lists::
248: * Environmental Queries::
1.12 anton 249: * Files::
250: * Blocks::
251: * Other I/O::
1.78 anton 252: * Locals::
253: * Structures::
254: * Object-oriented Forth::
1.12 anton 255: * Programming Tools::
256: * Assembler and Code Words::
257: * Threading Words::
1.65 anton 258: * Passing Commands to the OS::
259: * Keeping track of Time::
260: * Miscellaneous Words::
1.12 anton 261:
262: Arithmetic
263:
264: * Single precision::
1.67 anton 265: * Double precision:: Double-cell integer arithmetic
1.12 anton 266: * Bitwise operations::
1.67 anton 267: * Numeric comparison::
1.32 anton 268: * Mixed precision:: Operations with single and double-cell integers
1.12 anton 269: * Floating Point::
270:
271: Stack Manipulation
272:
273: * Data stack::
274: * Floating point stack::
275: * Return stack::
276: * Locals stack::
277: * Stack pointer manipulation::
278:
279: Memory
280:
1.32 anton 281: * Memory model::
282: * Dictionary allocation::
283: * Heap Allocation::
284: * Memory Access::
285: * Address arithmetic::
286: * Memory Blocks::
1.12 anton 287:
288: Control Structures
289:
1.41 anton 290: * Selection:: IF ... ELSE ... ENDIF
291: * Simple Loops:: BEGIN ...
1.32 anton 292: * Counted Loops:: DO
1.67 anton 293: * Arbitrary control structures::
294: * Calls and returns::
1.12 anton 295: * Exception Handling::
296:
297: Defining Words
298:
1.67 anton 299: * CREATE::
1.44 crook 300: * Variables:: Variables and user variables
1.67 anton 301: * Constants::
1.44 crook 302: * Values:: Initialised variables
1.67 anton 303: * Colon Definitions::
1.44 crook 304: * Anonymous Definitions:: Definitions without names
1.71 anton 305: * Supplying names:: Passing definition names as strings
1.67 anton 306: * User-defined Defining Words::
1.44 crook 307: * Deferred words:: Allow forward references
1.67 anton 308: * Aliases::
1.47 crook 309:
1.63 anton 310: User-defined Defining Words
311:
312: * CREATE..DOES> applications::
313: * CREATE..DOES> details::
314: * Advanced does> usage example::
315:
1.47 crook 316: Interpretation and Compilation Semantics
317:
1.67 anton 318: * Combined words::
1.12 anton 319:
1.71 anton 320: Tokens for Words
321:
322: * Execution token:: represents execution/interpretation semantics
323: * Compilation token:: represents compilation semantics
324: * Name token:: represents named words
325:
1.82 anton 326: Compiling words
327:
328: * Literals:: Compiling data values
329: * Macros:: Compiling words
330:
1.21 crook 331: The Text Interpreter
332:
1.67 anton 333: * Input Sources::
334: * Number Conversion::
335: * Interpret/Compile states::
336: * Interpreter Directives::
1.21 crook 337:
1.26 crook 338: Word Lists
339:
1.75 anton 340: * Vocabularies::
1.67 anton 341: * Why use word lists?::
1.75 anton 342: * Word list example::
1.26 crook 343:
344: Files
345:
1.48 anton 346: * Forth source files::
347: * General files::
348: * Search Paths::
349:
350: Search Paths
351:
1.75 anton 352: * Source Search Paths::
1.26 crook 353: * General Search Paths::
354:
355: Other I/O
356:
1.32 anton 357: * Simple numeric output:: Predefined formats
358: * Formatted numeric output:: Formatted (pictured) output
359: * String Formats:: How Forth stores strings in memory
1.67 anton 360: * Displaying characters and strings:: Other stuff
1.32 anton 361: * Input:: Input
1.26 crook 362:
363: Locals
364:
365: * Gforth locals::
366: * ANS Forth locals::
367:
368: Gforth locals
369:
370: * Where are locals visible by name?::
371: * How long do locals live?::
1.78 anton 372: * Locals programming style::
373: * Locals implementation::
1.26 crook 374:
1.12 anton 375: Structures
376:
377: * Why explicit structure support?::
378: * Structure Usage::
379: * Structure Naming Convention::
380: * Structure Implementation::
381: * Structure Glossary::
382:
383: Object-oriented Forth
384:
1.48 anton 385: * Why object-oriented programming?::
386: * Object-Oriented Terminology::
387: * Objects::
388: * OOF::
389: * Mini-OOF::
1.23 crook 390: * Comparison with other object models::
1.12 anton 391:
1.24 anton 392: The @file{objects.fs} model
1.12 anton 393:
394: * Properties of the Objects model::
395: * Basic Objects Usage::
1.41 anton 396: * The Objects base class::
1.12 anton 397: * Creating objects::
398: * Object-Oriented Programming Style::
399: * Class Binding::
400: * Method conveniences::
401: * Classes and Scoping::
1.41 anton 402: * Dividing classes::
1.12 anton 403: * Object Interfaces::
404: * Objects Implementation::
405: * Objects Glossary::
406:
1.24 anton 407: The @file{oof.fs} model
1.12 anton 408:
1.67 anton 409: * Properties of the OOF model::
410: * Basic OOF Usage::
411: * The OOF base class::
412: * Class Declaration::
413: * Class Implementation::
1.12 anton 414:
1.24 anton 415: The @file{mini-oof.fs} model
1.23 crook 416:
1.48 anton 417: * Basic Mini-OOF Usage::
418: * Mini-OOF Example::
419: * Mini-OOF Implementation::
1.23 crook 420:
1.78 anton 421: Programming Tools
422:
423: * Examining::
424: * Forgetting words::
425: * Debugging:: Simple and quick.
426: * Assertions:: Making your programs self-checking.
427: * Singlestep Debugger:: Executing your program word by word.
428:
429: Assembler and Code Words
430:
431: * Code and ;code::
432: * Common Assembler:: Assembler Syntax
433: * Common Disassembler::
434: * 386 Assembler:: Deviations and special cases
435: * Alpha Assembler:: Deviations and special cases
436: * MIPS assembler:: Deviations and special cases
437: * Other assemblers:: How to write them
438:
1.12 anton 439: Tools
440:
441: * ANS Report:: Report the words used, sorted by wordset.
442:
443: ANS conformance
444:
445: * The Core Words::
446: * The optional Block word set::
447: * The optional Double Number word set::
448: * The optional Exception word set::
449: * The optional Facility word set::
450: * The optional File-Access word set::
451: * The optional Floating-Point word set::
452: * The optional Locals word set::
453: * The optional Memory-Allocation word set::
454: * The optional Programming-Tools word set::
455: * The optional Search-Order word set::
456:
457: The Core Words
458:
459: * core-idef:: Implementation Defined Options
460: * core-ambcond:: Ambiguous Conditions
461: * core-other:: Other System Documentation
462:
463: The optional Block word set
464:
465: * block-idef:: Implementation Defined Options
466: * block-ambcond:: Ambiguous Conditions
467: * block-other:: Other System Documentation
468:
469: The optional Double Number word set
470:
471: * double-ambcond:: Ambiguous Conditions
472:
473: The optional Exception word set
474:
475: * exception-idef:: Implementation Defined Options
476:
477: The optional Facility word set
478:
479: * facility-idef:: Implementation Defined Options
480: * facility-ambcond:: Ambiguous Conditions
481:
482: The optional File-Access word set
483:
484: * file-idef:: Implementation Defined Options
485: * file-ambcond:: Ambiguous Conditions
486:
487: The optional Floating-Point word set
488:
489: * floating-idef:: Implementation Defined Options
490: * floating-ambcond:: Ambiguous Conditions
491:
492: The optional Locals word set
493:
494: * locals-idef:: Implementation Defined Options
495: * locals-ambcond:: Ambiguous Conditions
496:
497: The optional Memory-Allocation word set
498:
499: * memory-idef:: Implementation Defined Options
500:
501: The optional Programming-Tools word set
502:
503: * programming-idef:: Implementation Defined Options
504: * programming-ambcond:: Ambiguous Conditions
505:
506: The optional Search-Order word set
507:
508: * search-idef:: Implementation Defined Options
509: * search-ambcond:: Ambiguous Conditions
510:
511: Image Files
512:
1.24 anton 513: * Image Licensing Issues:: Distribution terms for images.
514: * Image File Background:: Why have image files?
1.67 anton 515: * Non-Relocatable Image Files:: don't always work.
1.24 anton 516: * Data-Relocatable Image Files:: are better.
1.67 anton 517: * Fully Relocatable Image Files:: better yet.
1.24 anton 518: * Stack and Dictionary Sizes:: Setting the default sizes for an image.
1.32 anton 519: * Running Image Files:: @code{gforth -i @i{file}} or @i{file}.
1.24 anton 520: * Modifying the Startup Sequence:: and turnkey applications.
1.12 anton 521:
522: Fully Relocatable Image Files
523:
1.27 crook 524: * gforthmi:: The normal way
1.12 anton 525: * cross.fs:: The hard way
526:
527: Engine
528:
529: * Portability::
530: * Threading::
531: * Primitives::
532: * Performance::
533:
534: Threading
535:
536: * Scheduling::
537: * Direct or Indirect Threaded?::
538: * DOES>::
539:
540: Primitives
541:
542: * Automatic Generation::
543: * TOS Optimization::
544: * Produced code::
1.13 pazsan 545:
546: Cross Compiler
547:
1.67 anton 548: * Using the Cross Compiler::
549: * How the Cross Compiler Works::
1.13 pazsan 550:
1.24 anton 551: @end detailmenu
1.1 anton 552: @end menu
553:
1.26 crook 554: @node License, Goals, Top, Top
1.1 anton 555: @unnumbered GNU GENERAL PUBLIC LICENSE
556: @center Version 2, June 1991
557:
558: @display
559: Copyright @copyright{} 1989, 1991 Free Software Foundation, Inc.
560: 675 Mass Ave, Cambridge, MA 02139, USA
561:
562: Everyone is permitted to copy and distribute verbatim copies
563: of this license document, but changing it is not allowed.
564: @end display
565:
566: @unnumberedsec Preamble
567:
568: The licenses for most software are designed to take away your
569: freedom to share and change it. By contrast, the GNU General Public
570: License is intended to guarantee your freedom to share and change free
571: software---to make sure the software is free for all its users. This
572: General Public License applies to most of the Free Software
573: Foundation's software and to any other program whose authors commit to
574: using it. (Some other Free Software Foundation software is covered by
575: the GNU Library General Public License instead.) You can apply it to
576: your programs, too.
577:
578: When we speak of free software, we are referring to freedom, not
579: price. Our General Public Licenses are designed to make sure that you
580: have the freedom to distribute copies of free software (and charge for
581: this service if you wish), that you receive source code or can get it
582: if you want it, that you can change the software or use pieces of it
583: in new free programs; and that you know you can do these things.
584:
585: To protect your rights, we need to make restrictions that forbid
586: anyone to deny you these rights or to ask you to surrender the rights.
587: These restrictions translate to certain responsibilities for you if you
588: distribute copies of the software, or if you modify it.
589:
590: For example, if you distribute copies of such a program, whether
591: gratis or for a fee, you must give the recipients all the rights that
592: you have. You must make sure that they, too, receive or can get the
593: source code. And you must show them these terms so they know their
594: rights.
595:
596: We protect your rights with two steps: (1) copyright the software, and
597: (2) offer you this license which gives you legal permission to copy,
598: distribute and/or modify the software.
599:
600: Also, for each author's protection and ours, we want to make certain
601: that everyone understands that there is no warranty for this free
602: software. If the software is modified by someone else and passed on, we
603: want its recipients to know that what they have is not the original, so
604: that any problems introduced by others will not reflect on the original
605: authors' reputations.
606:
607: Finally, any free program is threatened constantly by software
608: patents. We wish to avoid the danger that redistributors of a free
609: program will individually obtain patent licenses, in effect making the
610: program proprietary. To prevent this, we have made it clear that any
611: patent must be licensed for everyone's free use or not licensed at all.
612:
613: The precise terms and conditions for copying, distribution and
614: modification follow.
615:
616: @iftex
617: @unnumberedsec TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
618: @end iftex
1.49 anton 619: @ifnottex
1.1 anton 620: @center TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
1.49 anton 621: @end ifnottex
1.1 anton 622:
623: @enumerate 0
624: @item
625: This License applies to any program or other work which contains
626: a notice placed by the copyright holder saying it may be distributed
627: under the terms of this General Public License. The ``Program'', below,
628: refers to any such program or work, and a ``work based on the Program''
629: means either the Program or any derivative work under copyright law:
630: that is to say, a work containing the Program or a portion of it,
631: either verbatim or with modifications and/or translated into another
632: language. (Hereinafter, translation is included without limitation in
633: the term ``modification''.) Each licensee is addressed as ``you''.
634:
635: Activities other than copying, distribution and modification are not
636: covered by this License; they are outside its scope. The act of
637: running the Program is not restricted, and the output from the Program
638: is covered only if its contents constitute a work based on the
639: Program (independent of having been made by running the Program).
640: Whether that is true depends on what the Program does.
641:
642: @item
643: You may copy and distribute verbatim copies of the Program's
644: source code as you receive it, in any medium, provided that you
645: conspicuously and appropriately publish on each copy an appropriate
646: copyright notice and disclaimer of warranty; keep intact all the
647: notices that refer to this License and to the absence of any warranty;
648: and give any other recipients of the Program a copy of this License
649: along with the Program.
650:
651: You may charge a fee for the physical act of transferring a copy, and
652: you may at your option offer warranty protection in exchange for a fee.
653:
654: @item
655: You may modify your copy or copies of the Program or any portion
656: of it, thus forming a work based on the Program, and copy and
657: distribute such modifications or work under the terms of Section 1
658: above, provided that you also meet all of these conditions:
659:
660: @enumerate a
661: @item
662: You must cause the modified files to carry prominent notices
663: stating that you changed the files and the date of any change.
664:
665: @item
666: You must cause any work that you distribute or publish, that in
667: whole or in part contains or is derived from the Program or any
668: part thereof, to be licensed as a whole at no charge to all third
669: parties under the terms of this License.
670:
671: @item
672: If the modified program normally reads commands interactively
673: when run, you must cause it, when started running for such
674: interactive use in the most ordinary way, to print or display an
675: announcement including an appropriate copyright notice and a
676: notice that there is no warranty (or else, saying that you provide
677: a warranty) and that users may redistribute the program under
678: these conditions, and telling the user how to view a copy of this
679: License. (Exception: if the Program itself is interactive but
680: does not normally print such an announcement, your work based on
681: the Program is not required to print an announcement.)
682: @end enumerate
683:
684: These requirements apply to the modified work as a whole. If
685: identifiable sections of that work are not derived from the Program,
686: and can be reasonably considered independent and separate works in
687: themselves, then this License, and its terms, do not apply to those
688: sections when you distribute them as separate works. But when you
689: distribute the same sections as part of a whole which is a work based
690: on the Program, the distribution of the whole must be on the terms of
691: this License, whose permissions for other licensees extend to the
692: entire whole, and thus to each and every part regardless of who wrote it.
693:
694: Thus, it is not the intent of this section to claim rights or contest
695: your rights to work written entirely by you; rather, the intent is to
696: exercise the right to control the distribution of derivative or
697: collective works based on the Program.
698:
699: In addition, mere aggregation of another work not based on the Program
700: with the Program (or with a work based on the Program) on a volume of
701: a storage or distribution medium does not bring the other work under
702: the scope of this License.
703:
704: @item
705: You may copy and distribute the Program (or a work based on it,
706: under Section 2) in object code or executable form under the terms of
707: Sections 1 and 2 above provided that you also do one of the following:
708:
709: @enumerate a
710: @item
711: Accompany it with the complete corresponding machine-readable
712: source code, which must be distributed under the terms of Sections
713: 1 and 2 above on a medium customarily used for software interchange; or,
714:
715: @item
716: Accompany it with a written offer, valid for at least three
717: years, to give any third party, for a charge no more than your
718: cost of physically performing source distribution, a complete
719: machine-readable copy of the corresponding source code, to be
720: distributed under the terms of Sections 1 and 2 above on a medium
721: customarily used for software interchange; or,
722:
723: @item
724: Accompany it with the information you received as to the offer
725: to distribute corresponding source code. (This alternative is
726: allowed only for noncommercial distribution and only if you
727: received the program in object code or executable form with such
728: an offer, in accord with Subsection b above.)
729: @end enumerate
730:
731: The source code for a work means the preferred form of the work for
732: making modifications to it. For an executable work, complete source
733: code means all the source code for all modules it contains, plus any
734: associated interface definition files, plus the scripts used to
735: control compilation and installation of the executable. However, as a
736: special exception, the source code distributed need not include
737: anything that is normally distributed (in either source or binary
738: form) with the major components (compiler, kernel, and so on) of the
739: operating system on which the executable runs, unless that component
740: itself accompanies the executable.
741:
742: If distribution of executable or object code is made by offering
743: access to copy from a designated place, then offering equivalent
744: access to copy the source code from the same place counts as
745: distribution of the source code, even though third parties are not
746: compelled to copy the source along with the object code.
747:
748: @item
749: You may not copy, modify, sublicense, or distribute the Program
750: except as expressly provided under this License. Any attempt
751: otherwise to copy, modify, sublicense or distribute the Program is
752: void, and will automatically terminate your rights under this License.
753: However, parties who have received copies, or rights, from you under
754: this License will not have their licenses terminated so long as such
755: parties remain in full compliance.
756:
757: @item
758: You are not required to accept this License, since you have not
759: signed it. However, nothing else grants you permission to modify or
760: distribute the Program or its derivative works. These actions are
761: prohibited by law if you do not accept this License. Therefore, by
762: modifying or distributing the Program (or any work based on the
763: Program), you indicate your acceptance of this License to do so, and
764: all its terms and conditions for copying, distributing or modifying
765: the Program or works based on it.
766:
767: @item
768: Each time you redistribute the Program (or any work based on the
769: Program), the recipient automatically receives a license from the
770: original licensor to copy, distribute or modify the Program subject to
771: these terms and conditions. You may not impose any further
772: restrictions on the recipients' exercise of the rights granted herein.
773: You are not responsible for enforcing compliance by third parties to
774: this License.
775:
776: @item
777: If, as a consequence of a court judgment or allegation of patent
778: infringement or for any other reason (not limited to patent issues),
779: conditions are imposed on you (whether by court order, agreement or
780: otherwise) that contradict the conditions of this License, they do not
781: excuse you from the conditions of this License. If you cannot
782: distribute so as to satisfy simultaneously your obligations under this
783: License and any other pertinent obligations, then as a consequence you
784: may not distribute the Program at all. For example, if a patent
785: license would not permit royalty-free redistribution of the Program by
786: all those who receive copies directly or indirectly through you, then
787: the only way you could satisfy both it and this License would be to
788: refrain entirely from distribution of the Program.
789:
790: If any portion of this section is held invalid or unenforceable under
791: any particular circumstance, the balance of the section is intended to
792: apply and the section as a whole is intended to apply in other
793: circumstances.
794:
795: It is not the purpose of this section to induce you to infringe any
796: patents or other property right claims or to contest validity of any
797: such claims; this section has the sole purpose of protecting the
798: integrity of the free software distribution system, which is
799: implemented by public license practices. Many people have made
800: generous contributions to the wide range of software distributed
801: through that system in reliance on consistent application of that
802: system; it is up to the author/donor to decide if he or she is willing
803: to distribute software through any other system and a licensee cannot
804: impose that choice.
805:
806: This section is intended to make thoroughly clear what is believed to
807: be a consequence of the rest of this License.
808:
809: @item
810: If the distribution and/or use of the Program is restricted in
811: certain countries either by patents or by copyrighted interfaces, the
812: original copyright holder who places the Program under this License
813: may add an explicit geographical distribution limitation excluding
814: those countries, so that distribution is permitted only in or among
815: countries not thus excluded. In such case, this License incorporates
816: the limitation as if written in the body of this License.
817:
818: @item
819: The Free Software Foundation may publish revised and/or new versions
820: of the General Public License from time to time. Such new versions will
821: be similar in spirit to the present version, but may differ in detail to
822: address new problems or concerns.
823:
824: Each version is given a distinguishing version number. If the Program
825: specifies a version number of this License which applies to it and ``any
826: later version'', you have the option of following the terms and conditions
827: either of that version or of any later version published by the Free
828: Software Foundation. If the Program does not specify a version number of
829: this License, you may choose any version ever published by the Free Software
830: Foundation.
831:
832: @item
833: If you wish to incorporate parts of the Program into other free
834: programs whose distribution conditions are different, write to the author
835: to ask for permission. For software which is copyrighted by the Free
836: Software Foundation, write to the Free Software Foundation; we sometimes
837: make exceptions for this. Our decision will be guided by the two goals
838: of preserving the free status of all derivatives of our free software and
839: of promoting the sharing and reuse of software generally.
840:
841: @iftex
842: @heading NO WARRANTY
843: @end iftex
1.49 anton 844: @ifnottex
1.1 anton 845: @center NO WARRANTY
1.49 anton 846: @end ifnottex
1.1 anton 847:
848: @item
849: BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
850: FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
851: OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
852: PROVIDE THE PROGRAM ``AS IS'' WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
853: OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
854: MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
855: TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
856: PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
857: REPAIR OR CORRECTION.
858:
859: @item
860: IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
861: WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
862: REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
863: INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
864: OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
865: TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
866: YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
867: PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
868: POSSIBILITY OF SUCH DAMAGES.
869: @end enumerate
870:
871: @iftex
872: @heading END OF TERMS AND CONDITIONS
873: @end iftex
1.49 anton 874: @ifnottex
1.1 anton 875: @center END OF TERMS AND CONDITIONS
1.49 anton 876: @end ifnottex
1.1 anton 877:
878: @page
879: @unnumberedsec How to Apply These Terms to Your New Programs
880:
881: If you develop a new program, and you want it to be of the greatest
882: possible use to the public, the best way to achieve this is to make it
883: free software which everyone can redistribute and change under these terms.
884:
885: To do so, attach the following notices to the program. It is safest
886: to attach them to the start of each source file to most effectively
887: convey the exclusion of warranty; and each file should have at least
888: the ``copyright'' line and a pointer to where the full notice is found.
889:
890: @smallexample
891: @var{one line to give the program's name and a brief idea of what it does.}
892: Copyright (C) 19@var{yy} @var{name of author}
893:
894: This program is free software; you can redistribute it and/or modify
895: it under the terms of the GNU General Public License as published by
896: the Free Software Foundation; either version 2 of the License, or
897: (at your option) any later version.
898:
899: This program is distributed in the hope that it will be useful,
900: but WITHOUT ANY WARRANTY; without even the implied warranty of
901: MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
902: GNU General Public License for more details.
903:
904: You should have received a copy of the GNU General Public License
905: along with this program; if not, write to the Free Software
906: Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
907: @end smallexample
908:
909: Also add information on how to contact you by electronic and paper mail.
910:
911: If the program is interactive, make it output a short notice like this
912: when it starts in an interactive mode:
913:
914: @smallexample
915: Gnomovision version 69, Copyright (C) 19@var{yy} @var{name of author}
916: Gnomovision comes with ABSOLUTELY NO WARRANTY; for details
917: type `show w'.
918: This is free software, and you are welcome to redistribute it
919: under certain conditions; type `show c' for details.
920: @end smallexample
921:
922: The hypothetical commands @samp{show w} and @samp{show c} should show
923: the appropriate parts of the General Public License. Of course, the
924: commands you use may be called something other than @samp{show w} and
925: @samp{show c}; they could even be mouse-clicks or menu items---whatever
926: suits your program.
927:
928: You should also get your employer (if you work as a programmer) or your
929: school, if any, to sign a ``copyright disclaimer'' for the program, if
930: necessary. Here is a sample; alter the names:
931:
932: @smallexample
933: Yoyodyne, Inc., hereby disclaims all copyright interest in the program
934: `Gnomovision' (which makes passes at compilers) written by James Hacker.
935:
936: @var{signature of Ty Coon}, 1 April 1989
937: Ty Coon, President of Vice
938: @end smallexample
939:
940: This General Public License does not permit incorporating your program into
941: proprietary programs. If your program is a subroutine library, you may
942: consider it more useful to permit linking proprietary applications with the
943: library. If this is what you want to do, use the GNU Library General
944: Public License instead of this License.
945:
946: @iftex
947: @unnumbered Preface
948: @cindex Preface
1.21 crook 949: This manual documents Gforth. Some introductory material is provided for
950: readers who are unfamiliar with Forth or who are migrating to Gforth
951: from other Forth compilers. However, this manual is primarily a
952: reference manual.
1.1 anton 953: @end iftex
954:
1.28 crook 955: @comment TODO much more blurb here.
1.26 crook 956:
957: @c ******************************************************************
1.29 crook 958: @node Goals, Gforth Environment, License, Top
1.26 crook 959: @comment node-name, next, previous, up
960: @chapter Goals of Gforth
961: @cindex goals of the Gforth project
962: The goal of the Gforth Project is to develop a standard model for
963: ANS Forth. This can be split into several subgoals:
964:
965: @itemize @bullet
966: @item
967: Gforth should conform to the ANS Forth Standard.
968: @item
969: It should be a model, i.e. it should define all the
970: implementation-dependent things.
971: @item
972: It should become standard, i.e. widely accepted and used. This goal
973: is the most difficult one.
974: @end itemize
975:
976: To achieve these goals Gforth should be
977: @itemize @bullet
978: @item
979: Similar to previous models (fig-Forth, F83)
980: @item
981: Powerful. It should provide for all the things that are considered
982: necessary today and even some that are not yet considered necessary.
983: @item
984: Efficient. It should not get the reputation of being exceptionally
985: slow.
986: @item
987: Free.
988: @item
989: Available on many machines/easy to port.
990: @end itemize
991:
992: Have we achieved these goals? Gforth conforms to the ANS Forth
993: standard. It may be considered a model, but we have not yet documented
994: which parts of the model are stable and which parts we are likely to
995: change. It certainly has not yet become a de facto standard, but it
996: appears to be quite popular. It has some similarities to and some
997: differences from previous models. It has some powerful features, but not
998: yet everything that we envisioned. We certainly have achieved our
1.65 anton 999: execution speed goals (@pxref{Performance})@footnote{However, in 1998
1000: the bar was raised when the major commercial Forth vendors switched to
1001: native code compilers.}. It is free and available on many machines.
1.29 crook 1002:
1.26 crook 1003: @c ******************************************************************
1.48 anton 1004: @node Gforth Environment, Tutorial, Goals, Top
1.29 crook 1005: @chapter Gforth Environment
1006: @cindex Gforth environment
1.21 crook 1007:
1.45 crook 1008: Note: ultimately, the Gforth man page will be auto-generated from the
1.29 crook 1009: material in this chapter.
1.21 crook 1010:
1011: @menu
1.29 crook 1012: * Invoking Gforth:: Getting in
1013: * Leaving Gforth:: Getting out
1014: * Command-line editing::
1.48 anton 1015: * Environment variables:: that affect how Gforth starts up
1.29 crook 1016: * Gforth Files:: What gets installed and where
1.48 anton 1017: * Startup speed:: When 35ms is not fast enough ...
1.21 crook 1018: @end menu
1019:
1.49 anton 1020: For related information about the creation of images see @ref{Image Files}.
1.29 crook 1021:
1.21 crook 1022: @comment ----------------------------------------------
1.48 anton 1023: @node Invoking Gforth, Leaving Gforth, Gforth Environment, Gforth Environment
1.29 crook 1024: @section Invoking Gforth
1025: @cindex invoking Gforth
1026: @cindex running Gforth
1027: @cindex command-line options
1028: @cindex options on the command line
1029: @cindex flags on the command line
1.21 crook 1030:
1.30 anton 1031: Gforth is made up of two parts; an executable ``engine'' (named
1032: @file{gforth} or @file{gforth-fast}) and an image file. To start it, you
1033: will usually just say @code{gforth} -- this automatically loads the
1034: default image file @file{gforth.fi}. In many other cases the default
1035: Gforth image will be invoked like this:
1.21 crook 1036: @example
1.30 anton 1037: gforth [file | -e forth-code] ...
1.21 crook 1038: @end example
1.29 crook 1039: @noindent
1040: This interprets the contents of the files and the Forth code in the order they
1041: are given.
1.21 crook 1042:
1.30 anton 1043: In addition to the @file{gforth} engine, there is also an engine called
1044: @file{gforth-fast}, which is faster, but gives less informative error
1045: messages (@pxref{Error messages}).
1046:
1.29 crook 1047: In general, the command line looks like this:
1.21 crook 1048:
1049: @example
1.30 anton 1050: gforth[-fast] [engine options] [image options]
1.21 crook 1051: @end example
1052:
1.30 anton 1053: The engine options must come before the rest of the command
1.29 crook 1054: line. They are:
1.26 crook 1055:
1.29 crook 1056: @table @code
1057: @cindex -i, command-line option
1058: @cindex --image-file, command-line option
1059: @item --image-file @i{file}
1060: @itemx -i @i{file}
1061: Loads the Forth image @i{file} instead of the default
1062: @file{gforth.fi} (@pxref{Image Files}).
1.21 crook 1063:
1.39 anton 1064: @cindex --appl-image, command-line option
1065: @item --appl-image @i{file}
1066: Loads the image @i{file} and leaves all further command-line arguments
1.65 anton 1067: to the image (instead of processing them as engine options). This is
1068: useful for building executable application images on Unix, built with
1.39 anton 1069: @code{gforthmi --application ...}.
1070:
1.29 crook 1071: @cindex --path, command-line option
1072: @cindex -p, command-line option
1073: @item --path @i{path}
1074: @itemx -p @i{path}
1075: Uses @i{path} for searching the image file and Forth source code files
1076: instead of the default in the environment variable @code{GFORTHPATH} or
1077: the path specified at installation time (e.g.,
1078: @file{/usr/local/share/gforth/0.2.0:.}). A path is given as a list of
1079: directories, separated by @samp{:} (on Unix) or @samp{;} (on other OSs).
1.21 crook 1080:
1.29 crook 1081: @cindex --dictionary-size, command-line option
1082: @cindex -m, command-line option
1083: @cindex @i{size} parameters for command-line options
1084: @cindex size of the dictionary and the stacks
1085: @item --dictionary-size @i{size}
1086: @itemx -m @i{size}
1087: Allocate @i{size} space for the Forth dictionary space instead of
1088: using the default specified in the image (typically 256K). The
1089: @i{size} specification for this and subsequent options consists of
1090: an integer and a unit (e.g.,
1091: @code{4M}). The unit can be one of @code{b} (bytes), @code{e} (element
1092: size, in this case Cells), @code{k} (kilobytes), @code{M} (Megabytes),
1093: @code{G} (Gigabytes), and @code{T} (Terabytes). If no unit is specified,
1094: @code{e} is used.
1.21 crook 1095:
1.29 crook 1096: @cindex --data-stack-size, command-line option
1097: @cindex -d, command-line option
1098: @item --data-stack-size @i{size}
1099: @itemx -d @i{size}
1100: Allocate @i{size} space for the data stack instead of using the
1101: default specified in the image (typically 16K).
1.21 crook 1102:
1.29 crook 1103: @cindex --return-stack-size, command-line option
1104: @cindex -r, command-line option
1105: @item --return-stack-size @i{size}
1106: @itemx -r @i{size}
1107: Allocate @i{size} space for the return stack instead of using the
1108: default specified in the image (typically 15K).
1.21 crook 1109:
1.29 crook 1110: @cindex --fp-stack-size, command-line option
1111: @cindex -f, command-line option
1112: @item --fp-stack-size @i{size}
1113: @itemx -f @i{size}
1114: Allocate @i{size} space for the floating point stack instead of
1115: using the default specified in the image (typically 15.5K). In this case
1116: the unit specifier @code{e} refers to floating point numbers.
1.21 crook 1117:
1.48 anton 1118: @cindex --locals-stack-size, command-line option
1119: @cindex -l, command-line option
1120: @item --locals-stack-size @i{size}
1121: @itemx -l @i{size}
1122: Allocate @i{size} space for the locals stack instead of using the
1123: default specified in the image (typically 14.5K).
1124:
1125: @cindex -h, command-line option
1126: @cindex --help, command-line option
1127: @item --help
1128: @itemx -h
1129: Print a message about the command-line options
1130:
1131: @cindex -v, command-line option
1132: @cindex --version, command-line option
1133: @item --version
1134: @itemx -v
1135: Print version and exit
1136:
1137: @cindex --debug, command-line option
1138: @item --debug
1139: Print some information useful for debugging on startup.
1140:
1141: @cindex --offset-image, command-line option
1142: @item --offset-image
1143: Start the dictionary at a slightly different position than would be used
1144: otherwise (useful for creating data-relocatable images,
1145: @pxref{Data-Relocatable Image Files}).
1146:
1147: @cindex --no-offset-im, command-line option
1148: @item --no-offset-im
1149: Start the dictionary at the normal position.
1150:
1151: @cindex --clear-dictionary, command-line option
1152: @item --clear-dictionary
1153: Initialize all bytes in the dictionary to 0 before loading the image
1154: (@pxref{Data-Relocatable Image Files}).
1155:
1156: @cindex --die-on-signal, command-line-option
1157: @item --die-on-signal
1158: Normally Gforth handles most signals (e.g., the user interrupt SIGINT,
1159: or the segmentation violation SIGSEGV) by translating it into a Forth
1160: @code{THROW}. With this option, Gforth exits if it receives such a
1161: signal. This option is useful when the engine and/or the image might be
1162: severely broken (such that it causes another signal before recovering
1163: from the first); this option avoids endless loops in such cases.
1164: @end table
1165:
1166: @cindex loading files at startup
1167: @cindex executing code on startup
1168: @cindex batch processing with Gforth
1169: As explained above, the image-specific command-line arguments for the
1170: default image @file{gforth.fi} consist of a sequence of filenames and
1171: @code{-e @var{forth-code}} options that are interpreted in the sequence
1172: in which they are given. The @code{-e @var{forth-code}} or
1173: @code{--evaluate @var{forth-code}} option evaluates the Forth
1174: code. This option takes only one argument; if you want to evaluate more
1175: Forth words, you have to quote them or use @code{-e} several times. To exit
1176: after processing the command line (instead of entering interactive mode)
1177: append @code{-e bye} to the command line.
1178:
1179: @cindex versions, invoking other versions of Gforth
1180: If you have several versions of Gforth installed, @code{gforth} will
1181: invoke the version that was installed last. @code{gforth-@i{version}}
1182: invokes a specific version. If your environment contains the variable
1183: @code{GFORTHPATH}, you may want to override it by using the
1184: @code{--path} option.
1185:
1186: Not yet implemented:
1187: On startup the system first executes the system initialization file
1188: (unless the option @code{--no-init-file} is given; note that the system
1189: resulting from using this option may not be ANS Forth conformant). Then
1190: the user initialization file @file{.gforth.fs} is executed, unless the
1.62 crook 1191: option @code{--no-rc} is given; this file is searched for in @file{.},
1.48 anton 1192: then in @file{~}, then in the normal path (see above).
1193:
1194:
1195:
1196: @comment ----------------------------------------------
1197: @node Leaving Gforth, Command-line editing, Invoking Gforth, Gforth Environment
1198: @section Leaving Gforth
1199: @cindex Gforth - leaving
1200: @cindex leaving Gforth
1201:
1202: You can leave Gforth by typing @code{bye} or @kbd{Ctrl-d} (at the start
1203: of a line) or (if you invoked Gforth with the @code{--die-on-signal}
1204: option) @kbd{Ctrl-c}. When you leave Gforth, all of your definitions and
1.49 anton 1205: data are discarded. For ways of saving the state of the system before
1206: leaving Gforth see @ref{Image Files}.
1.48 anton 1207:
1208: doc-bye
1209:
1210:
1211: @comment ----------------------------------------------
1.65 anton 1212: @node Command-line editing, Environment variables, Leaving Gforth, Gforth Environment
1.48 anton 1213: @section Command-line editing
1214: @cindex command-line editing
1215:
1216: Gforth maintains a history file that records every line that you type to
1217: the text interpreter. This file is preserved between sessions, and is
1218: used to provide a command-line recall facility; if you type @kbd{Ctrl-P}
1219: repeatedly you can recall successively older commands from this (or
1220: previous) session(s). The full list of command-line editing facilities is:
1221:
1222: @itemize @bullet
1223: @item
1224: @kbd{Ctrl-p} (``previous'') (or up-arrow) to recall successively older
1225: commands from the history buffer.
1226: @item
1227: @kbd{Ctrl-n} (``next'') (or down-arrow) to recall successively newer commands
1228: from the history buffer.
1229: @item
1230: @kbd{Ctrl-f} (or right-arrow) to move the cursor right, non-destructively.
1231: @item
1232: @kbd{Ctrl-b} (or left-arrow) to move the cursor left, non-destructively.
1233: @item
1234: @kbd{Ctrl-h} (backspace) to delete the character to the left of the cursor,
1235: closing up the line.
1236: @item
1237: @kbd{Ctrl-k} to delete (``kill'') from the cursor to the end of the line.
1238: @item
1239: @kbd{Ctrl-a} to move the cursor to the start of the line.
1240: @item
1241: @kbd{Ctrl-e} to move the cursor to the end of the line.
1242: @item
1243: @key{RET} (@kbd{Ctrl-m}) or @key{LFD} (@kbd{Ctrl-j}) to submit the current
1244: line.
1245: @item
1246: @key{TAB} to step through all possible full-word completions of the word
1247: currently being typed.
1248: @item
1.65 anton 1249: @kbd{Ctrl-d} on an empty line line to terminate Gforth (gracefully,
1250: using @code{bye}).
1251: @item
1252: @kbd{Ctrl-x} (or @code{Ctrl-d} on a non-empty line) to delete the
1253: character under the cursor.
1.48 anton 1254: @end itemize
1255:
1256: When editing, displayable characters are inserted to the left of the
1257: cursor position; the line is always in ``insert'' (as opposed to
1258: ``overstrike'') mode.
1259:
1260: @cindex history file
1261: @cindex @file{.gforth-history}
1262: On Unix systems, the history file is @file{~/.gforth-history} by
1263: default@footnote{i.e. it is stored in the user's home directory.}. You
1264: can find out the name and location of your history file using:
1265:
1266: @example
1267: history-file type \ Unix-class systems
1268:
1269: history-file type \ Other systems
1270: history-dir type
1271: @end example
1272:
1273: If you enter long definitions by hand, you can use a text editor to
1274: paste them out of the history file into a Forth source file for reuse at
1275: a later time.
1276:
1277: Gforth never trims the size of the history file, so you should do this
1278: periodically, if necessary.
1279:
1280: @comment this is all defined in history.fs
1281: @comment NAC TODO the ctrl-D behaviour can either do a bye or a beep.. how is that option
1282: @comment chosen?
1283:
1284:
1285: @comment ----------------------------------------------
1.65 anton 1286: @node Environment variables, Gforth Files, Command-line editing, Gforth Environment
1.48 anton 1287: @section Environment variables
1288: @cindex environment variables
1289:
1290: Gforth uses these environment variables:
1291:
1292: @itemize @bullet
1293: @item
1294: @cindex @code{GFORTHHIST} -- environment variable
1295: @code{GFORTHHIST} -- (Unix systems only) specifies the directory in which to
1296: open/create the history file, @file{.gforth-history}. Default:
1297: @code{$HOME}.
1298:
1299: @item
1300: @cindex @code{GFORTHPATH} -- environment variable
1301: @code{GFORTHPATH} -- specifies the path used when searching for the gforth image file and
1302: for Forth source-code files.
1303:
1304: @item
1305: @cindex @code{GFORTH} -- environment variable
1.49 anton 1306: @code{GFORTH} -- used by @file{gforthmi}, @xref{gforthmi}.
1.48 anton 1307:
1308: @item
1309: @cindex @code{GFORTHD} -- environment variable
1.62 crook 1310: @code{GFORTHD} -- used by @file{gforthmi}, @xref{gforthmi}.
1.48 anton 1311:
1312: @item
1313: @cindex @code{TMP}, @code{TEMP} - environment variable
1314: @code{TMP}, @code{TEMP} - (non-Unix systems only) used as a potential
1315: location for the history file.
1316: @end itemize
1317:
1318: @comment also POSIXELY_CORRECT LINES COLUMNS HOME but no interest in
1319: @comment mentioning these.
1320:
1321: All the Gforth environment variables default to sensible values if they
1322: are not set.
1323:
1324:
1325: @comment ----------------------------------------------
1326: @node Gforth Files, Startup speed, Environment variables, Gforth Environment
1327: @section Gforth files
1328: @cindex Gforth files
1329:
1330: When you install Gforth on a Unix system, it installs files in these
1331: locations by default:
1332:
1333: @itemize @bullet
1334: @item
1335: @file{/usr/local/bin/gforth}
1336: @item
1337: @file{/usr/local/bin/gforthmi}
1338: @item
1339: @file{/usr/local/man/man1/gforth.1} - man page.
1340: @item
1341: @file{/usr/local/info} - the Info version of this manual.
1342: @item
1343: @file{/usr/local/lib/gforth/<version>/...} - Gforth @file{.fi} files.
1344: @item
1345: @file{/usr/local/share/gforth/<version>/TAGS} - Emacs TAGS file.
1346: @item
1347: @file{/usr/local/share/gforth/<version>/...} - Gforth source files.
1348: @item
1349: @file{.../emacs/site-lisp/gforth.el} - Emacs gforth mode.
1350: @end itemize
1351:
1352: You can select different places for installation by using
1353: @code{configure} options (listed with @code{configure --help}).
1354:
1355: @comment ----------------------------------------------
1356: @node Startup speed, , Gforth Files, Gforth Environment
1357: @section Startup speed
1358: @cindex Startup speed
1359: @cindex speed, startup
1360:
1361: If Gforth is used for CGI scripts or in shell scripts, its startup
1362: speed may become a problem. On a 300MHz 21064a under Linux-2.2.13 with
1363: glibc-2.0.7, @code{gforth -e bye} takes about 24.6ms user and 11.3ms
1364: system time.
1365:
1366: If startup speed is a problem, you may consider the following ways to
1367: improve it; or you may consider ways to reduce the number of startups
1.62 crook 1368: (for example, by using Fast-CGI).
1.48 anton 1369:
1370: The first step to improve startup speed is to statically link Gforth, by
1371: building it with @code{XLDFLAGS=-static}. This requires more memory for
1372: the code and will therefore slow down the first invocation, but
1373: subsequent invocations avoid the dynamic linking overhead. Another
1374: disadvantage is that Gforth won't profit from library upgrades. As a
1375: result, @code{gforth-static -e bye} takes about 17.1ms user and
1376: 8.2ms system time.
1377:
1378: The next step to improve startup speed is to use a non-relocatable image
1.65 anton 1379: (@pxref{Non-Relocatable Image Files}). You can create this image with
1.48 anton 1380: @code{gforth -e "savesystem gforthnr.fi bye"} and later use it with
1381: @code{gforth -i gforthnr.fi ...}. This avoids the relocation overhead
1382: and a part of the copy-on-write overhead. The disadvantage is that the
1.62 crook 1383: non-relocatable image does not work if the OS gives Gforth a different
1.48 anton 1384: address for the dictionary, for whatever reason; so you better provide a
1385: fallback on a relocatable image. @code{gforth-static -i gforthnr.fi -e
1386: bye} takes about 15.3ms user and 7.5ms system time.
1387:
1388: The final step is to disable dictionary hashing in Gforth. Gforth
1389: builds the hash table on startup, which takes much of the startup
1390: overhead. You can do this by commenting out the @code{include hash.fs}
1391: in @file{startup.fs} and everything that requires @file{hash.fs} (at the
1392: moment @file{table.fs} and @file{ekey.fs}) and then doing @code{make}.
1393: The disadvantages are that functionality like @code{table} and
1394: @code{ekey} is missing and that text interpretation (e.g., compiling)
1395: now takes much longer. So, you should only use this method if there is
1396: no significant text interpretation to perform (the script should be
1.62 crook 1397: compiled into the image, amongst other things). @code{gforth-static -i
1.48 anton 1398: gforthnrnh.fi -e bye} takes about 2.1ms user and 6.1ms system time.
1399:
1400: @c ******************************************************************
1401: @node Tutorial, Introduction, Gforth Environment, Top
1402: @chapter Forth Tutorial
1403: @cindex Tutorial
1404: @cindex Forth Tutorial
1405:
1.67 anton 1406: @c Topics from nac's Introduction that could be mentioned:
1407: @c press <ret> after each line
1408: @c Prompt
1409: @c numbers vs. words in dictionary on text interpretation
1410: @c what happens on redefinition
1411: @c parsing words (in particular, defining words)
1412:
1.83 anton 1413: The difference of this chapter from the Introduction
1414: (@pxref{Introduction}) is that this tutorial is more fast-paced, should
1415: be used while sitting in front of a computer, and covers much more
1416: material, but does not explain how the Forth system works.
1417:
1.62 crook 1418: This tutorial can be used with any ANS-compliant Forth; any
1419: Gforth-specific features are marked as such and you can skip them if you
1420: work with another Forth. This tutorial does not explain all features of
1421: Forth, just enough to get you started and give you some ideas about the
1422: facilities available in Forth. Read the rest of the manual and the
1423: standard when you are through this.
1.48 anton 1424:
1425: The intended way to use this tutorial is that you work through it while
1426: sitting in front of the console, take a look at the examples and predict
1427: what they will do, then try them out; if the outcome is not as expected,
1428: find out why (e.g., by trying out variations of the example), so you
1429: understand what's going on. There are also some assignments that you
1430: should solve.
1431:
1432: This tutorial assumes that you have programmed before and know what,
1433: e.g., a loop is.
1434:
1435: @c !! explain compat library
1436:
1437: @menu
1438: * Starting Gforth Tutorial::
1439: * Syntax Tutorial::
1440: * Crash Course Tutorial::
1441: * Stack Tutorial::
1442: * Arithmetics Tutorial::
1443: * Stack Manipulation Tutorial::
1444: * Using files for Forth code Tutorial::
1445: * Comments Tutorial::
1446: * Colon Definitions Tutorial::
1447: * Decompilation Tutorial::
1448: * Stack-Effect Comments Tutorial::
1449: * Types Tutorial::
1450: * Factoring Tutorial::
1451: * Designing the stack effect Tutorial::
1452: * Local Variables Tutorial::
1453: * Conditional execution Tutorial::
1454: * Flags and Comparisons Tutorial::
1455: * General Loops Tutorial::
1456: * Counted loops Tutorial::
1457: * Recursion Tutorial::
1458: * Leaving definitions or loops Tutorial::
1459: * Return Stack Tutorial::
1460: * Memory Tutorial::
1461: * Characters and Strings Tutorial::
1462: * Alignment Tutorial::
1463: * Interpretation and Compilation Semantics and Immediacy Tutorial::
1464: * Execution Tokens Tutorial::
1465: * Exceptions Tutorial::
1466: * Defining Words Tutorial::
1467: * Arrays and Records Tutorial::
1468: * POSTPONE Tutorial::
1469: * Literal Tutorial::
1470: * Advanced macros Tutorial::
1471: * Compilation Tokens Tutorial::
1472: * Wordlists and Search Order Tutorial::
1473: @end menu
1474:
1475: @node Starting Gforth Tutorial, Syntax Tutorial, Tutorial, Tutorial
1476: @section Starting Gforth
1.66 anton 1477: @cindex starting Gforth tutorial
1.48 anton 1478: You can start Gforth by typing its name:
1479:
1480: @example
1481: gforth
1482: @end example
1483:
1484: That puts you into interactive mode; you can leave Gforth by typing
1485: @code{bye}. While in Gforth, you can edit the command line and access
1486: the command line history with cursor keys, similar to bash.
1487:
1488:
1489: @node Syntax Tutorial, Crash Course Tutorial, Starting Gforth Tutorial, Tutorial
1490: @section Syntax
1.66 anton 1491: @cindex syntax tutorial
1.48 anton 1492:
1493: A @dfn{word} is a sequence of arbitrary characters (expcept white
1494: space). Words are separated by white space. E.g., each of the
1495: following lines contains exactly one word:
1496:
1497: @example
1498: word
1499: !@@#$%^&*()
1500: 1234567890
1501: 5!a
1502: @end example
1503:
1504: A frequent beginner's error is to leave away necessary white space,
1505: resulting in an error like @samp{Undefined word}; so if you see such an
1506: error, check if you have put spaces wherever necessary.
1507:
1508: @example
1509: ." hello, world" \ correct
1510: ."hello, world" \ gives an "Undefined word" error
1511: @end example
1512:
1.65 anton 1513: Gforth and most other Forth systems ignore differences in case (they are
1.48 anton 1514: case-insensitive), i.e., @samp{word} is the same as @samp{Word}. If
1515: your system is case-sensitive, you may have to type all the examples
1516: given here in upper case.
1517:
1518:
1519: @node Crash Course Tutorial, Stack Tutorial, Syntax Tutorial, Tutorial
1520: @section Crash Course
1521:
1522: Type
1523:
1524: @example
1525: 0 0 !
1526: here execute
1527: ' catch >body 20 erase abort
1528: ' (quit) >body 20 erase
1529: @end example
1530:
1531: The last two examples are guaranteed to destroy parts of Gforth (and
1532: most other systems), so you better leave Gforth afterwards (if it has
1533: not finished by itself). On some systems you may have to kill gforth
1534: from outside (e.g., in Unix with @code{kill}).
1535:
1536: Now that you know how to produce crashes (and that there's not much to
1537: them), let's learn how to produce meaningful programs.
1538:
1539:
1540: @node Stack Tutorial, Arithmetics Tutorial, Crash Course Tutorial, Tutorial
1541: @section Stack
1.66 anton 1542: @cindex stack tutorial
1.48 anton 1543:
1544: The most obvious feature of Forth is the stack. When you type in a
1545: number, it is pushed on the stack. You can display the content of the
1546: stack with @code{.s}.
1547:
1548: @example
1549: 1 2 .s
1550: 3 .s
1551: @end example
1552:
1553: @code{.s} displays the top-of-stack to the right, i.e., the numbers
1554: appear in @code{.s} output as they appeared in the input.
1555:
1556: You can print the top of stack element with @code{.}.
1557:
1558: @example
1559: 1 2 3 . . .
1560: @end example
1561:
1562: In general, words consume their stack arguments (@code{.s} is an
1563: exception).
1564:
1565: @assignment
1566: What does the stack contain after @code{5 6 7 .}?
1567: @endassignment
1568:
1569:
1570: @node Arithmetics Tutorial, Stack Manipulation Tutorial, Stack Tutorial, Tutorial
1571: @section Arithmetics
1.66 anton 1572: @cindex arithmetics tutorial
1.48 anton 1573:
1574: The words @code{+}, @code{-}, @code{*}, @code{/}, and @code{mod} always
1575: operate on the top two stack items:
1576:
1577: @example
1.67 anton 1578: 2 2 .s
1579: + .s
1580: .
1.48 anton 1581: 2 1 - .
1582: 7 3 mod .
1583: @end example
1584:
1585: The operands of @code{-}, @code{/}, and @code{mod} are in the same order
1586: as in the corresponding infix expression (this is generally the case in
1587: Forth).
1588:
1589: Parentheses are superfluous (and not available), because the order of
1590: the words unambiguously determines the order of evaluation and the
1591: operands:
1592:
1593: @example
1594: 3 4 + 5 * .
1595: 3 4 5 * + .
1596: @end example
1597:
1598: @assignment
1599: What are the infix expressions corresponding to the Forth code above?
1600: Write @code{6-7*8+9} in Forth notation@footnote{This notation is also
1601: known as Postfix or RPN (Reverse Polish Notation).}.
1602: @endassignment
1603:
1604: To change the sign, use @code{negate}:
1605:
1606: @example
1607: 2 negate .
1608: @end example
1609:
1610: @assignment
1611: Convert -(-3)*4-5 to Forth.
1612: @endassignment
1613:
1614: @code{/mod} performs both @code{/} and @code{mod}.
1615:
1616: @example
1617: 7 3 /mod . .
1618: @end example
1619:
1.66 anton 1620: Reference: @ref{Arithmetic}.
1621:
1622:
1.48 anton 1623: @node Stack Manipulation Tutorial, Using files for Forth code Tutorial, Arithmetics Tutorial, Tutorial
1624: @section Stack Manipulation
1.66 anton 1625: @cindex stack manipulation tutorial
1.48 anton 1626:
1627: Stack manipulation words rearrange the data on the stack.
1628:
1629: @example
1630: 1 .s drop .s
1631: 1 .s dup .s drop drop .s
1632: 1 2 .s over .s drop drop drop
1633: 1 2 .s swap .s drop drop
1634: 1 2 3 .s rot .s drop drop drop
1635: @end example
1636:
1637: These are the most important stack manipulation words. There are also
1638: variants that manipulate twice as many stack items:
1639:
1640: @example
1641: 1 2 3 4 .s 2swap .s 2drop 2drop
1642: @end example
1643:
1644: Two more stack manipulation words are:
1645:
1646: @example
1647: 1 2 .s nip .s drop
1648: 1 2 .s tuck .s 2drop drop
1649: @end example
1650:
1651: @assignment
1652: Replace @code{nip} and @code{tuck} with combinations of other stack
1653: manipulation words.
1654:
1655: @example
1656: Given: How do you get:
1657: 1 2 3 3 2 1
1658: 1 2 3 1 2 3 2
1659: 1 2 3 1 2 3 3
1660: 1 2 3 1 3 3
1661: 1 2 3 2 1 3
1662: 1 2 3 4 4 3 2 1
1663: 1 2 3 1 2 3 1 2 3
1664: 1 2 3 4 1 2 3 4 1 2
1665: 1 2 3
1666: 1 2 3 1 2 3 4
1667: 1 2 3 1 3
1668: @end example
1669: @endassignment
1670:
1671: @example
1672: 5 dup * .
1673: @end example
1674:
1675: @assignment
1676: Write 17^3 and 17^4 in Forth, without writing @code{17} more than once.
1677: Write a piece of Forth code that expects two numbers on the stack
1678: (@var{a} and @var{b}, with @var{b} on top) and computes
1679: @code{(a-b)(a+1)}.
1680: @endassignment
1681:
1.66 anton 1682: Reference: @ref{Stack Manipulation}.
1683:
1684:
1.48 anton 1685: @node Using files for Forth code Tutorial, Comments Tutorial, Stack Manipulation Tutorial, Tutorial
1686: @section Using files for Forth code
1.66 anton 1687: @cindex loading Forth code, tutorial
1688: @cindex files containing Forth code, tutorial
1.48 anton 1689:
1690: While working at the Forth command line is convenient for one-line
1691: examples and short one-off code, you probably want to store your source
1692: code in files for convenient editing and persistence. You can use your
1693: favourite editor (Gforth includes Emacs support, @pxref{Emacs and
1694: Gforth}) to create @var{file} and use
1695:
1696: @example
1697: s" @var{file}" included
1698: @end example
1699:
1700: to load it into your Forth system. The file name extension I use for
1701: Forth files is @samp{.fs}.
1702:
1703: You can easily start Gforth with some files loaded like this:
1704:
1705: @example
1706: gforth @var{file1} @var{file2}
1707: @end example
1708:
1709: If an error occurs during loading these files, Gforth terminates,
1710: whereas an error during @code{INCLUDED} within Gforth usually gives you
1711: a Gforth command line. Starting the Forth system every time gives you a
1712: clean start every time, without interference from the results of earlier
1713: tries.
1714:
1715: I often put all the tests in a file, then load the code and run the
1716: tests with
1717:
1718: @example
1719: gforth @var{code} @var{tests} -e bye
1720: @end example
1721:
1722: (often by performing this command with @kbd{C-x C-e} in Emacs). The
1723: @code{-e bye} ensures that Gforth terminates afterwards so that I can
1724: restart this command without ado.
1725:
1726: The advantage of this approach is that the tests can be repeated easily
1727: every time the program ist changed, making it easy to catch bugs
1728: introduced by the change.
1729:
1.66 anton 1730: Reference: @ref{Forth source files}.
1731:
1.48 anton 1732:
1733: @node Comments Tutorial, Colon Definitions Tutorial, Using files for Forth code Tutorial, Tutorial
1734: @section Comments
1.66 anton 1735: @cindex comments tutorial
1.48 anton 1736:
1737: @example
1738: \ That's a comment; it ends at the end of the line
1739: ( Another comment; it ends here: ) .s
1740: @end example
1741:
1742: @code{\} and @code{(} are ordinary Forth words and therefore have to be
1743: separated with white space from the following text.
1744:
1745: @example
1746: \This gives an "Undefined word" error
1747: @end example
1748:
1749: The first @code{)} ends a comment started with @code{(}, so you cannot
1750: nest @code{(}-comments; and you cannot comment out text containing a
1751: @code{)} with @code{( ... )}@footnote{therefore it's a good idea to
1752: avoid @code{)} in word names.}.
1753:
1754: I use @code{\}-comments for descriptive text and for commenting out code
1755: of one or more line; I use @code{(}-comments for describing the stack
1756: effect, the stack contents, or for commenting out sub-line pieces of
1757: code.
1758:
1759: The Emacs mode @file{gforth.el} (@pxref{Emacs and Gforth}) supports
1760: these uses by commenting out a region with @kbd{C-x \}, uncommenting a
1761: region with @kbd{C-u C-x \}, and filling a @code{\}-commented region
1762: with @kbd{M-q}.
1763:
1.66 anton 1764: Reference: @ref{Comments}.
1765:
1.48 anton 1766:
1767: @node Colon Definitions Tutorial, Decompilation Tutorial, Comments Tutorial, Tutorial
1768: @section Colon Definitions
1.66 anton 1769: @cindex colon definitions, tutorial
1770: @cindex definitions, tutorial
1771: @cindex procedures, tutorial
1772: @cindex functions, tutorial
1.48 anton 1773:
1774: are similar to procedures and functions in other programming languages.
1775:
1776: @example
1777: : squared ( n -- n^2 )
1778: dup * ;
1779: 5 squared .
1780: 7 squared .
1781: @end example
1782:
1783: @code{:} starts the colon definition; its name is @code{squared}. The
1784: following comment describes its stack effect. The words @code{dup *}
1785: are not executed, but compiled into the definition. @code{;} ends the
1786: colon definition.
1787:
1788: The newly-defined word can be used like any other word, including using
1789: it in other definitions:
1790:
1791: @example
1792: : cubed ( n -- n^3 )
1793: dup squared * ;
1794: -5 cubed .
1795: : fourth-power ( n -- n^4 )
1796: squared squared ;
1797: 3 fourth-power .
1798: @end example
1799:
1800: @assignment
1801: Write colon definitions for @code{nip}, @code{tuck}, @code{negate}, and
1802: @code{/mod} in terms of other Forth words, and check if they work (hint:
1803: test your tests on the originals first). Don't let the
1804: @samp{redefined}-Messages spook you, they are just warnings.
1805: @endassignment
1806:
1.66 anton 1807: Reference: @ref{Colon Definitions}.
1808:
1.48 anton 1809:
1810: @node Decompilation Tutorial, Stack-Effect Comments Tutorial, Colon Definitions Tutorial, Tutorial
1811: @section Decompilation
1.66 anton 1812: @cindex decompilation tutorial
1813: @cindex see tutorial
1.48 anton 1814:
1815: You can decompile colon definitions with @code{see}:
1816:
1817: @example
1818: see squared
1819: see cubed
1820: @end example
1821:
1822: In Gforth @code{see} shows you a reconstruction of the source code from
1823: the executable code. Informations that were present in the source, but
1824: not in the executable code, are lost (e.g., comments).
1825:
1.65 anton 1826: You can also decompile the predefined words:
1827:
1828: @example
1829: see .
1830: see +
1831: @end example
1832:
1833:
1.48 anton 1834: @node Stack-Effect Comments Tutorial, Types Tutorial, Decompilation Tutorial, Tutorial
1835: @section Stack-Effect Comments
1.66 anton 1836: @cindex stack-effect comments, tutorial
1837: @cindex --, tutorial
1.48 anton 1838: By convention the comment after the name of a definition describes the
1839: stack effect: The part in from of the @samp{--} describes the state of
1840: the stack before the execution of the definition, i.e., the parameters
1841: that are passed into the colon definition; the part behind the @samp{--}
1842: is the state of the stack after the execution of the definition, i.e.,
1843: the results of the definition. The stack comment only shows the top
1844: stack items that the definition accesses and/or changes.
1845:
1846: You should put a correct stack effect on every definition, even if it is
1847: just @code{( -- )}. You should also add some descriptive comment to
1848: more complicated words (I usually do this in the lines following
1849: @code{:}). If you don't do this, your code becomes unreadable (because
1850: you have to work through every definition before you can undertsand
1851: any).
1852:
1853: @assignment
1854: The stack effect of @code{swap} can be written like this: @code{x1 x2 --
1855: x2 x1}. Describe the stack effect of @code{-}, @code{drop}, @code{dup},
1856: @code{over}, @code{rot}, @code{nip}, and @code{tuck}. Hint: When you
1.65 anton 1857: are done, you can compare your stack effects to those in this manual
1.48 anton 1858: (@pxref{Word Index}).
1859: @endassignment
1860:
1861: Sometimes programmers put comments at various places in colon
1862: definitions that describe the contents of the stack at that place (stack
1863: comments); i.e., they are like the first part of a stack-effect
1864: comment. E.g.,
1865:
1866: @example
1867: : cubed ( n -- n^3 )
1868: dup squared ( n n^2 ) * ;
1869: @end example
1870:
1871: In this case the stack comment is pretty superfluous, because the word
1872: is simple enough. If you think it would be a good idea to add such a
1873: comment to increase readability, you should also consider factoring the
1874: word into several simpler words (@pxref{Factoring Tutorial,,
1.60 anton 1875: Factoring}), which typically eliminates the need for the stack comment;
1.48 anton 1876: however, if you decide not to refactor it, then having such a comment is
1877: better than not having it.
1878:
1879: The names of the stack items in stack-effect and stack comments in the
1880: standard, in this manual, and in many programs specify the type through
1881: a type prefix, similar to Fortran and Hungarian notation. The most
1882: frequent prefixes are:
1883:
1884: @table @code
1885: @item n
1886: signed integer
1887: @item u
1888: unsigned integer
1889: @item c
1890: character
1891: @item f
1892: Boolean flags, i.e. @code{false} or @code{true}.
1893: @item a-addr,a-
1894: Cell-aligned address
1895: @item c-addr,c-
1896: Char-aligned address (note that a Char may have two bytes in Windows NT)
1897: @item xt
1898: Execution token, same size as Cell
1899: @item w,x
1900: Cell, can contain an integer or an address. It usually takes 32, 64 or
1901: 16 bits (depending on your platform and Forth system). A cell is more
1902: commonly known as machine word, but the term @emph{word} already means
1903: something different in Forth.
1904: @item d
1905: signed double-cell integer
1906: @item ud
1907: unsigned double-cell integer
1908: @item r
1909: Float (on the FP stack)
1910: @end table
1911:
1912: You can find a more complete list in @ref{Notation}.
1913:
1914: @assignment
1915: Write stack-effect comments for all definitions you have written up to
1916: now.
1917: @endassignment
1918:
1919:
1920: @node Types Tutorial, Factoring Tutorial, Stack-Effect Comments Tutorial, Tutorial
1921: @section Types
1.66 anton 1922: @cindex types tutorial
1.48 anton 1923:
1924: In Forth the names of the operations are not overloaded; so similar
1925: operations on different types need different names; e.g., @code{+} adds
1926: integers, and you have to use @code{f+} to add floating-point numbers.
1927: The following prefixes are often used for related operations on
1928: different types:
1929:
1930: @table @code
1931: @item (none)
1932: signed integer
1933: @item u
1934: unsigned integer
1935: @item c
1936: character
1937: @item d
1938: signed double-cell integer
1939: @item ud, du
1940: unsigned double-cell integer
1941: @item 2
1942: two cells (not-necessarily double-cell numbers)
1943: @item m, um
1944: mixed single-cell and double-cell operations
1945: @item f
1946: floating-point (note that in stack comments @samp{f} represents flags,
1.66 anton 1947: and @samp{r} represents FP numbers).
1.48 anton 1948: @end table
1949:
1950: If there are no differences between the signed and the unsigned variant
1951: (e.g., for @code{+}), there is only the prefix-less variant.
1952:
1953: Forth does not perform type checking, neither at compile time, nor at
1954: run time. If you use the wrong oeration, the data are interpreted
1955: incorrectly:
1956:
1957: @example
1958: -1 u.
1959: @end example
1960:
1961: If you have only experience with type-checked languages until now, and
1962: have heard how important type-checking is, don't panic! In my
1963: experience (and that of other Forthers), type errors in Forth code are
1964: usually easy to find (once you get used to it), the increased vigilance
1965: of the programmer tends to catch some harder errors in addition to most
1966: type errors, and you never have to work around the type system, so in
1967: most situations the lack of type-checking seems to be a win (projects to
1968: add type checking to Forth have not caught on).
1969:
1970:
1971: @node Factoring Tutorial, Designing the stack effect Tutorial, Types Tutorial, Tutorial
1972: @section Factoring
1.66 anton 1973: @cindex factoring tutorial
1.48 anton 1974:
1975: If you try to write longer definitions, you will soon find it hard to
1976: keep track of the stack contents. Therefore, good Forth programmers
1977: tend to write only short definitions (e.g., three lines). The art of
1978: finding meaningful short definitions is known as factoring (as in
1979: factoring polynomials).
1980:
1981: Well-factored programs offer additional advantages: smaller, more
1982: general words, are easier to test and debug and can be reused more and
1983: better than larger, specialized words.
1984:
1985: So, if you run into difficulties with stack management, when writing
1986: code, try to define meaningful factors for the word, and define the word
1987: in terms of those. Even if a factor contains only two words, it is
1988: often helpful.
1989:
1.65 anton 1990: Good factoring is not easy, and it takes some practice to get the knack
1991: for it; but even experienced Forth programmers often don't find the
1992: right solution right away, but only when rewriting the program. So, if
1993: you don't come up with a good solution immediately, keep trying, don't
1994: despair.
1.48 anton 1995:
1996: @c example !!
1997:
1998:
1999: @node Designing the stack effect Tutorial, Local Variables Tutorial, Factoring Tutorial, Tutorial
2000: @section Designing the stack effect
1.66 anton 2001: @cindex Stack effect design, tutorial
2002: @cindex design of stack effects, tutorial
1.48 anton 2003:
2004: In other languages you can use an arbitrary order of parameters for a
1.65 anton 2005: function; and since there is only one result, you don't have to deal with
1.48 anton 2006: the order of results, either.
2007:
2008: In Forth (and other stack-based languages, e.g., Postscript) the
2009: parameter and result order of a definition is important and should be
2010: designed well. The general guideline is to design the stack effect such
2011: that the word is simple to use in most cases, even if that complicates
2012: the implementation of the word. Some concrete rules are:
2013:
2014: @itemize @bullet
2015:
2016: @item
2017: Words consume all of their parameters (e.g., @code{.}).
2018:
2019: @item
2020: If there is a convention on the order of parameters (e.g., from
2021: mathematics or another programming language), stick with it (e.g.,
2022: @code{-}).
2023:
2024: @item
2025: If one parameter usually requires only a short computation (e.g., it is
2026: a constant), pass it on the top of the stack. Conversely, parameters
2027: that usually require a long sequence of code to compute should be passed
2028: as the bottom (i.e., first) parameter. This makes the code easier to
2029: read, because reader does not need to keep track of the bottom item
2030: through a long sequence of code (or, alternatively, through stack
1.49 anton 2031: manipulations). E.g., @code{!} (store, @pxref{Memory}) expects the
1.48 anton 2032: address on top of the stack because it is usually simpler to compute
2033: than the stored value (often the address is just a variable).
2034:
2035: @item
2036: Similarly, results that are usually consumed quickly should be returned
2037: on the top of stack, whereas a result that is often used in long
2038: computations should be passed as bottom result. E.g., the file words
2039: like @code{open-file} return the error code on the top of stack, because
2040: it is usually consumed quickly by @code{throw}; moreover, the error code
2041: has to be checked before doing anything with the other results.
2042:
2043: @end itemize
2044:
2045: These rules are just general guidelines, don't lose sight of the overall
2046: goal to make the words easy to use. E.g., if the convention rule
2047: conflicts with the computation-length rule, you might decide in favour
2048: of the convention if the word will be used rarely, and in favour of the
2049: computation-length rule if the word will be used frequently (because
2050: with frequent use the cost of breaking the computation-length rule would
2051: be quite high, and frequent use makes it easier to remember an
2052: unconventional order).
2053:
2054: @c example !! structure package
2055:
1.65 anton 2056:
1.48 anton 2057: @node Local Variables Tutorial, Conditional execution Tutorial, Designing the stack effect Tutorial, Tutorial
2058: @section Local Variables
1.66 anton 2059: @cindex local variables, tutorial
1.48 anton 2060:
2061: You can define local variables (@emph{locals}) in a colon definition:
2062:
2063: @example
2064: : swap @{ a b -- b a @}
2065: b a ;
2066: 1 2 swap .s 2drop
2067: @end example
2068:
2069: (If your Forth system does not support this syntax, include
2070: @file{compat/anslocals.fs} first).
2071:
2072: In this example @code{@{ a b -- b a @}} is the locals definition; it
2073: takes two cells from the stack, puts the top of stack in @code{b} and
2074: the next stack element in @code{a}. @code{--} starts a comment ending
2075: with @code{@}}. After the locals definition, using the name of the
2076: local will push its value on the stack. You can leave the comment
2077: part (@code{-- b a}) away:
2078:
2079: @example
2080: : swap ( x1 x2 -- x2 x1 )
2081: @{ a b @} b a ;
2082: @end example
2083:
2084: In Gforth you can have several locals definitions, anywhere in a colon
2085: definition; in contrast, in a standard program you can have only one
2086: locals definition per colon definition, and that locals definition must
2087: be outside any controll structure.
2088:
2089: With locals you can write slightly longer definitions without running
2090: into stack trouble. However, I recommend trying to write colon
2091: definitions without locals for exercise purposes to help you gain the
2092: essential factoring skills.
2093:
2094: @assignment
2095: Rewrite your definitions until now with locals
2096: @endassignment
2097:
1.66 anton 2098: Reference: @ref{Locals}.
2099:
1.48 anton 2100:
2101: @node Conditional execution Tutorial, Flags and Comparisons Tutorial, Local Variables Tutorial, Tutorial
2102: @section Conditional execution
1.66 anton 2103: @cindex conditionals, tutorial
2104: @cindex if, tutorial
1.48 anton 2105:
2106: In Forth you can use control structures only inside colon definitions.
2107: An @code{if}-structure looks like this:
2108:
2109: @example
2110: : abs ( n1 -- +n2 )
2111: dup 0 < if
2112: negate
2113: endif ;
2114: 5 abs .
2115: -5 abs .
2116: @end example
2117:
2118: @code{if} takes a flag from the stack. If the flag is non-zero (true),
2119: the following code is performed, otherwise execution continues after the
1.51 pazsan 2120: @code{endif} (or @code{else}). @code{<} compares the top two stack
1.48 anton 2121: elements and prioduces a flag:
2122:
2123: @example
2124: 1 2 < .
2125: 2 1 < .
2126: 1 1 < .
2127: @end example
2128:
2129: Actually the standard name for @code{endif} is @code{then}. This
2130: tutorial presents the examples using @code{endif}, because this is often
2131: less confusing for people familiar with other programming languages
2132: where @code{then} has a different meaning. If your system does not have
2133: @code{endif}, define it with
2134:
2135: @example
2136: : endif postpone then ; immediate
2137: @end example
2138:
2139: You can optionally use an @code{else}-part:
2140:
2141: @example
2142: : min ( n1 n2 -- n )
2143: 2dup < if
2144: drop
2145: else
2146: nip
2147: endif ;
2148: 2 3 min .
2149: 3 2 min .
2150: @end example
2151:
2152: @assignment
2153: Write @code{min} without @code{else}-part (hint: what's the definition
2154: of @code{nip}?).
2155: @endassignment
2156:
1.66 anton 2157: Reference: @ref{Selection}.
2158:
1.48 anton 2159:
2160: @node Flags and Comparisons Tutorial, General Loops Tutorial, Conditional execution Tutorial, Tutorial
2161: @section Flags and Comparisons
1.66 anton 2162: @cindex flags tutorial
2163: @cindex comparison tutorial
1.48 anton 2164:
2165: In a false-flag all bits are clear (0 when interpreted as integer). In
2166: a canonical true-flag all bits are set (-1 as a twos-complement signed
2167: integer); in many contexts (e.g., @code{if}) any non-zero value is
2168: treated as true flag.
2169:
2170: @example
2171: false .
2172: true .
2173: true hex u. decimal
2174: @end example
2175:
2176: Comparison words produce canonical flags:
2177:
2178: @example
2179: 1 1 = .
2180: 1 0= .
2181: 0 1 < .
2182: 0 0 < .
2183: -1 1 u< . \ type error, u< interprets -1 as large unsigned number
2184: -1 1 < .
2185: @end example
2186:
1.66 anton 2187: Gforth supports all combinations of the prefixes @code{0 u d d0 du f f0}
2188: (or none) and the comparisons @code{= <> < > <= >=}. Only a part of
2189: these combinations are standard (for details see the standard,
2190: @ref{Numeric comparison}, @ref{Floating Point} or @ref{Word Index}).
1.48 anton 2191:
2192: You can use @code{and or xor invert} can be used as operations on
2193: canonical flags. Actually they are bitwise operations:
2194:
2195: @example
2196: 1 2 and .
2197: 1 2 or .
2198: 1 3 xor .
2199: 1 invert .
2200: @end example
2201:
2202: You can convert a zero/non-zero flag into a canonical flag with
2203: @code{0<>} (and complement it on the way with @code{0=}).
2204:
2205: @example
2206: 1 0= .
2207: 1 0<> .
2208: @end example
2209:
1.65 anton 2210: You can use the all-bits-set feature of canonical flags and the bitwise
1.48 anton 2211: operation of the Boolean operations to avoid @code{if}s:
2212:
2213: @example
2214: : foo ( n1 -- n2 )
2215: 0= if
2216: 14
2217: else
2218: 0
2219: endif ;
2220: 0 foo .
2221: 1 foo .
2222:
2223: : foo ( n1 -- n2 )
2224: 0= 14 and ;
2225: 0 foo .
2226: 1 foo .
2227: @end example
2228:
2229: @assignment
2230: Write @code{min} without @code{if}.
2231: @endassignment
2232:
1.66 anton 2233: For reference, see @ref{Boolean Flags}, @ref{Numeric comparison}, and
2234: @ref{Bitwise operations}.
2235:
1.48 anton 2236:
2237: @node General Loops Tutorial, Counted loops Tutorial, Flags and Comparisons Tutorial, Tutorial
2238: @section General Loops
1.66 anton 2239: @cindex loops, indefinite, tutorial
1.48 anton 2240:
2241: The endless loop is the most simple one:
2242:
2243: @example
2244: : endless ( -- )
2245: 0 begin
2246: dup . 1+
2247: again ;
2248: endless
2249: @end example
2250:
2251: Terminate this loop by pressing @kbd{Ctrl-C} (in Gforth). @code{begin}
2252: does nothing at run-time, @code{again} jumps back to @code{begin}.
2253:
2254: A loop with one exit at any place looks like this:
2255:
2256: @example
2257: : log2 ( +n1 -- n2 )
2258: \ logarithmus dualis of n1>0, rounded down to the next integer
2259: assert( dup 0> )
2260: 2/ 0 begin
2261: over 0> while
2262: 1+ swap 2/ swap
2263: repeat
2264: nip ;
2265: 7 log2 .
2266: 8 log2 .
2267: @end example
2268:
2269: At run-time @code{while} consumes a flag; if it is 0, execution
1.51 pazsan 2270: continues behind the @code{repeat}; if the flag is non-zero, execution
1.48 anton 2271: continues behind the @code{while}. @code{Repeat} jumps back to
2272: @code{begin}, just like @code{again}.
2273:
2274: In Forth there are many combinations/abbreviations, like @code{1+}.
2275: However, @code{2/} is not one of them; it shifts it's argument right by
2276: one bit (arithmetic shift right):
2277:
2278: @example
2279: -5 2 / .
2280: -5 2/ .
2281: @end example
2282:
2283: @code{assert(} is no standard word, but you can get it on systems other
2284: then Gforth by including @file{compat/assert.fs}. You can see what it
2285: does by trying
2286:
2287: @example
2288: 0 log2 .
2289: @end example
2290:
2291: Here's a loop with an exit at the end:
2292:
2293: @example
2294: : log2 ( +n1 -- n2 )
2295: \ logarithmus dualis of n1>0, rounded down to the next integer
2296: assert( dup 0 > )
2297: -1 begin
2298: 1+ swap 2/ swap
2299: over 0 <=
2300: until
2301: nip ;
2302: @end example
2303:
2304: @code{Until} consumes a flag; if it is non-zero, execution continues at
2305: the @code{begin}, otherwise after the @code{until}.
2306:
2307: @assignment
2308: Write a definition for computing the greatest common divisor.
2309: @endassignment
2310:
1.66 anton 2311: Reference: @ref{Simple Loops}.
2312:
1.48 anton 2313:
2314: @node Counted loops Tutorial, Recursion Tutorial, General Loops Tutorial, Tutorial
2315: @section Counted loops
1.66 anton 2316: @cindex loops, counted, tutorial
1.48 anton 2317:
2318: @example
2319: : ^ ( n1 u -- n )
2320: \ n = the uth power of u1
2321: 1 swap 0 u+do
2322: over *
2323: loop
2324: nip ;
2325: 3 2 ^ .
2326: 4 3 ^ .
2327: @end example
2328:
2329: @code{U+do} (from @file{compat/loops.fs}, if your Forth system doesn't
2330: have it) takes two numbers of the stack @code{( u3 u4 -- )}, and then
2331: performs the code between @code{u+do} and @code{loop} for @code{u3-u4}
2332: times (or not at all, if @code{u3-u4<0}).
2333:
2334: You can see the stack effect design rules at work in the stack effect of
2335: the loop start words: Since the start value of the loop is more
2336: frequently constant than the end value, the start value is passed on
2337: the top-of-stack.
2338:
2339: You can access the counter of a counted loop with @code{i}:
2340:
2341: @example
2342: : fac ( u -- u! )
2343: 1 swap 1+ 1 u+do
2344: i *
2345: loop ;
2346: 5 fac .
2347: 7 fac .
2348: @end example
2349:
2350: There is also @code{+do}, which expects signed numbers (important for
2351: deciding whether to enter the loop).
2352:
2353: @assignment
2354: Write a definition for computing the nth Fibonacci number.
2355: @endassignment
2356:
1.65 anton 2357: You can also use increments other than 1:
2358:
2359: @example
2360: : up2 ( n1 n2 -- )
2361: +do
2362: i .
2363: 2 +loop ;
2364: 10 0 up2
2365:
2366: : down2 ( n1 n2 -- )
2367: -do
2368: i .
2369: 2 -loop ;
2370: 0 10 down2
2371: @end example
1.48 anton 2372:
1.66 anton 2373: Reference: @ref{Counted Loops}.
2374:
1.48 anton 2375:
2376: @node Recursion Tutorial, Leaving definitions or loops Tutorial, Counted loops Tutorial, Tutorial
2377: @section Recursion
1.66 anton 2378: @cindex recursion tutorial
1.48 anton 2379:
2380: Usually the name of a definition is not visible in the definition; but
2381: earlier definitions are usually visible:
2382:
2383: @example
2384: 1 0 / . \ "Floating-point unidentified fault" in Gforth on most platforms
2385: : / ( n1 n2 -- n )
2386: dup 0= if
2387: -10 throw \ report division by zero
2388: endif
2389: / \ old version
2390: ;
2391: 1 0 /
2392: @end example
2393:
2394: For recursive definitions you can use @code{recursive} (non-standard) or
2395: @code{recurse}:
2396:
2397: @example
2398: : fac1 ( n -- n! ) recursive
2399: dup 0> if
2400: dup 1- fac1 *
2401: else
2402: drop 1
2403: endif ;
2404: 7 fac1 .
2405:
2406: : fac2 ( n -- n! )
2407: dup 0> if
2408: dup 1- recurse *
2409: else
2410: drop 1
2411: endif ;
2412: 8 fac2 .
2413: @end example
2414:
2415: @assignment
2416: Write a recursive definition for computing the nth Fibonacci number.
2417: @endassignment
2418:
1.66 anton 2419: Reference (including indirect recursion): @xref{Calls and returns}.
2420:
1.48 anton 2421:
2422: @node Leaving definitions or loops Tutorial, Return Stack Tutorial, Recursion Tutorial, Tutorial
2423: @section Leaving definitions or loops
1.66 anton 2424: @cindex leaving definitions, tutorial
2425: @cindex leaving loops, tutorial
1.48 anton 2426:
2427: @code{EXIT} exits the current definition right away. For every counted
2428: loop that is left in this way, an @code{UNLOOP} has to be performed
2429: before the @code{EXIT}:
2430:
2431: @c !! real examples
2432: @example
2433: : ...
2434: ... u+do
2435: ... if
2436: ... unloop exit
2437: endif
2438: ...
2439: loop
2440: ... ;
2441: @end example
2442:
2443: @code{LEAVE} leaves the innermost counted loop right away:
2444:
2445: @example
2446: : ...
2447: ... u+do
2448: ... if
2449: ... leave
2450: endif
2451: ...
2452: loop
2453: ... ;
2454: @end example
2455:
1.65 anton 2456: @c !! example
1.48 anton 2457:
1.66 anton 2458: Reference: @ref{Calls and returns}, @ref{Counted Loops}.
2459:
2460:
1.48 anton 2461: @node Return Stack Tutorial, Memory Tutorial, Leaving definitions or loops Tutorial, Tutorial
2462: @section Return Stack
1.66 anton 2463: @cindex return stack tutorial
1.48 anton 2464:
2465: In addition to the data stack Forth also has a second stack, the return
2466: stack; most Forth systems store the return addresses of procedure calls
2467: there (thus its name). Programmers can also use this stack:
2468:
2469: @example
2470: : foo ( n1 n2 -- )
2471: .s
2472: >r .s
1.50 anton 2473: r@@ .
1.48 anton 2474: >r .s
1.50 anton 2475: r@@ .
1.48 anton 2476: r> .
1.50 anton 2477: r@@ .
1.48 anton 2478: r> . ;
2479: 1 2 foo
2480: @end example
2481:
2482: @code{>r} takes an element from the data stack and pushes it onto the
2483: return stack; conversely, @code{r>} moves an elementm from the return to
2484: the data stack; @code{r@@} pushes a copy of the top of the return stack
2485: on the return stack.
2486:
2487: Forth programmers usually use the return stack for storing data
2488: temporarily, if using the data stack alone would be too complex, and
2489: factoring and locals are not an option:
2490:
2491: @example
2492: : 2swap ( x1 x2 x3 x4 -- x3 x4 x1 x2 )
2493: rot >r rot r> ;
2494: @end example
2495:
2496: The return address of the definition and the loop control parameters of
2497: counted loops usually reside on the return stack, so you have to take
2498: all items, that you have pushed on the return stack in a colon
2499: definition or counted loop, from the return stack before the definition
2500: or loop ends. You cannot access items that you pushed on the return
2501: stack outside some definition or loop within the definition of loop.
2502:
2503: If you miscount the return stack items, this usually ends in a crash:
2504:
2505: @example
2506: : crash ( n -- )
2507: >r ;
2508: 5 crash
2509: @end example
2510:
2511: You cannot mix using locals and using the return stack (according to the
2512: standard; Gforth has no problem). However, they solve the same
2513: problems, so this shouldn't be an issue.
2514:
2515: @assignment
2516: Can you rewrite any of the definitions you wrote until now in a better
2517: way using the return stack?
2518: @endassignment
2519:
1.66 anton 2520: Reference: @ref{Return stack}.
2521:
1.48 anton 2522:
2523: @node Memory Tutorial, Characters and Strings Tutorial, Return Stack Tutorial, Tutorial
2524: @section Memory
1.66 anton 2525: @cindex memory access/allocation tutorial
1.48 anton 2526:
2527: You can create a global variable @code{v} with
2528:
2529: @example
2530: variable v ( -- addr )
2531: @end example
2532:
2533: @code{v} pushes the address of a cell in memory on the stack. This cell
2534: was reserved by @code{variable}. You can use @code{!} (store) to store
2535: values into this cell and @code{@@} (fetch) to load the value from the
2536: stack into memory:
2537:
2538: @example
2539: v .
2540: 5 v ! .s
1.50 anton 2541: v @@ .
1.48 anton 2542: @end example
2543:
1.65 anton 2544: You can see a raw dump of memory with @code{dump}:
2545:
2546: @example
2547: v 1 cells .s dump
2548: @end example
2549:
2550: @code{Cells ( n1 -- n2 )} gives you the number of bytes (or, more
2551: generally, address units (aus)) that @code{n1 cells} occupy. You can
2552: also reserve more memory:
1.48 anton 2553:
2554: @example
2555: create v2 20 cells allot
1.65 anton 2556: v2 20 cells dump
1.48 anton 2557: @end example
2558:
1.65 anton 2559: creates a word @code{v2} and reserves 20 uninitialized cells; the
2560: address pushed by @code{v2} points to the start of these 20 cells. You
2561: can use address arithmetic to access these cells:
1.48 anton 2562:
2563: @example
2564: 3 v2 5 cells + !
1.65 anton 2565: v2 20 cells dump
1.48 anton 2566: @end example
2567:
2568: You can reserve and initialize memory with @code{,}:
2569:
2570: @example
2571: create v3
2572: 5 , 4 , 3 , 2 , 1 ,
1.50 anton 2573: v3 @@ .
2574: v3 cell+ @@ .
2575: v3 2 cells + @@ .
1.65 anton 2576: v3 5 cells dump
1.48 anton 2577: @end example
2578:
2579: @assignment
2580: Write a definition @code{vsum ( addr u -- n )} that computes the sum of
2581: @code{u} cells, with the first of these cells at @code{addr}, the next
2582: one at @code{addr cell+} etc.
2583: @endassignment
2584:
2585: You can also reserve memory without creating a new word:
2586:
2587: @example
1.60 anton 2588: here 10 cells allot .
2589: here .
1.48 anton 2590: @end example
2591:
2592: @code{Here} pushes the start address of the memory area. You should
2593: store it somewhere, or you will have a hard time finding the memory area
2594: again.
2595:
2596: @code{Allot} manages dictionary memory. The dictionary memory contains
2597: the system's data structures for words etc. on Gforth and most other
2598: Forth systems. It is managed like a stack: You can free the memory that
2599: you have just @code{allot}ed with
2600:
2601: @example
2602: -10 cells allot
1.60 anton 2603: here .
1.48 anton 2604: @end example
2605:
2606: Note that you cannot do this if you have created a new word in the
2607: meantime (because then your @code{allot}ed memory is no longer on the
2608: top of the dictionary ``stack'').
2609:
2610: Alternatively, you can use @code{allocate} and @code{free} which allow
2611: freeing memory in any order:
2612:
2613: @example
2614: 10 cells allocate throw .s
2615: 20 cells allocate throw .s
2616: swap
2617: free throw
2618: free throw
2619: @end example
2620:
2621: The @code{throw}s deal with errors (e.g., out of memory).
2622:
1.65 anton 2623: And there is also a
2624: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
2625: garbage collector}, which eliminates the need to @code{free} memory
2626: explicitly.
1.48 anton 2627:
1.66 anton 2628: Reference: @ref{Memory}.
2629:
1.48 anton 2630:
2631: @node Characters and Strings Tutorial, Alignment Tutorial, Memory Tutorial, Tutorial
2632: @section Characters and Strings
1.66 anton 2633: @cindex strings tutorial
2634: @cindex characters tutorial
1.48 anton 2635:
2636: On the stack characters take up a cell, like numbers. In memory they
2637: have their own size (one 8-bit byte on most systems), and therefore
2638: require their own words for memory access:
2639:
2640: @example
2641: create v4
2642: 104 c, 97 c, 108 c, 108 c, 111 c,
1.50 anton 2643: v4 4 chars + c@@ .
1.65 anton 2644: v4 5 chars dump
1.48 anton 2645: @end example
2646:
2647: The preferred representation of strings on the stack is @code{addr
2648: u-count}, where @code{addr} is the address of the first character and
2649: @code{u-count} is the number of characters in the string.
2650:
2651: @example
2652: v4 5 type
2653: @end example
2654:
2655: You get a string constant with
2656:
2657: @example
2658: s" hello, world" .s
2659: type
2660: @end example
2661:
2662: Make sure you have a space between @code{s"} and the string; @code{s"}
2663: is a normal Forth word and must be delimited with white space (try what
2664: happens when you remove the space).
2665:
2666: However, this interpretive use of @code{s"} is quite restricted: the
2667: string exists only until the next call of @code{s"} (some Forth systems
2668: keep more than one of these strings, but usually they still have a
1.62 crook 2669: limited lifetime).
1.48 anton 2670:
2671: @example
2672: s" hello," s" world" .s
2673: type
2674: type
2675: @end example
2676:
1.62 crook 2677: You can also use @code{s"} in a definition, and the resulting
2678: strings then live forever (well, for as long as the definition):
1.48 anton 2679:
2680: @example
2681: : foo s" hello," s" world" ;
2682: foo .s
2683: type
2684: type
2685: @end example
2686:
2687: @assignment
2688: @code{Emit ( c -- )} types @code{c} as character (not a number).
2689: Implement @code{type ( addr u -- )}.
2690: @endassignment
2691:
1.66 anton 2692: Reference: @ref{Memory Blocks}.
2693:
2694:
1.84 pazsan 2695: @node Alignment Tutorial, Files Tutorial, Characters and Strings Tutorial, Tutorial
1.48 anton 2696: @section Alignment
1.66 anton 2697: @cindex alignment tutorial
2698: @cindex memory alignment tutorial
1.48 anton 2699:
2700: On many processors cells have to be aligned in memory, if you want to
2701: access them with @code{@@} and @code{!} (and even if the processor does
1.62 crook 2702: not require alignment, access to aligned cells is faster).
1.48 anton 2703:
2704: @code{Create} aligns @code{here} (i.e., the place where the next
2705: allocation will occur, and that the @code{create}d word points to).
2706: Likewise, the memory produced by @code{allocate} starts at an aligned
2707: address. Adding a number of @code{cells} to an aligned address produces
2708: another aligned address.
2709:
2710: However, address arithmetic involving @code{char+} and @code{chars} can
2711: create an address that is not cell-aligned. @code{Aligned ( addr --
2712: a-addr )} produces the next aligned address:
2713:
2714: @example
1.50 anton 2715: v3 char+ aligned .s @@ .
2716: v3 char+ .s @@ .
1.48 anton 2717: @end example
2718:
2719: Similarly, @code{align} advances @code{here} to the next aligned
2720: address:
2721:
2722: @example
2723: create v5 97 c,
2724: here .
2725: align here .
2726: 1000 ,
2727: @end example
2728:
2729: Note that you should use aligned addresses even if your processor does
2730: not require them, if you want your program to be portable.
2731:
1.66 anton 2732: Reference: @ref{Address arithmetic}.
2733:
1.48 anton 2734:
1.84 pazsan 2735: @node Files Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Alignment Tutorial, Tutorial
2736: @section Files
2737: @cindex files tutorial
2738:
2739: This section gives a short introduction into how to use files inside
2740: Forth. It's broken up into five easy steps:
2741:
2742: @enumerate 1
2743: @item Opened an ASCII text file for input
2744: @item Opened a file for output
2745: @item Read input file until string matched (or some other condition matched)
2746: @item Wrote some lines from input ( modified or not) to output
2747: @item Closed the files.
2748: @end enumerate
2749:
2750: @subsection Open file for input
2751:
2752: @example
2753: s" foo.in" r/o open-file throw Value fd-in
2754: @end example
2755:
2756: @subsection Create file for output
2757:
2758: @example
2759: s" foo.out" w/o create-file throw Value fd-out
2760: @end example
2761:
2762: The available file modes are r/o for read-only access, r/w for
2763: read-write access, and w/o for write-only access. You could open both
2764: files with r/w, too, if you like. All file words return error codes; for
2765: most applications, it's best to pass there error codes with @code{throw}
2766: to the outer error handler.
2767:
2768: If you want words for opening and assigning, define them as follows:
2769:
2770: @example
2771: 0 Value fd-in
2772: 0 Value fd-out
2773: : open-input ( addr u -- ) r/o open-file throw to fd-in ;
2774: : open-output ( addr u -- ) w/o create-file throw to fd-out ;
2775: @end example
2776:
2777: Usage example:
2778:
2779: @example
2780: s" foo.in" open-input
2781: s" foo.out" open-output
2782: @end example
2783:
2784: @subsection Scan file for a particular line
2785:
2786: @example
2787: 256 Constant max-line
2788: Create line-buffer max-line 2 + allot
2789:
2790: : scan-file ( addr u -- )
2791: begin
2792: line-buffer max-line fd-in read-line throw
2793: while
2794: >r 2dup line-buffer r> compare 0=
2795: until
2796: else
2797: drop
2798: then
2799: 2drop ;
2800: @end example
2801:
2802: @code{read-line ( addr u1 fd -- u2 flag ior )} reads up to u1 bytes into
2803: the buffer at addr, and returns the number of bytes read, a flag that's
2804: true when the end of file is reached, and an error code.
2805:
2806: @code{compare ( addr1 u1 addr2 u2 -- n )} compares two strings and
2807: returns zero if both strings are equal. It returns a positive number if
2808: the first string is lexically greater, a negative if the second string
2809: is lexically greater.
2810:
2811: We haven't seen this loop here; it has two exits. Since the @code{while}
2812: exits with the number of bytes read on the stack, we have to clean up
2813: that separately; that's after the @code{else}.
2814:
2815: Usage example:
2816:
2817: @example
2818: s" The text I search is here" scan-file
2819: @end example
2820:
2821: @subsection Copy input to output
2822:
2823: @example
2824: : copy-file ( -- )
2825: begin
2826: line-buffer max-line fd-in read-line throw
2827: while
2828: line-buffer swap fd-out write-file throw
2829: repeat ;
2830: @end example
2831:
2832: @subsection Close files
2833:
2834: @example
2835: fd-in close-file throw
2836: fd-out close-file throw
2837: @end example
2838:
2839: Likewise, you can put that into definitions, too:
2840:
2841: @example
2842: : close-input ( -- ) fd-in close-file throw ;
2843: : close-output ( -- ) fd-out close-file throw ;
2844: @end example
2845:
2846: @assignment
2847: How could you modify @code{copy-file} so that it copies until a second line is
2848: matched? Can you write a program that extracts a section of a text file,
2849: given the line that starts and the line that terminates that section?
2850: @endassignment
2851:
2852: @node Interpretation and Compilation Semantics and Immediacy Tutorial, Execution Tokens Tutorial, Files Tutorial, Tutorial
1.48 anton 2853: @section Interpretation and Compilation Semantics and Immediacy
1.66 anton 2854: @cindex semantics tutorial
2855: @cindex interpretation semantics tutorial
2856: @cindex compilation semantics tutorial
2857: @cindex immediate, tutorial
1.48 anton 2858:
2859: When a word is compiled, it behaves differently from being interpreted.
2860: E.g., consider @code{+}:
2861:
2862: @example
2863: 1 2 + .
2864: : foo + ;
2865: @end example
2866:
2867: These two behaviours are known as compilation and interpretation
2868: semantics. For normal words (e.g., @code{+}), the compilation semantics
2869: is to append the interpretation semantics to the currently defined word
2870: (@code{foo} in the example above). I.e., when @code{foo} is executed
2871: later, the interpretation semantics of @code{+} (i.e., adding two
2872: numbers) will be performed.
2873:
2874: However, there are words with non-default compilation semantics, e.g.,
2875: the control-flow words like @code{if}. You can use @code{immediate} to
2876: change the compilation semantics of the last defined word to be equal to
2877: the interpretation semantics:
2878:
2879: @example
2880: : [FOO] ( -- )
2881: 5 . ; immediate
2882:
2883: [FOO]
2884: : bar ( -- )
2885: [FOO] ;
2886: bar
2887: see bar
2888: @end example
2889:
2890: Two conventions to mark words with non-default compilation semnatics are
2891: names with brackets (more frequently used) and to write them all in
2892: upper case (less frequently used).
2893:
2894: In Gforth (and many other systems) you can also remove the
2895: interpretation semantics with @code{compile-only} (the compilation
2896: semantics is derived from the original interpretation semantics):
2897:
2898: @example
2899: : flip ( -- )
2900: 6 . ; compile-only \ but not immediate
2901: flip
2902:
2903: : flop ( -- )
2904: flip ;
2905: flop
2906: @end example
2907:
2908: In this example the interpretation semantics of @code{flop} is equal to
2909: the original interpretation semantics of @code{flip}.
2910:
2911: The text interpreter has two states: in interpret state, it performs the
2912: interpretation semantics of words it encounters; in compile state, it
2913: performs the compilation semantics of these words.
2914:
2915: Among other things, @code{:} switches into compile state, and @code{;}
2916: switches back to interpret state. They contain the factors @code{]}
2917: (switch to compile state) and @code{[} (switch to interpret state), that
2918: do nothing but switch the state.
2919:
2920: @example
2921: : xxx ( -- )
2922: [ 5 . ]
2923: ;
2924:
2925: xxx
2926: see xxx
2927: @end example
2928:
2929: These brackets are also the source of the naming convention mentioned
2930: above.
2931:
1.66 anton 2932: Reference: @ref{Interpretation and Compilation Semantics}.
2933:
1.48 anton 2934:
2935: @node Execution Tokens Tutorial, Exceptions Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Tutorial
2936: @section Execution Tokens
1.66 anton 2937: @cindex execution tokens tutorial
2938: @cindex XT tutorial
1.48 anton 2939:
2940: @code{' word} gives you the execution token (XT) of a word. The XT is a
2941: cell representing the interpretation semantics of a word. You can
2942: execute this semantics with @code{execute}:
2943:
2944: @example
2945: ' + .s
2946: 1 2 rot execute .
2947: @end example
2948:
2949: The XT is similar to a function pointer in C. However, parameter
2950: passing through the stack makes it a little more flexible:
2951:
2952: @example
2953: : map-array ( ... addr u xt -- ... )
1.50 anton 2954: \ executes xt ( ... x -- ... ) for every element of the array starting
2955: \ at addr and containing u elements
1.48 anton 2956: @{ xt @}
2957: cells over + swap ?do
1.50 anton 2958: i @@ xt execute
1.48 anton 2959: 1 cells +loop ;
2960:
2961: create a 3 , 4 , 2 , -1 , 4 ,
2962: a 5 ' . map-array .s
2963: 0 a 5 ' + map-array .
2964: s" max-n" environment? drop .s
2965: a 5 ' min map-array .
2966: @end example
2967:
2968: You can use map-array with the XTs of words that consume one element
2969: more than they produce. In theory you can also use it with other XTs,
2970: but the stack effect then depends on the size of the array, which is
2971: hard to understand.
2972:
1.51 pazsan 2973: Since XTs are cell-sized, you can store them in memory and manipulate
2974: them on the stack like other cells. You can also compile the XT into a
1.48 anton 2975: word with @code{compile,}:
2976:
2977: @example
2978: : foo1 ( n1 n2 -- n )
2979: [ ' + compile, ] ;
2980: see foo
2981: @end example
2982:
2983: This is non-standard, because @code{compile,} has no compilation
2984: semantics in the standard, but it works in good Forth systems. For the
2985: broken ones, use
2986:
2987: @example
2988: : [compile,] compile, ; immediate
2989:
2990: : foo1 ( n1 n2 -- n )
2991: [ ' + ] [compile,] ;
2992: see foo
2993: @end example
2994:
2995: @code{'} is a word with default compilation semantics; it parses the
2996: next word when its interpretation semantics are executed, not during
2997: compilation:
2998:
2999: @example
3000: : foo ( -- xt )
3001: ' ;
3002: see foo
3003: : bar ( ... "word" -- ... )
3004: ' execute ;
3005: see bar
1.60 anton 3006: 1 2 bar + .
1.48 anton 3007: @end example
3008:
3009: You often want to parse a word during compilation and compile its XT so
3010: it will be pushed on the stack at run-time. @code{[']} does this:
3011:
3012: @example
3013: : xt-+ ( -- xt )
3014: ['] + ;
3015: see xt-+
3016: 1 2 xt-+ execute .
3017: @end example
3018:
3019: Many programmers tend to see @code{'} and the word it parses as one
3020: unit, and expect it to behave like @code{[']} when compiled, and are
3021: confused by the actual behaviour. If you are, just remember that the
3022: Forth system just takes @code{'} as one unit and has no idea that it is
3023: a parsing word (attempts to convenience programmers in this issue have
3024: usually resulted in even worse pitfalls, see
1.66 anton 3025: @uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,
3026: @code{State}-smartness---Why it is evil and How to Exorcise it}).
1.48 anton 3027:
3028: Note that the state of the interpreter does not come into play when
1.51 pazsan 3029: creating and executing XTs. I.e., even when you execute @code{'} in
1.48 anton 3030: compile state, it still gives you the interpretation semantics. And
3031: whatever that state is, @code{execute} performs the semantics
1.66 anton 3032: represented by the XT (i.e., for XTs produced with @code{'} the
3033: interpretation semantics).
3034:
3035: Reference: @ref{Tokens for Words}.
1.48 anton 3036:
3037:
3038: @node Exceptions Tutorial, Defining Words Tutorial, Execution Tokens Tutorial, Tutorial
3039: @section Exceptions
1.66 anton 3040: @cindex exceptions tutorial
1.48 anton 3041:
3042: @code{throw ( n -- )} causes an exception unless n is zero.
3043:
3044: @example
3045: 100 throw .s
3046: 0 throw .s
3047: @end example
3048:
3049: @code{catch ( ... xt -- ... n )} behaves similar to @code{execute}, but
3050: it catches exceptions and pushes the number of the exception on the
3051: stack (or 0, if the xt executed without exception). If there was an
3052: exception, the stacks have the same depth as when entering @code{catch}:
3053:
3054: @example
3055: .s
3056: 3 0 ' / catch .s
3057: 3 2 ' / catch .s
3058: @end example
3059:
3060: @assignment
3061: Try the same with @code{execute} instead of @code{catch}.
3062: @endassignment
3063:
3064: @code{Throw} always jumps to the dynamically next enclosing
3065: @code{catch}, even if it has to leave several call levels to achieve
3066: this:
3067:
3068: @example
3069: : foo 100 throw ;
3070: : foo1 foo ." after foo" ;
1.51 pazsan 3071: : bar ['] foo1 catch ;
1.60 anton 3072: bar .
1.48 anton 3073: @end example
3074:
3075: It is often important to restore a value upon leaving a definition, even
3076: if the definition is left through an exception. You can ensure this
3077: like this:
3078:
3079: @example
3080: : ...
3081: save-x
1.51 pazsan 3082: ['] word-changing-x catch ( ... n )
1.48 anton 3083: restore-x
3084: ( ... n ) throw ;
3085: @end example
3086:
1.55 anton 3087: Gforth provides an alternative syntax in addition to @code{catch}:
1.48 anton 3088: @code{try ... recover ... endtry}. If the code between @code{try} and
3089: @code{recover} has an exception, the stack depths are restored, the
3090: exception number is pushed on the stack, and the code between
3091: @code{recover} and @code{endtry} is performed. E.g., the definition for
3092: @code{catch} is
3093:
3094: @example
3095: : catch ( x1 .. xn xt -- y1 .. ym 0 / z1 .. zn error ) \ exception
3096: try
3097: execute 0
3098: recover
3099: nip
3100: endtry ;
3101: @end example
3102:
3103: The equivalent to the restoration code above is
3104:
3105: @example
3106: : ...
3107: save-x
3108: try
3109: word-changing-x
3110: end-try
3111: restore-x
3112: throw ;
3113: @end example
3114:
3115: As you can see, the @code{recover} part is optional.
3116:
1.66 anton 3117: Reference: @ref{Exception Handling}.
3118:
1.48 anton 3119:
3120: @node Defining Words Tutorial, Arrays and Records Tutorial, Exceptions Tutorial, Tutorial
3121: @section Defining Words
1.66 anton 3122: @cindex defining words tutorial
3123: @cindex does> tutorial
3124: @cindex create...does> tutorial
3125:
3126: @c before semantics?
1.48 anton 3127:
3128: @code{:}, @code{create}, and @code{variable} are definition words: They
3129: define other words. @code{Constant} is another definition word:
3130:
3131: @example
3132: 5 constant foo
3133: foo .
3134: @end example
3135:
3136: You can also use the prefixes @code{2} (double-cell) and @code{f}
3137: (floating point) with @code{variable} and @code{constant}.
3138:
3139: You can also define your own defining words. E.g.:
3140:
3141: @example
3142: : variable ( "name" -- )
3143: create 0 , ;
3144: @end example
3145:
3146: You can also define defining words that create words that do something
3147: other than just producing their address:
3148:
3149: @example
3150: : constant ( n "name" -- )
3151: create ,
3152: does> ( -- n )
1.50 anton 3153: ( addr ) @@ ;
1.48 anton 3154:
3155: 5 constant foo
3156: foo .
3157: @end example
3158:
3159: The definition of @code{constant} above ends at the @code{does>}; i.e.,
3160: @code{does>} replaces @code{;}, but it also does something else: It
3161: changes the last defined word such that it pushes the address of the
3162: body of the word and then performs the code after the @code{does>}
3163: whenever it is called.
3164:
3165: In the example above, @code{constant} uses @code{,} to store 5 into the
3166: body of @code{foo}. When @code{foo} executes, it pushes the address of
3167: the body onto the stack, then (in the code after the @code{does>})
3168: fetches the 5 from there.
3169:
3170: The stack comment near the @code{does>} reflects the stack effect of the
3171: defined word, not the stack effect of the code after the @code{does>}
3172: (the difference is that the code expects the address of the body that
3173: the stack comment does not show).
3174:
3175: You can use these definition words to do factoring in cases that involve
3176: (other) definition words. E.g., a field offset is always added to an
3177: address. Instead of defining
3178:
3179: @example
3180: 2 cells constant offset-field1
3181: @end example
3182:
3183: and using this like
3184:
3185: @example
3186: ( addr ) offset-field1 +
3187: @end example
3188:
3189: you can define a definition word
3190:
3191: @example
3192: : simple-field ( n "name" -- )
3193: create ,
3194: does> ( n1 -- n1+n )
1.50 anton 3195: ( addr ) @@ + ;
1.48 anton 3196: @end example
1.21 crook 3197:
1.48 anton 3198: Definition and use of field offsets now look like this:
1.21 crook 3199:
1.48 anton 3200: @example
3201: 2 cells simple-field field1
1.60 anton 3202: create mystruct 4 cells allot
3203: mystruct .s field1 .s drop
1.48 anton 3204: @end example
1.21 crook 3205:
1.48 anton 3206: If you want to do something with the word without performing the code
3207: after the @code{does>}, you can access the body of a @code{create}d word
3208: with @code{>body ( xt -- addr )}:
1.21 crook 3209:
1.48 anton 3210: @example
3211: : value ( n "name" -- )
3212: create ,
3213: does> ( -- n1 )
1.50 anton 3214: @@ ;
1.48 anton 3215: : to ( n "name" -- )
3216: ' >body ! ;
1.21 crook 3217:
1.48 anton 3218: 5 value foo
3219: foo .
3220: 7 to foo
3221: foo .
3222: @end example
1.21 crook 3223:
1.48 anton 3224: @assignment
3225: Define @code{defer ( "name" -- )}, which creates a word that stores an
3226: XT (at the start the XT of @code{abort}), and upon execution
3227: @code{execute}s the XT. Define @code{is ( xt "name" -- )} that stores
3228: @code{xt} into @code{name}, a word defined with @code{defer}. Indirect
3229: recursion is one application of @code{defer}.
3230: @endassignment
1.29 crook 3231:
1.66 anton 3232: Reference: @ref{User-defined Defining Words}.
3233:
3234:
1.48 anton 3235: @node Arrays and Records Tutorial, POSTPONE Tutorial, Defining Words Tutorial, Tutorial
3236: @section Arrays and Records
1.66 anton 3237: @cindex arrays tutorial
3238: @cindex records tutorial
3239: @cindex structs tutorial
1.29 crook 3240:
1.48 anton 3241: Forth has no standard words for defining data structures such as arrays
3242: and records (structs in C terminology), but you can build them yourself
3243: based on address arithmetic. You can also define words for defining
3244: arrays and records (@pxref{Defining Words Tutorial,, Defining Words}).
1.29 crook 3245:
1.48 anton 3246: One of the first projects a Forth newcomer sets out upon when learning
3247: about defining words is an array defining word (possibly for
3248: n-dimensional arrays). Go ahead and do it, I did it, too; you will
3249: learn something from it. However, don't be disappointed when you later
3250: learn that you have little use for these words (inappropriate use would
3251: be even worse). I have not yet found a set of useful array words yet;
3252: the needs are just too diverse, and named, global arrays (the result of
3253: naive use of defining words) are often not flexible enough (e.g.,
1.66 anton 3254: consider how to pass them as parameters). Another such project is a set
3255: of words to help dealing with strings.
1.29 crook 3256:
1.48 anton 3257: On the other hand, there is a useful set of record words, and it has
3258: been defined in @file{compat/struct.fs}; these words are predefined in
3259: Gforth. They are explained in depth elsewhere in this manual (see
3260: @pxref{Structures}). The @code{simple-field} example above is
3261: simplified variant of fields in this package.
1.21 crook 3262:
3263:
1.48 anton 3264: @node POSTPONE Tutorial, Literal Tutorial, Arrays and Records Tutorial, Tutorial
3265: @section @code{POSTPONE}
1.66 anton 3266: @cindex postpone tutorial
1.21 crook 3267:
1.48 anton 3268: You can compile the compilation semantics (instead of compiling the
3269: interpretation semantics) of a word with @code{POSTPONE}:
1.21 crook 3270:
1.48 anton 3271: @example
3272: : MY-+ ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
1.51 pazsan 3273: POSTPONE + ; immediate
1.48 anton 3274: : foo ( n1 n2 -- n )
3275: MY-+ ;
3276: 1 2 foo .
3277: see foo
3278: @end example
1.21 crook 3279:
1.48 anton 3280: During the definition of @code{foo} the text interpreter performs the
3281: compilation semantics of @code{MY-+}, which performs the compilation
3282: semantics of @code{+}, i.e., it compiles @code{+} into @code{foo}.
3283:
3284: This example also displays separate stack comments for the compilation
3285: semantics and for the stack effect of the compiled code. For words with
3286: default compilation semantics these stack effects are usually not
3287: displayed; the stack effect of the compilation semantics is always
3288: @code{( -- )} for these words, the stack effect for the compiled code is
3289: the stack effect of the interpretation semantics.
3290:
3291: Note that the state of the interpreter does not come into play when
3292: performing the compilation semantics in this way. You can also perform
3293: it interpretively, e.g.:
3294:
3295: @example
3296: : foo2 ( n1 n2 -- n )
3297: [ MY-+ ] ;
3298: 1 2 foo .
3299: see foo
3300: @end example
1.21 crook 3301:
1.48 anton 3302: However, there are some broken Forth systems where this does not always
1.62 crook 3303: work, and therefore this practice was been declared non-standard in
1.48 anton 3304: 1999.
3305: @c !! repair.fs
3306:
3307: Here is another example for using @code{POSTPONE}:
1.44 crook 3308:
1.48 anton 3309: @example
3310: : MY-- ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
3311: POSTPONE negate POSTPONE + ; immediate compile-only
3312: : bar ( n1 n2 -- n )
3313: MY-- ;
3314: 2 1 bar .
3315: see bar
3316: @end example
1.21 crook 3317:
1.48 anton 3318: You can define @code{ENDIF} in this way:
1.21 crook 3319:
1.48 anton 3320: @example
3321: : ENDIF ( Compilation: orig -- )
3322: POSTPONE then ; immediate
3323: @end example
1.21 crook 3324:
1.48 anton 3325: @assignment
3326: Write @code{MY-2DUP} that has compilation semantics equivalent to
3327: @code{2dup}, but compiles @code{over over}.
3328: @endassignment
1.29 crook 3329:
1.66 anton 3330: @c !! @xref{Macros} for reference
3331:
3332:
1.48 anton 3333: @node Literal Tutorial, Advanced macros Tutorial, POSTPONE Tutorial, Tutorial
3334: @section @code{Literal}
1.66 anton 3335: @cindex literal tutorial
1.29 crook 3336:
1.48 anton 3337: You cannot @code{POSTPONE} numbers:
1.21 crook 3338:
1.48 anton 3339: @example
3340: : [FOO] POSTPONE 500 ; immediate
1.21 crook 3341: @end example
3342:
1.48 anton 3343: Instead, you can use @code{LITERAL (compilation: n --; run-time: -- n )}:
1.29 crook 3344:
1.48 anton 3345: @example
3346: : [FOO] ( compilation: --; run-time: -- n )
3347: 500 POSTPONE literal ; immediate
1.29 crook 3348:
1.60 anton 3349: : flip [FOO] ;
1.48 anton 3350: flip .
3351: see flip
3352: @end example
1.29 crook 3353:
1.48 anton 3354: @code{LITERAL} consumes a number at compile-time (when it's compilation
3355: semantics are executed) and pushes it at run-time (when the code it
3356: compiled is executed). A frequent use of @code{LITERAL} is to compile a
3357: number computed at compile time into the current word:
1.29 crook 3358:
1.48 anton 3359: @example
3360: : bar ( -- n )
3361: [ 2 2 + ] literal ;
3362: see bar
3363: @end example
1.29 crook 3364:
1.48 anton 3365: @assignment
3366: Write @code{]L} which allows writing the example above as @code{: bar (
3367: -- n ) [ 2 2 + ]L ;}
3368: @endassignment
3369:
1.66 anton 3370: @c !! @xref{Macros} for reference
3371:
1.48 anton 3372:
3373: @node Advanced macros Tutorial, Compilation Tokens Tutorial, Literal Tutorial, Tutorial
3374: @section Advanced macros
1.66 anton 3375: @cindex macros, advanced tutorial
3376: @cindex run-time code generation, tutorial
1.48 anton 3377:
1.66 anton 3378: Reconsider @code{map-array} from @ref{Execution Tokens Tutorial,,
3379: Execution Tokens}. It frequently performs @code{execute}, a relatively
3380: expensive operation in some Forth implementations. You can use
1.48 anton 3381: @code{compile,} and @code{POSTPONE} to eliminate these @code{execute}s
3382: and produce a word that contains the word to be performed directly:
3383:
3384: @c use ]] ... [[
3385: @example
3386: : compile-map-array ( compilation: xt -- ; run-time: ... addr u -- ... )
3387: \ at run-time, execute xt ( ... x -- ... ) for each element of the
3388: \ array beginning at addr and containing u elements
3389: @{ xt @}
3390: POSTPONE cells POSTPONE over POSTPONE + POSTPONE swap POSTPONE ?do
1.50 anton 3391: POSTPONE i POSTPONE @@ xt compile,
1.48 anton 3392: 1 cells POSTPONE literal POSTPONE +loop ;
3393:
3394: : sum-array ( addr u -- n )
3395: 0 rot rot [ ' + compile-map-array ] ;
3396: see sum-array
3397: a 5 sum-array .
3398: @end example
3399:
3400: You can use the full power of Forth for generating the code; here's an
3401: example where the code is generated in a loop:
3402:
3403: @example
3404: : compile-vmul-step ( compilation: n --; run-time: n1 addr1 -- n2 addr2 )
3405: \ n2=n1+(addr1)*n, addr2=addr1+cell
1.50 anton 3406: POSTPONE tuck POSTPONE @@
1.48 anton 3407: POSTPONE literal POSTPONE * POSTPONE +
3408: POSTPONE swap POSTPONE cell+ ;
3409:
3410: : compile-vmul ( compilation: addr1 u -- ; run-time: addr2 -- n )
1.51 pazsan 3411: \ n=v1*v2 (inner product), where the v_i are represented as addr_i u
1.48 anton 3412: 0 postpone literal postpone swap
3413: [ ' compile-vmul-step compile-map-array ]
3414: postpone drop ;
3415: see compile-vmul
3416:
3417: : a-vmul ( addr -- n )
1.51 pazsan 3418: \ n=a*v, where v is a vector that's as long as a and starts at addr
1.48 anton 3419: [ a 5 compile-vmul ] ;
3420: see a-vmul
3421: a a-vmul .
3422: @end example
3423:
3424: This example uses @code{compile-map-array} to show off, but you could
1.66 anton 3425: also use @code{map-array} instead (try it now!).
1.48 anton 3426:
3427: You can use this technique for efficient multiplication of large
3428: matrices. In matrix multiplication, you multiply every line of one
3429: matrix with every column of the other matrix. You can generate the code
3430: for one line once, and use it for every column. The only downside of
3431: this technique is that it is cumbersome to recover the memory consumed
3432: by the generated code when you are done (and in more complicated cases
3433: it is not possible portably).
3434:
1.66 anton 3435: @c !! @xref{Macros} for reference
3436:
3437:
1.48 anton 3438: @node Compilation Tokens Tutorial, Wordlists and Search Order Tutorial, Advanced macros Tutorial, Tutorial
3439: @section Compilation Tokens
1.66 anton 3440: @cindex compilation tokens, tutorial
3441: @cindex CT, tutorial
1.48 anton 3442:
3443: This section is Gforth-specific. You can skip it.
3444:
3445: @code{' word compile,} compiles the interpretation semantics. For words
3446: with default compilation semantics this is the same as performing the
3447: compilation semantics. To represent the compilation semantics of other
3448: words (e.g., words like @code{if} that have no interpretation
3449: semantics), Gforth has the concept of a compilation token (CT,
3450: consisting of two cells), and words @code{comp'} and @code{[comp']}.
3451: You can perform the compilation semantics represented by a CT with
3452: @code{execute}:
1.29 crook 3453:
1.48 anton 3454: @example
3455: : foo2 ( n1 n2 -- n )
3456: [ comp' + execute ] ;
3457: see foo
3458: @end example
1.29 crook 3459:
1.48 anton 3460: You can compile the compilation semantics represented by a CT with
3461: @code{postpone,}:
1.30 anton 3462:
1.48 anton 3463: @example
3464: : foo3 ( -- )
3465: [ comp' + postpone, ] ;
3466: see foo3
3467: @end example
1.30 anton 3468:
1.51 pazsan 3469: @code{[ comp' word postpone, ]} is equivalent to @code{POSTPONE word}.
1.48 anton 3470: @code{comp'} is particularly useful for words that have no
3471: interpretation semantics:
1.29 crook 3472:
1.30 anton 3473: @example
1.48 anton 3474: ' if
1.60 anton 3475: comp' if .s 2drop
1.30 anton 3476: @end example
3477:
1.66 anton 3478: Reference: @ref{Tokens for Words}.
3479:
1.29 crook 3480:
1.48 anton 3481: @node Wordlists and Search Order Tutorial, , Compilation Tokens Tutorial, Tutorial
3482: @section Wordlists and Search Order
1.66 anton 3483: @cindex wordlists tutorial
3484: @cindex search order, tutorial
1.48 anton 3485:
3486: The dictionary is not just a memory area that allows you to allocate
3487: memory with @code{allot}, it also contains the Forth words, arranged in
3488: several wordlists. When searching for a word in a wordlist,
3489: conceptually you start searching at the youngest and proceed towards
3490: older words (in reality most systems nowadays use hash-tables); i.e., if
3491: you define a word with the same name as an older word, the new word
3492: shadows the older word.
3493:
3494: Which wordlists are searched in which order is determined by the search
3495: order. You can display the search order with @code{order}. It displays
3496: first the search order, starting with the wordlist searched first, then
3497: it displays the wordlist that will contain newly defined words.
1.21 crook 3498:
1.48 anton 3499: You can create a new, empty wordlist with @code{wordlist ( -- wid )}:
1.21 crook 3500:
1.48 anton 3501: @example
3502: wordlist constant mywords
3503: @end example
1.21 crook 3504:
1.48 anton 3505: @code{Set-current ( wid -- )} sets the wordlist that will contain newly
3506: defined words (the @emph{current} wordlist):
1.21 crook 3507:
1.48 anton 3508: @example
3509: mywords set-current
3510: order
3511: @end example
1.26 crook 3512:
1.48 anton 3513: Gforth does not display a name for the wordlist in @code{mywords}
3514: because this wordlist was created anonymously with @code{wordlist}.
1.21 crook 3515:
1.48 anton 3516: You can get the current wordlist with @code{get-current ( -- wid)}. If
3517: you want to put something into a specific wordlist without overall
3518: effect on the current wordlist, this typically looks like this:
1.21 crook 3519:
1.48 anton 3520: @example
3521: get-current mywords set-current ( wid )
3522: create someword
3523: ( wid ) set-current
3524: @end example
1.21 crook 3525:
1.48 anton 3526: You can write the search order with @code{set-order ( wid1 .. widn n --
3527: )} and read it with @code{get-order ( -- wid1 .. widn n )}. The first
3528: searched wordlist is topmost.
1.21 crook 3529:
1.48 anton 3530: @example
3531: get-order mywords swap 1+ set-order
3532: order
3533: @end example
1.21 crook 3534:
1.48 anton 3535: Yes, the order of wordlists in the output of @code{order} is reversed
3536: from stack comments and the output of @code{.s} and thus unintuitive.
1.21 crook 3537:
1.48 anton 3538: @assignment
3539: Define @code{>order ( wid -- )} with adds @code{wid} as first searched
3540: wordlist to the search order. Define @code{previous ( -- )}, which
3541: removes the first searched wordlist from the search order. Experiment
3542: with boundary conditions (you will see some crashes or situations that
3543: are hard or impossible to leave).
3544: @endassignment
1.21 crook 3545:
1.48 anton 3546: The search order is a powerful foundation for providing features similar
3547: to Modula-2 modules and C++ namespaces. However, trying to modularize
3548: programs in this way has disadvantages for debugging and reuse/factoring
3549: that overcome the advantages in my experience (I don't do huge projects,
1.55 anton 3550: though). These disadvantages are not so clear in other
1.82 anton 3551: languages/programming environments, because these languages are not so
1.48 anton 3552: strong in debugging and reuse.
1.21 crook 3553:
1.66 anton 3554: @c !! example
3555:
3556: Reference: @ref{Word Lists}.
1.21 crook 3557:
1.29 crook 3558: @c ******************************************************************
1.48 anton 3559: @node Introduction, Words, Tutorial, Top
1.29 crook 3560: @comment node-name, next, previous, up
3561: @chapter An Introduction to ANS Forth
3562: @cindex Forth - an introduction
1.21 crook 3563:
1.83 anton 3564: The difference of this chapter from the Tutorial (@pxref{Tutorial}) is
3565: that it is slower-paced in its examples, but uses them to dive deep into
3566: explaining Forth internals (not covered by the Tutorial). Apart from
3567: that, this chapter covers far less material. It is suitable for reading
3568: without using a computer.
3569:
1.29 crook 3570: The primary purpose of this manual is to document Gforth. However, since
3571: Forth is not a widely-known language and there is a lack of up-to-date
3572: teaching material, it seems worthwhile to provide some introductory
1.49 anton 3573: material. For other sources of Forth-related
3574: information, see @ref{Forth-related information}.
1.21 crook 3575:
1.29 crook 3576: The examples in this section should work on any ANS Forth; the
3577: output shown was produced using Gforth. Each example attempts to
3578: reproduce the exact output that Gforth produces. If you try out the
3579: examples (and you should), what you should type is shown @kbd{like this}
3580: and Gforth's response is shown @code{like this}. The single exception is
1.30 anton 3581: that, where the example shows @key{RET} it means that you should
1.29 crook 3582: press the ``carriage return'' key. Unfortunately, some output formats for
3583: this manual cannot show the difference between @kbd{this} and
3584: @code{this} which will make trying out the examples harder (but not
3585: impossible).
1.21 crook 3586:
1.29 crook 3587: Forth is an unusual language. It provides an interactive development
3588: environment which includes both an interpreter and compiler. Forth
3589: programming style encourages you to break a problem down into many
3590: @cindex factoring
3591: small fragments (@dfn{factoring}), and then to develop and test each
3592: fragment interactively. Forth advocates assert that breaking the
3593: edit-compile-test cycle used by conventional programming languages can
3594: lead to great productivity improvements.
1.21 crook 3595:
1.29 crook 3596: @menu
1.67 anton 3597: * Introducing the Text Interpreter::
3598: * Stacks and Postfix notation::
3599: * Your first definition::
3600: * How does that work?::
3601: * Forth is written in Forth::
3602: * Review - elements of a Forth system::
3603: * Where to go next::
3604: * Exercises::
1.29 crook 3605: @end menu
1.21 crook 3606:
1.29 crook 3607: @comment ----------------------------------------------
3608: @node Introducing the Text Interpreter, Stacks and Postfix notation, Introduction, Introduction
3609: @section Introducing the Text Interpreter
3610: @cindex text interpreter
3611: @cindex outer interpreter
1.21 crook 3612:
1.30 anton 3613: @c IMO this is too detailed and the pace is too slow for
3614: @c an introduction. If you know German, take a look at
3615: @c http://www.complang.tuwien.ac.at/anton/lvas/skriptum-stack.html
3616: @c to see how I do it - anton
3617:
1.44 crook 3618: @c nac-> Where I have accepted your comments 100% and modified the text
3619: @c accordingly, I have deleted your comments. Elsewhere I have added a
3620: @c response like this to attempt to rationalise what I have done. Of
3621: @c course, this is a very clumsy mechanism for something that would be
3622: @c done far more efficiently over a beer. Please delete any dialogue
3623: @c you consider closed.
3624:
1.29 crook 3625: When you invoke the Forth image, you will see a startup banner printed
3626: and nothing else (if you have Gforth installed on your system, try
1.30 anton 3627: invoking it now, by typing @kbd{gforth@key{RET}}). Forth is now running
1.29 crook 3628: its command line interpreter, which is called the @dfn{Text Interpreter}
3629: (also known as the @dfn{Outer Interpreter}). (You will learn a lot
1.49 anton 3630: about the text interpreter as you read through this chapter, for more
3631: detail @pxref{The Text Interpreter}).
1.21 crook 3632:
1.29 crook 3633: Although it's not obvious, Forth is actually waiting for your
1.30 anton 3634: input. Type a number and press the @key{RET} key:
1.21 crook 3635:
1.26 crook 3636: @example
1.30 anton 3637: @kbd{45@key{RET}} ok
1.26 crook 3638: @end example
1.21 crook 3639:
1.29 crook 3640: Rather than give you a prompt to invite you to input something, the text
3641: interpreter prints a status message @i{after} it has processed a line
3642: of input. The status message in this case (``@code{ ok}'' followed by
3643: carriage-return) indicates that the text interpreter was able to process
3644: all of your input successfully. Now type something illegal:
3645:
3646: @example
1.30 anton 3647: @kbd{qwer341@key{RET}}
1.29 crook 3648: :1: Undefined word
3649: qwer341
3650: ^^^^^^^
3651: $400D2BA8 Bounce
3652: $400DBDA8 no.extensions
3653: @end example
1.23 crook 3654:
1.29 crook 3655: The exact text, other than the ``Undefined word'' may differ slightly on
3656: your system, but the effect is the same; when the text interpreter
3657: detects an error, it discards any remaining text on a line, resets
1.49 anton 3658: certain internal state and prints an error message. For a detailed description of error messages see @ref{Error
3659: messages}.
1.23 crook 3660:
1.29 crook 3661: The text interpreter waits for you to press carriage-return, and then
3662: processes your input line. Starting at the beginning of the line, it
3663: breaks the line into groups of characters separated by spaces. For each
3664: group of characters in turn, it makes two attempts to do something:
1.23 crook 3665:
1.29 crook 3666: @itemize @bullet
3667: @item
1.44 crook 3668: @cindex name dictionary
1.29 crook 3669: It tries to treat it as a command. It does this by searching a @dfn{name
3670: dictionary}. If the group of characters matches an entry in the name
3671: dictionary, the name dictionary provides the text interpreter with
3672: information that allows the text interpreter perform some actions. In
3673: Forth jargon, we say that the group
3674: @cindex word
3675: @cindex definition
3676: @cindex execution token
3677: @cindex xt
3678: of characters names a @dfn{word}, that the dictionary search returns an
3679: @dfn{execution token (xt)} corresponding to the @dfn{definition} of the
3680: word, and that the text interpreter executes the xt. Often, the terms
3681: @dfn{word} and @dfn{definition} are used interchangeably.
3682: @item
3683: If the text interpreter fails to find a match in the name dictionary, it
3684: tries to treat the group of characters as a number in the current number
3685: base (when you start up Forth, the current number base is base 10). If
3686: the group of characters legitimately represents a number, the text
3687: interpreter pushes the number onto a stack (we'll learn more about that
3688: in the next section).
3689: @end itemize
1.23 crook 3690:
1.29 crook 3691: If the text interpreter is unable to do either of these things with any
3692: group of characters, it discards the group of characters and the rest of
3693: the line, then prints an error message. If the text interpreter reaches
3694: the end of the line without error, it prints the status message ``@code{ ok}''
3695: followed by carriage-return.
1.21 crook 3696:
1.29 crook 3697: This is the simplest command we can give to the text interpreter:
1.23 crook 3698:
3699: @example
1.30 anton 3700: @key{RET} ok
1.23 crook 3701: @end example
1.21 crook 3702:
1.29 crook 3703: The text interpreter did everything we asked it to do (nothing) without
3704: an error, so it said that everything is ``@code{ ok}''. Try a slightly longer
3705: command:
1.21 crook 3706:
1.23 crook 3707: @example
1.30 anton 3708: @kbd{12 dup fred dup@key{RET}}
1.29 crook 3709: :1: Undefined word
3710: 12 dup fred dup
3711: ^^^^
3712: $400D2BA8 Bounce
3713: $400DBDA8 no.extensions
1.23 crook 3714: @end example
1.21 crook 3715:
1.29 crook 3716: When you press the carriage-return key, the text interpreter starts to
3717: work its way along the line:
1.21 crook 3718:
1.29 crook 3719: @itemize @bullet
3720: @item
3721: When it gets to the space after the @code{2}, it takes the group of
3722: characters @code{12} and looks them up in the name
3723: dictionary@footnote{We can't tell if it found them or not, but assume
3724: for now that it did not}. There is no match for this group of characters
3725: in the name dictionary, so it tries to treat them as a number. It is
3726: able to do this successfully, so it puts the number, 12, ``on the stack''
3727: (whatever that means).
3728: @item
3729: The text interpreter resumes scanning the line and gets the next group
3730: of characters, @code{dup}. It looks it up in the name dictionary and
3731: (you'll have to take my word for this) finds it, and executes the word
3732: @code{dup} (whatever that means).
3733: @item
3734: Once again, the text interpreter resumes scanning the line and gets the
3735: group of characters @code{fred}. It looks them up in the name
3736: dictionary, but can't find them. It tries to treat them as a number, but
3737: they don't represent any legal number.
3738: @end itemize
1.21 crook 3739:
1.29 crook 3740: At this point, the text interpreter gives up and prints an error
3741: message. The error message shows exactly how far the text interpreter
3742: got in processing the line. In particular, it shows that the text
3743: interpreter made no attempt to do anything with the final character
3744: group, @code{dup}, even though we have good reason to believe that the
3745: text interpreter would have no problem looking that word up and
3746: executing it a second time.
1.21 crook 3747:
3748:
1.29 crook 3749: @comment ----------------------------------------------
3750: @node Stacks and Postfix notation, Your first definition, Introducing the Text Interpreter, Introduction
3751: @section Stacks, postfix notation and parameter passing
3752: @cindex text interpreter
3753: @cindex outer interpreter
1.21 crook 3754:
1.29 crook 3755: In procedural programming languages (like C and Pascal), the
3756: building-block of programs is the @dfn{function} or @dfn{procedure}. These
3757: functions or procedures are called with @dfn{explicit parameters}. For
3758: example, in C we might write:
1.21 crook 3759:
1.23 crook 3760: @example
1.29 crook 3761: total = total + new_volume(length,height,depth);
1.23 crook 3762: @end example
1.21 crook 3763:
1.23 crook 3764: @noindent
1.29 crook 3765: where new_volume is a function-call to another piece of code, and total,
3766: length, height and depth are all variables. length, height and depth are
3767: parameters to the function-call.
1.21 crook 3768:
1.29 crook 3769: In Forth, the equivalent of the function or procedure is the
3770: @dfn{definition} and parameters are implicitly passed between
3771: definitions using a shared stack that is visible to the
3772: programmer. Although Forth does support variables, the existence of the
3773: stack means that they are used far less often than in most other
3774: programming languages. When the text interpreter encounters a number, it
3775: will place (@dfn{push}) it on the stack. There are several stacks (the
1.30 anton 3776: actual number is implementation-dependent ...) and the particular stack
1.29 crook 3777: used for any operation is implied unambiguously by the operation being
3778: performed. The stack used for all integer operations is called the @dfn{data
3779: stack} and, since this is the stack used most commonly, references to
3780: ``the data stack'' are often abbreviated to ``the stack''.
1.21 crook 3781:
1.29 crook 3782: The stacks have a last-in, first-out (LIFO) organisation. If you type:
1.21 crook 3783:
1.23 crook 3784: @example
1.30 anton 3785: @kbd{1 2 3@key{RET}} ok
1.23 crook 3786: @end example
1.21 crook 3787:
1.29 crook 3788: Then this instructs the text interpreter to placed three numbers on the
3789: (data) stack. An analogy for the behaviour of the stack is to take a
3790: pack of playing cards and deal out the ace (1), 2 and 3 into a pile on
3791: the table. The 3 was the last card onto the pile (``last-in'') and if
3792: you take a card off the pile then, unless you're prepared to fiddle a
3793: bit, the card that you take off will be the 3 (``first-out''). The
3794: number that will be first-out of the stack is called the @dfn{top of
3795: stack}, which
3796: @cindex TOS definition
3797: is often abbreviated to @dfn{TOS}.
1.21 crook 3798:
1.29 crook 3799: To understand how parameters are passed in Forth, consider the
3800: behaviour of the definition @code{+} (pronounced ``plus''). You will not
3801: be surprised to learn that this definition performs addition. More
3802: precisely, it adds two number together and produces a result. Where does
3803: it get the two numbers from? It takes the top two numbers off the
3804: stack. Where does it place the result? On the stack. You can act-out the
3805: behaviour of @code{+} with your playing cards like this:
1.21 crook 3806:
3807: @itemize @bullet
3808: @item
1.29 crook 3809: Pick up two cards from the stack on the table
1.21 crook 3810: @item
1.29 crook 3811: Stare at them intently and ask yourself ``what @i{is} the sum of these two
3812: numbers''
1.21 crook 3813: @item
1.29 crook 3814: Decide that the answer is 5
1.21 crook 3815: @item
1.29 crook 3816: Shuffle the two cards back into the pack and find a 5
1.21 crook 3817: @item
1.29 crook 3818: Put a 5 on the remaining ace that's on the table.
1.21 crook 3819: @end itemize
3820:
1.29 crook 3821: If you don't have a pack of cards handy but you do have Forth running,
3822: you can use the definition @code{.s} to show the current state of the stack,
3823: without affecting the stack. Type:
1.21 crook 3824:
3825: @example
1.30 anton 3826: @kbd{clearstack 1 2 3@key{RET}} ok
3827: @kbd{.s@key{RET}} <3> 1 2 3 ok
1.23 crook 3828: @end example
3829:
1.29 crook 3830: The text interpreter looks up the word @code{clearstack} and executes
3831: it; it tidies up the stack and removes any entries that may have been
3832: left on it by earlier examples. The text interpreter pushes each of the
3833: three numbers in turn onto the stack. Finally, the text interpreter
3834: looks up the word @code{.s} and executes it. The effect of executing
3835: @code{.s} is to print the ``<3>'' (the total number of items on the stack)
3836: followed by a list of all the items on the stack; the item on the far
3837: right-hand side is the TOS.
1.21 crook 3838:
1.29 crook 3839: You can now type:
1.21 crook 3840:
1.29 crook 3841: @example
1.30 anton 3842: @kbd{+ .s@key{RET}} <2> 1 5 ok
1.29 crook 3843: @end example
1.21 crook 3844:
1.29 crook 3845: @noindent
3846: which is correct; there are now 2 items on the stack and the result of
3847: the addition is 5.
1.23 crook 3848:
1.29 crook 3849: If you're playing with cards, try doing a second addition: pick up the
3850: two cards, work out that their sum is 6, shuffle them into the pack,
3851: look for a 6 and place that on the table. You now have just one item on
3852: the stack. What happens if you try to do a third addition? Pick up the
3853: first card, pick up the second card -- ah! There is no second card. This
3854: is called a @dfn{stack underflow} and consitutes an error. If you try to
3855: do the same thing with Forth it will report an error (probably a Stack
3856: Underflow or an Invalid Memory Address error).
1.23 crook 3857:
1.29 crook 3858: The opposite situation to a stack underflow is a @dfn{stack overflow},
3859: which simply accepts that there is a finite amount of storage space
3860: reserved for the stack. To stretch the playing card analogy, if you had
3861: enough packs of cards and you piled the cards up on the table, you would
3862: eventually be unable to add another card; you'd hit the ceiling. Gforth
3863: allows you to set the maximum size of the stacks. In general, the only
3864: time that you will get a stack overflow is because a definition has a
3865: bug in it and is generating data on the stack uncontrollably.
1.23 crook 3866:
1.29 crook 3867: There's one final use for the playing card analogy. If you model your
3868: stack using a pack of playing cards, the maximum number of items on
3869: your stack will be 52 (I assume you didn't use the Joker). The maximum
3870: @i{value} of any item on the stack is 13 (the King). In fact, the only
3871: possible numbers are positive integer numbers 1 through 13; you can't
3872: have (for example) 0 or 27 or 3.52 or -2. If you change the way you
3873: think about some of the cards, you can accommodate different
3874: numbers. For example, you could think of the Jack as representing 0,
3875: the Queen as representing -1 and the King as representing -2. Your
1.45 crook 3876: @i{range} remains unchanged (you can still only represent a total of 13
1.29 crook 3877: numbers) but the numbers that you can represent are -2 through 10.
1.28 crook 3878:
1.29 crook 3879: In that analogy, the limit was the amount of information that a single
3880: stack entry could hold, and Forth has a similar limit. In Forth, the
3881: size of a stack entry is called a @dfn{cell}. The actual size of a cell is
3882: implementation dependent and affects the maximum value that a stack
3883: entry can hold. A Standard Forth provides a cell size of at least
3884: 16-bits, and most desktop systems use a cell size of 32-bits.
1.21 crook 3885:
1.29 crook 3886: Forth does not do any type checking for you, so you are free to
3887: manipulate and combine stack items in any way you wish. A convenient way
3888: of treating stack items is as 2's complement signed integers, and that
3889: is what Standard words like @code{+} do. Therefore you can type:
1.21 crook 3890:
1.29 crook 3891: @example
1.30 anton 3892: @kbd{-5 12 + .s@key{RET}} <1> 7 ok
1.29 crook 3893: @end example
1.21 crook 3894:
1.29 crook 3895: If you use numbers and definitions like @code{+} in order to turn Forth
3896: into a great big pocket calculator, you will realise that it's rather
3897: different from a normal calculator. Rather than typing 2 + 3 = you had
3898: to type 2 3 + (ignore the fact that you had to use @code{.s} to see the
3899: result). The terminology used to describe this difference is to say that
3900: your calculator uses @dfn{Infix Notation} (parameters and operators are
3901: mixed) whilst Forth uses @dfn{Postfix Notation} (parameters and
3902: operators are separate), also called @dfn{Reverse Polish Notation}.
1.21 crook 3903:
1.29 crook 3904: Whilst postfix notation might look confusing to begin with, it has
3905: several important advantages:
1.21 crook 3906:
1.23 crook 3907: @itemize @bullet
3908: @item
1.29 crook 3909: it is unambiguous
1.23 crook 3910: @item
1.29 crook 3911: it is more concise
1.23 crook 3912: @item
1.29 crook 3913: it fits naturally with a stack-based system
1.23 crook 3914: @end itemize
1.21 crook 3915:
1.29 crook 3916: To examine these claims in more detail, consider these sums:
1.21 crook 3917:
1.29 crook 3918: @example
3919: 6 + 5 * 4 =
3920: 4 * 5 + 6 =
3921: @end example
1.21 crook 3922:
1.29 crook 3923: If you're just learning maths or your maths is very rusty, you will
3924: probably come up with the answer 44 for the first and 26 for the
3925: second. If you are a bit of a whizz at maths you will remember the
3926: @i{convention} that multiplication takes precendence over addition, and
3927: you'd come up with the answer 26 both times. To explain the answer 26
3928: to someone who got the answer 44, you'd probably rewrite the first sum
3929: like this:
1.21 crook 3930:
1.29 crook 3931: @example
3932: 6 + (5 * 4) =
3933: @end example
1.21 crook 3934:
1.29 crook 3935: If what you really wanted was to perform the addition before the
3936: multiplication, you would have to use parentheses to force it.
1.21 crook 3937:
1.29 crook 3938: If you did the first two sums on a pocket calculator you would probably
3939: get the right answers, unless you were very cautious and entered them using
3940: these keystroke sequences:
1.21 crook 3941:
1.29 crook 3942: 6 + 5 = * 4 =
3943: 4 * 5 = + 6 =
1.21 crook 3944:
1.29 crook 3945: Postfix notation is unambiguous because the order that the operators
3946: are applied is always explicit; that also means that parentheses are
3947: never required. The operators are @i{active} (the act of quoting the
3948: operator makes the operation occur) which removes the need for ``=''.
1.28 crook 3949:
1.29 crook 3950: The sum 6 + 5 * 4 can be written (in postfix notation) in two
3951: equivalent ways:
1.26 crook 3952:
3953: @example
1.29 crook 3954: 6 5 4 * + or:
3955: 5 4 * 6 +
1.26 crook 3956: @end example
1.23 crook 3957:
1.29 crook 3958: An important thing that you should notice about this notation is that
3959: the @i{order} of the numbers does not change; if you want to subtract
3960: 2 from 10 you type @code{10 2 -}.
1.1 anton 3961:
1.29 crook 3962: The reason that Forth uses postfix notation is very simple to explain: it
3963: makes the implementation extremely simple, and it follows naturally from
3964: using the stack as a mechanism for passing parameters. Another way of
3965: thinking about this is to realise that all Forth definitions are
3966: @i{active}; they execute as they are encountered by the text
3967: interpreter. The result of this is that the syntax of Forth is trivially
3968: simple.
1.1 anton 3969:
3970:
3971:
1.29 crook 3972: @comment ----------------------------------------------
3973: @node Your first definition, How does that work?, Stacks and Postfix notation, Introduction
3974: @section Your first Forth definition
3975: @cindex first definition
1.1 anton 3976:
1.29 crook 3977: Until now, the examples we've seen have been trivial; we've just been
3978: using Forth as a bigger-than-pocket calculator. Also, each calculation
3979: we've shown has been a ``one-off'' -- to repeat it we'd need to type it in
3980: again@footnote{That's not quite true. If you press the up-arrow key on
3981: your keyboard you should be able to scroll back to any earlier command,
3982: edit it and re-enter it.} In this section we'll see how to add new
3983: words to Forth's vocabulary.
1.1 anton 3984:
1.29 crook 3985: The easiest way to create a new word is to use a @dfn{colon
3986: definition}. We'll define a few and try them out before worrying too
3987: much about how they work. Try typing in these examples; be careful to
3988: copy the spaces accurately:
1.1 anton 3989:
1.29 crook 3990: @example
3991: : add-two 2 + . ;
3992: : greet ." Hello and welcome" ;
3993: : demo 5 add-two ;
3994: @end example
1.1 anton 3995:
1.29 crook 3996: @noindent
3997: Now try them out:
1.1 anton 3998:
1.29 crook 3999: @example
1.30 anton 4000: @kbd{greet@key{RET}} Hello and welcome ok
4001: @kbd{greet greet@key{RET}} Hello and welcomeHello and welcome ok
4002: @kbd{4 add-two@key{RET}} 6 ok
4003: @kbd{demo@key{RET}} 7 ok
4004: @kbd{9 greet demo add-two@key{RET}} Hello and welcome7 11 ok
1.29 crook 4005: @end example
1.1 anton 4006:
1.29 crook 4007: The first new thing that we've introduced here is the pair of words
4008: @code{:} and @code{;}. These are used to start and terminate a new
4009: definition, respectively. The first word after the @code{:} is the name
4010: for the new definition.
1.1 anton 4011:
1.29 crook 4012: As you can see from the examples, a definition is built up of words that
4013: have already been defined; Forth makes no distinction between
4014: definitions that existed when you started the system up, and those that
4015: you define yourself.
1.1 anton 4016:
1.29 crook 4017: The examples also introduce the words @code{.} (dot), @code{."}
4018: (dot-quote) and @code{dup} (dewp). Dot takes the value from the top of
4019: the stack and displays it. It's like @code{.s} except that it only
4020: displays the top item of the stack and it is destructive; after it has
4021: executed, the number is no longer on the stack. There is always one
4022: space printed after the number, and no spaces before it. Dot-quote
4023: defines a string (a sequence of characters) that will be printed when
4024: the word is executed. The string can contain any printable characters
4025: except @code{"}. A @code{"} has a special function; it is not a Forth
4026: word but it acts as a delimiter (the way that delimiters work is
4027: described in the next section). Finally, @code{dup} duplicates the value
4028: at the top of the stack. Try typing @code{5 dup .s} to see what it does.
1.1 anton 4029:
1.29 crook 4030: We already know that the text interpreter searches through the
4031: dictionary to locate names. If you've followed the examples earlier, you
4032: will already have a definition called @code{add-two}. Lets try modifying
4033: it by typing in a new definition:
1.1 anton 4034:
1.29 crook 4035: @example
1.30 anton 4036: @kbd{: add-two dup . ." + 2 =" 2 + . ;@key{RET}} redefined add-two ok
1.29 crook 4037: @end example
1.5 anton 4038:
1.29 crook 4039: Forth recognised that we were defining a word that already exists, and
4040: printed a message to warn us of that fact. Let's try out the new
4041: definition:
1.5 anton 4042:
1.29 crook 4043: @example
1.30 anton 4044: @kbd{9 add-two@key{RET}} 9 + 2 =11 ok
1.29 crook 4045: @end example
1.1 anton 4046:
1.29 crook 4047: @noindent
4048: All that we've actually done here, though, is to create a new
4049: definition, with a particular name. The fact that there was already a
4050: definition with the same name did not make any difference to the way
4051: that the new definition was created (except that Forth printed a warning
4052: message). The old definition of add-two still exists (try @code{demo}
4053: again to see that this is true). Any new definition will use the new
4054: definition of @code{add-two}, but old definitions continue to use the
4055: version that already existed at the time that they were @code{compiled}.
1.1 anton 4056:
1.29 crook 4057: Before you go on to the next section, try defining and redefining some
4058: words of your own.
1.1 anton 4059:
1.29 crook 4060: @comment ----------------------------------------------
4061: @node How does that work?, Forth is written in Forth, Your first definition, Introduction
4062: @section How does that work?
4063: @cindex parsing words
1.1 anton 4064:
1.30 anton 4065: @c That's pretty deep (IMO way too deep) for an introduction. - anton
4066:
4067: @c Is it a good idea to talk about the interpretation semantics of a
4068: @c number? We don't have an xt to go along with it. - anton
4069:
4070: @c Now that I have eliminated execution semantics, I wonder if it would not
4071: @c be better to keep them (or add run-time semantics), to make it easier to
4072: @c explain what compilation semantics usually does. - anton
4073:
1.44 crook 4074: @c nac-> I removed the term ``default compilation sematics'' from the
4075: @c introductory chapter. Removing ``execution semantics'' was making
4076: @c everything simpler to explain, then I think the use of this term made
4077: @c everything more complex again. I replaced it with ``default
4078: @c semantics'' (which is used elsewhere in the manual) by which I mean
4079: @c ``a definition that has neither the immediate nor the compile-only
1.83 anton 4080: @c flag set''.
4081:
4082: @c anton: I have eliminated default semantics (except in one place where it
4083: @c means "default interpretation and compilation semantics"), because it
4084: @c makes no sense in the presence of combined words. I reverted to
4085: @c "execution semantics" where necessary.
4086:
4087: @c nac-> I reworded big chunks of the ``how does that work''
1.44 crook 4088: @c section (and, unusually for me, I think I even made it shorter!). See
4089: @c what you think -- I know I have not addressed your primary concern
4090: @c that it is too heavy-going for an introduction. From what I understood
4091: @c of your course notes it looks as though they might be a good framework.
4092: @c Things that I've tried to capture here are some things that came as a
4093: @c great revelation here when I first understood them. Also, I like the
4094: @c fact that a very simple code example shows up almost all of the issues
4095: @c that you need to understand to see how Forth works. That's unique and
4096: @c worthwhile to emphasise.
4097:
1.83 anton 4098: @c anton: I think it's a good idea to present the details, especially those
4099: @c that you found to be a revelation, and probably the tutorial tries to be
4100: @c too superficial and does not get some of the things across that make
4101: @c Forth special. I do believe that most of the time these things should
4102: @c be discussed at the end of a section or in separate sections instead of
4103: @c in the middle of a section (e.g., the stuff you added in "User-defined
4104: @c defining words" leads in a completely different direction from the rest
4105: @c of the section).
4106:
1.29 crook 4107: Now we're going to take another look at the definition of @code{add-two}
4108: from the previous section. From our knowledge of the way that the text
4109: interpreter works, we would have expected this result when we tried to
4110: define @code{add-two}:
1.21 crook 4111:
1.29 crook 4112: @example
1.44 crook 4113: @kbd{: add-two 2 + . ;@key{RET}}
1.29 crook 4114: ^^^^^^^
4115: Error: Undefined word
4116: @end example
1.28 crook 4117:
1.29 crook 4118: The reason that this didn't happen is bound up in the way that @code{:}
4119: works. The word @code{:} does two special things. The first special
4120: thing that it does prevents the text interpreter from ever seeing the
4121: characters @code{add-two}. The text interpreter uses a variable called
4122: @cindex modifying >IN
1.44 crook 4123: @code{>IN} (pronounced ``to-in'') to keep track of where it is in the
1.29 crook 4124: input line. When it encounters the word @code{:} it behaves in exactly
4125: the same way as it does for any other word; it looks it up in the name
4126: dictionary, finds its xt and executes it. When @code{:} executes, it
4127: looks at the input buffer, finds the word @code{add-two} and advances the
4128: value of @code{>IN} to point past it. It then does some other stuff
4129: associated with creating the new definition (including creating an entry
4130: for @code{add-two} in the name dictionary). When the execution of @code{:}
4131: completes, control returns to the text interpreter, which is oblivious
4132: to the fact that it has been tricked into ignoring part of the input
4133: line.
1.21 crook 4134:
1.29 crook 4135: @cindex parsing words
4136: Words like @code{:} -- words that advance the value of @code{>IN} and so
4137: prevent the text interpreter from acting on the whole of the input line
4138: -- are called @dfn{parsing words}.
1.21 crook 4139:
1.29 crook 4140: @cindex @code{state} - effect on the text interpreter
4141: @cindex text interpreter - effect of state
4142: The second special thing that @code{:} does is change the value of a
4143: variable called @code{state}, which affects the way that the text
4144: interpreter behaves. When Gforth starts up, @code{state} has the value
4145: 0, and the text interpreter is said to be @dfn{interpreting}. During a
4146: colon definition (started with @code{:}), @code{state} is set to -1 and
1.44 crook 4147: the text interpreter is said to be @dfn{compiling}.
4148:
4149: In this example, the text interpreter is compiling when it processes the
4150: string ``@code{2 + . ;}''. It still breaks the string down into
4151: character sequences in the same way. However, instead of pushing the
4152: number @code{2} onto the stack, it lays down (@dfn{compiles}) some magic
4153: into the definition of @code{add-two} that will make the number @code{2} get
4154: pushed onto the stack when @code{add-two} is @dfn{executed}. Similarly,
4155: the behaviours of @code{+} and @code{.} are also compiled into the
4156: definition.
4157:
4158: One category of words don't get compiled. These so-called @dfn{immediate
4159: words} get executed (performed @i{now}) regardless of whether the text
4160: interpreter is interpreting or compiling. The word @code{;} is an
4161: immediate word. Rather than being compiled into the definition, it
4162: executes. Its effect is to terminate the current definition, which
4163: includes changing the value of @code{state} back to 0.
4164:
4165: When you execute @code{add-two}, it has a @dfn{run-time effect} that is
4166: exactly the same as if you had typed @code{2 + . @key{RET}} outside of a
4167: definition.
1.28 crook 4168:
1.30 anton 4169: In Forth, every word or number can be described in terms of two
1.29 crook 4170: properties:
1.28 crook 4171:
4172: @itemize @bullet
4173: @item
1.29 crook 4174: @cindex interpretation semantics
1.44 crook 4175: Its @dfn{interpretation semantics} describe how it will behave when the
4176: text interpreter encounters it in @dfn{interpret} state. The
4177: interpretation semantics of a word are represented by an @dfn{execution
4178: token}.
1.28 crook 4179: @item
1.29 crook 4180: @cindex compilation semantics
1.44 crook 4181: Its @dfn{compilation semantics} describe how it will behave when the
4182: text interpreter encounters it in @dfn{compile} state. The compilation
4183: semantics of a word are represented in an implementation-dependent way;
4184: Gforth uses a @dfn{compilation token}.
1.29 crook 4185: @end itemize
4186:
4187: @noindent
4188: Numbers are always treated in a fixed way:
4189:
4190: @itemize @bullet
1.28 crook 4191: @item
1.44 crook 4192: When the number is @dfn{interpreted}, its behaviour is to push the
4193: number onto the stack.
1.28 crook 4194: @item
1.30 anton 4195: When the number is @dfn{compiled}, a piece of code is appended to the
4196: current definition that pushes the number when it runs. (In other words,
4197: the compilation semantics of a number are to postpone its interpretation
4198: semantics until the run-time of the definition that it is being compiled
4199: into.)
1.29 crook 4200: @end itemize
4201:
1.44 crook 4202: Words don't behave in such a regular way, but most have @i{default
4203: semantics} which means that they behave like this:
1.29 crook 4204:
4205: @itemize @bullet
1.28 crook 4206: @item
1.30 anton 4207: The @dfn{interpretation semantics} of the word are to do something useful.
4208: @item
1.29 crook 4209: The @dfn{compilation semantics} of the word are to append its
1.30 anton 4210: @dfn{interpretation semantics} to the current definition (so that its
4211: run-time behaviour is to do something useful).
1.28 crook 4212: @end itemize
4213:
1.30 anton 4214: @cindex immediate words
1.44 crook 4215: The actual behaviour of any particular word can be controlled by using
4216: the words @code{immediate} and @code{compile-only} when the word is
4217: defined. These words set flags in the name dictionary entry of the most
4218: recently defined word, and these flags are retrieved by the text
4219: interpreter when it finds the word in the name dictionary.
4220:
4221: A word that is marked as @dfn{immediate} has compilation semantics that
4222: are identical to its interpretation semantics. In other words, it
4223: behaves like this:
1.29 crook 4224:
4225: @itemize @bullet
4226: @item
1.30 anton 4227: The @dfn{interpretation semantics} of the word are to do something useful.
1.29 crook 4228: @item
1.30 anton 4229: The @dfn{compilation semantics} of the word are to do something useful
4230: (and actually the same thing); i.e., it is executed during compilation.
1.29 crook 4231: @end itemize
1.28 crook 4232:
1.44 crook 4233: Marking a word as @dfn{compile-only} prohibits the text interpreter from
4234: performing the interpretation semantics of the word directly; an attempt
4235: to do so will generate an error. It is never necessary to use
4236: @code{compile-only} (and it is not even part of ANS Forth, though it is
4237: provided by many implementations) but it is good etiquette to apply it
4238: to a word that will not behave correctly (and might have unexpected
4239: side-effects) in interpret state. For example, it is only legal to use
4240: the conditional word @code{IF} within a definition. If you forget this
4241: and try to use it elsewhere, the fact that (in Gforth) it is marked as
4242: @code{compile-only} allows the text interpreter to generate a helpful
4243: error message rather than subjecting you to the consequences of your
4244: folly.
4245:
1.29 crook 4246: This example shows the difference between an immediate and a
4247: non-immediate word:
1.28 crook 4248:
1.29 crook 4249: @example
4250: : show-state state @@ . ;
4251: : show-state-now show-state ; immediate
4252: : word1 show-state ;
4253: : word2 show-state-now ;
1.28 crook 4254: @end example
1.23 crook 4255:
1.29 crook 4256: The word @code{immediate} after the definition of @code{show-state-now}
4257: makes that word an immediate word. These definitions introduce a new
4258: word: @code{@@} (pronounced ``fetch''). This word fetches the value of a
4259: variable, and leaves it on the stack. Therefore, the behaviour of
4260: @code{show-state} is to print a number that represents the current value
4261: of @code{state}.
1.28 crook 4262:
1.29 crook 4263: When you execute @code{word1}, it prints the number 0, indicating that
4264: the system is interpreting. When the text interpreter compiled the
4265: definition of @code{word1}, it encountered @code{show-state} whose
1.30 anton 4266: compilation semantics are to append its interpretation semantics to the
1.29 crook 4267: current definition. When you execute @code{word1}, it performs the
1.30 anton 4268: interpretation semantics of @code{show-state}. At the time that @code{word1}
1.29 crook 4269: (and therefore @code{show-state}) are executed, the system is
4270: interpreting.
1.28 crook 4271:
1.30 anton 4272: When you pressed @key{RET} after entering the definition of @code{word2},
1.29 crook 4273: you should have seen the number -1 printed, followed by ``@code{
4274: ok}''. When the text interpreter compiled the definition of
4275: @code{word2}, it encountered @code{show-state-now}, an immediate word,
1.30 anton 4276: whose compilation semantics are therefore to perform its interpretation
1.29 crook 4277: semantics. It is executed straight away (even before the text
4278: interpreter has moved on to process another group of characters; the
4279: @code{;} in this example). The effect of executing it are to display the
4280: value of @code{state} @i{at the time that the definition of}
4281: @code{word2} @i{is being defined}. Printing -1 demonstrates that the
4282: system is compiling at this time. If you execute @code{word2} it does
4283: nothing at all.
1.28 crook 4284:
1.29 crook 4285: @cindex @code{."}, how it works
4286: Before leaving the subject of immediate words, consider the behaviour of
4287: @code{."} in the definition of @code{greet}, in the previous
4288: section. This word is both a parsing word and an immediate word. Notice
4289: that there is a space between @code{."} and the start of the text
4290: @code{Hello and welcome}, but that there is no space between the last
4291: letter of @code{welcome} and the @code{"} character. The reason for this
4292: is that @code{."} is a Forth word; it must have a space after it so that
4293: the text interpreter can identify it. The @code{"} is not a Forth word;
4294: it is a @dfn{delimiter}. The examples earlier show that, when the string
4295: is displayed, there is neither a space before the @code{H} nor after the
4296: @code{e}. Since @code{."} is an immediate word, it executes at the time
4297: that @code{greet} is defined. When it executes, its behaviour is to
4298: search forward in the input line looking for the delimiter. When it
4299: finds the delimiter, it updates @code{>IN} to point past the
4300: delimiter. It also compiles some magic code into the definition of
4301: @code{greet}; the xt of a run-time routine that prints a text string. It
4302: compiles the string @code{Hello and welcome} into memory so that it is
4303: available to be printed later. When the text interpreter gains control,
4304: the next word it finds in the input stream is @code{;} and so it
4305: terminates the definition of @code{greet}.
1.28 crook 4306:
4307:
4308: @comment ----------------------------------------------
1.29 crook 4309: @node Forth is written in Forth, Review - elements of a Forth system, How does that work?, Introduction
4310: @section Forth is written in Forth
4311: @cindex structure of Forth programs
4312:
4313: When you start up a Forth compiler, a large number of definitions
4314: already exist. In Forth, you develop a new application using bottom-up
4315: programming techniques to create new definitions that are defined in
4316: terms of existing definitions. As you create each definition you can
4317: test and debug it interactively.
4318:
4319: If you have tried out the examples in this section, you will probably
4320: have typed them in by hand; when you leave Gforth, your definitions will
4321: be lost. You can avoid this by using a text editor to enter Forth source
4322: code into a file, and then loading code from the file using
1.49 anton 4323: @code{include} (@pxref{Forth source files}). A Forth source file is
1.29 crook 4324: processed by the text interpreter, just as though you had typed it in by
4325: hand@footnote{Actually, there are some subtle differences -- see
4326: @ref{The Text Interpreter}.}.
4327:
4328: Gforth also supports the traditional Forth alternative to using text
1.49 anton 4329: files for program entry (@pxref{Blocks}).
1.28 crook 4330:
1.29 crook 4331: In common with many, if not most, Forth compilers, most of Gforth is
4332: actually written in Forth. All of the @file{.fs} files in the
4333: installation directory@footnote{For example,
1.30 anton 4334: @file{/usr/local/share/gforth...}} are Forth source files, which you can
1.29 crook 4335: study to see examples of Forth programming.
1.28 crook 4336:
1.29 crook 4337: Gforth maintains a history file that records every line that you type to
4338: the text interpreter. This file is preserved between sessions, and is
4339: used to provide a command-line recall facility. If you enter long
4340: definitions by hand, you can use a text editor to paste them out of the
4341: history file into a Forth source file for reuse at a later time
1.49 anton 4342: (for more information @pxref{Command-line editing}).
1.28 crook 4343:
4344:
4345: @comment ----------------------------------------------
1.29 crook 4346: @node Review - elements of a Forth system, Where to go next, Forth is written in Forth, Introduction
4347: @section Review - elements of a Forth system
4348: @cindex elements of a Forth system
1.28 crook 4349:
1.29 crook 4350: To summarise this chapter:
1.28 crook 4351:
4352: @itemize @bullet
4353: @item
1.29 crook 4354: Forth programs use @dfn{factoring} to break a problem down into small
4355: fragments called @dfn{words} or @dfn{definitions}.
4356: @item
4357: Forth program development is an interactive process.
4358: @item
4359: The main command loop that accepts input, and controls both
4360: interpretation and compilation, is called the @dfn{text interpreter}
4361: (also known as the @dfn{outer interpreter}).
4362: @item
4363: Forth has a very simple syntax, consisting of words and numbers
4364: separated by spaces or carriage-return characters. Any additional syntax
4365: is imposed by @dfn{parsing words}.
4366: @item
4367: Forth uses a stack to pass parameters between words. As a result, it
4368: uses postfix notation.
4369: @item
4370: To use a word that has previously been defined, the text interpreter
4371: searches for the word in the @dfn{name dictionary}.
4372: @item
1.30 anton 4373: Words have @dfn{interpretation semantics} and @dfn{compilation semantics}.
1.28 crook 4374: @item
1.29 crook 4375: The text interpreter uses the value of @code{state} to select between
4376: the use of the @dfn{interpretation semantics} and the @dfn{compilation
4377: semantics} of a word that it encounters.
1.28 crook 4378: @item
1.30 anton 4379: The relationship between the @dfn{interpretation semantics} and
4380: @dfn{compilation semantics} for a word
1.29 crook 4381: depend upon the way in which the word was defined (for example, whether
4382: it is an @dfn{immediate} word).
1.28 crook 4383: @item
1.29 crook 4384: Forth definitions can be implemented in Forth (called @dfn{high-level
4385: definitions}) or in some other way (usually a lower-level language and
4386: as a result often called @dfn{low-level definitions}, @dfn{code
4387: definitions} or @dfn{primitives}).
1.28 crook 4388: @item
1.29 crook 4389: Many Forth systems are implemented mainly in Forth.
1.28 crook 4390: @end itemize
4391:
4392:
1.29 crook 4393: @comment ----------------------------------------------
1.48 anton 4394: @node Where to go next, Exercises, Review - elements of a Forth system, Introduction
1.29 crook 4395: @section Where To Go Next
4396: @cindex where to go next
1.28 crook 4397:
1.29 crook 4398: Amazing as it may seem, if you have read (and understood) this far, you
4399: know almost all the fundamentals about the inner workings of a Forth
4400: system. You certainly know enough to be able to read and understand the
4401: rest of this manual and the ANS Forth document, to learn more about the
4402: facilities that Forth in general and Gforth in particular provide. Even
4403: scarier, you know almost enough to implement your own Forth system.
1.30 anton 4404: However, that's not a good idea just yet... better to try writing some
1.29 crook 4405: programs in Gforth.
1.28 crook 4406:
1.29 crook 4407: Forth has such a rich vocabulary that it can be hard to know where to
4408: start in learning it. This section suggests a few sets of words that are
4409: enough to write small but useful programs. Use the word index in this
4410: document to learn more about each word, then try it out and try to write
4411: small definitions using it. Start by experimenting with these words:
1.28 crook 4412:
4413: @itemize @bullet
4414: @item
1.29 crook 4415: Arithmetic: @code{+ - * / /MOD */ ABS INVERT}
4416: @item
4417: Comparison: @code{MIN MAX =}
4418: @item
4419: Logic: @code{AND OR XOR NOT}
4420: @item
4421: Stack manipulation: @code{DUP DROP SWAP OVER}
1.28 crook 4422: @item
1.29 crook 4423: Loops and decisions: @code{IF ELSE ENDIF ?DO I LOOP}
1.28 crook 4424: @item
1.29 crook 4425: Input/Output: @code{. ." EMIT CR KEY}
1.28 crook 4426: @item
1.29 crook 4427: Defining words: @code{: ; CREATE}
1.28 crook 4428: @item
1.29 crook 4429: Memory allocation words: @code{ALLOT ,}
1.28 crook 4430: @item
1.29 crook 4431: Tools: @code{SEE WORDS .S MARKER}
4432: @end itemize
4433:
4434: When you have mastered those, go on to:
4435:
4436: @itemize @bullet
1.28 crook 4437: @item
1.29 crook 4438: More defining words: @code{VARIABLE CONSTANT VALUE TO CREATE DOES>}
1.28 crook 4439: @item
1.29 crook 4440: Memory access: @code{@@ !}
1.28 crook 4441: @end itemize
1.23 crook 4442:
1.29 crook 4443: When you have mastered these, there's nothing for it but to read through
4444: the whole of this manual and find out what you've missed.
4445:
4446: @comment ----------------------------------------------
1.48 anton 4447: @node Exercises, , Where to go next, Introduction
1.29 crook 4448: @section Exercises
4449: @cindex exercises
4450:
4451: TODO: provide a set of programming excercises linked into the stuff done
4452: already and into other sections of the manual. Provide solutions to all
4453: the exercises in a .fs file in the distribution.
4454:
4455: @c Get some inspiration from Starting Forth and Kelly&Spies.
4456:
4457: @c excercises:
4458: @c 1. take inches and convert to feet and inches.
4459: @c 2. take temperature and convert from fahrenheight to celcius;
4460: @c may need to care about symmetric vs floored??
4461: @c 3. take input line and do character substitution
4462: @c to encipher or decipher
4463: @c 4. as above but work on a file for in and out
4464: @c 5. take input line and convert to pig-latin
4465: @c
4466: @c thing of sets of things to exercise then come up with
4467: @c problems that need those things.
4468:
4469:
1.26 crook 4470: @c ******************************************************************
1.29 crook 4471: @node Words, Error messages, Introduction, Top
1.1 anton 4472: @chapter Forth Words
1.26 crook 4473: @cindex words
1.1 anton 4474:
4475: @menu
4476: * Notation::
1.65 anton 4477: * Case insensitivity::
4478: * Comments::
4479: * Boolean Flags::
1.1 anton 4480: * Arithmetic::
4481: * Stack Manipulation::
1.5 anton 4482: * Memory::
1.1 anton 4483: * Control Structures::
4484: * Defining Words::
1.65 anton 4485: * Interpretation and Compilation Semantics::
1.47 crook 4486: * Tokens for Words::
1.81 anton 4487: * Compiling words::
1.65 anton 4488: * The Text Interpreter::
4489: * Word Lists::
4490: * Environmental Queries::
1.12 anton 4491: * Files::
4492: * Blocks::
4493: * Other I/O::
1.78 anton 4494: * Locals::
4495: * Structures::
4496: * Object-oriented Forth::
1.12 anton 4497: * Programming Tools::
4498: * Assembler and Code Words::
4499: * Threading Words::
1.65 anton 4500: * Passing Commands to the OS::
4501: * Keeping track of Time::
4502: * Miscellaneous Words::
1.1 anton 4503: @end menu
4504:
1.65 anton 4505: @node Notation, Case insensitivity, Words, Words
1.1 anton 4506: @section Notation
4507: @cindex notation of glossary entries
4508: @cindex format of glossary entries
4509: @cindex glossary notation format
4510: @cindex word glossary entry format
4511:
4512: The Forth words are described in this section in the glossary notation
1.67 anton 4513: that has become a de-facto standard for Forth texts:
1.1 anton 4514:
4515: @format
1.29 crook 4516: @i{word} @i{Stack effect} @i{wordset} @i{pronunciation}
1.1 anton 4517: @end format
1.29 crook 4518: @i{Description}
1.1 anton 4519:
4520: @table @var
4521: @item word
1.28 crook 4522: The name of the word.
1.1 anton 4523:
4524: @item Stack effect
4525: @cindex stack effect
1.29 crook 4526: The stack effect is written in the notation @code{@i{before} --
4527: @i{after}}, where @i{before} and @i{after} describe the top of
1.1 anton 4528: stack entries before and after the execution of the word. The rest of
4529: the stack is not touched by the word. The top of stack is rightmost,
4530: i.e., a stack sequence is written as it is typed in. Note that Gforth
4531: uses a separate floating point stack, but a unified stack
1.29 crook 4532: notation. Also, return stack effects are not shown in @i{stack
4533: effect}, but in @i{Description}. The name of a stack item describes
1.1 anton 4534: the type and/or the function of the item. See below for a discussion of
4535: the types.
4536:
4537: All words have two stack effects: A compile-time stack effect and a
4538: run-time stack effect. The compile-time stack-effect of most words is
1.29 crook 4539: @i{ -- }. If the compile-time stack-effect of a word deviates from
1.1 anton 4540: this standard behaviour, or the word does other unusual things at
4541: compile time, both stack effects are shown; otherwise only the run-time
4542: stack effect is shown.
4543:
4544: @cindex pronounciation of words
4545: @item pronunciation
4546: How the word is pronounced.
4547:
4548: @cindex wordset
1.67 anton 4549: @cindex environment wordset
1.1 anton 4550: @item wordset
1.21 crook 4551: The ANS Forth standard is divided into several word sets. A standard
4552: system need not support all of them. Therefore, in theory, the fewer
4553: word sets your program uses the more portable it will be. However, we
4554: suspect that most ANS Forth systems on personal machines will feature
1.26 crook 4555: all word sets. Words that are not defined in ANS Forth have
1.21 crook 4556: @code{gforth} or @code{gforth-internal} as word set. @code{gforth}
1.1 anton 4557: describes words that will work in future releases of Gforth;
4558: @code{gforth-internal} words are more volatile. Environmental query
4559: strings are also displayed like words; you can recognize them by the
1.21 crook 4560: @code{environment} in the word set field.
1.1 anton 4561:
4562: @item Description
4563: A description of the behaviour of the word.
4564: @end table
4565:
4566: @cindex types of stack items
4567: @cindex stack item types
4568: The type of a stack item is specified by the character(s) the name
4569: starts with:
4570:
4571: @table @code
4572: @item f
4573: @cindex @code{f}, stack item type
4574: Boolean flags, i.e. @code{false} or @code{true}.
4575: @item c
4576: @cindex @code{c}, stack item type
4577: Char
4578: @item w
4579: @cindex @code{w}, stack item type
4580: Cell, can contain an integer or an address
4581: @item n
4582: @cindex @code{n}, stack item type
4583: signed integer
4584: @item u
4585: @cindex @code{u}, stack item type
4586: unsigned integer
4587: @item d
4588: @cindex @code{d}, stack item type
4589: double sized signed integer
4590: @item ud
4591: @cindex @code{ud}, stack item type
4592: double sized unsigned integer
4593: @item r
4594: @cindex @code{r}, stack item type
4595: Float (on the FP stack)
1.21 crook 4596: @item a-
1.1 anton 4597: @cindex @code{a_}, stack item type
4598: Cell-aligned address
1.21 crook 4599: @item c-
1.1 anton 4600: @cindex @code{c_}, stack item type
4601: Char-aligned address (note that a Char may have two bytes in Windows NT)
1.21 crook 4602: @item f-
1.1 anton 4603: @cindex @code{f_}, stack item type
4604: Float-aligned address
1.21 crook 4605: @item df-
1.1 anton 4606: @cindex @code{df_}, stack item type
4607: Address aligned for IEEE double precision float
1.21 crook 4608: @item sf-
1.1 anton 4609: @cindex @code{sf_}, stack item type
4610: Address aligned for IEEE single precision float
4611: @item xt
4612: @cindex @code{xt}, stack item type
4613: Execution token, same size as Cell
4614: @item wid
4615: @cindex @code{wid}, stack item type
1.21 crook 4616: Word list ID, same size as Cell
1.68 anton 4617: @item ior, wior
4618: @cindex ior type description
4619: @cindex wior type description
4620: I/O result code, cell-sized. In Gforth, you can @code{throw} iors.
1.1 anton 4621: @item f83name
4622: @cindex @code{f83name}, stack item type
4623: Pointer to a name structure
4624: @item "
4625: @cindex @code{"}, stack item type
1.12 anton 4626: string in the input stream (not on the stack). The terminating character
4627: is a blank by default. If it is not a blank, it is shown in @code{<>}
1.1 anton 4628: quotes.
4629: @end table
4630:
1.65 anton 4631: @comment ----------------------------------------------
4632: @node Case insensitivity, Comments, Notation, Words
4633: @section Case insensitivity
4634: @cindex case sensitivity
4635: @cindex upper and lower case
4636:
4637: Gforth is case-insensitive; you can enter definitions and invoke
4638: Standard words using upper, lower or mixed case (however,
4639: @pxref{core-idef, Implementation-defined options, Implementation-defined
4640: options}).
4641:
4642: ANS Forth only @i{requires} implementations to recognise Standard words
4643: when they are typed entirely in upper case. Therefore, a Standard
4644: program must use upper case for all Standard words. You can use whatever
4645: case you like for words that you define, but in a Standard program you
4646: have to use the words in the same case that you defined them.
4647:
4648: Gforth supports case sensitivity through @code{table}s (case-sensitive
4649: wordlists, @pxref{Word Lists}).
4650:
4651: Two people have asked how to convert Gforth to be case-sensitive; while
4652: we think this is a bad idea, you can change all wordlists into tables
4653: like this:
4654:
4655: @example
4656: ' table-find forth-wordlist wordlist-map @ !
4657: @end example
4658:
4659: Note that you now have to type the predefined words in the same case
4660: that we defined them, which are varying. You may want to convert them
4661: to your favourite case before doing this operation (I won't explain how,
4662: because if you are even contemplating doing this, you'd better have
4663: enough knowledge of Forth systems to know this already).
4664:
4665: @node Comments, Boolean Flags, Case insensitivity, Words
1.21 crook 4666: @section Comments
1.26 crook 4667: @cindex comments
1.21 crook 4668:
1.29 crook 4669: Forth supports two styles of comment; the traditional @i{in-line} comment,
4670: @code{(} and its modern cousin, the @i{comment to end of line}; @code{\}.
1.21 crook 4671:
1.44 crook 4672:
1.23 crook 4673: doc-(
1.21 crook 4674: doc-\
1.23 crook 4675: doc-\G
1.21 crook 4676:
1.44 crook 4677:
1.21 crook 4678: @node Boolean Flags, Arithmetic, Comments, Words
4679: @section Boolean Flags
1.26 crook 4680: @cindex Boolean flags
1.21 crook 4681:
4682: A Boolean flag is cell-sized. A cell with all bits clear represents the
4683: flag @code{false} and a flag with all bits set represents the flag
1.26 crook 4684: @code{true}. Words that check a flag (for example, @code{IF}) will treat
1.29 crook 4685: a cell that has @i{any} bit set as @code{true}.
1.67 anton 4686: @c on and off to Memory?
4687: @c true and false to "Bitwise operations" or "Numeric comparison"?
1.44 crook 4688:
1.21 crook 4689: doc-true
4690: doc-false
1.29 crook 4691: doc-on
4692: doc-off
1.21 crook 4693:
1.44 crook 4694:
1.21 crook 4695: @node Arithmetic, Stack Manipulation, Boolean Flags, Words
1.1 anton 4696: @section Arithmetic
4697: @cindex arithmetic words
4698:
4699: @cindex division with potentially negative operands
4700: Forth arithmetic is not checked, i.e., you will not hear about integer
4701: overflow on addition or multiplication, you may hear about division by
4702: zero if you are lucky. The operator is written after the operands, but
4703: the operands are still in the original order. I.e., the infix @code{2-1}
4704: corresponds to @code{2 1 -}. Forth offers a variety of division
4705: operators. If you perform division with potentially negative operands,
4706: you do not want to use @code{/} or @code{/mod} with its undefined
4707: behaviour, but rather @code{fm/mod} or @code{sm/mod} (probably the
4708: former, @pxref{Mixed precision}).
1.26 crook 4709: @comment TODO discuss the different division forms and the std approach
1.1 anton 4710:
4711: @menu
4712: * Single precision::
1.67 anton 4713: * Double precision:: Double-cell integer arithmetic
1.1 anton 4714: * Bitwise operations::
1.67 anton 4715: * Numeric comparison::
1.29 crook 4716: * Mixed precision:: Operations with single and double-cell integers
1.1 anton 4717: * Floating Point::
4718: @end menu
4719:
1.67 anton 4720: @node Single precision, Double precision, Arithmetic, Arithmetic
1.1 anton 4721: @subsection Single precision
4722: @cindex single precision arithmetic words
4723:
1.67 anton 4724: @c !! cell undefined
4725:
4726: By default, numbers in Forth are single-precision integers that are one
1.26 crook 4727: cell in size. They can be signed or unsigned, depending upon how you
1.49 anton 4728: treat them. For the rules used by the text interpreter for recognising
4729: single-precision integers see @ref{Number Conversion}.
1.21 crook 4730:
1.67 anton 4731: These words are all defined for signed operands, but some of them also
4732: work for unsigned numbers: @code{+}, @code{1+}, @code{-}, @code{1-},
4733: @code{*}.
1.44 crook 4734:
1.1 anton 4735: doc-+
1.21 crook 4736: doc-1+
1.1 anton 4737: doc--
1.21 crook 4738: doc-1-
1.1 anton 4739: doc-*
4740: doc-/
4741: doc-mod
4742: doc-/mod
4743: doc-negate
4744: doc-abs
4745: doc-min
4746: doc-max
1.27 crook 4747: doc-floored
1.1 anton 4748:
1.44 crook 4749:
1.67 anton 4750: @node Double precision, Bitwise operations, Single precision, Arithmetic
1.21 crook 4751: @subsection Double precision
4752: @cindex double precision arithmetic words
4753:
1.49 anton 4754: For the rules used by the text interpreter for
4755: recognising double-precision integers, see @ref{Number Conversion}.
1.21 crook 4756:
4757: A double precision number is represented by a cell pair, with the most
1.67 anton 4758: significant cell at the TOS. It is trivial to convert an unsigned single
4759: to a double: simply push a @code{0} onto the TOS. Since numbers are
4760: represented by Gforth using 2's complement arithmetic, converting a
4761: signed single to a (signed) double requires sign-extension across the
4762: most significant cell. This can be achieved using @code{s>d}. The moral
4763: of the story is that you cannot convert a number without knowing whether
4764: it represents an unsigned or a signed number.
1.21 crook 4765:
1.67 anton 4766: These words are all defined for signed operands, but some of them also
4767: work for unsigned numbers: @code{d+}, @code{d-}.
1.44 crook 4768:
1.21 crook 4769: doc-s>d
1.67 anton 4770: doc-d>s
1.21 crook 4771: doc-d+
4772: doc-d-
4773: doc-dnegate
4774: doc-dabs
4775: doc-dmin
4776: doc-dmax
4777:
1.44 crook 4778:
1.67 anton 4779: @node Bitwise operations, Numeric comparison, Double precision, Arithmetic
4780: @subsection Bitwise operations
4781: @cindex bitwise operation words
4782:
4783:
4784: doc-and
4785: doc-or
4786: doc-xor
4787: doc-invert
4788: doc-lshift
4789: doc-rshift
4790: doc-2*
4791: doc-d2*
4792: doc-2/
4793: doc-d2/
4794:
4795:
4796: @node Numeric comparison, Mixed precision, Bitwise operations, Arithmetic
1.21 crook 4797: @subsection Numeric comparison
4798: @cindex numeric comparison words
4799:
1.67 anton 4800: Note that the words that compare for equality (@code{= <> 0= 0<> d= d<>
4801: d0= d0<>}) work for for both signed and unsigned numbers.
1.44 crook 4802:
1.28 crook 4803: doc-<
4804: doc-<=
4805: doc-<>
4806: doc-=
4807: doc->
4808: doc->=
4809:
1.21 crook 4810: doc-0<
1.23 crook 4811: doc-0<=
1.21 crook 4812: doc-0<>
4813: doc-0=
1.23 crook 4814: doc-0>
4815: doc-0>=
1.28 crook 4816:
4817: doc-u<
4818: doc-u<=
1.44 crook 4819: @c u<> and u= exist but are the same as <> and =
1.31 anton 4820: @c doc-u<>
4821: @c doc-u=
1.28 crook 4822: doc-u>
4823: doc-u>=
4824:
4825: doc-within
4826:
4827: doc-d<
4828: doc-d<=
4829: doc-d<>
4830: doc-d=
4831: doc-d>
4832: doc-d>=
1.23 crook 4833:
1.21 crook 4834: doc-d0<
1.23 crook 4835: doc-d0<=
4836: doc-d0<>
1.21 crook 4837: doc-d0=
1.23 crook 4838: doc-d0>
4839: doc-d0>=
4840:
1.21 crook 4841: doc-du<
1.28 crook 4842: doc-du<=
1.44 crook 4843: @c du<> and du= exist but are the same as d<> and d=
1.31 anton 4844: @c doc-du<>
4845: @c doc-du=
1.28 crook 4846: doc-du>
4847: doc-du>=
1.1 anton 4848:
1.44 crook 4849:
1.21 crook 4850: @node Mixed precision, Floating Point, Numeric comparison, Arithmetic
1.1 anton 4851: @subsection Mixed precision
4852: @cindex mixed precision arithmetic words
4853:
1.44 crook 4854:
1.1 anton 4855: doc-m+
4856: doc-*/
4857: doc-*/mod
4858: doc-m*
4859: doc-um*
4860: doc-m*/
4861: doc-um/mod
4862: doc-fm/mod
4863: doc-sm/rem
4864:
1.44 crook 4865:
1.21 crook 4866: @node Floating Point, , Mixed precision, Arithmetic
1.1 anton 4867: @subsection Floating Point
4868: @cindex floating point arithmetic words
4869:
1.49 anton 4870: For the rules used by the text interpreter for
4871: recognising floating-point numbers see @ref{Number Conversion}.
1.1 anton 4872:
1.67 anton 4873: Gforth has a separate floating point stack, but the documentation uses
4874: the unified notation.@footnote{It's easy to generate the separate
4875: notation from that by just separating the floating-point numbers out:
4876: e.g. @code{( n r1 u r2 -- r3 )} becomes @code{( n u -- ) ( F: r1 r2 --
4877: r3 )}.}
1.1 anton 4878:
4879: @cindex floating-point arithmetic, pitfalls
4880: Floating point numbers have a number of unpleasant surprises for the
4881: unwary (e.g., floating point addition is not associative) and even a few
4882: for the wary. You should not use them unless you know what you are doing
4883: or you don't care that the results you get are totally bogus. If you
4884: want to learn about the problems of floating point numbers (and how to
1.66 anton 4885: avoid them), you might start with @cite{David Goldberg,
4886: @uref{http://www.validgh.com/goldberg/paper.ps,What Every Computer
4887: Scientist Should Know About Floating-Point Arithmetic}, ACM Computing
4888: Surveys 23(1):5@minus{}48, March 1991}.
1.1 anton 4889:
1.44 crook 4890:
1.21 crook 4891: doc-d>f
4892: doc-f>d
1.1 anton 4893: doc-f+
4894: doc-f-
4895: doc-f*
4896: doc-f/
4897: doc-fnegate
4898: doc-fabs
4899: doc-fmax
4900: doc-fmin
4901: doc-floor
4902: doc-fround
4903: doc-f**
4904: doc-fsqrt
4905: doc-fexp
4906: doc-fexpm1
4907: doc-fln
4908: doc-flnp1
4909: doc-flog
4910: doc-falog
1.32 anton 4911: doc-f2*
4912: doc-f2/
4913: doc-1/f
4914: doc-precision
4915: doc-set-precision
4916:
4917: @cindex angles in trigonometric operations
4918: @cindex trigonometric operations
4919: Angles in floating point operations are given in radians (a full circle
4920: has 2 pi radians).
4921:
1.1 anton 4922: doc-fsin
4923: doc-fcos
4924: doc-fsincos
4925: doc-ftan
4926: doc-fasin
4927: doc-facos
4928: doc-fatan
4929: doc-fatan2
4930: doc-fsinh
4931: doc-fcosh
4932: doc-ftanh
4933: doc-fasinh
4934: doc-facosh
4935: doc-fatanh
1.21 crook 4936: doc-pi
1.28 crook 4937:
1.32 anton 4938: @cindex equality of floats
4939: @cindex floating-point comparisons
1.31 anton 4940: One particular problem with floating-point arithmetic is that comparison
4941: for equality often fails when you would expect it to succeed. For this
4942: reason approximate equality is often preferred (but you still have to
1.67 anton 4943: know what you are doing). Also note that IEEE NaNs may compare
1.68 anton 4944: differently from what you might expect. The comparison words are:
1.31 anton 4945:
4946: doc-f~rel
4947: doc-f~abs
1.68 anton 4948: doc-f~
1.31 anton 4949: doc-f=
4950: doc-f<>
4951:
4952: doc-f<
4953: doc-f<=
4954: doc-f>
4955: doc-f>=
4956:
1.21 crook 4957: doc-f0<
1.28 crook 4958: doc-f0<=
4959: doc-f0<>
1.21 crook 4960: doc-f0=
1.28 crook 4961: doc-f0>
4962: doc-f0>=
4963:
1.1 anton 4964:
4965: @node Stack Manipulation, Memory, Arithmetic, Words
4966: @section Stack Manipulation
4967: @cindex stack manipulation words
4968:
4969: @cindex floating-point stack in the standard
1.21 crook 4970: Gforth maintains a number of separate stacks:
4971:
1.29 crook 4972: @cindex data stack
4973: @cindex parameter stack
1.21 crook 4974: @itemize @bullet
4975: @item
1.29 crook 4976: A data stack (also known as the @dfn{parameter stack}) -- for
4977: characters, cells, addresses, and double cells.
1.21 crook 4978:
1.29 crook 4979: @cindex floating-point stack
1.21 crook 4980: @item
1.44 crook 4981: A floating point stack -- for holding floating point (FP) numbers.
1.21 crook 4982:
1.29 crook 4983: @cindex return stack
1.21 crook 4984: @item
1.44 crook 4985: A return stack -- for holding the return addresses of colon
1.32 anton 4986: definitions and other (non-FP) data.
1.21 crook 4987:
1.29 crook 4988: @cindex locals stack
1.21 crook 4989: @item
1.44 crook 4990: A locals stack -- for holding local variables.
1.21 crook 4991: @end itemize
4992:
1.1 anton 4993: @menu
4994: * Data stack::
4995: * Floating point stack::
4996: * Return stack::
4997: * Locals stack::
4998: * Stack pointer manipulation::
4999: @end menu
5000:
5001: @node Data stack, Floating point stack, Stack Manipulation, Stack Manipulation
5002: @subsection Data stack
5003: @cindex data stack manipulation words
5004: @cindex stack manipulations words, data stack
5005:
1.44 crook 5006:
1.1 anton 5007: doc-drop
5008: doc-nip
5009: doc-dup
5010: doc-over
5011: doc-tuck
5012: doc-swap
1.21 crook 5013: doc-pick
1.1 anton 5014: doc-rot
5015: doc--rot
5016: doc-?dup
5017: doc-roll
5018: doc-2drop
5019: doc-2nip
5020: doc-2dup
5021: doc-2over
5022: doc-2tuck
5023: doc-2swap
5024: doc-2rot
5025:
1.44 crook 5026:
1.1 anton 5027: @node Floating point stack, Return stack, Data stack, Stack Manipulation
5028: @subsection Floating point stack
5029: @cindex floating-point stack manipulation words
5030: @cindex stack manipulation words, floating-point stack
5031:
1.32 anton 5032: Whilst every sane Forth has a separate floating-point stack, it is not
5033: strictly required; an ANS Forth system could theoretically keep
5034: floating-point numbers on the data stack. As an additional difficulty,
5035: you don't know how many cells a floating-point number takes. It is
5036: reportedly possible to write words in a way that they work also for a
5037: unified stack model, but we do not recommend trying it. Instead, just
5038: say that your program has an environmental dependency on a separate
5039: floating-point stack.
5040:
5041: doc-floating-stack
5042:
1.1 anton 5043: doc-fdrop
5044: doc-fnip
5045: doc-fdup
5046: doc-fover
5047: doc-ftuck
5048: doc-fswap
1.21 crook 5049: doc-fpick
1.1 anton 5050: doc-frot
5051:
1.44 crook 5052:
1.1 anton 5053: @node Return stack, Locals stack, Floating point stack, Stack Manipulation
5054: @subsection Return stack
5055: @cindex return stack manipulation words
5056: @cindex stack manipulation words, return stack
5057:
1.32 anton 5058: @cindex return stack and locals
5059: @cindex locals and return stack
5060: A Forth system is allowed to keep local variables on the
5061: return stack. This is reasonable, as local variables usually eliminate
5062: the need to use the return stack explicitly. So, if you want to produce
5063: a standard compliant program and you are using local variables in a
5064: word, forget about return stack manipulations in that word (refer to the
5065: standard document for the exact rules).
5066:
1.1 anton 5067: doc->r
5068: doc-r>
5069: doc-r@
5070: doc-rdrop
5071: doc-2>r
5072: doc-2r>
5073: doc-2r@
5074: doc-2rdrop
5075:
1.44 crook 5076:
1.1 anton 5077: @node Locals stack, Stack pointer manipulation, Return stack, Stack Manipulation
5078: @subsection Locals stack
5079:
1.78 anton 5080: Gforth uses an extra locals stack. It is described, along with the
5081: reasons for its existence, in @ref{Locals implementation}.
1.21 crook 5082:
1.1 anton 5083: @node Stack pointer manipulation, , Locals stack, Stack Manipulation
5084: @subsection Stack pointer manipulation
5085: @cindex stack pointer manipulation words
5086:
1.44 crook 5087: @c removed s0 r0 l0 -- they are obsolete aliases for sp0 rp0 lp0
1.21 crook 5088: doc-sp0
1.1 anton 5089: doc-sp@
5090: doc-sp!
1.21 crook 5091: doc-fp0
1.1 anton 5092: doc-fp@
5093: doc-fp!
1.21 crook 5094: doc-rp0
1.1 anton 5095: doc-rp@
5096: doc-rp!
1.21 crook 5097: doc-lp0
1.1 anton 5098: doc-lp@
5099: doc-lp!
5100:
1.44 crook 5101:
1.1 anton 5102: @node Memory, Control Structures, Stack Manipulation, Words
5103: @section Memory
1.26 crook 5104: @cindex memory words
1.1 anton 5105:
1.32 anton 5106: @menu
5107: * Memory model::
5108: * Dictionary allocation::
5109: * Heap Allocation::
5110: * Memory Access::
5111: * Address arithmetic::
5112: * Memory Blocks::
5113: @end menu
5114:
1.67 anton 5115: In addition to the standard Forth memory allocation words, there is also
5116: a @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
5117: garbage collector}.
5118:
1.32 anton 5119: @node Memory model, Dictionary allocation, Memory, Memory
5120: @subsection ANS Forth and Gforth memory models
5121:
5122: @c The ANS Forth description is a mess (e.g., is the heap part of
5123: @c the dictionary?), so let's not stick to closely with it.
5124:
1.67 anton 5125: ANS Forth considers a Forth system as consisting of several address
5126: spaces, of which only @dfn{data space} is managed and accessible with
5127: the memory words. Memory not necessarily in data space includes the
5128: stacks, the code (called code space) and the headers (called name
5129: space). In Gforth everything is in data space, but the code for the
5130: primitives is usually read-only.
1.32 anton 5131:
5132: Data space is divided into a number of areas: The (data space portion of
5133: the) dictionary@footnote{Sometimes, the term @dfn{dictionary} is used to
5134: refer to the search data structure embodied in word lists and headers,
5135: because it is used for looking up names, just as you would in a
5136: conventional dictionary.}, the heap, and a number of system-allocated
5137: buffers.
5138:
1.68 anton 5139: @cindex address arithmetic restrictions, ANS vs. Gforth
5140: @cindex contiguous regions, ANS vs. Gforth
1.32 anton 5141: In ANS Forth data space is also divided into contiguous regions. You
5142: can only use address arithmetic within a contiguous region, not between
5143: them. Usually each allocation gives you one contiguous region, but the
1.33 anton 5144: dictionary allocation words have additional rules (@pxref{Dictionary
1.32 anton 5145: allocation}).
5146:
5147: Gforth provides one big address space, and address arithmetic can be
5148: performed between any addresses. However, in the dictionary headers or
5149: code are interleaved with data, so almost the only contiguous data space
5150: regions there are those described by ANS Forth as contiguous; but you
5151: can be sure that the dictionary is allocated towards increasing
5152: addresses even between contiguous regions. The memory order of
5153: allocations in the heap is platform-dependent (and possibly different
5154: from one run to the next).
5155:
1.27 crook 5156:
1.32 anton 5157: @node Dictionary allocation, Heap Allocation, Memory model, Memory
5158: @subsection Dictionary allocation
1.27 crook 5159: @cindex reserving data space
5160: @cindex data space - reserving some
5161:
1.32 anton 5162: Dictionary allocation is a stack-oriented allocation scheme, i.e., if
5163: you want to deallocate X, you also deallocate everything
5164: allocated after X.
5165:
1.68 anton 5166: @cindex contiguous regions in dictionary allocation
1.32 anton 5167: The allocations using the words below are contiguous and grow the region
5168: towards increasing addresses. Other words that allocate dictionary
5169: memory of any kind (i.e., defining words including @code{:noname}) end
5170: the contiguous region and start a new one.
5171:
5172: In ANS Forth only @code{create}d words are guaranteed to produce an
5173: address that is the start of the following contiguous region. In
5174: particular, the cell allocated by @code{variable} is not guaranteed to
5175: be contiguous with following @code{allot}ed memory.
5176:
5177: You can deallocate memory by using @code{allot} with a negative argument
5178: (with some restrictions, see @code{allot}). For larger deallocations use
5179: @code{marker}.
1.27 crook 5180:
1.29 crook 5181:
1.27 crook 5182: doc-here
5183: doc-unused
5184: doc-allot
5185: doc-c,
1.29 crook 5186: doc-f,
1.27 crook 5187: doc-,
5188: doc-2,
5189:
1.32 anton 5190: Memory accesses have to be aligned (@pxref{Address arithmetic}). So of
5191: course you should allocate memory in an aligned way, too. I.e., before
5192: allocating allocating a cell, @code{here} must be cell-aligned, etc.
5193: The words below align @code{here} if it is not already. Basically it is
5194: only already aligned for a type, if the last allocation was a multiple
5195: of the size of this type and if @code{here} was aligned for this type
5196: before.
5197:
5198: After freshly @code{create}ing a word, @code{here} is @code{align}ed in
5199: ANS Forth (@code{maxalign}ed in Gforth).
5200:
5201: doc-align
5202: doc-falign
5203: doc-sfalign
5204: doc-dfalign
5205: doc-maxalign
5206: doc-cfalign
5207:
5208:
5209: @node Heap Allocation, Memory Access, Dictionary allocation, Memory
5210: @subsection Heap allocation
5211: @cindex heap allocation
5212: @cindex dynamic allocation of memory
5213: @cindex memory-allocation word set
5214:
1.68 anton 5215: @cindex contiguous regions and heap allocation
1.32 anton 5216: Heap allocation supports deallocation of allocated memory in any
5217: order. Dictionary allocation is not affected by it (i.e., it does not
5218: end a contiguous region). In Gforth, these words are implemented using
5219: the standard C library calls malloc(), free() and resize().
5220:
1.68 anton 5221: The memory region produced by one invocation of @code{allocate} or
5222: @code{resize} is internally contiguous. There is no contiguity between
5223: such a region and any other region (including others allocated from the
5224: heap).
5225:
1.32 anton 5226: doc-allocate
5227: doc-free
5228: doc-resize
5229:
1.27 crook 5230:
1.32 anton 5231: @node Memory Access, Address arithmetic, Heap Allocation, Memory
1.1 anton 5232: @subsection Memory Access
5233: @cindex memory access words
5234:
5235: doc-@
5236: doc-!
5237: doc-+!
5238: doc-c@
5239: doc-c!
5240: doc-2@
5241: doc-2!
5242: doc-f@
5243: doc-f!
5244: doc-sf@
5245: doc-sf!
5246: doc-df@
5247: doc-df!
5248:
1.68 anton 5249:
1.32 anton 5250: @node Address arithmetic, Memory Blocks, Memory Access, Memory
5251: @subsection Address arithmetic
1.1 anton 5252: @cindex address arithmetic words
5253:
1.67 anton 5254: Address arithmetic is the foundation on which you can build data
5255: structures like arrays, records (@pxref{Structures}) and objects
5256: (@pxref{Object-oriented Forth}).
1.32 anton 5257:
1.68 anton 5258: @cindex address unit
5259: @cindex au (address unit)
1.1 anton 5260: ANS Forth does not specify the sizes of the data types. Instead, it
5261: offers a number of words for computing sizes and doing address
1.29 crook 5262: arithmetic. Address arithmetic is performed in terms of address units
5263: (aus); on most systems the address unit is one byte. Note that a
5264: character may have more than one au, so @code{chars} is no noop (on
1.68 anton 5265: platforms where it is a noop, it compiles to nothing).
1.1 anton 5266:
1.67 anton 5267: The basic address arithmetic words are @code{+} and @code{-}. E.g., if
5268: you have the address of a cell, perform @code{1 cells +}, and you will
5269: have the address of the next cell.
5270:
1.68 anton 5271: @cindex contiguous regions and address arithmetic
1.67 anton 5272: In ANS Forth you can perform address arithmetic only within a contiguous
5273: region, i.e., if you have an address into one region, you can only add
5274: and subtract such that the result is still within the region; you can
5275: only subtract or compare addresses from within the same contiguous
5276: region. Reasons: several contiguous regions can be arranged in memory
5277: in any way; on segmented systems addresses may have unusual
5278: representations, such that address arithmetic only works within a
5279: region. Gforth provides a few more guarantees (linear address space,
5280: dictionary grows upwards), but in general I have found it easy to stay
5281: within contiguous regions (exception: computing and comparing to the
5282: address just beyond the end of an array).
5283:
1.1 anton 5284: @cindex alignment of addresses for types
5285: ANS Forth also defines words for aligning addresses for specific
5286: types. Many computers require that accesses to specific data types
5287: must only occur at specific addresses; e.g., that cells may only be
5288: accessed at addresses divisible by 4. Even if a machine allows unaligned
5289: accesses, it can usually perform aligned accesses faster.
5290:
5291: For the performance-conscious: alignment operations are usually only
5292: necessary during the definition of a data structure, not during the
5293: (more frequent) accesses to it.
5294:
5295: ANS Forth defines no words for character-aligning addresses. This is not
5296: an oversight, but reflects the fact that addresses that are not
5297: char-aligned have no use in the standard and therefore will not be
5298: created.
5299:
5300: @cindex @code{CREATE} and alignment
1.29 crook 5301: ANS Forth guarantees that addresses returned by @code{CREATE}d words
1.1 anton 5302: are cell-aligned; in addition, Gforth guarantees that these addresses
5303: are aligned for all purposes.
5304:
1.26 crook 5305: Note that the ANS Forth word @code{char} has nothing to do with address
5306: arithmetic.
1.1 anton 5307:
1.44 crook 5308:
1.1 anton 5309: doc-chars
5310: doc-char+
5311: doc-cells
5312: doc-cell+
5313: doc-cell
5314: doc-aligned
5315: doc-floats
5316: doc-float+
5317: doc-float
5318: doc-faligned
5319: doc-sfloats
5320: doc-sfloat+
5321: doc-sfaligned
5322: doc-dfloats
5323: doc-dfloat+
5324: doc-dfaligned
5325: doc-maxaligned
5326: doc-cfaligned
5327: doc-address-unit-bits
5328:
1.44 crook 5329:
1.32 anton 5330: @node Memory Blocks, , Address arithmetic, Memory
1.1 anton 5331: @subsection Memory Blocks
5332: @cindex memory block words
1.27 crook 5333: @cindex character strings - moving and copying
5334:
1.49 anton 5335: Memory blocks often represent character strings; For ways of storing
5336: character strings in memory see @ref{String Formats}. For other
5337: string-processing words see @ref{Displaying characters and strings}.
1.1 anton 5338:
1.67 anton 5339: A few of these words work on address unit blocks. In that case, you
5340: usually have to insert @code{CHARS} before the word when working on
5341: character strings. Most words work on character blocks, and expect a
5342: char-aligned address.
5343:
5344: When copying characters between overlapping memory regions, use
5345: @code{chars move} or choose carefully between @code{cmove} and
5346: @code{cmove>}.
1.44 crook 5347:
1.1 anton 5348: doc-move
5349: doc-erase
5350: doc-cmove
5351: doc-cmove>
5352: doc-fill
5353: doc-blank
1.21 crook 5354: doc-compare
5355: doc-search
1.27 crook 5356: doc--trailing
5357: doc-/string
1.82 anton 5358: doc-bounds
1.44 crook 5359:
1.27 crook 5360: @comment TODO examples
5361:
1.1 anton 5362:
1.26 crook 5363: @node Control Structures, Defining Words, Memory, Words
1.1 anton 5364: @section Control Structures
5365: @cindex control structures
5366:
1.33 anton 5367: Control structures in Forth cannot be used interpretively, only in a
5368: colon definition@footnote{To be precise, they have no interpretation
5369: semantics (@pxref{Interpretation and Compilation Semantics}).}. We do
5370: not like this limitation, but have not seen a satisfying way around it
5371: yet, although many schemes have been proposed.
1.1 anton 5372:
5373: @menu
1.33 anton 5374: * Selection:: IF ... ELSE ... ENDIF
5375: * Simple Loops:: BEGIN ...
1.29 crook 5376: * Counted Loops:: DO
1.67 anton 5377: * Arbitrary control structures::
5378: * Calls and returns::
1.1 anton 5379: * Exception Handling::
5380: @end menu
5381:
5382: @node Selection, Simple Loops, Control Structures, Control Structures
5383: @subsection Selection
5384: @cindex selection control structures
5385: @cindex control structures for selection
5386:
5387: @cindex @code{IF} control structure
5388: @example
1.29 crook 5389: @i{flag}
1.1 anton 5390: IF
1.29 crook 5391: @i{code}
1.1 anton 5392: ENDIF
5393: @end example
1.21 crook 5394: @noindent
1.33 anton 5395:
1.44 crook 5396: If @i{flag} is non-zero (as far as @code{IF} etc. are concerned, a cell
5397: with any bit set represents truth) @i{code} is executed.
1.33 anton 5398:
1.1 anton 5399: @example
1.29 crook 5400: @i{flag}
1.1 anton 5401: IF
1.29 crook 5402: @i{code1}
1.1 anton 5403: ELSE
1.29 crook 5404: @i{code2}
1.1 anton 5405: ENDIF
5406: @end example
5407:
1.44 crook 5408: If @var{flag} is true, @i{code1} is executed, otherwise @i{code2} is
5409: executed.
1.33 anton 5410:
1.1 anton 5411: You can use @code{THEN} instead of @code{ENDIF}. Indeed, @code{THEN} is
5412: standard, and @code{ENDIF} is not, although it is quite popular. We
5413: recommend using @code{ENDIF}, because it is less confusing for people
5414: who also know other languages (and is not prone to reinforcing negative
5415: prejudices against Forth in these people). Adding @code{ENDIF} to a
5416: system that only supplies @code{THEN} is simple:
5417: @example
1.82 anton 5418: : ENDIF POSTPONE then ; immediate
1.1 anton 5419: @end example
5420:
5421: [According to @cite{Webster's New Encyclopedic Dictionary}, @dfn{then
5422: (adv.)} has the following meanings:
5423: @quotation
5424: ... 2b: following next after in order ... 3d: as a necessary consequence
5425: (if you were there, then you saw them).
5426: @end quotation
5427: Forth's @code{THEN} has the meaning 2b, whereas @code{THEN} in Pascal
5428: and many other programming languages has the meaning 3d.]
5429:
1.21 crook 5430: Gforth also provides the words @code{?DUP-IF} and @code{?DUP-0=-IF}, so
1.1 anton 5431: you can avoid using @code{?dup}. Using these alternatives is also more
1.26 crook 5432: efficient than using @code{?dup}. Definitions in ANS Forth
1.1 anton 5433: for @code{ENDIF}, @code{?DUP-IF} and @code{?DUP-0=-IF} are provided in
5434: @file{compat/control.fs}.
5435:
5436: @cindex @code{CASE} control structure
5437: @example
1.29 crook 5438: @i{n}
1.1 anton 5439: CASE
1.29 crook 5440: @i{n1} OF @i{code1} ENDOF
5441: @i{n2} OF @i{code2} ENDOF
1.1 anton 5442: @dots{}
1.68 anton 5443: ( n ) @i{default-code} ( n )
1.1 anton 5444: ENDCASE
5445: @end example
5446:
1.68 anton 5447: Executes the first @i{codei}, where the @i{ni} is equal to @i{n}. If no
5448: @i{ni} matches, the optional @i{default-code} is executed. The optional
5449: default case can be added by simply writing the code after the last
5450: @code{ENDOF}. It may use @i{n}, which is on top of the stack, but must
5451: not consume it.
1.1 anton 5452:
1.69 anton 5453: @progstyle
5454: To keep the code understandable, you should ensure that on all paths
5455: through a selection construct the stack is changed in the same way
5456: (wrt. number and types of stack items consumed and pushed).
5457:
1.1 anton 5458: @node Simple Loops, Counted Loops, Selection, Control Structures
5459: @subsection Simple Loops
5460: @cindex simple loops
5461: @cindex loops without count
5462:
5463: @cindex @code{WHILE} loop
5464: @example
5465: BEGIN
1.29 crook 5466: @i{code1}
5467: @i{flag}
1.1 anton 5468: WHILE
1.29 crook 5469: @i{code2}
1.1 anton 5470: REPEAT
5471: @end example
5472:
1.29 crook 5473: @i{code1} is executed and @i{flag} is computed. If it is true,
5474: @i{code2} is executed and the loop is restarted; If @i{flag} is
1.1 anton 5475: false, execution continues after the @code{REPEAT}.
5476:
5477: @cindex @code{UNTIL} loop
5478: @example
5479: BEGIN
1.29 crook 5480: @i{code}
5481: @i{flag}
1.1 anton 5482: UNTIL
5483: @end example
5484:
1.29 crook 5485: @i{code} is executed. The loop is restarted if @code{flag} is false.
1.1 anton 5486:
1.69 anton 5487: @progstyle
5488: To keep the code understandable, a complete iteration of the loop should
5489: not change the number and types of the items on the stacks.
5490:
1.1 anton 5491: @cindex endless loop
5492: @cindex loops, endless
5493: @example
5494: BEGIN
1.29 crook 5495: @i{code}
1.1 anton 5496: AGAIN
5497: @end example
5498:
5499: This is an endless loop.
5500:
5501: @node Counted Loops, Arbitrary control structures, Simple Loops, Control Structures
5502: @subsection Counted Loops
5503: @cindex counted loops
5504: @cindex loops, counted
5505: @cindex @code{DO} loops
5506:
5507: The basic counted loop is:
5508: @example
1.29 crook 5509: @i{limit} @i{start}
1.1 anton 5510: ?DO
1.29 crook 5511: @i{body}
1.1 anton 5512: LOOP
5513: @end example
5514:
1.29 crook 5515: This performs one iteration for every integer, starting from @i{start}
5516: and up to, but excluding @i{limit}. The counter, or @i{index}, can be
1.21 crook 5517: accessed with @code{i}. For example, the loop:
1.1 anton 5518: @example
5519: 10 0 ?DO
5520: i .
5521: LOOP
5522: @end example
1.21 crook 5523: @noindent
5524: prints @code{0 1 2 3 4 5 6 7 8 9}
5525:
1.1 anton 5526: The index of the innermost loop can be accessed with @code{i}, the index
5527: of the next loop with @code{j}, and the index of the third loop with
5528: @code{k}.
5529:
1.44 crook 5530:
1.1 anton 5531: doc-i
5532: doc-j
5533: doc-k
5534:
1.44 crook 5535:
1.1 anton 5536: The loop control data are kept on the return stack, so there are some
1.21 crook 5537: restrictions on mixing return stack accesses and counted loop words. In
5538: particuler, if you put values on the return stack outside the loop, you
5539: cannot read them inside the loop@footnote{well, not in a way that is
5540: portable.}. If you put values on the return stack within a loop, you
5541: have to remove them before the end of the loop and before accessing the
5542: index of the loop.
1.1 anton 5543:
5544: There are several variations on the counted loop:
5545:
1.21 crook 5546: @itemize @bullet
5547: @item
5548: @code{LEAVE} leaves the innermost counted loop immediately; execution
5549: continues after the associated @code{LOOP} or @code{NEXT}. For example:
5550:
5551: @example
5552: 10 0 ?DO i DUP . 3 = IF LEAVE THEN LOOP
5553: @end example
5554: prints @code{0 1 2 3}
5555:
1.1 anton 5556:
1.21 crook 5557: @item
5558: @code{UNLOOP} prepares for an abnormal loop exit, e.g., via
5559: @code{EXIT}. @code{UNLOOP} removes the loop control parameters from the
5560: return stack so @code{EXIT} can get to its return address. For example:
5561:
5562: @example
5563: : demo 10 0 ?DO i DUP . 3 = IF UNLOOP EXIT THEN LOOP ." Done" ;
5564: @end example
5565: prints @code{0 1 2 3}
5566:
5567:
5568: @item
1.29 crook 5569: If @i{start} is greater than @i{limit}, a @code{?DO} loop is entered
1.1 anton 5570: (and @code{LOOP} iterates until they become equal by wrap-around
5571: arithmetic). This behaviour is usually not what you want. Therefore,
5572: Gforth offers @code{+DO} and @code{U+DO} (as replacements for
1.29 crook 5573: @code{?DO}), which do not enter the loop if @i{start} is greater than
5574: @i{limit}; @code{+DO} is for signed loop parameters, @code{U+DO} for
1.1 anton 5575: unsigned loop parameters.
5576:
1.21 crook 5577: @item
5578: @code{?DO} can be replaced by @code{DO}. @code{DO} always enters
5579: the loop, independent of the loop parameters. Do not use @code{DO}, even
5580: if you know that the loop is entered in any case. Such knowledge tends
5581: to become invalid during maintenance of a program, and then the
5582: @code{DO} will make trouble.
5583:
5584: @item
1.29 crook 5585: @code{LOOP} can be replaced with @code{@i{n} +LOOP}; this updates the
5586: index by @i{n} instead of by 1. The loop is terminated when the border
5587: between @i{limit-1} and @i{limit} is crossed. E.g.:
1.1 anton 5588:
1.21 crook 5589: @example
5590: 4 0 +DO i . 2 +LOOP
5591: @end example
5592: @noindent
5593: prints @code{0 2}
5594:
5595: @example
5596: 4 1 +DO i . 2 +LOOP
5597: @end example
5598: @noindent
5599: prints @code{1 3}
1.1 anton 5600:
1.68 anton 5601: @item
1.1 anton 5602: @cindex negative increment for counted loops
5603: @cindex counted loops with negative increment
1.29 crook 5604: The behaviour of @code{@i{n} +LOOP} is peculiar when @i{n} is negative:
1.1 anton 5605:
1.21 crook 5606: @example
5607: -1 0 ?DO i . -1 +LOOP
5608: @end example
5609: @noindent
5610: prints @code{0 -1}
1.1 anton 5611:
1.21 crook 5612: @example
5613: 0 0 ?DO i . -1 +LOOP
5614: @end example
5615: prints nothing.
1.1 anton 5616:
1.29 crook 5617: Therefore we recommend avoiding @code{@i{n} +LOOP} with negative
5618: @i{n}. One alternative is @code{@i{u} -LOOP}, which reduces the
5619: index by @i{u} each iteration. The loop is terminated when the border
5620: between @i{limit+1} and @i{limit} is crossed. Gforth also provides
1.1 anton 5621: @code{-DO} and @code{U-DO} for down-counting loops. E.g.:
5622:
1.21 crook 5623: @example
5624: -2 0 -DO i . 1 -LOOP
5625: @end example
5626: @noindent
5627: prints @code{0 -1}
1.1 anton 5628:
1.21 crook 5629: @example
5630: -1 0 -DO i . 1 -LOOP
5631: @end example
5632: @noindent
5633: prints @code{0}
5634:
5635: @example
5636: 0 0 -DO i . 1 -LOOP
5637: @end example
5638: @noindent
5639: prints nothing.
1.1 anton 5640:
1.21 crook 5641: @end itemize
1.1 anton 5642:
5643: Unfortunately, @code{+DO}, @code{U+DO}, @code{-DO}, @code{U-DO} and
1.26 crook 5644: @code{-LOOP} are not defined in ANS Forth. However, an implementation
5645: for these words that uses only standard words is provided in
5646: @file{compat/loops.fs}.
1.1 anton 5647:
5648:
5649: @cindex @code{FOR} loops
1.26 crook 5650: Another counted loop is:
1.1 anton 5651: @example
1.29 crook 5652: @i{n}
1.1 anton 5653: FOR
1.29 crook 5654: @i{body}
1.1 anton 5655: NEXT
5656: @end example
5657: This is the preferred loop of native code compiler writers who are too
1.26 crook 5658: lazy to optimize @code{?DO} loops properly. This loop structure is not
1.29 crook 5659: defined in ANS Forth. In Gforth, this loop iterates @i{n+1} times;
5660: @code{i} produces values starting with @i{n} and ending with 0. Other
1.26 crook 5661: Forth systems may behave differently, even if they support @code{FOR}
5662: loops. To avoid problems, don't use @code{FOR} loops.
1.1 anton 5663:
5664: @node Arbitrary control structures, Calls and returns, Counted Loops, Control Structures
5665: @subsection Arbitrary control structures
5666: @cindex control structures, user-defined
5667:
5668: @cindex control-flow stack
5669: ANS Forth permits and supports using control structures in a non-nested
5670: way. Information about incomplete control structures is stored on the
5671: control-flow stack. This stack may be implemented on the Forth data
5672: stack, and this is what we have done in Gforth.
5673:
5674: @cindex @code{orig}, control-flow stack item
5675: @cindex @code{dest}, control-flow stack item
5676: An @i{orig} entry represents an unresolved forward branch, a @i{dest}
5677: entry represents a backward branch target. A few words are the basis for
5678: building any control structure possible (except control structures that
5679: need storage, like calls, coroutines, and backtracking).
5680:
1.44 crook 5681:
1.1 anton 5682: doc-if
5683: doc-ahead
5684: doc-then
5685: doc-begin
5686: doc-until
5687: doc-again
5688: doc-cs-pick
5689: doc-cs-roll
5690:
1.44 crook 5691:
1.21 crook 5692: The Standard words @code{CS-PICK} and @code{CS-ROLL} allow you to
5693: manipulate the control-flow stack in a portable way. Without them, you
5694: would need to know how many stack items are occupied by a control-flow
5695: entry (many systems use one cell. In Gforth they currently take three,
5696: but this may change in the future).
5697:
1.1 anton 5698: Some standard control structure words are built from these words:
5699:
1.44 crook 5700:
1.1 anton 5701: doc-else
5702: doc-while
5703: doc-repeat
5704:
1.44 crook 5705:
5706: @noindent
1.1 anton 5707: Gforth adds some more control-structure words:
5708:
1.44 crook 5709:
1.1 anton 5710: doc-endif
5711: doc-?dup-if
5712: doc-?dup-0=-if
5713:
1.44 crook 5714:
5715: @noindent
1.1 anton 5716: Counted loop words constitute a separate group of words:
5717:
1.44 crook 5718:
1.1 anton 5719: doc-?do
5720: doc-+do
5721: doc-u+do
5722: doc--do
5723: doc-u-do
5724: doc-do
5725: doc-for
5726: doc-loop
5727: doc-+loop
5728: doc--loop
5729: doc-next
5730: doc-leave
5731: doc-?leave
5732: doc-unloop
5733: doc-done
5734:
1.44 crook 5735:
1.21 crook 5736: The standard does not allow using @code{CS-PICK} and @code{CS-ROLL} on
5737: @i{do-sys}. Gforth allows it, but it's your job to ensure that for
1.1 anton 5738: every @code{?DO} etc. there is exactly one @code{UNLOOP} on any path
5739: through the definition (@code{LOOP} etc. compile an @code{UNLOOP} on the
5740: fall-through path). Also, you have to ensure that all @code{LEAVE}s are
5741: resolved (by using one of the loop-ending words or @code{DONE}).
5742:
1.44 crook 5743: @noindent
1.26 crook 5744: Another group of control structure words are:
1.1 anton 5745:
1.44 crook 5746:
1.1 anton 5747: doc-case
5748: doc-endcase
5749: doc-of
5750: doc-endof
5751:
1.44 crook 5752:
1.21 crook 5753: @i{case-sys} and @i{of-sys} cannot be processed using @code{CS-PICK} and
5754: @code{CS-ROLL}.
1.1 anton 5755:
5756: @subsubsection Programming Style
1.47 crook 5757: @cindex control structures programming style
5758: @cindex programming style, arbitrary control structures
1.1 anton 5759:
5760: In order to ensure readability we recommend that you do not create
5761: arbitrary control structures directly, but define new control structure
5762: words for the control structure you want and use these words in your
1.26 crook 5763: program. For example, instead of writing:
1.1 anton 5764:
5765: @example
1.26 crook 5766: BEGIN
1.1 anton 5767: ...
1.26 crook 5768: IF [ 1 CS-ROLL ]
1.1 anton 5769: ...
1.26 crook 5770: AGAIN THEN
1.1 anton 5771: @end example
5772:
1.21 crook 5773: @noindent
1.1 anton 5774: we recommend defining control structure words, e.g.,
5775:
5776: @example
1.26 crook 5777: : WHILE ( DEST -- ORIG DEST )
5778: POSTPONE IF
5779: 1 CS-ROLL ; immediate
5780:
5781: : REPEAT ( orig dest -- )
5782: POSTPONE AGAIN
5783: POSTPONE THEN ; immediate
1.1 anton 5784: @end example
5785:
1.21 crook 5786: @noindent
1.1 anton 5787: and then using these to create the control structure:
5788:
5789: @example
1.26 crook 5790: BEGIN
1.1 anton 5791: ...
1.26 crook 5792: WHILE
1.1 anton 5793: ...
1.26 crook 5794: REPEAT
1.1 anton 5795: @end example
5796:
5797: That's much easier to read, isn't it? Of course, @code{REPEAT} and
5798: @code{WHILE} are predefined, so in this example it would not be
5799: necessary to define them.
5800:
5801: @node Calls and returns, Exception Handling, Arbitrary control structures, Control Structures
5802: @subsection Calls and returns
5803: @cindex calling a definition
5804: @cindex returning from a definition
5805:
1.3 anton 5806: @cindex recursive definitions
5807: A definition can be called simply be writing the name of the definition
1.26 crook 5808: to be called. Normally a definition is invisible during its own
1.3 anton 5809: definition. If you want to write a directly recursive definition, you
1.26 crook 5810: can use @code{recursive} to make the current definition visible, or
5811: @code{recurse} to call the current definition directly.
1.3 anton 5812:
1.44 crook 5813:
1.3 anton 5814: doc-recursive
5815: doc-recurse
5816:
1.44 crook 5817:
1.21 crook 5818: @comment TODO add example of the two recursion methods
1.12 anton 5819: @quotation
5820: @progstyle
5821: I prefer using @code{recursive} to @code{recurse}, because calling the
5822: definition by name is more descriptive (if the name is well-chosen) than
5823: the somewhat cryptic @code{recurse}. E.g., in a quicksort
5824: implementation, it is much better to read (and think) ``now sort the
5825: partitions'' than to read ``now do a recursive call''.
5826: @end quotation
1.3 anton 5827:
1.29 crook 5828: For mutual recursion, use @code{Defer}red words, like this:
1.3 anton 5829:
5830: @example
1.28 crook 5831: Defer foo
1.3 anton 5832:
5833: : bar ( ... -- ... )
5834: ... foo ... ;
5835:
5836: :noname ( ... -- ... )
5837: ... bar ... ;
5838: IS foo
5839: @end example
5840:
1.44 crook 5841: Deferred words are discussed in more detail in @ref{Deferred words}.
1.33 anton 5842:
1.26 crook 5843: The current definition returns control to the calling definition when
1.33 anton 5844: the end of the definition is reached or @code{EXIT} is encountered.
1.1 anton 5845:
5846: doc-exit
5847: doc-;s
5848:
1.44 crook 5849:
1.1 anton 5850: @node Exception Handling, , Calls and returns, Control Structures
5851: @subsection Exception Handling
1.26 crook 5852: @cindex exceptions
1.1 anton 5853:
1.68 anton 5854: @c quit is a very bad idea for error handling,
5855: @c because it does not translate into a THROW
5856: @c it also does not belong into this chapter
5857:
5858: If a word detects an error condition that it cannot handle, it can
5859: @code{throw} an exception. In the simplest case, this will terminate
5860: your program, and report an appropriate error.
1.21 crook 5861:
1.68 anton 5862: doc-throw
1.1 anton 5863:
1.69 anton 5864: @code{Throw} consumes a cell-sized error number on the stack. There are
5865: some predefined error numbers in ANS Forth (see @file{errors.fs}). In
5866: Gforth (and most other systems) you can use the iors produced by various
5867: words as error numbers (e.g., a typical use of @code{allocate} is
5868: @code{allocate throw}). Gforth also provides the word @code{exception}
5869: to define your own error numbers (with decent error reporting); an ANS
5870: Forth version of this word (but without the error messages) is available
5871: in @code{compat/except.fs}. And finally, you can use your own error
1.68 anton 5872: numbers (anything outside the range -4095..0), but won't get nice error
5873: messages, only numbers. For example, try:
5874:
5875: @example
1.69 anton 5876: -10 throw \ ANS defined
5877: -267 throw \ system defined
5878: s" my error" exception throw \ user defined
5879: 7 throw \ arbitrary number
1.68 anton 5880: @end example
5881:
5882: doc---exception-exception
1.1 anton 5883:
1.69 anton 5884: A common idiom to @code{THROW} a specific error if a flag is true is
5885: this:
5886:
5887: @example
5888: @code{( flag ) 0<> @i{errno} and throw}
5889: @end example
5890:
5891: Your program can provide exception handlers to catch exceptions. An
5892: exception handler can be used to correct the problem, or to clean up
5893: some data structures and just throw the exception to the next exception
5894: handler. Note that @code{throw} jumps to the dynamically innermost
5895: exception handler. The system's exception handler is outermost, and just
5896: prints an error and restarts command-line interpretation (or, in batch
5897: mode (i.e., while processing the shell command line), leaves Gforth).
1.1 anton 5898:
1.68 anton 5899: The ANS Forth way to catch exceptions is @code{catch}:
1.1 anton 5900:
1.68 anton 5901: doc-catch
5902:
5903: The most common use of exception handlers is to clean up the state when
5904: an error happens. E.g.,
1.1 anton 5905:
1.26 crook 5906: @example
1.68 anton 5907: base @ >r hex \ actually the hex should be inside foo, or we h
5908: ['] foo catch ( nerror|0 )
5909: r> base !
1.69 anton 5910: ( nerror|0 ) throw \ pass it on
1.26 crook 5911: @end example
1.1 anton 5912:
1.69 anton 5913: A use of @code{catch} for handling the error @code{myerror} might look
5914: like this:
1.44 crook 5915:
1.68 anton 5916: @example
1.69 anton 5917: ['] foo catch
5918: CASE
5919: myerror OF ... ( do something about it ) ENDOF
5920: dup throw \ default: pass other errors on, do nothing on non-errors
5921: ENDCASE
1.68 anton 5922: @end example
1.44 crook 5923:
1.68 anton 5924: Having to wrap the code into a separate word is often cumbersome,
5925: therefore Gforth provides an alternative syntax:
1.1 anton 5926:
5927: @example
1.69 anton 5928: TRY
1.68 anton 5929: @i{code1}
1.69 anton 5930: RECOVER \ optional
1.68 anton 5931: @i{code2} \ optional
1.69 anton 5932: ENDTRY
1.1 anton 5933: @end example
5934:
1.68 anton 5935: This performs @i{Code1}. If @i{code1} completes normally, execution
5936: continues after the @code{endtry}. If @i{Code1} throws, the stacks are
5937: reset to the state during @code{try}, the throw value is pushed on the
5938: data stack, and execution constinues at @i{code2}, and finally falls
5939: through the @code{endtry} into the following code. If there is no
5940: @code{recover} clause, this works like an empty recover clause.
1.26 crook 5941:
1.68 anton 5942: doc-try
5943: doc-recover
5944: doc-endtry
1.26 crook 5945:
1.69 anton 5946: The cleanup example from above in this syntax:
1.26 crook 5947:
1.68 anton 5948: @example
1.69 anton 5949: base @ >r TRY
1.68 anton 5950: hex foo \ now the hex is placed correctly
1.69 anton 5951: 0 \ value for throw
5952: ENDTRY
1.68 anton 5953: r> base ! throw
1.1 anton 5954: @end example
5955:
1.69 anton 5956: And here's the error handling example:
1.1 anton 5957:
1.68 anton 5958: @example
1.69 anton 5959: TRY
1.68 anton 5960: foo
1.69 anton 5961: RECOVER
5962: CASE
5963: myerror OF ... ( do something about it ) ENDOF
5964: throw \ pass other errors on
5965: ENDCASE
5966: ENDTRY
1.68 anton 5967: @end example
1.1 anton 5968:
1.69 anton 5969: @progstyle
5970: As usual, you should ensure that the stack depth is statically known at
5971: the end: either after the @code{throw} for passing on errors, or after
5972: the @code{ENDTRY} (or, if you use @code{catch}, after the end of the
5973: selection construct for handling the error).
5974:
1.68 anton 5975: There are two alternatives to @code{throw}: @code{Abort"} is conditional
5976: and you can provide an error message. @code{Abort} just produces an
5977: ``Aborted'' error.
1.1 anton 5978:
1.68 anton 5979: The problem with these words is that exception handlers cannot
5980: differentiate between different @code{abort"}s; they just look like
5981: @code{-2 throw} to them (the error message cannot be accessed by
5982: standard programs). Similar @code{abort} looks like @code{-1 throw} to
5983: exception handlers.
1.44 crook 5984:
1.68 anton 5985: doc-abort"
1.26 crook 5986: doc-abort
1.29 crook 5987:
5988:
1.44 crook 5989:
1.29 crook 5990: @c -------------------------------------------------------------
1.47 crook 5991: @node Defining Words, Interpretation and Compilation Semantics, Control Structures, Words
1.29 crook 5992: @section Defining Words
5993: @cindex defining words
5994:
1.47 crook 5995: Defining words are used to extend Forth by creating new entries in the dictionary.
5996:
1.29 crook 5997: @menu
1.67 anton 5998: * CREATE::
1.44 crook 5999: * Variables:: Variables and user variables
1.67 anton 6000: * Constants::
1.44 crook 6001: * Values:: Initialised variables
1.67 anton 6002: * Colon Definitions::
1.44 crook 6003: * Anonymous Definitions:: Definitions without names
1.69 anton 6004: * Supplying names:: Passing definition names as strings
1.67 anton 6005: * User-defined Defining Words::
1.44 crook 6006: * Deferred words:: Allow forward references
1.67 anton 6007: * Aliases::
1.29 crook 6008: @end menu
6009:
1.44 crook 6010: @node CREATE, Variables, Defining Words, Defining Words
6011: @subsection @code{CREATE}
1.29 crook 6012: @cindex simple defining words
6013: @cindex defining words, simple
6014:
6015: Defining words are used to create new entries in the dictionary. The
6016: simplest defining word is @code{CREATE}. @code{CREATE} is used like
6017: this:
6018:
6019: @example
6020: CREATE new-word1
6021: @end example
6022:
1.69 anton 6023: @code{CREATE} is a parsing word, i.e., it takes an argument from the
6024: input stream (@code{new-word1} in our example). It generates a
6025: dictionary entry for @code{new-word1}. When @code{new-word1} is
6026: executed, all that it does is leave an address on the stack. The address
6027: represents the value of the data space pointer (@code{HERE}) at the time
6028: that @code{new-word1} was defined. Therefore, @code{CREATE} is a way of
6029: associating a name with the address of a region of memory.
1.29 crook 6030:
1.34 anton 6031: doc-create
6032:
1.69 anton 6033: Note that in ANS Forth guarantees only for @code{create} that its body
6034: is in dictionary data space (i.e., where @code{here}, @code{allot}
6035: etc. work, @pxref{Dictionary allocation}). Also, in ANS Forth only
6036: @code{create}d words can be modified with @code{does>}
6037: (@pxref{User-defined Defining Words}). And in ANS Forth @code{>body}
6038: can only be applied to @code{create}d words.
6039:
1.29 crook 6040: By extending this example to reserve some memory in data space, we end
1.69 anton 6041: up with something like a @i{variable}. Here are two different ways to do
6042: it:
1.29 crook 6043:
6044: @example
6045: CREATE new-word2 1 cells allot \ reserve 1 cell - initial value undefined
6046: CREATE new-word3 4 , \ reserve 1 cell and initialise it (to 4)
6047: @end example
6048:
6049: The variable can be examined and modified using @code{@@} (``fetch'') and
6050: @code{!} (``store'') like this:
6051:
6052: @example
6053: new-word2 @@ . \ get address, fetch from it and display
6054: 1234 new-word2 ! \ new value, get address, store to it
6055: @end example
6056:
1.44 crook 6057: @cindex arrays
6058: A similar mechanism can be used to create arrays. For example, an
6059: 80-character text input buffer:
1.29 crook 6060:
6061: @example
1.44 crook 6062: CREATE text-buf 80 chars allot
6063:
6064: text-buf 0 chars c@@ \ the 1st character (offset 0)
6065: text-buf 3 chars c@@ \ the 4th character (offset 3)
6066: @end example
1.29 crook 6067:
1.44 crook 6068: You can build arbitrarily complex data structures by allocating
1.49 anton 6069: appropriate areas of memory. For further discussions of this, and to
1.66 anton 6070: learn about some Gforth tools that make it easier,
1.49 anton 6071: @xref{Structures}.
1.44 crook 6072:
6073:
6074: @node Variables, Constants, CREATE, Defining Words
6075: @subsection Variables
6076: @cindex variables
6077:
6078: The previous section showed how a sequence of commands could be used to
6079: generate a variable. As a final refinement, the whole code sequence can
6080: be wrapped up in a defining word (pre-empting the subject of the next
6081: section), making it easier to create new variables:
6082:
6083: @example
6084: : myvariableX ( "name" -- a-addr ) CREATE 1 cells allot ;
6085: : myvariable0 ( "name" -- a-addr ) CREATE 0 , ;
6086:
6087: myvariableX foo \ variable foo starts off with an unknown value
6088: myvariable0 joe \ whilst joe is initialised to 0
1.29 crook 6089:
6090: 45 3 * foo ! \ set foo to 135
6091: 1234 joe ! \ set joe to 1234
6092: 3 joe +! \ increment joe by 3.. to 1237
6093: @end example
6094:
6095: Not surprisingly, there is no need to define @code{myvariable}, since
1.44 crook 6096: Forth already has a definition @code{Variable}. ANS Forth does not
1.69 anton 6097: guarantee that a @code{Variable} is initialised when it is created
6098: (i.e., it may behave like @code{myvariableX}). In contrast, Gforth's
6099: @code{Variable} initialises the variable to 0 (i.e., it behaves exactly
6100: like @code{myvariable0}). Forth also provides @code{2Variable} and
1.47 crook 6101: @code{fvariable} for double and floating-point variables, respectively
1.69 anton 6102: -- they are initialised to 0. and 0e in Gforth. If you use a @code{Variable} to
1.47 crook 6103: store a boolean, you can use @code{on} and @code{off} to toggle its
6104: state.
1.29 crook 6105:
1.34 anton 6106: doc-variable
6107: doc-2variable
6108: doc-fvariable
6109:
1.29 crook 6110: @cindex user variables
6111: @cindex user space
6112: The defining word @code{User} behaves in the same way as @code{Variable}.
6113: The difference is that it reserves space in @i{user (data) space} rather
6114: than normal data space. In a Forth system that has a multi-tasker, each
6115: task has its own set of user variables.
6116:
1.34 anton 6117: doc-user
1.67 anton 6118: @c doc-udp
6119: @c doc-uallot
1.34 anton 6120:
1.29 crook 6121: @comment TODO is that stuff about user variables strictly correct? Is it
6122: @comment just terminal tasks that have user variables?
6123: @comment should document tasker.fs (with some examples) elsewhere
6124: @comment in this manual, then expand on user space and user variables.
6125:
1.44 crook 6126: @node Constants, Values, Variables, Defining Words
6127: @subsection Constants
6128: @cindex constants
6129:
6130: @code{Constant} allows you to declare a fixed value and refer to it by
6131: name. For example:
1.29 crook 6132:
6133: @example
6134: 12 Constant INCHES-PER-FOOT
6135: 3E+08 fconstant SPEED-O-LIGHT
6136: @end example
6137:
6138: A @code{Variable} can be both read and written, so its run-time
6139: behaviour is to supply an address through which its current value can be
6140: manipulated. In contrast, the value of a @code{Constant} cannot be
6141: changed once it has been declared@footnote{Well, often it can be -- but
6142: not in a Standard, portable way. It's safer to use a @code{Value} (read
6143: on).} so it's not necessary to supply the address -- it is more
6144: efficient to return the value of the constant directly. That's exactly
6145: what happens; the run-time effect of a constant is to put its value on
1.49 anton 6146: the top of the stack (You can find one
6147: way of implementing @code{Constant} in @ref{User-defined Defining Words}).
1.29 crook 6148:
1.69 anton 6149: Forth also provides @code{2Constant} and @code{fconstant} for defining
1.29 crook 6150: double and floating-point constants, respectively.
6151:
1.34 anton 6152: doc-constant
6153: doc-2constant
6154: doc-fconstant
6155:
6156: @c that's too deep, and it's not necessarily true for all ANS Forths. - anton
1.44 crook 6157: @c nac-> How could that not be true in an ANS Forth? You can't define a
6158: @c constant, use it and then delete the definition of the constant..
1.69 anton 6159:
6160: @c anton->An ANS Forth system can compile a constant to a literal; On
6161: @c decompilation you would see only the number, just as if it had been used
6162: @c in the first place. The word will stay, of course, but it will only be
6163: @c used by the text interpreter (no run-time duties, except when it is
6164: @c POSTPONEd or somesuch).
6165:
6166: @c nac:
1.44 crook 6167: @c I agree that it's rather deep, but IMO it is an important difference
6168: @c relative to other programming languages.. often it's annoying: it
6169: @c certainly changes my programming style relative to C.
6170:
1.69 anton 6171: @c anton: In what way?
6172:
1.29 crook 6173: Constants in Forth behave differently from their equivalents in other
6174: programming languages. In other languages, a constant (such as an EQU in
6175: assembler or a #define in C) only exists at compile-time; in the
6176: executable program the constant has been translated into an absolute
6177: number and, unless you are using a symbolic debugger, it's impossible to
6178: know what abstract thing that number represents. In Forth a constant has
1.44 crook 6179: an entry in the header space and remains there after the code that uses
6180: it has been defined. In fact, it must remain in the dictionary since it
6181: has run-time duties to perform. For example:
1.29 crook 6182:
6183: @example
6184: 12 Constant INCHES-PER-FOOT
6185: : FEET-TO-INCHES ( n1 -- n2 ) INCHES-PER-FOOT * ;
6186: @end example
6187:
6188: @cindex in-lining of constants
6189: When @code{FEET-TO-INCHES} is executed, it will in turn execute the xt
6190: associated with the constant @code{INCHES-PER-FOOT}. If you use
6191: @code{see} to decompile the definition of @code{FEET-TO-INCHES}, you can
6192: see that it makes a call to @code{INCHES-PER-FOOT}. Some Forth compilers
6193: attempt to optimise constants by in-lining them where they are used. You
6194: can force Gforth to in-line a constant like this:
6195:
6196: @example
6197: : FEET-TO-INCHES ( n1 -- n2 ) [ INCHES-PER-FOOT ] LITERAL * ;
6198: @end example
6199:
6200: If you use @code{see} to decompile @i{this} version of
6201: @code{FEET-TO-INCHES}, you can see that @code{INCHES-PER-FOOT} is no
1.49 anton 6202: longer present. To understand how this works, read
6203: @ref{Interpret/Compile states}, and @ref{Literals}.
1.29 crook 6204:
6205: In-lining constants in this way might improve execution time
6206: fractionally, and can ensure that a constant is now only referenced at
6207: compile-time. However, the definition of the constant still remains in
6208: the dictionary. Some Forth compilers provide a mechanism for controlling
6209: a second dictionary for holding transient words such that this second
6210: dictionary can be deleted later in order to recover memory
6211: space. However, there is no standard way of doing this.
6212:
6213:
1.44 crook 6214: @node Values, Colon Definitions, Constants, Defining Words
6215: @subsection Values
6216: @cindex values
1.34 anton 6217:
1.69 anton 6218: A @code{Value} behaves like a @code{Constant}, but it can be changed.
6219: @code{TO} is a parsing word that changes a @code{Values}. In Gforth
6220: (not in ANS Forth) you can access (and change) a @code{value} also with
6221: @code{>body}.
6222:
6223: Here are some
6224: examples:
1.29 crook 6225:
6226: @example
1.69 anton 6227: 12 Value APPLES \ Define APPLES with an initial value of 12
6228: 34 TO APPLES \ Change the value of APPLES. TO is a parsing word
6229: 1 ' APPLES >body +! \ Increment APPLES. Non-standard usage.
6230: APPLES \ puts 35 on the top of the stack.
1.29 crook 6231: @end example
6232:
1.44 crook 6233: doc-value
6234: doc-to
1.29 crook 6235:
1.35 anton 6236:
1.69 anton 6237:
1.44 crook 6238: @node Colon Definitions, Anonymous Definitions, Values, Defining Words
6239: @subsection Colon Definitions
6240: @cindex colon definitions
1.35 anton 6241:
6242: @example
1.44 crook 6243: : name ( ... -- ... )
6244: word1 word2 word3 ;
1.29 crook 6245: @end example
6246:
1.44 crook 6247: @noindent
6248: Creates a word called @code{name} that, upon execution, executes
6249: @code{word1 word2 word3}. @code{name} is a @dfn{(colon) definition}.
1.29 crook 6250:
1.49 anton 6251: The explanation above is somewhat superficial. For simple examples of
6252: colon definitions see @ref{Your first definition}. For an in-depth
1.66 anton 6253: discussion of some of the issues involved, @xref{Interpretation and
1.49 anton 6254: Compilation Semantics}.
1.29 crook 6255:
1.44 crook 6256: doc-:
6257: doc-;
1.1 anton 6258:
1.34 anton 6259:
1.69 anton 6260: @node Anonymous Definitions, Supplying names, Colon Definitions, Defining Words
1.44 crook 6261: @subsection Anonymous Definitions
6262: @cindex colon definitions
6263: @cindex defining words without name
1.34 anton 6264:
1.44 crook 6265: Sometimes you want to define an @dfn{anonymous word}; a word without a
6266: name. You can do this with:
1.1 anton 6267:
1.44 crook 6268: doc-:noname
1.1 anton 6269:
1.44 crook 6270: This leaves the execution token for the word on the stack after the
6271: closing @code{;}. Here's an example in which a deferred word is
6272: initialised with an @code{xt} from an anonymous colon definition:
1.1 anton 6273:
1.29 crook 6274: @example
1.44 crook 6275: Defer deferred
6276: :noname ( ... -- ... )
6277: ... ;
6278: IS deferred
1.29 crook 6279: @end example
1.26 crook 6280:
1.44 crook 6281: @noindent
6282: Gforth provides an alternative way of doing this, using two separate
6283: words:
1.27 crook 6284:
1.44 crook 6285: doc-noname
6286: @cindex execution token of last defined word
6287: doc-lastxt
1.1 anton 6288:
1.44 crook 6289: @noindent
6290: The previous example can be rewritten using @code{noname} and
6291: @code{lastxt}:
1.1 anton 6292:
1.26 crook 6293: @example
1.44 crook 6294: Defer deferred
6295: noname : ( ... -- ... )
6296: ... ;
6297: lastxt IS deferred
1.26 crook 6298: @end example
1.1 anton 6299:
1.29 crook 6300: @noindent
1.44 crook 6301: @code{noname} works with any defining word, not just @code{:}.
6302:
6303: @code{lastxt} also works when the last word was not defined as
1.71 anton 6304: @code{noname}. It does not work for combined words, though. It also has
6305: the useful property that is is valid as soon as the header for a
6306: definition has been built. Thus:
1.44 crook 6307:
6308: @example
6309: lastxt . : foo [ lastxt . ] ; ' foo .
6310: @end example
1.1 anton 6311:
1.44 crook 6312: @noindent
6313: prints 3 numbers; the last two are the same.
1.26 crook 6314:
1.69 anton 6315: @node Supplying names, User-defined Defining Words, Anonymous Definitions, Defining Words
6316: @subsection Supplying the name of a defined word
6317: @cindex names for defined words
6318: @cindex defining words, name given in a string
6319:
6320: By default, a defining word takes the name for the defined word from the
6321: input stream. Sometimes you want to supply the name from a string. You
6322: can do this with:
6323:
6324: doc-nextname
6325:
6326: For example:
6327:
6328: @example
6329: s" foo" nextname create
6330: @end example
6331:
6332: @noindent
6333: is equivalent to:
6334:
6335: @example
6336: create foo
6337: @end example
6338:
6339: @noindent
6340: @code{nextname} works with any defining word.
6341:
1.1 anton 6342:
1.69 anton 6343: @node User-defined Defining Words, Deferred words, Supplying names, Defining Words
1.26 crook 6344: @subsection User-defined Defining Words
6345: @cindex user-defined defining words
6346: @cindex defining words, user-defined
1.1 anton 6347:
1.29 crook 6348: You can create a new defining word by wrapping defining-time code around
6349: an existing defining word and putting the sequence in a colon
1.69 anton 6350: definition.
6351:
6352: @c anton: This example is very complex and leads in a quite different
6353: @c direction from the CREATE-DOES> stuff that follows. It should probably
6354: @c be done elsewhere, or as a subsubsection of this subsection (or as a
6355: @c subsection of Defining Words)
6356:
6357: For example, suppose that you have a word @code{stats} that
1.29 crook 6358: gathers statistics about colon definitions given the @i{xt} of the
6359: definition, and you want every colon definition in your application to
6360: make a call to @code{stats}. You can define and use a new version of
6361: @code{:} like this:
6362:
6363: @example
6364: : stats ( xt -- ) DUP ." (Gathering statistics for " . ." )"
6365: ... ; \ other code
6366:
6367: : my: : lastxt postpone literal ['] stats compile, ;
6368:
6369: my: foo + - ;
6370: @end example
6371:
6372: When @code{foo} is defined using @code{my:} these steps occur:
6373:
6374: @itemize @bullet
6375: @item
6376: @code{my:} is executed.
6377: @item
6378: The @code{:} within the definition (the one between @code{my:} and
6379: @code{lastxt}) is executed, and does just what it always does; it parses
6380: the input stream for a name, builds a dictionary header for the name
6381: @code{foo} and switches @code{state} from interpret to compile.
6382: @item
6383: The word @code{lastxt} is executed. It puts the @i{xt} for the word that is
6384: being defined -- @code{foo} -- onto the stack.
6385: @item
6386: The code that was produced by @code{postpone literal} is executed; this
6387: causes the value on the stack to be compiled as a literal in the code
6388: area of @code{foo}.
6389: @item
6390: The code @code{['] stats} compiles a literal into the definition of
6391: @code{my:}. When @code{compile,} is executed, that literal -- the
6392: execution token for @code{stats} -- is layed down in the code area of
6393: @code{foo} , following the literal@footnote{Strictly speaking, the
6394: mechanism that @code{compile,} uses to convert an @i{xt} into something
6395: in the code area is implementation-dependent. A threaded implementation
6396: might spit out the execution token directly whilst another
6397: implementation might spit out a native code sequence.}.
6398: @item
6399: At this point, the execution of @code{my:} is complete, and control
6400: returns to the text interpreter. The text interpreter is in compile
6401: state, so subsequent text @code{+ -} is compiled into the definition of
6402: @code{foo} and the @code{;} terminates the definition as always.
6403: @end itemize
6404:
6405: You can use @code{see} to decompile a word that was defined using
6406: @code{my:} and see how it is different from a normal @code{:}
6407: definition. For example:
6408:
6409: @example
6410: : bar + - ; \ like foo but using : rather than my:
6411: see bar
6412: : bar
6413: + - ;
6414: see foo
6415: : foo
6416: 107645672 stats + - ;
6417:
6418: \ use ' stats . to show that 107645672 is the xt for stats
6419: @end example
6420:
6421: You can use techniques like this to make new defining words in terms of
6422: @i{any} existing defining word.
1.1 anton 6423:
6424:
1.29 crook 6425: @cindex defining defining words
1.26 crook 6426: @cindex @code{CREATE} ... @code{DOES>}
6427: If you want the words defined with your defining words to behave
6428: differently from words defined with standard defining words, you can
6429: write your defining word like this:
1.1 anton 6430:
6431: @example
1.26 crook 6432: : def-word ( "name" -- )
1.29 crook 6433: CREATE @i{code1}
1.26 crook 6434: DOES> ( ... -- ... )
1.29 crook 6435: @i{code2} ;
1.26 crook 6436:
6437: def-word name
1.1 anton 6438: @end example
6439:
1.29 crook 6440: @cindex child words
6441: This fragment defines a @dfn{defining word} @code{def-word} and then
6442: executes it. When @code{def-word} executes, it @code{CREATE}s a new
6443: word, @code{name}, and executes the code @i{code1}. The code @i{code2}
6444: is not executed at this time. The word @code{name} is sometimes called a
6445: @dfn{child} of @code{def-word}.
6446:
6447: When you execute @code{name}, the address of the body of @code{name} is
6448: put on the data stack and @i{code2} is executed (the address of the body
6449: of @code{name} is the address @code{HERE} returns immediately after the
1.69 anton 6450: @code{CREATE}, i.e., the address a @code{create}d word returns by
6451: default).
6452:
6453: @c anton:
6454: @c www.dictionary.com says:
6455: @c at·a·vism: 1.The reappearance of a characteristic in an organism after
6456: @c several generations of absence, usually caused by the chance
6457: @c recombination of genes. 2.An individual or a part that exhibits
6458: @c atavism. Also called throwback. 3.The return of a trait or recurrence
6459: @c of previous behavior after a period of absence.
6460: @c
6461: @c Doesn't seem to fit.
1.29 crook 6462:
1.69 anton 6463: @c @cindex atavism in child words
1.33 anton 6464: You can use @code{def-word} to define a set of child words that behave
1.69 anton 6465: similarly; they all have a common run-time behaviour determined by
6466: @i{code2}. Typically, the @i{code1} sequence builds a data area in the
6467: body of the child word. The structure of the data is common to all
6468: children of @code{def-word}, but the data values are specific -- and
6469: private -- to each child word. When a child word is executed, the
6470: address of its private data area is passed as a parameter on TOS to be
6471: used and manipulated@footnote{It is legitimate both to read and write to
6472: this data area.} by @i{code2}.
1.29 crook 6473:
6474: The two fragments of code that make up the defining words act (are
6475: executed) at two completely separate times:
1.1 anton 6476:
1.29 crook 6477: @itemize @bullet
6478: @item
6479: At @i{define time}, the defining word executes @i{code1} to generate a
6480: child word
6481: @item
6482: At @i{child execution time}, when a child word is invoked, @i{code2}
6483: is executed, using parameters (data) that are private and specific to
6484: the child word.
6485: @end itemize
6486:
1.44 crook 6487: Another way of understanding the behaviour of @code{def-word} and
6488: @code{name} is to say that, if you make the following definitions:
1.33 anton 6489: @example
6490: : def-word1 ( "name" -- )
6491: CREATE @i{code1} ;
6492:
6493: : action1 ( ... -- ... )
6494: @i{code2} ;
6495:
6496: def-word1 name1
6497: @end example
6498:
1.44 crook 6499: @noindent
6500: Then using @code{name1 action1} is equivalent to using @code{name}.
1.1 anton 6501:
1.29 crook 6502: The classic example is that you can define @code{CONSTANT} in this way:
1.26 crook 6503:
1.1 anton 6504: @example
1.29 crook 6505: : CONSTANT ( w "name" -- )
6506: CREATE ,
1.26 crook 6507: DOES> ( -- w )
6508: @@ ;
1.1 anton 6509: @end example
6510:
1.29 crook 6511: @comment There is a beautiful description of how this works and what
6512: @comment it does in the Forthwrite 100th edition.. as well as an elegant
6513: @comment commentary on the Counting Fruits problem.
6514:
6515: When you create a constant with @code{5 CONSTANT five}, a set of
6516: define-time actions take place; first a new word @code{five} is created,
6517: then the value 5 is laid down in the body of @code{five} with
1.44 crook 6518: @code{,}. When @code{five} is executed, the address of the body is put on
1.29 crook 6519: the stack, and @code{@@} retrieves the value 5. The word @code{five} has
6520: no code of its own; it simply contains a data field and a pointer to the
6521: code that follows @code{DOES>} in its defining word. That makes words
6522: created in this way very compact.
6523:
6524: The final example in this section is intended to remind you that space
6525: reserved in @code{CREATE}d words is @i{data} space and therefore can be
6526: both read and written by a Standard program@footnote{Exercise: use this
6527: example as a starting point for your own implementation of @code{Value}
6528: and @code{TO} -- if you get stuck, investigate the behaviour of @code{'} and
6529: @code{[']}.}:
6530:
6531: @example
6532: : foo ( "name" -- )
6533: CREATE -1 ,
6534: DOES> ( -- )
1.33 anton 6535: @@ . ;
1.29 crook 6536:
6537: foo first-word
6538: foo second-word
6539:
6540: 123 ' first-word >BODY !
6541: @end example
6542:
6543: If @code{first-word} had been a @code{CREATE}d word, we could simply
6544: have executed it to get the address of its data field. However, since it
6545: was defined to have @code{DOES>} actions, its execution semantics are to
6546: perform those @code{DOES>} actions. To get the address of its data field
6547: it's necessary to use @code{'} to get its xt, then @code{>BODY} to
6548: translate the xt into the address of the data field. When you execute
6549: @code{first-word}, it will display @code{123}. When you execute
6550: @code{second-word} it will display @code{-1}.
1.26 crook 6551:
6552: @cindex stack effect of @code{DOES>}-parts
6553: @cindex @code{DOES>}-parts, stack effect
1.29 crook 6554: In the examples above the stack comment after the @code{DOES>} specifies
1.26 crook 6555: the stack effect of the defined words, not the stack effect of the
6556: following code (the following code expects the address of the body on
6557: the top of stack, which is not reflected in the stack comment). This is
6558: the convention that I use and recommend (it clashes a bit with using
6559: locals declarations for stack effect specification, though).
1.1 anton 6560:
1.53 anton 6561: @menu
6562: * CREATE..DOES> applications::
6563: * CREATE..DOES> details::
1.63 anton 6564: * Advanced does> usage example::
1.53 anton 6565: @end menu
6566:
6567: @node CREATE..DOES> applications, CREATE..DOES> details, User-defined Defining Words, User-defined Defining Words
1.26 crook 6568: @subsubsection Applications of @code{CREATE..DOES>}
6569: @cindex @code{CREATE} ... @code{DOES>}, applications
1.1 anton 6570:
1.26 crook 6571: You may wonder how to use this feature. Here are some usage patterns:
1.1 anton 6572:
1.26 crook 6573: @cindex factoring similar colon definitions
6574: When you see a sequence of code occurring several times, and you can
6575: identify a meaning, you will factor it out as a colon definition. When
6576: you see similar colon definitions, you can factor them using
6577: @code{CREATE..DOES>}. E.g., an assembler usually defines several words
6578: that look very similar:
1.1 anton 6579: @example
1.26 crook 6580: : ori, ( reg-target reg-source n -- )
6581: 0 asm-reg-reg-imm ;
6582: : andi, ( reg-target reg-source n -- )
6583: 1 asm-reg-reg-imm ;
1.1 anton 6584: @end example
6585:
1.26 crook 6586: @noindent
6587: This could be factored with:
6588: @example
6589: : reg-reg-imm ( op-code -- )
6590: CREATE ,
6591: DOES> ( reg-target reg-source n -- )
6592: @@ asm-reg-reg-imm ;
6593:
6594: 0 reg-reg-imm ori,
6595: 1 reg-reg-imm andi,
6596: @end example
1.1 anton 6597:
1.26 crook 6598: @cindex currying
6599: Another view of @code{CREATE..DOES>} is to consider it as a crude way to
6600: supply a part of the parameters for a word (known as @dfn{currying} in
6601: the functional language community). E.g., @code{+} needs two
6602: parameters. Creating versions of @code{+} with one parameter fixed can
6603: be done like this:
1.82 anton 6604:
1.1 anton 6605: @example
1.82 anton 6606: : curry+ ( n1 "name" -- )
1.26 crook 6607: CREATE ,
6608: DOES> ( n2 -- n1+n2 )
6609: @@ + ;
6610:
6611: 3 curry+ 3+
6612: -2 curry+ 2-
1.1 anton 6613: @end example
6614:
1.63 anton 6615: @node CREATE..DOES> details, Advanced does> usage example, CREATE..DOES> applications, User-defined Defining Words
1.26 crook 6616: @subsubsection The gory details of @code{CREATE..DOES>}
6617: @cindex @code{CREATE} ... @code{DOES>}, details
1.1 anton 6618:
1.26 crook 6619: doc-does>
1.1 anton 6620:
1.26 crook 6621: @cindex @code{DOES>} in a separate definition
6622: This means that you need not use @code{CREATE} and @code{DOES>} in the
6623: same definition; you can put the @code{DOES>}-part in a separate
1.29 crook 6624: definition. This allows us to, e.g., select among different @code{DOES>}-parts:
1.26 crook 6625: @example
6626: : does1
6627: DOES> ( ... -- ... )
1.44 crook 6628: ... ;
6629:
6630: : does2
6631: DOES> ( ... -- ... )
6632: ... ;
6633:
6634: : def-word ( ... -- ... )
6635: create ...
6636: IF
6637: does1
6638: ELSE
6639: does2
6640: ENDIF ;
6641: @end example
6642:
6643: In this example, the selection of whether to use @code{does1} or
1.69 anton 6644: @code{does2} is made at definition-time; at the time that the child word is
1.44 crook 6645: @code{CREATE}d.
6646:
6647: @cindex @code{DOES>} in interpretation state
6648: In a standard program you can apply a @code{DOES>}-part only if the last
6649: word was defined with @code{CREATE}. In Gforth, the @code{DOES>}-part
6650: will override the behaviour of the last word defined in any case. In a
6651: standard program, you can use @code{DOES>} only in a colon
6652: definition. In Gforth, you can also use it in interpretation state, in a
6653: kind of one-shot mode; for example:
6654: @example
6655: CREATE name ( ... -- ... )
6656: @i{initialization}
6657: DOES>
6658: @i{code} ;
6659: @end example
6660:
6661: @noindent
6662: is equivalent to the standard:
6663: @example
6664: :noname
6665: DOES>
6666: @i{code} ;
6667: CREATE name EXECUTE ( ... -- ... )
6668: @i{initialization}
6669: @end example
6670:
1.53 anton 6671: doc->body
6672:
1.63 anton 6673: @node Advanced does> usage example, , CREATE..DOES> details, User-defined Defining Words
6674: @subsubsection Advanced does> usage example
6675:
6676: The MIPS disassembler (@file{arch/mips/disasm.fs}) contains many words
6677: for disassembling instructions, that follow a very repetetive scheme:
6678:
6679: @example
6680: :noname @var{disasm-operands} s" @var{inst-name}" type ;
6681: @var{entry-num} cells @var{table} + !
6682: @end example
6683:
6684: Of course, this inspires the idea to factor out the commonalities to
6685: allow a definition like
6686:
6687: @example
6688: @var{disasm-operands} @var{entry-num} @var{table} define-inst @var{inst-name}
6689: @end example
6690:
6691: The parameters @var{disasm-operands} and @var{table} are usually
1.69 anton 6692: correlated. Moreover, before I wrote the disassembler, there already
6693: existed code that defines instructions like this:
1.63 anton 6694:
6695: @example
6696: @var{entry-num} @var{inst-format} @var{inst-name}
6697: @end example
6698:
6699: This code comes from the assembler and resides in
6700: @file{arch/mips/insts.fs}.
6701:
6702: So I had to define the @var{inst-format} words that performed the scheme
6703: above when executed. At first I chose to use run-time code-generation:
6704:
6705: @example
6706: : @var{inst-format} ( entry-num "name" -- ; compiled code: addr w -- )
6707: :noname Postpone @var{disasm-operands}
6708: name Postpone sliteral Postpone type Postpone ;
6709: swap cells @var{table} + ! ;
6710: @end example
6711:
6712: Note that this supplies the other two parameters of the scheme above.
1.44 crook 6713:
1.63 anton 6714: An alternative would have been to write this using
6715: @code{create}/@code{does>}:
6716:
6717: @example
6718: : @var{inst-format} ( entry-num "name" -- )
6719: here name string, ( entry-num c-addr ) \ parse and save "name"
6720: noname create , ( entry-num )
6721: lastxt swap cells @var{table} + !
6722: does> ( addr w -- )
6723: \ disassemble instruction w at addr
6724: @@ >r
6725: @var{disasm-operands}
6726: r> count type ;
6727: @end example
6728:
6729: Somehow the first solution is simpler, mainly because it's simpler to
6730: shift a string from definition-time to use-time with @code{sliteral}
6731: than with @code{string,} and friends.
6732:
6733: I wrote a lot of words following this scheme and soon thought about
6734: factoring out the commonalities among them. Note that this uses a
6735: two-level defining word, i.e., a word that defines ordinary defining
6736: words.
6737:
6738: This time a solution involving @code{postpone} and friends seemed more
6739: difficult (try it as an exercise), so I decided to use a
6740: @code{create}/@code{does>} word; since I was already at it, I also used
6741: @code{create}/@code{does>} for the lower level (try using
6742: @code{postpone} etc. as an exercise), resulting in the following
6743: definition:
6744:
6745: @example
6746: : define-format ( disasm-xt table-xt -- )
6747: \ define an instruction format that uses disasm-xt for
6748: \ disassembling and enters the defined instructions into table
6749: \ table-xt
6750: create 2,
6751: does> ( u "inst" -- )
6752: \ defines an anonymous word for disassembling instruction inst,
6753: \ and enters it as u-th entry into table-xt
6754: 2@@ swap here name string, ( u table-xt disasm-xt c-addr ) \ remember string
6755: noname create 2, \ define anonymous word
6756: execute lastxt swap ! \ enter xt of defined word into table-xt
6757: does> ( addr w -- )
6758: \ disassemble instruction w at addr
6759: 2@@ >r ( addr w disasm-xt R: c-addr )
6760: execute ( R: c-addr ) \ disassemble operands
6761: r> count type ; \ print name
6762: @end example
6763:
6764: Note that the tables here (in contrast to above) do the @code{cells +}
6765: by themselves (that's why you have to pass an xt). This word is used in
6766: the following way:
6767:
6768: @example
6769: ' @var{disasm-operands} ' @var{table} define-format @var{inst-format}
6770: @end example
6771:
1.71 anton 6772: As shown above, the defined instruction format is then used like this:
6773:
6774: @example
6775: @var{entry-num} @var{inst-format} @var{inst-name}
6776: @end example
6777:
1.63 anton 6778: In terms of currying, this kind of two-level defining word provides the
6779: parameters in three stages: first @var{disasm-operands} and @var{table},
6780: then @var{entry-num} and @var{inst-name}, finally @code{addr w}, i.e.,
6781: the instruction to be disassembled.
6782:
6783: Of course this did not quite fit all the instruction format names used
6784: in @file{insts.fs}, so I had to define a few wrappers that conditioned
6785: the parameters into the right form.
6786:
6787: If you have trouble following this section, don't worry. First, this is
6788: involved and takes time (and probably some playing around) to
6789: understand; second, this is the first two-level
6790: @code{create}/@code{does>} word I have written in seventeen years of
6791: Forth; and if I did not have @file{insts.fs} to start with, I may well
6792: have elected to use just a one-level defining word (with some repeating
6793: of parameters when using the defining word). So it is not necessary to
6794: understand this, but it may improve your understanding of Forth.
1.44 crook 6795:
6796:
6797: @node Deferred words, Aliases, User-defined Defining Words, Defining Words
6798: @subsection Deferred words
6799: @cindex deferred words
6800:
6801: The defining word @code{Defer} allows you to define a word by name
6802: without defining its behaviour; the definition of its behaviour is
6803: deferred. Here are two situation where this can be useful:
6804:
6805: @itemize @bullet
6806: @item
6807: Where you want to allow the behaviour of a word to be altered later, and
6808: for all precompiled references to the word to change when its behaviour
6809: is changed.
6810: @item
6811: For mutual recursion; @xref{Calls and returns}.
6812: @end itemize
6813:
6814: In the following example, @code{foo} always invokes the version of
6815: @code{greet} that prints ``@code{Good morning}'' whilst @code{bar}
6816: always invokes the version that prints ``@code{Hello}''. There is no way
6817: of getting @code{foo} to use the later version without re-ordering the
6818: source code and recompiling it.
6819:
6820: @example
6821: : greet ." Good morning" ;
6822: : foo ... greet ... ;
6823: : greet ." Hello" ;
6824: : bar ... greet ... ;
6825: @end example
6826:
6827: This problem can be solved by defining @code{greet} as a @code{Defer}red
6828: word. The behaviour of a @code{Defer}red word can be defined and
6829: redefined at any time by using @code{IS} to associate the xt of a
6830: previously-defined word with it. The previous example becomes:
6831:
6832: @example
1.69 anton 6833: Defer greet ( -- )
1.44 crook 6834: : foo ... greet ... ;
6835: : bar ... greet ... ;
1.69 anton 6836: : greet1 ( -- ) ." Good morning" ;
6837: : greet2 ( -- ) ." Hello" ;
1.44 crook 6838: ' greet2 <IS> greet \ make greet behave like greet2
6839: @end example
6840:
1.69 anton 6841: @progstyle
6842: You should write a stack comment for every deferred word, and put only
6843: XTs into deferred words that conform to this stack effect. Otherwise
6844: it's too difficult to use the deferred word.
6845:
1.44 crook 6846: A deferred word can be used to improve the statistics-gathering example
6847: from @ref{User-defined Defining Words}; rather than edit the
6848: application's source code to change every @code{:} to a @code{my:}, do
6849: this:
6850:
6851: @example
6852: : real: : ; \ retain access to the original
6853: defer : \ redefine as a deferred word
1.69 anton 6854: ' my: <IS> : \ use special version of :
1.44 crook 6855: \
6856: \ load application here
6857: \
1.69 anton 6858: ' real: <IS> : \ go back to the original
1.44 crook 6859: @end example
6860:
6861:
6862: One thing to note is that @code{<IS>} consumes its name when it is
6863: executed. If you want to specify the name at compile time, use
6864: @code{[IS]}:
6865:
6866: @example
6867: : set-greet ( xt -- )
6868: [IS] greet ;
6869:
6870: ' greet1 set-greet
6871: @end example
6872:
1.69 anton 6873: A deferred word can only inherit execution semantics from the xt
6874: (because that is all that an xt can represent -- for more discussion of
6875: this @pxref{Tokens for Words}); by default it will have default
6876: interpretation and compilation semantics deriving from this execution
6877: semantics. However, you can change the interpretation and compilation
6878: semantics of the deferred word in the usual ways:
1.44 crook 6879:
6880: @example
6881: : bar .... ; compile-only
6882: Defer fred immediate
6883: Defer jim
6884:
6885: ' bar <IS> jim \ jim has default semantics
6886: ' bar <IS> fred \ fred is immediate
6887: @end example
6888:
6889: doc-defer
6890: doc-<is>
6891: doc-[is]
6892: doc-is
6893: @comment TODO document these: what's defers [is]
6894: doc-what's
6895: doc-defers
6896:
6897: @c Use @code{words-deferred} to see a list of deferred words.
6898:
6899: Definitions in ANS Forth for @code{defer}, @code{<is>} and @code{[is]}
6900: are provided in @file{compat/defer.fs}.
6901:
6902:
1.69 anton 6903: @node Aliases, , Deferred words, Defining Words
1.44 crook 6904: @subsection Aliases
6905: @cindex aliases
1.1 anton 6906:
1.44 crook 6907: The defining word @code{Alias} allows you to define a word by name that
6908: has the same behaviour as some other word. Here are two situation where
6909: this can be useful:
1.1 anton 6910:
1.44 crook 6911: @itemize @bullet
6912: @item
6913: When you want access to a word's definition from a different word list
6914: (for an example of this, see the definition of the @code{Root} word list
6915: in the Gforth source).
6916: @item
6917: When you want to create a synonym; a definition that can be known by
6918: either of two names (for example, @code{THEN} and @code{ENDIF} are
6919: aliases).
6920: @end itemize
1.1 anton 6921:
1.69 anton 6922: Like deferred words, an alias has default compilation and interpretation
6923: semantics at the beginning (not the modifications of the other word),
6924: but you can change them in the usual ways (@code{immediate},
6925: @code{compile-only}). For example:
1.1 anton 6926:
6927: @example
1.44 crook 6928: : foo ... ; immediate
6929:
6930: ' foo Alias bar \ bar is not an immediate word
6931: ' foo Alias fooby immediate \ fooby is an immediate word
1.1 anton 6932: @end example
6933:
1.44 crook 6934: Words that are aliases have the same xt, different headers in the
6935: dictionary, and consequently different name tokens (@pxref{Tokens for
6936: Words}) and possibly different immediate flags. An alias can only have
6937: default or immediate compilation semantics; you can define aliases for
6938: combined words with @code{interpret/compile:} -- see @ref{Combined words}.
1.1 anton 6939:
1.44 crook 6940: doc-alias
1.1 anton 6941:
6942:
1.47 crook 6943: @node Interpretation and Compilation Semantics, Tokens for Words, Defining Words, Words
6944: @section Interpretation and Compilation Semantics
1.26 crook 6945: @cindex semantics, interpretation and compilation
1.1 anton 6946:
1.71 anton 6947: @c !! state and ' are used without explanation
6948: @c example for immediate/compile-only? or is the tutorial enough
6949:
1.26 crook 6950: @cindex interpretation semantics
1.71 anton 6951: The @dfn{interpretation semantics} of a (named) word are what the text
1.26 crook 6952: interpreter does when it encounters the word in interpret state. It also
6953: appears in some other contexts, e.g., the execution token returned by
1.71 anton 6954: @code{' @i{word}} identifies the interpretation semantics of @i{word}
6955: (in other words, @code{' @i{word} execute} is equivalent to
1.29 crook 6956: interpret-state text interpretation of @code{@i{word}}).
1.1 anton 6957:
1.26 crook 6958: @cindex compilation semantics
1.71 anton 6959: The @dfn{compilation semantics} of a (named) word are what the text
6960: interpreter does when it encounters the word in compile state. It also
6961: appears in other contexts, e.g, @code{POSTPONE @i{word}}
6962: compiles@footnote{In standard terminology, ``appends to the current
6963: definition''.} the compilation semantics of @i{word}.
1.1 anton 6964:
1.26 crook 6965: @cindex execution semantics
6966: The standard also talks about @dfn{execution semantics}. They are used
6967: only for defining the interpretation and compilation semantics of many
6968: words. By default, the interpretation semantics of a word are to
6969: @code{execute} its execution semantics, and the compilation semantics of
6970: a word are to @code{compile,} its execution semantics.@footnote{In
6971: standard terminology: The default interpretation semantics are its
6972: execution semantics; the default compilation semantics are to append its
6973: execution semantics to the execution semantics of the current
6974: definition.}
6975:
1.71 anton 6976: Unnamed words (@pxref{Anonymous Definitions}) cannot be encountered by
6977: the text interpreter, ticked, or @code{postpone}d, so they have no
6978: interpretation or compilation semantics. Their behaviour is represented
6979: by their XT (@pxref{Tokens for Words}), and we call it execution
6980: semantics, too.
6981:
1.26 crook 6982: @comment TODO expand, make it co-operate with new sections on text interpreter.
6983:
6984: @cindex immediate words
6985: @cindex compile-only words
6986: You can change the semantics of the most-recently defined word:
6987:
1.44 crook 6988:
1.26 crook 6989: doc-immediate
6990: doc-compile-only
6991: doc-restrict
6992:
1.82 anton 6993: By convention, words with non-default compilation semantics (e.g.,
6994: immediate words) often have names surrounded with brackets (e.g.,
6995: @code{[']}, @pxref{Execution token}).
1.44 crook 6996:
1.26 crook 6997: Note that ticking (@code{'}) a compile-only word gives an error
6998: (``Interpreting a compile-only word'').
1.1 anton 6999:
1.47 crook 7000: @menu
1.67 anton 7001: * Combined words::
1.47 crook 7002: @end menu
1.44 crook 7003:
1.71 anton 7004:
1.48 anton 7005: @node Combined words, , Interpretation and Compilation Semantics, Interpretation and Compilation Semantics
1.44 crook 7006: @subsection Combined Words
7007: @cindex combined words
7008:
7009: Gforth allows you to define @dfn{combined words} -- words that have an
7010: arbitrary combination of interpretation and compilation semantics.
7011:
1.26 crook 7012: doc-interpret/compile:
1.1 anton 7013:
1.26 crook 7014: This feature was introduced for implementing @code{TO} and @code{S"}. I
7015: recommend that you do not define such words, as cute as they may be:
7016: they make it hard to get at both parts of the word in some contexts.
7017: E.g., assume you want to get an execution token for the compilation
7018: part. Instead, define two words, one that embodies the interpretation
7019: part, and one that embodies the compilation part. Once you have done
7020: that, you can define a combined word with @code{interpret/compile:} for
7021: the convenience of your users.
1.1 anton 7022:
1.26 crook 7023: You might try to use this feature to provide an optimizing
7024: implementation of the default compilation semantics of a word. For
7025: example, by defining:
1.1 anton 7026: @example
1.26 crook 7027: :noname
7028: foo bar ;
7029: :noname
7030: POSTPONE foo POSTPONE bar ;
1.29 crook 7031: interpret/compile: opti-foobar
1.1 anton 7032: @end example
1.26 crook 7033:
1.23 crook 7034: @noindent
1.26 crook 7035: as an optimizing version of:
7036:
1.1 anton 7037: @example
1.26 crook 7038: : foobar
7039: foo bar ;
1.1 anton 7040: @end example
7041:
1.26 crook 7042: Unfortunately, this does not work correctly with @code{[compile]},
7043: because @code{[compile]} assumes that the compilation semantics of all
7044: @code{interpret/compile:} words are non-default. I.e., @code{[compile]
1.29 crook 7045: opti-foobar} would compile compilation semantics, whereas
7046: @code{[compile] foobar} would compile interpretation semantics.
1.1 anton 7047:
1.26 crook 7048: @cindex state-smart words (are a bad idea)
1.82 anton 7049: @anchor{state-smartness}
1.29 crook 7050: Some people try to use @dfn{state-smart} words to emulate the feature provided
1.26 crook 7051: by @code{interpret/compile:} (words are state-smart if they check
7052: @code{STATE} during execution). E.g., they would try to code
7053: @code{foobar} like this:
1.1 anton 7054:
1.26 crook 7055: @example
7056: : foobar
7057: STATE @@
7058: IF ( compilation state )
7059: POSTPONE foo POSTPONE bar
7060: ELSE
7061: foo bar
7062: ENDIF ; immediate
7063: @end example
1.1 anton 7064:
1.26 crook 7065: Although this works if @code{foobar} is only processed by the text
7066: interpreter, it does not work in other contexts (like @code{'} or
7067: @code{POSTPONE}). E.g., @code{' foobar} will produce an execution token
7068: for a state-smart word, not for the interpretation semantics of the
7069: original @code{foobar}; when you execute this execution token (directly
7070: with @code{EXECUTE} or indirectly through @code{COMPILE,}) in compile
7071: state, the result will not be what you expected (i.e., it will not
7072: perform @code{foo bar}). State-smart words are a bad idea. Simply don't
7073: write them@footnote{For a more detailed discussion of this topic, see
1.66 anton 7074: M. Anton Ertl,
7075: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,@code{State}-smartness---Why
7076: it is Evil and How to Exorcise it}}, EuroForth '98.}!
1.1 anton 7077:
1.26 crook 7078: @cindex defining words with arbitrary semantics combinations
7079: It is also possible to write defining words that define words with
7080: arbitrary combinations of interpretation and compilation semantics. In
7081: general, they look like this:
1.1 anton 7082:
1.26 crook 7083: @example
7084: : def-word
7085: create-interpret/compile
1.29 crook 7086: @i{code1}
1.26 crook 7087: interpretation>
1.29 crook 7088: @i{code2}
1.26 crook 7089: <interpretation
7090: compilation>
1.29 crook 7091: @i{code3}
1.26 crook 7092: <compilation ;
7093: @end example
1.1 anton 7094:
1.29 crook 7095: For a @i{word} defined with @code{def-word}, the interpretation
7096: semantics are to push the address of the body of @i{word} and perform
7097: @i{code2}, and the compilation semantics are to push the address of
7098: the body of @i{word} and perform @i{code3}. E.g., @code{constant}
1.26 crook 7099: can also be defined like this (except that the defined constants don't
7100: behave correctly when @code{[compile]}d):
1.1 anton 7101:
1.26 crook 7102: @example
7103: : constant ( n "name" -- )
7104: create-interpret/compile
7105: ,
7106: interpretation> ( -- n )
7107: @@
7108: <interpretation
7109: compilation> ( compilation. -- ; run-time. -- n )
7110: @@ postpone literal
7111: <compilation ;
7112: @end example
1.1 anton 7113:
1.44 crook 7114:
1.26 crook 7115: doc-create-interpret/compile
7116: doc-interpretation>
7117: doc-<interpretation
7118: doc-compilation>
7119: doc-<compilation
1.1 anton 7120:
1.44 crook 7121:
1.29 crook 7122: Words defined with @code{interpret/compile:} and
1.26 crook 7123: @code{create-interpret/compile} have an extended header structure that
7124: differs from other words; however, unless you try to access them with
7125: plain address arithmetic, you should not notice this. Words for
7126: accessing the header structure usually know how to deal with this; e.g.,
1.29 crook 7127: @code{'} @i{word} @code{>body} also gives you the body of a word created
7128: with @code{create-interpret/compile}.
1.1 anton 7129:
1.44 crook 7130:
1.47 crook 7131: @c -------------------------------------------------------------
1.81 anton 7132: @node Tokens for Words, Compiling words, Interpretation and Compilation Semantics, Words
1.47 crook 7133: @section Tokens for Words
7134: @cindex tokens for words
7135:
7136: This section describes the creation and use of tokens that represent
7137: words.
7138:
1.71 anton 7139: @menu
7140: * Execution token:: represents execution/interpretation semantics
7141: * Compilation token:: represents compilation semantics
7142: * Name token:: represents named words
7143: @end menu
1.47 crook 7144:
1.71 anton 7145: @node Execution token, Compilation token, Tokens for Words, Tokens for Words
7146: @subsection Execution token
1.47 crook 7147:
7148: @cindex xt
7149: @cindex execution token
1.71 anton 7150: An @dfn{execution token} (@i{XT}) represents some behaviour of a word.
7151: You can use @code{execute} to invoke this behaviour.
1.47 crook 7152:
1.71 anton 7153: @cindex tick (')
7154: You can use @code{'} to get an execution token that represents the
7155: interpretation semantics of a named word:
1.47 crook 7156:
7157: @example
1.71 anton 7158: 5 ' .
7159: execute
7160: @end example
1.47 crook 7161:
1.71 anton 7162: doc-'
7163:
7164: @code{'} parses at run-time; there is also a word @code{[']} that parses
7165: when it is compiled, and compiles the resulting XT:
7166:
7167: @example
7168: : foo ['] . execute ;
7169: 5 foo
7170: : bar ' execute ; \ by contrast,
7171: 5 bar . \ ' parses "." when bar executes
7172: @end example
7173:
7174: doc-[']
7175:
7176: If you want the execution token of @i{word}, write @code{['] @i{word}}
7177: in compiled code and @code{' @i{word}} in interpreted code. Gforth's
7178: @code{'} and @code{[']} behave somewhat unusually by complaining about
7179: compile-only words (because these words have no interpretation
7180: semantics). You might get what you want by using @code{COMP' @i{word}
7181: DROP} or @code{[COMP'] @i{word} DROP} (for details @pxref{Compilation
7182: token}).
7183:
7184: Another way to get an XT is @code{:noname} or @code{lastxt}
7185: (@pxref{Anonymous Definitions}). For anonymous words this gives an xt
7186: for the only behaviour the word has (the execution semantics). For
7187: named words, @code{lastxt} produces an XT for the same behaviour it
7188: would produce if the word was defined anonymously.
7189:
7190: @example
7191: :noname ." hello" ;
7192: execute
1.47 crook 7193: @end example
7194:
1.71 anton 7195: An XT occupies one cell and can be manipulated like any other cell.
7196:
1.47 crook 7197: @cindex code field address
7198: @cindex CFA
1.71 anton 7199: In ANS Forth the XT is just an abstract data type (i.e., defined by the
7200: operations that produce or consume it). For old hands: In Gforth, the
7201: XT is implemented as a code field address (CFA).
7202:
7203: doc-execute
7204: doc-perform
7205:
7206: @node Compilation token, Name token, Execution token, Tokens for Words
7207: @subsection Compilation token
1.47 crook 7208:
7209: @cindex compilation token
1.71 anton 7210: @cindex CT (compilation token)
7211: Gforth represents the compilation semantics of a named word by a
1.47 crook 7212: @dfn{compilation token} consisting of two cells: @i{w xt}. The top cell
7213: @i{xt} is an execution token. The compilation semantics represented by
7214: the compilation token can be performed with @code{execute}, which
7215: consumes the whole compilation token, with an additional stack effect
7216: determined by the represented compilation semantics.
7217:
7218: At present, the @i{w} part of a compilation token is an execution token,
7219: and the @i{xt} part represents either @code{execute} or
7220: @code{compile,}@footnote{Depending upon the compilation semantics of the
7221: word. If the word has default compilation semantics, the @i{xt} will
7222: represent @code{compile,}. Otherwise (e.g., for immediate words), the
7223: @i{xt} will represent @code{execute}.}. However, don't rely on that
7224: knowledge, unless necessary; future versions of Gforth may introduce
7225: unusual compilation tokens (e.g., a compilation token that represents
7226: the compilation semantics of a literal).
7227:
1.71 anton 7228: You can perform the compilation semantics represented by the compilation
7229: token with @code{execute}. You can compile the compilation semantics
7230: with @code{postpone,}. I.e., @code{COMP' @i{word} postpone,} is
7231: equivalent to @code{postpone @i{word}}.
7232:
7233: doc-[comp']
7234: doc-comp'
7235: doc-postpone,
7236:
7237: @node Name token, , Compilation token, Tokens for Words
7238: @subsection Name token
1.47 crook 7239:
7240: @cindex name token
7241: @cindex name field address
7242: @cindex NFA
1.71 anton 7243: Gforth represents named words by the @dfn{name token}, (@i{nt}). In
1.47 crook 7244: Gforth, the abstract data type @emph{name token} is implemented as a
7245: name field address (NFA).
7246:
7247: doc-find-name
7248: doc-name>int
7249: doc-name?int
7250: doc-name>comp
7251: doc-name>string
7252:
1.81 anton 7253: @c ----------------------------------------------------------
7254: @node Compiling words, The Text Interpreter, Tokens for Words, Words
7255: @section Compiling words
7256: @cindex compiling words
7257: @cindex macros
7258:
7259: In contrast to most other languages, Forth has no strict boundary
1.82 anton 7260: between compilation and run-time. E.g., you can run arbitrary code
7261: between defining words (or for computing data used by defining words
7262: like @code{constant}). Moreover, @code{Immediate} (@pxref{Interpretation
7263: and Compilation Semantics} and @code{[}...@code{]} (see below) allow
7264: running arbitrary code while compiling a colon definition (exception:
7265: you must not allot dictionary space).
7266:
7267: @menu
7268: * Literals:: Compiling data values
7269: * Macros:: Compiling words
7270: @end menu
7271:
7272: @node Literals, Macros, Compiling words, Compiling words
7273: @subsection Literals
7274: @cindex Literals
7275:
7276: The simplest and most frequent example is to compute a literal during
7277: compilation. E.g., the following definition prints an array of strings,
7278: one string per line:
7279:
7280: @example
7281: : .strings ( addr u -- ) \ gforth
7282: 2* cells bounds U+DO
7283: cr i 2@@ type
7284: 2 cells +LOOP ;
7285: @end example
1.81 anton 7286:
1.82 anton 7287: With a simple-minded compiler like Gforth's, this computes @code{2
7288: cells} on every loop iteration. You can compute this value once and for
7289: all at compile time and compile it into the definition like this:
7290:
7291: @example
7292: : .strings ( addr u -- ) \ gforth
7293: 2* cells bounds U+DO
7294: cr i 2@@ type
7295: [ 2 cells ] literal +LOOP ;
7296: @end example
7297:
7298: @code{[} switches the text interpreter to interpret state (you will get
7299: an @code{ok} prompt if you type this example interactively and insert a
7300: newline between @code{[} and @code{]}), so it performs the
7301: interpretation semantics of @code{2 cells}; this computes a number.
7302: @code{]} switches the text interpreter back into compile state. It then
7303: performs @code{Literal}'s compilation semantics, which are to compile
7304: this number into the current word. You can decompile the word with
7305: @code{see .strings} to see the effect on the compiled code.
1.81 anton 7306:
1.82 anton 7307: You can also optimize the @code{2* cells} into @code{[ 2 cells ] literal
7308: *} in this way.
1.81 anton 7309:
1.82 anton 7310: doc-[
7311: doc-]
1.81 anton 7312: doc-literal
7313: doc-]L
1.82 anton 7314:
7315: There are also words for compiling other data types than single cells as
7316: literals:
7317:
1.81 anton 7318: doc-2literal
7319: doc-fliteral
1.82 anton 7320: doc-sliteral
7321:
7322: @cindex colon-sys, passing data across @code{:}
7323: @cindex @code{:}, passing data across
7324: You might be tempted to pass data from outside a colon definition to the
7325: inside on the data stack. This does not work, because @code{:} puhes a
7326: colon-sys, making stuff below unaccessible. E.g., this does not work:
7327:
7328: @example
7329: 5 : foo literal ; \ error: "unstructured"
7330: @end example
7331:
7332: Instead, you have to pass the value in some other way, e.g., through a
7333: variable:
7334:
7335: @example
7336: variable temp
7337: 5 temp !
7338: : foo [ temp @@ ] literal ;
7339: @end example
7340:
7341:
7342: @node Macros, , Literals, Compiling words
7343: @subsection Macros
7344: @cindex Macros
7345: @cindex compiling compilation semantics
7346:
7347: @code{Literal} and friends compile data values into the current
7348: definition. You can also write words that compile other words into the
7349: current definition. E.g.,
7350:
7351: @example
7352: : compile-+ ( -- ) \ compiled code: ( n1 n2 -- n )
7353: POSTPONE + ;
7354:
7355: : foo ( n1 n2 -- n )
7356: [ compile-+ ] ;
7357: 1 2 foo .
7358: @end example
7359:
7360: This is equivalent to @code{: foo + ;} (@code{see foo} to check this).
7361: What happens in this example? @code{Postpone} compiles the compilation
7362: semantics of @code{+} into @code{compile-+}; later the text interpreter
7363: executes @code{compile-+} and thus the compilation semantics of +, which
7364: compile (the execution semantics of) @code{+} into
7365: @code{foo}.@footnote{A recent RFI answer requires that compiling words
7366: should only be executed in compile state, so this example is not
7367: guaranteed to work on all standard systems, but on any decent system it
7368: will work.}
7369:
7370: doc-postpone
7371: doc-[compile]
7372:
7373: Compiling words like @code{compile-+} are usually immediate (or similar)
7374: so you do not have to switch to interpret state to execute them;
7375: mopifying the last example accordingly produces:
7376:
7377: @example
7378: : [compile-+] ( compilation: --; interpretation: -- )
7379: \ compiled code: ( n1 n2 -- n )
7380: POSTPONE + ; immediate
7381:
7382: : foo ( n1 n2 -- n )
7383: [compile-+] ;
7384: 1 2 foo .
7385: @end example
7386:
7387: Immediate compiling words are similar to macros in other languages (in
7388: particular, Lisp). The important differences to macros in, e.g., C are:
7389:
7390: @itemize @bullet
7391:
7392: @item
7393: You use the same language for defining and processing macros, not a
7394: separate preprocessing language and processor.
7395:
7396: @item
7397: Consequently, the full power of Forth is available in macro definitions.
7398: E.g., you can perform arbitrarily complex computations, or generate
7399: different code conditionally or in a loop (e.g., @pxref{Advanced macros
7400: Tutorial}). This power is very useful when writing a parser generators
7401: or other code-generating software.
7402:
7403: @item
7404: Macros defined using @code{postpone} etc. deal with the language at a
7405: higher level than strings; name binding happens at macro definition
7406: time, so you can avoid the pitfalls of name collisions that can happen
7407: in C macros. Of course, Forth is a liberal language and also allows to
7408: shoot yourself in the foot with text-interpreted macros like
7409:
7410: @example
7411: : [compile-+] s" +" evaluate ; immediate
7412: @end example
7413:
7414: Apart from binding the name at macro use time, using @code{evaluate}
7415: also makes your definition @code{state}-smart (@pxref{state-smartness}).
7416: @end itemize
7417:
7418: You may want the macro to compile a number into a word. The word to do
7419: it is @code{literal}, but you have to @code{postpone} it, so its
7420: compilation semantics take effect when the macro is executed, not when
7421: it is compiled:
7422:
7423: @example
7424: : [compile-5] ( -- ) \ compiled code: ( -- n )
7425: 5 POSTPONE literal ; immediate
7426:
7427: : foo [compile-5] ;
7428: foo .
7429: @end example
7430:
7431: You may want to pass parameters to a macro, that the macro should
7432: compile into the current definition. If the parameter is a number, then
7433: you can use @code{postpone literal} (similar for other values).
7434:
7435: If you want to pass a word that is to be compiled, the usual way is to
7436: pass an execution token and @code{compile,} it:
7437:
7438: @example
7439: : twice1 ( xt -- ) \ compiled code: ... -- ...
7440: dup compile, compile, ;
7441:
7442: : 2+ ( n1 -- n2 )
7443: [ ' 1+ twice1 ] ;
7444: @end example
7445:
7446: doc-compile,
7447:
7448: An alternative available in Gforth, that allows you to pass compile-only
7449: words as parameters is to use the compilation token (@pxref{Compilation
7450: token}). The same example in this technique:
7451:
7452: @example
7453: : twice ( ... ct -- ... ) \ compiled code: ... -- ...
7454: 2dup 2>r execute 2r> execute ;
7455:
7456: : 2+ ( n1 -- n2 )
7457: [ comp' 1+ twice ] ;
7458: @end example
7459:
7460: In the example above @code{2>r} and @code{2r>} ensure that @code{twice}
7461: works even if the executed compilation semantics has an effect on the
7462: data stack.
7463:
7464: You can also define complete definitions with these words; this provides
7465: an alternative to using @code{does>} (@pxref{User-defined Defining
7466: Words}). E.g., instead of
7467:
7468: @example
7469: : curry+ ( n1 "name" -- )
7470: CREATE ,
7471: DOES> ( n2 -- n1+n2 )
7472: @@ + ;
7473: @end example
7474:
7475: you could define
7476:
7477: @example
7478: : curry+ ( n1 "name" -- )
7479: \ name execution: ( n2 -- n1+n2 )
7480: >r : r> POSTPONE literal POSTPONE + POSTPONE ; ;
1.81 anton 7481:
1.82 anton 7482: -3 curry+ 3-
7483: see 3-
7484: @end example
1.81 anton 7485:
1.82 anton 7486: The sequence @code{>r : r>} is necessary, because @code{:} puts a
7487: colon-sys on the data stack that makes everything below it unaccessible.
1.81 anton 7488:
1.82 anton 7489: This way of writing defining words is sometimes more, sometimes less
7490: convenient than using @code{does>} (@pxref{Advanced does> usage
7491: example}). One advantage of this method is that it can be optimized
7492: better, because the compiler knows that the value compiled with
7493: @code{literal} is fixed, whereas the data associated with a
7494: @code{create}d word can be changed.
1.47 crook 7495:
1.26 crook 7496: @c ----------------------------------------------------------
1.81 anton 7497: @node The Text Interpreter, Word Lists, Compiling words, Words
1.26 crook 7498: @section The Text Interpreter
7499: @cindex interpreter - outer
7500: @cindex text interpreter
7501: @cindex outer interpreter
1.1 anton 7502:
1.34 anton 7503: @c Should we really describe all these ugly details? IMO the text
7504: @c interpreter should be much cleaner, but that may not be possible within
7505: @c ANS Forth. - anton
1.44 crook 7506: @c nac-> I wanted to explain how it works to show how you can exploit
7507: @c it in your own programs. When I was writing a cross-compiler, figuring out
7508: @c some of these gory details was very helpful to me. None of the textbooks
7509: @c I've seen cover it, and the most modern Forth textbook -- Forth Inc's,
7510: @c seems to positively avoid going into too much detail for some of
7511: @c the internals.
1.34 anton 7512:
1.71 anton 7513: @c anton: ok. I wonder, though, if this is the right place; for some stuff
7514: @c it is; for the ugly details, I would prefer another place. I wonder
7515: @c whether we should have a chapter before "Words" that describes some
7516: @c basic concepts referred to in words, and a chapter after "Words" that
7517: @c describes implementation details.
7518:
1.29 crook 7519: The text interpreter@footnote{This is an expanded version of the
7520: material in @ref{Introducing the Text Interpreter}.} is an endless loop
1.34 anton 7521: that processes input from the current input device. It is also called
7522: the outer interpreter, in contrast to the inner interpreter
7523: (@pxref{Engine}) which executes the compiled Forth code on interpretive
7524: implementations.
1.27 crook 7525:
1.29 crook 7526: @cindex interpret state
7527: @cindex compile state
7528: The text interpreter operates in one of two states: @dfn{interpret
7529: state} and @dfn{compile state}. The current state is defined by the
1.71 anton 7530: aptly-named variable @code{state}.
1.29 crook 7531:
7532: This section starts by describing how the text interpreter behaves when
7533: it is in interpret state, processing input from the user input device --
7534: the keyboard. This is the mode that a Forth system is in after it starts
7535: up.
7536:
7537: @cindex input buffer
7538: @cindex terminal input buffer
7539: The text interpreter works from an area of memory called the @dfn{input
7540: buffer}@footnote{When the text interpreter is processing input from the
7541: keyboard, this area of memory is called the @dfn{terminal input buffer}
7542: (TIB) and is addressed by the (obsolescent) words @code{TIB} and
7543: @code{#TIB}.}, which stores your keyboard input when you press the
1.30 anton 7544: @key{RET} key. Starting at the beginning of the input buffer, it skips
1.29 crook 7545: leading spaces (called @dfn{delimiters}) then parses a string (a
7546: sequence of non-space characters) until it reaches either a space
7547: character or the end of the buffer. Having parsed a string, it makes two
7548: attempts to process it:
1.27 crook 7549:
1.29 crook 7550: @cindex dictionary
1.27 crook 7551: @itemize @bullet
7552: @item
1.29 crook 7553: It looks for the string in a @dfn{dictionary} of definitions. If the
7554: string is found, the string names a @dfn{definition} (also known as a
7555: @dfn{word}) and the dictionary search returns information that allows
7556: the text interpreter to perform the word's @dfn{interpretation
7557: semantics}. In most cases, this simply means that the word will be
7558: executed.
1.27 crook 7559: @item
7560: If the string is not found in the dictionary, the text interpreter
1.29 crook 7561: attempts to treat it as a number, using the rules described in
7562: @ref{Number Conversion}. If the string represents a legal number in the
7563: current radix, the number is pushed onto a parameter stack (the data
7564: stack for integers, the floating-point stack for floating-point
7565: numbers).
7566: @end itemize
7567:
7568: If both attempts fail, or if the word is found in the dictionary but has
7569: no interpretation semantics@footnote{This happens if the word was
7570: defined as @code{COMPILE-ONLY}.} the text interpreter discards the
7571: remainder of the input buffer, issues an error message and waits for
7572: more input. If one of the attempts succeeds, the text interpreter
7573: repeats the parsing process until the whole of the input buffer has been
7574: processed, at which point it prints the status message ``@code{ ok}''
7575: and waits for more input.
7576:
1.71 anton 7577: @c anton: this should be in the input stream subsection (or below it)
7578:
1.29 crook 7579: @cindex parse area
7580: The text interpreter keeps track of its position in the input buffer by
7581: updating a variable called @code{>IN} (pronounced ``to-in''). The value
7582: of @code{>IN} starts out as 0, indicating an offset of 0 from the start
7583: of the input buffer. The region from offset @code{>IN @@} to the end of
7584: the input buffer is called the @dfn{parse area}@footnote{In other words,
7585: the text interpreter processes the contents of the input buffer by
7586: parsing strings from the parse area until the parse area is empty.}.
7587: This example shows how @code{>IN} changes as the text interpreter parses
7588: the input buffer:
7589:
7590: @example
7591: : remaining >IN @@ SOURCE 2 PICK - -ROT + SWAP
7592: CR ." ->" TYPE ." <-" ; IMMEDIATE
7593:
7594: 1 2 3 remaining + remaining .
7595:
7596: : foo 1 2 3 remaining SWAP remaining ;
7597: @end example
7598:
7599: @noindent
7600: The result is:
7601:
7602: @example
7603: ->+ remaining .<-
7604: ->.<-5 ok
7605:
7606: ->SWAP remaining ;-<
7607: ->;<- ok
7608: @end example
7609:
7610: @cindex parsing words
7611: The value of @code{>IN} can also be modified by a word in the input
7612: buffer that is executed by the text interpreter. This means that a word
7613: can ``trick'' the text interpreter into either skipping a section of the
7614: input buffer@footnote{This is how parsing words work.} or into parsing a
7615: section twice. For example:
1.27 crook 7616:
1.29 crook 7617: @example
1.71 anton 7618: : lat ." <<foo>>" ;
7619: : flat ." <<bar>>" >IN DUP @@ 3 - SWAP ! ;
1.29 crook 7620: @end example
7621:
7622: @noindent
7623: When @code{flat} is executed, this output is produced@footnote{Exercise
7624: for the reader: what would happen if the @code{3} were replaced with
7625: @code{4}?}:
7626:
7627: @example
1.71 anton 7628: <<bar>><<foo>>
1.29 crook 7629: @end example
7630:
1.71 anton 7631: This technique can be used to work around some of the interoperability
7632: problems of parsing words. Of course, it's better to avoid parsing
7633: words where possible.
7634:
1.29 crook 7635: @noindent
7636: Two important notes about the behaviour of the text interpreter:
1.27 crook 7637:
7638: @itemize @bullet
7639: @item
7640: It processes each input string to completion before parsing additional
1.29 crook 7641: characters from the input buffer.
7642: @item
7643: It treats the input buffer as a read-only region (and so must your code).
7644: @end itemize
7645:
7646: @noindent
7647: When the text interpreter is in compile state, its behaviour changes in
7648: these ways:
7649:
7650: @itemize @bullet
7651: @item
7652: If a parsed string is found in the dictionary, the text interpreter will
7653: perform the word's @dfn{compilation semantics}. In most cases, this
7654: simply means that the execution semantics of the word will be appended
7655: to the current definition.
1.27 crook 7656: @item
1.29 crook 7657: When a number is encountered, it is compiled into the current definition
7658: (as a literal) rather than being pushed onto a parameter stack.
7659: @item
7660: If an error occurs, @code{state} is modified to put the text interpreter
7661: back into interpret state.
7662: @item
7663: Each time a line is entered from the keyboard, Gforth prints
7664: ``@code{ compiled}'' rather than `` @code{ok}''.
7665: @end itemize
7666:
7667: @cindex text interpreter - input sources
7668: When the text interpreter is using an input device other than the
7669: keyboard, its behaviour changes in these ways:
7670:
7671: @itemize @bullet
7672: @item
7673: When the parse area is empty, the text interpreter attempts to refill
7674: the input buffer from the input source. When the input source is
1.71 anton 7675: exhausted, the input source is set back to the previous input source.
1.29 crook 7676: @item
7677: It doesn't print out ``@code{ ok}'' or ``@code{ compiled}'' messages each
7678: time the parse area is emptied.
7679: @item
7680: If an error occurs, the input source is set back to the user input
7681: device.
1.27 crook 7682: @end itemize
1.21 crook 7683:
1.49 anton 7684: You can read about this in more detail in @ref{Input Sources}.
1.44 crook 7685:
1.26 crook 7686: doc->in
1.27 crook 7687: doc-source
7688:
1.26 crook 7689: doc-tib
7690: doc-#tib
1.1 anton 7691:
1.44 crook 7692:
1.26 crook 7693: @menu
1.67 anton 7694: * Input Sources::
7695: * Number Conversion::
7696: * Interpret/Compile states::
7697: * Interpreter Directives::
1.26 crook 7698: @end menu
1.1 anton 7699:
1.29 crook 7700: @node Input Sources, Number Conversion, The Text Interpreter, The Text Interpreter
7701: @subsection Input Sources
7702: @cindex input sources
7703: @cindex text interpreter - input sources
7704:
1.44 crook 7705: By default, the text interpreter processes input from the user input
1.29 crook 7706: device (the keyboard) when Forth starts up. The text interpreter can
7707: process input from any of these sources:
7708:
7709: @itemize @bullet
7710: @item
7711: The user input device -- the keyboard.
7712: @item
7713: A file, using the words described in @ref{Forth source files}.
7714: @item
7715: A block, using the words described in @ref{Blocks}.
7716: @item
7717: A text string, using @code{evaluate}.
7718: @end itemize
7719:
7720: A program can identify the current input device from the values of
7721: @code{source-id} and @code{blk}.
7722:
1.44 crook 7723:
1.29 crook 7724: doc-source-id
7725: doc-blk
7726:
7727: doc-save-input
7728: doc-restore-input
7729:
7730: doc-evaluate
1.1 anton 7731:
1.29 crook 7732:
1.44 crook 7733:
1.29 crook 7734: @node Number Conversion, Interpret/Compile states, Input Sources, The Text Interpreter
1.26 crook 7735: @subsection Number Conversion
7736: @cindex number conversion
7737: @cindex double-cell numbers, input format
7738: @cindex input format for double-cell numbers
7739: @cindex single-cell numbers, input format
7740: @cindex input format for single-cell numbers
7741: @cindex floating-point numbers, input format
7742: @cindex input format for floating-point numbers
1.1 anton 7743:
1.29 crook 7744: This section describes the rules that the text interpreter uses when it
7745: tries to convert a string into a number.
1.1 anton 7746:
1.26 crook 7747: Let <digit> represent any character that is a legal digit in the current
1.29 crook 7748: number base@footnote{For example, 0-9 when the number base is decimal or
7749: 0-9, A-F when the number base is hexadecimal.}.
1.1 anton 7750:
1.26 crook 7751: Let <decimal digit> represent any character in the range 0-9.
1.1 anton 7752:
1.29 crook 7753: Let @{@i{a b}@} represent the @i{optional} presence of any of the characters
7754: in the braces (@i{a} or @i{b} or neither).
1.1 anton 7755:
1.26 crook 7756: Let * represent any number of instances of the previous character
7757: (including none).
1.1 anton 7758:
1.26 crook 7759: Let any other character represent itself.
1.1 anton 7760:
1.29 crook 7761: @noindent
1.26 crook 7762: Now, the conversion rules are:
1.21 crook 7763:
1.26 crook 7764: @itemize @bullet
7765: @item
7766: A string of the form <digit><digit>* is treated as a single-precision
1.29 crook 7767: (cell-sized) positive integer. Examples are 0 123 6784532 32343212343456 42
1.26 crook 7768: @item
7769: A string of the form -<digit><digit>* is treated as a single-precision
1.29 crook 7770: (cell-sized) negative integer, and is represented using 2's-complement
1.26 crook 7771: arithmetic. Examples are -45 -5681 -0
7772: @item
7773: A string of the form <digit><digit>*.<digit>* is treated as a double-precision
1.29 crook 7774: (double-cell-sized) positive integer. Examples are 3465. 3.465 34.65
7775: (all three of these represent the same number).
1.26 crook 7776: @item
7777: A string of the form -<digit><digit>*.<digit>* is treated as a
1.29 crook 7778: double-precision (double-cell-sized) negative integer, and is
1.26 crook 7779: represented using 2's-complement arithmetic. Examples are -3465. -3.465
1.29 crook 7780: -34.65 (all three of these represent the same number).
1.26 crook 7781: @item
1.29 crook 7782: A string of the form @{+ -@}<decimal digit>@{.@}<decimal digit>*@{e
7783: E@}@{+ -@}<decimal digit><decimal digit>* is treated as a floating-point
1.35 anton 7784: number. Examples are 1e 1e0 1.e 1.e0 +1e+0 (which all represent the same
1.29 crook 7785: number) +12.E-4
1.26 crook 7786: @end itemize
1.1 anton 7787:
1.26 crook 7788: By default, the number base used for integer number conversion is given
1.35 anton 7789: by the contents of the variable @code{base}. Note that a lot of
7790: confusion can result from unexpected values of @code{base}. If you
7791: change @code{base} anywhere, make sure to save the old value and restore
7792: it afterwards. In general I recommend keeping @code{base} decimal, and
7793: using the prefixes described below for the popular non-decimal bases.
1.1 anton 7794:
1.29 crook 7795: doc-dpl
1.26 crook 7796: doc-base
7797: doc-hex
7798: doc-decimal
1.1 anton 7799:
1.44 crook 7800:
1.26 crook 7801: @cindex '-prefix for character strings
7802: @cindex &-prefix for decimal numbers
7803: @cindex %-prefix for binary numbers
7804: @cindex $-prefix for hexadecimal numbers
1.35 anton 7805: Gforth allows you to override the value of @code{base} by using a
1.29 crook 7806: prefix@footnote{Some Forth implementations provide a similar scheme by
7807: implementing @code{$} etc. as parsing words that process the subsequent
7808: number in the input stream and push it onto the stack. For example, see
7809: @cite{Number Conversion and Literals}, by Wil Baden; Forth Dimensions
7810: 20(3) pages 26--27. In such implementations, unlike in Gforth, a space
7811: is required between the prefix and the number.} before the first digit
7812: of an (integer) number. Four prefixes are supported:
1.1 anton 7813:
1.26 crook 7814: @itemize @bullet
7815: @item
1.35 anton 7816: @code{&} -- decimal
1.26 crook 7817: @item
1.35 anton 7818: @code{%} -- binary
1.26 crook 7819: @item
1.35 anton 7820: @code{$} -- hexadecimal
1.26 crook 7821: @item
1.35 anton 7822: @code{'} -- base @code{max-char+1}
1.26 crook 7823: @end itemize
1.1 anton 7824:
1.26 crook 7825: Here are some examples, with the equivalent decimal number shown after
7826: in braces:
1.1 anton 7827:
1.26 crook 7828: -$41 (-65), %1001101 (205), %1001.0001 (145 - a double-precision number),
7829: 'AB (16706; ascii A is 65, ascii B is 66, number is 65*256 + 66),
7830: 'ab (24930; ascii a is 97, ascii B is 98, number is 97*256 + 98),
7831: &905 (905), $abc (2478), $ABC (2478).
1.1 anton 7832:
1.26 crook 7833: @cindex number conversion - traps for the unwary
1.29 crook 7834: @noindent
1.26 crook 7835: Number conversion has a number of traps for the unwary:
1.1 anton 7836:
1.26 crook 7837: @itemize @bullet
7838: @item
7839: You cannot determine the current number base using the code sequence
1.35 anton 7840: @code{base @@ .} -- the number base is always 10 in the current number
7841: base. Instead, use something like @code{base @@ dec.}
1.26 crook 7842: @item
7843: If the number base is set to a value greater than 14 (for example,
7844: hexadecimal), the number 123E4 is ambiguous; the conversion rules allow
7845: it to be intepreted as either a single-precision integer or a
7846: floating-point number (Gforth treats it as an integer). The ambiguity
7847: can be resolved by explicitly stating the sign of the mantissa and/or
7848: exponent: 123E+4 or +123E4 -- if the number base is decimal, no
7849: ambiguity arises; either representation will be treated as a
7850: floating-point number.
7851: @item
1.29 crook 7852: There is a word @code{bin} but it does @i{not} set the number base!
1.26 crook 7853: It is used to specify file types.
7854: @item
1.72 anton 7855: ANS Forth requires the @code{.} of a double-precision number to be the
7856: final character in the string. Gforth allows the @code{.} to be
7857: anywhere after the first digit.
1.26 crook 7858: @item
7859: The number conversion process does not check for overflow.
7860: @item
1.72 anton 7861: In an ANS Forth program @code{base} is required to be decimal when
7862: converting floating-point numbers. In Gforth, number conversion to
7863: floating-point numbers always uses base &10, irrespective of the value
7864: of @code{base}.
1.26 crook 7865: @end itemize
1.1 anton 7866:
1.49 anton 7867: You can read numbers into your programs with the words described in
7868: @ref{Input}.
1.1 anton 7869:
1.82 anton 7870: @node Interpret/Compile states, Interpreter Directives, Number Conversion, The Text Interpreter
1.26 crook 7871: @subsection Interpret/Compile states
7872: @cindex Interpret/Compile states
1.1 anton 7873:
1.29 crook 7874: A standard program is not permitted to change @code{state}
7875: explicitly. However, it can change @code{state} implicitly, using the
7876: words @code{[} and @code{]}. When @code{[} is executed it switches
7877: @code{state} to interpret state, and therefore the text interpreter
7878: starts interpreting. When @code{]} is executed it switches @code{state}
7879: to compile state and therefore the text interpreter starts
1.44 crook 7880: compiling. The most common usage for these words is for switching into
7881: interpret state and back from within a colon definition; this technique
1.49 anton 7882: can be used to compile a literal (for an example, @pxref{Literals}) or
7883: for conditional compilation (for an example, @pxref{Interpreter
7884: Directives}).
1.44 crook 7885:
1.35 anton 7886:
7887: @c This is a bad example: It's non-standard, and it's not necessary.
7888: @c However, I can't think of a good example for switching into compile
7889: @c state when there is no current word (@code{state}-smart words are not a
7890: @c good reason). So maybe we should use an example for switching into
7891: @c interpret @code{state} in a colon def. - anton
1.44 crook 7892: @c nac-> I agree. I started out by putting in the example, then realised
7893: @c that it was non-ANS, so wrote more words around it. I hope this
7894: @c re-written version is acceptable to you. I do want to keep the example
7895: @c as it is helpful for showing what is and what is not portable, particularly
7896: @c where it outlaws a style in common use.
7897:
1.72 anton 7898: @c anton: it's more important to show what's portable. After we have done
1.83 anton 7899: @c that, we can also show what's not. In any case, I have written a
7900: @c section Compiling Words which also deals with [ ].
1.35 anton 7901:
1.44 crook 7902: @code{[} and @code{]} also give you the ability to switch into compile
7903: state and back, but we cannot think of any useful Standard application
7904: for this ability. Pre-ANS Forth textbooks have examples like this:
1.29 crook 7905:
7906: @example
7907: : AA ." this is A" ;
7908: : BB ." this is B" ;
7909: : CC ." this is C" ;
7910:
1.44 crook 7911: create table ] aa bb cc [
7912:
1.29 crook 7913: : go ( n -- ) \ n is offset into table.. 0 for 1st entry
7914: cells table + @ execute ;
7915: @end example
7916:
1.44 crook 7917: This example builds a jump table; @code{0 go} will display ``@code{this
7918: is A}''. Using @code{[} and @code{]} in this example is equivalent to
7919: defining @code{table} like this:
1.29 crook 7920:
7921: @example
1.44 crook 7922: create table ' aa COMPILE, ' bb COMPILE, ' cc COMPILE,
1.29 crook 7923: @end example
7924:
1.44 crook 7925: The problem with this code is that the definition of @code{table} is not
7926: portable -- it @i{compile}s execution tokens into code space. Whilst it
7927: @i{may} work on systems where code space and data space co-incide, the
1.29 crook 7928: Standard only allows data space to be assigned for a @code{CREATE}d
7929: word. In addition, the Standard only allows @code{@@} to access data
7930: space, whilst this example is using it to access code space. The only
7931: portable, Standard way to build this table is to build it in data space,
7932: like this:
7933:
7934: @example
7935: create table ' aa , ' bb , ' cc ,
7936: @end example
7937:
1.26 crook 7938: doc-state
1.44 crook 7939:
1.29 crook 7940:
1.82 anton 7941: @node Interpreter Directives, , Interpret/Compile states, The Text Interpreter
1.26 crook 7942: @subsection Interpreter Directives
7943: @cindex interpreter directives
1.72 anton 7944: @cindex conditional compilation
1.1 anton 7945:
1.29 crook 7946: These words are usually used in interpret state; typically to control
7947: which parts of a source file are processed by the text
1.26 crook 7948: interpreter. There are only a few ANS Forth Standard words, but Gforth
7949: supplements these with a rich set of immediate control structure words
7950: to compensate for the fact that the non-immediate versions can only be
1.29 crook 7951: used in compile state (@pxref{Control Structures}). Typical usages:
7952:
7953: @example
1.72 anton 7954: FALSE Constant HAVE-ASSEMBLER
1.29 crook 7955: .
7956: .
1.72 anton 7957: HAVE-ASSEMBLER [IF]
1.29 crook 7958: : ASSEMBLER-FEATURE
7959: ...
7960: ;
7961: [ENDIF]
7962: .
7963: .
7964: : SEE
7965: ... \ general-purpose SEE code
1.72 anton 7966: [ HAVE-ASSEMBLER [IF] ]
1.29 crook 7967: ... \ assembler-specific SEE code
7968: [ [ENDIF] ]
7969: ;
7970: @end example
1.1 anton 7971:
1.44 crook 7972:
1.26 crook 7973: doc-[IF]
7974: doc-[ELSE]
7975: doc-[THEN]
7976: doc-[ENDIF]
1.1 anton 7977:
1.26 crook 7978: doc-[IFDEF]
7979: doc-[IFUNDEF]
1.1 anton 7980:
1.26 crook 7981: doc-[?DO]
7982: doc-[DO]
7983: doc-[FOR]
7984: doc-[LOOP]
7985: doc-[+LOOP]
7986: doc-[NEXT]
1.1 anton 7987:
1.26 crook 7988: doc-[BEGIN]
7989: doc-[UNTIL]
7990: doc-[AGAIN]
7991: doc-[WHILE]
7992: doc-[REPEAT]
1.1 anton 7993:
1.27 crook 7994:
1.26 crook 7995: @c -------------------------------------------------------------
1.47 crook 7996: @node Word Lists, Environmental Queries, The Text Interpreter, Words
1.26 crook 7997: @section Word Lists
7998: @cindex word lists
1.32 anton 7999: @cindex header space
1.1 anton 8000:
1.36 anton 8001: A wordlist is a list of named words; you can add new words and look up
8002: words by name (and you can remove words in a restricted way with
8003: markers). Every named (and @code{reveal}ed) word is in one wordlist.
8004:
8005: @cindex search order stack
8006: The text interpreter searches the wordlists present in the search order
8007: (a stack of wordlists), from the top to the bottom. Within each
8008: wordlist, the search starts conceptually at the newest word; i.e., if
8009: two words in a wordlist have the same name, the newer word is found.
1.1 anton 8010:
1.26 crook 8011: @cindex compilation word list
1.36 anton 8012: New words are added to the @dfn{compilation wordlist} (aka current
8013: wordlist).
1.1 anton 8014:
1.36 anton 8015: @cindex wid
8016: A word list is identified by a cell-sized word list identifier (@i{wid})
8017: in much the same way as a file is identified by a file handle. The
8018: numerical value of the wid has no (portable) meaning, and might change
8019: from session to session.
1.1 anton 8020:
1.29 crook 8021: The ANS Forth ``Search order'' word set is intended to provide a set of
8022: low-level tools that allow various different schemes to be
1.74 anton 8023: implemented. Gforth also provides @code{vocabulary}, a traditional Forth
1.26 crook 8024: word. @file{compat/vocabulary.fs} provides an implementation in ANS
1.45 crook 8025: Forth.
1.1 anton 8026:
1.27 crook 8027: @comment TODO: locals section refers to here, saying that every word list (aka
8028: @comment vocabulary) has its own methods for searching etc. Need to document that.
1.78 anton 8029: @c anton: but better in a separate subsection on wordlist internals
1.1 anton 8030:
1.45 crook 8031: @comment TODO: document markers, reveal, tables, mappedwordlist
8032:
8033: @comment the gforthman- prefix is used to pick out the true definition of a
1.27 crook 8034: @comment word from the source files, rather than some alias.
1.44 crook 8035:
1.26 crook 8036: doc-forth-wordlist
8037: doc-definitions
8038: doc-get-current
8039: doc-set-current
8040: doc-get-order
1.45 crook 8041: doc---gforthman-set-order
1.26 crook 8042: doc-wordlist
1.30 anton 8043: doc-table
1.79 anton 8044: doc->order
1.36 anton 8045: doc-previous
1.26 crook 8046: doc-also
1.45 crook 8047: doc---gforthman-forth
1.26 crook 8048: doc-only
1.45 crook 8049: doc---gforthman-order
1.15 anton 8050:
1.26 crook 8051: doc-find
8052: doc-search-wordlist
1.15 anton 8053:
1.26 crook 8054: doc-words
8055: doc-vlist
1.44 crook 8056: @c doc-words-deferred
1.1 anton 8057:
1.74 anton 8058: @c doc-mappedwordlist @c map-structure undefined, implemantation-specific
1.26 crook 8059: doc-root
8060: doc-vocabulary
8061: doc-seal
8062: doc-vocs
8063: doc-current
8064: doc-context
1.1 anton 8065:
1.44 crook 8066:
1.26 crook 8067: @menu
1.75 anton 8068: * Vocabularies::
1.67 anton 8069: * Why use word lists?::
1.75 anton 8070: * Word list example::
1.26 crook 8071: @end menu
8072:
1.75 anton 8073: @node Vocabularies, Why use word lists?, Word Lists, Word Lists
8074: @subsection Vocabularies
8075: @cindex Vocabularies, detailed explanation
8076:
8077: Here is an example of creating and using a new wordlist using ANS
8078: Forth words:
8079:
8080: @example
8081: wordlist constant my-new-words-wordlist
8082: : my-new-words get-order nip my-new-words-wordlist swap set-order ;
8083:
8084: \ add it to the search order
8085: also my-new-words
8086:
8087: \ alternatively, add it to the search order and make it
8088: \ the compilation word list
8089: also my-new-words definitions
8090: \ type "order" to see the problem
8091: @end example
8092:
8093: The problem with this example is that @code{order} has no way to
8094: associate the name @code{my-new-words} with the wid of the word list (in
8095: Gforth, @code{order} and @code{vocs} will display @code{???} for a wid
8096: that has no associated name). There is no Standard way of associating a
8097: name with a wid.
8098:
8099: In Gforth, this example can be re-coded using @code{vocabulary}, which
8100: associates a name with a wid:
8101:
8102: @example
8103: vocabulary my-new-words
8104:
8105: \ add it to the search order
8106: also my-new-words
8107:
8108: \ alternatively, add it to the search order and make it
8109: \ the compilation word list
8110: my-new-words definitions
8111: \ type "order" to see that the problem is solved
8112: @end example
8113:
8114:
8115: @node Why use word lists?, Word list example, Vocabularies, Word Lists
1.26 crook 8116: @subsection Why use word lists?
8117: @cindex word lists - why use them?
8118:
1.74 anton 8119: Here are some reasons why people use wordlists:
1.26 crook 8120:
8121: @itemize @bullet
1.74 anton 8122:
8123: @c anton: Gforth's hashing implementation makes the search speed
8124: @c independent from the number of words. But it is linear with the number
8125: @c of wordlists that have to be searched, so in effect using more wordlists
8126: @c actually slows down compilation.
8127:
8128: @c @item
8129: @c To improve compilation speed by reducing the number of header space
8130: @c entries that must be searched. This is achieved by creating a new
8131: @c word list that contains all of the definitions that are used in the
8132: @c definition of a Forth system but which would not usually be used by
8133: @c programs running on that system. That word list would be on the search
8134: @c list when the Forth system was compiled but would be removed from the
8135: @c search list for normal operation. This can be a useful technique for
8136: @c low-performance systems (for example, 8-bit processors in embedded
8137: @c systems) but is unlikely to be necessary in high-performance desktop
8138: @c systems.
8139:
1.26 crook 8140: @item
8141: To prevent a set of words from being used outside the context in which
8142: they are valid. Two classic examples of this are an integrated editor
8143: (all of the edit commands are defined in a separate word list; the
8144: search order is set to the editor word list when the editor is invoked;
8145: the old search order is restored when the editor is terminated) and an
8146: integrated assembler (the op-codes for the machine are defined in a
8147: separate word list which is used when a @code{CODE} word is defined).
1.74 anton 8148:
8149: @item
8150: To organize the words of an application or library into a user-visible
8151: set (in @code{forth-wordlist} or some other common wordlist) and a set
8152: of helper words used just for the implementation (hidden in a separate
1.75 anton 8153: wordlist). This keeps @code{words}' output smaller, separates
8154: implementation and interface, and reduces the chance of name conflicts
8155: within the common wordlist.
1.74 anton 8156:
1.26 crook 8157: @item
8158: To prevent a name-space clash between multiple definitions with the same
8159: name. For example, when building a cross-compiler you might have a word
8160: @code{IF} that generates conditional code for your target system. By
8161: placing this definition in a different word list you can control whether
8162: the host system's @code{IF} or the target system's @code{IF} get used in
8163: any particular context by controlling the order of the word lists on the
8164: search order stack.
1.74 anton 8165:
1.26 crook 8166: @end itemize
1.1 anton 8167:
1.74 anton 8168: The downsides of using wordlists are:
8169:
8170: @itemize
8171:
8172: @item
8173: Debugging becomes more cumbersome.
8174:
8175: @item
8176: Name conflicts worked around with wordlists are still there, and you
8177: have to arrange the search order carefully to get the desired results;
8178: if you forget to do that, you get hard-to-find errors (as in any case
8179: where you read the code differently from the compiler; @code{see} can
1.75 anton 8180: help seeing which of several possible words the name resolves to in such
8181: cases). @code{See} displays just the name of the words, not what
8182: wordlist they belong to, so it might be misleading. Using unique names
8183: is a better approach to avoid name conflicts.
1.74 anton 8184:
8185: @item
8186: You have to explicitly undo any changes to the search order. In many
8187: cases it would be more convenient if this happened implicitly. Gforth
8188: currently does not provide such a feature, but it may do so in the
8189: future.
8190: @end itemize
8191:
8192:
1.75 anton 8193: @node Word list example, , Why use word lists?, Word Lists
8194: @subsection Word list example
8195: @cindex word lists - example
1.1 anton 8196:
1.74 anton 8197: The following example is from the
8198: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
8199: garbage collector} and uses wordlists to separate public words from
8200: helper words:
8201:
8202: @example
8203: get-current ( wid )
8204: vocabulary garbage-collector also garbage-collector definitions
8205: ... \ define helper words
8206: ( wid ) set-current \ restore original (i.e., public) compilation wordlist
8207: ... \ define the public (i.e., API) words
8208: \ they can refer to the helper words
8209: previous \ restore original search order (helper words become invisible)
8210: @end example
8211:
1.26 crook 8212: @c -------------------------------------------------------------
8213: @node Environmental Queries, Files, Word Lists, Words
8214: @section Environmental Queries
8215: @cindex environmental queries
1.21 crook 8216:
1.26 crook 8217: ANS Forth introduced the idea of ``environmental queries'' as a way
8218: for a program running on a system to determine certain characteristics of the system.
8219: The Standard specifies a number of strings that might be recognised by a system.
1.21 crook 8220:
1.32 anton 8221: The Standard requires that the header space used for environmental queries
8222: be distinct from the header space used for definitions.
1.21 crook 8223:
1.26 crook 8224: Typically, environmental queries are supported by creating a set of
1.29 crook 8225: definitions in a word list that is @i{only} used during environmental
1.26 crook 8226: queries; that is what Gforth does. There is no Standard way of adding
8227: definitions to the set of recognised environmental queries, but any
8228: implementation that supports the loading of optional word sets must have
8229: some mechanism for doing this (after loading the word set, the
8230: associated environmental query string must return @code{true}). In
8231: Gforth, the word list used to honour environmental queries can be
8232: manipulated just like any other word list.
1.21 crook 8233:
1.44 crook 8234:
1.26 crook 8235: doc-environment?
8236: doc-environment-wordlist
1.21 crook 8237:
1.26 crook 8238: doc-gforth
8239: doc-os-class
1.21 crook 8240:
1.44 crook 8241:
1.26 crook 8242: Note that, whilst the documentation for (e.g.) @code{gforth} shows it
8243: returning two items on the stack, querying it using @code{environment?}
8244: will return an additional item; the @code{true} flag that shows that the
8245: string was recognised.
1.21 crook 8246:
1.26 crook 8247: @comment TODO Document the standard strings or note where they are documented herein
1.21 crook 8248:
1.26 crook 8249: Here are some examples of using environmental queries:
1.21 crook 8250:
1.26 crook 8251: @example
8252: s" address-unit-bits" environment? 0=
8253: [IF]
8254: cr .( environmental attribute address-units-bits unknown... ) cr
1.75 anton 8255: [ELSE]
8256: drop \ ensure balanced stack effect
1.26 crook 8257: [THEN]
1.21 crook 8258:
1.75 anton 8259: \ this might occur in the prelude of a standard program that uses THROW
8260: s" exception" environment? [IF]
8261: 0= [IF]
8262: : throw abort" exception thrown" ;
8263: [THEN]
8264: [ELSE] \ we don't know, so make sure
8265: : throw abort" exception thrown" ;
8266: [THEN]
1.21 crook 8267:
1.26 crook 8268: s" gforth" environment? [IF] .( Gforth version ) TYPE
8269: [ELSE] .( Not Gforth..) [THEN]
1.75 anton 8270:
8271: \ a program using v*
8272: s" gforth" environment? [IF]
8273: s" 0.5.0" compare 0< [IF] \ v* is a primitive since 0.5.0
8274: : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
8275: >r swap 2swap swap 0e r> 0 ?DO
8276: dup f@ over + 2swap dup f@ f* f+ over + 2swap
8277: LOOP
8278: 2drop 2drop ;
8279: [THEN]
8280: [ELSE] \
8281: : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
8282: ...
8283: [THEN]
1.26 crook 8284: @end example
1.21 crook 8285:
1.26 crook 8286: Here is an example of adding a definition to the environment word list:
1.21 crook 8287:
1.26 crook 8288: @example
8289: get-current environment-wordlist set-current
8290: true constant block
8291: true constant block-ext
8292: set-current
8293: @end example
1.21 crook 8294:
1.26 crook 8295: You can see what definitions are in the environment word list like this:
1.21 crook 8296:
1.26 crook 8297: @example
1.79 anton 8298: environment-wordlist >order words previous
1.26 crook 8299: @end example
1.21 crook 8300:
8301:
1.26 crook 8302: @c -------------------------------------------------------------
8303: @node Files, Blocks, Environmental Queries, Words
8304: @section Files
1.28 crook 8305: @cindex files
8306: @cindex I/O - file-handling
1.21 crook 8307:
1.26 crook 8308: Gforth provides facilities for accessing files that are stored in the
8309: host operating system's file-system. Files that are processed by Gforth
8310: can be divided into two categories:
1.21 crook 8311:
1.23 crook 8312: @itemize @bullet
8313: @item
1.29 crook 8314: Files that are processed by the Text Interpreter (@dfn{Forth source files}).
1.23 crook 8315: @item
1.29 crook 8316: Files that are processed by some other program (@dfn{general files}).
1.26 crook 8317: @end itemize
8318:
8319: @menu
1.48 anton 8320: * Forth source files::
8321: * General files::
8322: * Search Paths::
1.26 crook 8323: @end menu
8324:
8325: @c -------------------------------------------------------------
8326: @node Forth source files, General files, Files, Files
8327: @subsection Forth source files
8328: @cindex including files
8329: @cindex Forth source files
1.21 crook 8330:
1.26 crook 8331: The simplest way to interpret the contents of a file is to use one of
8332: these two formats:
1.21 crook 8333:
1.26 crook 8334: @example
8335: include mysource.fs
8336: s" mysource.fs" included
8337: @end example
1.21 crook 8338:
1.75 anton 8339: You usually want to include a file only if it is not included already
1.26 crook 8340: (by, say, another source file). In that case, you can use one of these
1.45 crook 8341: three formats:
1.21 crook 8342:
1.26 crook 8343: @example
8344: require mysource.fs
8345: needs mysource.fs
8346: s" mysource.fs" required
8347: @end example
1.21 crook 8348:
1.26 crook 8349: @cindex stack effect of included files
8350: @cindex including files, stack effect
1.45 crook 8351: It is good practice to write your source files such that interpreting them
8352: does not change the stack. Source files designed in this way can be used with
1.26 crook 8353: @code{required} and friends without complications. For example:
1.21 crook 8354:
1.26 crook 8355: @example
1.75 anton 8356: 1024 require foo.fs drop
1.26 crook 8357: @end example
1.21 crook 8358:
1.75 anton 8359: Here you want to pass the argument 1024 (e.g., a buffer size) to
8360: @file{foo.fs}. Interpreting @file{foo.fs} has the stack effect ( n -- n
8361: ), which allows its use with @code{require}. Of course with such
8362: parameters to required files, you have to ensure that the first
8363: @code{require} fits for all uses (i.e., @code{require} it early in the
8364: master load file).
1.44 crook 8365:
1.26 crook 8366: doc-include-file
8367: doc-included
1.28 crook 8368: doc-included?
1.26 crook 8369: doc-include
8370: doc-required
8371: doc-require
8372: doc-needs
1.75 anton 8373: @c doc-init-included-files @c internal
8374: @c doc-loadfilename @c internal word
8375: doc-sourcefilename
8376: doc-sourceline#
1.44 crook 8377:
1.26 crook 8378: A definition in ANS Forth for @code{required} is provided in
8379: @file{compat/required.fs}.
1.21 crook 8380:
1.26 crook 8381: @c -------------------------------------------------------------
8382: @node General files, Search Paths, Forth source files, Files
8383: @subsection General files
8384: @cindex general files
8385: @cindex file-handling
1.21 crook 8386:
1.75 anton 8387: Files are opened/created by name and type. The following file access
8388: methods (FAMs) are recognised:
1.44 crook 8389:
1.75 anton 8390: @cindex fam (file access method)
1.26 crook 8391: doc-r/o
8392: doc-r/w
8393: doc-w/o
8394: doc-bin
1.1 anton 8395:
1.44 crook 8396:
1.26 crook 8397: When a file is opened/created, it returns a file identifier,
1.29 crook 8398: @i{wfileid} that is used for all other file commands. All file
8399: commands also return a status value, @i{wior}, that is 0 for a
1.26 crook 8400: successful operation and an implementation-defined non-zero value in the
8401: case of an error.
1.21 crook 8402:
1.44 crook 8403:
1.26 crook 8404: doc-open-file
8405: doc-create-file
1.21 crook 8406:
1.26 crook 8407: doc-close-file
8408: doc-delete-file
8409: doc-rename-file
8410: doc-read-file
8411: doc-read-line
8412: doc-write-file
8413: doc-write-line
8414: doc-emit-file
8415: doc-flush-file
1.21 crook 8416:
1.26 crook 8417: doc-file-status
8418: doc-file-position
8419: doc-reposition-file
8420: doc-file-size
8421: doc-resize-file
1.21 crook 8422:
1.44 crook 8423:
1.26 crook 8424: @c ---------------------------------------------------------
1.48 anton 8425: @node Search Paths, , General files, Files
1.26 crook 8426: @subsection Search Paths
8427: @cindex path for @code{included}
8428: @cindex file search path
8429: @cindex @code{include} search path
8430: @cindex search path for files
1.21 crook 8431:
1.26 crook 8432: If you specify an absolute filename (i.e., a filename starting with
8433: @file{/} or @file{~}, or with @file{:} in the second position (as in
8434: @samp{C:...})) for @code{included} and friends, that file is included
8435: just as you would expect.
1.21 crook 8436:
1.75 anton 8437: If the filename starts with @file{./}, this refers to the directory that
8438: the present file was @code{included} from. This allows files to include
8439: other files relative to their own position (irrespective of the current
8440: working directory or the absolute position). This feature is essential
8441: for libraries consisting of several files, where a file may include
8442: other files from the library. It corresponds to @code{#include "..."}
8443: in C. If the current input source is not a file, @file{.} refers to the
8444: directory of the innermost file being included, or, if there is no file
8445: being included, to the current working directory.
8446:
8447: For relative filenames (not starting with @file{./}), Gforth uses a
8448: search path similar to Forth's search order (@pxref{Word Lists}). It
8449: tries to find the given filename in the directories present in the path,
8450: and includes the first one it finds. There are separate search paths for
8451: Forth source files and general files. If the search path contains the
8452: directory @file{.}, this refers to the directory of the current file, or
8453: the working directory, as if the file had been specified with @file{./}.
1.21 crook 8454:
1.26 crook 8455: Use @file{~+} to refer to the current working directory (as in the
8456: @code{bash}).
1.1 anton 8457:
1.75 anton 8458: @c anton: fold the following subsubsections into this subsection?
1.1 anton 8459:
1.48 anton 8460: @menu
1.75 anton 8461: * Source Search Paths::
1.48 anton 8462: * General Search Paths::
8463: @end menu
8464:
1.26 crook 8465: @c ---------------------------------------------------------
1.75 anton 8466: @node Source Search Paths, General Search Paths, Search Paths, Search Paths
8467: @subsubsection Source Search Paths
8468: @cindex search path control, source files
1.5 anton 8469:
1.26 crook 8470: The search path is initialized when you start Gforth (@pxref{Invoking
1.75 anton 8471: Gforth}). You can display it and change it using @code{fpath} in
8472: combination with the general path handling words.
1.5 anton 8473:
1.75 anton 8474: doc-fpath
8475: @c the functionality of the following words is easily available through
8476: @c fpath and the general path words. The may go away.
8477: @c doc-.fpath
8478: @c doc-fpath+
8479: @c doc-fpath=
8480: @c doc-open-fpath-file
1.44 crook 8481:
8482: @noindent
1.26 crook 8483: Here is an example of using @code{fpath} and @code{require}:
1.5 anton 8484:
1.26 crook 8485: @example
1.75 anton 8486: fpath path= /usr/lib/forth/|./
1.26 crook 8487: require timer.fs
8488: @end example
1.5 anton 8489:
1.75 anton 8490:
1.26 crook 8491: @c ---------------------------------------------------------
1.75 anton 8492: @node General Search Paths, , Source Search Paths, Search Paths
1.26 crook 8493: @subsubsection General Search Paths
1.75 anton 8494: @cindex search path control, source files
1.5 anton 8495:
1.26 crook 8496: Your application may need to search files in several directories, like
8497: @code{included} does. To facilitate this, Gforth allows you to define
8498: and use your own search paths, by providing generic equivalents of the
8499: Forth search path words:
1.5 anton 8500:
1.75 anton 8501: doc-open-path-file
8502: doc-path-allot
8503: doc-clear-path
8504: doc-also-path
1.26 crook 8505: doc-.path
8506: doc-path+
8507: doc-path=
1.5 anton 8508:
1.75 anton 8509: @c anton: better define a word for it, say "path-allot ( ucount -- path-addr )
1.44 crook 8510:
1.75 anton 8511: Here's an example of creating an empty search path:
8512: @c
1.26 crook 8513: @example
1.75 anton 8514: create mypath 500 path-allot \ maximum length 500 chars (is checked)
1.26 crook 8515: @end example
1.5 anton 8516:
1.26 crook 8517: @c -------------------------------------------------------------
8518: @node Blocks, Other I/O, Files, Words
8519: @section Blocks
1.28 crook 8520: @cindex I/O - blocks
8521: @cindex blocks
8522:
8523: When you run Gforth on a modern desk-top computer, it runs under the
8524: control of an operating system which provides certain services. One of
8525: these services is @var{file services}, which allows Forth source code
8526: and data to be stored in files and read into Gforth (@pxref{Files}).
8527:
8528: Traditionally, Forth has been an important programming language on
8529: systems where it has interfaced directly to the underlying hardware with
8530: no intervening operating system. Forth provides a mechanism, called
1.29 crook 8531: @dfn{blocks}, for accessing mass storage on such systems.
1.28 crook 8532:
8533: A block is a 1024-byte data area, which can be used to hold data or
8534: Forth source code. No structure is imposed on the contents of the
8535: block. A block is identified by its number; blocks are numbered
8536: contiguously from 1 to an implementation-defined maximum.
8537:
8538: A typical system that used blocks but no operating system might use a
8539: single floppy-disk drive for mass storage, with the disks formatted to
8540: provide 256-byte sectors. Blocks would be implemented by assigning the
8541: first four sectors of the disk to block 1, the second four sectors to
8542: block 2 and so on, up to the limit of the capacity of the disk. The disk
8543: would not contain any file system information, just the set of blocks.
8544:
1.29 crook 8545: @cindex blocks file
1.28 crook 8546: On systems that do provide file services, blocks are typically
1.29 crook 8547: implemented by storing a sequence of blocks within a single @dfn{blocks
1.28 crook 8548: file}. The size of the blocks file will be an exact multiple of 1024
8549: bytes, corresponding to the number of blocks it contains. This is the
8550: mechanism that Gforth uses.
8551:
1.29 crook 8552: @cindex @file{blocks.fb}
1.75 anton 8553: Only one blocks file can be open at a time. If you use block words without
1.28 crook 8554: having specified a blocks file, Gforth defaults to the blocks file
8555: @file{blocks.fb}. Gforth uses the Forth search path when attempting to
1.75 anton 8556: locate a blocks file (@pxref{Source Search Paths}).
1.28 crook 8557:
1.29 crook 8558: @cindex block buffers
1.28 crook 8559: When you read and write blocks under program control, Gforth uses a
1.29 crook 8560: number of @dfn{block buffers} as intermediate storage. These buffers are
1.28 crook 8561: not used when you use @code{load} to interpret the contents of a block.
8562:
1.75 anton 8563: The behaviour of the block buffers is analagous to that of a cache.
8564: Each block buffer has three states:
1.28 crook 8565:
8566: @itemize @bullet
8567: @item
8568: Unassigned
8569: @item
8570: Assigned-clean
8571: @item
8572: Assigned-dirty
8573: @end itemize
8574:
1.29 crook 8575: Initially, all block buffers are @i{unassigned}. In order to access a
1.28 crook 8576: block, the block (specified by its block number) must be assigned to a
8577: block buffer.
8578:
8579: The assignment of a block to a block buffer is performed by @code{block}
8580: or @code{buffer}. Use @code{block} when you wish to modify the existing
8581: contents of a block. Use @code{buffer} when you don't care about the
8582: existing contents of the block@footnote{The ANS Forth definition of
1.35 anton 8583: @code{buffer} is intended not to cause disk I/O; if the data associated
1.28 crook 8584: with the particular block is already stored in a block buffer due to an
8585: earlier @code{block} command, @code{buffer} will return that block
8586: buffer and the existing contents of the block will be
8587: available. Otherwise, @code{buffer} will simply assign a new, empty
1.29 crook 8588: block buffer for the block.}.
1.28 crook 8589:
1.47 crook 8590: Once a block has been assigned to a block buffer using @code{block} or
1.75 anton 8591: @code{buffer}, that block buffer becomes the @i{current block
8592: buffer}. Data may only be manipulated (read or written) within the
8593: current block buffer.
1.47 crook 8594:
8595: When the contents of the current block buffer has been modified it is
1.48 anton 8596: necessary, @emph{before calling @code{block} or @code{buffer} again}, to
1.75 anton 8597: either abandon the changes (by doing nothing) or mark the block as
8598: changed (assigned-dirty), using @code{update}. Using @code{update} does
8599: not change the blocks file; it simply changes a block buffer's state to
8600: @i{assigned-dirty}. The block will be written implicitly when it's
8601: buffer is needed for another block, or explicitly by @code{flush} or
8602: @code{save-buffers}.
8603:
8604: word @code{Flush} writes all @i{assigned-dirty} blocks back to the
8605: blocks file on disk. Leaving Gforth with @code{bye} also performs a
8606: @code{flush}.
1.28 crook 8607:
1.29 crook 8608: In Gforth, @code{block} and @code{buffer} use a @i{direct-mapped}
1.28 crook 8609: algorithm to assign a block buffer to a block. That means that any
8610: particular block can only be assigned to one specific block buffer,
1.29 crook 8611: called (for the particular operation) the @i{victim buffer}. If the
1.47 crook 8612: victim buffer is @i{unassigned} or @i{assigned-clean} it is allocated to
8613: the new block immediately. If it is @i{assigned-dirty} its current
8614: contents are written back to the blocks file on disk before it is
1.28 crook 8615: allocated to the new block.
8616:
8617: Although no structure is imposed on the contents of a block, it is
8618: traditional to display the contents as 16 lines each of 64 characters. A
8619: block provides a single, continuous stream of input (for example, it
8620: acts as a single parse area) -- there are no end-of-line characters
8621: within a block, and no end-of-file character at the end of a
8622: block. There are two consequences of this:
1.26 crook 8623:
1.28 crook 8624: @itemize @bullet
8625: @item
8626: The last character of one line wraps straight into the first character
8627: of the following line
8628: @item
8629: The word @code{\} -- comment to end of line -- requires special
8630: treatment; in the context of a block it causes all characters until the
8631: end of the current 64-character ``line'' to be ignored.
8632: @end itemize
8633:
8634: In Gforth, when you use @code{block} with a non-existent block number,
1.45 crook 8635: the current blocks file will be extended to the appropriate size and the
1.28 crook 8636: block buffer will be initialised with spaces.
8637:
1.47 crook 8638: Gforth includes a simple block editor (type @code{use blocked.fb 0 list}
8639: for details) but doesn't encourage the use of blocks; the mechanism is
8640: only provided for backward compatibility -- ANS Forth requires blocks to
8641: be available when files are.
1.28 crook 8642:
8643: Common techniques that are used when working with blocks include:
8644:
8645: @itemize @bullet
8646: @item
8647: A screen editor that allows you to edit blocks without leaving the Forth
8648: environment.
8649: @item
8650: Shadow screens; where every code block has an associated block
8651: containing comments (for example: code in odd block numbers, comments in
8652: even block numbers). Typically, the block editor provides a convenient
8653: mechanism to toggle between code and comments.
8654: @item
8655: Load blocks; a single block (typically block 1) contains a number of
8656: @code{thru} commands which @code{load} the whole of the application.
8657: @end itemize
1.26 crook 8658:
1.29 crook 8659: See Frank Sergeant's Pygmy Forth to see just how well blocks can be
8660: integrated into a Forth programming environment.
1.26 crook 8661:
8662: @comment TODO what about errors on open-blocks?
1.44 crook 8663:
1.26 crook 8664: doc-open-blocks
8665: doc-use
1.75 anton 8666: doc-block-offset
1.26 crook 8667: doc-get-block-fid
8668: doc-block-position
1.28 crook 8669:
1.75 anton 8670: doc-list
1.28 crook 8671: doc-scr
8672:
1.45 crook 8673: doc---gforthman-block
1.28 crook 8674: doc-buffer
8675:
1.75 anton 8676: doc-empty-buffers
8677: doc-empty-buffer
1.26 crook 8678: doc-update
1.28 crook 8679: doc-updated?
1.26 crook 8680: doc-save-buffers
1.75 anton 8681: doc-save-buffer
1.26 crook 8682: doc-flush
1.28 crook 8683:
1.26 crook 8684: doc-load
8685: doc-thru
8686: doc-+load
8687: doc-+thru
1.45 crook 8688: doc---gforthman--->
1.26 crook 8689: doc-block-included
8690:
1.44 crook 8691:
1.26 crook 8692: @c -------------------------------------------------------------
1.78 anton 8693: @node Other I/O, Locals, Blocks, Words
1.26 crook 8694: @section Other I/O
1.28 crook 8695: @cindex I/O - keyboard and display
1.26 crook 8696:
8697: @menu
8698: * Simple numeric output:: Predefined formats
8699: * Formatted numeric output:: Formatted (pictured) output
8700: * String Formats:: How Forth stores strings in memory
1.67 anton 8701: * Displaying characters and strings:: Other stuff
1.26 crook 8702: * Input:: Input
8703: @end menu
8704:
8705: @node Simple numeric output, Formatted numeric output, Other I/O, Other I/O
8706: @subsection Simple numeric output
1.28 crook 8707: @cindex numeric output - simple/free-format
1.5 anton 8708:
1.26 crook 8709: The simplest output functions are those that display numbers from the
8710: data or floating-point stacks. Floating-point output is always displayed
8711: using base 10. Numbers displayed from the data stack use the value stored
8712: in @code{base}.
1.5 anton 8713:
1.44 crook 8714:
1.26 crook 8715: doc-.
8716: doc-dec.
8717: doc-hex.
8718: doc-u.
8719: doc-.r
8720: doc-u.r
8721: doc-d.
8722: doc-ud.
8723: doc-d.r
8724: doc-ud.r
8725: doc-f.
8726: doc-fe.
8727: doc-fs.
1.5 anton 8728:
1.44 crook 8729:
1.26 crook 8730: Examples of printing the number 1234.5678E23 in the different floating-point output
8731: formats are shown below:
1.5 anton 8732:
8733: @example
1.26 crook 8734: f. 123456779999999000000000000.
8735: fe. 123.456779999999E24
8736: fs. 1.23456779999999E26
1.5 anton 8737: @end example
8738:
8739:
1.26 crook 8740: @node Formatted numeric output, String Formats, Simple numeric output, Other I/O
8741: @subsection Formatted numeric output
1.28 crook 8742: @cindex formatted numeric output
1.26 crook 8743: @cindex pictured numeric output
1.28 crook 8744: @cindex numeric output - formatted
1.26 crook 8745:
1.29 crook 8746: Forth traditionally uses a technique called @dfn{pictured numeric
1.26 crook 8747: output} for formatted printing of integers. In this technique, digits
8748: are extracted from the number (using the current output radix defined by
8749: @code{base}), converted to ASCII codes and appended to a string that is
8750: built in a scratch-pad area of memory (@pxref{core-idef,
8751: Implementation-defined options, Implementation-defined
8752: options}). Arbitrary characters can be appended to the string during the
8753: extraction process. The completed string is specified by an address
8754: and length and can be manipulated (@code{TYPE}ed, copied, modified)
8755: under program control.
1.5 anton 8756:
1.75 anton 8757: All of the integer output words described in the previous section
8758: (@pxref{Simple numeric output}) are implemented in Gforth using pictured
8759: numeric output.
1.5 anton 8760:
1.47 crook 8761: Three important things to remember about pictured numeric output:
1.5 anton 8762:
1.26 crook 8763: @itemize @bullet
8764: @item
1.28 crook 8765: It always operates on double-precision numbers; to display a
1.49 anton 8766: single-precision number, convert it first (for ways of doing this
8767: @pxref{Double precision}).
1.26 crook 8768: @item
1.28 crook 8769: It always treats the double-precision number as though it were
8770: unsigned. The examples below show ways of printing signed numbers.
1.26 crook 8771: @item
8772: The string is built up from right to left; least significant digit first.
8773: @end itemize
1.5 anton 8774:
1.44 crook 8775:
1.26 crook 8776: doc-<#
1.47 crook 8777: doc-<<#
1.26 crook 8778: doc-#
8779: doc-#s
8780: doc-hold
8781: doc-sign
8782: doc-#>
1.47 crook 8783: doc-#>>
1.5 anton 8784:
1.26 crook 8785: doc-represent
1.5 anton 8786:
1.44 crook 8787:
8788: @noindent
1.26 crook 8789: Here are some examples of using pictured numeric output:
1.5 anton 8790:
8791: @example
1.26 crook 8792: : my-u. ( u -- )
8793: \ Simplest use of pns.. behaves like Standard u.
8794: 0 \ convert to unsigned double
1.75 anton 8795: <<# \ start conversion
1.26 crook 8796: #s \ convert all digits
8797: #> \ complete conversion
1.75 anton 8798: TYPE SPACE \ display, with trailing space
8799: #>> ; \ release hold area
1.5 anton 8800:
1.26 crook 8801: : cents-only ( u -- )
8802: 0 \ convert to unsigned double
1.75 anton 8803: <<# \ start conversion
1.26 crook 8804: # # \ convert two least-significant digits
8805: #> \ complete conversion, discard other digits
1.75 anton 8806: TYPE SPACE \ display, with trailing space
8807: #>> ; \ release hold area
1.5 anton 8808:
1.26 crook 8809: : dollars-and-cents ( u -- )
8810: 0 \ convert to unsigned double
1.75 anton 8811: <<# \ start conversion
1.26 crook 8812: # # \ convert two least-significant digits
8813: [char] . hold \ insert decimal point
8814: #s \ convert remaining digits
8815: [char] $ hold \ append currency symbol
8816: #> \ complete conversion
1.75 anton 8817: TYPE SPACE \ display, with trailing space
8818: #>> ; \ release hold area
1.5 anton 8819:
1.26 crook 8820: : my-. ( n -- )
8821: \ handling negatives.. behaves like Standard .
8822: s>d \ convert to signed double
8823: swap over dabs \ leave sign byte followed by unsigned double
1.75 anton 8824: <<# \ start conversion
1.26 crook 8825: #s \ convert all digits
8826: rot sign \ get at sign byte, append "-" if needed
8827: #> \ complete conversion
1.75 anton 8828: TYPE SPACE \ display, with trailing space
8829: #>> ; \ release hold area
1.5 anton 8830:
1.26 crook 8831: : account. ( n -- )
1.75 anton 8832: \ accountants don't like minus signs, they use parentheses
1.26 crook 8833: \ for negative numbers
8834: s>d \ convert to signed double
8835: swap over dabs \ leave sign byte followed by unsigned double
1.75 anton 8836: <<# \ start conversion
1.26 crook 8837: 2 pick \ get copy of sign byte
8838: 0< IF [char] ) hold THEN \ right-most character of output
8839: #s \ convert all digits
8840: rot \ get at sign byte
8841: 0< IF [char] ( hold THEN
8842: #> \ complete conversion
1.75 anton 8843: TYPE SPACE \ display, with trailing space
8844: #>> ; \ release hold area
8845:
1.5 anton 8846: @end example
8847:
1.26 crook 8848: Here are some examples of using these words:
1.5 anton 8849:
8850: @example
1.26 crook 8851: 1 my-u. 1
8852: hex -1 my-u. decimal FFFFFFFF
8853: 1 cents-only 01
8854: 1234 cents-only 34
8855: 2 dollars-and-cents $0.02
8856: 1234 dollars-and-cents $12.34
8857: 123 my-. 123
8858: -123 my. -123
8859: 123 account. 123
8860: -456 account. (456)
1.5 anton 8861: @end example
8862:
8863:
1.26 crook 8864: @node String Formats, Displaying characters and strings, Formatted numeric output, Other I/O
8865: @subsection String Formats
1.27 crook 8866: @cindex strings - see character strings
8867: @cindex character strings - formats
1.28 crook 8868: @cindex I/O - see character strings
1.75 anton 8869: @cindex counted strings
8870:
8871: @c anton: this does not really belong here; maybe the memory section,
8872: @c or the principles chapter
1.26 crook 8873:
1.27 crook 8874: Forth commonly uses two different methods for representing character
8875: strings:
1.26 crook 8876:
8877: @itemize @bullet
8878: @item
8879: @cindex address of counted string
1.45 crook 8880: @cindex counted string
1.29 crook 8881: As a @dfn{counted string}, represented by a @i{c-addr}. The char
8882: addressed by @i{c-addr} contains a character-count, @i{n}, of the
8883: string and the string occupies the subsequent @i{n} char addresses in
1.26 crook 8884: memory.
8885: @item
1.29 crook 8886: As cell pair on the stack; @i{c-addr u}, where @i{u} is the length
8887: of the string in characters, and @i{c-addr} is the address of the
1.26 crook 8888: first byte of the string.
8889: @end itemize
8890:
8891: ANS Forth encourages the use of the second format when representing
1.75 anton 8892: strings.
1.26 crook 8893:
1.44 crook 8894:
1.26 crook 8895: doc-count
8896:
1.44 crook 8897:
1.49 anton 8898: For words that move, copy and search for strings see @ref{Memory
8899: Blocks}. For words that display characters and strings see
8900: @ref{Displaying characters and strings}.
1.26 crook 8901:
8902: @node Displaying characters and strings, Input, String Formats, Other I/O
8903: @subsection Displaying characters and strings
1.27 crook 8904: @cindex characters - compiling and displaying
8905: @cindex character strings - compiling and displaying
1.26 crook 8906:
8907: This section starts with a glossary of Forth words and ends with a set
8908: of examples.
8909:
1.44 crook 8910:
1.26 crook 8911: doc-bl
8912: doc-space
8913: doc-spaces
8914: doc-emit
8915: doc-toupper
8916: doc-."
8917: doc-.(
8918: doc-type
1.44 crook 8919: doc-typewhite
1.26 crook 8920: doc-cr
1.27 crook 8921: @cindex cursor control
1.26 crook 8922: doc-at-xy
8923: doc-page
8924: doc-s"
8925: doc-c"
8926: doc-char
8927: doc-[char]
8928:
1.44 crook 8929:
8930: @noindent
1.26 crook 8931: As an example, consider the following text, stored in a file @file{test.fs}:
1.5 anton 8932:
8933: @example
1.26 crook 8934: .( text-1)
8935: : my-word
8936: ." text-2" cr
8937: .( text-3)
8938: ;
8939:
8940: ." text-4"
8941:
8942: : my-char
8943: [char] ALPHABET emit
8944: char emit
8945: ;
1.5 anton 8946: @end example
8947:
1.26 crook 8948: When you load this code into Gforth, the following output is generated:
1.5 anton 8949:
1.26 crook 8950: @example
1.30 anton 8951: @kbd{include test.fs @key{RET}} text-1text-3text-4 ok
1.26 crook 8952: @end example
1.5 anton 8953:
1.26 crook 8954: @itemize @bullet
8955: @item
8956: Messages @code{text-1} and @code{text-3} are displayed because @code{.(}
8957: is an immediate word; it behaves in the same way whether it is used inside
8958: or outside a colon definition.
8959: @item
8960: Message @code{text-4} is displayed because of Gforth's added interpretation
8961: semantics for @code{."}.
8962: @item
1.29 crook 8963: Message @code{text-2} is @i{not} displayed, because the text interpreter
1.26 crook 8964: performs the compilation semantics for @code{."} within the definition of
8965: @code{my-word}.
8966: @end itemize
1.5 anton 8967:
1.26 crook 8968: Here are some examples of executing @code{my-word} and @code{my-char}:
1.5 anton 8969:
1.26 crook 8970: @example
1.30 anton 8971: @kbd{my-word @key{RET}} text-2
1.26 crook 8972: ok
1.30 anton 8973: @kbd{my-char fred @key{RET}} Af ok
8974: @kbd{my-char jim @key{RET}} Aj ok
1.26 crook 8975: @end example
1.5 anton 8976:
8977: @itemize @bullet
8978: @item
1.26 crook 8979: Message @code{text-2} is displayed because of the run-time behaviour of
8980: @code{."}.
8981: @item
8982: @code{[char]} compiles the ``A'' from ``ALPHABET'' and puts its display code
8983: on the stack at run-time. @code{emit} always displays the character
8984: when @code{my-char} is executed.
8985: @item
8986: @code{char} parses a string at run-time and the second @code{emit} displays
8987: the first character of the string.
1.5 anton 8988: @item
1.26 crook 8989: If you type @code{see my-char} you can see that @code{[char]} discarded
8990: the text ``LPHABET'' and only compiled the display code for ``A'' into the
8991: definition of @code{my-char}.
1.5 anton 8992: @end itemize
8993:
8994:
8995:
1.48 anton 8996: @node Input, , Displaying characters and strings, Other I/O
1.26 crook 8997: @subsection Input
8998: @cindex input
1.28 crook 8999: @cindex I/O - see input
9000: @cindex parsing a string
1.5 anton 9001:
1.49 anton 9002: For ways of storing character strings in memory see @ref{String Formats}.
1.5 anton 9003:
1.27 crook 9004: @comment TODO examples for >number >float accept key key? pad parse word refill
1.29 crook 9005: @comment then index them
1.27 crook 9006:
1.44 crook 9007:
1.27 crook 9008: doc-key
9009: doc-key?
1.45 crook 9010: doc-ekey
9011: doc-ekey?
9012: doc-ekey>char
1.26 crook 9013: doc->number
9014: doc->float
9015: doc-accept
1.27 crook 9016: doc-pad
1.75 anton 9017: @c anton: these belong in the input stream section
1.27 crook 9018: doc-parse
9019: doc-word
9020: doc-sword
1.75 anton 9021: doc-name
1.27 crook 9022: doc-refill
9023: @comment obsolescent words..
9024: doc-convert
1.26 crook 9025: doc-query
9026: doc-expect
1.27 crook 9027: doc-span
1.5 anton 9028:
9029:
1.78 anton 9030: @c -------------------------------------------------------------
9031: @node Locals, Structures, Other I/O, Words
9032: @section Locals
9033: @cindex locals
9034:
9035: Local variables can make Forth programming more enjoyable and Forth
9036: programs easier to read. Unfortunately, the locals of ANS Forth are
9037: laden with restrictions. Therefore, we provide not only the ANS Forth
9038: locals wordset, but also our own, more powerful locals wordset (we
9039: implemented the ANS Forth locals wordset through our locals wordset).
1.44 crook 9040:
1.78 anton 9041: The ideas in this section have also been published in M. Anton Ertl,
9042: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl94l.ps.gz,
9043: Automatic Scoping of Local Variables}}, EuroForth '94.
1.12 anton 9044:
9045: @menu
1.78 anton 9046: * Gforth locals::
9047: * ANS Forth locals::
1.5 anton 9048: @end menu
9049:
1.78 anton 9050: @node Gforth locals, ANS Forth locals, Locals, Locals
9051: @subsection Gforth locals
9052: @cindex Gforth locals
9053: @cindex locals, Gforth style
1.5 anton 9054:
1.78 anton 9055: Locals can be defined with
1.44 crook 9056:
1.78 anton 9057: @example
9058: @{ local1 local2 ... -- comment @}
9059: @end example
9060: or
9061: @example
9062: @{ local1 local2 ... @}
9063: @end example
1.5 anton 9064:
1.78 anton 9065: E.g.,
9066: @example
9067: : max @{ n1 n2 -- n3 @}
9068: n1 n2 > if
9069: n1
9070: else
9071: n2
9072: endif ;
9073: @end example
1.44 crook 9074:
1.78 anton 9075: The similarity of locals definitions with stack comments is intended. A
9076: locals definition often replaces the stack comment of a word. The order
9077: of the locals corresponds to the order in a stack comment and everything
9078: after the @code{--} is really a comment.
1.77 anton 9079:
1.78 anton 9080: This similarity has one disadvantage: It is too easy to confuse locals
9081: declarations with stack comments, causing bugs and making them hard to
9082: find. However, this problem can be avoided by appropriate coding
9083: conventions: Do not use both notations in the same program. If you do,
9084: they should be distinguished using additional means, e.g. by position.
1.77 anton 9085:
1.78 anton 9086: @cindex types of locals
9087: @cindex locals types
9088: The name of the local may be preceded by a type specifier, e.g.,
9089: @code{F:} for a floating point value:
1.5 anton 9090:
1.78 anton 9091: @example
9092: : CX* @{ F: Ar F: Ai F: Br F: Bi -- Cr Ci @}
9093: \ complex multiplication
9094: Ar Br f* Ai Bi f* f-
9095: Ar Bi f* Ai Br f* f+ ;
9096: @end example
1.44 crook 9097:
1.78 anton 9098: @cindex flavours of locals
9099: @cindex locals flavours
9100: @cindex value-flavoured locals
9101: @cindex variable-flavoured locals
9102: Gforth currently supports cells (@code{W:}, @code{W^}), doubles
9103: (@code{D:}, @code{D^}), floats (@code{F:}, @code{F^}) and characters
9104: (@code{C:}, @code{C^}) in two flavours: a value-flavoured local (defined
9105: with @code{W:}, @code{D:} etc.) produces its value and can be changed
9106: with @code{TO}. A variable-flavoured local (defined with @code{W^} etc.)
9107: produces its address (which becomes invalid when the variable's scope is
9108: left). E.g., the standard word @code{emit} can be defined in terms of
9109: @code{type} like this:
1.5 anton 9110:
1.78 anton 9111: @example
9112: : emit @{ C^ char* -- @}
9113: char* 1 type ;
9114: @end example
1.5 anton 9115:
1.78 anton 9116: @cindex default type of locals
9117: @cindex locals, default type
9118: A local without type specifier is a @code{W:} local. Both flavours of
9119: locals are initialized with values from the data or FP stack.
1.44 crook 9120:
1.78 anton 9121: Currently there is no way to define locals with user-defined data
9122: structures, but we are working on it.
1.5 anton 9123:
1.78 anton 9124: Gforth allows defining locals everywhere in a colon definition. This
9125: poses the following questions:
1.5 anton 9126:
1.78 anton 9127: @menu
9128: * Where are locals visible by name?::
9129: * How long do locals live?::
9130: * Locals programming style::
9131: * Locals implementation::
9132: @end menu
1.44 crook 9133:
1.78 anton 9134: @node Where are locals visible by name?, How long do locals live?, Gforth locals, Gforth locals
9135: @subsubsection Where are locals visible by name?
9136: @cindex locals visibility
9137: @cindex visibility of locals
9138: @cindex scope of locals
1.5 anton 9139:
1.78 anton 9140: Basically, the answer is that locals are visible where you would expect
9141: it in block-structured languages, and sometimes a little longer. If you
9142: want to restrict the scope of a local, enclose its definition in
9143: @code{SCOPE}...@code{ENDSCOPE}.
1.5 anton 9144:
9145:
1.78 anton 9146: doc-scope
9147: doc-endscope
1.5 anton 9148:
9149:
1.78 anton 9150: These words behave like control structure words, so you can use them
9151: with @code{CS-PICK} and @code{CS-ROLL} to restrict the scope in
9152: arbitrary ways.
1.77 anton 9153:
1.78 anton 9154: If you want a more exact answer to the visibility question, here's the
9155: basic principle: A local is visible in all places that can only be
9156: reached through the definition of the local@footnote{In compiler
9157: construction terminology, all places dominated by the definition of the
9158: local.}. In other words, it is not visible in places that can be reached
9159: without going through the definition of the local. E.g., locals defined
9160: in @code{IF}...@code{ENDIF} are visible until the @code{ENDIF}, locals
9161: defined in @code{BEGIN}...@code{UNTIL} are visible after the
9162: @code{UNTIL} (until, e.g., a subsequent @code{ENDSCOPE}).
1.77 anton 9163:
1.78 anton 9164: The reasoning behind this solution is: We want to have the locals
9165: visible as long as it is meaningful. The user can always make the
9166: visibility shorter by using explicit scoping. In a place that can
9167: only be reached through the definition of a local, the meaning of a
9168: local name is clear. In other places it is not: How is the local
9169: initialized at the control flow path that does not contain the
9170: definition? Which local is meant, if the same name is defined twice in
9171: two independent control flow paths?
1.77 anton 9172:
1.78 anton 9173: This should be enough detail for nearly all users, so you can skip the
9174: rest of this section. If you really must know all the gory details and
9175: options, read on.
1.77 anton 9176:
1.78 anton 9177: In order to implement this rule, the compiler has to know which places
9178: are unreachable. It knows this automatically after @code{AHEAD},
9179: @code{AGAIN}, @code{EXIT} and @code{LEAVE}; in other cases (e.g., after
9180: most @code{THROW}s), you can use the word @code{UNREACHABLE} to tell the
9181: compiler that the control flow never reaches that place. If
9182: @code{UNREACHABLE} is not used where it could, the only consequence is
9183: that the visibility of some locals is more limited than the rule above
9184: says. If @code{UNREACHABLE} is used where it should not (i.e., if you
9185: lie to the compiler), buggy code will be produced.
1.77 anton 9186:
1.5 anton 9187:
1.78 anton 9188: doc-unreachable
1.5 anton 9189:
1.23 crook 9190:
1.78 anton 9191: Another problem with this rule is that at @code{BEGIN}, the compiler
9192: does not know which locals will be visible on the incoming
9193: back-edge. All problems discussed in the following are due to this
9194: ignorance of the compiler (we discuss the problems using @code{BEGIN}
9195: loops as examples; the discussion also applies to @code{?DO} and other
9196: loops). Perhaps the most insidious example is:
1.26 crook 9197: @example
1.78 anton 9198: AHEAD
9199: BEGIN
9200: x
9201: [ 1 CS-ROLL ] THEN
9202: @{ x @}
9203: ...
9204: UNTIL
1.26 crook 9205: @end example
1.23 crook 9206:
1.78 anton 9207: This should be legal according to the visibility rule. The use of
9208: @code{x} can only be reached through the definition; but that appears
9209: textually below the use.
9210:
9211: From this example it is clear that the visibility rules cannot be fully
9212: implemented without major headaches. Our implementation treats common
9213: cases as advertised and the exceptions are treated in a safe way: The
9214: compiler makes a reasonable guess about the locals visible after a
9215: @code{BEGIN}; if it is too pessimistic, the
9216: user will get a spurious error about the local not being defined; if the
9217: compiler is too optimistic, it will notice this later and issue a
9218: warning. In the case above the compiler would complain about @code{x}
9219: being undefined at its use. You can see from the obscure examples in
9220: this section that it takes quite unusual control structures to get the
9221: compiler into trouble, and even then it will often do fine.
1.23 crook 9222:
1.78 anton 9223: If the @code{BEGIN} is reachable from above, the most optimistic guess
9224: is that all locals visible before the @code{BEGIN} will also be
9225: visible after the @code{BEGIN}. This guess is valid for all loops that
9226: are entered only through the @code{BEGIN}, in particular, for normal
9227: @code{BEGIN}...@code{WHILE}...@code{REPEAT} and
9228: @code{BEGIN}...@code{UNTIL} loops and it is implemented in our
9229: compiler. When the branch to the @code{BEGIN} is finally generated by
9230: @code{AGAIN} or @code{UNTIL}, the compiler checks the guess and
9231: warns the user if it was too optimistic:
1.26 crook 9232: @example
1.78 anton 9233: IF
9234: @{ x @}
9235: BEGIN
9236: \ x ?
9237: [ 1 cs-roll ] THEN
9238: ...
9239: UNTIL
1.26 crook 9240: @end example
1.23 crook 9241:
1.78 anton 9242: Here, @code{x} lives only until the @code{BEGIN}, but the compiler
9243: optimistically assumes that it lives until the @code{THEN}. It notices
9244: this difference when it compiles the @code{UNTIL} and issues a
9245: warning. The user can avoid the warning, and make sure that @code{x}
9246: is not used in the wrong area by using explicit scoping:
9247: @example
9248: IF
9249: SCOPE
9250: @{ x @}
9251: ENDSCOPE
9252: BEGIN
9253: [ 1 cs-roll ] THEN
9254: ...
9255: UNTIL
9256: @end example
1.23 crook 9257:
1.78 anton 9258: Since the guess is optimistic, there will be no spurious error messages
9259: about undefined locals.
1.44 crook 9260:
1.78 anton 9261: If the @code{BEGIN} is not reachable from above (e.g., after
9262: @code{AHEAD} or @code{EXIT}), the compiler cannot even make an
9263: optimistic guess, as the locals visible after the @code{BEGIN} may be
9264: defined later. Therefore, the compiler assumes that no locals are
9265: visible after the @code{BEGIN}. However, the user can use
9266: @code{ASSUME-LIVE} to make the compiler assume that the same locals are
9267: visible at the BEGIN as at the point where the top control-flow stack
9268: item was created.
1.23 crook 9269:
1.44 crook 9270:
1.78 anton 9271: doc-assume-live
1.26 crook 9272:
1.23 crook 9273:
1.78 anton 9274: @noindent
9275: E.g.,
9276: @example
9277: @{ x @}
9278: AHEAD
9279: ASSUME-LIVE
9280: BEGIN
9281: x
9282: [ 1 CS-ROLL ] THEN
9283: ...
9284: UNTIL
9285: @end example
1.44 crook 9286:
1.78 anton 9287: Other cases where the locals are defined before the @code{BEGIN} can be
9288: handled by inserting an appropriate @code{CS-ROLL} before the
9289: @code{ASSUME-LIVE} (and changing the control-flow stack manipulation
9290: behind the @code{ASSUME-LIVE}).
1.23 crook 9291:
1.78 anton 9292: Cases where locals are defined after the @code{BEGIN} (but should be
9293: visible immediately after the @code{BEGIN}) can only be handled by
9294: rearranging the loop. E.g., the ``most insidious'' example above can be
9295: arranged into:
9296: @example
9297: BEGIN
9298: @{ x @}
9299: ... 0=
9300: WHILE
9301: x
9302: REPEAT
9303: @end example
1.44 crook 9304:
1.78 anton 9305: @node How long do locals live?, Locals programming style, Where are locals visible by name?, Gforth locals
9306: @subsubsection How long do locals live?
9307: @cindex locals lifetime
9308: @cindex lifetime of locals
1.23 crook 9309:
1.78 anton 9310: The right answer for the lifetime question would be: A local lives at
9311: least as long as it can be accessed. For a value-flavoured local this
9312: means: until the end of its visibility. However, a variable-flavoured
9313: local could be accessed through its address far beyond its visibility
9314: scope. Ultimately, this would mean that such locals would have to be
9315: garbage collected. Since this entails un-Forth-like implementation
9316: complexities, I adopted the same cowardly solution as some other
9317: languages (e.g., C): The local lives only as long as it is visible;
9318: afterwards its address is invalid (and programs that access it
9319: afterwards are erroneous).
1.23 crook 9320:
1.78 anton 9321: @node Locals programming style, Locals implementation, How long do locals live?, Gforth locals
9322: @subsubsection Locals programming style
9323: @cindex locals programming style
9324: @cindex programming style, locals
1.23 crook 9325:
1.78 anton 9326: The freedom to define locals anywhere has the potential to change
9327: programming styles dramatically. In particular, the need to use the
9328: return stack for intermediate storage vanishes. Moreover, all stack
9329: manipulations (except @code{PICK}s and @code{ROLL}s with run-time
9330: determined arguments) can be eliminated: If the stack items are in the
9331: wrong order, just write a locals definition for all of them; then
9332: write the items in the order you want.
1.23 crook 9333:
1.78 anton 9334: This seems a little far-fetched and eliminating stack manipulations is
9335: unlikely to become a conscious programming objective. Still, the number
9336: of stack manipulations will be reduced dramatically if local variables
9337: are used liberally (e.g., compare @code{max} (@pxref{Gforth locals}) with
9338: a traditional implementation of @code{max}).
1.23 crook 9339:
1.78 anton 9340: This shows one potential benefit of locals: making Forth programs more
9341: readable. Of course, this benefit will only be realized if the
9342: programmers continue to honour the principle of factoring instead of
9343: using the added latitude to make the words longer.
1.23 crook 9344:
1.78 anton 9345: @cindex single-assignment style for locals
9346: Using @code{TO} can and should be avoided. Without @code{TO},
9347: every value-flavoured local has only a single assignment and many
9348: advantages of functional languages apply to Forth. I.e., programs are
9349: easier to analyse, to optimize and to read: It is clear from the
9350: definition what the local stands for, it does not turn into something
9351: different later.
1.23 crook 9352:
1.78 anton 9353: E.g., a definition using @code{TO} might look like this:
9354: @example
9355: : strcmp @{ addr1 u1 addr2 u2 -- n @}
9356: u1 u2 min 0
9357: ?do
9358: addr1 c@@ addr2 c@@ -
9359: ?dup-if
9360: unloop exit
9361: then
9362: addr1 char+ TO addr1
9363: addr2 char+ TO addr2
9364: loop
9365: u1 u2 - ;
1.26 crook 9366: @end example
1.78 anton 9367: Here, @code{TO} is used to update @code{addr1} and @code{addr2} at
9368: every loop iteration. @code{strcmp} is a typical example of the
9369: readability problems of using @code{TO}. When you start reading
9370: @code{strcmp}, you think that @code{addr1} refers to the start of the
9371: string. Only near the end of the loop you realize that it is something
9372: else.
1.23 crook 9373:
1.78 anton 9374: This can be avoided by defining two locals at the start of the loop that
9375: are initialized with the right value for the current iteration.
9376: @example
9377: : strcmp @{ addr1 u1 addr2 u2 -- n @}
9378: addr1 addr2
9379: u1 u2 min 0
9380: ?do @{ s1 s2 @}
9381: s1 c@@ s2 c@@ -
9382: ?dup-if
9383: unloop exit
9384: then
9385: s1 char+ s2 char+
9386: loop
9387: 2drop
9388: u1 u2 - ;
9389: @end example
9390: Here it is clear from the start that @code{s1} has a different value
9391: in every loop iteration.
1.23 crook 9392:
1.78 anton 9393: @node Locals implementation, , Locals programming style, Gforth locals
9394: @subsubsection Locals implementation
9395: @cindex locals implementation
9396: @cindex implementation of locals
1.23 crook 9397:
1.78 anton 9398: @cindex locals stack
9399: Gforth uses an extra locals stack. The most compelling reason for
9400: this is that the return stack is not float-aligned; using an extra stack
9401: also eliminates the problems and restrictions of using the return stack
9402: as locals stack. Like the other stacks, the locals stack grows toward
9403: lower addresses. A few primitives allow an efficient implementation:
9404:
9405:
9406: doc-@local#
9407: doc-f@local#
9408: doc-laddr#
9409: doc-lp+!#
9410: doc-lp!
9411: doc->l
9412: doc-f>l
9413:
9414:
9415: In addition to these primitives, some specializations of these
9416: primitives for commonly occurring inline arguments are provided for
9417: efficiency reasons, e.g., @code{@@local0} as specialization of
9418: @code{@@local#} for the inline argument 0. The following compiling words
9419: compile the right specialized version, or the general version, as
9420: appropriate:
1.23 crook 9421:
1.5 anton 9422:
1.78 anton 9423: doc-compile-@local
9424: doc-compile-f@local
9425: doc-compile-lp+!
1.5 anton 9426:
9427:
1.78 anton 9428: Combinations of conditional branches and @code{lp+!#} like
9429: @code{?branch-lp+!#} (the locals pointer is only changed if the branch
9430: is taken) are provided for efficiency and correctness in loops.
1.5 anton 9431:
1.78 anton 9432: A special area in the dictionary space is reserved for keeping the
9433: local variable names. @code{@{} switches the dictionary pointer to this
9434: area and @code{@}} switches it back and generates the locals
9435: initializing code. @code{W:} etc.@ are normal defining words. This
9436: special area is cleared at the start of every colon definition.
1.5 anton 9437:
1.78 anton 9438: @cindex word list for defining locals
9439: A special feature of Gforth's dictionary is used to implement the
9440: definition of locals without type specifiers: every word list (aka
9441: vocabulary) has its own methods for searching
9442: etc. (@pxref{Word Lists}). For the present purpose we defined a word list
9443: with a special search method: When it is searched for a word, it
9444: actually creates that word using @code{W:}. @code{@{} changes the search
9445: order to first search the word list containing @code{@}}, @code{W:} etc.,
9446: and then the word list for defining locals without type specifiers.
1.5 anton 9447:
1.78 anton 9448: The lifetime rules support a stack discipline within a colon
9449: definition: The lifetime of a local is either nested with other locals
9450: lifetimes or it does not overlap them.
1.23 crook 9451:
1.78 anton 9452: At @code{BEGIN}, @code{IF}, and @code{AHEAD} no code for locals stack
9453: pointer manipulation is generated. Between control structure words
9454: locals definitions can push locals onto the locals stack. @code{AGAIN}
9455: is the simplest of the other three control flow words. It has to
9456: restore the locals stack depth of the corresponding @code{BEGIN}
9457: before branching. The code looks like this:
9458: @format
9459: @code{lp+!#} current-locals-size @minus{} dest-locals-size
9460: @code{branch} <begin>
9461: @end format
1.26 crook 9462:
1.78 anton 9463: @code{UNTIL} is a little more complicated: If it branches back, it
9464: must adjust the stack just like @code{AGAIN}. But if it falls through,
9465: the locals stack must not be changed. The compiler generates the
9466: following code:
9467: @format
9468: @code{?branch-lp+!#} <begin> current-locals-size @minus{} dest-locals-size
9469: @end format
9470: The locals stack pointer is only adjusted if the branch is taken.
1.44 crook 9471:
1.78 anton 9472: @code{THEN} can produce somewhat inefficient code:
9473: @format
9474: @code{lp+!#} current-locals-size @minus{} orig-locals-size
9475: <orig target>:
9476: @code{lp+!#} orig-locals-size @minus{} new-locals-size
9477: @end format
9478: The second @code{lp+!#} adjusts the locals stack pointer from the
9479: level at the @i{orig} point to the level after the @code{THEN}. The
9480: first @code{lp+!#} adjusts the locals stack pointer from the current
9481: level to the level at the orig point, so the complete effect is an
9482: adjustment from the current level to the right level after the
9483: @code{THEN}.
1.26 crook 9484:
1.78 anton 9485: @cindex locals information on the control-flow stack
9486: @cindex control-flow stack items, locals information
9487: In a conventional Forth implementation a dest control-flow stack entry
9488: is just the target address and an orig entry is just the address to be
9489: patched. Our locals implementation adds a word list to every orig or dest
9490: item. It is the list of locals visible (or assumed visible) at the point
9491: described by the entry. Our implementation also adds a tag to identify
9492: the kind of entry, in particular to differentiate between live and dead
9493: (reachable and unreachable) orig entries.
1.26 crook 9494:
1.78 anton 9495: A few unusual operations have to be performed on locals word lists:
1.44 crook 9496:
1.5 anton 9497:
1.78 anton 9498: doc-common-list
9499: doc-sub-list?
9500: doc-list-size
1.52 anton 9501:
9502:
1.78 anton 9503: Several features of our locals word list implementation make these
9504: operations easy to implement: The locals word lists are organised as
9505: linked lists; the tails of these lists are shared, if the lists
9506: contain some of the same locals; and the address of a name is greater
9507: than the address of the names behind it in the list.
1.5 anton 9508:
1.78 anton 9509: Another important implementation detail is the variable
9510: @code{dead-code}. It is used by @code{BEGIN} and @code{THEN} to
9511: determine if they can be reached directly or only through the branch
9512: that they resolve. @code{dead-code} is set by @code{UNREACHABLE},
9513: @code{AHEAD}, @code{EXIT} etc., and cleared at the start of a colon
9514: definition, by @code{BEGIN} and usually by @code{THEN}.
1.5 anton 9515:
1.78 anton 9516: Counted loops are similar to other loops in most respects, but
9517: @code{LEAVE} requires special attention: It performs basically the same
9518: service as @code{AHEAD}, but it does not create a control-flow stack
9519: entry. Therefore the information has to be stored elsewhere;
9520: traditionally, the information was stored in the target fields of the
9521: branches created by the @code{LEAVE}s, by organizing these fields into a
9522: linked list. Unfortunately, this clever trick does not provide enough
9523: space for storing our extended control flow information. Therefore, we
9524: introduce another stack, the leave stack. It contains the control-flow
9525: stack entries for all unresolved @code{LEAVE}s.
1.44 crook 9526:
1.78 anton 9527: Local names are kept until the end of the colon definition, even if
9528: they are no longer visible in any control-flow path. In a few cases
9529: this may lead to increased space needs for the locals name area, but
9530: usually less than reclaiming this space would cost in code size.
1.5 anton 9531:
1.44 crook 9532:
1.78 anton 9533: @node ANS Forth locals, , Gforth locals, Locals
9534: @subsection ANS Forth locals
9535: @cindex locals, ANS Forth style
1.5 anton 9536:
1.78 anton 9537: The ANS Forth locals wordset does not define a syntax for locals, but
9538: words that make it possible to define various syntaxes. One of the
9539: possible syntaxes is a subset of the syntax we used in the Gforth locals
9540: wordset, i.e.:
1.29 crook 9541:
9542: @example
1.78 anton 9543: @{ local1 local2 ... -- comment @}
9544: @end example
9545: @noindent
9546: or
9547: @example
9548: @{ local1 local2 ... @}
1.29 crook 9549: @end example
9550:
1.78 anton 9551: The order of the locals corresponds to the order in a stack comment. The
9552: restrictions are:
1.5 anton 9553:
1.78 anton 9554: @itemize @bullet
9555: @item
9556: Locals can only be cell-sized values (no type specifiers are allowed).
9557: @item
9558: Locals can be defined only outside control structures.
9559: @item
9560: Locals can interfere with explicit usage of the return stack. For the
9561: exact (and long) rules, see the standard. If you don't use return stack
9562: accessing words in a definition using locals, you will be all right. The
9563: purpose of this rule is to make locals implementation on the return
9564: stack easier.
9565: @item
9566: The whole definition must be in one line.
9567: @end itemize
1.5 anton 9568:
1.78 anton 9569: Locals defined in ANS Forth behave like @code{VALUE}s
9570: (@pxref{Values}). I.e., they are initialized from the stack. Using their
9571: name produces their value. Their value can be changed using @code{TO}.
1.77 anton 9572:
1.78 anton 9573: Since the syntax above is supported by Gforth directly, you need not do
9574: anything to use it. If you want to port a program using this syntax to
9575: another ANS Forth system, use @file{compat/anslocal.fs} to implement the
9576: syntax on the other system.
1.5 anton 9577:
1.78 anton 9578: Note that a syntax shown in the standard, section A.13 looks
9579: similar, but is quite different in having the order of locals
9580: reversed. Beware!
1.5 anton 9581:
1.78 anton 9582: The ANS Forth locals wordset itself consists of one word:
1.5 anton 9583:
1.78 anton 9584: doc-(local)
1.5 anton 9585:
1.78 anton 9586: The ANS Forth locals extension wordset defines a syntax using
9587: @code{locals|}, but it is so awful that we strongly recommend not to use
9588: it. We have implemented this syntax to make porting to Gforth easy, but
9589: do not document it here. The problem with this syntax is that the locals
9590: are defined in an order reversed with respect to the standard stack
9591: comment notation, making programs harder to read, and easier to misread
9592: and miswrite. The only merit of this syntax is that it is easy to
9593: implement using the ANS Forth locals wordset.
1.53 anton 9594:
9595:
1.78 anton 9596: @c ----------------------------------------------------------
9597: @node Structures, Object-oriented Forth, Locals, Words
9598: @section Structures
9599: @cindex structures
9600: @cindex records
1.53 anton 9601:
1.78 anton 9602: This section presents the structure package that comes with Gforth. A
9603: version of the package implemented in ANS Forth is available in
9604: @file{compat/struct.fs}. This package was inspired by a posting on
9605: comp.lang.forth in 1989 (unfortunately I don't remember, by whom;
9606: possibly John Hayes). A version of this section has been published in
9607: M. Anton Ertl,
9608: @uref{http://www.complang.tuwien.ac.at/forth/objects/structs.html, Yet
9609: Another Forth Structures Package}, Forth Dimensions 19(3), pages
9610: 13--16. Marcel Hendrix provided helpful comments.
1.53 anton 9611:
1.78 anton 9612: @menu
9613: * Why explicit structure support?::
9614: * Structure Usage::
9615: * Structure Naming Convention::
9616: * Structure Implementation::
9617: * Structure Glossary::
9618: @end menu
1.55 anton 9619:
1.78 anton 9620: @node Why explicit structure support?, Structure Usage, Structures, Structures
9621: @subsection Why explicit structure support?
1.53 anton 9622:
1.78 anton 9623: @cindex address arithmetic for structures
9624: @cindex structures using address arithmetic
9625: If we want to use a structure containing several fields, we could simply
9626: reserve memory for it, and access the fields using address arithmetic
9627: (@pxref{Address arithmetic}). As an example, consider a structure with
9628: the following fields
1.57 anton 9629:
1.78 anton 9630: @table @code
9631: @item a
9632: is a float
9633: @item b
9634: is a cell
9635: @item c
9636: is a float
9637: @end table
1.57 anton 9638:
1.78 anton 9639: Given the (float-aligned) base address of the structure we get the
9640: address of the field
1.52 anton 9641:
1.78 anton 9642: @table @code
9643: @item a
9644: without doing anything further.
9645: @item b
9646: with @code{float+}
9647: @item c
9648: with @code{float+ cell+ faligned}
9649: @end table
1.52 anton 9650:
1.78 anton 9651: It is easy to see that this can become quite tiring.
1.52 anton 9652:
1.78 anton 9653: Moreover, it is not very readable, because seeing a
9654: @code{cell+} tells us neither which kind of structure is
9655: accessed nor what field is accessed; we have to somehow infer the kind
9656: of structure, and then look up in the documentation, which field of
9657: that structure corresponds to that offset.
1.53 anton 9658:
1.78 anton 9659: Finally, this kind of address arithmetic also causes maintenance
9660: troubles: If you add or delete a field somewhere in the middle of the
9661: structure, you have to find and change all computations for the fields
9662: afterwards.
1.52 anton 9663:
1.78 anton 9664: So, instead of using @code{cell+} and friends directly, how
9665: about storing the offsets in constants:
1.52 anton 9666:
1.78 anton 9667: @example
9668: 0 constant a-offset
9669: 0 float+ constant b-offset
9670: 0 float+ cell+ faligned c-offset
9671: @end example
1.64 pazsan 9672:
1.78 anton 9673: Now we can get the address of field @code{x} with @code{x-offset
9674: +}. This is much better in all respects. Of course, you still
9675: have to change all later offset definitions if you add a field. You can
9676: fix this by declaring the offsets in the following way:
1.57 anton 9677:
1.78 anton 9678: @example
9679: 0 constant a-offset
9680: a-offset float+ constant b-offset
9681: b-offset cell+ faligned constant c-offset
9682: @end example
1.57 anton 9683:
1.78 anton 9684: Since we always use the offsets with @code{+}, we could use a defining
9685: word @code{cfield} that includes the @code{+} in the action of the
9686: defined word:
1.64 pazsan 9687:
1.78 anton 9688: @example
9689: : cfield ( n "name" -- )
9690: create ,
9691: does> ( name execution: addr1 -- addr2 )
9692: @@ + ;
1.64 pazsan 9693:
1.78 anton 9694: 0 cfield a
9695: 0 a float+ cfield b
9696: 0 b cell+ faligned cfield c
9697: @end example
1.64 pazsan 9698:
1.78 anton 9699: Instead of @code{x-offset +}, we now simply write @code{x}.
1.64 pazsan 9700:
1.78 anton 9701: The structure field words now can be used quite nicely. However,
9702: their definition is still a bit cumbersome: We have to repeat the
9703: name, the information about size and alignment is distributed before
9704: and after the field definitions etc. The structure package presented
9705: here addresses these problems.
1.64 pazsan 9706:
1.78 anton 9707: @node Structure Usage, Structure Naming Convention, Why explicit structure support?, Structures
9708: @subsection Structure Usage
9709: @cindex structure usage
1.57 anton 9710:
1.78 anton 9711: @cindex @code{field} usage
9712: @cindex @code{struct} usage
9713: @cindex @code{end-struct} usage
9714: You can define a structure for a (data-less) linked list with:
1.57 anton 9715: @example
1.78 anton 9716: struct
9717: cell% field list-next
9718: end-struct list%
1.57 anton 9719: @end example
9720:
1.78 anton 9721: With the address of the list node on the stack, you can compute the
9722: address of the field that contains the address of the next node with
9723: @code{list-next}. E.g., you can determine the length of a list
9724: with:
1.57 anton 9725:
9726: @example
1.78 anton 9727: : list-length ( list -- n )
9728: \ "list" is a pointer to the first element of a linked list
9729: \ "n" is the length of the list
9730: 0 BEGIN ( list1 n1 )
9731: over
9732: WHILE ( list1 n1 )
9733: 1+ swap list-next @@ swap
9734: REPEAT
9735: nip ;
1.57 anton 9736: @end example
9737:
1.78 anton 9738: You can reserve memory for a list node in the dictionary with
9739: @code{list% %allot}, which leaves the address of the list node on the
9740: stack. For the equivalent allocation on the heap you can use @code{list%
9741: %alloc} (or, for an @code{allocate}-like stack effect (i.e., with ior),
9742: use @code{list% %allocate}). You can get the the size of a list
9743: node with @code{list% %size} and its alignment with @code{list%
9744: %alignment}.
9745:
9746: Note that in ANS Forth the body of a @code{create}d word is
9747: @code{aligned} but not necessarily @code{faligned};
9748: therefore, if you do a:
1.57 anton 9749:
9750: @example
1.78 anton 9751: create @emph{name} foo% %allot drop
1.57 anton 9752: @end example
9753:
1.78 anton 9754: @noindent
9755: then the memory alloted for @code{foo%} is guaranteed to start at the
9756: body of @code{@emph{name}} only if @code{foo%} contains only character,
9757: cell and double fields. Therefore, if your structure contains floats,
9758: better use
1.57 anton 9759:
9760: @example
1.78 anton 9761: foo% %allot constant @emph{name}
1.57 anton 9762: @end example
9763:
1.78 anton 9764: @cindex structures containing structures
9765: You can include a structure @code{foo%} as a field of
9766: another structure, like this:
1.65 anton 9767: @example
1.78 anton 9768: struct
9769: ...
9770: foo% field ...
9771: ...
9772: end-struct ...
1.65 anton 9773: @end example
1.52 anton 9774:
1.78 anton 9775: @cindex structure extension
9776: @cindex extended records
9777: Instead of starting with an empty structure, you can extend an
9778: existing structure. E.g., a plain linked list without data, as defined
9779: above, is hardly useful; You can extend it to a linked list of integers,
9780: like this:@footnote{This feature is also known as @emph{extended
9781: records}. It is the main innovation in the Oberon language; in other
9782: words, adding this feature to Modula-2 led Wirth to create a new
9783: language, write a new compiler etc. Adding this feature to Forth just
9784: required a few lines of code.}
1.52 anton 9785:
1.78 anton 9786: @example
9787: list%
9788: cell% field intlist-int
9789: end-struct intlist%
9790: @end example
1.55 anton 9791:
1.78 anton 9792: @code{intlist%} is a structure with two fields:
9793: @code{list-next} and @code{intlist-int}.
1.55 anton 9794:
1.78 anton 9795: @cindex structures containing arrays
9796: You can specify an array type containing @emph{n} elements of
9797: type @code{foo%} like this:
1.55 anton 9798:
9799: @example
1.78 anton 9800: foo% @emph{n} *
1.56 anton 9801: @end example
1.55 anton 9802:
1.78 anton 9803: You can use this array type in any place where you can use a normal
9804: type, e.g., when defining a @code{field}, or with
9805: @code{%allot}.
9806:
9807: @cindex first field optimization
9808: The first field is at the base address of a structure and the word for
9809: this field (e.g., @code{list-next}) actually does not change the address
9810: on the stack. You may be tempted to leave it away in the interest of
9811: run-time and space efficiency. This is not necessary, because the
9812: structure package optimizes this case: If you compile a first-field
9813: words, no code is generated. So, in the interest of readability and
9814: maintainability you should include the word for the field when accessing
9815: the field.
1.52 anton 9816:
9817:
1.78 anton 9818: @node Structure Naming Convention, Structure Implementation, Structure Usage, Structures
9819: @subsection Structure Naming Convention
9820: @cindex structure naming convention
1.52 anton 9821:
1.78 anton 9822: The field names that come to (my) mind are often quite generic, and,
9823: if used, would cause frequent name clashes. E.g., many structures
9824: probably contain a @code{counter} field. The structure names
9825: that come to (my) mind are often also the logical choice for the names
9826: of words that create such a structure.
1.52 anton 9827:
1.78 anton 9828: Therefore, I have adopted the following naming conventions:
1.52 anton 9829:
1.78 anton 9830: @itemize @bullet
9831: @cindex field naming convention
9832: @item
9833: The names of fields are of the form
9834: @code{@emph{struct}-@emph{field}}, where
9835: @code{@emph{struct}} is the basic name of the structure, and
9836: @code{@emph{field}} is the basic name of the field. You can
9837: think of field words as converting the (address of the)
9838: structure into the (address of the) field.
1.52 anton 9839:
1.78 anton 9840: @cindex structure naming convention
9841: @item
9842: The names of structures are of the form
9843: @code{@emph{struct}%}, where
9844: @code{@emph{struct}} is the basic name of the structure.
9845: @end itemize
1.52 anton 9846:
1.78 anton 9847: This naming convention does not work that well for fields of extended
9848: structures; e.g., the integer list structure has a field
9849: @code{intlist-int}, but has @code{list-next}, not
9850: @code{intlist-next}.
1.53 anton 9851:
1.78 anton 9852: @node Structure Implementation, Structure Glossary, Structure Naming Convention, Structures
9853: @subsection Structure Implementation
9854: @cindex structure implementation
9855: @cindex implementation of structures
1.52 anton 9856:
1.78 anton 9857: The central idea in the implementation is to pass the data about the
9858: structure being built on the stack, not in some global
9859: variable. Everything else falls into place naturally once this design
9860: decision is made.
1.53 anton 9861:
1.78 anton 9862: The type description on the stack is of the form @emph{align
9863: size}. Keeping the size on the top-of-stack makes dealing with arrays
9864: very simple.
1.53 anton 9865:
1.78 anton 9866: @code{field} is a defining word that uses @code{Create}
9867: and @code{DOES>}. The body of the field contains the offset
9868: of the field, and the normal @code{DOES>} action is simply:
1.53 anton 9869:
9870: @example
1.78 anton 9871: @@ +
1.53 anton 9872: @end example
9873:
1.78 anton 9874: @noindent
9875: i.e., add the offset to the address, giving the stack effect
9876: @i{addr1 -- addr2} for a field.
9877:
9878: @cindex first field optimization, implementation
9879: This simple structure is slightly complicated by the optimization
9880: for fields with offset 0, which requires a different
9881: @code{DOES>}-part (because we cannot rely on there being
9882: something on the stack if such a field is invoked during
9883: compilation). Therefore, we put the different @code{DOES>}-parts
9884: in separate words, and decide which one to invoke based on the
9885: offset. For a zero offset, the field is basically a noop; it is
9886: immediate, and therefore no code is generated when it is compiled.
1.53 anton 9887:
1.78 anton 9888: @node Structure Glossary, , Structure Implementation, Structures
9889: @subsection Structure Glossary
9890: @cindex structure glossary
1.53 anton 9891:
1.5 anton 9892:
1.78 anton 9893: doc-%align
9894: doc-%alignment
9895: doc-%alloc
9896: doc-%allocate
9897: doc-%allot
9898: doc-cell%
9899: doc-char%
9900: doc-dfloat%
9901: doc-double%
9902: doc-end-struct
9903: doc-field
9904: doc-float%
9905: doc-naligned
9906: doc-sfloat%
9907: doc-%size
9908: doc-struct
1.54 anton 9909:
9910:
1.26 crook 9911: @c -------------------------------------------------------------
1.78 anton 9912: @node Object-oriented Forth, Programming Tools, Structures, Words
9913: @section Object-oriented Forth
9914:
9915: Gforth comes with three packages for object-oriented programming:
9916: @file{objects.fs}, @file{oof.fs}, and @file{mini-oof.fs}; none of them
9917: is preloaded, so you have to @code{include} them before use. The most
9918: important differences between these packages (and others) are discussed
9919: in @ref{Comparison with other object models}. All packages are written
9920: in ANS Forth and can be used with any other ANS Forth.
1.5 anton 9921:
1.78 anton 9922: @menu
9923: * Why object-oriented programming?::
9924: * Object-Oriented Terminology::
9925: * Objects::
9926: * OOF::
9927: * Mini-OOF::
9928: * Comparison with other object models::
9929: @end menu
1.5 anton 9930:
1.78 anton 9931: @c ----------------------------------------------------------------
9932: @node Why object-oriented programming?, Object-Oriented Terminology, Object-oriented Forth, Object-oriented Forth
9933: @subsection Why object-oriented programming?
9934: @cindex object-oriented programming motivation
9935: @cindex motivation for object-oriented programming
1.44 crook 9936:
1.78 anton 9937: Often we have to deal with several data structures (@emph{objects}),
9938: that have to be treated similarly in some respects, but differently in
9939: others. Graphical objects are the textbook example: circles, triangles,
9940: dinosaurs, icons, and others, and we may want to add more during program
9941: development. We want to apply some operations to any graphical object,
9942: e.g., @code{draw} for displaying it on the screen. However, @code{draw}
9943: has to do something different for every kind of object.
9944: @comment TODO add some other operations eg perimeter, area
9945: @comment and tie in to concrete examples later..
1.5 anton 9946:
1.78 anton 9947: We could implement @code{draw} as a big @code{CASE}
9948: control structure that executes the appropriate code depending on the
9949: kind of object to be drawn. This would be not be very elegant, and,
9950: moreover, we would have to change @code{draw} every time we add
9951: a new kind of graphical object (say, a spaceship).
1.44 crook 9952:
1.78 anton 9953: What we would rather do is: When defining spaceships, we would tell
9954: the system: ``Here's how you @code{draw} a spaceship; you figure
9955: out the rest''.
1.5 anton 9956:
1.78 anton 9957: This is the problem that all systems solve that (rightfully) call
9958: themselves object-oriented; the object-oriented packages presented here
9959: solve this problem (and not much else).
9960: @comment TODO ?list properties of oo systems.. oo vs o-based?
1.44 crook 9961:
1.78 anton 9962: @c ------------------------------------------------------------------------
9963: @node Object-Oriented Terminology, Objects, Why object-oriented programming?, Object-oriented Forth
9964: @subsection Object-Oriented Terminology
9965: @cindex object-oriented terminology
9966: @cindex terminology for object-oriented programming
1.5 anton 9967:
1.78 anton 9968: This section is mainly for reference, so you don't have to understand
9969: all of it right away. The terminology is mainly Smalltalk-inspired. In
9970: short:
1.44 crook 9971:
1.78 anton 9972: @table @emph
9973: @cindex class
9974: @item class
9975: a data structure definition with some extras.
1.5 anton 9976:
1.78 anton 9977: @cindex object
9978: @item object
9979: an instance of the data structure described by the class definition.
1.5 anton 9980:
1.78 anton 9981: @cindex instance variables
9982: @item instance variables
9983: fields of the data structure.
1.5 anton 9984:
1.78 anton 9985: @cindex selector
9986: @cindex method selector
9987: @cindex virtual function
9988: @item selector
9989: (or @emph{method selector}) a word (e.g.,
9990: @code{draw}) that performs an operation on a variety of data
9991: structures (classes). A selector describes @emph{what} operation to
9992: perform. In C++ terminology: a (pure) virtual function.
1.5 anton 9993:
1.78 anton 9994: @cindex method
9995: @item method
9996: the concrete definition that performs the operation
9997: described by the selector for a specific class. A method specifies
9998: @emph{how} the operation is performed for a specific class.
1.5 anton 9999:
1.78 anton 10000: @cindex selector invocation
10001: @cindex message send
10002: @cindex invoking a selector
10003: @item selector invocation
10004: a call of a selector. One argument of the call (the TOS (top-of-stack))
10005: is used for determining which method is used. In Smalltalk terminology:
10006: a message (consisting of the selector and the other arguments) is sent
10007: to the object.
1.5 anton 10008:
1.78 anton 10009: @cindex receiving object
10010: @item receiving object
10011: the object used for determining the method executed by a selector
10012: invocation. In the @file{objects.fs} model, it is the object that is on
10013: the TOS when the selector is invoked. (@emph{Receiving} comes from
10014: the Smalltalk @emph{message} terminology.)
1.5 anton 10015:
1.78 anton 10016: @cindex child class
10017: @cindex parent class
10018: @cindex inheritance
10019: @item child class
10020: a class that has (@emph{inherits}) all properties (instance variables,
10021: selectors, methods) from a @emph{parent class}. In Smalltalk
10022: terminology: The subclass inherits from the superclass. In C++
10023: terminology: The derived class inherits from the base class.
1.5 anton 10024:
1.78 anton 10025: @end table
1.5 anton 10026:
1.78 anton 10027: @c If you wonder about the message sending terminology, it comes from
10028: @c a time when each object had it's own task and objects communicated via
10029: @c message passing; eventually the Smalltalk developers realized that
10030: @c they can do most things through simple (indirect) calls. They kept the
10031: @c terminology.
1.5 anton 10032:
1.78 anton 10033: @c --------------------------------------------------------------
10034: @node Objects, OOF, Object-Oriented Terminology, Object-oriented Forth
10035: @subsection The @file{objects.fs} model
10036: @cindex objects
10037: @cindex object-oriented programming
1.26 crook 10038:
1.78 anton 10039: @cindex @file{objects.fs}
10040: @cindex @file{oof.fs}
1.26 crook 10041:
1.78 anton 10042: This section describes the @file{objects.fs} package. This material also
10043: has been published in M. Anton Ertl,
10044: @cite{@uref{http://www.complang.tuwien.ac.at/forth/objects/objects.html,
10045: Yet Another Forth Objects Package}}, Forth Dimensions 19(2), pages
10046: 37--43.
10047: @c McKewan's and Zsoter's packages
1.26 crook 10048:
1.78 anton 10049: This section assumes that you have read @ref{Structures}.
1.5 anton 10050:
1.78 anton 10051: The techniques on which this model is based have been used to implement
10052: the parser generator, Gray, and have also been used in Gforth for
10053: implementing the various flavours of word lists (hashed or not,
10054: case-sensitive or not, special-purpose word lists for locals etc.).
1.5 anton 10055:
10056:
1.26 crook 10057: @menu
1.78 anton 10058: * Properties of the Objects model::
10059: * Basic Objects Usage::
10060: * The Objects base class::
10061: * Creating objects::
10062: * Object-Oriented Programming Style::
10063: * Class Binding::
10064: * Method conveniences::
10065: * Classes and Scoping::
10066: * Dividing classes::
10067: * Object Interfaces::
10068: * Objects Implementation::
10069: * Objects Glossary::
1.26 crook 10070: @end menu
1.5 anton 10071:
1.78 anton 10072: Marcel Hendrix provided helpful comments on this section.
1.5 anton 10073:
1.78 anton 10074: @node Properties of the Objects model, Basic Objects Usage, Objects, Objects
10075: @subsubsection Properties of the @file{objects.fs} model
10076: @cindex @file{objects.fs} properties
1.5 anton 10077:
1.78 anton 10078: @itemize @bullet
10079: @item
10080: It is straightforward to pass objects on the stack. Passing
10081: selectors on the stack is a little less convenient, but possible.
1.44 crook 10082:
1.78 anton 10083: @item
10084: Objects are just data structures in memory, and are referenced by their
10085: address. You can create words for objects with normal defining words
10086: like @code{constant}. Likewise, there is no difference between instance
10087: variables that contain objects and those that contain other data.
1.5 anton 10088:
1.78 anton 10089: @item
10090: Late binding is efficient and easy to use.
1.44 crook 10091:
1.78 anton 10092: @item
10093: It avoids parsing, and thus avoids problems with state-smartness
10094: and reduced extensibility; for convenience there are a few parsing
10095: words, but they have non-parsing counterparts. There are also a few
10096: defining words that parse. This is hard to avoid, because all standard
10097: defining words parse (except @code{:noname}); however, such
10098: words are not as bad as many other parsing words, because they are not
10099: state-smart.
1.5 anton 10100:
1.78 anton 10101: @item
10102: It does not try to incorporate everything. It does a few things and does
10103: them well (IMO). In particular, this model was not designed to support
10104: information hiding (although it has features that may help); you can use
10105: a separate package for achieving this.
1.5 anton 10106:
1.78 anton 10107: @item
10108: It is layered; you don't have to learn and use all features to use this
10109: model. Only a few features are necessary (@pxref{Basic Objects Usage},
10110: @pxref{The Objects base class}, @pxref{Creating objects}.), the others
10111: are optional and independent of each other.
1.5 anton 10112:
1.78 anton 10113: @item
10114: An implementation in ANS Forth is available.
1.5 anton 10115:
1.78 anton 10116: @end itemize
1.5 anton 10117:
1.44 crook 10118:
1.78 anton 10119: @node Basic Objects Usage, The Objects base class, Properties of the Objects model, Objects
10120: @subsubsection Basic @file{objects.fs} Usage
10121: @cindex basic objects usage
10122: @cindex objects, basic usage
1.5 anton 10123:
1.78 anton 10124: You can define a class for graphical objects like this:
1.44 crook 10125:
1.78 anton 10126: @cindex @code{class} usage
10127: @cindex @code{end-class} usage
10128: @cindex @code{selector} usage
1.5 anton 10129: @example
1.78 anton 10130: object class \ "object" is the parent class
10131: selector draw ( x y graphical -- )
10132: end-class graphical
10133: @end example
10134:
10135: This code defines a class @code{graphical} with an
10136: operation @code{draw}. We can perform the operation
10137: @code{draw} on any @code{graphical} object, e.g.:
10138:
10139: @example
10140: 100 100 t-rex draw
1.26 crook 10141: @end example
1.5 anton 10142:
1.78 anton 10143: @noindent
10144: where @code{t-rex} is a word (say, a constant) that produces a
10145: graphical object.
10146:
10147: @comment TODO add a 2nd operation eg perimeter.. and use for
10148: @comment a concrete example
1.5 anton 10149:
1.78 anton 10150: @cindex abstract class
10151: How do we create a graphical object? With the present definitions,
10152: we cannot create a useful graphical object. The class
10153: @code{graphical} describes graphical objects in general, but not
10154: any concrete graphical object type (C++ users would call it an
10155: @emph{abstract class}); e.g., there is no method for the selector
10156: @code{draw} in the class @code{graphical}.
1.5 anton 10157:
1.78 anton 10158: For concrete graphical objects, we define child classes of the
10159: class @code{graphical}, e.g.:
1.5 anton 10160:
1.78 anton 10161: @cindex @code{overrides} usage
10162: @cindex @code{field} usage in class definition
1.26 crook 10163: @example
1.78 anton 10164: graphical class \ "graphical" is the parent class
10165: cell% field circle-radius
1.5 anton 10166:
1.78 anton 10167: :noname ( x y circle -- )
10168: circle-radius @@ draw-circle ;
10169: overrides draw
1.5 anton 10170:
1.78 anton 10171: :noname ( n-radius circle -- )
10172: circle-radius ! ;
10173: overrides construct
1.5 anton 10174:
1.78 anton 10175: end-class circle
10176: @end example
1.44 crook 10177:
1.78 anton 10178: Here we define a class @code{circle} as a child of @code{graphical},
10179: with field @code{circle-radius} (which behaves just like a field
10180: (@pxref{Structures}); it defines (using @code{overrides}) new methods
10181: for the selectors @code{draw} and @code{construct} (@code{construct} is
10182: defined in @code{object}, the parent class of @code{graphical}).
1.5 anton 10183:
1.78 anton 10184: Now we can create a circle on the heap (i.e.,
10185: @code{allocate}d memory) with:
1.44 crook 10186:
1.78 anton 10187: @cindex @code{heap-new} usage
1.5 anton 10188: @example
1.78 anton 10189: 50 circle heap-new constant my-circle
1.5 anton 10190: @end example
10191:
1.78 anton 10192: @noindent
10193: @code{heap-new} invokes @code{construct}, thus
10194: initializing the field @code{circle-radius} with 50. We can draw
10195: this new circle at (100,100) with:
1.5 anton 10196:
10197: @example
1.78 anton 10198: 100 100 my-circle draw
1.5 anton 10199: @end example
10200:
1.78 anton 10201: @cindex selector invocation, restrictions
10202: @cindex class definition, restrictions
10203: Note: You can only invoke a selector if the object on the TOS
10204: (the receiving object) belongs to the class where the selector was
10205: defined or one of its descendents; e.g., you can invoke
10206: @code{draw} only for objects belonging to @code{graphical}
10207: or its descendents (e.g., @code{circle}). Immediately before
10208: @code{end-class}, the search order has to be the same as
10209: immediately after @code{class}.
10210:
10211: @node The Objects base class, Creating objects, Basic Objects Usage, Objects
10212: @subsubsection The @file{object.fs} base class
10213: @cindex @code{object} class
10214:
10215: When you define a class, you have to specify a parent class. So how do
10216: you start defining classes? There is one class available from the start:
10217: @code{object}. It is ancestor for all classes and so is the
10218: only class that has no parent. It has two selectors: @code{construct}
10219: and @code{print}.
10220:
10221: @node Creating objects, Object-Oriented Programming Style, The Objects base class, Objects
10222: @subsubsection Creating objects
10223: @cindex creating objects
10224: @cindex object creation
10225: @cindex object allocation options
10226:
10227: @cindex @code{heap-new} discussion
10228: @cindex @code{dict-new} discussion
10229: @cindex @code{construct} discussion
10230: You can create and initialize an object of a class on the heap with
10231: @code{heap-new} ( ... class -- object ) and in the dictionary
10232: (allocation with @code{allot}) with @code{dict-new} (
10233: ... class -- object ). Both words invoke @code{construct}, which
10234: consumes the stack items indicated by "..." above.
10235:
10236: @cindex @code{init-object} discussion
10237: @cindex @code{class-inst-size} discussion
10238: If you want to allocate memory for an object yourself, you can get its
10239: alignment and size with @code{class-inst-size 2@@} ( class --
10240: align size ). Once you have memory for an object, you can initialize
10241: it with @code{init-object} ( ... class object -- );
10242: @code{construct} does only a part of the necessary work.
10243:
10244: @node Object-Oriented Programming Style, Class Binding, Creating objects, Objects
10245: @subsubsection Object-Oriented Programming Style
10246: @cindex object-oriented programming style
10247: @cindex programming style, object-oriented
1.5 anton 10248:
1.78 anton 10249: This section is not exhaustive.
1.5 anton 10250:
1.78 anton 10251: @cindex stack effects of selectors
10252: @cindex selectors and stack effects
10253: In general, it is a good idea to ensure that all methods for the
10254: same selector have the same stack effect: when you invoke a selector,
10255: you often have no idea which method will be invoked, so, unless all
10256: methods have the same stack effect, you will not know the stack effect
10257: of the selector invocation.
1.5 anton 10258:
1.78 anton 10259: One exception to this rule is methods for the selector
10260: @code{construct}. We know which method is invoked, because we
10261: specify the class to be constructed at the same place. Actually, I
10262: defined @code{construct} as a selector only to give the users a
10263: convenient way to specify initialization. The way it is used, a
10264: mechanism different from selector invocation would be more natural
10265: (but probably would take more code and more space to explain).
1.5 anton 10266:
1.78 anton 10267: @node Class Binding, Method conveniences, Object-Oriented Programming Style, Objects
10268: @subsubsection Class Binding
10269: @cindex class binding
10270: @cindex early binding
1.5 anton 10271:
1.78 anton 10272: @cindex late binding
10273: Normal selector invocations determine the method at run-time depending
10274: on the class of the receiving object. This run-time selection is called
10275: @i{late binding}.
1.5 anton 10276:
1.78 anton 10277: Sometimes it's preferable to invoke a different method. For example,
10278: you might want to use the simple method for @code{print}ing
10279: @code{object}s instead of the possibly long-winded @code{print} method
10280: of the receiver class. You can achieve this by replacing the invocation
10281: of @code{print} with:
1.5 anton 10282:
1.78 anton 10283: @cindex @code{[bind]} usage
1.5 anton 10284: @example
1.78 anton 10285: [bind] object print
1.5 anton 10286: @end example
10287:
1.78 anton 10288: @noindent
10289: in compiled code or:
10290:
10291: @cindex @code{bind} usage
1.5 anton 10292: @example
1.78 anton 10293: bind object print
1.5 anton 10294: @end example
10295:
1.78 anton 10296: @cindex class binding, alternative to
10297: @noindent
10298: in interpreted code. Alternatively, you can define the method with a
10299: name (e.g., @code{print-object}), and then invoke it through the
10300: name. Class binding is just a (often more convenient) way to achieve
10301: the same effect; it avoids name clutter and allows you to invoke
10302: methods directly without naming them first.
1.5 anton 10303:
1.78 anton 10304: @cindex superclass binding
10305: @cindex parent class binding
10306: A frequent use of class binding is this: When we define a method
10307: for a selector, we often want the method to do what the selector does
10308: in the parent class, and a little more. There is a special word for
10309: this purpose: @code{[parent]}; @code{[parent]
10310: @emph{selector}} is equivalent to @code{[bind] @emph{parent
10311: selector}}, where @code{@emph{parent}} is the parent
10312: class of the current class. E.g., a method definition might look like:
1.44 crook 10313:
1.78 anton 10314: @cindex @code{[parent]} usage
10315: @example
10316: :noname
10317: dup [parent] foo \ do parent's foo on the receiving object
10318: ... \ do some more
10319: ; overrides foo
10320: @end example
1.6 pazsan 10321:
1.78 anton 10322: @cindex class binding as optimization
10323: In @cite{Object-oriented programming in ANS Forth} (Forth Dimensions,
10324: March 1997), Andrew McKewan presents class binding as an optimization
10325: technique. I recommend not using it for this purpose unless you are in
10326: an emergency. Late binding is pretty fast with this model anyway, so the
10327: benefit of using class binding is small; the cost of using class binding
10328: where it is not appropriate is reduced maintainability.
1.44 crook 10329:
1.78 anton 10330: While we are at programming style questions: You should bind
10331: selectors only to ancestor classes of the receiving object. E.g., say,
10332: you know that the receiving object is of class @code{foo} or its
10333: descendents; then you should bind only to @code{foo} and its
10334: ancestors.
1.12 anton 10335:
1.78 anton 10336: @node Method conveniences, Classes and Scoping, Class Binding, Objects
10337: @subsubsection Method conveniences
10338: @cindex method conveniences
1.44 crook 10339:
1.78 anton 10340: In a method you usually access the receiving object pretty often. If
10341: you define the method as a plain colon definition (e.g., with
10342: @code{:noname}), you may have to do a lot of stack
10343: gymnastics. To avoid this, you can define the method with @code{m:
10344: ... ;m}. E.g., you could define the method for
10345: @code{draw}ing a @code{circle} with
1.6 pazsan 10346:
1.78 anton 10347: @cindex @code{this} usage
10348: @cindex @code{m:} usage
10349: @cindex @code{;m} usage
10350: @example
10351: m: ( x y circle -- )
10352: ( x y ) this circle-radius @@ draw-circle ;m
10353: @end example
1.6 pazsan 10354:
1.78 anton 10355: @cindex @code{exit} in @code{m: ... ;m}
10356: @cindex @code{exitm} discussion
10357: @cindex @code{catch} in @code{m: ... ;m}
10358: When this method is executed, the receiver object is removed from the
10359: stack; you can access it with @code{this} (admittedly, in this
10360: example the use of @code{m: ... ;m} offers no advantage). Note
10361: that I specify the stack effect for the whole method (i.e. including
10362: the receiver object), not just for the code between @code{m:}
10363: and @code{;m}. You cannot use @code{exit} in
10364: @code{m:...;m}; instead, use
10365: @code{exitm}.@footnote{Moreover, for any word that calls
10366: @code{catch} and was defined before loading
10367: @code{objects.fs}, you have to redefine it like I redefined
10368: @code{catch}: @code{: catch this >r catch r> to-this ;}}
1.12 anton 10369:
1.78 anton 10370: @cindex @code{inst-var} usage
10371: You will frequently use sequences of the form @code{this
10372: @emph{field}} (in the example above: @code{this
10373: circle-radius}). If you use the field only in this way, you can
10374: define it with @code{inst-var} and eliminate the
10375: @code{this} before the field name. E.g., the @code{circle}
10376: class above could also be defined with:
1.6 pazsan 10377:
1.78 anton 10378: @example
10379: graphical class
10380: cell% inst-var radius
1.6 pazsan 10381:
1.78 anton 10382: m: ( x y circle -- )
10383: radius @@ draw-circle ;m
10384: overrides draw
1.6 pazsan 10385:
1.78 anton 10386: m: ( n-radius circle -- )
10387: radius ! ;m
10388: overrides construct
1.6 pazsan 10389:
1.78 anton 10390: end-class circle
10391: @end example
1.6 pazsan 10392:
1.78 anton 10393: @code{radius} can only be used in @code{circle} and its
10394: descendent classes and inside @code{m:...;m}.
1.6 pazsan 10395:
1.78 anton 10396: @cindex @code{inst-value} usage
10397: You can also define fields with @code{inst-value}, which is
10398: to @code{inst-var} what @code{value} is to
10399: @code{variable}. You can change the value of such a field with
10400: @code{[to-inst]}. E.g., we could also define the class
10401: @code{circle} like this:
1.44 crook 10402:
1.78 anton 10403: @example
10404: graphical class
10405: inst-value radius
1.6 pazsan 10406:
1.78 anton 10407: m: ( x y circle -- )
10408: radius draw-circle ;m
10409: overrides draw
1.44 crook 10410:
1.78 anton 10411: m: ( n-radius circle -- )
10412: [to-inst] radius ;m
10413: overrides construct
1.6 pazsan 10414:
1.78 anton 10415: end-class circle
10416: @end example
1.6 pazsan 10417:
1.78 anton 10418: @c !! :m is easy to confuse with m:. Another name would be better.
1.6 pazsan 10419:
1.78 anton 10420: @c Finally, you can define named methods with @code{:m}. One use of this
10421: @c feature is the definition of words that occur only in one class and are
10422: @c not intended to be overridden, but which still need method context
10423: @c (e.g., for accessing @code{inst-var}s). Another use is for methods that
10424: @c would be bound frequently, if defined anonymously.
1.6 pazsan 10425:
10426:
1.78 anton 10427: @node Classes and Scoping, Dividing classes, Method conveniences, Objects
10428: @subsubsection Classes and Scoping
10429: @cindex classes and scoping
10430: @cindex scoping and classes
1.6 pazsan 10431:
1.78 anton 10432: Inheritance is frequent, unlike structure extension. This exacerbates
10433: the problem with the field name convention (@pxref{Structure Naming
10434: Convention}): One always has to remember in which class the field was
10435: originally defined; changing a part of the class structure would require
10436: changes for renaming in otherwise unaffected code.
1.6 pazsan 10437:
1.78 anton 10438: @cindex @code{inst-var} visibility
10439: @cindex @code{inst-value} visibility
10440: To solve this problem, I added a scoping mechanism (which was not in my
10441: original charter): A field defined with @code{inst-var} (or
10442: @code{inst-value}) is visible only in the class where it is defined and in
10443: the descendent classes of this class. Using such fields only makes
10444: sense in @code{m:}-defined methods in these classes anyway.
1.6 pazsan 10445:
1.78 anton 10446: This scoping mechanism allows us to use the unadorned field name,
10447: because name clashes with unrelated words become much less likely.
1.6 pazsan 10448:
1.78 anton 10449: @cindex @code{protected} discussion
10450: @cindex @code{private} discussion
10451: Once we have this mechanism, we can also use it for controlling the
10452: visibility of other words: All words defined after
10453: @code{protected} are visible only in the current class and its
10454: descendents. @code{public} restores the compilation
10455: (i.e. @code{current}) word list that was in effect before. If you
10456: have several @code{protected}s without an intervening
10457: @code{public} or @code{set-current}, @code{public}
10458: will restore the compilation word list in effect before the first of
10459: these @code{protected}s.
1.6 pazsan 10460:
1.78 anton 10461: @node Dividing classes, Object Interfaces, Classes and Scoping, Objects
10462: @subsubsection Dividing classes
10463: @cindex Dividing classes
10464: @cindex @code{methods}...@code{end-methods}
1.6 pazsan 10465:
1.78 anton 10466: You may want to do the definition of methods separate from the
10467: definition of the class, its selectors, fields, and instance variables,
10468: i.e., separate the implementation from the definition. You can do this
10469: in the following way:
1.6 pazsan 10470:
1.78 anton 10471: @example
10472: graphical class
10473: inst-value radius
10474: end-class circle
1.6 pazsan 10475:
1.78 anton 10476: ... \ do some other stuff
1.6 pazsan 10477:
1.78 anton 10478: circle methods \ now we are ready
1.44 crook 10479:
1.78 anton 10480: m: ( x y circle -- )
10481: radius draw-circle ;m
10482: overrides draw
1.6 pazsan 10483:
1.78 anton 10484: m: ( n-radius circle -- )
10485: [to-inst] radius ;m
10486: overrides construct
1.44 crook 10487:
1.78 anton 10488: end-methods
10489: @end example
1.7 pazsan 10490:
1.78 anton 10491: You can use several @code{methods}...@code{end-methods} sections. The
10492: only things you can do to the class in these sections are: defining
10493: methods, and overriding the class's selectors. You must not define new
10494: selectors or fields.
1.7 pazsan 10495:
1.78 anton 10496: Note that you often have to override a selector before using it. In
10497: particular, you usually have to override @code{construct} with a new
10498: method before you can invoke @code{heap-new} and friends. E.g., you
10499: must not create a circle before the @code{overrides construct} sequence
10500: in the example above.
1.7 pazsan 10501:
1.78 anton 10502: @node Object Interfaces, Objects Implementation, Dividing classes, Objects
10503: @subsubsection Object Interfaces
10504: @cindex object interfaces
10505: @cindex interfaces for objects
1.7 pazsan 10506:
1.78 anton 10507: In this model you can only call selectors defined in the class of the
10508: receiving objects or in one of its ancestors. If you call a selector
10509: with a receiving object that is not in one of these classes, the
10510: result is undefined; if you are lucky, the program crashes
10511: immediately.
1.7 pazsan 10512:
1.78 anton 10513: @cindex selectors common to hardly-related classes
10514: Now consider the case when you want to have a selector (or several)
10515: available in two classes: You would have to add the selector to a
10516: common ancestor class, in the worst case to @code{object}. You
10517: may not want to do this, e.g., because someone else is responsible for
10518: this ancestor class.
1.7 pazsan 10519:
1.78 anton 10520: The solution for this problem is interfaces. An interface is a
10521: collection of selectors. If a class implements an interface, the
10522: selectors become available to the class and its descendents. A class
10523: can implement an unlimited number of interfaces. For the problem
10524: discussed above, we would define an interface for the selector(s), and
10525: both classes would implement the interface.
1.7 pazsan 10526:
1.78 anton 10527: As an example, consider an interface @code{storage} for
10528: writing objects to disk and getting them back, and a class
10529: @code{foo} that implements it. The code would look like this:
1.7 pazsan 10530:
1.78 anton 10531: @cindex @code{interface} usage
10532: @cindex @code{end-interface} usage
10533: @cindex @code{implementation} usage
10534: @example
10535: interface
10536: selector write ( file object -- )
10537: selector read1 ( file object -- )
10538: end-interface storage
1.13 pazsan 10539:
1.78 anton 10540: bar class
10541: storage implementation
1.13 pazsan 10542:
1.78 anton 10543: ... overrides write
10544: ... overrides read1
10545: ...
10546: end-class foo
10547: @end example
1.13 pazsan 10548:
1.78 anton 10549: @noindent
10550: (I would add a word @code{read} @i{( file -- object )} that uses
10551: @code{read1} internally, but that's beyond the point illustrated
10552: here.)
1.13 pazsan 10553:
1.78 anton 10554: Note that you cannot use @code{protected} in an interface; and
10555: of course you cannot define fields.
1.13 pazsan 10556:
1.78 anton 10557: In the Neon model, all selectors are available for all classes;
10558: therefore it does not need interfaces. The price you pay in this model
10559: is slower late binding, and therefore, added complexity to avoid late
10560: binding.
1.13 pazsan 10561:
1.78 anton 10562: @node Objects Implementation, Objects Glossary, Object Interfaces, Objects
10563: @subsubsection @file{objects.fs} Implementation
10564: @cindex @file{objects.fs} implementation
1.13 pazsan 10565:
1.78 anton 10566: @cindex @code{object-map} discussion
10567: An object is a piece of memory, like one of the data structures
10568: described with @code{struct...end-struct}. It has a field
10569: @code{object-map} that points to the method map for the object's
10570: class.
1.13 pazsan 10571:
1.78 anton 10572: @cindex method map
10573: @cindex virtual function table
10574: The @emph{method map}@footnote{This is Self terminology; in C++
10575: terminology: virtual function table.} is an array that contains the
10576: execution tokens (@i{xt}s) of the methods for the object's class. Each
10577: selector contains an offset into a method map.
1.13 pazsan 10578:
1.78 anton 10579: @cindex @code{selector} implementation, class
10580: @code{selector} is a defining word that uses
10581: @code{CREATE} and @code{DOES>}. The body of the
10582: selector contains the offset; the @code{DOES>} action for a
10583: class selector is, basically:
1.8 pazsan 10584:
10585: @example
1.78 anton 10586: ( object addr ) @@ over object-map @@ + @@ execute
1.13 pazsan 10587: @end example
10588:
1.78 anton 10589: Since @code{object-map} is the first field of the object, it
10590: does not generate any code. As you can see, calling a selector has a
10591: small, constant cost.
1.26 crook 10592:
1.78 anton 10593: @cindex @code{current-interface} discussion
10594: @cindex class implementation and representation
10595: A class is basically a @code{struct} combined with a method
10596: map. During the class definition the alignment and size of the class
10597: are passed on the stack, just as with @code{struct}s, so
10598: @code{field} can also be used for defining class
10599: fields. However, passing more items on the stack would be
10600: inconvenient, so @code{class} builds a data structure in memory,
10601: which is accessed through the variable
10602: @code{current-interface}. After its definition is complete, the
10603: class is represented on the stack by a pointer (e.g., as parameter for
10604: a child class definition).
1.26 crook 10605:
1.78 anton 10606: A new class starts off with the alignment and size of its parent,
10607: and a copy of the parent's method map. Defining new fields extends the
10608: size and alignment; likewise, defining new selectors extends the
10609: method map. @code{overrides} just stores a new @i{xt} in the method
10610: map at the offset given by the selector.
1.13 pazsan 10611:
1.78 anton 10612: @cindex class binding, implementation
10613: Class binding just gets the @i{xt} at the offset given by the selector
10614: from the class's method map and @code{compile,}s (in the case of
10615: @code{[bind]}) it.
1.13 pazsan 10616:
1.78 anton 10617: @cindex @code{this} implementation
10618: @cindex @code{catch} and @code{this}
10619: @cindex @code{this} and @code{catch}
10620: I implemented @code{this} as a @code{value}. At the
10621: start of an @code{m:...;m} method the old @code{this} is
10622: stored to the return stack and restored at the end; and the object on
10623: the TOS is stored @code{TO this}. This technique has one
10624: disadvantage: If the user does not leave the method via
10625: @code{;m}, but via @code{throw} or @code{exit},
10626: @code{this} is not restored (and @code{exit} may
10627: crash). To deal with the @code{throw} problem, I have redefined
10628: @code{catch} to save and restore @code{this}; the same
10629: should be done with any word that can catch an exception. As for
10630: @code{exit}, I simply forbid it (as a replacement, there is
10631: @code{exitm}).
1.13 pazsan 10632:
1.78 anton 10633: @cindex @code{inst-var} implementation
10634: @code{inst-var} is just the same as @code{field}, with
10635: a different @code{DOES>} action:
1.13 pazsan 10636: @example
1.78 anton 10637: @@ this +
1.8 pazsan 10638: @end example
1.78 anton 10639: Similar for @code{inst-value}.
1.8 pazsan 10640:
1.78 anton 10641: @cindex class scoping implementation
10642: Each class also has a word list that contains the words defined with
10643: @code{inst-var} and @code{inst-value}, and its protected
10644: words. It also has a pointer to its parent. @code{class} pushes
10645: the word lists of the class and all its ancestors onto the search order stack,
10646: and @code{end-class} drops them.
1.20 pazsan 10647:
1.78 anton 10648: @cindex interface implementation
10649: An interface is like a class without fields, parent and protected
10650: words; i.e., it just has a method map. If a class implements an
10651: interface, its method map contains a pointer to the method map of the
10652: interface. The positive offsets in the map are reserved for class
10653: methods, therefore interface map pointers have negative
10654: offsets. Interfaces have offsets that are unique throughout the
10655: system, unlike class selectors, whose offsets are only unique for the
10656: classes where the selector is available (invokable).
1.20 pazsan 10657:
1.78 anton 10658: This structure means that interface selectors have to perform one
10659: indirection more than class selectors to find their method. Their body
10660: contains the interface map pointer offset in the class method map, and
10661: the method offset in the interface method map. The
10662: @code{does>} action for an interface selector is, basically:
1.20 pazsan 10663:
10664: @example
1.78 anton 10665: ( object selector-body )
10666: 2dup selector-interface @@ ( object selector-body object interface-offset )
10667: swap object-map @@ + @@ ( object selector-body map )
10668: swap selector-offset @@ + @@ execute
1.20 pazsan 10669: @end example
10670:
1.78 anton 10671: where @code{object-map} and @code{selector-offset} are
10672: first fields and generate no code.
1.20 pazsan 10673:
1.78 anton 10674: As a concrete example, consider the following code:
1.20 pazsan 10675:
10676: @example
1.78 anton 10677: interface
10678: selector if1sel1
10679: selector if1sel2
10680: end-interface if1
1.20 pazsan 10681:
1.78 anton 10682: object class
10683: if1 implementation
10684: selector cl1sel1
10685: cell% inst-var cl1iv1
1.20 pazsan 10686:
1.78 anton 10687: ' m1 overrides construct
10688: ' m2 overrides if1sel1
10689: ' m3 overrides if1sel2
10690: ' m4 overrides cl1sel2
10691: end-class cl1
1.20 pazsan 10692:
1.78 anton 10693: create obj1 object dict-new drop
10694: create obj2 cl1 dict-new drop
10695: @end example
1.20 pazsan 10696:
1.78 anton 10697: The data structure created by this code (including the data structure
10698: for @code{object}) is shown in the
10699: @uref{objects-implementation.eps,figure}, assuming a cell size of 4.
10700: @comment TODO add this diagram..
1.20 pazsan 10701:
1.78 anton 10702: @node Objects Glossary, , Objects Implementation, Objects
10703: @subsubsection @file{objects.fs} Glossary
10704: @cindex @file{objects.fs} Glossary
1.20 pazsan 10705:
10706:
1.78 anton 10707: doc---objects-bind
10708: doc---objects-<bind>
10709: doc---objects-bind'
10710: doc---objects-[bind]
10711: doc---objects-class
10712: doc---objects-class->map
10713: doc---objects-class-inst-size
10714: doc---objects-class-override!
1.79 anton 10715: doc---objects-class-previous
10716: doc---objects-class>order
1.78 anton 10717: doc---objects-construct
10718: doc---objects-current'
10719: doc---objects-[current]
10720: doc---objects-current-interface
10721: doc---objects-dict-new
10722: doc---objects-end-class
10723: doc---objects-end-class-noname
10724: doc---objects-end-interface
10725: doc---objects-end-interface-noname
10726: doc---objects-end-methods
10727: doc---objects-exitm
10728: doc---objects-heap-new
10729: doc---objects-implementation
10730: doc---objects-init-object
10731: doc---objects-inst-value
10732: doc---objects-inst-var
10733: doc---objects-interface
10734: doc---objects-m:
10735: doc---objects-:m
10736: doc---objects-;m
10737: doc---objects-method
10738: doc---objects-methods
10739: doc---objects-object
10740: doc---objects-overrides
10741: doc---objects-[parent]
10742: doc---objects-print
10743: doc---objects-protected
10744: doc---objects-public
10745: doc---objects-selector
10746: doc---objects-this
10747: doc---objects-<to-inst>
10748: doc---objects-[to-inst]
10749: doc---objects-to-this
10750: doc---objects-xt-new
1.20 pazsan 10751:
10752:
1.78 anton 10753: @c -------------------------------------------------------------
10754: @node OOF, Mini-OOF, Objects, Object-oriented Forth
10755: @subsection The @file{oof.fs} model
10756: @cindex oof
10757: @cindex object-oriented programming
1.20 pazsan 10758:
1.78 anton 10759: @cindex @file{objects.fs}
10760: @cindex @file{oof.fs}
1.20 pazsan 10761:
1.78 anton 10762: This section describes the @file{oof.fs} package.
1.20 pazsan 10763:
1.78 anton 10764: The package described in this section has been used in bigFORTH since 1991, and
10765: used for two large applications: a chromatographic system used to
10766: create new medicaments, and a graphic user interface library (MINOS).
1.20 pazsan 10767:
1.78 anton 10768: You can find a description (in German) of @file{oof.fs} in @cite{Object
10769: oriented bigFORTH} by Bernd Paysan, published in @cite{Vierte Dimension}
10770: 10(2), 1994.
1.20 pazsan 10771:
1.78 anton 10772: @menu
10773: * Properties of the OOF model::
10774: * Basic OOF Usage::
10775: * The OOF base class::
10776: * Class Declaration::
10777: * Class Implementation::
10778: @end menu
1.20 pazsan 10779:
1.78 anton 10780: @node Properties of the OOF model, Basic OOF Usage, OOF, OOF
10781: @subsubsection Properties of the @file{oof.fs} model
10782: @cindex @file{oof.fs} properties
1.20 pazsan 10783:
1.78 anton 10784: @itemize @bullet
10785: @item
10786: This model combines object oriented programming with information
10787: hiding. It helps you writing large application, where scoping is
10788: necessary, because it provides class-oriented scoping.
1.20 pazsan 10789:
1.78 anton 10790: @item
10791: Named objects, object pointers, and object arrays can be created,
10792: selector invocation uses the ``object selector'' syntax. Selector invocation
10793: to objects and/or selectors on the stack is a bit less convenient, but
10794: possible.
1.44 crook 10795:
1.78 anton 10796: @item
10797: Selector invocation and instance variable usage of the active object is
10798: straightforward, since both make use of the active object.
1.44 crook 10799:
1.78 anton 10800: @item
10801: Late binding is efficient and easy to use.
1.20 pazsan 10802:
1.78 anton 10803: @item
10804: State-smart objects parse selectors. However, extensibility is provided
10805: using a (parsing) selector @code{postpone} and a selector @code{'}.
1.20 pazsan 10806:
1.78 anton 10807: @item
10808: An implementation in ANS Forth is available.
1.20 pazsan 10809:
1.78 anton 10810: @end itemize
1.23 crook 10811:
10812:
1.78 anton 10813: @node Basic OOF Usage, The OOF base class, Properties of the OOF model, OOF
10814: @subsubsection Basic @file{oof.fs} Usage
10815: @cindex @file{oof.fs} usage
1.23 crook 10816:
1.78 anton 10817: This section uses the same example as for @code{objects} (@pxref{Basic Objects Usage}).
1.23 crook 10818:
1.78 anton 10819: You can define a class for graphical objects like this:
1.23 crook 10820:
1.78 anton 10821: @cindex @code{class} usage
10822: @cindex @code{class;} usage
10823: @cindex @code{method} usage
10824: @example
10825: object class graphical \ "object" is the parent class
10826: method draw ( x y graphical -- )
10827: class;
10828: @end example
1.23 crook 10829:
1.78 anton 10830: This code defines a class @code{graphical} with an
10831: operation @code{draw}. We can perform the operation
10832: @code{draw} on any @code{graphical} object, e.g.:
1.23 crook 10833:
1.78 anton 10834: @example
10835: 100 100 t-rex draw
10836: @end example
1.23 crook 10837:
1.78 anton 10838: @noindent
10839: where @code{t-rex} is an object or object pointer, created with e.g.
10840: @code{graphical : t-rex}.
1.23 crook 10841:
1.78 anton 10842: @cindex abstract class
10843: How do we create a graphical object? With the present definitions,
10844: we cannot create a useful graphical object. The class
10845: @code{graphical} describes graphical objects in general, but not
10846: any concrete graphical object type (C++ users would call it an
10847: @emph{abstract class}); e.g., there is no method for the selector
10848: @code{draw} in the class @code{graphical}.
1.23 crook 10849:
1.78 anton 10850: For concrete graphical objects, we define child classes of the
10851: class @code{graphical}, e.g.:
1.23 crook 10852:
1.78 anton 10853: @example
10854: graphical class circle \ "graphical" is the parent class
10855: cell var circle-radius
10856: how:
10857: : draw ( x y -- )
10858: circle-radius @@ draw-circle ;
1.23 crook 10859:
1.78 anton 10860: : init ( n-radius -- (
10861: circle-radius ! ;
10862: class;
10863: @end example
1.1 anton 10864:
1.78 anton 10865: Here we define a class @code{circle} as a child of @code{graphical},
10866: with a field @code{circle-radius}; it defines new methods for the
10867: selectors @code{draw} and @code{init} (@code{init} is defined in
10868: @code{object}, the parent class of @code{graphical}).
1.1 anton 10869:
1.78 anton 10870: Now we can create a circle in the dictionary with:
1.1 anton 10871:
1.78 anton 10872: @example
10873: 50 circle : my-circle
10874: @end example
1.21 crook 10875:
1.78 anton 10876: @noindent
10877: @code{:} invokes @code{init}, thus initializing the field
10878: @code{circle-radius} with 50. We can draw this new circle at (100,100)
10879: with:
1.1 anton 10880:
1.78 anton 10881: @example
10882: 100 100 my-circle draw
10883: @end example
1.1 anton 10884:
1.78 anton 10885: @cindex selector invocation, restrictions
10886: @cindex class definition, restrictions
10887: Note: You can only invoke a selector if the receiving object belongs to
10888: the class where the selector was defined or one of its descendents;
10889: e.g., you can invoke @code{draw} only for objects belonging to
10890: @code{graphical} or its descendents (e.g., @code{circle}). The scoping
10891: mechanism will check if you try to invoke a selector that is not
10892: defined in this class hierarchy, so you'll get an error at compilation
10893: time.
1.1 anton 10894:
10895:
1.78 anton 10896: @node The OOF base class, Class Declaration, Basic OOF Usage, OOF
10897: @subsubsection The @file{oof.fs} base class
10898: @cindex @file{oof.fs} base class
1.1 anton 10899:
1.78 anton 10900: When you define a class, you have to specify a parent class. So how do
10901: you start defining classes? There is one class available from the start:
10902: @code{object}. You have to use it as ancestor for all classes. It is the
10903: only class that has no parent. Classes are also objects, except that
10904: they don't have instance variables; class manipulation such as
10905: inheritance or changing definitions of a class is handled through
10906: selectors of the class @code{object}.
1.1 anton 10907:
1.78 anton 10908: @code{object} provides a number of selectors:
1.1 anton 10909:
1.78 anton 10910: @itemize @bullet
10911: @item
10912: @code{class} for subclassing, @code{definitions} to add definitions
10913: later on, and @code{class?} to get type informations (is the class a
10914: subclass of the class passed on the stack?).
1.1 anton 10915:
1.78 anton 10916: doc---object-class
10917: doc---object-definitions
10918: doc---object-class?
1.1 anton 10919:
10920:
1.26 crook 10921: @item
1.78 anton 10922: @code{init} and @code{dispose} as constructor and destructor of the
10923: object. @code{init} is invocated after the object's memory is allocated,
10924: while @code{dispose} also handles deallocation. Thus if you redefine
10925: @code{dispose}, you have to call the parent's dispose with @code{super
10926: dispose}, too.
10927:
10928: doc---object-init
10929: doc---object-dispose
10930:
1.1 anton 10931:
1.26 crook 10932: @item
1.78 anton 10933: @code{new}, @code{new[]}, @code{:}, @code{ptr}, @code{asptr}, and
10934: @code{[]} to create named and unnamed objects and object arrays or
10935: object pointers.
10936:
10937: doc---object-new
10938: doc---object-new[]
10939: doc---object-:
10940: doc---object-ptr
10941: doc---object-asptr
10942: doc---object-[]
10943:
1.1 anton 10944:
1.26 crook 10945: @item
1.78 anton 10946: @code{::} and @code{super} for explicit scoping. You should use explicit
10947: scoping only for super classes or classes with the same set of instance
10948: variables. Explicitly-scoped selectors use early binding.
1.21 crook 10949:
1.78 anton 10950: doc---object-::
10951: doc---object-super
1.21 crook 10952:
10953:
1.26 crook 10954: @item
1.78 anton 10955: @code{self} to get the address of the object
1.21 crook 10956:
1.78 anton 10957: doc---object-self
1.21 crook 10958:
10959:
1.78 anton 10960: @item
10961: @code{bind}, @code{bound}, @code{link}, and @code{is} to assign object
10962: pointers and instance defers.
1.21 crook 10963:
1.78 anton 10964: doc---object-bind
10965: doc---object-bound
10966: doc---object-link
10967: doc---object-is
1.21 crook 10968:
10969:
1.78 anton 10970: @item
10971: @code{'} to obtain selector tokens, @code{send} to invocate selectors
10972: form the stack, and @code{postpone} to generate selector invocation code.
1.21 crook 10973:
1.78 anton 10974: doc---object-'
10975: doc---object-postpone
1.21 crook 10976:
10977:
1.78 anton 10978: @item
10979: @code{with} and @code{endwith} to select the active object from the
10980: stack, and enable its scope. Using @code{with} and @code{endwith}
10981: also allows you to create code using selector @code{postpone} without being
10982: trapped by the state-smart objects.
1.21 crook 10983:
1.78 anton 10984: doc---object-with
10985: doc---object-endwith
1.21 crook 10986:
10987:
1.78 anton 10988: @end itemize
1.21 crook 10989:
1.78 anton 10990: @node Class Declaration, Class Implementation, The OOF base class, OOF
10991: @subsubsection Class Declaration
10992: @cindex class declaration
1.21 crook 10993:
1.78 anton 10994: @itemize @bullet
10995: @item
10996: Instance variables
1.21 crook 10997:
1.78 anton 10998: doc---oof-var
1.21 crook 10999:
11000:
1.78 anton 11001: @item
11002: Object pointers
1.21 crook 11003:
1.78 anton 11004: doc---oof-ptr
11005: doc---oof-asptr
1.21 crook 11006:
11007:
1.78 anton 11008: @item
11009: Instance defers
1.21 crook 11010:
1.78 anton 11011: doc---oof-defer
1.21 crook 11012:
11013:
1.78 anton 11014: @item
11015: Method selectors
1.21 crook 11016:
1.78 anton 11017: doc---oof-early
11018: doc---oof-method
1.21 crook 11019:
11020:
1.78 anton 11021: @item
11022: Class-wide variables
1.21 crook 11023:
1.78 anton 11024: doc---oof-static
1.21 crook 11025:
11026:
1.78 anton 11027: @item
11028: End declaration
1.1 anton 11029:
1.78 anton 11030: doc---oof-how:
11031: doc---oof-class;
1.21 crook 11032:
11033:
1.78 anton 11034: @end itemize
1.21 crook 11035:
1.78 anton 11036: @c -------------------------------------------------------------
11037: @node Class Implementation, , Class Declaration, OOF
11038: @subsubsection Class Implementation
11039: @cindex class implementation
1.21 crook 11040:
1.78 anton 11041: @c -------------------------------------------------------------
11042: @node Mini-OOF, Comparison with other object models, OOF, Object-oriented Forth
11043: @subsection The @file{mini-oof.fs} model
11044: @cindex mini-oof
1.21 crook 11045:
1.78 anton 11046: Gforth's third object oriented Forth package is a 12-liner. It uses a
1.79 anton 11047: mixture of the @file{objects.fs} and the @file{oof.fs} syntax,
1.78 anton 11048: and reduces to the bare minimum of features. This is based on a posting
11049: of Bernd Paysan in comp.lang.forth.
1.21 crook 11050:
1.78 anton 11051: @menu
11052: * Basic Mini-OOF Usage::
11053: * Mini-OOF Example::
11054: * Mini-OOF Implementation::
11055: @end menu
1.21 crook 11056:
1.78 anton 11057: @c -------------------------------------------------------------
11058: @node Basic Mini-OOF Usage, Mini-OOF Example, Mini-OOF, Mini-OOF
11059: @subsubsection Basic @file{mini-oof.fs} Usage
11060: @cindex mini-oof usage
1.21 crook 11061:
1.78 anton 11062: There is a base class (@code{class}, which allocates one cell for the
11063: object pointer) plus seven other words: to define a method, a variable,
11064: a class; to end a class, to resolve binding, to allocate an object and
11065: to compile a class method.
11066: @comment TODO better description of the last one
1.26 crook 11067:
1.21 crook 11068:
1.78 anton 11069: doc-object
11070: doc-method
11071: doc-var
11072: doc-class
11073: doc-end-class
11074: doc-defines
11075: doc-new
11076: doc-::
1.21 crook 11077:
11078:
11079:
1.78 anton 11080: @c -------------------------------------------------------------
11081: @node Mini-OOF Example, Mini-OOF Implementation, Basic Mini-OOF Usage, Mini-OOF
11082: @subsubsection Mini-OOF Example
11083: @cindex mini-oof example
1.1 anton 11084:
1.78 anton 11085: A short example shows how to use this package. This example, in slightly
11086: extended form, is supplied as @file{moof-exm.fs}
11087: @comment TODO could flesh this out with some comments from the Forthwrite article
1.20 pazsan 11088:
1.26 crook 11089: @example
1.78 anton 11090: object class
11091: method init
11092: method draw
11093: end-class graphical
1.26 crook 11094: @end example
1.20 pazsan 11095:
1.78 anton 11096: This code defines a class @code{graphical} with an
11097: operation @code{draw}. We can perform the operation
11098: @code{draw} on any @code{graphical} object, e.g.:
1.20 pazsan 11099:
1.26 crook 11100: @example
1.78 anton 11101: 100 100 t-rex draw
1.26 crook 11102: @end example
1.12 anton 11103:
1.78 anton 11104: where @code{t-rex} is an object or object pointer, created with e.g.
11105: @code{graphical new Constant t-rex}.
1.12 anton 11106:
1.78 anton 11107: For concrete graphical objects, we define child classes of the
11108: class @code{graphical}, e.g.:
1.12 anton 11109:
1.26 crook 11110: @example
11111: graphical class
1.78 anton 11112: cell var circle-radius
11113: end-class circle \ "graphical" is the parent class
1.12 anton 11114:
1.78 anton 11115: :noname ( x y -- )
11116: circle-radius @@ draw-circle ; circle defines draw
11117: :noname ( r -- )
11118: circle-radius ! ; circle defines init
11119: @end example
1.12 anton 11120:
1.78 anton 11121: There is no implicit init method, so we have to define one. The creation
11122: code of the object now has to call init explicitely.
1.21 crook 11123:
1.78 anton 11124: @example
11125: circle new Constant my-circle
11126: 50 my-circle init
1.12 anton 11127: @end example
11128:
1.78 anton 11129: It is also possible to add a function to create named objects with
11130: automatic call of @code{init}, given that all objects have @code{init}
11131: on the same place:
1.38 anton 11132:
1.78 anton 11133: @example
11134: : new: ( .. o "name" -- )
11135: new dup Constant init ;
11136: 80 circle new: large-circle
11137: @end example
1.12 anton 11138:
1.78 anton 11139: We can draw this new circle at (100,100) with:
1.12 anton 11140:
1.78 anton 11141: @example
11142: 100 100 my-circle draw
11143: @end example
1.12 anton 11144:
1.78 anton 11145: @node Mini-OOF Implementation, , Mini-OOF Example, Mini-OOF
11146: @subsubsection @file{mini-oof.fs} Implementation
1.12 anton 11147:
1.78 anton 11148: Object-oriented systems with late binding typically use a
11149: ``vtable''-approach: the first variable in each object is a pointer to a
11150: table, which contains the methods as function pointers. The vtable
11151: may also contain other information.
1.12 anton 11152:
1.79 anton 11153: So first, let's declare selectors:
1.37 anton 11154:
11155: @example
1.79 anton 11156: : method ( m v "name" -- m' v ) Create over , swap cell+ swap
1.78 anton 11157: DOES> ( ... o -- ... ) @@ over @@ + @@ execute ;
11158: @end example
1.37 anton 11159:
1.79 anton 11160: During selector declaration, the number of selectors and instance
11161: variables is on the stack (in address units). @code{method} creates one
11162: selector and increments the selector number. To execute a selector, it
1.78 anton 11163: takes the object, fetches the vtable pointer, adds the offset, and
1.79 anton 11164: executes the method @i{xt} stored there. Each selector takes the object
11165: it is invoked with as top of stack parameter; it passes the parameters
11166: (including the object) unchanged to the appropriate method which should
1.78 anton 11167: consume that object.
1.37 anton 11168:
1.78 anton 11169: Now, we also have to declare instance variables
1.37 anton 11170:
1.78 anton 11171: @example
1.79 anton 11172: : var ( m v size "name" -- m v' ) Create over , +
1.78 anton 11173: DOES> ( o -- addr ) @@ + ;
1.37 anton 11174: @end example
11175:
1.78 anton 11176: As before, a word is created with the current offset. Instance
11177: variables can have different sizes (cells, floats, doubles, chars), so
11178: all we do is take the size and add it to the offset. If your machine
11179: has alignment restrictions, put the proper @code{aligned} or
11180: @code{faligned} before the variable, to adjust the variable
11181: offset. That's why it is on the top of stack.
1.37 anton 11182:
1.78 anton 11183: We need a starting point (the base object) and some syntactic sugar:
1.37 anton 11184:
1.78 anton 11185: @example
11186: Create object 1 cells , 2 cells ,
1.79 anton 11187: : class ( class -- class selectors vars ) dup 2@@ ;
1.78 anton 11188: @end example
1.12 anton 11189:
1.78 anton 11190: For inheritance, the vtable of the parent object has to be
11191: copied when a new, derived class is declared. This gives all the
11192: methods of the parent class, which can be overridden, though.
1.12 anton 11193:
1.78 anton 11194: @example
1.79 anton 11195: : end-class ( class selectors vars "name" -- )
1.78 anton 11196: Create here >r , dup , 2 cells ?DO ['] noop , 1 cells +LOOP
11197: cell+ dup cell+ r> rot @@ 2 cells /string move ;
11198: @end example
1.12 anton 11199:
1.78 anton 11200: The first line creates the vtable, initialized with
11201: @code{noop}s. The second line is the inheritance mechanism, it
11202: copies the xts from the parent vtable.
1.12 anton 11203:
1.78 anton 11204: We still have no way to define new methods, let's do that now:
1.12 anton 11205:
1.26 crook 11206: @example
1.79 anton 11207: : defines ( xt class "name" -- ) ' >body @@ + ! ;
1.78 anton 11208: @end example
1.12 anton 11209:
1.78 anton 11210: To allocate a new object, we need a word, too:
1.12 anton 11211:
1.78 anton 11212: @example
11213: : new ( class -- o ) here over @@ allot swap over ! ;
1.12 anton 11214: @end example
11215:
1.78 anton 11216: Sometimes derived classes want to access the method of the
11217: parent object. There are two ways to achieve this with Mini-OOF:
11218: first, you could use named words, and second, you could look up the
11219: vtable of the parent object.
1.12 anton 11220:
1.78 anton 11221: @example
11222: : :: ( class "name" -- ) ' >body @@ + @@ compile, ;
11223: @end example
1.12 anton 11224:
11225:
1.78 anton 11226: Nothing can be more confusing than a good example, so here is
11227: one. First let's declare a text object (called
11228: @code{button}), that stores text and position:
1.12 anton 11229:
1.78 anton 11230: @example
11231: object class
11232: cell var text
11233: cell var len
11234: cell var x
11235: cell var y
11236: method init
11237: method draw
11238: end-class button
11239: @end example
1.12 anton 11240:
1.78 anton 11241: @noindent
11242: Now, implement the two methods, @code{draw} and @code{init}:
1.21 crook 11243:
1.26 crook 11244: @example
1.78 anton 11245: :noname ( o -- )
11246: >r r@@ x @@ r@@ y @@ at-xy r@@ text @@ r> len @@ type ;
11247: button defines draw
11248: :noname ( addr u o -- )
11249: >r 0 r@@ x ! 0 r@@ y ! r@@ len ! r> text ! ;
11250: button defines init
1.26 crook 11251: @end example
1.12 anton 11252:
1.78 anton 11253: @noindent
11254: To demonstrate inheritance, we define a class @code{bold-button}, with no
1.79 anton 11255: new data and no new selectors:
1.78 anton 11256:
11257: @example
11258: button class
11259: end-class bold-button
1.12 anton 11260:
1.78 anton 11261: : bold 27 emit ." [1m" ;
11262: : normal 27 emit ." [0m" ;
11263: @end example
1.1 anton 11264:
1.78 anton 11265: @noindent
11266: The class @code{bold-button} has a different draw method to
11267: @code{button}, but the new method is defined in terms of the draw method
11268: for @code{button}:
1.20 pazsan 11269:
1.78 anton 11270: @example
11271: :noname bold [ button :: draw ] normal ; bold-button defines draw
11272: @end example
1.21 crook 11273:
1.78 anton 11274: @noindent
1.79 anton 11275: Finally, create two objects and apply selectors:
1.21 crook 11276:
1.26 crook 11277: @example
1.78 anton 11278: button new Constant foo
11279: s" thin foo" foo init
11280: page
11281: foo draw
11282: bold-button new Constant bar
11283: s" fat bar" bar init
11284: 1 bar y !
11285: bar draw
1.26 crook 11286: @end example
1.21 crook 11287:
11288:
1.78 anton 11289: @node Comparison with other object models, , Mini-OOF, Object-oriented Forth
11290: @subsection Comparison with other object models
11291: @cindex comparison of object models
11292: @cindex object models, comparison
11293:
11294: Many object-oriented Forth extensions have been proposed (@cite{A survey
11295: of object-oriented Forths} (SIGPLAN Notices, April 1996) by Bradford
11296: J. Rodriguez and W. F. S. Poehlman lists 17). This section discusses the
11297: relation of the object models described here to two well-known and two
11298: closely-related (by the use of method maps) models. Andras Zsoter
11299: helped us with this section.
11300:
11301: @cindex Neon model
11302: The most popular model currently seems to be the Neon model (see
11303: @cite{Object-oriented programming in ANS Forth} (Forth Dimensions, March
11304: 1997) by Andrew McKewan) but this model has a number of limitations
11305: @footnote{A longer version of this critique can be
11306: found in @cite{On Standardizing Object-Oriented Forth Extensions} (Forth
11307: Dimensions, May 1997) by Anton Ertl.}:
11308:
11309: @itemize @bullet
11310: @item
11311: It uses a @code{@emph{selector object}} syntax, which makes it unnatural
11312: to pass objects on the stack.
1.21 crook 11313:
1.78 anton 11314: @item
11315: It requires that the selector parses the input stream (at
1.79 anton 11316: compile time); this leads to reduced extensibility and to bugs that are
1.78 anton 11317: hard to find.
1.21 crook 11318:
1.78 anton 11319: @item
1.79 anton 11320: It allows using every selector on every object; this eliminates the
11321: need for interfaces, but makes it harder to create efficient
11322: implementations.
1.78 anton 11323: @end itemize
1.21 crook 11324:
1.78 anton 11325: @cindex Pountain's object-oriented model
11326: Another well-known publication is @cite{Object-Oriented Forth} (Academic
11327: Press, London, 1987) by Dick Pountain. However, it is not really about
11328: object-oriented programming, because it hardly deals with late
11329: binding. Instead, it focuses on features like information hiding and
11330: overloading that are characteristic of modular languages like Ada (83).
1.26 crook 11331:
1.78 anton 11332: @cindex Zsoter's object-oriented model
1.79 anton 11333: In @uref{http://www.forth.org/oopf.html, Does late binding have to be
11334: slow?} (Forth Dimensions 18(1) 1996, pages 31-35) Andras Zsoter
11335: describes a model that makes heavy use of an active object (like
11336: @code{this} in @file{objects.fs}): The active object is not only used
11337: for accessing all fields, but also specifies the receiving object of
11338: every selector invocation; you have to change the active object
11339: explicitly with @code{@{ ... @}}, whereas in @file{objects.fs} it
11340: changes more or less implicitly at @code{m: ... ;m}. Such a change at
11341: the method entry point is unnecessary with Zsoter's model, because the
11342: receiving object is the active object already. On the other hand, the
11343: explicit change is absolutely necessary in that model, because otherwise
11344: no one could ever change the active object. An ANS Forth implementation
11345: of this model is available through
11346: @uref{http://www.forth.org/oopf.html}.
1.21 crook 11347:
1.78 anton 11348: @cindex @file{oof.fs}, differences to other models
11349: The @file{oof.fs} model combines information hiding and overloading
11350: resolution (by keeping names in various word lists) with object-oriented
11351: programming. It sets the active object implicitly on method entry, but
11352: also allows explicit changing (with @code{>o...o>} or with
11353: @code{with...endwith}). It uses parsing and state-smart objects and
11354: classes for resolving overloading and for early binding: the object or
11355: class parses the selector and determines the method from this. If the
11356: selector is not parsed by an object or class, it performs a call to the
11357: selector for the active object (late binding), like Zsoter's model.
11358: Fields are always accessed through the active object. The big
11359: disadvantage of this model is the parsing and the state-smartness, which
11360: reduces extensibility and increases the opportunities for subtle bugs;
11361: essentially, you are only safe if you never tick or @code{postpone} an
11362: object or class (Bernd disagrees, but I (Anton) am not convinced).
1.21 crook 11363:
1.78 anton 11364: @cindex @file{mini-oof.fs}, differences to other models
11365: The @file{mini-oof.fs} model is quite similar to a very stripped-down
11366: version of the @file{objects.fs} model, but syntactically it is a
11367: mixture of the @file{objects.fs} and @file{oof.fs} models.
1.21 crook 11368:
11369:
1.78 anton 11370: @c -------------------------------------------------------------
11371: @node Programming Tools, Assembler and Code Words, Object-oriented Forth, Words
11372: @section Programming Tools
11373: @cindex programming tools
1.21 crook 11374:
1.78 anton 11375: @c !! move this and assembler down below OO stuff.
1.21 crook 11376:
1.78 anton 11377: @menu
11378: * Examining::
11379: * Forgetting words::
11380: * Debugging:: Simple and quick.
11381: * Assertions:: Making your programs self-checking.
11382: * Singlestep Debugger:: Executing your program word by word.
11383: @end menu
1.21 crook 11384:
1.78 anton 11385: @node Examining, Forgetting words, Programming Tools, Programming Tools
11386: @subsection Examining data and code
11387: @cindex examining data and code
11388: @cindex data examination
11389: @cindex code examination
1.44 crook 11390:
1.78 anton 11391: The following words inspect the stack non-destructively:
1.21 crook 11392:
1.78 anton 11393: doc-.s
11394: doc-f.s
1.44 crook 11395:
1.78 anton 11396: There is a word @code{.r} but it does @i{not} display the return stack!
11397: It is used for formatted numeric output (@pxref{Simple numeric output}).
1.21 crook 11398:
1.78 anton 11399: doc-depth
11400: doc-fdepth
11401: doc-clearstack
1.21 crook 11402:
1.78 anton 11403: The following words inspect memory.
1.21 crook 11404:
1.78 anton 11405: doc-?
11406: doc-dump
1.21 crook 11407:
1.78 anton 11408: And finally, @code{see} allows to inspect code:
1.21 crook 11409:
1.78 anton 11410: doc-see
11411: doc-xt-see
1.21 crook 11412:
1.78 anton 11413: @node Forgetting words, Debugging, Examining, Programming Tools
11414: @subsection Forgetting words
11415: @cindex words, forgetting
11416: @cindex forgeting words
1.21 crook 11417:
1.78 anton 11418: @c anton: other, maybe better places for this subsection: Defining Words;
11419: @c Dictionary allocation. At least a reference should be there.
1.21 crook 11420:
1.78 anton 11421: Forth allows you to forget words (and everything that was alloted in the
11422: dictonary after them) in a LIFO manner.
1.21 crook 11423:
1.78 anton 11424: doc-marker
1.21 crook 11425:
1.78 anton 11426: The most common use of this feature is during progam development: when
11427: you change a source file, forget all the words it defined and load it
11428: again (since you also forget everything defined after the source file
11429: was loaded, you have to reload that, too). Note that effects like
11430: storing to variables and destroyed system words are not undone when you
11431: forget words. With a system like Gforth, that is fast enough at
11432: starting up and compiling, I find it more convenient to exit and restart
11433: Gforth, as this gives me a clean slate.
1.21 crook 11434:
1.78 anton 11435: Here's an example of using @code{marker} at the start of a source file
11436: that you are debugging; it ensures that you only ever have one copy of
11437: the file's definitions compiled at any time:
1.21 crook 11438:
1.78 anton 11439: @example
11440: [IFDEF] my-code
11441: my-code
11442: [ENDIF]
1.26 crook 11443:
1.78 anton 11444: marker my-code
11445: init-included-files
1.21 crook 11446:
1.78 anton 11447: \ .. definitions start here
11448: \ .
11449: \ .
11450: \ end
11451: @end example
1.21 crook 11452:
1.26 crook 11453:
1.78 anton 11454: @node Debugging, Assertions, Forgetting words, Programming Tools
11455: @subsection Debugging
11456: @cindex debugging
1.21 crook 11457:
1.78 anton 11458: Languages with a slow edit/compile/link/test development loop tend to
11459: require sophisticated tracing/stepping debuggers to facilate debugging.
1.21 crook 11460:
1.78 anton 11461: A much better (faster) way in fast-compiling languages is to add
11462: printing code at well-selected places, let the program run, look at
11463: the output, see where things went wrong, add more printing code, etc.,
11464: until the bug is found.
1.21 crook 11465:
1.78 anton 11466: The simple debugging aids provided in @file{debugs.fs}
11467: are meant to support this style of debugging.
1.21 crook 11468:
1.78 anton 11469: The word @code{~~} prints debugging information (by default the source
11470: location and the stack contents). It is easy to insert. If you use Emacs
11471: it is also easy to remove (@kbd{C-x ~} in the Emacs Forth mode to
11472: query-replace them with nothing). The deferred words
11473: @code{printdebugdata} and @code{printdebugline} control the output of
11474: @code{~~}. The default source location output format works well with
11475: Emacs' compilation mode, so you can step through the program at the
11476: source level using @kbd{C-x `} (the advantage over a stepping debugger
11477: is that you can step in any direction and you know where the crash has
11478: happened or where the strange data has occurred).
1.21 crook 11479:
1.78 anton 11480: doc-~~
11481: doc-printdebugdata
11482: doc-printdebugline
1.21 crook 11483:
1.78 anton 11484: @node Assertions, Singlestep Debugger, Debugging, Programming Tools
11485: @subsection Assertions
11486: @cindex assertions
1.21 crook 11487:
1.78 anton 11488: It is a good idea to make your programs self-checking, especially if you
11489: make an assumption that may become invalid during maintenance (for
11490: example, that a certain field of a data structure is never zero). Gforth
11491: supports @dfn{assertions} for this purpose. They are used like this:
1.21 crook 11492:
11493: @example
1.78 anton 11494: assert( @i{flag} )
1.26 crook 11495: @end example
11496:
1.78 anton 11497: The code between @code{assert(} and @code{)} should compute a flag, that
11498: should be true if everything is alright and false otherwise. It should
11499: not change anything else on the stack. The overall stack effect of the
11500: assertion is @code{( -- )}. E.g.
1.21 crook 11501:
1.26 crook 11502: @example
1.78 anton 11503: assert( 1 1 + 2 = ) \ what we learn in school
11504: assert( dup 0<> ) \ assert that the top of stack is not zero
11505: assert( false ) \ this code should not be reached
1.21 crook 11506: @end example
11507:
1.78 anton 11508: The need for assertions is different at different times. During
11509: debugging, we want more checking, in production we sometimes care more
11510: for speed. Therefore, assertions can be turned off, i.e., the assertion
11511: becomes a comment. Depending on the importance of an assertion and the
11512: time it takes to check it, you may want to turn off some assertions and
11513: keep others turned on. Gforth provides several levels of assertions for
11514: this purpose:
11515:
11516:
11517: doc-assert0(
11518: doc-assert1(
11519: doc-assert2(
11520: doc-assert3(
11521: doc-assert(
11522: doc-)
1.21 crook 11523:
11524:
1.78 anton 11525: The variable @code{assert-level} specifies the highest assertions that
11526: are turned on. I.e., at the default @code{assert-level} of one,
11527: @code{assert0(} and @code{assert1(} assertions perform checking, while
11528: @code{assert2(} and @code{assert3(} assertions are treated as comments.
1.26 crook 11529:
1.78 anton 11530: The value of @code{assert-level} is evaluated at compile-time, not at
11531: run-time. Therefore you cannot turn assertions on or off at run-time;
11532: you have to set the @code{assert-level} appropriately before compiling a
11533: piece of code. You can compile different pieces of code at different
11534: @code{assert-level}s (e.g., a trusted library at level 1 and
11535: newly-written code at level 3).
1.26 crook 11536:
11537:
1.78 anton 11538: doc-assert-level
1.26 crook 11539:
11540:
1.78 anton 11541: If an assertion fails, a message compatible with Emacs' compilation mode
11542: is produced and the execution is aborted (currently with @code{ABORT"}.
11543: If there is interest, we will introduce a special throw code. But if you
11544: intend to @code{catch} a specific condition, using @code{throw} is
11545: probably more appropriate than an assertion).
1.44 crook 11546:
1.78 anton 11547: Definitions in ANS Forth for these assertion words are provided
11548: in @file{compat/assert.fs}.
1.26 crook 11549:
1.44 crook 11550:
1.78 anton 11551: @node Singlestep Debugger, , Assertions, Programming Tools
11552: @subsection Singlestep Debugger
11553: @cindex singlestep Debugger
11554: @cindex debugging Singlestep
1.44 crook 11555:
1.78 anton 11556: When you create a new word there's often the need to check whether it
11557: behaves correctly or not. You can do this by typing @code{dbg
11558: badword}. A debug session might look like this:
1.26 crook 11559:
1.78 anton 11560: @example
11561: : badword 0 DO i . LOOP ; ok
11562: 2 dbg badword
11563: : badword
11564: Scanning code...
1.44 crook 11565:
1.78 anton 11566: Nesting debugger ready!
1.44 crook 11567:
1.78 anton 11568: 400D4738 8049BC4 0 -> [ 2 ] 00002 00000
11569: 400D4740 8049F68 DO -> [ 0 ]
11570: 400D4744 804A0C8 i -> [ 1 ] 00000
11571: 400D4748 400C5E60 . -> 0 [ 0 ]
11572: 400D474C 8049D0C LOOP -> [ 0 ]
11573: 400D4744 804A0C8 i -> [ 1 ] 00001
11574: 400D4748 400C5E60 . -> 1 [ 0 ]
11575: 400D474C 8049D0C LOOP -> [ 0 ]
11576: 400D4758 804B384 ; -> ok
11577: @end example
1.21 crook 11578:
1.78 anton 11579: Each line displayed is one step. You always have to hit return to
11580: execute the next word that is displayed. If you don't want to execute
11581: the next word in a whole, you have to type @kbd{n} for @code{nest}. Here is
11582: an overview what keys are available:
1.44 crook 11583:
1.78 anton 11584: @table @i
1.44 crook 11585:
1.78 anton 11586: @item @key{RET}
11587: Next; Execute the next word.
1.21 crook 11588:
1.78 anton 11589: @item n
11590: Nest; Single step through next word.
1.44 crook 11591:
1.78 anton 11592: @item u
11593: Unnest; Stop debugging and execute rest of word. If we got to this word
11594: with nest, continue debugging with the calling word.
1.44 crook 11595:
1.78 anton 11596: @item d
11597: Done; Stop debugging and execute rest.
1.21 crook 11598:
1.78 anton 11599: @item s
11600: Stop; Abort immediately.
1.44 crook 11601:
1.78 anton 11602: @end table
1.44 crook 11603:
1.78 anton 11604: Debugging large application with this mechanism is very difficult, because
11605: you have to nest very deeply into the program before the interesting part
11606: begins. This takes a lot of time.
1.26 crook 11607:
1.78 anton 11608: To do it more directly put a @code{BREAK:} command into your source code.
11609: When program execution reaches @code{BREAK:} the single step debugger is
11610: invoked and you have all the features described above.
1.44 crook 11611:
1.78 anton 11612: If you have more than one part to debug it is useful to know where the
11613: program has stopped at the moment. You can do this by the
11614: @code{BREAK" string"} command. This behaves like @code{BREAK:} except that
11615: string is typed out when the ``breakpoint'' is reached.
1.44 crook 11616:
1.26 crook 11617:
1.78 anton 11618: doc-dbg
11619: doc-break:
11620: doc-break"
1.44 crook 11621:
11622:
1.26 crook 11623:
1.78 anton 11624: @c -------------------------------------------------------------
11625: @node Assembler and Code Words, Threading Words, Programming Tools, Words
11626: @section Assembler and Code Words
11627: @cindex assembler
11628: @cindex code words
1.44 crook 11629:
1.78 anton 11630: @menu
11631: * Code and ;code::
11632: * Common Assembler:: Assembler Syntax
11633: * Common Disassembler::
11634: * 386 Assembler:: Deviations and special cases
11635: * Alpha Assembler:: Deviations and special cases
11636: * MIPS assembler:: Deviations and special cases
11637: * Other assemblers:: How to write them
11638: @end menu
1.21 crook 11639:
1.78 anton 11640: @node Code and ;code, Common Assembler, Assembler and Code Words, Assembler and Code Words
11641: @subsection @code{Code} and @code{;code}
1.26 crook 11642:
1.78 anton 11643: Gforth provides some words for defining primitives (words written in
11644: machine code), and for defining the machine-code equivalent of
11645: @code{DOES>}-based defining words. However, the machine-independent
11646: nature of Gforth poses a few problems: First of all, Gforth runs on
11647: several architectures, so it can provide no standard assembler. What's
11648: worse is that the register allocation not only depends on the processor,
11649: but also on the @code{gcc} version and options used.
1.44 crook 11650:
1.78 anton 11651: The words that Gforth offers encapsulate some system dependences (e.g.,
11652: the header structure), so a system-independent assembler may be used in
11653: Gforth. If you do not have an assembler, you can compile machine code
11654: directly with @code{,} and @code{c,}@footnote{This isn't portable,
11655: because these words emit stuff in @i{data} space; it works because
11656: Gforth has unified code/data spaces. Assembler isn't likely to be
11657: portable anyway.}.
1.21 crook 11658:
1.44 crook 11659:
1.78 anton 11660: doc-assembler
11661: doc-init-asm
11662: doc-code
11663: doc-end-code
11664: doc-;code
11665: doc-flush-icache
1.44 crook 11666:
1.21 crook 11667:
1.78 anton 11668: If @code{flush-icache} does not work correctly, @code{code} words
11669: etc. will not work (reliably), either.
1.44 crook 11670:
1.78 anton 11671: The typical usage of these @code{code} words can be shown most easily by
11672: analogy to the equivalent high-level defining words:
1.44 crook 11673:
1.78 anton 11674: @example
11675: : foo code foo
11676: <high-level Forth words> <assembler>
11677: ; end-code
11678:
11679: : bar : bar
11680: <high-level Forth words> <high-level Forth words>
11681: CREATE CREATE
11682: <high-level Forth words> <high-level Forth words>
11683: DOES> ;code
11684: <high-level Forth words> <assembler>
11685: ; end-code
11686: @end example
1.21 crook 11687:
1.78 anton 11688: @c anton: the following stuff is also in "Common Assembler", in less detail.
1.44 crook 11689:
1.78 anton 11690: @cindex registers of the inner interpreter
11691: In the assembly code you will want to refer to the inner interpreter's
11692: registers (e.g., the data stack pointer) and you may want to use other
11693: registers for temporary storage. Unfortunately, the register allocation
11694: is installation-dependent.
1.44 crook 11695:
1.78 anton 11696: In particular, @code{ip} (Forth instruction pointer) and @code{rp}
11697: (return stack pointer) are in different places in @code{gforth} and
11698: @code{gforth-fast}. This means that you cannot write a @code{NEXT}
11699: routine that works on both versions; so for doing @code{NEXT}, I
11700: recomment jumping to @code{' noop >code-address}, which contains nothing
11701: but a @code{NEXT}.
1.21 crook 11702:
1.78 anton 11703: For general accesses to the inner interpreter's registers, the easiest
11704: solution is to use explicit register declarations (@pxref{Explicit Reg
11705: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) for
11706: all of the inner interpreter's registers: You have to compile Gforth
11707: with @code{-DFORCE_REG} (configure option @code{--enable-force-reg}) and
11708: the appropriate declarations must be present in the @code{machine.h}
11709: file (see @code{mips.h} for an example; you can find a full list of all
11710: declarable register symbols with @code{grep register engine.c}). If you
11711: give explicit registers to all variables that are declared at the
11712: beginning of @code{engine()}, you should be able to use the other
11713: caller-saved registers for temporary storage. Alternatively, you can use
11714: the @code{gcc} option @code{-ffixed-REG} (@pxref{Code Gen Options, ,
11715: Options for Code Generation Conventions, gcc.info, GNU C Manual}) to
11716: reserve a register (however, this restriction on register allocation may
11717: slow Gforth significantly).
1.44 crook 11718:
1.78 anton 11719: If this solution is not viable (e.g., because @code{gcc} does not allow
11720: you to explicitly declare all the registers you need), you have to find
11721: out by looking at the code where the inner interpreter's registers
11722: reside and which registers can be used for temporary storage. You can
11723: get an assembly listing of the engine's code with @code{make engine.s}.
1.44 crook 11724:
1.78 anton 11725: In any case, it is good practice to abstract your assembly code from the
11726: actual register allocation. E.g., if the data stack pointer resides in
11727: register @code{$17}, create an alias for this register called @code{sp},
11728: and use that in your assembly code.
1.21 crook 11729:
1.78 anton 11730: @cindex code words, portable
11731: Another option for implementing normal and defining words efficiently
11732: is to add the desired functionality to the source of Gforth. For normal
11733: words you just have to edit @file{primitives} (@pxref{Automatic
11734: Generation}). Defining words (equivalent to @code{;CODE} words, for fast
11735: defined words) may require changes in @file{engine.c}, @file{kernel.fs},
11736: @file{prims2x.fs}, and possibly @file{cross.fs}.
1.44 crook 11737:
1.78 anton 11738: @node Common Assembler, Common Disassembler, Code and ;code, Assembler and Code Words
11739: @subsection Common Assembler
1.44 crook 11740:
1.78 anton 11741: The assemblers in Gforth generally use a postfix syntax, i.e., the
11742: instruction name follows the operands.
1.21 crook 11743:
1.78 anton 11744: The operands are passed in the usual order (the same that is used in the
11745: manual of the architecture). Since they all are Forth words, they have
11746: to be separated by spaces; you can also use Forth words to compute the
11747: operands.
1.44 crook 11748:
1.78 anton 11749: The instruction names usually end with a @code{,}. This makes it easier
11750: to visually separate instructions if you put several of them on one
11751: line; it also avoids shadowing other Forth words (e.g., @code{and}).
1.21 crook 11752:
1.78 anton 11753: Registers are usually specified by number; e.g., (decimal) @code{11}
11754: specifies registers R11 and F11 on the Alpha architecture (which one,
11755: depends on the instruction). The usual names are also available, e.g.,
11756: @code{s2} for R11 on Alpha.
1.21 crook 11757:
1.78 anton 11758: Control flow is specified similar to normal Forth code (@pxref{Arbitrary
11759: control structures}), with @code{if,}, @code{ahead,}, @code{then,},
11760: @code{begin,}, @code{until,}, @code{again,}, @code{cs-roll},
11761: @code{cs-pick}, @code{else,}, @code{while,}, and @code{repeat,}. The
11762: conditions are specified in a way specific to each assembler.
1.1 anton 11763:
1.78 anton 11764: Note that the register assignments of the Gforth engine can change
11765: between Gforth versions, or even between different compilations of the
11766: same Gforth version (e.g., if you use a different GCC version). So if
11767: you want to refer to Gforth's registers (e.g., the stack pointer or
11768: TOS), I recommend defining your own words for refering to these
11769: registers, and using them later on; then you can easily adapt to a
11770: changed register assignment. The stability of the register assignment
11771: is usually better if you build Gforth with @code{--enable-force-reg}.
1.1 anton 11772:
1.78 anton 11773: In particular, the return stack pointer and the instruction pointer are
11774: in memory in @code{gforth}, and usually in registers in
11775: @code{gforth-fast}. The most common use of these registers is to
11776: dispatch to the next word (the @code{next} routine). A portable way to
11777: do this is to jump to @code{' noop >code-address} (of course, this is
11778: less efficient than integrating the @code{next} code and scheduling it
11779: well).
1.1 anton 11780:
1.78 anton 11781: @node Common Disassembler, 386 Assembler, Common Assembler, Assembler and Code Words
11782: @subsection Common Disassembler
1.1 anton 11783:
1.78 anton 11784: You can disassemble a @code{code} word with @code{see}
11785: (@pxref{Debugging}). You can disassemble a section of memory with
1.1 anton 11786:
1.78 anton 11787: doc-disasm
1.44 crook 11788:
1.78 anton 11789: The disassembler generally produces output that can be fed into the
11790: assembler (i.e., same syntax, etc.). It also includes additional
11791: information in comments. In particular, the address of the instruction
11792: is given in a comment before the instruction.
1.1 anton 11793:
1.78 anton 11794: @code{See} may display more or less than the actual code of the word,
11795: because the recognition of the end of the code is unreliable. You can
11796: use @code{disasm} if it did not display enough. It may display more, if
11797: the code word is not immediately followed by a named word. If you have
11798: something else there, you can follow the word with @code{align last @ ,}
11799: to ensure that the end is recognized.
1.21 crook 11800:
1.78 anton 11801: @node 386 Assembler, Alpha Assembler, Common Disassembler, Assembler and Code Words
11802: @subsection 386 Assembler
1.44 crook 11803:
1.78 anton 11804: The 386 assembler included in Gforth was written by Bernd Paysan, it's
11805: available under GPL, and originally part of bigFORTH.
1.21 crook 11806:
1.78 anton 11807: The 386 disassembler included in Gforth was written by Andrew McKewan
11808: and is in the public domain.
1.21 crook 11809:
1.78 anton 11810: The disassembler displays code in prefix Intel syntax.
1.21 crook 11811:
1.78 anton 11812: The assembler uses a postfix syntax with reversed parameters.
1.1 anton 11813:
1.78 anton 11814: The assembler includes all instruction of the Athlon, i.e. 486 core
11815: instructions, Pentium and PPro extensions, floating point, MMX, 3Dnow!,
11816: but not ISSE. It's an integrated 16- and 32-bit assembler. Default is 32
11817: bit, you can switch to 16 bit with .86 and back to 32 bit with .386.
1.1 anton 11818:
1.78 anton 11819: There are several prefixes to switch between different operation sizes,
11820: @code{.b} for byte accesses, @code{.w} for word accesses, @code{.d} for
11821: double-word accesses. Addressing modes can be switched with @code{.wa}
11822: for 16 bit addresses, and @code{.da} for 32 bit addresses. You don't
11823: need a prefix for byte register names (@code{AL} et al).
1.1 anton 11824:
1.78 anton 11825: For floating point operations, the prefixes are @code{.fs} (IEEE
11826: single), @code{.fl} (IEEE double), @code{.fx} (extended), @code{.fw}
11827: (word), @code{.fd} (double-word), and @code{.fq} (quad-word).
1.21 crook 11828:
1.78 anton 11829: The MMX opcodes don't have size prefixes, they are spelled out like in
11830: the Intel assembler. Instead of move from and to memory, there are
11831: PLDQ/PLDD and PSTQ/PSTD.
1.21 crook 11832:
1.78 anton 11833: The registers lack the 'e' prefix; even in 32 bit mode, eax is called
11834: ax. Immediate values are indicated by postfixing them with @code{#},
11835: e.g., @code{3 #}. Here are some examples of addressing modes:
1.21 crook 11836:
1.26 crook 11837: @example
1.78 anton 11838: 3 # \ immediate
1.85 ! anton 11839: 1000 #) \ absolute
1.78 anton 11840: ax \ register
11841: 100 di d) \ 100[edi]
11842: 4 bx cx di) \ 4[ebx][ecx]
11843: di ax *4 i) \ [edi][eax*4]
11844: 20 ax *4 i#) \ 20[eax*4]
1.26 crook 11845: @end example
1.21 crook 11846:
1.78 anton 11847: Some example of instructions are:
1.1 anton 11848:
11849: @example
1.78 anton 11850: ax bx mov \ move ebx,eax
11851: 3 # ax mov \ mov eax,3
11852: 100 di ) ax mov \ mov eax,100[edi]
11853: 4 bx cx di) ax mov \ mov eax,4[ebx][ecx]
11854: .w ax bx mov \ mov bx,ax
1.1 anton 11855: @end example
11856:
1.78 anton 11857: The following forms are supported for binary instructions:
1.1 anton 11858:
11859: @example
1.78 anton 11860: <reg> <reg> <inst>
11861: <n> # <reg> <inst>
11862: <mem> <reg> <inst>
11863: <reg> <mem> <inst>
1.1 anton 11864: @end example
11865:
1.78 anton 11866: Immediate to memory is not supported. The shift/rotate syntax is:
1.1 anton 11867:
1.26 crook 11868: @example
1.78 anton 11869: <reg/mem> 1 # shl \ shortens to shift without immediate
11870: <reg/mem> 4 # shl
11871: <reg/mem> cl shl
1.26 crook 11872: @end example
1.1 anton 11873:
1.78 anton 11874: Precede string instructions (@code{movs} etc.) with @code{.b} to get
11875: the byte version.
1.1 anton 11876:
1.78 anton 11877: The control structure words @code{IF} @code{UNTIL} etc. must be preceded
11878: by one of these conditions: @code{vs vc u< u>= 0= 0<> u<= u> 0< 0>= ps
11879: pc < >= <= >}. (Note that most of these words shadow some Forth words
11880: when @code{assembler} is in front of @code{forth} in the search path,
11881: e.g., in @code{code} words). Currently the control structure words use
11882: one stack item, so you have to use @code{roll} instead of @code{cs-roll}
11883: to shuffle them (you can also use @code{swap} etc.).
1.21 crook 11884:
1.78 anton 11885: Here is an example of a @code{code} word (assumes that the stack pointer
11886: is in esi and the TOS is in ebx):
1.21 crook 11887:
1.26 crook 11888: @example
1.78 anton 11889: code my+ ( n1 n2 -- n )
11890: 4 si D) bx add
11891: 4 # si add
11892: Next
11893: end-code
1.26 crook 11894: @end example
1.21 crook 11895:
1.78 anton 11896: @node Alpha Assembler, MIPS assembler, 386 Assembler, Assembler and Code Words
11897: @subsection Alpha Assembler
1.21 crook 11898:
1.78 anton 11899: The Alpha assembler and disassembler were originally written by Bernd
11900: Thallner.
1.26 crook 11901:
1.78 anton 11902: The register names @code{a0}--@code{a5} are not available to avoid
11903: shadowing hex numbers.
1.2 jwilke 11904:
1.78 anton 11905: Immediate forms of arithmetic instructions are distinguished by a
11906: @code{#} just before the @code{,}, e.g., @code{and#,} (note: @code{lda,}
11907: does not count as arithmetic instruction).
1.2 jwilke 11908:
1.78 anton 11909: You have to specify all operands to an instruction, even those that
11910: other assemblers consider optional, e.g., the destination register for
11911: @code{br,}, or the destination register and hint for @code{jmp,}.
1.2 jwilke 11912:
1.78 anton 11913: You can specify conditions for @code{if,} by removing the first @code{b}
11914: and the trailing @code{,} from a branch with a corresponding name; e.g.,
1.2 jwilke 11915:
1.26 crook 11916: @example
1.78 anton 11917: 11 fgt if, \ if F11>0e
11918: ...
11919: endif,
1.26 crook 11920: @end example
1.2 jwilke 11921:
1.78 anton 11922: @code{fbgt,} gives @code{fgt}.
11923:
11924: @node MIPS assembler, Other assemblers, Alpha Assembler, Assembler and Code Words
11925: @subsection MIPS assembler
1.2 jwilke 11926:
1.78 anton 11927: The MIPS assembler was originally written by Christian Pirker.
1.2 jwilke 11928:
1.78 anton 11929: Currently the assembler and disassembler only cover the MIPS-I
11930: architecture (R3000), and don't support FP instructions.
1.2 jwilke 11931:
1.78 anton 11932: The register names @code{$a0}--@code{$a3} are not available to avoid
11933: shadowing hex numbers.
1.2 jwilke 11934:
1.78 anton 11935: Because there is no way to distinguish registers from immediate values,
11936: you have to explicitly use the immediate forms of instructions, i.e.,
11937: @code{addiu,}, not just @code{addu,} (@command{as} does this
11938: implicitly).
1.2 jwilke 11939:
1.78 anton 11940: If the architecture manual specifies several formats for the instruction
11941: (e.g., for @code{jalr,}), you usually have to use the one with more
11942: arguments (i.e., two for @code{jalr,}). When in doubt, see
11943: @code{arch/mips/testasm.fs} for an example of correct use.
1.2 jwilke 11944:
1.78 anton 11945: Branches and jumps in the MIPS architecture have a delay slot. You have
11946: to fill it yourself (the simplest way is to use @code{nop,}), the
11947: assembler does not do it for you (unlike @command{as}). Even
11948: @code{if,}, @code{ahead,}, @code{until,}, @code{again,}, @code{while,},
11949: @code{else,} and @code{repeat,} need a delay slot. Since @code{begin,}
11950: and @code{then,} just specify branch targets, they are not affected.
1.2 jwilke 11951:
1.78 anton 11952: Note that you must not put branches, jumps, or @code{li,} into the delay
11953: slot: @code{li,} may expand to several instructions, and control flow
11954: instructions may not be put into the branch delay slot in any case.
1.2 jwilke 11955:
1.78 anton 11956: For branches the argument specifying the target is a relative address;
11957: You have to add the address of the delay slot to get the absolute
11958: address.
1.1 anton 11959:
1.78 anton 11960: The MIPS architecture also has load delay slots and restrictions on
11961: using @code{mfhi,} and @code{mflo,}; you have to order the instructions
11962: yourself to satisfy these restrictions, the assembler does not do it for
11963: you.
1.1 anton 11964:
1.78 anton 11965: You can specify the conditions for @code{if,} etc. by taking a
11966: conditional branch and leaving away the @code{b} at the start and the
11967: @code{,} at the end. E.g.,
1.1 anton 11968:
1.26 crook 11969: @example
1.78 anton 11970: 4 5 eq if,
11971: ... \ do something if $4 equals $5
11972: then,
1.26 crook 11973: @end example
1.1 anton 11974:
1.78 anton 11975: @node Other assemblers, , MIPS assembler, Assembler and Code Words
11976: @subsection Other assemblers
11977:
11978: If you want to contribute another assembler/disassembler, please contact
11979: us (@email{bug-gforth@@gnu.org}) to check if we have such an assembler
11980: already. If you are writing them from scratch, please use a similar
11981: syntax style as the one we use (i.e., postfix, commas at the end of the
11982: instruction names, @pxref{Common Assembler}); make the output of the
11983: disassembler be valid input for the assembler, and keep the style
11984: similar to the style we used.
11985:
11986: Hints on implementation: The most important part is to have a good test
11987: suite that contains all instructions. Once you have that, the rest is
11988: easy. For actual coding you can take a look at
11989: @file{arch/mips/disasm.fs} to get some ideas on how to use data for both
11990: the assembler and disassembler, avoiding redundancy and some potential
11991: bugs. You can also look at that file (and @pxref{Advanced does> usage
11992: example}) to get ideas how to factor a disassembler.
11993:
11994: Start with the disassembler, because it's easier to reuse data from the
11995: disassembler for the assembler than the other way round.
1.1 anton 11996:
1.78 anton 11997: For the assembler, take a look at @file{arch/alpha/asm.fs}, which shows
11998: how simple it can be.
1.1 anton 11999:
1.78 anton 12000: @c -------------------------------------------------------------
12001: @node Threading Words, Passing Commands to the OS, Assembler and Code Words, Words
12002: @section Threading Words
12003: @cindex threading words
1.1 anton 12004:
1.78 anton 12005: @cindex code address
12006: These words provide access to code addresses and other threading stuff
12007: in Gforth (and, possibly, other interpretive Forths). It more or less
12008: abstracts away the differences between direct and indirect threading
12009: (and, for direct threading, the machine dependences). However, at
12010: present this wordset is still incomplete. It is also pretty low-level;
12011: some day it will hopefully be made unnecessary by an internals wordset
12012: that abstracts implementation details away completely.
1.1 anton 12013:
1.78 anton 12014: The terminology used here stems from indirect threaded Forth systems; in
12015: such a system, the XT of a word is represented by the CFA (code field
12016: address) of a word; the CFA points to a cell that contains the code
12017: address. The code address is the address of some machine code that
12018: performs the run-time action of invoking the word (e.g., the
12019: @code{dovar:} routine pushes the address of the body of the word (a
12020: variable) on the stack
12021: ).
1.1 anton 12022:
1.78 anton 12023: @cindex code address
12024: @cindex code field address
12025: In an indirect threaded Forth, you can get the code address of @i{name}
12026: with @code{' @i{name} @@}; in Gforth you can get it with @code{' @i{name}
12027: >code-address}, independent of the threading method.
1.1 anton 12028:
1.78 anton 12029: doc-threading-method
12030: doc->code-address
12031: doc-code-address!
1.1 anton 12032:
1.78 anton 12033: @cindex @code{does>}-handler
12034: @cindex @code{does>}-code
12035: For a word defined with @code{DOES>}, the code address usually points to
12036: a jump instruction (the @dfn{does-handler}) that jumps to the dodoes
12037: routine (in Gforth on some platforms, it can also point to the dodoes
12038: routine itself). What you are typically interested in, though, is
12039: whether a word is a @code{DOES>}-defined word, and what Forth code it
12040: executes; @code{>does-code} tells you that.
1.1 anton 12041:
1.78 anton 12042: doc->does-code
1.1 anton 12043:
1.78 anton 12044: To create a @code{DOES>}-defined word with the following basic words,
12045: you have to set up a @code{DOES>}-handler with @code{does-handler!};
12046: @code{/does-handler} aus behind you have to place your executable Forth
12047: code. Finally you have to create a word and modify its behaviour with
12048: @code{does-handler!}.
1.1 anton 12049:
1.78 anton 12050: doc-does-code!
12051: doc-does-handler!
12052: doc-/does-handler
1.1 anton 12053:
1.78 anton 12054: The code addresses produced by various defining words are produced by
12055: the following words:
1.1 anton 12056:
1.78 anton 12057: doc-docol:
12058: doc-docon:
12059: doc-dovar:
12060: doc-douser:
12061: doc-dodefer:
12062: doc-dofield:
1.1 anton 12063:
1.26 crook 12064: @c -------------------------------------------------------------
1.78 anton 12065: @node Passing Commands to the OS, Keeping track of Time, Threading Words, Words
1.21 crook 12066: @section Passing Commands to the Operating System
12067: @cindex operating system - passing commands
12068: @cindex shell commands
12069:
12070: Gforth allows you to pass an arbitrary string to the host operating
12071: system shell (if such a thing exists) for execution.
12072:
1.44 crook 12073:
1.21 crook 12074: doc-sh
12075: doc-system
12076: doc-$?
1.23 crook 12077: doc-getenv
1.21 crook 12078:
1.44 crook 12079:
1.26 crook 12080: @c -------------------------------------------------------------
1.47 crook 12081: @node Keeping track of Time, Miscellaneous Words, Passing Commands to the OS, Words
12082: @section Keeping track of Time
12083: @cindex time-related words
12084:
12085: doc-ms
12086: doc-time&date
1.79 anton 12087: doc-utime
12088: doc-cputime
1.47 crook 12089:
12090:
12091: @c -------------------------------------------------------------
12092: @node Miscellaneous Words, , Keeping track of Time, Words
1.21 crook 12093: @section Miscellaneous Words
12094: @cindex miscellaneous words
12095:
1.29 crook 12096: @comment TODO find homes for these
12097:
1.26 crook 12098: These section lists the ANS Forth words that are not documented
1.21 crook 12099: elsewhere in this manual. Ultimately, they all need proper homes.
12100:
1.68 anton 12101: doc-quit
1.44 crook 12102:
1.26 crook 12103: The following ANS Forth words are not currently supported by Gforth
1.27 crook 12104: (@pxref{ANS conformance}):
1.21 crook 12105:
12106: @code{EDITOR}
12107: @code{EMIT?}
12108: @code{FORGET}
12109:
1.24 anton 12110: @c ******************************************************************
12111: @node Error messages, Tools, Words, Top
12112: @chapter Error messages
12113: @cindex error messages
12114: @cindex backtrace
12115:
12116: A typical Gforth error message looks like this:
12117:
12118: @example
12119: in file included from :-1
12120: in file included from ./yyy.fs:1
12121: ./xxx.fs:4: Invalid memory address
12122: bar
12123: ^^^
1.79 anton 12124: Backtrace:
1.25 anton 12125: $400E664C @@
12126: $400E6664 foo
1.24 anton 12127: @end example
12128:
12129: The message identifying the error is @code{Invalid memory address}. The
12130: error happened when text-interpreting line 4 of the file
12131: @file{./xxx.fs}. This line is given (it contains @code{bar}), and the
12132: word on the line where the error happened, is pointed out (with
12133: @code{^^^}).
12134:
12135: The file containing the error was included in line 1 of @file{./yyy.fs},
12136: and @file{yyy.fs} was included from a non-file (in this case, by giving
12137: @file{yyy.fs} as command-line parameter to Gforth).
12138:
12139: At the end of the error message you find a return stack dump that can be
12140: interpreted as a backtrace (possibly empty). On top you find the top of
12141: the return stack when the @code{throw} happened, and at the bottom you
12142: find the return stack entry just above the return stack of the topmost
12143: text interpreter.
12144:
12145: To the right of most return stack entries you see a guess for the word
12146: that pushed that return stack entry as its return address. This gives a
12147: backtrace. In our case we see that @code{bar} called @code{foo}, and
12148: @code{foo} called @code{@@} (and @code{@@} had an @emph{Invalid memory
12149: address} exception).
12150:
12151: Note that the backtrace is not perfect: We don't know which return stack
12152: entries are return addresses (so we may get false positives); and in
12153: some cases (e.g., for @code{abort"}) we cannot determine from the return
12154: address the word that pushed the return address, so for some return
12155: addresses you see no names in the return stack dump.
1.25 anton 12156:
12157: @cindex @code{catch} and backtraces
12158: The return stack dump represents the return stack at the time when a
12159: specific @code{throw} was executed. In programs that make use of
12160: @code{catch}, it is not necessarily clear which @code{throw} should be
12161: used for the return stack dump (e.g., consider one @code{throw} that
12162: indicates an error, which is caught, and during recovery another error
1.42 anton 12163: happens; which @code{throw} should be used for the stack dump?). Gforth
1.25 anton 12164: presents the return stack dump for the first @code{throw} after the last
12165: executed (not returned-to) @code{catch}; this works well in the usual
12166: case.
12167:
12168: @cindex @code{gforth-fast} and backtraces
12169: @cindex @code{gforth-fast}, difference from @code{gforth}
12170: @cindex backtraces with @code{gforth-fast}
12171: @cindex return stack dump with @code{gforth-fast}
1.79 anton 12172: @code{Gforth} is able to do a return stack dump for throws generated
1.25 anton 12173: from primitives (e.g., invalid memory address, stack empty etc.);
12174: @code{gforth-fast} is only able to do a return stack dump from a
12175: directly called @code{throw} (including @code{abort} etc.). This is the
1.30 anton 12176: only difference (apart from a speed factor of between 1.15 (K6-2) and
1.78 anton 12177: 2 (21264)) between @code{gforth} and @code{gforth-fast}. Given an
1.30 anton 12178: exception caused by a primitive in @code{gforth-fast}, you will
12179: typically see no return stack dump at all; however, if the exception is
12180: caught by @code{catch} (e.g., for restoring some state), and then
12181: @code{throw}n again, the return stack dump will be for the first such
12182: @code{throw}.
1.2 jwilke 12183:
1.5 anton 12184: @c ******************************************************************
1.24 anton 12185: @node Tools, ANS conformance, Error messages, Top
1.1 anton 12186: @chapter Tools
12187:
12188: @menu
12189: * ANS Report:: Report the words used, sorted by wordset.
12190: @end menu
12191:
12192: See also @ref{Emacs and Gforth}.
12193:
12194: @node ANS Report, , Tools, Tools
12195: @section @file{ans-report.fs}: Report the words used, sorted by wordset
12196: @cindex @file{ans-report.fs}
12197: @cindex report the words used in your program
12198: @cindex words used in your program
12199:
12200: If you want to label a Forth program as ANS Forth Program, you must
12201: document which wordsets the program uses; for extension wordsets, it is
12202: helpful to list the words the program requires from these wordsets
12203: (because Forth systems are allowed to provide only some words of them).
12204:
12205: The @file{ans-report.fs} tool makes it easy for you to determine which
12206: words from which wordset and which non-ANS words your application
12207: uses. You simply have to include @file{ans-report.fs} before loading the
12208: program you want to check. After loading your program, you can get the
12209: report with @code{print-ans-report}. A typical use is to run this as
12210: batch job like this:
12211: @example
12212: gforth ans-report.fs myprog.fs -e "print-ans-report bye"
12213: @end example
12214:
12215: The output looks like this (for @file{compat/control.fs}):
12216: @example
12217: The program uses the following words
12218: from CORE :
12219: : POSTPONE THEN ; immediate ?dup IF 0=
12220: from BLOCK-EXT :
12221: \
12222: from FILE :
12223: (
12224: @end example
12225:
12226: @subsection Caveats
12227:
12228: Note that @file{ans-report.fs} just checks which words are used, not whether
12229: they are used in an ANS Forth conforming way!
12230:
12231: Some words are defined in several wordsets in the
12232: standard. @file{ans-report.fs} reports them for only one of the
12233: wordsets, and not necessarily the one you expect. It depends on usage
12234: which wordset is the right one to specify. E.g., if you only use the
12235: compilation semantics of @code{S"}, it is a Core word; if you also use
12236: its interpretation semantics, it is a File word.
12237:
12238: @c ******************************************************************
1.65 anton 12239: @node ANS conformance, Standard vs Extensions, Tools, Top
1.1 anton 12240: @chapter ANS conformance
12241: @cindex ANS conformance of Gforth
12242:
12243: To the best of our knowledge, Gforth is an
12244:
12245: ANS Forth System
12246: @itemize @bullet
12247: @item providing the Core Extensions word set
12248: @item providing the Block word set
12249: @item providing the Block Extensions word set
12250: @item providing the Double-Number word set
12251: @item providing the Double-Number Extensions word set
12252: @item providing the Exception word set
12253: @item providing the Exception Extensions word set
12254: @item providing the Facility word set
1.40 anton 12255: @item providing @code{EKEY}, @code{EKEY>CHAR}, @code{EKEY?}, @code{MS} and @code{TIME&DATE} from the Facility Extensions word set
1.1 anton 12256: @item providing the File Access word set
12257: @item providing the File Access Extensions word set
12258: @item providing the Floating-Point word set
12259: @item providing the Floating-Point Extensions word set
12260: @item providing the Locals word set
12261: @item providing the Locals Extensions word set
12262: @item providing the Memory-Allocation word set
12263: @item providing the Memory-Allocation Extensions word set (that one's easy)
12264: @item providing the Programming-Tools word set
12265: @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
12266: @item providing the Search-Order word set
12267: @item providing the Search-Order Extensions word set
12268: @item providing the String word set
12269: @item providing the String Extensions word set (another easy one)
12270: @end itemize
12271:
12272: @cindex system documentation
12273: In addition, ANS Forth systems are required to document certain
12274: implementation choices. This chapter tries to meet these
12275: requirements. In many cases it gives a way to ask the system for the
12276: information instead of providing the information directly, in
12277: particular, if the information depends on the processor, the operating
12278: system or the installation options chosen, or if they are likely to
12279: change during the maintenance of Gforth.
12280:
12281: @comment The framework for the rest has been taken from pfe.
12282:
12283: @menu
12284: * The Core Words::
12285: * The optional Block word set::
12286: * The optional Double Number word set::
12287: * The optional Exception word set::
12288: * The optional Facility word set::
12289: * The optional File-Access word set::
12290: * The optional Floating-Point word set::
12291: * The optional Locals word set::
12292: * The optional Memory-Allocation word set::
12293: * The optional Programming-Tools word set::
12294: * The optional Search-Order word set::
12295: @end menu
12296:
12297:
12298: @c =====================================================================
12299: @node The Core Words, The optional Block word set, ANS conformance, ANS conformance
12300: @comment node-name, next, previous, up
12301: @section The Core Words
12302: @c =====================================================================
12303: @cindex core words, system documentation
12304: @cindex system documentation, core words
12305:
12306: @menu
12307: * core-idef:: Implementation Defined Options
12308: * core-ambcond:: Ambiguous Conditions
12309: * core-other:: Other System Documentation
12310: @end menu
12311:
12312: @c ---------------------------------------------------------------------
12313: @node core-idef, core-ambcond, The Core Words, The Core Words
12314: @subsection Implementation Defined Options
12315: @c ---------------------------------------------------------------------
12316: @cindex core words, implementation-defined options
12317: @cindex implementation-defined options, core words
12318:
12319:
12320: @table @i
12321: @item (Cell) aligned addresses:
12322: @cindex cell-aligned addresses
12323: @cindex aligned addresses
12324: processor-dependent. Gforth's alignment words perform natural alignment
12325: (e.g., an address aligned for a datum of size 8 is divisible by
12326: 8). Unaligned accesses usually result in a @code{-23 THROW}.
12327:
12328: @item @code{EMIT} and non-graphic characters:
12329: @cindex @code{EMIT} and non-graphic characters
12330: @cindex non-graphic characters and @code{EMIT}
12331: The character is output using the C library function (actually, macro)
12332: @code{putc}.
12333:
12334: @item character editing of @code{ACCEPT} and @code{EXPECT}:
12335: @cindex character editing of @code{ACCEPT} and @code{EXPECT}
12336: @cindex editing in @code{ACCEPT} and @code{EXPECT}
12337: @cindex @code{ACCEPT}, editing
12338: @cindex @code{EXPECT}, editing
12339: This is modeled on the GNU readline library (@pxref{Readline
12340: Interaction, , Command Line Editing, readline, The GNU Readline
12341: Library}) with Emacs-like key bindings. @kbd{Tab} deviates a little by
12342: producing a full word completion every time you type it (instead of
1.28 crook 12343: producing the common prefix of all completions). @xref{Command-line editing}.
1.1 anton 12344:
12345: @item character set:
12346: @cindex character set
12347: The character set of your computer and display device. Gforth is
12348: 8-bit-clean (but some other component in your system may make trouble).
12349:
12350: @item Character-aligned address requirements:
12351: @cindex character-aligned address requirements
12352: installation-dependent. Currently a character is represented by a C
12353: @code{unsigned char}; in the future we might switch to @code{wchar_t}
12354: (Comments on that requested).
12355:
12356: @item character-set extensions and matching of names:
12357: @cindex character-set extensions and matching of names
1.26 crook 12358: @cindex case-sensitivity for name lookup
12359: @cindex name lookup, case-sensitivity
12360: @cindex locale and case-sensitivity
1.21 crook 12361: Any character except the ASCII NUL character can be used in a
1.1 anton 12362: name. Matching is case-insensitive (except in @code{TABLE}s). The
1.47 crook 12363: matching is performed using the C library function @code{strncasecmp}, whose
1.1 anton 12364: function is probably influenced by the locale. E.g., the @code{C} locale
12365: does not know about accents and umlauts, so they are matched
12366: case-sensitively in that locale. For portability reasons it is best to
12367: write programs such that they work in the @code{C} locale. Then one can
12368: use libraries written by a Polish programmer (who might use words
12369: containing ISO Latin-2 encoded characters) and by a French programmer
12370: (ISO Latin-1) in the same program (of course, @code{WORDS} will produce
12371: funny results for some of the words (which ones, depends on the font you
12372: are using)). Also, the locale you prefer may not be available in other
12373: operating systems. Hopefully, Unicode will solve these problems one day.
12374:
12375: @item conditions under which control characters match a space delimiter:
12376: @cindex space delimiters
12377: @cindex control characters as delimiters
12378: If @code{WORD} is called with the space character as a delimiter, all
12379: white-space characters (as identified by the C macro @code{isspace()})
12380: are delimiters. @code{PARSE}, on the other hand, treats space like other
1.44 crook 12381: delimiters. @code{SWORD} treats space like @code{WORD}, but behaves
1.79 anton 12382: like @code{PARSE} otherwise. @code{Name}, which is used by the outer
1.1 anton 12383: interpreter (aka text interpreter) by default, treats all white-space
12384: characters as delimiters.
12385:
1.26 crook 12386: @item format of the control-flow stack:
12387: @cindex control-flow stack, format
12388: The data stack is used as control-flow stack. The size of a control-flow
1.1 anton 12389: stack item in cells is given by the constant @code{cs-item-size}. At the
12390: time of this writing, an item consists of a (pointer to a) locals list
12391: (third), an address in the code (second), and a tag for identifying the
12392: item (TOS). The following tags are used: @code{defstart},
12393: @code{live-orig}, @code{dead-orig}, @code{dest}, @code{do-dest},
12394: @code{scopestart}.
12395:
12396: @item conversion of digits > 35
12397: @cindex digits > 35
12398: The characters @code{[\]^_'} are the digits with the decimal value
12399: 36@minus{}41. There is no way to input many of the larger digits.
12400:
12401: @item display after input terminates in @code{ACCEPT} and @code{EXPECT}:
12402: @cindex @code{EXPECT}, display after end of input
12403: @cindex @code{ACCEPT}, display after end of input
12404: The cursor is moved to the end of the entered string. If the input is
12405: terminated using the @kbd{Return} key, a space is typed.
12406:
12407: @item exception abort sequence of @code{ABORT"}:
12408: @cindex exception abort sequence of @code{ABORT"}
12409: @cindex @code{ABORT"}, exception abort sequence
12410: The error string is stored into the variable @code{"error} and a
12411: @code{-2 throw} is performed.
12412:
12413: @item input line terminator:
12414: @cindex input line terminator
12415: @cindex line terminator on input
1.26 crook 12416: @cindex newline character on input
1.1 anton 12417: For interactive input, @kbd{C-m} (CR) and @kbd{C-j} (LF) terminate
12418: lines. One of these characters is typically produced when you type the
12419: @kbd{Enter} or @kbd{Return} key.
12420:
12421: @item maximum size of a counted string:
12422: @cindex maximum size of a counted string
12423: @cindex counted string, maximum size
12424: @code{s" /counted-string" environment? drop .}. Currently 255 characters
1.79 anton 12425: on all platforms, but this may change.
1.1 anton 12426:
12427: @item maximum size of a parsed string:
12428: @cindex maximum size of a parsed string
12429: @cindex parsed string, maximum size
12430: Given by the constant @code{/line}. Currently 255 characters.
12431:
12432: @item maximum size of a definition name, in characters:
12433: @cindex maximum size of a definition name, in characters
12434: @cindex name, maximum length
12435: 31
12436:
12437: @item maximum string length for @code{ENVIRONMENT?}, in characters:
12438: @cindex maximum string length for @code{ENVIRONMENT?}, in characters
12439: @cindex @code{ENVIRONMENT?} string length, maximum
12440: 31
12441:
12442: @item method of selecting the user input device:
12443: @cindex user input device, method of selecting
12444: The user input device is the standard input. There is currently no way to
12445: change it from within Gforth. However, the input can typically be
12446: redirected in the command line that starts Gforth.
12447:
12448: @item method of selecting the user output device:
12449: @cindex user output device, method of selecting
12450: @code{EMIT} and @code{TYPE} output to the file-id stored in the value
1.10 anton 12451: @code{outfile-id} (@code{stdout} by default). Gforth uses unbuffered
12452: output when the user output device is a terminal, otherwise the output
12453: is buffered.
1.1 anton 12454:
12455: @item methods of dictionary compilation:
12456: What are we expected to document here?
12457:
12458: @item number of bits in one address unit:
12459: @cindex number of bits in one address unit
12460: @cindex address unit, size in bits
12461: @code{s" address-units-bits" environment? drop .}. 8 in all current
1.79 anton 12462: platforms.
1.1 anton 12463:
12464: @item number representation and arithmetic:
12465: @cindex number representation and arithmetic
1.79 anton 12466: Processor-dependent. Binary two's complement on all current platforms.
1.1 anton 12467:
12468: @item ranges for integer types:
12469: @cindex ranges for integer types
12470: @cindex integer types, ranges
12471: Installation-dependent. Make environmental queries for @code{MAX-N},
12472: @code{MAX-U}, @code{MAX-D} and @code{MAX-UD}. The lower bounds for
12473: unsigned (and positive) types is 0. The lower bound for signed types on
12474: two's complement and one's complement machines machines can be computed
12475: by adding 1 to the upper bound.
12476:
12477: @item read-only data space regions:
12478: @cindex read-only data space regions
12479: @cindex data-space, read-only regions
12480: The whole Forth data space is writable.
12481:
12482: @item size of buffer at @code{WORD}:
12483: @cindex size of buffer at @code{WORD}
12484: @cindex @code{WORD} buffer size
12485: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
12486: shared with the pictured numeric output string. If overwriting
12487: @code{PAD} is acceptable, it is as large as the remaining dictionary
12488: space, although only as much can be sensibly used as fits in a counted
12489: string.
12490:
12491: @item size of one cell in address units:
12492: @cindex cell size
12493: @code{1 cells .}.
12494:
12495: @item size of one character in address units:
12496: @cindex char size
1.79 anton 12497: @code{1 chars .}. 1 on all current platforms.
1.1 anton 12498:
12499: @item size of the keyboard terminal buffer:
12500: @cindex size of the keyboard terminal buffer
12501: @cindex terminal buffer, size
12502: Varies. You can determine the size at a specific time using @code{lp@@
12503: tib - .}. It is shared with the locals stack and TIBs of files that
12504: include the current file. You can change the amount of space for TIBs
12505: and locals stack at Gforth startup with the command line option
12506: @code{-l}.
12507:
12508: @item size of the pictured numeric output buffer:
12509: @cindex size of the pictured numeric output buffer
12510: @cindex pictured numeric output buffer, size
12511: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
12512: shared with @code{WORD}.
12513:
12514: @item size of the scratch area returned by @code{PAD}:
12515: @cindex size of the scratch area returned by @code{PAD}
12516: @cindex @code{PAD} size
12517: The remainder of dictionary space. @code{unused pad here - - .}.
12518:
12519: @item system case-sensitivity characteristics:
12520: @cindex case-sensitivity characteristics
1.26 crook 12521: Dictionary searches are case-insensitive (except in
1.1 anton 12522: @code{TABLE}s). However, as explained above under @i{character-set
12523: extensions}, the matching for non-ASCII characters is determined by the
12524: locale you are using. In the default @code{C} locale all non-ASCII
12525: characters are matched case-sensitively.
12526:
12527: @item system prompt:
12528: @cindex system prompt
12529: @cindex prompt
12530: @code{ ok} in interpret state, @code{ compiled} in compile state.
12531:
12532: @item division rounding:
12533: @cindex division rounding
12534: installation dependent. @code{s" floored" environment? drop .}. We leave
12535: the choice to @code{gcc} (what to use for @code{/}) and to you (whether
12536: to use @code{fm/mod}, @code{sm/rem} or simply @code{/}).
12537:
12538: @item values of @code{STATE} when true:
12539: @cindex @code{STATE} values
12540: -1.
12541:
12542: @item values returned after arithmetic overflow:
12543: On two's complement machines, arithmetic is performed modulo
12544: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
12545: arithmetic (with appropriate mapping for signed types). Division by zero
12546: typically results in a @code{-55 throw} (Floating-point unidentified
1.80 anton 12547: fault) or @code{-10 throw} (divide by zero).
1.1 anton 12548:
12549: @item whether the current definition can be found after @t{DOES>}:
12550: @cindex @t{DOES>}, visibility of current definition
12551: No.
12552:
12553: @end table
12554:
12555: @c ---------------------------------------------------------------------
12556: @node core-ambcond, core-other, core-idef, The Core Words
12557: @subsection Ambiguous conditions
12558: @c ---------------------------------------------------------------------
12559: @cindex core words, ambiguous conditions
12560: @cindex ambiguous conditions, core words
12561:
12562: @table @i
12563:
12564: @item a name is neither a word nor a number:
12565: @cindex name not found
1.26 crook 12566: @cindex undefined word
1.80 anton 12567: @code{-13 throw} (Undefined word).
1.1 anton 12568:
12569: @item a definition name exceeds the maximum length allowed:
1.26 crook 12570: @cindex word name too long
1.1 anton 12571: @code{-19 throw} (Word name too long)
12572:
12573: @item addressing a region not inside the various data spaces of the forth system:
12574: @cindex Invalid memory address
1.32 anton 12575: The stacks, code space and header space are accessible. Machine code space is
1.1 anton 12576: typically readable. Accessing other addresses gives results dependent on
12577: the operating system. On decent systems: @code{-9 throw} (Invalid memory
12578: address).
12579:
12580: @item argument type incompatible with parameter:
1.26 crook 12581: @cindex argument type mismatch
1.1 anton 12582: This is usually not caught. Some words perform checks, e.g., the control
12583: flow words, and issue a @code{ABORT"} or @code{-12 THROW} (Argument type
12584: mismatch).
12585:
12586: @item attempting to obtain the execution token of a word with undefined execution semantics:
12587: @cindex Interpreting a compile-only word, for @code{'} etc.
12588: @cindex execution token of words with undefined execution semantics
12589: @code{-14 throw} (Interpreting a compile-only word). In some cases, you
12590: get an execution token for @code{compile-only-error} (which performs a
12591: @code{-14 throw} when executed).
12592:
12593: @item dividing by zero:
12594: @cindex dividing by zero
12595: @cindex floating point unidentified fault, integer division
1.80 anton 12596: On some platforms, this produces a @code{-10 throw} (Division by
1.24 anton 12597: zero); on other systems, this typically results in a @code{-55 throw}
12598: (Floating-point unidentified fault).
1.1 anton 12599:
12600: @item insufficient data stack or return stack space:
12601: @cindex insufficient data stack or return stack space
12602: @cindex stack overflow
1.26 crook 12603: @cindex address alignment exception, stack overflow
1.1 anton 12604: @cindex Invalid memory address, stack overflow
12605: Depending on the operating system, the installation, and the invocation
12606: of Gforth, this is either checked by the memory management hardware, or
1.24 anton 12607: it is not checked. If it is checked, you typically get a @code{-3 throw}
12608: (Stack overflow), @code{-5 throw} (Return stack overflow), or @code{-9
12609: throw} (Invalid memory address) (depending on the platform and how you
12610: achieved the overflow) as soon as the overflow happens. If it is not
12611: checked, overflows typically result in mysterious illegal memory
12612: accesses, producing @code{-9 throw} (Invalid memory address) or
12613: @code{-23 throw} (Address alignment exception); they might also destroy
12614: the internal data structure of @code{ALLOCATE} and friends, resulting in
12615: various errors in these words.
1.1 anton 12616:
12617: @item insufficient space for loop control parameters:
12618: @cindex insufficient space for loop control parameters
1.80 anton 12619: Like other return stack overflows.
1.1 anton 12620:
12621: @item insufficient space in the dictionary:
12622: @cindex insufficient space in the dictionary
12623: @cindex dictionary overflow
1.12 anton 12624: If you try to allot (either directly with @code{allot}, or indirectly
12625: with @code{,}, @code{create} etc.) more memory than available in the
12626: dictionary, you get a @code{-8 throw} (Dictionary overflow). If you try
12627: to access memory beyond the end of the dictionary, the results are
12628: similar to stack overflows.
1.1 anton 12629:
12630: @item interpreting a word with undefined interpretation semantics:
12631: @cindex interpreting a word with undefined interpretation semantics
12632: @cindex Interpreting a compile-only word
12633: For some words, we have defined interpretation semantics. For the
12634: others: @code{-14 throw} (Interpreting a compile-only word).
12635:
12636: @item modifying the contents of the input buffer or a string literal:
12637: @cindex modifying the contents of the input buffer or a string literal
12638: These are located in writable memory and can be modified.
12639:
12640: @item overflow of the pictured numeric output string:
12641: @cindex overflow of the pictured numeric output string
12642: @cindex pictured numeric output string, overflow
1.24 anton 12643: @code{-17 throw} (Pictured numeric ouput string overflow).
1.1 anton 12644:
12645: @item parsed string overflow:
12646: @cindex parsed string overflow
12647: @code{PARSE} cannot overflow. @code{WORD} does not check for overflow.
12648:
12649: @item producing a result out of range:
12650: @cindex result out of range
12651: On two's complement machines, arithmetic is performed modulo
12652: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
12653: arithmetic (with appropriate mapping for signed types). Division by zero
1.24 anton 12654: typically results in a @code{-10 throw} (divide by zero) or @code{-55
12655: throw} (floating point unidentified fault). @code{convert} and
12656: @code{>number} currently overflow silently.
1.1 anton 12657:
12658: @item reading from an empty data or return stack:
12659: @cindex stack empty
12660: @cindex stack underflow
1.24 anton 12661: @cindex return stack underflow
1.1 anton 12662: The data stack is checked by the outer (aka text) interpreter after
12663: every word executed. If it has underflowed, a @code{-4 throw} (Stack
12664: underflow) is performed. Apart from that, stacks may be checked or not,
1.24 anton 12665: depending on operating system, installation, and invocation. If they are
12666: caught by a check, they typically result in @code{-4 throw} (Stack
12667: underflow), @code{-6 throw} (Return stack underflow) or @code{-9 throw}
12668: (Invalid memory address), depending on the platform and which stack
12669: underflows and by how much. Note that even if the system uses checking
12670: (through the MMU), your program may have to underflow by a significant
12671: number of stack items to trigger the reaction (the reason for this is
12672: that the MMU, and therefore the checking, works with a page-size
12673: granularity). If there is no checking, the symptoms resulting from an
12674: underflow are similar to those from an overflow. Unbalanced return
1.80 anton 12675: stack errors can result in a variety of symptoms, including @code{-9 throw}
1.24 anton 12676: (Invalid memory address) and Illegal Instruction (typically @code{-260
12677: throw}).
1.1 anton 12678:
12679: @item unexpected end of the input buffer, resulting in an attempt to use a zero-length string as a name:
12680: @cindex unexpected end of the input buffer
12681: @cindex zero-length string as a name
12682: @cindex Attempt to use zero-length string as a name
12683: @code{Create} and its descendants perform a @code{-16 throw} (Attempt to
12684: use zero-length string as a name). Words like @code{'} probably will not
12685: find what they search. Note that it is possible to create zero-length
12686: names with @code{nextname} (should it not?).
12687:
12688: @item @code{>IN} greater than input buffer:
12689: @cindex @code{>IN} greater than input buffer
12690: The next invocation of a parsing word returns a string with length 0.
12691:
12692: @item @code{RECURSE} appears after @code{DOES>}:
12693: @cindex @code{RECURSE} appears after @code{DOES>}
12694: Compiles a recursive call to the defining word, not to the defined word.
12695:
12696: @item argument input source different than current input source for @code{RESTORE-INPUT}:
12697: @cindex argument input source different than current input source for @code{RESTORE-INPUT}
1.26 crook 12698: @cindex argument type mismatch, @code{RESTORE-INPUT}
1.1 anton 12699: @cindex @code{RESTORE-INPUT}, Argument type mismatch
12700: @code{-12 THROW}. Note that, once an input file is closed (e.g., because
12701: the end of the file was reached), its source-id may be
12702: reused. Therefore, restoring an input source specification referencing a
12703: closed file may lead to unpredictable results instead of a @code{-12
12704: THROW}.
12705:
12706: In the future, Gforth may be able to restore input source specifications
12707: from other than the current input source.
12708:
12709: @item data space containing definitions gets de-allocated:
12710: @cindex data space containing definitions gets de-allocated
12711: Deallocation with @code{allot} is not checked. This typically results in
12712: memory access faults or execution of illegal instructions.
12713:
12714: @item data space read/write with incorrect alignment:
12715: @cindex data space read/write with incorrect alignment
12716: @cindex alignment faults
1.26 crook 12717: @cindex address alignment exception
1.1 anton 12718: Processor-dependent. Typically results in a @code{-23 throw} (Address
1.12 anton 12719: alignment exception). Under Linux-Intel on a 486 or later processor with
1.1 anton 12720: alignment turned on, incorrect alignment results in a @code{-9 throw}
12721: (Invalid memory address). There are reportedly some processors with
1.12 anton 12722: alignment restrictions that do not report violations.
1.1 anton 12723:
12724: @item data space pointer not properly aligned, @code{,}, @code{C,}:
12725: @cindex data space pointer not properly aligned, @code{,}, @code{C,}
12726: Like other alignment errors.
12727:
12728: @item less than u+2 stack items (@code{PICK} and @code{ROLL}):
12729: Like other stack underflows.
12730:
12731: @item loop control parameters not available:
12732: @cindex loop control parameters not available
12733: Not checked. The counted loop words simply assume that the top of return
12734: stack items are loop control parameters and behave accordingly.
12735:
12736: @item most recent definition does not have a name (@code{IMMEDIATE}):
12737: @cindex most recent definition does not have a name (@code{IMMEDIATE})
12738: @cindex last word was headerless
12739: @code{abort" last word was headerless"}.
12740:
12741: @item name not defined by @code{VALUE} used by @code{TO}:
12742: @cindex name not defined by @code{VALUE} used by @code{TO}
12743: @cindex @code{TO} on non-@code{VALUE}s
12744: @cindex Invalid name argument, @code{TO}
12745: @code{-32 throw} (Invalid name argument) (unless name is a local or was
12746: defined by @code{CONSTANT}; in the latter case it just changes the constant).
12747:
12748: @item name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}):
12749: @cindex name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]})
1.26 crook 12750: @cindex undefined word, @code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}
1.1 anton 12751: @code{-13 throw} (Undefined word)
12752:
12753: @item parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN}):
12754: @cindex parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN})
12755: Gforth behaves as if they were of the same type. I.e., you can predict
12756: the behaviour by interpreting all parameters as, e.g., signed.
12757:
12758: @item @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}:
12759: @cindex @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}
12760: Assume @code{: X POSTPONE TO ; IMMEDIATE}. @code{X} performs the
12761: compilation semantics of @code{TO}.
12762:
12763: @item String longer than a counted string returned by @code{WORD}:
1.26 crook 12764: @cindex string longer than a counted string returned by @code{WORD}
1.1 anton 12765: @cindex @code{WORD}, string overflow
12766: Not checked. The string will be ok, but the count will, of course,
12767: contain only the least significant bits of the length.
12768:
12769: @item u greater than or equal to the number of bits in a cell (@code{LSHIFT}, @code{RSHIFT}):
12770: @cindex @code{LSHIFT}, large shift counts
12771: @cindex @code{RSHIFT}, large shift counts
12772: Processor-dependent. Typical behaviours are returning 0 and using only
12773: the low bits of the shift count.
12774:
12775: @item word not defined via @code{CREATE}:
12776: @cindex @code{>BODY} of non-@code{CREATE}d words
12777: @code{>BODY} produces the PFA of the word no matter how it was defined.
12778:
12779: @cindex @code{DOES>} of non-@code{CREATE}d words
12780: @code{DOES>} changes the execution semantics of the last defined word no
12781: matter how it was defined. E.g., @code{CONSTANT DOES>} is equivalent to
12782: @code{CREATE , DOES>}.
12783:
12784: @item words improperly used outside @code{<#} and @code{#>}:
12785: Not checked. As usual, you can expect memory faults.
12786:
12787: @end table
12788:
12789:
12790: @c ---------------------------------------------------------------------
12791: @node core-other, , core-ambcond, The Core Words
12792: @subsection Other system documentation
12793: @c ---------------------------------------------------------------------
12794: @cindex other system documentation, core words
12795: @cindex core words, other system documentation
12796:
12797: @table @i
12798: @item nonstandard words using @code{PAD}:
12799: @cindex @code{PAD} use by nonstandard words
12800: None.
12801:
12802: @item operator's terminal facilities available:
12803: @cindex operator's terminal facilities available
1.80 anton 12804: After processing the OS's command line, Gforth goes into interactive mode,
1.1 anton 12805: and you can give commands to Gforth interactively. The actual facilities
12806: available depend on how you invoke Gforth.
12807:
12808: @item program data space available:
12809: @cindex program data space available
12810: @cindex data space available
12811: @code{UNUSED .} gives the remaining dictionary space. The total
12812: dictionary space can be specified with the @code{-m} switch
12813: (@pxref{Invoking Gforth}) when Gforth starts up.
12814:
12815: @item return stack space available:
12816: @cindex return stack space available
12817: You can compute the total return stack space in cells with
12818: @code{s" RETURN-STACK-CELLS" environment? drop .}. You can specify it at
12819: startup time with the @code{-r} switch (@pxref{Invoking Gforth}).
12820:
12821: @item stack space available:
12822: @cindex stack space available
12823: You can compute the total data stack space in cells with
12824: @code{s" STACK-CELLS" environment? drop .}. You can specify it at
12825: startup time with the @code{-d} switch (@pxref{Invoking Gforth}).
12826:
12827: @item system dictionary space required, in address units:
12828: @cindex system dictionary space required, in address units
12829: Type @code{here forthstart - .} after startup. At the time of this
12830: writing, this gives 80080 (bytes) on a 32-bit system.
12831: @end table
12832:
12833:
12834: @c =====================================================================
12835: @node The optional Block word set, The optional Double Number word set, The Core Words, ANS conformance
12836: @section The optional Block word set
12837: @c =====================================================================
12838: @cindex system documentation, block words
12839: @cindex block words, system documentation
12840:
12841: @menu
12842: * block-idef:: Implementation Defined Options
12843: * block-ambcond:: Ambiguous Conditions
12844: * block-other:: Other System Documentation
12845: @end menu
12846:
12847:
12848: @c ---------------------------------------------------------------------
12849: @node block-idef, block-ambcond, The optional Block word set, The optional Block word set
12850: @subsection Implementation Defined Options
12851: @c ---------------------------------------------------------------------
12852: @cindex implementation-defined options, block words
12853: @cindex block words, implementation-defined options
12854:
12855: @table @i
12856: @item the format for display by @code{LIST}:
12857: @cindex @code{LIST} display format
12858: First the screen number is displayed, then 16 lines of 64 characters,
12859: each line preceded by the line number.
12860:
12861: @item the length of a line affected by @code{\}:
12862: @cindex length of a line affected by @code{\}
12863: @cindex @code{\}, line length in blocks
12864: 64 characters.
12865: @end table
12866:
12867:
12868: @c ---------------------------------------------------------------------
12869: @node block-ambcond, block-other, block-idef, The optional Block word set
12870: @subsection Ambiguous conditions
12871: @c ---------------------------------------------------------------------
12872: @cindex block words, ambiguous conditions
12873: @cindex ambiguous conditions, block words
12874:
12875: @table @i
12876: @item correct block read was not possible:
12877: @cindex block read not possible
12878: Typically results in a @code{throw} of some OS-derived value (between
12879: -512 and -2048). If the blocks file was just not long enough, blanks are
12880: supplied for the missing portion.
12881:
12882: @item I/O exception in block transfer:
12883: @cindex I/O exception in block transfer
12884: @cindex block transfer, I/O exception
12885: Typically results in a @code{throw} of some OS-derived value (between
12886: -512 and -2048).
12887:
12888: @item invalid block number:
12889: @cindex invalid block number
12890: @cindex block number invalid
12891: @code{-35 throw} (Invalid block number)
12892:
12893: @item a program directly alters the contents of @code{BLK}:
12894: @cindex @code{BLK}, altering @code{BLK}
12895: The input stream is switched to that other block, at the same
12896: position. If the storing to @code{BLK} happens when interpreting
12897: non-block input, the system will get quite confused when the block ends.
12898:
12899: @item no current block buffer for @code{UPDATE}:
12900: @cindex @code{UPDATE}, no current block buffer
12901: @code{UPDATE} has no effect.
12902:
12903: @end table
12904:
12905: @c ---------------------------------------------------------------------
12906: @node block-other, , block-ambcond, The optional Block word set
12907: @subsection Other system documentation
12908: @c ---------------------------------------------------------------------
12909: @cindex other system documentation, block words
12910: @cindex block words, other system documentation
12911:
12912: @table @i
12913: @item any restrictions a multiprogramming system places on the use of buffer addresses:
12914: No restrictions (yet).
12915:
12916: @item the number of blocks available for source and data:
12917: depends on your disk space.
12918:
12919: @end table
12920:
12921:
12922: @c =====================================================================
12923: @node The optional Double Number word set, The optional Exception word set, The optional Block word set, ANS conformance
12924: @section The optional Double Number word set
12925: @c =====================================================================
12926: @cindex system documentation, double words
12927: @cindex double words, system documentation
12928:
12929: @menu
12930: * double-ambcond:: Ambiguous Conditions
12931: @end menu
12932:
12933:
12934: @c ---------------------------------------------------------------------
12935: @node double-ambcond, , The optional Double Number word set, The optional Double Number word set
12936: @subsection Ambiguous conditions
12937: @c ---------------------------------------------------------------------
12938: @cindex double words, ambiguous conditions
12939: @cindex ambiguous conditions, double words
12940:
12941: @table @i
1.29 crook 12942: @item @i{d} outside of range of @i{n} in @code{D>S}:
12943: @cindex @code{D>S}, @i{d} out of range of @i{n}
12944: The least significant cell of @i{d} is produced.
1.1 anton 12945:
12946: @end table
12947:
12948:
12949: @c =====================================================================
12950: @node The optional Exception word set, The optional Facility word set, The optional Double Number word set, ANS conformance
12951: @section The optional Exception word set
12952: @c =====================================================================
12953: @cindex system documentation, exception words
12954: @cindex exception words, system documentation
12955:
12956: @menu
12957: * exception-idef:: Implementation Defined Options
12958: @end menu
12959:
12960:
12961: @c ---------------------------------------------------------------------
12962: @node exception-idef, , The optional Exception word set, The optional Exception word set
12963: @subsection Implementation Defined Options
12964: @c ---------------------------------------------------------------------
12965: @cindex implementation-defined options, exception words
12966: @cindex exception words, implementation-defined options
12967:
12968: @table @i
12969: @item @code{THROW}-codes used in the system:
12970: @cindex @code{THROW}-codes used in the system
12971: The codes -256@minus{}-511 are used for reporting signals. The mapping
1.29 crook 12972: from OS signal numbers to throw codes is -256@minus{}@i{signal}. The
1.1 anton 12973: codes -512@minus{}-2047 are used for OS errors (for file and memory
12974: allocation operations). The mapping from OS error numbers to throw codes
12975: is -512@minus{}@code{errno}. One side effect of this mapping is that
12976: undefined OS errors produce a message with a strange number; e.g.,
12977: @code{-1000 THROW} results in @code{Unknown error 488} on my system.
12978: @end table
12979:
12980: @c =====================================================================
12981: @node The optional Facility word set, The optional File-Access word set, The optional Exception word set, ANS conformance
12982: @section The optional Facility word set
12983: @c =====================================================================
12984: @cindex system documentation, facility words
12985: @cindex facility words, system documentation
12986:
12987: @menu
12988: * facility-idef:: Implementation Defined Options
12989: * facility-ambcond:: Ambiguous Conditions
12990: @end menu
12991:
12992:
12993: @c ---------------------------------------------------------------------
12994: @node facility-idef, facility-ambcond, The optional Facility word set, The optional Facility word set
12995: @subsection Implementation Defined Options
12996: @c ---------------------------------------------------------------------
12997: @cindex implementation-defined options, facility words
12998: @cindex facility words, implementation-defined options
12999:
13000: @table @i
13001: @item encoding of keyboard events (@code{EKEY}):
13002: @cindex keyboard events, encoding in @code{EKEY}
13003: @cindex @code{EKEY}, encoding of keyboard events
1.40 anton 13004: Keys corresponding to ASCII characters are encoded as ASCII characters.
1.41 anton 13005: Other keys are encoded with the constants @code{k-left}, @code{k-right},
13006: @code{k-up}, @code{k-down}, @code{k-home}, @code{k-end}, @code{k1},
13007: @code{k2}, @code{k3}, @code{k4}, @code{k5}, @code{k6}, @code{k7},
13008: @code{k8}, @code{k9}, @code{k10}, @code{k11}, @code{k12}.
1.40 anton 13009:
1.1 anton 13010:
13011: @item duration of a system clock tick:
13012: @cindex duration of a system clock tick
13013: @cindex clock tick duration
13014: System dependent. With respect to @code{MS}, the time is specified in
13015: microseconds. How well the OS and the hardware implement this, is
13016: another question.
13017:
13018: @item repeatability to be expected from the execution of @code{MS}:
13019: @cindex repeatability to be expected from the execution of @code{MS}
13020: @cindex @code{MS}, repeatability to be expected
13021: System dependent. On Unix, a lot depends on load. If the system is
13022: lightly loaded, and the delay is short enough that Gforth does not get
13023: swapped out, the performance should be acceptable. Under MS-DOS and
13024: other single-tasking systems, it should be good.
13025:
13026: @end table
13027:
13028:
13029: @c ---------------------------------------------------------------------
13030: @node facility-ambcond, , facility-idef, The optional Facility word set
13031: @subsection Ambiguous conditions
13032: @c ---------------------------------------------------------------------
13033: @cindex facility words, ambiguous conditions
13034: @cindex ambiguous conditions, facility words
13035:
13036: @table @i
13037: @item @code{AT-XY} can't be performed on user output device:
13038: @cindex @code{AT-XY} can't be performed on user output device
13039: Largely terminal dependent. No range checks are done on the arguments.
13040: No errors are reported. You may see some garbage appearing, you may see
13041: simply nothing happen.
13042:
13043: @end table
13044:
13045:
13046: @c =====================================================================
13047: @node The optional File-Access word set, The optional Floating-Point word set, The optional Facility word set, ANS conformance
13048: @section The optional File-Access word set
13049: @c =====================================================================
13050: @cindex system documentation, file words
13051: @cindex file words, system documentation
13052:
13053: @menu
13054: * file-idef:: Implementation Defined Options
13055: * file-ambcond:: Ambiguous Conditions
13056: @end menu
13057:
13058: @c ---------------------------------------------------------------------
13059: @node file-idef, file-ambcond, The optional File-Access word set, The optional File-Access word set
13060: @subsection Implementation Defined Options
13061: @c ---------------------------------------------------------------------
13062: @cindex implementation-defined options, file words
13063: @cindex file words, implementation-defined options
13064:
13065: @table @i
13066: @item file access methods used:
13067: @cindex file access methods used
13068: @code{R/O}, @code{R/W} and @code{BIN} work as you would
13069: expect. @code{W/O} translates into the C file opening mode @code{w} (or
13070: @code{wb}): The file is cleared, if it exists, and created, if it does
13071: not (with both @code{open-file} and @code{create-file}). Under Unix
13072: @code{create-file} creates a file with 666 permissions modified by your
13073: umask.
13074:
13075: @item file exceptions:
13076: @cindex file exceptions
13077: The file words do not raise exceptions (except, perhaps, memory access
13078: faults when you pass illegal addresses or file-ids).
13079:
13080: @item file line terminator:
13081: @cindex file line terminator
13082: System-dependent. Gforth uses C's newline character as line
13083: terminator. What the actual character code(s) of this are is
13084: system-dependent.
13085:
13086: @item file name format:
13087: @cindex file name format
13088: System dependent. Gforth just uses the file name format of your OS.
13089:
13090: @item information returned by @code{FILE-STATUS}:
13091: @cindex @code{FILE-STATUS}, returned information
13092: @code{FILE-STATUS} returns the most powerful file access mode allowed
13093: for the file: Either @code{R/O}, @code{W/O} or @code{R/W}. If the file
13094: cannot be accessed, @code{R/O BIN} is returned. @code{BIN} is applicable
13095: along with the returned mode.
13096:
13097: @item input file state after an exception when including source:
13098: @cindex exception when including source
13099: All files that are left via the exception are closed.
13100:
1.29 crook 13101: @item @i{ior} values and meaning:
13102: @cindex @i{ior} values and meaning
1.68 anton 13103: @cindex @i{wior} values and meaning
1.29 crook 13104: The @i{ior}s returned by the file and memory allocation words are
1.1 anton 13105: intended as throw codes. They typically are in the range
13106: -512@minus{}-2047 of OS errors. The mapping from OS error numbers to
1.29 crook 13107: @i{ior}s is -512@minus{}@i{errno}.
1.1 anton 13108:
13109: @item maximum depth of file input nesting:
13110: @cindex maximum depth of file input nesting
13111: @cindex file input nesting, maximum depth
13112: limited by the amount of return stack, locals/TIB stack, and the number
13113: of open files available. This should not give you troubles.
13114:
13115: @item maximum size of input line:
13116: @cindex maximum size of input line
13117: @cindex input line size, maximum
13118: @code{/line}. Currently 255.
13119:
13120: @item methods of mapping block ranges to files:
13121: @cindex mapping block ranges to files
13122: @cindex files containing blocks
13123: @cindex blocks in files
13124: By default, blocks are accessed in the file @file{blocks.fb} in the
13125: current working directory. The file can be switched with @code{USE}.
13126:
13127: @item number of string buffers provided by @code{S"}:
13128: @cindex @code{S"}, number of string buffers
13129: 1
13130:
13131: @item size of string buffer used by @code{S"}:
13132: @cindex @code{S"}, size of string buffer
13133: @code{/line}. currently 255.
13134:
13135: @end table
13136:
13137: @c ---------------------------------------------------------------------
13138: @node file-ambcond, , file-idef, The optional File-Access word set
13139: @subsection Ambiguous conditions
13140: @c ---------------------------------------------------------------------
13141: @cindex file words, ambiguous conditions
13142: @cindex ambiguous conditions, file words
13143:
13144: @table @i
13145: @item attempting to position a file outside its boundaries:
13146: @cindex @code{REPOSITION-FILE}, outside the file's boundaries
13147: @code{REPOSITION-FILE} is performed as usual: Afterwards,
13148: @code{FILE-POSITION} returns the value given to @code{REPOSITION-FILE}.
13149:
13150: @item attempting to read from file positions not yet written:
13151: @cindex reading from file positions not yet written
13152: End-of-file, i.e., zero characters are read and no error is reported.
13153:
1.29 crook 13154: @item @i{file-id} is invalid (@code{INCLUDE-FILE}):
13155: @cindex @code{INCLUDE-FILE}, @i{file-id} is invalid
1.1 anton 13156: An appropriate exception may be thrown, but a memory fault or other
13157: problem is more probable.
13158:
1.29 crook 13159: @item I/O exception reading or closing @i{file-id} (@code{INCLUDE-FILE}, @code{INCLUDED}):
13160: @cindex @code{INCLUDE-FILE}, I/O exception reading or closing @i{file-id}
13161: @cindex @code{INCLUDED}, I/O exception reading or closing @i{file-id}
13162: The @i{ior} produced by the operation, that discovered the problem, is
1.1 anton 13163: thrown.
13164:
13165: @item named file cannot be opened (@code{INCLUDED}):
13166: @cindex @code{INCLUDED}, named file cannot be opened
1.29 crook 13167: The @i{ior} produced by @code{open-file} is thrown.
1.1 anton 13168:
13169: @item requesting an unmapped block number:
13170: @cindex unmapped block numbers
13171: There are no unmapped legal block numbers. On some operating systems,
13172: writing a block with a large number may overflow the file system and
13173: have an error message as consequence.
13174:
13175: @item using @code{source-id} when @code{blk} is non-zero:
13176: @cindex @code{SOURCE-ID}, behaviour when @code{BLK} is non-zero
13177: @code{source-id} performs its function. Typically it will give the id of
13178: the source which loaded the block. (Better ideas?)
13179:
13180: @end table
13181:
13182:
13183: @c =====================================================================
13184: @node The optional Floating-Point word set, The optional Locals word set, The optional File-Access word set, ANS conformance
13185: @section The optional Floating-Point word set
13186: @c =====================================================================
13187: @cindex system documentation, floating-point words
13188: @cindex floating-point words, system documentation
13189:
13190: @menu
13191: * floating-idef:: Implementation Defined Options
13192: * floating-ambcond:: Ambiguous Conditions
13193: @end menu
13194:
13195:
13196: @c ---------------------------------------------------------------------
13197: @node floating-idef, floating-ambcond, The optional Floating-Point word set, The optional Floating-Point word set
13198: @subsection Implementation Defined Options
13199: @c ---------------------------------------------------------------------
13200: @cindex implementation-defined options, floating-point words
13201: @cindex floating-point words, implementation-defined options
13202:
13203: @table @i
13204: @item format and range of floating point numbers:
13205: @cindex format and range of floating point numbers
13206: @cindex floating point numbers, format and range
13207: System-dependent; the @code{double} type of C.
13208:
1.29 crook 13209: @item results of @code{REPRESENT} when @i{float} is out of range:
13210: @cindex @code{REPRESENT}, results when @i{float} is out of range
1.1 anton 13211: System dependent; @code{REPRESENT} is implemented using the C library
13212: function @code{ecvt()} and inherits its behaviour in this respect.
13213:
13214: @item rounding or truncation of floating-point numbers:
13215: @cindex rounding of floating-point numbers
13216: @cindex truncation of floating-point numbers
13217: @cindex floating-point numbers, rounding or truncation
13218: System dependent; the rounding behaviour is inherited from the hosting C
13219: compiler. IEEE-FP-based (i.e., most) systems by default round to
13220: nearest, and break ties by rounding to even (i.e., such that the last
13221: bit of the mantissa is 0).
13222:
13223: @item size of floating-point stack:
13224: @cindex floating-point stack size
13225: @code{s" FLOATING-STACK" environment? drop .} gives the total size of
13226: the floating-point stack (in floats). You can specify this on startup
13227: with the command-line option @code{-f} (@pxref{Invoking Gforth}).
13228:
13229: @item width of floating-point stack:
13230: @cindex floating-point stack width
13231: @code{1 floats}.
13232:
13233: @end table
13234:
13235:
13236: @c ---------------------------------------------------------------------
13237: @node floating-ambcond, , floating-idef, The optional Floating-Point word set
13238: @subsection Ambiguous conditions
13239: @c ---------------------------------------------------------------------
13240: @cindex floating-point words, ambiguous conditions
13241: @cindex ambiguous conditions, floating-point words
13242:
13243: @table @i
13244: @item @code{df@@} or @code{df!} used with an address that is not double-float aligned:
13245: @cindex @code{df@@} or @code{df!} used with an address that is not double-float aligned
13246: System-dependent. Typically results in a @code{-23 THROW} like other
13247: alignment violations.
13248:
13249: @item @code{f@@} or @code{f!} used with an address that is not float aligned:
13250: @cindex @code{f@@} used with an address that is not float aligned
13251: @cindex @code{f!} used with an address that is not float aligned
13252: System-dependent. Typically results in a @code{-23 THROW} like other
13253: alignment violations.
13254:
13255: @item floating-point result out of range:
13256: @cindex floating-point result out of range
1.80 anton 13257: System-dependent. Can result in a @code{-43 throw} (floating point
13258: overflow), @code{-54 throw} (floating point underflow), @code{-41 throw}
13259: (floating point inexact result), @code{-55 THROW} (Floating-point
1.1 anton 13260: unidentified fault), or can produce a special value representing, e.g.,
13261: Infinity.
13262:
13263: @item @code{sf@@} or @code{sf!} used with an address that is not single-float aligned:
13264: @cindex @code{sf@@} or @code{sf!} used with an address that is not single-float aligned
13265: System-dependent. Typically results in an alignment fault like other
13266: alignment violations.
13267:
1.35 anton 13268: @item @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.}):
13269: @cindex @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.})
1.1 anton 13270: The floating-point number is converted into decimal nonetheless.
13271:
13272: @item Both arguments are equal to zero (@code{FATAN2}):
13273: @cindex @code{FATAN2}, both arguments are equal to zero
13274: System-dependent. @code{FATAN2} is implemented using the C library
13275: function @code{atan2()}.
13276:
1.29 crook 13277: @item Using @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero:
13278: @cindex @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero
13279: System-dependent. Anyway, typically the cos of @i{r1} will not be zero
1.1 anton 13280: because of small errors and the tan will be a very large (or very small)
13281: but finite number.
13282:
1.29 crook 13283: @item @i{d} cannot be presented precisely as a float in @code{D>F}:
13284: @cindex @code{D>F}, @i{d} cannot be presented precisely as a float
1.1 anton 13285: The result is rounded to the nearest float.
13286:
13287: @item dividing by zero:
13288: @cindex dividing by zero, floating-point
13289: @cindex floating-point dividing by zero
13290: @cindex floating-point unidentified fault, FP divide-by-zero
1.80 anton 13291: Platform-dependent; can produce an Infinity, NaN, @code{-42 throw}
13292: (floating point divide by zero) or @code{-55 throw} (Floating-point
13293: unidentified fault).
1.1 anton 13294:
13295: @item exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@}):
13296: @cindex exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@})
13297: System dependent. On IEEE-FP based systems the number is converted into
13298: an infinity.
13299:
1.29 crook 13300: @item @i{float}<1 (@code{FACOSH}):
13301: @cindex @code{FACOSH}, @i{float}<1
1.1 anton 13302: @cindex floating-point unidentified fault, @code{FACOSH}
1.80 anton 13303: Platform-dependent; on IEEE-FP systems typically produces a NaN.
1.1 anton 13304:
1.29 crook 13305: @item @i{float}=<-1 (@code{FLNP1}):
13306: @cindex @code{FLNP1}, @i{float}=<-1
1.1 anton 13307: @cindex floating-point unidentified fault, @code{FLNP1}
1.80 anton 13308: Platform-dependent; on IEEE-FP systems typically produces a NaN (or a
13309: negative infinity for @i{float}=-1).
1.1 anton 13310:
1.29 crook 13311: @item @i{float}=<0 (@code{FLN}, @code{FLOG}):
13312: @cindex @code{FLN}, @i{float}=<0
13313: @cindex @code{FLOG}, @i{float}=<0
1.1 anton 13314: @cindex floating-point unidentified fault, @code{FLN} or @code{FLOG}
1.80 anton 13315: Platform-dependent; on IEEE-FP systems typically produces a NaN (or a
13316: negative infinity for @i{float}=0).
1.1 anton 13317:
1.29 crook 13318: @item @i{float}<0 (@code{FASINH}, @code{FSQRT}):
13319: @cindex @code{FASINH}, @i{float}<0
13320: @cindex @code{FSQRT}, @i{float}<0
1.1 anton 13321: @cindex floating-point unidentified fault, @code{FASINH} or @code{FSQRT}
1.80 anton 13322: Platform-dependent; for @code{fsqrt} this typically gives a NaN, for
13323: @code{fasinh} some platforms produce a NaN, others a number (bug in the
13324: C library?).
1.1 anton 13325:
1.29 crook 13326: @item |@i{float}|>1 (@code{FACOS}, @code{FASIN}, @code{FATANH}):
13327: @cindex @code{FACOS}, |@i{float}|>1
13328: @cindex @code{FASIN}, |@i{float}|>1
13329: @cindex @code{FATANH}, |@i{float}|>1
1.1 anton 13330: @cindex floating-point unidentified fault, @code{FACOS}, @code{FASIN} or @code{FATANH}
1.80 anton 13331: Platform-dependent; IEEE-FP systems typically produce a NaN.
1.1 anton 13332:
1.29 crook 13333: @item integer part of float cannot be represented by @i{d} in @code{F>D}:
13334: @cindex @code{F>D}, integer part of float cannot be represented by @i{d}
1.1 anton 13335: @cindex floating-point unidentified fault, @code{F>D}
1.80 anton 13336: Platform-dependent; typically, some double number is produced and no
13337: error is reported.
1.1 anton 13338:
13339: @item string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.}):
13340: @cindex string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.})
1.80 anton 13341: @code{Precision} characters of the numeric output area are used. If
13342: @code{precision} is too high, these words will smash the data or code
13343: close to @code{here}.
1.1 anton 13344: @end table
13345:
13346: @c =====================================================================
13347: @node The optional Locals word set, The optional Memory-Allocation word set, The optional Floating-Point word set, ANS conformance
13348: @section The optional Locals word set
13349: @c =====================================================================
13350: @cindex system documentation, locals words
13351: @cindex locals words, system documentation
13352:
13353: @menu
13354: * locals-idef:: Implementation Defined Options
13355: * locals-ambcond:: Ambiguous Conditions
13356: @end menu
13357:
13358:
13359: @c ---------------------------------------------------------------------
13360: @node locals-idef, locals-ambcond, The optional Locals word set, The optional Locals word set
13361: @subsection Implementation Defined Options
13362: @c ---------------------------------------------------------------------
13363: @cindex implementation-defined options, locals words
13364: @cindex locals words, implementation-defined options
13365:
13366: @table @i
13367: @item maximum number of locals in a definition:
13368: @cindex maximum number of locals in a definition
13369: @cindex locals, maximum number in a definition
13370: @code{s" #locals" environment? drop .}. Currently 15. This is a lower
13371: bound, e.g., on a 32-bit machine there can be 41 locals of up to 8
13372: characters. The number of locals in a definition is bounded by the size
13373: of locals-buffer, which contains the names of the locals.
13374:
13375: @end table
13376:
13377:
13378: @c ---------------------------------------------------------------------
13379: @node locals-ambcond, , locals-idef, The optional Locals word set
13380: @subsection Ambiguous conditions
13381: @c ---------------------------------------------------------------------
13382: @cindex locals words, ambiguous conditions
13383: @cindex ambiguous conditions, locals words
13384:
13385: @table @i
13386: @item executing a named local in interpretation state:
13387: @cindex local in interpretation state
13388: @cindex Interpreting a compile-only word, for a local
13389: Locals have no interpretation semantics. If you try to perform the
13390: interpretation semantics, you will get a @code{-14 throw} somewhere
13391: (Interpreting a compile-only word). If you perform the compilation
13392: semantics, the locals access will be compiled (irrespective of state).
13393:
1.29 crook 13394: @item @i{name} not defined by @code{VALUE} or @code{(LOCAL)} (@code{TO}):
1.1 anton 13395: @cindex name not defined by @code{VALUE} or @code{(LOCAL)} used by @code{TO}
13396: @cindex @code{TO} on non-@code{VALUE}s and non-locals
13397: @cindex Invalid name argument, @code{TO}
13398: @code{-32 throw} (Invalid name argument)
13399:
13400: @end table
13401:
13402:
13403: @c =====================================================================
13404: @node The optional Memory-Allocation word set, The optional Programming-Tools word set, The optional Locals word set, ANS conformance
13405: @section The optional Memory-Allocation word set
13406: @c =====================================================================
13407: @cindex system documentation, memory-allocation words
13408: @cindex memory-allocation words, system documentation
13409:
13410: @menu
13411: * memory-idef:: Implementation Defined Options
13412: @end menu
13413:
13414:
13415: @c ---------------------------------------------------------------------
13416: @node memory-idef, , The optional Memory-Allocation word set, The optional Memory-Allocation word set
13417: @subsection Implementation Defined Options
13418: @c ---------------------------------------------------------------------
13419: @cindex implementation-defined options, memory-allocation words
13420: @cindex memory-allocation words, implementation-defined options
13421:
13422: @table @i
1.29 crook 13423: @item values and meaning of @i{ior}:
13424: @cindex @i{ior} values and meaning
13425: The @i{ior}s returned by the file and memory allocation words are
1.1 anton 13426: intended as throw codes. They typically are in the range
13427: -512@minus{}-2047 of OS errors. The mapping from OS error numbers to
1.29 crook 13428: @i{ior}s is -512@minus{}@i{errno}.
1.1 anton 13429:
13430: @end table
13431:
13432: @c =====================================================================
13433: @node The optional Programming-Tools word set, The optional Search-Order word set, The optional Memory-Allocation word set, ANS conformance
13434: @section The optional Programming-Tools word set
13435: @c =====================================================================
13436: @cindex system documentation, programming-tools words
13437: @cindex programming-tools words, system documentation
13438:
13439: @menu
13440: * programming-idef:: Implementation Defined Options
13441: * programming-ambcond:: Ambiguous Conditions
13442: @end menu
13443:
13444:
13445: @c ---------------------------------------------------------------------
13446: @node programming-idef, programming-ambcond, The optional Programming-Tools word set, The optional Programming-Tools word set
13447: @subsection Implementation Defined Options
13448: @c ---------------------------------------------------------------------
13449: @cindex implementation-defined options, programming-tools words
13450: @cindex programming-tools words, implementation-defined options
13451:
13452: @table @i
13453: @item ending sequence for input following @code{;CODE} and @code{CODE}:
13454: @cindex @code{;CODE} ending sequence
13455: @cindex @code{CODE} ending sequence
13456: @code{END-CODE}
13457:
13458: @item manner of processing input following @code{;CODE} and @code{CODE}:
13459: @cindex @code{;CODE}, processing input
13460: @cindex @code{CODE}, processing input
13461: The @code{ASSEMBLER} vocabulary is pushed on the search order stack, and
13462: the input is processed by the text interpreter, (starting) in interpret
13463: state.
13464:
13465: @item search order capability for @code{EDITOR} and @code{ASSEMBLER}:
13466: @cindex @code{ASSEMBLER}, search order capability
13467: The ANS Forth search order word set.
13468:
13469: @item source and format of display by @code{SEE}:
13470: @cindex @code{SEE}, source and format of output
1.80 anton 13471: The source for @code{see} is the executable code used by the inner
1.1 anton 13472: interpreter. The current @code{see} tries to output Forth source code
1.80 anton 13473: (and on some platforms, assembly code for primitives) as well as
13474: possible.
1.1 anton 13475:
13476: @end table
13477:
13478: @c ---------------------------------------------------------------------
13479: @node programming-ambcond, , programming-idef, The optional Programming-Tools word set
13480: @subsection Ambiguous conditions
13481: @c ---------------------------------------------------------------------
13482: @cindex programming-tools words, ambiguous conditions
13483: @cindex ambiguous conditions, programming-tools words
13484:
13485: @table @i
13486:
1.21 crook 13487: @item deleting the compilation word list (@code{FORGET}):
13488: @cindex @code{FORGET}, deleting the compilation word list
1.1 anton 13489: Not implemented (yet).
13490:
1.29 crook 13491: @item fewer than @i{u}+1 items on the control-flow stack (@code{CS-PICK}, @code{CS-ROLL}):
13492: @cindex @code{CS-PICK}, fewer than @i{u}+1 items on the control flow-stack
13493: @cindex @code{CS-ROLL}, fewer than @i{u}+1 items on the control flow-stack
1.1 anton 13494: @cindex control-flow stack underflow
13495: This typically results in an @code{abort"} with a descriptive error
13496: message (may change into a @code{-22 throw} (Control structure mismatch)
13497: in the future). You may also get a memory access error. If you are
13498: unlucky, this ambiguous condition is not caught.
13499:
1.29 crook 13500: @item @i{name} can't be found (@code{FORGET}):
13501: @cindex @code{FORGET}, @i{name} can't be found
1.1 anton 13502: Not implemented (yet).
13503:
1.29 crook 13504: @item @i{name} not defined via @code{CREATE}:
13505: @cindex @code{;CODE}, @i{name} not defined via @code{CREATE}
1.1 anton 13506: @code{;CODE} behaves like @code{DOES>} in this respect, i.e., it changes
13507: the execution semantics of the last defined word no matter how it was
13508: defined.
13509:
13510: @item @code{POSTPONE} applied to @code{[IF]}:
13511: @cindex @code{POSTPONE} applied to @code{[IF]}
13512: @cindex @code{[IF]} and @code{POSTPONE}
13513: After defining @code{: X POSTPONE [IF] ; IMMEDIATE}. @code{X} is
13514: equivalent to @code{[IF]}.
13515:
13516: @item reaching the end of the input source before matching @code{[ELSE]} or @code{[THEN]}:
13517: @cindex @code{[IF]}, end of the input source before matching @code{[ELSE]} or @code{[THEN]}
13518: Continue in the same state of conditional compilation in the next outer
13519: input source. Currently there is no warning to the user about this.
13520:
13521: @item removing a needed definition (@code{FORGET}):
13522: @cindex @code{FORGET}, removing a needed definition
13523: Not implemented (yet).
13524:
13525: @end table
13526:
13527:
13528: @c =====================================================================
13529: @node The optional Search-Order word set, , The optional Programming-Tools word set, ANS conformance
13530: @section The optional Search-Order word set
13531: @c =====================================================================
13532: @cindex system documentation, search-order words
13533: @cindex search-order words, system documentation
13534:
13535: @menu
13536: * search-idef:: Implementation Defined Options
13537: * search-ambcond:: Ambiguous Conditions
13538: @end menu
13539:
13540:
13541: @c ---------------------------------------------------------------------
13542: @node search-idef, search-ambcond, The optional Search-Order word set, The optional Search-Order word set
13543: @subsection Implementation Defined Options
13544: @c ---------------------------------------------------------------------
13545: @cindex implementation-defined options, search-order words
13546: @cindex search-order words, implementation-defined options
13547:
13548: @table @i
13549: @item maximum number of word lists in search order:
13550: @cindex maximum number of word lists in search order
13551: @cindex search order, maximum depth
13552: @code{s" wordlists" environment? drop .}. Currently 16.
13553:
13554: @item minimum search order:
13555: @cindex minimum search order
13556: @cindex search order, minimum
13557: @code{root root}.
13558:
13559: @end table
13560:
13561: @c ---------------------------------------------------------------------
13562: @node search-ambcond, , search-idef, The optional Search-Order word set
13563: @subsection Ambiguous conditions
13564: @c ---------------------------------------------------------------------
13565: @cindex search-order words, ambiguous conditions
13566: @cindex ambiguous conditions, search-order words
13567:
13568: @table @i
1.21 crook 13569: @item changing the compilation word list (during compilation):
13570: @cindex changing the compilation word list (during compilation)
13571: @cindex compilation word list, change before definition ends
13572: The word is entered into the word list that was the compilation word list
1.1 anton 13573: at the start of the definition. Any changes to the name field (e.g.,
13574: @code{immediate}) or the code field (e.g., when executing @code{DOES>})
13575: are applied to the latest defined word (as reported by @code{last} or
1.21 crook 13576: @code{lastxt}), if possible, irrespective of the compilation word list.
1.1 anton 13577:
13578: @item search order empty (@code{previous}):
13579: @cindex @code{previous}, search order empty
1.26 crook 13580: @cindex vocstack empty, @code{previous}
1.1 anton 13581: @code{abort" Vocstack empty"}.
13582:
13583: @item too many word lists in search order (@code{also}):
13584: @cindex @code{also}, too many word lists in search order
1.26 crook 13585: @cindex vocstack full, @code{also}
1.1 anton 13586: @code{abort" Vocstack full"}.
13587:
13588: @end table
13589:
13590: @c ***************************************************************
1.65 anton 13591: @node Standard vs Extensions, Model, ANS conformance, Top
13592: @chapter Should I use Gforth extensions?
13593: @cindex Gforth extensions
13594:
13595: As you read through the rest of this manual, you will see documentation
13596: for @i{Standard} words, and documentation for some appealing Gforth
13597: @i{extensions}. You might ask yourself the question: @i{``Should I
13598: restrict myself to the standard, or should I use the extensions?''}
13599:
13600: The answer depends on the goals you have for the program you are working
13601: on:
13602:
13603: @itemize @bullet
13604:
13605: @item Is it just for yourself or do you want to share it with others?
13606:
13607: @item
13608: If you want to share it, do the others all use Gforth?
13609:
13610: @item
13611: If it is just for yourself, do you want to restrict yourself to Gforth?
13612:
13613: @end itemize
13614:
13615: If restricting the program to Gforth is ok, then there is no reason not
13616: to use extensions. It is still a good idea to keep to the standard
13617: where it is easy, in case you want to reuse these parts in another
13618: program that you want to be portable.
13619:
13620: If you want to be able to port the program to other Forth systems, there
13621: are the following points to consider:
13622:
13623: @itemize @bullet
13624:
13625: @item
13626: Most Forth systems that are being maintained support the ANS Forth
13627: standard. So if your program complies with the standard, it will be
13628: portable among many systems.
13629:
13630: @item
13631: A number of the Gforth extensions can be implemented in ANS Forth using
13632: public-domain files provided in the @file{compat/} directory. These are
13633: mentioned in the text in passing. There is no reason not to use these
13634: extensions, your program will still be ANS Forth compliant; just include
13635: the appropriate compat files with your program.
13636:
13637: @item
13638: The tool @file{ans-report.fs} (@pxref{ANS Report}) makes it easy to
13639: analyse your program and determine what non-Standard words it relies
13640: upon. However, it does not check whether you use standard words in a
13641: non-standard way.
13642:
13643: @item
13644: Some techniques are not standardized by ANS Forth, and are hard or
13645: impossible to implement in a standard way, but can be implemented in
13646: most Forth systems easily, and usually in similar ways (e.g., accessing
13647: word headers). Forth has a rich historical precedent for programmers
13648: taking advantage of implementation-dependent features of their tools
13649: (for example, relying on a knowledge of the dictionary
13650: structure). Sometimes these techniques are necessary to extract every
13651: last bit of performance from the hardware, sometimes they are just a
13652: programming shorthand.
13653:
13654: @item
13655: Does using a Gforth extension save more work than the porting this part
13656: to other Forth systems (if any) will cost?
13657:
13658: @item
13659: Is the additional functionality worth the reduction in portability and
13660: the additional porting problems?
13661:
13662: @end itemize
13663:
13664: In order to perform these consideratios, you need to know what's
13665: standard and what's not. This manual generally states if something is
1.81 anton 13666: non-standard, but the authoritative source is the
13667: @uref{http://www.taygeta.com/forth/dpans.html,standard document}.
1.65 anton 13668: Appendix A of the Standard (@var{Rationale}) provides a valuable insight
13669: into the thought processes of the technical committee.
13670:
13671: Note also that portability between Forth systems is not the only
13672: portability issue; there is also the issue of portability between
13673: different platforms (processor/OS combinations).
13674:
13675: @c ***************************************************************
13676: @node Model, Integrating Gforth, Standard vs Extensions, Top
1.1 anton 13677: @chapter Model
13678:
13679: This chapter has yet to be written. It will contain information, on
13680: which internal structures you can rely.
13681:
13682: @c ***************************************************************
13683: @node Integrating Gforth, Emacs and Gforth, Model, Top
13684: @chapter Integrating Gforth into C programs
13685:
13686: This is not yet implemented.
13687:
13688: Several people like to use Forth as scripting language for applications
13689: that are otherwise written in C, C++, or some other language.
13690:
13691: The Forth system ATLAST provides facilities for embedding it into
13692: applications; unfortunately it has several disadvantages: most
13693: importantly, it is not based on ANS Forth, and it is apparently dead
13694: (i.e., not developed further and not supported). The facilities
1.21 crook 13695: provided by Gforth in this area are inspired by ATLAST's facilities, so
1.1 anton 13696: making the switch should not be hard.
13697:
13698: We also tried to design the interface such that it can easily be
13699: implemented by other Forth systems, so that we may one day arrive at a
13700: standardized interface. Such a standard interface would allow you to
13701: replace the Forth system without having to rewrite C code.
13702:
13703: You embed the Gforth interpreter by linking with the library
13704: @code{libgforth.a} (give the compiler the option @code{-lgforth}). All
13705: global symbols in this library that belong to the interface, have the
13706: prefix @code{forth_}. (Global symbols that are used internally have the
13707: prefix @code{gforth_}).
13708:
13709: You can include the declarations of Forth types and the functions and
13710: variables of the interface with @code{#include <forth.h>}.
13711:
13712: Types.
13713:
13714: Variables.
13715:
13716: Data and FP Stack pointer. Area sizes.
13717:
13718: functions.
13719:
13720: forth_init(imagefile)
13721: forth_evaluate(string) exceptions?
13722: forth_goto(address) (or forth_execute(xt)?)
13723: forth_continue() (a corountining mechanism)
13724:
13725: Adding primitives.
13726:
13727: No checking.
13728:
13729: Signals?
13730:
13731: Accessing the Stacks
13732:
1.26 crook 13733: @c ******************************************************************
1.1 anton 13734: @node Emacs and Gforth, Image Files, Integrating Gforth, Top
13735: @chapter Emacs and Gforth
13736: @cindex Emacs and Gforth
13737:
13738: @cindex @file{gforth.el}
13739: @cindex @file{forth.el}
13740: @cindex Rydqvist, Goran
13741: @cindex comment editing commands
13742: @cindex @code{\}, editing with Emacs
13743: @cindex debug tracer editing commands
13744: @cindex @code{~~}, removal with Emacs
13745: @cindex Forth mode in Emacs
13746: Gforth comes with @file{gforth.el}, an improved version of
13747: @file{forth.el} by Goran Rydqvist (included in the TILE package). The
1.26 crook 13748: improvements are:
13749:
13750: @itemize @bullet
13751: @item
13752: A better (but still not perfect) handling of indentation.
13753: @item
13754: Comment paragraph filling (@kbd{M-q})
13755: @item
13756: Commenting (@kbd{C-x \}) and uncommenting (@kbd{C-u C-x \}) of regions
13757: @item
13758: Removal of debugging tracers (@kbd{C-x ~}, @pxref{Debugging}).
1.41 anton 13759: @item
13760: Support of the @code{info-lookup} feature for looking up the
13761: documentation of a word.
1.26 crook 13762: @end itemize
13763:
13764: I left the stuff I do not use alone, even though some of it only makes
13765: sense for TILE. To get a description of these features, enter Forth mode
13766: and type @kbd{C-h m}.
1.1 anton 13767:
13768: @cindex source location of error or debugging output in Emacs
13769: @cindex error output, finding the source location in Emacs
13770: @cindex debugging output, finding the source location in Emacs
13771: In addition, Gforth supports Emacs quite well: The source code locations
13772: given in error messages, debugging output (from @code{~~}) and failed
13773: assertion messages are in the right format for Emacs' compilation mode
13774: (@pxref{Compilation, , Running Compilations under Emacs, emacs, Emacs
13775: Manual}) so the source location corresponding to an error or other
13776: message is only a few keystrokes away (@kbd{C-x `} for the next error,
13777: @kbd{C-c C-c} for the error under the cursor).
13778:
13779: @cindex @file{TAGS} file
13780: @cindex @file{etags.fs}
13781: @cindex viewing the source of a word in Emacs
1.43 anton 13782: @cindex @code{require}, placement in files
13783: @cindex @code{include}, placement in files
13784: Also, if you @code{require} @file{etags.fs}, a new @file{TAGS} file will
1.26 crook 13785: be produced (@pxref{Tags, , Tags Tables, emacs, Emacs Manual}) that
1.1 anton 13786: contains the definitions of all words defined afterwards. You can then
13787: find the source for a word using @kbd{M-.}. Note that emacs can use
13788: several tags files at the same time (e.g., one for the Gforth sources
13789: and one for your program, @pxref{Select Tags Table,,Selecting a Tags
13790: Table,emacs, Emacs Manual}). The TAGS file for the preloaded words is
13791: @file{$(datadir)/gforth/$(VERSION)/TAGS} (e.g.,
1.43 anton 13792: @file{/usr/local/share/gforth/0.2.0/TAGS}). To get the best behaviour
13793: with @file{etags.fs}, you should avoid putting definitions both before
13794: and after @code{require} etc., otherwise you will see the same file
13795: visited several times by commands like @code{tags-search}.
1.1 anton 13796:
1.41 anton 13797: @cindex viewing the documentation of a word in Emacs
13798: @cindex context-sensitive help
13799: Moreover, for words documented in this manual, you can look up the
13800: glossary entry quickly by using @kbd{C-h TAB}
1.80 anton 13801: (@code{info-lookup-symbol}, @pxref{Documentation, ,Documentation
1.41 anton 13802: Commands, emacs, Emacs Manual}). This feature requires Emacs 20.3 or
1.42 anton 13803: later and does not work for words containing @code{:}.
1.41 anton 13804:
13805:
1.1 anton 13806: @cindex @file{.emacs}
13807: To get all these benefits, add the following lines to your @file{.emacs}
13808: file:
13809:
13810: @example
13811: (autoload 'forth-mode "gforth.el")
13812: (setq auto-mode-alist (cons '("\\.fs\\'" . forth-mode) auto-mode-alist))
13813: @end example
13814:
1.26 crook 13815: @c ******************************************************************
1.1 anton 13816: @node Image Files, Engine, Emacs and Gforth, Top
13817: @chapter Image Files
1.26 crook 13818: @cindex image file
13819: @cindex @file{.fi} files
1.1 anton 13820: @cindex precompiled Forth code
13821: @cindex dictionary in persistent form
13822: @cindex persistent form of dictionary
13823:
13824: An image file is a file containing an image of the Forth dictionary,
13825: i.e., compiled Forth code and data residing in the dictionary. By
13826: convention, we use the extension @code{.fi} for image files.
13827:
13828: @menu
1.18 anton 13829: * Image Licensing Issues:: Distribution terms for images.
13830: * Image File Background:: Why have image files?
1.67 anton 13831: * Non-Relocatable Image Files:: don't always work.
1.18 anton 13832: * Data-Relocatable Image Files:: are better.
1.67 anton 13833: * Fully Relocatable Image Files:: better yet.
1.18 anton 13834: * Stack and Dictionary Sizes:: Setting the default sizes for an image.
1.29 crook 13835: * Running Image Files:: @code{gforth -i @i{file}} or @i{file}.
1.18 anton 13836: * Modifying the Startup Sequence:: and turnkey applications.
1.1 anton 13837: @end menu
13838:
1.18 anton 13839: @node Image Licensing Issues, Image File Background, Image Files, Image Files
13840: @section Image Licensing Issues
13841: @cindex license for images
13842: @cindex image license
13843:
13844: An image created with @code{gforthmi} (@pxref{gforthmi}) or
13845: @code{savesystem} (@pxref{Non-Relocatable Image Files}) includes the
13846: original image; i.e., according to copyright law it is a derived work of
13847: the original image.
13848:
13849: Since Gforth is distributed under the GNU GPL, the newly created image
13850: falls under the GNU GPL, too. In particular, this means that if you
13851: distribute the image, you have to make all of the sources for the image
13852: available, including those you wrote. For details see @ref{License, ,
13853: GNU General Public License (Section 3)}.
13854:
13855: If you create an image with @code{cross} (@pxref{cross.fs}), the image
13856: contains only code compiled from the sources you gave it; if none of
13857: these sources is under the GPL, the terms discussed above do not apply
13858: to the image. However, if your image needs an engine (a gforth binary)
13859: that is under the GPL, you should make sure that you distribute both in
13860: a way that is at most a @emph{mere aggregation}, if you don't want the
13861: terms of the GPL to apply to the image.
13862:
13863: @node Image File Background, Non-Relocatable Image Files, Image Licensing Issues, Image Files
1.1 anton 13864: @section Image File Background
13865: @cindex image file background
13866:
1.80 anton 13867: Gforth consists not only of primitives (in the engine), but also of
1.1 anton 13868: definitions written in Forth. Since the Forth compiler itself belongs to
13869: those definitions, it is not possible to start the system with the
1.80 anton 13870: engine and the Forth source alone. Therefore we provide the Forth
1.26 crook 13871: code as an image file in nearly executable form. When Gforth starts up,
13872: a C routine loads the image file into memory, optionally relocates the
13873: addresses, then sets up the memory (stacks etc.) according to
13874: information in the image file, and (finally) starts executing Forth
13875: code.
1.1 anton 13876:
13877: The image file variants represent different compromises between the
13878: goals of making it easy to generate image files and making them
13879: portable.
13880:
13881: @cindex relocation at run-time
1.26 crook 13882: Win32Forth 3.4 and Mitch Bradley's @code{cforth} use relocation at
1.1 anton 13883: run-time. This avoids many of the complications discussed below (image
13884: files are data relocatable without further ado), but costs performance
13885: (one addition per memory access).
13886:
13887: @cindex relocation at load-time
1.26 crook 13888: By contrast, the Gforth loader performs relocation at image load time. The
13889: loader also has to replace tokens that represent primitive calls with the
1.1 anton 13890: appropriate code-field addresses (or code addresses in the case of
13891: direct threading).
13892:
13893: There are three kinds of image files, with different degrees of
13894: relocatability: non-relocatable, data-relocatable, and fully relocatable
13895: image files.
13896:
13897: @cindex image file loader
13898: @cindex relocating loader
13899: @cindex loader for image files
13900: These image file variants have several restrictions in common; they are
13901: caused by the design of the image file loader:
13902:
13903: @itemize @bullet
13904: @item
13905: There is only one segment; in particular, this means, that an image file
13906: cannot represent @code{ALLOCATE}d memory chunks (and pointers to
1.26 crook 13907: them). The contents of the stacks are not represented, either.
1.1 anton 13908:
13909: @item
13910: The only kinds of relocation supported are: adding the same offset to
13911: all cells that represent data addresses; and replacing special tokens
13912: with code addresses or with pieces of machine code.
13913:
13914: If any complex computations involving addresses are performed, the
13915: results cannot be represented in the image file. Several applications that
13916: use such computations come to mind:
13917: @itemize @minus
13918: @item
13919: Hashing addresses (or data structures which contain addresses) for table
13920: lookup. If you use Gforth's @code{table}s or @code{wordlist}s for this
13921: purpose, you will have no problem, because the hash tables are
13922: recomputed automatically when the system is started. If you use your own
13923: hash tables, you will have to do something similar.
13924:
13925: @item
13926: There's a cute implementation of doubly-linked lists that uses
13927: @code{XOR}ed addresses. You could represent such lists as singly-linked
13928: in the image file, and restore the doubly-linked representation on
13929: startup.@footnote{In my opinion, though, you should think thrice before
13930: using a doubly-linked list (whatever implementation).}
13931:
13932: @item
13933: The code addresses of run-time routines like @code{docol:} cannot be
13934: represented in the image file (because their tokens would be replaced by
13935: machine code in direct threaded implementations). As a workaround,
13936: compute these addresses at run-time with @code{>code-address} from the
13937: executions tokens of appropriate words (see the definitions of
1.80 anton 13938: @code{docol:} and friends in @file{kernel/getdoers.fs}).
1.1 anton 13939:
13940: @item
13941: On many architectures addresses are represented in machine code in some
13942: shifted or mangled form. You cannot put @code{CODE} words that contain
13943: absolute addresses in this form in a relocatable image file. Workarounds
13944: are representing the address in some relative form (e.g., relative to
13945: the CFA, which is present in some register), or loading the address from
13946: a place where it is stored in a non-mangled form.
13947: @end itemize
13948: @end itemize
13949:
13950: @node Non-Relocatable Image Files, Data-Relocatable Image Files, Image File Background, Image Files
13951: @section Non-Relocatable Image Files
13952: @cindex non-relocatable image files
1.26 crook 13953: @cindex image file, non-relocatable
1.1 anton 13954:
13955: These files are simple memory dumps of the dictionary. They are specific
13956: to the executable (i.e., @file{gforth} file) they were created
13957: with. What's worse, they are specific to the place on which the
13958: dictionary resided when the image was created. Now, there is no
13959: guarantee that the dictionary will reside at the same place the next
13960: time you start Gforth, so there's no guarantee that a non-relocatable
13961: image will work the next time (Gforth will complain instead of crashing,
13962: though).
13963:
13964: You can create a non-relocatable image file with
13965:
1.44 crook 13966:
1.1 anton 13967: doc-savesystem
13968:
1.44 crook 13969:
1.1 anton 13970: @node Data-Relocatable Image Files, Fully Relocatable Image Files, Non-Relocatable Image Files, Image Files
13971: @section Data-Relocatable Image Files
13972: @cindex data-relocatable image files
1.26 crook 13973: @cindex image file, data-relocatable
1.1 anton 13974:
13975: These files contain relocatable data addresses, but fixed code addresses
13976: (instead of tokens). They are specific to the executable (i.e.,
13977: @file{gforth} file) they were created with. For direct threading on some
13978: architectures (e.g., the i386), data-relocatable images do not work. You
13979: get a data-relocatable image, if you use @file{gforthmi} with a
13980: Gforth binary that is not doubly indirect threaded (@pxref{Fully
13981: Relocatable Image Files}).
13982:
13983: @node Fully Relocatable Image Files, Stack and Dictionary Sizes, Data-Relocatable Image Files, Image Files
13984: @section Fully Relocatable Image Files
13985: @cindex fully relocatable image files
1.26 crook 13986: @cindex image file, fully relocatable
1.1 anton 13987:
13988: @cindex @file{kern*.fi}, relocatability
13989: @cindex @file{gforth.fi}, relocatability
13990: These image files have relocatable data addresses, and tokens for code
13991: addresses. They can be used with different binaries (e.g., with and
13992: without debugging) on the same machine, and even across machines with
13993: the same data formats (byte order, cell size, floating point
13994: format). However, they are usually specific to the version of Gforth
13995: they were created with. The files @file{gforth.fi} and @file{kernl*.fi}
13996: are fully relocatable.
13997:
13998: There are two ways to create a fully relocatable image file:
13999:
14000: @menu
1.29 crook 14001: * gforthmi:: The normal way
1.1 anton 14002: * cross.fs:: The hard way
14003: @end menu
14004:
14005: @node gforthmi, cross.fs, Fully Relocatable Image Files, Fully Relocatable Image Files
14006: @subsection @file{gforthmi}
14007: @cindex @file{comp-i.fs}
14008: @cindex @file{gforthmi}
14009:
14010: You will usually use @file{gforthmi}. If you want to create an
1.29 crook 14011: image @i{file} that contains everything you would load by invoking
14012: Gforth with @code{gforth @i{options}}, you simply say:
1.1 anton 14013: @example
1.29 crook 14014: gforthmi @i{file} @i{options}
1.1 anton 14015: @end example
14016:
14017: E.g., if you want to create an image @file{asm.fi} that has the file
14018: @file{asm.fs} loaded in addition to the usual stuff, you could do it
14019: like this:
14020:
14021: @example
14022: gforthmi asm.fi asm.fs
14023: @end example
14024:
1.27 crook 14025: @file{gforthmi} is implemented as a sh script and works like this: It
14026: produces two non-relocatable images for different addresses and then
14027: compares them. Its output reflects this: first you see the output (if
1.62 crook 14028: any) of the two Gforth invocations that produce the non-relocatable image
1.27 crook 14029: files, then you see the output of the comparing program: It displays the
14030: offset used for data addresses and the offset used for code addresses;
1.1 anton 14031: moreover, for each cell that cannot be represented correctly in the
1.44 crook 14032: image files, it displays a line like this:
1.1 anton 14033:
14034: @example
14035: 78DC BFFFFA50 BFFFFA40
14036: @end example
14037:
14038: This means that at offset $78dc from @code{forthstart}, one input image
14039: contains $bffffa50, and the other contains $bffffa40. Since these cells
14040: cannot be represented correctly in the output image, you should examine
14041: these places in the dictionary and verify that these cells are dead
14042: (i.e., not read before they are written).
1.39 anton 14043:
14044: @cindex --application, @code{gforthmi} option
14045: If you insert the option @code{--application} in front of the image file
14046: name, you will get an image that uses the @code{--appl-image} option
14047: instead of the @code{--image-file} option (@pxref{Invoking
14048: Gforth}). When you execute such an image on Unix (by typing the image
14049: name as command), the Gforth engine will pass all options to the image
14050: instead of trying to interpret them as engine options.
1.1 anton 14051:
1.27 crook 14052: If you type @file{gforthmi} with no arguments, it prints some usage
14053: instructions.
14054:
1.1 anton 14055: @cindex @code{savesystem} during @file{gforthmi}
14056: @cindex @code{bye} during @file{gforthmi}
14057: @cindex doubly indirect threaded code
1.44 crook 14058: @cindex environment variables
14059: @cindex @code{GFORTHD} -- environment variable
14060: @cindex @code{GFORTH} -- environment variable
1.1 anton 14061: @cindex @code{gforth-ditc}
1.29 crook 14062: There are a few wrinkles: After processing the passed @i{options}, the
1.1 anton 14063: words @code{savesystem} and @code{bye} must be visible. A special doubly
14064: indirect threaded version of the @file{gforth} executable is used for
1.62 crook 14065: creating the non-relocatable images; you can pass the exact filename of
1.1 anton 14066: this executable through the environment variable @code{GFORTHD}
14067: (default: @file{gforth-ditc}); if you pass a version that is not doubly
14068: indirect threaded, you will not get a fully relocatable image, but a
1.27 crook 14069: data-relocatable image (because there is no code address offset). The
14070: normal @file{gforth} executable is used for creating the relocatable
14071: image; you can pass the exact filename of this executable through the
14072: environment variable @code{GFORTH}.
1.1 anton 14073:
14074: @node cross.fs, , gforthmi, Fully Relocatable Image Files
14075: @subsection @file{cross.fs}
14076: @cindex @file{cross.fs}
14077: @cindex cross-compiler
14078: @cindex metacompiler
1.47 crook 14079: @cindex target compiler
1.1 anton 14080:
14081: You can also use @code{cross}, a batch compiler that accepts a Forth-like
1.47 crook 14082: programming language (@pxref{Cross Compiler}).
1.1 anton 14083:
1.47 crook 14084: @code{cross} allows you to create image files for machines with
1.1 anton 14085: different data sizes and data formats than the one used for generating
14086: the image file. You can also use it to create an application image that
14087: does not contain a Forth compiler. These features are bought with
14088: restrictions and inconveniences in programming. E.g., addresses have to
14089: be stored in memory with special words (@code{A!}, @code{A,}, etc.) in
14090: order to make the code relocatable.
14091:
14092:
14093: @node Stack and Dictionary Sizes, Running Image Files, Fully Relocatable Image Files, Image Files
14094: @section Stack and Dictionary Sizes
14095: @cindex image file, stack and dictionary sizes
14096: @cindex dictionary size default
14097: @cindex stack size default
14098:
14099: If you invoke Gforth with a command line flag for the size
14100: (@pxref{Invoking Gforth}), the size you specify is stored in the
14101: dictionary. If you save the dictionary with @code{savesystem} or create
14102: an image with @file{gforthmi}, this size will become the default
14103: for the resulting image file. E.g., the following will create a
1.21 crook 14104: fully relocatable version of @file{gforth.fi} with a 1MB dictionary:
1.1 anton 14105:
14106: @example
14107: gforthmi gforth.fi -m 1M
14108: @end example
14109:
14110: In other words, if you want to set the default size for the dictionary
14111: and the stacks of an image, just invoke @file{gforthmi} with the
14112: appropriate options when creating the image.
14113:
14114: @cindex stack size, cache-friendly
14115: Note: For cache-friendly behaviour (i.e., good performance), you should
14116: make the sizes of the stacks modulo, say, 2K, somewhat different. E.g.,
14117: the default stack sizes are: data: 16k (mod 2k=0); fp: 15.5k (mod
14118: 2k=1.5k); return: 15k(mod 2k=1k); locals: 14.5k (mod 2k=0.5k).
14119:
14120: @node Running Image Files, Modifying the Startup Sequence, Stack and Dictionary Sizes, Image Files
14121: @section Running Image Files
14122: @cindex running image files
14123: @cindex invoking image files
14124: @cindex image file invocation
14125:
14126: @cindex -i, invoke image file
14127: @cindex --image file, invoke image file
1.29 crook 14128: You can invoke Gforth with an image file @i{image} instead of the
1.1 anton 14129: default @file{gforth.fi} with the @code{-i} flag (@pxref{Invoking Gforth}):
14130: @example
1.29 crook 14131: gforth -i @i{image}
1.1 anton 14132: @end example
14133:
14134: @cindex executable image file
1.26 crook 14135: @cindex image file, executable
1.1 anton 14136: If your operating system supports starting scripts with a line of the
14137: form @code{#! ...}, you just have to type the image file name to start
14138: Gforth with this image file (note that the file extension @code{.fi} is
1.29 crook 14139: just a convention). I.e., to run Gforth with the image file @i{image},
14140: you can just type @i{image} instead of @code{gforth -i @i{image}}.
1.27 crook 14141: This works because every @code{.fi} file starts with a line of this
14142: format:
14143:
14144: @example
14145: #! /usr/local/bin/gforth-0.4.0 -i
14146: @end example
14147:
14148: The file and pathname for the Gforth engine specified on this line is
14149: the specific Gforth executable that it was built against; i.e. the value
14150: of the environment variable @code{GFORTH} at the time that
14151: @file{gforthmi} was executed.
1.1 anton 14152:
1.27 crook 14153: You can make use of the same shell capability to make a Forth source
14154: file into an executable. For example, if you place this text in a file:
1.26 crook 14155:
14156: @example
14157: #! /usr/local/bin/gforth
14158:
14159: ." Hello, world" CR
14160: bye
14161: @end example
14162:
14163: @noindent
1.27 crook 14164: and then make the file executable (chmod +x in Unix), you can run it
1.26 crook 14165: directly from the command line. The sequence @code{#!} is used in two
14166: ways; firstly, it is recognised as a ``magic sequence'' by the operating
1.29 crook 14167: system@footnote{The Unix kernel actually recognises two types of files:
14168: executable files and files of data, where the data is processed by an
14169: interpreter that is specified on the ``interpreter line'' -- the first
14170: line of the file, starting with the sequence #!. There may be a small
14171: limit (e.g., 32) on the number of characters that may be specified on
14172: the interpreter line.} secondly it is treated as a comment character by
14173: Gforth. Because of the second usage, a space is required between
1.80 anton 14174: @code{#!} and the path to the executable (moreover, some Unixes
14175: require the sequence @code{#! /}).
1.27 crook 14176:
14177: The disadvantage of this latter technique, compared with using
1.80 anton 14178: @file{gforthmi}, is that it is slightly slower; the Forth source code is
14179: compiled on-the-fly, each time the program is invoked.
1.26 crook 14180:
1.1 anton 14181: doc-#!
14182:
1.44 crook 14183:
1.1 anton 14184: @node Modifying the Startup Sequence, , Running Image Files, Image Files
14185: @section Modifying the Startup Sequence
14186: @cindex startup sequence for image file
14187: @cindex image file initialization sequence
14188: @cindex initialization sequence of image file
14189:
14190: You can add your own initialization to the startup sequence through the
1.26 crook 14191: deferred word @code{'cold}. @code{'cold} is invoked just before the
1.80 anton 14192: image-specific command line processing (i.e., loading files and
1.26 crook 14193: evaluating (@code{-e}) strings) starts.
1.1 anton 14194:
14195: A sequence for adding your initialization usually looks like this:
14196:
14197: @example
14198: :noname
14199: Defers 'cold \ do other initialization stuff (e.g., rehashing wordlists)
14200: ... \ your stuff
14201: ; IS 'cold
14202: @end example
14203:
14204: @cindex turnkey image files
1.26 crook 14205: @cindex image file, turnkey applications
1.1 anton 14206: You can make a turnkey image by letting @code{'cold} execute a word
14207: (your turnkey application) that never returns; instead, it exits Gforth
14208: via @code{bye} or @code{throw}.
14209:
14210: @cindex command-line arguments, access
14211: @cindex arguments on the command line, access
14212: You can access the (image-specific) command-line arguments through the
1.26 crook 14213: variables @code{argc} and @code{argv}. @code{arg} provides convenient
1.1 anton 14214: access to @code{argv}.
14215:
1.26 crook 14216: If @code{'cold} exits normally, Gforth processes the command-line
14217: arguments as files to be loaded and strings to be evaluated. Therefore,
14218: @code{'cold} should remove the arguments it has used in this case.
14219:
1.44 crook 14220:
14221:
1.26 crook 14222: doc-'cold
1.1 anton 14223: doc-argc
14224: doc-argv
14225: doc-arg
14226:
14227:
1.44 crook 14228:
1.1 anton 14229: @c ******************************************************************
1.13 pazsan 14230: @node Engine, Binding to System Library, Image Files, Top
1.1 anton 14231: @chapter Engine
14232: @cindex engine
14233: @cindex virtual machine
14234:
1.26 crook 14235: Reading this chapter is not necessary for programming with Gforth. It
1.1 anton 14236: may be helpful for finding your way in the Gforth sources.
14237:
1.66 anton 14238: The ideas in this section have also been published in Bernd Paysan,
14239: @cite{ANS fig/GNU/??? Forth} (in German), Forth-Tagung '93 and M. Anton
14240: Ertl, @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl93.ps.Z, A
14241: Portable Forth Engine}}, EuroForth '93.
1.1 anton 14242:
14243: @menu
14244: * Portability::
14245: * Threading::
14246: * Primitives::
14247: * Performance::
14248: @end menu
14249:
14250: @node Portability, Threading, Engine, Engine
14251: @section Portability
14252: @cindex engine portability
14253:
1.26 crook 14254: An important goal of the Gforth Project is availability across a wide
14255: range of personal machines. fig-Forth, and, to a lesser extent, F83,
14256: achieved this goal by manually coding the engine in assembly language
14257: for several then-popular processors. This approach is very
14258: labor-intensive and the results are short-lived due to progress in
14259: computer architecture.
1.1 anton 14260:
14261: @cindex C, using C for the engine
14262: Others have avoided this problem by coding in C, e.g., Mitch Bradley
14263: (cforth), Mikael Patel (TILE) and Dirk Zoller (pfe). This approach is
14264: particularly popular for UNIX-based Forths due to the large variety of
14265: architectures of UNIX machines. Unfortunately an implementation in C
14266: does not mix well with the goals of efficiency and with using
14267: traditional techniques: Indirect or direct threading cannot be expressed
14268: in C, and switch threading, the fastest technique available in C, is
14269: significantly slower. Another problem with C is that it is very
14270: cumbersome to express double integer arithmetic.
14271:
14272: @cindex GNU C for the engine
14273: @cindex long long
14274: Fortunately, there is a portable language that does not have these
14275: limitations: GNU C, the version of C processed by the GNU C compiler
14276: (@pxref{C Extensions, , Extensions to the C Language Family, gcc.info,
14277: GNU C Manual}). Its labels as values feature (@pxref{Labels as Values, ,
14278: Labels as Values, gcc.info, GNU C Manual}) makes direct and indirect
14279: threading possible, its @code{long long} type (@pxref{Long Long, ,
14280: Double-Word Integers, gcc.info, GNU C Manual}) corresponds to Forth's
14281: double numbers@footnote{Unfortunately, long longs are not implemented
14282: properly on all machines (e.g., on alpha-osf1, long longs are only 64
14283: bits, the same size as longs (and pointers), but they should be twice as
1.4 anton 14284: long according to @pxref{Long Long, , Double-Word Integers, gcc.info, GNU
1.1 anton 14285: C Manual}). So, we had to implement doubles in C after all. Still, on
14286: most machines we can use long longs and achieve better performance than
14287: with the emulation package.}. GNU C is available for free on all
14288: important (and many unimportant) UNIX machines, VMS, 80386s running
14289: MS-DOS, the Amiga, and the Atari ST, so a Forth written in GNU C can run
14290: on all these machines.
14291:
14292: Writing in a portable language has the reputation of producing code that
14293: is slower than assembly. For our Forth engine we repeatedly looked at
14294: the code produced by the compiler and eliminated most compiler-induced
14295: inefficiencies by appropriate changes in the source code.
14296:
14297: @cindex explicit register declarations
14298: @cindex --enable-force-reg, configuration flag
14299: @cindex -DFORCE_REG
14300: However, register allocation cannot be portably influenced by the
14301: programmer, leading to some inefficiencies on register-starved
14302: machines. We use explicit register declarations (@pxref{Explicit Reg
14303: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) to
14304: improve the speed on some machines. They are turned on by using the
14305: configuration flag @code{--enable-force-reg} (@code{gcc} switch
14306: @code{-DFORCE_REG}). Unfortunately, this feature not only depends on the
14307: machine, but also on the compiler version: On some machines some
14308: compiler versions produce incorrect code when certain explicit register
14309: declarations are used. So by default @code{-DFORCE_REG} is not used.
14310:
14311: @node Threading, Primitives, Portability, Engine
14312: @section Threading
14313: @cindex inner interpreter implementation
14314: @cindex threaded code implementation
14315:
14316: @cindex labels as values
14317: GNU C's labels as values extension (available since @code{gcc-2.0},
14318: @pxref{Labels as Values, , Labels as Values, gcc.info, GNU C Manual})
1.29 crook 14319: makes it possible to take the address of @i{label} by writing
14320: @code{&&@i{label}}. This address can then be used in a statement like
14321: @code{goto *@i{address}}. I.e., @code{goto *&&x} is the same as
1.1 anton 14322: @code{goto x}.
14323:
1.26 crook 14324: @cindex @code{NEXT}, indirect threaded
1.1 anton 14325: @cindex indirect threaded inner interpreter
14326: @cindex inner interpreter, indirect threaded
1.26 crook 14327: With this feature an indirect threaded @code{NEXT} looks like:
1.1 anton 14328: @example
14329: cfa = *ip++;
14330: ca = *cfa;
14331: goto *ca;
14332: @end example
14333: @cindex instruction pointer
14334: For those unfamiliar with the names: @code{ip} is the Forth instruction
14335: pointer; the @code{cfa} (code-field address) corresponds to ANS Forths
14336: execution token and points to the code field of the next word to be
14337: executed; The @code{ca} (code address) fetched from there points to some
14338: executable code, e.g., a primitive or the colon definition handler
14339: @code{docol}.
14340:
1.26 crook 14341: @cindex @code{NEXT}, direct threaded
1.1 anton 14342: @cindex direct threaded inner interpreter
14343: @cindex inner interpreter, direct threaded
14344: Direct threading is even simpler:
14345: @example
14346: ca = *ip++;
14347: goto *ca;
14348: @end example
14349:
14350: Of course we have packaged the whole thing neatly in macros called
1.26 crook 14351: @code{NEXT} and @code{NEXT1} (the part of @code{NEXT} after fetching the cfa).
1.1 anton 14352:
14353: @menu
14354: * Scheduling::
14355: * Direct or Indirect Threaded?::
14356: * DOES>::
14357: @end menu
14358:
14359: @node Scheduling, Direct or Indirect Threaded?, Threading, Threading
14360: @subsection Scheduling
14361: @cindex inner interpreter optimization
14362:
14363: There is a little complication: Pipelined and superscalar processors,
14364: i.e., RISC and some modern CISC machines can process independent
14365: instructions while waiting for the results of an instruction. The
14366: compiler usually reorders (schedules) the instructions in a way that
14367: achieves good usage of these delay slots. However, on our first tries
14368: the compiler did not do well on scheduling primitives. E.g., for
14369: @code{+} implemented as
14370: @example
14371: n=sp[0]+sp[1];
14372: sp++;
14373: sp[0]=n;
14374: NEXT;
14375: @end example
1.81 anton 14376: the @code{NEXT} comes strictly after the other code, i.e., there is
14377: nearly no scheduling. After a little thought the problem becomes clear:
14378: The compiler cannot know that @code{sp} and @code{ip} point to different
1.21 crook 14379: addresses (and the version of @code{gcc} we used would not know it even
14380: if it was possible), so it could not move the load of the cfa above the
14381: store to the TOS. Indeed the pointers could be the same, if code on or
14382: very near the top of stack were executed. In the interest of speed we
14383: chose to forbid this probably unused ``feature'' and helped the compiler
1.81 anton 14384: in scheduling: @code{NEXT} is divided into several parts:
14385: @code{NEXT_P0}, @code{NEXT_P1} and @code{NEXT_P2}). @code{+} now looks
14386: like:
1.1 anton 14387: @example
1.81 anton 14388: NEXT_P0;
1.1 anton 14389: n=sp[0]+sp[1];
14390: sp++;
14391: NEXT_P1;
14392: sp[0]=n;
14393: NEXT_P2;
14394: @end example
14395:
1.81 anton 14396: There are various schemes that distribute the different operations of
14397: NEXT between these parts in several ways; in general, different schemes
14398: perform best on different processors. We use a scheme for most
14399: architectures that performs well for most processors of this
14400: architecture; in the furture we may switch to benchmarking and chosing
14401: the scheme on installation time.
14402:
1.1 anton 14403:
14404: @node Direct or Indirect Threaded?, DOES>, Scheduling, Threading
14405: @subsection Direct or Indirect Threaded?
14406: @cindex threading, direct or indirect?
14407:
14408: @cindex -DDIRECT_THREADED
14409: Both! After packaging the nasty details in macro definitions we
14410: realized that we could switch between direct and indirect threading by
14411: simply setting a compilation flag (@code{-DDIRECT_THREADED}) and
14412: defining a few machine-specific macros for the direct-threading case.
14413: On the Forth level we also offer access words that hide the
14414: differences between the threading methods (@pxref{Threading Words}).
14415:
14416: Indirect threading is implemented completely machine-independently.
14417: Direct threading needs routines for creating jumps to the executable
1.21 crook 14418: code (e.g. to @code{docol} or @code{dodoes}). These routines are inherently
14419: machine-dependent, but they do not amount to many source lines. Therefore,
14420: even porting direct threading to a new machine requires little effort.
1.1 anton 14421:
14422: @cindex --enable-indirect-threaded, configuration flag
14423: @cindex --enable-direct-threaded, configuration flag
14424: The default threading method is machine-dependent. You can enforce a
14425: specific threading method when building Gforth with the configuration
14426: flag @code{--enable-direct-threaded} or
14427: @code{--enable-indirect-threaded}. Note that direct threading is not
14428: supported on all machines.
14429:
14430: @node DOES>, , Direct or Indirect Threaded?, Threading
14431: @subsection DOES>
14432: @cindex @code{DOES>} implementation
14433:
1.26 crook 14434: @cindex @code{dodoes} routine
14435: @cindex @code{DOES>}-code
1.1 anton 14436: One of the most complex parts of a Forth engine is @code{dodoes}, i.e.,
14437: the chunk of code executed by every word defined by a
14438: @code{CREATE}...@code{DOES>} pair. The main problem here is: How to find
14439: the Forth code to be executed, i.e. the code after the
1.26 crook 14440: @code{DOES>} (the @code{DOES>}-code)? There are two solutions:
1.1 anton 14441:
1.21 crook 14442: In fig-Forth the code field points directly to the @code{dodoes} and the
1.45 crook 14443: @code{DOES>}-code address is stored in the cell after the code address (i.e. at
1.29 crook 14444: @code{@i{CFA} cell+}). It may seem that this solution is illegal in
1.1 anton 14445: the Forth-79 and all later standards, because in fig-Forth this address
14446: lies in the body (which is illegal in these standards). However, by
14447: making the code field larger for all words this solution becomes legal
14448: again. We use this approach for the indirect threaded version and for
14449: direct threading on some machines. Leaving a cell unused in most words
14450: is a bit wasteful, but on the machines we are targeting this is hardly a
14451: problem. The other reason for having a code field size of two cells is
14452: to avoid having different image files for direct and indirect threaded
14453: systems (direct threaded systems require two-cell code fields on many
14454: machines).
14455:
1.26 crook 14456: @cindex @code{DOES>}-handler
1.1 anton 14457: The other approach is that the code field points or jumps to the cell
1.26 crook 14458: after @code{DOES>}. In this variant there is a jump to @code{dodoes} at
14459: this address (the @code{DOES>}-handler). @code{dodoes} can then get the
14460: @code{DOES>}-code address by computing the code address, i.e., the address of
1.45 crook 14461: the jump to @code{dodoes}, and add the length of that jump field. A variant of
1.1 anton 14462: this is to have a call to @code{dodoes} after the @code{DOES>}; then the
14463: return address (which can be found in the return register on RISCs) is
1.26 crook 14464: the @code{DOES>}-code address. Since the two cells available in the code field
1.1 anton 14465: are used up by the jump to the code address in direct threading on many
14466: architectures, we use this approach for direct threading on these
14467: architectures. We did not want to add another cell to the code field.
14468:
14469: @node Primitives, Performance, Threading, Engine
14470: @section Primitives
14471: @cindex primitives, implementation
14472: @cindex virtual machine instructions, implementation
14473:
14474: @menu
14475: * Automatic Generation::
14476: * TOS Optimization::
14477: * Produced code::
14478: @end menu
14479:
14480: @node Automatic Generation, TOS Optimization, Primitives, Primitives
14481: @subsection Automatic Generation
14482: @cindex primitives, automatic generation
14483:
14484: @cindex @file{prims2x.fs}
14485: Since the primitives are implemented in a portable language, there is no
14486: longer any need to minimize the number of primitives. On the contrary,
14487: having many primitives has an advantage: speed. In order to reduce the
14488: number of errors in primitives and to make programming them easier, we
14489: provide a tool, the primitive generator (@file{prims2x.fs}), that
14490: automatically generates most (and sometimes all) of the C code for a
14491: primitive from the stack effect notation. The source for a primitive
14492: has the following form:
14493:
14494: @cindex primitive source format
14495: @format
1.58 anton 14496: @i{Forth-name} ( @i{stack-effect} ) @i{category} [@i{pronounc.}]
1.29 crook 14497: [@code{""}@i{glossary entry}@code{""}]
14498: @i{C code}
1.1 anton 14499: [@code{:}
1.29 crook 14500: @i{Forth code}]
1.1 anton 14501: @end format
14502:
14503: The items in brackets are optional. The category and glossary fields
14504: are there for generating the documentation, the Forth code is there
14505: for manual implementations on machines without GNU C. E.g., the source
14506: for the primitive @code{+} is:
14507: @example
1.58 anton 14508: + ( n1 n2 -- n ) core plus
1.1 anton 14509: n = n1+n2;
14510: @end example
14511:
14512: This looks like a specification, but in fact @code{n = n1+n2} is C
14513: code. Our primitive generation tool extracts a lot of information from
14514: the stack effect notations@footnote{We use a one-stack notation, even
14515: though we have separate data and floating-point stacks; The separate
14516: notation can be generated easily from the unified notation.}: The number
14517: of items popped from and pushed on the stack, their type, and by what
14518: name they are referred to in the C code. It then generates a C code
14519: prelude and postlude for each primitive. The final C code for @code{+}
14520: looks like this:
14521:
14522: @example
1.46 pazsan 14523: I_plus: /* + ( n1 n2 -- n ) */ /* label, stack effect */
1.1 anton 14524: /* */ /* documentation */
1.81 anton 14525: NAME("+") /* debugging output (with -DDEBUG) */
1.1 anton 14526: @{
14527: DEF_CA /* definition of variable ca (indirect threading) */
14528: Cell n1; /* definitions of variables */
14529: Cell n2;
14530: Cell n;
1.81 anton 14531: NEXT_P0; /* NEXT part 0 */
1.1 anton 14532: n1 = (Cell) sp[1]; /* input */
14533: n2 = (Cell) TOS;
14534: sp += 1; /* stack adjustment */
14535: @{
14536: n = n1+n2; /* C code taken from the source */
14537: @}
14538: NEXT_P1; /* NEXT part 1 */
14539: TOS = (Cell)n; /* output */
14540: NEXT_P2; /* NEXT part 2 */
14541: @}
14542: @end example
14543:
14544: This looks long and inefficient, but the GNU C compiler optimizes quite
14545: well and produces optimal code for @code{+} on, e.g., the R3000 and the
14546: HP RISC machines: Defining the @code{n}s does not produce any code, and
14547: using them as intermediate storage also adds no cost.
14548:
1.26 crook 14549: There are also other optimizations that are not illustrated by this
14550: example: assignments between simple variables are usually for free (copy
1.1 anton 14551: propagation). If one of the stack items is not used by the primitive
14552: (e.g. in @code{drop}), the compiler eliminates the load from the stack
14553: (dead code elimination). On the other hand, there are some things that
14554: the compiler does not do, therefore they are performed by
14555: @file{prims2x.fs}: The compiler does not optimize code away that stores
14556: a stack item to the place where it just came from (e.g., @code{over}).
14557:
14558: While programming a primitive is usually easy, there are a few cases
14559: where the programmer has to take the actions of the generator into
14560: account, most notably @code{?dup}, but also words that do not (always)
1.26 crook 14561: fall through to @code{NEXT}.
1.1 anton 14562:
14563: @node TOS Optimization, Produced code, Automatic Generation, Primitives
14564: @subsection TOS Optimization
14565: @cindex TOS optimization for primitives
14566: @cindex primitives, keeping the TOS in a register
14567:
14568: An important optimization for stack machine emulators, e.g., Forth
14569: engines, is keeping one or more of the top stack items in
1.29 crook 14570: registers. If a word has the stack effect @i{in1}...@i{inx} @code{--}
14571: @i{out1}...@i{outy}, keeping the top @i{n} items in registers
1.1 anton 14572: @itemize @bullet
14573: @item
1.29 crook 14574: is better than keeping @i{n-1} items, if @i{x>=n} and @i{y>=n},
1.1 anton 14575: due to fewer loads from and stores to the stack.
1.29 crook 14576: @item is slower than keeping @i{n-1} items, if @i{x<>y} and @i{x<n} and
14577: @i{y<n}, due to additional moves between registers.
1.1 anton 14578: @end itemize
14579:
14580: @cindex -DUSE_TOS
14581: @cindex -DUSE_NO_TOS
14582: In particular, keeping one item in a register is never a disadvantage,
14583: if there are enough registers. Keeping two items in registers is a
14584: disadvantage for frequent words like @code{?branch}, constants,
14585: variables, literals and @code{i}. Therefore our generator only produces
14586: code that keeps zero or one items in registers. The generated C code
14587: covers both cases; the selection between these alternatives is made at
14588: C-compile time using the switch @code{-DUSE_TOS}. @code{TOS} in the C
14589: code for @code{+} is just a simple variable name in the one-item case,
14590: otherwise it is a macro that expands into @code{sp[0]}. Note that the
14591: GNU C compiler tries to keep simple variables like @code{TOS} in
14592: registers, and it usually succeeds, if there are enough registers.
14593:
14594: @cindex -DUSE_FTOS
14595: @cindex -DUSE_NO_FTOS
14596: The primitive generator performs the TOS optimization for the
14597: floating-point stack, too (@code{-DUSE_FTOS}). For floating-point
14598: operations the benefit of this optimization is even larger:
14599: floating-point operations take quite long on most processors, but can be
14600: performed in parallel with other operations as long as their results are
14601: not used. If the FP-TOS is kept in a register, this works. If
14602: it is kept on the stack, i.e., in memory, the store into memory has to
14603: wait for the result of the floating-point operation, lengthening the
14604: execution time of the primitive considerably.
14605:
14606: The TOS optimization makes the automatic generation of primitives a
14607: bit more complicated. Just replacing all occurrences of @code{sp[0]} by
14608: @code{TOS} is not sufficient. There are some special cases to
14609: consider:
14610: @itemize @bullet
14611: @item In the case of @code{dup ( w -- w w )} the generator must not
14612: eliminate the store to the original location of the item on the stack,
14613: if the TOS optimization is turned on.
14614: @item Primitives with stack effects of the form @code{--}
1.29 crook 14615: @i{out1}...@i{outy} must store the TOS to the stack at the start.
14616: Likewise, primitives with the stack effect @i{in1}...@i{inx} @code{--}
1.1 anton 14617: must load the TOS from the stack at the end. But for the null stack
14618: effect @code{--} no stores or loads should be generated.
14619: @end itemize
14620:
14621: @node Produced code, , TOS Optimization, Primitives
14622: @subsection Produced code
14623: @cindex primitives, assembly code listing
14624:
14625: @cindex @file{engine.s}
14626: To see what assembly code is produced for the primitives on your machine
14627: with your compiler and your flag settings, type @code{make engine.s} and
1.81 anton 14628: look at the resulting file @file{engine.s}. Alternatively, you can also
14629: disassemble the code of primitives with @code{see} on some architectures.
1.1 anton 14630:
14631: @node Performance, , Primitives, Engine
14632: @section Performance
14633: @cindex performance of some Forth interpreters
14634: @cindex engine performance
14635: @cindex benchmarking Forth systems
14636: @cindex Gforth performance
14637:
14638: On RISCs the Gforth engine is very close to optimal; i.e., it is usually
14639: impossible to write a significantly faster engine.
14640:
14641: On register-starved machines like the 386 architecture processors
14642: improvements are possible, because @code{gcc} does not utilize the
14643: registers as well as a human, even with explicit register declarations;
14644: e.g., Bernd Beuster wrote a Forth system fragment in assembly language
14645: and hand-tuned it for the 486; this system is 1.19 times faster on the
14646: Sieve benchmark on a 486DX2/66 than Gforth compiled with
1.40 anton 14647: @code{gcc-2.6.3} with @code{-DFORCE_REG}. The situation has improved
14648: with gcc-2.95 and gforth-0.4.9; now the most important virtual machine
14649: registers fit in real registers (and we can even afford to use the TOS
14650: optimization), resulting in a speedup of 1.14 on the sieve over the
14651: earlier results.
1.1 anton 14652:
14653: @cindex Win32Forth performance
14654: @cindex NT Forth performance
14655: @cindex eforth performance
14656: @cindex ThisForth performance
14657: @cindex PFE performance
14658: @cindex TILE performance
1.81 anton 14659: The potential advantage of assembly language implementations is not
14660: necessarily realized in complete Forth systems: We compared Gforth-0.4.9
14661: (direct threaded, compiled with @code{gcc-2.95.1} and
14662: @code{-DFORCE_REG}) with Win32Forth 1.2093 (newer versions are
14663: reportedly much faster), LMI's NT Forth (Beta, May 1994) and Eforth
14664: (with and without peephole (aka pinhole) optimization of the threaded
14665: code); all these systems were written in assembly language. We also
14666: compared Gforth with three systems written in C: PFE-0.9.14 (compiled
14667: with @code{gcc-2.6.3} with the default configuration for Linux:
14668: @code{-O2 -fomit-frame-pointer -DUSE_REGS -DUNROLL_NEXT}), ThisForth
14669: Beta (compiled with @code{gcc-2.6.3 -O3 -fomit-frame-pointer}; ThisForth
14670: employs peephole optimization of the threaded code) and TILE (compiled
14671: with @code{make opt}). We benchmarked Gforth, PFE, ThisForth and TILE on
14672: a 486DX2/66 under Linux. Kenneth O'Heskin kindly provided the results
14673: for Win32Forth and NT Forth on a 486DX2/66 with similar memory
14674: performance under Windows NT. Marcel Hendrix ported Eforth to Linux,
14675: then extended it to run the benchmarks, added the peephole optimizer,
14676: ran the benchmarks and reported the results.
1.40 anton 14677:
1.1 anton 14678: We used four small benchmarks: the ubiquitous Sieve; bubble-sorting and
14679: matrix multiplication come from the Stanford integer benchmarks and have
14680: been translated into Forth by Martin Fraeman; we used the versions
14681: included in the TILE Forth package, but with bigger data set sizes; and
14682: a recursive Fibonacci number computation for benchmarking calling
14683: performance. The following table shows the time taken for the benchmarks
14684: scaled by the time taken by Gforth (in other words, it shows the speedup
14685: factor that Gforth achieved over the other systems).
14686:
14687: @example
1.40 anton 14688: relative Win32- NT eforth This-
1.1 anton 14689: time Gforth Forth Forth eforth +opt PFE Forth TILE
1.81 anton 14690: sieve 1.00 1.60 1.32 1.60 0.98 1.82 3.67 9.91
14691: bubble 1.00 1.55 1.66 1.75 1.04 1.78 4.58
14692: matmul 1.00 1.71 1.57 1.69 0.86 1.83 4.74
14693: fib 1.00 1.76 1.54 1.41 1.00 2.01 3.45 4.96
1.1 anton 14694: @end example
14695:
1.26 crook 14696: You may be quite surprised by the good performance of Gforth when
14697: compared with systems written in assembly language. One important reason
14698: for the disappointing performance of these other systems is probably
14699: that they are not written optimally for the 486 (e.g., they use the
14700: @code{lods} instruction). In addition, Win32Forth uses a comfortable,
14701: but costly method for relocating the Forth image: like @code{cforth}, it
14702: computes the actual addresses at run time, resulting in two address
14703: computations per @code{NEXT} (@pxref{Image File Background}).
14704:
1.40 anton 14705: Only Eforth with the peephole optimizer performs comparable to
14706: Gforth. The speedups achieved with peephole optimization of threaded
14707: code are quite remarkable. Adding a peephole optimizer to Gforth should
14708: cause similar speedups.
1.1 anton 14709:
14710: The speedup of Gforth over PFE, ThisForth and TILE can be easily
14711: explained with the self-imposed restriction of the latter systems to
14712: standard C, which makes efficient threading impossible (however, the
1.4 anton 14713: measured implementation of PFE uses a GNU C extension: @pxref{Global Reg
1.1 anton 14714: Vars, , Defining Global Register Variables, gcc.info, GNU C Manual}).
14715: Moreover, current C compilers have a hard time optimizing other aspects
14716: of the ThisForth and the TILE source.
14717:
1.26 crook 14718: The performance of Gforth on 386 architecture processors varies widely
14719: with the version of @code{gcc} used. E.g., @code{gcc-2.5.8} failed to
14720: allocate any of the virtual machine registers into real machine
14721: registers by itself and would not work correctly with explicit register
1.40 anton 14722: declarations, giving a 1.5 times slower engine (on a 486DX2/66 running
1.26 crook 14723: the Sieve) than the one measured above.
1.1 anton 14724:
1.26 crook 14725: Note that there have been several releases of Win32Forth since the
14726: release presented here, so the results presented above may have little
1.40 anton 14727: predictive value for the performance of Win32Forth today (results for
14728: the current release on an i486DX2/66 are welcome).
1.1 anton 14729:
14730: @cindex @file{Benchres}
1.66 anton 14731: In
14732: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl&maierhofer95.ps.gz,
14733: Translating Forth to Efficient C}} by M. Anton Ertl and Martin
1.1 anton 14734: Maierhofer (presented at EuroForth '95), an indirect threaded version of
1.66 anton 14735: Gforth is compared with Win32Forth, NT Forth, PFE, ThisForth, and
14736: several native code systems; that version of Gforth is slower on a 486
14737: than the direct threaded version used here. You can find a newer version
14738: of these measurements at
1.47 crook 14739: @uref{http://www.complang.tuwien.ac.at/forth/performance.html}. You can
1.1 anton 14740: find numbers for Gforth on various machines in @file{Benchres}.
14741:
1.26 crook 14742: @c ******************************************************************
1.13 pazsan 14743: @node Binding to System Library, Cross Compiler, Engine, Top
1.14 pazsan 14744: @chapter Binding to System Library
1.13 pazsan 14745:
14746: @node Cross Compiler, Bugs, Binding to System Library, Top
1.14 pazsan 14747: @chapter Cross Compiler
1.47 crook 14748: @cindex @file{cross.fs}
14749: @cindex cross-compiler
14750: @cindex metacompiler
14751: @cindex target compiler
1.13 pazsan 14752:
1.46 pazsan 14753: The cross compiler is used to bootstrap a Forth kernel. Since Gforth is
14754: mostly written in Forth, including crucial parts like the outer
14755: interpreter and compiler, it needs compiled Forth code to get
14756: started. The cross compiler allows to create new images for other
14757: architectures, even running under another Forth system.
1.13 pazsan 14758:
14759: @menu
1.67 anton 14760: * Using the Cross Compiler::
14761: * How the Cross Compiler Works::
1.13 pazsan 14762: @end menu
14763:
1.21 crook 14764: @node Using the Cross Compiler, How the Cross Compiler Works, Cross Compiler, Cross Compiler
1.14 pazsan 14765: @section Using the Cross Compiler
1.46 pazsan 14766:
14767: The cross compiler uses a language that resembles Forth, but isn't. The
14768: main difference is that you can execute Forth code after definition,
14769: while you usually can't execute the code compiled by cross, because the
14770: code you are compiling is typically for a different computer than the
14771: one you are compiling on.
14772:
1.81 anton 14773: @c anton: This chapter is somewhat different from waht I would expect: I
14774: @c would expect an explanation of the cross language and how to create an
14775: @c application image with it. The section explains some aspects of
14776: @c creating a Gforth kernel.
14777:
1.46 pazsan 14778: The Makefile is already set up to allow you to create kernels for new
14779: architectures with a simple make command. The generic kernels using the
14780: GCC compiled virtual machine are created in the normal build process
14781: with @code{make}. To create a embedded Gforth executable for e.g. the
14782: 8086 processor (running on a DOS machine), type
14783:
14784: @example
14785: make kernl-8086.fi
14786: @end example
14787:
14788: This will use the machine description from the @file{arch/8086}
14789: directory to create a new kernel. A machine file may look like that:
14790:
14791: @example
14792: \ Parameter for target systems 06oct92py
14793:
14794: 4 Constant cell \ cell size in bytes
14795: 2 Constant cell<< \ cell shift to bytes
14796: 5 Constant cell>bit \ cell shift to bits
14797: 8 Constant bits/char \ bits per character
14798: 8 Constant bits/byte \ bits per byte [default: 8]
14799: 8 Constant float \ bytes per float
14800: 8 Constant /maxalign \ maximum alignment in bytes
14801: false Constant bigendian \ byte order
14802: ( true=big, false=little )
14803:
14804: include machpc.fs \ feature list
14805: @end example
14806:
14807: This part is obligatory for the cross compiler itself, the feature list
14808: is used by the kernel to conditionally compile some features in and out,
14809: depending on whether the target supports these features.
14810:
14811: There are some optional features, if you define your own primitives,
14812: have an assembler, or need special, nonstandard preparation to make the
1.81 anton 14813: boot process work. @code{asm-include} includes an assembler,
1.46 pazsan 14814: @code{prims-include} includes primitives, and @code{>boot} prepares for
14815: booting.
14816:
14817: @example
14818: : asm-include ." Include assembler" cr
14819: s" arch/8086/asm.fs" included ;
14820:
14821: : prims-include ." Include primitives" cr
14822: s" arch/8086/prim.fs" included ;
14823:
14824: : >boot ." Prepare booting" cr
14825: s" ' boot >body into-forth 1+ !" evaluate ;
14826: @end example
14827:
14828: These words are used as sort of macro during the cross compilation in
1.81 anton 14829: the file @file{kernel/main.fs}. Instead of using these macros, it would
1.46 pazsan 14830: be possible --- but more complicated --- to write a new kernel project
14831: file, too.
14832:
14833: @file{kernel/main.fs} expects the machine description file name on the
14834: stack; the cross compiler itself (@file{cross.fs}) assumes that either
14835: @code{mach-file} leaves a counted string on the stack, or
14836: @code{machine-file} leaves an address, count pair of the filename on the
14837: stack.
14838:
14839: The feature list is typically controlled using @code{SetValue}, generic
14840: files that are used by several projects can use @code{DefaultValue}
14841: instead. Both functions work like @code{Value}, when the value isn't
14842: defined, but @code{SetValue} works like @code{to} if the value is
14843: defined, and @code{DefaultValue} doesn't set anything, if the value is
14844: defined.
14845:
14846: @example
14847: \ generic mach file for pc gforth 03sep97jaw
14848:
14849: true DefaultValue NIL \ relocating
14850:
14851: >ENVIRON
14852:
14853: true DefaultValue file \ controls the presence of the
14854: \ file access wordset
14855: true DefaultValue OS \ flag to indicate a operating system
14856:
14857: true DefaultValue prims \ true: primitives are c-code
14858:
14859: true DefaultValue floating \ floating point wordset is present
14860:
14861: true DefaultValue glocals \ gforth locals are present
14862: \ will be loaded
14863: true DefaultValue dcomps \ double number comparisons
14864:
14865: true DefaultValue hash \ hashing primitives are loaded/present
14866:
14867: true DefaultValue xconds \ used together with glocals,
14868: \ special conditionals supporting gforths'
14869: \ local variables
14870: true DefaultValue header \ save a header information
14871:
14872: true DefaultValue backtrace \ enables backtrace code
14873:
14874: false DefaultValue ec
14875: false DefaultValue crlf
14876:
14877: cell 2 = [IF] &32 [ELSE] &256 [THEN] KB DefaultValue kernel-size
14878:
14879: &16 KB DefaultValue stack-size
14880: &15 KB &512 + DefaultValue fstack-size
14881: &15 KB DefaultValue rstack-size
14882: &14 KB &512 + DefaultValue lstack-size
14883: @end example
1.13 pazsan 14884:
1.48 anton 14885: @node How the Cross Compiler Works, , Using the Cross Compiler, Cross Compiler
1.14 pazsan 14886: @section How the Cross Compiler Works
1.13 pazsan 14887:
14888: @node Bugs, Origin, Cross Compiler, Top
1.21 crook 14889: @appendix Bugs
1.1 anton 14890: @cindex bug reporting
14891:
1.21 crook 14892: Known bugs are described in the file @file{BUGS} in the Gforth distribution.
1.1 anton 14893:
14894: If you find a bug, please send a bug report to
1.33 anton 14895: @email{bug-gforth@@gnu.org}. A bug report should include this
1.21 crook 14896: information:
14897:
14898: @itemize @bullet
14899: @item
1.81 anton 14900: A program (or a sequence of keyboard commands) that reproduces the bug.
14901: @item
14902: A description of what you think constitutes the buggy behaviour.
14903: @item
1.21 crook 14904: The Gforth version used (it is announced at the start of an
14905: interactive Gforth session).
14906: @item
14907: The machine and operating system (on Unix
14908: systems @code{uname -a} will report this information).
14909: @item
1.81 anton 14910: The installation options (you can find the configure options at the
14911: start of @file{config.status}) and configuration (@code{configure}
14912: output or @file{config.cache}).
1.21 crook 14913: @item
14914: A complete list of changes (if any) you (or your installer) have made to the
14915: Gforth sources.
14916: @end itemize
1.1 anton 14917:
14918: For a thorough guide on reporting bugs read @ref{Bug Reporting, , How
14919: to Report Bugs, gcc.info, GNU C Manual}.
14920:
14921:
1.21 crook 14922: @node Origin, Forth-related information, Bugs, Top
14923: @appendix Authors and Ancestors of Gforth
1.1 anton 14924:
14925: @section Authors and Contributors
14926: @cindex authors of Gforth
14927: @cindex contributors to Gforth
14928:
14929: The Gforth project was started in mid-1992 by Bernd Paysan and Anton
1.81 anton 14930: Ertl. The third major author was Jens Wilke. Neal Crook contributed a
14931: lot to the manual. Assemblers and disassemblers were contributed by
14932: Andrew McKewan, Christian Pirker, and Bernd Thallner. Lennart Benschop
14933: (who was one of Gforth's first users, in mid-1993) and Stuart Ramsden
14934: inspired us with their continuous feedback. Lennart Benshop contributed
1.1 anton 14935: @file{glosgen.fs}, while Stuart Ramsden has been working on automatic
14936: support for calling C libraries. Helpful comments also came from Paul
14937: Kleinrubatscher, Christian Pirker, Dirk Zoller, Marcel Hendrix, John
1.58 anton 14938: Wavrik, Barrie Stott, Marc de Groot, Jorge Acerada, Bruce Hoyt, and
14939: Robert Epprecht. Since the release of Gforth-0.2.1 there were also
14940: helpful comments from many others; thank you all, sorry for not listing
14941: you here (but digging through my mailbox to extract your names is on my
1.81 anton 14942: to-do list).
1.1 anton 14943:
14944: Gforth also owes a lot to the authors of the tools we used (GCC, CVS,
14945: and autoconf, among others), and to the creators of the Internet: Gforth
1.21 crook 14946: was developed across the Internet, and its authors did not meet
1.20 pazsan 14947: physically for the first 4 years of development.
1.1 anton 14948:
14949: @section Pedigree
1.26 crook 14950: @cindex pedigree of Gforth
1.1 anton 14951:
1.81 anton 14952: Gforth descends from bigFORTH (1993) and fig-Forth. Of course, a
14953: significant part of the design of Gforth was prescribed by ANS Forth.
1.1 anton 14954:
1.20 pazsan 14955: Bernd Paysan wrote bigFORTH, a descendent from TurboForth, an unreleased
1.1 anton 14956: 32 bit native code version of VolksForth for the Atari ST, written
14957: mostly by Dietrich Weineck.
14958:
1.81 anton 14959: VolksForth was written by Klaus Schleisiek, Bernd Pennemann, Georg
14960: Rehfeld and Dietrich Weineck for the C64 (called UltraForth there) in
14961: the mid-80s and ported to the Atari ST in 1986. It descends from F83.
1.1 anton 14962:
14963: Henry Laxen and Mike Perry wrote F83 as a model implementation of the
14964: Forth-83 standard. !! Pedigree? When?
14965:
14966: A team led by Bill Ragsdale implemented fig-Forth on many processors in
14967: 1979. Robert Selzer and Bill Ragsdale developed the original
14968: implementation of fig-Forth for the 6502 based on microForth.
14969:
14970: The principal architect of microForth was Dean Sanderson. microForth was
14971: FORTH, Inc.'s first off-the-shelf product. It was developed in 1976 for
14972: the 1802, and subsequently implemented on the 8080, the 6800 and the
14973: Z80.
14974:
14975: All earlier Forth systems were custom-made, usually by Charles Moore,
14976: who discovered (as he puts it) Forth during the late 60s. The first full
14977: Forth existed in 1971.
14978:
1.81 anton 14979: A part of the information in this section comes from
14980: @cite{@uref{http://www.forth.com/Content/History/History1.htm,The
14981: Evolution of Forth}} by Elizabeth D. Rather, Donald R. Colburn and
14982: Charles H. Moore, presented at the HOPL-II conference and preprinted in
14983: SIGPLAN Notices 28(3), 1993. You can find more historical and
14984: genealogical information about Forth there.
1.1 anton 14985:
1.81 anton 14986: @c ------------------------------------------------------------------
1.21 crook 14987: @node Forth-related information, Word Index, Origin, Top
14988: @appendix Other Forth-related information
14989: @cindex Forth-related information
14990:
1.81 anton 14991: @c anton: I threw most of this stuff out, because it can be found through
14992: @c the FAQ and the FAQ is more likely to be up-to-date.
1.21 crook 14993:
14994: @cindex comp.lang.forth
14995: @cindex frequently asked questions
1.81 anton 14996: There is an active news group (comp.lang.forth) discussing Forth
14997: (including Gforth) and Forth-related issues. Its
14998: @uref{http://www.complang.tuwien.ac.at/forth/faq/faq-general-2.html,FAQs}
14999: (frequently asked questions and their answers) contains a lot of
15000: information on Forth. You should read it before posting to
15001: comp.lang.forth.
1.21 crook 15002:
1.81 anton 15003: The ANS Forth standard is most usable in its
15004: @uref{http://www.taygeta.com/forth/dpans.html, HTML form}.
1.21 crook 15005:
1.81 anton 15006: @c ------------------------------------------------------------------
15007: @node Word Index, Concept Index, Forth-related information, Top
1.1 anton 15008: @unnumbered Word Index
15009:
1.26 crook 15010: This index is a list of Forth words that have ``glossary'' entries
15011: within this manual. Each word is listed with its stack effect and
15012: wordset.
1.1 anton 15013:
15014: @printindex fn
15015:
1.81 anton 15016: @c anton: the name index seems superfluous given the word and concept indices.
15017:
15018: @c @node Name Index, Concept Index, Word Index, Top
15019: @c @unnumbered Name Index
1.41 anton 15020:
1.81 anton 15021: @c This index is a list of Forth words that have ``glossary'' entries
15022: @c within this manual.
1.41 anton 15023:
1.81 anton 15024: @c @printindex ky
1.41 anton 15025:
1.81 anton 15026: @node Concept Index, , Word Index, Top
1.1 anton 15027: @unnumbered Concept and Word Index
15028:
1.26 crook 15029: Not all entries listed in this index are present verbatim in the
15030: text. This index also duplicates, in abbreviated form, all of the words
15031: listed in the Word Index (only the names are listed for the words here).
1.1 anton 15032:
15033: @printindex cp
15034:
15035: @contents
15036: @bye
1.81 anton 15037:
15038:
1.1 anton 15039:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>