Annotation of gforth/doc/gforth.ds, revision 1.82
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.62 crook 1413: This tutorial can be used with any ANS-compliant Forth; any
1414: Gforth-specific features are marked as such and you can skip them if you
1415: work with another Forth. This tutorial does not explain all features of
1416: Forth, just enough to get you started and give you some ideas about the
1417: facilities available in Forth. Read the rest of the manual and the
1418: standard when you are through this.
1.48 anton 1419:
1420: The intended way to use this tutorial is that you work through it while
1421: sitting in front of the console, take a look at the examples and predict
1422: what they will do, then try them out; if the outcome is not as expected,
1423: find out why (e.g., by trying out variations of the example), so you
1424: understand what's going on. There are also some assignments that you
1425: should solve.
1426:
1427: This tutorial assumes that you have programmed before and know what,
1428: e.g., a loop is.
1429:
1430: @c !! explain compat library
1431:
1432: @menu
1433: * Starting Gforth Tutorial::
1434: * Syntax Tutorial::
1435: * Crash Course Tutorial::
1436: * Stack Tutorial::
1437: * Arithmetics Tutorial::
1438: * Stack Manipulation Tutorial::
1439: * Using files for Forth code Tutorial::
1440: * Comments Tutorial::
1441: * Colon Definitions Tutorial::
1442: * Decompilation Tutorial::
1443: * Stack-Effect Comments Tutorial::
1444: * Types Tutorial::
1445: * Factoring Tutorial::
1446: * Designing the stack effect Tutorial::
1447: * Local Variables Tutorial::
1448: * Conditional execution Tutorial::
1449: * Flags and Comparisons Tutorial::
1450: * General Loops Tutorial::
1451: * Counted loops Tutorial::
1452: * Recursion Tutorial::
1453: * Leaving definitions or loops Tutorial::
1454: * Return Stack Tutorial::
1455: * Memory Tutorial::
1456: * Characters and Strings Tutorial::
1457: * Alignment Tutorial::
1458: * Interpretation and Compilation Semantics and Immediacy Tutorial::
1459: * Execution Tokens Tutorial::
1460: * Exceptions Tutorial::
1461: * Defining Words Tutorial::
1462: * Arrays and Records Tutorial::
1463: * POSTPONE Tutorial::
1464: * Literal Tutorial::
1465: * Advanced macros Tutorial::
1466: * Compilation Tokens Tutorial::
1467: * Wordlists and Search Order Tutorial::
1468: @end menu
1469:
1470: @node Starting Gforth Tutorial, Syntax Tutorial, Tutorial, Tutorial
1471: @section Starting Gforth
1.66 anton 1472: @cindex starting Gforth tutorial
1.48 anton 1473: You can start Gforth by typing its name:
1474:
1475: @example
1476: gforth
1477: @end example
1478:
1479: That puts you into interactive mode; you can leave Gforth by typing
1480: @code{bye}. While in Gforth, you can edit the command line and access
1481: the command line history with cursor keys, similar to bash.
1482:
1483:
1484: @node Syntax Tutorial, Crash Course Tutorial, Starting Gforth Tutorial, Tutorial
1485: @section Syntax
1.66 anton 1486: @cindex syntax tutorial
1.48 anton 1487:
1488: A @dfn{word} is a sequence of arbitrary characters (expcept white
1489: space). Words are separated by white space. E.g., each of the
1490: following lines contains exactly one word:
1491:
1492: @example
1493: word
1494: !@@#$%^&*()
1495: 1234567890
1496: 5!a
1497: @end example
1498:
1499: A frequent beginner's error is to leave away necessary white space,
1500: resulting in an error like @samp{Undefined word}; so if you see such an
1501: error, check if you have put spaces wherever necessary.
1502:
1503: @example
1504: ." hello, world" \ correct
1505: ."hello, world" \ gives an "Undefined word" error
1506: @end example
1507:
1.65 anton 1508: Gforth and most other Forth systems ignore differences in case (they are
1.48 anton 1509: case-insensitive), i.e., @samp{word} is the same as @samp{Word}. If
1510: your system is case-sensitive, you may have to type all the examples
1511: given here in upper case.
1512:
1513:
1514: @node Crash Course Tutorial, Stack Tutorial, Syntax Tutorial, Tutorial
1515: @section Crash Course
1516:
1517: Type
1518:
1519: @example
1520: 0 0 !
1521: here execute
1522: ' catch >body 20 erase abort
1523: ' (quit) >body 20 erase
1524: @end example
1525:
1526: The last two examples are guaranteed to destroy parts of Gforth (and
1527: most other systems), so you better leave Gforth afterwards (if it has
1528: not finished by itself). On some systems you may have to kill gforth
1529: from outside (e.g., in Unix with @code{kill}).
1530:
1531: Now that you know how to produce crashes (and that there's not much to
1532: them), let's learn how to produce meaningful programs.
1533:
1534:
1535: @node Stack Tutorial, Arithmetics Tutorial, Crash Course Tutorial, Tutorial
1536: @section Stack
1.66 anton 1537: @cindex stack tutorial
1.48 anton 1538:
1539: The most obvious feature of Forth is the stack. When you type in a
1540: number, it is pushed on the stack. You can display the content of the
1541: stack with @code{.s}.
1542:
1543: @example
1544: 1 2 .s
1545: 3 .s
1546: @end example
1547:
1548: @code{.s} displays the top-of-stack to the right, i.e., the numbers
1549: appear in @code{.s} output as they appeared in the input.
1550:
1551: You can print the top of stack element with @code{.}.
1552:
1553: @example
1554: 1 2 3 . . .
1555: @end example
1556:
1557: In general, words consume their stack arguments (@code{.s} is an
1558: exception).
1559:
1560: @assignment
1561: What does the stack contain after @code{5 6 7 .}?
1562: @endassignment
1563:
1564:
1565: @node Arithmetics Tutorial, Stack Manipulation Tutorial, Stack Tutorial, Tutorial
1566: @section Arithmetics
1.66 anton 1567: @cindex arithmetics tutorial
1.48 anton 1568:
1569: The words @code{+}, @code{-}, @code{*}, @code{/}, and @code{mod} always
1570: operate on the top two stack items:
1571:
1572: @example
1.67 anton 1573: 2 2 .s
1574: + .s
1575: .
1.48 anton 1576: 2 1 - .
1577: 7 3 mod .
1578: @end example
1579:
1580: The operands of @code{-}, @code{/}, and @code{mod} are in the same order
1581: as in the corresponding infix expression (this is generally the case in
1582: Forth).
1583:
1584: Parentheses are superfluous (and not available), because the order of
1585: the words unambiguously determines the order of evaluation and the
1586: operands:
1587:
1588: @example
1589: 3 4 + 5 * .
1590: 3 4 5 * + .
1591: @end example
1592:
1593: @assignment
1594: What are the infix expressions corresponding to the Forth code above?
1595: Write @code{6-7*8+9} in Forth notation@footnote{This notation is also
1596: known as Postfix or RPN (Reverse Polish Notation).}.
1597: @endassignment
1598:
1599: To change the sign, use @code{negate}:
1600:
1601: @example
1602: 2 negate .
1603: @end example
1604:
1605: @assignment
1606: Convert -(-3)*4-5 to Forth.
1607: @endassignment
1608:
1609: @code{/mod} performs both @code{/} and @code{mod}.
1610:
1611: @example
1612: 7 3 /mod . .
1613: @end example
1614:
1.66 anton 1615: Reference: @ref{Arithmetic}.
1616:
1617:
1.48 anton 1618: @node Stack Manipulation Tutorial, Using files for Forth code Tutorial, Arithmetics Tutorial, Tutorial
1619: @section Stack Manipulation
1.66 anton 1620: @cindex stack manipulation tutorial
1.48 anton 1621:
1622: Stack manipulation words rearrange the data on the stack.
1623:
1624: @example
1625: 1 .s drop .s
1626: 1 .s dup .s drop drop .s
1627: 1 2 .s over .s drop drop drop
1628: 1 2 .s swap .s drop drop
1629: 1 2 3 .s rot .s drop drop drop
1630: @end example
1631:
1632: These are the most important stack manipulation words. There are also
1633: variants that manipulate twice as many stack items:
1634:
1635: @example
1636: 1 2 3 4 .s 2swap .s 2drop 2drop
1637: @end example
1638:
1639: Two more stack manipulation words are:
1640:
1641: @example
1642: 1 2 .s nip .s drop
1643: 1 2 .s tuck .s 2drop drop
1644: @end example
1645:
1646: @assignment
1647: Replace @code{nip} and @code{tuck} with combinations of other stack
1648: manipulation words.
1649:
1650: @example
1651: Given: How do you get:
1652: 1 2 3 3 2 1
1653: 1 2 3 1 2 3 2
1654: 1 2 3 1 2 3 3
1655: 1 2 3 1 3 3
1656: 1 2 3 2 1 3
1657: 1 2 3 4 4 3 2 1
1658: 1 2 3 1 2 3 1 2 3
1659: 1 2 3 4 1 2 3 4 1 2
1660: 1 2 3
1661: 1 2 3 1 2 3 4
1662: 1 2 3 1 3
1663: @end example
1664: @endassignment
1665:
1666: @example
1667: 5 dup * .
1668: @end example
1669:
1670: @assignment
1671: Write 17^3 and 17^4 in Forth, without writing @code{17} more than once.
1672: Write a piece of Forth code that expects two numbers on the stack
1673: (@var{a} and @var{b}, with @var{b} on top) and computes
1674: @code{(a-b)(a+1)}.
1675: @endassignment
1676:
1.66 anton 1677: Reference: @ref{Stack Manipulation}.
1678:
1679:
1.48 anton 1680: @node Using files for Forth code Tutorial, Comments Tutorial, Stack Manipulation Tutorial, Tutorial
1681: @section Using files for Forth code
1.66 anton 1682: @cindex loading Forth code, tutorial
1683: @cindex files containing Forth code, tutorial
1.48 anton 1684:
1685: While working at the Forth command line is convenient for one-line
1686: examples and short one-off code, you probably want to store your source
1687: code in files for convenient editing and persistence. You can use your
1688: favourite editor (Gforth includes Emacs support, @pxref{Emacs and
1689: Gforth}) to create @var{file} and use
1690:
1691: @example
1692: s" @var{file}" included
1693: @end example
1694:
1695: to load it into your Forth system. The file name extension I use for
1696: Forth files is @samp{.fs}.
1697:
1698: You can easily start Gforth with some files loaded like this:
1699:
1700: @example
1701: gforth @var{file1} @var{file2}
1702: @end example
1703:
1704: If an error occurs during loading these files, Gforth terminates,
1705: whereas an error during @code{INCLUDED} within Gforth usually gives you
1706: a Gforth command line. Starting the Forth system every time gives you a
1707: clean start every time, without interference from the results of earlier
1708: tries.
1709:
1710: I often put all the tests in a file, then load the code and run the
1711: tests with
1712:
1713: @example
1714: gforth @var{code} @var{tests} -e bye
1715: @end example
1716:
1717: (often by performing this command with @kbd{C-x C-e} in Emacs). The
1718: @code{-e bye} ensures that Gforth terminates afterwards so that I can
1719: restart this command without ado.
1720:
1721: The advantage of this approach is that the tests can be repeated easily
1722: every time the program ist changed, making it easy to catch bugs
1723: introduced by the change.
1724:
1.66 anton 1725: Reference: @ref{Forth source files}.
1726:
1.48 anton 1727:
1728: @node Comments Tutorial, Colon Definitions Tutorial, Using files for Forth code Tutorial, Tutorial
1729: @section Comments
1.66 anton 1730: @cindex comments tutorial
1.48 anton 1731:
1732: @example
1733: \ That's a comment; it ends at the end of the line
1734: ( Another comment; it ends here: ) .s
1735: @end example
1736:
1737: @code{\} and @code{(} are ordinary Forth words and therefore have to be
1738: separated with white space from the following text.
1739:
1740: @example
1741: \This gives an "Undefined word" error
1742: @end example
1743:
1744: The first @code{)} ends a comment started with @code{(}, so you cannot
1745: nest @code{(}-comments; and you cannot comment out text containing a
1746: @code{)} with @code{( ... )}@footnote{therefore it's a good idea to
1747: avoid @code{)} in word names.}.
1748:
1749: I use @code{\}-comments for descriptive text and for commenting out code
1750: of one or more line; I use @code{(}-comments for describing the stack
1751: effect, the stack contents, or for commenting out sub-line pieces of
1752: code.
1753:
1754: The Emacs mode @file{gforth.el} (@pxref{Emacs and Gforth}) supports
1755: these uses by commenting out a region with @kbd{C-x \}, uncommenting a
1756: region with @kbd{C-u C-x \}, and filling a @code{\}-commented region
1757: with @kbd{M-q}.
1758:
1.66 anton 1759: Reference: @ref{Comments}.
1760:
1.48 anton 1761:
1762: @node Colon Definitions Tutorial, Decompilation Tutorial, Comments Tutorial, Tutorial
1763: @section Colon Definitions
1.66 anton 1764: @cindex colon definitions, tutorial
1765: @cindex definitions, tutorial
1766: @cindex procedures, tutorial
1767: @cindex functions, tutorial
1.48 anton 1768:
1769: are similar to procedures and functions in other programming languages.
1770:
1771: @example
1772: : squared ( n -- n^2 )
1773: dup * ;
1774: 5 squared .
1775: 7 squared .
1776: @end example
1777:
1778: @code{:} starts the colon definition; its name is @code{squared}. The
1779: following comment describes its stack effect. The words @code{dup *}
1780: are not executed, but compiled into the definition. @code{;} ends the
1781: colon definition.
1782:
1783: The newly-defined word can be used like any other word, including using
1784: it in other definitions:
1785:
1786: @example
1787: : cubed ( n -- n^3 )
1788: dup squared * ;
1789: -5 cubed .
1790: : fourth-power ( n -- n^4 )
1791: squared squared ;
1792: 3 fourth-power .
1793: @end example
1794:
1795: @assignment
1796: Write colon definitions for @code{nip}, @code{tuck}, @code{negate}, and
1797: @code{/mod} in terms of other Forth words, and check if they work (hint:
1798: test your tests on the originals first). Don't let the
1799: @samp{redefined}-Messages spook you, they are just warnings.
1800: @endassignment
1801:
1.66 anton 1802: Reference: @ref{Colon Definitions}.
1803:
1.48 anton 1804:
1805: @node Decompilation Tutorial, Stack-Effect Comments Tutorial, Colon Definitions Tutorial, Tutorial
1806: @section Decompilation
1.66 anton 1807: @cindex decompilation tutorial
1808: @cindex see tutorial
1.48 anton 1809:
1810: You can decompile colon definitions with @code{see}:
1811:
1812: @example
1813: see squared
1814: see cubed
1815: @end example
1816:
1817: In Gforth @code{see} shows you a reconstruction of the source code from
1818: the executable code. Informations that were present in the source, but
1819: not in the executable code, are lost (e.g., comments).
1820:
1.65 anton 1821: You can also decompile the predefined words:
1822:
1823: @example
1824: see .
1825: see +
1826: @end example
1827:
1828:
1.48 anton 1829: @node Stack-Effect Comments Tutorial, Types Tutorial, Decompilation Tutorial, Tutorial
1830: @section Stack-Effect Comments
1.66 anton 1831: @cindex stack-effect comments, tutorial
1832: @cindex --, tutorial
1.48 anton 1833: By convention the comment after the name of a definition describes the
1834: stack effect: The part in from of the @samp{--} describes the state of
1835: the stack before the execution of the definition, i.e., the parameters
1836: that are passed into the colon definition; the part behind the @samp{--}
1837: is the state of the stack after the execution of the definition, i.e.,
1838: the results of the definition. The stack comment only shows the top
1839: stack items that the definition accesses and/or changes.
1840:
1841: You should put a correct stack effect on every definition, even if it is
1842: just @code{( -- )}. You should also add some descriptive comment to
1843: more complicated words (I usually do this in the lines following
1844: @code{:}). If you don't do this, your code becomes unreadable (because
1845: you have to work through every definition before you can undertsand
1846: any).
1847:
1848: @assignment
1849: The stack effect of @code{swap} can be written like this: @code{x1 x2 --
1850: x2 x1}. Describe the stack effect of @code{-}, @code{drop}, @code{dup},
1851: @code{over}, @code{rot}, @code{nip}, and @code{tuck}. Hint: When you
1.65 anton 1852: are done, you can compare your stack effects to those in this manual
1.48 anton 1853: (@pxref{Word Index}).
1854: @endassignment
1855:
1856: Sometimes programmers put comments at various places in colon
1857: definitions that describe the contents of the stack at that place (stack
1858: comments); i.e., they are like the first part of a stack-effect
1859: comment. E.g.,
1860:
1861: @example
1862: : cubed ( n -- n^3 )
1863: dup squared ( n n^2 ) * ;
1864: @end example
1865:
1866: In this case the stack comment is pretty superfluous, because the word
1867: is simple enough. If you think it would be a good idea to add such a
1868: comment to increase readability, you should also consider factoring the
1869: word into several simpler words (@pxref{Factoring Tutorial,,
1.60 anton 1870: Factoring}), which typically eliminates the need for the stack comment;
1.48 anton 1871: however, if you decide not to refactor it, then having such a comment is
1872: better than not having it.
1873:
1874: The names of the stack items in stack-effect and stack comments in the
1875: standard, in this manual, and in many programs specify the type through
1876: a type prefix, similar to Fortran and Hungarian notation. The most
1877: frequent prefixes are:
1878:
1879: @table @code
1880: @item n
1881: signed integer
1882: @item u
1883: unsigned integer
1884: @item c
1885: character
1886: @item f
1887: Boolean flags, i.e. @code{false} or @code{true}.
1888: @item a-addr,a-
1889: Cell-aligned address
1890: @item c-addr,c-
1891: Char-aligned address (note that a Char may have two bytes in Windows NT)
1892: @item xt
1893: Execution token, same size as Cell
1894: @item w,x
1895: Cell, can contain an integer or an address. It usually takes 32, 64 or
1896: 16 bits (depending on your platform and Forth system). A cell is more
1897: commonly known as machine word, but the term @emph{word} already means
1898: something different in Forth.
1899: @item d
1900: signed double-cell integer
1901: @item ud
1902: unsigned double-cell integer
1903: @item r
1904: Float (on the FP stack)
1905: @end table
1906:
1907: You can find a more complete list in @ref{Notation}.
1908:
1909: @assignment
1910: Write stack-effect comments for all definitions you have written up to
1911: now.
1912: @endassignment
1913:
1914:
1915: @node Types Tutorial, Factoring Tutorial, Stack-Effect Comments Tutorial, Tutorial
1916: @section Types
1.66 anton 1917: @cindex types tutorial
1.48 anton 1918:
1919: In Forth the names of the operations are not overloaded; so similar
1920: operations on different types need different names; e.g., @code{+} adds
1921: integers, and you have to use @code{f+} to add floating-point numbers.
1922: The following prefixes are often used for related operations on
1923: different types:
1924:
1925: @table @code
1926: @item (none)
1927: signed integer
1928: @item u
1929: unsigned integer
1930: @item c
1931: character
1932: @item d
1933: signed double-cell integer
1934: @item ud, du
1935: unsigned double-cell integer
1936: @item 2
1937: two cells (not-necessarily double-cell numbers)
1938: @item m, um
1939: mixed single-cell and double-cell operations
1940: @item f
1941: floating-point (note that in stack comments @samp{f} represents flags,
1.66 anton 1942: and @samp{r} represents FP numbers).
1.48 anton 1943: @end table
1944:
1945: If there are no differences between the signed and the unsigned variant
1946: (e.g., for @code{+}), there is only the prefix-less variant.
1947:
1948: Forth does not perform type checking, neither at compile time, nor at
1949: run time. If you use the wrong oeration, the data are interpreted
1950: incorrectly:
1951:
1952: @example
1953: -1 u.
1954: @end example
1955:
1956: If you have only experience with type-checked languages until now, and
1957: have heard how important type-checking is, don't panic! In my
1958: experience (and that of other Forthers), type errors in Forth code are
1959: usually easy to find (once you get used to it), the increased vigilance
1960: of the programmer tends to catch some harder errors in addition to most
1961: type errors, and you never have to work around the type system, so in
1962: most situations the lack of type-checking seems to be a win (projects to
1963: add type checking to Forth have not caught on).
1964:
1965:
1966: @node Factoring Tutorial, Designing the stack effect Tutorial, Types Tutorial, Tutorial
1967: @section Factoring
1.66 anton 1968: @cindex factoring tutorial
1.48 anton 1969:
1970: If you try to write longer definitions, you will soon find it hard to
1971: keep track of the stack contents. Therefore, good Forth programmers
1972: tend to write only short definitions (e.g., three lines). The art of
1973: finding meaningful short definitions is known as factoring (as in
1974: factoring polynomials).
1975:
1976: Well-factored programs offer additional advantages: smaller, more
1977: general words, are easier to test and debug and can be reused more and
1978: better than larger, specialized words.
1979:
1980: So, if you run into difficulties with stack management, when writing
1981: code, try to define meaningful factors for the word, and define the word
1982: in terms of those. Even if a factor contains only two words, it is
1983: often helpful.
1984:
1.65 anton 1985: Good factoring is not easy, and it takes some practice to get the knack
1986: for it; but even experienced Forth programmers often don't find the
1987: right solution right away, but only when rewriting the program. So, if
1988: you don't come up with a good solution immediately, keep trying, don't
1989: despair.
1.48 anton 1990:
1991: @c example !!
1992:
1993:
1994: @node Designing the stack effect Tutorial, Local Variables Tutorial, Factoring Tutorial, Tutorial
1995: @section Designing the stack effect
1.66 anton 1996: @cindex Stack effect design, tutorial
1997: @cindex design of stack effects, tutorial
1.48 anton 1998:
1999: In other languages you can use an arbitrary order of parameters for a
1.65 anton 2000: function; and since there is only one result, you don't have to deal with
1.48 anton 2001: the order of results, either.
2002:
2003: In Forth (and other stack-based languages, e.g., Postscript) the
2004: parameter and result order of a definition is important and should be
2005: designed well. The general guideline is to design the stack effect such
2006: that the word is simple to use in most cases, even if that complicates
2007: the implementation of the word. Some concrete rules are:
2008:
2009: @itemize @bullet
2010:
2011: @item
2012: Words consume all of their parameters (e.g., @code{.}).
2013:
2014: @item
2015: If there is a convention on the order of parameters (e.g., from
2016: mathematics or another programming language), stick with it (e.g.,
2017: @code{-}).
2018:
2019: @item
2020: If one parameter usually requires only a short computation (e.g., it is
2021: a constant), pass it on the top of the stack. Conversely, parameters
2022: that usually require a long sequence of code to compute should be passed
2023: as the bottom (i.e., first) parameter. This makes the code easier to
2024: read, because reader does not need to keep track of the bottom item
2025: through a long sequence of code (or, alternatively, through stack
1.49 anton 2026: manipulations). E.g., @code{!} (store, @pxref{Memory}) expects the
1.48 anton 2027: address on top of the stack because it is usually simpler to compute
2028: than the stored value (often the address is just a variable).
2029:
2030: @item
2031: Similarly, results that are usually consumed quickly should be returned
2032: on the top of stack, whereas a result that is often used in long
2033: computations should be passed as bottom result. E.g., the file words
2034: like @code{open-file} return the error code on the top of stack, because
2035: it is usually consumed quickly by @code{throw}; moreover, the error code
2036: has to be checked before doing anything with the other results.
2037:
2038: @end itemize
2039:
2040: These rules are just general guidelines, don't lose sight of the overall
2041: goal to make the words easy to use. E.g., if the convention rule
2042: conflicts with the computation-length rule, you might decide in favour
2043: of the convention if the word will be used rarely, and in favour of the
2044: computation-length rule if the word will be used frequently (because
2045: with frequent use the cost of breaking the computation-length rule would
2046: be quite high, and frequent use makes it easier to remember an
2047: unconventional order).
2048:
2049: @c example !! structure package
2050:
1.65 anton 2051:
1.48 anton 2052: @node Local Variables Tutorial, Conditional execution Tutorial, Designing the stack effect Tutorial, Tutorial
2053: @section Local Variables
1.66 anton 2054: @cindex local variables, tutorial
1.48 anton 2055:
2056: You can define local variables (@emph{locals}) in a colon definition:
2057:
2058: @example
2059: : swap @{ a b -- b a @}
2060: b a ;
2061: 1 2 swap .s 2drop
2062: @end example
2063:
2064: (If your Forth system does not support this syntax, include
2065: @file{compat/anslocals.fs} first).
2066:
2067: In this example @code{@{ a b -- b a @}} is the locals definition; it
2068: takes two cells from the stack, puts the top of stack in @code{b} and
2069: the next stack element in @code{a}. @code{--} starts a comment ending
2070: with @code{@}}. After the locals definition, using the name of the
2071: local will push its value on the stack. You can leave the comment
2072: part (@code{-- b a}) away:
2073:
2074: @example
2075: : swap ( x1 x2 -- x2 x1 )
2076: @{ a b @} b a ;
2077: @end example
2078:
2079: In Gforth you can have several locals definitions, anywhere in a colon
2080: definition; in contrast, in a standard program you can have only one
2081: locals definition per colon definition, and that locals definition must
2082: be outside any controll structure.
2083:
2084: With locals you can write slightly longer definitions without running
2085: into stack trouble. However, I recommend trying to write colon
2086: definitions without locals for exercise purposes to help you gain the
2087: essential factoring skills.
2088:
2089: @assignment
2090: Rewrite your definitions until now with locals
2091: @endassignment
2092:
1.66 anton 2093: Reference: @ref{Locals}.
2094:
1.48 anton 2095:
2096: @node Conditional execution Tutorial, Flags and Comparisons Tutorial, Local Variables Tutorial, Tutorial
2097: @section Conditional execution
1.66 anton 2098: @cindex conditionals, tutorial
2099: @cindex if, tutorial
1.48 anton 2100:
2101: In Forth you can use control structures only inside colon definitions.
2102: An @code{if}-structure looks like this:
2103:
2104: @example
2105: : abs ( n1 -- +n2 )
2106: dup 0 < if
2107: negate
2108: endif ;
2109: 5 abs .
2110: -5 abs .
2111: @end example
2112:
2113: @code{if} takes a flag from the stack. If the flag is non-zero (true),
2114: the following code is performed, otherwise execution continues after the
1.51 pazsan 2115: @code{endif} (or @code{else}). @code{<} compares the top two stack
1.48 anton 2116: elements and prioduces a flag:
2117:
2118: @example
2119: 1 2 < .
2120: 2 1 < .
2121: 1 1 < .
2122: @end example
2123:
2124: Actually the standard name for @code{endif} is @code{then}. This
2125: tutorial presents the examples using @code{endif}, because this is often
2126: less confusing for people familiar with other programming languages
2127: where @code{then} has a different meaning. If your system does not have
2128: @code{endif}, define it with
2129:
2130: @example
2131: : endif postpone then ; immediate
2132: @end example
2133:
2134: You can optionally use an @code{else}-part:
2135:
2136: @example
2137: : min ( n1 n2 -- n )
2138: 2dup < if
2139: drop
2140: else
2141: nip
2142: endif ;
2143: 2 3 min .
2144: 3 2 min .
2145: @end example
2146:
2147: @assignment
2148: Write @code{min} without @code{else}-part (hint: what's the definition
2149: of @code{nip}?).
2150: @endassignment
2151:
1.66 anton 2152: Reference: @ref{Selection}.
2153:
1.48 anton 2154:
2155: @node Flags and Comparisons Tutorial, General Loops Tutorial, Conditional execution Tutorial, Tutorial
2156: @section Flags and Comparisons
1.66 anton 2157: @cindex flags tutorial
2158: @cindex comparison tutorial
1.48 anton 2159:
2160: In a false-flag all bits are clear (0 when interpreted as integer). In
2161: a canonical true-flag all bits are set (-1 as a twos-complement signed
2162: integer); in many contexts (e.g., @code{if}) any non-zero value is
2163: treated as true flag.
2164:
2165: @example
2166: false .
2167: true .
2168: true hex u. decimal
2169: @end example
2170:
2171: Comparison words produce canonical flags:
2172:
2173: @example
2174: 1 1 = .
2175: 1 0= .
2176: 0 1 < .
2177: 0 0 < .
2178: -1 1 u< . \ type error, u< interprets -1 as large unsigned number
2179: -1 1 < .
2180: @end example
2181:
1.66 anton 2182: Gforth supports all combinations of the prefixes @code{0 u d d0 du f f0}
2183: (or none) and the comparisons @code{= <> < > <= >=}. Only a part of
2184: these combinations are standard (for details see the standard,
2185: @ref{Numeric comparison}, @ref{Floating Point} or @ref{Word Index}).
1.48 anton 2186:
2187: You can use @code{and or xor invert} can be used as operations on
2188: canonical flags. Actually they are bitwise operations:
2189:
2190: @example
2191: 1 2 and .
2192: 1 2 or .
2193: 1 3 xor .
2194: 1 invert .
2195: @end example
2196:
2197: You can convert a zero/non-zero flag into a canonical flag with
2198: @code{0<>} (and complement it on the way with @code{0=}).
2199:
2200: @example
2201: 1 0= .
2202: 1 0<> .
2203: @end example
2204:
1.65 anton 2205: You can use the all-bits-set feature of canonical flags and the bitwise
1.48 anton 2206: operation of the Boolean operations to avoid @code{if}s:
2207:
2208: @example
2209: : foo ( n1 -- n2 )
2210: 0= if
2211: 14
2212: else
2213: 0
2214: endif ;
2215: 0 foo .
2216: 1 foo .
2217:
2218: : foo ( n1 -- n2 )
2219: 0= 14 and ;
2220: 0 foo .
2221: 1 foo .
2222: @end example
2223:
2224: @assignment
2225: Write @code{min} without @code{if}.
2226: @endassignment
2227:
1.66 anton 2228: For reference, see @ref{Boolean Flags}, @ref{Numeric comparison}, and
2229: @ref{Bitwise operations}.
2230:
1.48 anton 2231:
2232: @node General Loops Tutorial, Counted loops Tutorial, Flags and Comparisons Tutorial, Tutorial
2233: @section General Loops
1.66 anton 2234: @cindex loops, indefinite, tutorial
1.48 anton 2235:
2236: The endless loop is the most simple one:
2237:
2238: @example
2239: : endless ( -- )
2240: 0 begin
2241: dup . 1+
2242: again ;
2243: endless
2244: @end example
2245:
2246: Terminate this loop by pressing @kbd{Ctrl-C} (in Gforth). @code{begin}
2247: does nothing at run-time, @code{again} jumps back to @code{begin}.
2248:
2249: A loop with one exit at any place looks like this:
2250:
2251: @example
2252: : log2 ( +n1 -- n2 )
2253: \ logarithmus dualis of n1>0, rounded down to the next integer
2254: assert( dup 0> )
2255: 2/ 0 begin
2256: over 0> while
2257: 1+ swap 2/ swap
2258: repeat
2259: nip ;
2260: 7 log2 .
2261: 8 log2 .
2262: @end example
2263:
2264: At run-time @code{while} consumes a flag; if it is 0, execution
1.51 pazsan 2265: continues behind the @code{repeat}; if the flag is non-zero, execution
1.48 anton 2266: continues behind the @code{while}. @code{Repeat} jumps back to
2267: @code{begin}, just like @code{again}.
2268:
2269: In Forth there are many combinations/abbreviations, like @code{1+}.
2270: However, @code{2/} is not one of them; it shifts it's argument right by
2271: one bit (arithmetic shift right):
2272:
2273: @example
2274: -5 2 / .
2275: -5 2/ .
2276: @end example
2277:
2278: @code{assert(} is no standard word, but you can get it on systems other
2279: then Gforth by including @file{compat/assert.fs}. You can see what it
2280: does by trying
2281:
2282: @example
2283: 0 log2 .
2284: @end example
2285:
2286: Here's a loop with an exit at the end:
2287:
2288: @example
2289: : log2 ( +n1 -- n2 )
2290: \ logarithmus dualis of n1>0, rounded down to the next integer
2291: assert( dup 0 > )
2292: -1 begin
2293: 1+ swap 2/ swap
2294: over 0 <=
2295: until
2296: nip ;
2297: @end example
2298:
2299: @code{Until} consumes a flag; if it is non-zero, execution continues at
2300: the @code{begin}, otherwise after the @code{until}.
2301:
2302: @assignment
2303: Write a definition for computing the greatest common divisor.
2304: @endassignment
2305:
1.66 anton 2306: Reference: @ref{Simple Loops}.
2307:
1.48 anton 2308:
2309: @node Counted loops Tutorial, Recursion Tutorial, General Loops Tutorial, Tutorial
2310: @section Counted loops
1.66 anton 2311: @cindex loops, counted, tutorial
1.48 anton 2312:
2313: @example
2314: : ^ ( n1 u -- n )
2315: \ n = the uth power of u1
2316: 1 swap 0 u+do
2317: over *
2318: loop
2319: nip ;
2320: 3 2 ^ .
2321: 4 3 ^ .
2322: @end example
2323:
2324: @code{U+do} (from @file{compat/loops.fs}, if your Forth system doesn't
2325: have it) takes two numbers of the stack @code{( u3 u4 -- )}, and then
2326: performs the code between @code{u+do} and @code{loop} for @code{u3-u4}
2327: times (or not at all, if @code{u3-u4<0}).
2328:
2329: You can see the stack effect design rules at work in the stack effect of
2330: the loop start words: Since the start value of the loop is more
2331: frequently constant than the end value, the start value is passed on
2332: the top-of-stack.
2333:
2334: You can access the counter of a counted loop with @code{i}:
2335:
2336: @example
2337: : fac ( u -- u! )
2338: 1 swap 1+ 1 u+do
2339: i *
2340: loop ;
2341: 5 fac .
2342: 7 fac .
2343: @end example
2344:
2345: There is also @code{+do}, which expects signed numbers (important for
2346: deciding whether to enter the loop).
2347:
2348: @assignment
2349: Write a definition for computing the nth Fibonacci number.
2350: @endassignment
2351:
1.65 anton 2352: You can also use increments other than 1:
2353:
2354: @example
2355: : up2 ( n1 n2 -- )
2356: +do
2357: i .
2358: 2 +loop ;
2359: 10 0 up2
2360:
2361: : down2 ( n1 n2 -- )
2362: -do
2363: i .
2364: 2 -loop ;
2365: 0 10 down2
2366: @end example
1.48 anton 2367:
1.66 anton 2368: Reference: @ref{Counted Loops}.
2369:
1.48 anton 2370:
2371: @node Recursion Tutorial, Leaving definitions or loops Tutorial, Counted loops Tutorial, Tutorial
2372: @section Recursion
1.66 anton 2373: @cindex recursion tutorial
1.48 anton 2374:
2375: Usually the name of a definition is not visible in the definition; but
2376: earlier definitions are usually visible:
2377:
2378: @example
2379: 1 0 / . \ "Floating-point unidentified fault" in Gforth on most platforms
2380: : / ( n1 n2 -- n )
2381: dup 0= if
2382: -10 throw \ report division by zero
2383: endif
2384: / \ old version
2385: ;
2386: 1 0 /
2387: @end example
2388:
2389: For recursive definitions you can use @code{recursive} (non-standard) or
2390: @code{recurse}:
2391:
2392: @example
2393: : fac1 ( n -- n! ) recursive
2394: dup 0> if
2395: dup 1- fac1 *
2396: else
2397: drop 1
2398: endif ;
2399: 7 fac1 .
2400:
2401: : fac2 ( n -- n! )
2402: dup 0> if
2403: dup 1- recurse *
2404: else
2405: drop 1
2406: endif ;
2407: 8 fac2 .
2408: @end example
2409:
2410: @assignment
2411: Write a recursive definition for computing the nth Fibonacci number.
2412: @endassignment
2413:
1.66 anton 2414: Reference (including indirect recursion): @xref{Calls and returns}.
2415:
1.48 anton 2416:
2417: @node Leaving definitions or loops Tutorial, Return Stack Tutorial, Recursion Tutorial, Tutorial
2418: @section Leaving definitions or loops
1.66 anton 2419: @cindex leaving definitions, tutorial
2420: @cindex leaving loops, tutorial
1.48 anton 2421:
2422: @code{EXIT} exits the current definition right away. For every counted
2423: loop that is left in this way, an @code{UNLOOP} has to be performed
2424: before the @code{EXIT}:
2425:
2426: @c !! real examples
2427: @example
2428: : ...
2429: ... u+do
2430: ... if
2431: ... unloop exit
2432: endif
2433: ...
2434: loop
2435: ... ;
2436: @end example
2437:
2438: @code{LEAVE} leaves the innermost counted loop right away:
2439:
2440: @example
2441: : ...
2442: ... u+do
2443: ... if
2444: ... leave
2445: endif
2446: ...
2447: loop
2448: ... ;
2449: @end example
2450:
1.65 anton 2451: @c !! example
1.48 anton 2452:
1.66 anton 2453: Reference: @ref{Calls and returns}, @ref{Counted Loops}.
2454:
2455:
1.48 anton 2456: @node Return Stack Tutorial, Memory Tutorial, Leaving definitions or loops Tutorial, Tutorial
2457: @section Return Stack
1.66 anton 2458: @cindex return stack tutorial
1.48 anton 2459:
2460: In addition to the data stack Forth also has a second stack, the return
2461: stack; most Forth systems store the return addresses of procedure calls
2462: there (thus its name). Programmers can also use this stack:
2463:
2464: @example
2465: : foo ( n1 n2 -- )
2466: .s
2467: >r .s
1.50 anton 2468: r@@ .
1.48 anton 2469: >r .s
1.50 anton 2470: r@@ .
1.48 anton 2471: r> .
1.50 anton 2472: r@@ .
1.48 anton 2473: r> . ;
2474: 1 2 foo
2475: @end example
2476:
2477: @code{>r} takes an element from the data stack and pushes it onto the
2478: return stack; conversely, @code{r>} moves an elementm from the return to
2479: the data stack; @code{r@@} pushes a copy of the top of the return stack
2480: on the return stack.
2481:
2482: Forth programmers usually use the return stack for storing data
2483: temporarily, if using the data stack alone would be too complex, and
2484: factoring and locals are not an option:
2485:
2486: @example
2487: : 2swap ( x1 x2 x3 x4 -- x3 x4 x1 x2 )
2488: rot >r rot r> ;
2489: @end example
2490:
2491: The return address of the definition and the loop control parameters of
2492: counted loops usually reside on the return stack, so you have to take
2493: all items, that you have pushed on the return stack in a colon
2494: definition or counted loop, from the return stack before the definition
2495: or loop ends. You cannot access items that you pushed on the return
2496: stack outside some definition or loop within the definition of loop.
2497:
2498: If you miscount the return stack items, this usually ends in a crash:
2499:
2500: @example
2501: : crash ( n -- )
2502: >r ;
2503: 5 crash
2504: @end example
2505:
2506: You cannot mix using locals and using the return stack (according to the
2507: standard; Gforth has no problem). However, they solve the same
2508: problems, so this shouldn't be an issue.
2509:
2510: @assignment
2511: Can you rewrite any of the definitions you wrote until now in a better
2512: way using the return stack?
2513: @endassignment
2514:
1.66 anton 2515: Reference: @ref{Return stack}.
2516:
1.48 anton 2517:
2518: @node Memory Tutorial, Characters and Strings Tutorial, Return Stack Tutorial, Tutorial
2519: @section Memory
1.66 anton 2520: @cindex memory access/allocation tutorial
1.48 anton 2521:
2522: You can create a global variable @code{v} with
2523:
2524: @example
2525: variable v ( -- addr )
2526: @end example
2527:
2528: @code{v} pushes the address of a cell in memory on the stack. This cell
2529: was reserved by @code{variable}. You can use @code{!} (store) to store
2530: values into this cell and @code{@@} (fetch) to load the value from the
2531: stack into memory:
2532:
2533: @example
2534: v .
2535: 5 v ! .s
1.50 anton 2536: v @@ .
1.48 anton 2537: @end example
2538:
1.65 anton 2539: You can see a raw dump of memory with @code{dump}:
2540:
2541: @example
2542: v 1 cells .s dump
2543: @end example
2544:
2545: @code{Cells ( n1 -- n2 )} gives you the number of bytes (or, more
2546: generally, address units (aus)) that @code{n1 cells} occupy. You can
2547: also reserve more memory:
1.48 anton 2548:
2549: @example
2550: create v2 20 cells allot
1.65 anton 2551: v2 20 cells dump
1.48 anton 2552: @end example
2553:
1.65 anton 2554: creates a word @code{v2} and reserves 20 uninitialized cells; the
2555: address pushed by @code{v2} points to the start of these 20 cells. You
2556: can use address arithmetic to access these cells:
1.48 anton 2557:
2558: @example
2559: 3 v2 5 cells + !
1.65 anton 2560: v2 20 cells dump
1.48 anton 2561: @end example
2562:
2563: You can reserve and initialize memory with @code{,}:
2564:
2565: @example
2566: create v3
2567: 5 , 4 , 3 , 2 , 1 ,
1.50 anton 2568: v3 @@ .
2569: v3 cell+ @@ .
2570: v3 2 cells + @@ .
1.65 anton 2571: v3 5 cells dump
1.48 anton 2572: @end example
2573:
2574: @assignment
2575: Write a definition @code{vsum ( addr u -- n )} that computes the sum of
2576: @code{u} cells, with the first of these cells at @code{addr}, the next
2577: one at @code{addr cell+} etc.
2578: @endassignment
2579:
2580: You can also reserve memory without creating a new word:
2581:
2582: @example
1.60 anton 2583: here 10 cells allot .
2584: here .
1.48 anton 2585: @end example
2586:
2587: @code{Here} pushes the start address of the memory area. You should
2588: store it somewhere, or you will have a hard time finding the memory area
2589: again.
2590:
2591: @code{Allot} manages dictionary memory. The dictionary memory contains
2592: the system's data structures for words etc. on Gforth and most other
2593: Forth systems. It is managed like a stack: You can free the memory that
2594: you have just @code{allot}ed with
2595:
2596: @example
2597: -10 cells allot
1.60 anton 2598: here .
1.48 anton 2599: @end example
2600:
2601: Note that you cannot do this if you have created a new word in the
2602: meantime (because then your @code{allot}ed memory is no longer on the
2603: top of the dictionary ``stack'').
2604:
2605: Alternatively, you can use @code{allocate} and @code{free} which allow
2606: freeing memory in any order:
2607:
2608: @example
2609: 10 cells allocate throw .s
2610: 20 cells allocate throw .s
2611: swap
2612: free throw
2613: free throw
2614: @end example
2615:
2616: The @code{throw}s deal with errors (e.g., out of memory).
2617:
1.65 anton 2618: And there is also a
2619: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
2620: garbage collector}, which eliminates the need to @code{free} memory
2621: explicitly.
1.48 anton 2622:
1.66 anton 2623: Reference: @ref{Memory}.
2624:
1.48 anton 2625:
2626: @node Characters and Strings Tutorial, Alignment Tutorial, Memory Tutorial, Tutorial
2627: @section Characters and Strings
1.66 anton 2628: @cindex strings tutorial
2629: @cindex characters tutorial
1.48 anton 2630:
2631: On the stack characters take up a cell, like numbers. In memory they
2632: have their own size (one 8-bit byte on most systems), and therefore
2633: require their own words for memory access:
2634:
2635: @example
2636: create v4
2637: 104 c, 97 c, 108 c, 108 c, 111 c,
1.50 anton 2638: v4 4 chars + c@@ .
1.65 anton 2639: v4 5 chars dump
1.48 anton 2640: @end example
2641:
2642: The preferred representation of strings on the stack is @code{addr
2643: u-count}, where @code{addr} is the address of the first character and
2644: @code{u-count} is the number of characters in the string.
2645:
2646: @example
2647: v4 5 type
2648: @end example
2649:
2650: You get a string constant with
2651:
2652: @example
2653: s" hello, world" .s
2654: type
2655: @end example
2656:
2657: Make sure you have a space between @code{s"} and the string; @code{s"}
2658: is a normal Forth word and must be delimited with white space (try what
2659: happens when you remove the space).
2660:
2661: However, this interpretive use of @code{s"} is quite restricted: the
2662: string exists only until the next call of @code{s"} (some Forth systems
2663: keep more than one of these strings, but usually they still have a
1.62 crook 2664: limited lifetime).
1.48 anton 2665:
2666: @example
2667: s" hello," s" world" .s
2668: type
2669: type
2670: @end example
2671:
1.62 crook 2672: You can also use @code{s"} in a definition, and the resulting
2673: strings then live forever (well, for as long as the definition):
1.48 anton 2674:
2675: @example
2676: : foo s" hello," s" world" ;
2677: foo .s
2678: type
2679: type
2680: @end example
2681:
2682: @assignment
2683: @code{Emit ( c -- )} types @code{c} as character (not a number).
2684: Implement @code{type ( addr u -- )}.
2685: @endassignment
2686:
1.66 anton 2687: Reference: @ref{Memory Blocks}.
2688:
2689:
1.48 anton 2690: @node Alignment Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Characters and Strings Tutorial, Tutorial
2691: @section Alignment
1.66 anton 2692: @cindex alignment tutorial
2693: @cindex memory alignment tutorial
1.48 anton 2694:
2695: On many processors cells have to be aligned in memory, if you want to
2696: access them with @code{@@} and @code{!} (and even if the processor does
1.62 crook 2697: not require alignment, access to aligned cells is faster).
1.48 anton 2698:
2699: @code{Create} aligns @code{here} (i.e., the place where the next
2700: allocation will occur, and that the @code{create}d word points to).
2701: Likewise, the memory produced by @code{allocate} starts at an aligned
2702: address. Adding a number of @code{cells} to an aligned address produces
2703: another aligned address.
2704:
2705: However, address arithmetic involving @code{char+} and @code{chars} can
2706: create an address that is not cell-aligned. @code{Aligned ( addr --
2707: a-addr )} produces the next aligned address:
2708:
2709: @example
1.50 anton 2710: v3 char+ aligned .s @@ .
2711: v3 char+ .s @@ .
1.48 anton 2712: @end example
2713:
2714: Similarly, @code{align} advances @code{here} to the next aligned
2715: address:
2716:
2717: @example
2718: create v5 97 c,
2719: here .
2720: align here .
2721: 1000 ,
2722: @end example
2723:
2724: Note that you should use aligned addresses even if your processor does
2725: not require them, if you want your program to be portable.
2726:
1.66 anton 2727: Reference: @ref{Address arithmetic}.
2728:
1.48 anton 2729:
2730: @node Interpretation and Compilation Semantics and Immediacy Tutorial, Execution Tokens Tutorial, Alignment Tutorial, Tutorial
2731: @section Interpretation and Compilation Semantics and Immediacy
1.66 anton 2732: @cindex semantics tutorial
2733: @cindex interpretation semantics tutorial
2734: @cindex compilation semantics tutorial
2735: @cindex immediate, tutorial
1.48 anton 2736:
2737: When a word is compiled, it behaves differently from being interpreted.
2738: E.g., consider @code{+}:
2739:
2740: @example
2741: 1 2 + .
2742: : foo + ;
2743: @end example
2744:
2745: These two behaviours are known as compilation and interpretation
2746: semantics. For normal words (e.g., @code{+}), the compilation semantics
2747: is to append the interpretation semantics to the currently defined word
2748: (@code{foo} in the example above). I.e., when @code{foo} is executed
2749: later, the interpretation semantics of @code{+} (i.e., adding two
2750: numbers) will be performed.
2751:
2752: However, there are words with non-default compilation semantics, e.g.,
2753: the control-flow words like @code{if}. You can use @code{immediate} to
2754: change the compilation semantics of the last defined word to be equal to
2755: the interpretation semantics:
2756:
2757: @example
2758: : [FOO] ( -- )
2759: 5 . ; immediate
2760:
2761: [FOO]
2762: : bar ( -- )
2763: [FOO] ;
2764: bar
2765: see bar
2766: @end example
2767:
2768: Two conventions to mark words with non-default compilation semnatics are
2769: names with brackets (more frequently used) and to write them all in
2770: upper case (less frequently used).
2771:
2772: In Gforth (and many other systems) you can also remove the
2773: interpretation semantics with @code{compile-only} (the compilation
2774: semantics is derived from the original interpretation semantics):
2775:
2776: @example
2777: : flip ( -- )
2778: 6 . ; compile-only \ but not immediate
2779: flip
2780:
2781: : flop ( -- )
2782: flip ;
2783: flop
2784: @end example
2785:
2786: In this example the interpretation semantics of @code{flop} is equal to
2787: the original interpretation semantics of @code{flip}.
2788:
2789: The text interpreter has two states: in interpret state, it performs the
2790: interpretation semantics of words it encounters; in compile state, it
2791: performs the compilation semantics of these words.
2792:
2793: Among other things, @code{:} switches into compile state, and @code{;}
2794: switches back to interpret state. They contain the factors @code{]}
2795: (switch to compile state) and @code{[} (switch to interpret state), that
2796: do nothing but switch the state.
2797:
2798: @example
2799: : xxx ( -- )
2800: [ 5 . ]
2801: ;
2802:
2803: xxx
2804: see xxx
2805: @end example
2806:
2807: These brackets are also the source of the naming convention mentioned
2808: above.
2809:
1.66 anton 2810: Reference: @ref{Interpretation and Compilation Semantics}.
2811:
1.48 anton 2812:
2813: @node Execution Tokens Tutorial, Exceptions Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Tutorial
2814: @section Execution Tokens
1.66 anton 2815: @cindex execution tokens tutorial
2816: @cindex XT tutorial
1.48 anton 2817:
2818: @code{' word} gives you the execution token (XT) of a word. The XT is a
2819: cell representing the interpretation semantics of a word. You can
2820: execute this semantics with @code{execute}:
2821:
2822: @example
2823: ' + .s
2824: 1 2 rot execute .
2825: @end example
2826:
2827: The XT is similar to a function pointer in C. However, parameter
2828: passing through the stack makes it a little more flexible:
2829:
2830: @example
2831: : map-array ( ... addr u xt -- ... )
1.50 anton 2832: \ executes xt ( ... x -- ... ) for every element of the array starting
2833: \ at addr and containing u elements
1.48 anton 2834: @{ xt @}
2835: cells over + swap ?do
1.50 anton 2836: i @@ xt execute
1.48 anton 2837: 1 cells +loop ;
2838:
2839: create a 3 , 4 , 2 , -1 , 4 ,
2840: a 5 ' . map-array .s
2841: 0 a 5 ' + map-array .
2842: s" max-n" environment? drop .s
2843: a 5 ' min map-array .
2844: @end example
2845:
2846: You can use map-array with the XTs of words that consume one element
2847: more than they produce. In theory you can also use it with other XTs,
2848: but the stack effect then depends on the size of the array, which is
2849: hard to understand.
2850:
1.51 pazsan 2851: Since XTs are cell-sized, you can store them in memory and manipulate
2852: them on the stack like other cells. You can also compile the XT into a
1.48 anton 2853: word with @code{compile,}:
2854:
2855: @example
2856: : foo1 ( n1 n2 -- n )
2857: [ ' + compile, ] ;
2858: see foo
2859: @end example
2860:
2861: This is non-standard, because @code{compile,} has no compilation
2862: semantics in the standard, but it works in good Forth systems. For the
2863: broken ones, use
2864:
2865: @example
2866: : [compile,] compile, ; immediate
2867:
2868: : foo1 ( n1 n2 -- n )
2869: [ ' + ] [compile,] ;
2870: see foo
2871: @end example
2872:
2873: @code{'} is a word with default compilation semantics; it parses the
2874: next word when its interpretation semantics are executed, not during
2875: compilation:
2876:
2877: @example
2878: : foo ( -- xt )
2879: ' ;
2880: see foo
2881: : bar ( ... "word" -- ... )
2882: ' execute ;
2883: see bar
1.60 anton 2884: 1 2 bar + .
1.48 anton 2885: @end example
2886:
2887: You often want to parse a word during compilation and compile its XT so
2888: it will be pushed on the stack at run-time. @code{[']} does this:
2889:
2890: @example
2891: : xt-+ ( -- xt )
2892: ['] + ;
2893: see xt-+
2894: 1 2 xt-+ execute .
2895: @end example
2896:
2897: Many programmers tend to see @code{'} and the word it parses as one
2898: unit, and expect it to behave like @code{[']} when compiled, and are
2899: confused by the actual behaviour. If you are, just remember that the
2900: Forth system just takes @code{'} as one unit and has no idea that it is
2901: a parsing word (attempts to convenience programmers in this issue have
2902: usually resulted in even worse pitfalls, see
1.66 anton 2903: @uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,
2904: @code{State}-smartness---Why it is evil and How to Exorcise it}).
1.48 anton 2905:
2906: Note that the state of the interpreter does not come into play when
1.51 pazsan 2907: creating and executing XTs. I.e., even when you execute @code{'} in
1.48 anton 2908: compile state, it still gives you the interpretation semantics. And
2909: whatever that state is, @code{execute} performs the semantics
1.66 anton 2910: represented by the XT (i.e., for XTs produced with @code{'} the
2911: interpretation semantics).
2912:
2913: Reference: @ref{Tokens for Words}.
1.48 anton 2914:
2915:
2916: @node Exceptions Tutorial, Defining Words Tutorial, Execution Tokens Tutorial, Tutorial
2917: @section Exceptions
1.66 anton 2918: @cindex exceptions tutorial
1.48 anton 2919:
2920: @code{throw ( n -- )} causes an exception unless n is zero.
2921:
2922: @example
2923: 100 throw .s
2924: 0 throw .s
2925: @end example
2926:
2927: @code{catch ( ... xt -- ... n )} behaves similar to @code{execute}, but
2928: it catches exceptions and pushes the number of the exception on the
2929: stack (or 0, if the xt executed without exception). If there was an
2930: exception, the stacks have the same depth as when entering @code{catch}:
2931:
2932: @example
2933: .s
2934: 3 0 ' / catch .s
2935: 3 2 ' / catch .s
2936: @end example
2937:
2938: @assignment
2939: Try the same with @code{execute} instead of @code{catch}.
2940: @endassignment
2941:
2942: @code{Throw} always jumps to the dynamically next enclosing
2943: @code{catch}, even if it has to leave several call levels to achieve
2944: this:
2945:
2946: @example
2947: : foo 100 throw ;
2948: : foo1 foo ." after foo" ;
1.51 pazsan 2949: : bar ['] foo1 catch ;
1.60 anton 2950: bar .
1.48 anton 2951: @end example
2952:
2953: It is often important to restore a value upon leaving a definition, even
2954: if the definition is left through an exception. You can ensure this
2955: like this:
2956:
2957: @example
2958: : ...
2959: save-x
1.51 pazsan 2960: ['] word-changing-x catch ( ... n )
1.48 anton 2961: restore-x
2962: ( ... n ) throw ;
2963: @end example
2964:
1.55 anton 2965: Gforth provides an alternative syntax in addition to @code{catch}:
1.48 anton 2966: @code{try ... recover ... endtry}. If the code between @code{try} and
2967: @code{recover} has an exception, the stack depths are restored, the
2968: exception number is pushed on the stack, and the code between
2969: @code{recover} and @code{endtry} is performed. E.g., the definition for
2970: @code{catch} is
2971:
2972: @example
2973: : catch ( x1 .. xn xt -- y1 .. ym 0 / z1 .. zn error ) \ exception
2974: try
2975: execute 0
2976: recover
2977: nip
2978: endtry ;
2979: @end example
2980:
2981: The equivalent to the restoration code above is
2982:
2983: @example
2984: : ...
2985: save-x
2986: try
2987: word-changing-x
2988: end-try
2989: restore-x
2990: throw ;
2991: @end example
2992:
2993: As you can see, the @code{recover} part is optional.
2994:
1.66 anton 2995: Reference: @ref{Exception Handling}.
2996:
1.48 anton 2997:
2998: @node Defining Words Tutorial, Arrays and Records Tutorial, Exceptions Tutorial, Tutorial
2999: @section Defining Words
1.66 anton 3000: @cindex defining words tutorial
3001: @cindex does> tutorial
3002: @cindex create...does> tutorial
3003:
3004: @c before semantics?
1.48 anton 3005:
3006: @code{:}, @code{create}, and @code{variable} are definition words: They
3007: define other words. @code{Constant} is another definition word:
3008:
3009: @example
3010: 5 constant foo
3011: foo .
3012: @end example
3013:
3014: You can also use the prefixes @code{2} (double-cell) and @code{f}
3015: (floating point) with @code{variable} and @code{constant}.
3016:
3017: You can also define your own defining words. E.g.:
3018:
3019: @example
3020: : variable ( "name" -- )
3021: create 0 , ;
3022: @end example
3023:
3024: You can also define defining words that create words that do something
3025: other than just producing their address:
3026:
3027: @example
3028: : constant ( n "name" -- )
3029: create ,
3030: does> ( -- n )
1.50 anton 3031: ( addr ) @@ ;
1.48 anton 3032:
3033: 5 constant foo
3034: foo .
3035: @end example
3036:
3037: The definition of @code{constant} above ends at the @code{does>}; i.e.,
3038: @code{does>} replaces @code{;}, but it also does something else: It
3039: changes the last defined word such that it pushes the address of the
3040: body of the word and then performs the code after the @code{does>}
3041: whenever it is called.
3042:
3043: In the example above, @code{constant} uses @code{,} to store 5 into the
3044: body of @code{foo}. When @code{foo} executes, it pushes the address of
3045: the body onto the stack, then (in the code after the @code{does>})
3046: fetches the 5 from there.
3047:
3048: The stack comment near the @code{does>} reflects the stack effect of the
3049: defined word, not the stack effect of the code after the @code{does>}
3050: (the difference is that the code expects the address of the body that
3051: the stack comment does not show).
3052:
3053: You can use these definition words to do factoring in cases that involve
3054: (other) definition words. E.g., a field offset is always added to an
3055: address. Instead of defining
3056:
3057: @example
3058: 2 cells constant offset-field1
3059: @end example
3060:
3061: and using this like
3062:
3063: @example
3064: ( addr ) offset-field1 +
3065: @end example
3066:
3067: you can define a definition word
3068:
3069: @example
3070: : simple-field ( n "name" -- )
3071: create ,
3072: does> ( n1 -- n1+n )
1.50 anton 3073: ( addr ) @@ + ;
1.48 anton 3074: @end example
1.21 crook 3075:
1.48 anton 3076: Definition and use of field offsets now look like this:
1.21 crook 3077:
1.48 anton 3078: @example
3079: 2 cells simple-field field1
1.60 anton 3080: create mystruct 4 cells allot
3081: mystruct .s field1 .s drop
1.48 anton 3082: @end example
1.21 crook 3083:
1.48 anton 3084: If you want to do something with the word without performing the code
3085: after the @code{does>}, you can access the body of a @code{create}d word
3086: with @code{>body ( xt -- addr )}:
1.21 crook 3087:
1.48 anton 3088: @example
3089: : value ( n "name" -- )
3090: create ,
3091: does> ( -- n1 )
1.50 anton 3092: @@ ;
1.48 anton 3093: : to ( n "name" -- )
3094: ' >body ! ;
1.21 crook 3095:
1.48 anton 3096: 5 value foo
3097: foo .
3098: 7 to foo
3099: foo .
3100: @end example
1.21 crook 3101:
1.48 anton 3102: @assignment
3103: Define @code{defer ( "name" -- )}, which creates a word that stores an
3104: XT (at the start the XT of @code{abort}), and upon execution
3105: @code{execute}s the XT. Define @code{is ( xt "name" -- )} that stores
3106: @code{xt} into @code{name}, a word defined with @code{defer}. Indirect
3107: recursion is one application of @code{defer}.
3108: @endassignment
1.29 crook 3109:
1.66 anton 3110: Reference: @ref{User-defined Defining Words}.
3111:
3112:
1.48 anton 3113: @node Arrays and Records Tutorial, POSTPONE Tutorial, Defining Words Tutorial, Tutorial
3114: @section Arrays and Records
1.66 anton 3115: @cindex arrays tutorial
3116: @cindex records tutorial
3117: @cindex structs tutorial
1.29 crook 3118:
1.48 anton 3119: Forth has no standard words for defining data structures such as arrays
3120: and records (structs in C terminology), but you can build them yourself
3121: based on address arithmetic. You can also define words for defining
3122: arrays and records (@pxref{Defining Words Tutorial,, Defining Words}).
1.29 crook 3123:
1.48 anton 3124: One of the first projects a Forth newcomer sets out upon when learning
3125: about defining words is an array defining word (possibly for
3126: n-dimensional arrays). Go ahead and do it, I did it, too; you will
3127: learn something from it. However, don't be disappointed when you later
3128: learn that you have little use for these words (inappropriate use would
3129: be even worse). I have not yet found a set of useful array words yet;
3130: the needs are just too diverse, and named, global arrays (the result of
3131: naive use of defining words) are often not flexible enough (e.g.,
1.66 anton 3132: consider how to pass them as parameters). Another such project is a set
3133: of words to help dealing with strings.
1.29 crook 3134:
1.48 anton 3135: On the other hand, there is a useful set of record words, and it has
3136: been defined in @file{compat/struct.fs}; these words are predefined in
3137: Gforth. They are explained in depth elsewhere in this manual (see
3138: @pxref{Structures}). The @code{simple-field} example above is
3139: simplified variant of fields in this package.
1.21 crook 3140:
3141:
1.48 anton 3142: @node POSTPONE Tutorial, Literal Tutorial, Arrays and Records Tutorial, Tutorial
3143: @section @code{POSTPONE}
1.66 anton 3144: @cindex postpone tutorial
1.21 crook 3145:
1.48 anton 3146: You can compile the compilation semantics (instead of compiling the
3147: interpretation semantics) of a word with @code{POSTPONE}:
1.21 crook 3148:
1.48 anton 3149: @example
3150: : MY-+ ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
1.51 pazsan 3151: POSTPONE + ; immediate
1.48 anton 3152: : foo ( n1 n2 -- n )
3153: MY-+ ;
3154: 1 2 foo .
3155: see foo
3156: @end example
1.21 crook 3157:
1.48 anton 3158: During the definition of @code{foo} the text interpreter performs the
3159: compilation semantics of @code{MY-+}, which performs the compilation
3160: semantics of @code{+}, i.e., it compiles @code{+} into @code{foo}.
3161:
3162: This example also displays separate stack comments for the compilation
3163: semantics and for the stack effect of the compiled code. For words with
3164: default compilation semantics these stack effects are usually not
3165: displayed; the stack effect of the compilation semantics is always
3166: @code{( -- )} for these words, the stack effect for the compiled code is
3167: the stack effect of the interpretation semantics.
3168:
3169: Note that the state of the interpreter does not come into play when
3170: performing the compilation semantics in this way. You can also perform
3171: it interpretively, e.g.:
3172:
3173: @example
3174: : foo2 ( n1 n2 -- n )
3175: [ MY-+ ] ;
3176: 1 2 foo .
3177: see foo
3178: @end example
1.21 crook 3179:
1.48 anton 3180: However, there are some broken Forth systems where this does not always
1.62 crook 3181: work, and therefore this practice was been declared non-standard in
1.48 anton 3182: 1999.
3183: @c !! repair.fs
3184:
3185: Here is another example for using @code{POSTPONE}:
1.44 crook 3186:
1.48 anton 3187: @example
3188: : MY-- ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
3189: POSTPONE negate POSTPONE + ; immediate compile-only
3190: : bar ( n1 n2 -- n )
3191: MY-- ;
3192: 2 1 bar .
3193: see bar
3194: @end example
1.21 crook 3195:
1.48 anton 3196: You can define @code{ENDIF} in this way:
1.21 crook 3197:
1.48 anton 3198: @example
3199: : ENDIF ( Compilation: orig -- )
3200: POSTPONE then ; immediate
3201: @end example
1.21 crook 3202:
1.48 anton 3203: @assignment
3204: Write @code{MY-2DUP} that has compilation semantics equivalent to
3205: @code{2dup}, but compiles @code{over over}.
3206: @endassignment
1.29 crook 3207:
1.66 anton 3208: @c !! @xref{Macros} for reference
3209:
3210:
1.48 anton 3211: @node Literal Tutorial, Advanced macros Tutorial, POSTPONE Tutorial, Tutorial
3212: @section @code{Literal}
1.66 anton 3213: @cindex literal tutorial
1.29 crook 3214:
1.48 anton 3215: You cannot @code{POSTPONE} numbers:
1.21 crook 3216:
1.48 anton 3217: @example
3218: : [FOO] POSTPONE 500 ; immediate
1.21 crook 3219: @end example
3220:
1.48 anton 3221: Instead, you can use @code{LITERAL (compilation: n --; run-time: -- n )}:
1.29 crook 3222:
1.48 anton 3223: @example
3224: : [FOO] ( compilation: --; run-time: -- n )
3225: 500 POSTPONE literal ; immediate
1.29 crook 3226:
1.60 anton 3227: : flip [FOO] ;
1.48 anton 3228: flip .
3229: see flip
3230: @end example
1.29 crook 3231:
1.48 anton 3232: @code{LITERAL} consumes a number at compile-time (when it's compilation
3233: semantics are executed) and pushes it at run-time (when the code it
3234: compiled is executed). A frequent use of @code{LITERAL} is to compile a
3235: number computed at compile time into the current word:
1.29 crook 3236:
1.48 anton 3237: @example
3238: : bar ( -- n )
3239: [ 2 2 + ] literal ;
3240: see bar
3241: @end example
1.29 crook 3242:
1.48 anton 3243: @assignment
3244: Write @code{]L} which allows writing the example above as @code{: bar (
3245: -- n ) [ 2 2 + ]L ;}
3246: @endassignment
3247:
1.66 anton 3248: @c !! @xref{Macros} for reference
3249:
1.48 anton 3250:
3251: @node Advanced macros Tutorial, Compilation Tokens Tutorial, Literal Tutorial, Tutorial
3252: @section Advanced macros
1.66 anton 3253: @cindex macros, advanced tutorial
3254: @cindex run-time code generation, tutorial
1.48 anton 3255:
1.66 anton 3256: Reconsider @code{map-array} from @ref{Execution Tokens Tutorial,,
3257: Execution Tokens}. It frequently performs @code{execute}, a relatively
3258: expensive operation in some Forth implementations. You can use
1.48 anton 3259: @code{compile,} and @code{POSTPONE} to eliminate these @code{execute}s
3260: and produce a word that contains the word to be performed directly:
3261:
3262: @c use ]] ... [[
3263: @example
3264: : compile-map-array ( compilation: xt -- ; run-time: ... addr u -- ... )
3265: \ at run-time, execute xt ( ... x -- ... ) for each element of the
3266: \ array beginning at addr and containing u elements
3267: @{ xt @}
3268: POSTPONE cells POSTPONE over POSTPONE + POSTPONE swap POSTPONE ?do
1.50 anton 3269: POSTPONE i POSTPONE @@ xt compile,
1.48 anton 3270: 1 cells POSTPONE literal POSTPONE +loop ;
3271:
3272: : sum-array ( addr u -- n )
3273: 0 rot rot [ ' + compile-map-array ] ;
3274: see sum-array
3275: a 5 sum-array .
3276: @end example
3277:
3278: You can use the full power of Forth for generating the code; here's an
3279: example where the code is generated in a loop:
3280:
3281: @example
3282: : compile-vmul-step ( compilation: n --; run-time: n1 addr1 -- n2 addr2 )
3283: \ n2=n1+(addr1)*n, addr2=addr1+cell
1.50 anton 3284: POSTPONE tuck POSTPONE @@
1.48 anton 3285: POSTPONE literal POSTPONE * POSTPONE +
3286: POSTPONE swap POSTPONE cell+ ;
3287:
3288: : compile-vmul ( compilation: addr1 u -- ; run-time: addr2 -- n )
1.51 pazsan 3289: \ n=v1*v2 (inner product), where the v_i are represented as addr_i u
1.48 anton 3290: 0 postpone literal postpone swap
3291: [ ' compile-vmul-step compile-map-array ]
3292: postpone drop ;
3293: see compile-vmul
3294:
3295: : a-vmul ( addr -- n )
1.51 pazsan 3296: \ n=a*v, where v is a vector that's as long as a and starts at addr
1.48 anton 3297: [ a 5 compile-vmul ] ;
3298: see a-vmul
3299: a a-vmul .
3300: @end example
3301:
3302: This example uses @code{compile-map-array} to show off, but you could
1.66 anton 3303: also use @code{map-array} instead (try it now!).
1.48 anton 3304:
3305: You can use this technique for efficient multiplication of large
3306: matrices. In matrix multiplication, you multiply every line of one
3307: matrix with every column of the other matrix. You can generate the code
3308: for one line once, and use it for every column. The only downside of
3309: this technique is that it is cumbersome to recover the memory consumed
3310: by the generated code when you are done (and in more complicated cases
3311: it is not possible portably).
3312:
1.66 anton 3313: @c !! @xref{Macros} for reference
3314:
3315:
1.48 anton 3316: @node Compilation Tokens Tutorial, Wordlists and Search Order Tutorial, Advanced macros Tutorial, Tutorial
3317: @section Compilation Tokens
1.66 anton 3318: @cindex compilation tokens, tutorial
3319: @cindex CT, tutorial
1.48 anton 3320:
3321: This section is Gforth-specific. You can skip it.
3322:
3323: @code{' word compile,} compiles the interpretation semantics. For words
3324: with default compilation semantics this is the same as performing the
3325: compilation semantics. To represent the compilation semantics of other
3326: words (e.g., words like @code{if} that have no interpretation
3327: semantics), Gforth has the concept of a compilation token (CT,
3328: consisting of two cells), and words @code{comp'} and @code{[comp']}.
3329: You can perform the compilation semantics represented by a CT with
3330: @code{execute}:
1.29 crook 3331:
1.48 anton 3332: @example
3333: : foo2 ( n1 n2 -- n )
3334: [ comp' + execute ] ;
3335: see foo
3336: @end example
1.29 crook 3337:
1.48 anton 3338: You can compile the compilation semantics represented by a CT with
3339: @code{postpone,}:
1.30 anton 3340:
1.48 anton 3341: @example
3342: : foo3 ( -- )
3343: [ comp' + postpone, ] ;
3344: see foo3
3345: @end example
1.30 anton 3346:
1.51 pazsan 3347: @code{[ comp' word postpone, ]} is equivalent to @code{POSTPONE word}.
1.48 anton 3348: @code{comp'} is particularly useful for words that have no
3349: interpretation semantics:
1.29 crook 3350:
1.30 anton 3351: @example
1.48 anton 3352: ' if
1.60 anton 3353: comp' if .s 2drop
1.30 anton 3354: @end example
3355:
1.66 anton 3356: Reference: @ref{Tokens for Words}.
3357:
1.29 crook 3358:
1.48 anton 3359: @node Wordlists and Search Order Tutorial, , Compilation Tokens Tutorial, Tutorial
3360: @section Wordlists and Search Order
1.66 anton 3361: @cindex wordlists tutorial
3362: @cindex search order, tutorial
1.48 anton 3363:
3364: The dictionary is not just a memory area that allows you to allocate
3365: memory with @code{allot}, it also contains the Forth words, arranged in
3366: several wordlists. When searching for a word in a wordlist,
3367: conceptually you start searching at the youngest and proceed towards
3368: older words (in reality most systems nowadays use hash-tables); i.e., if
3369: you define a word with the same name as an older word, the new word
3370: shadows the older word.
3371:
3372: Which wordlists are searched in which order is determined by the search
3373: order. You can display the search order with @code{order}. It displays
3374: first the search order, starting with the wordlist searched first, then
3375: it displays the wordlist that will contain newly defined words.
1.21 crook 3376:
1.48 anton 3377: You can create a new, empty wordlist with @code{wordlist ( -- wid )}:
1.21 crook 3378:
1.48 anton 3379: @example
3380: wordlist constant mywords
3381: @end example
1.21 crook 3382:
1.48 anton 3383: @code{Set-current ( wid -- )} sets the wordlist that will contain newly
3384: defined words (the @emph{current} wordlist):
1.21 crook 3385:
1.48 anton 3386: @example
3387: mywords set-current
3388: order
3389: @end example
1.26 crook 3390:
1.48 anton 3391: Gforth does not display a name for the wordlist in @code{mywords}
3392: because this wordlist was created anonymously with @code{wordlist}.
1.21 crook 3393:
1.48 anton 3394: You can get the current wordlist with @code{get-current ( -- wid)}. If
3395: you want to put something into a specific wordlist without overall
3396: effect on the current wordlist, this typically looks like this:
1.21 crook 3397:
1.48 anton 3398: @example
3399: get-current mywords set-current ( wid )
3400: create someword
3401: ( wid ) set-current
3402: @end example
1.21 crook 3403:
1.48 anton 3404: You can write the search order with @code{set-order ( wid1 .. widn n --
3405: )} and read it with @code{get-order ( -- wid1 .. widn n )}. The first
3406: searched wordlist is topmost.
1.21 crook 3407:
1.48 anton 3408: @example
3409: get-order mywords swap 1+ set-order
3410: order
3411: @end example
1.21 crook 3412:
1.48 anton 3413: Yes, the order of wordlists in the output of @code{order} is reversed
3414: from stack comments and the output of @code{.s} and thus unintuitive.
1.21 crook 3415:
1.48 anton 3416: @assignment
3417: Define @code{>order ( wid -- )} with adds @code{wid} as first searched
3418: wordlist to the search order. Define @code{previous ( -- )}, which
3419: removes the first searched wordlist from the search order. Experiment
3420: with boundary conditions (you will see some crashes or situations that
3421: are hard or impossible to leave).
3422: @endassignment
1.21 crook 3423:
1.48 anton 3424: The search order is a powerful foundation for providing features similar
3425: to Modula-2 modules and C++ namespaces. However, trying to modularize
3426: programs in this way has disadvantages for debugging and reuse/factoring
3427: that overcome the advantages in my experience (I don't do huge projects,
1.55 anton 3428: though). These disadvantages are not so clear in other
1.82 ! anton 3429: languages/programming environments, because these languages are not so
1.48 anton 3430: strong in debugging and reuse.
1.21 crook 3431:
1.66 anton 3432: @c !! example
3433:
3434: Reference: @ref{Word Lists}.
1.21 crook 3435:
1.29 crook 3436: @c ******************************************************************
1.48 anton 3437: @node Introduction, Words, Tutorial, Top
1.29 crook 3438: @comment node-name, next, previous, up
3439: @chapter An Introduction to ANS Forth
3440: @cindex Forth - an introduction
1.21 crook 3441:
1.29 crook 3442: The primary purpose of this manual is to document Gforth. However, since
3443: Forth is not a widely-known language and there is a lack of up-to-date
3444: teaching material, it seems worthwhile to provide some introductory
1.49 anton 3445: material. For other sources of Forth-related
3446: information, see @ref{Forth-related information}.
1.21 crook 3447:
1.29 crook 3448: The examples in this section should work on any ANS Forth; the
3449: output shown was produced using Gforth. Each example attempts to
3450: reproduce the exact output that Gforth produces. If you try out the
3451: examples (and you should), what you should type is shown @kbd{like this}
3452: and Gforth's response is shown @code{like this}. The single exception is
1.30 anton 3453: that, where the example shows @key{RET} it means that you should
1.29 crook 3454: press the ``carriage return'' key. Unfortunately, some output formats for
3455: this manual cannot show the difference between @kbd{this} and
3456: @code{this} which will make trying out the examples harder (but not
3457: impossible).
1.21 crook 3458:
1.29 crook 3459: Forth is an unusual language. It provides an interactive development
3460: environment which includes both an interpreter and compiler. Forth
3461: programming style encourages you to break a problem down into many
3462: @cindex factoring
3463: small fragments (@dfn{factoring}), and then to develop and test each
3464: fragment interactively. Forth advocates assert that breaking the
3465: edit-compile-test cycle used by conventional programming languages can
3466: lead to great productivity improvements.
1.21 crook 3467:
1.29 crook 3468: @menu
1.67 anton 3469: * Introducing the Text Interpreter::
3470: * Stacks and Postfix notation::
3471: * Your first definition::
3472: * How does that work?::
3473: * Forth is written in Forth::
3474: * Review - elements of a Forth system::
3475: * Where to go next::
3476: * Exercises::
1.29 crook 3477: @end menu
1.21 crook 3478:
1.29 crook 3479: @comment ----------------------------------------------
3480: @node Introducing the Text Interpreter, Stacks and Postfix notation, Introduction, Introduction
3481: @section Introducing the Text Interpreter
3482: @cindex text interpreter
3483: @cindex outer interpreter
1.21 crook 3484:
1.30 anton 3485: @c IMO this is too detailed and the pace is too slow for
3486: @c an introduction. If you know German, take a look at
3487: @c http://www.complang.tuwien.ac.at/anton/lvas/skriptum-stack.html
3488: @c to see how I do it - anton
3489:
1.44 crook 3490: @c nac-> Where I have accepted your comments 100% and modified the text
3491: @c accordingly, I have deleted your comments. Elsewhere I have added a
3492: @c response like this to attempt to rationalise what I have done. Of
3493: @c course, this is a very clumsy mechanism for something that would be
3494: @c done far more efficiently over a beer. Please delete any dialogue
3495: @c you consider closed.
3496:
1.29 crook 3497: When you invoke the Forth image, you will see a startup banner printed
3498: and nothing else (if you have Gforth installed on your system, try
1.30 anton 3499: invoking it now, by typing @kbd{gforth@key{RET}}). Forth is now running
1.29 crook 3500: its command line interpreter, which is called the @dfn{Text Interpreter}
3501: (also known as the @dfn{Outer Interpreter}). (You will learn a lot
1.49 anton 3502: about the text interpreter as you read through this chapter, for more
3503: detail @pxref{The Text Interpreter}).
1.21 crook 3504:
1.29 crook 3505: Although it's not obvious, Forth is actually waiting for your
1.30 anton 3506: input. Type a number and press the @key{RET} key:
1.21 crook 3507:
1.26 crook 3508: @example
1.30 anton 3509: @kbd{45@key{RET}} ok
1.26 crook 3510: @end example
1.21 crook 3511:
1.29 crook 3512: Rather than give you a prompt to invite you to input something, the text
3513: interpreter prints a status message @i{after} it has processed a line
3514: of input. The status message in this case (``@code{ ok}'' followed by
3515: carriage-return) indicates that the text interpreter was able to process
3516: all of your input successfully. Now type something illegal:
3517:
3518: @example
1.30 anton 3519: @kbd{qwer341@key{RET}}
1.29 crook 3520: :1: Undefined word
3521: qwer341
3522: ^^^^^^^
3523: $400D2BA8 Bounce
3524: $400DBDA8 no.extensions
3525: @end example
1.23 crook 3526:
1.29 crook 3527: The exact text, other than the ``Undefined word'' may differ slightly on
3528: your system, but the effect is the same; when the text interpreter
3529: detects an error, it discards any remaining text on a line, resets
1.49 anton 3530: certain internal state and prints an error message. For a detailed description of error messages see @ref{Error
3531: messages}.
1.23 crook 3532:
1.29 crook 3533: The text interpreter waits for you to press carriage-return, and then
3534: processes your input line. Starting at the beginning of the line, it
3535: breaks the line into groups of characters separated by spaces. For each
3536: group of characters in turn, it makes two attempts to do something:
1.23 crook 3537:
1.29 crook 3538: @itemize @bullet
3539: @item
1.44 crook 3540: @cindex name dictionary
1.29 crook 3541: It tries to treat it as a command. It does this by searching a @dfn{name
3542: dictionary}. If the group of characters matches an entry in the name
3543: dictionary, the name dictionary provides the text interpreter with
3544: information that allows the text interpreter perform some actions. In
3545: Forth jargon, we say that the group
3546: @cindex word
3547: @cindex definition
3548: @cindex execution token
3549: @cindex xt
3550: of characters names a @dfn{word}, that the dictionary search returns an
3551: @dfn{execution token (xt)} corresponding to the @dfn{definition} of the
3552: word, and that the text interpreter executes the xt. Often, the terms
3553: @dfn{word} and @dfn{definition} are used interchangeably.
3554: @item
3555: If the text interpreter fails to find a match in the name dictionary, it
3556: tries to treat the group of characters as a number in the current number
3557: base (when you start up Forth, the current number base is base 10). If
3558: the group of characters legitimately represents a number, the text
3559: interpreter pushes the number onto a stack (we'll learn more about that
3560: in the next section).
3561: @end itemize
1.23 crook 3562:
1.29 crook 3563: If the text interpreter is unable to do either of these things with any
3564: group of characters, it discards the group of characters and the rest of
3565: the line, then prints an error message. If the text interpreter reaches
3566: the end of the line without error, it prints the status message ``@code{ ok}''
3567: followed by carriage-return.
1.21 crook 3568:
1.29 crook 3569: This is the simplest command we can give to the text interpreter:
1.23 crook 3570:
3571: @example
1.30 anton 3572: @key{RET} ok
1.23 crook 3573: @end example
1.21 crook 3574:
1.29 crook 3575: The text interpreter did everything we asked it to do (nothing) without
3576: an error, so it said that everything is ``@code{ ok}''. Try a slightly longer
3577: command:
1.21 crook 3578:
1.23 crook 3579: @example
1.30 anton 3580: @kbd{12 dup fred dup@key{RET}}
1.29 crook 3581: :1: Undefined word
3582: 12 dup fred dup
3583: ^^^^
3584: $400D2BA8 Bounce
3585: $400DBDA8 no.extensions
1.23 crook 3586: @end example
1.21 crook 3587:
1.29 crook 3588: When you press the carriage-return key, the text interpreter starts to
3589: work its way along the line:
1.21 crook 3590:
1.29 crook 3591: @itemize @bullet
3592: @item
3593: When it gets to the space after the @code{2}, it takes the group of
3594: characters @code{12} and looks them up in the name
3595: dictionary@footnote{We can't tell if it found them or not, but assume
3596: for now that it did not}. There is no match for this group of characters
3597: in the name dictionary, so it tries to treat them as a number. It is
3598: able to do this successfully, so it puts the number, 12, ``on the stack''
3599: (whatever that means).
3600: @item
3601: The text interpreter resumes scanning the line and gets the next group
3602: of characters, @code{dup}. It looks it up in the name dictionary and
3603: (you'll have to take my word for this) finds it, and executes the word
3604: @code{dup} (whatever that means).
3605: @item
3606: Once again, the text interpreter resumes scanning the line and gets the
3607: group of characters @code{fred}. It looks them up in the name
3608: dictionary, but can't find them. It tries to treat them as a number, but
3609: they don't represent any legal number.
3610: @end itemize
1.21 crook 3611:
1.29 crook 3612: At this point, the text interpreter gives up and prints an error
3613: message. The error message shows exactly how far the text interpreter
3614: got in processing the line. In particular, it shows that the text
3615: interpreter made no attempt to do anything with the final character
3616: group, @code{dup}, even though we have good reason to believe that the
3617: text interpreter would have no problem looking that word up and
3618: executing it a second time.
1.21 crook 3619:
3620:
1.29 crook 3621: @comment ----------------------------------------------
3622: @node Stacks and Postfix notation, Your first definition, Introducing the Text Interpreter, Introduction
3623: @section Stacks, postfix notation and parameter passing
3624: @cindex text interpreter
3625: @cindex outer interpreter
1.21 crook 3626:
1.29 crook 3627: In procedural programming languages (like C and Pascal), the
3628: building-block of programs is the @dfn{function} or @dfn{procedure}. These
3629: functions or procedures are called with @dfn{explicit parameters}. For
3630: example, in C we might write:
1.21 crook 3631:
1.23 crook 3632: @example
1.29 crook 3633: total = total + new_volume(length,height,depth);
1.23 crook 3634: @end example
1.21 crook 3635:
1.23 crook 3636: @noindent
1.29 crook 3637: where new_volume is a function-call to another piece of code, and total,
3638: length, height and depth are all variables. length, height and depth are
3639: parameters to the function-call.
1.21 crook 3640:
1.29 crook 3641: In Forth, the equivalent of the function or procedure is the
3642: @dfn{definition} and parameters are implicitly passed between
3643: definitions using a shared stack that is visible to the
3644: programmer. Although Forth does support variables, the existence of the
3645: stack means that they are used far less often than in most other
3646: programming languages. When the text interpreter encounters a number, it
3647: will place (@dfn{push}) it on the stack. There are several stacks (the
1.30 anton 3648: actual number is implementation-dependent ...) and the particular stack
1.29 crook 3649: used for any operation is implied unambiguously by the operation being
3650: performed. The stack used for all integer operations is called the @dfn{data
3651: stack} and, since this is the stack used most commonly, references to
3652: ``the data stack'' are often abbreviated to ``the stack''.
1.21 crook 3653:
1.29 crook 3654: The stacks have a last-in, first-out (LIFO) organisation. If you type:
1.21 crook 3655:
1.23 crook 3656: @example
1.30 anton 3657: @kbd{1 2 3@key{RET}} ok
1.23 crook 3658: @end example
1.21 crook 3659:
1.29 crook 3660: Then this instructs the text interpreter to placed three numbers on the
3661: (data) stack. An analogy for the behaviour of the stack is to take a
3662: pack of playing cards and deal out the ace (1), 2 and 3 into a pile on
3663: the table. The 3 was the last card onto the pile (``last-in'') and if
3664: you take a card off the pile then, unless you're prepared to fiddle a
3665: bit, the card that you take off will be the 3 (``first-out''). The
3666: number that will be first-out of the stack is called the @dfn{top of
3667: stack}, which
3668: @cindex TOS definition
3669: is often abbreviated to @dfn{TOS}.
1.21 crook 3670:
1.29 crook 3671: To understand how parameters are passed in Forth, consider the
3672: behaviour of the definition @code{+} (pronounced ``plus''). You will not
3673: be surprised to learn that this definition performs addition. More
3674: precisely, it adds two number together and produces a result. Where does
3675: it get the two numbers from? It takes the top two numbers off the
3676: stack. Where does it place the result? On the stack. You can act-out the
3677: behaviour of @code{+} with your playing cards like this:
1.21 crook 3678:
3679: @itemize @bullet
3680: @item
1.29 crook 3681: Pick up two cards from the stack on the table
1.21 crook 3682: @item
1.29 crook 3683: Stare at them intently and ask yourself ``what @i{is} the sum of these two
3684: numbers''
1.21 crook 3685: @item
1.29 crook 3686: Decide that the answer is 5
1.21 crook 3687: @item
1.29 crook 3688: Shuffle the two cards back into the pack and find a 5
1.21 crook 3689: @item
1.29 crook 3690: Put a 5 on the remaining ace that's on the table.
1.21 crook 3691: @end itemize
3692:
1.29 crook 3693: If you don't have a pack of cards handy but you do have Forth running,
3694: you can use the definition @code{.s} to show the current state of the stack,
3695: without affecting the stack. Type:
1.21 crook 3696:
3697: @example
1.30 anton 3698: @kbd{clearstack 1 2 3@key{RET}} ok
3699: @kbd{.s@key{RET}} <3> 1 2 3 ok
1.23 crook 3700: @end example
3701:
1.29 crook 3702: The text interpreter looks up the word @code{clearstack} and executes
3703: it; it tidies up the stack and removes any entries that may have been
3704: left on it by earlier examples. The text interpreter pushes each of the
3705: three numbers in turn onto the stack. Finally, the text interpreter
3706: looks up the word @code{.s} and executes it. The effect of executing
3707: @code{.s} is to print the ``<3>'' (the total number of items on the stack)
3708: followed by a list of all the items on the stack; the item on the far
3709: right-hand side is the TOS.
1.21 crook 3710:
1.29 crook 3711: You can now type:
1.21 crook 3712:
1.29 crook 3713: @example
1.30 anton 3714: @kbd{+ .s@key{RET}} <2> 1 5 ok
1.29 crook 3715: @end example
1.21 crook 3716:
1.29 crook 3717: @noindent
3718: which is correct; there are now 2 items on the stack and the result of
3719: the addition is 5.
1.23 crook 3720:
1.29 crook 3721: If you're playing with cards, try doing a second addition: pick up the
3722: two cards, work out that their sum is 6, shuffle them into the pack,
3723: look for a 6 and place that on the table. You now have just one item on
3724: the stack. What happens if you try to do a third addition? Pick up the
3725: first card, pick up the second card -- ah! There is no second card. This
3726: is called a @dfn{stack underflow} and consitutes an error. If you try to
3727: do the same thing with Forth it will report an error (probably a Stack
3728: Underflow or an Invalid Memory Address error).
1.23 crook 3729:
1.29 crook 3730: The opposite situation to a stack underflow is a @dfn{stack overflow},
3731: which simply accepts that there is a finite amount of storage space
3732: reserved for the stack. To stretch the playing card analogy, if you had
3733: enough packs of cards and you piled the cards up on the table, you would
3734: eventually be unable to add another card; you'd hit the ceiling. Gforth
3735: allows you to set the maximum size of the stacks. In general, the only
3736: time that you will get a stack overflow is because a definition has a
3737: bug in it and is generating data on the stack uncontrollably.
1.23 crook 3738:
1.29 crook 3739: There's one final use for the playing card analogy. If you model your
3740: stack using a pack of playing cards, the maximum number of items on
3741: your stack will be 52 (I assume you didn't use the Joker). The maximum
3742: @i{value} of any item on the stack is 13 (the King). In fact, the only
3743: possible numbers are positive integer numbers 1 through 13; you can't
3744: have (for example) 0 or 27 or 3.52 or -2. If you change the way you
3745: think about some of the cards, you can accommodate different
3746: numbers. For example, you could think of the Jack as representing 0,
3747: the Queen as representing -1 and the King as representing -2. Your
1.45 crook 3748: @i{range} remains unchanged (you can still only represent a total of 13
1.29 crook 3749: numbers) but the numbers that you can represent are -2 through 10.
1.28 crook 3750:
1.29 crook 3751: In that analogy, the limit was the amount of information that a single
3752: stack entry could hold, and Forth has a similar limit. In Forth, the
3753: size of a stack entry is called a @dfn{cell}. The actual size of a cell is
3754: implementation dependent and affects the maximum value that a stack
3755: entry can hold. A Standard Forth provides a cell size of at least
3756: 16-bits, and most desktop systems use a cell size of 32-bits.
1.21 crook 3757:
1.29 crook 3758: Forth does not do any type checking for you, so you are free to
3759: manipulate and combine stack items in any way you wish. A convenient way
3760: of treating stack items is as 2's complement signed integers, and that
3761: is what Standard words like @code{+} do. Therefore you can type:
1.21 crook 3762:
1.29 crook 3763: @example
1.30 anton 3764: @kbd{-5 12 + .s@key{RET}} <1> 7 ok
1.29 crook 3765: @end example
1.21 crook 3766:
1.29 crook 3767: If you use numbers and definitions like @code{+} in order to turn Forth
3768: into a great big pocket calculator, you will realise that it's rather
3769: different from a normal calculator. Rather than typing 2 + 3 = you had
3770: to type 2 3 + (ignore the fact that you had to use @code{.s} to see the
3771: result). The terminology used to describe this difference is to say that
3772: your calculator uses @dfn{Infix Notation} (parameters and operators are
3773: mixed) whilst Forth uses @dfn{Postfix Notation} (parameters and
3774: operators are separate), also called @dfn{Reverse Polish Notation}.
1.21 crook 3775:
1.29 crook 3776: Whilst postfix notation might look confusing to begin with, it has
3777: several important advantages:
1.21 crook 3778:
1.23 crook 3779: @itemize @bullet
3780: @item
1.29 crook 3781: it is unambiguous
1.23 crook 3782: @item
1.29 crook 3783: it is more concise
1.23 crook 3784: @item
1.29 crook 3785: it fits naturally with a stack-based system
1.23 crook 3786: @end itemize
1.21 crook 3787:
1.29 crook 3788: To examine these claims in more detail, consider these sums:
1.21 crook 3789:
1.29 crook 3790: @example
3791: 6 + 5 * 4 =
3792: 4 * 5 + 6 =
3793: @end example
1.21 crook 3794:
1.29 crook 3795: If you're just learning maths or your maths is very rusty, you will
3796: probably come up with the answer 44 for the first and 26 for the
3797: second. If you are a bit of a whizz at maths you will remember the
3798: @i{convention} that multiplication takes precendence over addition, and
3799: you'd come up with the answer 26 both times. To explain the answer 26
3800: to someone who got the answer 44, you'd probably rewrite the first sum
3801: like this:
1.21 crook 3802:
1.29 crook 3803: @example
3804: 6 + (5 * 4) =
3805: @end example
1.21 crook 3806:
1.29 crook 3807: If what you really wanted was to perform the addition before the
3808: multiplication, you would have to use parentheses to force it.
1.21 crook 3809:
1.29 crook 3810: If you did the first two sums on a pocket calculator you would probably
3811: get the right answers, unless you were very cautious and entered them using
3812: these keystroke sequences:
1.21 crook 3813:
1.29 crook 3814: 6 + 5 = * 4 =
3815: 4 * 5 = + 6 =
1.21 crook 3816:
1.29 crook 3817: Postfix notation is unambiguous because the order that the operators
3818: are applied is always explicit; that also means that parentheses are
3819: never required. The operators are @i{active} (the act of quoting the
3820: operator makes the operation occur) which removes the need for ``=''.
1.28 crook 3821:
1.29 crook 3822: The sum 6 + 5 * 4 can be written (in postfix notation) in two
3823: equivalent ways:
1.26 crook 3824:
3825: @example
1.29 crook 3826: 6 5 4 * + or:
3827: 5 4 * 6 +
1.26 crook 3828: @end example
1.23 crook 3829:
1.29 crook 3830: An important thing that you should notice about this notation is that
3831: the @i{order} of the numbers does not change; if you want to subtract
3832: 2 from 10 you type @code{10 2 -}.
1.1 anton 3833:
1.29 crook 3834: The reason that Forth uses postfix notation is very simple to explain: it
3835: makes the implementation extremely simple, and it follows naturally from
3836: using the stack as a mechanism for passing parameters. Another way of
3837: thinking about this is to realise that all Forth definitions are
3838: @i{active}; they execute as they are encountered by the text
3839: interpreter. The result of this is that the syntax of Forth is trivially
3840: simple.
1.1 anton 3841:
3842:
3843:
1.29 crook 3844: @comment ----------------------------------------------
3845: @node Your first definition, How does that work?, Stacks and Postfix notation, Introduction
3846: @section Your first Forth definition
3847: @cindex first definition
1.1 anton 3848:
1.29 crook 3849: Until now, the examples we've seen have been trivial; we've just been
3850: using Forth as a bigger-than-pocket calculator. Also, each calculation
3851: we've shown has been a ``one-off'' -- to repeat it we'd need to type it in
3852: again@footnote{That's not quite true. If you press the up-arrow key on
3853: your keyboard you should be able to scroll back to any earlier command,
3854: edit it and re-enter it.} In this section we'll see how to add new
3855: words to Forth's vocabulary.
1.1 anton 3856:
1.29 crook 3857: The easiest way to create a new word is to use a @dfn{colon
3858: definition}. We'll define a few and try them out before worrying too
3859: much about how they work. Try typing in these examples; be careful to
3860: copy the spaces accurately:
1.1 anton 3861:
1.29 crook 3862: @example
3863: : add-two 2 + . ;
3864: : greet ." Hello and welcome" ;
3865: : demo 5 add-two ;
3866: @end example
1.1 anton 3867:
1.29 crook 3868: @noindent
3869: Now try them out:
1.1 anton 3870:
1.29 crook 3871: @example
1.30 anton 3872: @kbd{greet@key{RET}} Hello and welcome ok
3873: @kbd{greet greet@key{RET}} Hello and welcomeHello and welcome ok
3874: @kbd{4 add-two@key{RET}} 6 ok
3875: @kbd{demo@key{RET}} 7 ok
3876: @kbd{9 greet demo add-two@key{RET}} Hello and welcome7 11 ok
1.29 crook 3877: @end example
1.1 anton 3878:
1.29 crook 3879: The first new thing that we've introduced here is the pair of words
3880: @code{:} and @code{;}. These are used to start and terminate a new
3881: definition, respectively. The first word after the @code{:} is the name
3882: for the new definition.
1.1 anton 3883:
1.29 crook 3884: As you can see from the examples, a definition is built up of words that
3885: have already been defined; Forth makes no distinction between
3886: definitions that existed when you started the system up, and those that
3887: you define yourself.
1.1 anton 3888:
1.29 crook 3889: The examples also introduce the words @code{.} (dot), @code{."}
3890: (dot-quote) and @code{dup} (dewp). Dot takes the value from the top of
3891: the stack and displays it. It's like @code{.s} except that it only
3892: displays the top item of the stack and it is destructive; after it has
3893: executed, the number is no longer on the stack. There is always one
3894: space printed after the number, and no spaces before it. Dot-quote
3895: defines a string (a sequence of characters) that will be printed when
3896: the word is executed. The string can contain any printable characters
3897: except @code{"}. A @code{"} has a special function; it is not a Forth
3898: word but it acts as a delimiter (the way that delimiters work is
3899: described in the next section). Finally, @code{dup} duplicates the value
3900: at the top of the stack. Try typing @code{5 dup .s} to see what it does.
1.1 anton 3901:
1.29 crook 3902: We already know that the text interpreter searches through the
3903: dictionary to locate names. If you've followed the examples earlier, you
3904: will already have a definition called @code{add-two}. Lets try modifying
3905: it by typing in a new definition:
1.1 anton 3906:
1.29 crook 3907: @example
1.30 anton 3908: @kbd{: add-two dup . ." + 2 =" 2 + . ;@key{RET}} redefined add-two ok
1.29 crook 3909: @end example
1.5 anton 3910:
1.29 crook 3911: Forth recognised that we were defining a word that already exists, and
3912: printed a message to warn us of that fact. Let's try out the new
3913: definition:
1.5 anton 3914:
1.29 crook 3915: @example
1.30 anton 3916: @kbd{9 add-two@key{RET}} 9 + 2 =11 ok
1.29 crook 3917: @end example
1.1 anton 3918:
1.29 crook 3919: @noindent
3920: All that we've actually done here, though, is to create a new
3921: definition, with a particular name. The fact that there was already a
3922: definition with the same name did not make any difference to the way
3923: that the new definition was created (except that Forth printed a warning
3924: message). The old definition of add-two still exists (try @code{demo}
3925: again to see that this is true). Any new definition will use the new
3926: definition of @code{add-two}, but old definitions continue to use the
3927: version that already existed at the time that they were @code{compiled}.
1.1 anton 3928:
1.29 crook 3929: Before you go on to the next section, try defining and redefining some
3930: words of your own.
1.1 anton 3931:
1.29 crook 3932: @comment ----------------------------------------------
3933: @node How does that work?, Forth is written in Forth, Your first definition, Introduction
3934: @section How does that work?
3935: @cindex parsing words
1.1 anton 3936:
1.30 anton 3937: @c That's pretty deep (IMO way too deep) for an introduction. - anton
3938:
3939: @c Is it a good idea to talk about the interpretation semantics of a
3940: @c number? We don't have an xt to go along with it. - anton
3941:
3942: @c Now that I have eliminated execution semantics, I wonder if it would not
3943: @c be better to keep them (or add run-time semantics), to make it easier to
3944: @c explain what compilation semantics usually does. - anton
3945:
1.44 crook 3946: @c nac-> I removed the term ``default compilation sematics'' from the
3947: @c introductory chapter. Removing ``execution semantics'' was making
3948: @c everything simpler to explain, then I think the use of this term made
3949: @c everything more complex again. I replaced it with ``default
3950: @c semantics'' (which is used elsewhere in the manual) by which I mean
3951: @c ``a definition that has neither the immediate nor the compile-only
3952: @c flag set''. I reworded big chunks of the ``how does that work''
3953: @c section (and, unusually for me, I think I even made it shorter!). See
3954: @c what you think -- I know I have not addressed your primary concern
3955: @c that it is too heavy-going for an introduction. From what I understood
3956: @c of your course notes it looks as though they might be a good framework.
3957: @c Things that I've tried to capture here are some things that came as a
3958: @c great revelation here when I first understood them. Also, I like the
3959: @c fact that a very simple code example shows up almost all of the issues
3960: @c that you need to understand to see how Forth works. That's unique and
3961: @c worthwhile to emphasise.
3962:
1.29 crook 3963: Now we're going to take another look at the definition of @code{add-two}
3964: from the previous section. From our knowledge of the way that the text
3965: interpreter works, we would have expected this result when we tried to
3966: define @code{add-two}:
1.21 crook 3967:
1.29 crook 3968: @example
1.44 crook 3969: @kbd{: add-two 2 + . ;@key{RET}}
1.29 crook 3970: ^^^^^^^
3971: Error: Undefined word
3972: @end example
1.28 crook 3973:
1.29 crook 3974: The reason that this didn't happen is bound up in the way that @code{:}
3975: works. The word @code{:} does two special things. The first special
3976: thing that it does prevents the text interpreter from ever seeing the
3977: characters @code{add-two}. The text interpreter uses a variable called
3978: @cindex modifying >IN
1.44 crook 3979: @code{>IN} (pronounced ``to-in'') to keep track of where it is in the
1.29 crook 3980: input line. When it encounters the word @code{:} it behaves in exactly
3981: the same way as it does for any other word; it looks it up in the name
3982: dictionary, finds its xt and executes it. When @code{:} executes, it
3983: looks at the input buffer, finds the word @code{add-two} and advances the
3984: value of @code{>IN} to point past it. It then does some other stuff
3985: associated with creating the new definition (including creating an entry
3986: for @code{add-two} in the name dictionary). When the execution of @code{:}
3987: completes, control returns to the text interpreter, which is oblivious
3988: to the fact that it has been tricked into ignoring part of the input
3989: line.
1.21 crook 3990:
1.29 crook 3991: @cindex parsing words
3992: Words like @code{:} -- words that advance the value of @code{>IN} and so
3993: prevent the text interpreter from acting on the whole of the input line
3994: -- are called @dfn{parsing words}.
1.21 crook 3995:
1.29 crook 3996: @cindex @code{state} - effect on the text interpreter
3997: @cindex text interpreter - effect of state
3998: The second special thing that @code{:} does is change the value of a
3999: variable called @code{state}, which affects the way that the text
4000: interpreter behaves. When Gforth starts up, @code{state} has the value
4001: 0, and the text interpreter is said to be @dfn{interpreting}. During a
4002: colon definition (started with @code{:}), @code{state} is set to -1 and
1.44 crook 4003: the text interpreter is said to be @dfn{compiling}.
4004:
4005: In this example, the text interpreter is compiling when it processes the
4006: string ``@code{2 + . ;}''. It still breaks the string down into
4007: character sequences in the same way. However, instead of pushing the
4008: number @code{2} onto the stack, it lays down (@dfn{compiles}) some magic
4009: into the definition of @code{add-two} that will make the number @code{2} get
4010: pushed onto the stack when @code{add-two} is @dfn{executed}. Similarly,
4011: the behaviours of @code{+} and @code{.} are also compiled into the
4012: definition.
4013:
4014: One category of words don't get compiled. These so-called @dfn{immediate
4015: words} get executed (performed @i{now}) regardless of whether the text
4016: interpreter is interpreting or compiling. The word @code{;} is an
4017: immediate word. Rather than being compiled into the definition, it
4018: executes. Its effect is to terminate the current definition, which
4019: includes changing the value of @code{state} back to 0.
4020:
4021: When you execute @code{add-two}, it has a @dfn{run-time effect} that is
4022: exactly the same as if you had typed @code{2 + . @key{RET}} outside of a
4023: definition.
1.28 crook 4024:
1.30 anton 4025: In Forth, every word or number can be described in terms of two
1.29 crook 4026: properties:
1.28 crook 4027:
4028: @itemize @bullet
4029: @item
1.29 crook 4030: @cindex interpretation semantics
1.44 crook 4031: Its @dfn{interpretation semantics} describe how it will behave when the
4032: text interpreter encounters it in @dfn{interpret} state. The
4033: interpretation semantics of a word are represented by an @dfn{execution
4034: token}.
1.28 crook 4035: @item
1.29 crook 4036: @cindex compilation semantics
1.44 crook 4037: Its @dfn{compilation semantics} describe how it will behave when the
4038: text interpreter encounters it in @dfn{compile} state. The compilation
4039: semantics of a word are represented in an implementation-dependent way;
4040: Gforth uses a @dfn{compilation token}.
1.29 crook 4041: @end itemize
4042:
4043: @noindent
4044: Numbers are always treated in a fixed way:
4045:
4046: @itemize @bullet
1.28 crook 4047: @item
1.44 crook 4048: When the number is @dfn{interpreted}, its behaviour is to push the
4049: number onto the stack.
1.28 crook 4050: @item
1.30 anton 4051: When the number is @dfn{compiled}, a piece of code is appended to the
4052: current definition that pushes the number when it runs. (In other words,
4053: the compilation semantics of a number are to postpone its interpretation
4054: semantics until the run-time of the definition that it is being compiled
4055: into.)
1.29 crook 4056: @end itemize
4057:
1.44 crook 4058: Words don't behave in such a regular way, but most have @i{default
4059: semantics} which means that they behave like this:
1.29 crook 4060:
4061: @itemize @bullet
1.28 crook 4062: @item
1.30 anton 4063: The @dfn{interpretation semantics} of the word are to do something useful.
4064: @item
1.29 crook 4065: The @dfn{compilation semantics} of the word are to append its
1.30 anton 4066: @dfn{interpretation semantics} to the current definition (so that its
4067: run-time behaviour is to do something useful).
1.28 crook 4068: @end itemize
4069:
1.30 anton 4070: @cindex immediate words
1.44 crook 4071: The actual behaviour of any particular word can be controlled by using
4072: the words @code{immediate} and @code{compile-only} when the word is
4073: defined. These words set flags in the name dictionary entry of the most
4074: recently defined word, and these flags are retrieved by the text
4075: interpreter when it finds the word in the name dictionary.
4076:
4077: A word that is marked as @dfn{immediate} has compilation semantics that
4078: are identical to its interpretation semantics. In other words, it
4079: behaves like this:
1.29 crook 4080:
4081: @itemize @bullet
4082: @item
1.30 anton 4083: The @dfn{interpretation semantics} of the word are to do something useful.
1.29 crook 4084: @item
1.30 anton 4085: The @dfn{compilation semantics} of the word are to do something useful
4086: (and actually the same thing); i.e., it is executed during compilation.
1.29 crook 4087: @end itemize
1.28 crook 4088:
1.44 crook 4089: Marking a word as @dfn{compile-only} prohibits the text interpreter from
4090: performing the interpretation semantics of the word directly; an attempt
4091: to do so will generate an error. It is never necessary to use
4092: @code{compile-only} (and it is not even part of ANS Forth, though it is
4093: provided by many implementations) but it is good etiquette to apply it
4094: to a word that will not behave correctly (and might have unexpected
4095: side-effects) in interpret state. For example, it is only legal to use
4096: the conditional word @code{IF} within a definition. If you forget this
4097: and try to use it elsewhere, the fact that (in Gforth) it is marked as
4098: @code{compile-only} allows the text interpreter to generate a helpful
4099: error message rather than subjecting you to the consequences of your
4100: folly.
4101:
1.29 crook 4102: This example shows the difference between an immediate and a
4103: non-immediate word:
1.28 crook 4104:
1.29 crook 4105: @example
4106: : show-state state @@ . ;
4107: : show-state-now show-state ; immediate
4108: : word1 show-state ;
4109: : word2 show-state-now ;
1.28 crook 4110: @end example
1.23 crook 4111:
1.29 crook 4112: The word @code{immediate} after the definition of @code{show-state-now}
4113: makes that word an immediate word. These definitions introduce a new
4114: word: @code{@@} (pronounced ``fetch''). This word fetches the value of a
4115: variable, and leaves it on the stack. Therefore, the behaviour of
4116: @code{show-state} is to print a number that represents the current value
4117: of @code{state}.
1.28 crook 4118:
1.29 crook 4119: When you execute @code{word1}, it prints the number 0, indicating that
4120: the system is interpreting. When the text interpreter compiled the
4121: definition of @code{word1}, it encountered @code{show-state} whose
1.30 anton 4122: compilation semantics are to append its interpretation semantics to the
1.29 crook 4123: current definition. When you execute @code{word1}, it performs the
1.30 anton 4124: interpretation semantics of @code{show-state}. At the time that @code{word1}
1.29 crook 4125: (and therefore @code{show-state}) are executed, the system is
4126: interpreting.
1.28 crook 4127:
1.30 anton 4128: When you pressed @key{RET} after entering the definition of @code{word2},
1.29 crook 4129: you should have seen the number -1 printed, followed by ``@code{
4130: ok}''. When the text interpreter compiled the definition of
4131: @code{word2}, it encountered @code{show-state-now}, an immediate word,
1.30 anton 4132: whose compilation semantics are therefore to perform its interpretation
1.29 crook 4133: semantics. It is executed straight away (even before the text
4134: interpreter has moved on to process another group of characters; the
4135: @code{;} in this example). The effect of executing it are to display the
4136: value of @code{state} @i{at the time that the definition of}
4137: @code{word2} @i{is being defined}. Printing -1 demonstrates that the
4138: system is compiling at this time. If you execute @code{word2} it does
4139: nothing at all.
1.28 crook 4140:
1.29 crook 4141: @cindex @code{."}, how it works
4142: Before leaving the subject of immediate words, consider the behaviour of
4143: @code{."} in the definition of @code{greet}, in the previous
4144: section. This word is both a parsing word and an immediate word. Notice
4145: that there is a space between @code{."} and the start of the text
4146: @code{Hello and welcome}, but that there is no space between the last
4147: letter of @code{welcome} and the @code{"} character. The reason for this
4148: is that @code{."} is a Forth word; it must have a space after it so that
4149: the text interpreter can identify it. The @code{"} is not a Forth word;
4150: it is a @dfn{delimiter}. The examples earlier show that, when the string
4151: is displayed, there is neither a space before the @code{H} nor after the
4152: @code{e}. Since @code{."} is an immediate word, it executes at the time
4153: that @code{greet} is defined. When it executes, its behaviour is to
4154: search forward in the input line looking for the delimiter. When it
4155: finds the delimiter, it updates @code{>IN} to point past the
4156: delimiter. It also compiles some magic code into the definition of
4157: @code{greet}; the xt of a run-time routine that prints a text string. It
4158: compiles the string @code{Hello and welcome} into memory so that it is
4159: available to be printed later. When the text interpreter gains control,
4160: the next word it finds in the input stream is @code{;} and so it
4161: terminates the definition of @code{greet}.
1.28 crook 4162:
4163:
4164: @comment ----------------------------------------------
1.29 crook 4165: @node Forth is written in Forth, Review - elements of a Forth system, How does that work?, Introduction
4166: @section Forth is written in Forth
4167: @cindex structure of Forth programs
4168:
4169: When you start up a Forth compiler, a large number of definitions
4170: already exist. In Forth, you develop a new application using bottom-up
4171: programming techniques to create new definitions that are defined in
4172: terms of existing definitions. As you create each definition you can
4173: test and debug it interactively.
4174:
4175: If you have tried out the examples in this section, you will probably
4176: have typed them in by hand; when you leave Gforth, your definitions will
4177: be lost. You can avoid this by using a text editor to enter Forth source
4178: code into a file, and then loading code from the file using
1.49 anton 4179: @code{include} (@pxref{Forth source files}). A Forth source file is
1.29 crook 4180: processed by the text interpreter, just as though you had typed it in by
4181: hand@footnote{Actually, there are some subtle differences -- see
4182: @ref{The Text Interpreter}.}.
4183:
4184: Gforth also supports the traditional Forth alternative to using text
1.49 anton 4185: files for program entry (@pxref{Blocks}).
1.28 crook 4186:
1.29 crook 4187: In common with many, if not most, Forth compilers, most of Gforth is
4188: actually written in Forth. All of the @file{.fs} files in the
4189: installation directory@footnote{For example,
1.30 anton 4190: @file{/usr/local/share/gforth...}} are Forth source files, which you can
1.29 crook 4191: study to see examples of Forth programming.
1.28 crook 4192:
1.29 crook 4193: Gforth maintains a history file that records every line that you type to
4194: the text interpreter. This file is preserved between sessions, and is
4195: used to provide a command-line recall facility. If you enter long
4196: definitions by hand, you can use a text editor to paste them out of the
4197: history file into a Forth source file for reuse at a later time
1.49 anton 4198: (for more information @pxref{Command-line editing}).
1.28 crook 4199:
4200:
4201: @comment ----------------------------------------------
1.29 crook 4202: @node Review - elements of a Forth system, Where to go next, Forth is written in Forth, Introduction
4203: @section Review - elements of a Forth system
4204: @cindex elements of a Forth system
1.28 crook 4205:
1.29 crook 4206: To summarise this chapter:
1.28 crook 4207:
4208: @itemize @bullet
4209: @item
1.29 crook 4210: Forth programs use @dfn{factoring} to break a problem down into small
4211: fragments called @dfn{words} or @dfn{definitions}.
4212: @item
4213: Forth program development is an interactive process.
4214: @item
4215: The main command loop that accepts input, and controls both
4216: interpretation and compilation, is called the @dfn{text interpreter}
4217: (also known as the @dfn{outer interpreter}).
4218: @item
4219: Forth has a very simple syntax, consisting of words and numbers
4220: separated by spaces or carriage-return characters. Any additional syntax
4221: is imposed by @dfn{parsing words}.
4222: @item
4223: Forth uses a stack to pass parameters between words. As a result, it
4224: uses postfix notation.
4225: @item
4226: To use a word that has previously been defined, the text interpreter
4227: searches for the word in the @dfn{name dictionary}.
4228: @item
1.30 anton 4229: Words have @dfn{interpretation semantics} and @dfn{compilation semantics}.
1.28 crook 4230: @item
1.29 crook 4231: The text interpreter uses the value of @code{state} to select between
4232: the use of the @dfn{interpretation semantics} and the @dfn{compilation
4233: semantics} of a word that it encounters.
1.28 crook 4234: @item
1.30 anton 4235: The relationship between the @dfn{interpretation semantics} and
4236: @dfn{compilation semantics} for a word
1.29 crook 4237: depend upon the way in which the word was defined (for example, whether
4238: it is an @dfn{immediate} word).
1.28 crook 4239: @item
1.29 crook 4240: Forth definitions can be implemented in Forth (called @dfn{high-level
4241: definitions}) or in some other way (usually a lower-level language and
4242: as a result often called @dfn{low-level definitions}, @dfn{code
4243: definitions} or @dfn{primitives}).
1.28 crook 4244: @item
1.29 crook 4245: Many Forth systems are implemented mainly in Forth.
1.28 crook 4246: @end itemize
4247:
4248:
1.29 crook 4249: @comment ----------------------------------------------
1.48 anton 4250: @node Where to go next, Exercises, Review - elements of a Forth system, Introduction
1.29 crook 4251: @section Where To Go Next
4252: @cindex where to go next
1.28 crook 4253:
1.29 crook 4254: Amazing as it may seem, if you have read (and understood) this far, you
4255: know almost all the fundamentals about the inner workings of a Forth
4256: system. You certainly know enough to be able to read and understand the
4257: rest of this manual and the ANS Forth document, to learn more about the
4258: facilities that Forth in general and Gforth in particular provide. Even
4259: scarier, you know almost enough to implement your own Forth system.
1.30 anton 4260: However, that's not a good idea just yet... better to try writing some
1.29 crook 4261: programs in Gforth.
1.28 crook 4262:
1.29 crook 4263: Forth has such a rich vocabulary that it can be hard to know where to
4264: start in learning it. This section suggests a few sets of words that are
4265: enough to write small but useful programs. Use the word index in this
4266: document to learn more about each word, then try it out and try to write
4267: small definitions using it. Start by experimenting with these words:
1.28 crook 4268:
4269: @itemize @bullet
4270: @item
1.29 crook 4271: Arithmetic: @code{+ - * / /MOD */ ABS INVERT}
4272: @item
4273: Comparison: @code{MIN MAX =}
4274: @item
4275: Logic: @code{AND OR XOR NOT}
4276: @item
4277: Stack manipulation: @code{DUP DROP SWAP OVER}
1.28 crook 4278: @item
1.29 crook 4279: Loops and decisions: @code{IF ELSE ENDIF ?DO I LOOP}
1.28 crook 4280: @item
1.29 crook 4281: Input/Output: @code{. ." EMIT CR KEY}
1.28 crook 4282: @item
1.29 crook 4283: Defining words: @code{: ; CREATE}
1.28 crook 4284: @item
1.29 crook 4285: Memory allocation words: @code{ALLOT ,}
1.28 crook 4286: @item
1.29 crook 4287: Tools: @code{SEE WORDS .S MARKER}
4288: @end itemize
4289:
4290: When you have mastered those, go on to:
4291:
4292: @itemize @bullet
1.28 crook 4293: @item
1.29 crook 4294: More defining words: @code{VARIABLE CONSTANT VALUE TO CREATE DOES>}
1.28 crook 4295: @item
1.29 crook 4296: Memory access: @code{@@ !}
1.28 crook 4297: @end itemize
1.23 crook 4298:
1.29 crook 4299: When you have mastered these, there's nothing for it but to read through
4300: the whole of this manual and find out what you've missed.
4301:
4302: @comment ----------------------------------------------
1.48 anton 4303: @node Exercises, , Where to go next, Introduction
1.29 crook 4304: @section Exercises
4305: @cindex exercises
4306:
4307: TODO: provide a set of programming excercises linked into the stuff done
4308: already and into other sections of the manual. Provide solutions to all
4309: the exercises in a .fs file in the distribution.
4310:
4311: @c Get some inspiration from Starting Forth and Kelly&Spies.
4312:
4313: @c excercises:
4314: @c 1. take inches and convert to feet and inches.
4315: @c 2. take temperature and convert from fahrenheight to celcius;
4316: @c may need to care about symmetric vs floored??
4317: @c 3. take input line and do character substitution
4318: @c to encipher or decipher
4319: @c 4. as above but work on a file for in and out
4320: @c 5. take input line and convert to pig-latin
4321: @c
4322: @c thing of sets of things to exercise then come up with
4323: @c problems that need those things.
4324:
4325:
1.26 crook 4326: @c ******************************************************************
1.29 crook 4327: @node Words, Error messages, Introduction, Top
1.1 anton 4328: @chapter Forth Words
1.26 crook 4329: @cindex words
1.1 anton 4330:
4331: @menu
4332: * Notation::
1.65 anton 4333: * Case insensitivity::
4334: * Comments::
4335: * Boolean Flags::
1.1 anton 4336: * Arithmetic::
4337: * Stack Manipulation::
1.5 anton 4338: * Memory::
1.1 anton 4339: * Control Structures::
4340: * Defining Words::
1.65 anton 4341: * Interpretation and Compilation Semantics::
1.47 crook 4342: * Tokens for Words::
1.81 anton 4343: * Compiling words::
1.65 anton 4344: * The Text Interpreter::
4345: * Word Lists::
4346: * Environmental Queries::
1.12 anton 4347: * Files::
4348: * Blocks::
4349: * Other I/O::
1.78 anton 4350: * Locals::
4351: * Structures::
4352: * Object-oriented Forth::
1.12 anton 4353: * Programming Tools::
4354: * Assembler and Code Words::
4355: * Threading Words::
1.65 anton 4356: * Passing Commands to the OS::
4357: * Keeping track of Time::
4358: * Miscellaneous Words::
1.1 anton 4359: @end menu
4360:
1.65 anton 4361: @node Notation, Case insensitivity, Words, Words
1.1 anton 4362: @section Notation
4363: @cindex notation of glossary entries
4364: @cindex format of glossary entries
4365: @cindex glossary notation format
4366: @cindex word glossary entry format
4367:
4368: The Forth words are described in this section in the glossary notation
1.67 anton 4369: that has become a de-facto standard for Forth texts:
1.1 anton 4370:
4371: @format
1.29 crook 4372: @i{word} @i{Stack effect} @i{wordset} @i{pronunciation}
1.1 anton 4373: @end format
1.29 crook 4374: @i{Description}
1.1 anton 4375:
4376: @table @var
4377: @item word
1.28 crook 4378: The name of the word.
1.1 anton 4379:
4380: @item Stack effect
4381: @cindex stack effect
1.29 crook 4382: The stack effect is written in the notation @code{@i{before} --
4383: @i{after}}, where @i{before} and @i{after} describe the top of
1.1 anton 4384: stack entries before and after the execution of the word. The rest of
4385: the stack is not touched by the word. The top of stack is rightmost,
4386: i.e., a stack sequence is written as it is typed in. Note that Gforth
4387: uses a separate floating point stack, but a unified stack
1.29 crook 4388: notation. Also, return stack effects are not shown in @i{stack
4389: effect}, but in @i{Description}. The name of a stack item describes
1.1 anton 4390: the type and/or the function of the item. See below for a discussion of
4391: the types.
4392:
4393: All words have two stack effects: A compile-time stack effect and a
4394: run-time stack effect. The compile-time stack-effect of most words is
1.29 crook 4395: @i{ -- }. If the compile-time stack-effect of a word deviates from
1.1 anton 4396: this standard behaviour, or the word does other unusual things at
4397: compile time, both stack effects are shown; otherwise only the run-time
4398: stack effect is shown.
4399:
4400: @cindex pronounciation of words
4401: @item pronunciation
4402: How the word is pronounced.
4403:
4404: @cindex wordset
1.67 anton 4405: @cindex environment wordset
1.1 anton 4406: @item wordset
1.21 crook 4407: The ANS Forth standard is divided into several word sets. A standard
4408: system need not support all of them. Therefore, in theory, the fewer
4409: word sets your program uses the more portable it will be. However, we
4410: suspect that most ANS Forth systems on personal machines will feature
1.26 crook 4411: all word sets. Words that are not defined in ANS Forth have
1.21 crook 4412: @code{gforth} or @code{gforth-internal} as word set. @code{gforth}
1.1 anton 4413: describes words that will work in future releases of Gforth;
4414: @code{gforth-internal} words are more volatile. Environmental query
4415: strings are also displayed like words; you can recognize them by the
1.21 crook 4416: @code{environment} in the word set field.
1.1 anton 4417:
4418: @item Description
4419: A description of the behaviour of the word.
4420: @end table
4421:
4422: @cindex types of stack items
4423: @cindex stack item types
4424: The type of a stack item is specified by the character(s) the name
4425: starts with:
4426:
4427: @table @code
4428: @item f
4429: @cindex @code{f}, stack item type
4430: Boolean flags, i.e. @code{false} or @code{true}.
4431: @item c
4432: @cindex @code{c}, stack item type
4433: Char
4434: @item w
4435: @cindex @code{w}, stack item type
4436: Cell, can contain an integer or an address
4437: @item n
4438: @cindex @code{n}, stack item type
4439: signed integer
4440: @item u
4441: @cindex @code{u}, stack item type
4442: unsigned integer
4443: @item d
4444: @cindex @code{d}, stack item type
4445: double sized signed integer
4446: @item ud
4447: @cindex @code{ud}, stack item type
4448: double sized unsigned integer
4449: @item r
4450: @cindex @code{r}, stack item type
4451: Float (on the FP stack)
1.21 crook 4452: @item a-
1.1 anton 4453: @cindex @code{a_}, stack item type
4454: Cell-aligned address
1.21 crook 4455: @item c-
1.1 anton 4456: @cindex @code{c_}, stack item type
4457: Char-aligned address (note that a Char may have two bytes in Windows NT)
1.21 crook 4458: @item f-
1.1 anton 4459: @cindex @code{f_}, stack item type
4460: Float-aligned address
1.21 crook 4461: @item df-
1.1 anton 4462: @cindex @code{df_}, stack item type
4463: Address aligned for IEEE double precision float
1.21 crook 4464: @item sf-
1.1 anton 4465: @cindex @code{sf_}, stack item type
4466: Address aligned for IEEE single precision float
4467: @item xt
4468: @cindex @code{xt}, stack item type
4469: Execution token, same size as Cell
4470: @item wid
4471: @cindex @code{wid}, stack item type
1.21 crook 4472: Word list ID, same size as Cell
1.68 anton 4473: @item ior, wior
4474: @cindex ior type description
4475: @cindex wior type description
4476: I/O result code, cell-sized. In Gforth, you can @code{throw} iors.
1.1 anton 4477: @item f83name
4478: @cindex @code{f83name}, stack item type
4479: Pointer to a name structure
4480: @item "
4481: @cindex @code{"}, stack item type
1.12 anton 4482: string in the input stream (not on the stack). The terminating character
4483: is a blank by default. If it is not a blank, it is shown in @code{<>}
1.1 anton 4484: quotes.
4485: @end table
4486:
1.65 anton 4487: @comment ----------------------------------------------
4488: @node Case insensitivity, Comments, Notation, Words
4489: @section Case insensitivity
4490: @cindex case sensitivity
4491: @cindex upper and lower case
4492:
4493: Gforth is case-insensitive; you can enter definitions and invoke
4494: Standard words using upper, lower or mixed case (however,
4495: @pxref{core-idef, Implementation-defined options, Implementation-defined
4496: options}).
4497:
4498: ANS Forth only @i{requires} implementations to recognise Standard words
4499: when they are typed entirely in upper case. Therefore, a Standard
4500: program must use upper case for all Standard words. You can use whatever
4501: case you like for words that you define, but in a Standard program you
4502: have to use the words in the same case that you defined them.
4503:
4504: Gforth supports case sensitivity through @code{table}s (case-sensitive
4505: wordlists, @pxref{Word Lists}).
4506:
4507: Two people have asked how to convert Gforth to be case-sensitive; while
4508: we think this is a bad idea, you can change all wordlists into tables
4509: like this:
4510:
4511: @example
4512: ' table-find forth-wordlist wordlist-map @ !
4513: @end example
4514:
4515: Note that you now have to type the predefined words in the same case
4516: that we defined them, which are varying. You may want to convert them
4517: to your favourite case before doing this operation (I won't explain how,
4518: because if you are even contemplating doing this, you'd better have
4519: enough knowledge of Forth systems to know this already).
4520:
4521: @node Comments, Boolean Flags, Case insensitivity, Words
1.21 crook 4522: @section Comments
1.26 crook 4523: @cindex comments
1.21 crook 4524:
1.29 crook 4525: Forth supports two styles of comment; the traditional @i{in-line} comment,
4526: @code{(} and its modern cousin, the @i{comment to end of line}; @code{\}.
1.21 crook 4527:
1.44 crook 4528:
1.23 crook 4529: doc-(
1.21 crook 4530: doc-\
1.23 crook 4531: doc-\G
1.21 crook 4532:
1.44 crook 4533:
1.21 crook 4534: @node Boolean Flags, Arithmetic, Comments, Words
4535: @section Boolean Flags
1.26 crook 4536: @cindex Boolean flags
1.21 crook 4537:
4538: A Boolean flag is cell-sized. A cell with all bits clear represents the
4539: flag @code{false} and a flag with all bits set represents the flag
1.26 crook 4540: @code{true}. Words that check a flag (for example, @code{IF}) will treat
1.29 crook 4541: a cell that has @i{any} bit set as @code{true}.
1.67 anton 4542: @c on and off to Memory?
4543: @c true and false to "Bitwise operations" or "Numeric comparison"?
1.44 crook 4544:
1.21 crook 4545: doc-true
4546: doc-false
1.29 crook 4547: doc-on
4548: doc-off
1.21 crook 4549:
1.44 crook 4550:
1.21 crook 4551: @node Arithmetic, Stack Manipulation, Boolean Flags, Words
1.1 anton 4552: @section Arithmetic
4553: @cindex arithmetic words
4554:
4555: @cindex division with potentially negative operands
4556: Forth arithmetic is not checked, i.e., you will not hear about integer
4557: overflow on addition or multiplication, you may hear about division by
4558: zero if you are lucky. The operator is written after the operands, but
4559: the operands are still in the original order. I.e., the infix @code{2-1}
4560: corresponds to @code{2 1 -}. Forth offers a variety of division
4561: operators. If you perform division with potentially negative operands,
4562: you do not want to use @code{/} or @code{/mod} with its undefined
4563: behaviour, but rather @code{fm/mod} or @code{sm/mod} (probably the
4564: former, @pxref{Mixed precision}).
1.26 crook 4565: @comment TODO discuss the different division forms and the std approach
1.1 anton 4566:
4567: @menu
4568: * Single precision::
1.67 anton 4569: * Double precision:: Double-cell integer arithmetic
1.1 anton 4570: * Bitwise operations::
1.67 anton 4571: * Numeric comparison::
1.29 crook 4572: * Mixed precision:: Operations with single and double-cell integers
1.1 anton 4573: * Floating Point::
4574: @end menu
4575:
1.67 anton 4576: @node Single precision, Double precision, Arithmetic, Arithmetic
1.1 anton 4577: @subsection Single precision
4578: @cindex single precision arithmetic words
4579:
1.67 anton 4580: @c !! cell undefined
4581:
4582: By default, numbers in Forth are single-precision integers that are one
1.26 crook 4583: cell in size. They can be signed or unsigned, depending upon how you
1.49 anton 4584: treat them. For the rules used by the text interpreter for recognising
4585: single-precision integers see @ref{Number Conversion}.
1.21 crook 4586:
1.67 anton 4587: These words are all defined for signed operands, but some of them also
4588: work for unsigned numbers: @code{+}, @code{1+}, @code{-}, @code{1-},
4589: @code{*}.
1.44 crook 4590:
1.1 anton 4591: doc-+
1.21 crook 4592: doc-1+
1.1 anton 4593: doc--
1.21 crook 4594: doc-1-
1.1 anton 4595: doc-*
4596: doc-/
4597: doc-mod
4598: doc-/mod
4599: doc-negate
4600: doc-abs
4601: doc-min
4602: doc-max
1.27 crook 4603: doc-floored
1.1 anton 4604:
1.44 crook 4605:
1.67 anton 4606: @node Double precision, Bitwise operations, Single precision, Arithmetic
1.21 crook 4607: @subsection Double precision
4608: @cindex double precision arithmetic words
4609:
1.49 anton 4610: For the rules used by the text interpreter for
4611: recognising double-precision integers, see @ref{Number Conversion}.
1.21 crook 4612:
4613: A double precision number is represented by a cell pair, with the most
1.67 anton 4614: significant cell at the TOS. It is trivial to convert an unsigned single
4615: to a double: simply push a @code{0} onto the TOS. Since numbers are
4616: represented by Gforth using 2's complement arithmetic, converting a
4617: signed single to a (signed) double requires sign-extension across the
4618: most significant cell. This can be achieved using @code{s>d}. The moral
4619: of the story is that you cannot convert a number without knowing whether
4620: it represents an unsigned or a signed number.
1.21 crook 4621:
1.67 anton 4622: These words are all defined for signed operands, but some of them also
4623: work for unsigned numbers: @code{d+}, @code{d-}.
1.44 crook 4624:
1.21 crook 4625: doc-s>d
1.67 anton 4626: doc-d>s
1.21 crook 4627: doc-d+
4628: doc-d-
4629: doc-dnegate
4630: doc-dabs
4631: doc-dmin
4632: doc-dmax
4633:
1.44 crook 4634:
1.67 anton 4635: @node Bitwise operations, Numeric comparison, Double precision, Arithmetic
4636: @subsection Bitwise operations
4637: @cindex bitwise operation words
4638:
4639:
4640: doc-and
4641: doc-or
4642: doc-xor
4643: doc-invert
4644: doc-lshift
4645: doc-rshift
4646: doc-2*
4647: doc-d2*
4648: doc-2/
4649: doc-d2/
4650:
4651:
4652: @node Numeric comparison, Mixed precision, Bitwise operations, Arithmetic
1.21 crook 4653: @subsection Numeric comparison
4654: @cindex numeric comparison words
4655:
1.67 anton 4656: Note that the words that compare for equality (@code{= <> 0= 0<> d= d<>
4657: d0= d0<>}) work for for both signed and unsigned numbers.
1.44 crook 4658:
1.28 crook 4659: doc-<
4660: doc-<=
4661: doc-<>
4662: doc-=
4663: doc->
4664: doc->=
4665:
1.21 crook 4666: doc-0<
1.23 crook 4667: doc-0<=
1.21 crook 4668: doc-0<>
4669: doc-0=
1.23 crook 4670: doc-0>
4671: doc-0>=
1.28 crook 4672:
4673: doc-u<
4674: doc-u<=
1.44 crook 4675: @c u<> and u= exist but are the same as <> and =
1.31 anton 4676: @c doc-u<>
4677: @c doc-u=
1.28 crook 4678: doc-u>
4679: doc-u>=
4680:
4681: doc-within
4682:
4683: doc-d<
4684: doc-d<=
4685: doc-d<>
4686: doc-d=
4687: doc-d>
4688: doc-d>=
1.23 crook 4689:
1.21 crook 4690: doc-d0<
1.23 crook 4691: doc-d0<=
4692: doc-d0<>
1.21 crook 4693: doc-d0=
1.23 crook 4694: doc-d0>
4695: doc-d0>=
4696:
1.21 crook 4697: doc-du<
1.28 crook 4698: doc-du<=
1.44 crook 4699: @c du<> and du= exist but are the same as d<> and d=
1.31 anton 4700: @c doc-du<>
4701: @c doc-du=
1.28 crook 4702: doc-du>
4703: doc-du>=
1.1 anton 4704:
1.44 crook 4705:
1.21 crook 4706: @node Mixed precision, Floating Point, Numeric comparison, Arithmetic
1.1 anton 4707: @subsection Mixed precision
4708: @cindex mixed precision arithmetic words
4709:
1.44 crook 4710:
1.1 anton 4711: doc-m+
4712: doc-*/
4713: doc-*/mod
4714: doc-m*
4715: doc-um*
4716: doc-m*/
4717: doc-um/mod
4718: doc-fm/mod
4719: doc-sm/rem
4720:
1.44 crook 4721:
1.21 crook 4722: @node Floating Point, , Mixed precision, Arithmetic
1.1 anton 4723: @subsection Floating Point
4724: @cindex floating point arithmetic words
4725:
1.49 anton 4726: For the rules used by the text interpreter for
4727: recognising floating-point numbers see @ref{Number Conversion}.
1.1 anton 4728:
1.67 anton 4729: Gforth has a separate floating point stack, but the documentation uses
4730: the unified notation.@footnote{It's easy to generate the separate
4731: notation from that by just separating the floating-point numbers out:
4732: e.g. @code{( n r1 u r2 -- r3 )} becomes @code{( n u -- ) ( F: r1 r2 --
4733: r3 )}.}
1.1 anton 4734:
4735: @cindex floating-point arithmetic, pitfalls
4736: Floating point numbers have a number of unpleasant surprises for the
4737: unwary (e.g., floating point addition is not associative) and even a few
4738: for the wary. You should not use them unless you know what you are doing
4739: or you don't care that the results you get are totally bogus. If you
4740: want to learn about the problems of floating point numbers (and how to
1.66 anton 4741: avoid them), you might start with @cite{David Goldberg,
4742: @uref{http://www.validgh.com/goldberg/paper.ps,What Every Computer
4743: Scientist Should Know About Floating-Point Arithmetic}, ACM Computing
4744: Surveys 23(1):5@minus{}48, March 1991}.
1.1 anton 4745:
1.44 crook 4746:
1.21 crook 4747: doc-d>f
4748: doc-f>d
1.1 anton 4749: doc-f+
4750: doc-f-
4751: doc-f*
4752: doc-f/
4753: doc-fnegate
4754: doc-fabs
4755: doc-fmax
4756: doc-fmin
4757: doc-floor
4758: doc-fround
4759: doc-f**
4760: doc-fsqrt
4761: doc-fexp
4762: doc-fexpm1
4763: doc-fln
4764: doc-flnp1
4765: doc-flog
4766: doc-falog
1.32 anton 4767: doc-f2*
4768: doc-f2/
4769: doc-1/f
4770: doc-precision
4771: doc-set-precision
4772:
4773: @cindex angles in trigonometric operations
4774: @cindex trigonometric operations
4775: Angles in floating point operations are given in radians (a full circle
4776: has 2 pi radians).
4777:
1.1 anton 4778: doc-fsin
4779: doc-fcos
4780: doc-fsincos
4781: doc-ftan
4782: doc-fasin
4783: doc-facos
4784: doc-fatan
4785: doc-fatan2
4786: doc-fsinh
4787: doc-fcosh
4788: doc-ftanh
4789: doc-fasinh
4790: doc-facosh
4791: doc-fatanh
1.21 crook 4792: doc-pi
1.28 crook 4793:
1.32 anton 4794: @cindex equality of floats
4795: @cindex floating-point comparisons
1.31 anton 4796: One particular problem with floating-point arithmetic is that comparison
4797: for equality often fails when you would expect it to succeed. For this
4798: reason approximate equality is often preferred (but you still have to
1.67 anton 4799: know what you are doing). Also note that IEEE NaNs may compare
1.68 anton 4800: differently from what you might expect. The comparison words are:
1.31 anton 4801:
4802: doc-f~rel
4803: doc-f~abs
1.68 anton 4804: doc-f~
1.31 anton 4805: doc-f=
4806: doc-f<>
4807:
4808: doc-f<
4809: doc-f<=
4810: doc-f>
4811: doc-f>=
4812:
1.21 crook 4813: doc-f0<
1.28 crook 4814: doc-f0<=
4815: doc-f0<>
1.21 crook 4816: doc-f0=
1.28 crook 4817: doc-f0>
4818: doc-f0>=
4819:
1.1 anton 4820:
4821: @node Stack Manipulation, Memory, Arithmetic, Words
4822: @section Stack Manipulation
4823: @cindex stack manipulation words
4824:
4825: @cindex floating-point stack in the standard
1.21 crook 4826: Gforth maintains a number of separate stacks:
4827:
1.29 crook 4828: @cindex data stack
4829: @cindex parameter stack
1.21 crook 4830: @itemize @bullet
4831: @item
1.29 crook 4832: A data stack (also known as the @dfn{parameter stack}) -- for
4833: characters, cells, addresses, and double cells.
1.21 crook 4834:
1.29 crook 4835: @cindex floating-point stack
1.21 crook 4836: @item
1.44 crook 4837: A floating point stack -- for holding floating point (FP) numbers.
1.21 crook 4838:
1.29 crook 4839: @cindex return stack
1.21 crook 4840: @item
1.44 crook 4841: A return stack -- for holding the return addresses of colon
1.32 anton 4842: definitions and other (non-FP) data.
1.21 crook 4843:
1.29 crook 4844: @cindex locals stack
1.21 crook 4845: @item
1.44 crook 4846: A locals stack -- for holding local variables.
1.21 crook 4847: @end itemize
4848:
1.1 anton 4849: @menu
4850: * Data stack::
4851: * Floating point stack::
4852: * Return stack::
4853: * Locals stack::
4854: * Stack pointer manipulation::
4855: @end menu
4856:
4857: @node Data stack, Floating point stack, Stack Manipulation, Stack Manipulation
4858: @subsection Data stack
4859: @cindex data stack manipulation words
4860: @cindex stack manipulations words, data stack
4861:
1.44 crook 4862:
1.1 anton 4863: doc-drop
4864: doc-nip
4865: doc-dup
4866: doc-over
4867: doc-tuck
4868: doc-swap
1.21 crook 4869: doc-pick
1.1 anton 4870: doc-rot
4871: doc--rot
4872: doc-?dup
4873: doc-roll
4874: doc-2drop
4875: doc-2nip
4876: doc-2dup
4877: doc-2over
4878: doc-2tuck
4879: doc-2swap
4880: doc-2rot
4881:
1.44 crook 4882:
1.1 anton 4883: @node Floating point stack, Return stack, Data stack, Stack Manipulation
4884: @subsection Floating point stack
4885: @cindex floating-point stack manipulation words
4886: @cindex stack manipulation words, floating-point stack
4887:
1.32 anton 4888: Whilst every sane Forth has a separate floating-point stack, it is not
4889: strictly required; an ANS Forth system could theoretically keep
4890: floating-point numbers on the data stack. As an additional difficulty,
4891: you don't know how many cells a floating-point number takes. It is
4892: reportedly possible to write words in a way that they work also for a
4893: unified stack model, but we do not recommend trying it. Instead, just
4894: say that your program has an environmental dependency on a separate
4895: floating-point stack.
4896:
4897: doc-floating-stack
4898:
1.1 anton 4899: doc-fdrop
4900: doc-fnip
4901: doc-fdup
4902: doc-fover
4903: doc-ftuck
4904: doc-fswap
1.21 crook 4905: doc-fpick
1.1 anton 4906: doc-frot
4907:
1.44 crook 4908:
1.1 anton 4909: @node Return stack, Locals stack, Floating point stack, Stack Manipulation
4910: @subsection Return stack
4911: @cindex return stack manipulation words
4912: @cindex stack manipulation words, return stack
4913:
1.32 anton 4914: @cindex return stack and locals
4915: @cindex locals and return stack
4916: A Forth system is allowed to keep local variables on the
4917: return stack. This is reasonable, as local variables usually eliminate
4918: the need to use the return stack explicitly. So, if you want to produce
4919: a standard compliant program and you are using local variables in a
4920: word, forget about return stack manipulations in that word (refer to the
4921: standard document for the exact rules).
4922:
1.1 anton 4923: doc->r
4924: doc-r>
4925: doc-r@
4926: doc-rdrop
4927: doc-2>r
4928: doc-2r>
4929: doc-2r@
4930: doc-2rdrop
4931:
1.44 crook 4932:
1.1 anton 4933: @node Locals stack, Stack pointer manipulation, Return stack, Stack Manipulation
4934: @subsection Locals stack
4935:
1.78 anton 4936: Gforth uses an extra locals stack. It is described, along with the
4937: reasons for its existence, in @ref{Locals implementation}.
1.21 crook 4938:
1.1 anton 4939: @node Stack pointer manipulation, , Locals stack, Stack Manipulation
4940: @subsection Stack pointer manipulation
4941: @cindex stack pointer manipulation words
4942:
1.44 crook 4943: @c removed s0 r0 l0 -- they are obsolete aliases for sp0 rp0 lp0
1.21 crook 4944: doc-sp0
1.1 anton 4945: doc-sp@
4946: doc-sp!
1.21 crook 4947: doc-fp0
1.1 anton 4948: doc-fp@
4949: doc-fp!
1.21 crook 4950: doc-rp0
1.1 anton 4951: doc-rp@
4952: doc-rp!
1.21 crook 4953: doc-lp0
1.1 anton 4954: doc-lp@
4955: doc-lp!
4956:
1.44 crook 4957:
1.1 anton 4958: @node Memory, Control Structures, Stack Manipulation, Words
4959: @section Memory
1.26 crook 4960: @cindex memory words
1.1 anton 4961:
1.32 anton 4962: @menu
4963: * Memory model::
4964: * Dictionary allocation::
4965: * Heap Allocation::
4966: * Memory Access::
4967: * Address arithmetic::
4968: * Memory Blocks::
4969: @end menu
4970:
1.67 anton 4971: In addition to the standard Forth memory allocation words, there is also
4972: a @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
4973: garbage collector}.
4974:
1.32 anton 4975: @node Memory model, Dictionary allocation, Memory, Memory
4976: @subsection ANS Forth and Gforth memory models
4977:
4978: @c The ANS Forth description is a mess (e.g., is the heap part of
4979: @c the dictionary?), so let's not stick to closely with it.
4980:
1.67 anton 4981: ANS Forth considers a Forth system as consisting of several address
4982: spaces, of which only @dfn{data space} is managed and accessible with
4983: the memory words. Memory not necessarily in data space includes the
4984: stacks, the code (called code space) and the headers (called name
4985: space). In Gforth everything is in data space, but the code for the
4986: primitives is usually read-only.
1.32 anton 4987:
4988: Data space is divided into a number of areas: The (data space portion of
4989: the) dictionary@footnote{Sometimes, the term @dfn{dictionary} is used to
4990: refer to the search data structure embodied in word lists and headers,
4991: because it is used for looking up names, just as you would in a
4992: conventional dictionary.}, the heap, and a number of system-allocated
4993: buffers.
4994:
1.68 anton 4995: @cindex address arithmetic restrictions, ANS vs. Gforth
4996: @cindex contiguous regions, ANS vs. Gforth
1.32 anton 4997: In ANS Forth data space is also divided into contiguous regions. You
4998: can only use address arithmetic within a contiguous region, not between
4999: them. Usually each allocation gives you one contiguous region, but the
1.33 anton 5000: dictionary allocation words have additional rules (@pxref{Dictionary
1.32 anton 5001: allocation}).
5002:
5003: Gforth provides one big address space, and address arithmetic can be
5004: performed between any addresses. However, in the dictionary headers or
5005: code are interleaved with data, so almost the only contiguous data space
5006: regions there are those described by ANS Forth as contiguous; but you
5007: can be sure that the dictionary is allocated towards increasing
5008: addresses even between contiguous regions. The memory order of
5009: allocations in the heap is platform-dependent (and possibly different
5010: from one run to the next).
5011:
1.27 crook 5012:
1.32 anton 5013: @node Dictionary allocation, Heap Allocation, Memory model, Memory
5014: @subsection Dictionary allocation
1.27 crook 5015: @cindex reserving data space
5016: @cindex data space - reserving some
5017:
1.32 anton 5018: Dictionary allocation is a stack-oriented allocation scheme, i.e., if
5019: you want to deallocate X, you also deallocate everything
5020: allocated after X.
5021:
1.68 anton 5022: @cindex contiguous regions in dictionary allocation
1.32 anton 5023: The allocations using the words below are contiguous and grow the region
5024: towards increasing addresses. Other words that allocate dictionary
5025: memory of any kind (i.e., defining words including @code{:noname}) end
5026: the contiguous region and start a new one.
5027:
5028: In ANS Forth only @code{create}d words are guaranteed to produce an
5029: address that is the start of the following contiguous region. In
5030: particular, the cell allocated by @code{variable} is not guaranteed to
5031: be contiguous with following @code{allot}ed memory.
5032:
5033: You can deallocate memory by using @code{allot} with a negative argument
5034: (with some restrictions, see @code{allot}). For larger deallocations use
5035: @code{marker}.
1.27 crook 5036:
1.29 crook 5037:
1.27 crook 5038: doc-here
5039: doc-unused
5040: doc-allot
5041: doc-c,
1.29 crook 5042: doc-f,
1.27 crook 5043: doc-,
5044: doc-2,
5045:
1.32 anton 5046: Memory accesses have to be aligned (@pxref{Address arithmetic}). So of
5047: course you should allocate memory in an aligned way, too. I.e., before
5048: allocating allocating a cell, @code{here} must be cell-aligned, etc.
5049: The words below align @code{here} if it is not already. Basically it is
5050: only already aligned for a type, if the last allocation was a multiple
5051: of the size of this type and if @code{here} was aligned for this type
5052: before.
5053:
5054: After freshly @code{create}ing a word, @code{here} is @code{align}ed in
5055: ANS Forth (@code{maxalign}ed in Gforth).
5056:
5057: doc-align
5058: doc-falign
5059: doc-sfalign
5060: doc-dfalign
5061: doc-maxalign
5062: doc-cfalign
5063:
5064:
5065: @node Heap Allocation, Memory Access, Dictionary allocation, Memory
5066: @subsection Heap allocation
5067: @cindex heap allocation
5068: @cindex dynamic allocation of memory
5069: @cindex memory-allocation word set
5070:
1.68 anton 5071: @cindex contiguous regions and heap allocation
1.32 anton 5072: Heap allocation supports deallocation of allocated memory in any
5073: order. Dictionary allocation is not affected by it (i.e., it does not
5074: end a contiguous region). In Gforth, these words are implemented using
5075: the standard C library calls malloc(), free() and resize().
5076:
1.68 anton 5077: The memory region produced by one invocation of @code{allocate} or
5078: @code{resize} is internally contiguous. There is no contiguity between
5079: such a region and any other region (including others allocated from the
5080: heap).
5081:
1.32 anton 5082: doc-allocate
5083: doc-free
5084: doc-resize
5085:
1.27 crook 5086:
1.32 anton 5087: @node Memory Access, Address arithmetic, Heap Allocation, Memory
1.1 anton 5088: @subsection Memory Access
5089: @cindex memory access words
5090:
5091: doc-@
5092: doc-!
5093: doc-+!
5094: doc-c@
5095: doc-c!
5096: doc-2@
5097: doc-2!
5098: doc-f@
5099: doc-f!
5100: doc-sf@
5101: doc-sf!
5102: doc-df@
5103: doc-df!
5104:
1.68 anton 5105:
1.32 anton 5106: @node Address arithmetic, Memory Blocks, Memory Access, Memory
5107: @subsection Address arithmetic
1.1 anton 5108: @cindex address arithmetic words
5109:
1.67 anton 5110: Address arithmetic is the foundation on which you can build data
5111: structures like arrays, records (@pxref{Structures}) and objects
5112: (@pxref{Object-oriented Forth}).
1.32 anton 5113:
1.68 anton 5114: @cindex address unit
5115: @cindex au (address unit)
1.1 anton 5116: ANS Forth does not specify the sizes of the data types. Instead, it
5117: offers a number of words for computing sizes and doing address
1.29 crook 5118: arithmetic. Address arithmetic is performed in terms of address units
5119: (aus); on most systems the address unit is one byte. Note that a
5120: character may have more than one au, so @code{chars} is no noop (on
1.68 anton 5121: platforms where it is a noop, it compiles to nothing).
1.1 anton 5122:
1.67 anton 5123: The basic address arithmetic words are @code{+} and @code{-}. E.g., if
5124: you have the address of a cell, perform @code{1 cells +}, and you will
5125: have the address of the next cell.
5126:
1.68 anton 5127: @cindex contiguous regions and address arithmetic
1.67 anton 5128: In ANS Forth you can perform address arithmetic only within a contiguous
5129: region, i.e., if you have an address into one region, you can only add
5130: and subtract such that the result is still within the region; you can
5131: only subtract or compare addresses from within the same contiguous
5132: region. Reasons: several contiguous regions can be arranged in memory
5133: in any way; on segmented systems addresses may have unusual
5134: representations, such that address arithmetic only works within a
5135: region. Gforth provides a few more guarantees (linear address space,
5136: dictionary grows upwards), but in general I have found it easy to stay
5137: within contiguous regions (exception: computing and comparing to the
5138: address just beyond the end of an array).
5139:
1.1 anton 5140: @cindex alignment of addresses for types
5141: ANS Forth also defines words for aligning addresses for specific
5142: types. Many computers require that accesses to specific data types
5143: must only occur at specific addresses; e.g., that cells may only be
5144: accessed at addresses divisible by 4. Even if a machine allows unaligned
5145: accesses, it can usually perform aligned accesses faster.
5146:
5147: For the performance-conscious: alignment operations are usually only
5148: necessary during the definition of a data structure, not during the
5149: (more frequent) accesses to it.
5150:
5151: ANS Forth defines no words for character-aligning addresses. This is not
5152: an oversight, but reflects the fact that addresses that are not
5153: char-aligned have no use in the standard and therefore will not be
5154: created.
5155:
5156: @cindex @code{CREATE} and alignment
1.29 crook 5157: ANS Forth guarantees that addresses returned by @code{CREATE}d words
1.1 anton 5158: are cell-aligned; in addition, Gforth guarantees that these addresses
5159: are aligned for all purposes.
5160:
1.26 crook 5161: Note that the ANS Forth word @code{char} has nothing to do with address
5162: arithmetic.
1.1 anton 5163:
1.44 crook 5164:
1.1 anton 5165: doc-chars
5166: doc-char+
5167: doc-cells
5168: doc-cell+
5169: doc-cell
5170: doc-aligned
5171: doc-floats
5172: doc-float+
5173: doc-float
5174: doc-faligned
5175: doc-sfloats
5176: doc-sfloat+
5177: doc-sfaligned
5178: doc-dfloats
5179: doc-dfloat+
5180: doc-dfaligned
5181: doc-maxaligned
5182: doc-cfaligned
5183: doc-address-unit-bits
5184:
1.44 crook 5185:
1.32 anton 5186: @node Memory Blocks, , Address arithmetic, Memory
1.1 anton 5187: @subsection Memory Blocks
5188: @cindex memory block words
1.27 crook 5189: @cindex character strings - moving and copying
5190:
1.49 anton 5191: Memory blocks often represent character strings; For ways of storing
5192: character strings in memory see @ref{String Formats}. For other
5193: string-processing words see @ref{Displaying characters and strings}.
1.1 anton 5194:
1.67 anton 5195: A few of these words work on address unit blocks. In that case, you
5196: usually have to insert @code{CHARS} before the word when working on
5197: character strings. Most words work on character blocks, and expect a
5198: char-aligned address.
5199:
5200: When copying characters between overlapping memory regions, use
5201: @code{chars move} or choose carefully between @code{cmove} and
5202: @code{cmove>}.
1.44 crook 5203:
1.1 anton 5204: doc-move
5205: doc-erase
5206: doc-cmove
5207: doc-cmove>
5208: doc-fill
5209: doc-blank
1.21 crook 5210: doc-compare
5211: doc-search
1.27 crook 5212: doc--trailing
5213: doc-/string
1.82 ! anton 5214: doc-bounds
1.44 crook 5215:
1.27 crook 5216: @comment TODO examples
5217:
1.1 anton 5218:
1.26 crook 5219: @node Control Structures, Defining Words, Memory, Words
1.1 anton 5220: @section Control Structures
5221: @cindex control structures
5222:
1.33 anton 5223: Control structures in Forth cannot be used interpretively, only in a
5224: colon definition@footnote{To be precise, they have no interpretation
5225: semantics (@pxref{Interpretation and Compilation Semantics}).}. We do
5226: not like this limitation, but have not seen a satisfying way around it
5227: yet, although many schemes have been proposed.
1.1 anton 5228:
5229: @menu
1.33 anton 5230: * Selection:: IF ... ELSE ... ENDIF
5231: * Simple Loops:: BEGIN ...
1.29 crook 5232: * Counted Loops:: DO
1.67 anton 5233: * Arbitrary control structures::
5234: * Calls and returns::
1.1 anton 5235: * Exception Handling::
5236: @end menu
5237:
5238: @node Selection, Simple Loops, Control Structures, Control Structures
5239: @subsection Selection
5240: @cindex selection control structures
5241: @cindex control structures for selection
5242:
5243: @cindex @code{IF} control structure
5244: @example
1.29 crook 5245: @i{flag}
1.1 anton 5246: IF
1.29 crook 5247: @i{code}
1.1 anton 5248: ENDIF
5249: @end example
1.21 crook 5250: @noindent
1.33 anton 5251:
1.44 crook 5252: If @i{flag} is non-zero (as far as @code{IF} etc. are concerned, a cell
5253: with any bit set represents truth) @i{code} is executed.
1.33 anton 5254:
1.1 anton 5255: @example
1.29 crook 5256: @i{flag}
1.1 anton 5257: IF
1.29 crook 5258: @i{code1}
1.1 anton 5259: ELSE
1.29 crook 5260: @i{code2}
1.1 anton 5261: ENDIF
5262: @end example
5263:
1.44 crook 5264: If @var{flag} is true, @i{code1} is executed, otherwise @i{code2} is
5265: executed.
1.33 anton 5266:
1.1 anton 5267: You can use @code{THEN} instead of @code{ENDIF}. Indeed, @code{THEN} is
5268: standard, and @code{ENDIF} is not, although it is quite popular. We
5269: recommend using @code{ENDIF}, because it is less confusing for people
5270: who also know other languages (and is not prone to reinforcing negative
5271: prejudices against Forth in these people). Adding @code{ENDIF} to a
5272: system that only supplies @code{THEN} is simple:
5273: @example
1.82 ! anton 5274: : ENDIF POSTPONE then ; immediate
1.1 anton 5275: @end example
5276:
5277: [According to @cite{Webster's New Encyclopedic Dictionary}, @dfn{then
5278: (adv.)} has the following meanings:
5279: @quotation
5280: ... 2b: following next after in order ... 3d: as a necessary consequence
5281: (if you were there, then you saw them).
5282: @end quotation
5283: Forth's @code{THEN} has the meaning 2b, whereas @code{THEN} in Pascal
5284: and many other programming languages has the meaning 3d.]
5285:
1.21 crook 5286: Gforth also provides the words @code{?DUP-IF} and @code{?DUP-0=-IF}, so
1.1 anton 5287: you can avoid using @code{?dup}. Using these alternatives is also more
1.26 crook 5288: efficient than using @code{?dup}. Definitions in ANS Forth
1.1 anton 5289: for @code{ENDIF}, @code{?DUP-IF} and @code{?DUP-0=-IF} are provided in
5290: @file{compat/control.fs}.
5291:
5292: @cindex @code{CASE} control structure
5293: @example
1.29 crook 5294: @i{n}
1.1 anton 5295: CASE
1.29 crook 5296: @i{n1} OF @i{code1} ENDOF
5297: @i{n2} OF @i{code2} ENDOF
1.1 anton 5298: @dots{}
1.68 anton 5299: ( n ) @i{default-code} ( n )
1.1 anton 5300: ENDCASE
5301: @end example
5302:
1.68 anton 5303: Executes the first @i{codei}, where the @i{ni} is equal to @i{n}. If no
5304: @i{ni} matches, the optional @i{default-code} is executed. The optional
5305: default case can be added by simply writing the code after the last
5306: @code{ENDOF}. It may use @i{n}, which is on top of the stack, but must
5307: not consume it.
1.1 anton 5308:
1.69 anton 5309: @progstyle
5310: To keep the code understandable, you should ensure that on all paths
5311: through a selection construct the stack is changed in the same way
5312: (wrt. number and types of stack items consumed and pushed).
5313:
1.1 anton 5314: @node Simple Loops, Counted Loops, Selection, Control Structures
5315: @subsection Simple Loops
5316: @cindex simple loops
5317: @cindex loops without count
5318:
5319: @cindex @code{WHILE} loop
5320: @example
5321: BEGIN
1.29 crook 5322: @i{code1}
5323: @i{flag}
1.1 anton 5324: WHILE
1.29 crook 5325: @i{code2}
1.1 anton 5326: REPEAT
5327: @end example
5328:
1.29 crook 5329: @i{code1} is executed and @i{flag} is computed. If it is true,
5330: @i{code2} is executed and the loop is restarted; If @i{flag} is
1.1 anton 5331: false, execution continues after the @code{REPEAT}.
5332:
5333: @cindex @code{UNTIL} loop
5334: @example
5335: BEGIN
1.29 crook 5336: @i{code}
5337: @i{flag}
1.1 anton 5338: UNTIL
5339: @end example
5340:
1.29 crook 5341: @i{code} is executed. The loop is restarted if @code{flag} is false.
1.1 anton 5342:
1.69 anton 5343: @progstyle
5344: To keep the code understandable, a complete iteration of the loop should
5345: not change the number and types of the items on the stacks.
5346:
1.1 anton 5347: @cindex endless loop
5348: @cindex loops, endless
5349: @example
5350: BEGIN
1.29 crook 5351: @i{code}
1.1 anton 5352: AGAIN
5353: @end example
5354:
5355: This is an endless loop.
5356:
5357: @node Counted Loops, Arbitrary control structures, Simple Loops, Control Structures
5358: @subsection Counted Loops
5359: @cindex counted loops
5360: @cindex loops, counted
5361: @cindex @code{DO} loops
5362:
5363: The basic counted loop is:
5364: @example
1.29 crook 5365: @i{limit} @i{start}
1.1 anton 5366: ?DO
1.29 crook 5367: @i{body}
1.1 anton 5368: LOOP
5369: @end example
5370:
1.29 crook 5371: This performs one iteration for every integer, starting from @i{start}
5372: and up to, but excluding @i{limit}. The counter, or @i{index}, can be
1.21 crook 5373: accessed with @code{i}. For example, the loop:
1.1 anton 5374: @example
5375: 10 0 ?DO
5376: i .
5377: LOOP
5378: @end example
1.21 crook 5379: @noindent
5380: prints @code{0 1 2 3 4 5 6 7 8 9}
5381:
1.1 anton 5382: The index of the innermost loop can be accessed with @code{i}, the index
5383: of the next loop with @code{j}, and the index of the third loop with
5384: @code{k}.
5385:
1.44 crook 5386:
1.1 anton 5387: doc-i
5388: doc-j
5389: doc-k
5390:
1.44 crook 5391:
1.1 anton 5392: The loop control data are kept on the return stack, so there are some
1.21 crook 5393: restrictions on mixing return stack accesses and counted loop words. In
5394: particuler, if you put values on the return stack outside the loop, you
5395: cannot read them inside the loop@footnote{well, not in a way that is
5396: portable.}. If you put values on the return stack within a loop, you
5397: have to remove them before the end of the loop and before accessing the
5398: index of the loop.
1.1 anton 5399:
5400: There are several variations on the counted loop:
5401:
1.21 crook 5402: @itemize @bullet
5403: @item
5404: @code{LEAVE} leaves the innermost counted loop immediately; execution
5405: continues after the associated @code{LOOP} or @code{NEXT}. For example:
5406:
5407: @example
5408: 10 0 ?DO i DUP . 3 = IF LEAVE THEN LOOP
5409: @end example
5410: prints @code{0 1 2 3}
5411:
1.1 anton 5412:
1.21 crook 5413: @item
5414: @code{UNLOOP} prepares for an abnormal loop exit, e.g., via
5415: @code{EXIT}. @code{UNLOOP} removes the loop control parameters from the
5416: return stack so @code{EXIT} can get to its return address. For example:
5417:
5418: @example
5419: : demo 10 0 ?DO i DUP . 3 = IF UNLOOP EXIT THEN LOOP ." Done" ;
5420: @end example
5421: prints @code{0 1 2 3}
5422:
5423:
5424: @item
1.29 crook 5425: If @i{start} is greater than @i{limit}, a @code{?DO} loop is entered
1.1 anton 5426: (and @code{LOOP} iterates until they become equal by wrap-around
5427: arithmetic). This behaviour is usually not what you want. Therefore,
5428: Gforth offers @code{+DO} and @code{U+DO} (as replacements for
1.29 crook 5429: @code{?DO}), which do not enter the loop if @i{start} is greater than
5430: @i{limit}; @code{+DO} is for signed loop parameters, @code{U+DO} for
1.1 anton 5431: unsigned loop parameters.
5432:
1.21 crook 5433: @item
5434: @code{?DO} can be replaced by @code{DO}. @code{DO} always enters
5435: the loop, independent of the loop parameters. Do not use @code{DO}, even
5436: if you know that the loop is entered in any case. Such knowledge tends
5437: to become invalid during maintenance of a program, and then the
5438: @code{DO} will make trouble.
5439:
5440: @item
1.29 crook 5441: @code{LOOP} can be replaced with @code{@i{n} +LOOP}; this updates the
5442: index by @i{n} instead of by 1. The loop is terminated when the border
5443: between @i{limit-1} and @i{limit} is crossed. E.g.:
1.1 anton 5444:
1.21 crook 5445: @example
5446: 4 0 +DO i . 2 +LOOP
5447: @end example
5448: @noindent
5449: prints @code{0 2}
5450:
5451: @example
5452: 4 1 +DO i . 2 +LOOP
5453: @end example
5454: @noindent
5455: prints @code{1 3}
1.1 anton 5456:
1.68 anton 5457: @item
1.1 anton 5458: @cindex negative increment for counted loops
5459: @cindex counted loops with negative increment
1.29 crook 5460: The behaviour of @code{@i{n} +LOOP} is peculiar when @i{n} is negative:
1.1 anton 5461:
1.21 crook 5462: @example
5463: -1 0 ?DO i . -1 +LOOP
5464: @end example
5465: @noindent
5466: prints @code{0 -1}
1.1 anton 5467:
1.21 crook 5468: @example
5469: 0 0 ?DO i . -1 +LOOP
5470: @end example
5471: prints nothing.
1.1 anton 5472:
1.29 crook 5473: Therefore we recommend avoiding @code{@i{n} +LOOP} with negative
5474: @i{n}. One alternative is @code{@i{u} -LOOP}, which reduces the
5475: index by @i{u} each iteration. The loop is terminated when the border
5476: between @i{limit+1} and @i{limit} is crossed. Gforth also provides
1.1 anton 5477: @code{-DO} and @code{U-DO} for down-counting loops. E.g.:
5478:
1.21 crook 5479: @example
5480: -2 0 -DO i . 1 -LOOP
5481: @end example
5482: @noindent
5483: prints @code{0 -1}
1.1 anton 5484:
1.21 crook 5485: @example
5486: -1 0 -DO i . 1 -LOOP
5487: @end example
5488: @noindent
5489: prints @code{0}
5490:
5491: @example
5492: 0 0 -DO i . 1 -LOOP
5493: @end example
5494: @noindent
5495: prints nothing.
1.1 anton 5496:
1.21 crook 5497: @end itemize
1.1 anton 5498:
5499: Unfortunately, @code{+DO}, @code{U+DO}, @code{-DO}, @code{U-DO} and
1.26 crook 5500: @code{-LOOP} are not defined in ANS Forth. However, an implementation
5501: for these words that uses only standard words is provided in
5502: @file{compat/loops.fs}.
1.1 anton 5503:
5504:
5505: @cindex @code{FOR} loops
1.26 crook 5506: Another counted loop is:
1.1 anton 5507: @example
1.29 crook 5508: @i{n}
1.1 anton 5509: FOR
1.29 crook 5510: @i{body}
1.1 anton 5511: NEXT
5512: @end example
5513: This is the preferred loop of native code compiler writers who are too
1.26 crook 5514: lazy to optimize @code{?DO} loops properly. This loop structure is not
1.29 crook 5515: defined in ANS Forth. In Gforth, this loop iterates @i{n+1} times;
5516: @code{i} produces values starting with @i{n} and ending with 0. Other
1.26 crook 5517: Forth systems may behave differently, even if they support @code{FOR}
5518: loops. To avoid problems, don't use @code{FOR} loops.
1.1 anton 5519:
5520: @node Arbitrary control structures, Calls and returns, Counted Loops, Control Structures
5521: @subsection Arbitrary control structures
5522: @cindex control structures, user-defined
5523:
5524: @cindex control-flow stack
5525: ANS Forth permits and supports using control structures in a non-nested
5526: way. Information about incomplete control structures is stored on the
5527: control-flow stack. This stack may be implemented on the Forth data
5528: stack, and this is what we have done in Gforth.
5529:
5530: @cindex @code{orig}, control-flow stack item
5531: @cindex @code{dest}, control-flow stack item
5532: An @i{orig} entry represents an unresolved forward branch, a @i{dest}
5533: entry represents a backward branch target. A few words are the basis for
5534: building any control structure possible (except control structures that
5535: need storage, like calls, coroutines, and backtracking).
5536:
1.44 crook 5537:
1.1 anton 5538: doc-if
5539: doc-ahead
5540: doc-then
5541: doc-begin
5542: doc-until
5543: doc-again
5544: doc-cs-pick
5545: doc-cs-roll
5546:
1.44 crook 5547:
1.21 crook 5548: The Standard words @code{CS-PICK} and @code{CS-ROLL} allow you to
5549: manipulate the control-flow stack in a portable way. Without them, you
5550: would need to know how many stack items are occupied by a control-flow
5551: entry (many systems use one cell. In Gforth they currently take three,
5552: but this may change in the future).
5553:
1.1 anton 5554: Some standard control structure words are built from these words:
5555:
1.44 crook 5556:
1.1 anton 5557: doc-else
5558: doc-while
5559: doc-repeat
5560:
1.44 crook 5561:
5562: @noindent
1.1 anton 5563: Gforth adds some more control-structure words:
5564:
1.44 crook 5565:
1.1 anton 5566: doc-endif
5567: doc-?dup-if
5568: doc-?dup-0=-if
5569:
1.44 crook 5570:
5571: @noindent
1.1 anton 5572: Counted loop words constitute a separate group of words:
5573:
1.44 crook 5574:
1.1 anton 5575: doc-?do
5576: doc-+do
5577: doc-u+do
5578: doc--do
5579: doc-u-do
5580: doc-do
5581: doc-for
5582: doc-loop
5583: doc-+loop
5584: doc--loop
5585: doc-next
5586: doc-leave
5587: doc-?leave
5588: doc-unloop
5589: doc-done
5590:
1.44 crook 5591:
1.21 crook 5592: The standard does not allow using @code{CS-PICK} and @code{CS-ROLL} on
5593: @i{do-sys}. Gforth allows it, but it's your job to ensure that for
1.1 anton 5594: every @code{?DO} etc. there is exactly one @code{UNLOOP} on any path
5595: through the definition (@code{LOOP} etc. compile an @code{UNLOOP} on the
5596: fall-through path). Also, you have to ensure that all @code{LEAVE}s are
5597: resolved (by using one of the loop-ending words or @code{DONE}).
5598:
1.44 crook 5599: @noindent
1.26 crook 5600: Another group of control structure words are:
1.1 anton 5601:
1.44 crook 5602:
1.1 anton 5603: doc-case
5604: doc-endcase
5605: doc-of
5606: doc-endof
5607:
1.44 crook 5608:
1.21 crook 5609: @i{case-sys} and @i{of-sys} cannot be processed using @code{CS-PICK} and
5610: @code{CS-ROLL}.
1.1 anton 5611:
5612: @subsubsection Programming Style
1.47 crook 5613: @cindex control structures programming style
5614: @cindex programming style, arbitrary control structures
1.1 anton 5615:
5616: In order to ensure readability we recommend that you do not create
5617: arbitrary control structures directly, but define new control structure
5618: words for the control structure you want and use these words in your
1.26 crook 5619: program. For example, instead of writing:
1.1 anton 5620:
5621: @example
1.26 crook 5622: BEGIN
1.1 anton 5623: ...
1.26 crook 5624: IF [ 1 CS-ROLL ]
1.1 anton 5625: ...
1.26 crook 5626: AGAIN THEN
1.1 anton 5627: @end example
5628:
1.21 crook 5629: @noindent
1.1 anton 5630: we recommend defining control structure words, e.g.,
5631:
5632: @example
1.26 crook 5633: : WHILE ( DEST -- ORIG DEST )
5634: POSTPONE IF
5635: 1 CS-ROLL ; immediate
5636:
5637: : REPEAT ( orig dest -- )
5638: POSTPONE AGAIN
5639: POSTPONE THEN ; immediate
1.1 anton 5640: @end example
5641:
1.21 crook 5642: @noindent
1.1 anton 5643: and then using these to create the control structure:
5644:
5645: @example
1.26 crook 5646: BEGIN
1.1 anton 5647: ...
1.26 crook 5648: WHILE
1.1 anton 5649: ...
1.26 crook 5650: REPEAT
1.1 anton 5651: @end example
5652:
5653: That's much easier to read, isn't it? Of course, @code{REPEAT} and
5654: @code{WHILE} are predefined, so in this example it would not be
5655: necessary to define them.
5656:
5657: @node Calls and returns, Exception Handling, Arbitrary control structures, Control Structures
5658: @subsection Calls and returns
5659: @cindex calling a definition
5660: @cindex returning from a definition
5661:
1.3 anton 5662: @cindex recursive definitions
5663: A definition can be called simply be writing the name of the definition
1.26 crook 5664: to be called. Normally a definition is invisible during its own
1.3 anton 5665: definition. If you want to write a directly recursive definition, you
1.26 crook 5666: can use @code{recursive} to make the current definition visible, or
5667: @code{recurse} to call the current definition directly.
1.3 anton 5668:
1.44 crook 5669:
1.3 anton 5670: doc-recursive
5671: doc-recurse
5672:
1.44 crook 5673:
1.21 crook 5674: @comment TODO add example of the two recursion methods
1.12 anton 5675: @quotation
5676: @progstyle
5677: I prefer using @code{recursive} to @code{recurse}, because calling the
5678: definition by name is more descriptive (if the name is well-chosen) than
5679: the somewhat cryptic @code{recurse}. E.g., in a quicksort
5680: implementation, it is much better to read (and think) ``now sort the
5681: partitions'' than to read ``now do a recursive call''.
5682: @end quotation
1.3 anton 5683:
1.29 crook 5684: For mutual recursion, use @code{Defer}red words, like this:
1.3 anton 5685:
5686: @example
1.28 crook 5687: Defer foo
1.3 anton 5688:
5689: : bar ( ... -- ... )
5690: ... foo ... ;
5691:
5692: :noname ( ... -- ... )
5693: ... bar ... ;
5694: IS foo
5695: @end example
5696:
1.44 crook 5697: Deferred words are discussed in more detail in @ref{Deferred words}.
1.33 anton 5698:
1.26 crook 5699: The current definition returns control to the calling definition when
1.33 anton 5700: the end of the definition is reached or @code{EXIT} is encountered.
1.1 anton 5701:
5702: doc-exit
5703: doc-;s
5704:
1.44 crook 5705:
1.1 anton 5706: @node Exception Handling, , Calls and returns, Control Structures
5707: @subsection Exception Handling
1.26 crook 5708: @cindex exceptions
1.1 anton 5709:
1.68 anton 5710: @c quit is a very bad idea for error handling,
5711: @c because it does not translate into a THROW
5712: @c it also does not belong into this chapter
5713:
5714: If a word detects an error condition that it cannot handle, it can
5715: @code{throw} an exception. In the simplest case, this will terminate
5716: your program, and report an appropriate error.
1.21 crook 5717:
1.68 anton 5718: doc-throw
1.1 anton 5719:
1.69 anton 5720: @code{Throw} consumes a cell-sized error number on the stack. There are
5721: some predefined error numbers in ANS Forth (see @file{errors.fs}). In
5722: Gforth (and most other systems) you can use the iors produced by various
5723: words as error numbers (e.g., a typical use of @code{allocate} is
5724: @code{allocate throw}). Gforth also provides the word @code{exception}
5725: to define your own error numbers (with decent error reporting); an ANS
5726: Forth version of this word (but without the error messages) is available
5727: in @code{compat/except.fs}. And finally, you can use your own error
1.68 anton 5728: numbers (anything outside the range -4095..0), but won't get nice error
5729: messages, only numbers. For example, try:
5730:
5731: @example
1.69 anton 5732: -10 throw \ ANS defined
5733: -267 throw \ system defined
5734: s" my error" exception throw \ user defined
5735: 7 throw \ arbitrary number
1.68 anton 5736: @end example
5737:
5738: doc---exception-exception
1.1 anton 5739:
1.69 anton 5740: A common idiom to @code{THROW} a specific error if a flag is true is
5741: this:
5742:
5743: @example
5744: @code{( flag ) 0<> @i{errno} and throw}
5745: @end example
5746:
5747: Your program can provide exception handlers to catch exceptions. An
5748: exception handler can be used to correct the problem, or to clean up
5749: some data structures and just throw the exception to the next exception
5750: handler. Note that @code{throw} jumps to the dynamically innermost
5751: exception handler. The system's exception handler is outermost, and just
5752: prints an error and restarts command-line interpretation (or, in batch
5753: mode (i.e., while processing the shell command line), leaves Gforth).
1.1 anton 5754:
1.68 anton 5755: The ANS Forth way to catch exceptions is @code{catch}:
1.1 anton 5756:
1.68 anton 5757: doc-catch
5758:
5759: The most common use of exception handlers is to clean up the state when
5760: an error happens. E.g.,
1.1 anton 5761:
1.26 crook 5762: @example
1.68 anton 5763: base @ >r hex \ actually the hex should be inside foo, or we h
5764: ['] foo catch ( nerror|0 )
5765: r> base !
1.69 anton 5766: ( nerror|0 ) throw \ pass it on
1.26 crook 5767: @end example
1.1 anton 5768:
1.69 anton 5769: A use of @code{catch} for handling the error @code{myerror} might look
5770: like this:
1.44 crook 5771:
1.68 anton 5772: @example
1.69 anton 5773: ['] foo catch
5774: CASE
5775: myerror OF ... ( do something about it ) ENDOF
5776: dup throw \ default: pass other errors on, do nothing on non-errors
5777: ENDCASE
1.68 anton 5778: @end example
1.44 crook 5779:
1.68 anton 5780: Having to wrap the code into a separate word is often cumbersome,
5781: therefore Gforth provides an alternative syntax:
1.1 anton 5782:
5783: @example
1.69 anton 5784: TRY
1.68 anton 5785: @i{code1}
1.69 anton 5786: RECOVER \ optional
1.68 anton 5787: @i{code2} \ optional
1.69 anton 5788: ENDTRY
1.1 anton 5789: @end example
5790:
1.68 anton 5791: This performs @i{Code1}. If @i{code1} completes normally, execution
5792: continues after the @code{endtry}. If @i{Code1} throws, the stacks are
5793: reset to the state during @code{try}, the throw value is pushed on the
5794: data stack, and execution constinues at @i{code2}, and finally falls
5795: through the @code{endtry} into the following code. If there is no
5796: @code{recover} clause, this works like an empty recover clause.
1.26 crook 5797:
1.68 anton 5798: doc-try
5799: doc-recover
5800: doc-endtry
1.26 crook 5801:
1.69 anton 5802: The cleanup example from above in this syntax:
1.26 crook 5803:
1.68 anton 5804: @example
1.69 anton 5805: base @ >r TRY
1.68 anton 5806: hex foo \ now the hex is placed correctly
1.69 anton 5807: 0 \ value for throw
5808: ENDTRY
1.68 anton 5809: r> base ! throw
1.1 anton 5810: @end example
5811:
1.69 anton 5812: And here's the error handling example:
1.1 anton 5813:
1.68 anton 5814: @example
1.69 anton 5815: TRY
1.68 anton 5816: foo
1.69 anton 5817: RECOVER
5818: CASE
5819: myerror OF ... ( do something about it ) ENDOF
5820: throw \ pass other errors on
5821: ENDCASE
5822: ENDTRY
1.68 anton 5823: @end example
1.1 anton 5824:
1.69 anton 5825: @progstyle
5826: As usual, you should ensure that the stack depth is statically known at
5827: the end: either after the @code{throw} for passing on errors, or after
5828: the @code{ENDTRY} (or, if you use @code{catch}, after the end of the
5829: selection construct for handling the error).
5830:
1.68 anton 5831: There are two alternatives to @code{throw}: @code{Abort"} is conditional
5832: and you can provide an error message. @code{Abort} just produces an
5833: ``Aborted'' error.
1.1 anton 5834:
1.68 anton 5835: The problem with these words is that exception handlers cannot
5836: differentiate between different @code{abort"}s; they just look like
5837: @code{-2 throw} to them (the error message cannot be accessed by
5838: standard programs). Similar @code{abort} looks like @code{-1 throw} to
5839: exception handlers.
1.44 crook 5840:
1.68 anton 5841: doc-abort"
1.26 crook 5842: doc-abort
1.29 crook 5843:
5844:
1.44 crook 5845:
1.29 crook 5846: @c -------------------------------------------------------------
1.47 crook 5847: @node Defining Words, Interpretation and Compilation Semantics, Control Structures, Words
1.29 crook 5848: @section Defining Words
5849: @cindex defining words
5850:
1.47 crook 5851: Defining words are used to extend Forth by creating new entries in the dictionary.
5852:
1.29 crook 5853: @menu
1.67 anton 5854: * CREATE::
1.44 crook 5855: * Variables:: Variables and user variables
1.67 anton 5856: * Constants::
1.44 crook 5857: * Values:: Initialised variables
1.67 anton 5858: * Colon Definitions::
1.44 crook 5859: * Anonymous Definitions:: Definitions without names
1.69 anton 5860: * Supplying names:: Passing definition names as strings
1.67 anton 5861: * User-defined Defining Words::
1.44 crook 5862: * Deferred words:: Allow forward references
1.67 anton 5863: * Aliases::
1.29 crook 5864: @end menu
5865:
1.44 crook 5866: @node CREATE, Variables, Defining Words, Defining Words
5867: @subsection @code{CREATE}
1.29 crook 5868: @cindex simple defining words
5869: @cindex defining words, simple
5870:
5871: Defining words are used to create new entries in the dictionary. The
5872: simplest defining word is @code{CREATE}. @code{CREATE} is used like
5873: this:
5874:
5875: @example
5876: CREATE new-word1
5877: @end example
5878:
1.69 anton 5879: @code{CREATE} is a parsing word, i.e., it takes an argument from the
5880: input stream (@code{new-word1} in our example). It generates a
5881: dictionary entry for @code{new-word1}. When @code{new-word1} is
5882: executed, all that it does is leave an address on the stack. The address
5883: represents the value of the data space pointer (@code{HERE}) at the time
5884: that @code{new-word1} was defined. Therefore, @code{CREATE} is a way of
5885: associating a name with the address of a region of memory.
1.29 crook 5886:
1.34 anton 5887: doc-create
5888:
1.69 anton 5889: Note that in ANS Forth guarantees only for @code{create} that its body
5890: is in dictionary data space (i.e., where @code{here}, @code{allot}
5891: etc. work, @pxref{Dictionary allocation}). Also, in ANS Forth only
5892: @code{create}d words can be modified with @code{does>}
5893: (@pxref{User-defined Defining Words}). And in ANS Forth @code{>body}
5894: can only be applied to @code{create}d words.
5895:
1.29 crook 5896: By extending this example to reserve some memory in data space, we end
1.69 anton 5897: up with something like a @i{variable}. Here are two different ways to do
5898: it:
1.29 crook 5899:
5900: @example
5901: CREATE new-word2 1 cells allot \ reserve 1 cell - initial value undefined
5902: CREATE new-word3 4 , \ reserve 1 cell and initialise it (to 4)
5903: @end example
5904:
5905: The variable can be examined and modified using @code{@@} (``fetch'') and
5906: @code{!} (``store'') like this:
5907:
5908: @example
5909: new-word2 @@ . \ get address, fetch from it and display
5910: 1234 new-word2 ! \ new value, get address, store to it
5911: @end example
5912:
1.44 crook 5913: @cindex arrays
5914: A similar mechanism can be used to create arrays. For example, an
5915: 80-character text input buffer:
1.29 crook 5916:
5917: @example
1.44 crook 5918: CREATE text-buf 80 chars allot
5919:
5920: text-buf 0 chars c@@ \ the 1st character (offset 0)
5921: text-buf 3 chars c@@ \ the 4th character (offset 3)
5922: @end example
1.29 crook 5923:
1.44 crook 5924: You can build arbitrarily complex data structures by allocating
1.49 anton 5925: appropriate areas of memory. For further discussions of this, and to
1.66 anton 5926: learn about some Gforth tools that make it easier,
1.49 anton 5927: @xref{Structures}.
1.44 crook 5928:
5929:
5930: @node Variables, Constants, CREATE, Defining Words
5931: @subsection Variables
5932: @cindex variables
5933:
5934: The previous section showed how a sequence of commands could be used to
5935: generate a variable. As a final refinement, the whole code sequence can
5936: be wrapped up in a defining word (pre-empting the subject of the next
5937: section), making it easier to create new variables:
5938:
5939: @example
5940: : myvariableX ( "name" -- a-addr ) CREATE 1 cells allot ;
5941: : myvariable0 ( "name" -- a-addr ) CREATE 0 , ;
5942:
5943: myvariableX foo \ variable foo starts off with an unknown value
5944: myvariable0 joe \ whilst joe is initialised to 0
1.29 crook 5945:
5946: 45 3 * foo ! \ set foo to 135
5947: 1234 joe ! \ set joe to 1234
5948: 3 joe +! \ increment joe by 3.. to 1237
5949: @end example
5950:
5951: Not surprisingly, there is no need to define @code{myvariable}, since
1.44 crook 5952: Forth already has a definition @code{Variable}. ANS Forth does not
1.69 anton 5953: guarantee that a @code{Variable} is initialised when it is created
5954: (i.e., it may behave like @code{myvariableX}). In contrast, Gforth's
5955: @code{Variable} initialises the variable to 0 (i.e., it behaves exactly
5956: like @code{myvariable0}). Forth also provides @code{2Variable} and
1.47 crook 5957: @code{fvariable} for double and floating-point variables, respectively
1.69 anton 5958: -- they are initialised to 0. and 0e in Gforth. If you use a @code{Variable} to
1.47 crook 5959: store a boolean, you can use @code{on} and @code{off} to toggle its
5960: state.
1.29 crook 5961:
1.34 anton 5962: doc-variable
5963: doc-2variable
5964: doc-fvariable
5965:
1.29 crook 5966: @cindex user variables
5967: @cindex user space
5968: The defining word @code{User} behaves in the same way as @code{Variable}.
5969: The difference is that it reserves space in @i{user (data) space} rather
5970: than normal data space. In a Forth system that has a multi-tasker, each
5971: task has its own set of user variables.
5972:
1.34 anton 5973: doc-user
1.67 anton 5974: @c doc-udp
5975: @c doc-uallot
1.34 anton 5976:
1.29 crook 5977: @comment TODO is that stuff about user variables strictly correct? Is it
5978: @comment just terminal tasks that have user variables?
5979: @comment should document tasker.fs (with some examples) elsewhere
5980: @comment in this manual, then expand on user space and user variables.
5981:
1.44 crook 5982: @node Constants, Values, Variables, Defining Words
5983: @subsection Constants
5984: @cindex constants
5985:
5986: @code{Constant} allows you to declare a fixed value and refer to it by
5987: name. For example:
1.29 crook 5988:
5989: @example
5990: 12 Constant INCHES-PER-FOOT
5991: 3E+08 fconstant SPEED-O-LIGHT
5992: @end example
5993:
5994: A @code{Variable} can be both read and written, so its run-time
5995: behaviour is to supply an address through which its current value can be
5996: manipulated. In contrast, the value of a @code{Constant} cannot be
5997: changed once it has been declared@footnote{Well, often it can be -- but
5998: not in a Standard, portable way. It's safer to use a @code{Value} (read
5999: on).} so it's not necessary to supply the address -- it is more
6000: efficient to return the value of the constant directly. That's exactly
6001: what happens; the run-time effect of a constant is to put its value on
1.49 anton 6002: the top of the stack (You can find one
6003: way of implementing @code{Constant} in @ref{User-defined Defining Words}).
1.29 crook 6004:
1.69 anton 6005: Forth also provides @code{2Constant} and @code{fconstant} for defining
1.29 crook 6006: double and floating-point constants, respectively.
6007:
1.34 anton 6008: doc-constant
6009: doc-2constant
6010: doc-fconstant
6011:
6012: @c that's too deep, and it's not necessarily true for all ANS Forths. - anton
1.44 crook 6013: @c nac-> How could that not be true in an ANS Forth? You can't define a
6014: @c constant, use it and then delete the definition of the constant..
1.69 anton 6015:
6016: @c anton->An ANS Forth system can compile a constant to a literal; On
6017: @c decompilation you would see only the number, just as if it had been used
6018: @c in the first place. The word will stay, of course, but it will only be
6019: @c used by the text interpreter (no run-time duties, except when it is
6020: @c POSTPONEd or somesuch).
6021:
6022: @c nac:
1.44 crook 6023: @c I agree that it's rather deep, but IMO it is an important difference
6024: @c relative to other programming languages.. often it's annoying: it
6025: @c certainly changes my programming style relative to C.
6026:
1.69 anton 6027: @c anton: In what way?
6028:
1.29 crook 6029: Constants in Forth behave differently from their equivalents in other
6030: programming languages. In other languages, a constant (such as an EQU in
6031: assembler or a #define in C) only exists at compile-time; in the
6032: executable program the constant has been translated into an absolute
6033: number and, unless you are using a symbolic debugger, it's impossible to
6034: know what abstract thing that number represents. In Forth a constant has
1.44 crook 6035: an entry in the header space and remains there after the code that uses
6036: it has been defined. In fact, it must remain in the dictionary since it
6037: has run-time duties to perform. For example:
1.29 crook 6038:
6039: @example
6040: 12 Constant INCHES-PER-FOOT
6041: : FEET-TO-INCHES ( n1 -- n2 ) INCHES-PER-FOOT * ;
6042: @end example
6043:
6044: @cindex in-lining of constants
6045: When @code{FEET-TO-INCHES} is executed, it will in turn execute the xt
6046: associated with the constant @code{INCHES-PER-FOOT}. If you use
6047: @code{see} to decompile the definition of @code{FEET-TO-INCHES}, you can
6048: see that it makes a call to @code{INCHES-PER-FOOT}. Some Forth compilers
6049: attempt to optimise constants by in-lining them where they are used. You
6050: can force Gforth to in-line a constant like this:
6051:
6052: @example
6053: : FEET-TO-INCHES ( n1 -- n2 ) [ INCHES-PER-FOOT ] LITERAL * ;
6054: @end example
6055:
6056: If you use @code{see} to decompile @i{this} version of
6057: @code{FEET-TO-INCHES}, you can see that @code{INCHES-PER-FOOT} is no
1.49 anton 6058: longer present. To understand how this works, read
6059: @ref{Interpret/Compile states}, and @ref{Literals}.
1.29 crook 6060:
6061: In-lining constants in this way might improve execution time
6062: fractionally, and can ensure that a constant is now only referenced at
6063: compile-time. However, the definition of the constant still remains in
6064: the dictionary. Some Forth compilers provide a mechanism for controlling
6065: a second dictionary for holding transient words such that this second
6066: dictionary can be deleted later in order to recover memory
6067: space. However, there is no standard way of doing this.
6068:
6069:
1.44 crook 6070: @node Values, Colon Definitions, Constants, Defining Words
6071: @subsection Values
6072: @cindex values
1.34 anton 6073:
1.69 anton 6074: A @code{Value} behaves like a @code{Constant}, but it can be changed.
6075: @code{TO} is a parsing word that changes a @code{Values}. In Gforth
6076: (not in ANS Forth) you can access (and change) a @code{value} also with
6077: @code{>body}.
6078:
6079: Here are some
6080: examples:
1.29 crook 6081:
6082: @example
1.69 anton 6083: 12 Value APPLES \ Define APPLES with an initial value of 12
6084: 34 TO APPLES \ Change the value of APPLES. TO is a parsing word
6085: 1 ' APPLES >body +! \ Increment APPLES. Non-standard usage.
6086: APPLES \ puts 35 on the top of the stack.
1.29 crook 6087: @end example
6088:
1.44 crook 6089: doc-value
6090: doc-to
1.29 crook 6091:
1.35 anton 6092:
1.69 anton 6093:
1.44 crook 6094: @node Colon Definitions, Anonymous Definitions, Values, Defining Words
6095: @subsection Colon Definitions
6096: @cindex colon definitions
1.35 anton 6097:
6098: @example
1.44 crook 6099: : name ( ... -- ... )
6100: word1 word2 word3 ;
1.29 crook 6101: @end example
6102:
1.44 crook 6103: @noindent
6104: Creates a word called @code{name} that, upon execution, executes
6105: @code{word1 word2 word3}. @code{name} is a @dfn{(colon) definition}.
1.29 crook 6106:
1.49 anton 6107: The explanation above is somewhat superficial. For simple examples of
6108: colon definitions see @ref{Your first definition}. For an in-depth
1.66 anton 6109: discussion of some of the issues involved, @xref{Interpretation and
1.49 anton 6110: Compilation Semantics}.
1.29 crook 6111:
1.44 crook 6112: doc-:
6113: doc-;
1.1 anton 6114:
1.34 anton 6115:
1.69 anton 6116: @node Anonymous Definitions, Supplying names, Colon Definitions, Defining Words
1.44 crook 6117: @subsection Anonymous Definitions
6118: @cindex colon definitions
6119: @cindex defining words without name
1.34 anton 6120:
1.44 crook 6121: Sometimes you want to define an @dfn{anonymous word}; a word without a
6122: name. You can do this with:
1.1 anton 6123:
1.44 crook 6124: doc-:noname
1.1 anton 6125:
1.44 crook 6126: This leaves the execution token for the word on the stack after the
6127: closing @code{;}. Here's an example in which a deferred word is
6128: initialised with an @code{xt} from an anonymous colon definition:
1.1 anton 6129:
1.29 crook 6130: @example
1.44 crook 6131: Defer deferred
6132: :noname ( ... -- ... )
6133: ... ;
6134: IS deferred
1.29 crook 6135: @end example
1.26 crook 6136:
1.44 crook 6137: @noindent
6138: Gforth provides an alternative way of doing this, using two separate
6139: words:
1.27 crook 6140:
1.44 crook 6141: doc-noname
6142: @cindex execution token of last defined word
6143: doc-lastxt
1.1 anton 6144:
1.44 crook 6145: @noindent
6146: The previous example can be rewritten using @code{noname} and
6147: @code{lastxt}:
1.1 anton 6148:
1.26 crook 6149: @example
1.44 crook 6150: Defer deferred
6151: noname : ( ... -- ... )
6152: ... ;
6153: lastxt IS deferred
1.26 crook 6154: @end example
1.1 anton 6155:
1.29 crook 6156: @noindent
1.44 crook 6157: @code{noname} works with any defining word, not just @code{:}.
6158:
6159: @code{lastxt} also works when the last word was not defined as
1.71 anton 6160: @code{noname}. It does not work for combined words, though. It also has
6161: the useful property that is is valid as soon as the header for a
6162: definition has been built. Thus:
1.44 crook 6163:
6164: @example
6165: lastxt . : foo [ lastxt . ] ; ' foo .
6166: @end example
1.1 anton 6167:
1.44 crook 6168: @noindent
6169: prints 3 numbers; the last two are the same.
1.26 crook 6170:
1.69 anton 6171: @node Supplying names, User-defined Defining Words, Anonymous Definitions, Defining Words
6172: @subsection Supplying the name of a defined word
6173: @cindex names for defined words
6174: @cindex defining words, name given in a string
6175:
6176: By default, a defining word takes the name for the defined word from the
6177: input stream. Sometimes you want to supply the name from a string. You
6178: can do this with:
6179:
6180: doc-nextname
6181:
6182: For example:
6183:
6184: @example
6185: s" foo" nextname create
6186: @end example
6187:
6188: @noindent
6189: is equivalent to:
6190:
6191: @example
6192: create foo
6193: @end example
6194:
6195: @noindent
6196: @code{nextname} works with any defining word.
6197:
1.1 anton 6198:
1.69 anton 6199: @node User-defined Defining Words, Deferred words, Supplying names, Defining Words
1.26 crook 6200: @subsection User-defined Defining Words
6201: @cindex user-defined defining words
6202: @cindex defining words, user-defined
1.1 anton 6203:
1.29 crook 6204: You can create a new defining word by wrapping defining-time code around
6205: an existing defining word and putting the sequence in a colon
1.69 anton 6206: definition.
6207:
6208: @c anton: This example is very complex and leads in a quite different
6209: @c direction from the CREATE-DOES> stuff that follows. It should probably
6210: @c be done elsewhere, or as a subsubsection of this subsection (or as a
6211: @c subsection of Defining Words)
6212:
6213: For example, suppose that you have a word @code{stats} that
1.29 crook 6214: gathers statistics about colon definitions given the @i{xt} of the
6215: definition, and you want every colon definition in your application to
6216: make a call to @code{stats}. You can define and use a new version of
6217: @code{:} like this:
6218:
6219: @example
6220: : stats ( xt -- ) DUP ." (Gathering statistics for " . ." )"
6221: ... ; \ other code
6222:
6223: : my: : lastxt postpone literal ['] stats compile, ;
6224:
6225: my: foo + - ;
6226: @end example
6227:
6228: When @code{foo} is defined using @code{my:} these steps occur:
6229:
6230: @itemize @bullet
6231: @item
6232: @code{my:} is executed.
6233: @item
6234: The @code{:} within the definition (the one between @code{my:} and
6235: @code{lastxt}) is executed, and does just what it always does; it parses
6236: the input stream for a name, builds a dictionary header for the name
6237: @code{foo} and switches @code{state} from interpret to compile.
6238: @item
6239: The word @code{lastxt} is executed. It puts the @i{xt} for the word that is
6240: being defined -- @code{foo} -- onto the stack.
6241: @item
6242: The code that was produced by @code{postpone literal} is executed; this
6243: causes the value on the stack to be compiled as a literal in the code
6244: area of @code{foo}.
6245: @item
6246: The code @code{['] stats} compiles a literal into the definition of
6247: @code{my:}. When @code{compile,} is executed, that literal -- the
6248: execution token for @code{stats} -- is layed down in the code area of
6249: @code{foo} , following the literal@footnote{Strictly speaking, the
6250: mechanism that @code{compile,} uses to convert an @i{xt} into something
6251: in the code area is implementation-dependent. A threaded implementation
6252: might spit out the execution token directly whilst another
6253: implementation might spit out a native code sequence.}.
6254: @item
6255: At this point, the execution of @code{my:} is complete, and control
6256: returns to the text interpreter. The text interpreter is in compile
6257: state, so subsequent text @code{+ -} is compiled into the definition of
6258: @code{foo} and the @code{;} terminates the definition as always.
6259: @end itemize
6260:
6261: You can use @code{see} to decompile a word that was defined using
6262: @code{my:} and see how it is different from a normal @code{:}
6263: definition. For example:
6264:
6265: @example
6266: : bar + - ; \ like foo but using : rather than my:
6267: see bar
6268: : bar
6269: + - ;
6270: see foo
6271: : foo
6272: 107645672 stats + - ;
6273:
6274: \ use ' stats . to show that 107645672 is the xt for stats
6275: @end example
6276:
6277: You can use techniques like this to make new defining words in terms of
6278: @i{any} existing defining word.
1.1 anton 6279:
6280:
1.29 crook 6281: @cindex defining defining words
1.26 crook 6282: @cindex @code{CREATE} ... @code{DOES>}
6283: If you want the words defined with your defining words to behave
6284: differently from words defined with standard defining words, you can
6285: write your defining word like this:
1.1 anton 6286:
6287: @example
1.26 crook 6288: : def-word ( "name" -- )
1.29 crook 6289: CREATE @i{code1}
1.26 crook 6290: DOES> ( ... -- ... )
1.29 crook 6291: @i{code2} ;
1.26 crook 6292:
6293: def-word name
1.1 anton 6294: @end example
6295:
1.29 crook 6296: @cindex child words
6297: This fragment defines a @dfn{defining word} @code{def-word} and then
6298: executes it. When @code{def-word} executes, it @code{CREATE}s a new
6299: word, @code{name}, and executes the code @i{code1}. The code @i{code2}
6300: is not executed at this time. The word @code{name} is sometimes called a
6301: @dfn{child} of @code{def-word}.
6302:
6303: When you execute @code{name}, the address of the body of @code{name} is
6304: put on the data stack and @i{code2} is executed (the address of the body
6305: of @code{name} is the address @code{HERE} returns immediately after the
1.69 anton 6306: @code{CREATE}, i.e., the address a @code{create}d word returns by
6307: default).
6308:
6309: @c anton:
6310: @c www.dictionary.com says:
6311: @c at·a·vism: 1.The reappearance of a characteristic in an organism after
6312: @c several generations of absence, usually caused by the chance
6313: @c recombination of genes. 2.An individual or a part that exhibits
6314: @c atavism. Also called throwback. 3.The return of a trait or recurrence
6315: @c of previous behavior after a period of absence.
6316: @c
6317: @c Doesn't seem to fit.
1.29 crook 6318:
1.69 anton 6319: @c @cindex atavism in child words
1.33 anton 6320: You can use @code{def-word} to define a set of child words that behave
1.69 anton 6321: similarly; they all have a common run-time behaviour determined by
6322: @i{code2}. Typically, the @i{code1} sequence builds a data area in the
6323: body of the child word. The structure of the data is common to all
6324: children of @code{def-word}, but the data values are specific -- and
6325: private -- to each child word. When a child word is executed, the
6326: address of its private data area is passed as a parameter on TOS to be
6327: used and manipulated@footnote{It is legitimate both to read and write to
6328: this data area.} by @i{code2}.
1.29 crook 6329:
6330: The two fragments of code that make up the defining words act (are
6331: executed) at two completely separate times:
1.1 anton 6332:
1.29 crook 6333: @itemize @bullet
6334: @item
6335: At @i{define time}, the defining word executes @i{code1} to generate a
6336: child word
6337: @item
6338: At @i{child execution time}, when a child word is invoked, @i{code2}
6339: is executed, using parameters (data) that are private and specific to
6340: the child word.
6341: @end itemize
6342:
1.44 crook 6343: Another way of understanding the behaviour of @code{def-word} and
6344: @code{name} is to say that, if you make the following definitions:
1.33 anton 6345: @example
6346: : def-word1 ( "name" -- )
6347: CREATE @i{code1} ;
6348:
6349: : action1 ( ... -- ... )
6350: @i{code2} ;
6351:
6352: def-word1 name1
6353: @end example
6354:
1.44 crook 6355: @noindent
6356: Then using @code{name1 action1} is equivalent to using @code{name}.
1.1 anton 6357:
1.29 crook 6358: The classic example is that you can define @code{CONSTANT} in this way:
1.26 crook 6359:
1.1 anton 6360: @example
1.29 crook 6361: : CONSTANT ( w "name" -- )
6362: CREATE ,
1.26 crook 6363: DOES> ( -- w )
6364: @@ ;
1.1 anton 6365: @end example
6366:
1.29 crook 6367: @comment There is a beautiful description of how this works and what
6368: @comment it does in the Forthwrite 100th edition.. as well as an elegant
6369: @comment commentary on the Counting Fruits problem.
6370:
6371: When you create a constant with @code{5 CONSTANT five}, a set of
6372: define-time actions take place; first a new word @code{five} is created,
6373: then the value 5 is laid down in the body of @code{five} with
1.44 crook 6374: @code{,}. When @code{five} is executed, the address of the body is put on
1.29 crook 6375: the stack, and @code{@@} retrieves the value 5. The word @code{five} has
6376: no code of its own; it simply contains a data field and a pointer to the
6377: code that follows @code{DOES>} in its defining word. That makes words
6378: created in this way very compact.
6379:
6380: The final example in this section is intended to remind you that space
6381: reserved in @code{CREATE}d words is @i{data} space and therefore can be
6382: both read and written by a Standard program@footnote{Exercise: use this
6383: example as a starting point for your own implementation of @code{Value}
6384: and @code{TO} -- if you get stuck, investigate the behaviour of @code{'} and
6385: @code{[']}.}:
6386:
6387: @example
6388: : foo ( "name" -- )
6389: CREATE -1 ,
6390: DOES> ( -- )
1.33 anton 6391: @@ . ;
1.29 crook 6392:
6393: foo first-word
6394: foo second-word
6395:
6396: 123 ' first-word >BODY !
6397: @end example
6398:
6399: If @code{first-word} had been a @code{CREATE}d word, we could simply
6400: have executed it to get the address of its data field. However, since it
6401: was defined to have @code{DOES>} actions, its execution semantics are to
6402: perform those @code{DOES>} actions. To get the address of its data field
6403: it's necessary to use @code{'} to get its xt, then @code{>BODY} to
6404: translate the xt into the address of the data field. When you execute
6405: @code{first-word}, it will display @code{123}. When you execute
6406: @code{second-word} it will display @code{-1}.
1.26 crook 6407:
6408: @cindex stack effect of @code{DOES>}-parts
6409: @cindex @code{DOES>}-parts, stack effect
1.29 crook 6410: In the examples above the stack comment after the @code{DOES>} specifies
1.26 crook 6411: the stack effect of the defined words, not the stack effect of the
6412: following code (the following code expects the address of the body on
6413: the top of stack, which is not reflected in the stack comment). This is
6414: the convention that I use and recommend (it clashes a bit with using
6415: locals declarations for stack effect specification, though).
1.1 anton 6416:
1.53 anton 6417: @menu
6418: * CREATE..DOES> applications::
6419: * CREATE..DOES> details::
1.63 anton 6420: * Advanced does> usage example::
1.53 anton 6421: @end menu
6422:
6423: @node CREATE..DOES> applications, CREATE..DOES> details, User-defined Defining Words, User-defined Defining Words
1.26 crook 6424: @subsubsection Applications of @code{CREATE..DOES>}
6425: @cindex @code{CREATE} ... @code{DOES>}, applications
1.1 anton 6426:
1.26 crook 6427: You may wonder how to use this feature. Here are some usage patterns:
1.1 anton 6428:
1.26 crook 6429: @cindex factoring similar colon definitions
6430: When you see a sequence of code occurring several times, and you can
6431: identify a meaning, you will factor it out as a colon definition. When
6432: you see similar colon definitions, you can factor them using
6433: @code{CREATE..DOES>}. E.g., an assembler usually defines several words
6434: that look very similar:
1.1 anton 6435: @example
1.26 crook 6436: : ori, ( reg-target reg-source n -- )
6437: 0 asm-reg-reg-imm ;
6438: : andi, ( reg-target reg-source n -- )
6439: 1 asm-reg-reg-imm ;
1.1 anton 6440: @end example
6441:
1.26 crook 6442: @noindent
6443: This could be factored with:
6444: @example
6445: : reg-reg-imm ( op-code -- )
6446: CREATE ,
6447: DOES> ( reg-target reg-source n -- )
6448: @@ asm-reg-reg-imm ;
6449:
6450: 0 reg-reg-imm ori,
6451: 1 reg-reg-imm andi,
6452: @end example
1.1 anton 6453:
1.26 crook 6454: @cindex currying
6455: Another view of @code{CREATE..DOES>} is to consider it as a crude way to
6456: supply a part of the parameters for a word (known as @dfn{currying} in
6457: the functional language community). E.g., @code{+} needs two
6458: parameters. Creating versions of @code{+} with one parameter fixed can
6459: be done like this:
1.82 ! anton 6460:
1.1 anton 6461: @example
1.82 ! anton 6462: : curry+ ( n1 "name" -- )
1.26 crook 6463: CREATE ,
6464: DOES> ( n2 -- n1+n2 )
6465: @@ + ;
6466:
6467: 3 curry+ 3+
6468: -2 curry+ 2-
1.1 anton 6469: @end example
6470:
1.63 anton 6471: @node CREATE..DOES> details, Advanced does> usage example, CREATE..DOES> applications, User-defined Defining Words
1.26 crook 6472: @subsubsection The gory details of @code{CREATE..DOES>}
6473: @cindex @code{CREATE} ... @code{DOES>}, details
1.1 anton 6474:
1.26 crook 6475: doc-does>
1.1 anton 6476:
1.26 crook 6477: @cindex @code{DOES>} in a separate definition
6478: This means that you need not use @code{CREATE} and @code{DOES>} in the
6479: same definition; you can put the @code{DOES>}-part in a separate
1.29 crook 6480: definition. This allows us to, e.g., select among different @code{DOES>}-parts:
1.26 crook 6481: @example
6482: : does1
6483: DOES> ( ... -- ... )
1.44 crook 6484: ... ;
6485:
6486: : does2
6487: DOES> ( ... -- ... )
6488: ... ;
6489:
6490: : def-word ( ... -- ... )
6491: create ...
6492: IF
6493: does1
6494: ELSE
6495: does2
6496: ENDIF ;
6497: @end example
6498:
6499: In this example, the selection of whether to use @code{does1} or
1.69 anton 6500: @code{does2} is made at definition-time; at the time that the child word is
1.44 crook 6501: @code{CREATE}d.
6502:
6503: @cindex @code{DOES>} in interpretation state
6504: In a standard program you can apply a @code{DOES>}-part only if the last
6505: word was defined with @code{CREATE}. In Gforth, the @code{DOES>}-part
6506: will override the behaviour of the last word defined in any case. In a
6507: standard program, you can use @code{DOES>} only in a colon
6508: definition. In Gforth, you can also use it in interpretation state, in a
6509: kind of one-shot mode; for example:
6510: @example
6511: CREATE name ( ... -- ... )
6512: @i{initialization}
6513: DOES>
6514: @i{code} ;
6515: @end example
6516:
6517: @noindent
6518: is equivalent to the standard:
6519: @example
6520: :noname
6521: DOES>
6522: @i{code} ;
6523: CREATE name EXECUTE ( ... -- ... )
6524: @i{initialization}
6525: @end example
6526:
1.53 anton 6527: doc->body
6528:
1.63 anton 6529: @node Advanced does> usage example, , CREATE..DOES> details, User-defined Defining Words
6530: @subsubsection Advanced does> usage example
6531:
6532: The MIPS disassembler (@file{arch/mips/disasm.fs}) contains many words
6533: for disassembling instructions, that follow a very repetetive scheme:
6534:
6535: @example
6536: :noname @var{disasm-operands} s" @var{inst-name}" type ;
6537: @var{entry-num} cells @var{table} + !
6538: @end example
6539:
6540: Of course, this inspires the idea to factor out the commonalities to
6541: allow a definition like
6542:
6543: @example
6544: @var{disasm-operands} @var{entry-num} @var{table} define-inst @var{inst-name}
6545: @end example
6546:
6547: The parameters @var{disasm-operands} and @var{table} are usually
1.69 anton 6548: correlated. Moreover, before I wrote the disassembler, there already
6549: existed code that defines instructions like this:
1.63 anton 6550:
6551: @example
6552: @var{entry-num} @var{inst-format} @var{inst-name}
6553: @end example
6554:
6555: This code comes from the assembler and resides in
6556: @file{arch/mips/insts.fs}.
6557:
6558: So I had to define the @var{inst-format} words that performed the scheme
6559: above when executed. At first I chose to use run-time code-generation:
6560:
6561: @example
6562: : @var{inst-format} ( entry-num "name" -- ; compiled code: addr w -- )
6563: :noname Postpone @var{disasm-operands}
6564: name Postpone sliteral Postpone type Postpone ;
6565: swap cells @var{table} + ! ;
6566: @end example
6567:
6568: Note that this supplies the other two parameters of the scheme above.
1.44 crook 6569:
1.63 anton 6570: An alternative would have been to write this using
6571: @code{create}/@code{does>}:
6572:
6573: @example
6574: : @var{inst-format} ( entry-num "name" -- )
6575: here name string, ( entry-num c-addr ) \ parse and save "name"
6576: noname create , ( entry-num )
6577: lastxt swap cells @var{table} + !
6578: does> ( addr w -- )
6579: \ disassemble instruction w at addr
6580: @@ >r
6581: @var{disasm-operands}
6582: r> count type ;
6583: @end example
6584:
6585: Somehow the first solution is simpler, mainly because it's simpler to
6586: shift a string from definition-time to use-time with @code{sliteral}
6587: than with @code{string,} and friends.
6588:
6589: I wrote a lot of words following this scheme and soon thought about
6590: factoring out the commonalities among them. Note that this uses a
6591: two-level defining word, i.e., a word that defines ordinary defining
6592: words.
6593:
6594: This time a solution involving @code{postpone} and friends seemed more
6595: difficult (try it as an exercise), so I decided to use a
6596: @code{create}/@code{does>} word; since I was already at it, I also used
6597: @code{create}/@code{does>} for the lower level (try using
6598: @code{postpone} etc. as an exercise), resulting in the following
6599: definition:
6600:
6601: @example
6602: : define-format ( disasm-xt table-xt -- )
6603: \ define an instruction format that uses disasm-xt for
6604: \ disassembling and enters the defined instructions into table
6605: \ table-xt
6606: create 2,
6607: does> ( u "inst" -- )
6608: \ defines an anonymous word for disassembling instruction inst,
6609: \ and enters it as u-th entry into table-xt
6610: 2@@ swap here name string, ( u table-xt disasm-xt c-addr ) \ remember string
6611: noname create 2, \ define anonymous word
6612: execute lastxt swap ! \ enter xt of defined word into table-xt
6613: does> ( addr w -- )
6614: \ disassemble instruction w at addr
6615: 2@@ >r ( addr w disasm-xt R: c-addr )
6616: execute ( R: c-addr ) \ disassemble operands
6617: r> count type ; \ print name
6618: @end example
6619:
6620: Note that the tables here (in contrast to above) do the @code{cells +}
6621: by themselves (that's why you have to pass an xt). This word is used in
6622: the following way:
6623:
6624: @example
6625: ' @var{disasm-operands} ' @var{table} define-format @var{inst-format}
6626: @end example
6627:
1.71 anton 6628: As shown above, the defined instruction format is then used like this:
6629:
6630: @example
6631: @var{entry-num} @var{inst-format} @var{inst-name}
6632: @end example
6633:
1.63 anton 6634: In terms of currying, this kind of two-level defining word provides the
6635: parameters in three stages: first @var{disasm-operands} and @var{table},
6636: then @var{entry-num} and @var{inst-name}, finally @code{addr w}, i.e.,
6637: the instruction to be disassembled.
6638:
6639: Of course this did not quite fit all the instruction format names used
6640: in @file{insts.fs}, so I had to define a few wrappers that conditioned
6641: the parameters into the right form.
6642:
6643: If you have trouble following this section, don't worry. First, this is
6644: involved and takes time (and probably some playing around) to
6645: understand; second, this is the first two-level
6646: @code{create}/@code{does>} word I have written in seventeen years of
6647: Forth; and if I did not have @file{insts.fs} to start with, I may well
6648: have elected to use just a one-level defining word (with some repeating
6649: of parameters when using the defining word). So it is not necessary to
6650: understand this, but it may improve your understanding of Forth.
1.44 crook 6651:
6652:
6653: @node Deferred words, Aliases, User-defined Defining Words, Defining Words
6654: @subsection Deferred words
6655: @cindex deferred words
6656:
6657: The defining word @code{Defer} allows you to define a word by name
6658: without defining its behaviour; the definition of its behaviour is
6659: deferred. Here are two situation where this can be useful:
6660:
6661: @itemize @bullet
6662: @item
6663: Where you want to allow the behaviour of a word to be altered later, and
6664: for all precompiled references to the word to change when its behaviour
6665: is changed.
6666: @item
6667: For mutual recursion; @xref{Calls and returns}.
6668: @end itemize
6669:
6670: In the following example, @code{foo} always invokes the version of
6671: @code{greet} that prints ``@code{Good morning}'' whilst @code{bar}
6672: always invokes the version that prints ``@code{Hello}''. There is no way
6673: of getting @code{foo} to use the later version without re-ordering the
6674: source code and recompiling it.
6675:
6676: @example
6677: : greet ." Good morning" ;
6678: : foo ... greet ... ;
6679: : greet ." Hello" ;
6680: : bar ... greet ... ;
6681: @end example
6682:
6683: This problem can be solved by defining @code{greet} as a @code{Defer}red
6684: word. The behaviour of a @code{Defer}red word can be defined and
6685: redefined at any time by using @code{IS} to associate the xt of a
6686: previously-defined word with it. The previous example becomes:
6687:
6688: @example
1.69 anton 6689: Defer greet ( -- )
1.44 crook 6690: : foo ... greet ... ;
6691: : bar ... greet ... ;
1.69 anton 6692: : greet1 ( -- ) ." Good morning" ;
6693: : greet2 ( -- ) ." Hello" ;
1.44 crook 6694: ' greet2 <IS> greet \ make greet behave like greet2
6695: @end example
6696:
1.69 anton 6697: @progstyle
6698: You should write a stack comment for every deferred word, and put only
6699: XTs into deferred words that conform to this stack effect. Otherwise
6700: it's too difficult to use the deferred word.
6701:
1.44 crook 6702: A deferred word can be used to improve the statistics-gathering example
6703: from @ref{User-defined Defining Words}; rather than edit the
6704: application's source code to change every @code{:} to a @code{my:}, do
6705: this:
6706:
6707: @example
6708: : real: : ; \ retain access to the original
6709: defer : \ redefine as a deferred word
1.69 anton 6710: ' my: <IS> : \ use special version of :
1.44 crook 6711: \
6712: \ load application here
6713: \
1.69 anton 6714: ' real: <IS> : \ go back to the original
1.44 crook 6715: @end example
6716:
6717:
6718: One thing to note is that @code{<IS>} consumes its name when it is
6719: executed. If you want to specify the name at compile time, use
6720: @code{[IS]}:
6721:
6722: @example
6723: : set-greet ( xt -- )
6724: [IS] greet ;
6725:
6726: ' greet1 set-greet
6727: @end example
6728:
1.69 anton 6729: A deferred word can only inherit execution semantics from the xt
6730: (because that is all that an xt can represent -- for more discussion of
6731: this @pxref{Tokens for Words}); by default it will have default
6732: interpretation and compilation semantics deriving from this execution
6733: semantics. However, you can change the interpretation and compilation
6734: semantics of the deferred word in the usual ways:
1.44 crook 6735:
6736: @example
6737: : bar .... ; compile-only
6738: Defer fred immediate
6739: Defer jim
6740:
6741: ' bar <IS> jim \ jim has default semantics
6742: ' bar <IS> fred \ fred is immediate
6743: @end example
6744:
6745: doc-defer
6746: doc-<is>
6747: doc-[is]
6748: doc-is
6749: @comment TODO document these: what's defers [is]
6750: doc-what's
6751: doc-defers
6752:
6753: @c Use @code{words-deferred} to see a list of deferred words.
6754:
6755: Definitions in ANS Forth for @code{defer}, @code{<is>} and @code{[is]}
6756: are provided in @file{compat/defer.fs}.
6757:
6758:
1.69 anton 6759: @node Aliases, , Deferred words, Defining Words
1.44 crook 6760: @subsection Aliases
6761: @cindex aliases
1.1 anton 6762:
1.44 crook 6763: The defining word @code{Alias} allows you to define a word by name that
6764: has the same behaviour as some other word. Here are two situation where
6765: this can be useful:
1.1 anton 6766:
1.44 crook 6767: @itemize @bullet
6768: @item
6769: When you want access to a word's definition from a different word list
6770: (for an example of this, see the definition of the @code{Root} word list
6771: in the Gforth source).
6772: @item
6773: When you want to create a synonym; a definition that can be known by
6774: either of two names (for example, @code{THEN} and @code{ENDIF} are
6775: aliases).
6776: @end itemize
1.1 anton 6777:
1.69 anton 6778: Like deferred words, an alias has default compilation and interpretation
6779: semantics at the beginning (not the modifications of the other word),
6780: but you can change them in the usual ways (@code{immediate},
6781: @code{compile-only}). For example:
1.1 anton 6782:
6783: @example
1.44 crook 6784: : foo ... ; immediate
6785:
6786: ' foo Alias bar \ bar is not an immediate word
6787: ' foo Alias fooby immediate \ fooby is an immediate word
1.1 anton 6788: @end example
6789:
1.44 crook 6790: Words that are aliases have the same xt, different headers in the
6791: dictionary, and consequently different name tokens (@pxref{Tokens for
6792: Words}) and possibly different immediate flags. An alias can only have
6793: default or immediate compilation semantics; you can define aliases for
6794: combined words with @code{interpret/compile:} -- see @ref{Combined words}.
1.1 anton 6795:
1.44 crook 6796: doc-alias
1.1 anton 6797:
6798:
1.47 crook 6799: @node Interpretation and Compilation Semantics, Tokens for Words, Defining Words, Words
6800: @section Interpretation and Compilation Semantics
1.26 crook 6801: @cindex semantics, interpretation and compilation
1.1 anton 6802:
1.71 anton 6803: @c !! state and ' are used without explanation
6804: @c example for immediate/compile-only? or is the tutorial enough
6805:
1.26 crook 6806: @cindex interpretation semantics
1.71 anton 6807: The @dfn{interpretation semantics} of a (named) word are what the text
1.26 crook 6808: interpreter does when it encounters the word in interpret state. It also
6809: appears in some other contexts, e.g., the execution token returned by
1.71 anton 6810: @code{' @i{word}} identifies the interpretation semantics of @i{word}
6811: (in other words, @code{' @i{word} execute} is equivalent to
1.29 crook 6812: interpret-state text interpretation of @code{@i{word}}).
1.1 anton 6813:
1.26 crook 6814: @cindex compilation semantics
1.71 anton 6815: The @dfn{compilation semantics} of a (named) word are what the text
6816: interpreter does when it encounters the word in compile state. It also
6817: appears in other contexts, e.g, @code{POSTPONE @i{word}}
6818: compiles@footnote{In standard terminology, ``appends to the current
6819: definition''.} the compilation semantics of @i{word}.
1.1 anton 6820:
1.26 crook 6821: @cindex execution semantics
6822: The standard also talks about @dfn{execution semantics}. They are used
6823: only for defining the interpretation and compilation semantics of many
6824: words. By default, the interpretation semantics of a word are to
6825: @code{execute} its execution semantics, and the compilation semantics of
6826: a word are to @code{compile,} its execution semantics.@footnote{In
6827: standard terminology: The default interpretation semantics are its
6828: execution semantics; the default compilation semantics are to append its
6829: execution semantics to the execution semantics of the current
6830: definition.}
6831:
1.71 anton 6832: Unnamed words (@pxref{Anonymous Definitions}) cannot be encountered by
6833: the text interpreter, ticked, or @code{postpone}d, so they have no
6834: interpretation or compilation semantics. Their behaviour is represented
6835: by their XT (@pxref{Tokens for Words}), and we call it execution
6836: semantics, too.
6837:
1.26 crook 6838: @comment TODO expand, make it co-operate with new sections on text interpreter.
6839:
6840: @cindex immediate words
6841: @cindex compile-only words
6842: You can change the semantics of the most-recently defined word:
6843:
1.44 crook 6844:
1.26 crook 6845: doc-immediate
6846: doc-compile-only
6847: doc-restrict
6848:
1.82 ! anton 6849: By convention, words with non-default compilation semantics (e.g.,
! 6850: immediate words) often have names surrounded with brackets (e.g.,
! 6851: @code{[']}, @pxref{Execution token}).
1.44 crook 6852:
1.26 crook 6853: Note that ticking (@code{'}) a compile-only word gives an error
6854: (``Interpreting a compile-only word'').
1.1 anton 6855:
1.47 crook 6856: @menu
1.67 anton 6857: * Combined words::
1.47 crook 6858: @end menu
1.44 crook 6859:
1.71 anton 6860:
1.48 anton 6861: @node Combined words, , Interpretation and Compilation Semantics, Interpretation and Compilation Semantics
1.44 crook 6862: @subsection Combined Words
6863: @cindex combined words
6864:
6865: Gforth allows you to define @dfn{combined words} -- words that have an
6866: arbitrary combination of interpretation and compilation semantics.
6867:
1.26 crook 6868: doc-interpret/compile:
1.1 anton 6869:
1.26 crook 6870: This feature was introduced for implementing @code{TO} and @code{S"}. I
6871: recommend that you do not define such words, as cute as they may be:
6872: they make it hard to get at both parts of the word in some contexts.
6873: E.g., assume you want to get an execution token for the compilation
6874: part. Instead, define two words, one that embodies the interpretation
6875: part, and one that embodies the compilation part. Once you have done
6876: that, you can define a combined word with @code{interpret/compile:} for
6877: the convenience of your users.
1.1 anton 6878:
1.26 crook 6879: You might try to use this feature to provide an optimizing
6880: implementation of the default compilation semantics of a word. For
6881: example, by defining:
1.1 anton 6882: @example
1.26 crook 6883: :noname
6884: foo bar ;
6885: :noname
6886: POSTPONE foo POSTPONE bar ;
1.29 crook 6887: interpret/compile: opti-foobar
1.1 anton 6888: @end example
1.26 crook 6889:
1.23 crook 6890: @noindent
1.26 crook 6891: as an optimizing version of:
6892:
1.1 anton 6893: @example
1.26 crook 6894: : foobar
6895: foo bar ;
1.1 anton 6896: @end example
6897:
1.26 crook 6898: Unfortunately, this does not work correctly with @code{[compile]},
6899: because @code{[compile]} assumes that the compilation semantics of all
6900: @code{interpret/compile:} words are non-default. I.e., @code{[compile]
1.29 crook 6901: opti-foobar} would compile compilation semantics, whereas
6902: @code{[compile] foobar} would compile interpretation semantics.
1.1 anton 6903:
1.26 crook 6904: @cindex state-smart words (are a bad idea)
1.82 ! anton 6905: @anchor{state-smartness}
1.29 crook 6906: Some people try to use @dfn{state-smart} words to emulate the feature provided
1.26 crook 6907: by @code{interpret/compile:} (words are state-smart if they check
6908: @code{STATE} during execution). E.g., they would try to code
6909: @code{foobar} like this:
1.1 anton 6910:
1.26 crook 6911: @example
6912: : foobar
6913: STATE @@
6914: IF ( compilation state )
6915: POSTPONE foo POSTPONE bar
6916: ELSE
6917: foo bar
6918: ENDIF ; immediate
6919: @end example
1.1 anton 6920:
1.26 crook 6921: Although this works if @code{foobar} is only processed by the text
6922: interpreter, it does not work in other contexts (like @code{'} or
6923: @code{POSTPONE}). E.g., @code{' foobar} will produce an execution token
6924: for a state-smart word, not for the interpretation semantics of the
6925: original @code{foobar}; when you execute this execution token (directly
6926: with @code{EXECUTE} or indirectly through @code{COMPILE,}) in compile
6927: state, the result will not be what you expected (i.e., it will not
6928: perform @code{foo bar}). State-smart words are a bad idea. Simply don't
6929: write them@footnote{For a more detailed discussion of this topic, see
1.66 anton 6930: M. Anton Ertl,
6931: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,@code{State}-smartness---Why
6932: it is Evil and How to Exorcise it}}, EuroForth '98.}!
1.1 anton 6933:
1.26 crook 6934: @cindex defining words with arbitrary semantics combinations
6935: It is also possible to write defining words that define words with
6936: arbitrary combinations of interpretation and compilation semantics. In
6937: general, they look like this:
1.1 anton 6938:
1.26 crook 6939: @example
6940: : def-word
6941: create-interpret/compile
1.29 crook 6942: @i{code1}
1.26 crook 6943: interpretation>
1.29 crook 6944: @i{code2}
1.26 crook 6945: <interpretation
6946: compilation>
1.29 crook 6947: @i{code3}
1.26 crook 6948: <compilation ;
6949: @end example
1.1 anton 6950:
1.29 crook 6951: For a @i{word} defined with @code{def-word}, the interpretation
6952: semantics are to push the address of the body of @i{word} and perform
6953: @i{code2}, and the compilation semantics are to push the address of
6954: the body of @i{word} and perform @i{code3}. E.g., @code{constant}
1.26 crook 6955: can also be defined like this (except that the defined constants don't
6956: behave correctly when @code{[compile]}d):
1.1 anton 6957:
1.26 crook 6958: @example
6959: : constant ( n "name" -- )
6960: create-interpret/compile
6961: ,
6962: interpretation> ( -- n )
6963: @@
6964: <interpretation
6965: compilation> ( compilation. -- ; run-time. -- n )
6966: @@ postpone literal
6967: <compilation ;
6968: @end example
1.1 anton 6969:
1.44 crook 6970:
1.26 crook 6971: doc-create-interpret/compile
6972: doc-interpretation>
6973: doc-<interpretation
6974: doc-compilation>
6975: doc-<compilation
1.1 anton 6976:
1.44 crook 6977:
1.29 crook 6978: Words defined with @code{interpret/compile:} and
1.26 crook 6979: @code{create-interpret/compile} have an extended header structure that
6980: differs from other words; however, unless you try to access them with
6981: plain address arithmetic, you should not notice this. Words for
6982: accessing the header structure usually know how to deal with this; e.g.,
1.29 crook 6983: @code{'} @i{word} @code{>body} also gives you the body of a word created
6984: with @code{create-interpret/compile}.
1.1 anton 6985:
1.44 crook 6986:
1.47 crook 6987: @c -------------------------------------------------------------
1.81 anton 6988: @node Tokens for Words, Compiling words, Interpretation and Compilation Semantics, Words
1.47 crook 6989: @section Tokens for Words
6990: @cindex tokens for words
6991:
6992: This section describes the creation and use of tokens that represent
6993: words.
6994:
1.71 anton 6995: @menu
6996: * Execution token:: represents execution/interpretation semantics
6997: * Compilation token:: represents compilation semantics
6998: * Name token:: represents named words
6999: @end menu
1.47 crook 7000:
1.71 anton 7001: @node Execution token, Compilation token, Tokens for Words, Tokens for Words
7002: @subsection Execution token
1.47 crook 7003:
7004: @cindex xt
7005: @cindex execution token
1.71 anton 7006: An @dfn{execution token} (@i{XT}) represents some behaviour of a word.
7007: You can use @code{execute} to invoke this behaviour.
1.47 crook 7008:
1.71 anton 7009: @cindex tick (')
7010: You can use @code{'} to get an execution token that represents the
7011: interpretation semantics of a named word:
1.47 crook 7012:
7013: @example
1.71 anton 7014: 5 ' .
7015: execute
7016: @end example
1.47 crook 7017:
1.71 anton 7018: doc-'
7019:
7020: @code{'} parses at run-time; there is also a word @code{[']} that parses
7021: when it is compiled, and compiles the resulting XT:
7022:
7023: @example
7024: : foo ['] . execute ;
7025: 5 foo
7026: : bar ' execute ; \ by contrast,
7027: 5 bar . \ ' parses "." when bar executes
7028: @end example
7029:
7030: doc-[']
7031:
7032: If you want the execution token of @i{word}, write @code{['] @i{word}}
7033: in compiled code and @code{' @i{word}} in interpreted code. Gforth's
7034: @code{'} and @code{[']} behave somewhat unusually by complaining about
7035: compile-only words (because these words have no interpretation
7036: semantics). You might get what you want by using @code{COMP' @i{word}
7037: DROP} or @code{[COMP'] @i{word} DROP} (for details @pxref{Compilation
7038: token}).
7039:
7040: Another way to get an XT is @code{:noname} or @code{lastxt}
7041: (@pxref{Anonymous Definitions}). For anonymous words this gives an xt
7042: for the only behaviour the word has (the execution semantics). For
7043: named words, @code{lastxt} produces an XT for the same behaviour it
7044: would produce if the word was defined anonymously.
7045:
7046: @example
7047: :noname ." hello" ;
7048: execute
1.47 crook 7049: @end example
7050:
1.71 anton 7051: An XT occupies one cell and can be manipulated like any other cell.
7052:
1.47 crook 7053: @cindex code field address
7054: @cindex CFA
1.71 anton 7055: In ANS Forth the XT is just an abstract data type (i.e., defined by the
7056: operations that produce or consume it). For old hands: In Gforth, the
7057: XT is implemented as a code field address (CFA).
7058:
7059: doc-execute
7060: doc-perform
7061:
7062: @node Compilation token, Name token, Execution token, Tokens for Words
7063: @subsection Compilation token
1.47 crook 7064:
7065: @cindex compilation token
1.71 anton 7066: @cindex CT (compilation token)
7067: Gforth represents the compilation semantics of a named word by a
1.47 crook 7068: @dfn{compilation token} consisting of two cells: @i{w xt}. The top cell
7069: @i{xt} is an execution token. The compilation semantics represented by
7070: the compilation token can be performed with @code{execute}, which
7071: consumes the whole compilation token, with an additional stack effect
7072: determined by the represented compilation semantics.
7073:
7074: At present, the @i{w} part of a compilation token is an execution token,
7075: and the @i{xt} part represents either @code{execute} or
7076: @code{compile,}@footnote{Depending upon the compilation semantics of the
7077: word. If the word has default compilation semantics, the @i{xt} will
7078: represent @code{compile,}. Otherwise (e.g., for immediate words), the
7079: @i{xt} will represent @code{execute}.}. However, don't rely on that
7080: knowledge, unless necessary; future versions of Gforth may introduce
7081: unusual compilation tokens (e.g., a compilation token that represents
7082: the compilation semantics of a literal).
7083:
1.71 anton 7084: You can perform the compilation semantics represented by the compilation
7085: token with @code{execute}. You can compile the compilation semantics
7086: with @code{postpone,}. I.e., @code{COMP' @i{word} postpone,} is
7087: equivalent to @code{postpone @i{word}}.
7088:
7089: doc-[comp']
7090: doc-comp'
7091: doc-postpone,
7092:
7093: @node Name token, , Compilation token, Tokens for Words
7094: @subsection Name token
1.47 crook 7095:
7096: @cindex name token
7097: @cindex name field address
7098: @cindex NFA
1.71 anton 7099: Gforth represents named words by the @dfn{name token}, (@i{nt}). In
1.47 crook 7100: Gforth, the abstract data type @emph{name token} is implemented as a
7101: name field address (NFA).
7102:
7103: doc-find-name
7104: doc-name>int
7105: doc-name?int
7106: doc-name>comp
7107: doc-name>string
7108:
1.81 anton 7109: @c ----------------------------------------------------------
7110: @node Compiling words, The Text Interpreter, Tokens for Words, Words
7111: @section Compiling words
7112: @cindex compiling words
7113: @cindex macros
7114:
7115: In contrast to most other languages, Forth has no strict boundary
1.82 ! anton 7116: between compilation and run-time. E.g., you can run arbitrary code
! 7117: between defining words (or for computing data used by defining words
! 7118: like @code{constant}). Moreover, @code{Immediate} (@pxref{Interpretation
! 7119: and Compilation Semantics} and @code{[}...@code{]} (see below) allow
! 7120: running arbitrary code while compiling a colon definition (exception:
! 7121: you must not allot dictionary space).
! 7122:
! 7123: @menu
! 7124: * Literals:: Compiling data values
! 7125: * Macros:: Compiling words
! 7126: @end menu
! 7127:
! 7128: @node Literals, Macros, Compiling words, Compiling words
! 7129: @subsection Literals
! 7130: @cindex Literals
! 7131:
! 7132: The simplest and most frequent example is to compute a literal during
! 7133: compilation. E.g., the following definition prints an array of strings,
! 7134: one string per line:
! 7135:
! 7136: @example
! 7137: : .strings ( addr u -- ) \ gforth
! 7138: 2* cells bounds U+DO
! 7139: cr i 2@@ type
! 7140: 2 cells +LOOP ;
! 7141: @end example
1.81 anton 7142:
1.82 ! anton 7143: With a simple-minded compiler like Gforth's, this computes @code{2
! 7144: cells} on every loop iteration. You can compute this value once and for
! 7145: all at compile time and compile it into the definition like this:
! 7146:
! 7147: @example
! 7148: : .strings ( addr u -- ) \ gforth
! 7149: 2* cells bounds U+DO
! 7150: cr i 2@@ type
! 7151: [ 2 cells ] literal +LOOP ;
! 7152: @end example
! 7153:
! 7154: @code{[} switches the text interpreter to interpret state (you will get
! 7155: an @code{ok} prompt if you type this example interactively and insert a
! 7156: newline between @code{[} and @code{]}), so it performs the
! 7157: interpretation semantics of @code{2 cells}; this computes a number.
! 7158: @code{]} switches the text interpreter back into compile state. It then
! 7159: performs @code{Literal}'s compilation semantics, which are to compile
! 7160: this number into the current word. You can decompile the word with
! 7161: @code{see .strings} to see the effect on the compiled code.
1.81 anton 7162:
1.82 ! anton 7163: You can also optimize the @code{2* cells} into @code{[ 2 cells ] literal
! 7164: *} in this way.
1.81 anton 7165:
1.82 ! anton 7166: doc-[
! 7167: doc-]
1.81 anton 7168: doc-literal
7169: doc-]L
1.82 ! anton 7170:
! 7171: There are also words for compiling other data types than single cells as
! 7172: literals:
! 7173:
1.81 anton 7174: doc-2literal
7175: doc-fliteral
1.82 ! anton 7176: doc-sliteral
! 7177:
! 7178: @cindex colon-sys, passing data across @code{:}
! 7179: @cindex @code{:}, passing data across
! 7180: You might be tempted to pass data from outside a colon definition to the
! 7181: inside on the data stack. This does not work, because @code{:} puhes a
! 7182: colon-sys, making stuff below unaccessible. E.g., this does not work:
! 7183:
! 7184: @example
! 7185: 5 : foo literal ; \ error: "unstructured"
! 7186: @end example
! 7187:
! 7188: Instead, you have to pass the value in some other way, e.g., through a
! 7189: variable:
! 7190:
! 7191: @example
! 7192: variable temp
! 7193: 5 temp !
! 7194: : foo [ temp @@ ] literal ;
! 7195: @end example
! 7196:
! 7197:
! 7198: @node Macros, , Literals, Compiling words
! 7199: @subsection Macros
! 7200: @cindex Macros
! 7201: @cindex compiling compilation semantics
! 7202:
! 7203: @code{Literal} and friends compile data values into the current
! 7204: definition. You can also write words that compile other words into the
! 7205: current definition. E.g.,
! 7206:
! 7207: @example
! 7208: : compile-+ ( -- ) \ compiled code: ( n1 n2 -- n )
! 7209: POSTPONE + ;
! 7210:
! 7211: : foo ( n1 n2 -- n )
! 7212: [ compile-+ ] ;
! 7213: 1 2 foo .
! 7214: @end example
! 7215:
! 7216: This is equivalent to @code{: foo + ;} (@code{see foo} to check this).
! 7217: What happens in this example? @code{Postpone} compiles the compilation
! 7218: semantics of @code{+} into @code{compile-+}; later the text interpreter
! 7219: executes @code{compile-+} and thus the compilation semantics of +, which
! 7220: compile (the execution semantics of) @code{+} into
! 7221: @code{foo}.@footnote{A recent RFI answer requires that compiling words
! 7222: should only be executed in compile state, so this example is not
! 7223: guaranteed to work on all standard systems, but on any decent system it
! 7224: will work.}
! 7225:
! 7226: doc-postpone
! 7227: doc-[compile]
! 7228:
! 7229: Compiling words like @code{compile-+} are usually immediate (or similar)
! 7230: so you do not have to switch to interpret state to execute them;
! 7231: mopifying the last example accordingly produces:
! 7232:
! 7233: @example
! 7234: : [compile-+] ( compilation: --; interpretation: -- )
! 7235: \ compiled code: ( n1 n2 -- n )
! 7236: POSTPONE + ; immediate
! 7237:
! 7238: : foo ( n1 n2 -- n )
! 7239: [compile-+] ;
! 7240: 1 2 foo .
! 7241: @end example
! 7242:
! 7243: Immediate compiling words are similar to macros in other languages (in
! 7244: particular, Lisp). The important differences to macros in, e.g., C are:
! 7245:
! 7246: @itemize @bullet
! 7247:
! 7248: @item
! 7249: You use the same language for defining and processing macros, not a
! 7250: separate preprocessing language and processor.
! 7251:
! 7252: @item
! 7253: Consequently, the full power of Forth is available in macro definitions.
! 7254: E.g., you can perform arbitrarily complex computations, or generate
! 7255: different code conditionally or in a loop (e.g., @pxref{Advanced macros
! 7256: Tutorial}). This power is very useful when writing a parser generators
! 7257: or other code-generating software.
! 7258:
! 7259: @item
! 7260: Macros defined using @code{postpone} etc. deal with the language at a
! 7261: higher level than strings; name binding happens at macro definition
! 7262: time, so you can avoid the pitfalls of name collisions that can happen
! 7263: in C macros. Of course, Forth is a liberal language and also allows to
! 7264: shoot yourself in the foot with text-interpreted macros like
! 7265:
! 7266: @example
! 7267: : [compile-+] s" +" evaluate ; immediate
! 7268: @end example
! 7269:
! 7270: Apart from binding the name at macro use time, using @code{evaluate}
! 7271: also makes your definition @code{state}-smart (@pxref{state-smartness}).
! 7272: @end itemize
! 7273:
! 7274: You may want the macro to compile a number into a word. The word to do
! 7275: it is @code{literal}, but you have to @code{postpone} it, so its
! 7276: compilation semantics take effect when the macro is executed, not when
! 7277: it is compiled:
! 7278:
! 7279: @example
! 7280: : [compile-5] ( -- ) \ compiled code: ( -- n )
! 7281: 5 POSTPONE literal ; immediate
! 7282:
! 7283: : foo [compile-5] ;
! 7284: foo .
! 7285: @end example
! 7286:
! 7287: You may want to pass parameters to a macro, that the macro should
! 7288: compile into the current definition. If the parameter is a number, then
! 7289: you can use @code{postpone literal} (similar for other values).
! 7290:
! 7291: If you want to pass a word that is to be compiled, the usual way is to
! 7292: pass an execution token and @code{compile,} it:
! 7293:
! 7294: @example
! 7295: : twice1 ( xt -- ) \ compiled code: ... -- ...
! 7296: dup compile, compile, ;
! 7297:
! 7298: : 2+ ( n1 -- n2 )
! 7299: [ ' 1+ twice1 ] ;
! 7300: @end example
! 7301:
! 7302: doc-compile,
! 7303:
! 7304: An alternative available in Gforth, that allows you to pass compile-only
! 7305: words as parameters is to use the compilation token (@pxref{Compilation
! 7306: token}). The same example in this technique:
! 7307:
! 7308: @example
! 7309: : twice ( ... ct -- ... ) \ compiled code: ... -- ...
! 7310: 2dup 2>r execute 2r> execute ;
! 7311:
! 7312: : 2+ ( n1 -- n2 )
! 7313: [ comp' 1+ twice ] ;
! 7314: @end example
! 7315:
! 7316: In the example above @code{2>r} and @code{2r>} ensure that @code{twice}
! 7317: works even if the executed compilation semantics has an effect on the
! 7318: data stack.
! 7319:
! 7320: You can also define complete definitions with these words; this provides
! 7321: an alternative to using @code{does>} (@pxref{User-defined Defining
! 7322: Words}). E.g., instead of
! 7323:
! 7324: @example
! 7325: : curry+ ( n1 "name" -- )
! 7326: CREATE ,
! 7327: DOES> ( n2 -- n1+n2 )
! 7328: @@ + ;
! 7329: @end example
! 7330:
! 7331: you could define
! 7332:
! 7333: @example
! 7334: : curry+ ( n1 "name" -- )
! 7335: \ name execution: ( n2 -- n1+n2 )
! 7336: >r : r> POSTPONE literal POSTPONE + POSTPONE ; ;
1.81 anton 7337:
1.82 ! anton 7338: -3 curry+ 3-
! 7339: see 3-
! 7340: @end example
1.81 anton 7341:
1.82 ! anton 7342: The sequence @code{>r : r>} is necessary, because @code{:} puts a
! 7343: colon-sys on the data stack that makes everything below it unaccessible.
1.81 anton 7344:
1.82 ! anton 7345: This way of writing defining words is sometimes more, sometimes less
! 7346: convenient than using @code{does>} (@pxref{Advanced does> usage
! 7347: example}). One advantage of this method is that it can be optimized
! 7348: better, because the compiler knows that the value compiled with
! 7349: @code{literal} is fixed, whereas the data associated with a
! 7350: @code{create}d word can be changed.
1.47 crook 7351:
1.26 crook 7352: @c ----------------------------------------------------------
1.81 anton 7353: @node The Text Interpreter, Word Lists, Compiling words, Words
1.26 crook 7354: @section The Text Interpreter
7355: @cindex interpreter - outer
7356: @cindex text interpreter
7357: @cindex outer interpreter
1.1 anton 7358:
1.34 anton 7359: @c Should we really describe all these ugly details? IMO the text
7360: @c interpreter should be much cleaner, but that may not be possible within
7361: @c ANS Forth. - anton
1.44 crook 7362: @c nac-> I wanted to explain how it works to show how you can exploit
7363: @c it in your own programs. When I was writing a cross-compiler, figuring out
7364: @c some of these gory details was very helpful to me. None of the textbooks
7365: @c I've seen cover it, and the most modern Forth textbook -- Forth Inc's,
7366: @c seems to positively avoid going into too much detail for some of
7367: @c the internals.
1.34 anton 7368:
1.71 anton 7369: @c anton: ok. I wonder, though, if this is the right place; for some stuff
7370: @c it is; for the ugly details, I would prefer another place. I wonder
7371: @c whether we should have a chapter before "Words" that describes some
7372: @c basic concepts referred to in words, and a chapter after "Words" that
7373: @c describes implementation details.
7374:
1.29 crook 7375: The text interpreter@footnote{This is an expanded version of the
7376: material in @ref{Introducing the Text Interpreter}.} is an endless loop
1.34 anton 7377: that processes input from the current input device. It is also called
7378: the outer interpreter, in contrast to the inner interpreter
7379: (@pxref{Engine}) which executes the compiled Forth code on interpretive
7380: implementations.
1.27 crook 7381:
1.29 crook 7382: @cindex interpret state
7383: @cindex compile state
7384: The text interpreter operates in one of two states: @dfn{interpret
7385: state} and @dfn{compile state}. The current state is defined by the
1.71 anton 7386: aptly-named variable @code{state}.
1.29 crook 7387:
7388: This section starts by describing how the text interpreter behaves when
7389: it is in interpret state, processing input from the user input device --
7390: the keyboard. This is the mode that a Forth system is in after it starts
7391: up.
7392:
7393: @cindex input buffer
7394: @cindex terminal input buffer
7395: The text interpreter works from an area of memory called the @dfn{input
7396: buffer}@footnote{When the text interpreter is processing input from the
7397: keyboard, this area of memory is called the @dfn{terminal input buffer}
7398: (TIB) and is addressed by the (obsolescent) words @code{TIB} and
7399: @code{#TIB}.}, which stores your keyboard input when you press the
1.30 anton 7400: @key{RET} key. Starting at the beginning of the input buffer, it skips
1.29 crook 7401: leading spaces (called @dfn{delimiters}) then parses a string (a
7402: sequence of non-space characters) until it reaches either a space
7403: character or the end of the buffer. Having parsed a string, it makes two
7404: attempts to process it:
1.27 crook 7405:
1.29 crook 7406: @cindex dictionary
1.27 crook 7407: @itemize @bullet
7408: @item
1.29 crook 7409: It looks for the string in a @dfn{dictionary} of definitions. If the
7410: string is found, the string names a @dfn{definition} (also known as a
7411: @dfn{word}) and the dictionary search returns information that allows
7412: the text interpreter to perform the word's @dfn{interpretation
7413: semantics}. In most cases, this simply means that the word will be
7414: executed.
1.27 crook 7415: @item
7416: If the string is not found in the dictionary, the text interpreter
1.29 crook 7417: attempts to treat it as a number, using the rules described in
7418: @ref{Number Conversion}. If the string represents a legal number in the
7419: current radix, the number is pushed onto a parameter stack (the data
7420: stack for integers, the floating-point stack for floating-point
7421: numbers).
7422: @end itemize
7423:
7424: If both attempts fail, or if the word is found in the dictionary but has
7425: no interpretation semantics@footnote{This happens if the word was
7426: defined as @code{COMPILE-ONLY}.} the text interpreter discards the
7427: remainder of the input buffer, issues an error message and waits for
7428: more input. If one of the attempts succeeds, the text interpreter
7429: repeats the parsing process until the whole of the input buffer has been
7430: processed, at which point it prints the status message ``@code{ ok}''
7431: and waits for more input.
7432:
1.71 anton 7433: @c anton: this should be in the input stream subsection (or below it)
7434:
1.29 crook 7435: @cindex parse area
7436: The text interpreter keeps track of its position in the input buffer by
7437: updating a variable called @code{>IN} (pronounced ``to-in''). The value
7438: of @code{>IN} starts out as 0, indicating an offset of 0 from the start
7439: of the input buffer. The region from offset @code{>IN @@} to the end of
7440: the input buffer is called the @dfn{parse area}@footnote{In other words,
7441: the text interpreter processes the contents of the input buffer by
7442: parsing strings from the parse area until the parse area is empty.}.
7443: This example shows how @code{>IN} changes as the text interpreter parses
7444: the input buffer:
7445:
7446: @example
7447: : remaining >IN @@ SOURCE 2 PICK - -ROT + SWAP
7448: CR ." ->" TYPE ." <-" ; IMMEDIATE
7449:
7450: 1 2 3 remaining + remaining .
7451:
7452: : foo 1 2 3 remaining SWAP remaining ;
7453: @end example
7454:
7455: @noindent
7456: The result is:
7457:
7458: @example
7459: ->+ remaining .<-
7460: ->.<-5 ok
7461:
7462: ->SWAP remaining ;-<
7463: ->;<- ok
7464: @end example
7465:
7466: @cindex parsing words
7467: The value of @code{>IN} can also be modified by a word in the input
7468: buffer that is executed by the text interpreter. This means that a word
7469: can ``trick'' the text interpreter into either skipping a section of the
7470: input buffer@footnote{This is how parsing words work.} or into parsing a
7471: section twice. For example:
1.27 crook 7472:
1.29 crook 7473: @example
1.71 anton 7474: : lat ." <<foo>>" ;
7475: : flat ." <<bar>>" >IN DUP @@ 3 - SWAP ! ;
1.29 crook 7476: @end example
7477:
7478: @noindent
7479: When @code{flat} is executed, this output is produced@footnote{Exercise
7480: for the reader: what would happen if the @code{3} were replaced with
7481: @code{4}?}:
7482:
7483: @example
1.71 anton 7484: <<bar>><<foo>>
1.29 crook 7485: @end example
7486:
1.71 anton 7487: This technique can be used to work around some of the interoperability
7488: problems of parsing words. Of course, it's better to avoid parsing
7489: words where possible.
7490:
1.29 crook 7491: @noindent
7492: Two important notes about the behaviour of the text interpreter:
1.27 crook 7493:
7494: @itemize @bullet
7495: @item
7496: It processes each input string to completion before parsing additional
1.29 crook 7497: characters from the input buffer.
7498: @item
7499: It treats the input buffer as a read-only region (and so must your code).
7500: @end itemize
7501:
7502: @noindent
7503: When the text interpreter is in compile state, its behaviour changes in
7504: these ways:
7505:
7506: @itemize @bullet
7507: @item
7508: If a parsed string is found in the dictionary, the text interpreter will
7509: perform the word's @dfn{compilation semantics}. In most cases, this
7510: simply means that the execution semantics of the word will be appended
7511: to the current definition.
1.27 crook 7512: @item
1.29 crook 7513: When a number is encountered, it is compiled into the current definition
7514: (as a literal) rather than being pushed onto a parameter stack.
7515: @item
7516: If an error occurs, @code{state} is modified to put the text interpreter
7517: back into interpret state.
7518: @item
7519: Each time a line is entered from the keyboard, Gforth prints
7520: ``@code{ compiled}'' rather than `` @code{ok}''.
7521: @end itemize
7522:
7523: @cindex text interpreter - input sources
7524: When the text interpreter is using an input device other than the
7525: keyboard, its behaviour changes in these ways:
7526:
7527: @itemize @bullet
7528: @item
7529: When the parse area is empty, the text interpreter attempts to refill
7530: the input buffer from the input source. When the input source is
1.71 anton 7531: exhausted, the input source is set back to the previous input source.
1.29 crook 7532: @item
7533: It doesn't print out ``@code{ ok}'' or ``@code{ compiled}'' messages each
7534: time the parse area is emptied.
7535: @item
7536: If an error occurs, the input source is set back to the user input
7537: device.
1.27 crook 7538: @end itemize
1.21 crook 7539:
1.49 anton 7540: You can read about this in more detail in @ref{Input Sources}.
1.44 crook 7541:
1.26 crook 7542: doc->in
1.27 crook 7543: doc-source
7544:
1.26 crook 7545: doc-tib
7546: doc-#tib
1.1 anton 7547:
1.44 crook 7548:
1.26 crook 7549: @menu
1.67 anton 7550: * Input Sources::
7551: * Number Conversion::
7552: * Interpret/Compile states::
7553: * Interpreter Directives::
1.26 crook 7554: @end menu
1.1 anton 7555:
1.29 crook 7556: @node Input Sources, Number Conversion, The Text Interpreter, The Text Interpreter
7557: @subsection Input Sources
7558: @cindex input sources
7559: @cindex text interpreter - input sources
7560:
1.44 crook 7561: By default, the text interpreter processes input from the user input
1.29 crook 7562: device (the keyboard) when Forth starts up. The text interpreter can
7563: process input from any of these sources:
7564:
7565: @itemize @bullet
7566: @item
7567: The user input device -- the keyboard.
7568: @item
7569: A file, using the words described in @ref{Forth source files}.
7570: @item
7571: A block, using the words described in @ref{Blocks}.
7572: @item
7573: A text string, using @code{evaluate}.
7574: @end itemize
7575:
7576: A program can identify the current input device from the values of
7577: @code{source-id} and @code{blk}.
7578:
1.44 crook 7579:
1.29 crook 7580: doc-source-id
7581: doc-blk
7582:
7583: doc-save-input
7584: doc-restore-input
7585:
7586: doc-evaluate
1.1 anton 7587:
1.29 crook 7588:
1.44 crook 7589:
1.29 crook 7590: @node Number Conversion, Interpret/Compile states, Input Sources, The Text Interpreter
1.26 crook 7591: @subsection Number Conversion
7592: @cindex number conversion
7593: @cindex double-cell numbers, input format
7594: @cindex input format for double-cell numbers
7595: @cindex single-cell numbers, input format
7596: @cindex input format for single-cell numbers
7597: @cindex floating-point numbers, input format
7598: @cindex input format for floating-point numbers
1.1 anton 7599:
1.29 crook 7600: This section describes the rules that the text interpreter uses when it
7601: tries to convert a string into a number.
1.1 anton 7602:
1.26 crook 7603: Let <digit> represent any character that is a legal digit in the current
1.29 crook 7604: number base@footnote{For example, 0-9 when the number base is decimal or
7605: 0-9, A-F when the number base is hexadecimal.}.
1.1 anton 7606:
1.26 crook 7607: Let <decimal digit> represent any character in the range 0-9.
1.1 anton 7608:
1.29 crook 7609: Let @{@i{a b}@} represent the @i{optional} presence of any of the characters
7610: in the braces (@i{a} or @i{b} or neither).
1.1 anton 7611:
1.26 crook 7612: Let * represent any number of instances of the previous character
7613: (including none).
1.1 anton 7614:
1.26 crook 7615: Let any other character represent itself.
1.1 anton 7616:
1.29 crook 7617: @noindent
1.26 crook 7618: Now, the conversion rules are:
1.21 crook 7619:
1.26 crook 7620: @itemize @bullet
7621: @item
7622: A string of the form <digit><digit>* is treated as a single-precision
1.29 crook 7623: (cell-sized) positive integer. Examples are 0 123 6784532 32343212343456 42
1.26 crook 7624: @item
7625: A string of the form -<digit><digit>* is treated as a single-precision
1.29 crook 7626: (cell-sized) negative integer, and is represented using 2's-complement
1.26 crook 7627: arithmetic. Examples are -45 -5681 -0
7628: @item
7629: A string of the form <digit><digit>*.<digit>* is treated as a double-precision
1.29 crook 7630: (double-cell-sized) positive integer. Examples are 3465. 3.465 34.65
7631: (all three of these represent the same number).
1.26 crook 7632: @item
7633: A string of the form -<digit><digit>*.<digit>* is treated as a
1.29 crook 7634: double-precision (double-cell-sized) negative integer, and is
1.26 crook 7635: represented using 2's-complement arithmetic. Examples are -3465. -3.465
1.29 crook 7636: -34.65 (all three of these represent the same number).
1.26 crook 7637: @item
1.29 crook 7638: A string of the form @{+ -@}<decimal digit>@{.@}<decimal digit>*@{e
7639: E@}@{+ -@}<decimal digit><decimal digit>* is treated as a floating-point
1.35 anton 7640: number. Examples are 1e 1e0 1.e 1.e0 +1e+0 (which all represent the same
1.29 crook 7641: number) +12.E-4
1.26 crook 7642: @end itemize
1.1 anton 7643:
1.26 crook 7644: By default, the number base used for integer number conversion is given
1.35 anton 7645: by the contents of the variable @code{base}. Note that a lot of
7646: confusion can result from unexpected values of @code{base}. If you
7647: change @code{base} anywhere, make sure to save the old value and restore
7648: it afterwards. In general I recommend keeping @code{base} decimal, and
7649: using the prefixes described below for the popular non-decimal bases.
1.1 anton 7650:
1.29 crook 7651: doc-dpl
1.26 crook 7652: doc-base
7653: doc-hex
7654: doc-decimal
1.1 anton 7655:
1.44 crook 7656:
1.26 crook 7657: @cindex '-prefix for character strings
7658: @cindex &-prefix for decimal numbers
7659: @cindex %-prefix for binary numbers
7660: @cindex $-prefix for hexadecimal numbers
1.35 anton 7661: Gforth allows you to override the value of @code{base} by using a
1.29 crook 7662: prefix@footnote{Some Forth implementations provide a similar scheme by
7663: implementing @code{$} etc. as parsing words that process the subsequent
7664: number in the input stream and push it onto the stack. For example, see
7665: @cite{Number Conversion and Literals}, by Wil Baden; Forth Dimensions
7666: 20(3) pages 26--27. In such implementations, unlike in Gforth, a space
7667: is required between the prefix and the number.} before the first digit
7668: of an (integer) number. Four prefixes are supported:
1.1 anton 7669:
1.26 crook 7670: @itemize @bullet
7671: @item
1.35 anton 7672: @code{&} -- decimal
1.26 crook 7673: @item
1.35 anton 7674: @code{%} -- binary
1.26 crook 7675: @item
1.35 anton 7676: @code{$} -- hexadecimal
1.26 crook 7677: @item
1.35 anton 7678: @code{'} -- base @code{max-char+1}
1.26 crook 7679: @end itemize
1.1 anton 7680:
1.26 crook 7681: Here are some examples, with the equivalent decimal number shown after
7682: in braces:
1.1 anton 7683:
1.26 crook 7684: -$41 (-65), %1001101 (205), %1001.0001 (145 - a double-precision number),
7685: 'AB (16706; ascii A is 65, ascii B is 66, number is 65*256 + 66),
7686: 'ab (24930; ascii a is 97, ascii B is 98, number is 97*256 + 98),
7687: &905 (905), $abc (2478), $ABC (2478).
1.1 anton 7688:
1.26 crook 7689: @cindex number conversion - traps for the unwary
1.29 crook 7690: @noindent
1.26 crook 7691: Number conversion has a number of traps for the unwary:
1.1 anton 7692:
1.26 crook 7693: @itemize @bullet
7694: @item
7695: You cannot determine the current number base using the code sequence
1.35 anton 7696: @code{base @@ .} -- the number base is always 10 in the current number
7697: base. Instead, use something like @code{base @@ dec.}
1.26 crook 7698: @item
7699: If the number base is set to a value greater than 14 (for example,
7700: hexadecimal), the number 123E4 is ambiguous; the conversion rules allow
7701: it to be intepreted as either a single-precision integer or a
7702: floating-point number (Gforth treats it as an integer). The ambiguity
7703: can be resolved by explicitly stating the sign of the mantissa and/or
7704: exponent: 123E+4 or +123E4 -- if the number base is decimal, no
7705: ambiguity arises; either representation will be treated as a
7706: floating-point number.
7707: @item
1.29 crook 7708: There is a word @code{bin} but it does @i{not} set the number base!
1.26 crook 7709: It is used to specify file types.
7710: @item
1.72 anton 7711: ANS Forth requires the @code{.} of a double-precision number to be the
7712: final character in the string. Gforth allows the @code{.} to be
7713: anywhere after the first digit.
1.26 crook 7714: @item
7715: The number conversion process does not check for overflow.
7716: @item
1.72 anton 7717: In an ANS Forth program @code{base} is required to be decimal when
7718: converting floating-point numbers. In Gforth, number conversion to
7719: floating-point numbers always uses base &10, irrespective of the value
7720: of @code{base}.
1.26 crook 7721: @end itemize
1.1 anton 7722:
1.49 anton 7723: You can read numbers into your programs with the words described in
7724: @ref{Input}.
1.1 anton 7725:
1.82 ! anton 7726: @node Interpret/Compile states, Interpreter Directives, Number Conversion, The Text Interpreter
1.26 crook 7727: @subsection Interpret/Compile states
7728: @cindex Interpret/Compile states
1.1 anton 7729:
1.29 crook 7730: A standard program is not permitted to change @code{state}
7731: explicitly. However, it can change @code{state} implicitly, using the
7732: words @code{[} and @code{]}. When @code{[} is executed it switches
7733: @code{state} to interpret state, and therefore the text interpreter
7734: starts interpreting. When @code{]} is executed it switches @code{state}
7735: to compile state and therefore the text interpreter starts
1.44 crook 7736: compiling. The most common usage for these words is for switching into
7737: interpret state and back from within a colon definition; this technique
1.49 anton 7738: can be used to compile a literal (for an example, @pxref{Literals}) or
7739: for conditional compilation (for an example, @pxref{Interpreter
7740: Directives}).
1.44 crook 7741:
1.35 anton 7742:
7743: @c This is a bad example: It's non-standard, and it's not necessary.
7744: @c However, I can't think of a good example for switching into compile
7745: @c state when there is no current word (@code{state}-smart words are not a
7746: @c good reason). So maybe we should use an example for switching into
7747: @c interpret @code{state} in a colon def. - anton
1.44 crook 7748: @c nac-> I agree. I started out by putting in the example, then realised
7749: @c that it was non-ANS, so wrote more words around it. I hope this
7750: @c re-written version is acceptable to you. I do want to keep the example
7751: @c as it is helpful for showing what is and what is not portable, particularly
7752: @c where it outlaws a style in common use.
7753:
1.72 anton 7754: @c anton: it's more important to show what's portable. After we have done
7755: @c that, we can also show what's not. In any case, I intend to write a
7756: @c section Macros (or so) which will also deal with [ ].
1.35 anton 7757:
1.44 crook 7758: @code{[} and @code{]} also give you the ability to switch into compile
7759: state and back, but we cannot think of any useful Standard application
7760: for this ability. Pre-ANS Forth textbooks have examples like this:
1.29 crook 7761:
7762: @example
7763: : AA ." this is A" ;
7764: : BB ." this is B" ;
7765: : CC ." this is C" ;
7766:
1.44 crook 7767: create table ] aa bb cc [
7768:
1.29 crook 7769: : go ( n -- ) \ n is offset into table.. 0 for 1st entry
7770: cells table + @ execute ;
7771: @end example
7772:
1.44 crook 7773: This example builds a jump table; @code{0 go} will display ``@code{this
7774: is A}''. Using @code{[} and @code{]} in this example is equivalent to
7775: defining @code{table} like this:
1.29 crook 7776:
7777: @example
1.44 crook 7778: create table ' aa COMPILE, ' bb COMPILE, ' cc COMPILE,
1.29 crook 7779: @end example
7780:
1.44 crook 7781: The problem with this code is that the definition of @code{table} is not
7782: portable -- it @i{compile}s execution tokens into code space. Whilst it
7783: @i{may} work on systems where code space and data space co-incide, the
1.29 crook 7784: Standard only allows data space to be assigned for a @code{CREATE}d
7785: word. In addition, the Standard only allows @code{@@} to access data
7786: space, whilst this example is using it to access code space. The only
7787: portable, Standard way to build this table is to build it in data space,
7788: like this:
7789:
7790: @example
7791: create table ' aa , ' bb , ' cc ,
7792: @end example
7793:
1.26 crook 7794: doc-state
1.44 crook 7795:
1.29 crook 7796:
1.82 ! anton 7797: @node Interpreter Directives, , Interpret/Compile states, The Text Interpreter
1.26 crook 7798: @subsection Interpreter Directives
7799: @cindex interpreter directives
1.72 anton 7800: @cindex conditional compilation
1.1 anton 7801:
1.29 crook 7802: These words are usually used in interpret state; typically to control
7803: which parts of a source file are processed by the text
1.26 crook 7804: interpreter. There are only a few ANS Forth Standard words, but Gforth
7805: supplements these with a rich set of immediate control structure words
7806: to compensate for the fact that the non-immediate versions can only be
1.29 crook 7807: used in compile state (@pxref{Control Structures}). Typical usages:
7808:
7809: @example
1.72 anton 7810: FALSE Constant HAVE-ASSEMBLER
1.29 crook 7811: .
7812: .
1.72 anton 7813: HAVE-ASSEMBLER [IF]
1.29 crook 7814: : ASSEMBLER-FEATURE
7815: ...
7816: ;
7817: [ENDIF]
7818: .
7819: .
7820: : SEE
7821: ... \ general-purpose SEE code
1.72 anton 7822: [ HAVE-ASSEMBLER [IF] ]
1.29 crook 7823: ... \ assembler-specific SEE code
7824: [ [ENDIF] ]
7825: ;
7826: @end example
1.1 anton 7827:
1.44 crook 7828:
1.26 crook 7829: doc-[IF]
7830: doc-[ELSE]
7831: doc-[THEN]
7832: doc-[ENDIF]
1.1 anton 7833:
1.26 crook 7834: doc-[IFDEF]
7835: doc-[IFUNDEF]
1.1 anton 7836:
1.26 crook 7837: doc-[?DO]
7838: doc-[DO]
7839: doc-[FOR]
7840: doc-[LOOP]
7841: doc-[+LOOP]
7842: doc-[NEXT]
1.1 anton 7843:
1.26 crook 7844: doc-[BEGIN]
7845: doc-[UNTIL]
7846: doc-[AGAIN]
7847: doc-[WHILE]
7848: doc-[REPEAT]
1.1 anton 7849:
1.27 crook 7850:
1.26 crook 7851: @c -------------------------------------------------------------
1.47 crook 7852: @node Word Lists, Environmental Queries, The Text Interpreter, Words
1.26 crook 7853: @section Word Lists
7854: @cindex word lists
1.32 anton 7855: @cindex header space
1.1 anton 7856:
1.36 anton 7857: A wordlist is a list of named words; you can add new words and look up
7858: words by name (and you can remove words in a restricted way with
7859: markers). Every named (and @code{reveal}ed) word is in one wordlist.
7860:
7861: @cindex search order stack
7862: The text interpreter searches the wordlists present in the search order
7863: (a stack of wordlists), from the top to the bottom. Within each
7864: wordlist, the search starts conceptually at the newest word; i.e., if
7865: two words in a wordlist have the same name, the newer word is found.
1.1 anton 7866:
1.26 crook 7867: @cindex compilation word list
1.36 anton 7868: New words are added to the @dfn{compilation wordlist} (aka current
7869: wordlist).
1.1 anton 7870:
1.36 anton 7871: @cindex wid
7872: A word list is identified by a cell-sized word list identifier (@i{wid})
7873: in much the same way as a file is identified by a file handle. The
7874: numerical value of the wid has no (portable) meaning, and might change
7875: from session to session.
1.1 anton 7876:
1.29 crook 7877: The ANS Forth ``Search order'' word set is intended to provide a set of
7878: low-level tools that allow various different schemes to be
1.74 anton 7879: implemented. Gforth also provides @code{vocabulary}, a traditional Forth
1.26 crook 7880: word. @file{compat/vocabulary.fs} provides an implementation in ANS
1.45 crook 7881: Forth.
1.1 anton 7882:
1.27 crook 7883: @comment TODO: locals section refers to here, saying that every word list (aka
7884: @comment vocabulary) has its own methods for searching etc. Need to document that.
1.78 anton 7885: @c anton: but better in a separate subsection on wordlist internals
1.1 anton 7886:
1.45 crook 7887: @comment TODO: document markers, reveal, tables, mappedwordlist
7888:
7889: @comment the gforthman- prefix is used to pick out the true definition of a
1.27 crook 7890: @comment word from the source files, rather than some alias.
1.44 crook 7891:
1.26 crook 7892: doc-forth-wordlist
7893: doc-definitions
7894: doc-get-current
7895: doc-set-current
7896: doc-get-order
1.45 crook 7897: doc---gforthman-set-order
1.26 crook 7898: doc-wordlist
1.30 anton 7899: doc-table
1.79 anton 7900: doc->order
1.36 anton 7901: doc-previous
1.26 crook 7902: doc-also
1.45 crook 7903: doc---gforthman-forth
1.26 crook 7904: doc-only
1.45 crook 7905: doc---gforthman-order
1.15 anton 7906:
1.26 crook 7907: doc-find
7908: doc-search-wordlist
1.15 anton 7909:
1.26 crook 7910: doc-words
7911: doc-vlist
1.44 crook 7912: @c doc-words-deferred
1.1 anton 7913:
1.74 anton 7914: @c doc-mappedwordlist @c map-structure undefined, implemantation-specific
1.26 crook 7915: doc-root
7916: doc-vocabulary
7917: doc-seal
7918: doc-vocs
7919: doc-current
7920: doc-context
1.1 anton 7921:
1.44 crook 7922:
1.26 crook 7923: @menu
1.75 anton 7924: * Vocabularies::
1.67 anton 7925: * Why use word lists?::
1.75 anton 7926: * Word list example::
1.26 crook 7927: @end menu
7928:
1.75 anton 7929: @node Vocabularies, Why use word lists?, Word Lists, Word Lists
7930: @subsection Vocabularies
7931: @cindex Vocabularies, detailed explanation
7932:
7933: Here is an example of creating and using a new wordlist using ANS
7934: Forth words:
7935:
7936: @example
7937: wordlist constant my-new-words-wordlist
7938: : my-new-words get-order nip my-new-words-wordlist swap set-order ;
7939:
7940: \ add it to the search order
7941: also my-new-words
7942:
7943: \ alternatively, add it to the search order and make it
7944: \ the compilation word list
7945: also my-new-words definitions
7946: \ type "order" to see the problem
7947: @end example
7948:
7949: The problem with this example is that @code{order} has no way to
7950: associate the name @code{my-new-words} with the wid of the word list (in
7951: Gforth, @code{order} and @code{vocs} will display @code{???} for a wid
7952: that has no associated name). There is no Standard way of associating a
7953: name with a wid.
7954:
7955: In Gforth, this example can be re-coded using @code{vocabulary}, which
7956: associates a name with a wid:
7957:
7958: @example
7959: vocabulary my-new-words
7960:
7961: \ add it to the search order
7962: also my-new-words
7963:
7964: \ alternatively, add it to the search order and make it
7965: \ the compilation word list
7966: my-new-words definitions
7967: \ type "order" to see that the problem is solved
7968: @end example
7969:
7970:
7971: @node Why use word lists?, Word list example, Vocabularies, Word Lists
1.26 crook 7972: @subsection Why use word lists?
7973: @cindex word lists - why use them?
7974:
1.74 anton 7975: Here are some reasons why people use wordlists:
1.26 crook 7976:
7977: @itemize @bullet
1.74 anton 7978:
7979: @c anton: Gforth's hashing implementation makes the search speed
7980: @c independent from the number of words. But it is linear with the number
7981: @c of wordlists that have to be searched, so in effect using more wordlists
7982: @c actually slows down compilation.
7983:
7984: @c @item
7985: @c To improve compilation speed by reducing the number of header space
7986: @c entries that must be searched. This is achieved by creating a new
7987: @c word list that contains all of the definitions that are used in the
7988: @c definition of a Forth system but which would not usually be used by
7989: @c programs running on that system. That word list would be on the search
7990: @c list when the Forth system was compiled but would be removed from the
7991: @c search list for normal operation. This can be a useful technique for
7992: @c low-performance systems (for example, 8-bit processors in embedded
7993: @c systems) but is unlikely to be necessary in high-performance desktop
7994: @c systems.
7995:
1.26 crook 7996: @item
7997: To prevent a set of words from being used outside the context in which
7998: they are valid. Two classic examples of this are an integrated editor
7999: (all of the edit commands are defined in a separate word list; the
8000: search order is set to the editor word list when the editor is invoked;
8001: the old search order is restored when the editor is terminated) and an
8002: integrated assembler (the op-codes for the machine are defined in a
8003: separate word list which is used when a @code{CODE} word is defined).
1.74 anton 8004:
8005: @item
8006: To organize the words of an application or library into a user-visible
8007: set (in @code{forth-wordlist} or some other common wordlist) and a set
8008: of helper words used just for the implementation (hidden in a separate
1.75 anton 8009: wordlist). This keeps @code{words}' output smaller, separates
8010: implementation and interface, and reduces the chance of name conflicts
8011: within the common wordlist.
1.74 anton 8012:
1.26 crook 8013: @item
8014: To prevent a name-space clash between multiple definitions with the same
8015: name. For example, when building a cross-compiler you might have a word
8016: @code{IF} that generates conditional code for your target system. By
8017: placing this definition in a different word list you can control whether
8018: the host system's @code{IF} or the target system's @code{IF} get used in
8019: any particular context by controlling the order of the word lists on the
8020: search order stack.
1.74 anton 8021:
1.26 crook 8022: @end itemize
1.1 anton 8023:
1.74 anton 8024: The downsides of using wordlists are:
8025:
8026: @itemize
8027:
8028: @item
8029: Debugging becomes more cumbersome.
8030:
8031: @item
8032: Name conflicts worked around with wordlists are still there, and you
8033: have to arrange the search order carefully to get the desired results;
8034: if you forget to do that, you get hard-to-find errors (as in any case
8035: where you read the code differently from the compiler; @code{see} can
1.75 anton 8036: help seeing which of several possible words the name resolves to in such
8037: cases). @code{See} displays just the name of the words, not what
8038: wordlist they belong to, so it might be misleading. Using unique names
8039: is a better approach to avoid name conflicts.
1.74 anton 8040:
8041: @item
8042: You have to explicitly undo any changes to the search order. In many
8043: cases it would be more convenient if this happened implicitly. Gforth
8044: currently does not provide such a feature, but it may do so in the
8045: future.
8046: @end itemize
8047:
8048:
1.75 anton 8049: @node Word list example, , Why use word lists?, Word Lists
8050: @subsection Word list example
8051: @cindex word lists - example
1.1 anton 8052:
1.74 anton 8053: The following example is from the
8054: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
8055: garbage collector} and uses wordlists to separate public words from
8056: helper words:
8057:
8058: @example
8059: get-current ( wid )
8060: vocabulary garbage-collector also garbage-collector definitions
8061: ... \ define helper words
8062: ( wid ) set-current \ restore original (i.e., public) compilation wordlist
8063: ... \ define the public (i.e., API) words
8064: \ they can refer to the helper words
8065: previous \ restore original search order (helper words become invisible)
8066: @end example
8067:
1.26 crook 8068: @c -------------------------------------------------------------
8069: @node Environmental Queries, Files, Word Lists, Words
8070: @section Environmental Queries
8071: @cindex environmental queries
1.21 crook 8072:
1.26 crook 8073: ANS Forth introduced the idea of ``environmental queries'' as a way
8074: for a program running on a system to determine certain characteristics of the system.
8075: The Standard specifies a number of strings that might be recognised by a system.
1.21 crook 8076:
1.32 anton 8077: The Standard requires that the header space used for environmental queries
8078: be distinct from the header space used for definitions.
1.21 crook 8079:
1.26 crook 8080: Typically, environmental queries are supported by creating a set of
1.29 crook 8081: definitions in a word list that is @i{only} used during environmental
1.26 crook 8082: queries; that is what Gforth does. There is no Standard way of adding
8083: definitions to the set of recognised environmental queries, but any
8084: implementation that supports the loading of optional word sets must have
8085: some mechanism for doing this (after loading the word set, the
8086: associated environmental query string must return @code{true}). In
8087: Gforth, the word list used to honour environmental queries can be
8088: manipulated just like any other word list.
1.21 crook 8089:
1.44 crook 8090:
1.26 crook 8091: doc-environment?
8092: doc-environment-wordlist
1.21 crook 8093:
1.26 crook 8094: doc-gforth
8095: doc-os-class
1.21 crook 8096:
1.44 crook 8097:
1.26 crook 8098: Note that, whilst the documentation for (e.g.) @code{gforth} shows it
8099: returning two items on the stack, querying it using @code{environment?}
8100: will return an additional item; the @code{true} flag that shows that the
8101: string was recognised.
1.21 crook 8102:
1.26 crook 8103: @comment TODO Document the standard strings or note where they are documented herein
1.21 crook 8104:
1.26 crook 8105: Here are some examples of using environmental queries:
1.21 crook 8106:
1.26 crook 8107: @example
8108: s" address-unit-bits" environment? 0=
8109: [IF]
8110: cr .( environmental attribute address-units-bits unknown... ) cr
1.75 anton 8111: [ELSE]
8112: drop \ ensure balanced stack effect
1.26 crook 8113: [THEN]
1.21 crook 8114:
1.75 anton 8115: \ this might occur in the prelude of a standard program that uses THROW
8116: s" exception" environment? [IF]
8117: 0= [IF]
8118: : throw abort" exception thrown" ;
8119: [THEN]
8120: [ELSE] \ we don't know, so make sure
8121: : throw abort" exception thrown" ;
8122: [THEN]
1.21 crook 8123:
1.26 crook 8124: s" gforth" environment? [IF] .( Gforth version ) TYPE
8125: [ELSE] .( Not Gforth..) [THEN]
1.75 anton 8126:
8127: \ a program using v*
8128: s" gforth" environment? [IF]
8129: s" 0.5.0" compare 0< [IF] \ v* is a primitive since 0.5.0
8130: : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
8131: >r swap 2swap swap 0e r> 0 ?DO
8132: dup f@ over + 2swap dup f@ f* f+ over + 2swap
8133: LOOP
8134: 2drop 2drop ;
8135: [THEN]
8136: [ELSE] \
8137: : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
8138: ...
8139: [THEN]
1.26 crook 8140: @end example
1.21 crook 8141:
1.26 crook 8142: Here is an example of adding a definition to the environment word list:
1.21 crook 8143:
1.26 crook 8144: @example
8145: get-current environment-wordlist set-current
8146: true constant block
8147: true constant block-ext
8148: set-current
8149: @end example
1.21 crook 8150:
1.26 crook 8151: You can see what definitions are in the environment word list like this:
1.21 crook 8152:
1.26 crook 8153: @example
1.79 anton 8154: environment-wordlist >order words previous
1.26 crook 8155: @end example
1.21 crook 8156:
8157:
1.26 crook 8158: @c -------------------------------------------------------------
8159: @node Files, Blocks, Environmental Queries, Words
8160: @section Files
1.28 crook 8161: @cindex files
8162: @cindex I/O - file-handling
1.21 crook 8163:
1.26 crook 8164: Gforth provides facilities for accessing files that are stored in the
8165: host operating system's file-system. Files that are processed by Gforth
8166: can be divided into two categories:
1.21 crook 8167:
1.23 crook 8168: @itemize @bullet
8169: @item
1.29 crook 8170: Files that are processed by the Text Interpreter (@dfn{Forth source files}).
1.23 crook 8171: @item
1.29 crook 8172: Files that are processed by some other program (@dfn{general files}).
1.26 crook 8173: @end itemize
8174:
8175: @menu
1.48 anton 8176: * Forth source files::
8177: * General files::
8178: * Search Paths::
1.26 crook 8179: @end menu
8180:
8181: @c -------------------------------------------------------------
8182: @node Forth source files, General files, Files, Files
8183: @subsection Forth source files
8184: @cindex including files
8185: @cindex Forth source files
1.21 crook 8186:
1.26 crook 8187: The simplest way to interpret the contents of a file is to use one of
8188: these two formats:
1.21 crook 8189:
1.26 crook 8190: @example
8191: include mysource.fs
8192: s" mysource.fs" included
8193: @end example
1.21 crook 8194:
1.75 anton 8195: You usually want to include a file only if it is not included already
1.26 crook 8196: (by, say, another source file). In that case, you can use one of these
1.45 crook 8197: three formats:
1.21 crook 8198:
1.26 crook 8199: @example
8200: require mysource.fs
8201: needs mysource.fs
8202: s" mysource.fs" required
8203: @end example
1.21 crook 8204:
1.26 crook 8205: @cindex stack effect of included files
8206: @cindex including files, stack effect
1.45 crook 8207: It is good practice to write your source files such that interpreting them
8208: does not change the stack. Source files designed in this way can be used with
1.26 crook 8209: @code{required} and friends without complications. For example:
1.21 crook 8210:
1.26 crook 8211: @example
1.75 anton 8212: 1024 require foo.fs drop
1.26 crook 8213: @end example
1.21 crook 8214:
1.75 anton 8215: Here you want to pass the argument 1024 (e.g., a buffer size) to
8216: @file{foo.fs}. Interpreting @file{foo.fs} has the stack effect ( n -- n
8217: ), which allows its use with @code{require}. Of course with such
8218: parameters to required files, you have to ensure that the first
8219: @code{require} fits for all uses (i.e., @code{require} it early in the
8220: master load file).
1.44 crook 8221:
1.26 crook 8222: doc-include-file
8223: doc-included
1.28 crook 8224: doc-included?
1.26 crook 8225: doc-include
8226: doc-required
8227: doc-require
8228: doc-needs
1.75 anton 8229: @c doc-init-included-files @c internal
8230: @c doc-loadfilename @c internal word
8231: doc-sourcefilename
8232: doc-sourceline#
1.44 crook 8233:
1.26 crook 8234: A definition in ANS Forth for @code{required} is provided in
8235: @file{compat/required.fs}.
1.21 crook 8236:
1.26 crook 8237: @c -------------------------------------------------------------
8238: @node General files, Search Paths, Forth source files, Files
8239: @subsection General files
8240: @cindex general files
8241: @cindex file-handling
1.21 crook 8242:
1.75 anton 8243: Files are opened/created by name and type. The following file access
8244: methods (FAMs) are recognised:
1.44 crook 8245:
1.75 anton 8246: @cindex fam (file access method)
1.26 crook 8247: doc-r/o
8248: doc-r/w
8249: doc-w/o
8250: doc-bin
1.1 anton 8251:
1.44 crook 8252:
1.26 crook 8253: When a file is opened/created, it returns a file identifier,
1.29 crook 8254: @i{wfileid} that is used for all other file commands. All file
8255: commands also return a status value, @i{wior}, that is 0 for a
1.26 crook 8256: successful operation and an implementation-defined non-zero value in the
8257: case of an error.
1.21 crook 8258:
1.44 crook 8259:
1.26 crook 8260: doc-open-file
8261: doc-create-file
1.21 crook 8262:
1.26 crook 8263: doc-close-file
8264: doc-delete-file
8265: doc-rename-file
8266: doc-read-file
8267: doc-read-line
8268: doc-write-file
8269: doc-write-line
8270: doc-emit-file
8271: doc-flush-file
1.21 crook 8272:
1.26 crook 8273: doc-file-status
8274: doc-file-position
8275: doc-reposition-file
8276: doc-file-size
8277: doc-resize-file
1.21 crook 8278:
1.44 crook 8279:
1.26 crook 8280: @c ---------------------------------------------------------
1.48 anton 8281: @node Search Paths, , General files, Files
1.26 crook 8282: @subsection Search Paths
8283: @cindex path for @code{included}
8284: @cindex file search path
8285: @cindex @code{include} search path
8286: @cindex search path for files
1.21 crook 8287:
1.26 crook 8288: If you specify an absolute filename (i.e., a filename starting with
8289: @file{/} or @file{~}, or with @file{:} in the second position (as in
8290: @samp{C:...})) for @code{included} and friends, that file is included
8291: just as you would expect.
1.21 crook 8292:
1.75 anton 8293: If the filename starts with @file{./}, this refers to the directory that
8294: the present file was @code{included} from. This allows files to include
8295: other files relative to their own position (irrespective of the current
8296: working directory or the absolute position). This feature is essential
8297: for libraries consisting of several files, where a file may include
8298: other files from the library. It corresponds to @code{#include "..."}
8299: in C. If the current input source is not a file, @file{.} refers to the
8300: directory of the innermost file being included, or, if there is no file
8301: being included, to the current working directory.
8302:
8303: For relative filenames (not starting with @file{./}), Gforth uses a
8304: search path similar to Forth's search order (@pxref{Word Lists}). It
8305: tries to find the given filename in the directories present in the path,
8306: and includes the first one it finds. There are separate search paths for
8307: Forth source files and general files. If the search path contains the
8308: directory @file{.}, this refers to the directory of the current file, or
8309: the working directory, as if the file had been specified with @file{./}.
1.21 crook 8310:
1.26 crook 8311: Use @file{~+} to refer to the current working directory (as in the
8312: @code{bash}).
1.1 anton 8313:
1.75 anton 8314: @c anton: fold the following subsubsections into this subsection?
1.1 anton 8315:
1.48 anton 8316: @menu
1.75 anton 8317: * Source Search Paths::
1.48 anton 8318: * General Search Paths::
8319: @end menu
8320:
1.26 crook 8321: @c ---------------------------------------------------------
1.75 anton 8322: @node Source Search Paths, General Search Paths, Search Paths, Search Paths
8323: @subsubsection Source Search Paths
8324: @cindex search path control, source files
1.5 anton 8325:
1.26 crook 8326: The search path is initialized when you start Gforth (@pxref{Invoking
1.75 anton 8327: Gforth}). You can display it and change it using @code{fpath} in
8328: combination with the general path handling words.
1.5 anton 8329:
1.75 anton 8330: doc-fpath
8331: @c the functionality of the following words is easily available through
8332: @c fpath and the general path words. The may go away.
8333: @c doc-.fpath
8334: @c doc-fpath+
8335: @c doc-fpath=
8336: @c doc-open-fpath-file
1.44 crook 8337:
8338: @noindent
1.26 crook 8339: Here is an example of using @code{fpath} and @code{require}:
1.5 anton 8340:
1.26 crook 8341: @example
1.75 anton 8342: fpath path= /usr/lib/forth/|./
1.26 crook 8343: require timer.fs
8344: @end example
1.5 anton 8345:
1.75 anton 8346:
1.26 crook 8347: @c ---------------------------------------------------------
1.75 anton 8348: @node General Search Paths, , Source Search Paths, Search Paths
1.26 crook 8349: @subsubsection General Search Paths
1.75 anton 8350: @cindex search path control, source files
1.5 anton 8351:
1.26 crook 8352: Your application may need to search files in several directories, like
8353: @code{included} does. To facilitate this, Gforth allows you to define
8354: and use your own search paths, by providing generic equivalents of the
8355: Forth search path words:
1.5 anton 8356:
1.75 anton 8357: doc-open-path-file
8358: doc-path-allot
8359: doc-clear-path
8360: doc-also-path
1.26 crook 8361: doc-.path
8362: doc-path+
8363: doc-path=
1.5 anton 8364:
1.75 anton 8365: @c anton: better define a word for it, say "path-allot ( ucount -- path-addr )
1.44 crook 8366:
1.75 anton 8367: Here's an example of creating an empty search path:
8368: @c
1.26 crook 8369: @example
1.75 anton 8370: create mypath 500 path-allot \ maximum length 500 chars (is checked)
1.26 crook 8371: @end example
1.5 anton 8372:
1.26 crook 8373: @c -------------------------------------------------------------
8374: @node Blocks, Other I/O, Files, Words
8375: @section Blocks
1.28 crook 8376: @cindex I/O - blocks
8377: @cindex blocks
8378:
8379: When you run Gforth on a modern desk-top computer, it runs under the
8380: control of an operating system which provides certain services. One of
8381: these services is @var{file services}, which allows Forth source code
8382: and data to be stored in files and read into Gforth (@pxref{Files}).
8383:
8384: Traditionally, Forth has been an important programming language on
8385: systems where it has interfaced directly to the underlying hardware with
8386: no intervening operating system. Forth provides a mechanism, called
1.29 crook 8387: @dfn{blocks}, for accessing mass storage on such systems.
1.28 crook 8388:
8389: A block is a 1024-byte data area, which can be used to hold data or
8390: Forth source code. No structure is imposed on the contents of the
8391: block. A block is identified by its number; blocks are numbered
8392: contiguously from 1 to an implementation-defined maximum.
8393:
8394: A typical system that used blocks but no operating system might use a
8395: single floppy-disk drive for mass storage, with the disks formatted to
8396: provide 256-byte sectors. Blocks would be implemented by assigning the
8397: first four sectors of the disk to block 1, the second four sectors to
8398: block 2 and so on, up to the limit of the capacity of the disk. The disk
8399: would not contain any file system information, just the set of blocks.
8400:
1.29 crook 8401: @cindex blocks file
1.28 crook 8402: On systems that do provide file services, blocks are typically
1.29 crook 8403: implemented by storing a sequence of blocks within a single @dfn{blocks
1.28 crook 8404: file}. The size of the blocks file will be an exact multiple of 1024
8405: bytes, corresponding to the number of blocks it contains. This is the
8406: mechanism that Gforth uses.
8407:
1.29 crook 8408: @cindex @file{blocks.fb}
1.75 anton 8409: Only one blocks file can be open at a time. If you use block words without
1.28 crook 8410: having specified a blocks file, Gforth defaults to the blocks file
8411: @file{blocks.fb}. Gforth uses the Forth search path when attempting to
1.75 anton 8412: locate a blocks file (@pxref{Source Search Paths}).
1.28 crook 8413:
1.29 crook 8414: @cindex block buffers
1.28 crook 8415: When you read and write blocks under program control, Gforth uses a
1.29 crook 8416: number of @dfn{block buffers} as intermediate storage. These buffers are
1.28 crook 8417: not used when you use @code{load} to interpret the contents of a block.
8418:
1.75 anton 8419: The behaviour of the block buffers is analagous to that of a cache.
8420: Each block buffer has three states:
1.28 crook 8421:
8422: @itemize @bullet
8423: @item
8424: Unassigned
8425: @item
8426: Assigned-clean
8427: @item
8428: Assigned-dirty
8429: @end itemize
8430:
1.29 crook 8431: Initially, all block buffers are @i{unassigned}. In order to access a
1.28 crook 8432: block, the block (specified by its block number) must be assigned to a
8433: block buffer.
8434:
8435: The assignment of a block to a block buffer is performed by @code{block}
8436: or @code{buffer}. Use @code{block} when you wish to modify the existing
8437: contents of a block. Use @code{buffer} when you don't care about the
8438: existing contents of the block@footnote{The ANS Forth definition of
1.35 anton 8439: @code{buffer} is intended not to cause disk I/O; if the data associated
1.28 crook 8440: with the particular block is already stored in a block buffer due to an
8441: earlier @code{block} command, @code{buffer} will return that block
8442: buffer and the existing contents of the block will be
8443: available. Otherwise, @code{buffer} will simply assign a new, empty
1.29 crook 8444: block buffer for the block.}.
1.28 crook 8445:
1.47 crook 8446: Once a block has been assigned to a block buffer using @code{block} or
1.75 anton 8447: @code{buffer}, that block buffer becomes the @i{current block
8448: buffer}. Data may only be manipulated (read or written) within the
8449: current block buffer.
1.47 crook 8450:
8451: When the contents of the current block buffer has been modified it is
1.48 anton 8452: necessary, @emph{before calling @code{block} or @code{buffer} again}, to
1.75 anton 8453: either abandon the changes (by doing nothing) or mark the block as
8454: changed (assigned-dirty), using @code{update}. Using @code{update} does
8455: not change the blocks file; it simply changes a block buffer's state to
8456: @i{assigned-dirty}. The block will be written implicitly when it's
8457: buffer is needed for another block, or explicitly by @code{flush} or
8458: @code{save-buffers}.
8459:
8460: word @code{Flush} writes all @i{assigned-dirty} blocks back to the
8461: blocks file on disk. Leaving Gforth with @code{bye} also performs a
8462: @code{flush}.
1.28 crook 8463:
1.29 crook 8464: In Gforth, @code{block} and @code{buffer} use a @i{direct-mapped}
1.28 crook 8465: algorithm to assign a block buffer to a block. That means that any
8466: particular block can only be assigned to one specific block buffer,
1.29 crook 8467: called (for the particular operation) the @i{victim buffer}. If the
1.47 crook 8468: victim buffer is @i{unassigned} or @i{assigned-clean} it is allocated to
8469: the new block immediately. If it is @i{assigned-dirty} its current
8470: contents are written back to the blocks file on disk before it is
1.28 crook 8471: allocated to the new block.
8472:
8473: Although no structure is imposed on the contents of a block, it is
8474: traditional to display the contents as 16 lines each of 64 characters. A
8475: block provides a single, continuous stream of input (for example, it
8476: acts as a single parse area) -- there are no end-of-line characters
8477: within a block, and no end-of-file character at the end of a
8478: block. There are two consequences of this:
1.26 crook 8479:
1.28 crook 8480: @itemize @bullet
8481: @item
8482: The last character of one line wraps straight into the first character
8483: of the following line
8484: @item
8485: The word @code{\} -- comment to end of line -- requires special
8486: treatment; in the context of a block it causes all characters until the
8487: end of the current 64-character ``line'' to be ignored.
8488: @end itemize
8489:
8490: In Gforth, when you use @code{block} with a non-existent block number,
1.45 crook 8491: the current blocks file will be extended to the appropriate size and the
1.28 crook 8492: block buffer will be initialised with spaces.
8493:
1.47 crook 8494: Gforth includes a simple block editor (type @code{use blocked.fb 0 list}
8495: for details) but doesn't encourage the use of blocks; the mechanism is
8496: only provided for backward compatibility -- ANS Forth requires blocks to
8497: be available when files are.
1.28 crook 8498:
8499: Common techniques that are used when working with blocks include:
8500:
8501: @itemize @bullet
8502: @item
8503: A screen editor that allows you to edit blocks without leaving the Forth
8504: environment.
8505: @item
8506: Shadow screens; where every code block has an associated block
8507: containing comments (for example: code in odd block numbers, comments in
8508: even block numbers). Typically, the block editor provides a convenient
8509: mechanism to toggle between code and comments.
8510: @item
8511: Load blocks; a single block (typically block 1) contains a number of
8512: @code{thru} commands which @code{load} the whole of the application.
8513: @end itemize
1.26 crook 8514:
1.29 crook 8515: See Frank Sergeant's Pygmy Forth to see just how well blocks can be
8516: integrated into a Forth programming environment.
1.26 crook 8517:
8518: @comment TODO what about errors on open-blocks?
1.44 crook 8519:
1.26 crook 8520: doc-open-blocks
8521: doc-use
1.75 anton 8522: doc-block-offset
1.26 crook 8523: doc-get-block-fid
8524: doc-block-position
1.28 crook 8525:
1.75 anton 8526: doc-list
1.28 crook 8527: doc-scr
8528:
1.45 crook 8529: doc---gforthman-block
1.28 crook 8530: doc-buffer
8531:
1.75 anton 8532: doc-empty-buffers
8533: doc-empty-buffer
1.26 crook 8534: doc-update
1.28 crook 8535: doc-updated?
1.26 crook 8536: doc-save-buffers
1.75 anton 8537: doc-save-buffer
1.26 crook 8538: doc-flush
1.28 crook 8539:
1.26 crook 8540: doc-load
8541: doc-thru
8542: doc-+load
8543: doc-+thru
1.45 crook 8544: doc---gforthman--->
1.26 crook 8545: doc-block-included
8546:
1.44 crook 8547:
1.26 crook 8548: @c -------------------------------------------------------------
1.78 anton 8549: @node Other I/O, Locals, Blocks, Words
1.26 crook 8550: @section Other I/O
1.28 crook 8551: @cindex I/O - keyboard and display
1.26 crook 8552:
8553: @menu
8554: * Simple numeric output:: Predefined formats
8555: * Formatted numeric output:: Formatted (pictured) output
8556: * String Formats:: How Forth stores strings in memory
1.67 anton 8557: * Displaying characters and strings:: Other stuff
1.26 crook 8558: * Input:: Input
8559: @end menu
8560:
8561: @node Simple numeric output, Formatted numeric output, Other I/O, Other I/O
8562: @subsection Simple numeric output
1.28 crook 8563: @cindex numeric output - simple/free-format
1.5 anton 8564:
1.26 crook 8565: The simplest output functions are those that display numbers from the
8566: data or floating-point stacks. Floating-point output is always displayed
8567: using base 10. Numbers displayed from the data stack use the value stored
8568: in @code{base}.
1.5 anton 8569:
1.44 crook 8570:
1.26 crook 8571: doc-.
8572: doc-dec.
8573: doc-hex.
8574: doc-u.
8575: doc-.r
8576: doc-u.r
8577: doc-d.
8578: doc-ud.
8579: doc-d.r
8580: doc-ud.r
8581: doc-f.
8582: doc-fe.
8583: doc-fs.
1.5 anton 8584:
1.44 crook 8585:
1.26 crook 8586: Examples of printing the number 1234.5678E23 in the different floating-point output
8587: formats are shown below:
1.5 anton 8588:
8589: @example
1.26 crook 8590: f. 123456779999999000000000000.
8591: fe. 123.456779999999E24
8592: fs. 1.23456779999999E26
1.5 anton 8593: @end example
8594:
8595:
1.26 crook 8596: @node Formatted numeric output, String Formats, Simple numeric output, Other I/O
8597: @subsection Formatted numeric output
1.28 crook 8598: @cindex formatted numeric output
1.26 crook 8599: @cindex pictured numeric output
1.28 crook 8600: @cindex numeric output - formatted
1.26 crook 8601:
1.29 crook 8602: Forth traditionally uses a technique called @dfn{pictured numeric
1.26 crook 8603: output} for formatted printing of integers. In this technique, digits
8604: are extracted from the number (using the current output radix defined by
8605: @code{base}), converted to ASCII codes and appended to a string that is
8606: built in a scratch-pad area of memory (@pxref{core-idef,
8607: Implementation-defined options, Implementation-defined
8608: options}). Arbitrary characters can be appended to the string during the
8609: extraction process. The completed string is specified by an address
8610: and length and can be manipulated (@code{TYPE}ed, copied, modified)
8611: under program control.
1.5 anton 8612:
1.75 anton 8613: All of the integer output words described in the previous section
8614: (@pxref{Simple numeric output}) are implemented in Gforth using pictured
8615: numeric output.
1.5 anton 8616:
1.47 crook 8617: Three important things to remember about pictured numeric output:
1.5 anton 8618:
1.26 crook 8619: @itemize @bullet
8620: @item
1.28 crook 8621: It always operates on double-precision numbers; to display a
1.49 anton 8622: single-precision number, convert it first (for ways of doing this
8623: @pxref{Double precision}).
1.26 crook 8624: @item
1.28 crook 8625: It always treats the double-precision number as though it were
8626: unsigned. The examples below show ways of printing signed numbers.
1.26 crook 8627: @item
8628: The string is built up from right to left; least significant digit first.
8629: @end itemize
1.5 anton 8630:
1.44 crook 8631:
1.26 crook 8632: doc-<#
1.47 crook 8633: doc-<<#
1.26 crook 8634: doc-#
8635: doc-#s
8636: doc-hold
8637: doc-sign
8638: doc-#>
1.47 crook 8639: doc-#>>
1.5 anton 8640:
1.26 crook 8641: doc-represent
1.5 anton 8642:
1.44 crook 8643:
8644: @noindent
1.26 crook 8645: Here are some examples of using pictured numeric output:
1.5 anton 8646:
8647: @example
1.26 crook 8648: : my-u. ( u -- )
8649: \ Simplest use of pns.. behaves like Standard u.
8650: 0 \ convert to unsigned double
1.75 anton 8651: <<# \ start conversion
1.26 crook 8652: #s \ convert all digits
8653: #> \ complete conversion
1.75 anton 8654: TYPE SPACE \ display, with trailing space
8655: #>> ; \ release hold area
1.5 anton 8656:
1.26 crook 8657: : cents-only ( u -- )
8658: 0 \ convert to unsigned double
1.75 anton 8659: <<# \ start conversion
1.26 crook 8660: # # \ convert two least-significant digits
8661: #> \ complete conversion, discard other digits
1.75 anton 8662: TYPE SPACE \ display, with trailing space
8663: #>> ; \ release hold area
1.5 anton 8664:
1.26 crook 8665: : dollars-and-cents ( u -- )
8666: 0 \ convert to unsigned double
1.75 anton 8667: <<# \ start conversion
1.26 crook 8668: # # \ convert two least-significant digits
8669: [char] . hold \ insert decimal point
8670: #s \ convert remaining digits
8671: [char] $ hold \ append currency symbol
8672: #> \ complete conversion
1.75 anton 8673: TYPE SPACE \ display, with trailing space
8674: #>> ; \ release hold area
1.5 anton 8675:
1.26 crook 8676: : my-. ( n -- )
8677: \ handling negatives.. behaves like Standard .
8678: s>d \ convert to signed double
8679: swap over dabs \ leave sign byte followed by unsigned double
1.75 anton 8680: <<# \ start conversion
1.26 crook 8681: #s \ convert all digits
8682: rot sign \ get at sign byte, append "-" if needed
8683: #> \ complete conversion
1.75 anton 8684: TYPE SPACE \ display, with trailing space
8685: #>> ; \ release hold area
1.5 anton 8686:
1.26 crook 8687: : account. ( n -- )
1.75 anton 8688: \ accountants don't like minus signs, they use parentheses
1.26 crook 8689: \ for negative numbers
8690: s>d \ convert to signed double
8691: swap over dabs \ leave sign byte followed by unsigned double
1.75 anton 8692: <<# \ start conversion
1.26 crook 8693: 2 pick \ get copy of sign byte
8694: 0< IF [char] ) hold THEN \ right-most character of output
8695: #s \ convert all digits
8696: rot \ get at sign byte
8697: 0< IF [char] ( hold THEN
8698: #> \ complete conversion
1.75 anton 8699: TYPE SPACE \ display, with trailing space
8700: #>> ; \ release hold area
8701:
1.5 anton 8702: @end example
8703:
1.26 crook 8704: Here are some examples of using these words:
1.5 anton 8705:
8706: @example
1.26 crook 8707: 1 my-u. 1
8708: hex -1 my-u. decimal FFFFFFFF
8709: 1 cents-only 01
8710: 1234 cents-only 34
8711: 2 dollars-and-cents $0.02
8712: 1234 dollars-and-cents $12.34
8713: 123 my-. 123
8714: -123 my. -123
8715: 123 account. 123
8716: -456 account. (456)
1.5 anton 8717: @end example
8718:
8719:
1.26 crook 8720: @node String Formats, Displaying characters and strings, Formatted numeric output, Other I/O
8721: @subsection String Formats
1.27 crook 8722: @cindex strings - see character strings
8723: @cindex character strings - formats
1.28 crook 8724: @cindex I/O - see character strings
1.75 anton 8725: @cindex counted strings
8726:
8727: @c anton: this does not really belong here; maybe the memory section,
8728: @c or the principles chapter
1.26 crook 8729:
1.27 crook 8730: Forth commonly uses two different methods for representing character
8731: strings:
1.26 crook 8732:
8733: @itemize @bullet
8734: @item
8735: @cindex address of counted string
1.45 crook 8736: @cindex counted string
1.29 crook 8737: As a @dfn{counted string}, represented by a @i{c-addr}. The char
8738: addressed by @i{c-addr} contains a character-count, @i{n}, of the
8739: string and the string occupies the subsequent @i{n} char addresses in
1.26 crook 8740: memory.
8741: @item
1.29 crook 8742: As cell pair on the stack; @i{c-addr u}, where @i{u} is the length
8743: of the string in characters, and @i{c-addr} is the address of the
1.26 crook 8744: first byte of the string.
8745: @end itemize
8746:
8747: ANS Forth encourages the use of the second format when representing
1.75 anton 8748: strings.
1.26 crook 8749:
1.44 crook 8750:
1.26 crook 8751: doc-count
8752:
1.44 crook 8753:
1.49 anton 8754: For words that move, copy and search for strings see @ref{Memory
8755: Blocks}. For words that display characters and strings see
8756: @ref{Displaying characters and strings}.
1.26 crook 8757:
8758: @node Displaying characters and strings, Input, String Formats, Other I/O
8759: @subsection Displaying characters and strings
1.27 crook 8760: @cindex characters - compiling and displaying
8761: @cindex character strings - compiling and displaying
1.26 crook 8762:
8763: This section starts with a glossary of Forth words and ends with a set
8764: of examples.
8765:
1.44 crook 8766:
1.26 crook 8767: doc-bl
8768: doc-space
8769: doc-spaces
8770: doc-emit
8771: doc-toupper
8772: doc-."
8773: doc-.(
8774: doc-type
1.44 crook 8775: doc-typewhite
1.26 crook 8776: doc-cr
1.27 crook 8777: @cindex cursor control
1.26 crook 8778: doc-at-xy
8779: doc-page
8780: doc-s"
8781: doc-c"
8782: doc-char
8783: doc-[char]
8784:
1.44 crook 8785:
8786: @noindent
1.26 crook 8787: As an example, consider the following text, stored in a file @file{test.fs}:
1.5 anton 8788:
8789: @example
1.26 crook 8790: .( text-1)
8791: : my-word
8792: ." text-2" cr
8793: .( text-3)
8794: ;
8795:
8796: ." text-4"
8797:
8798: : my-char
8799: [char] ALPHABET emit
8800: char emit
8801: ;
1.5 anton 8802: @end example
8803:
1.26 crook 8804: When you load this code into Gforth, the following output is generated:
1.5 anton 8805:
1.26 crook 8806: @example
1.30 anton 8807: @kbd{include test.fs @key{RET}} text-1text-3text-4 ok
1.26 crook 8808: @end example
1.5 anton 8809:
1.26 crook 8810: @itemize @bullet
8811: @item
8812: Messages @code{text-1} and @code{text-3} are displayed because @code{.(}
8813: is an immediate word; it behaves in the same way whether it is used inside
8814: or outside a colon definition.
8815: @item
8816: Message @code{text-4} is displayed because of Gforth's added interpretation
8817: semantics for @code{."}.
8818: @item
1.29 crook 8819: Message @code{text-2} is @i{not} displayed, because the text interpreter
1.26 crook 8820: performs the compilation semantics for @code{."} within the definition of
8821: @code{my-word}.
8822: @end itemize
1.5 anton 8823:
1.26 crook 8824: Here are some examples of executing @code{my-word} and @code{my-char}:
1.5 anton 8825:
1.26 crook 8826: @example
1.30 anton 8827: @kbd{my-word @key{RET}} text-2
1.26 crook 8828: ok
1.30 anton 8829: @kbd{my-char fred @key{RET}} Af ok
8830: @kbd{my-char jim @key{RET}} Aj ok
1.26 crook 8831: @end example
1.5 anton 8832:
8833: @itemize @bullet
8834: @item
1.26 crook 8835: Message @code{text-2} is displayed because of the run-time behaviour of
8836: @code{."}.
8837: @item
8838: @code{[char]} compiles the ``A'' from ``ALPHABET'' and puts its display code
8839: on the stack at run-time. @code{emit} always displays the character
8840: when @code{my-char} is executed.
8841: @item
8842: @code{char} parses a string at run-time and the second @code{emit} displays
8843: the first character of the string.
1.5 anton 8844: @item
1.26 crook 8845: If you type @code{see my-char} you can see that @code{[char]} discarded
8846: the text ``LPHABET'' and only compiled the display code for ``A'' into the
8847: definition of @code{my-char}.
1.5 anton 8848: @end itemize
8849:
8850:
8851:
1.48 anton 8852: @node Input, , Displaying characters and strings, Other I/O
1.26 crook 8853: @subsection Input
8854: @cindex input
1.28 crook 8855: @cindex I/O - see input
8856: @cindex parsing a string
1.5 anton 8857:
1.49 anton 8858: For ways of storing character strings in memory see @ref{String Formats}.
1.5 anton 8859:
1.27 crook 8860: @comment TODO examples for >number >float accept key key? pad parse word refill
1.29 crook 8861: @comment then index them
1.27 crook 8862:
1.44 crook 8863:
1.27 crook 8864: doc-key
8865: doc-key?
1.45 crook 8866: doc-ekey
8867: doc-ekey?
8868: doc-ekey>char
1.26 crook 8869: doc->number
8870: doc->float
8871: doc-accept
1.27 crook 8872: doc-pad
1.75 anton 8873: @c anton: these belong in the input stream section
1.27 crook 8874: doc-parse
8875: doc-word
8876: doc-sword
1.75 anton 8877: doc-name
1.27 crook 8878: doc-refill
8879: @comment obsolescent words..
8880: doc-convert
1.26 crook 8881: doc-query
8882: doc-expect
1.27 crook 8883: doc-span
1.5 anton 8884:
8885:
1.78 anton 8886: @c -------------------------------------------------------------
8887: @node Locals, Structures, Other I/O, Words
8888: @section Locals
8889: @cindex locals
8890:
8891: Local variables can make Forth programming more enjoyable and Forth
8892: programs easier to read. Unfortunately, the locals of ANS Forth are
8893: laden with restrictions. Therefore, we provide not only the ANS Forth
8894: locals wordset, but also our own, more powerful locals wordset (we
8895: implemented the ANS Forth locals wordset through our locals wordset).
1.44 crook 8896:
1.78 anton 8897: The ideas in this section have also been published in M. Anton Ertl,
8898: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl94l.ps.gz,
8899: Automatic Scoping of Local Variables}}, EuroForth '94.
1.12 anton 8900:
8901: @menu
1.78 anton 8902: * Gforth locals::
8903: * ANS Forth locals::
1.5 anton 8904: @end menu
8905:
1.78 anton 8906: @node Gforth locals, ANS Forth locals, Locals, Locals
8907: @subsection Gforth locals
8908: @cindex Gforth locals
8909: @cindex locals, Gforth style
1.5 anton 8910:
1.78 anton 8911: Locals can be defined with
1.44 crook 8912:
1.78 anton 8913: @example
8914: @{ local1 local2 ... -- comment @}
8915: @end example
8916: or
8917: @example
8918: @{ local1 local2 ... @}
8919: @end example
1.5 anton 8920:
1.78 anton 8921: E.g.,
8922: @example
8923: : max @{ n1 n2 -- n3 @}
8924: n1 n2 > if
8925: n1
8926: else
8927: n2
8928: endif ;
8929: @end example
1.44 crook 8930:
1.78 anton 8931: The similarity of locals definitions with stack comments is intended. A
8932: locals definition often replaces the stack comment of a word. The order
8933: of the locals corresponds to the order in a stack comment and everything
8934: after the @code{--} is really a comment.
1.77 anton 8935:
1.78 anton 8936: This similarity has one disadvantage: It is too easy to confuse locals
8937: declarations with stack comments, causing bugs and making them hard to
8938: find. However, this problem can be avoided by appropriate coding
8939: conventions: Do not use both notations in the same program. If you do,
8940: they should be distinguished using additional means, e.g. by position.
1.77 anton 8941:
1.78 anton 8942: @cindex types of locals
8943: @cindex locals types
8944: The name of the local may be preceded by a type specifier, e.g.,
8945: @code{F:} for a floating point value:
1.5 anton 8946:
1.78 anton 8947: @example
8948: : CX* @{ F: Ar F: Ai F: Br F: Bi -- Cr Ci @}
8949: \ complex multiplication
8950: Ar Br f* Ai Bi f* f-
8951: Ar Bi f* Ai Br f* f+ ;
8952: @end example
1.44 crook 8953:
1.78 anton 8954: @cindex flavours of locals
8955: @cindex locals flavours
8956: @cindex value-flavoured locals
8957: @cindex variable-flavoured locals
8958: Gforth currently supports cells (@code{W:}, @code{W^}), doubles
8959: (@code{D:}, @code{D^}), floats (@code{F:}, @code{F^}) and characters
8960: (@code{C:}, @code{C^}) in two flavours: a value-flavoured local (defined
8961: with @code{W:}, @code{D:} etc.) produces its value and can be changed
8962: with @code{TO}. A variable-flavoured local (defined with @code{W^} etc.)
8963: produces its address (which becomes invalid when the variable's scope is
8964: left). E.g., the standard word @code{emit} can be defined in terms of
8965: @code{type} like this:
1.5 anton 8966:
1.78 anton 8967: @example
8968: : emit @{ C^ char* -- @}
8969: char* 1 type ;
8970: @end example
1.5 anton 8971:
1.78 anton 8972: @cindex default type of locals
8973: @cindex locals, default type
8974: A local without type specifier is a @code{W:} local. Both flavours of
8975: locals are initialized with values from the data or FP stack.
1.44 crook 8976:
1.78 anton 8977: Currently there is no way to define locals with user-defined data
8978: structures, but we are working on it.
1.5 anton 8979:
1.78 anton 8980: Gforth allows defining locals everywhere in a colon definition. This
8981: poses the following questions:
1.5 anton 8982:
1.78 anton 8983: @menu
8984: * Where are locals visible by name?::
8985: * How long do locals live?::
8986: * Locals programming style::
8987: * Locals implementation::
8988: @end menu
1.44 crook 8989:
1.78 anton 8990: @node Where are locals visible by name?, How long do locals live?, Gforth locals, Gforth locals
8991: @subsubsection Where are locals visible by name?
8992: @cindex locals visibility
8993: @cindex visibility of locals
8994: @cindex scope of locals
1.5 anton 8995:
1.78 anton 8996: Basically, the answer is that locals are visible where you would expect
8997: it in block-structured languages, and sometimes a little longer. If you
8998: want to restrict the scope of a local, enclose its definition in
8999: @code{SCOPE}...@code{ENDSCOPE}.
1.5 anton 9000:
9001:
1.78 anton 9002: doc-scope
9003: doc-endscope
1.5 anton 9004:
9005:
1.78 anton 9006: These words behave like control structure words, so you can use them
9007: with @code{CS-PICK} and @code{CS-ROLL} to restrict the scope in
9008: arbitrary ways.
1.77 anton 9009:
1.78 anton 9010: If you want a more exact answer to the visibility question, here's the
9011: basic principle: A local is visible in all places that can only be
9012: reached through the definition of the local@footnote{In compiler
9013: construction terminology, all places dominated by the definition of the
9014: local.}. In other words, it is not visible in places that can be reached
9015: without going through the definition of the local. E.g., locals defined
9016: in @code{IF}...@code{ENDIF} are visible until the @code{ENDIF}, locals
9017: defined in @code{BEGIN}...@code{UNTIL} are visible after the
9018: @code{UNTIL} (until, e.g., a subsequent @code{ENDSCOPE}).
1.77 anton 9019:
1.78 anton 9020: The reasoning behind this solution is: We want to have the locals
9021: visible as long as it is meaningful. The user can always make the
9022: visibility shorter by using explicit scoping. In a place that can
9023: only be reached through the definition of a local, the meaning of a
9024: local name is clear. In other places it is not: How is the local
9025: initialized at the control flow path that does not contain the
9026: definition? Which local is meant, if the same name is defined twice in
9027: two independent control flow paths?
1.77 anton 9028:
1.78 anton 9029: This should be enough detail for nearly all users, so you can skip the
9030: rest of this section. If you really must know all the gory details and
9031: options, read on.
1.77 anton 9032:
1.78 anton 9033: In order to implement this rule, the compiler has to know which places
9034: are unreachable. It knows this automatically after @code{AHEAD},
9035: @code{AGAIN}, @code{EXIT} and @code{LEAVE}; in other cases (e.g., after
9036: most @code{THROW}s), you can use the word @code{UNREACHABLE} to tell the
9037: compiler that the control flow never reaches that place. If
9038: @code{UNREACHABLE} is not used where it could, the only consequence is
9039: that the visibility of some locals is more limited than the rule above
9040: says. If @code{UNREACHABLE} is used where it should not (i.e., if you
9041: lie to the compiler), buggy code will be produced.
1.77 anton 9042:
1.5 anton 9043:
1.78 anton 9044: doc-unreachable
1.5 anton 9045:
1.23 crook 9046:
1.78 anton 9047: Another problem with this rule is that at @code{BEGIN}, the compiler
9048: does not know which locals will be visible on the incoming
9049: back-edge. All problems discussed in the following are due to this
9050: ignorance of the compiler (we discuss the problems using @code{BEGIN}
9051: loops as examples; the discussion also applies to @code{?DO} and other
9052: loops). Perhaps the most insidious example is:
1.26 crook 9053: @example
1.78 anton 9054: AHEAD
9055: BEGIN
9056: x
9057: [ 1 CS-ROLL ] THEN
9058: @{ x @}
9059: ...
9060: UNTIL
1.26 crook 9061: @end example
1.23 crook 9062:
1.78 anton 9063: This should be legal according to the visibility rule. The use of
9064: @code{x} can only be reached through the definition; but that appears
9065: textually below the use.
9066:
9067: From this example it is clear that the visibility rules cannot be fully
9068: implemented without major headaches. Our implementation treats common
9069: cases as advertised and the exceptions are treated in a safe way: The
9070: compiler makes a reasonable guess about the locals visible after a
9071: @code{BEGIN}; if it is too pessimistic, the
9072: user will get a spurious error about the local not being defined; if the
9073: compiler is too optimistic, it will notice this later and issue a
9074: warning. In the case above the compiler would complain about @code{x}
9075: being undefined at its use. You can see from the obscure examples in
9076: this section that it takes quite unusual control structures to get the
9077: compiler into trouble, and even then it will often do fine.
1.23 crook 9078:
1.78 anton 9079: If the @code{BEGIN} is reachable from above, the most optimistic guess
9080: is that all locals visible before the @code{BEGIN} will also be
9081: visible after the @code{BEGIN}. This guess is valid for all loops that
9082: are entered only through the @code{BEGIN}, in particular, for normal
9083: @code{BEGIN}...@code{WHILE}...@code{REPEAT} and
9084: @code{BEGIN}...@code{UNTIL} loops and it is implemented in our
9085: compiler. When the branch to the @code{BEGIN} is finally generated by
9086: @code{AGAIN} or @code{UNTIL}, the compiler checks the guess and
9087: warns the user if it was too optimistic:
1.26 crook 9088: @example
1.78 anton 9089: IF
9090: @{ x @}
9091: BEGIN
9092: \ x ?
9093: [ 1 cs-roll ] THEN
9094: ...
9095: UNTIL
1.26 crook 9096: @end example
1.23 crook 9097:
1.78 anton 9098: Here, @code{x} lives only until the @code{BEGIN}, but the compiler
9099: optimistically assumes that it lives until the @code{THEN}. It notices
9100: this difference when it compiles the @code{UNTIL} and issues a
9101: warning. The user can avoid the warning, and make sure that @code{x}
9102: is not used in the wrong area by using explicit scoping:
9103: @example
9104: IF
9105: SCOPE
9106: @{ x @}
9107: ENDSCOPE
9108: BEGIN
9109: [ 1 cs-roll ] THEN
9110: ...
9111: UNTIL
9112: @end example
1.23 crook 9113:
1.78 anton 9114: Since the guess is optimistic, there will be no spurious error messages
9115: about undefined locals.
1.44 crook 9116:
1.78 anton 9117: If the @code{BEGIN} is not reachable from above (e.g., after
9118: @code{AHEAD} or @code{EXIT}), the compiler cannot even make an
9119: optimistic guess, as the locals visible after the @code{BEGIN} may be
9120: defined later. Therefore, the compiler assumes that no locals are
9121: visible after the @code{BEGIN}. However, the user can use
9122: @code{ASSUME-LIVE} to make the compiler assume that the same locals are
9123: visible at the BEGIN as at the point where the top control-flow stack
9124: item was created.
1.23 crook 9125:
1.44 crook 9126:
1.78 anton 9127: doc-assume-live
1.26 crook 9128:
1.23 crook 9129:
1.78 anton 9130: @noindent
9131: E.g.,
9132: @example
9133: @{ x @}
9134: AHEAD
9135: ASSUME-LIVE
9136: BEGIN
9137: x
9138: [ 1 CS-ROLL ] THEN
9139: ...
9140: UNTIL
9141: @end example
1.44 crook 9142:
1.78 anton 9143: Other cases where the locals are defined before the @code{BEGIN} can be
9144: handled by inserting an appropriate @code{CS-ROLL} before the
9145: @code{ASSUME-LIVE} (and changing the control-flow stack manipulation
9146: behind the @code{ASSUME-LIVE}).
1.23 crook 9147:
1.78 anton 9148: Cases where locals are defined after the @code{BEGIN} (but should be
9149: visible immediately after the @code{BEGIN}) can only be handled by
9150: rearranging the loop. E.g., the ``most insidious'' example above can be
9151: arranged into:
9152: @example
9153: BEGIN
9154: @{ x @}
9155: ... 0=
9156: WHILE
9157: x
9158: REPEAT
9159: @end example
1.44 crook 9160:
1.78 anton 9161: @node How long do locals live?, Locals programming style, Where are locals visible by name?, Gforth locals
9162: @subsubsection How long do locals live?
9163: @cindex locals lifetime
9164: @cindex lifetime of locals
1.23 crook 9165:
1.78 anton 9166: The right answer for the lifetime question would be: A local lives at
9167: least as long as it can be accessed. For a value-flavoured local this
9168: means: until the end of its visibility. However, a variable-flavoured
9169: local could be accessed through its address far beyond its visibility
9170: scope. Ultimately, this would mean that such locals would have to be
9171: garbage collected. Since this entails un-Forth-like implementation
9172: complexities, I adopted the same cowardly solution as some other
9173: languages (e.g., C): The local lives only as long as it is visible;
9174: afterwards its address is invalid (and programs that access it
9175: afterwards are erroneous).
1.23 crook 9176:
1.78 anton 9177: @node Locals programming style, Locals implementation, How long do locals live?, Gforth locals
9178: @subsubsection Locals programming style
9179: @cindex locals programming style
9180: @cindex programming style, locals
1.23 crook 9181:
1.78 anton 9182: The freedom to define locals anywhere has the potential to change
9183: programming styles dramatically. In particular, the need to use the
9184: return stack for intermediate storage vanishes. Moreover, all stack
9185: manipulations (except @code{PICK}s and @code{ROLL}s with run-time
9186: determined arguments) can be eliminated: If the stack items are in the
9187: wrong order, just write a locals definition for all of them; then
9188: write the items in the order you want.
1.23 crook 9189:
1.78 anton 9190: This seems a little far-fetched and eliminating stack manipulations is
9191: unlikely to become a conscious programming objective. Still, the number
9192: of stack manipulations will be reduced dramatically if local variables
9193: are used liberally (e.g., compare @code{max} (@pxref{Gforth locals}) with
9194: a traditional implementation of @code{max}).
1.23 crook 9195:
1.78 anton 9196: This shows one potential benefit of locals: making Forth programs more
9197: readable. Of course, this benefit will only be realized if the
9198: programmers continue to honour the principle of factoring instead of
9199: using the added latitude to make the words longer.
1.23 crook 9200:
1.78 anton 9201: @cindex single-assignment style for locals
9202: Using @code{TO} can and should be avoided. Without @code{TO},
9203: every value-flavoured local has only a single assignment and many
9204: advantages of functional languages apply to Forth. I.e., programs are
9205: easier to analyse, to optimize and to read: It is clear from the
9206: definition what the local stands for, it does not turn into something
9207: different later.
1.23 crook 9208:
1.78 anton 9209: E.g., a definition using @code{TO} might look like this:
9210: @example
9211: : strcmp @{ addr1 u1 addr2 u2 -- n @}
9212: u1 u2 min 0
9213: ?do
9214: addr1 c@@ addr2 c@@ -
9215: ?dup-if
9216: unloop exit
9217: then
9218: addr1 char+ TO addr1
9219: addr2 char+ TO addr2
9220: loop
9221: u1 u2 - ;
1.26 crook 9222: @end example
1.78 anton 9223: Here, @code{TO} is used to update @code{addr1} and @code{addr2} at
9224: every loop iteration. @code{strcmp} is a typical example of the
9225: readability problems of using @code{TO}. When you start reading
9226: @code{strcmp}, you think that @code{addr1} refers to the start of the
9227: string. Only near the end of the loop you realize that it is something
9228: else.
1.23 crook 9229:
1.78 anton 9230: This can be avoided by defining two locals at the start of the loop that
9231: are initialized with the right value for the current iteration.
9232: @example
9233: : strcmp @{ addr1 u1 addr2 u2 -- n @}
9234: addr1 addr2
9235: u1 u2 min 0
9236: ?do @{ s1 s2 @}
9237: s1 c@@ s2 c@@ -
9238: ?dup-if
9239: unloop exit
9240: then
9241: s1 char+ s2 char+
9242: loop
9243: 2drop
9244: u1 u2 - ;
9245: @end example
9246: Here it is clear from the start that @code{s1} has a different value
9247: in every loop iteration.
1.23 crook 9248:
1.78 anton 9249: @node Locals implementation, , Locals programming style, Gforth locals
9250: @subsubsection Locals implementation
9251: @cindex locals implementation
9252: @cindex implementation of locals
1.23 crook 9253:
1.78 anton 9254: @cindex locals stack
9255: Gforth uses an extra locals stack. The most compelling reason for
9256: this is that the return stack is not float-aligned; using an extra stack
9257: also eliminates the problems and restrictions of using the return stack
9258: as locals stack. Like the other stacks, the locals stack grows toward
9259: lower addresses. A few primitives allow an efficient implementation:
9260:
9261:
9262: doc-@local#
9263: doc-f@local#
9264: doc-laddr#
9265: doc-lp+!#
9266: doc-lp!
9267: doc->l
9268: doc-f>l
9269:
9270:
9271: In addition to these primitives, some specializations of these
9272: primitives for commonly occurring inline arguments are provided for
9273: efficiency reasons, e.g., @code{@@local0} as specialization of
9274: @code{@@local#} for the inline argument 0. The following compiling words
9275: compile the right specialized version, or the general version, as
9276: appropriate:
1.23 crook 9277:
1.5 anton 9278:
1.78 anton 9279: doc-compile-@local
9280: doc-compile-f@local
9281: doc-compile-lp+!
1.5 anton 9282:
9283:
1.78 anton 9284: Combinations of conditional branches and @code{lp+!#} like
9285: @code{?branch-lp+!#} (the locals pointer is only changed if the branch
9286: is taken) are provided for efficiency and correctness in loops.
1.5 anton 9287:
1.78 anton 9288: A special area in the dictionary space is reserved for keeping the
9289: local variable names. @code{@{} switches the dictionary pointer to this
9290: area and @code{@}} switches it back and generates the locals
9291: initializing code. @code{W:} etc.@ are normal defining words. This
9292: special area is cleared at the start of every colon definition.
1.5 anton 9293:
1.78 anton 9294: @cindex word list for defining locals
9295: A special feature of Gforth's dictionary is used to implement the
9296: definition of locals without type specifiers: every word list (aka
9297: vocabulary) has its own methods for searching
9298: etc. (@pxref{Word Lists}). For the present purpose we defined a word list
9299: with a special search method: When it is searched for a word, it
9300: actually creates that word using @code{W:}. @code{@{} changes the search
9301: order to first search the word list containing @code{@}}, @code{W:} etc.,
9302: and then the word list for defining locals without type specifiers.
1.5 anton 9303:
1.78 anton 9304: The lifetime rules support a stack discipline within a colon
9305: definition: The lifetime of a local is either nested with other locals
9306: lifetimes or it does not overlap them.
1.23 crook 9307:
1.78 anton 9308: At @code{BEGIN}, @code{IF}, and @code{AHEAD} no code for locals stack
9309: pointer manipulation is generated. Between control structure words
9310: locals definitions can push locals onto the locals stack. @code{AGAIN}
9311: is the simplest of the other three control flow words. It has to
9312: restore the locals stack depth of the corresponding @code{BEGIN}
9313: before branching. The code looks like this:
9314: @format
9315: @code{lp+!#} current-locals-size @minus{} dest-locals-size
9316: @code{branch} <begin>
9317: @end format
1.26 crook 9318:
1.78 anton 9319: @code{UNTIL} is a little more complicated: If it branches back, it
9320: must adjust the stack just like @code{AGAIN}. But if it falls through,
9321: the locals stack must not be changed. The compiler generates the
9322: following code:
9323: @format
9324: @code{?branch-lp+!#} <begin> current-locals-size @minus{} dest-locals-size
9325: @end format
9326: The locals stack pointer is only adjusted if the branch is taken.
1.44 crook 9327:
1.78 anton 9328: @code{THEN} can produce somewhat inefficient code:
9329: @format
9330: @code{lp+!#} current-locals-size @minus{} orig-locals-size
9331: <orig target>:
9332: @code{lp+!#} orig-locals-size @minus{} new-locals-size
9333: @end format
9334: The second @code{lp+!#} adjusts the locals stack pointer from the
9335: level at the @i{orig} point to the level after the @code{THEN}. The
9336: first @code{lp+!#} adjusts the locals stack pointer from the current
9337: level to the level at the orig point, so the complete effect is an
9338: adjustment from the current level to the right level after the
9339: @code{THEN}.
1.26 crook 9340:
1.78 anton 9341: @cindex locals information on the control-flow stack
9342: @cindex control-flow stack items, locals information
9343: In a conventional Forth implementation a dest control-flow stack entry
9344: is just the target address and an orig entry is just the address to be
9345: patched. Our locals implementation adds a word list to every orig or dest
9346: item. It is the list of locals visible (or assumed visible) at the point
9347: described by the entry. Our implementation also adds a tag to identify
9348: the kind of entry, in particular to differentiate between live and dead
9349: (reachable and unreachable) orig entries.
1.26 crook 9350:
1.78 anton 9351: A few unusual operations have to be performed on locals word lists:
1.44 crook 9352:
1.5 anton 9353:
1.78 anton 9354: doc-common-list
9355: doc-sub-list?
9356: doc-list-size
1.52 anton 9357:
9358:
1.78 anton 9359: Several features of our locals word list implementation make these
9360: operations easy to implement: The locals word lists are organised as
9361: linked lists; the tails of these lists are shared, if the lists
9362: contain some of the same locals; and the address of a name is greater
9363: than the address of the names behind it in the list.
1.5 anton 9364:
1.78 anton 9365: Another important implementation detail is the variable
9366: @code{dead-code}. It is used by @code{BEGIN} and @code{THEN} to
9367: determine if they can be reached directly or only through the branch
9368: that they resolve. @code{dead-code} is set by @code{UNREACHABLE},
9369: @code{AHEAD}, @code{EXIT} etc., and cleared at the start of a colon
9370: definition, by @code{BEGIN} and usually by @code{THEN}.
1.5 anton 9371:
1.78 anton 9372: Counted loops are similar to other loops in most respects, but
9373: @code{LEAVE} requires special attention: It performs basically the same
9374: service as @code{AHEAD}, but it does not create a control-flow stack
9375: entry. Therefore the information has to be stored elsewhere;
9376: traditionally, the information was stored in the target fields of the
9377: branches created by the @code{LEAVE}s, by organizing these fields into a
9378: linked list. Unfortunately, this clever trick does not provide enough
9379: space for storing our extended control flow information. Therefore, we
9380: introduce another stack, the leave stack. It contains the control-flow
9381: stack entries for all unresolved @code{LEAVE}s.
1.44 crook 9382:
1.78 anton 9383: Local names are kept until the end of the colon definition, even if
9384: they are no longer visible in any control-flow path. In a few cases
9385: this may lead to increased space needs for the locals name area, but
9386: usually less than reclaiming this space would cost in code size.
1.5 anton 9387:
1.44 crook 9388:
1.78 anton 9389: @node ANS Forth locals, , Gforth locals, Locals
9390: @subsection ANS Forth locals
9391: @cindex locals, ANS Forth style
1.5 anton 9392:
1.78 anton 9393: The ANS Forth locals wordset does not define a syntax for locals, but
9394: words that make it possible to define various syntaxes. One of the
9395: possible syntaxes is a subset of the syntax we used in the Gforth locals
9396: wordset, i.e.:
1.29 crook 9397:
9398: @example
1.78 anton 9399: @{ local1 local2 ... -- comment @}
9400: @end example
9401: @noindent
9402: or
9403: @example
9404: @{ local1 local2 ... @}
1.29 crook 9405: @end example
9406:
1.78 anton 9407: The order of the locals corresponds to the order in a stack comment. The
9408: restrictions are:
1.5 anton 9409:
1.78 anton 9410: @itemize @bullet
9411: @item
9412: Locals can only be cell-sized values (no type specifiers are allowed).
9413: @item
9414: Locals can be defined only outside control structures.
9415: @item
9416: Locals can interfere with explicit usage of the return stack. For the
9417: exact (and long) rules, see the standard. If you don't use return stack
9418: accessing words in a definition using locals, you will be all right. The
9419: purpose of this rule is to make locals implementation on the return
9420: stack easier.
9421: @item
9422: The whole definition must be in one line.
9423: @end itemize
1.5 anton 9424:
1.78 anton 9425: Locals defined in ANS Forth behave like @code{VALUE}s
9426: (@pxref{Values}). I.e., they are initialized from the stack. Using their
9427: name produces their value. Their value can be changed using @code{TO}.
1.77 anton 9428:
1.78 anton 9429: Since the syntax above is supported by Gforth directly, you need not do
9430: anything to use it. If you want to port a program using this syntax to
9431: another ANS Forth system, use @file{compat/anslocal.fs} to implement the
9432: syntax on the other system.
1.5 anton 9433:
1.78 anton 9434: Note that a syntax shown in the standard, section A.13 looks
9435: similar, but is quite different in having the order of locals
9436: reversed. Beware!
1.5 anton 9437:
1.78 anton 9438: The ANS Forth locals wordset itself consists of one word:
1.5 anton 9439:
1.78 anton 9440: doc-(local)
1.5 anton 9441:
1.78 anton 9442: The ANS Forth locals extension wordset defines a syntax using
9443: @code{locals|}, but it is so awful that we strongly recommend not to use
9444: it. We have implemented this syntax to make porting to Gforth easy, but
9445: do not document it here. The problem with this syntax is that the locals
9446: are defined in an order reversed with respect to the standard stack
9447: comment notation, making programs harder to read, and easier to misread
9448: and miswrite. The only merit of this syntax is that it is easy to
9449: implement using the ANS Forth locals wordset.
1.53 anton 9450:
9451:
1.78 anton 9452: @c ----------------------------------------------------------
9453: @node Structures, Object-oriented Forth, Locals, Words
9454: @section Structures
9455: @cindex structures
9456: @cindex records
1.53 anton 9457:
1.78 anton 9458: This section presents the structure package that comes with Gforth. A
9459: version of the package implemented in ANS Forth is available in
9460: @file{compat/struct.fs}. This package was inspired by a posting on
9461: comp.lang.forth in 1989 (unfortunately I don't remember, by whom;
9462: possibly John Hayes). A version of this section has been published in
9463: M. Anton Ertl,
9464: @uref{http://www.complang.tuwien.ac.at/forth/objects/structs.html, Yet
9465: Another Forth Structures Package}, Forth Dimensions 19(3), pages
9466: 13--16. Marcel Hendrix provided helpful comments.
1.53 anton 9467:
1.78 anton 9468: @menu
9469: * Why explicit structure support?::
9470: * Structure Usage::
9471: * Structure Naming Convention::
9472: * Structure Implementation::
9473: * Structure Glossary::
9474: @end menu
1.55 anton 9475:
1.78 anton 9476: @node Why explicit structure support?, Structure Usage, Structures, Structures
9477: @subsection Why explicit structure support?
1.53 anton 9478:
1.78 anton 9479: @cindex address arithmetic for structures
9480: @cindex structures using address arithmetic
9481: If we want to use a structure containing several fields, we could simply
9482: reserve memory for it, and access the fields using address arithmetic
9483: (@pxref{Address arithmetic}). As an example, consider a structure with
9484: the following fields
1.57 anton 9485:
1.78 anton 9486: @table @code
9487: @item a
9488: is a float
9489: @item b
9490: is a cell
9491: @item c
9492: is a float
9493: @end table
1.57 anton 9494:
1.78 anton 9495: Given the (float-aligned) base address of the structure we get the
9496: address of the field
1.52 anton 9497:
1.78 anton 9498: @table @code
9499: @item a
9500: without doing anything further.
9501: @item b
9502: with @code{float+}
9503: @item c
9504: with @code{float+ cell+ faligned}
9505: @end table
1.52 anton 9506:
1.78 anton 9507: It is easy to see that this can become quite tiring.
1.52 anton 9508:
1.78 anton 9509: Moreover, it is not very readable, because seeing a
9510: @code{cell+} tells us neither which kind of structure is
9511: accessed nor what field is accessed; we have to somehow infer the kind
9512: of structure, and then look up in the documentation, which field of
9513: that structure corresponds to that offset.
1.53 anton 9514:
1.78 anton 9515: Finally, this kind of address arithmetic also causes maintenance
9516: troubles: If you add or delete a field somewhere in the middle of the
9517: structure, you have to find and change all computations for the fields
9518: afterwards.
1.52 anton 9519:
1.78 anton 9520: So, instead of using @code{cell+} and friends directly, how
9521: about storing the offsets in constants:
1.52 anton 9522:
1.78 anton 9523: @example
9524: 0 constant a-offset
9525: 0 float+ constant b-offset
9526: 0 float+ cell+ faligned c-offset
9527: @end example
1.64 pazsan 9528:
1.78 anton 9529: Now we can get the address of field @code{x} with @code{x-offset
9530: +}. This is much better in all respects. Of course, you still
9531: have to change all later offset definitions if you add a field. You can
9532: fix this by declaring the offsets in the following way:
1.57 anton 9533:
1.78 anton 9534: @example
9535: 0 constant a-offset
9536: a-offset float+ constant b-offset
9537: b-offset cell+ faligned constant c-offset
9538: @end example
1.57 anton 9539:
1.78 anton 9540: Since we always use the offsets with @code{+}, we could use a defining
9541: word @code{cfield} that includes the @code{+} in the action of the
9542: defined word:
1.64 pazsan 9543:
1.78 anton 9544: @example
9545: : cfield ( n "name" -- )
9546: create ,
9547: does> ( name execution: addr1 -- addr2 )
9548: @@ + ;
1.64 pazsan 9549:
1.78 anton 9550: 0 cfield a
9551: 0 a float+ cfield b
9552: 0 b cell+ faligned cfield c
9553: @end example
1.64 pazsan 9554:
1.78 anton 9555: Instead of @code{x-offset +}, we now simply write @code{x}.
1.64 pazsan 9556:
1.78 anton 9557: The structure field words now can be used quite nicely. However,
9558: their definition is still a bit cumbersome: We have to repeat the
9559: name, the information about size and alignment is distributed before
9560: and after the field definitions etc. The structure package presented
9561: here addresses these problems.
1.64 pazsan 9562:
1.78 anton 9563: @node Structure Usage, Structure Naming Convention, Why explicit structure support?, Structures
9564: @subsection Structure Usage
9565: @cindex structure usage
1.57 anton 9566:
1.78 anton 9567: @cindex @code{field} usage
9568: @cindex @code{struct} usage
9569: @cindex @code{end-struct} usage
9570: You can define a structure for a (data-less) linked list with:
1.57 anton 9571: @example
1.78 anton 9572: struct
9573: cell% field list-next
9574: end-struct list%
1.57 anton 9575: @end example
9576:
1.78 anton 9577: With the address of the list node on the stack, you can compute the
9578: address of the field that contains the address of the next node with
9579: @code{list-next}. E.g., you can determine the length of a list
9580: with:
1.57 anton 9581:
9582: @example
1.78 anton 9583: : list-length ( list -- n )
9584: \ "list" is a pointer to the first element of a linked list
9585: \ "n" is the length of the list
9586: 0 BEGIN ( list1 n1 )
9587: over
9588: WHILE ( list1 n1 )
9589: 1+ swap list-next @@ swap
9590: REPEAT
9591: nip ;
1.57 anton 9592: @end example
9593:
1.78 anton 9594: You can reserve memory for a list node in the dictionary with
9595: @code{list% %allot}, which leaves the address of the list node on the
9596: stack. For the equivalent allocation on the heap you can use @code{list%
9597: %alloc} (or, for an @code{allocate}-like stack effect (i.e., with ior),
9598: use @code{list% %allocate}). You can get the the size of a list
9599: node with @code{list% %size} and its alignment with @code{list%
9600: %alignment}.
9601:
9602: Note that in ANS Forth the body of a @code{create}d word is
9603: @code{aligned} but not necessarily @code{faligned};
9604: therefore, if you do a:
1.57 anton 9605:
9606: @example
1.78 anton 9607: create @emph{name} foo% %allot drop
1.57 anton 9608: @end example
9609:
1.78 anton 9610: @noindent
9611: then the memory alloted for @code{foo%} is guaranteed to start at the
9612: body of @code{@emph{name}} only if @code{foo%} contains only character,
9613: cell and double fields. Therefore, if your structure contains floats,
9614: better use
1.57 anton 9615:
9616: @example
1.78 anton 9617: foo% %allot constant @emph{name}
1.57 anton 9618: @end example
9619:
1.78 anton 9620: @cindex structures containing structures
9621: You can include a structure @code{foo%} as a field of
9622: another structure, like this:
1.65 anton 9623: @example
1.78 anton 9624: struct
9625: ...
9626: foo% field ...
9627: ...
9628: end-struct ...
1.65 anton 9629: @end example
1.52 anton 9630:
1.78 anton 9631: @cindex structure extension
9632: @cindex extended records
9633: Instead of starting with an empty structure, you can extend an
9634: existing structure. E.g., a plain linked list without data, as defined
9635: above, is hardly useful; You can extend it to a linked list of integers,
9636: like this:@footnote{This feature is also known as @emph{extended
9637: records}. It is the main innovation in the Oberon language; in other
9638: words, adding this feature to Modula-2 led Wirth to create a new
9639: language, write a new compiler etc. Adding this feature to Forth just
9640: required a few lines of code.}
1.52 anton 9641:
1.78 anton 9642: @example
9643: list%
9644: cell% field intlist-int
9645: end-struct intlist%
9646: @end example
1.55 anton 9647:
1.78 anton 9648: @code{intlist%} is a structure with two fields:
9649: @code{list-next} and @code{intlist-int}.
1.55 anton 9650:
1.78 anton 9651: @cindex structures containing arrays
9652: You can specify an array type containing @emph{n} elements of
9653: type @code{foo%} like this:
1.55 anton 9654:
9655: @example
1.78 anton 9656: foo% @emph{n} *
1.56 anton 9657: @end example
1.55 anton 9658:
1.78 anton 9659: You can use this array type in any place where you can use a normal
9660: type, e.g., when defining a @code{field}, or with
9661: @code{%allot}.
9662:
9663: @cindex first field optimization
9664: The first field is at the base address of a structure and the word for
9665: this field (e.g., @code{list-next}) actually does not change the address
9666: on the stack. You may be tempted to leave it away in the interest of
9667: run-time and space efficiency. This is not necessary, because the
9668: structure package optimizes this case: If you compile a first-field
9669: words, no code is generated. So, in the interest of readability and
9670: maintainability you should include the word for the field when accessing
9671: the field.
1.52 anton 9672:
9673:
1.78 anton 9674: @node Structure Naming Convention, Structure Implementation, Structure Usage, Structures
9675: @subsection Structure Naming Convention
9676: @cindex structure naming convention
1.52 anton 9677:
1.78 anton 9678: The field names that come to (my) mind are often quite generic, and,
9679: if used, would cause frequent name clashes. E.g., many structures
9680: probably contain a @code{counter} field. The structure names
9681: that come to (my) mind are often also the logical choice for the names
9682: of words that create such a structure.
1.52 anton 9683:
1.78 anton 9684: Therefore, I have adopted the following naming conventions:
1.52 anton 9685:
1.78 anton 9686: @itemize @bullet
9687: @cindex field naming convention
9688: @item
9689: The names of fields are of the form
9690: @code{@emph{struct}-@emph{field}}, where
9691: @code{@emph{struct}} is the basic name of the structure, and
9692: @code{@emph{field}} is the basic name of the field. You can
9693: think of field words as converting the (address of the)
9694: structure into the (address of the) field.
1.52 anton 9695:
1.78 anton 9696: @cindex structure naming convention
9697: @item
9698: The names of structures are of the form
9699: @code{@emph{struct}%}, where
9700: @code{@emph{struct}} is the basic name of the structure.
9701: @end itemize
1.52 anton 9702:
1.78 anton 9703: This naming convention does not work that well for fields of extended
9704: structures; e.g., the integer list structure has a field
9705: @code{intlist-int}, but has @code{list-next}, not
9706: @code{intlist-next}.
1.53 anton 9707:
1.78 anton 9708: @node Structure Implementation, Structure Glossary, Structure Naming Convention, Structures
9709: @subsection Structure Implementation
9710: @cindex structure implementation
9711: @cindex implementation of structures
1.52 anton 9712:
1.78 anton 9713: The central idea in the implementation is to pass the data about the
9714: structure being built on the stack, not in some global
9715: variable. Everything else falls into place naturally once this design
9716: decision is made.
1.53 anton 9717:
1.78 anton 9718: The type description on the stack is of the form @emph{align
9719: size}. Keeping the size on the top-of-stack makes dealing with arrays
9720: very simple.
1.53 anton 9721:
1.78 anton 9722: @code{field} is a defining word that uses @code{Create}
9723: and @code{DOES>}. The body of the field contains the offset
9724: of the field, and the normal @code{DOES>} action is simply:
1.53 anton 9725:
9726: @example
1.78 anton 9727: @@ +
1.53 anton 9728: @end example
9729:
1.78 anton 9730: @noindent
9731: i.e., add the offset to the address, giving the stack effect
9732: @i{addr1 -- addr2} for a field.
9733:
9734: @cindex first field optimization, implementation
9735: This simple structure is slightly complicated by the optimization
9736: for fields with offset 0, which requires a different
9737: @code{DOES>}-part (because we cannot rely on there being
9738: something on the stack if such a field is invoked during
9739: compilation). Therefore, we put the different @code{DOES>}-parts
9740: in separate words, and decide which one to invoke based on the
9741: offset. For a zero offset, the field is basically a noop; it is
9742: immediate, and therefore no code is generated when it is compiled.
1.53 anton 9743:
1.78 anton 9744: @node Structure Glossary, , Structure Implementation, Structures
9745: @subsection Structure Glossary
9746: @cindex structure glossary
1.53 anton 9747:
1.5 anton 9748:
1.78 anton 9749: doc-%align
9750: doc-%alignment
9751: doc-%alloc
9752: doc-%allocate
9753: doc-%allot
9754: doc-cell%
9755: doc-char%
9756: doc-dfloat%
9757: doc-double%
9758: doc-end-struct
9759: doc-field
9760: doc-float%
9761: doc-naligned
9762: doc-sfloat%
9763: doc-%size
9764: doc-struct
1.54 anton 9765:
9766:
1.26 crook 9767: @c -------------------------------------------------------------
1.78 anton 9768: @node Object-oriented Forth, Programming Tools, Structures, Words
9769: @section Object-oriented Forth
9770:
9771: Gforth comes with three packages for object-oriented programming:
9772: @file{objects.fs}, @file{oof.fs}, and @file{mini-oof.fs}; none of them
9773: is preloaded, so you have to @code{include} them before use. The most
9774: important differences between these packages (and others) are discussed
9775: in @ref{Comparison with other object models}. All packages are written
9776: in ANS Forth and can be used with any other ANS Forth.
1.5 anton 9777:
1.78 anton 9778: @menu
9779: * Why object-oriented programming?::
9780: * Object-Oriented Terminology::
9781: * Objects::
9782: * OOF::
9783: * Mini-OOF::
9784: * Comparison with other object models::
9785: @end menu
1.5 anton 9786:
1.78 anton 9787: @c ----------------------------------------------------------------
9788: @node Why object-oriented programming?, Object-Oriented Terminology, Object-oriented Forth, Object-oriented Forth
9789: @subsection Why object-oriented programming?
9790: @cindex object-oriented programming motivation
9791: @cindex motivation for object-oriented programming
1.44 crook 9792:
1.78 anton 9793: Often we have to deal with several data structures (@emph{objects}),
9794: that have to be treated similarly in some respects, but differently in
9795: others. Graphical objects are the textbook example: circles, triangles,
9796: dinosaurs, icons, and others, and we may want to add more during program
9797: development. We want to apply some operations to any graphical object,
9798: e.g., @code{draw} for displaying it on the screen. However, @code{draw}
9799: has to do something different for every kind of object.
9800: @comment TODO add some other operations eg perimeter, area
9801: @comment and tie in to concrete examples later..
1.5 anton 9802:
1.78 anton 9803: We could implement @code{draw} as a big @code{CASE}
9804: control structure that executes the appropriate code depending on the
9805: kind of object to be drawn. This would be not be very elegant, and,
9806: moreover, we would have to change @code{draw} every time we add
9807: a new kind of graphical object (say, a spaceship).
1.44 crook 9808:
1.78 anton 9809: What we would rather do is: When defining spaceships, we would tell
9810: the system: ``Here's how you @code{draw} a spaceship; you figure
9811: out the rest''.
1.5 anton 9812:
1.78 anton 9813: This is the problem that all systems solve that (rightfully) call
9814: themselves object-oriented; the object-oriented packages presented here
9815: solve this problem (and not much else).
9816: @comment TODO ?list properties of oo systems.. oo vs o-based?
1.44 crook 9817:
1.78 anton 9818: @c ------------------------------------------------------------------------
9819: @node Object-Oriented Terminology, Objects, Why object-oriented programming?, Object-oriented Forth
9820: @subsection Object-Oriented Terminology
9821: @cindex object-oriented terminology
9822: @cindex terminology for object-oriented programming
1.5 anton 9823:
1.78 anton 9824: This section is mainly for reference, so you don't have to understand
9825: all of it right away. The terminology is mainly Smalltalk-inspired. In
9826: short:
1.44 crook 9827:
1.78 anton 9828: @table @emph
9829: @cindex class
9830: @item class
9831: a data structure definition with some extras.
1.5 anton 9832:
1.78 anton 9833: @cindex object
9834: @item object
9835: an instance of the data structure described by the class definition.
1.5 anton 9836:
1.78 anton 9837: @cindex instance variables
9838: @item instance variables
9839: fields of the data structure.
1.5 anton 9840:
1.78 anton 9841: @cindex selector
9842: @cindex method selector
9843: @cindex virtual function
9844: @item selector
9845: (or @emph{method selector}) a word (e.g.,
9846: @code{draw}) that performs an operation on a variety of data
9847: structures (classes). A selector describes @emph{what} operation to
9848: perform. In C++ terminology: a (pure) virtual function.
1.5 anton 9849:
1.78 anton 9850: @cindex method
9851: @item method
9852: the concrete definition that performs the operation
9853: described by the selector for a specific class. A method specifies
9854: @emph{how} the operation is performed for a specific class.
1.5 anton 9855:
1.78 anton 9856: @cindex selector invocation
9857: @cindex message send
9858: @cindex invoking a selector
9859: @item selector invocation
9860: a call of a selector. One argument of the call (the TOS (top-of-stack))
9861: is used for determining which method is used. In Smalltalk terminology:
9862: a message (consisting of the selector and the other arguments) is sent
9863: to the object.
1.5 anton 9864:
1.78 anton 9865: @cindex receiving object
9866: @item receiving object
9867: the object used for determining the method executed by a selector
9868: invocation. In the @file{objects.fs} model, it is the object that is on
9869: the TOS when the selector is invoked. (@emph{Receiving} comes from
9870: the Smalltalk @emph{message} terminology.)
1.5 anton 9871:
1.78 anton 9872: @cindex child class
9873: @cindex parent class
9874: @cindex inheritance
9875: @item child class
9876: a class that has (@emph{inherits}) all properties (instance variables,
9877: selectors, methods) from a @emph{parent class}. In Smalltalk
9878: terminology: The subclass inherits from the superclass. In C++
9879: terminology: The derived class inherits from the base class.
1.5 anton 9880:
1.78 anton 9881: @end table
1.5 anton 9882:
1.78 anton 9883: @c If you wonder about the message sending terminology, it comes from
9884: @c a time when each object had it's own task and objects communicated via
9885: @c message passing; eventually the Smalltalk developers realized that
9886: @c they can do most things through simple (indirect) calls. They kept the
9887: @c terminology.
1.5 anton 9888:
1.78 anton 9889: @c --------------------------------------------------------------
9890: @node Objects, OOF, Object-Oriented Terminology, Object-oriented Forth
9891: @subsection The @file{objects.fs} model
9892: @cindex objects
9893: @cindex object-oriented programming
1.26 crook 9894:
1.78 anton 9895: @cindex @file{objects.fs}
9896: @cindex @file{oof.fs}
1.26 crook 9897:
1.78 anton 9898: This section describes the @file{objects.fs} package. This material also
9899: has been published in M. Anton Ertl,
9900: @cite{@uref{http://www.complang.tuwien.ac.at/forth/objects/objects.html,
9901: Yet Another Forth Objects Package}}, Forth Dimensions 19(2), pages
9902: 37--43.
9903: @c McKewan's and Zsoter's packages
1.26 crook 9904:
1.78 anton 9905: This section assumes that you have read @ref{Structures}.
1.5 anton 9906:
1.78 anton 9907: The techniques on which this model is based have been used to implement
9908: the parser generator, Gray, and have also been used in Gforth for
9909: implementing the various flavours of word lists (hashed or not,
9910: case-sensitive or not, special-purpose word lists for locals etc.).
1.5 anton 9911:
9912:
1.26 crook 9913: @menu
1.78 anton 9914: * Properties of the Objects model::
9915: * Basic Objects Usage::
9916: * The Objects base class::
9917: * Creating objects::
9918: * Object-Oriented Programming Style::
9919: * Class Binding::
9920: * Method conveniences::
9921: * Classes and Scoping::
9922: * Dividing classes::
9923: * Object Interfaces::
9924: * Objects Implementation::
9925: * Objects Glossary::
1.26 crook 9926: @end menu
1.5 anton 9927:
1.78 anton 9928: Marcel Hendrix provided helpful comments on this section.
1.5 anton 9929:
1.78 anton 9930: @node Properties of the Objects model, Basic Objects Usage, Objects, Objects
9931: @subsubsection Properties of the @file{objects.fs} model
9932: @cindex @file{objects.fs} properties
1.5 anton 9933:
1.78 anton 9934: @itemize @bullet
9935: @item
9936: It is straightforward to pass objects on the stack. Passing
9937: selectors on the stack is a little less convenient, but possible.
1.44 crook 9938:
1.78 anton 9939: @item
9940: Objects are just data structures in memory, and are referenced by their
9941: address. You can create words for objects with normal defining words
9942: like @code{constant}. Likewise, there is no difference between instance
9943: variables that contain objects and those that contain other data.
1.5 anton 9944:
1.78 anton 9945: @item
9946: Late binding is efficient and easy to use.
1.44 crook 9947:
1.78 anton 9948: @item
9949: It avoids parsing, and thus avoids problems with state-smartness
9950: and reduced extensibility; for convenience there are a few parsing
9951: words, but they have non-parsing counterparts. There are also a few
9952: defining words that parse. This is hard to avoid, because all standard
9953: defining words parse (except @code{:noname}); however, such
9954: words are not as bad as many other parsing words, because they are not
9955: state-smart.
1.5 anton 9956:
1.78 anton 9957: @item
9958: It does not try to incorporate everything. It does a few things and does
9959: them well (IMO). In particular, this model was not designed to support
9960: information hiding (although it has features that may help); you can use
9961: a separate package for achieving this.
1.5 anton 9962:
1.78 anton 9963: @item
9964: It is layered; you don't have to learn and use all features to use this
9965: model. Only a few features are necessary (@pxref{Basic Objects Usage},
9966: @pxref{The Objects base class}, @pxref{Creating objects}.), the others
9967: are optional and independent of each other.
1.5 anton 9968:
1.78 anton 9969: @item
9970: An implementation in ANS Forth is available.
1.5 anton 9971:
1.78 anton 9972: @end itemize
1.5 anton 9973:
1.44 crook 9974:
1.78 anton 9975: @node Basic Objects Usage, The Objects base class, Properties of the Objects model, Objects
9976: @subsubsection Basic @file{objects.fs} Usage
9977: @cindex basic objects usage
9978: @cindex objects, basic usage
1.5 anton 9979:
1.78 anton 9980: You can define a class for graphical objects like this:
1.44 crook 9981:
1.78 anton 9982: @cindex @code{class} usage
9983: @cindex @code{end-class} usage
9984: @cindex @code{selector} usage
1.5 anton 9985: @example
1.78 anton 9986: object class \ "object" is the parent class
9987: selector draw ( x y graphical -- )
9988: end-class graphical
9989: @end example
9990:
9991: This code defines a class @code{graphical} with an
9992: operation @code{draw}. We can perform the operation
9993: @code{draw} on any @code{graphical} object, e.g.:
9994:
9995: @example
9996: 100 100 t-rex draw
1.26 crook 9997: @end example
1.5 anton 9998:
1.78 anton 9999: @noindent
10000: where @code{t-rex} is a word (say, a constant) that produces a
10001: graphical object.
10002:
10003: @comment TODO add a 2nd operation eg perimeter.. and use for
10004: @comment a concrete example
1.5 anton 10005:
1.78 anton 10006: @cindex abstract class
10007: How do we create a graphical object? With the present definitions,
10008: we cannot create a useful graphical object. The class
10009: @code{graphical} describes graphical objects in general, but not
10010: any concrete graphical object type (C++ users would call it an
10011: @emph{abstract class}); e.g., there is no method for the selector
10012: @code{draw} in the class @code{graphical}.
1.5 anton 10013:
1.78 anton 10014: For concrete graphical objects, we define child classes of the
10015: class @code{graphical}, e.g.:
1.5 anton 10016:
1.78 anton 10017: @cindex @code{overrides} usage
10018: @cindex @code{field} usage in class definition
1.26 crook 10019: @example
1.78 anton 10020: graphical class \ "graphical" is the parent class
10021: cell% field circle-radius
1.5 anton 10022:
1.78 anton 10023: :noname ( x y circle -- )
10024: circle-radius @@ draw-circle ;
10025: overrides draw
1.5 anton 10026:
1.78 anton 10027: :noname ( n-radius circle -- )
10028: circle-radius ! ;
10029: overrides construct
1.5 anton 10030:
1.78 anton 10031: end-class circle
10032: @end example
1.44 crook 10033:
1.78 anton 10034: Here we define a class @code{circle} as a child of @code{graphical},
10035: with field @code{circle-radius} (which behaves just like a field
10036: (@pxref{Structures}); it defines (using @code{overrides}) new methods
10037: for the selectors @code{draw} and @code{construct} (@code{construct} is
10038: defined in @code{object}, the parent class of @code{graphical}).
1.5 anton 10039:
1.78 anton 10040: Now we can create a circle on the heap (i.e.,
10041: @code{allocate}d memory) with:
1.44 crook 10042:
1.78 anton 10043: @cindex @code{heap-new} usage
1.5 anton 10044: @example
1.78 anton 10045: 50 circle heap-new constant my-circle
1.5 anton 10046: @end example
10047:
1.78 anton 10048: @noindent
10049: @code{heap-new} invokes @code{construct}, thus
10050: initializing the field @code{circle-radius} with 50. We can draw
10051: this new circle at (100,100) with:
1.5 anton 10052:
10053: @example
1.78 anton 10054: 100 100 my-circle draw
1.5 anton 10055: @end example
10056:
1.78 anton 10057: @cindex selector invocation, restrictions
10058: @cindex class definition, restrictions
10059: Note: You can only invoke a selector if the object on the TOS
10060: (the receiving object) belongs to the class where the selector was
10061: defined or one of its descendents; e.g., you can invoke
10062: @code{draw} only for objects belonging to @code{graphical}
10063: or its descendents (e.g., @code{circle}). Immediately before
10064: @code{end-class}, the search order has to be the same as
10065: immediately after @code{class}.
10066:
10067: @node The Objects base class, Creating objects, Basic Objects Usage, Objects
10068: @subsubsection The @file{object.fs} base class
10069: @cindex @code{object} class
10070:
10071: When you define a class, you have to specify a parent class. So how do
10072: you start defining classes? There is one class available from the start:
10073: @code{object}. It is ancestor for all classes and so is the
10074: only class that has no parent. It has two selectors: @code{construct}
10075: and @code{print}.
10076:
10077: @node Creating objects, Object-Oriented Programming Style, The Objects base class, Objects
10078: @subsubsection Creating objects
10079: @cindex creating objects
10080: @cindex object creation
10081: @cindex object allocation options
10082:
10083: @cindex @code{heap-new} discussion
10084: @cindex @code{dict-new} discussion
10085: @cindex @code{construct} discussion
10086: You can create and initialize an object of a class on the heap with
10087: @code{heap-new} ( ... class -- object ) and in the dictionary
10088: (allocation with @code{allot}) with @code{dict-new} (
10089: ... class -- object ). Both words invoke @code{construct}, which
10090: consumes the stack items indicated by "..." above.
10091:
10092: @cindex @code{init-object} discussion
10093: @cindex @code{class-inst-size} discussion
10094: If you want to allocate memory for an object yourself, you can get its
10095: alignment and size with @code{class-inst-size 2@@} ( class --
10096: align size ). Once you have memory for an object, you can initialize
10097: it with @code{init-object} ( ... class object -- );
10098: @code{construct} does only a part of the necessary work.
10099:
10100: @node Object-Oriented Programming Style, Class Binding, Creating objects, Objects
10101: @subsubsection Object-Oriented Programming Style
10102: @cindex object-oriented programming style
10103: @cindex programming style, object-oriented
1.5 anton 10104:
1.78 anton 10105: This section is not exhaustive.
1.5 anton 10106:
1.78 anton 10107: @cindex stack effects of selectors
10108: @cindex selectors and stack effects
10109: In general, it is a good idea to ensure that all methods for the
10110: same selector have the same stack effect: when you invoke a selector,
10111: you often have no idea which method will be invoked, so, unless all
10112: methods have the same stack effect, you will not know the stack effect
10113: of the selector invocation.
1.5 anton 10114:
1.78 anton 10115: One exception to this rule is methods for the selector
10116: @code{construct}. We know which method is invoked, because we
10117: specify the class to be constructed at the same place. Actually, I
10118: defined @code{construct} as a selector only to give the users a
10119: convenient way to specify initialization. The way it is used, a
10120: mechanism different from selector invocation would be more natural
10121: (but probably would take more code and more space to explain).
1.5 anton 10122:
1.78 anton 10123: @node Class Binding, Method conveniences, Object-Oriented Programming Style, Objects
10124: @subsubsection Class Binding
10125: @cindex class binding
10126: @cindex early binding
1.5 anton 10127:
1.78 anton 10128: @cindex late binding
10129: Normal selector invocations determine the method at run-time depending
10130: on the class of the receiving object. This run-time selection is called
10131: @i{late binding}.
1.5 anton 10132:
1.78 anton 10133: Sometimes it's preferable to invoke a different method. For example,
10134: you might want to use the simple method for @code{print}ing
10135: @code{object}s instead of the possibly long-winded @code{print} method
10136: of the receiver class. You can achieve this by replacing the invocation
10137: of @code{print} with:
1.5 anton 10138:
1.78 anton 10139: @cindex @code{[bind]} usage
1.5 anton 10140: @example
1.78 anton 10141: [bind] object print
1.5 anton 10142: @end example
10143:
1.78 anton 10144: @noindent
10145: in compiled code or:
10146:
10147: @cindex @code{bind} usage
1.5 anton 10148: @example
1.78 anton 10149: bind object print
1.5 anton 10150: @end example
10151:
1.78 anton 10152: @cindex class binding, alternative to
10153: @noindent
10154: in interpreted code. Alternatively, you can define the method with a
10155: name (e.g., @code{print-object}), and then invoke it through the
10156: name. Class binding is just a (often more convenient) way to achieve
10157: the same effect; it avoids name clutter and allows you to invoke
10158: methods directly without naming them first.
1.5 anton 10159:
1.78 anton 10160: @cindex superclass binding
10161: @cindex parent class binding
10162: A frequent use of class binding is this: When we define a method
10163: for a selector, we often want the method to do what the selector does
10164: in the parent class, and a little more. There is a special word for
10165: this purpose: @code{[parent]}; @code{[parent]
10166: @emph{selector}} is equivalent to @code{[bind] @emph{parent
10167: selector}}, where @code{@emph{parent}} is the parent
10168: class of the current class. E.g., a method definition might look like:
1.44 crook 10169:
1.78 anton 10170: @cindex @code{[parent]} usage
10171: @example
10172: :noname
10173: dup [parent] foo \ do parent's foo on the receiving object
10174: ... \ do some more
10175: ; overrides foo
10176: @end example
1.6 pazsan 10177:
1.78 anton 10178: @cindex class binding as optimization
10179: In @cite{Object-oriented programming in ANS Forth} (Forth Dimensions,
10180: March 1997), Andrew McKewan presents class binding as an optimization
10181: technique. I recommend not using it for this purpose unless you are in
10182: an emergency. Late binding is pretty fast with this model anyway, so the
10183: benefit of using class binding is small; the cost of using class binding
10184: where it is not appropriate is reduced maintainability.
1.44 crook 10185:
1.78 anton 10186: While we are at programming style questions: You should bind
10187: selectors only to ancestor classes of the receiving object. E.g., say,
10188: you know that the receiving object is of class @code{foo} or its
10189: descendents; then you should bind only to @code{foo} and its
10190: ancestors.
1.12 anton 10191:
1.78 anton 10192: @node Method conveniences, Classes and Scoping, Class Binding, Objects
10193: @subsubsection Method conveniences
10194: @cindex method conveniences
1.44 crook 10195:
1.78 anton 10196: In a method you usually access the receiving object pretty often. If
10197: you define the method as a plain colon definition (e.g., with
10198: @code{:noname}), you may have to do a lot of stack
10199: gymnastics. To avoid this, you can define the method with @code{m:
10200: ... ;m}. E.g., you could define the method for
10201: @code{draw}ing a @code{circle} with
1.6 pazsan 10202:
1.78 anton 10203: @cindex @code{this} usage
10204: @cindex @code{m:} usage
10205: @cindex @code{;m} usage
10206: @example
10207: m: ( x y circle -- )
10208: ( x y ) this circle-radius @@ draw-circle ;m
10209: @end example
1.6 pazsan 10210:
1.78 anton 10211: @cindex @code{exit} in @code{m: ... ;m}
10212: @cindex @code{exitm} discussion
10213: @cindex @code{catch} in @code{m: ... ;m}
10214: When this method is executed, the receiver object is removed from the
10215: stack; you can access it with @code{this} (admittedly, in this
10216: example the use of @code{m: ... ;m} offers no advantage). Note
10217: that I specify the stack effect for the whole method (i.e. including
10218: the receiver object), not just for the code between @code{m:}
10219: and @code{;m}. You cannot use @code{exit} in
10220: @code{m:...;m}; instead, use
10221: @code{exitm}.@footnote{Moreover, for any word that calls
10222: @code{catch} and was defined before loading
10223: @code{objects.fs}, you have to redefine it like I redefined
10224: @code{catch}: @code{: catch this >r catch r> to-this ;}}
1.12 anton 10225:
1.78 anton 10226: @cindex @code{inst-var} usage
10227: You will frequently use sequences of the form @code{this
10228: @emph{field}} (in the example above: @code{this
10229: circle-radius}). If you use the field only in this way, you can
10230: define it with @code{inst-var} and eliminate the
10231: @code{this} before the field name. E.g., the @code{circle}
10232: class above could also be defined with:
1.6 pazsan 10233:
1.78 anton 10234: @example
10235: graphical class
10236: cell% inst-var radius
1.6 pazsan 10237:
1.78 anton 10238: m: ( x y circle -- )
10239: radius @@ draw-circle ;m
10240: overrides draw
1.6 pazsan 10241:
1.78 anton 10242: m: ( n-radius circle -- )
10243: radius ! ;m
10244: overrides construct
1.6 pazsan 10245:
1.78 anton 10246: end-class circle
10247: @end example
1.6 pazsan 10248:
1.78 anton 10249: @code{radius} can only be used in @code{circle} and its
10250: descendent classes and inside @code{m:...;m}.
1.6 pazsan 10251:
1.78 anton 10252: @cindex @code{inst-value} usage
10253: You can also define fields with @code{inst-value}, which is
10254: to @code{inst-var} what @code{value} is to
10255: @code{variable}. You can change the value of such a field with
10256: @code{[to-inst]}. E.g., we could also define the class
10257: @code{circle} like this:
1.44 crook 10258:
1.78 anton 10259: @example
10260: graphical class
10261: inst-value radius
1.6 pazsan 10262:
1.78 anton 10263: m: ( x y circle -- )
10264: radius draw-circle ;m
10265: overrides draw
1.44 crook 10266:
1.78 anton 10267: m: ( n-radius circle -- )
10268: [to-inst] radius ;m
10269: overrides construct
1.6 pazsan 10270:
1.78 anton 10271: end-class circle
10272: @end example
1.6 pazsan 10273:
1.78 anton 10274: @c !! :m is easy to confuse with m:. Another name would be better.
1.6 pazsan 10275:
1.78 anton 10276: @c Finally, you can define named methods with @code{:m}. One use of this
10277: @c feature is the definition of words that occur only in one class and are
10278: @c not intended to be overridden, but which still need method context
10279: @c (e.g., for accessing @code{inst-var}s). Another use is for methods that
10280: @c would be bound frequently, if defined anonymously.
1.6 pazsan 10281:
10282:
1.78 anton 10283: @node Classes and Scoping, Dividing classes, Method conveniences, Objects
10284: @subsubsection Classes and Scoping
10285: @cindex classes and scoping
10286: @cindex scoping and classes
1.6 pazsan 10287:
1.78 anton 10288: Inheritance is frequent, unlike structure extension. This exacerbates
10289: the problem with the field name convention (@pxref{Structure Naming
10290: Convention}): One always has to remember in which class the field was
10291: originally defined; changing a part of the class structure would require
10292: changes for renaming in otherwise unaffected code.
1.6 pazsan 10293:
1.78 anton 10294: @cindex @code{inst-var} visibility
10295: @cindex @code{inst-value} visibility
10296: To solve this problem, I added a scoping mechanism (which was not in my
10297: original charter): A field defined with @code{inst-var} (or
10298: @code{inst-value}) is visible only in the class where it is defined and in
10299: the descendent classes of this class. Using such fields only makes
10300: sense in @code{m:}-defined methods in these classes anyway.
1.6 pazsan 10301:
1.78 anton 10302: This scoping mechanism allows us to use the unadorned field name,
10303: because name clashes with unrelated words become much less likely.
1.6 pazsan 10304:
1.78 anton 10305: @cindex @code{protected} discussion
10306: @cindex @code{private} discussion
10307: Once we have this mechanism, we can also use it for controlling the
10308: visibility of other words: All words defined after
10309: @code{protected} are visible only in the current class and its
10310: descendents. @code{public} restores the compilation
10311: (i.e. @code{current}) word list that was in effect before. If you
10312: have several @code{protected}s without an intervening
10313: @code{public} or @code{set-current}, @code{public}
10314: will restore the compilation word list in effect before the first of
10315: these @code{protected}s.
1.6 pazsan 10316:
1.78 anton 10317: @node Dividing classes, Object Interfaces, Classes and Scoping, Objects
10318: @subsubsection Dividing classes
10319: @cindex Dividing classes
10320: @cindex @code{methods}...@code{end-methods}
1.6 pazsan 10321:
1.78 anton 10322: You may want to do the definition of methods separate from the
10323: definition of the class, its selectors, fields, and instance variables,
10324: i.e., separate the implementation from the definition. You can do this
10325: in the following way:
1.6 pazsan 10326:
1.78 anton 10327: @example
10328: graphical class
10329: inst-value radius
10330: end-class circle
1.6 pazsan 10331:
1.78 anton 10332: ... \ do some other stuff
1.6 pazsan 10333:
1.78 anton 10334: circle methods \ now we are ready
1.44 crook 10335:
1.78 anton 10336: m: ( x y circle -- )
10337: radius draw-circle ;m
10338: overrides draw
1.6 pazsan 10339:
1.78 anton 10340: m: ( n-radius circle -- )
10341: [to-inst] radius ;m
10342: overrides construct
1.44 crook 10343:
1.78 anton 10344: end-methods
10345: @end example
1.7 pazsan 10346:
1.78 anton 10347: You can use several @code{methods}...@code{end-methods} sections. The
10348: only things you can do to the class in these sections are: defining
10349: methods, and overriding the class's selectors. You must not define new
10350: selectors or fields.
1.7 pazsan 10351:
1.78 anton 10352: Note that you often have to override a selector before using it. In
10353: particular, you usually have to override @code{construct} with a new
10354: method before you can invoke @code{heap-new} and friends. E.g., you
10355: must not create a circle before the @code{overrides construct} sequence
10356: in the example above.
1.7 pazsan 10357:
1.78 anton 10358: @node Object Interfaces, Objects Implementation, Dividing classes, Objects
10359: @subsubsection Object Interfaces
10360: @cindex object interfaces
10361: @cindex interfaces for objects
1.7 pazsan 10362:
1.78 anton 10363: In this model you can only call selectors defined in the class of the
10364: receiving objects or in one of its ancestors. If you call a selector
10365: with a receiving object that is not in one of these classes, the
10366: result is undefined; if you are lucky, the program crashes
10367: immediately.
1.7 pazsan 10368:
1.78 anton 10369: @cindex selectors common to hardly-related classes
10370: Now consider the case when you want to have a selector (or several)
10371: available in two classes: You would have to add the selector to a
10372: common ancestor class, in the worst case to @code{object}. You
10373: may not want to do this, e.g., because someone else is responsible for
10374: this ancestor class.
1.7 pazsan 10375:
1.78 anton 10376: The solution for this problem is interfaces. An interface is a
10377: collection of selectors. If a class implements an interface, the
10378: selectors become available to the class and its descendents. A class
10379: can implement an unlimited number of interfaces. For the problem
10380: discussed above, we would define an interface for the selector(s), and
10381: both classes would implement the interface.
1.7 pazsan 10382:
1.78 anton 10383: As an example, consider an interface @code{storage} for
10384: writing objects to disk and getting them back, and a class
10385: @code{foo} that implements it. The code would look like this:
1.7 pazsan 10386:
1.78 anton 10387: @cindex @code{interface} usage
10388: @cindex @code{end-interface} usage
10389: @cindex @code{implementation} usage
10390: @example
10391: interface
10392: selector write ( file object -- )
10393: selector read1 ( file object -- )
10394: end-interface storage
1.13 pazsan 10395:
1.78 anton 10396: bar class
10397: storage implementation
1.13 pazsan 10398:
1.78 anton 10399: ... overrides write
10400: ... overrides read1
10401: ...
10402: end-class foo
10403: @end example
1.13 pazsan 10404:
1.78 anton 10405: @noindent
10406: (I would add a word @code{read} @i{( file -- object )} that uses
10407: @code{read1} internally, but that's beyond the point illustrated
10408: here.)
1.13 pazsan 10409:
1.78 anton 10410: Note that you cannot use @code{protected} in an interface; and
10411: of course you cannot define fields.
1.13 pazsan 10412:
1.78 anton 10413: In the Neon model, all selectors are available for all classes;
10414: therefore it does not need interfaces. The price you pay in this model
10415: is slower late binding, and therefore, added complexity to avoid late
10416: binding.
1.13 pazsan 10417:
1.78 anton 10418: @node Objects Implementation, Objects Glossary, Object Interfaces, Objects
10419: @subsubsection @file{objects.fs} Implementation
10420: @cindex @file{objects.fs} implementation
1.13 pazsan 10421:
1.78 anton 10422: @cindex @code{object-map} discussion
10423: An object is a piece of memory, like one of the data structures
10424: described with @code{struct...end-struct}. It has a field
10425: @code{object-map} that points to the method map for the object's
10426: class.
1.13 pazsan 10427:
1.78 anton 10428: @cindex method map
10429: @cindex virtual function table
10430: The @emph{method map}@footnote{This is Self terminology; in C++
10431: terminology: virtual function table.} is an array that contains the
10432: execution tokens (@i{xt}s) of the methods for the object's class. Each
10433: selector contains an offset into a method map.
1.13 pazsan 10434:
1.78 anton 10435: @cindex @code{selector} implementation, class
10436: @code{selector} is a defining word that uses
10437: @code{CREATE} and @code{DOES>}. The body of the
10438: selector contains the offset; the @code{DOES>} action for a
10439: class selector is, basically:
1.8 pazsan 10440:
10441: @example
1.78 anton 10442: ( object addr ) @@ over object-map @@ + @@ execute
1.13 pazsan 10443: @end example
10444:
1.78 anton 10445: Since @code{object-map} is the first field of the object, it
10446: does not generate any code. As you can see, calling a selector has a
10447: small, constant cost.
1.26 crook 10448:
1.78 anton 10449: @cindex @code{current-interface} discussion
10450: @cindex class implementation and representation
10451: A class is basically a @code{struct} combined with a method
10452: map. During the class definition the alignment and size of the class
10453: are passed on the stack, just as with @code{struct}s, so
10454: @code{field} can also be used for defining class
10455: fields. However, passing more items on the stack would be
10456: inconvenient, so @code{class} builds a data structure in memory,
10457: which is accessed through the variable
10458: @code{current-interface}. After its definition is complete, the
10459: class is represented on the stack by a pointer (e.g., as parameter for
10460: a child class definition).
1.26 crook 10461:
1.78 anton 10462: A new class starts off with the alignment and size of its parent,
10463: and a copy of the parent's method map. Defining new fields extends the
10464: size and alignment; likewise, defining new selectors extends the
10465: method map. @code{overrides} just stores a new @i{xt} in the method
10466: map at the offset given by the selector.
1.13 pazsan 10467:
1.78 anton 10468: @cindex class binding, implementation
10469: Class binding just gets the @i{xt} at the offset given by the selector
10470: from the class's method map and @code{compile,}s (in the case of
10471: @code{[bind]}) it.
1.13 pazsan 10472:
1.78 anton 10473: @cindex @code{this} implementation
10474: @cindex @code{catch} and @code{this}
10475: @cindex @code{this} and @code{catch}
10476: I implemented @code{this} as a @code{value}. At the
10477: start of an @code{m:...;m} method the old @code{this} is
10478: stored to the return stack and restored at the end; and the object on
10479: the TOS is stored @code{TO this}. This technique has one
10480: disadvantage: If the user does not leave the method via
10481: @code{;m}, but via @code{throw} or @code{exit},
10482: @code{this} is not restored (and @code{exit} may
10483: crash). To deal with the @code{throw} problem, I have redefined
10484: @code{catch} to save and restore @code{this}; the same
10485: should be done with any word that can catch an exception. As for
10486: @code{exit}, I simply forbid it (as a replacement, there is
10487: @code{exitm}).
1.13 pazsan 10488:
1.78 anton 10489: @cindex @code{inst-var} implementation
10490: @code{inst-var} is just the same as @code{field}, with
10491: a different @code{DOES>} action:
1.13 pazsan 10492: @example
1.78 anton 10493: @@ this +
1.8 pazsan 10494: @end example
1.78 anton 10495: Similar for @code{inst-value}.
1.8 pazsan 10496:
1.78 anton 10497: @cindex class scoping implementation
10498: Each class also has a word list that contains the words defined with
10499: @code{inst-var} and @code{inst-value}, and its protected
10500: words. It also has a pointer to its parent. @code{class} pushes
10501: the word lists of the class and all its ancestors onto the search order stack,
10502: and @code{end-class} drops them.
1.20 pazsan 10503:
1.78 anton 10504: @cindex interface implementation
10505: An interface is like a class without fields, parent and protected
10506: words; i.e., it just has a method map. If a class implements an
10507: interface, its method map contains a pointer to the method map of the
10508: interface. The positive offsets in the map are reserved for class
10509: methods, therefore interface map pointers have negative
10510: offsets. Interfaces have offsets that are unique throughout the
10511: system, unlike class selectors, whose offsets are only unique for the
10512: classes where the selector is available (invokable).
1.20 pazsan 10513:
1.78 anton 10514: This structure means that interface selectors have to perform one
10515: indirection more than class selectors to find their method. Their body
10516: contains the interface map pointer offset in the class method map, and
10517: the method offset in the interface method map. The
10518: @code{does>} action for an interface selector is, basically:
1.20 pazsan 10519:
10520: @example
1.78 anton 10521: ( object selector-body )
10522: 2dup selector-interface @@ ( object selector-body object interface-offset )
10523: swap object-map @@ + @@ ( object selector-body map )
10524: swap selector-offset @@ + @@ execute
1.20 pazsan 10525: @end example
10526:
1.78 anton 10527: where @code{object-map} and @code{selector-offset} are
10528: first fields and generate no code.
1.20 pazsan 10529:
1.78 anton 10530: As a concrete example, consider the following code:
1.20 pazsan 10531:
10532: @example
1.78 anton 10533: interface
10534: selector if1sel1
10535: selector if1sel2
10536: end-interface if1
1.20 pazsan 10537:
1.78 anton 10538: object class
10539: if1 implementation
10540: selector cl1sel1
10541: cell% inst-var cl1iv1
1.20 pazsan 10542:
1.78 anton 10543: ' m1 overrides construct
10544: ' m2 overrides if1sel1
10545: ' m3 overrides if1sel2
10546: ' m4 overrides cl1sel2
10547: end-class cl1
1.20 pazsan 10548:
1.78 anton 10549: create obj1 object dict-new drop
10550: create obj2 cl1 dict-new drop
10551: @end example
1.20 pazsan 10552:
1.78 anton 10553: The data structure created by this code (including the data structure
10554: for @code{object}) is shown in the
10555: @uref{objects-implementation.eps,figure}, assuming a cell size of 4.
10556: @comment TODO add this diagram..
1.20 pazsan 10557:
1.78 anton 10558: @node Objects Glossary, , Objects Implementation, Objects
10559: @subsubsection @file{objects.fs} Glossary
10560: @cindex @file{objects.fs} Glossary
1.20 pazsan 10561:
10562:
1.78 anton 10563: doc---objects-bind
10564: doc---objects-<bind>
10565: doc---objects-bind'
10566: doc---objects-[bind]
10567: doc---objects-class
10568: doc---objects-class->map
10569: doc---objects-class-inst-size
10570: doc---objects-class-override!
1.79 anton 10571: doc---objects-class-previous
10572: doc---objects-class>order
1.78 anton 10573: doc---objects-construct
10574: doc---objects-current'
10575: doc---objects-[current]
10576: doc---objects-current-interface
10577: doc---objects-dict-new
10578: doc---objects-end-class
10579: doc---objects-end-class-noname
10580: doc---objects-end-interface
10581: doc---objects-end-interface-noname
10582: doc---objects-end-methods
10583: doc---objects-exitm
10584: doc---objects-heap-new
10585: doc---objects-implementation
10586: doc---objects-init-object
10587: doc---objects-inst-value
10588: doc---objects-inst-var
10589: doc---objects-interface
10590: doc---objects-m:
10591: doc---objects-:m
10592: doc---objects-;m
10593: doc---objects-method
10594: doc---objects-methods
10595: doc---objects-object
10596: doc---objects-overrides
10597: doc---objects-[parent]
10598: doc---objects-print
10599: doc---objects-protected
10600: doc---objects-public
10601: doc---objects-selector
10602: doc---objects-this
10603: doc---objects-<to-inst>
10604: doc---objects-[to-inst]
10605: doc---objects-to-this
10606: doc---objects-xt-new
1.20 pazsan 10607:
10608:
1.78 anton 10609: @c -------------------------------------------------------------
10610: @node OOF, Mini-OOF, Objects, Object-oriented Forth
10611: @subsection The @file{oof.fs} model
10612: @cindex oof
10613: @cindex object-oriented programming
1.20 pazsan 10614:
1.78 anton 10615: @cindex @file{objects.fs}
10616: @cindex @file{oof.fs}
1.20 pazsan 10617:
1.78 anton 10618: This section describes the @file{oof.fs} package.
1.20 pazsan 10619:
1.78 anton 10620: The package described in this section has been used in bigFORTH since 1991, and
10621: used for two large applications: a chromatographic system used to
10622: create new medicaments, and a graphic user interface library (MINOS).
1.20 pazsan 10623:
1.78 anton 10624: You can find a description (in German) of @file{oof.fs} in @cite{Object
10625: oriented bigFORTH} by Bernd Paysan, published in @cite{Vierte Dimension}
10626: 10(2), 1994.
1.20 pazsan 10627:
1.78 anton 10628: @menu
10629: * Properties of the OOF model::
10630: * Basic OOF Usage::
10631: * The OOF base class::
10632: * Class Declaration::
10633: * Class Implementation::
10634: @end menu
1.20 pazsan 10635:
1.78 anton 10636: @node Properties of the OOF model, Basic OOF Usage, OOF, OOF
10637: @subsubsection Properties of the @file{oof.fs} model
10638: @cindex @file{oof.fs} properties
1.20 pazsan 10639:
1.78 anton 10640: @itemize @bullet
10641: @item
10642: This model combines object oriented programming with information
10643: hiding. It helps you writing large application, where scoping is
10644: necessary, because it provides class-oriented scoping.
1.20 pazsan 10645:
1.78 anton 10646: @item
10647: Named objects, object pointers, and object arrays can be created,
10648: selector invocation uses the ``object selector'' syntax. Selector invocation
10649: to objects and/or selectors on the stack is a bit less convenient, but
10650: possible.
1.44 crook 10651:
1.78 anton 10652: @item
10653: Selector invocation and instance variable usage of the active object is
10654: straightforward, since both make use of the active object.
1.44 crook 10655:
1.78 anton 10656: @item
10657: Late binding is efficient and easy to use.
1.20 pazsan 10658:
1.78 anton 10659: @item
10660: State-smart objects parse selectors. However, extensibility is provided
10661: using a (parsing) selector @code{postpone} and a selector @code{'}.
1.20 pazsan 10662:
1.78 anton 10663: @item
10664: An implementation in ANS Forth is available.
1.20 pazsan 10665:
1.78 anton 10666: @end itemize
1.23 crook 10667:
10668:
1.78 anton 10669: @node Basic OOF Usage, The OOF base class, Properties of the OOF model, OOF
10670: @subsubsection Basic @file{oof.fs} Usage
10671: @cindex @file{oof.fs} usage
1.23 crook 10672:
1.78 anton 10673: This section uses the same example as for @code{objects} (@pxref{Basic Objects Usage}).
1.23 crook 10674:
1.78 anton 10675: You can define a class for graphical objects like this:
1.23 crook 10676:
1.78 anton 10677: @cindex @code{class} usage
10678: @cindex @code{class;} usage
10679: @cindex @code{method} usage
10680: @example
10681: object class graphical \ "object" is the parent class
10682: method draw ( x y graphical -- )
10683: class;
10684: @end example
1.23 crook 10685:
1.78 anton 10686: This code defines a class @code{graphical} with an
10687: operation @code{draw}. We can perform the operation
10688: @code{draw} on any @code{graphical} object, e.g.:
1.23 crook 10689:
1.78 anton 10690: @example
10691: 100 100 t-rex draw
10692: @end example
1.23 crook 10693:
1.78 anton 10694: @noindent
10695: where @code{t-rex} is an object or object pointer, created with e.g.
10696: @code{graphical : t-rex}.
1.23 crook 10697:
1.78 anton 10698: @cindex abstract class
10699: How do we create a graphical object? With the present definitions,
10700: we cannot create a useful graphical object. The class
10701: @code{graphical} describes graphical objects in general, but not
10702: any concrete graphical object type (C++ users would call it an
10703: @emph{abstract class}); e.g., there is no method for the selector
10704: @code{draw} in the class @code{graphical}.
1.23 crook 10705:
1.78 anton 10706: For concrete graphical objects, we define child classes of the
10707: class @code{graphical}, e.g.:
1.23 crook 10708:
1.78 anton 10709: @example
10710: graphical class circle \ "graphical" is the parent class
10711: cell var circle-radius
10712: how:
10713: : draw ( x y -- )
10714: circle-radius @@ draw-circle ;
1.23 crook 10715:
1.78 anton 10716: : init ( n-radius -- (
10717: circle-radius ! ;
10718: class;
10719: @end example
1.1 anton 10720:
1.78 anton 10721: Here we define a class @code{circle} as a child of @code{graphical},
10722: with a field @code{circle-radius}; it defines new methods for the
10723: selectors @code{draw} and @code{init} (@code{init} is defined in
10724: @code{object}, the parent class of @code{graphical}).
1.1 anton 10725:
1.78 anton 10726: Now we can create a circle in the dictionary with:
1.1 anton 10727:
1.78 anton 10728: @example
10729: 50 circle : my-circle
10730: @end example
1.21 crook 10731:
1.78 anton 10732: @noindent
10733: @code{:} invokes @code{init}, thus initializing the field
10734: @code{circle-radius} with 50. We can draw this new circle at (100,100)
10735: with:
1.1 anton 10736:
1.78 anton 10737: @example
10738: 100 100 my-circle draw
10739: @end example
1.1 anton 10740:
1.78 anton 10741: @cindex selector invocation, restrictions
10742: @cindex class definition, restrictions
10743: Note: You can only invoke a selector if the receiving object belongs to
10744: the class where the selector was defined or one of its descendents;
10745: e.g., you can invoke @code{draw} only for objects belonging to
10746: @code{graphical} or its descendents (e.g., @code{circle}). The scoping
10747: mechanism will check if you try to invoke a selector that is not
10748: defined in this class hierarchy, so you'll get an error at compilation
10749: time.
1.1 anton 10750:
10751:
1.78 anton 10752: @node The OOF base class, Class Declaration, Basic OOF Usage, OOF
10753: @subsubsection The @file{oof.fs} base class
10754: @cindex @file{oof.fs} base class
1.1 anton 10755:
1.78 anton 10756: When you define a class, you have to specify a parent class. So how do
10757: you start defining classes? There is one class available from the start:
10758: @code{object}. You have to use it as ancestor for all classes. It is the
10759: only class that has no parent. Classes are also objects, except that
10760: they don't have instance variables; class manipulation such as
10761: inheritance or changing definitions of a class is handled through
10762: selectors of the class @code{object}.
1.1 anton 10763:
1.78 anton 10764: @code{object} provides a number of selectors:
1.1 anton 10765:
1.78 anton 10766: @itemize @bullet
10767: @item
10768: @code{class} for subclassing, @code{definitions} to add definitions
10769: later on, and @code{class?} to get type informations (is the class a
10770: subclass of the class passed on the stack?).
1.1 anton 10771:
1.78 anton 10772: doc---object-class
10773: doc---object-definitions
10774: doc---object-class?
1.1 anton 10775:
10776:
1.26 crook 10777: @item
1.78 anton 10778: @code{init} and @code{dispose} as constructor and destructor of the
10779: object. @code{init} is invocated after the object's memory is allocated,
10780: while @code{dispose} also handles deallocation. Thus if you redefine
10781: @code{dispose}, you have to call the parent's dispose with @code{super
10782: dispose}, too.
10783:
10784: doc---object-init
10785: doc---object-dispose
10786:
1.1 anton 10787:
1.26 crook 10788: @item
1.78 anton 10789: @code{new}, @code{new[]}, @code{:}, @code{ptr}, @code{asptr}, and
10790: @code{[]} to create named and unnamed objects and object arrays or
10791: object pointers.
10792:
10793: doc---object-new
10794: doc---object-new[]
10795: doc---object-:
10796: doc---object-ptr
10797: doc---object-asptr
10798: doc---object-[]
10799:
1.1 anton 10800:
1.26 crook 10801: @item
1.78 anton 10802: @code{::} and @code{super} for explicit scoping. You should use explicit
10803: scoping only for super classes or classes with the same set of instance
10804: variables. Explicitly-scoped selectors use early binding.
1.21 crook 10805:
1.78 anton 10806: doc---object-::
10807: doc---object-super
1.21 crook 10808:
10809:
1.26 crook 10810: @item
1.78 anton 10811: @code{self} to get the address of the object
1.21 crook 10812:
1.78 anton 10813: doc---object-self
1.21 crook 10814:
10815:
1.78 anton 10816: @item
10817: @code{bind}, @code{bound}, @code{link}, and @code{is} to assign object
10818: pointers and instance defers.
1.21 crook 10819:
1.78 anton 10820: doc---object-bind
10821: doc---object-bound
10822: doc---object-link
10823: doc---object-is
1.21 crook 10824:
10825:
1.78 anton 10826: @item
10827: @code{'} to obtain selector tokens, @code{send} to invocate selectors
10828: form the stack, and @code{postpone} to generate selector invocation code.
1.21 crook 10829:
1.78 anton 10830: doc---object-'
10831: doc---object-postpone
1.21 crook 10832:
10833:
1.78 anton 10834: @item
10835: @code{with} and @code{endwith} to select the active object from the
10836: stack, and enable its scope. Using @code{with} and @code{endwith}
10837: also allows you to create code using selector @code{postpone} without being
10838: trapped by the state-smart objects.
1.21 crook 10839:
1.78 anton 10840: doc---object-with
10841: doc---object-endwith
1.21 crook 10842:
10843:
1.78 anton 10844: @end itemize
1.21 crook 10845:
1.78 anton 10846: @node Class Declaration, Class Implementation, The OOF base class, OOF
10847: @subsubsection Class Declaration
10848: @cindex class declaration
1.21 crook 10849:
1.78 anton 10850: @itemize @bullet
10851: @item
10852: Instance variables
1.21 crook 10853:
1.78 anton 10854: doc---oof-var
1.21 crook 10855:
10856:
1.78 anton 10857: @item
10858: Object pointers
1.21 crook 10859:
1.78 anton 10860: doc---oof-ptr
10861: doc---oof-asptr
1.21 crook 10862:
10863:
1.78 anton 10864: @item
10865: Instance defers
1.21 crook 10866:
1.78 anton 10867: doc---oof-defer
1.21 crook 10868:
10869:
1.78 anton 10870: @item
10871: Method selectors
1.21 crook 10872:
1.78 anton 10873: doc---oof-early
10874: doc---oof-method
1.21 crook 10875:
10876:
1.78 anton 10877: @item
10878: Class-wide variables
1.21 crook 10879:
1.78 anton 10880: doc---oof-static
1.21 crook 10881:
10882:
1.78 anton 10883: @item
10884: End declaration
1.1 anton 10885:
1.78 anton 10886: doc---oof-how:
10887: doc---oof-class;
1.21 crook 10888:
10889:
1.78 anton 10890: @end itemize
1.21 crook 10891:
1.78 anton 10892: @c -------------------------------------------------------------
10893: @node Class Implementation, , Class Declaration, OOF
10894: @subsubsection Class Implementation
10895: @cindex class implementation
1.21 crook 10896:
1.78 anton 10897: @c -------------------------------------------------------------
10898: @node Mini-OOF, Comparison with other object models, OOF, Object-oriented Forth
10899: @subsection The @file{mini-oof.fs} model
10900: @cindex mini-oof
1.21 crook 10901:
1.78 anton 10902: Gforth's third object oriented Forth package is a 12-liner. It uses a
1.79 anton 10903: mixture of the @file{objects.fs} and the @file{oof.fs} syntax,
1.78 anton 10904: and reduces to the bare minimum of features. This is based on a posting
10905: of Bernd Paysan in comp.lang.forth.
1.21 crook 10906:
1.78 anton 10907: @menu
10908: * Basic Mini-OOF Usage::
10909: * Mini-OOF Example::
10910: * Mini-OOF Implementation::
10911: @end menu
1.21 crook 10912:
1.78 anton 10913: @c -------------------------------------------------------------
10914: @node Basic Mini-OOF Usage, Mini-OOF Example, Mini-OOF, Mini-OOF
10915: @subsubsection Basic @file{mini-oof.fs} Usage
10916: @cindex mini-oof usage
1.21 crook 10917:
1.78 anton 10918: There is a base class (@code{class}, which allocates one cell for the
10919: object pointer) plus seven other words: to define a method, a variable,
10920: a class; to end a class, to resolve binding, to allocate an object and
10921: to compile a class method.
10922: @comment TODO better description of the last one
1.26 crook 10923:
1.21 crook 10924:
1.78 anton 10925: doc-object
10926: doc-method
10927: doc-var
10928: doc-class
10929: doc-end-class
10930: doc-defines
10931: doc-new
10932: doc-::
1.21 crook 10933:
10934:
10935:
1.78 anton 10936: @c -------------------------------------------------------------
10937: @node Mini-OOF Example, Mini-OOF Implementation, Basic Mini-OOF Usage, Mini-OOF
10938: @subsubsection Mini-OOF Example
10939: @cindex mini-oof example
1.1 anton 10940:
1.78 anton 10941: A short example shows how to use this package. This example, in slightly
10942: extended form, is supplied as @file{moof-exm.fs}
10943: @comment TODO could flesh this out with some comments from the Forthwrite article
1.20 pazsan 10944:
1.26 crook 10945: @example
1.78 anton 10946: object class
10947: method init
10948: method draw
10949: end-class graphical
1.26 crook 10950: @end example
1.20 pazsan 10951:
1.78 anton 10952: This code defines a class @code{graphical} with an
10953: operation @code{draw}. We can perform the operation
10954: @code{draw} on any @code{graphical} object, e.g.:
1.20 pazsan 10955:
1.26 crook 10956: @example
1.78 anton 10957: 100 100 t-rex draw
1.26 crook 10958: @end example
1.12 anton 10959:
1.78 anton 10960: where @code{t-rex} is an object or object pointer, created with e.g.
10961: @code{graphical new Constant t-rex}.
1.12 anton 10962:
1.78 anton 10963: For concrete graphical objects, we define child classes of the
10964: class @code{graphical}, e.g.:
1.12 anton 10965:
1.26 crook 10966: @example
10967: graphical class
1.78 anton 10968: cell var circle-radius
10969: end-class circle \ "graphical" is the parent class
1.12 anton 10970:
1.78 anton 10971: :noname ( x y -- )
10972: circle-radius @@ draw-circle ; circle defines draw
10973: :noname ( r -- )
10974: circle-radius ! ; circle defines init
10975: @end example
1.12 anton 10976:
1.78 anton 10977: There is no implicit init method, so we have to define one. The creation
10978: code of the object now has to call init explicitely.
1.21 crook 10979:
1.78 anton 10980: @example
10981: circle new Constant my-circle
10982: 50 my-circle init
1.12 anton 10983: @end example
10984:
1.78 anton 10985: It is also possible to add a function to create named objects with
10986: automatic call of @code{init}, given that all objects have @code{init}
10987: on the same place:
1.38 anton 10988:
1.78 anton 10989: @example
10990: : new: ( .. o "name" -- )
10991: new dup Constant init ;
10992: 80 circle new: large-circle
10993: @end example
1.12 anton 10994:
1.78 anton 10995: We can draw this new circle at (100,100) with:
1.12 anton 10996:
1.78 anton 10997: @example
10998: 100 100 my-circle draw
10999: @end example
1.12 anton 11000:
1.78 anton 11001: @node Mini-OOF Implementation, , Mini-OOF Example, Mini-OOF
11002: @subsubsection @file{mini-oof.fs} Implementation
1.12 anton 11003:
1.78 anton 11004: Object-oriented systems with late binding typically use a
11005: ``vtable''-approach: the first variable in each object is a pointer to a
11006: table, which contains the methods as function pointers. The vtable
11007: may also contain other information.
1.12 anton 11008:
1.79 anton 11009: So first, let's declare selectors:
1.37 anton 11010:
11011: @example
1.79 anton 11012: : method ( m v "name" -- m' v ) Create over , swap cell+ swap
1.78 anton 11013: DOES> ( ... o -- ... ) @@ over @@ + @@ execute ;
11014: @end example
1.37 anton 11015:
1.79 anton 11016: During selector declaration, the number of selectors and instance
11017: variables is on the stack (in address units). @code{method} creates one
11018: selector and increments the selector number. To execute a selector, it
1.78 anton 11019: takes the object, fetches the vtable pointer, adds the offset, and
1.79 anton 11020: executes the method @i{xt} stored there. Each selector takes the object
11021: it is invoked with as top of stack parameter; it passes the parameters
11022: (including the object) unchanged to the appropriate method which should
1.78 anton 11023: consume that object.
1.37 anton 11024:
1.78 anton 11025: Now, we also have to declare instance variables
1.37 anton 11026:
1.78 anton 11027: @example
1.79 anton 11028: : var ( m v size "name" -- m v' ) Create over , +
1.78 anton 11029: DOES> ( o -- addr ) @@ + ;
1.37 anton 11030: @end example
11031:
1.78 anton 11032: As before, a word is created with the current offset. Instance
11033: variables can have different sizes (cells, floats, doubles, chars), so
11034: all we do is take the size and add it to the offset. If your machine
11035: has alignment restrictions, put the proper @code{aligned} or
11036: @code{faligned} before the variable, to adjust the variable
11037: offset. That's why it is on the top of stack.
1.37 anton 11038:
1.78 anton 11039: We need a starting point (the base object) and some syntactic sugar:
1.37 anton 11040:
1.78 anton 11041: @example
11042: Create object 1 cells , 2 cells ,
1.79 anton 11043: : class ( class -- class selectors vars ) dup 2@@ ;
1.78 anton 11044: @end example
1.12 anton 11045:
1.78 anton 11046: For inheritance, the vtable of the parent object has to be
11047: copied when a new, derived class is declared. This gives all the
11048: methods of the parent class, which can be overridden, though.
1.12 anton 11049:
1.78 anton 11050: @example
1.79 anton 11051: : end-class ( class selectors vars "name" -- )
1.78 anton 11052: Create here >r , dup , 2 cells ?DO ['] noop , 1 cells +LOOP
11053: cell+ dup cell+ r> rot @@ 2 cells /string move ;
11054: @end example
1.12 anton 11055:
1.78 anton 11056: The first line creates the vtable, initialized with
11057: @code{noop}s. The second line is the inheritance mechanism, it
11058: copies the xts from the parent vtable.
1.12 anton 11059:
1.78 anton 11060: We still have no way to define new methods, let's do that now:
1.12 anton 11061:
1.26 crook 11062: @example
1.79 anton 11063: : defines ( xt class "name" -- ) ' >body @@ + ! ;
1.78 anton 11064: @end example
1.12 anton 11065:
1.78 anton 11066: To allocate a new object, we need a word, too:
1.12 anton 11067:
1.78 anton 11068: @example
11069: : new ( class -- o ) here over @@ allot swap over ! ;
1.12 anton 11070: @end example
11071:
1.78 anton 11072: Sometimes derived classes want to access the method of the
11073: parent object. There are two ways to achieve this with Mini-OOF:
11074: first, you could use named words, and second, you could look up the
11075: vtable of the parent object.
1.12 anton 11076:
1.78 anton 11077: @example
11078: : :: ( class "name" -- ) ' >body @@ + @@ compile, ;
11079: @end example
1.12 anton 11080:
11081:
1.78 anton 11082: Nothing can be more confusing than a good example, so here is
11083: one. First let's declare a text object (called
11084: @code{button}), that stores text and position:
1.12 anton 11085:
1.78 anton 11086: @example
11087: object class
11088: cell var text
11089: cell var len
11090: cell var x
11091: cell var y
11092: method init
11093: method draw
11094: end-class button
11095: @end example
1.12 anton 11096:
1.78 anton 11097: @noindent
11098: Now, implement the two methods, @code{draw} and @code{init}:
1.21 crook 11099:
1.26 crook 11100: @example
1.78 anton 11101: :noname ( o -- )
11102: >r r@@ x @@ r@@ y @@ at-xy r@@ text @@ r> len @@ type ;
11103: button defines draw
11104: :noname ( addr u o -- )
11105: >r 0 r@@ x ! 0 r@@ y ! r@@ len ! r> text ! ;
11106: button defines init
1.26 crook 11107: @end example
1.12 anton 11108:
1.78 anton 11109: @noindent
11110: To demonstrate inheritance, we define a class @code{bold-button}, with no
1.79 anton 11111: new data and no new selectors:
1.78 anton 11112:
11113: @example
11114: button class
11115: end-class bold-button
1.12 anton 11116:
1.78 anton 11117: : bold 27 emit ." [1m" ;
11118: : normal 27 emit ." [0m" ;
11119: @end example
1.1 anton 11120:
1.78 anton 11121: @noindent
11122: The class @code{bold-button} has a different draw method to
11123: @code{button}, but the new method is defined in terms of the draw method
11124: for @code{button}:
1.20 pazsan 11125:
1.78 anton 11126: @example
11127: :noname bold [ button :: draw ] normal ; bold-button defines draw
11128: @end example
1.21 crook 11129:
1.78 anton 11130: @noindent
1.79 anton 11131: Finally, create two objects and apply selectors:
1.21 crook 11132:
1.26 crook 11133: @example
1.78 anton 11134: button new Constant foo
11135: s" thin foo" foo init
11136: page
11137: foo draw
11138: bold-button new Constant bar
11139: s" fat bar" bar init
11140: 1 bar y !
11141: bar draw
1.26 crook 11142: @end example
1.21 crook 11143:
11144:
1.78 anton 11145: @node Comparison with other object models, , Mini-OOF, Object-oriented Forth
11146: @subsection Comparison with other object models
11147: @cindex comparison of object models
11148: @cindex object models, comparison
11149:
11150: Many object-oriented Forth extensions have been proposed (@cite{A survey
11151: of object-oriented Forths} (SIGPLAN Notices, April 1996) by Bradford
11152: J. Rodriguez and W. F. S. Poehlman lists 17). This section discusses the
11153: relation of the object models described here to two well-known and two
11154: closely-related (by the use of method maps) models. Andras Zsoter
11155: helped us with this section.
11156:
11157: @cindex Neon model
11158: The most popular model currently seems to be the Neon model (see
11159: @cite{Object-oriented programming in ANS Forth} (Forth Dimensions, March
11160: 1997) by Andrew McKewan) but this model has a number of limitations
11161: @footnote{A longer version of this critique can be
11162: found in @cite{On Standardizing Object-Oriented Forth Extensions} (Forth
11163: Dimensions, May 1997) by Anton Ertl.}:
11164:
11165: @itemize @bullet
11166: @item
11167: It uses a @code{@emph{selector object}} syntax, which makes it unnatural
11168: to pass objects on the stack.
1.21 crook 11169:
1.78 anton 11170: @item
11171: It requires that the selector parses the input stream (at
1.79 anton 11172: compile time); this leads to reduced extensibility and to bugs that are
1.78 anton 11173: hard to find.
1.21 crook 11174:
1.78 anton 11175: @item
1.79 anton 11176: It allows using every selector on every object; this eliminates the
11177: need for interfaces, but makes it harder to create efficient
11178: implementations.
1.78 anton 11179: @end itemize
1.21 crook 11180:
1.78 anton 11181: @cindex Pountain's object-oriented model
11182: Another well-known publication is @cite{Object-Oriented Forth} (Academic
11183: Press, London, 1987) by Dick Pountain. However, it is not really about
11184: object-oriented programming, because it hardly deals with late
11185: binding. Instead, it focuses on features like information hiding and
11186: overloading that are characteristic of modular languages like Ada (83).
1.26 crook 11187:
1.78 anton 11188: @cindex Zsoter's object-oriented model
1.79 anton 11189: In @uref{http://www.forth.org/oopf.html, Does late binding have to be
11190: slow?} (Forth Dimensions 18(1) 1996, pages 31-35) Andras Zsoter
11191: describes a model that makes heavy use of an active object (like
11192: @code{this} in @file{objects.fs}): The active object is not only used
11193: for accessing all fields, but also specifies the receiving object of
11194: every selector invocation; you have to change the active object
11195: explicitly with @code{@{ ... @}}, whereas in @file{objects.fs} it
11196: changes more or less implicitly at @code{m: ... ;m}. Such a change at
11197: the method entry point is unnecessary with Zsoter's model, because the
11198: receiving object is the active object already. On the other hand, the
11199: explicit change is absolutely necessary in that model, because otherwise
11200: no one could ever change the active object. An ANS Forth implementation
11201: of this model is available through
11202: @uref{http://www.forth.org/oopf.html}.
1.21 crook 11203:
1.78 anton 11204: @cindex @file{oof.fs}, differences to other models
11205: The @file{oof.fs} model combines information hiding and overloading
11206: resolution (by keeping names in various word lists) with object-oriented
11207: programming. It sets the active object implicitly on method entry, but
11208: also allows explicit changing (with @code{>o...o>} or with
11209: @code{with...endwith}). It uses parsing and state-smart objects and
11210: classes for resolving overloading and for early binding: the object or
11211: class parses the selector and determines the method from this. If the
11212: selector is not parsed by an object or class, it performs a call to the
11213: selector for the active object (late binding), like Zsoter's model.
11214: Fields are always accessed through the active object. The big
11215: disadvantage of this model is the parsing and the state-smartness, which
11216: reduces extensibility and increases the opportunities for subtle bugs;
11217: essentially, you are only safe if you never tick or @code{postpone} an
11218: object or class (Bernd disagrees, but I (Anton) am not convinced).
1.21 crook 11219:
1.78 anton 11220: @cindex @file{mini-oof.fs}, differences to other models
11221: The @file{mini-oof.fs} model is quite similar to a very stripped-down
11222: version of the @file{objects.fs} model, but syntactically it is a
11223: mixture of the @file{objects.fs} and @file{oof.fs} models.
1.21 crook 11224:
11225:
1.78 anton 11226: @c -------------------------------------------------------------
11227: @node Programming Tools, Assembler and Code Words, Object-oriented Forth, Words
11228: @section Programming Tools
11229: @cindex programming tools
1.21 crook 11230:
1.78 anton 11231: @c !! move this and assembler down below OO stuff.
1.21 crook 11232:
1.78 anton 11233: @menu
11234: * Examining::
11235: * Forgetting words::
11236: * Debugging:: Simple and quick.
11237: * Assertions:: Making your programs self-checking.
11238: * Singlestep Debugger:: Executing your program word by word.
11239: @end menu
1.21 crook 11240:
1.78 anton 11241: @node Examining, Forgetting words, Programming Tools, Programming Tools
11242: @subsection Examining data and code
11243: @cindex examining data and code
11244: @cindex data examination
11245: @cindex code examination
1.44 crook 11246:
1.78 anton 11247: The following words inspect the stack non-destructively:
1.21 crook 11248:
1.78 anton 11249: doc-.s
11250: doc-f.s
1.44 crook 11251:
1.78 anton 11252: There is a word @code{.r} but it does @i{not} display the return stack!
11253: It is used for formatted numeric output (@pxref{Simple numeric output}).
1.21 crook 11254:
1.78 anton 11255: doc-depth
11256: doc-fdepth
11257: doc-clearstack
1.21 crook 11258:
1.78 anton 11259: The following words inspect memory.
1.21 crook 11260:
1.78 anton 11261: doc-?
11262: doc-dump
1.21 crook 11263:
1.78 anton 11264: And finally, @code{see} allows to inspect code:
1.21 crook 11265:
1.78 anton 11266: doc-see
11267: doc-xt-see
1.21 crook 11268:
1.78 anton 11269: @node Forgetting words, Debugging, Examining, Programming Tools
11270: @subsection Forgetting words
11271: @cindex words, forgetting
11272: @cindex forgeting words
1.21 crook 11273:
1.78 anton 11274: @c anton: other, maybe better places for this subsection: Defining Words;
11275: @c Dictionary allocation. At least a reference should be there.
1.21 crook 11276:
1.78 anton 11277: Forth allows you to forget words (and everything that was alloted in the
11278: dictonary after them) in a LIFO manner.
1.21 crook 11279:
1.78 anton 11280: doc-marker
1.21 crook 11281:
1.78 anton 11282: The most common use of this feature is during progam development: when
11283: you change a source file, forget all the words it defined and load it
11284: again (since you also forget everything defined after the source file
11285: was loaded, you have to reload that, too). Note that effects like
11286: storing to variables and destroyed system words are not undone when you
11287: forget words. With a system like Gforth, that is fast enough at
11288: starting up and compiling, I find it more convenient to exit and restart
11289: Gforth, as this gives me a clean slate.
1.21 crook 11290:
1.78 anton 11291: Here's an example of using @code{marker} at the start of a source file
11292: that you are debugging; it ensures that you only ever have one copy of
11293: the file's definitions compiled at any time:
1.21 crook 11294:
1.78 anton 11295: @example
11296: [IFDEF] my-code
11297: my-code
11298: [ENDIF]
1.26 crook 11299:
1.78 anton 11300: marker my-code
11301: init-included-files
1.21 crook 11302:
1.78 anton 11303: \ .. definitions start here
11304: \ .
11305: \ .
11306: \ end
11307: @end example
1.21 crook 11308:
1.26 crook 11309:
1.78 anton 11310: @node Debugging, Assertions, Forgetting words, Programming Tools
11311: @subsection Debugging
11312: @cindex debugging
1.21 crook 11313:
1.78 anton 11314: Languages with a slow edit/compile/link/test development loop tend to
11315: require sophisticated tracing/stepping debuggers to facilate debugging.
1.21 crook 11316:
1.78 anton 11317: A much better (faster) way in fast-compiling languages is to add
11318: printing code at well-selected places, let the program run, look at
11319: the output, see where things went wrong, add more printing code, etc.,
11320: until the bug is found.
1.21 crook 11321:
1.78 anton 11322: The simple debugging aids provided in @file{debugs.fs}
11323: are meant to support this style of debugging.
1.21 crook 11324:
1.78 anton 11325: The word @code{~~} prints debugging information (by default the source
11326: location and the stack contents). It is easy to insert. If you use Emacs
11327: it is also easy to remove (@kbd{C-x ~} in the Emacs Forth mode to
11328: query-replace them with nothing). The deferred words
11329: @code{printdebugdata} and @code{printdebugline} control the output of
11330: @code{~~}. The default source location output format works well with
11331: Emacs' compilation mode, so you can step through the program at the
11332: source level using @kbd{C-x `} (the advantage over a stepping debugger
11333: is that you can step in any direction and you know where the crash has
11334: happened or where the strange data has occurred).
1.21 crook 11335:
1.78 anton 11336: doc-~~
11337: doc-printdebugdata
11338: doc-printdebugline
1.21 crook 11339:
1.78 anton 11340: @node Assertions, Singlestep Debugger, Debugging, Programming Tools
11341: @subsection Assertions
11342: @cindex assertions
1.21 crook 11343:
1.78 anton 11344: It is a good idea to make your programs self-checking, especially if you
11345: make an assumption that may become invalid during maintenance (for
11346: example, that a certain field of a data structure is never zero). Gforth
11347: supports @dfn{assertions} for this purpose. They are used like this:
1.21 crook 11348:
11349: @example
1.78 anton 11350: assert( @i{flag} )
1.26 crook 11351: @end example
11352:
1.78 anton 11353: The code between @code{assert(} and @code{)} should compute a flag, that
11354: should be true if everything is alright and false otherwise. It should
11355: not change anything else on the stack. The overall stack effect of the
11356: assertion is @code{( -- )}. E.g.
1.21 crook 11357:
1.26 crook 11358: @example
1.78 anton 11359: assert( 1 1 + 2 = ) \ what we learn in school
11360: assert( dup 0<> ) \ assert that the top of stack is not zero
11361: assert( false ) \ this code should not be reached
1.21 crook 11362: @end example
11363:
1.78 anton 11364: The need for assertions is different at different times. During
11365: debugging, we want more checking, in production we sometimes care more
11366: for speed. Therefore, assertions can be turned off, i.e., the assertion
11367: becomes a comment. Depending on the importance of an assertion and the
11368: time it takes to check it, you may want to turn off some assertions and
11369: keep others turned on. Gforth provides several levels of assertions for
11370: this purpose:
11371:
11372:
11373: doc-assert0(
11374: doc-assert1(
11375: doc-assert2(
11376: doc-assert3(
11377: doc-assert(
11378: doc-)
1.21 crook 11379:
11380:
1.78 anton 11381: The variable @code{assert-level} specifies the highest assertions that
11382: are turned on. I.e., at the default @code{assert-level} of one,
11383: @code{assert0(} and @code{assert1(} assertions perform checking, while
11384: @code{assert2(} and @code{assert3(} assertions are treated as comments.
1.26 crook 11385:
1.78 anton 11386: The value of @code{assert-level} is evaluated at compile-time, not at
11387: run-time. Therefore you cannot turn assertions on or off at run-time;
11388: you have to set the @code{assert-level} appropriately before compiling a
11389: piece of code. You can compile different pieces of code at different
11390: @code{assert-level}s (e.g., a trusted library at level 1 and
11391: newly-written code at level 3).
1.26 crook 11392:
11393:
1.78 anton 11394: doc-assert-level
1.26 crook 11395:
11396:
1.78 anton 11397: If an assertion fails, a message compatible with Emacs' compilation mode
11398: is produced and the execution is aborted (currently with @code{ABORT"}.
11399: If there is interest, we will introduce a special throw code. But if you
11400: intend to @code{catch} a specific condition, using @code{throw} is
11401: probably more appropriate than an assertion).
1.44 crook 11402:
1.78 anton 11403: Definitions in ANS Forth for these assertion words are provided
11404: in @file{compat/assert.fs}.
1.26 crook 11405:
1.44 crook 11406:
1.78 anton 11407: @node Singlestep Debugger, , Assertions, Programming Tools
11408: @subsection Singlestep Debugger
11409: @cindex singlestep Debugger
11410: @cindex debugging Singlestep
1.44 crook 11411:
1.78 anton 11412: When you create a new word there's often the need to check whether it
11413: behaves correctly or not. You can do this by typing @code{dbg
11414: badword}. A debug session might look like this:
1.26 crook 11415:
1.78 anton 11416: @example
11417: : badword 0 DO i . LOOP ; ok
11418: 2 dbg badword
11419: : badword
11420: Scanning code...
1.44 crook 11421:
1.78 anton 11422: Nesting debugger ready!
1.44 crook 11423:
1.78 anton 11424: 400D4738 8049BC4 0 -> [ 2 ] 00002 00000
11425: 400D4740 8049F68 DO -> [ 0 ]
11426: 400D4744 804A0C8 i -> [ 1 ] 00000
11427: 400D4748 400C5E60 . -> 0 [ 0 ]
11428: 400D474C 8049D0C LOOP -> [ 0 ]
11429: 400D4744 804A0C8 i -> [ 1 ] 00001
11430: 400D4748 400C5E60 . -> 1 [ 0 ]
11431: 400D474C 8049D0C LOOP -> [ 0 ]
11432: 400D4758 804B384 ; -> ok
11433: @end example
1.21 crook 11434:
1.78 anton 11435: Each line displayed is one step. You always have to hit return to
11436: execute the next word that is displayed. If you don't want to execute
11437: the next word in a whole, you have to type @kbd{n} for @code{nest}. Here is
11438: an overview what keys are available:
1.44 crook 11439:
1.78 anton 11440: @table @i
1.44 crook 11441:
1.78 anton 11442: @item @key{RET}
11443: Next; Execute the next word.
1.21 crook 11444:
1.78 anton 11445: @item n
11446: Nest; Single step through next word.
1.44 crook 11447:
1.78 anton 11448: @item u
11449: Unnest; Stop debugging and execute rest of word. If we got to this word
11450: with nest, continue debugging with the calling word.
1.44 crook 11451:
1.78 anton 11452: @item d
11453: Done; Stop debugging and execute rest.
1.21 crook 11454:
1.78 anton 11455: @item s
11456: Stop; Abort immediately.
1.44 crook 11457:
1.78 anton 11458: @end table
1.44 crook 11459:
1.78 anton 11460: Debugging large application with this mechanism is very difficult, because
11461: you have to nest very deeply into the program before the interesting part
11462: begins. This takes a lot of time.
1.26 crook 11463:
1.78 anton 11464: To do it more directly put a @code{BREAK:} command into your source code.
11465: When program execution reaches @code{BREAK:} the single step debugger is
11466: invoked and you have all the features described above.
1.44 crook 11467:
1.78 anton 11468: If you have more than one part to debug it is useful to know where the
11469: program has stopped at the moment. You can do this by the
11470: @code{BREAK" string"} command. This behaves like @code{BREAK:} except that
11471: string is typed out when the ``breakpoint'' is reached.
1.44 crook 11472:
1.26 crook 11473:
1.78 anton 11474: doc-dbg
11475: doc-break:
11476: doc-break"
1.44 crook 11477:
11478:
1.26 crook 11479:
1.78 anton 11480: @c -------------------------------------------------------------
11481: @node Assembler and Code Words, Threading Words, Programming Tools, Words
11482: @section Assembler and Code Words
11483: @cindex assembler
11484: @cindex code words
1.44 crook 11485:
1.78 anton 11486: @menu
11487: * Code and ;code::
11488: * Common Assembler:: Assembler Syntax
11489: * Common Disassembler::
11490: * 386 Assembler:: Deviations and special cases
11491: * Alpha Assembler:: Deviations and special cases
11492: * MIPS assembler:: Deviations and special cases
11493: * Other assemblers:: How to write them
11494: @end menu
1.21 crook 11495:
1.78 anton 11496: @node Code and ;code, Common Assembler, Assembler and Code Words, Assembler and Code Words
11497: @subsection @code{Code} and @code{;code}
1.26 crook 11498:
1.78 anton 11499: Gforth provides some words for defining primitives (words written in
11500: machine code), and for defining the machine-code equivalent of
11501: @code{DOES>}-based defining words. However, the machine-independent
11502: nature of Gforth poses a few problems: First of all, Gforth runs on
11503: several architectures, so it can provide no standard assembler. What's
11504: worse is that the register allocation not only depends on the processor,
11505: but also on the @code{gcc} version and options used.
1.44 crook 11506:
1.78 anton 11507: The words that Gforth offers encapsulate some system dependences (e.g.,
11508: the header structure), so a system-independent assembler may be used in
11509: Gforth. If you do not have an assembler, you can compile machine code
11510: directly with @code{,} and @code{c,}@footnote{This isn't portable,
11511: because these words emit stuff in @i{data} space; it works because
11512: Gforth has unified code/data spaces. Assembler isn't likely to be
11513: portable anyway.}.
1.21 crook 11514:
1.44 crook 11515:
1.78 anton 11516: doc-assembler
11517: doc-init-asm
11518: doc-code
11519: doc-end-code
11520: doc-;code
11521: doc-flush-icache
1.44 crook 11522:
1.21 crook 11523:
1.78 anton 11524: If @code{flush-icache} does not work correctly, @code{code} words
11525: etc. will not work (reliably), either.
1.44 crook 11526:
1.78 anton 11527: The typical usage of these @code{code} words can be shown most easily by
11528: analogy to the equivalent high-level defining words:
1.44 crook 11529:
1.78 anton 11530: @example
11531: : foo code foo
11532: <high-level Forth words> <assembler>
11533: ; end-code
11534:
11535: : bar : bar
11536: <high-level Forth words> <high-level Forth words>
11537: CREATE CREATE
11538: <high-level Forth words> <high-level Forth words>
11539: DOES> ;code
11540: <high-level Forth words> <assembler>
11541: ; end-code
11542: @end example
1.21 crook 11543:
1.78 anton 11544: @c anton: the following stuff is also in "Common Assembler", in less detail.
1.44 crook 11545:
1.78 anton 11546: @cindex registers of the inner interpreter
11547: In the assembly code you will want to refer to the inner interpreter's
11548: registers (e.g., the data stack pointer) and you may want to use other
11549: registers for temporary storage. Unfortunately, the register allocation
11550: is installation-dependent.
1.44 crook 11551:
1.78 anton 11552: In particular, @code{ip} (Forth instruction pointer) and @code{rp}
11553: (return stack pointer) are in different places in @code{gforth} and
11554: @code{gforth-fast}. This means that you cannot write a @code{NEXT}
11555: routine that works on both versions; so for doing @code{NEXT}, I
11556: recomment jumping to @code{' noop >code-address}, which contains nothing
11557: but a @code{NEXT}.
1.21 crook 11558:
1.78 anton 11559: For general accesses to the inner interpreter's registers, the easiest
11560: solution is to use explicit register declarations (@pxref{Explicit Reg
11561: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) for
11562: all of the inner interpreter's registers: You have to compile Gforth
11563: with @code{-DFORCE_REG} (configure option @code{--enable-force-reg}) and
11564: the appropriate declarations must be present in the @code{machine.h}
11565: file (see @code{mips.h} for an example; you can find a full list of all
11566: declarable register symbols with @code{grep register engine.c}). If you
11567: give explicit registers to all variables that are declared at the
11568: beginning of @code{engine()}, you should be able to use the other
11569: caller-saved registers for temporary storage. Alternatively, you can use
11570: the @code{gcc} option @code{-ffixed-REG} (@pxref{Code Gen Options, ,
11571: Options for Code Generation Conventions, gcc.info, GNU C Manual}) to
11572: reserve a register (however, this restriction on register allocation may
11573: slow Gforth significantly).
1.44 crook 11574:
1.78 anton 11575: If this solution is not viable (e.g., because @code{gcc} does not allow
11576: you to explicitly declare all the registers you need), you have to find
11577: out by looking at the code where the inner interpreter's registers
11578: reside and which registers can be used for temporary storage. You can
11579: get an assembly listing of the engine's code with @code{make engine.s}.
1.44 crook 11580:
1.78 anton 11581: In any case, it is good practice to abstract your assembly code from the
11582: actual register allocation. E.g., if the data stack pointer resides in
11583: register @code{$17}, create an alias for this register called @code{sp},
11584: and use that in your assembly code.
1.21 crook 11585:
1.78 anton 11586: @cindex code words, portable
11587: Another option for implementing normal and defining words efficiently
11588: is to add the desired functionality to the source of Gforth. For normal
11589: words you just have to edit @file{primitives} (@pxref{Automatic
11590: Generation}). Defining words (equivalent to @code{;CODE} words, for fast
11591: defined words) may require changes in @file{engine.c}, @file{kernel.fs},
11592: @file{prims2x.fs}, and possibly @file{cross.fs}.
1.44 crook 11593:
1.78 anton 11594: @node Common Assembler, Common Disassembler, Code and ;code, Assembler and Code Words
11595: @subsection Common Assembler
1.44 crook 11596:
1.78 anton 11597: The assemblers in Gforth generally use a postfix syntax, i.e., the
11598: instruction name follows the operands.
1.21 crook 11599:
1.78 anton 11600: The operands are passed in the usual order (the same that is used in the
11601: manual of the architecture). Since they all are Forth words, they have
11602: to be separated by spaces; you can also use Forth words to compute the
11603: operands.
1.44 crook 11604:
1.78 anton 11605: The instruction names usually end with a @code{,}. This makes it easier
11606: to visually separate instructions if you put several of them on one
11607: line; it also avoids shadowing other Forth words (e.g., @code{and}).
1.21 crook 11608:
1.78 anton 11609: Registers are usually specified by number; e.g., (decimal) @code{11}
11610: specifies registers R11 and F11 on the Alpha architecture (which one,
11611: depends on the instruction). The usual names are also available, e.g.,
11612: @code{s2} for R11 on Alpha.
1.21 crook 11613:
1.78 anton 11614: Control flow is specified similar to normal Forth code (@pxref{Arbitrary
11615: control structures}), with @code{if,}, @code{ahead,}, @code{then,},
11616: @code{begin,}, @code{until,}, @code{again,}, @code{cs-roll},
11617: @code{cs-pick}, @code{else,}, @code{while,}, and @code{repeat,}. The
11618: conditions are specified in a way specific to each assembler.
1.1 anton 11619:
1.78 anton 11620: Note that the register assignments of the Gforth engine can change
11621: between Gforth versions, or even between different compilations of the
11622: same Gforth version (e.g., if you use a different GCC version). So if
11623: you want to refer to Gforth's registers (e.g., the stack pointer or
11624: TOS), I recommend defining your own words for refering to these
11625: registers, and using them later on; then you can easily adapt to a
11626: changed register assignment. The stability of the register assignment
11627: is usually better if you build Gforth with @code{--enable-force-reg}.
1.1 anton 11628:
1.78 anton 11629: In particular, the return stack pointer and the instruction pointer are
11630: in memory in @code{gforth}, and usually in registers in
11631: @code{gforth-fast}. The most common use of these registers is to
11632: dispatch to the next word (the @code{next} routine). A portable way to
11633: do this is to jump to @code{' noop >code-address} (of course, this is
11634: less efficient than integrating the @code{next} code and scheduling it
11635: well).
1.1 anton 11636:
1.78 anton 11637: @node Common Disassembler, 386 Assembler, Common Assembler, Assembler and Code Words
11638: @subsection Common Disassembler
1.1 anton 11639:
1.78 anton 11640: You can disassemble a @code{code} word with @code{see}
11641: (@pxref{Debugging}). You can disassemble a section of memory with
1.1 anton 11642:
1.78 anton 11643: doc-disasm
1.44 crook 11644:
1.78 anton 11645: The disassembler generally produces output that can be fed into the
11646: assembler (i.e., same syntax, etc.). It also includes additional
11647: information in comments. In particular, the address of the instruction
11648: is given in a comment before the instruction.
1.1 anton 11649:
1.78 anton 11650: @code{See} may display more or less than the actual code of the word,
11651: because the recognition of the end of the code is unreliable. You can
11652: use @code{disasm} if it did not display enough. It may display more, if
11653: the code word is not immediately followed by a named word. If you have
11654: something else there, you can follow the word with @code{align last @ ,}
11655: to ensure that the end is recognized.
1.21 crook 11656:
1.78 anton 11657: @node 386 Assembler, Alpha Assembler, Common Disassembler, Assembler and Code Words
11658: @subsection 386 Assembler
1.44 crook 11659:
1.78 anton 11660: The 386 assembler included in Gforth was written by Bernd Paysan, it's
11661: available under GPL, and originally part of bigFORTH.
1.21 crook 11662:
1.78 anton 11663: The 386 disassembler included in Gforth was written by Andrew McKewan
11664: and is in the public domain.
1.21 crook 11665:
1.78 anton 11666: The disassembler displays code in prefix Intel syntax.
1.21 crook 11667:
1.78 anton 11668: The assembler uses a postfix syntax with reversed parameters.
1.1 anton 11669:
1.78 anton 11670: The assembler includes all instruction of the Athlon, i.e. 486 core
11671: instructions, Pentium and PPro extensions, floating point, MMX, 3Dnow!,
11672: but not ISSE. It's an integrated 16- and 32-bit assembler. Default is 32
11673: bit, you can switch to 16 bit with .86 and back to 32 bit with .386.
1.1 anton 11674:
1.78 anton 11675: There are several prefixes to switch between different operation sizes,
11676: @code{.b} for byte accesses, @code{.w} for word accesses, @code{.d} for
11677: double-word accesses. Addressing modes can be switched with @code{.wa}
11678: for 16 bit addresses, and @code{.da} for 32 bit addresses. You don't
11679: need a prefix for byte register names (@code{AL} et al).
1.1 anton 11680:
1.78 anton 11681: For floating point operations, the prefixes are @code{.fs} (IEEE
11682: single), @code{.fl} (IEEE double), @code{.fx} (extended), @code{.fw}
11683: (word), @code{.fd} (double-word), and @code{.fq} (quad-word).
1.21 crook 11684:
1.78 anton 11685: The MMX opcodes don't have size prefixes, they are spelled out like in
11686: the Intel assembler. Instead of move from and to memory, there are
11687: PLDQ/PLDD and PSTQ/PSTD.
1.21 crook 11688:
1.78 anton 11689: The registers lack the 'e' prefix; even in 32 bit mode, eax is called
11690: ax. Immediate values are indicated by postfixing them with @code{#},
11691: e.g., @code{3 #}. Here are some examples of addressing modes:
1.21 crook 11692:
1.26 crook 11693: @example
1.78 anton 11694: 3 # \ immediate
11695: ax \ register
11696: 100 di d) \ 100[edi]
11697: 4 bx cx di) \ 4[ebx][ecx]
11698: di ax *4 i) \ [edi][eax*4]
11699: 20 ax *4 i#) \ 20[eax*4]
1.26 crook 11700: @end example
1.21 crook 11701:
1.78 anton 11702: Some example of instructions are:
1.1 anton 11703:
11704: @example
1.78 anton 11705: ax bx mov \ move ebx,eax
11706: 3 # ax mov \ mov eax,3
11707: 100 di ) ax mov \ mov eax,100[edi]
11708: 4 bx cx di) ax mov \ mov eax,4[ebx][ecx]
11709: .w ax bx mov \ mov bx,ax
1.1 anton 11710: @end example
11711:
1.78 anton 11712: The following forms are supported for binary instructions:
1.1 anton 11713:
11714: @example
1.78 anton 11715: <reg> <reg> <inst>
11716: <n> # <reg> <inst>
11717: <mem> <reg> <inst>
11718: <reg> <mem> <inst>
1.1 anton 11719: @end example
11720:
1.78 anton 11721: Immediate to memory is not supported. The shift/rotate syntax is:
1.1 anton 11722:
1.26 crook 11723: @example
1.78 anton 11724: <reg/mem> 1 # shl \ shortens to shift without immediate
11725: <reg/mem> 4 # shl
11726: <reg/mem> cl shl
1.26 crook 11727: @end example
1.1 anton 11728:
1.78 anton 11729: Precede string instructions (@code{movs} etc.) with @code{.b} to get
11730: the byte version.
1.1 anton 11731:
1.78 anton 11732: The control structure words @code{IF} @code{UNTIL} etc. must be preceded
11733: by one of these conditions: @code{vs vc u< u>= 0= 0<> u<= u> 0< 0>= ps
11734: pc < >= <= >}. (Note that most of these words shadow some Forth words
11735: when @code{assembler} is in front of @code{forth} in the search path,
11736: e.g., in @code{code} words). Currently the control structure words use
11737: one stack item, so you have to use @code{roll} instead of @code{cs-roll}
11738: to shuffle them (you can also use @code{swap} etc.).
1.21 crook 11739:
1.78 anton 11740: Here is an example of a @code{code} word (assumes that the stack pointer
11741: is in esi and the TOS is in ebx):
1.21 crook 11742:
1.26 crook 11743: @example
1.78 anton 11744: code my+ ( n1 n2 -- n )
11745: 4 si D) bx add
11746: 4 # si add
11747: Next
11748: end-code
1.26 crook 11749: @end example
1.21 crook 11750:
1.78 anton 11751: @node Alpha Assembler, MIPS assembler, 386 Assembler, Assembler and Code Words
11752: @subsection Alpha Assembler
1.21 crook 11753:
1.78 anton 11754: The Alpha assembler and disassembler were originally written by Bernd
11755: Thallner.
1.26 crook 11756:
1.78 anton 11757: The register names @code{a0}--@code{a5} are not available to avoid
11758: shadowing hex numbers.
1.2 jwilke 11759:
1.78 anton 11760: Immediate forms of arithmetic instructions are distinguished by a
11761: @code{#} just before the @code{,}, e.g., @code{and#,} (note: @code{lda,}
11762: does not count as arithmetic instruction).
1.2 jwilke 11763:
1.78 anton 11764: You have to specify all operands to an instruction, even those that
11765: other assemblers consider optional, e.g., the destination register for
11766: @code{br,}, or the destination register and hint for @code{jmp,}.
1.2 jwilke 11767:
1.78 anton 11768: You can specify conditions for @code{if,} by removing the first @code{b}
11769: and the trailing @code{,} from a branch with a corresponding name; e.g.,
1.2 jwilke 11770:
1.26 crook 11771: @example
1.78 anton 11772: 11 fgt if, \ if F11>0e
11773: ...
11774: endif,
1.26 crook 11775: @end example
1.2 jwilke 11776:
1.78 anton 11777: @code{fbgt,} gives @code{fgt}.
11778:
11779: @node MIPS assembler, Other assemblers, Alpha Assembler, Assembler and Code Words
11780: @subsection MIPS assembler
1.2 jwilke 11781:
1.78 anton 11782: The MIPS assembler was originally written by Christian Pirker.
1.2 jwilke 11783:
1.78 anton 11784: Currently the assembler and disassembler only cover the MIPS-I
11785: architecture (R3000), and don't support FP instructions.
1.2 jwilke 11786:
1.78 anton 11787: The register names @code{$a0}--@code{$a3} are not available to avoid
11788: shadowing hex numbers.
1.2 jwilke 11789:
1.78 anton 11790: Because there is no way to distinguish registers from immediate values,
11791: you have to explicitly use the immediate forms of instructions, i.e.,
11792: @code{addiu,}, not just @code{addu,} (@command{as} does this
11793: implicitly).
1.2 jwilke 11794:
1.78 anton 11795: If the architecture manual specifies several formats for the instruction
11796: (e.g., for @code{jalr,}), you usually have to use the one with more
11797: arguments (i.e., two for @code{jalr,}). When in doubt, see
11798: @code{arch/mips/testasm.fs} for an example of correct use.
1.2 jwilke 11799:
1.78 anton 11800: Branches and jumps in the MIPS architecture have a delay slot. You have
11801: to fill it yourself (the simplest way is to use @code{nop,}), the
11802: assembler does not do it for you (unlike @command{as}). Even
11803: @code{if,}, @code{ahead,}, @code{until,}, @code{again,}, @code{while,},
11804: @code{else,} and @code{repeat,} need a delay slot. Since @code{begin,}
11805: and @code{then,} just specify branch targets, they are not affected.
1.2 jwilke 11806:
1.78 anton 11807: Note that you must not put branches, jumps, or @code{li,} into the delay
11808: slot: @code{li,} may expand to several instructions, and control flow
11809: instructions may not be put into the branch delay slot in any case.
1.2 jwilke 11810:
1.78 anton 11811: For branches the argument specifying the target is a relative address;
11812: You have to add the address of the delay slot to get the absolute
11813: address.
1.1 anton 11814:
1.78 anton 11815: The MIPS architecture also has load delay slots and restrictions on
11816: using @code{mfhi,} and @code{mflo,}; you have to order the instructions
11817: yourself to satisfy these restrictions, the assembler does not do it for
11818: you.
1.1 anton 11819:
1.78 anton 11820: You can specify the conditions for @code{if,} etc. by taking a
11821: conditional branch and leaving away the @code{b} at the start and the
11822: @code{,} at the end. E.g.,
1.1 anton 11823:
1.26 crook 11824: @example
1.78 anton 11825: 4 5 eq if,
11826: ... \ do something if $4 equals $5
11827: then,
1.26 crook 11828: @end example
1.1 anton 11829:
1.78 anton 11830: @node Other assemblers, , MIPS assembler, Assembler and Code Words
11831: @subsection Other assemblers
11832:
11833: If you want to contribute another assembler/disassembler, please contact
11834: us (@email{bug-gforth@@gnu.org}) to check if we have such an assembler
11835: already. If you are writing them from scratch, please use a similar
11836: syntax style as the one we use (i.e., postfix, commas at the end of the
11837: instruction names, @pxref{Common Assembler}); make the output of the
11838: disassembler be valid input for the assembler, and keep the style
11839: similar to the style we used.
11840:
11841: Hints on implementation: The most important part is to have a good test
11842: suite that contains all instructions. Once you have that, the rest is
11843: easy. For actual coding you can take a look at
11844: @file{arch/mips/disasm.fs} to get some ideas on how to use data for both
11845: the assembler and disassembler, avoiding redundancy and some potential
11846: bugs. You can also look at that file (and @pxref{Advanced does> usage
11847: example}) to get ideas how to factor a disassembler.
11848:
11849: Start with the disassembler, because it's easier to reuse data from the
11850: disassembler for the assembler than the other way round.
1.1 anton 11851:
1.78 anton 11852: For the assembler, take a look at @file{arch/alpha/asm.fs}, which shows
11853: how simple it can be.
1.1 anton 11854:
1.78 anton 11855: @c -------------------------------------------------------------
11856: @node Threading Words, Passing Commands to the OS, Assembler and Code Words, Words
11857: @section Threading Words
11858: @cindex threading words
1.1 anton 11859:
1.78 anton 11860: @cindex code address
11861: These words provide access to code addresses and other threading stuff
11862: in Gforth (and, possibly, other interpretive Forths). It more or less
11863: abstracts away the differences between direct and indirect threading
11864: (and, for direct threading, the machine dependences). However, at
11865: present this wordset is still incomplete. It is also pretty low-level;
11866: some day it will hopefully be made unnecessary by an internals wordset
11867: that abstracts implementation details away completely.
1.1 anton 11868:
1.78 anton 11869: The terminology used here stems from indirect threaded Forth systems; in
11870: such a system, the XT of a word is represented by the CFA (code field
11871: address) of a word; the CFA points to a cell that contains the code
11872: address. The code address is the address of some machine code that
11873: performs the run-time action of invoking the word (e.g., the
11874: @code{dovar:} routine pushes the address of the body of the word (a
11875: variable) on the stack
11876: ).
1.1 anton 11877:
1.78 anton 11878: @cindex code address
11879: @cindex code field address
11880: In an indirect threaded Forth, you can get the code address of @i{name}
11881: with @code{' @i{name} @@}; in Gforth you can get it with @code{' @i{name}
11882: >code-address}, independent of the threading method.
1.1 anton 11883:
1.78 anton 11884: doc-threading-method
11885: doc->code-address
11886: doc-code-address!
1.1 anton 11887:
1.78 anton 11888: @cindex @code{does>}-handler
11889: @cindex @code{does>}-code
11890: For a word defined with @code{DOES>}, the code address usually points to
11891: a jump instruction (the @dfn{does-handler}) that jumps to the dodoes
11892: routine (in Gforth on some platforms, it can also point to the dodoes
11893: routine itself). What you are typically interested in, though, is
11894: whether a word is a @code{DOES>}-defined word, and what Forth code it
11895: executes; @code{>does-code} tells you that.
1.1 anton 11896:
1.78 anton 11897: doc->does-code
1.1 anton 11898:
1.78 anton 11899: To create a @code{DOES>}-defined word with the following basic words,
11900: you have to set up a @code{DOES>}-handler with @code{does-handler!};
11901: @code{/does-handler} aus behind you have to place your executable Forth
11902: code. Finally you have to create a word and modify its behaviour with
11903: @code{does-handler!}.
1.1 anton 11904:
1.78 anton 11905: doc-does-code!
11906: doc-does-handler!
11907: doc-/does-handler
1.1 anton 11908:
1.78 anton 11909: The code addresses produced by various defining words are produced by
11910: the following words:
1.1 anton 11911:
1.78 anton 11912: doc-docol:
11913: doc-docon:
11914: doc-dovar:
11915: doc-douser:
11916: doc-dodefer:
11917: doc-dofield:
1.1 anton 11918:
1.26 crook 11919: @c -------------------------------------------------------------
1.78 anton 11920: @node Passing Commands to the OS, Keeping track of Time, Threading Words, Words
1.21 crook 11921: @section Passing Commands to the Operating System
11922: @cindex operating system - passing commands
11923: @cindex shell commands
11924:
11925: Gforth allows you to pass an arbitrary string to the host operating
11926: system shell (if such a thing exists) for execution.
11927:
1.44 crook 11928:
1.21 crook 11929: doc-sh
11930: doc-system
11931: doc-$?
1.23 crook 11932: doc-getenv
1.21 crook 11933:
1.44 crook 11934:
1.26 crook 11935: @c -------------------------------------------------------------
1.47 crook 11936: @node Keeping track of Time, Miscellaneous Words, Passing Commands to the OS, Words
11937: @section Keeping track of Time
11938: @cindex time-related words
11939:
11940: doc-ms
11941: doc-time&date
1.79 anton 11942: doc-utime
11943: doc-cputime
1.47 crook 11944:
11945:
11946: @c -------------------------------------------------------------
11947: @node Miscellaneous Words, , Keeping track of Time, Words
1.21 crook 11948: @section Miscellaneous Words
11949: @cindex miscellaneous words
11950:
1.29 crook 11951: @comment TODO find homes for these
11952:
1.26 crook 11953: These section lists the ANS Forth words that are not documented
1.21 crook 11954: elsewhere in this manual. Ultimately, they all need proper homes.
11955:
1.68 anton 11956: doc-quit
1.44 crook 11957:
1.26 crook 11958: The following ANS Forth words are not currently supported by Gforth
1.27 crook 11959: (@pxref{ANS conformance}):
1.21 crook 11960:
11961: @code{EDITOR}
11962: @code{EMIT?}
11963: @code{FORGET}
11964:
1.24 anton 11965: @c ******************************************************************
11966: @node Error messages, Tools, Words, Top
11967: @chapter Error messages
11968: @cindex error messages
11969: @cindex backtrace
11970:
11971: A typical Gforth error message looks like this:
11972:
11973: @example
11974: in file included from :-1
11975: in file included from ./yyy.fs:1
11976: ./xxx.fs:4: Invalid memory address
11977: bar
11978: ^^^
1.79 anton 11979: Backtrace:
1.25 anton 11980: $400E664C @@
11981: $400E6664 foo
1.24 anton 11982: @end example
11983:
11984: The message identifying the error is @code{Invalid memory address}. The
11985: error happened when text-interpreting line 4 of the file
11986: @file{./xxx.fs}. This line is given (it contains @code{bar}), and the
11987: word on the line where the error happened, is pointed out (with
11988: @code{^^^}).
11989:
11990: The file containing the error was included in line 1 of @file{./yyy.fs},
11991: and @file{yyy.fs} was included from a non-file (in this case, by giving
11992: @file{yyy.fs} as command-line parameter to Gforth).
11993:
11994: At the end of the error message you find a return stack dump that can be
11995: interpreted as a backtrace (possibly empty). On top you find the top of
11996: the return stack when the @code{throw} happened, and at the bottom you
11997: find the return stack entry just above the return stack of the topmost
11998: text interpreter.
11999:
12000: To the right of most return stack entries you see a guess for the word
12001: that pushed that return stack entry as its return address. This gives a
12002: backtrace. In our case we see that @code{bar} called @code{foo}, and
12003: @code{foo} called @code{@@} (and @code{@@} had an @emph{Invalid memory
12004: address} exception).
12005:
12006: Note that the backtrace is not perfect: We don't know which return stack
12007: entries are return addresses (so we may get false positives); and in
12008: some cases (e.g., for @code{abort"}) we cannot determine from the return
12009: address the word that pushed the return address, so for some return
12010: addresses you see no names in the return stack dump.
1.25 anton 12011:
12012: @cindex @code{catch} and backtraces
12013: The return stack dump represents the return stack at the time when a
12014: specific @code{throw} was executed. In programs that make use of
12015: @code{catch}, it is not necessarily clear which @code{throw} should be
12016: used for the return stack dump (e.g., consider one @code{throw} that
12017: indicates an error, which is caught, and during recovery another error
1.42 anton 12018: happens; which @code{throw} should be used for the stack dump?). Gforth
1.25 anton 12019: presents the return stack dump for the first @code{throw} after the last
12020: executed (not returned-to) @code{catch}; this works well in the usual
12021: case.
12022:
12023: @cindex @code{gforth-fast} and backtraces
12024: @cindex @code{gforth-fast}, difference from @code{gforth}
12025: @cindex backtraces with @code{gforth-fast}
12026: @cindex return stack dump with @code{gforth-fast}
1.79 anton 12027: @code{Gforth} is able to do a return stack dump for throws generated
1.25 anton 12028: from primitives (e.g., invalid memory address, stack empty etc.);
12029: @code{gforth-fast} is only able to do a return stack dump from a
12030: directly called @code{throw} (including @code{abort} etc.). This is the
1.30 anton 12031: only difference (apart from a speed factor of between 1.15 (K6-2) and
1.78 anton 12032: 2 (21264)) between @code{gforth} and @code{gforth-fast}. Given an
1.30 anton 12033: exception caused by a primitive in @code{gforth-fast}, you will
12034: typically see no return stack dump at all; however, if the exception is
12035: caught by @code{catch} (e.g., for restoring some state), and then
12036: @code{throw}n again, the return stack dump will be for the first such
12037: @code{throw}.
1.2 jwilke 12038:
1.5 anton 12039: @c ******************************************************************
1.24 anton 12040: @node Tools, ANS conformance, Error messages, Top
1.1 anton 12041: @chapter Tools
12042:
12043: @menu
12044: * ANS Report:: Report the words used, sorted by wordset.
12045: @end menu
12046:
12047: See also @ref{Emacs and Gforth}.
12048:
12049: @node ANS Report, , Tools, Tools
12050: @section @file{ans-report.fs}: Report the words used, sorted by wordset
12051: @cindex @file{ans-report.fs}
12052: @cindex report the words used in your program
12053: @cindex words used in your program
12054:
12055: If you want to label a Forth program as ANS Forth Program, you must
12056: document which wordsets the program uses; for extension wordsets, it is
12057: helpful to list the words the program requires from these wordsets
12058: (because Forth systems are allowed to provide only some words of them).
12059:
12060: The @file{ans-report.fs} tool makes it easy for you to determine which
12061: words from which wordset and which non-ANS words your application
12062: uses. You simply have to include @file{ans-report.fs} before loading the
12063: program you want to check. After loading your program, you can get the
12064: report with @code{print-ans-report}. A typical use is to run this as
12065: batch job like this:
12066: @example
12067: gforth ans-report.fs myprog.fs -e "print-ans-report bye"
12068: @end example
12069:
12070: The output looks like this (for @file{compat/control.fs}):
12071: @example
12072: The program uses the following words
12073: from CORE :
12074: : POSTPONE THEN ; immediate ?dup IF 0=
12075: from BLOCK-EXT :
12076: \
12077: from FILE :
12078: (
12079: @end example
12080:
12081: @subsection Caveats
12082:
12083: Note that @file{ans-report.fs} just checks which words are used, not whether
12084: they are used in an ANS Forth conforming way!
12085:
12086: Some words are defined in several wordsets in the
12087: standard. @file{ans-report.fs} reports them for only one of the
12088: wordsets, and not necessarily the one you expect. It depends on usage
12089: which wordset is the right one to specify. E.g., if you only use the
12090: compilation semantics of @code{S"}, it is a Core word; if you also use
12091: its interpretation semantics, it is a File word.
12092:
12093: @c ******************************************************************
1.65 anton 12094: @node ANS conformance, Standard vs Extensions, Tools, Top
1.1 anton 12095: @chapter ANS conformance
12096: @cindex ANS conformance of Gforth
12097:
12098: To the best of our knowledge, Gforth is an
12099:
12100: ANS Forth System
12101: @itemize @bullet
12102: @item providing the Core Extensions word set
12103: @item providing the Block word set
12104: @item providing the Block Extensions word set
12105: @item providing the Double-Number word set
12106: @item providing the Double-Number Extensions word set
12107: @item providing the Exception word set
12108: @item providing the Exception Extensions word set
12109: @item providing the Facility word set
1.40 anton 12110: @item providing @code{EKEY}, @code{EKEY>CHAR}, @code{EKEY?}, @code{MS} and @code{TIME&DATE} from the Facility Extensions word set
1.1 anton 12111: @item providing the File Access word set
12112: @item providing the File Access Extensions word set
12113: @item providing the Floating-Point word set
12114: @item providing the Floating-Point Extensions word set
12115: @item providing the Locals word set
12116: @item providing the Locals Extensions word set
12117: @item providing the Memory-Allocation word set
12118: @item providing the Memory-Allocation Extensions word set (that one's easy)
12119: @item providing the Programming-Tools word set
12120: @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
12121: @item providing the Search-Order word set
12122: @item providing the Search-Order Extensions word set
12123: @item providing the String word set
12124: @item providing the String Extensions word set (another easy one)
12125: @end itemize
12126:
12127: @cindex system documentation
12128: In addition, ANS Forth systems are required to document certain
12129: implementation choices. This chapter tries to meet these
12130: requirements. In many cases it gives a way to ask the system for the
12131: information instead of providing the information directly, in
12132: particular, if the information depends on the processor, the operating
12133: system or the installation options chosen, or if they are likely to
12134: change during the maintenance of Gforth.
12135:
12136: @comment The framework for the rest has been taken from pfe.
12137:
12138: @menu
12139: * The Core Words::
12140: * The optional Block word set::
12141: * The optional Double Number word set::
12142: * The optional Exception word set::
12143: * The optional Facility word set::
12144: * The optional File-Access word set::
12145: * The optional Floating-Point word set::
12146: * The optional Locals word set::
12147: * The optional Memory-Allocation word set::
12148: * The optional Programming-Tools word set::
12149: * The optional Search-Order word set::
12150: @end menu
12151:
12152:
12153: @c =====================================================================
12154: @node The Core Words, The optional Block word set, ANS conformance, ANS conformance
12155: @comment node-name, next, previous, up
12156: @section The Core Words
12157: @c =====================================================================
12158: @cindex core words, system documentation
12159: @cindex system documentation, core words
12160:
12161: @menu
12162: * core-idef:: Implementation Defined Options
12163: * core-ambcond:: Ambiguous Conditions
12164: * core-other:: Other System Documentation
12165: @end menu
12166:
12167: @c ---------------------------------------------------------------------
12168: @node core-idef, core-ambcond, The Core Words, The Core Words
12169: @subsection Implementation Defined Options
12170: @c ---------------------------------------------------------------------
12171: @cindex core words, implementation-defined options
12172: @cindex implementation-defined options, core words
12173:
12174:
12175: @table @i
12176: @item (Cell) aligned addresses:
12177: @cindex cell-aligned addresses
12178: @cindex aligned addresses
12179: processor-dependent. Gforth's alignment words perform natural alignment
12180: (e.g., an address aligned for a datum of size 8 is divisible by
12181: 8). Unaligned accesses usually result in a @code{-23 THROW}.
12182:
12183: @item @code{EMIT} and non-graphic characters:
12184: @cindex @code{EMIT} and non-graphic characters
12185: @cindex non-graphic characters and @code{EMIT}
12186: The character is output using the C library function (actually, macro)
12187: @code{putc}.
12188:
12189: @item character editing of @code{ACCEPT} and @code{EXPECT}:
12190: @cindex character editing of @code{ACCEPT} and @code{EXPECT}
12191: @cindex editing in @code{ACCEPT} and @code{EXPECT}
12192: @cindex @code{ACCEPT}, editing
12193: @cindex @code{EXPECT}, editing
12194: This is modeled on the GNU readline library (@pxref{Readline
12195: Interaction, , Command Line Editing, readline, The GNU Readline
12196: Library}) with Emacs-like key bindings. @kbd{Tab} deviates a little by
12197: producing a full word completion every time you type it (instead of
1.28 crook 12198: producing the common prefix of all completions). @xref{Command-line editing}.
1.1 anton 12199:
12200: @item character set:
12201: @cindex character set
12202: The character set of your computer and display device. Gforth is
12203: 8-bit-clean (but some other component in your system may make trouble).
12204:
12205: @item Character-aligned address requirements:
12206: @cindex character-aligned address requirements
12207: installation-dependent. Currently a character is represented by a C
12208: @code{unsigned char}; in the future we might switch to @code{wchar_t}
12209: (Comments on that requested).
12210:
12211: @item character-set extensions and matching of names:
12212: @cindex character-set extensions and matching of names
1.26 crook 12213: @cindex case-sensitivity for name lookup
12214: @cindex name lookup, case-sensitivity
12215: @cindex locale and case-sensitivity
1.21 crook 12216: Any character except the ASCII NUL character can be used in a
1.1 anton 12217: name. Matching is case-insensitive (except in @code{TABLE}s). The
1.47 crook 12218: matching is performed using the C library function @code{strncasecmp}, whose
1.1 anton 12219: function is probably influenced by the locale. E.g., the @code{C} locale
12220: does not know about accents and umlauts, so they are matched
12221: case-sensitively in that locale. For portability reasons it is best to
12222: write programs such that they work in the @code{C} locale. Then one can
12223: use libraries written by a Polish programmer (who might use words
12224: containing ISO Latin-2 encoded characters) and by a French programmer
12225: (ISO Latin-1) in the same program (of course, @code{WORDS} will produce
12226: funny results for some of the words (which ones, depends on the font you
12227: are using)). Also, the locale you prefer may not be available in other
12228: operating systems. Hopefully, Unicode will solve these problems one day.
12229:
12230: @item conditions under which control characters match a space delimiter:
12231: @cindex space delimiters
12232: @cindex control characters as delimiters
12233: If @code{WORD} is called with the space character as a delimiter, all
12234: white-space characters (as identified by the C macro @code{isspace()})
12235: are delimiters. @code{PARSE}, on the other hand, treats space like other
1.44 crook 12236: delimiters. @code{SWORD} treats space like @code{WORD}, but behaves
1.79 anton 12237: like @code{PARSE} otherwise. @code{Name}, which is used by the outer
1.1 anton 12238: interpreter (aka text interpreter) by default, treats all white-space
12239: characters as delimiters.
12240:
1.26 crook 12241: @item format of the control-flow stack:
12242: @cindex control-flow stack, format
12243: The data stack is used as control-flow stack. The size of a control-flow
1.1 anton 12244: stack item in cells is given by the constant @code{cs-item-size}. At the
12245: time of this writing, an item consists of a (pointer to a) locals list
12246: (third), an address in the code (second), and a tag for identifying the
12247: item (TOS). The following tags are used: @code{defstart},
12248: @code{live-orig}, @code{dead-orig}, @code{dest}, @code{do-dest},
12249: @code{scopestart}.
12250:
12251: @item conversion of digits > 35
12252: @cindex digits > 35
12253: The characters @code{[\]^_'} are the digits with the decimal value
12254: 36@minus{}41. There is no way to input many of the larger digits.
12255:
12256: @item display after input terminates in @code{ACCEPT} and @code{EXPECT}:
12257: @cindex @code{EXPECT}, display after end of input
12258: @cindex @code{ACCEPT}, display after end of input
12259: The cursor is moved to the end of the entered string. If the input is
12260: terminated using the @kbd{Return} key, a space is typed.
12261:
12262: @item exception abort sequence of @code{ABORT"}:
12263: @cindex exception abort sequence of @code{ABORT"}
12264: @cindex @code{ABORT"}, exception abort sequence
12265: The error string is stored into the variable @code{"error} and a
12266: @code{-2 throw} is performed.
12267:
12268: @item input line terminator:
12269: @cindex input line terminator
12270: @cindex line terminator on input
1.26 crook 12271: @cindex newline character on input
1.1 anton 12272: For interactive input, @kbd{C-m} (CR) and @kbd{C-j} (LF) terminate
12273: lines. One of these characters is typically produced when you type the
12274: @kbd{Enter} or @kbd{Return} key.
12275:
12276: @item maximum size of a counted string:
12277: @cindex maximum size of a counted string
12278: @cindex counted string, maximum size
12279: @code{s" /counted-string" environment? drop .}. Currently 255 characters
1.79 anton 12280: on all platforms, but this may change.
1.1 anton 12281:
12282: @item maximum size of a parsed string:
12283: @cindex maximum size of a parsed string
12284: @cindex parsed string, maximum size
12285: Given by the constant @code{/line}. Currently 255 characters.
12286:
12287: @item maximum size of a definition name, in characters:
12288: @cindex maximum size of a definition name, in characters
12289: @cindex name, maximum length
12290: 31
12291:
12292: @item maximum string length for @code{ENVIRONMENT?}, in characters:
12293: @cindex maximum string length for @code{ENVIRONMENT?}, in characters
12294: @cindex @code{ENVIRONMENT?} string length, maximum
12295: 31
12296:
12297: @item method of selecting the user input device:
12298: @cindex user input device, method of selecting
12299: The user input device is the standard input. There is currently no way to
12300: change it from within Gforth. However, the input can typically be
12301: redirected in the command line that starts Gforth.
12302:
12303: @item method of selecting the user output device:
12304: @cindex user output device, method of selecting
12305: @code{EMIT} and @code{TYPE} output to the file-id stored in the value
1.10 anton 12306: @code{outfile-id} (@code{stdout} by default). Gforth uses unbuffered
12307: output when the user output device is a terminal, otherwise the output
12308: is buffered.
1.1 anton 12309:
12310: @item methods of dictionary compilation:
12311: What are we expected to document here?
12312:
12313: @item number of bits in one address unit:
12314: @cindex number of bits in one address unit
12315: @cindex address unit, size in bits
12316: @code{s" address-units-bits" environment? drop .}. 8 in all current
1.79 anton 12317: platforms.
1.1 anton 12318:
12319: @item number representation and arithmetic:
12320: @cindex number representation and arithmetic
1.79 anton 12321: Processor-dependent. Binary two's complement on all current platforms.
1.1 anton 12322:
12323: @item ranges for integer types:
12324: @cindex ranges for integer types
12325: @cindex integer types, ranges
12326: Installation-dependent. Make environmental queries for @code{MAX-N},
12327: @code{MAX-U}, @code{MAX-D} and @code{MAX-UD}. The lower bounds for
12328: unsigned (and positive) types is 0. The lower bound for signed types on
12329: two's complement and one's complement machines machines can be computed
12330: by adding 1 to the upper bound.
12331:
12332: @item read-only data space regions:
12333: @cindex read-only data space regions
12334: @cindex data-space, read-only regions
12335: The whole Forth data space is writable.
12336:
12337: @item size of buffer at @code{WORD}:
12338: @cindex size of buffer at @code{WORD}
12339: @cindex @code{WORD} buffer size
12340: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
12341: shared with the pictured numeric output string. If overwriting
12342: @code{PAD} is acceptable, it is as large as the remaining dictionary
12343: space, although only as much can be sensibly used as fits in a counted
12344: string.
12345:
12346: @item size of one cell in address units:
12347: @cindex cell size
12348: @code{1 cells .}.
12349:
12350: @item size of one character in address units:
12351: @cindex char size
1.79 anton 12352: @code{1 chars .}. 1 on all current platforms.
1.1 anton 12353:
12354: @item size of the keyboard terminal buffer:
12355: @cindex size of the keyboard terminal buffer
12356: @cindex terminal buffer, size
12357: Varies. You can determine the size at a specific time using @code{lp@@
12358: tib - .}. It is shared with the locals stack and TIBs of files that
12359: include the current file. You can change the amount of space for TIBs
12360: and locals stack at Gforth startup with the command line option
12361: @code{-l}.
12362:
12363: @item size of the pictured numeric output buffer:
12364: @cindex size of the pictured numeric output buffer
12365: @cindex pictured numeric output buffer, size
12366: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
12367: shared with @code{WORD}.
12368:
12369: @item size of the scratch area returned by @code{PAD}:
12370: @cindex size of the scratch area returned by @code{PAD}
12371: @cindex @code{PAD} size
12372: The remainder of dictionary space. @code{unused pad here - - .}.
12373:
12374: @item system case-sensitivity characteristics:
12375: @cindex case-sensitivity characteristics
1.26 crook 12376: Dictionary searches are case-insensitive (except in
1.1 anton 12377: @code{TABLE}s). However, as explained above under @i{character-set
12378: extensions}, the matching for non-ASCII characters is determined by the
12379: locale you are using. In the default @code{C} locale all non-ASCII
12380: characters are matched case-sensitively.
12381:
12382: @item system prompt:
12383: @cindex system prompt
12384: @cindex prompt
12385: @code{ ok} in interpret state, @code{ compiled} in compile state.
12386:
12387: @item division rounding:
12388: @cindex division rounding
12389: installation dependent. @code{s" floored" environment? drop .}. We leave
12390: the choice to @code{gcc} (what to use for @code{/}) and to you (whether
12391: to use @code{fm/mod}, @code{sm/rem} or simply @code{/}).
12392:
12393: @item values of @code{STATE} when true:
12394: @cindex @code{STATE} values
12395: -1.
12396:
12397: @item values returned after arithmetic overflow:
12398: On two's complement machines, arithmetic is performed modulo
12399: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
12400: arithmetic (with appropriate mapping for signed types). Division by zero
12401: typically results in a @code{-55 throw} (Floating-point unidentified
1.80 anton 12402: fault) or @code{-10 throw} (divide by zero).
1.1 anton 12403:
12404: @item whether the current definition can be found after @t{DOES>}:
12405: @cindex @t{DOES>}, visibility of current definition
12406: No.
12407:
12408: @end table
12409:
12410: @c ---------------------------------------------------------------------
12411: @node core-ambcond, core-other, core-idef, The Core Words
12412: @subsection Ambiguous conditions
12413: @c ---------------------------------------------------------------------
12414: @cindex core words, ambiguous conditions
12415: @cindex ambiguous conditions, core words
12416:
12417: @table @i
12418:
12419: @item a name is neither a word nor a number:
12420: @cindex name not found
1.26 crook 12421: @cindex undefined word
1.80 anton 12422: @code{-13 throw} (Undefined word).
1.1 anton 12423:
12424: @item a definition name exceeds the maximum length allowed:
1.26 crook 12425: @cindex word name too long
1.1 anton 12426: @code{-19 throw} (Word name too long)
12427:
12428: @item addressing a region not inside the various data spaces of the forth system:
12429: @cindex Invalid memory address
1.32 anton 12430: The stacks, code space and header space are accessible. Machine code space is
1.1 anton 12431: typically readable. Accessing other addresses gives results dependent on
12432: the operating system. On decent systems: @code{-9 throw} (Invalid memory
12433: address).
12434:
12435: @item argument type incompatible with parameter:
1.26 crook 12436: @cindex argument type mismatch
1.1 anton 12437: This is usually not caught. Some words perform checks, e.g., the control
12438: flow words, and issue a @code{ABORT"} or @code{-12 THROW} (Argument type
12439: mismatch).
12440:
12441: @item attempting to obtain the execution token of a word with undefined execution semantics:
12442: @cindex Interpreting a compile-only word, for @code{'} etc.
12443: @cindex execution token of words with undefined execution semantics
12444: @code{-14 throw} (Interpreting a compile-only word). In some cases, you
12445: get an execution token for @code{compile-only-error} (which performs a
12446: @code{-14 throw} when executed).
12447:
12448: @item dividing by zero:
12449: @cindex dividing by zero
12450: @cindex floating point unidentified fault, integer division
1.80 anton 12451: On some platforms, this produces a @code{-10 throw} (Division by
1.24 anton 12452: zero); on other systems, this typically results in a @code{-55 throw}
12453: (Floating-point unidentified fault).
1.1 anton 12454:
12455: @item insufficient data stack or return stack space:
12456: @cindex insufficient data stack or return stack space
12457: @cindex stack overflow
1.26 crook 12458: @cindex address alignment exception, stack overflow
1.1 anton 12459: @cindex Invalid memory address, stack overflow
12460: Depending on the operating system, the installation, and the invocation
12461: of Gforth, this is either checked by the memory management hardware, or
1.24 anton 12462: it is not checked. If it is checked, you typically get a @code{-3 throw}
12463: (Stack overflow), @code{-5 throw} (Return stack overflow), or @code{-9
12464: throw} (Invalid memory address) (depending on the platform and how you
12465: achieved the overflow) as soon as the overflow happens. If it is not
12466: checked, overflows typically result in mysterious illegal memory
12467: accesses, producing @code{-9 throw} (Invalid memory address) or
12468: @code{-23 throw} (Address alignment exception); they might also destroy
12469: the internal data structure of @code{ALLOCATE} and friends, resulting in
12470: various errors in these words.
1.1 anton 12471:
12472: @item insufficient space for loop control parameters:
12473: @cindex insufficient space for loop control parameters
1.80 anton 12474: Like other return stack overflows.
1.1 anton 12475:
12476: @item insufficient space in the dictionary:
12477: @cindex insufficient space in the dictionary
12478: @cindex dictionary overflow
1.12 anton 12479: If you try to allot (either directly with @code{allot}, or indirectly
12480: with @code{,}, @code{create} etc.) more memory than available in the
12481: dictionary, you get a @code{-8 throw} (Dictionary overflow). If you try
12482: to access memory beyond the end of the dictionary, the results are
12483: similar to stack overflows.
1.1 anton 12484:
12485: @item interpreting a word with undefined interpretation semantics:
12486: @cindex interpreting a word with undefined interpretation semantics
12487: @cindex Interpreting a compile-only word
12488: For some words, we have defined interpretation semantics. For the
12489: others: @code{-14 throw} (Interpreting a compile-only word).
12490:
12491: @item modifying the contents of the input buffer or a string literal:
12492: @cindex modifying the contents of the input buffer or a string literal
12493: These are located in writable memory and can be modified.
12494:
12495: @item overflow of the pictured numeric output string:
12496: @cindex overflow of the pictured numeric output string
12497: @cindex pictured numeric output string, overflow
1.24 anton 12498: @code{-17 throw} (Pictured numeric ouput string overflow).
1.1 anton 12499:
12500: @item parsed string overflow:
12501: @cindex parsed string overflow
12502: @code{PARSE} cannot overflow. @code{WORD} does not check for overflow.
12503:
12504: @item producing a result out of range:
12505: @cindex result out of range
12506: On two's complement machines, arithmetic is performed modulo
12507: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
12508: arithmetic (with appropriate mapping for signed types). Division by zero
1.24 anton 12509: typically results in a @code{-10 throw} (divide by zero) or @code{-55
12510: throw} (floating point unidentified fault). @code{convert} and
12511: @code{>number} currently overflow silently.
1.1 anton 12512:
12513: @item reading from an empty data or return stack:
12514: @cindex stack empty
12515: @cindex stack underflow
1.24 anton 12516: @cindex return stack underflow
1.1 anton 12517: The data stack is checked by the outer (aka text) interpreter after
12518: every word executed. If it has underflowed, a @code{-4 throw} (Stack
12519: underflow) is performed. Apart from that, stacks may be checked or not,
1.24 anton 12520: depending on operating system, installation, and invocation. If they are
12521: caught by a check, they typically result in @code{-4 throw} (Stack
12522: underflow), @code{-6 throw} (Return stack underflow) or @code{-9 throw}
12523: (Invalid memory address), depending on the platform and which stack
12524: underflows and by how much. Note that even if the system uses checking
12525: (through the MMU), your program may have to underflow by a significant
12526: number of stack items to trigger the reaction (the reason for this is
12527: that the MMU, and therefore the checking, works with a page-size
12528: granularity). If there is no checking, the symptoms resulting from an
12529: underflow are similar to those from an overflow. Unbalanced return
1.80 anton 12530: stack errors can result in a variety of symptoms, including @code{-9 throw}
1.24 anton 12531: (Invalid memory address) and Illegal Instruction (typically @code{-260
12532: throw}).
1.1 anton 12533:
12534: @item unexpected end of the input buffer, resulting in an attempt to use a zero-length string as a name:
12535: @cindex unexpected end of the input buffer
12536: @cindex zero-length string as a name
12537: @cindex Attempt to use zero-length string as a name
12538: @code{Create} and its descendants perform a @code{-16 throw} (Attempt to
12539: use zero-length string as a name). Words like @code{'} probably will not
12540: find what they search. Note that it is possible to create zero-length
12541: names with @code{nextname} (should it not?).
12542:
12543: @item @code{>IN} greater than input buffer:
12544: @cindex @code{>IN} greater than input buffer
12545: The next invocation of a parsing word returns a string with length 0.
12546:
12547: @item @code{RECURSE} appears after @code{DOES>}:
12548: @cindex @code{RECURSE} appears after @code{DOES>}
12549: Compiles a recursive call to the defining word, not to the defined word.
12550:
12551: @item argument input source different than current input source for @code{RESTORE-INPUT}:
12552: @cindex argument input source different than current input source for @code{RESTORE-INPUT}
1.26 crook 12553: @cindex argument type mismatch, @code{RESTORE-INPUT}
1.1 anton 12554: @cindex @code{RESTORE-INPUT}, Argument type mismatch
12555: @code{-12 THROW}. Note that, once an input file is closed (e.g., because
12556: the end of the file was reached), its source-id may be
12557: reused. Therefore, restoring an input source specification referencing a
12558: closed file may lead to unpredictable results instead of a @code{-12
12559: THROW}.
12560:
12561: In the future, Gforth may be able to restore input source specifications
12562: from other than the current input source.
12563:
12564: @item data space containing definitions gets de-allocated:
12565: @cindex data space containing definitions gets de-allocated
12566: Deallocation with @code{allot} is not checked. This typically results in
12567: memory access faults or execution of illegal instructions.
12568:
12569: @item data space read/write with incorrect alignment:
12570: @cindex data space read/write with incorrect alignment
12571: @cindex alignment faults
1.26 crook 12572: @cindex address alignment exception
1.1 anton 12573: Processor-dependent. Typically results in a @code{-23 throw} (Address
1.12 anton 12574: alignment exception). Under Linux-Intel on a 486 or later processor with
1.1 anton 12575: alignment turned on, incorrect alignment results in a @code{-9 throw}
12576: (Invalid memory address). There are reportedly some processors with
1.12 anton 12577: alignment restrictions that do not report violations.
1.1 anton 12578:
12579: @item data space pointer not properly aligned, @code{,}, @code{C,}:
12580: @cindex data space pointer not properly aligned, @code{,}, @code{C,}
12581: Like other alignment errors.
12582:
12583: @item less than u+2 stack items (@code{PICK} and @code{ROLL}):
12584: Like other stack underflows.
12585:
12586: @item loop control parameters not available:
12587: @cindex loop control parameters not available
12588: Not checked. The counted loop words simply assume that the top of return
12589: stack items are loop control parameters and behave accordingly.
12590:
12591: @item most recent definition does not have a name (@code{IMMEDIATE}):
12592: @cindex most recent definition does not have a name (@code{IMMEDIATE})
12593: @cindex last word was headerless
12594: @code{abort" last word was headerless"}.
12595:
12596: @item name not defined by @code{VALUE} used by @code{TO}:
12597: @cindex name not defined by @code{VALUE} used by @code{TO}
12598: @cindex @code{TO} on non-@code{VALUE}s
12599: @cindex Invalid name argument, @code{TO}
12600: @code{-32 throw} (Invalid name argument) (unless name is a local or was
12601: defined by @code{CONSTANT}; in the latter case it just changes the constant).
12602:
12603: @item name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}):
12604: @cindex name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]})
1.26 crook 12605: @cindex undefined word, @code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}
1.1 anton 12606: @code{-13 throw} (Undefined word)
12607:
12608: @item parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN}):
12609: @cindex parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN})
12610: Gforth behaves as if they were of the same type. I.e., you can predict
12611: the behaviour by interpreting all parameters as, e.g., signed.
12612:
12613: @item @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}:
12614: @cindex @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}
12615: Assume @code{: X POSTPONE TO ; IMMEDIATE}. @code{X} performs the
12616: compilation semantics of @code{TO}.
12617:
12618: @item String longer than a counted string returned by @code{WORD}:
1.26 crook 12619: @cindex string longer than a counted string returned by @code{WORD}
1.1 anton 12620: @cindex @code{WORD}, string overflow
12621: Not checked. The string will be ok, but the count will, of course,
12622: contain only the least significant bits of the length.
12623:
12624: @item u greater than or equal to the number of bits in a cell (@code{LSHIFT}, @code{RSHIFT}):
12625: @cindex @code{LSHIFT}, large shift counts
12626: @cindex @code{RSHIFT}, large shift counts
12627: Processor-dependent. Typical behaviours are returning 0 and using only
12628: the low bits of the shift count.
12629:
12630: @item word not defined via @code{CREATE}:
12631: @cindex @code{>BODY} of non-@code{CREATE}d words
12632: @code{>BODY} produces the PFA of the word no matter how it was defined.
12633:
12634: @cindex @code{DOES>} of non-@code{CREATE}d words
12635: @code{DOES>} changes the execution semantics of the last defined word no
12636: matter how it was defined. E.g., @code{CONSTANT DOES>} is equivalent to
12637: @code{CREATE , DOES>}.
12638:
12639: @item words improperly used outside @code{<#} and @code{#>}:
12640: Not checked. As usual, you can expect memory faults.
12641:
12642: @end table
12643:
12644:
12645: @c ---------------------------------------------------------------------
12646: @node core-other, , core-ambcond, The Core Words
12647: @subsection Other system documentation
12648: @c ---------------------------------------------------------------------
12649: @cindex other system documentation, core words
12650: @cindex core words, other system documentation
12651:
12652: @table @i
12653: @item nonstandard words using @code{PAD}:
12654: @cindex @code{PAD} use by nonstandard words
12655: None.
12656:
12657: @item operator's terminal facilities available:
12658: @cindex operator's terminal facilities available
1.80 anton 12659: After processing the OS's command line, Gforth goes into interactive mode,
1.1 anton 12660: and you can give commands to Gforth interactively. The actual facilities
12661: available depend on how you invoke Gforth.
12662:
12663: @item program data space available:
12664: @cindex program data space available
12665: @cindex data space available
12666: @code{UNUSED .} gives the remaining dictionary space. The total
12667: dictionary space can be specified with the @code{-m} switch
12668: (@pxref{Invoking Gforth}) when Gforth starts up.
12669:
12670: @item return stack space available:
12671: @cindex return stack space available
12672: You can compute the total return stack space in cells with
12673: @code{s" RETURN-STACK-CELLS" environment? drop .}. You can specify it at
12674: startup time with the @code{-r} switch (@pxref{Invoking Gforth}).
12675:
12676: @item stack space available:
12677: @cindex stack space available
12678: You can compute the total data stack space in cells with
12679: @code{s" STACK-CELLS" environment? drop .}. You can specify it at
12680: startup time with the @code{-d} switch (@pxref{Invoking Gforth}).
12681:
12682: @item system dictionary space required, in address units:
12683: @cindex system dictionary space required, in address units
12684: Type @code{here forthstart - .} after startup. At the time of this
12685: writing, this gives 80080 (bytes) on a 32-bit system.
12686: @end table
12687:
12688:
12689: @c =====================================================================
12690: @node The optional Block word set, The optional Double Number word set, The Core Words, ANS conformance
12691: @section The optional Block word set
12692: @c =====================================================================
12693: @cindex system documentation, block words
12694: @cindex block words, system documentation
12695:
12696: @menu
12697: * block-idef:: Implementation Defined Options
12698: * block-ambcond:: Ambiguous Conditions
12699: * block-other:: Other System Documentation
12700: @end menu
12701:
12702:
12703: @c ---------------------------------------------------------------------
12704: @node block-idef, block-ambcond, The optional Block word set, The optional Block word set
12705: @subsection Implementation Defined Options
12706: @c ---------------------------------------------------------------------
12707: @cindex implementation-defined options, block words
12708: @cindex block words, implementation-defined options
12709:
12710: @table @i
12711: @item the format for display by @code{LIST}:
12712: @cindex @code{LIST} display format
12713: First the screen number is displayed, then 16 lines of 64 characters,
12714: each line preceded by the line number.
12715:
12716: @item the length of a line affected by @code{\}:
12717: @cindex length of a line affected by @code{\}
12718: @cindex @code{\}, line length in blocks
12719: 64 characters.
12720: @end table
12721:
12722:
12723: @c ---------------------------------------------------------------------
12724: @node block-ambcond, block-other, block-idef, The optional Block word set
12725: @subsection Ambiguous conditions
12726: @c ---------------------------------------------------------------------
12727: @cindex block words, ambiguous conditions
12728: @cindex ambiguous conditions, block words
12729:
12730: @table @i
12731: @item correct block read was not possible:
12732: @cindex block read not possible
12733: Typically results in a @code{throw} of some OS-derived value (between
12734: -512 and -2048). If the blocks file was just not long enough, blanks are
12735: supplied for the missing portion.
12736:
12737: @item I/O exception in block transfer:
12738: @cindex I/O exception in block transfer
12739: @cindex block transfer, I/O exception
12740: Typically results in a @code{throw} of some OS-derived value (between
12741: -512 and -2048).
12742:
12743: @item invalid block number:
12744: @cindex invalid block number
12745: @cindex block number invalid
12746: @code{-35 throw} (Invalid block number)
12747:
12748: @item a program directly alters the contents of @code{BLK}:
12749: @cindex @code{BLK}, altering @code{BLK}
12750: The input stream is switched to that other block, at the same
12751: position. If the storing to @code{BLK} happens when interpreting
12752: non-block input, the system will get quite confused when the block ends.
12753:
12754: @item no current block buffer for @code{UPDATE}:
12755: @cindex @code{UPDATE}, no current block buffer
12756: @code{UPDATE} has no effect.
12757:
12758: @end table
12759:
12760: @c ---------------------------------------------------------------------
12761: @node block-other, , block-ambcond, The optional Block word set
12762: @subsection Other system documentation
12763: @c ---------------------------------------------------------------------
12764: @cindex other system documentation, block words
12765: @cindex block words, other system documentation
12766:
12767: @table @i
12768: @item any restrictions a multiprogramming system places on the use of buffer addresses:
12769: No restrictions (yet).
12770:
12771: @item the number of blocks available for source and data:
12772: depends on your disk space.
12773:
12774: @end table
12775:
12776:
12777: @c =====================================================================
12778: @node The optional Double Number word set, The optional Exception word set, The optional Block word set, ANS conformance
12779: @section The optional Double Number word set
12780: @c =====================================================================
12781: @cindex system documentation, double words
12782: @cindex double words, system documentation
12783:
12784: @menu
12785: * double-ambcond:: Ambiguous Conditions
12786: @end menu
12787:
12788:
12789: @c ---------------------------------------------------------------------
12790: @node double-ambcond, , The optional Double Number word set, The optional Double Number word set
12791: @subsection Ambiguous conditions
12792: @c ---------------------------------------------------------------------
12793: @cindex double words, ambiguous conditions
12794: @cindex ambiguous conditions, double words
12795:
12796: @table @i
1.29 crook 12797: @item @i{d} outside of range of @i{n} in @code{D>S}:
12798: @cindex @code{D>S}, @i{d} out of range of @i{n}
12799: The least significant cell of @i{d} is produced.
1.1 anton 12800:
12801: @end table
12802:
12803:
12804: @c =====================================================================
12805: @node The optional Exception word set, The optional Facility word set, The optional Double Number word set, ANS conformance
12806: @section The optional Exception word set
12807: @c =====================================================================
12808: @cindex system documentation, exception words
12809: @cindex exception words, system documentation
12810:
12811: @menu
12812: * exception-idef:: Implementation Defined Options
12813: @end menu
12814:
12815:
12816: @c ---------------------------------------------------------------------
12817: @node exception-idef, , The optional Exception word set, The optional Exception word set
12818: @subsection Implementation Defined Options
12819: @c ---------------------------------------------------------------------
12820: @cindex implementation-defined options, exception words
12821: @cindex exception words, implementation-defined options
12822:
12823: @table @i
12824: @item @code{THROW}-codes used in the system:
12825: @cindex @code{THROW}-codes used in the system
12826: The codes -256@minus{}-511 are used for reporting signals. The mapping
1.29 crook 12827: from OS signal numbers to throw codes is -256@minus{}@i{signal}. The
1.1 anton 12828: codes -512@minus{}-2047 are used for OS errors (for file and memory
12829: allocation operations). The mapping from OS error numbers to throw codes
12830: is -512@minus{}@code{errno}. One side effect of this mapping is that
12831: undefined OS errors produce a message with a strange number; e.g.,
12832: @code{-1000 THROW} results in @code{Unknown error 488} on my system.
12833: @end table
12834:
12835: @c =====================================================================
12836: @node The optional Facility word set, The optional File-Access word set, The optional Exception word set, ANS conformance
12837: @section The optional Facility word set
12838: @c =====================================================================
12839: @cindex system documentation, facility words
12840: @cindex facility words, system documentation
12841:
12842: @menu
12843: * facility-idef:: Implementation Defined Options
12844: * facility-ambcond:: Ambiguous Conditions
12845: @end menu
12846:
12847:
12848: @c ---------------------------------------------------------------------
12849: @node facility-idef, facility-ambcond, The optional Facility word set, The optional Facility word set
12850: @subsection Implementation Defined Options
12851: @c ---------------------------------------------------------------------
12852: @cindex implementation-defined options, facility words
12853: @cindex facility words, implementation-defined options
12854:
12855: @table @i
12856: @item encoding of keyboard events (@code{EKEY}):
12857: @cindex keyboard events, encoding in @code{EKEY}
12858: @cindex @code{EKEY}, encoding of keyboard events
1.40 anton 12859: Keys corresponding to ASCII characters are encoded as ASCII characters.
1.41 anton 12860: Other keys are encoded with the constants @code{k-left}, @code{k-right},
12861: @code{k-up}, @code{k-down}, @code{k-home}, @code{k-end}, @code{k1},
12862: @code{k2}, @code{k3}, @code{k4}, @code{k5}, @code{k6}, @code{k7},
12863: @code{k8}, @code{k9}, @code{k10}, @code{k11}, @code{k12}.
1.40 anton 12864:
1.1 anton 12865:
12866: @item duration of a system clock tick:
12867: @cindex duration of a system clock tick
12868: @cindex clock tick duration
12869: System dependent. With respect to @code{MS}, the time is specified in
12870: microseconds. How well the OS and the hardware implement this, is
12871: another question.
12872:
12873: @item repeatability to be expected from the execution of @code{MS}:
12874: @cindex repeatability to be expected from the execution of @code{MS}
12875: @cindex @code{MS}, repeatability to be expected
12876: System dependent. On Unix, a lot depends on load. If the system is
12877: lightly loaded, and the delay is short enough that Gforth does not get
12878: swapped out, the performance should be acceptable. Under MS-DOS and
12879: other single-tasking systems, it should be good.
12880:
12881: @end table
12882:
12883:
12884: @c ---------------------------------------------------------------------
12885: @node facility-ambcond, , facility-idef, The optional Facility word set
12886: @subsection Ambiguous conditions
12887: @c ---------------------------------------------------------------------
12888: @cindex facility words, ambiguous conditions
12889: @cindex ambiguous conditions, facility words
12890:
12891: @table @i
12892: @item @code{AT-XY} can't be performed on user output device:
12893: @cindex @code{AT-XY} can't be performed on user output device
12894: Largely terminal dependent. No range checks are done on the arguments.
12895: No errors are reported. You may see some garbage appearing, you may see
12896: simply nothing happen.
12897:
12898: @end table
12899:
12900:
12901: @c =====================================================================
12902: @node The optional File-Access word set, The optional Floating-Point word set, The optional Facility word set, ANS conformance
12903: @section The optional File-Access word set
12904: @c =====================================================================
12905: @cindex system documentation, file words
12906: @cindex file words, system documentation
12907:
12908: @menu
12909: * file-idef:: Implementation Defined Options
12910: * file-ambcond:: Ambiguous Conditions
12911: @end menu
12912:
12913: @c ---------------------------------------------------------------------
12914: @node file-idef, file-ambcond, The optional File-Access word set, The optional File-Access word set
12915: @subsection Implementation Defined Options
12916: @c ---------------------------------------------------------------------
12917: @cindex implementation-defined options, file words
12918: @cindex file words, implementation-defined options
12919:
12920: @table @i
12921: @item file access methods used:
12922: @cindex file access methods used
12923: @code{R/O}, @code{R/W} and @code{BIN} work as you would
12924: expect. @code{W/O} translates into the C file opening mode @code{w} (or
12925: @code{wb}): The file is cleared, if it exists, and created, if it does
12926: not (with both @code{open-file} and @code{create-file}). Under Unix
12927: @code{create-file} creates a file with 666 permissions modified by your
12928: umask.
12929:
12930: @item file exceptions:
12931: @cindex file exceptions
12932: The file words do not raise exceptions (except, perhaps, memory access
12933: faults when you pass illegal addresses or file-ids).
12934:
12935: @item file line terminator:
12936: @cindex file line terminator
12937: System-dependent. Gforth uses C's newline character as line
12938: terminator. What the actual character code(s) of this are is
12939: system-dependent.
12940:
12941: @item file name format:
12942: @cindex file name format
12943: System dependent. Gforth just uses the file name format of your OS.
12944:
12945: @item information returned by @code{FILE-STATUS}:
12946: @cindex @code{FILE-STATUS}, returned information
12947: @code{FILE-STATUS} returns the most powerful file access mode allowed
12948: for the file: Either @code{R/O}, @code{W/O} or @code{R/W}. If the file
12949: cannot be accessed, @code{R/O BIN} is returned. @code{BIN} is applicable
12950: along with the returned mode.
12951:
12952: @item input file state after an exception when including source:
12953: @cindex exception when including source
12954: All files that are left via the exception are closed.
12955:
1.29 crook 12956: @item @i{ior} values and meaning:
12957: @cindex @i{ior} values and meaning
1.68 anton 12958: @cindex @i{wior} values and meaning
1.29 crook 12959: The @i{ior}s returned by the file and memory allocation words are
1.1 anton 12960: intended as throw codes. They typically are in the range
12961: -512@minus{}-2047 of OS errors. The mapping from OS error numbers to
1.29 crook 12962: @i{ior}s is -512@minus{}@i{errno}.
1.1 anton 12963:
12964: @item maximum depth of file input nesting:
12965: @cindex maximum depth of file input nesting
12966: @cindex file input nesting, maximum depth
12967: limited by the amount of return stack, locals/TIB stack, and the number
12968: of open files available. This should not give you troubles.
12969:
12970: @item maximum size of input line:
12971: @cindex maximum size of input line
12972: @cindex input line size, maximum
12973: @code{/line}. Currently 255.
12974:
12975: @item methods of mapping block ranges to files:
12976: @cindex mapping block ranges to files
12977: @cindex files containing blocks
12978: @cindex blocks in files
12979: By default, blocks are accessed in the file @file{blocks.fb} in the
12980: current working directory. The file can be switched with @code{USE}.
12981:
12982: @item number of string buffers provided by @code{S"}:
12983: @cindex @code{S"}, number of string buffers
12984: 1
12985:
12986: @item size of string buffer used by @code{S"}:
12987: @cindex @code{S"}, size of string buffer
12988: @code{/line}. currently 255.
12989:
12990: @end table
12991:
12992: @c ---------------------------------------------------------------------
12993: @node file-ambcond, , file-idef, The optional File-Access word set
12994: @subsection Ambiguous conditions
12995: @c ---------------------------------------------------------------------
12996: @cindex file words, ambiguous conditions
12997: @cindex ambiguous conditions, file words
12998:
12999: @table @i
13000: @item attempting to position a file outside its boundaries:
13001: @cindex @code{REPOSITION-FILE}, outside the file's boundaries
13002: @code{REPOSITION-FILE} is performed as usual: Afterwards,
13003: @code{FILE-POSITION} returns the value given to @code{REPOSITION-FILE}.
13004:
13005: @item attempting to read from file positions not yet written:
13006: @cindex reading from file positions not yet written
13007: End-of-file, i.e., zero characters are read and no error is reported.
13008:
1.29 crook 13009: @item @i{file-id} is invalid (@code{INCLUDE-FILE}):
13010: @cindex @code{INCLUDE-FILE}, @i{file-id} is invalid
1.1 anton 13011: An appropriate exception may be thrown, but a memory fault or other
13012: problem is more probable.
13013:
1.29 crook 13014: @item I/O exception reading or closing @i{file-id} (@code{INCLUDE-FILE}, @code{INCLUDED}):
13015: @cindex @code{INCLUDE-FILE}, I/O exception reading or closing @i{file-id}
13016: @cindex @code{INCLUDED}, I/O exception reading or closing @i{file-id}
13017: The @i{ior} produced by the operation, that discovered the problem, is
1.1 anton 13018: thrown.
13019:
13020: @item named file cannot be opened (@code{INCLUDED}):
13021: @cindex @code{INCLUDED}, named file cannot be opened
1.29 crook 13022: The @i{ior} produced by @code{open-file} is thrown.
1.1 anton 13023:
13024: @item requesting an unmapped block number:
13025: @cindex unmapped block numbers
13026: There are no unmapped legal block numbers. On some operating systems,
13027: writing a block with a large number may overflow the file system and
13028: have an error message as consequence.
13029:
13030: @item using @code{source-id} when @code{blk} is non-zero:
13031: @cindex @code{SOURCE-ID}, behaviour when @code{BLK} is non-zero
13032: @code{source-id} performs its function. Typically it will give the id of
13033: the source which loaded the block. (Better ideas?)
13034:
13035: @end table
13036:
13037:
13038: @c =====================================================================
13039: @node The optional Floating-Point word set, The optional Locals word set, The optional File-Access word set, ANS conformance
13040: @section The optional Floating-Point word set
13041: @c =====================================================================
13042: @cindex system documentation, floating-point words
13043: @cindex floating-point words, system documentation
13044:
13045: @menu
13046: * floating-idef:: Implementation Defined Options
13047: * floating-ambcond:: Ambiguous Conditions
13048: @end menu
13049:
13050:
13051: @c ---------------------------------------------------------------------
13052: @node floating-idef, floating-ambcond, The optional Floating-Point word set, The optional Floating-Point word set
13053: @subsection Implementation Defined Options
13054: @c ---------------------------------------------------------------------
13055: @cindex implementation-defined options, floating-point words
13056: @cindex floating-point words, implementation-defined options
13057:
13058: @table @i
13059: @item format and range of floating point numbers:
13060: @cindex format and range of floating point numbers
13061: @cindex floating point numbers, format and range
13062: System-dependent; the @code{double} type of C.
13063:
1.29 crook 13064: @item results of @code{REPRESENT} when @i{float} is out of range:
13065: @cindex @code{REPRESENT}, results when @i{float} is out of range
1.1 anton 13066: System dependent; @code{REPRESENT} is implemented using the C library
13067: function @code{ecvt()} and inherits its behaviour in this respect.
13068:
13069: @item rounding or truncation of floating-point numbers:
13070: @cindex rounding of floating-point numbers
13071: @cindex truncation of floating-point numbers
13072: @cindex floating-point numbers, rounding or truncation
13073: System dependent; the rounding behaviour is inherited from the hosting C
13074: compiler. IEEE-FP-based (i.e., most) systems by default round to
13075: nearest, and break ties by rounding to even (i.e., such that the last
13076: bit of the mantissa is 0).
13077:
13078: @item size of floating-point stack:
13079: @cindex floating-point stack size
13080: @code{s" FLOATING-STACK" environment? drop .} gives the total size of
13081: the floating-point stack (in floats). You can specify this on startup
13082: with the command-line option @code{-f} (@pxref{Invoking Gforth}).
13083:
13084: @item width of floating-point stack:
13085: @cindex floating-point stack width
13086: @code{1 floats}.
13087:
13088: @end table
13089:
13090:
13091: @c ---------------------------------------------------------------------
13092: @node floating-ambcond, , floating-idef, The optional Floating-Point word set
13093: @subsection Ambiguous conditions
13094: @c ---------------------------------------------------------------------
13095: @cindex floating-point words, ambiguous conditions
13096: @cindex ambiguous conditions, floating-point words
13097:
13098: @table @i
13099: @item @code{df@@} or @code{df!} used with an address that is not double-float aligned:
13100: @cindex @code{df@@} or @code{df!} used with an address that is not double-float aligned
13101: System-dependent. Typically results in a @code{-23 THROW} like other
13102: alignment violations.
13103:
13104: @item @code{f@@} or @code{f!} used with an address that is not float aligned:
13105: @cindex @code{f@@} used with an address that is not float aligned
13106: @cindex @code{f!} used with an address that is not float aligned
13107: System-dependent. Typically results in a @code{-23 THROW} like other
13108: alignment violations.
13109:
13110: @item floating-point result out of range:
13111: @cindex floating-point result out of range
1.80 anton 13112: System-dependent. Can result in a @code{-43 throw} (floating point
13113: overflow), @code{-54 throw} (floating point underflow), @code{-41 throw}
13114: (floating point inexact result), @code{-55 THROW} (Floating-point
1.1 anton 13115: unidentified fault), or can produce a special value representing, e.g.,
13116: Infinity.
13117:
13118: @item @code{sf@@} or @code{sf!} used with an address that is not single-float aligned:
13119: @cindex @code{sf@@} or @code{sf!} used with an address that is not single-float aligned
13120: System-dependent. Typically results in an alignment fault like other
13121: alignment violations.
13122:
1.35 anton 13123: @item @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.}):
13124: @cindex @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.})
1.1 anton 13125: The floating-point number is converted into decimal nonetheless.
13126:
13127: @item Both arguments are equal to zero (@code{FATAN2}):
13128: @cindex @code{FATAN2}, both arguments are equal to zero
13129: System-dependent. @code{FATAN2} is implemented using the C library
13130: function @code{atan2()}.
13131:
1.29 crook 13132: @item Using @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero:
13133: @cindex @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero
13134: System-dependent. Anyway, typically the cos of @i{r1} will not be zero
1.1 anton 13135: because of small errors and the tan will be a very large (or very small)
13136: but finite number.
13137:
1.29 crook 13138: @item @i{d} cannot be presented precisely as a float in @code{D>F}:
13139: @cindex @code{D>F}, @i{d} cannot be presented precisely as a float
1.1 anton 13140: The result is rounded to the nearest float.
13141:
13142: @item dividing by zero:
13143: @cindex dividing by zero, floating-point
13144: @cindex floating-point dividing by zero
13145: @cindex floating-point unidentified fault, FP divide-by-zero
1.80 anton 13146: Platform-dependent; can produce an Infinity, NaN, @code{-42 throw}
13147: (floating point divide by zero) or @code{-55 throw} (Floating-point
13148: unidentified fault).
1.1 anton 13149:
13150: @item exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@}):
13151: @cindex exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@})
13152: System dependent. On IEEE-FP based systems the number is converted into
13153: an infinity.
13154:
1.29 crook 13155: @item @i{float}<1 (@code{FACOSH}):
13156: @cindex @code{FACOSH}, @i{float}<1
1.1 anton 13157: @cindex floating-point unidentified fault, @code{FACOSH}
1.80 anton 13158: Platform-dependent; on IEEE-FP systems typically produces a NaN.
1.1 anton 13159:
1.29 crook 13160: @item @i{float}=<-1 (@code{FLNP1}):
13161: @cindex @code{FLNP1}, @i{float}=<-1
1.1 anton 13162: @cindex floating-point unidentified fault, @code{FLNP1}
1.80 anton 13163: Platform-dependent; on IEEE-FP systems typically produces a NaN (or a
13164: negative infinity for @i{float}=-1).
1.1 anton 13165:
1.29 crook 13166: @item @i{float}=<0 (@code{FLN}, @code{FLOG}):
13167: @cindex @code{FLN}, @i{float}=<0
13168: @cindex @code{FLOG}, @i{float}=<0
1.1 anton 13169: @cindex floating-point unidentified fault, @code{FLN} or @code{FLOG}
1.80 anton 13170: Platform-dependent; on IEEE-FP systems typically produces a NaN (or a
13171: negative infinity for @i{float}=0).
1.1 anton 13172:
1.29 crook 13173: @item @i{float}<0 (@code{FASINH}, @code{FSQRT}):
13174: @cindex @code{FASINH}, @i{float}<0
13175: @cindex @code{FSQRT}, @i{float}<0
1.1 anton 13176: @cindex floating-point unidentified fault, @code{FASINH} or @code{FSQRT}
1.80 anton 13177: Platform-dependent; for @code{fsqrt} this typically gives a NaN, for
13178: @code{fasinh} some platforms produce a NaN, others a number (bug in the
13179: C library?).
1.1 anton 13180:
1.29 crook 13181: @item |@i{float}|>1 (@code{FACOS}, @code{FASIN}, @code{FATANH}):
13182: @cindex @code{FACOS}, |@i{float}|>1
13183: @cindex @code{FASIN}, |@i{float}|>1
13184: @cindex @code{FATANH}, |@i{float}|>1
1.1 anton 13185: @cindex floating-point unidentified fault, @code{FACOS}, @code{FASIN} or @code{FATANH}
1.80 anton 13186: Platform-dependent; IEEE-FP systems typically produce a NaN.
1.1 anton 13187:
1.29 crook 13188: @item integer part of float cannot be represented by @i{d} in @code{F>D}:
13189: @cindex @code{F>D}, integer part of float cannot be represented by @i{d}
1.1 anton 13190: @cindex floating-point unidentified fault, @code{F>D}
1.80 anton 13191: Platform-dependent; typically, some double number is produced and no
13192: error is reported.
1.1 anton 13193:
13194: @item string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.}):
13195: @cindex string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.})
1.80 anton 13196: @code{Precision} characters of the numeric output area are used. If
13197: @code{precision} is too high, these words will smash the data or code
13198: close to @code{here}.
1.1 anton 13199: @end table
13200:
13201: @c =====================================================================
13202: @node The optional Locals word set, The optional Memory-Allocation word set, The optional Floating-Point word set, ANS conformance
13203: @section The optional Locals word set
13204: @c =====================================================================
13205: @cindex system documentation, locals words
13206: @cindex locals words, system documentation
13207:
13208: @menu
13209: * locals-idef:: Implementation Defined Options
13210: * locals-ambcond:: Ambiguous Conditions
13211: @end menu
13212:
13213:
13214: @c ---------------------------------------------------------------------
13215: @node locals-idef, locals-ambcond, The optional Locals word set, The optional Locals word set
13216: @subsection Implementation Defined Options
13217: @c ---------------------------------------------------------------------
13218: @cindex implementation-defined options, locals words
13219: @cindex locals words, implementation-defined options
13220:
13221: @table @i
13222: @item maximum number of locals in a definition:
13223: @cindex maximum number of locals in a definition
13224: @cindex locals, maximum number in a definition
13225: @code{s" #locals" environment? drop .}. Currently 15. This is a lower
13226: bound, e.g., on a 32-bit machine there can be 41 locals of up to 8
13227: characters. The number of locals in a definition is bounded by the size
13228: of locals-buffer, which contains the names of the locals.
13229:
13230: @end table
13231:
13232:
13233: @c ---------------------------------------------------------------------
13234: @node locals-ambcond, , locals-idef, The optional Locals word set
13235: @subsection Ambiguous conditions
13236: @c ---------------------------------------------------------------------
13237: @cindex locals words, ambiguous conditions
13238: @cindex ambiguous conditions, locals words
13239:
13240: @table @i
13241: @item executing a named local in interpretation state:
13242: @cindex local in interpretation state
13243: @cindex Interpreting a compile-only word, for a local
13244: Locals have no interpretation semantics. If you try to perform the
13245: interpretation semantics, you will get a @code{-14 throw} somewhere
13246: (Interpreting a compile-only word). If you perform the compilation
13247: semantics, the locals access will be compiled (irrespective of state).
13248:
1.29 crook 13249: @item @i{name} not defined by @code{VALUE} or @code{(LOCAL)} (@code{TO}):
1.1 anton 13250: @cindex name not defined by @code{VALUE} or @code{(LOCAL)} used by @code{TO}
13251: @cindex @code{TO} on non-@code{VALUE}s and non-locals
13252: @cindex Invalid name argument, @code{TO}
13253: @code{-32 throw} (Invalid name argument)
13254:
13255: @end table
13256:
13257:
13258: @c =====================================================================
13259: @node The optional Memory-Allocation word set, The optional Programming-Tools word set, The optional Locals word set, ANS conformance
13260: @section The optional Memory-Allocation word set
13261: @c =====================================================================
13262: @cindex system documentation, memory-allocation words
13263: @cindex memory-allocation words, system documentation
13264:
13265: @menu
13266: * memory-idef:: Implementation Defined Options
13267: @end menu
13268:
13269:
13270: @c ---------------------------------------------------------------------
13271: @node memory-idef, , The optional Memory-Allocation word set, The optional Memory-Allocation word set
13272: @subsection Implementation Defined Options
13273: @c ---------------------------------------------------------------------
13274: @cindex implementation-defined options, memory-allocation words
13275: @cindex memory-allocation words, implementation-defined options
13276:
13277: @table @i
1.29 crook 13278: @item values and meaning of @i{ior}:
13279: @cindex @i{ior} values and meaning
13280: The @i{ior}s returned by the file and memory allocation words are
1.1 anton 13281: intended as throw codes. They typically are in the range
13282: -512@minus{}-2047 of OS errors. The mapping from OS error numbers to
1.29 crook 13283: @i{ior}s is -512@minus{}@i{errno}.
1.1 anton 13284:
13285: @end table
13286:
13287: @c =====================================================================
13288: @node The optional Programming-Tools word set, The optional Search-Order word set, The optional Memory-Allocation word set, ANS conformance
13289: @section The optional Programming-Tools word set
13290: @c =====================================================================
13291: @cindex system documentation, programming-tools words
13292: @cindex programming-tools words, system documentation
13293:
13294: @menu
13295: * programming-idef:: Implementation Defined Options
13296: * programming-ambcond:: Ambiguous Conditions
13297: @end menu
13298:
13299:
13300: @c ---------------------------------------------------------------------
13301: @node programming-idef, programming-ambcond, The optional Programming-Tools word set, The optional Programming-Tools word set
13302: @subsection Implementation Defined Options
13303: @c ---------------------------------------------------------------------
13304: @cindex implementation-defined options, programming-tools words
13305: @cindex programming-tools words, implementation-defined options
13306:
13307: @table @i
13308: @item ending sequence for input following @code{;CODE} and @code{CODE}:
13309: @cindex @code{;CODE} ending sequence
13310: @cindex @code{CODE} ending sequence
13311: @code{END-CODE}
13312:
13313: @item manner of processing input following @code{;CODE} and @code{CODE}:
13314: @cindex @code{;CODE}, processing input
13315: @cindex @code{CODE}, processing input
13316: The @code{ASSEMBLER} vocabulary is pushed on the search order stack, and
13317: the input is processed by the text interpreter, (starting) in interpret
13318: state.
13319:
13320: @item search order capability for @code{EDITOR} and @code{ASSEMBLER}:
13321: @cindex @code{ASSEMBLER}, search order capability
13322: The ANS Forth search order word set.
13323:
13324: @item source and format of display by @code{SEE}:
13325: @cindex @code{SEE}, source and format of output
1.80 anton 13326: The source for @code{see} is the executable code used by the inner
1.1 anton 13327: interpreter. The current @code{see} tries to output Forth source code
1.80 anton 13328: (and on some platforms, assembly code for primitives) as well as
13329: possible.
1.1 anton 13330:
13331: @end table
13332:
13333: @c ---------------------------------------------------------------------
13334: @node programming-ambcond, , programming-idef, The optional Programming-Tools word set
13335: @subsection Ambiguous conditions
13336: @c ---------------------------------------------------------------------
13337: @cindex programming-tools words, ambiguous conditions
13338: @cindex ambiguous conditions, programming-tools words
13339:
13340: @table @i
13341:
1.21 crook 13342: @item deleting the compilation word list (@code{FORGET}):
13343: @cindex @code{FORGET}, deleting the compilation word list
1.1 anton 13344: Not implemented (yet).
13345:
1.29 crook 13346: @item fewer than @i{u}+1 items on the control-flow stack (@code{CS-PICK}, @code{CS-ROLL}):
13347: @cindex @code{CS-PICK}, fewer than @i{u}+1 items on the control flow-stack
13348: @cindex @code{CS-ROLL}, fewer than @i{u}+1 items on the control flow-stack
1.1 anton 13349: @cindex control-flow stack underflow
13350: This typically results in an @code{abort"} with a descriptive error
13351: message (may change into a @code{-22 throw} (Control structure mismatch)
13352: in the future). You may also get a memory access error. If you are
13353: unlucky, this ambiguous condition is not caught.
13354:
1.29 crook 13355: @item @i{name} can't be found (@code{FORGET}):
13356: @cindex @code{FORGET}, @i{name} can't be found
1.1 anton 13357: Not implemented (yet).
13358:
1.29 crook 13359: @item @i{name} not defined via @code{CREATE}:
13360: @cindex @code{;CODE}, @i{name} not defined via @code{CREATE}
1.1 anton 13361: @code{;CODE} behaves like @code{DOES>} in this respect, i.e., it changes
13362: the execution semantics of the last defined word no matter how it was
13363: defined.
13364:
13365: @item @code{POSTPONE} applied to @code{[IF]}:
13366: @cindex @code{POSTPONE} applied to @code{[IF]}
13367: @cindex @code{[IF]} and @code{POSTPONE}
13368: After defining @code{: X POSTPONE [IF] ; IMMEDIATE}. @code{X} is
13369: equivalent to @code{[IF]}.
13370:
13371: @item reaching the end of the input source before matching @code{[ELSE]} or @code{[THEN]}:
13372: @cindex @code{[IF]}, end of the input source before matching @code{[ELSE]} or @code{[THEN]}
13373: Continue in the same state of conditional compilation in the next outer
13374: input source. Currently there is no warning to the user about this.
13375:
13376: @item removing a needed definition (@code{FORGET}):
13377: @cindex @code{FORGET}, removing a needed definition
13378: Not implemented (yet).
13379:
13380: @end table
13381:
13382:
13383: @c =====================================================================
13384: @node The optional Search-Order word set, , The optional Programming-Tools word set, ANS conformance
13385: @section The optional Search-Order word set
13386: @c =====================================================================
13387: @cindex system documentation, search-order words
13388: @cindex search-order words, system documentation
13389:
13390: @menu
13391: * search-idef:: Implementation Defined Options
13392: * search-ambcond:: Ambiguous Conditions
13393: @end menu
13394:
13395:
13396: @c ---------------------------------------------------------------------
13397: @node search-idef, search-ambcond, The optional Search-Order word set, The optional Search-Order word set
13398: @subsection Implementation Defined Options
13399: @c ---------------------------------------------------------------------
13400: @cindex implementation-defined options, search-order words
13401: @cindex search-order words, implementation-defined options
13402:
13403: @table @i
13404: @item maximum number of word lists in search order:
13405: @cindex maximum number of word lists in search order
13406: @cindex search order, maximum depth
13407: @code{s" wordlists" environment? drop .}. Currently 16.
13408:
13409: @item minimum search order:
13410: @cindex minimum search order
13411: @cindex search order, minimum
13412: @code{root root}.
13413:
13414: @end table
13415:
13416: @c ---------------------------------------------------------------------
13417: @node search-ambcond, , search-idef, The optional Search-Order word set
13418: @subsection Ambiguous conditions
13419: @c ---------------------------------------------------------------------
13420: @cindex search-order words, ambiguous conditions
13421: @cindex ambiguous conditions, search-order words
13422:
13423: @table @i
1.21 crook 13424: @item changing the compilation word list (during compilation):
13425: @cindex changing the compilation word list (during compilation)
13426: @cindex compilation word list, change before definition ends
13427: The word is entered into the word list that was the compilation word list
1.1 anton 13428: at the start of the definition. Any changes to the name field (e.g.,
13429: @code{immediate}) or the code field (e.g., when executing @code{DOES>})
13430: are applied to the latest defined word (as reported by @code{last} or
1.21 crook 13431: @code{lastxt}), if possible, irrespective of the compilation word list.
1.1 anton 13432:
13433: @item search order empty (@code{previous}):
13434: @cindex @code{previous}, search order empty
1.26 crook 13435: @cindex vocstack empty, @code{previous}
1.1 anton 13436: @code{abort" Vocstack empty"}.
13437:
13438: @item too many word lists in search order (@code{also}):
13439: @cindex @code{also}, too many word lists in search order
1.26 crook 13440: @cindex vocstack full, @code{also}
1.1 anton 13441: @code{abort" Vocstack full"}.
13442:
13443: @end table
13444:
13445: @c ***************************************************************
1.65 anton 13446: @node Standard vs Extensions, Model, ANS conformance, Top
13447: @chapter Should I use Gforth extensions?
13448: @cindex Gforth extensions
13449:
13450: As you read through the rest of this manual, you will see documentation
13451: for @i{Standard} words, and documentation for some appealing Gforth
13452: @i{extensions}. You might ask yourself the question: @i{``Should I
13453: restrict myself to the standard, or should I use the extensions?''}
13454:
13455: The answer depends on the goals you have for the program you are working
13456: on:
13457:
13458: @itemize @bullet
13459:
13460: @item Is it just for yourself or do you want to share it with others?
13461:
13462: @item
13463: If you want to share it, do the others all use Gforth?
13464:
13465: @item
13466: If it is just for yourself, do you want to restrict yourself to Gforth?
13467:
13468: @end itemize
13469:
13470: If restricting the program to Gforth is ok, then there is no reason not
13471: to use extensions. It is still a good idea to keep to the standard
13472: where it is easy, in case you want to reuse these parts in another
13473: program that you want to be portable.
13474:
13475: If you want to be able to port the program to other Forth systems, there
13476: are the following points to consider:
13477:
13478: @itemize @bullet
13479:
13480: @item
13481: Most Forth systems that are being maintained support the ANS Forth
13482: standard. So if your program complies with the standard, it will be
13483: portable among many systems.
13484:
13485: @item
13486: A number of the Gforth extensions can be implemented in ANS Forth using
13487: public-domain files provided in the @file{compat/} directory. These are
13488: mentioned in the text in passing. There is no reason not to use these
13489: extensions, your program will still be ANS Forth compliant; just include
13490: the appropriate compat files with your program.
13491:
13492: @item
13493: The tool @file{ans-report.fs} (@pxref{ANS Report}) makes it easy to
13494: analyse your program and determine what non-Standard words it relies
13495: upon. However, it does not check whether you use standard words in a
13496: non-standard way.
13497:
13498: @item
13499: Some techniques are not standardized by ANS Forth, and are hard or
13500: impossible to implement in a standard way, but can be implemented in
13501: most Forth systems easily, and usually in similar ways (e.g., accessing
13502: word headers). Forth has a rich historical precedent for programmers
13503: taking advantage of implementation-dependent features of their tools
13504: (for example, relying on a knowledge of the dictionary
13505: structure). Sometimes these techniques are necessary to extract every
13506: last bit of performance from the hardware, sometimes they are just a
13507: programming shorthand.
13508:
13509: @item
13510: Does using a Gforth extension save more work than the porting this part
13511: to other Forth systems (if any) will cost?
13512:
13513: @item
13514: Is the additional functionality worth the reduction in portability and
13515: the additional porting problems?
13516:
13517: @end itemize
13518:
13519: In order to perform these consideratios, you need to know what's
13520: standard and what's not. This manual generally states if something is
1.81 anton 13521: non-standard, but the authoritative source is the
13522: @uref{http://www.taygeta.com/forth/dpans.html,standard document}.
1.65 anton 13523: Appendix A of the Standard (@var{Rationale}) provides a valuable insight
13524: into the thought processes of the technical committee.
13525:
13526: Note also that portability between Forth systems is not the only
13527: portability issue; there is also the issue of portability between
13528: different platforms (processor/OS combinations).
13529:
13530: @c ***************************************************************
13531: @node Model, Integrating Gforth, Standard vs Extensions, Top
1.1 anton 13532: @chapter Model
13533:
13534: This chapter has yet to be written. It will contain information, on
13535: which internal structures you can rely.
13536:
13537: @c ***************************************************************
13538: @node Integrating Gforth, Emacs and Gforth, Model, Top
13539: @chapter Integrating Gforth into C programs
13540:
13541: This is not yet implemented.
13542:
13543: Several people like to use Forth as scripting language for applications
13544: that are otherwise written in C, C++, or some other language.
13545:
13546: The Forth system ATLAST provides facilities for embedding it into
13547: applications; unfortunately it has several disadvantages: most
13548: importantly, it is not based on ANS Forth, and it is apparently dead
13549: (i.e., not developed further and not supported). The facilities
1.21 crook 13550: provided by Gforth in this area are inspired by ATLAST's facilities, so
1.1 anton 13551: making the switch should not be hard.
13552:
13553: We also tried to design the interface such that it can easily be
13554: implemented by other Forth systems, so that we may one day arrive at a
13555: standardized interface. Such a standard interface would allow you to
13556: replace the Forth system without having to rewrite C code.
13557:
13558: You embed the Gforth interpreter by linking with the library
13559: @code{libgforth.a} (give the compiler the option @code{-lgforth}). All
13560: global symbols in this library that belong to the interface, have the
13561: prefix @code{forth_}. (Global symbols that are used internally have the
13562: prefix @code{gforth_}).
13563:
13564: You can include the declarations of Forth types and the functions and
13565: variables of the interface with @code{#include <forth.h>}.
13566:
13567: Types.
13568:
13569: Variables.
13570:
13571: Data and FP Stack pointer. Area sizes.
13572:
13573: functions.
13574:
13575: forth_init(imagefile)
13576: forth_evaluate(string) exceptions?
13577: forth_goto(address) (or forth_execute(xt)?)
13578: forth_continue() (a corountining mechanism)
13579:
13580: Adding primitives.
13581:
13582: No checking.
13583:
13584: Signals?
13585:
13586: Accessing the Stacks
13587:
1.26 crook 13588: @c ******************************************************************
1.1 anton 13589: @node Emacs and Gforth, Image Files, Integrating Gforth, Top
13590: @chapter Emacs and Gforth
13591: @cindex Emacs and Gforth
13592:
13593: @cindex @file{gforth.el}
13594: @cindex @file{forth.el}
13595: @cindex Rydqvist, Goran
13596: @cindex comment editing commands
13597: @cindex @code{\}, editing with Emacs
13598: @cindex debug tracer editing commands
13599: @cindex @code{~~}, removal with Emacs
13600: @cindex Forth mode in Emacs
13601: Gforth comes with @file{gforth.el}, an improved version of
13602: @file{forth.el} by Goran Rydqvist (included in the TILE package). The
1.26 crook 13603: improvements are:
13604:
13605: @itemize @bullet
13606: @item
13607: A better (but still not perfect) handling of indentation.
13608: @item
13609: Comment paragraph filling (@kbd{M-q})
13610: @item
13611: Commenting (@kbd{C-x \}) and uncommenting (@kbd{C-u C-x \}) of regions
13612: @item
13613: Removal of debugging tracers (@kbd{C-x ~}, @pxref{Debugging}).
1.41 anton 13614: @item
13615: Support of the @code{info-lookup} feature for looking up the
13616: documentation of a word.
1.26 crook 13617: @end itemize
13618:
13619: I left the stuff I do not use alone, even though some of it only makes
13620: sense for TILE. To get a description of these features, enter Forth mode
13621: and type @kbd{C-h m}.
1.1 anton 13622:
13623: @cindex source location of error or debugging output in Emacs
13624: @cindex error output, finding the source location in Emacs
13625: @cindex debugging output, finding the source location in Emacs
13626: In addition, Gforth supports Emacs quite well: The source code locations
13627: given in error messages, debugging output (from @code{~~}) and failed
13628: assertion messages are in the right format for Emacs' compilation mode
13629: (@pxref{Compilation, , Running Compilations under Emacs, emacs, Emacs
13630: Manual}) so the source location corresponding to an error or other
13631: message is only a few keystrokes away (@kbd{C-x `} for the next error,
13632: @kbd{C-c C-c} for the error under the cursor).
13633:
13634: @cindex @file{TAGS} file
13635: @cindex @file{etags.fs}
13636: @cindex viewing the source of a word in Emacs
1.43 anton 13637: @cindex @code{require}, placement in files
13638: @cindex @code{include}, placement in files
13639: Also, if you @code{require} @file{etags.fs}, a new @file{TAGS} file will
1.26 crook 13640: be produced (@pxref{Tags, , Tags Tables, emacs, Emacs Manual}) that
1.1 anton 13641: contains the definitions of all words defined afterwards. You can then
13642: find the source for a word using @kbd{M-.}. Note that emacs can use
13643: several tags files at the same time (e.g., one for the Gforth sources
13644: and one for your program, @pxref{Select Tags Table,,Selecting a Tags
13645: Table,emacs, Emacs Manual}). The TAGS file for the preloaded words is
13646: @file{$(datadir)/gforth/$(VERSION)/TAGS} (e.g.,
1.43 anton 13647: @file{/usr/local/share/gforth/0.2.0/TAGS}). To get the best behaviour
13648: with @file{etags.fs}, you should avoid putting definitions both before
13649: and after @code{require} etc., otherwise you will see the same file
13650: visited several times by commands like @code{tags-search}.
1.1 anton 13651:
1.41 anton 13652: @cindex viewing the documentation of a word in Emacs
13653: @cindex context-sensitive help
13654: Moreover, for words documented in this manual, you can look up the
13655: glossary entry quickly by using @kbd{C-h TAB}
1.80 anton 13656: (@code{info-lookup-symbol}, @pxref{Documentation, ,Documentation
1.41 anton 13657: Commands, emacs, Emacs Manual}). This feature requires Emacs 20.3 or
1.42 anton 13658: later and does not work for words containing @code{:}.
1.41 anton 13659:
13660:
1.1 anton 13661: @cindex @file{.emacs}
13662: To get all these benefits, add the following lines to your @file{.emacs}
13663: file:
13664:
13665: @example
13666: (autoload 'forth-mode "gforth.el")
13667: (setq auto-mode-alist (cons '("\\.fs\\'" . forth-mode) auto-mode-alist))
13668: @end example
13669:
1.26 crook 13670: @c ******************************************************************
1.1 anton 13671: @node Image Files, Engine, Emacs and Gforth, Top
13672: @chapter Image Files
1.26 crook 13673: @cindex image file
13674: @cindex @file{.fi} files
1.1 anton 13675: @cindex precompiled Forth code
13676: @cindex dictionary in persistent form
13677: @cindex persistent form of dictionary
13678:
13679: An image file is a file containing an image of the Forth dictionary,
13680: i.e., compiled Forth code and data residing in the dictionary. By
13681: convention, we use the extension @code{.fi} for image files.
13682:
13683: @menu
1.18 anton 13684: * Image Licensing Issues:: Distribution terms for images.
13685: * Image File Background:: Why have image files?
1.67 anton 13686: * Non-Relocatable Image Files:: don't always work.
1.18 anton 13687: * Data-Relocatable Image Files:: are better.
1.67 anton 13688: * Fully Relocatable Image Files:: better yet.
1.18 anton 13689: * Stack and Dictionary Sizes:: Setting the default sizes for an image.
1.29 crook 13690: * Running Image Files:: @code{gforth -i @i{file}} or @i{file}.
1.18 anton 13691: * Modifying the Startup Sequence:: and turnkey applications.
1.1 anton 13692: @end menu
13693:
1.18 anton 13694: @node Image Licensing Issues, Image File Background, Image Files, Image Files
13695: @section Image Licensing Issues
13696: @cindex license for images
13697: @cindex image license
13698:
13699: An image created with @code{gforthmi} (@pxref{gforthmi}) or
13700: @code{savesystem} (@pxref{Non-Relocatable Image Files}) includes the
13701: original image; i.e., according to copyright law it is a derived work of
13702: the original image.
13703:
13704: Since Gforth is distributed under the GNU GPL, the newly created image
13705: falls under the GNU GPL, too. In particular, this means that if you
13706: distribute the image, you have to make all of the sources for the image
13707: available, including those you wrote. For details see @ref{License, ,
13708: GNU General Public License (Section 3)}.
13709:
13710: If you create an image with @code{cross} (@pxref{cross.fs}), the image
13711: contains only code compiled from the sources you gave it; if none of
13712: these sources is under the GPL, the terms discussed above do not apply
13713: to the image. However, if your image needs an engine (a gforth binary)
13714: that is under the GPL, you should make sure that you distribute both in
13715: a way that is at most a @emph{mere aggregation}, if you don't want the
13716: terms of the GPL to apply to the image.
13717:
13718: @node Image File Background, Non-Relocatable Image Files, Image Licensing Issues, Image Files
1.1 anton 13719: @section Image File Background
13720: @cindex image file background
13721:
1.80 anton 13722: Gforth consists not only of primitives (in the engine), but also of
1.1 anton 13723: definitions written in Forth. Since the Forth compiler itself belongs to
13724: those definitions, it is not possible to start the system with the
1.80 anton 13725: engine and the Forth source alone. Therefore we provide the Forth
1.26 crook 13726: code as an image file in nearly executable form. When Gforth starts up,
13727: a C routine loads the image file into memory, optionally relocates the
13728: addresses, then sets up the memory (stacks etc.) according to
13729: information in the image file, and (finally) starts executing Forth
13730: code.
1.1 anton 13731:
13732: The image file variants represent different compromises between the
13733: goals of making it easy to generate image files and making them
13734: portable.
13735:
13736: @cindex relocation at run-time
1.26 crook 13737: Win32Forth 3.4 and Mitch Bradley's @code{cforth} use relocation at
1.1 anton 13738: run-time. This avoids many of the complications discussed below (image
13739: files are data relocatable without further ado), but costs performance
13740: (one addition per memory access).
13741:
13742: @cindex relocation at load-time
1.26 crook 13743: By contrast, the Gforth loader performs relocation at image load time. The
13744: loader also has to replace tokens that represent primitive calls with the
1.1 anton 13745: appropriate code-field addresses (or code addresses in the case of
13746: direct threading).
13747:
13748: There are three kinds of image files, with different degrees of
13749: relocatability: non-relocatable, data-relocatable, and fully relocatable
13750: image files.
13751:
13752: @cindex image file loader
13753: @cindex relocating loader
13754: @cindex loader for image files
13755: These image file variants have several restrictions in common; they are
13756: caused by the design of the image file loader:
13757:
13758: @itemize @bullet
13759: @item
13760: There is only one segment; in particular, this means, that an image file
13761: cannot represent @code{ALLOCATE}d memory chunks (and pointers to
1.26 crook 13762: them). The contents of the stacks are not represented, either.
1.1 anton 13763:
13764: @item
13765: The only kinds of relocation supported are: adding the same offset to
13766: all cells that represent data addresses; and replacing special tokens
13767: with code addresses or with pieces of machine code.
13768:
13769: If any complex computations involving addresses are performed, the
13770: results cannot be represented in the image file. Several applications that
13771: use such computations come to mind:
13772: @itemize @minus
13773: @item
13774: Hashing addresses (or data structures which contain addresses) for table
13775: lookup. If you use Gforth's @code{table}s or @code{wordlist}s for this
13776: purpose, you will have no problem, because the hash tables are
13777: recomputed automatically when the system is started. If you use your own
13778: hash tables, you will have to do something similar.
13779:
13780: @item
13781: There's a cute implementation of doubly-linked lists that uses
13782: @code{XOR}ed addresses. You could represent such lists as singly-linked
13783: in the image file, and restore the doubly-linked representation on
13784: startup.@footnote{In my opinion, though, you should think thrice before
13785: using a doubly-linked list (whatever implementation).}
13786:
13787: @item
13788: The code addresses of run-time routines like @code{docol:} cannot be
13789: represented in the image file (because their tokens would be replaced by
13790: machine code in direct threaded implementations). As a workaround,
13791: compute these addresses at run-time with @code{>code-address} from the
13792: executions tokens of appropriate words (see the definitions of
1.80 anton 13793: @code{docol:} and friends in @file{kernel/getdoers.fs}).
1.1 anton 13794:
13795: @item
13796: On many architectures addresses are represented in machine code in some
13797: shifted or mangled form. You cannot put @code{CODE} words that contain
13798: absolute addresses in this form in a relocatable image file. Workarounds
13799: are representing the address in some relative form (e.g., relative to
13800: the CFA, which is present in some register), or loading the address from
13801: a place where it is stored in a non-mangled form.
13802: @end itemize
13803: @end itemize
13804:
13805: @node Non-Relocatable Image Files, Data-Relocatable Image Files, Image File Background, Image Files
13806: @section Non-Relocatable Image Files
13807: @cindex non-relocatable image files
1.26 crook 13808: @cindex image file, non-relocatable
1.1 anton 13809:
13810: These files are simple memory dumps of the dictionary. They are specific
13811: to the executable (i.e., @file{gforth} file) they were created
13812: with. What's worse, they are specific to the place on which the
13813: dictionary resided when the image was created. Now, there is no
13814: guarantee that the dictionary will reside at the same place the next
13815: time you start Gforth, so there's no guarantee that a non-relocatable
13816: image will work the next time (Gforth will complain instead of crashing,
13817: though).
13818:
13819: You can create a non-relocatable image file with
13820:
1.44 crook 13821:
1.1 anton 13822: doc-savesystem
13823:
1.44 crook 13824:
1.1 anton 13825: @node Data-Relocatable Image Files, Fully Relocatable Image Files, Non-Relocatable Image Files, Image Files
13826: @section Data-Relocatable Image Files
13827: @cindex data-relocatable image files
1.26 crook 13828: @cindex image file, data-relocatable
1.1 anton 13829:
13830: These files contain relocatable data addresses, but fixed code addresses
13831: (instead of tokens). They are specific to the executable (i.e.,
13832: @file{gforth} file) they were created with. For direct threading on some
13833: architectures (e.g., the i386), data-relocatable images do not work. You
13834: get a data-relocatable image, if you use @file{gforthmi} with a
13835: Gforth binary that is not doubly indirect threaded (@pxref{Fully
13836: Relocatable Image Files}).
13837:
13838: @node Fully Relocatable Image Files, Stack and Dictionary Sizes, Data-Relocatable Image Files, Image Files
13839: @section Fully Relocatable Image Files
13840: @cindex fully relocatable image files
1.26 crook 13841: @cindex image file, fully relocatable
1.1 anton 13842:
13843: @cindex @file{kern*.fi}, relocatability
13844: @cindex @file{gforth.fi}, relocatability
13845: These image files have relocatable data addresses, and tokens for code
13846: addresses. They can be used with different binaries (e.g., with and
13847: without debugging) on the same machine, and even across machines with
13848: the same data formats (byte order, cell size, floating point
13849: format). However, they are usually specific to the version of Gforth
13850: they were created with. The files @file{gforth.fi} and @file{kernl*.fi}
13851: are fully relocatable.
13852:
13853: There are two ways to create a fully relocatable image file:
13854:
13855: @menu
1.29 crook 13856: * gforthmi:: The normal way
1.1 anton 13857: * cross.fs:: The hard way
13858: @end menu
13859:
13860: @node gforthmi, cross.fs, Fully Relocatable Image Files, Fully Relocatable Image Files
13861: @subsection @file{gforthmi}
13862: @cindex @file{comp-i.fs}
13863: @cindex @file{gforthmi}
13864:
13865: You will usually use @file{gforthmi}. If you want to create an
1.29 crook 13866: image @i{file} that contains everything you would load by invoking
13867: Gforth with @code{gforth @i{options}}, you simply say:
1.1 anton 13868: @example
1.29 crook 13869: gforthmi @i{file} @i{options}
1.1 anton 13870: @end example
13871:
13872: E.g., if you want to create an image @file{asm.fi} that has the file
13873: @file{asm.fs} loaded in addition to the usual stuff, you could do it
13874: like this:
13875:
13876: @example
13877: gforthmi asm.fi asm.fs
13878: @end example
13879:
1.27 crook 13880: @file{gforthmi} is implemented as a sh script and works like this: It
13881: produces two non-relocatable images for different addresses and then
13882: compares them. Its output reflects this: first you see the output (if
1.62 crook 13883: any) of the two Gforth invocations that produce the non-relocatable image
1.27 crook 13884: files, then you see the output of the comparing program: It displays the
13885: offset used for data addresses and the offset used for code addresses;
1.1 anton 13886: moreover, for each cell that cannot be represented correctly in the
1.44 crook 13887: image files, it displays a line like this:
1.1 anton 13888:
13889: @example
13890: 78DC BFFFFA50 BFFFFA40
13891: @end example
13892:
13893: This means that at offset $78dc from @code{forthstart}, one input image
13894: contains $bffffa50, and the other contains $bffffa40. Since these cells
13895: cannot be represented correctly in the output image, you should examine
13896: these places in the dictionary and verify that these cells are dead
13897: (i.e., not read before they are written).
1.39 anton 13898:
13899: @cindex --application, @code{gforthmi} option
13900: If you insert the option @code{--application} in front of the image file
13901: name, you will get an image that uses the @code{--appl-image} option
13902: instead of the @code{--image-file} option (@pxref{Invoking
13903: Gforth}). When you execute such an image on Unix (by typing the image
13904: name as command), the Gforth engine will pass all options to the image
13905: instead of trying to interpret them as engine options.
1.1 anton 13906:
1.27 crook 13907: If you type @file{gforthmi} with no arguments, it prints some usage
13908: instructions.
13909:
1.1 anton 13910: @cindex @code{savesystem} during @file{gforthmi}
13911: @cindex @code{bye} during @file{gforthmi}
13912: @cindex doubly indirect threaded code
1.44 crook 13913: @cindex environment variables
13914: @cindex @code{GFORTHD} -- environment variable
13915: @cindex @code{GFORTH} -- environment variable
1.1 anton 13916: @cindex @code{gforth-ditc}
1.29 crook 13917: There are a few wrinkles: After processing the passed @i{options}, the
1.1 anton 13918: words @code{savesystem} and @code{bye} must be visible. A special doubly
13919: indirect threaded version of the @file{gforth} executable is used for
1.62 crook 13920: creating the non-relocatable images; you can pass the exact filename of
1.1 anton 13921: this executable through the environment variable @code{GFORTHD}
13922: (default: @file{gforth-ditc}); if you pass a version that is not doubly
13923: indirect threaded, you will not get a fully relocatable image, but a
1.27 crook 13924: data-relocatable image (because there is no code address offset). The
13925: normal @file{gforth} executable is used for creating the relocatable
13926: image; you can pass the exact filename of this executable through the
13927: environment variable @code{GFORTH}.
1.1 anton 13928:
13929: @node cross.fs, , gforthmi, Fully Relocatable Image Files
13930: @subsection @file{cross.fs}
13931: @cindex @file{cross.fs}
13932: @cindex cross-compiler
13933: @cindex metacompiler
1.47 crook 13934: @cindex target compiler
1.1 anton 13935:
13936: You can also use @code{cross}, a batch compiler that accepts a Forth-like
1.47 crook 13937: programming language (@pxref{Cross Compiler}).
1.1 anton 13938:
1.47 crook 13939: @code{cross} allows you to create image files for machines with
1.1 anton 13940: different data sizes and data formats than the one used for generating
13941: the image file. You can also use it to create an application image that
13942: does not contain a Forth compiler. These features are bought with
13943: restrictions and inconveniences in programming. E.g., addresses have to
13944: be stored in memory with special words (@code{A!}, @code{A,}, etc.) in
13945: order to make the code relocatable.
13946:
13947:
13948: @node Stack and Dictionary Sizes, Running Image Files, Fully Relocatable Image Files, Image Files
13949: @section Stack and Dictionary Sizes
13950: @cindex image file, stack and dictionary sizes
13951: @cindex dictionary size default
13952: @cindex stack size default
13953:
13954: If you invoke Gforth with a command line flag for the size
13955: (@pxref{Invoking Gforth}), the size you specify is stored in the
13956: dictionary. If you save the dictionary with @code{savesystem} or create
13957: an image with @file{gforthmi}, this size will become the default
13958: for the resulting image file. E.g., the following will create a
1.21 crook 13959: fully relocatable version of @file{gforth.fi} with a 1MB dictionary:
1.1 anton 13960:
13961: @example
13962: gforthmi gforth.fi -m 1M
13963: @end example
13964:
13965: In other words, if you want to set the default size for the dictionary
13966: and the stacks of an image, just invoke @file{gforthmi} with the
13967: appropriate options when creating the image.
13968:
13969: @cindex stack size, cache-friendly
13970: Note: For cache-friendly behaviour (i.e., good performance), you should
13971: make the sizes of the stacks modulo, say, 2K, somewhat different. E.g.,
13972: the default stack sizes are: data: 16k (mod 2k=0); fp: 15.5k (mod
13973: 2k=1.5k); return: 15k(mod 2k=1k); locals: 14.5k (mod 2k=0.5k).
13974:
13975: @node Running Image Files, Modifying the Startup Sequence, Stack and Dictionary Sizes, Image Files
13976: @section Running Image Files
13977: @cindex running image files
13978: @cindex invoking image files
13979: @cindex image file invocation
13980:
13981: @cindex -i, invoke image file
13982: @cindex --image file, invoke image file
1.29 crook 13983: You can invoke Gforth with an image file @i{image} instead of the
1.1 anton 13984: default @file{gforth.fi} with the @code{-i} flag (@pxref{Invoking Gforth}):
13985: @example
1.29 crook 13986: gforth -i @i{image}
1.1 anton 13987: @end example
13988:
13989: @cindex executable image file
1.26 crook 13990: @cindex image file, executable
1.1 anton 13991: If your operating system supports starting scripts with a line of the
13992: form @code{#! ...}, you just have to type the image file name to start
13993: Gforth with this image file (note that the file extension @code{.fi} is
1.29 crook 13994: just a convention). I.e., to run Gforth with the image file @i{image},
13995: you can just type @i{image} instead of @code{gforth -i @i{image}}.
1.27 crook 13996: This works because every @code{.fi} file starts with a line of this
13997: format:
13998:
13999: @example
14000: #! /usr/local/bin/gforth-0.4.0 -i
14001: @end example
14002:
14003: The file and pathname for the Gforth engine specified on this line is
14004: the specific Gforth executable that it was built against; i.e. the value
14005: of the environment variable @code{GFORTH} at the time that
14006: @file{gforthmi} was executed.
1.1 anton 14007:
1.27 crook 14008: You can make use of the same shell capability to make a Forth source
14009: file into an executable. For example, if you place this text in a file:
1.26 crook 14010:
14011: @example
14012: #! /usr/local/bin/gforth
14013:
14014: ." Hello, world" CR
14015: bye
14016: @end example
14017:
14018: @noindent
1.27 crook 14019: and then make the file executable (chmod +x in Unix), you can run it
1.26 crook 14020: directly from the command line. The sequence @code{#!} is used in two
14021: ways; firstly, it is recognised as a ``magic sequence'' by the operating
1.29 crook 14022: system@footnote{The Unix kernel actually recognises two types of files:
14023: executable files and files of data, where the data is processed by an
14024: interpreter that is specified on the ``interpreter line'' -- the first
14025: line of the file, starting with the sequence #!. There may be a small
14026: limit (e.g., 32) on the number of characters that may be specified on
14027: the interpreter line.} secondly it is treated as a comment character by
14028: Gforth. Because of the second usage, a space is required between
1.80 anton 14029: @code{#!} and the path to the executable (moreover, some Unixes
14030: require the sequence @code{#! /}).
1.27 crook 14031:
14032: The disadvantage of this latter technique, compared with using
1.80 anton 14033: @file{gforthmi}, is that it is slightly slower; the Forth source code is
14034: compiled on-the-fly, each time the program is invoked.
1.26 crook 14035:
1.1 anton 14036: doc-#!
14037:
1.44 crook 14038:
1.1 anton 14039: @node Modifying the Startup Sequence, , Running Image Files, Image Files
14040: @section Modifying the Startup Sequence
14041: @cindex startup sequence for image file
14042: @cindex image file initialization sequence
14043: @cindex initialization sequence of image file
14044:
14045: You can add your own initialization to the startup sequence through the
1.26 crook 14046: deferred word @code{'cold}. @code{'cold} is invoked just before the
1.80 anton 14047: image-specific command line processing (i.e., loading files and
1.26 crook 14048: evaluating (@code{-e}) strings) starts.
1.1 anton 14049:
14050: A sequence for adding your initialization usually looks like this:
14051:
14052: @example
14053: :noname
14054: Defers 'cold \ do other initialization stuff (e.g., rehashing wordlists)
14055: ... \ your stuff
14056: ; IS 'cold
14057: @end example
14058:
14059: @cindex turnkey image files
1.26 crook 14060: @cindex image file, turnkey applications
1.1 anton 14061: You can make a turnkey image by letting @code{'cold} execute a word
14062: (your turnkey application) that never returns; instead, it exits Gforth
14063: via @code{bye} or @code{throw}.
14064:
14065: @cindex command-line arguments, access
14066: @cindex arguments on the command line, access
14067: You can access the (image-specific) command-line arguments through the
1.26 crook 14068: variables @code{argc} and @code{argv}. @code{arg} provides convenient
1.1 anton 14069: access to @code{argv}.
14070:
1.26 crook 14071: If @code{'cold} exits normally, Gforth processes the command-line
14072: arguments as files to be loaded and strings to be evaluated. Therefore,
14073: @code{'cold} should remove the arguments it has used in this case.
14074:
1.44 crook 14075:
14076:
1.26 crook 14077: doc-'cold
1.1 anton 14078: doc-argc
14079: doc-argv
14080: doc-arg
14081:
14082:
1.44 crook 14083:
1.1 anton 14084: @c ******************************************************************
1.13 pazsan 14085: @node Engine, Binding to System Library, Image Files, Top
1.1 anton 14086: @chapter Engine
14087: @cindex engine
14088: @cindex virtual machine
14089:
1.26 crook 14090: Reading this chapter is not necessary for programming with Gforth. It
1.1 anton 14091: may be helpful for finding your way in the Gforth sources.
14092:
1.66 anton 14093: The ideas in this section have also been published in Bernd Paysan,
14094: @cite{ANS fig/GNU/??? Forth} (in German), Forth-Tagung '93 and M. Anton
14095: Ertl, @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl93.ps.Z, A
14096: Portable Forth Engine}}, EuroForth '93.
1.1 anton 14097:
14098: @menu
14099: * Portability::
14100: * Threading::
14101: * Primitives::
14102: * Performance::
14103: @end menu
14104:
14105: @node Portability, Threading, Engine, Engine
14106: @section Portability
14107: @cindex engine portability
14108:
1.26 crook 14109: An important goal of the Gforth Project is availability across a wide
14110: range of personal machines. fig-Forth, and, to a lesser extent, F83,
14111: achieved this goal by manually coding the engine in assembly language
14112: for several then-popular processors. This approach is very
14113: labor-intensive and the results are short-lived due to progress in
14114: computer architecture.
1.1 anton 14115:
14116: @cindex C, using C for the engine
14117: Others have avoided this problem by coding in C, e.g., Mitch Bradley
14118: (cforth), Mikael Patel (TILE) and Dirk Zoller (pfe). This approach is
14119: particularly popular for UNIX-based Forths due to the large variety of
14120: architectures of UNIX machines. Unfortunately an implementation in C
14121: does not mix well with the goals of efficiency and with using
14122: traditional techniques: Indirect or direct threading cannot be expressed
14123: in C, and switch threading, the fastest technique available in C, is
14124: significantly slower. Another problem with C is that it is very
14125: cumbersome to express double integer arithmetic.
14126:
14127: @cindex GNU C for the engine
14128: @cindex long long
14129: Fortunately, there is a portable language that does not have these
14130: limitations: GNU C, the version of C processed by the GNU C compiler
14131: (@pxref{C Extensions, , Extensions to the C Language Family, gcc.info,
14132: GNU C Manual}). Its labels as values feature (@pxref{Labels as Values, ,
14133: Labels as Values, gcc.info, GNU C Manual}) makes direct and indirect
14134: threading possible, its @code{long long} type (@pxref{Long Long, ,
14135: Double-Word Integers, gcc.info, GNU C Manual}) corresponds to Forth's
14136: double numbers@footnote{Unfortunately, long longs are not implemented
14137: properly on all machines (e.g., on alpha-osf1, long longs are only 64
14138: bits, the same size as longs (and pointers), but they should be twice as
1.4 anton 14139: long according to @pxref{Long Long, , Double-Word Integers, gcc.info, GNU
1.1 anton 14140: C Manual}). So, we had to implement doubles in C after all. Still, on
14141: most machines we can use long longs and achieve better performance than
14142: with the emulation package.}. GNU C is available for free on all
14143: important (and many unimportant) UNIX machines, VMS, 80386s running
14144: MS-DOS, the Amiga, and the Atari ST, so a Forth written in GNU C can run
14145: on all these machines.
14146:
14147: Writing in a portable language has the reputation of producing code that
14148: is slower than assembly. For our Forth engine we repeatedly looked at
14149: the code produced by the compiler and eliminated most compiler-induced
14150: inefficiencies by appropriate changes in the source code.
14151:
14152: @cindex explicit register declarations
14153: @cindex --enable-force-reg, configuration flag
14154: @cindex -DFORCE_REG
14155: However, register allocation cannot be portably influenced by the
14156: programmer, leading to some inefficiencies on register-starved
14157: machines. We use explicit register declarations (@pxref{Explicit Reg
14158: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) to
14159: improve the speed on some machines. They are turned on by using the
14160: configuration flag @code{--enable-force-reg} (@code{gcc} switch
14161: @code{-DFORCE_REG}). Unfortunately, this feature not only depends on the
14162: machine, but also on the compiler version: On some machines some
14163: compiler versions produce incorrect code when certain explicit register
14164: declarations are used. So by default @code{-DFORCE_REG} is not used.
14165:
14166: @node Threading, Primitives, Portability, Engine
14167: @section Threading
14168: @cindex inner interpreter implementation
14169: @cindex threaded code implementation
14170:
14171: @cindex labels as values
14172: GNU C's labels as values extension (available since @code{gcc-2.0},
14173: @pxref{Labels as Values, , Labels as Values, gcc.info, GNU C Manual})
1.29 crook 14174: makes it possible to take the address of @i{label} by writing
14175: @code{&&@i{label}}. This address can then be used in a statement like
14176: @code{goto *@i{address}}. I.e., @code{goto *&&x} is the same as
1.1 anton 14177: @code{goto x}.
14178:
1.26 crook 14179: @cindex @code{NEXT}, indirect threaded
1.1 anton 14180: @cindex indirect threaded inner interpreter
14181: @cindex inner interpreter, indirect threaded
1.26 crook 14182: With this feature an indirect threaded @code{NEXT} looks like:
1.1 anton 14183: @example
14184: cfa = *ip++;
14185: ca = *cfa;
14186: goto *ca;
14187: @end example
14188: @cindex instruction pointer
14189: For those unfamiliar with the names: @code{ip} is the Forth instruction
14190: pointer; the @code{cfa} (code-field address) corresponds to ANS Forths
14191: execution token and points to the code field of the next word to be
14192: executed; The @code{ca} (code address) fetched from there points to some
14193: executable code, e.g., a primitive or the colon definition handler
14194: @code{docol}.
14195:
1.26 crook 14196: @cindex @code{NEXT}, direct threaded
1.1 anton 14197: @cindex direct threaded inner interpreter
14198: @cindex inner interpreter, direct threaded
14199: Direct threading is even simpler:
14200: @example
14201: ca = *ip++;
14202: goto *ca;
14203: @end example
14204:
14205: Of course we have packaged the whole thing neatly in macros called
1.26 crook 14206: @code{NEXT} and @code{NEXT1} (the part of @code{NEXT} after fetching the cfa).
1.1 anton 14207:
14208: @menu
14209: * Scheduling::
14210: * Direct or Indirect Threaded?::
14211: * DOES>::
14212: @end menu
14213:
14214: @node Scheduling, Direct or Indirect Threaded?, Threading, Threading
14215: @subsection Scheduling
14216: @cindex inner interpreter optimization
14217:
14218: There is a little complication: Pipelined and superscalar processors,
14219: i.e., RISC and some modern CISC machines can process independent
14220: instructions while waiting for the results of an instruction. The
14221: compiler usually reorders (schedules) the instructions in a way that
14222: achieves good usage of these delay slots. However, on our first tries
14223: the compiler did not do well on scheduling primitives. E.g., for
14224: @code{+} implemented as
14225: @example
14226: n=sp[0]+sp[1];
14227: sp++;
14228: sp[0]=n;
14229: NEXT;
14230: @end example
1.81 anton 14231: the @code{NEXT} comes strictly after the other code, i.e., there is
14232: nearly no scheduling. After a little thought the problem becomes clear:
14233: The compiler cannot know that @code{sp} and @code{ip} point to different
1.21 crook 14234: addresses (and the version of @code{gcc} we used would not know it even
14235: if it was possible), so it could not move the load of the cfa above the
14236: store to the TOS. Indeed the pointers could be the same, if code on or
14237: very near the top of stack were executed. In the interest of speed we
14238: chose to forbid this probably unused ``feature'' and helped the compiler
1.81 anton 14239: in scheduling: @code{NEXT} is divided into several parts:
14240: @code{NEXT_P0}, @code{NEXT_P1} and @code{NEXT_P2}). @code{+} now looks
14241: like:
1.1 anton 14242: @example
1.81 anton 14243: NEXT_P0;
1.1 anton 14244: n=sp[0]+sp[1];
14245: sp++;
14246: NEXT_P1;
14247: sp[0]=n;
14248: NEXT_P2;
14249: @end example
14250:
1.81 anton 14251: There are various schemes that distribute the different operations of
14252: NEXT between these parts in several ways; in general, different schemes
14253: perform best on different processors. We use a scheme for most
14254: architectures that performs well for most processors of this
14255: architecture; in the furture we may switch to benchmarking and chosing
14256: the scheme on installation time.
14257:
1.1 anton 14258:
14259: @node Direct or Indirect Threaded?, DOES>, Scheduling, Threading
14260: @subsection Direct or Indirect Threaded?
14261: @cindex threading, direct or indirect?
14262:
14263: @cindex -DDIRECT_THREADED
14264: Both! After packaging the nasty details in macro definitions we
14265: realized that we could switch between direct and indirect threading by
14266: simply setting a compilation flag (@code{-DDIRECT_THREADED}) and
14267: defining a few machine-specific macros for the direct-threading case.
14268: On the Forth level we also offer access words that hide the
14269: differences between the threading methods (@pxref{Threading Words}).
14270:
14271: Indirect threading is implemented completely machine-independently.
14272: Direct threading needs routines for creating jumps to the executable
1.21 crook 14273: code (e.g. to @code{docol} or @code{dodoes}). These routines are inherently
14274: machine-dependent, but they do not amount to many source lines. Therefore,
14275: even porting direct threading to a new machine requires little effort.
1.1 anton 14276:
14277: @cindex --enable-indirect-threaded, configuration flag
14278: @cindex --enable-direct-threaded, configuration flag
14279: The default threading method is machine-dependent. You can enforce a
14280: specific threading method when building Gforth with the configuration
14281: flag @code{--enable-direct-threaded} or
14282: @code{--enable-indirect-threaded}. Note that direct threading is not
14283: supported on all machines.
14284:
14285: @node DOES>, , Direct or Indirect Threaded?, Threading
14286: @subsection DOES>
14287: @cindex @code{DOES>} implementation
14288:
1.26 crook 14289: @cindex @code{dodoes} routine
14290: @cindex @code{DOES>}-code
1.1 anton 14291: One of the most complex parts of a Forth engine is @code{dodoes}, i.e.,
14292: the chunk of code executed by every word defined by a
14293: @code{CREATE}...@code{DOES>} pair. The main problem here is: How to find
14294: the Forth code to be executed, i.e. the code after the
1.26 crook 14295: @code{DOES>} (the @code{DOES>}-code)? There are two solutions:
1.1 anton 14296:
1.21 crook 14297: In fig-Forth the code field points directly to the @code{dodoes} and the
1.45 crook 14298: @code{DOES>}-code address is stored in the cell after the code address (i.e. at
1.29 crook 14299: @code{@i{CFA} cell+}). It may seem that this solution is illegal in
1.1 anton 14300: the Forth-79 and all later standards, because in fig-Forth this address
14301: lies in the body (which is illegal in these standards). However, by
14302: making the code field larger for all words this solution becomes legal
14303: again. We use this approach for the indirect threaded version and for
14304: direct threading on some machines. Leaving a cell unused in most words
14305: is a bit wasteful, but on the machines we are targeting this is hardly a
14306: problem. The other reason for having a code field size of two cells is
14307: to avoid having different image files for direct and indirect threaded
14308: systems (direct threaded systems require two-cell code fields on many
14309: machines).
14310:
1.26 crook 14311: @cindex @code{DOES>}-handler
1.1 anton 14312: The other approach is that the code field points or jumps to the cell
1.26 crook 14313: after @code{DOES>}. In this variant there is a jump to @code{dodoes} at
14314: this address (the @code{DOES>}-handler). @code{dodoes} can then get the
14315: @code{DOES>}-code address by computing the code address, i.e., the address of
1.45 crook 14316: the jump to @code{dodoes}, and add the length of that jump field. A variant of
1.1 anton 14317: this is to have a call to @code{dodoes} after the @code{DOES>}; then the
14318: return address (which can be found in the return register on RISCs) is
1.26 crook 14319: the @code{DOES>}-code address. Since the two cells available in the code field
1.1 anton 14320: are used up by the jump to the code address in direct threading on many
14321: architectures, we use this approach for direct threading on these
14322: architectures. We did not want to add another cell to the code field.
14323:
14324: @node Primitives, Performance, Threading, Engine
14325: @section Primitives
14326: @cindex primitives, implementation
14327: @cindex virtual machine instructions, implementation
14328:
14329: @menu
14330: * Automatic Generation::
14331: * TOS Optimization::
14332: * Produced code::
14333: @end menu
14334:
14335: @node Automatic Generation, TOS Optimization, Primitives, Primitives
14336: @subsection Automatic Generation
14337: @cindex primitives, automatic generation
14338:
14339: @cindex @file{prims2x.fs}
14340: Since the primitives are implemented in a portable language, there is no
14341: longer any need to minimize the number of primitives. On the contrary,
14342: having many primitives has an advantage: speed. In order to reduce the
14343: number of errors in primitives and to make programming them easier, we
14344: provide a tool, the primitive generator (@file{prims2x.fs}), that
14345: automatically generates most (and sometimes all) of the C code for a
14346: primitive from the stack effect notation. The source for a primitive
14347: has the following form:
14348:
14349: @cindex primitive source format
14350: @format
1.58 anton 14351: @i{Forth-name} ( @i{stack-effect} ) @i{category} [@i{pronounc.}]
1.29 crook 14352: [@code{""}@i{glossary entry}@code{""}]
14353: @i{C code}
1.1 anton 14354: [@code{:}
1.29 crook 14355: @i{Forth code}]
1.1 anton 14356: @end format
14357:
14358: The items in brackets are optional. The category and glossary fields
14359: are there for generating the documentation, the Forth code is there
14360: for manual implementations on machines without GNU C. E.g., the source
14361: for the primitive @code{+} is:
14362: @example
1.58 anton 14363: + ( n1 n2 -- n ) core plus
1.1 anton 14364: n = n1+n2;
14365: @end example
14366:
14367: This looks like a specification, but in fact @code{n = n1+n2} is C
14368: code. Our primitive generation tool extracts a lot of information from
14369: the stack effect notations@footnote{We use a one-stack notation, even
14370: though we have separate data and floating-point stacks; The separate
14371: notation can be generated easily from the unified notation.}: The number
14372: of items popped from and pushed on the stack, their type, and by what
14373: name they are referred to in the C code. It then generates a C code
14374: prelude and postlude for each primitive. The final C code for @code{+}
14375: looks like this:
14376:
14377: @example
1.46 pazsan 14378: I_plus: /* + ( n1 n2 -- n ) */ /* label, stack effect */
1.1 anton 14379: /* */ /* documentation */
1.81 anton 14380: NAME("+") /* debugging output (with -DDEBUG) */
1.1 anton 14381: @{
14382: DEF_CA /* definition of variable ca (indirect threading) */
14383: Cell n1; /* definitions of variables */
14384: Cell n2;
14385: Cell n;
1.81 anton 14386: NEXT_P0; /* NEXT part 0 */
1.1 anton 14387: n1 = (Cell) sp[1]; /* input */
14388: n2 = (Cell) TOS;
14389: sp += 1; /* stack adjustment */
14390: @{
14391: n = n1+n2; /* C code taken from the source */
14392: @}
14393: NEXT_P1; /* NEXT part 1 */
14394: TOS = (Cell)n; /* output */
14395: NEXT_P2; /* NEXT part 2 */
14396: @}
14397: @end example
14398:
14399: This looks long and inefficient, but the GNU C compiler optimizes quite
14400: well and produces optimal code for @code{+} on, e.g., the R3000 and the
14401: HP RISC machines: Defining the @code{n}s does not produce any code, and
14402: using them as intermediate storage also adds no cost.
14403:
1.26 crook 14404: There are also other optimizations that are not illustrated by this
14405: example: assignments between simple variables are usually for free (copy
1.1 anton 14406: propagation). If one of the stack items is not used by the primitive
14407: (e.g. in @code{drop}), the compiler eliminates the load from the stack
14408: (dead code elimination). On the other hand, there are some things that
14409: the compiler does not do, therefore they are performed by
14410: @file{prims2x.fs}: The compiler does not optimize code away that stores
14411: a stack item to the place where it just came from (e.g., @code{over}).
14412:
14413: While programming a primitive is usually easy, there are a few cases
14414: where the programmer has to take the actions of the generator into
14415: account, most notably @code{?dup}, but also words that do not (always)
1.26 crook 14416: fall through to @code{NEXT}.
1.1 anton 14417:
14418: @node TOS Optimization, Produced code, Automatic Generation, Primitives
14419: @subsection TOS Optimization
14420: @cindex TOS optimization for primitives
14421: @cindex primitives, keeping the TOS in a register
14422:
14423: An important optimization for stack machine emulators, e.g., Forth
14424: engines, is keeping one or more of the top stack items in
1.29 crook 14425: registers. If a word has the stack effect @i{in1}...@i{inx} @code{--}
14426: @i{out1}...@i{outy}, keeping the top @i{n} items in registers
1.1 anton 14427: @itemize @bullet
14428: @item
1.29 crook 14429: is better than keeping @i{n-1} items, if @i{x>=n} and @i{y>=n},
1.1 anton 14430: due to fewer loads from and stores to the stack.
1.29 crook 14431: @item is slower than keeping @i{n-1} items, if @i{x<>y} and @i{x<n} and
14432: @i{y<n}, due to additional moves between registers.
1.1 anton 14433: @end itemize
14434:
14435: @cindex -DUSE_TOS
14436: @cindex -DUSE_NO_TOS
14437: In particular, keeping one item in a register is never a disadvantage,
14438: if there are enough registers. Keeping two items in registers is a
14439: disadvantage for frequent words like @code{?branch}, constants,
14440: variables, literals and @code{i}. Therefore our generator only produces
14441: code that keeps zero or one items in registers. The generated C code
14442: covers both cases; the selection between these alternatives is made at
14443: C-compile time using the switch @code{-DUSE_TOS}. @code{TOS} in the C
14444: code for @code{+} is just a simple variable name in the one-item case,
14445: otherwise it is a macro that expands into @code{sp[0]}. Note that the
14446: GNU C compiler tries to keep simple variables like @code{TOS} in
14447: registers, and it usually succeeds, if there are enough registers.
14448:
14449: @cindex -DUSE_FTOS
14450: @cindex -DUSE_NO_FTOS
14451: The primitive generator performs the TOS optimization for the
14452: floating-point stack, too (@code{-DUSE_FTOS}). For floating-point
14453: operations the benefit of this optimization is even larger:
14454: floating-point operations take quite long on most processors, but can be
14455: performed in parallel with other operations as long as their results are
14456: not used. If the FP-TOS is kept in a register, this works. If
14457: it is kept on the stack, i.e., in memory, the store into memory has to
14458: wait for the result of the floating-point operation, lengthening the
14459: execution time of the primitive considerably.
14460:
14461: The TOS optimization makes the automatic generation of primitives a
14462: bit more complicated. Just replacing all occurrences of @code{sp[0]} by
14463: @code{TOS} is not sufficient. There are some special cases to
14464: consider:
14465: @itemize @bullet
14466: @item In the case of @code{dup ( w -- w w )} the generator must not
14467: eliminate the store to the original location of the item on the stack,
14468: if the TOS optimization is turned on.
14469: @item Primitives with stack effects of the form @code{--}
1.29 crook 14470: @i{out1}...@i{outy} must store the TOS to the stack at the start.
14471: Likewise, primitives with the stack effect @i{in1}...@i{inx} @code{--}
1.1 anton 14472: must load the TOS from the stack at the end. But for the null stack
14473: effect @code{--} no stores or loads should be generated.
14474: @end itemize
14475:
14476: @node Produced code, , TOS Optimization, Primitives
14477: @subsection Produced code
14478: @cindex primitives, assembly code listing
14479:
14480: @cindex @file{engine.s}
14481: To see what assembly code is produced for the primitives on your machine
14482: with your compiler and your flag settings, type @code{make engine.s} and
1.81 anton 14483: look at the resulting file @file{engine.s}. Alternatively, you can also
14484: disassemble the code of primitives with @code{see} on some architectures.
1.1 anton 14485:
14486: @node Performance, , Primitives, Engine
14487: @section Performance
14488: @cindex performance of some Forth interpreters
14489: @cindex engine performance
14490: @cindex benchmarking Forth systems
14491: @cindex Gforth performance
14492:
14493: On RISCs the Gforth engine is very close to optimal; i.e., it is usually
14494: impossible to write a significantly faster engine.
14495:
14496: On register-starved machines like the 386 architecture processors
14497: improvements are possible, because @code{gcc} does not utilize the
14498: registers as well as a human, even with explicit register declarations;
14499: e.g., Bernd Beuster wrote a Forth system fragment in assembly language
14500: and hand-tuned it for the 486; this system is 1.19 times faster on the
14501: Sieve benchmark on a 486DX2/66 than Gforth compiled with
1.40 anton 14502: @code{gcc-2.6.3} with @code{-DFORCE_REG}. The situation has improved
14503: with gcc-2.95 and gforth-0.4.9; now the most important virtual machine
14504: registers fit in real registers (and we can even afford to use the TOS
14505: optimization), resulting in a speedup of 1.14 on the sieve over the
14506: earlier results.
1.1 anton 14507:
14508: @cindex Win32Forth performance
14509: @cindex NT Forth performance
14510: @cindex eforth performance
14511: @cindex ThisForth performance
14512: @cindex PFE performance
14513: @cindex TILE performance
1.81 anton 14514: The potential advantage of assembly language implementations is not
14515: necessarily realized in complete Forth systems: We compared Gforth-0.4.9
14516: (direct threaded, compiled with @code{gcc-2.95.1} and
14517: @code{-DFORCE_REG}) with Win32Forth 1.2093 (newer versions are
14518: reportedly much faster), LMI's NT Forth (Beta, May 1994) and Eforth
14519: (with and without peephole (aka pinhole) optimization of the threaded
14520: code); all these systems were written in assembly language. We also
14521: compared Gforth with three systems written in C: PFE-0.9.14 (compiled
14522: with @code{gcc-2.6.3} with the default configuration for Linux:
14523: @code{-O2 -fomit-frame-pointer -DUSE_REGS -DUNROLL_NEXT}), ThisForth
14524: Beta (compiled with @code{gcc-2.6.3 -O3 -fomit-frame-pointer}; ThisForth
14525: employs peephole optimization of the threaded code) and TILE (compiled
14526: with @code{make opt}). We benchmarked Gforth, PFE, ThisForth and TILE on
14527: a 486DX2/66 under Linux. Kenneth O'Heskin kindly provided the results
14528: for Win32Forth and NT Forth on a 486DX2/66 with similar memory
14529: performance under Windows NT. Marcel Hendrix ported Eforth to Linux,
14530: then extended it to run the benchmarks, added the peephole optimizer,
14531: ran the benchmarks and reported the results.
1.40 anton 14532:
1.1 anton 14533: We used four small benchmarks: the ubiquitous Sieve; bubble-sorting and
14534: matrix multiplication come from the Stanford integer benchmarks and have
14535: been translated into Forth by Martin Fraeman; we used the versions
14536: included in the TILE Forth package, but with bigger data set sizes; and
14537: a recursive Fibonacci number computation for benchmarking calling
14538: performance. The following table shows the time taken for the benchmarks
14539: scaled by the time taken by Gforth (in other words, it shows the speedup
14540: factor that Gforth achieved over the other systems).
14541:
14542: @example
1.40 anton 14543: relative Win32- NT eforth This-
1.1 anton 14544: time Gforth Forth Forth eforth +opt PFE Forth TILE
1.81 anton 14545: sieve 1.00 1.60 1.32 1.60 0.98 1.82 3.67 9.91
14546: bubble 1.00 1.55 1.66 1.75 1.04 1.78 4.58
14547: matmul 1.00 1.71 1.57 1.69 0.86 1.83 4.74
14548: fib 1.00 1.76 1.54 1.41 1.00 2.01 3.45 4.96
1.1 anton 14549: @end example
14550:
1.26 crook 14551: You may be quite surprised by the good performance of Gforth when
14552: compared with systems written in assembly language. One important reason
14553: for the disappointing performance of these other systems is probably
14554: that they are not written optimally for the 486 (e.g., they use the
14555: @code{lods} instruction). In addition, Win32Forth uses a comfortable,
14556: but costly method for relocating the Forth image: like @code{cforth}, it
14557: computes the actual addresses at run time, resulting in two address
14558: computations per @code{NEXT} (@pxref{Image File Background}).
14559:
1.40 anton 14560: Only Eforth with the peephole optimizer performs comparable to
14561: Gforth. The speedups achieved with peephole optimization of threaded
14562: code are quite remarkable. Adding a peephole optimizer to Gforth should
14563: cause similar speedups.
1.1 anton 14564:
14565: The speedup of Gforth over PFE, ThisForth and TILE can be easily
14566: explained with the self-imposed restriction of the latter systems to
14567: standard C, which makes efficient threading impossible (however, the
1.4 anton 14568: measured implementation of PFE uses a GNU C extension: @pxref{Global Reg
1.1 anton 14569: Vars, , Defining Global Register Variables, gcc.info, GNU C Manual}).
14570: Moreover, current C compilers have a hard time optimizing other aspects
14571: of the ThisForth and the TILE source.
14572:
1.26 crook 14573: The performance of Gforth on 386 architecture processors varies widely
14574: with the version of @code{gcc} used. E.g., @code{gcc-2.5.8} failed to
14575: allocate any of the virtual machine registers into real machine
14576: registers by itself and would not work correctly with explicit register
1.40 anton 14577: declarations, giving a 1.5 times slower engine (on a 486DX2/66 running
1.26 crook 14578: the Sieve) than the one measured above.
1.1 anton 14579:
1.26 crook 14580: Note that there have been several releases of Win32Forth since the
14581: release presented here, so the results presented above may have little
1.40 anton 14582: predictive value for the performance of Win32Forth today (results for
14583: the current release on an i486DX2/66 are welcome).
1.1 anton 14584:
14585: @cindex @file{Benchres}
1.66 anton 14586: In
14587: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl&maierhofer95.ps.gz,
14588: Translating Forth to Efficient C}} by M. Anton Ertl and Martin
1.1 anton 14589: Maierhofer (presented at EuroForth '95), an indirect threaded version of
1.66 anton 14590: Gforth is compared with Win32Forth, NT Forth, PFE, ThisForth, and
14591: several native code systems; that version of Gforth is slower on a 486
14592: than the direct threaded version used here. You can find a newer version
14593: of these measurements at
1.47 crook 14594: @uref{http://www.complang.tuwien.ac.at/forth/performance.html}. You can
1.1 anton 14595: find numbers for Gforth on various machines in @file{Benchres}.
14596:
1.26 crook 14597: @c ******************************************************************
1.13 pazsan 14598: @node Binding to System Library, Cross Compiler, Engine, Top
1.14 pazsan 14599: @chapter Binding to System Library
1.13 pazsan 14600:
14601: @node Cross Compiler, Bugs, Binding to System Library, Top
1.14 pazsan 14602: @chapter Cross Compiler
1.47 crook 14603: @cindex @file{cross.fs}
14604: @cindex cross-compiler
14605: @cindex metacompiler
14606: @cindex target compiler
1.13 pazsan 14607:
1.46 pazsan 14608: The cross compiler is used to bootstrap a Forth kernel. Since Gforth is
14609: mostly written in Forth, including crucial parts like the outer
14610: interpreter and compiler, it needs compiled Forth code to get
14611: started. The cross compiler allows to create new images for other
14612: architectures, even running under another Forth system.
1.13 pazsan 14613:
14614: @menu
1.67 anton 14615: * Using the Cross Compiler::
14616: * How the Cross Compiler Works::
1.13 pazsan 14617: @end menu
14618:
1.21 crook 14619: @node Using the Cross Compiler, How the Cross Compiler Works, Cross Compiler, Cross Compiler
1.14 pazsan 14620: @section Using the Cross Compiler
1.46 pazsan 14621:
14622: The cross compiler uses a language that resembles Forth, but isn't. The
14623: main difference is that you can execute Forth code after definition,
14624: while you usually can't execute the code compiled by cross, because the
14625: code you are compiling is typically for a different computer than the
14626: one you are compiling on.
14627:
1.81 anton 14628: @c anton: This chapter is somewhat different from waht I would expect: I
14629: @c would expect an explanation of the cross language and how to create an
14630: @c application image with it. The section explains some aspects of
14631: @c creating a Gforth kernel.
14632:
1.46 pazsan 14633: The Makefile is already set up to allow you to create kernels for new
14634: architectures with a simple make command. The generic kernels using the
14635: GCC compiled virtual machine are created in the normal build process
14636: with @code{make}. To create a embedded Gforth executable for e.g. the
14637: 8086 processor (running on a DOS machine), type
14638:
14639: @example
14640: make kernl-8086.fi
14641: @end example
14642:
14643: This will use the machine description from the @file{arch/8086}
14644: directory to create a new kernel. A machine file may look like that:
14645:
14646: @example
14647: \ Parameter for target systems 06oct92py
14648:
14649: 4 Constant cell \ cell size in bytes
14650: 2 Constant cell<< \ cell shift to bytes
14651: 5 Constant cell>bit \ cell shift to bits
14652: 8 Constant bits/char \ bits per character
14653: 8 Constant bits/byte \ bits per byte [default: 8]
14654: 8 Constant float \ bytes per float
14655: 8 Constant /maxalign \ maximum alignment in bytes
14656: false Constant bigendian \ byte order
14657: ( true=big, false=little )
14658:
14659: include machpc.fs \ feature list
14660: @end example
14661:
14662: This part is obligatory for the cross compiler itself, the feature list
14663: is used by the kernel to conditionally compile some features in and out,
14664: depending on whether the target supports these features.
14665:
14666: There are some optional features, if you define your own primitives,
14667: have an assembler, or need special, nonstandard preparation to make the
1.81 anton 14668: boot process work. @code{asm-include} includes an assembler,
1.46 pazsan 14669: @code{prims-include} includes primitives, and @code{>boot} prepares for
14670: booting.
14671:
14672: @example
14673: : asm-include ." Include assembler" cr
14674: s" arch/8086/asm.fs" included ;
14675:
14676: : prims-include ." Include primitives" cr
14677: s" arch/8086/prim.fs" included ;
14678:
14679: : >boot ." Prepare booting" cr
14680: s" ' boot >body into-forth 1+ !" evaluate ;
14681: @end example
14682:
14683: These words are used as sort of macro during the cross compilation in
1.81 anton 14684: the file @file{kernel/main.fs}. Instead of using these macros, it would
1.46 pazsan 14685: be possible --- but more complicated --- to write a new kernel project
14686: file, too.
14687:
14688: @file{kernel/main.fs} expects the machine description file name on the
14689: stack; the cross compiler itself (@file{cross.fs}) assumes that either
14690: @code{mach-file} leaves a counted string on the stack, or
14691: @code{machine-file} leaves an address, count pair of the filename on the
14692: stack.
14693:
14694: The feature list is typically controlled using @code{SetValue}, generic
14695: files that are used by several projects can use @code{DefaultValue}
14696: instead. Both functions work like @code{Value}, when the value isn't
14697: defined, but @code{SetValue} works like @code{to} if the value is
14698: defined, and @code{DefaultValue} doesn't set anything, if the value is
14699: defined.
14700:
14701: @example
14702: \ generic mach file for pc gforth 03sep97jaw
14703:
14704: true DefaultValue NIL \ relocating
14705:
14706: >ENVIRON
14707:
14708: true DefaultValue file \ controls the presence of the
14709: \ file access wordset
14710: true DefaultValue OS \ flag to indicate a operating system
14711:
14712: true DefaultValue prims \ true: primitives are c-code
14713:
14714: true DefaultValue floating \ floating point wordset is present
14715:
14716: true DefaultValue glocals \ gforth locals are present
14717: \ will be loaded
14718: true DefaultValue dcomps \ double number comparisons
14719:
14720: true DefaultValue hash \ hashing primitives are loaded/present
14721:
14722: true DefaultValue xconds \ used together with glocals,
14723: \ special conditionals supporting gforths'
14724: \ local variables
14725: true DefaultValue header \ save a header information
14726:
14727: true DefaultValue backtrace \ enables backtrace code
14728:
14729: false DefaultValue ec
14730: false DefaultValue crlf
14731:
14732: cell 2 = [IF] &32 [ELSE] &256 [THEN] KB DefaultValue kernel-size
14733:
14734: &16 KB DefaultValue stack-size
14735: &15 KB &512 + DefaultValue fstack-size
14736: &15 KB DefaultValue rstack-size
14737: &14 KB &512 + DefaultValue lstack-size
14738: @end example
1.13 pazsan 14739:
1.48 anton 14740: @node How the Cross Compiler Works, , Using the Cross Compiler, Cross Compiler
1.14 pazsan 14741: @section How the Cross Compiler Works
1.13 pazsan 14742:
14743: @node Bugs, Origin, Cross Compiler, Top
1.21 crook 14744: @appendix Bugs
1.1 anton 14745: @cindex bug reporting
14746:
1.21 crook 14747: Known bugs are described in the file @file{BUGS} in the Gforth distribution.
1.1 anton 14748:
14749: If you find a bug, please send a bug report to
1.33 anton 14750: @email{bug-gforth@@gnu.org}. A bug report should include this
1.21 crook 14751: information:
14752:
14753: @itemize @bullet
14754: @item
1.81 anton 14755: A program (or a sequence of keyboard commands) that reproduces the bug.
14756: @item
14757: A description of what you think constitutes the buggy behaviour.
14758: @item
1.21 crook 14759: The Gforth version used (it is announced at the start of an
14760: interactive Gforth session).
14761: @item
14762: The machine and operating system (on Unix
14763: systems @code{uname -a} will report this information).
14764: @item
1.81 anton 14765: The installation options (you can find the configure options at the
14766: start of @file{config.status}) and configuration (@code{configure}
14767: output or @file{config.cache}).
1.21 crook 14768: @item
14769: A complete list of changes (if any) you (or your installer) have made to the
14770: Gforth sources.
14771: @end itemize
1.1 anton 14772:
14773: For a thorough guide on reporting bugs read @ref{Bug Reporting, , How
14774: to Report Bugs, gcc.info, GNU C Manual}.
14775:
14776:
1.21 crook 14777: @node Origin, Forth-related information, Bugs, Top
14778: @appendix Authors and Ancestors of Gforth
1.1 anton 14779:
14780: @section Authors and Contributors
14781: @cindex authors of Gforth
14782: @cindex contributors to Gforth
14783:
14784: The Gforth project was started in mid-1992 by Bernd Paysan and Anton
1.81 anton 14785: Ertl. The third major author was Jens Wilke. Neal Crook contributed a
14786: lot to the manual. Assemblers and disassemblers were contributed by
14787: Andrew McKewan, Christian Pirker, and Bernd Thallner. Lennart Benschop
14788: (who was one of Gforth's first users, in mid-1993) and Stuart Ramsden
14789: inspired us with their continuous feedback. Lennart Benshop contributed
1.1 anton 14790: @file{glosgen.fs}, while Stuart Ramsden has been working on automatic
14791: support for calling C libraries. Helpful comments also came from Paul
14792: Kleinrubatscher, Christian Pirker, Dirk Zoller, Marcel Hendrix, John
1.58 anton 14793: Wavrik, Barrie Stott, Marc de Groot, Jorge Acerada, Bruce Hoyt, and
14794: Robert Epprecht. Since the release of Gforth-0.2.1 there were also
14795: helpful comments from many others; thank you all, sorry for not listing
14796: you here (but digging through my mailbox to extract your names is on my
1.81 anton 14797: to-do list).
1.1 anton 14798:
14799: Gforth also owes a lot to the authors of the tools we used (GCC, CVS,
14800: and autoconf, among others), and to the creators of the Internet: Gforth
1.21 crook 14801: was developed across the Internet, and its authors did not meet
1.20 pazsan 14802: physically for the first 4 years of development.
1.1 anton 14803:
14804: @section Pedigree
1.26 crook 14805: @cindex pedigree of Gforth
1.1 anton 14806:
1.81 anton 14807: Gforth descends from bigFORTH (1993) and fig-Forth. Of course, a
14808: significant part of the design of Gforth was prescribed by ANS Forth.
1.1 anton 14809:
1.20 pazsan 14810: Bernd Paysan wrote bigFORTH, a descendent from TurboForth, an unreleased
1.1 anton 14811: 32 bit native code version of VolksForth for the Atari ST, written
14812: mostly by Dietrich Weineck.
14813:
1.81 anton 14814: VolksForth was written by Klaus Schleisiek, Bernd Pennemann, Georg
14815: Rehfeld and Dietrich Weineck for the C64 (called UltraForth there) in
14816: the mid-80s and ported to the Atari ST in 1986. It descends from F83.
1.1 anton 14817:
14818: Henry Laxen and Mike Perry wrote F83 as a model implementation of the
14819: Forth-83 standard. !! Pedigree? When?
14820:
14821: A team led by Bill Ragsdale implemented fig-Forth on many processors in
14822: 1979. Robert Selzer and Bill Ragsdale developed the original
14823: implementation of fig-Forth for the 6502 based on microForth.
14824:
14825: The principal architect of microForth was Dean Sanderson. microForth was
14826: FORTH, Inc.'s first off-the-shelf product. It was developed in 1976 for
14827: the 1802, and subsequently implemented on the 8080, the 6800 and the
14828: Z80.
14829:
14830: All earlier Forth systems were custom-made, usually by Charles Moore,
14831: who discovered (as he puts it) Forth during the late 60s. The first full
14832: Forth existed in 1971.
14833:
1.81 anton 14834: A part of the information in this section comes from
14835: @cite{@uref{http://www.forth.com/Content/History/History1.htm,The
14836: Evolution of Forth}} by Elizabeth D. Rather, Donald R. Colburn and
14837: Charles H. Moore, presented at the HOPL-II conference and preprinted in
14838: SIGPLAN Notices 28(3), 1993. You can find more historical and
14839: genealogical information about Forth there.
1.1 anton 14840:
1.81 anton 14841: @c ------------------------------------------------------------------
1.21 crook 14842: @node Forth-related information, Word Index, Origin, Top
14843: @appendix Other Forth-related information
14844: @cindex Forth-related information
14845:
1.81 anton 14846: @c anton: I threw most of this stuff out, because it can be found through
14847: @c the FAQ and the FAQ is more likely to be up-to-date.
1.21 crook 14848:
14849: @cindex comp.lang.forth
14850: @cindex frequently asked questions
1.81 anton 14851: There is an active news group (comp.lang.forth) discussing Forth
14852: (including Gforth) and Forth-related issues. Its
14853: @uref{http://www.complang.tuwien.ac.at/forth/faq/faq-general-2.html,FAQs}
14854: (frequently asked questions and their answers) contains a lot of
14855: information on Forth. You should read it before posting to
14856: comp.lang.forth.
1.21 crook 14857:
1.81 anton 14858: The ANS Forth standard is most usable in its
14859: @uref{http://www.taygeta.com/forth/dpans.html, HTML form}.
1.21 crook 14860:
1.81 anton 14861: @c ------------------------------------------------------------------
14862: @node Word Index, Concept Index, Forth-related information, Top
1.1 anton 14863: @unnumbered Word Index
14864:
1.26 crook 14865: This index is a list of Forth words that have ``glossary'' entries
14866: within this manual. Each word is listed with its stack effect and
14867: wordset.
1.1 anton 14868:
14869: @printindex fn
14870:
1.81 anton 14871: @c anton: the name index seems superfluous given the word and concept indices.
14872:
14873: @c @node Name Index, Concept Index, Word Index, Top
14874: @c @unnumbered Name Index
1.41 anton 14875:
1.81 anton 14876: @c This index is a list of Forth words that have ``glossary'' entries
14877: @c within this manual.
1.41 anton 14878:
1.81 anton 14879: @c @printindex ky
1.41 anton 14880:
1.81 anton 14881: @node Concept Index, , Word Index, Top
1.1 anton 14882: @unnumbered Concept and Word Index
14883:
1.26 crook 14884: Not all entries listed in this index are present verbatim in the
14885: text. This index also duplicates, in abbreviated form, all of the words
14886: listed in the Word Index (only the names are listed for the words here).
1.1 anton 14887:
14888: @printindex cp
14889:
14890: @contents
14891: @bye
1.81 anton 14892:
14893:
1.1 anton 14894:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>