Annotation of gforth/doc/gforth.ds, revision 1.23
1.1 anton 1: \input texinfo @c -*-texinfo-*-
2: @comment The source is gforth.ds, from which gforth.texi is generated
1.21 crook 3: @comment TODO: nac29jan99 - a list of things to add in the next edit:
4: @comment 1. x-ref all ambiguous or implementation-defined features
5: @comment 2. refer to all environment strings
6: @comment 3. gloss and info in blocks section
7: @comment 4. move file and blocks to common sub-section?
8: @comment 5. command-line editing, command completion etc.
9: @comment 6. document more of the words in require.fs
10: @comment 7. document the include files process (Describe the list,
11: @comment including its scope)
12: @comment 8. Describe the use of Auser Avariable etc.
13: @comment 9. cross-compiler
14: @comment 10.words in miscellaneous section need a home.
15: @comment 11.Move structures and oof into their own chapters.
16: @comment 12.search for TODO for other minor works
1.1 anton 17: @comment %**start of header (This is for running Texinfo on a region.)
18: @setfilename gforth.info
19: @settitle Gforth Manual
20: @dircategory GNU programming tools
21: @direntry
22: * Gforth: (gforth). A fast interpreter for the Forth language.
23: @end direntry
24: @comment @setchapternewpage odd
1.12 anton 25: @macro progstyle {}
26: Programming style note:
1.3 anton 27: @end macro
1.1 anton 28: @comment %**end of header (This is for running Texinfo on a region.)
29:
1.10 anton 30: @include version.texi
31:
1.1 anton 32: @ifinfo
1.11 anton 33: This file documents Gforth @value{VERSION}
1.1 anton 34:
1.13 pazsan 35: Copyright @copyright{} 1995-1998 Free Software Foundation, Inc.
1.1 anton 36:
37: Permission is granted to make and distribute verbatim copies of
38: this manual provided the copyright notice and this permission notice
39: are preserved on all copies.
40:
41: @ignore
42: Permission is granted to process this file through TeX and print the
43: results, provided the printed document carries a copying permission
44: notice identical to this one except for the removal of this paragraph
45: (this paragraph not being relevant to the printed manual).
46:
47: @end ignore
48: Permission is granted to copy and distribute modified versions of this
49: manual under the conditions for verbatim copying, provided also that the
50: sections entitled "Distribution" and "General Public License" are
51: included exactly as in the original, and provided that the entire
52: resulting derived work is distributed under the terms of a permission
53: notice identical to this one.
54:
55: Permission is granted to copy and distribute translations of this manual
56: into another language, under the above conditions for modified versions,
57: except that the sections entitled "Distribution" and "General Public
58: License" may be included in a translation approved by the author instead
59: of in the original English.
60: @end ifinfo
61:
62: @finalout
63: @titlepage
64: @sp 10
65: @center @titlefont{Gforth Manual}
66: @sp 2
1.11 anton 67: @center for version @value{VERSION}
1.1 anton 68: @sp 2
69: @center Anton Ertl
1.6 pazsan 70: @center Bernd Paysan
1.5 anton 71: @center Jens Wilke
1.23 ! crook 72: @center Neal Crook
1.1 anton 73: @sp 3
1.23 ! crook 74: @center This manual is permanently under construction and was last updated on 16-Feb-1999
1.1 anton 75:
76: @comment The following two commands start the copyright page.
77: @page
78: @vskip 0pt plus 1filll
1.13 pazsan 79: Copyright @copyright{} 1995--1998 Free Software Foundation, Inc.
1.1 anton 80:
81: @comment !! Published by ... or You can get a copy of this manual ...
82:
83: Permission is granted to make and distribute verbatim copies of
84: this manual provided the copyright notice and this permission notice
85: are preserved on all copies.
86:
87: Permission is granted to copy and distribute modified versions of this
88: manual under the conditions for verbatim copying, provided also that the
89: sections entitled "Distribution" and "General Public License" are
90: included exactly as in the original, and provided that the entire
91: resulting derived work is distributed under the terms of a permission
92: notice identical to this one.
93:
94: Permission is granted to copy and distribute translations of this manual
95: into another language, under the above conditions for modified versions,
96: except that the sections entitled "Distribution" and "General Public
97: License" may be included in a translation approved by the author instead
98: of in the original English.
99: @end titlepage
100:
101:
102: @node Top, License, (dir), (dir)
103: @ifinfo
104: Gforth is a free implementation of ANS Forth available on many
1.11 anton 105: personal machines. This manual corresponds to version @value{VERSION}.
1.1 anton 106: @end ifinfo
107:
108: @menu
1.21 crook 109: * License:: The GPL
110: * Introduction:: An introduction to ANS Forth
1.1 anton 111: * Goals:: About the Gforth Project
1.21 crook 112: * Invoking Gforth:: Starting (and exiting) Gforth
1.1 anton 113: * Words:: Forth words available in Gforth
114: * Tools:: Programming tools
115: * ANS conformance:: Implementation-defined options etc.
116: * Model:: The abstract machine of Gforth
117: * Integrating Gforth:: Forth as scripting language for applications
118: * Emacs and Gforth:: The Gforth Mode
119: * Image Files:: @code{.fi} files contain compiled code
120: * Engine:: The inner interpreter and the primitives
1.13 pazsan 121: * Cross Compiler:: The Cross Compiler
1.1 anton 122: * Bugs:: How to report them
123: * Origin:: Authors and ancestors of Gforth
1.21 crook 124: * Forth-related information:: Books and places to look on the WWW
1.1 anton 125: * Word Index:: An item for each Forth word
126: * Concept Index:: A menu covering many topics
1.12 anton 127:
128: --- The Detailed Node Listing ---
129:
1.21 crook 130: Goals
131:
132: * Gforth Extensions Sinful?::
133:
1.12 anton 134: Forth Words
135:
136: * Notation::
1.21 crook 137: * Comments::
138: * Boolean Flags::
1.12 anton 139: * Arithmetic::
140: * Stack Manipulation::
141: * Memory::
142: * Control Structures::
143: * Locals::
144: * Defining Words::
1.21 crook 145: * The Text Interpreter::
1.12 anton 146: * Structures::
147: * Object-oriented Forth::
148: * Tokens for Words::
1.21 crook 149: * Word Lists::
150: * Environmental Queries::
1.12 anton 151: * Files::
152: * Including Files::
153: * Blocks::
154: * Other I/O::
155: * Programming Tools::
156: * Assembler and Code Words::
157: * Threading Words::
1.21 crook 158: * Passing Commands to the OS::
159: * Miscellaneous Words::
1.12 anton 160:
161: Arithmetic
162:
163: * Single precision::
164: * Bitwise operations::
1.21 crook 165: * Double precision:: Double-cell integer arithmetic
166: * Numeric comparison::
1.12 anton 167: * Mixed precision:: operations with single and double-cell integers
168: * Floating Point::
169:
170: Stack Manipulation
171:
172: * Data stack::
173: * Floating point stack::
174: * Return stack::
175: * Locals stack::
176: * Stack pointer manipulation::
177:
178: Memory
179:
180: * Memory Access::
181: * Address arithmetic::
182: * Memory Blocks::
183:
184: Control Structures
185:
186: * Selection::
187: * Simple Loops::
188: * Counted Loops::
189: * Arbitrary control structures::
190: * Calls and returns::
191: * Exception Handling::
192:
193: Locals
194:
195: * Gforth locals::
196: * ANS Forth locals::
197:
198: Gforth locals
199:
200: * Where are locals visible by name?::
201: * How long do locals live?::
202: * Programming Style::
203: * Implementation::
204:
205: Defining Words
206:
207: * Simple Defining Words::
208: * Colon Definitions::
209: * User-defined Defining Words::
210: * Supplying names::
211: * Interpretation and Compilation Semantics::
212:
1.21 crook 213: The Text Interpreter
214:
215: * Number Conversion::
216: * Interpret/Compile states::
217: * Literals::
218: * Interpreter Directives::
219:
1.12 anton 220: Structures
221:
222: * Why explicit structure support?::
223: * Structure Usage::
224: * Structure Naming Convention::
225: * Structure Implementation::
226: * Structure Glossary::
227:
228: Object-oriented Forth
229:
1.23 ! crook 230: * Why object-oriented programming?::
! 231: * Object-Oriented Terminology::
1.12 anton 232: * Objects::
233: * OOF::
234: * Mini-OOF::
1.23 ! crook 235: * Comparison with other object models::
1.12 anton 236:
237: Objects
238:
239: * Properties of the Objects model::
240: * Basic Objects Usage::
1.23 ! crook 241: * The Objects base class::
1.12 anton 242: * Creating objects::
243: * Object-Oriented Programming Style::
244: * Class Binding::
245: * Method conveniences::
246: * Classes and Scoping::
247: * Object Interfaces::
248: * Objects Implementation::
249: * Objects Glossary::
250:
251: OOF
252:
253: * Properties of the OOF model::
254: * Basic OOF Usage::
1.23 ! crook 255: * The OOF base class::
1.12 anton 256: * Class Declaration::
257: * Class Implementation::
258:
1.23 ! crook 259: Mini-OOF
! 260:
! 261: * Basic Mini-OOF Usage::
! 262: * Mini-OOF Example::
! 263: * Mini-OOF Implementation::
! 264:
1.21 crook 265: Word Lists
266:
267: * Why use word lists?::
268: * Word list examples::
269:
1.12 anton 270: Including Files
271:
272: * Words for Including::
273: * Search Path::
1.21 crook 274: * Forth Search Paths::
1.12 anton 275: * General Search Paths::
276:
1.21 crook 277: Other I/O
278:
279: * Simple numeric output::
280: * Formatted numeric output::
281: * String Formats::
282: * Displaying characters and strings::
283: * Input::
284:
1.12 anton 285: Programming Tools
286:
287: * Debugging:: Simple and quick.
288: * Assertions:: Making your programs self-checking.
289: * Singlestep Debugger:: Executing your program word by word.
290:
291: Tools
292:
293: * ANS Report:: Report the words used, sorted by wordset.
294:
295: ANS conformance
296:
297: * The Core Words::
298: * The optional Block word set::
299: * The optional Double Number word set::
300: * The optional Exception word set::
301: * The optional Facility word set::
302: * The optional File-Access word set::
303: * The optional Floating-Point word set::
304: * The optional Locals word set::
305: * The optional Memory-Allocation word set::
306: * The optional Programming-Tools word set::
307: * The optional Search-Order word set::
308:
309: The Core Words
310:
311: * core-idef:: Implementation Defined Options
312: * core-ambcond:: Ambiguous Conditions
313: * core-other:: Other System Documentation
314:
315: The optional Block word set
316:
317: * block-idef:: Implementation Defined Options
318: * block-ambcond:: Ambiguous Conditions
319: * block-other:: Other System Documentation
320:
321: The optional Double Number word set
322:
323: * double-ambcond:: Ambiguous Conditions
324:
325: The optional Exception word set
326:
327: * exception-idef:: Implementation Defined Options
328:
329: The optional Facility word set
330:
331: * facility-idef:: Implementation Defined Options
332: * facility-ambcond:: Ambiguous Conditions
333:
334: The optional File-Access word set
335:
336: * file-idef:: Implementation Defined Options
337: * file-ambcond:: Ambiguous Conditions
338:
339: The optional Floating-Point word set
340:
341: * floating-idef:: Implementation Defined Options
342: * floating-ambcond:: Ambiguous Conditions
343:
344: The optional Locals word set
345:
346: * locals-idef:: Implementation Defined Options
347: * locals-ambcond:: Ambiguous Conditions
348:
349: The optional Memory-Allocation word set
350:
351: * memory-idef:: Implementation Defined Options
352:
353: The optional Programming-Tools word set
354:
355: * programming-idef:: Implementation Defined Options
356: * programming-ambcond:: Ambiguous Conditions
357:
358: The optional Search-Order word set
359:
360: * search-idef:: Implementation Defined Options
361: * search-ambcond:: Ambiguous Conditions
362:
363: Image Files
364:
365: * Image File Background:: Why have image files?
366: * Non-Relocatable Image Files:: don't always work.
367: * Data-Relocatable Image Files:: are better.
368: * Fully Relocatable Image Files:: better yet.
369: * Stack and Dictionary Sizes:: Setting the default sizes for an image.
370: * Running Image Files:: @code{gforth -i @var{file}} or @var{file}.
371: * Modifying the Startup Sequence:: and turnkey applications.
372:
373: Fully Relocatable Image Files
374:
1.21 crook 375: * gforthmi:: The normal way
1.12 anton 376: * cross.fs:: The hard way
377:
378: Engine
379:
380: * Portability::
381: * Threading::
382: * Primitives::
383: * Performance::
384:
385: Threading
386:
387: * Scheduling::
388: * Direct or Indirect Threaded?::
389: * DOES>::
390:
391: Primitives
392:
393: * Automatic Generation::
394: * TOS Optimization::
395: * Produced code::
1.13 pazsan 396:
397: System Libraries
398:
399: * Binding to System Library::
400:
401: Cross Compiler
402:
403: * Using the Cross Compiler::
404: * How the Cross Compiler Works::
405:
1.21 crook 406: Forth-related information
407:
408: * Internet resources::
409: * Books::
410: * The Forth Interest Group::
411: * Conferences::
412:
413:
414:
1.1 anton 415: @end menu
416:
1.21 crook 417: @node License, Introduction, Top, Top
1.1 anton 418: @unnumbered GNU GENERAL PUBLIC LICENSE
419: @center Version 2, June 1991
420:
421: @display
422: Copyright @copyright{} 1989, 1991 Free Software Foundation, Inc.
423: 675 Mass Ave, Cambridge, MA 02139, USA
424:
425: Everyone is permitted to copy and distribute verbatim copies
426: of this license document, but changing it is not allowed.
427: @end display
428:
429: @unnumberedsec Preamble
430:
431: The licenses for most software are designed to take away your
432: freedom to share and change it. By contrast, the GNU General Public
433: License is intended to guarantee your freedom to share and change free
434: software---to make sure the software is free for all its users. This
435: General Public License applies to most of the Free Software
436: Foundation's software and to any other program whose authors commit to
437: using it. (Some other Free Software Foundation software is covered by
438: the GNU Library General Public License instead.) You can apply it to
439: your programs, too.
440:
441: When we speak of free software, we are referring to freedom, not
442: price. Our General Public Licenses are designed to make sure that you
443: have the freedom to distribute copies of free software (and charge for
444: this service if you wish), that you receive source code or can get it
445: if you want it, that you can change the software or use pieces of it
446: in new free programs; and that you know you can do these things.
447:
448: To protect your rights, we need to make restrictions that forbid
449: anyone to deny you these rights or to ask you to surrender the rights.
450: These restrictions translate to certain responsibilities for you if you
451: distribute copies of the software, or if you modify it.
452:
453: For example, if you distribute copies of such a program, whether
454: gratis or for a fee, you must give the recipients all the rights that
455: you have. You must make sure that they, too, receive or can get the
456: source code. And you must show them these terms so they know their
457: rights.
458:
459: We protect your rights with two steps: (1) copyright the software, and
460: (2) offer you this license which gives you legal permission to copy,
461: distribute and/or modify the software.
462:
463: Also, for each author's protection and ours, we want to make certain
464: that everyone understands that there is no warranty for this free
465: software. If the software is modified by someone else and passed on, we
466: want its recipients to know that what they have is not the original, so
467: that any problems introduced by others will not reflect on the original
468: authors' reputations.
469:
470: Finally, any free program is threatened constantly by software
471: patents. We wish to avoid the danger that redistributors of a free
472: program will individually obtain patent licenses, in effect making the
473: program proprietary. To prevent this, we have made it clear that any
474: patent must be licensed for everyone's free use or not licensed at all.
475:
476: The precise terms and conditions for copying, distribution and
477: modification follow.
478:
479: @iftex
480: @unnumberedsec TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
481: @end iftex
482: @ifinfo
483: @center TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
484: @end ifinfo
485:
486: @enumerate 0
487: @item
488: This License applies to any program or other work which contains
489: a notice placed by the copyright holder saying it may be distributed
490: under the terms of this General Public License. The ``Program'', below,
491: refers to any such program or work, and a ``work based on the Program''
492: means either the Program or any derivative work under copyright law:
493: that is to say, a work containing the Program or a portion of it,
494: either verbatim or with modifications and/or translated into another
495: language. (Hereinafter, translation is included without limitation in
496: the term ``modification''.) Each licensee is addressed as ``you''.
497:
498: Activities other than copying, distribution and modification are not
499: covered by this License; they are outside its scope. The act of
500: running the Program is not restricted, and the output from the Program
501: is covered only if its contents constitute a work based on the
502: Program (independent of having been made by running the Program).
503: Whether that is true depends on what the Program does.
504:
505: @item
506: You may copy and distribute verbatim copies of the Program's
507: source code as you receive it, in any medium, provided that you
508: conspicuously and appropriately publish on each copy an appropriate
509: copyright notice and disclaimer of warranty; keep intact all the
510: notices that refer to this License and to the absence of any warranty;
511: and give any other recipients of the Program a copy of this License
512: along with the Program.
513:
514: You may charge a fee for the physical act of transferring a copy, and
515: you may at your option offer warranty protection in exchange for a fee.
516:
517: @item
518: You may modify your copy or copies of the Program or any portion
519: of it, thus forming a work based on the Program, and copy and
520: distribute such modifications or work under the terms of Section 1
521: above, provided that you also meet all of these conditions:
522:
523: @enumerate a
524: @item
525: You must cause the modified files to carry prominent notices
526: stating that you changed the files and the date of any change.
527:
528: @item
529: You must cause any work that you distribute or publish, that in
530: whole or in part contains or is derived from the Program or any
531: part thereof, to be licensed as a whole at no charge to all third
532: parties under the terms of this License.
533:
534: @item
535: If the modified program normally reads commands interactively
536: when run, you must cause it, when started running for such
537: interactive use in the most ordinary way, to print or display an
538: announcement including an appropriate copyright notice and a
539: notice that there is no warranty (or else, saying that you provide
540: a warranty) and that users may redistribute the program under
541: these conditions, and telling the user how to view a copy of this
542: License. (Exception: if the Program itself is interactive but
543: does not normally print such an announcement, your work based on
544: the Program is not required to print an announcement.)
545: @end enumerate
546:
547: These requirements apply to the modified work as a whole. If
548: identifiable sections of that work are not derived from the Program,
549: and can be reasonably considered independent and separate works in
550: themselves, then this License, and its terms, do not apply to those
551: sections when you distribute them as separate works. But when you
552: distribute the same sections as part of a whole which is a work based
553: on the Program, the distribution of the whole must be on the terms of
554: this License, whose permissions for other licensees extend to the
555: entire whole, and thus to each and every part regardless of who wrote it.
556:
557: Thus, it is not the intent of this section to claim rights or contest
558: your rights to work written entirely by you; rather, the intent is to
559: exercise the right to control the distribution of derivative or
560: collective works based on the Program.
561:
562: In addition, mere aggregation of another work not based on the Program
563: with the Program (or with a work based on the Program) on a volume of
564: a storage or distribution medium does not bring the other work under
565: the scope of this License.
566:
567: @item
568: You may copy and distribute the Program (or a work based on it,
569: under Section 2) in object code or executable form under the terms of
570: Sections 1 and 2 above provided that you also do one of the following:
571:
572: @enumerate a
573: @item
574: Accompany it with the complete corresponding machine-readable
575: source code, which must be distributed under the terms of Sections
576: 1 and 2 above on a medium customarily used for software interchange; or,
577:
578: @item
579: Accompany it with a written offer, valid for at least three
580: years, to give any third party, for a charge no more than your
581: cost of physically performing source distribution, a complete
582: machine-readable copy of the corresponding source code, to be
583: distributed under the terms of Sections 1 and 2 above on a medium
584: customarily used for software interchange; or,
585:
586: @item
587: Accompany it with the information you received as to the offer
588: to distribute corresponding source code. (This alternative is
589: allowed only for noncommercial distribution and only if you
590: received the program in object code or executable form with such
591: an offer, in accord with Subsection b above.)
592: @end enumerate
593:
594: The source code for a work means the preferred form of the work for
595: making modifications to it. For an executable work, complete source
596: code means all the source code for all modules it contains, plus any
597: associated interface definition files, plus the scripts used to
598: control compilation and installation of the executable. However, as a
599: special exception, the source code distributed need not include
600: anything that is normally distributed (in either source or binary
601: form) with the major components (compiler, kernel, and so on) of the
602: operating system on which the executable runs, unless that component
603: itself accompanies the executable.
604:
605: If distribution of executable or object code is made by offering
606: access to copy from a designated place, then offering equivalent
607: access to copy the source code from the same place counts as
608: distribution of the source code, even though third parties are not
609: compelled to copy the source along with the object code.
610:
611: @item
612: You may not copy, modify, sublicense, or distribute the Program
613: except as expressly provided under this License. Any attempt
614: otherwise to copy, modify, sublicense or distribute the Program is
615: void, and will automatically terminate your rights under this License.
616: However, parties who have received copies, or rights, from you under
617: this License will not have their licenses terminated so long as such
618: parties remain in full compliance.
619:
620: @item
621: You are not required to accept this License, since you have not
622: signed it. However, nothing else grants you permission to modify or
623: distribute the Program or its derivative works. These actions are
624: prohibited by law if you do not accept this License. Therefore, by
625: modifying or distributing the Program (or any work based on the
626: Program), you indicate your acceptance of this License to do so, and
627: all its terms and conditions for copying, distributing or modifying
628: the Program or works based on it.
629:
630: @item
631: Each time you redistribute the Program (or any work based on the
632: Program), the recipient automatically receives a license from the
633: original licensor to copy, distribute or modify the Program subject to
634: these terms and conditions. You may not impose any further
635: restrictions on the recipients' exercise of the rights granted herein.
636: You are not responsible for enforcing compliance by third parties to
637: this License.
638:
639: @item
640: If, as a consequence of a court judgment or allegation of patent
641: infringement or for any other reason (not limited to patent issues),
642: conditions are imposed on you (whether by court order, agreement or
643: otherwise) that contradict the conditions of this License, they do not
644: excuse you from the conditions of this License. If you cannot
645: distribute so as to satisfy simultaneously your obligations under this
646: License and any other pertinent obligations, then as a consequence you
647: may not distribute the Program at all. For example, if a patent
648: license would not permit royalty-free redistribution of the Program by
649: all those who receive copies directly or indirectly through you, then
650: the only way you could satisfy both it and this License would be to
651: refrain entirely from distribution of the Program.
652:
653: If any portion of this section is held invalid or unenforceable under
654: any particular circumstance, the balance of the section is intended to
655: apply and the section as a whole is intended to apply in other
656: circumstances.
657:
658: It is not the purpose of this section to induce you to infringe any
659: patents or other property right claims or to contest validity of any
660: such claims; this section has the sole purpose of protecting the
661: integrity of the free software distribution system, which is
662: implemented by public license practices. Many people have made
663: generous contributions to the wide range of software distributed
664: through that system in reliance on consistent application of that
665: system; it is up to the author/donor to decide if he or she is willing
666: to distribute software through any other system and a licensee cannot
667: impose that choice.
668:
669: This section is intended to make thoroughly clear what is believed to
670: be a consequence of the rest of this License.
671:
672: @item
673: If the distribution and/or use of the Program is restricted in
674: certain countries either by patents or by copyrighted interfaces, the
675: original copyright holder who places the Program under this License
676: may add an explicit geographical distribution limitation excluding
677: those countries, so that distribution is permitted only in or among
678: countries not thus excluded. In such case, this License incorporates
679: the limitation as if written in the body of this License.
680:
681: @item
682: The Free Software Foundation may publish revised and/or new versions
683: of the General Public License from time to time. Such new versions will
684: be similar in spirit to the present version, but may differ in detail to
685: address new problems or concerns.
686:
687: Each version is given a distinguishing version number. If the Program
688: specifies a version number of this License which applies to it and ``any
689: later version'', you have the option of following the terms and conditions
690: either of that version or of any later version published by the Free
691: Software Foundation. If the Program does not specify a version number of
692: this License, you may choose any version ever published by the Free Software
693: Foundation.
694:
695: @item
696: If you wish to incorporate parts of the Program into other free
697: programs whose distribution conditions are different, write to the author
698: to ask for permission. For software which is copyrighted by the Free
699: Software Foundation, write to the Free Software Foundation; we sometimes
700: make exceptions for this. Our decision will be guided by the two goals
701: of preserving the free status of all derivatives of our free software and
702: of promoting the sharing and reuse of software generally.
703:
704: @iftex
705: @heading NO WARRANTY
706: @end iftex
707: @ifinfo
708: @center NO WARRANTY
709: @end ifinfo
710:
711: @item
712: BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
713: FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
714: OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
715: PROVIDE THE PROGRAM ``AS IS'' WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
716: OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
717: MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
718: TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
719: PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
720: REPAIR OR CORRECTION.
721:
722: @item
723: IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
724: WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
725: REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
726: INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
727: OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
728: TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
729: YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
730: PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
731: POSSIBILITY OF SUCH DAMAGES.
732: @end enumerate
733:
734: @iftex
735: @heading END OF TERMS AND CONDITIONS
736: @end iftex
737: @ifinfo
738: @center END OF TERMS AND CONDITIONS
739: @end ifinfo
740:
741: @page
742: @unnumberedsec How to Apply These Terms to Your New Programs
743:
744: If you develop a new program, and you want it to be of the greatest
745: possible use to the public, the best way to achieve this is to make it
746: free software which everyone can redistribute and change under these terms.
747:
748: To do so, attach the following notices to the program. It is safest
749: to attach them to the start of each source file to most effectively
750: convey the exclusion of warranty; and each file should have at least
751: the ``copyright'' line and a pointer to where the full notice is found.
752:
753: @smallexample
754: @var{one line to give the program's name and a brief idea of what it does.}
755: Copyright (C) 19@var{yy} @var{name of author}
756:
757: This program is free software; you can redistribute it and/or modify
758: it under the terms of the GNU General Public License as published by
759: the Free Software Foundation; either version 2 of the License, or
760: (at your option) any later version.
761:
762: This program is distributed in the hope that it will be useful,
763: but WITHOUT ANY WARRANTY; without even the implied warranty of
764: MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
765: GNU General Public License for more details.
766:
767: You should have received a copy of the GNU General Public License
768: along with this program; if not, write to the Free Software
769: Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
770: @end smallexample
771:
772: Also add information on how to contact you by electronic and paper mail.
773:
774: If the program is interactive, make it output a short notice like this
775: when it starts in an interactive mode:
776:
777: @smallexample
778: Gnomovision version 69, Copyright (C) 19@var{yy} @var{name of author}
779: Gnomovision comes with ABSOLUTELY NO WARRANTY; for details
780: type `show w'.
781: This is free software, and you are welcome to redistribute it
782: under certain conditions; type `show c' for details.
783: @end smallexample
784:
785: The hypothetical commands @samp{show w} and @samp{show c} should show
786: the appropriate parts of the General Public License. Of course, the
787: commands you use may be called something other than @samp{show w} and
788: @samp{show c}; they could even be mouse-clicks or menu items---whatever
789: suits your program.
790:
791: You should also get your employer (if you work as a programmer) or your
792: school, if any, to sign a ``copyright disclaimer'' for the program, if
793: necessary. Here is a sample; alter the names:
794:
795: @smallexample
796: Yoyodyne, Inc., hereby disclaims all copyright interest in the program
797: `Gnomovision' (which makes passes at compilers) written by James Hacker.
798:
799: @var{signature of Ty Coon}, 1 April 1989
800: Ty Coon, President of Vice
801: @end smallexample
802:
803: This General Public License does not permit incorporating your program into
804: proprietary programs. If your program is a subroutine library, you may
805: consider it more useful to permit linking proprietary applications with the
806: library. If this is what you want to do, use the GNU Library General
807: Public License instead of this License.
808:
809: @iftex
810: @unnumbered Preface
811: @cindex Preface
1.21 crook 812: This manual documents Gforth. Some introductory material is provided for
813: readers who are unfamiliar with Forth or who are migrating to Gforth
814: from other Forth compilers. However, this manual is primarily a
815: reference manual.
1.1 anton 816: @end iftex
817:
1.21 crook 818: @c ----------------------------------------------------------
819: @node Introduction, Goals, License, Top
820: @comment node-name, next, previous, up
821: @chapter An Introduction to ANS Forth
822: @cindex Forth - an introduction
823:
824: The primary purpose of this manual is to document Gforth. However, since
825: Forth is not a widely-known language and there is a lack of up-to-date
826: teaching material, it seems worthwhile to provide some introductory
827: material. @xref{Forth-related information} for other sources of Forth-related
828: information.
829:
830: The examples in this section should work on any ANS Standard Forth, the
831: output shown was produced using Gforth. In each example, I have tried to
832: reproduce the exact output that Gforth produces. If you try out the
833: examples (and you should), what you should type is shown @kbd{like this}
834: and Gforth's response is shown @code{like this}. The single exception is
835: that, where the example shows @kbd{<return>} it means that you should
836: press the "carriage return" key. Unfortunatley, some output formats for
837: this manual cannot show the difference between @kbd{this} and
838: @code{this} which will make trying out the examples harder (but not
839: impossible).
840:
841: Forth is an unusual language. It provides an interactive development
842: environment which includes both an interpreter and compiler. Forth
843: programming style encourages you to break a problem down into many
844: @cindex factoring
845: small fragments (@var{factoring}), and then to develop and test each
846: fragment interactively. Forth advocates assert that breaking the
847: edit-compile-test cycle used by conventional programming languages can
848: lead to great productivity improvements.
849:
850: @menu
851: * Introducing the Text Interpreter::
852: * Stacks and Postfix notation::
853: * Your first definition::
854: * How does that work?::
855: * Forth is written in Forth::
856: * Review - elements of a Forth system::
857: * Exercises::
858: @end menu
859: @comment TODO add these sections to the top xref lists
860:
861: @comment ----------------------------------------------
862: @node Introducing the Text Interpreter, Stacks and Postfix notation, Introduction, Introduction
863: @section Introducing the Text Interpreter
864: @cindex text interpreter
865: @cindex outer interpreter
866:
867: When you invoke the Forth image, you will see a startup banner printed
868: and nothing else (if you have Gforth installed on your system, try
869: invoking it now, by typing @kbd{gforth<return>}). Forth is now running
870: its command line interpreter, which is called the @var{Text Interpreter}
871: (also known as the @var{Outer Interpreter}). (@pxref{The Text
872: Interpreter} describes it in more detail, but we will learn more about
873: its behaviour as we go through this chapter).
874:
875: Although it may not be obvious, Forth is actually waiting for your
876: input. Type a number and press the <return> key:
877:
878: @example
879: @kbd{45<return>} ok
880: @end example
881:
882: Rather than give you a prompt to invite you to input something, the text
883: interpreter prints a status message @var{after} it has processed a line
884: of input. The status message in this case (" ok" followed by
885: carriage-return) indicates that the text interpreter was able to process
886: all of your input successfully. Now type something illegal:
887:
888: @example
889: @kbd{qwer341<return>}
890: ^^^^^^^
891: Error: Undefined word
892: @end example
893:
894: When the text interpreter detects an error, it discards any remaining
895: text on a line, resets certain internal state and prints an error
896: message.
897:
898: The text interpreter works on input one line at a time. Starting at
899: the beginning of the line, it breaks the line into groups of characters
900: separated by spaces. For each group of characters in turn, it makes two
901: attempts to do something:
902:
903: @itemize @bullet
904: @item
905: It tries to treat it as a command. It does this by searching a @var{name
906: dictionary}. If the group of characters matches an entry in the name
907: dictionary, the name dictionary provides the text interpreter with
908: information that allows the text interpreter perform some actions. In
909: Forth jargon, we say that the group
910: @cindex word
911: @cindex definition
912: @cindex execution token
913: @cindex xt
914: of characters names a @var{word}, that the dictionary search returns an
915: @var{execution token (xt)} corresponding to the @var{definition} of the
916: word, and that the text interpreter executes the xt. Often, the terms
917: @var{word} and @var{definition} are used interchangeably.
918: @item
919: If the text interpreter fails to find a match in the name dictionary, it
920: tries to treat the group of characters as a number in the current number
921: base (when you start up Forth, the current number base is base 10). If
922: the group of characters legitimately represents a number, the text
923: interpreter pushes the number onto a stack (we'll learn more about that
924: in the next section).
925: @end itemize
926:
927: If the text interpreter is unable to do either of these things with any
928: group of characters, it discards the rest of the line and print an error
929: message. If the text interpreter reaches the end of the line without
930: error, it prints the status message " ok" followed by carriage-return.
931:
932: This is the simplest command we can give to the text interpreter:
933:
934: @example
935: @kbd{<return>} ok
936: @end example
937:
938: The text interpreter did everything we asked it to do (nothing) without
939: an error, so it said that everything is "ok". Try a slightly longer
940: command:
941:
942: @example
943: @kbd{12 dup fred dup<return>}
944: ^^^^
945: Error: Undefined word
946: @end example
947:
948: When you pres the <return> key, the text interpreter starts to work its
949: way along the line.
950:
951: @itemize @bullet
952: @item
953: When it gets to the space after the @code{2}, it takes the group of
954: characters @code{12} and looks them up in the name
955: dictionary@footnote{We can't tell if it found them or not, but assume
956: for now that it did not}. There is no match for this group of characters
957: in the name dictionary, so it tries to treat them as a number. It is
958: able to do this successfully, so it puts the number, 12, "on the stack"
959: (whatever that means).
960: @item
961: The text interpreter resumes scanning the line and gets the next group
962: of characters, @code{dup}. It looks them up in the name dictionary and
963: (you'll have to take my word for this) finds them, and executes the word
964: @code{dup} (whatever that means).
965: @item
966: Once again, the text interpreter resumes scanning the line and gets the
967: group of characters @code{fred}. It looks them up in the name
968: dictionary, but can't find them. It tries to treat them as a number, but
969: they don't represent any legal number.
970: @end itemize
971:
972: At this point, the text interpreter gives up and prints an error
973: message. The error message shows exactly how far the text interpreter
974: got in processing the line. In particular, it shows that the text
975: interpreter made no attempt to do anything with the final character
976: group, @code{dup}, even though we have good reason to believe that the
977: text interpreter would have had no problems with looking that word up
978: and executing it a second time.
979:
980:
981: @comment ----------------------------------------------
982: @node Stacks and Postfix notation, Your first definition, Introducing the Text Interpreter, Introduction
983: @section Stacks, postfix notation and parameter passing
984: @cindex text interpreter
985: @cindex outer interpreter
986:
987: In procedural programming languages (like C and Pascal), the
988: building-block of programs is the function or procedure. These
989: functions or procedures are called with explicit parameters. For
990: example, in C we might write:
991:
992: @example
993: total = total + new_volume(length,height,depth);
994: @end example
995:
996: where total, length, height, depth are all variables and new_volume is
997: a function-call to another piece of code.
998:
999: In Forth, the equivalent to the function or procedure is the
1000: @var{definition} and parameters are implicitly passed between
1001: definitions using a shared stack that is visible to the
1002: programmer. Although Forth does support variables, the existence of the
1003: stack means that they are used far less often than in most other
1004: programming languages. When the text interpreter encounters a number, it
1005: will place (@var{push}) it on the stack. There are several stacks (the
1006: actual number is implementation-dependent ..) and the particular stack
1007: used for any operation is implied unambiguously by the operation being
1008: performed. The stack used for all integer operations is called the @var{data
1009: stack} and, since this is the stack used most commonly, references to
1010: "the data stack" are often abbreviated to "the stack".
1011:
1012: The stacks have a last-in, first-out (LIFO) organisation. If you type:
1013:
1014: @example
1015: @kbd{1 2 3<return>} ok
1016: @end example
1017:
1018: Then you (well, the text interpreter, really) have placed three numbers
1019: on the (data) stack. An analogy for the behaviour of the stack is to
1020: take a pack of playing cards and deal out the ace (1), 2 and 3 into a
1021: pile on the table. The 3 was the last card onto the pile ("last-in") and
1022: if you take a card off the pile then, unless you're prepared to fiddle a
1023: bit, the card that you take off will be the 3 ("first-out"). The number
1024: that will be first-out of the stack is called the "top of stack", which
1025: is often abbreviated to @var{TOS}.
1026:
1027: To see how parameters are passed in Forth, we will consider the
1028: behaviour of the definition @code{+} (pronounced "plus"). You will not be
1029: surprised to learn that this definition performs addition. More
1030: precisely, it adds two number together and produces a result. Where does
1031: it get the two numbers from? It takes the first two numbers off the
1032: stack. Where does it place the result? On the stack. You can act-out the
1033: behaviour of @code{+} with your playing cards like this:
1034:
1035: @itemize @bullet
1036: @item
1037: Pick up two cards from the stack
1038: @item
1039: Stare at them intently and ask yourself "what *is* the sum of these two
1040: numbers"
1041: @item
1042: Decide that the answer is 5
1043: @item
1044: Shuffle the two cards back into the pack and find a 5
1045: @item
1046: Put a 5 on the remaining ace that's on the table.
1047: @end itemize
1048:
1049: If you don't have a pack of cards handy but you do have Forth running,
1050: you can use the definition .s to show the current state of the stack,
1051: without affecting the stack. Type:
1052:
1053: @example
1054: @kbd{clearstack 1 2 3<return>} ok
1055: @kbd{.s<return> <3> 1 2 3 } ok
1056: @end example
1057:
1058: The text interpreter looks up the word @code{clearstack} and executes
1059: it; it tidies up the stack and removes any entries that may have been
1060: left on it by earlier examples. The text interpreter pushes each of the
1061: three numbers in turn onto the stack. Finally, the text interpreter
1062: looks up the word @code{.s} and executes it. The effect of executing
1063: @code{.s} is to print the "<3>" (the total number of items on the stack)
1064: followed by a list of all the items and the item on the far right-hand
1065: side is the TOS.
1066:
1067: You can now type:
1068:
1069: + .s<return> <2> 1 5 ok
1070:
1071: which is correct; there are now 2 items on the stack and the result of
1072: the addition is 5.
1073:
1074: If you're playing with cards, try doing a second addition; pick up the
1075: two cards, work out that their sum is 6, shuffle them into the pack,
1076: look for a 6 and place that on the table. You now have just one item
1077: on the stack. What happens if you try to do a third addition? Pick up
1078: the first card, pick up the second card - ah. There is no second
1079: card. This is called a "stack underflow" and consitutes an error. If
1080: you try to do the same thing with Forth it will report an error
1081: (probably a Stack Underflow or an Invalid Memory Address error).
1082:
1083: The opposite situation to a stack underflow is a stack overflow, which
1084: simply accepts that there is a finite amount of storage space reserved
1085: for the stack. To stretch the playing card analogy, if you had enough
1086: packs of cards and you piled the cards up on the table, you would
1087: eventually be unable to add another card; you'd hit the
1088: ceiling. Gforth allows you to set the maximum size of the stacks. In
1089: general, the only time that you will get a stack overflow is because a
1090: definition has a bug in it and is generating data on the stack
1091: uncontrollably.
1092:
1093: There's one final use for the playing card analogy. If you model your
1094: stack using a pack of playing cards, the maximum number of items on
1095: your stack will be 52 (I assume you didn't use the Joker). The maximum
1096: *value* of any item on the stack is 13 (the King). In fact, the only
1097: possible numbers are positive integer numbers 1 through 13; you can't
1098: have (for example) 0 or 27 or 3.52 or -2. If you change the way you
1099: think about some of the cards, you can accommodate different
1100: numbers. For example, you could think of the Jack as representing 0,
1101: the Queen as representing -1 and the King as representing -2. Your
1102: *range* remains unchanged (you can still only represent a total of 13
1103: numbers) but the numbers that you can represent are -2 through 10.
1104:
1105: In that analogy, the limit was the amount of information that a single
1106: stack entry could hold, and Forth has a similar limit. In Forth, the
1107: size of a stack entry is called a "cell". The actual size of a cell is
1108: implementation dependent and affects the maximum value that a stack
1109: entry can hold. A Standard Forth provides a cell size of at least
1110: 16-bits, and most desktop systems use a cell size of 32-bits.
1111:
1112: Forth does not do any type checking for you, so you are free to
1113: manipulate and combine stack items in any way you wish. A convenient
1114: ways of treating stack items is as 2's complement signed integers, and
1115: that is what Standard words like "+" do. Therefore you can type:
1116:
1117: -5 12 + .s<return> <1> 7 ok
1118:
1119: If you use numbers and definitions like "+" in order to turn Forth
1120: into a great big pocket calculator, you will realise that it's rather
1121: different from a normal calculator. Rather than typing 2 + 3 = you had
1122: to type 2 3 + (ignore the fact that you had to use .s to see the
1123: result). The terminology used to describe this difference is to say
1124: that your calculator uses "Infix Notation" (parameters and operators
1125: are mixed) whilst Forth uses "Postfix Notation" (parameters and
1126: operators are separate), also called "Reverse Polish Notation".
1127:
1128: Whilst postfix notation might look confusing to begin with, it has
1129: several important advantages:
1130:
1131: - it is unambiguous
1132: - it is more concise
1133: - it fits naturally with a stack-based system
1134:
1135: To examine these claims in more detail, consider these sums:
1136:
1137: 6 + 5 * 4 =
1138: 4 * 5 + 6 =
1139:
1140: If you're just learning maths or your maths is very rusty, you will
1141: probably come up with the answer 44 for the first and 26 for the
1142: second. If you are a bit of a whizz at maths you will remember the
1143: *convention* that multiplication takes precendence over addition, and
1144: you'd come up with the answer 26 both times. To explain the answer 26
1145: to someone who got the answer 44, you'd probably rewrite the first sum
1146: like this:
1147:
1148: 6 + (5 * 4) =
1149:
1150: If what you really wanted was to perform the addition before the
1151: multiplication, you would have to use parentheses to force it.
1152:
1153: If you did the first two sums on a pocket calculator you would probably
1154: get the right answers, unless you were very cautious and entered them using
1155: these keystroke sequences:
1156:
1157: 6 + 5 = * 4 =
1158: 4 * 5 = + 6 =
1159:
1160: Postfix notation is unambiguous because the order that the operators
1161: are applied is always explicit; that also means that parentheses are
1162: never required. The operators are *active* (the act of quoting the
1163: operator makes the operation occur) which removes the need for "=".
1164:
1165: The sum 6 + 5 * 4 can be written (in postfix notation) in two
1166: equivalent ways:
1167:
1168: 6 5 4 * + or:
1169: 5 4 * 6 +
1170:
1.23 ! crook 1171: An important thing that you should notice about this notation is that
! 1172: the @var{order} of the numbers does not change; if you want to subtract
! 1173: 2 from 10 you type @code{10 2 -}.
! 1174:
! 1175: The reason why Forth uses postfix notation is very simple to explain: it
! 1176: makes the implementation extremely simple, and it follows naturally from
! 1177: using the stack as a mechanism for passing parameters. Another way of
! 1178: thinking about this is to realise that all Forth definitions are
! 1179: @var{active}; they execute as they are encountered by the text
! 1180: interpreter. The result of this is that the syntax of Forth is almost
! 1181: trivially simple.
! 1182:
! 1183:
! 1184:
! 1185: @comment ----------------------------------------------
! 1186: @node Your first definition, How does that work?, Stacks and Postfix notation, Introduction
! 1187: @section Your first Forth definition
! 1188: @cindex first definition
1.21 crook 1189:
1.23 ! crook 1190: Until now, the examples we've seen have been trivial; we've just been
! 1191: using Forth an a bigger-than-pocket calculator. Also, each calculation
! 1192: we've shown has been a "one-off" -- to repeat it we'd need to type it in
! 1193: again@footnote{That's not quite true. If you press the up-arrow key on
! 1194: your keyboard you should be able to scroll back to any earlier command,
! 1195: edit it and re-enter it.} In this section we'll see how to add new
! 1196: word to Forth's vocabulary.
! 1197:
! 1198: The easiest way to create a new word is to use a "colon
! 1199: definition". We'll define a few and try them out before we worry too
! 1200: much about how they work. Try typing in these examples; be careful to
! 1201: copy the spaces accurately:
! 1202:
! 1203: @example
! 1204: : add-two 2 + . ;
! 1205: : greet ." Hello and welcome" ;
! 1206: : demo 5 add-two ;
! 1207: @end example
1.21 crook 1208:
1.23 ! crook 1209: @noindent
! 1210: Now try them out:
1.21 crook 1211:
1.23 ! crook 1212: @example
! 1213: @kbd{greet<return>} Hello and welcome ok
! 1214: @kbd{greet greet<return>} Hello and welcomeHello and welcome ok
! 1215: @kbd{4 add-two<return>} 6 ok
! 1216: @kbd{demo<return>} 7 ok
! 1217: @kbd{9 greet demo add-two<return>} Hello and welcome7 11 ok
! 1218: @end example
1.21 crook 1219:
1.23 ! crook 1220: The first new thing that we've introduced here is the pair of words
! 1221: @code{:} and @code{;}. These are used to start and terminate a new
! 1222: definition, respectively. The first word after the @code{:} is the name
! 1223: for the new definition.
1.21 crook 1224:
1.23 ! crook 1225: As you can see from the examples, a definition is built up of words that
! 1226: have already been defined; Forth makes no distinction between
! 1227: definitions that existed when you started the system up, and those that
! 1228: you define yourself.
1.21 crook 1229:
1.23 ! crook 1230: The examples also introduce the words @code{.} (dot), @code{."} (dot-quote)
! 1231: and @code{dup} (dewp). Dot takes the value from the top of the stack and
! 1232: displays it. It's like @code{.s} except that it only displays the top
! 1233: item of the stack and it is destructive; after it has executed the
! 1234: number is no longer on the top of the stack. There is always one space
! 1235: printed after the number, and no spaces before it. Dot-quote defines a
! 1236: string (a sequence of characters) that will be printed when the word is
! 1237: executed. The string can contain any printable characters except
! 1238: @code{"}. A @code{"} has a special function; it is not itself a Forth
! 1239: word but it acts as a delimiter. The way that it works is described in
! 1240: the next section. Finally, @code{dup} duplicates the value at the top of
! 1241: the stack. Try typing @code{5 dup .s} to see what it does.
1.21 crook 1242:
1.23 ! crook 1243: We already know that the text interpreter searches through the
! 1244: dictionary to locate names. If you've followed the examples earlier, you
! 1245: will already have a definition called @code{add-two}. Lets try modifying
! 1246: it by typing in a new definition:
1.21 crook 1247:
1.23 ! crook 1248: @example
! 1249: @kbd{: add-two dup . ." + 2 =" 2 + . ;<return>} redefined add-two ok
! 1250: @end example
1.21 crook 1251:
1.23 ! crook 1252: Forth recognised that we were defining a word that already exists, and
! 1253: printed a message to warn us of that fact. Let's try out the new
! 1254: definition:
1.21 crook 1255:
1.23 ! crook 1256: @example
! 1257: @kbd{9 add-two<return>} 9 + 2 =11 ok
! 1258: @end example
1.21 crook 1259:
1.23 ! crook 1260: @noindent
! 1261: All that we've actually done here, though, is to create a new
! 1262: definition, with a particular name. The fact that there was already a
! 1263: definition with the same name did not make any difference to the way
! 1264: that the new definition was created (except that Forth printed a warning
! 1265: message). The old definition of add-two still exists (try @code{demo}
! 1266: again to see that this is true). Any new definition will use the new
! 1267: definition of @code{add-two}, but old definitions continue to use the
! 1268: version that already existed at the time that they were @code{compiled}.
1.21 crook 1269:
1.23 ! crook 1270: Before you go on to the next section, try defining and redefining some
! 1271: words of your own.
1.21 crook 1272:
1273: @comment ----------------------------------------------
1274: @node How does that work?, Forth is written in Forth, Your first definition, Introduction
1275: @section How does that work?
1276: @cindex parsing words
1277:
1.23 ! crook 1278: Now we're going to take another look at the definition of @code{add-two}
! 1279: from the previous section. From our knowledge of the way that the text
! 1280: interpreter works, we would have expected this result when we tried to
! 1281: define @code{add-two}:
1.21 crook 1282:
1.23 ! crook 1283: @example
! 1284: @kbd{: add-two 2 + . " ;<return>}
! 1285: ^^^^^^^
! 1286: Error: Undefined word
! 1287: @end example
1.21 crook 1288:
1.23 ! crook 1289: The reason that this didn't happen is bound up in the way that @code{:}
! 1290: works. The word @code{:} does two special things. The first special
! 1291: thing that it does prevents the text interpreter from ever seeing the
! 1292: characters @code{add-two}. The text interpreter uses a variable called
! 1293: @cindex modifying >IN
! 1294: @code{>IN} (pronounced ''to-in'') to keep track of where it is in the
! 1295: input line. When it encounters the word @code{:} it behaves in exactly
! 1296: the same way as it does for any other word; it looks it up in the name
! 1297: dictionary, finds its xt and executes it. When @code{:} executes, it
! 1298: looks at the input buffer, finds the word @code{add-two} and advances the
! 1299: value of @code{>IN} to point past it. It then does some other stuff
! 1300: associated with creating the new definition (including creating an entry
! 1301: for @code{add-two} in the name dictionary). When the execution of @code{:}
! 1302: completes, control returns to the text interpreter, which is oblivious
! 1303: to the fact that it has been tricked into ignoring part of the input
! 1304: line.
1.21 crook 1305:
1.23 ! crook 1306: @cindex parsing words
! 1307: Words like @code{:} -- words that advance the value of @code{>IN} and so
! 1308: prevent the text interpreter from acting on the whole of the input line
! 1309: -- are called @var{parsing words}.
! 1310:
! 1311: @cindex state - effect on the text interpreter
! 1312: @cindex text interpreter - effect of state
! 1313: The second special thing that @code{:} does is to change the value of a
! 1314: variable called @code{state}, which affects the way that the text
! 1315: interpreter behaves. When Gforth starts up, @code{state} has the value
! 1316: 0, and the text interpreter is said to be in @var{interpret}
! 1317: mode. During a colon definition (started with @code{:}), @code{state} is
! 1318: set to -1 and the text interpreter is said to be in @var{compile}
! 1319: mode. The word @code{;} ends the definition -- one of the things that it
! 1320: does is to change the value of @code{state} back to 0.
! 1321:
! 1322: When the text interpreter is in @var{interpret} mode, we already know
! 1323: how it behaves; it looks for each character sequence in the dictionary,
! 1324: finds its xt and executes it, or it converts it to a number and pushes
! 1325: it onto the stack, or it fails to do either and generates an error.
! 1326:
! 1327: When the text interpreter is in @var{compile} mode, its behaviour is
! 1328: slightly different; it still looks for each character sequence in the
! 1329: dictionary and finds its xt, or converts it to a number, or fails to do
! 1330: either and generates an error. However, instead of executing the xt or
! 1331: pushing the number onto the stack it lays down (@var{compiles}) some
! 1332: magic to make that xt or number get executed or pushed at a later time;
! 1333: at the time that @code{add-two} is @var{executed}. Therefore, when you
! 1334: execute @code{add-two} its @var{run-time effect} is exactly the same as
! 1335: if you had typed @code{2 + .} outside of a definition, and pressed
! 1336: <return>.
1.21 crook 1337:
1.23 ! crook 1338: In Forth, every word or number can be described in terms of three
! 1339: properties:
1.21 crook 1340:
1341: @itemize @bullet
1342: @item
1.23 ! crook 1343: Its behaviour at @var{compile} time
1.21 crook 1344: @item
1.23 ! crook 1345: Its behaviour at @var{interpret} time
1.21 crook 1346: @item
1.23 ! crook 1347: Its behaviour at @var{execution} time.
1.21 crook 1348: @end itemize
1349:
1.23 ! crook 1350: These behaviours are called the @var{semantics} of the word or
! 1351: number. The value of @var{state} determines whether the text
! 1352: interpreter will use the compile or interpret semantics of a word or
! 1353: number that it encounters.
1.21 crook 1354:
1355: @itemize @bullet
1356: @item
1.23 ! crook 1357: @cindex interpretation semantics
! 1358: When the text interpreter encounters a word or number in @var{interpret}
! 1359: state, it performs the @var{interpretation semantics} of the word or
! 1360: number.
1.21 crook 1361: @item
1.23 ! crook 1362: @cindex compilation semantics
! 1363: When the text interpreter encounters a word or number in @var{compile}
! 1364: state, it performs the @var{compilation semantics} of the word or
! 1365: number.
1.21 crook 1366: @end itemize
1367:
1.23 ! crook 1368: The behaviour of numbers is always the same:
1.21 crook 1369:
1370: @itemize @bullet
1371: @item
1.23 ! crook 1372: When the number is @var{compiled}, it is appended to the current
! 1373: definition so that its run-time behaviour is to execute. (In other
! 1374: words, the compilation semantics of a number are to postpone its
! 1375: execution semantics until the run-time of the definition that it is
! 1376: being compiled into.)
! 1377: @item
! 1378: When the number is @var{interpreted}, its behaviour is to execute. (In
! 1379: other words, the interpretation semantics of a number are to perform its
! 1380: execution semantics.)
1.21 crook 1381: @item
1.23 ! crook 1382: @cindex execution semantics
! 1383: When the number is @var{executed}, its behaviour is to push its value
! 1384: onto the stack. (In other words, the execution semantics of a number are
! 1385: to push its value onto the stack.)
1.21 crook 1386: @end itemize
1387:
1.23 ! crook 1388: The behaviour of a word is not so regular, but the vast majority behave
! 1389: like this:
1.21 crook 1390:
1391: @itemize @bullet
1392: @item
1.23 ! crook 1393: The @var{compilation semantics} of the word are to append its
! 1394: @var{execution semantics} to the current definition (so that its
! 1395: run-time behaviour is to execute).
1.21 crook 1396: @item
1.23 ! crook 1397: The @var{interpretation semantics} of the word are to execute.
! 1398: @item
! 1399: The @var{execution semantics} of the word are to do something useful.
1.21 crook 1400: @end itemize
1401:
1402:
1.23 ! crook 1403: The actual behaviour of any particular word depends upon the way in
! 1404: which it was defined. In all cases, the text interpreter decides what to
! 1405: do with the word; when it searches the name dictionary for a definition,
! 1406: it not only retrieves the xt for the word, it also retrieves a flag
! 1407: called the @var{immediate flag}. If the flag is set, the text
! 1408: interpreter will @var{execute} the word rather than @var{compiling}
! 1409: @cindex immediate words
! 1410: it. In other words, these so-called @var{immediate} words behave like
! 1411: this:
1.21 crook 1412:
1413: @itemize @bullet
1414: @item
1.23 ! crook 1415: The @var{compilation semantics} of the word are to perform its
! 1416: @var{execution semantics} (so that its compile-time behaviour is to
! 1417: execute).
1.21 crook 1418: @item
1.23 ! crook 1419: The @var{interpretation semantics} of the word are to execute.
! 1420: @item
! 1421: The @var{execution semantics} of the word are to do something useful.
1.21 crook 1422: @end itemize
1423:
1.23 ! crook 1424: This example shows the difference between an immediate and a
! 1425: non-immediate word:
1.21 crook 1426:
1427: @example
1.23 ! crook 1428: : show-state state @ . ;
! 1429: : show-state-now show-state ; immediate
! 1430: : word1 show-state ;
! 1431: : word2 show-state-now ;
! 1432: @end example
! 1433:
! 1434: The word @code{immediate} after the definition of @code{show-state-now}
! 1435: makes that word an immediate word. These definitions introduce a new
! 1436: word: @code{@@} (pronounced ''at''). This word fetches the value of a
! 1437: variable, and leaves it on the stack. Therefore, the behaviour of
! 1438: @code{show-state} is to print a number that represents the current value
! 1439: of @code{state}.
! 1440:
! 1441: When you execute @code{word1}, it prints the number 0, indicating
! 1442: that the system is in interpret state. When the text interpreter
! 1443: compiled the definition of @code{word1}, it encountered
! 1444: @code{show-state} whose compilation semantics are to append its
! 1445: execution semantics to the current definition. When you execute
! 1446: @code{word1}, it performs the execution semantics of @code{show-state}.
! 1447: At the time that @code{word1} (and therefore @code{show-state}) are
! 1448: executed, the system is in interpret state.
! 1449:
! 1450: When you pressed <return> after entering the definition of @code{word2},
! 1451: you should have seen the number -1 printed, followed by @code{ ok}. When
! 1452: the text interpreter compiled the definition of @code{word2}, it
! 1453: encountered @code{show-state-now}, an immediate word, whose compilation
! 1454: semantics are therefore to perform its execution semantics. It is
! 1455: executed straight away (even before the text interpreter has moved on
! 1456: to process another group of characters; the @code{;} in this
! 1457: example). The effect of executing it are to display the value of
! 1458: @code{state} @var{at the time that the definition of} @code{word2}
! 1459: @var{is being defined}. Printing -1 demonstrates that the system is in
! 1460: compilation state at this time. If you execute @code{word2} it does
! 1461: nothing at all.
! 1462:
! 1463: @cindex ." -- how it works
! 1464: Before leaving the subject of immediate words, consider the behaviour of
! 1465: @code{."} in the definition of @code{greet}, in the previous
! 1466: section. This word is both a parsing word and an immediate word. Notice
! 1467: that there is a space between @code{."} and the start of the text
! 1468: @code{Hello and welcome}, but that there is no space between the last
! 1469: letter of @code{welcome} and the @code{"} character. The reason for this
! 1470: is that @code{."} is a Forth word; it must have a space after it so that
! 1471: the text interpreter can identify it. The @code{"} is not a Forth word;
! 1472: it is a @var{delimiter}. The examples earlier show that, when the string
! 1473: is displayed, there is neither a space before the @code{H} nor after the
! 1474: @code{e}. Since @code{."} is an immediate word, it executes at the time
! 1475: that @code{greet is defined}. When it executes, it searches forward in
! 1476: the input line looking for the delimiter. When it finds the delimiter,
! 1477: it updates @code{>in} to point past the delimiter. It also compiles some
! 1478: magic code into the definition of @code{greet}; the xt of a run-time
! 1479: routine that prints a text string. It compiles the string @code{Hello
! 1480: and welcome} into memory so that it is available to be printed
! 1481: later. When the text interpreter gains control, the next word it finds
! 1482: in the input stream is @code{;} and so it terminates the definition of
! 1483: @code{greet}.
1.21 crook 1484:
1485:
1.23 ! crook 1486: @comment ----------------------------------------------
! 1487: @node Forth is written in Forth, Review - elements of a Forth system, How does that work?, Introduction
! 1488: @section Forth is written in Forth
! 1489: @cindex structure of Forth programs
1.21 crook 1490:
1.23 ! crook 1491: When you start up a Forth compiler, a large number of definitions
! 1492: already exist. In Forth, you develop a new application using bottom-up
! 1493: programming techniques to create new definitions that are defined in
! 1494: terms of existing definitions. As you create each definition you can
! 1495: test and debug it interactively.
! 1496:
! 1497: If you have tried out the examples in this section, you will probably
! 1498: have typed them in by hand; when you leave Gforth, your definitions will
! 1499: be deleted. You can avoid this by using a text editor to enter Forth
! 1500: source code into a file, and then load all of the code from the file
! 1501: using @code{include} (@xref{Including Files}). A Forth source
! 1502: file is processed by the text interpreter, just as though you had typed
! 1503: it in by hand@footnote{Actually, there are some subtle differences, like
! 1504: the fact that it doesn't print @code{ ok} at the end of each line}.
! 1505:
! 1506: Gforth also supports the traditional Forth alternative to using text
! 1507: files for program entry (@xref{Blocks}).
! 1508:
! 1509: In common with many, if not most, Forth compilers, most of Gforth is
! 1510: actually written in Forth. All of the @code{.fs} files in the
! 1511: installation directory are Forth source files, and you can look at them
! 1512: to see examples of Forth programming.
! 1513:
! 1514: Gforth maintains a history file that records every line that you
! 1515: type to the text interpreter. This file is preserved between sessions,
! 1516: and is used to provide the command-line recall facility. If you enter
! 1517: long definitions by hand, you can use a text editor to paste them out of
! 1518: the history file into a Forth source file for reuse at a later time.
! 1519:
! 1520: @cindex history file
! 1521: @cindex .gforth-history
! 1522: @cindex GFORTHHIST
! 1523: You can find out the name of your history file using @code{history-file
! 1524: type }. On non-Unix systems you can find the location of the file using
! 1525: @code{history-dir type }@footnote{The environment variable GFORTHHIST
! 1526: determines the location of the file.}
1.21 crook 1527:
1528:
1529:
1.23 ! crook 1530: @comment ----------------------------------------------
! 1531: @node Review - elements of a Forth system, Exercises, Forth is written in Forth, Introduction
! 1532: @section Review - elements of a Forth system
! 1533: @cindex elements of a Forth system
1.21 crook 1534:
1.23 ! crook 1535: To summarise this chapter:
1.21 crook 1536:
1537:
1.23 ! crook 1538: @itemize @bullet
! 1539: @item
! 1540: Forth programs use @var{factoring} to break a problem down into small
! 1541: fragments called @var{words} or @var{definitions}.
! 1542: @item
! 1543: Forth program development is an interactive process.
! 1544: @item
! 1545: The main command loop that accepts input, and controls both
! 1546: interpretation and compilation, is called the @var{text interpreter}
! 1547: (also known as the @var{outer interpreter}.
! 1548: @item
! 1549: Forth has a very simple syntax, consisting of words and numbers
! 1550: separated by spaces or carriage-return characters. Any additional syntax
! 1551: is imposed by @var{parsing words}.
! 1552: @item
! 1553: Forth uses a stack to pass parameters between words. As a result, it
! 1554: uses postfix notation.
! 1555: @item
! 1556: To use a word that has previously been defined, the text interpreter
! 1557: searches for the word in the @var{name dictionary}.
! 1558: @item
! 1559: Words have @var{interpretation semantics}, @var{compilation semantics}
! 1560: and @var{execution semantics}.
! 1561: @item
! 1562: The text interpreter uses the value of @code{state} to select between
! 1563: the use of the @var{interpretation semantics} and the @var{compilation
! 1564: semantics} of a word that it encounters.
! 1565: @item
! 1566: The relationship between the @var{interpretation semantics}, @var{compilation semantics}
! 1567: and @var{execution semantics} for a word depend upon the way in which
! 1568: the word was defined (for example, whether it is an @var{immediate} word.
! 1569: @item
! 1570: Forth definitions can be implemented in Forth (called @var{high-level
! 1571: definitions}) or in some other way (usually a lower-level language and
! 1572: as a result often called @var{low-level definitions}, @var{code
! 1573: definitions} or @var{primitives}).
! 1574: @item
! 1575: Many Forth systems are implemented mainly in Forth.
! 1576: @item
! 1577: You now know enough to read and understand the rest of this manual and
! 1578: the ANS Forth Standard.
! 1579: @end itemize
1.21 crook 1580:
1581:
1.23 ! crook 1582: @comment TODO - other defining words
! 1583: @comment other parsing words
! 1584: @comment Your first loop
! 1585: @comment syntax and semantics
! 1586: @comment DOES>
! 1587: @comment taste of other elements of Forth
1.21 crook 1588:
1589:
1590:
1591: @comment ----------------------------------------------
1.23 ! crook 1592: @node Exercises, ,Review - elements of a Forth system, Introduction
! 1593: @section Exercises
1.21 crook 1594: @cindex elements of a Forth system
1595:
1.23 ! crook 1596: Amazing as it may seem, if you have read (and understood) this far, you
! 1597: know almost all the fundamentals about the inner workings of a Forth
! 1598: system. You certainly know enough to be able to read and understand the
! 1599: rest of this manual, to learn more about the facilities that Gforth
! 1600: provides. Even scarier, you know almost enough to implement your own Forth
! 1601: system. However, that's not a good idea just yet.. better to try writing
! 1602: some programs in Gforth.
! 1603:
! 1604: The large number of Forth words available in ANS Standard Forth and
! 1605: Gforth make learning Forth somewhat daunting. To make the problem
! 1606: easier, use the index of this manual to learn more about these words:
1.21 crook 1607:
1.23 ! crook 1608: ..levels of Forth words.
1.21 crook 1609:
1610:
1611: Ideally, provide a set of programming excercises linked into the stuff
1612: done already and into other sections of the manual. Provide solutions to
1613: all the exercises in a .fs file in the distribution. Get some
1614: inspiration from Starting Forth and Kelly&Spies.
1615:
1616:
1.23 ! crook 1617:
1.21 crook 1618: @c ----------------------------------------------------------
1619: @node Goals, Invoking Gforth, Introduction, Top
1.1 anton 1620: @comment node-name, next, previous, up
1621: @chapter Goals of Gforth
1622: @cindex Goals
1623: The goal of the Gforth Project is to develop a standard model for
1624: ANS Forth. This can be split into several subgoals:
1625:
1626: @itemize @bullet
1627: @item
1.21 crook 1628: Gforth should conform to the ANS Forth Standard.
1.1 anton 1629: @item
1630: It should be a model, i.e. it should define all the
1631: implementation-dependent things.
1632: @item
1633: It should become standard, i.e. widely accepted and used. This goal
1634: is the most difficult one.
1635: @end itemize
1636:
1637: To achieve these goals Gforth should be
1638: @itemize @bullet
1639: @item
1640: Similar to previous models (fig-Forth, F83)
1641: @item
1642: Powerful. It should provide for all the things that are considered
1643: necessary today and even some that are not yet considered necessary.
1644: @item
1645: Efficient. It should not get the reputation of being exceptionally
1646: slow.
1647: @item
1648: Free.
1649: @item
1650: Available on many machines/easy to port.
1651: @end itemize
1652:
1653: Have we achieved these goals? Gforth conforms to the ANS Forth
1654: standard. It may be considered a model, but we have not yet documented
1655: which parts of the model are stable and which parts we are likely to
1.12 anton 1656: change. It certainly has not yet become a de facto standard, but it
1657: appears to be quite popular. It has some similarities to and some
1658: differences from previous models. It has some powerful features, but not
1659: yet everything that we envisioned. We certainly have achieved our
1660: execution speed goals (@pxref{Performance}). It is free and available
1661: on many machines.
1.1 anton 1662:
1.21 crook 1663: @menu
1664: * Gforth Extensions Sinful?::
1665: @end menu
1666:
1667: @node Gforth Extensions Sinful?, , Goals, Goals
1668: @comment node-name, next, previous, up
1669: @section Is it a Sin to use Gforth Extensions?
1670: @cindex Gforth extensions
1671:
1672: If you've been paying attention, you will have realised that there is an
1673: ANS Standard for Forth. As you read through the rest of this manual, you
1674: will see documentation for @var{Standard} words, and documentation for
1675: some appealing Gforth @var{extensions}. You might ask yourself the
1676: question: @var{"Given that there is a standard, would I be committing a
1677: sin to use (non-Standard) Gforth extensions?"}
1.1 anton 1678:
1.21 crook 1679: The answer to that question is somewhat pragmatic and somewhat
1680: philosophical. Consider these points:
1.1 anton 1681:
1.21 crook 1682: @itemize @bullet
1683: @item
1684: A number of the Gforth extensions can be implemented in ANS Standard
1685: Forth using files provided in the @file{compat/} directory. These are
1686: mentioned in the text in passing.
1687: @item
1688: Forth has a rich historical precedent for programmers taking advantage
1689: of implementation-dependent features of their tools (for example,
1690: relying on a knowledge of the dictionary structure). Sometimes these
1691: techniques are necessary to extract every last bit of performance from
1692: the hardware, sometimes they are just a programming shorthand.
1693: @item
1694: The best way to break the rules is to know what the rules are. To learn
1695: the rules, there is no substitute for studying the text of the Standard
1696: itself. In particular, Appendix A of the Standard (@var{Rationale})
1697: provides a valuable insight into the thought processes of the technical
1698: committee.
1699: @item
1700: The best reason to break a rule is because you have to; because it's
1701: more productive to do that, because it makes your code run fast enough
1702: or because you can see no Standard way to achieve what you want to
1703: achieve.
1704: @end itemize
1.1 anton 1705:
1.21 crook 1706: The tool @file{ans-report.fs} (@pxref{ANS Report}) makes it easy to
1707: analyse your program and determine what non-Standard definitions it
1708: relies upon.
1.1 anton 1709:
1710:
1.12 anton 1711:
1.21 crook 1712: @c ----------------------------------------------------------
1713: @node Invoking Gforth, Words, Goals, Top
1.1 anton 1714: @chapter Invoking Gforth
1.21 crook 1715: @cindex Gforth - invoking
1.1 anton 1716: @cindex invoking Gforth
1717: @cindex running Gforth
1718: @cindex command-line options
1719: @cindex options on the command line
1720: @cindex flags on the command line
1721:
1722: You will usually just say @code{gforth}. In many other cases the default
1723: Gforth image will be invoked like this:
1724: @example
1725: gforth [files] [-e forth-code]
1726: @end example
1.12 anton 1727: This interprets the contents of the files and the Forth code in the order they
1.1 anton 1728: are given.
1729:
1730: In general, the command line looks like this:
1731:
1732: @example
1733: gforth [initialization options] [image-specific options]
1734: @end example
1735:
1736: The initialization options must come before the rest of the command
1737: line. They are:
1738:
1739: @table @code
1740: @cindex -i, command-line option
1741: @cindex --image-file, command-line option
1742: @item --image-file @var{file}
1743: @itemx -i @var{file}
1744: Loads the Forth image @var{file} instead of the default
1745: @file{gforth.fi} (@pxref{Image Files}).
1746:
1747: @cindex --path, command-line option
1748: @cindex -p, command-line option
1749: @item --path @var{path}
1750: @itemx -p @var{path}
1751: Uses @var{path} for searching the image file and Forth source code files
1752: instead of the default in the environment variable @code{GFORTHPATH} or
1753: the path specified at installation time (e.g.,
1754: @file{/usr/local/share/gforth/0.2.0:.}). A path is given as a list of
1755: directories, separated by @samp{:} (on Unix) or @samp{;} (on other OSs).
1756:
1757: @cindex --dictionary-size, command-line option
1758: @cindex -m, command-line option
1759: @cindex @var{size} parameters for command-line options
1760: @cindex size of the dictionary and the stacks
1761: @item --dictionary-size @var{size}
1762: @itemx -m @var{size}
1763: Allocate @var{size} space for the Forth dictionary space instead of
1764: using the default specified in the image (typically 256K). The
1.21 crook 1765: @var{size} specification for this and subsequent options consists of
1766: an integer and a unit (e.g.,
1.1 anton 1767: @code{4M}). The unit can be one of @code{b} (bytes), @code{e} (element
1.12 anton 1768: size, in this case Cells), @code{k} (kilobytes), @code{M} (Megabytes),
1769: @code{G} (Gigabytes), and @code{T} (Terabytes). If no unit is specified,
1770: @code{e} is used.
1.1 anton 1771:
1772: @cindex --data-stack-size, command-line option
1773: @cindex -d, command-line option
1774: @item --data-stack-size @var{size}
1775: @itemx -d @var{size}
1776: Allocate @var{size} space for the data stack instead of using the
1777: default specified in the image (typically 16K).
1778:
1779: @cindex --return-stack-size, command-line option
1780: @cindex -r, command-line option
1781: @item --return-stack-size @var{size}
1782: @itemx -r @var{size}
1783: Allocate @var{size} space for the return stack instead of using the
1784: default specified in the image (typically 15K).
1785:
1786: @cindex --fp-stack-size, command-line option
1787: @cindex -f, command-line option
1788: @item --fp-stack-size @var{size}
1789: @itemx -f @var{size}
1790: Allocate @var{size} space for the floating point stack instead of
1791: using the default specified in the image (typically 15.5K). In this case
1792: the unit specifier @code{e} refers to floating point numbers.
1793:
1794: @cindex --locals-stack-size, command-line option
1795: @cindex -l, command-line option
1796: @item --locals-stack-size @var{size}
1797: @itemx -l @var{size}
1798: Allocate @var{size} space for the locals stack instead of using the
1799: default specified in the image (typically 14.5K).
1800:
1801: @cindex -h, command-line option
1802: @cindex --help, command-line option
1803: @item --help
1804: @itemx -h
1805: Print a message about the command-line options
1806:
1807: @cindex -v, command-line option
1808: @cindex --version, command-line option
1809: @item --version
1810: @itemx -v
1811: Print version and exit
1812:
1813: @cindex --debug, command-line option
1814: @item --debug
1815: Print some information useful for debugging on startup.
1816:
1817: @cindex --offset-image, command-line option
1818: @item --offset-image
1819: Start the dictionary at a slightly different position than would be used
1820: otherwise (useful for creating data-relocatable images,
1821: @pxref{Data-Relocatable Image Files}).
1822:
1.5 anton 1823: @cindex --no-offset-im, command-line option
1824: @item --no-offset-im
1825: Start the dictionary at the normal position.
1826:
1.1 anton 1827: @cindex --clear-dictionary, command-line option
1828: @item --clear-dictionary
1829: Initialize all bytes in the dictionary to 0 before loading the image
1830: (@pxref{Data-Relocatable Image Files}).
1.5 anton 1831:
1832: @cindex --die-on-signal, command-line-option
1833: @item --die-on-signal
1834: Normally Gforth handles most signals (e.g., the user interrupt SIGINT,
1835: or the segmentation violation SIGSEGV) by translating it into a Forth
1836: @code{THROW}. With this option, Gforth exits if it receives such a
1837: signal. This option is useful when the engine and/or the image might be
1838: severely broken (such that it causes another signal before recovering
1839: from the first); this option avoids endless loops in such cases.
1.1 anton 1840: @end table
1841:
1842: @cindex loading files at startup
1843: @cindex executing code on startup
1844: @cindex batch processing with Gforth
1845: As explained above, the image-specific command-line arguments for the
1846: default image @file{gforth.fi} consist of a sequence of filenames and
1847: @code{-e @var{forth-code}} options that are interpreted in the sequence
1848: in which they are given. The @code{-e @var{forth-code}} or
1.21 crook 1849: @code{--evaluate @var{forth-code}} option evaluates the Forth
1.1 anton 1850: code. This option takes only one argument; if you want to evaluate more
1851: Forth words, you have to quote them or use several @code{-e}s. To exit
1852: after processing the command line (instead of entering interactive mode)
1853: append @code{-e bye} to the command line.
1854:
1855: @cindex versions, invoking other versions of Gforth
1856: If you have several versions of Gforth installed, @code{gforth} will
1857: invoke the version that was installed last. @code{gforth-@var{version}}
1858: invokes a specific version. You may want to use the option
1859: @code{--path}, if your environment contains the variable
1860: @code{GFORTHPATH}.
1861:
1862: Not yet implemented:
1863: On startup the system first executes the system initialization file
1864: (unless the option @code{--no-init-file} is given; note that the system
1865: resulting from using this option may not be ANS Forth conformant). Then
1866: the user initialization file @file{.gforth.fs} is executed, unless the
1867: option @code{--no-rc} is given; this file is first searched in @file{.},
1868: then in @file{~}, then in the normal path (see above).
1869:
1.21 crook 1870:
1871: @cindex Gforth - leaving
1872: @cindex leaving Gforth
1873:
1874: You can leave Gforth by typing @code{bye} or (if you invoked Gforth with
1875: the @code{--die-on-signal} option) Ctrl-C. When you leave Gforth, all of
1876: your definitions and data are discarded. @xref{Image Files} for ways
1877: of saving the state of the system before leaving Gforth.
1878:
1879: doc-bye
1880:
1881:
1.23 ! crook 1882: @comment TODO add section on environment variables.. find them by
! 1883: @comment grep for "getenv" -- they are:
! 1884: @comment GFORTHHIST
! 1885: @comment POSIXELY_CORRECT
! 1886: @comment TMP TEMP
! 1887: @comment HOME
! 1888: @comment LINES
! 1889: @comment COLUMNS
! 1890: @comment GFORTHPATH
! 1891: @comment FORTHSIZES ?? in INSTALL but cannot find it in the source
! 1892: @comment some are in .c files.
! 1893:
! 1894:
1.1 anton 1895: @node Words, Tools, Invoking Gforth, Top
1896: @chapter Forth Words
1897: @cindex Words
1898:
1899: @menu
1900: * Notation::
1.21 crook 1901: * Comments::
1902: * Boolean Flags::
1.1 anton 1903: * Arithmetic::
1904: * Stack Manipulation::
1.5 anton 1905: * Memory::
1.1 anton 1906: * Control Structures::
1907: * Locals::
1908: * Defining Words::
1.21 crook 1909: * The Text Interpreter::
1.5 anton 1910: * Structures::
1.12 anton 1911: * Object-oriented Forth::
1912: * Tokens for Words::
1.21 crook 1913: * Word Lists::
1914: * Environmental Queries::
1.12 anton 1915: * Files::
1916: * Including Files::
1917: * Blocks::
1918: * Other I/O::
1919: * Programming Tools::
1920: * Assembler and Code Words::
1921: * Threading Words::
1.21 crook 1922: * Passing Commands to the OS::
1923: * Miscellaneous Words::
1.1 anton 1924: @end menu
1925:
1.21 crook 1926: @node Notation, Comments, Words, Words
1.1 anton 1927: @section Notation
1928: @cindex notation of glossary entries
1929: @cindex format of glossary entries
1930: @cindex glossary notation format
1931: @cindex word glossary entry format
1932:
1933: The Forth words are described in this section in the glossary notation
1934: that has become a de-facto standard for Forth texts, i.e.,
1935:
1936: @format
1937: @var{word} @var{Stack effect} @var{wordset} @var{pronunciation}
1938: @end format
1939: @var{Description}
1940:
1941: @table @var
1942: @item word
1943: @cindex case insensitivity
1944: The name of the word. BTW, Gforth is case insensitive, so you can
1945: type the words in in lower case (However, @pxref{core-idef}).
1946:
1947: @item Stack effect
1948: @cindex stack effect
1949: The stack effect is written in the notation @code{@var{before} --
1950: @var{after}}, where @var{before} and @var{after} describe the top of
1951: stack entries before and after the execution of the word. The rest of
1952: the stack is not touched by the word. The top of stack is rightmost,
1953: i.e., a stack sequence is written as it is typed in. Note that Gforth
1954: uses a separate floating point stack, but a unified stack
1955: notation. Also, return stack effects are not shown in @var{stack
1956: effect}, but in @var{Description}. The name of a stack item describes
1957: the type and/or the function of the item. See below for a discussion of
1958: the types.
1959:
1960: All words have two stack effects: A compile-time stack effect and a
1961: run-time stack effect. The compile-time stack-effect of most words is
1962: @var{ -- }. If the compile-time stack-effect of a word deviates from
1963: this standard behaviour, or the word does other unusual things at
1964: compile time, both stack effects are shown; otherwise only the run-time
1965: stack effect is shown.
1966:
1967: @cindex pronounciation of words
1968: @item pronunciation
1969: How the word is pronounced.
1970:
1971: @cindex wordset
1972: @item wordset
1.21 crook 1973: The ANS Forth standard is divided into several word sets. A standard
1974: system need not support all of them. Therefore, in theory, the fewer
1975: word sets your program uses the more portable it will be. However, we
1976: suspect that most ANS Forth systems on personal machines will feature
1977: all word sets. Words that are not defined in the ANS standard have
1978: @code{gforth} or @code{gforth-internal} as word set. @code{gforth}
1.1 anton 1979: describes words that will work in future releases of Gforth;
1980: @code{gforth-internal} words are more volatile. Environmental query
1981: strings are also displayed like words; you can recognize them by the
1.21 crook 1982: @code{environment} in the word set field.
1.1 anton 1983:
1984: @item Description
1985: A description of the behaviour of the word.
1986: @end table
1987:
1988: @cindex types of stack items
1989: @cindex stack item types
1990: The type of a stack item is specified by the character(s) the name
1991: starts with:
1992:
1993: @table @code
1994: @item f
1995: @cindex @code{f}, stack item type
1996: Boolean flags, i.e. @code{false} or @code{true}.
1997: @item c
1998: @cindex @code{c}, stack item type
1999: Char
2000: @item w
2001: @cindex @code{w}, stack item type
2002: Cell, can contain an integer or an address
2003: @item n
2004: @cindex @code{n}, stack item type
2005: signed integer
2006: @item u
2007: @cindex @code{u}, stack item type
2008: unsigned integer
2009: @item d
2010: @cindex @code{d}, stack item type
2011: double sized signed integer
2012: @item ud
2013: @cindex @code{ud}, stack item type
2014: double sized unsigned integer
2015: @item r
2016: @cindex @code{r}, stack item type
2017: Float (on the FP stack)
1.21 crook 2018: @item a-
1.1 anton 2019: @cindex @code{a_}, stack item type
2020: Cell-aligned address
1.21 crook 2021: @item c-
1.1 anton 2022: @cindex @code{c_}, stack item type
2023: Char-aligned address (note that a Char may have two bytes in Windows NT)
1.21 crook 2024: @item f-
1.1 anton 2025: @cindex @code{f_}, stack item type
2026: Float-aligned address
1.21 crook 2027: @item df-
1.1 anton 2028: @cindex @code{df_}, stack item type
2029: Address aligned for IEEE double precision float
1.21 crook 2030: @item sf-
1.1 anton 2031: @cindex @code{sf_}, stack item type
2032: Address aligned for IEEE single precision float
2033: @item xt
2034: @cindex @code{xt}, stack item type
2035: Execution token, same size as Cell
2036: @item wid
2037: @cindex @code{wid}, stack item type
1.21 crook 2038: Word list ID, same size as Cell
1.1 anton 2039: @item f83name
2040: @cindex @code{f83name}, stack item type
2041: Pointer to a name structure
2042: @item "
2043: @cindex @code{"}, stack item type
1.12 anton 2044: string in the input stream (not on the stack). The terminating character
2045: is a blank by default. If it is not a blank, it is shown in @code{<>}
1.1 anton 2046: quotes.
2047: @end table
2048:
1.21 crook 2049: @node Comments, Boolean Flags, Notation, Words
2050: @section Comments
2051: @cindex Comments
2052:
2053: Forth supports two styles of comment; the traditional "in-line" comment,
2054: @code{(} and its modern cousin, the "comment to end of line"; @code{\}.
2055:
1.23 ! crook 2056: doc-(
1.21 crook 2057: doc-\
1.23 ! crook 2058: doc-\G
1.21 crook 2059:
2060: @node Boolean Flags, Arithmetic, Comments, Words
2061: @section Boolean Flags
2062: @cindex Boolean Flags
2063:
2064: A Boolean flag is cell-sized. A cell with all bits clear represents the
2065: flag @code{false} and a flag with all bits set represents the flag
2066: @code{true}. Words that check a flag (for example, @var{IF}) will treat
2067: a cell that has @var{any} bit set as @code{true}.
2068:
2069: doc-true
2070: doc-false
2071:
2072:
2073: @node Arithmetic, Stack Manipulation, Boolean Flags, Words
1.1 anton 2074: @section Arithmetic
2075: @cindex arithmetic words
2076:
2077: @cindex division with potentially negative operands
2078: Forth arithmetic is not checked, i.e., you will not hear about integer
2079: overflow on addition or multiplication, you may hear about division by
2080: zero if you are lucky. The operator is written after the operands, but
2081: the operands are still in the original order. I.e., the infix @code{2-1}
2082: corresponds to @code{2 1 -}. Forth offers a variety of division
2083: operators. If you perform division with potentially negative operands,
2084: you do not want to use @code{/} or @code{/mod} with its undefined
2085: behaviour, but rather @code{fm/mod} or @code{sm/mod} (probably the
2086: former, @pxref{Mixed precision}).
2087:
2088: @menu
2089: * Single precision::
2090: * Bitwise operations::
1.21 crook 2091: * Double precision:: Double-cell integer arithmetic
2092: * Numeric comparison::
1.1 anton 2093: * Mixed precision:: operations with single and double-cell integers
2094: * Floating Point::
2095: @end menu
2096:
2097: @node Single precision, Bitwise operations, Arithmetic, Arithmetic
2098: @subsection Single precision
2099: @cindex single precision arithmetic words
2100:
1.21 crook 2101: By default, numbers in Forth are single-precision integers that are 1
2102: CELL in size. They can be signed or unsigned, depending upon how you
2103: treat them. @xref{Number Conversion} for the rules used by the text
2104: interpreter for recognising single-precision integers.
2105:
1.1 anton 2106: doc-+
1.21 crook 2107: doc-1+
1.1 anton 2108: doc--
1.21 crook 2109: doc-1-
1.1 anton 2110: doc-*
2111: doc-/
2112: doc-mod
2113: doc-/mod
2114: doc-negate
2115: doc-abs
2116: doc-min
2117: doc-max
1.21 crook 2118: doc-d>s
1.1 anton 2119:
1.21 crook 2120: @node Bitwise operations, Double precision, Single precision, Arithmetic
1.1 anton 2121: @subsection Bitwise operations
2122: @cindex bitwise operation words
2123:
2124: doc-and
2125: doc-or
2126: doc-xor
2127: doc-invert
1.21 crook 2128: doc-lshift
2129: doc-rshift
1.1 anton 2130: doc-2*
1.21 crook 2131: doc-d2*
1.1 anton 2132: doc-2/
1.21 crook 2133: doc-d2/
2134:
2135: @node Double precision, Numeric comparison, Bitwise operations, Arithmetic
2136: @subsection Double precision
2137: @cindex double precision arithmetic words
2138:
2139: @xref{Number Conversion} for the rules used by the text interpreter for
2140: recognising double-precision integers.
2141:
2142: A double precision number is represented by a cell pair, with the most
2143: significant digit at the TOS. It is trivial to convert an unsigned single
2144: to an (unsigned) double; simply push a @code{0} onto the TOS. Since numbers
2145: are represented by Gforth using 2's complement arithmetic, converting
2146: a signed single to a (signed) double requires sign-extension across the
2147: most significant digit. This can be achieved using @code{s>d}. The moral
2148: of the story is that you cannot convert a number without knowing what that
2149: number represents.
2150:
2151: doc-s>d
2152: doc-d+
2153: doc-d-
2154: doc-dnegate
2155: doc-dabs
2156: doc-dmin
2157: doc-dmax
2158:
2159: @node Numeric comparison, Mixed precision, Double precision, Arithmetic
2160: @subsection Numeric comparison
2161: @cindex numeric comparison words
2162:
2163: doc-0<
1.23 ! crook 2164: doc-0<=
1.21 crook 2165: doc-0<>
2166: doc-0=
1.23 ! crook 2167: doc-0>
! 2168: doc-0>=
1.21 crook 2169: doc-<
1.23 ! crook 2170: doc-<=
1.21 crook 2171: doc-<>
2172: doc-=
2173: doc->
1.23 ! crook 2174: doc->=
! 2175:
1.21 crook 2176: doc-d0<
1.23 ! crook 2177: doc-d0<=
! 2178: doc-d0<>
1.21 crook 2179: doc-d0=
1.23 ! crook 2180: doc-d0>
! 2181: doc-d0>=
1.21 crook 2182: doc-d<
1.23 ! crook 2183: doc-d<=
! 2184: doc-d<>
1.21 crook 2185: doc-d=
1.23 ! crook 2186: doc-d>
! 2187: doc-d>=
! 2188:
1.21 crook 2189: doc-u<
2190: doc-du<
2191: doc-u>
1.23 ! crook 2192: doc-u<=
! 2193: @comment why u<> and u= .. they are the same as <> and =
! 2194: doc-u<>
! 2195: doc-u=
! 2196: doc-u>=
1.21 crook 2197: doc-within
1.1 anton 2198:
1.21 crook 2199: @node Mixed precision, Floating Point, Numeric comparison, Arithmetic
1.1 anton 2200: @subsection Mixed precision
2201: @cindex mixed precision arithmetic words
2202:
2203: doc-m+
2204: doc-*/
2205: doc-*/mod
2206: doc-m*
2207: doc-um*
2208: doc-m*/
2209: doc-um/mod
2210: doc-fm/mod
2211: doc-sm/rem
2212:
1.21 crook 2213: @node Floating Point, , Mixed precision, Arithmetic
1.1 anton 2214: @subsection Floating Point
2215: @cindex floating point arithmetic words
2216:
1.21 crook 2217: @xref{Number Conversion} for the rules used by the text interpreter for
2218: recognising floating-point numbers.
1.1 anton 2219:
2220: @cindex angles in trigonometric operations
2221: @cindex trigonometric operations
2222: Angles in floating point operations are given in radians (a full circle
2223: has 2 pi radians). Note, that Gforth has a separate floating point
2224: stack, but we use the unified notation.
2225:
2226: @cindex floating-point arithmetic, pitfalls
2227: Floating point numbers have a number of unpleasant surprises for the
2228: unwary (e.g., floating point addition is not associative) and even a few
2229: for the wary. You should not use them unless you know what you are doing
2230: or you don't care that the results you get are totally bogus. If you
2231: want to learn about the problems of floating point numbers (and how to
2232: avoid them), you might start with @cite{David Goldberg, What Every
2233: Computer Scientist Should Know About Floating-Point Arithmetic, ACM
1.17 anton 2234: Computing Surveys 23(1):5@minus{}48, March 1991}
2235: (@url{http://www.validgh.com/goldberg/paper.ps}).
1.1 anton 2236:
1.21 crook 2237: doc-d>f
2238: doc-f>d
1.1 anton 2239: doc-f+
2240: doc-f-
2241: doc-f*
2242: doc-f/
2243: doc-fnegate
2244: doc-fabs
2245: doc-fmax
2246: doc-fmin
2247: doc-floor
2248: doc-fround
2249: doc-f**
2250: doc-fsqrt
2251: doc-fexp
2252: doc-fexpm1
2253: doc-fln
2254: doc-flnp1
2255: doc-flog
2256: doc-falog
2257: doc-fsin
2258: doc-fcos
2259: doc-fsincos
2260: doc-ftan
2261: doc-fasin
2262: doc-facos
2263: doc-fatan
2264: doc-fatan2
2265: doc-fsinh
2266: doc-fcosh
2267: doc-ftanh
2268: doc-fasinh
2269: doc-facosh
2270: doc-fatanh
1.21 crook 2271: doc-pi
2272: doc-f0<
2273: doc-f0=
2274: doc-f<
2275: doc-f<=
2276: doc-f<>
2277: doc-f=
2278: doc-f>
2279: doc-f>=
2280: doc-f2*
2281: doc-f2/
2282: doc-1/f
2283: doc-f~
2284: doc-precision
2285: doc-set-precision
1.1 anton 2286:
2287: @node Stack Manipulation, Memory, Arithmetic, Words
2288: @section Stack Manipulation
2289: @cindex stack manipulation words
2290:
2291: @cindex floating-point stack in the standard
1.21 crook 2292: Gforth maintains a number of separate stacks:
2293:
2294: @itemize @bullet
2295: @item
2296: A data stack (aka parameter stack) -- for characters, cells,
2297: addresses, and double cells.
2298:
2299: @item
2300: A floating point stack -- for floating point numbers.
2301:
2302: @item
2303: A return stack -- for storing the return addresses of colon
2304: definitions and other data.
2305:
2306: @item
2307: A locals stack for storing local variables.
2308: @end itemize
2309:
2310: Whilst every sane Forth has a separate floating-point stack, it is not
2311: strictly required; an ANS Forth system could theoretically keep
2312: floating-point numbers on the data stack. As an additional difficulty,
2313: you don't know how many cells a floating-point number takes. It is
2314: reportedly possible to write words in a way that they work also for a
2315: unified stack model, but we do not recommend trying it. Instead, just
2316: say that your program has an environmental dependency on a separate
2317: floating-point stack.
2318:
2319: doc-floating-stack
1.1 anton 2320:
2321: @cindex return stack and locals
2322: @cindex locals and return stack
1.21 crook 2323: A Forth system is allowed to keep local variables on the
1.1 anton 2324: return stack. This is reasonable, as local variables usually eliminate
2325: the need to use the return stack explicitly. So, if you want to produce
1.21 crook 2326: a standard compliant program and you are using local variables in a
2327: word, forget about return stack manipulations in that word (refer to the
1.1 anton 2328: standard document for the exact rules).
2329:
2330: @menu
2331: * Data stack::
2332: * Floating point stack::
2333: * Return stack::
2334: * Locals stack::
2335: * Stack pointer manipulation::
2336: @end menu
2337:
2338: @node Data stack, Floating point stack, Stack Manipulation, Stack Manipulation
2339: @subsection Data stack
2340: @cindex data stack manipulation words
2341: @cindex stack manipulations words, data stack
2342:
2343: doc-drop
2344: doc-nip
2345: doc-dup
2346: doc-over
2347: doc-tuck
2348: doc-swap
1.21 crook 2349: doc-pick
1.1 anton 2350: doc-rot
2351: doc--rot
2352: doc-?dup
2353: doc-roll
2354: doc-2drop
2355: doc-2nip
2356: doc-2dup
2357: doc-2over
2358: doc-2tuck
2359: doc-2swap
2360: doc-2rot
2361:
2362: @node Floating point stack, Return stack, Data stack, Stack Manipulation
2363: @subsection Floating point stack
2364: @cindex floating-point stack manipulation words
2365: @cindex stack manipulation words, floating-point stack
2366:
2367: doc-fdrop
2368: doc-fnip
2369: doc-fdup
2370: doc-fover
2371: doc-ftuck
2372: doc-fswap
1.21 crook 2373: doc-fpick
1.1 anton 2374: doc-frot
2375:
2376: @node Return stack, Locals stack, Floating point stack, Stack Manipulation
2377: @subsection Return stack
2378: @cindex return stack manipulation words
2379: @cindex stack manipulation words, return stack
2380:
2381: doc->r
2382: doc-r>
2383: doc-r@
2384: doc-rdrop
2385: doc-2>r
2386: doc-2r>
2387: doc-2r@
2388: doc-2rdrop
2389:
2390: @node Locals stack, Stack pointer manipulation, Return stack, Stack Manipulation
2391: @subsection Locals stack
2392:
1.21 crook 2393:
1.1 anton 2394: @node Stack pointer manipulation, , Locals stack, Stack Manipulation
2395: @subsection Stack pointer manipulation
2396: @cindex stack pointer manipulation words
2397:
1.21 crook 2398: doc-sp0
2399: doc-s0
1.1 anton 2400: doc-sp@
2401: doc-sp!
1.21 crook 2402: doc-fp0
1.1 anton 2403: doc-fp@
2404: doc-fp!
1.21 crook 2405: doc-rp0
2406: doc-r0
1.1 anton 2407: doc-rp@
2408: doc-rp!
1.21 crook 2409: doc-lp0
2410: doc-l0
1.1 anton 2411: doc-lp@
2412: doc-lp!
2413:
2414: @node Memory, Control Structures, Stack Manipulation, Words
2415: @section Memory
2416: @cindex Memory words
2417:
2418: @menu
2419: * Memory Access::
2420: * Address arithmetic::
2421: * Memory Blocks::
2422: @end menu
2423:
2424: @node Memory Access, Address arithmetic, Memory, Memory
2425: @subsection Memory Access
2426: @cindex memory access words
2427:
2428: doc-@
2429: doc-!
2430: doc-+!
2431: doc-c@
2432: doc-c!
2433: doc-2@
2434: doc-2!
2435: doc-f@
2436: doc-f!
2437: doc-sf@
2438: doc-sf!
2439: doc-df@
2440: doc-df!
2441:
2442: @node Address arithmetic, Memory Blocks, Memory Access, Memory
2443: @subsection Address arithmetic
2444: @cindex address arithmetic words
2445:
2446: ANS Forth does not specify the sizes of the data types. Instead, it
2447: offers a number of words for computing sizes and doing address
2448: arithmetic. Basically, address arithmetic is performed in terms of
2449: address units (aus); on most systems the address unit is one byte. Note
2450: that a character may have more than one au, so @code{chars} is no noop
2451: (on systems where it is a noop, it compiles to nothing).
2452:
2453: @cindex alignment of addresses for types
2454: ANS Forth also defines words for aligning addresses for specific
2455: types. Many computers require that accesses to specific data types
2456: must only occur at specific addresses; e.g., that cells may only be
2457: accessed at addresses divisible by 4. Even if a machine allows unaligned
2458: accesses, it can usually perform aligned accesses faster.
2459:
2460: For the performance-conscious: alignment operations are usually only
2461: necessary during the definition of a data structure, not during the
2462: (more frequent) accesses to it.
2463:
2464: ANS Forth defines no words for character-aligning addresses. This is not
2465: an oversight, but reflects the fact that addresses that are not
2466: char-aligned have no use in the standard and therefore will not be
2467: created.
2468:
2469: @cindex @code{CREATE} and alignment
2470: The standard guarantees that addresses returned by @code{CREATE}d words
2471: are cell-aligned; in addition, Gforth guarantees that these addresses
2472: are aligned for all purposes.
2473:
2474: Note that the standard defines a word @code{char}, which has nothing to
2475: do with address arithmetic.
2476:
2477: doc-chars
2478: doc-char+
2479: doc-cells
2480: doc-cell+
2481: doc-cell
2482: doc-align
2483: doc-aligned
2484: doc-floats
2485: doc-float+
2486: doc-float
2487: doc-falign
2488: doc-faligned
2489: doc-sfloats
2490: doc-sfloat+
2491: doc-sfalign
2492: doc-sfaligned
2493: doc-dfloats
2494: doc-dfloat+
2495: doc-dfalign
2496: doc-dfaligned
2497: doc-maxalign
2498: doc-maxaligned
2499: doc-cfalign
2500: doc-cfaligned
2501: doc-address-unit-bits
2502:
2503: @node Memory Blocks, , Address arithmetic, Memory
2504: @subsection Memory Blocks
2505: @cindex memory block words
2506:
1.21 crook 2507: Some of these words work on address units (increments of @code{CELL}),
2508: and expect a @code{CELL}-aligned address. Others work on character units
2509: (increments of @code{CHAR}), and expect a @code{CHAR}-aligned
2510: address. Choose the correct operation depending upon your data type. If
2511: you are moving a block of memory (for example, a region reserved by
2512: @code{allot}) it is safe to use @code{move}, and it should be faster
2513: than using @code{cmove}. If you are moving (for example) a string
2514: compiled using @code{S"}, it is not portable to use @code{move}; the
2515: alignment of the string in memory could change, and the relationship
2516: between @code{CELL} and @code{CHAR} could change.
2517:
2518: When copying characters between overlapping memory regions, choose
2519: carefully between @code{cmove} and @code{cmove>}.
2520:
2521: You can only use any of these words @var{portably} to access data space.
2522:
2523: @comment - think the naming of the arguments is wrong for move
1.1 anton 2524: doc-move
2525: doc-erase
2526:
1.21 crook 2527: @comment - think the naming of the arguments is wrong for cmove
1.1 anton 2528: doc-cmove
1.21 crook 2529: @comment - think the naming of the arguments is wrong for cmove>
1.1 anton 2530: doc-cmove>
2531: doc-fill
1.21 crook 2532: @comment - think the naming of the arguments is wrong for blank
1.1 anton 2533: doc-blank
1.21 crook 2534: doc-compare
2535: doc-search
1.1 anton 2536:
2537: @node Control Structures, Locals, Memory, Words
2538: @section Control Structures
2539: @cindex control structures
2540:
2541: Control structures in Forth cannot be used in interpret state, only in
2542: compile state@footnote{More precisely, they have no interpretation
2543: semantics (@pxref{Interpretation and Compilation Semantics})}, i.e., in
2544: a colon definition. We do not like this limitation, but have not seen a
2545: satisfying way around it yet, although many schemes have been proposed.
2546:
2547: @menu
2548: * Selection::
2549: * Simple Loops::
2550: * Counted Loops::
2551: * Arbitrary control structures::
2552: * Calls and returns::
2553: * Exception Handling::
2554: @end menu
2555:
2556: @node Selection, Simple Loops, Control Structures, Control Structures
2557: @subsection Selection
2558: @cindex selection control structures
2559: @cindex control structures for selection
2560:
2561: @cindex @code{IF} control structure
2562: @example
2563: @var{flag}
2564: IF
2565: @var{code}
2566: ENDIF
2567: @end example
1.21 crook 2568: @noindent
1.1 anton 2569: or
2570: @example
2571: @var{flag}
2572: IF
2573: @var{code1}
2574: ELSE
2575: @var{code2}
2576: ENDIF
2577: @end example
2578:
2579: You can use @code{THEN} instead of @code{ENDIF}. Indeed, @code{THEN} is
2580: standard, and @code{ENDIF} is not, although it is quite popular. We
2581: recommend using @code{ENDIF}, because it is less confusing for people
2582: who also know other languages (and is not prone to reinforcing negative
2583: prejudices against Forth in these people). Adding @code{ENDIF} to a
2584: system that only supplies @code{THEN} is simple:
2585: @example
1.21 crook 2586: : ENDIF POSTPONE THEN ; immediate
1.1 anton 2587: @end example
2588:
2589: [According to @cite{Webster's New Encyclopedic Dictionary}, @dfn{then
2590: (adv.)} has the following meanings:
2591: @quotation
2592: ... 2b: following next after in order ... 3d: as a necessary consequence
2593: (if you were there, then you saw them).
2594: @end quotation
2595: Forth's @code{THEN} has the meaning 2b, whereas @code{THEN} in Pascal
2596: and many other programming languages has the meaning 3d.]
2597:
1.21 crook 2598: Gforth also provides the words @code{?DUP-IF} and @code{?DUP-0=-IF}, so
1.1 anton 2599: you can avoid using @code{?dup}. Using these alternatives is also more
1.21 crook 2600: efficient than using @code{?dup}. Definitions in ANS Standard Forth
1.1 anton 2601: for @code{ENDIF}, @code{?DUP-IF} and @code{?DUP-0=-IF} are provided in
2602: @file{compat/control.fs}.
2603:
2604: @cindex @code{CASE} control structure
2605: @example
2606: @var{n}
2607: CASE
2608: @var{n1} OF @var{code1} ENDOF
2609: @var{n2} OF @var{code2} ENDOF
2610: @dots{}
2611: ENDCASE
2612: @end example
2613:
2614: Executes the first @var{codei}, where the @var{ni} is equal to
2615: @var{n}. A default case can be added by simply writing the code after
2616: the last @code{ENDOF}. It may use @var{n}, which is on top of the stack,
2617: but must not consume it.
2618:
2619: @node Simple Loops, Counted Loops, Selection, Control Structures
2620: @subsection Simple Loops
2621: @cindex simple loops
2622: @cindex loops without count
2623:
2624: @cindex @code{WHILE} loop
2625: @example
2626: BEGIN
2627: @var{code1}
2628: @var{flag}
2629: WHILE
2630: @var{code2}
2631: REPEAT
2632: @end example
2633:
2634: @var{code1} is executed and @var{flag} is computed. If it is true,
2635: @var{code2} is executed and the loop is restarted; If @var{flag} is
2636: false, execution continues after the @code{REPEAT}.
2637:
2638: @cindex @code{UNTIL} loop
2639: @example
2640: BEGIN
2641: @var{code}
2642: @var{flag}
2643: UNTIL
2644: @end example
2645:
2646: @var{code} is executed. The loop is restarted if @code{flag} is false.
2647:
2648: @cindex endless loop
2649: @cindex loops, endless
2650: @example
2651: BEGIN
2652: @var{code}
2653: AGAIN
2654: @end example
2655:
2656: This is an endless loop.
2657:
2658: @node Counted Loops, Arbitrary control structures, Simple Loops, Control Structures
2659: @subsection Counted Loops
2660: @cindex counted loops
2661: @cindex loops, counted
2662: @cindex @code{DO} loops
2663:
2664: The basic counted loop is:
2665: @example
2666: @var{limit} @var{start}
2667: ?DO
2668: @var{body}
2669: LOOP
2670: @end example
2671:
2672: This performs one iteration for every integer, starting from @var{start}
1.21 crook 2673: and up to, but excluding @var{limit}. The counter, or @var{index}, can be
2674: accessed with @code{i}. For example, the loop:
1.1 anton 2675: @example
2676: 10 0 ?DO
2677: i .
2678: LOOP
2679: @end example
1.21 crook 2680: @noindent
2681: prints @code{0 1 2 3 4 5 6 7 8 9}
2682:
1.1 anton 2683: The index of the innermost loop can be accessed with @code{i}, the index
2684: of the next loop with @code{j}, and the index of the third loop with
2685: @code{k}.
2686:
2687: doc-i
2688: doc-j
2689: doc-k
2690:
2691: The loop control data are kept on the return stack, so there are some
1.21 crook 2692: restrictions on mixing return stack accesses and counted loop words. In
2693: particuler, if you put values on the return stack outside the loop, you
2694: cannot read them inside the loop@footnote{well, not in a way that is
2695: portable.}. If you put values on the return stack within a loop, you
2696: have to remove them before the end of the loop and before accessing the
2697: index of the loop.
1.1 anton 2698:
2699: There are several variations on the counted loop:
2700:
1.21 crook 2701: @itemize @bullet
2702: @item
2703: @code{LEAVE} leaves the innermost counted loop immediately; execution
2704: continues after the associated @code{LOOP} or @code{NEXT}. For example:
2705:
2706: @example
2707: 10 0 ?DO i DUP . 3 = IF LEAVE THEN LOOP
2708: @end example
2709: prints @code{0 1 2 3}
2710:
1.1 anton 2711:
1.21 crook 2712: @item
2713: @code{UNLOOP} prepares for an abnormal loop exit, e.g., via
2714: @code{EXIT}. @code{UNLOOP} removes the loop control parameters from the
2715: return stack so @code{EXIT} can get to its return address. For example:
2716:
2717: @example
2718: : demo 10 0 ?DO i DUP . 3 = IF UNLOOP EXIT THEN LOOP ." Done" ;
2719: @end example
2720: prints @code{0 1 2 3}
2721:
2722:
2723: @item
1.1 anton 2724: If @var{start} is greater than @var{limit}, a @code{?DO} loop is entered
2725: (and @code{LOOP} iterates until they become equal by wrap-around
2726: arithmetic). This behaviour is usually not what you want. Therefore,
2727: Gforth offers @code{+DO} and @code{U+DO} (as replacements for
2728: @code{?DO}), which do not enter the loop if @var{start} is greater than
2729: @var{limit}; @code{+DO} is for signed loop parameters, @code{U+DO} for
2730: unsigned loop parameters.
2731:
1.21 crook 2732: @item
2733: @code{?DO} can be replaced by @code{DO}. @code{DO} always enters
2734: the loop, independent of the loop parameters. Do not use @code{DO}, even
2735: if you know that the loop is entered in any case. Such knowledge tends
2736: to become invalid during maintenance of a program, and then the
2737: @code{DO} will make trouble.
2738:
2739: @item
1.1 anton 2740: @code{LOOP} can be replaced with @code{@var{n} +LOOP}; this updates the
2741: index by @var{n} instead of by 1. The loop is terminated when the border
2742: between @var{limit-1} and @var{limit} is crossed. E.g.:
2743:
1.21 crook 2744: @example
2745: 4 0 +DO i . 2 +LOOP
2746: @end example
2747: @noindent
2748: prints @code{0 2}
2749:
2750: @example
2751: 4 1 +DO i . 2 +LOOP
2752: @end example
2753: @noindent
2754: prints @code{1 3}
1.1 anton 2755:
2756:
2757: @cindex negative increment for counted loops
2758: @cindex counted loops with negative increment
2759: The behaviour of @code{@var{n} +LOOP} is peculiar when @var{n} is negative:
2760:
1.21 crook 2761: @example
2762: -1 0 ?DO i . -1 +LOOP
2763: @end example
2764: @noindent
2765: prints @code{0 -1}
1.1 anton 2766:
1.21 crook 2767: @example
2768: 0 0 ?DO i . -1 +LOOP
2769: @end example
2770: prints nothing.
1.1 anton 2771:
2772: Therefore we recommend avoiding @code{@var{n} +LOOP} with negative
2773: @var{n}. One alternative is @code{@var{u} -LOOP}, which reduces the
2774: index by @var{u} each iteration. The loop is terminated when the border
2775: between @var{limit+1} and @var{limit} is crossed. Gforth also provides
2776: @code{-DO} and @code{U-DO} for down-counting loops. E.g.:
2777:
1.21 crook 2778: @example
2779: -2 0 -DO i . 1 -LOOP
2780: @end example
2781: @noindent
2782: prints @code{0 -1}
1.1 anton 2783:
1.21 crook 2784: @example
2785: -1 0 -DO i . 1 -LOOP
2786: @end example
2787: @noindent
2788: prints @code{0}
2789:
2790: @example
2791: 0 0 -DO i . 1 -LOOP
2792: @end example
2793: @noindent
2794: prints nothing.
1.1 anton 2795:
1.21 crook 2796: @end itemize
1.1 anton 2797:
2798: Unfortunately, @code{+DO}, @code{U+DO}, @code{-DO}, @code{U-DO} and
2799: @code{-LOOP} are not in the ANS Forth standard. However, an
2800: implementation for these words that uses only standard words is provided
2801: in @file{compat/loops.fs}.
2802:
2803:
2804:
2805: @cindex @code{FOR} loops
2806: Another counted loop is
2807: @example
2808: @var{n}
2809: FOR
2810: @var{body}
2811: NEXT
2812: @end example
2813: This is the preferred loop of native code compiler writers who are too
2814: lazy to optimize @code{?DO} loops properly. In Gforth, this loop
2815: iterates @var{n+1} times; @code{i} produces values starting with @var{n}
2816: and ending with 0. Other Forth systems may behave differently, even if
2817: they support @code{FOR} loops. To avoid problems, don't use @code{FOR}
2818: loops.
2819:
2820: @node Arbitrary control structures, Calls and returns, Counted Loops, Control Structures
2821: @subsection Arbitrary control structures
2822: @cindex control structures, user-defined
2823:
2824: @cindex control-flow stack
2825: ANS Forth permits and supports using control structures in a non-nested
2826: way. Information about incomplete control structures is stored on the
2827: control-flow stack. This stack may be implemented on the Forth data
2828: stack, and this is what we have done in Gforth.
2829:
2830: @cindex @code{orig}, control-flow stack item
2831: @cindex @code{dest}, control-flow stack item
2832: An @i{orig} entry represents an unresolved forward branch, a @i{dest}
2833: entry represents a backward branch target. A few words are the basis for
2834: building any control structure possible (except control structures that
2835: need storage, like calls, coroutines, and backtracking).
2836:
2837: doc-if
2838: doc-ahead
2839: doc-then
2840: doc-begin
2841: doc-until
2842: doc-again
2843: doc-cs-pick
2844: doc-cs-roll
2845:
1.21 crook 2846: The Standard words @code{CS-PICK} and @code{CS-ROLL} allow you to
2847: manipulate the control-flow stack in a portable way. Without them, you
2848: would need to know how many stack items are occupied by a control-flow
2849: entry (many systems use one cell. In Gforth they currently take three,
2850: but this may change in the future).
2851:
1.1 anton 2852:
2853: Some standard control structure words are built from these words:
2854:
2855: doc-else
2856: doc-while
2857: doc-repeat
2858:
2859: Gforth adds some more control-structure words:
2860:
2861: doc-endif
2862: doc-?dup-if
2863: doc-?dup-0=-if
2864:
2865: Counted loop words constitute a separate group of words:
2866:
2867: doc-?do
2868: doc-+do
2869: doc-u+do
2870: doc--do
2871: doc-u-do
2872: doc-do
2873: doc-for
2874: doc-loop
2875: doc-+loop
2876: doc--loop
2877: doc-next
2878: doc-leave
2879: doc-?leave
2880: doc-unloop
2881: doc-done
2882:
1.21 crook 2883: The standard does not allow using @code{CS-PICK} and @code{CS-ROLL} on
2884: @i{do-sys}. Gforth allows it, but it's your job to ensure that for
1.1 anton 2885: every @code{?DO} etc. there is exactly one @code{UNLOOP} on any path
2886: through the definition (@code{LOOP} etc. compile an @code{UNLOOP} on the
2887: fall-through path). Also, you have to ensure that all @code{LEAVE}s are
2888: resolved (by using one of the loop-ending words or @code{DONE}).
2889:
2890: Another group of control structure words are
2891:
2892: doc-case
2893: doc-endcase
2894: doc-of
2895: doc-endof
2896:
1.21 crook 2897: @i{case-sys} and @i{of-sys} cannot be processed using @code{CS-PICK} and
2898: @code{CS-ROLL}.
1.1 anton 2899:
2900: @subsubsection Programming Style
2901:
2902: In order to ensure readability we recommend that you do not create
2903: arbitrary control structures directly, but define new control structure
2904: words for the control structure you want and use these words in your
2905: program.
2906:
1.21 crook 2907: E.g., instead of writing:
1.1 anton 2908:
2909: @example
2910: begin
2911: ...
2912: if [ 1 cs-roll ]
2913: ...
2914: again then
2915: @end example
2916:
1.21 crook 2917: @noindent
1.1 anton 2918: we recommend defining control structure words, e.g.,
2919:
2920: @example
2921: : while ( dest -- orig dest )
2922: POSTPONE if
2923: 1 cs-roll ; immediate
2924:
2925: : repeat ( orig dest -- )
2926: POSTPONE again
2927: POSTPONE then ; immediate
2928: @end example
2929:
1.21 crook 2930: @noindent
1.1 anton 2931: and then using these to create the control structure:
2932:
2933: @example
2934: begin
2935: ...
2936: while
2937: ...
2938: repeat
2939: @end example
2940:
2941: That's much easier to read, isn't it? Of course, @code{REPEAT} and
2942: @code{WHILE} are predefined, so in this example it would not be
2943: necessary to define them.
2944:
2945: @node Calls and returns, Exception Handling, Arbitrary control structures, Control Structures
2946: @subsection Calls and returns
2947: @cindex calling a definition
2948: @cindex returning from a definition
2949:
1.3 anton 2950: @cindex recursive definitions
2951: A definition can be called simply be writing the name of the definition
2952: to be called. Note that normally a definition is invisible during its
2953: definition. If you want to write a directly recursive definition, you
2954: can use @code{recursive} to make the current definition visible.
2955:
2956: doc-recursive
2957:
2958: Another way to perform a recursive call is
2959:
2960: doc-recurse
2961:
1.21 crook 2962: @comment TODO add example of the two recursion methods
1.12 anton 2963: @quotation
2964: @progstyle
2965: I prefer using @code{recursive} to @code{recurse}, because calling the
2966: definition by name is more descriptive (if the name is well-chosen) than
2967: the somewhat cryptic @code{recurse}. E.g., in a quicksort
2968: implementation, it is much better to read (and think) ``now sort the
2969: partitions'' than to read ``now do a recursive call''.
2970: @end quotation
1.3 anton 2971:
1.21 crook 2972: @comment TODO maybe move deferred words to Defining Words section and x-ref
2973: @comment from here.. that is where these two are glossed.
2974:
1.3 anton 2975: For mutual recursion, use @code{defer}red words, like this:
2976:
2977: @example
2978: defer foo
2979:
2980: : bar ( ... -- ... )
2981: ... foo ... ;
2982:
2983: :noname ( ... -- ... )
2984: ... bar ... ;
2985: IS foo
2986: @end example
2987:
2988: When the end of the definition is reached, it returns. An earlier return
2989: can be forced using
1.1 anton 2990:
2991: doc-exit
2992:
2993: Don't forget to clean up the return stack and @code{UNLOOP} any
1.21 crook 2994: outstanding @code{?DO}...@code{LOOP}s before @code{EXIT}ing.
1.1 anton 2995:
2996: doc-;s
2997:
2998: @node Exception Handling, , Calls and returns, Control Structures
2999: @subsection Exception Handling
3000: @cindex Exceptions
3001:
1.21 crook 3002: @comment TODO examples and blurb
1.1 anton 3003: doc-catch
3004: doc-throw
1.21 crook 3005: @comment TODO -- think this will alllcate you a new THROW code?
3006: @comment for reserving new exception numbers. Note the existence of compat/exception.fs
3007: doc---exception-exception
3008: doc-quit
3009: doc-abort
3010: doc-abort"
3011:
1.1 anton 3012:
3013: @node Locals, Defining Words, Control Structures, Words
3014: @section Locals
3015: @cindex locals
3016:
3017: Local variables can make Forth programming more enjoyable and Forth
3018: programs easier to read. Unfortunately, the locals of ANS Forth are
3019: laden with restrictions. Therefore, we provide not only the ANS Forth
3020: locals wordset, but also our own, more powerful locals wordset (we
3021: implemented the ANS Forth locals wordset through our locals wordset).
3022:
3023: The ideas in this section have also been published in the paper
3024: @cite{Automatic Scoping of Local Variables} by M. Anton Ertl, presented
3025: at EuroForth '94; it is available at
3026: @*@url{http://www.complang.tuwien.ac.at/papers/ertl94l.ps.gz}.
3027:
3028: @menu
3029: * Gforth locals::
3030: * ANS Forth locals::
3031: @end menu
3032:
3033: @node Gforth locals, ANS Forth locals, Locals, Locals
3034: @subsection Gforth locals
3035: @cindex Gforth locals
3036: @cindex locals, Gforth style
3037:
3038: Locals can be defined with
3039:
3040: @example
3041: @{ local1 local2 ... -- comment @}
3042: @end example
3043: or
3044: @example
3045: @{ local1 local2 ... @}
3046: @end example
3047:
3048: E.g.,
3049: @example
3050: : max @{ n1 n2 -- n3 @}
3051: n1 n2 > if
3052: n1
3053: else
3054: n2
3055: endif ;
3056: @end example
3057:
3058: The similarity of locals definitions with stack comments is intended. A
3059: locals definition often replaces the stack comment of a word. The order
3060: of the locals corresponds to the order in a stack comment and everything
3061: after the @code{--} is really a comment.
3062:
3063: This similarity has one disadvantage: It is too easy to confuse locals
3064: declarations with stack comments, causing bugs and making them hard to
3065: find. However, this problem can be avoided by appropriate coding
3066: conventions: Do not use both notations in the same program. If you do,
3067: they should be distinguished using additional means, e.g. by position.
3068:
3069: @cindex types of locals
3070: @cindex locals types
3071: The name of the local may be preceded by a type specifier, e.g.,
3072: @code{F:} for a floating point value:
3073:
3074: @example
3075: : CX* @{ F: Ar F: Ai F: Br F: Bi -- Cr Ci @}
3076: \ complex multiplication
3077: Ar Br f* Ai Bi f* f-
3078: Ar Bi f* Ai Br f* f+ ;
3079: @end example
3080:
3081: @cindex flavours of locals
3082: @cindex locals flavours
3083: @cindex value-flavoured locals
3084: @cindex variable-flavoured locals
3085: Gforth currently supports cells (@code{W:}, @code{W^}), doubles
3086: (@code{D:}, @code{D^}), floats (@code{F:}, @code{F^}) and characters
3087: (@code{C:}, @code{C^}) in two flavours: a value-flavoured local (defined
3088: with @code{W:}, @code{D:} etc.) produces its value and can be changed
3089: with @code{TO}. A variable-flavoured local (defined with @code{W^} etc.)
3090: produces its address (which becomes invalid when the variable's scope is
3091: left). E.g., the standard word @code{emit} can be defined in terms of
3092: @code{type} like this:
3093:
3094: @example
3095: : emit @{ C^ char* -- @}
3096: char* 1 type ;
3097: @end example
3098:
3099: @cindex default type of locals
3100: @cindex locals, default type
3101: A local without type specifier is a @code{W:} local. Both flavours of
3102: locals are initialized with values from the data or FP stack.
3103:
3104: Currently there is no way to define locals with user-defined data
3105: structures, but we are working on it.
3106:
3107: Gforth allows defining locals everywhere in a colon definition. This
3108: poses the following questions:
3109:
3110: @menu
3111: * Where are locals visible by name?::
3112: * How long do locals live?::
3113: * Programming Style::
3114: * Implementation::
3115: @end menu
3116:
3117: @node Where are locals visible by name?, How long do locals live?, Gforth locals, Gforth locals
3118: @subsubsection Where are locals visible by name?
3119: @cindex locals visibility
3120: @cindex visibility of locals
3121: @cindex scope of locals
3122:
3123: Basically, the answer is that locals are visible where you would expect
3124: it in block-structured languages, and sometimes a little longer. If you
3125: want to restrict the scope of a local, enclose its definition in
3126: @code{SCOPE}...@code{ENDSCOPE}.
3127:
3128: doc-scope
3129: doc-endscope
3130:
3131: These words behave like control structure words, so you can use them
3132: with @code{CS-PICK} and @code{CS-ROLL} to restrict the scope in
3133: arbitrary ways.
3134:
3135: If you want a more exact answer to the visibility question, here's the
3136: basic principle: A local is visible in all places that can only be
3137: reached through the definition of the local@footnote{In compiler
3138: construction terminology, all places dominated by the definition of the
3139: local.}. In other words, it is not visible in places that can be reached
3140: without going through the definition of the local. E.g., locals defined
3141: in @code{IF}...@code{ENDIF} are visible until the @code{ENDIF}, locals
3142: defined in @code{BEGIN}...@code{UNTIL} are visible after the
3143: @code{UNTIL} (until, e.g., a subsequent @code{ENDSCOPE}).
3144:
3145: The reasoning behind this solution is: We want to have the locals
3146: visible as long as it is meaningful. The user can always make the
3147: visibility shorter by using explicit scoping. In a place that can
3148: only be reached through the definition of a local, the meaning of a
3149: local name is clear. In other places it is not: How is the local
3150: initialized at the control flow path that does not contain the
3151: definition? Which local is meant, if the same name is defined twice in
3152: two independent control flow paths?
3153:
3154: This should be enough detail for nearly all users, so you can skip the
3155: rest of this section. If you really must know all the gory details and
3156: options, read on.
3157:
3158: In order to implement this rule, the compiler has to know which places
3159: are unreachable. It knows this automatically after @code{AHEAD},
3160: @code{AGAIN}, @code{EXIT} and @code{LEAVE}; in other cases (e.g., after
3161: most @code{THROW}s), you can use the word @code{UNREACHABLE} to tell the
3162: compiler that the control flow never reaches that place. If
3163: @code{UNREACHABLE} is not used where it could, the only consequence is
3164: that the visibility of some locals is more limited than the rule above
3165: says. If @code{UNREACHABLE} is used where it should not (i.e., if you
3166: lie to the compiler), buggy code will be produced.
3167:
3168: doc-unreachable
3169:
3170: Another problem with this rule is that at @code{BEGIN}, the compiler
3171: does not know which locals will be visible on the incoming
3172: back-edge. All problems discussed in the following are due to this
3173: ignorance of the compiler (we discuss the problems using @code{BEGIN}
3174: loops as examples; the discussion also applies to @code{?DO} and other
3175: loops). Perhaps the most insidious example is:
3176: @example
3177: AHEAD
3178: BEGIN
3179: x
3180: [ 1 CS-ROLL ] THEN
3181: @{ x @}
3182: ...
3183: UNTIL
3184: @end example
3185:
3186: This should be legal according to the visibility rule. The use of
3187: @code{x} can only be reached through the definition; but that appears
3188: textually below the use.
3189:
3190: From this example it is clear that the visibility rules cannot be fully
3191: implemented without major headaches. Our implementation treats common
3192: cases as advertised and the exceptions are treated in a safe way: The
3193: compiler makes a reasonable guess about the locals visible after a
3194: @code{BEGIN}; if it is too pessimistic, the
3195: user will get a spurious error about the local not being defined; if the
3196: compiler is too optimistic, it will notice this later and issue a
3197: warning. In the case above the compiler would complain about @code{x}
3198: being undefined at its use. You can see from the obscure examples in
3199: this section that it takes quite unusual control structures to get the
3200: compiler into trouble, and even then it will often do fine.
3201:
3202: If the @code{BEGIN} is reachable from above, the most optimistic guess
3203: is that all locals visible before the @code{BEGIN} will also be
3204: visible after the @code{BEGIN}. This guess is valid for all loops that
3205: are entered only through the @code{BEGIN}, in particular, for normal
3206: @code{BEGIN}...@code{WHILE}...@code{REPEAT} and
3207: @code{BEGIN}...@code{UNTIL} loops and it is implemented in our
3208: compiler. When the branch to the @code{BEGIN} is finally generated by
3209: @code{AGAIN} or @code{UNTIL}, the compiler checks the guess and
3210: warns the user if it was too optimistic:
3211: @example
3212: IF
3213: @{ x @}
3214: BEGIN
3215: \ x ?
3216: [ 1 cs-roll ] THEN
3217: ...
3218: UNTIL
3219: @end example
3220:
3221: Here, @code{x} lives only until the @code{BEGIN}, but the compiler
3222: optimistically assumes that it lives until the @code{THEN}. It notices
3223: this difference when it compiles the @code{UNTIL} and issues a
3224: warning. The user can avoid the warning, and make sure that @code{x}
3225: is not used in the wrong area by using explicit scoping:
3226: @example
3227: IF
3228: SCOPE
3229: @{ x @}
3230: ENDSCOPE
3231: BEGIN
3232: [ 1 cs-roll ] THEN
3233: ...
3234: UNTIL
3235: @end example
3236:
3237: Since the guess is optimistic, there will be no spurious error messages
3238: about undefined locals.
3239:
3240: If the @code{BEGIN} is not reachable from above (e.g., after
3241: @code{AHEAD} or @code{EXIT}), the compiler cannot even make an
3242: optimistic guess, as the locals visible after the @code{BEGIN} may be
3243: defined later. Therefore, the compiler assumes that no locals are
3244: visible after the @code{BEGIN}. However, the user can use
3245: @code{ASSUME-LIVE} to make the compiler assume that the same locals are
3246: visible at the BEGIN as at the point where the top control-flow stack
3247: item was created.
3248:
3249: doc-assume-live
3250:
3251: E.g.,
3252: @example
3253: @{ x @}
3254: AHEAD
3255: ASSUME-LIVE
3256: BEGIN
3257: x
3258: [ 1 CS-ROLL ] THEN
3259: ...
3260: UNTIL
3261: @end example
3262:
3263: Other cases where the locals are defined before the @code{BEGIN} can be
3264: handled by inserting an appropriate @code{CS-ROLL} before the
3265: @code{ASSUME-LIVE} (and changing the control-flow stack manipulation
3266: behind the @code{ASSUME-LIVE}).
3267:
3268: Cases where locals are defined after the @code{BEGIN} (but should be
3269: visible immediately after the @code{BEGIN}) can only be handled by
3270: rearranging the loop. E.g., the ``most insidious'' example above can be
3271: arranged into:
3272: @example
3273: BEGIN
3274: @{ x @}
3275: ... 0=
3276: WHILE
3277: x
3278: REPEAT
3279: @end example
3280:
3281: @node How long do locals live?, Programming Style, Where are locals visible by name?, Gforth locals
3282: @subsubsection How long do locals live?
3283: @cindex locals lifetime
3284: @cindex lifetime of locals
3285:
3286: The right answer for the lifetime question would be: A local lives at
3287: least as long as it can be accessed. For a value-flavoured local this
3288: means: until the end of its visibility. However, a variable-flavoured
3289: local could be accessed through its address far beyond its visibility
3290: scope. Ultimately, this would mean that such locals would have to be
3291: garbage collected. Since this entails un-Forth-like implementation
3292: complexities, I adopted the same cowardly solution as some other
3293: languages (e.g., C): The local lives only as long as it is visible;
3294: afterwards its address is invalid (and programs that access it
3295: afterwards are erroneous).
3296:
3297: @node Programming Style, Implementation, How long do locals live?, Gforth locals
3298: @subsubsection Programming Style
3299: @cindex locals programming style
3300: @cindex programming style, locals
3301:
3302: The freedom to define locals anywhere has the potential to change
3303: programming styles dramatically. In particular, the need to use the
3304: return stack for intermediate storage vanishes. Moreover, all stack
3305: manipulations (except @code{PICK}s and @code{ROLL}s with run-time
3306: determined arguments) can be eliminated: If the stack items are in the
3307: wrong order, just write a locals definition for all of them; then
3308: write the items in the order you want.
3309:
3310: This seems a little far-fetched and eliminating stack manipulations is
3311: unlikely to become a conscious programming objective. Still, the number
3312: of stack manipulations will be reduced dramatically if local variables
3313: are used liberally (e.g., compare @code{max} in @ref{Gforth locals} with
3314: a traditional implementation of @code{max}).
3315:
3316: This shows one potential benefit of locals: making Forth programs more
3317: readable. Of course, this benefit will only be realized if the
3318: programmers continue to honour the principle of factoring instead of
3319: using the added latitude to make the words longer.
3320:
3321: @cindex single-assignment style for locals
3322: Using @code{TO} can and should be avoided. Without @code{TO},
3323: every value-flavoured local has only a single assignment and many
3324: advantages of functional languages apply to Forth. I.e., programs are
3325: easier to analyse, to optimize and to read: It is clear from the
3326: definition what the local stands for, it does not turn into something
3327: different later.
3328:
3329: E.g., a definition using @code{TO} might look like this:
3330: @example
3331: : strcmp @{ addr1 u1 addr2 u2 -- n @}
3332: u1 u2 min 0
3333: ?do
3334: addr1 c@@ addr2 c@@ -
3335: ?dup-if
3336: unloop exit
3337: then
3338: addr1 char+ TO addr1
3339: addr2 char+ TO addr2
3340: loop
3341: u1 u2 - ;
3342: @end example
3343: Here, @code{TO} is used to update @code{addr1} and @code{addr2} at
3344: every loop iteration. @code{strcmp} is a typical example of the
3345: readability problems of using @code{TO}. When you start reading
3346: @code{strcmp}, you think that @code{addr1} refers to the start of the
3347: string. Only near the end of the loop you realize that it is something
3348: else.
3349:
3350: This can be avoided by defining two locals at the start of the loop that
3351: are initialized with the right value for the current iteration.
3352: @example
3353: : strcmp @{ addr1 u1 addr2 u2 -- n @}
3354: addr1 addr2
3355: u1 u2 min 0
3356: ?do @{ s1 s2 @}
3357: s1 c@@ s2 c@@ -
3358: ?dup-if
3359: unloop exit
3360: then
3361: s1 char+ s2 char+
3362: loop
3363: 2drop
3364: u1 u2 - ;
3365: @end example
3366: Here it is clear from the start that @code{s1} has a different value
3367: in every loop iteration.
3368:
3369: @node Implementation, , Programming Style, Gforth locals
3370: @subsubsection Implementation
3371: @cindex locals implementation
3372: @cindex implementation of locals
3373:
3374: @cindex locals stack
3375: Gforth uses an extra locals stack. The most compelling reason for
3376: this is that the return stack is not float-aligned; using an extra stack
3377: also eliminates the problems and restrictions of using the return stack
3378: as locals stack. Like the other stacks, the locals stack grows toward
3379: lower addresses. A few primitives allow an efficient implementation:
3380:
3381: doc-@local#
3382: doc-f@local#
3383: doc-laddr#
3384: doc-lp+!#
3385: doc-lp!
3386: doc->l
3387: doc-f>l
3388:
3389: In addition to these primitives, some specializations of these
3390: primitives for commonly occurring inline arguments are provided for
3391: efficiency reasons, e.g., @code{@@local0} as specialization of
3392: @code{@@local#} for the inline argument 0. The following compiling words
3393: compile the right specialized version, or the general version, as
3394: appropriate:
3395:
3396: doc-compile-@local
3397: doc-compile-f@local
3398: doc-compile-lp+!
3399:
3400: Combinations of conditional branches and @code{lp+!#} like
3401: @code{?branch-lp+!#} (the locals pointer is only changed if the branch
3402: is taken) are provided for efficiency and correctness in loops.
3403:
3404: A special area in the dictionary space is reserved for keeping the
3405: local variable names. @code{@{} switches the dictionary pointer to this
3406: area and @code{@}} switches it back and generates the locals
3407: initializing code. @code{W:} etc.@ are normal defining words. This
3408: special area is cleared at the start of every colon definition.
3409:
1.21 crook 3410: @cindex word list for defining locals
1.1 anton 3411: A special feature of Gforth's dictionary is used to implement the
1.21 crook 3412: definition of locals without type specifiers: every word list (aka
1.1 anton 3413: vocabulary) has its own methods for searching
1.21 crook 3414: etc. (@pxref{Word Lists}). For the present purpose we defined a word list
1.1 anton 3415: with a special search method: When it is searched for a word, it
3416: actually creates that word using @code{W:}. @code{@{} changes the search
1.21 crook 3417: order to first search the word list containing @code{@}}, @code{W:} etc.,
3418: and then the word list for defining locals without type specifiers.
1.1 anton 3419:
3420: The lifetime rules support a stack discipline within a colon
3421: definition: The lifetime of a local is either nested with other locals
3422: lifetimes or it does not overlap them.
3423:
3424: At @code{BEGIN}, @code{IF}, and @code{AHEAD} no code for locals stack
3425: pointer manipulation is generated. Between control structure words
3426: locals definitions can push locals onto the locals stack. @code{AGAIN}
3427: is the simplest of the other three control flow words. It has to
3428: restore the locals stack depth of the corresponding @code{BEGIN}
3429: before branching. The code looks like this:
3430: @format
3431: @code{lp+!#} current-locals-size @minus{} dest-locals-size
3432: @code{branch} <begin>
3433: @end format
3434:
3435: @code{UNTIL} is a little more complicated: If it branches back, it
3436: must adjust the stack just like @code{AGAIN}. But if it falls through,
3437: the locals stack must not be changed. The compiler generates the
3438: following code:
3439: @format
3440: @code{?branch-lp+!#} <begin> current-locals-size @minus{} dest-locals-size
3441: @end format
3442: The locals stack pointer is only adjusted if the branch is taken.
3443:
3444: @code{THEN} can produce somewhat inefficient code:
3445: @format
3446: @code{lp+!#} current-locals-size @minus{} orig-locals-size
3447: <orig target>:
3448: @code{lp+!#} orig-locals-size @minus{} new-locals-size
3449: @end format
3450: The second @code{lp+!#} adjusts the locals stack pointer from the
3451: level at the @var{orig} point to the level after the @code{THEN}. The
3452: first @code{lp+!#} adjusts the locals stack pointer from the current
3453: level to the level at the orig point, so the complete effect is an
3454: adjustment from the current level to the right level after the
3455: @code{THEN}.
3456:
3457: @cindex locals information on the control-flow stack
3458: @cindex control-flow stack items, locals information
3459: In a conventional Forth implementation a dest control-flow stack entry
3460: is just the target address and an orig entry is just the address to be
1.21 crook 3461: patched. Our locals implementation adds a word list to every orig or dest
1.1 anton 3462: item. It is the list of locals visible (or assumed visible) at the point
3463: described by the entry. Our implementation also adds a tag to identify
3464: the kind of entry, in particular to differentiate between live and dead
3465: (reachable and unreachable) orig entries.
3466:
1.21 crook 3467: A few unusual operations have to be performed on locals word lists:
1.1 anton 3468:
3469: doc-common-list
3470: doc-sub-list?
3471: doc-list-size
3472:
1.21 crook 3473: Several features of our locals word list implementation make these
3474: operations easy to implement: The locals word lists are organised as
1.1 anton 3475: linked lists; the tails of these lists are shared, if the lists
3476: contain some of the same locals; and the address of a name is greater
3477: than the address of the names behind it in the list.
3478:
3479: Another important implementation detail is the variable
3480: @code{dead-code}. It is used by @code{BEGIN} and @code{THEN} to
3481: determine if they can be reached directly or only through the branch
3482: that they resolve. @code{dead-code} is set by @code{UNREACHABLE},
3483: @code{AHEAD}, @code{EXIT} etc., and cleared at the start of a colon
3484: definition, by @code{BEGIN} and usually by @code{THEN}.
3485:
3486: Counted loops are similar to other loops in most respects, but
3487: @code{LEAVE} requires special attention: It performs basically the same
3488: service as @code{AHEAD}, but it does not create a control-flow stack
3489: entry. Therefore the information has to be stored elsewhere;
3490: traditionally, the information was stored in the target fields of the
3491: branches created by the @code{LEAVE}s, by organizing these fields into a
3492: linked list. Unfortunately, this clever trick does not provide enough
3493: space for storing our extended control flow information. Therefore, we
3494: introduce another stack, the leave stack. It contains the control-flow
3495: stack entries for all unresolved @code{LEAVE}s.
3496:
3497: Local names are kept until the end of the colon definition, even if
3498: they are no longer visible in any control-flow path. In a few cases
3499: this may lead to increased space needs for the locals name area, but
3500: usually less than reclaiming this space would cost in code size.
3501:
3502:
3503: @node ANS Forth locals, , Gforth locals, Locals
3504: @subsection ANS Forth locals
3505: @cindex locals, ANS Forth style
3506:
3507: The ANS Forth locals wordset does not define a syntax for locals, but
3508: words that make it possible to define various syntaxes. One of the
3509: possible syntaxes is a subset of the syntax we used in the Gforth locals
3510: wordset, i.e.:
3511:
3512: @example
3513: @{ local1 local2 ... -- comment @}
3514: @end example
1.23 ! crook 3515: @noindent
1.1 anton 3516: or
3517: @example
3518: @{ local1 local2 ... @}
3519: @end example
3520:
3521: The order of the locals corresponds to the order in a stack comment. The
3522: restrictions are:
3523:
3524: @itemize @bullet
3525: @item
3526: Locals can only be cell-sized values (no type specifiers are allowed).
3527: @item
3528: Locals can be defined only outside control structures.
3529: @item
3530: Locals can interfere with explicit usage of the return stack. For the
3531: exact (and long) rules, see the standard. If you don't use return stack
3532: accessing words in a definition using locals, you will be all right. The
3533: purpose of this rule is to make locals implementation on the return
3534: stack easier.
3535: @item
3536: The whole definition must be in one line.
3537: @end itemize
3538:
3539: Locals defined in this way behave like @code{VALUE}s (@xref{Simple
3540: Defining Words}). I.e., they are initialized from the stack. Using their
3541: name produces their value. Their value can be changed using @code{TO}.
3542:
3543: Since this syntax is supported by Gforth directly, you need not do
3544: anything to use it. If you want to port a program using this syntax to
3545: another ANS Forth system, use @file{compat/anslocal.fs} to implement the
3546: syntax on the other system.
3547:
3548: Note that a syntax shown in the standard, section A.13 looks
3549: similar, but is quite different in having the order of locals
3550: reversed. Beware!
3551:
1.23 ! crook 3552: The ANS Forth locals wordset itself consists of a word:
1.1 anton 3553:
3554: doc-(local)
3555:
1.23 ! crook 3556: The ANS Forth locals extension wordset defines a syntax using @code{locals|}, but it is so
1.1 anton 3557: awful that we strongly recommend not to use it. We have implemented this
3558: syntax to make porting to Gforth easy, but do not document it here. The
3559: problem with this syntax is that the locals are defined in an order
3560: reversed with respect to the standard stack comment notation, making
3561: programs harder to read, and easier to misread and miswrite. The only
3562: merit of this syntax is that it is easy to implement using the ANS Forth
3563: locals wordset.
3564:
1.21 crook 3565: @node Defining Words, The Text Interpreter, Locals, Words
1.1 anton 3566: @section Defining Words
3567: @cindex defining words
3568:
3569: @menu
3570: * Simple Defining Words::
3571: * Colon Definitions::
3572: * User-defined Defining Words::
3573: * Supplying names::
3574: * Interpretation and Compilation Semantics::
3575: @end menu
3576:
3577: @node Simple Defining Words, Colon Definitions, Defining Words, Defining Words
3578: @subsection Simple Defining Words
3579: @cindex simple defining words
3580: @cindex defining words, simple
3581:
3582: doc-constant
3583: doc-2constant
3584: doc-fconstant
3585: doc-variable
3586: doc-2variable
3587: doc-fvariable
3588: doc-create
3589: doc-user
3590: doc-value
3591: doc-to
3592: doc-defer
3593: doc-is
3594:
1.21 crook 3595: Definitions in ANS Standard Forth for @code{defer}, @code{<is>} and
3596: @code{[is]} are provided in @file{compat/defer.fs}. TODO - what do
3597: the two is words do?
3598:
1.1 anton 3599: @node Colon Definitions, User-defined Defining Words, Simple Defining Words, Defining Words
3600: @subsection Colon Definitions
3601: @cindex colon definitions
3602:
3603: @example
3604: : name ( ... -- ... )
3605: word1 word2 word3 ;
3606: @end example
3607:
3608: creates a word called @code{name}, that, upon execution, executes
3609: @code{word1 word2 word3}. @code{name} is a @dfn{(colon) definition}.
3610:
3611: The explanation above is somewhat superficial. @xref{Interpretation and
3612: Compilation Semantics} for an in-depth discussion of some of the issues
3613: involved.
3614:
3615: doc-:
3616: doc-;
3617:
3618: @node User-defined Defining Words, Supplying names, Colon Definitions, Defining Words
3619: @subsection User-defined Defining Words
3620: @cindex user-defined defining words
3621: @cindex defining words, user-defined
3622:
3623: You can create new defining words simply by wrapping defining-time code
3624: around existing defining words and putting the sequence in a colon
3625: definition.
3626:
1.21 crook 3627: @comment TODO example
3628:
1.1 anton 3629: @cindex @code{CREATE} ... @code{DOES>}
3630: If you want the words defined with your defining words to behave
3631: differently from words defined with standard defining words, you can
3632: write your defining word like this:
3633:
3634: @example
3635: : def-word ( "name" -- )
3636: Create @var{code1}
3637: DOES> ( ... -- ... )
3638: @var{code2} ;
3639:
3640: def-word name
3641: @end example
3642:
3643: Technically, this fragment defines a defining word @code{def-word}, and
3644: a word @code{name}; when you execute @code{name}, the address of the
3645: body of @code{name} is put on the data stack and @var{code2} is executed
3646: (the address of the body of @code{name} is the address @code{HERE}
1.21 crook 3647: returns immediately after the @code{CREATE}). The word @code{name} is
3648: sometimes called a @var{child} of @code{def-word}.
1.1 anton 3649:
3650: In other words, if you make the following definitions:
3651:
3652: @example
3653: : def-word1 ( "name" -- )
3654: Create @var{code1} ;
3655:
3656: : action1 ( ... -- ... )
3657: @var{code2} ;
3658:
3659: def-word name1
3660: @end example
3661:
3662: Using @code{name1 action1} is equivalent to using @code{name}.
3663:
3664: E.g., you can implement @code{Constant} in this way:
3665:
3666: @example
3667: : constant ( w "name" -- )
3668: create ,
3669: DOES> ( -- w )
3670: @@ ;
3671: @end example
3672:
1.21 crook 3673: @comment that is the classic example.. maybe it should be earlier. There
3674: @comment is a beautiful description of how this works and what it does in
3675: @comment the Forthwrite 100th edition.
3676:
1.1 anton 3677: When you create a constant with @code{5 constant five}, first a new word
3678: @code{five} is created, then the value 5 is laid down in the body of
3679: @code{five} with @code{,}. When @code{five} is invoked, the address of
3680: the body is put on the stack, and @code{@@} retrieves the value 5.
3681:
3682: @cindex stack effect of @code{DOES>}-parts
3683: @cindex @code{DOES>}-parts, stack effect
3684: In the example above the stack comment after the @code{DOES>} specifies
3685: the stack effect of the defined words, not the stack effect of the
3686: following code (the following code expects the address of the body on
3687: the top of stack, which is not reflected in the stack comment). This is
3688: the convention that I use and recommend (it clashes a bit with using
3689: locals declarations for stack effect specification, though).
3690:
3691: @subsubsection Applications of @code{CREATE..DOES>}
3692: @cindex @code{CREATE} ... @code{DOES>}, applications
3693:
3694: You may wonder how to use this feature. Here are some usage patterns:
3695:
3696: @cindex factoring similar colon definitions
3697: When you see a sequence of code occurring several times, and you can
3698: identify a meaning, you will factor it out as a colon definition. When
3699: you see similar colon definitions, you can factor them using
3700: @code{CREATE..DOES>}. E.g., an assembler usually defines several words
3701: that look very similar:
3702: @example
3703: : ori, ( reg-target reg-source n -- )
3704: 0 asm-reg-reg-imm ;
3705: : andi, ( reg-target reg-source n -- )
3706: 1 asm-reg-reg-imm ;
3707: @end example
3708:
1.21 crook 3709: @noindent
1.1 anton 3710: This could be factored with:
3711: @example
3712: : reg-reg-imm ( op-code -- )
1.21 crook 3713: CREATE ,
1.1 anton 3714: DOES> ( reg-target reg-source n -- )
3715: @@ asm-reg-reg-imm ;
3716:
3717: 0 reg-reg-imm ori,
3718: 1 reg-reg-imm andi,
3719: @end example
3720:
3721: @cindex currying
3722: Another view of @code{CREATE..DOES>} is to consider it as a crude way to
3723: supply a part of the parameters for a word (known as @dfn{currying} in
3724: the functional language community). E.g., @code{+} needs two
3725: parameters. Creating versions of @code{+} with one parameter fixed can
3726: be done like this:
3727: @example
3728: : curry+ ( n1 -- )
1.21 crook 3729: CREATE ,
1.1 anton 3730: DOES> ( n2 -- n1+n2 )
3731: @@ + ;
3732:
3733: 3 curry+ 3+
3734: -2 curry+ 2-
3735: @end example
3736:
3737: @subsubsection The gory details of @code{CREATE..DOES>}
3738: @cindex @code{CREATE} ... @code{DOES>}, details
3739:
3740: doc-does>
3741:
3742: @cindex @code{DOES>} in a separate definition
3743: This means that you need not use @code{CREATE} and @code{DOES>} in the
1.21 crook 3744: same definition; you can put the @code{DOES>}-part in a separate
1.1 anton 3745: definition. This allows us to, e.g., select among different DOES>-parts:
3746: @example
3747: : does1
3748: DOES> ( ... -- ... )
3749: ... ;
3750:
3751: : does2
3752: DOES> ( ... -- ... )
3753: ... ;
3754:
3755: : def-word ( ... -- ... )
3756: create ...
3757: IF
3758: does1
3759: ELSE
3760: does2
3761: ENDIF ;
3762: @end example
3763:
1.21 crook 3764: In this example, the selection of whether to use @code{does1} or
3765: @code{does2} is made at compile-time; at the time that the child word is
3766: @code{Create}d.
3767:
1.1 anton 3768: @cindex @code{DOES>} in interpretation state
3769: In a standard program you can apply a @code{DOES>}-part only if the last
3770: word was defined with @code{CREATE}. In Gforth, the @code{DOES>}-part
3771: will override the behaviour of the last word defined in any case. In a
3772: standard program, you can use @code{DOES>} only in a colon
3773: definition. In Gforth, you can also use it in interpretation state, in a
1.23 ! crook 3774: kind of one-shot mode; for example:
1.1 anton 3775: @example
3776: CREATE name ( ... -- ... )
3777: @var{initialization}
3778: DOES>
3779: @var{code} ;
3780: @end example
1.23 ! crook 3781:
! 3782: @noindent
! 3783: is equivalent to the standard:
1.1 anton 3784: @example
3785: :noname
3786: DOES>
3787: @var{code} ;
3788: CREATE name EXECUTE ( ... -- ... )
3789: @var{initialization}
3790: @end example
3791:
1.23 ! crook 3792: You can get the address of the body of a word with:
1.1 anton 3793:
3794: doc->body
3795:
3796: @node Supplying names, Interpretation and Compilation Semantics, User-defined Defining Words, Defining Words
3797: @subsection Supplying names for the defined words
3798: @cindex names for defined words
3799: @cindex defining words, name parameter
3800:
3801: @cindex defining words, name given in a string
3802: By default, defining words take the names for the defined words from the
3803: input stream. Sometimes you want to supply the name from a string. You
1.21 crook 3804: can do this with:
1.1 anton 3805:
3806: doc-nextname
3807:
1.21 crook 3808: For example:
1.1 anton 3809:
3810: @example
3811: s" foo" nextname create
3812: @end example
1.21 crook 3813: @noindent
3814: is equivalent to:
1.1 anton 3815: @example
3816: create foo
3817: @end example
3818:
3819: @cindex defining words without name
1.21 crook 3820: Sometimes you want to define an @var{anonymous word}; a word without a
3821: name. You can do this with:
3822:
3823: doc-:noname
3824:
3825: This leaves the execution token for the word on the stack after the
3826: closing @code{;}. Here's an example in which a deferred word is
3827: initialised with an @code{xt} from an anonymous colon definition:
3828: @example
3829: Defer deferred
3830: :noname ( ... -- ... )
3831: ... ;
3832: IS deferred
3833: @end example
3834:
3835: Gforth provides an alternative way of doing this, using two separate
3836: words:
1.1 anton 3837:
3838: doc-noname
3839: @cindex execution token of last defined word
1.21 crook 3840: doc-lastxt
1.1 anton 3841:
1.21 crook 3842: The previous example can be rewritten using @code{noname} and
3843: @code{lastxt}:
1.1 anton 3844:
3845: @example
3846: Defer deferred
3847: noname : ( ... -- ... )
3848: ... ;
3849: lastxt IS deferred
3850: @end example
3851:
3852: @code{lastxt} also works when the last word was not defined as
3853: @code{noname}.
3854:
3855:
3856: @node Interpretation and Compilation Semantics, , Supplying names, Defining Words
3857: @subsection Interpretation and Compilation Semantics
3858: @cindex semantics, interpretation and compilation
3859:
3860: @cindex interpretation semantics
3861: The @dfn{interpretation semantics} of a word are what the text
3862: interpreter does when it encounters the word in interpret state. It also
3863: appears in some other contexts, e.g., the execution token returned by
3864: @code{' @var{word}} identifies the interpretation semantics of
3865: @var{word} (in other words, @code{' @var{word} execute} is equivalent to
3866: interpret-state text interpretation of @code{@var{word}}).
3867:
3868: @cindex compilation semantics
3869: The @dfn{compilation semantics} of a word are what the text interpreter
3870: does when it encounters the word in compile state. It also appears in
3871: other contexts, e.g, @code{POSTPONE @var{word}} compiles@footnote{In
3872: standard terminology, ``appends to the current definition''.} the
3873: compilation semantics of @var{word}.
3874:
3875: @cindex execution semantics
3876: The standard also talks about @dfn{execution semantics}. They are used
3877: only for defining the interpretation and compilation semantics of many
3878: words. By default, the interpretation semantics of a word are to
3879: @code{execute} its execution semantics, and the compilation semantics of
3880: a word are to @code{compile,} its execution semantics.@footnote{In
3881: standard terminology: The default interpretation semantics are its
3882: execution semantics; the default compilation semantics are to append its
3883: execution semantics to the execution semantics of the current
3884: definition.}
3885:
1.21 crook 3886: @comment TODO expand, make it co-operate with new sections on text interpreter.
3887:
1.1 anton 3888: @cindex immediate words
3889: You can change the compilation semantics into @code{execute}ing the
3890: execution semantics with
3891:
3892: doc-immediate
3893:
3894: @cindex compile-only words
3895: You can remove the interpretation semantics of a word with
3896:
3897: doc-compile-only
3898: doc-restrict
3899:
3900: Note that ticking (@code{'}) compile-only words gives an error
3901: (``Interpreting a compile-only word'').
3902:
3903: Gforth also allows you to define words with arbitrary combinations of
3904: interpretation and compilation semantics.
3905:
3906: doc-interpret/compile:
3907:
3908: This feature was introduced for implementing @code{TO} and @code{S"}. I
3909: recommend that you do not define such words, as cute as they may be:
3910: they make it hard to get at both parts of the word in some contexts.
3911: E.g., assume you want to get an execution token for the compilation
3912: part. Instead, define two words, one that embodies the interpretation
1.15 anton 3913: part, and one that embodies the compilation part. Once you have done
3914: that, you can define a combined word with @code{interpret/compile:} for
3915: the convenience of your users.
1.1 anton 3916:
1.23 ! crook 3917: You also might try to with this feature, like this:
1.1 anton 3918:
1.23 ! crook 3919: You might try to use this feature to provide an optimizing
! 3920: implementation of the default compilation semantics of a word. For
! 3921: example, by defining:
1.1 anton 3922: @example
3923: :noname
3924: foo bar ;
3925: :noname
3926: POSTPONE foo POSTPONE bar ;
3927: interpret/compile: foobar
3928: @end example
3929:
1.21 crook 3930: @noindent
3931: as an optimizing version of:
1.15 anton 3932:
3933: @example
3934: : foobar
3935: foo bar ;
3936: @end example
3937:
3938: Unfortunately, this does not work correctly with @code{[compile]},
3939: because @code{[compile]} assumes that the compilation semantics of all
3940: @code{interpret/compile:} words are non-default. I.e., @code{[compile]
3941: foobar} would compile the compilation semantics for the optimizing
3942: @code{foobar}, whereas it would compile the interpretation semantics for
3943: the non-optimizing @code{foobar}.
1.1 anton 3944:
1.23 ! crook 3945: @cindex state-smart words (are a bad idea)
! 3946: Some people try to use @var{state-smart} words to emulate the feature provided
1.1 anton 3947: by @code{interpret/compile:} (words are state-smart if they check
3948: @code{STATE} during execution). E.g., they would try to code
3949: @code{foobar} like this:
3950:
3951: @example
3952: : foobar
3953: STATE @@
3954: IF ( compilation state )
3955: POSTPONE foo POSTPONE bar
3956: ELSE
3957: foo bar
3958: ENDIF ; immediate
3959: @end example
3960:
1.23 ! crook 3961: Although this works if @code{foobar} is only processed by the text
1.1 anton 3962: interpreter, it does not work in other contexts (like @code{'} or
3963: @code{POSTPONE}). E.g., @code{' foobar} will produce an execution token
3964: for a state-smart word, not for the interpretation semantics of the
3965: original @code{foobar}; when you execute this execution token (directly
3966: with @code{EXECUTE} or indirectly through @code{COMPILE,}) in compile
3967: state, the result will not be what you expected (i.e., it will not
3968: perform @code{foo bar}). State-smart words are a bad idea. Simply don't
1.21 crook 3969: write them@footnote{For a more detailed discussion of this topic, see
3970: @cite{@code{State}-smartness -- Why it is Evil and How to Exorcise it} by Anton
3971: Ertl; presented at EuroForth '98 and available from
3972: @url{http://www.complang.tuwien.ac.at/papers/}}!
1.1 anton 3973:
3974: @cindex defining words with arbitrary semantics combinations
3975: It is also possible to write defining words that define words with
1.15 anton 3976: arbitrary combinations of interpretation and compilation semantics. In
1.23 ! crook 3977: general, they look like this:
1.1 anton 3978:
3979: @example
3980: : def-word
3981: create-interpret/compile
3982: @var{code1}
3983: interpretation>
3984: @var{code2}
3985: <interpretation
3986: compilation>
3987: @var{code3}
1.21 crook 3988: <compilation ;
3989: @end example
3990:
3991: For a @var{word} defined with @code{def-word}, the interpretation
3992: semantics are to push the address of the body of @var{word} and perform
3993: @var{code2}, and the compilation semantics are to push the address of
3994: the body of @var{word} and perform @var{code3}. E.g., @code{constant}
3995: can also be defined like this (except that the defined constants don't
3996: behave correctly when @code{[compile]}d):
3997:
3998: @example
3999: : constant ( n "name" -- )
4000: create-interpret/compile
4001: ,
4002: interpretation> ( -- n )
4003: @@
4004: <interpretation
4005: compilation> ( compilation. -- ; run-time. -- n )
4006: @@ postpone literal
4007: <compilation ;
4008: @end example
4009:
4010: doc-create-interpret/compile
4011: doc-interpretation>
4012: doc-<interpretation
4013: doc-compilation>
4014: doc-<compilation
4015:
4016: Note that words defined with @code{interpret/compile:} and
4017: @code{create-interpret/compile} have an extended header structure that
4018: differs from other words; however, unless you try to access them with
4019: plain address arithmetic, you should not notice this. Words for
4020: accessing the header structure usually know how to deal with this; e.g.,
4021: @code{' word >body} also gives you the body of a word created with
4022: @code{create-interpret/compile}.
4023:
4024: @c ----------------------------------------------------------
4025: @node The Text Interpreter, Structures, Defining Words, Words
4026: @section The Text Interpreter
4027: @cindex interpreter - outer
4028: @cindex text interpreter
4029: @cindex outer interpreter
4030:
1.23 ! crook 4031: Intro blah.
! 4032:
! 4033: @comment TODO
1.21 crook 4034:
4035: doc->in
1.23 ! crook 4036: doc-tib
! 4037: doc-#tib
! 4038: doc-span
! 4039: doc-restore-input
! 4040: doc-save-input
! 4041: doc-source
! 4042: doc-source-id
1.21 crook 4043:
4044:
4045: @menu
4046: * Number Conversion::
4047: * Interpret/Compile states::
4048: * Literals::
4049: * Interpreter Directives::
4050: @end menu
4051:
1.23 ! crook 4052: @comment TODO
1.21 crook 4053:
4054: The text interpreter works on input one line at a time. Starting at
4055: the beginning of the line, it skips leading spaces (called
4056: "delimiters") then parses a string (a sequence of non-space
4057: characters) until it either reaches a space character or it
4058: reaches the end of the line. Having parsed a string, it then makes two
4059: attempts to do something with it:
4060:
4061: * It looks the string up in a dictionary of definitions. If the string
4062: is found in the dictionary, the string names a "definition" (also
4063: known as a "word") and the dictionary search will return an
4064: "Execution token" (xt) for the definition and some flags that show
4065: when the definition can be used legally. If the definition can be
4066: legally executed in "Interpret" mode then the text interpreter will
4067: use the xt to execute it, otherwise it will issue an error
4068: message. The dictionary is described in more detail in <blah>.
4069:
4070: * If the string is not found in the dictionary, the text interpreter
4071: attempts to treat it as a number in the current radix (base 10 after
4072: initial startup). If the string represents a legal number in the
4073: current radix, the number is pushed onto the appropriate parameter
4074: stack. Stacks are discussed in more detail in <blah>. Number
4075: conversion is described in more detail in <section about +, -
4076: numbers and different number formats>.
4077:
4078: If both of these attempts fail, the remainer of the input line is
4079: discarded and the text interpreter isses an error message. If one of
4080: these attempts succeeds, the text interpreter repeats the parsing
4081: process until the end of the line has been reached. At this point,
4082: it prints the status message " ok" and waits for more input.
4083:
4084: There are two important things to note about the behaviour of the text
4085: interpreter:
4086:
4087: * it processes each input string to completion before parsing
4088: additional characters from the input line.
4089:
4090: * it keeps track of its position in the input line using a variable
4091: (called >IN, pronounced "to-in"). The value of >IN can be modified
4092: by the execution of definitions in the input line. This means that
4093: definitions can "trick" the text interpreter either into skipping
4094: sections of the input line or into parsing a section of the
4095: input line more than once.
4096:
4097:
1.23 ! crook 4098: @node Number Conversion, Interpret/Compile states, The Text Interpreter, The Text Interpreter
! 4099: @subsection Number Conversion
! 4100: @cindex Number conversion
! 4101: @cindex double-cell numbers, input format
! 4102: @cindex input format for double-cell numbers
! 4103: @cindex single-cell numbers, input format
! 4104: @cindex input format for single-cell numbers
! 4105: @cindex floating-point numbers, input format
! 4106: @cindex input format for floating-point numbers
1.21 crook 4107:
1.23 ! crook 4108: If the text interpreter fails to find a particular string in the name
! 4109: dictionary, it attempts to convert it to a number using a set of rules.
1.21 crook 4110:
1.23 ! crook 4111: Let <digit> represent any character that is a legal digit in the current
! 4112: number base (for example, 0-9 when the number base is decimal or 0-9, A-F
! 4113: when the number base is hexadecimal).
1.21 crook 4114:
1.23 ! crook 4115: Let <decimal digit> represent any character in the range 0-9.
1.21 crook 4116:
1.23 ! crook 4117: @comment TODO need to extend the next defn to support fp format
! 4118: Let @{+ | -@} represent the optional presence of either a @code{+} or
! 4119: @code{-} character.
1.21 crook 4120:
1.23 ! crook 4121: Let * represent any number of instances of the previous character
! 4122: (including none).
1.21 crook 4123:
1.23 ! crook 4124: Let any other character represent itself.
1.21 crook 4125:
1.23 ! crook 4126: Now, the conversion rules are:
1.21 crook 4127:
1.23 ! crook 4128: @itemize @bullet
! 4129: @item
! 4130: A string of the form <digit><digit>* is treated as a single-precision
! 4131: (CELL-sized) positive integer. Examples are 0 123 6784532 32343212343456 42
! 4132: @item
! 4133: A string of the form -<digit><digit>* is treated as a single-precision
! 4134: (CELL-sized) negative integer, and is represented using 2's-complement
! 4135: arithmetic. Examples are -45 -5681 -0
! 4136: @item
! 4137: A string of the form <digit><digit>*.<digit>* is treated as a double-precision
! 4138: (double-CELL-sized) positive integer. Examples are 3465. 3.465 34.65
! 4139: (and note that these all represent the same number).
! 4140: @item
! 4141: A string of the form -<digit><digit>*.<digit>* is treated as a
! 4142: double-precision (double-CELL-sized) negative integer, and is
! 4143: represented using 2's-complement arithmetic. Examples are -3465. -3.465
! 4144: -34.65 (and note that these all represent the same number).
! 4145: @item
! 4146: A string of the form @{+ | -@}<decimal digit>@{.@}<decimal digit>*@{e | E@}@{+
! 4147: | -@}<decimal digit><decimal digit>* is treated as floating-point
! 4148: number. Examples are 1e0 1.e 1.e0 +1e+0 (which all represent the same
! 4149: number) +12.E-4
! 4150: @end itemize
1.21 crook 4151:
1.23 ! crook 4152: By default, the number base used for integer number conversion is given
! 4153: by the contents of a variable named @code{BASE}. Base 10 (decimal) is
! 4154: always used for floating-point number conversion.
1.21 crook 4155:
1.23 ! crook 4156: doc-base
! 4157: doc-hex
! 4158: doc-decimal
1.21 crook 4159:
1.23 ! crook 4160: @cindex '-prefix for character strings
! 4161: @cindex &-prefix for decimal numbers
! 4162: @cindex %-prefix for binary numbers
! 4163: @cindex $-prefix for hexadecimal numbers
! 4164: Gforth allows you to override the value of @code{BASE} by using a prefix
! 4165: before the first digit of an (integer) number. Four prefixes are
! 4166: supported:
1.21 crook 4167:
1.23 ! crook 4168: @itemize @bullet
! 4169: @item
! 4170: @code{&} -- decimal number
! 4171: @item
! 4172: @code{%} -- binary number
! 4173: @item
! 4174: @code{$} -- hexadecimal number
! 4175: @item
! 4176: @code{'} -- base 256 number
! 4177: @end itemize
1.21 crook 4178:
1.23 ! crook 4179: Here are some examples, with the equivalent decimal number shown after
! 4180: in braces:
1.21 crook 4181:
4182: -$41 (-65) %1001101 (205) %1001.0001 (145 - a double-precision number)
4183: 'AB (16706; ascii A is 65, ascii B is 66, number is 65*256 + 66)
4184: 'ab (24930; ascii a is 97, ascii B is 98, number is 97*256 + 98)
4185: &905 (905) $abc (2478) $ABC (2478)
4186:
4187: @cindex Number conversion - traps for the unwary
4188: Number conversion has a number of traps for the unwary:
4189:
4190: @itemize @bullet
4191: @item
4192: You cannot determine the current number base using the code sequence
4193: @code{BASE @@ .} -- the number base is always 10 in the current number
4194: base. Instead, use something like @code{BASE @@ DECIMAL DUP . BASE !}
4195: @item
4196: If the number base is set to a value greater than 14 (for example,
4197: hexadecimal), the number 123E4 is ambiguous; the conversion rules allow
4198: it to be intepreted as either a single-precision integer or a
4199: floating-point number (Gforth treats it as an integer). The ambiguity
4200: can be resolved by explicitly stating the sign of the mantissa and/or
4201: exponent: 123E+4 or +123E4 -- if the number base is decimal, no
4202: ambiguity arises; either representation will be treated as a
4203: floating-point number.
4204: @item
4205: There is a word @code{bin} but it does @var{not} set the number base!
4206: It is used to specify file types.
4207: @item
4208: ANS Forth Standard requires the @code{.} of a double-precision number to
4209: be the final character in the string. Allowing the @code{.} to be
4210: anywhere after the first digit is a Gforth extension.
4211: @item
4212: The number conversion process does not check for overflow.
4213: @item
4214: In Gforth, number conversion to floating-point numbers always use base
4215: 10, irrespective of the value of @code{BASE}. For the ANS Forth
4216: Standard, conversion to floating-point numbers whilst the value of
4217: @code{BASE} is not 10 is an ambiguous condition.
4218: @end itemize
4219:
4220:
4221: @node Interpret/Compile states, Literals, Number Conversion, The Text Interpreter
4222: @subsection Interpret/Compile states
4223: @cindex Interpret/Compile states
4224:
1.23 ! crook 4225: @comment TODO
! 4226: Intro blah.
1.21 crook 4227:
4228: doc-state
4229: doc-[
4230: doc-]
1.1 anton 4231:
4232:
1.21 crook 4233: @node Literals, Interpreter Directives, Interpret/Compile states, The Text Interpreter
4234: @subsection Literals
4235: @cindex Literals
4236:
1.23 ! crook 4237: @comment TODO
! 4238: Intro blah.
1.21 crook 4239:
4240: doc-literal
1.23 ! crook 4241: doc-]L
1.21 crook 4242: doc-2literal
4243: doc-fliteral
4244:
4245: @node Interpreter Directives, ,Literals, The Text Interpreter
4246: @subsection Interpreter Directives
4247: @cindex Interpreter Directives
4248:
4249: These words are usually used outside of definitions; for example, to
4250: control which parts of a source file are processed by the text
4251: interpreter. There are only a few ANS Forth Standard words, but Gforth
4252: supplements these with a rich set of immediate control structure words
4253: to compensate for the fact that the non-immediate versions can only be
4254: used in compile state (@pxref{Control Structures}).
4255:
4256: doc-[IF]
4257: doc-[ELSE]
4258: doc-[THEN]
4259: doc-[ENDIF]
4260:
4261: doc-[IFDEF]
4262: doc-[IFUNDEF]
4263:
4264: doc-[?DO]
4265: doc-[DO]
4266: doc-[FOR]
4267: doc-[LOOP]
4268: doc-[+LOOP]
4269: doc-[NEXT]
4270:
4271: doc-[BEGIN]
4272: doc-[UNTIL]
4273: doc-[AGAIN]
4274: doc-[WHILE]
4275: doc-[REPEAT]
1.1 anton 4276:
4277:
1.5 anton 4278: @c ----------------------------------------------------------
1.21 crook 4279: @node Structures, Object-oriented Forth, The Text Interpreter, Words
1.5 anton 4280: @section Structures
4281: @cindex structures
4282: @cindex records
4283:
4284: This section presents the structure package that comes with Gforth. A
1.21 crook 4285: version of the package implemented in ANS Standard Forth is available in
1.5 anton 4286: @file{compat/struct.fs}. This package was inspired by a posting on
4287: comp.lang.forth in 1989 (unfortunately I don't remember, by whom;
4288: possibly John Hayes). A version of this section has been published in
4289: ???. Marcel Hendrix provided helpful comments.
4290:
4291: @menu
4292: * Why explicit structure support?::
4293: * Structure Usage::
4294: * Structure Naming Convention::
4295: * Structure Implementation::
4296: * Structure Glossary::
4297: @end menu
4298:
4299: @node Why explicit structure support?, Structure Usage, Structures, Structures
4300: @subsection Why explicit structure support?
4301:
4302: @cindex address arithmetic for structures
4303: @cindex structures using address arithmetic
4304: If we want to use a structure containing several fields, we could simply
4305: reserve memory for it, and access the fields using address arithmetic
4306: (@pxref{Address arithmetic}). As an example, consider a structure with
4307: the following fields
4308:
4309: @table @code
4310: @item a
4311: is a float
4312: @item b
4313: is a cell
4314: @item c
4315: is a float
4316: @end table
4317:
4318: Given the (float-aligned) base address of the structure we get the
4319: address of the field
4320:
4321: @table @code
4322: @item a
4323: without doing anything further.
4324: @item b
4325: with @code{float+}
4326: @item c
4327: with @code{float+ cell+ faligned}
4328: @end table
4329:
4330: It is easy to see that this can become quite tiring.
4331:
4332: Moreover, it is not very readable, because seeing a
4333: @code{cell+} tells us neither which kind of structure is
4334: accessed nor what field is accessed; we have to somehow infer the kind
4335: of structure, and then look up in the documentation, which field of
4336: that structure corresponds to that offset.
4337:
4338: Finally, this kind of address arithmetic also causes maintenance
4339: troubles: If you add or delete a field somewhere in the middle of the
4340: structure, you have to find and change all computations for the fields
4341: afterwards.
4342:
4343: So, instead of using @code{cell+} and friends directly, how
4344: about storing the offsets in constants:
4345:
4346: @example
4347: 0 constant a-offset
4348: 0 float+ constant b-offset
4349: 0 float+ cell+ faligned c-offset
4350: @end example
4351:
4352: Now we can get the address of field @code{x} with @code{x-offset
4353: +}. This is much better in all respects. Of course, you still
4354: have to change all later offset definitions if you add a field. You can
4355: fix this by declaring the offsets in the following way:
4356:
4357: @example
4358: 0 constant a-offset
4359: a-offset float+ constant b-offset
4360: b-offset cell+ faligned constant c-offset
4361: @end example
4362:
1.23 ! crook 4363: Since we always use the offsets with @code{+}, we could use a defining
! 4364: word @code{cfield} that includes the @code{+} in the action of the
! 4365: defined word:
1.5 anton 4366:
4367: @example
4368: : cfield ( n "name" -- )
4369: create ,
4370: does> ( name execution: addr1 -- addr2 )
4371: @@ + ;
4372:
4373: 0 cfield a
4374: 0 a float+ cfield b
4375: 0 b cell+ faligned cfield c
4376: @end example
4377:
4378: Instead of @code{x-offset +}, we now simply write @code{x}.
4379:
4380: The structure field words now can be used quite nicely. However,
4381: their definition is still a bit cumbersome: We have to repeat the
4382: name, the information about size and alignment is distributed before
4383: and after the field definitions etc. The structure package presented
4384: here addresses these problems.
4385:
4386: @node Structure Usage, Structure Naming Convention, Why explicit structure support?, Structures
4387: @subsection Structure Usage
4388: @cindex structure usage
4389:
4390: @cindex @code{field} usage
4391: @cindex @code{struct} usage
4392: @cindex @code{end-struct} usage
1.23 ! crook 4393: You can define a structure for a (data-less) linked list with:
1.5 anton 4394: @example
4395: struct
4396: cell% field list-next
4397: end-struct list%
4398: @end example
4399:
4400: With the address of the list node on the stack, you can compute the
4401: address of the field that contains the address of the next node with
4402: @code{list-next}. E.g., you can determine the length of a list
4403: with:
4404:
4405: @example
4406: : list-length ( list -- n )
4407: \ "list" is a pointer to the first element of a linked list
4408: \ "n" is the length of the list
4409: 0 begin ( list1 n1 )
4410: over
4411: while ( list1 n1 )
4412: 1+ swap list-next @@ swap
4413: repeat
4414: nip ;
4415: @end example
4416:
4417: You can reserve memory for a list node in the dictionary with
4418: @code{list% %allot}, which leaves the address of the list node on the
4419: stack. For the equivalent allocation on the heap you can use @code{list%
4420: %alloc} (or, for an @code{allocate}-like stack effect (i.e., with ior),
1.23 ! crook 4421: use @code{list% %allocate}). You can get the the size of a list
! 4422: node with @code{list% %size} and its alignment with @code{list%
1.5 anton 4423: %alignment}.
4424:
4425: Note that in ANS Forth the body of a @code{create}d word is
4426: @code{aligned} but not necessarily @code{faligned};
1.23 ! crook 4427: therefore, if you do a:
1.5 anton 4428: @example
4429: create @emph{name} foo% %allot
4430: @end example
4431:
1.23 ! crook 4432: @noindent
1.5 anton 4433: then the memory alloted for @code{foo%} is
4434: guaranteed to start at the body of @code{@emph{name}} only if
4435: @code{foo%} contains only character, cell and double fields.
4436:
4437: @cindex strcutures containing structures
1.23 ! crook 4438: You can include a structure @code{foo%} as a field of
! 4439: another structure, like this:
1.5 anton 4440: @example
4441: struct
4442: ...
4443: foo% field ...
4444: ...
4445: end-struct ...
4446: @end example
4447:
4448: @cindex structure extension
4449: @cindex extended records
1.23 ! crook 4450: Instead of starting with an empty structure, you can extend an
1.5 anton 4451: existing structure. E.g., a plain linked list without data, as defined
4452: above, is hardly useful; You can extend it to a linked list of integers,
4453: like this:@footnote{This feature is also known as @emph{extended
4454: records}. It is the main innovation in the Oberon language; in other
4455: words, adding this feature to Modula-2 led Wirth to create a new
4456: language, write a new compiler etc. Adding this feature to Forth just
1.23 ! crook 4457: required a few lines of code.}
1.5 anton 4458:
4459: @example
4460: list%
4461: cell% field intlist-int
4462: end-struct intlist%
4463: @end example
4464:
4465: @code{intlist%} is a structure with two fields:
4466: @code{list-next} and @code{intlist-int}.
4467:
4468: @cindex structures containing arrays
4469: You can specify an array type containing @emph{n} elements of
4470: type @code{foo%} like this:
4471:
4472: @example
4473: foo% @emph{n} *
4474: @end example
4475:
4476: You can use this array type in any place where you can use a normal
4477: type, e.g., when defining a @code{field}, or with
4478: @code{%allot}.
4479:
4480: @cindex first field optimization
4481: The first field is at the base address of a structure and the word
4482: for this field (e.g., @code{list-next}) actually does not change
4483: the address on the stack. You may be tempted to leave it away in the
4484: interest of run-time and space efficiency. This is not necessary,
4485: because the structure package optimizes this case and compiling such
4486: words does not generate any code. So, in the interest of readability
4487: and maintainability you should include the word for the field when
4488: accessing the field.
4489:
4490: @node Structure Naming Convention, Structure Implementation, Structure Usage, Structures
4491: @subsection Structure Naming Convention
4492: @cindex structure naming conventions
4493:
4494: The field names that come to (my) mind are often quite generic, and,
4495: if used, would cause frequent name clashes. E.g., many structures
4496: probably contain a @code{counter} field. The structure names
4497: that come to (my) mind are often also the logical choice for the names
4498: of words that create such a structure.
4499:
4500: Therefore, I have adopted the following naming conventions:
4501:
4502: @itemize @bullet
4503: @cindex field naming convention
4504: @item
4505: The names of fields are of the form
4506: @code{@emph{struct}-@emph{field}}, where
4507: @code{@emph{struct}} is the basic name of the structure, and
4508: @code{@emph{field}} is the basic name of the field. You can
1.23 ! crook 4509: think of field words as converting the (address of the)
1.5 anton 4510: structure into the (address of the) field.
4511:
4512: @cindex structure naming convention
4513: @item
4514: The names of structures are of the form
4515: @code{@emph{struct}%}, where
4516: @code{@emph{struct}} is the basic name of the structure.
4517: @end itemize
4518:
4519: This naming convention does not work that well for fields of extended
4520: structures; e.g., the integer list structure has a field
4521: @code{intlist-int}, but has @code{list-next}, not
4522: @code{intlist-next}.
4523:
4524: @node Structure Implementation, Structure Glossary, Structure Naming Convention, Structures
4525: @subsection Structure Implementation
4526: @cindex structure implementation
4527: @cindex implementation of structures
4528:
4529: The central idea in the implementation is to pass the data about the
4530: structure being built on the stack, not in some global
4531: variable. Everything else falls into place naturally once this design
4532: decision is made.
4533:
4534: The type description on the stack is of the form @emph{align
4535: size}. Keeping the size on the top-of-stack makes dealing with arrays
4536: very simple.
4537:
1.21 crook 4538: @code{field} is a defining word that uses @code{Create}
4539: and @code{DOES>}. The body of the field contains the offset
1.23 ! crook 4540: of the field, and the normal @code{DOES>} action is simply:
1.5 anton 4541:
4542: @example
4543: @ +
4544: @end example
4545:
1.21 crook 4546: @noindent
1.5 anton 4547: i.e., add the offset to the address, giving the stack effect
1.23 ! crook 4548: @var{addr1 -- addr2} for a field.
1.5 anton 4549:
4550: @cindex first field optimization, implementation
4551: This simple structure is slightly complicated by the optimization
4552: for fields with offset 0, which requires a different
1.21 crook 4553: @code{DOES>}-part (because we cannot rely on there being
1.5 anton 4554: something on the stack if such a field is invoked during
1.21 crook 4555: compilation). Therefore, we put the different @code{DOES>}-parts
1.5 anton 4556: in separate words, and decide which one to invoke based on the
4557: offset. For a zero offset, the field is basically a noop; it is
4558: immediate, and therefore no code is generated when it is compiled.
4559:
4560: @node Structure Glossary, , Structure Implementation, Structures
4561: @subsection Structure Glossary
4562: @cindex structure glossary
4563:
4564: doc-%align
4565: doc-%alignment
4566: doc-%alloc
4567: doc-%allocate
4568: doc-%allot
4569: doc-cell%
4570: doc-char%
4571: doc-dfloat%
4572: doc-double%
4573: doc-end-struct
4574: doc-field
4575: doc-float%
4576: doc-nalign
4577: doc-sfloat%
4578: doc-%size
4579: doc-struct
4580:
4581: @c -------------------------------------------------------------
1.12 anton 4582: @node Object-oriented Forth, Tokens for Words, Structures, Words
4583: @section Object-oriented Forth
4584:
1.23 ! crook 4585: Gforth comes with three packets for object-oriented programming:
1.12 anton 4586: @file{objects.fs}, @file{oof.fs}, and @file{mini-oof.fs}; none of them
4587: is preloaded, so you have to @code{include} them before use. The most
4588: important differences between these packets (and others) are discussed
4589: in @ref{Comparison with other object models}. All packets are written
4590: in ANS Forth and can be used with any other ANS Forth.
4591:
4592: @menu
1.23 ! crook 4593: * Why object-oriented programming?::
! 4594: * Object-Oriented Terminology::
! 4595: * Objects::
! 4596: * OOF::
! 4597: * Mini-OOF::
1.5 anton 4598: * Comparison with other object models::
4599: @end menu
4600:
4601:
1.23 ! crook 4602: @node Why object-oriented programming?, Object-Oriented Terminology, , Object-oriented Forth
1.12 anton 4603: @subsubsection Why object-oriented programming?
1.5 anton 4604: @cindex object-oriented programming motivation
4605: @cindex motivation for object-oriented programming
4606:
4607: Often we have to deal with several data structures (@emph{objects}),
1.23 ! crook 4608: that have to be treated similarly in some respects, but differently in
! 4609: others. Graphical objects are the textbook example: circles, triangles,
! 4610: dinosaurs, icons, and others, and we may want to add more during program
! 4611: development. We want to apply some operations to any graphical object,
! 4612: e.g., @code{draw} for displaying it on the screen. However, @code{draw}
! 4613: has to do something different for every kind of object.
! 4614: @comment TODO add some other operations eg perimeter, area
! 4615: @comment and tie in to concrete examples later..
1.5 anton 4616:
4617: We could implement @code{draw} as a big @code{CASE}
4618: control structure that executes the appropriate code depending on the
4619: kind of object to be drawn. This would be not be very elegant, and,
4620: moreover, we would have to change @code{draw} every time we add
4621: a new kind of graphical object (say, a spaceship).
4622:
4623: What we would rather do is: When defining spaceships, we would tell
4624: the system: "Here's how you @code{draw} a spaceship; you figure
4625: out the rest."
4626:
4627: This is the problem that all systems solve that (rightfully) call
1.23 ! crook 4628: themselves object-oriented; the object-oriented packages presented here
! 4629: solve this problem (and not much else).
! 4630: @comment TODO ?list properties of oo systems.. oo vs o-based?
1.5 anton 4631:
1.23 ! crook 4632: @node Object-Oriented Terminology, Objects, Why object-oriented programming?, Object-oriented Forth
1.12 anton 4633: @subsubsection Object-Oriented Terminology
1.5 anton 4634: @cindex object-oriented terminology
4635: @cindex terminology for object-oriented programming
4636:
4637: This section is mainly for reference, so you don't have to understand
4638: all of it right away. The terminology is mainly Smalltalk-inspired. In
4639: short:
4640:
4641: @table @emph
4642: @cindex class
4643: @item class
4644: a data structure definition with some extras.
4645:
4646: @cindex object
4647: @item object
4648: an instance of the data structure described by the class definition.
4649:
4650: @cindex instance variables
4651: @item instance variables
4652: fields of the data structure.
4653:
4654: @cindex selector
4655: @cindex method selector
4656: @cindex virtual function
4657: @item selector
4658: (or @emph{method selector}) a word (e.g.,
1.23 ! crook 4659: @code{draw}) that performs an operation on a variety of data
1.5 anton 4660: structures (classes). A selector describes @emph{what} operation to
4661: perform. In C++ terminology: a (pure) virtual function.
4662:
4663: @cindex method
4664: @item method
4665: the concrete definition that performs the operation
4666: described by the selector for a specific class. A method specifies
4667: @emph{how} the operation is performed for a specific class.
4668:
4669: @cindex selector invocation
4670: @cindex message send
4671: @cindex invoking a selector
4672: @item selector invocation
4673: a call of a selector. One argument of the call (the TOS (top-of-stack))
4674: is used for determining which method is used. In Smalltalk terminology:
4675: a message (consisting of the selector and the other arguments) is sent
4676: to the object.
4677:
4678: @cindex receiving object
4679: @item receiving object
4680: the object used for determining the method executed by a selector
1.23 ! crook 4681: invocation. In the @file{objects.fs} model, it is the object that is on
! 4682: the TOS when the selector is invoked. (@emph{Receiving} comes from
! 4683: the Smalltalk @emph{message} terminology.)
1.5 anton 4684:
4685: @cindex child class
4686: @cindex parent class
4687: @cindex inheritance
4688: @item child class
4689: a class that has (@emph{inherits}) all properties (instance variables,
4690: selectors, methods) from a @emph{parent class}. In Smalltalk
4691: terminology: The subclass inherits from the superclass. In C++
4692: terminology: The derived class inherits from the base class.
4693:
4694: @end table
4695:
4696: @c If you wonder about the message sending terminology, it comes from
4697: @c a time when each object had it's own task and objects communicated via
4698: @c message passing; eventually the Smalltalk developers realized that
4699: @c they can do most things through simple (indirect) calls. They kept the
4700: @c terminology.
4701:
1.23 ! crook 4702:
! 4703: @node Objects, OOF, Object-Oriented Terminology, Object-oriented Forth
! 4704: @subsection The @file{objects.fs} model
! 4705: @cindex objects
! 4706: @cindex object-oriented programming
! 4707:
! 4708: @cindex @file{objects.fs}
! 4709: @cindex @file{oof.fs}
! 4710:
! 4711: This section describes the @file{objects.fs} packet. This material also has been published in @cite{Yet Another Forth Objects Package} by Anton Ertl and appeared in Forth Dimensions 19(2), pages 37--43 (@url{http://www.complang.tuwien.ac.at/forth/objects/objects.html}).
! 4712: @c McKewan's and Zsoter's packages
! 4713:
! 4714: This section assumes that you have read @ref{Structures}.
! 4715:
! 4716: The techniques on which this model is based have been used to implement
! 4717: the parser generator, Gray, and have also been used in Gforth for
! 4718: implementing the various flavours of word lists (hashed or not,
! 4719: case-sensitive or not, special-purpose word lists for locals etc.).
! 4720:
! 4721:
! 4722: @menu
! 4723: * Properties of the Objects model::
! 4724: * Basic Objects Usage::
! 4725: * The Objects base class::
! 4726: * Creating objects::
! 4727: * Object-Oriented Programming Style::
! 4728: * Class Binding::
! 4729: * Method conveniences::
! 4730: * Classes and Scoping::
! 4731: * Object Interfaces::
! 4732: * Objects Implementation::
! 4733: * Objects Glossary::
! 4734: @end menu
! 4735:
! 4736: Marcel Hendrix provided helpful comments on this section. Andras Zsoter
! 4737: and Bernd Paysan helped me with the related works section.
! 4738:
! 4739: @node Properties of the Objects model, Basic Objects Usage, Objects, Objects
! 4740: @subsubsection Properties of the @file{objects.fs} model
! 4741: @cindex @file{objects.fs} properties
! 4742:
! 4743: @itemize @bullet
! 4744: @item
! 4745: It is straightforward to pass objects on the stack. Passing
! 4746: selectors on the stack is a little less convenient, but possible.
! 4747:
! 4748: @item
! 4749: Objects are just data structures in memory, and are referenced by their
! 4750: address. You can create words for objects with normal defining words
! 4751: like @code{constant}. Likewise, there is no difference between instance
! 4752: variables that contain objects and those that contain other data.
! 4753:
! 4754: @item
! 4755: Late binding is efficient and easy to use.
! 4756:
! 4757: @item
! 4758: It avoids parsing, and thus avoids problems with state-smartness
! 4759: and reduced extensibility; for convenience there are a few parsing
! 4760: words, but they have non-parsing counterparts. There are also a few
! 4761: defining words that parse. This is hard to avoid, because all standard
! 4762: defining words parse (except @code{:noname}); however, such
! 4763: words are not as bad as many other parsing words, because they are not
! 4764: state-smart.
! 4765:
! 4766: @item
! 4767: It does not try to incorporate everything. It does a few things and does
! 4768: them well (IMO). In particular, this model was not designed to support
! 4769: information hiding (although it has features that may help); you can use
! 4770: a separate package for achieving this.
! 4771:
! 4772: @item
! 4773: It is layered; you don't have to learn and use all features to use this
! 4774: model. Only a few features are necessary (@xref{Basic Objects Usage},
! 4775: @xref{The Objects base class}, @xref{Creating objects}.), the others
! 4776: are optional and independent of each other.
! 4777:
! 4778: @item
! 4779: An implementation in ANS Forth is available.
! 4780:
! 4781: @end itemize
! 4782:
! 4783:
! 4784: @node Basic Objects Usage, The Objects base class, Properties of the Objects model, Objects
! 4785: @subsubsection Basic @file{objects.fs} Usage
1.5 anton 4786: @cindex basic objects usage
4787: @cindex objects, basic usage
4788:
4789: You can define a class for graphical objects like this:
4790:
4791: @cindex @code{class} usage
4792: @cindex @code{end-class} usage
4793: @cindex @code{selector} usage
4794: @example
4795: object class \ "object" is the parent class
4796: selector draw ( x y graphical -- )
4797: end-class graphical
4798: @end example
4799:
4800: This code defines a class @code{graphical} with an
4801: operation @code{draw}. We can perform the operation
4802: @code{draw} on any @code{graphical} object, e.g.:
4803:
4804: @example
4805: 100 100 t-rex draw
4806: @end example
4807:
1.23 ! crook 4808: @noindent
1.5 anton 4809: where @code{t-rex} is a word (say, a constant) that produces a
4810: graphical object.
4811:
1.23 ! crook 4812: @comment nac TODO add a 2nd operation eg perimeter.. and use for
! 4813: @comment a concrete example
! 4814:
1.5 anton 4815: @cindex abstract class
4816: How do we create a graphical object? With the present definitions,
4817: we cannot create a useful graphical object. The class
4818: @code{graphical} describes graphical objects in general, but not
4819: any concrete graphical object type (C++ users would call it an
4820: @emph{abstract class}); e.g., there is no method for the selector
4821: @code{draw} in the class @code{graphical}.
4822:
4823: For concrete graphical objects, we define child classes of the
4824: class @code{graphical}, e.g.:
4825:
4826: @cindex @code{overrides} usage
4827: @cindex @code{field} usage in class definition
4828: @example
4829: graphical class \ "graphical" is the parent class
4830: cell% field circle-radius
4831:
4832: :noname ( x y circle -- )
4833: circle-radius @@ draw-circle ;
4834: overrides draw
4835:
4836: :noname ( n-radius circle -- )
4837: circle-radius ! ;
4838: overrides construct
4839:
4840: end-class circle
4841: @end example
4842:
4843: Here we define a class @code{circle} as a child of @code{graphical},
1.23 ! crook 4844: with field @code{circle-radius} (which behaves just like a field
! 4845: (@pxref{Structures}); it defines (using @code{overrides}) new methods
! 4846: for the selectors @code{draw} and @code{construct} (@code{construct} is
! 4847: defined in @code{object}, the parent class of @code{graphical}).
1.5 anton 4848:
4849: Now we can create a circle on the heap (i.e.,
1.23 ! crook 4850: @code{allocate}d memory) with:
1.5 anton 4851:
4852: @cindex @code{heap-new} usage
4853: @example
4854: 50 circle heap-new constant my-circle
4855: @end example
4856:
1.23 ! crook 4857: @noindent
1.5 anton 4858: @code{heap-new} invokes @code{construct}, thus
4859: initializing the field @code{circle-radius} with 50. We can draw
1.23 ! crook 4860: this new circle at (100,100) with:
1.5 anton 4861:
4862: @example
4863: 100 100 my-circle draw
4864: @end example
4865:
4866: @cindex selector invocation, restrictions
4867: @cindex class definition, restrictions
1.23 ! crook 4868: Note: You can only invoke a selector if the object on the TOS
1.5 anton 4869: (the receiving object) belongs to the class where the selector was
4870: defined or one of its descendents; e.g., you can invoke
4871: @code{draw} only for objects belonging to @code{graphical}
4872: or its descendents (e.g., @code{circle}). Immediately before
4873: @code{end-class}, the search order has to be the same as
4874: immediately after @code{class}.
4875:
1.23 ! crook 4876: @node The Objects base class, Creating objects, Basic Objects Usage, Objects
! 4877: @subsubsection The @file{object.fs} base class
1.5 anton 4878: @cindex @code{object} class
4879:
4880: When you define a class, you have to specify a parent class. So how do
4881: you start defining classes? There is one class available from the start:
1.23 ! crook 4882: @code{object}. It is ancestor for all classes and so is the
1.5 anton 4883: only class that has no parent. It has two selectors: @code{construct}
4884: and @code{print}.
4885:
1.23 ! crook 4886: @node Creating objects, Object-Oriented Programming Style, The Objects base class, Objects
1.12 anton 4887: @subsubsection Creating objects
1.5 anton 4888: @cindex creating objects
4889: @cindex object creation
4890: @cindex object allocation options
4891:
4892: @cindex @code{heap-new} discussion
4893: @cindex @code{dict-new} discussion
4894: @cindex @code{construct} discussion
4895: You can create and initialize an object of a class on the heap with
4896: @code{heap-new} ( ... class -- object ) and in the dictionary
4897: (allocation with @code{allot}) with @code{dict-new} (
4898: ... class -- object ). Both words invoke @code{construct}, which
4899: consumes the stack items indicated by "..." above.
4900:
4901: @cindex @code{init-object} discussion
4902: @cindex @code{class-inst-size} discussion
4903: If you want to allocate memory for an object yourself, you can get its
4904: alignment and size with @code{class-inst-size 2@@} ( class --
4905: align size ). Once you have memory for an object, you can initialize
4906: it with @code{init-object} ( ... class object -- );
4907: @code{construct} does only a part of the necessary work.
4908:
4909: @node Object-Oriented Programming Style, Class Binding, Creating objects, Objects
1.12 anton 4910: @subsubsection Object-Oriented Programming Style
1.5 anton 4911: @cindex object-oriented programming style
4912:
4913: This section is not exhaustive.
4914:
4915: @cindex stack effects of selectors
4916: @cindex selectors and stack effects
4917: In general, it is a good idea to ensure that all methods for the
4918: same selector have the same stack effect: when you invoke a selector,
4919: you often have no idea which method will be invoked, so, unless all
4920: methods have the same stack effect, you will not know the stack effect
4921: of the selector invocation.
4922:
4923: One exception to this rule is methods for the selector
4924: @code{construct}. We know which method is invoked, because we
4925: specify the class to be constructed at the same place. Actually, I
4926: defined @code{construct} as a selector only to give the users a
4927: convenient way to specify initialization. The way it is used, a
4928: mechanism different from selector invocation would be more natural
4929: (but probably would take more code and more space to explain).
4930:
4931: @node Class Binding, Method conveniences, Object-Oriented Programming Style, Objects
1.12 anton 4932: @subsubsection Class Binding
1.5 anton 4933: @cindex class binding
4934: @cindex early binding
4935:
4936: @cindex late binding
4937: Normal selector invocations determine the method at run-time depending
1.23 ! crook 4938: on the class of the receiving object. This run-time selection is called
! 4939: @var{late binding}.
1.5 anton 4940:
1.23 ! crook 4941: Sometimes it's preferable to invoke a different method. For example,
! 4942: you might want to use the simple method for @code{print}ing
! 4943: @code{object}s instead of the possibly long-winded @code{print} method
! 4944: of the receiver class. You can achieve this by replacing the invocation
! 4945: of @code{print} with:
1.5 anton 4946:
4947: @cindex @code{[bind]} usage
4948: @example
4949: [bind] object print
4950: @end example
4951:
1.23 ! crook 4952: @noindent
! 4953: in compiled code or:
1.5 anton 4954:
4955: @cindex @code{bind} usage
4956: @example
4957: bind object print
4958: @end example
4959:
4960: @cindex class binding, alternative to
1.23 ! crook 4961: @noindent
1.5 anton 4962: in interpreted code. Alternatively, you can define the method with a
4963: name (e.g., @code{print-object}), and then invoke it through the
4964: name. Class binding is just a (often more convenient) way to achieve
4965: the same effect; it avoids name clutter and allows you to invoke
4966: methods directly without naming them first.
4967:
4968: @cindex superclass binding
4969: @cindex parent class binding
4970: A frequent use of class binding is this: When we define a method
4971: for a selector, we often want the method to do what the selector does
4972: in the parent class, and a little more. There is a special word for
4973: this purpose: @code{[parent]}; @code{[parent]
4974: @emph{selector}} is equivalent to @code{[bind] @emph{parent
4975: selector}}, where @code{@emph{parent}} is the parent
4976: class of the current class. E.g., a method definition might look like:
4977:
4978: @cindex @code{[parent]} usage
4979: @example
4980: :noname
4981: dup [parent] foo \ do parent's foo on the receiving object
4982: ... \ do some more
4983: ; overrides foo
4984: @end example
4985:
4986: @cindex class binding as optimization
4987: In @cite{Object-oriented programming in ANS Forth} (Forth Dimensions,
4988: March 1997), Andrew McKewan presents class binding as an optimization
4989: technique. I recommend not using it for this purpose unless you are in
4990: an emergency. Late binding is pretty fast with this model anyway, so the
4991: benefit of using class binding is small; the cost of using class binding
4992: where it is not appropriate is reduced maintainability.
4993:
4994: While we are at programming style questions: You should bind
4995: selectors only to ancestor classes of the receiving object. E.g., say,
4996: you know that the receiving object is of class @code{foo} or its
4997: descendents; then you should bind only to @code{foo} and its
4998: ancestors.
4999:
5000: @node Method conveniences, Classes and Scoping, Class Binding, Objects
1.12 anton 5001: @subsubsection Method conveniences
1.5 anton 5002: @cindex method conveniences
5003:
5004: In a method you usually access the receiving object pretty often. If
5005: you define the method as a plain colon definition (e.g., with
5006: @code{:noname}), you may have to do a lot of stack
5007: gymnastics. To avoid this, you can define the method with @code{m:
5008: ... ;m}. E.g., you could define the method for
5009: @code{draw}ing a @code{circle} with
5010:
5011: @cindex @code{this} usage
5012: @cindex @code{m:} usage
5013: @cindex @code{;m} usage
5014: @example
5015: m: ( x y circle -- )
5016: ( x y ) this circle-radius @@ draw-circle ;m
5017: @end example
5018:
5019: @cindex @code{exit} in @code{m: ... ;m}
5020: @cindex @code{exitm} discussion
5021: @cindex @code{catch} in @code{m: ... ;m}
5022: When this method is executed, the receiver object is removed from the
5023: stack; you can access it with @code{this} (admittedly, in this
5024: example the use of @code{m: ... ;m} offers no advantage). Note
5025: that I specify the stack effect for the whole method (i.e. including
5026: the receiver object), not just for the code between @code{m:}
5027: and @code{;m}. You cannot use @code{exit} in
5028: @code{m:...;m}; instead, use
5029: @code{exitm}.@footnote{Moreover, for any word that calls
5030: @code{catch} and was defined before loading
5031: @code{objects.fs}, you have to redefine it like I redefined
5032: @code{catch}: @code{: catch this >r catch r> to-this ;}}
5033:
5034: @cindex @code{inst-var} usage
5035: You will frequently use sequences of the form @code{this
5036: @emph{field}} (in the example above: @code{this
5037: circle-radius}). If you use the field only in this way, you can
5038: define it with @code{inst-var} and eliminate the
5039: @code{this} before the field name. E.g., the @code{circle}
5040: class above could also be defined with:
5041:
5042: @example
5043: graphical class
5044: cell% inst-var radius
5045:
5046: m: ( x y circle -- )
5047: radius @@ draw-circle ;m
5048: overrides draw
5049:
5050: m: ( n-radius circle -- )
5051: radius ! ;m
5052: overrides construct
5053:
5054: end-class circle
5055: @end example
5056:
5057: @code{radius} can only be used in @code{circle} and its
5058: descendent classes and inside @code{m:...;m}.
5059:
5060: @cindex @code{inst-value} usage
5061: You can also define fields with @code{inst-value}, which is
5062: to @code{inst-var} what @code{value} is to
5063: @code{variable}. You can change the value of such a field with
5064: @code{[to-inst]}. E.g., we could also define the class
5065: @code{circle} like this:
5066:
5067: @example
5068: graphical class
5069: inst-value radius
5070:
5071: m: ( x y circle -- )
5072: radius draw-circle ;m
5073: overrides draw
5074:
5075: m: ( n-radius circle -- )
5076: [to-inst] radius ;m
5077: overrides construct
5078:
5079: end-class circle
5080: @end example
5081:
5082:
5083: @node Classes and Scoping, Object Interfaces, Method conveniences, Objects
1.12 anton 5084: @subsubsection Classes and Scoping
1.5 anton 5085: @cindex classes and scoping
5086: @cindex scoping and classes
5087:
5088: Inheritance is frequent, unlike structure extension. This exacerbates
5089: the problem with the field name convention (@pxref{Structure Naming
5090: Convention}): One always has to remember in which class the field was
5091: originally defined; changing a part of the class structure would require
5092: changes for renaming in otherwise unaffected code.
5093:
5094: @cindex @code{inst-var} visibility
5095: @cindex @code{inst-value} visibility
5096: To solve this problem, I added a scoping mechanism (which was not in my
5097: original charter): A field defined with @code{inst-var} (or
5098: @code{inst-value}) is visible only in the class where it is defined and in
5099: the descendent classes of this class. Using such fields only makes
5100: sense in @code{m:}-defined methods in these classes anyway.
5101:
5102: This scoping mechanism allows us to use the unadorned field name,
5103: because name clashes with unrelated words become much less likely.
5104:
5105: @cindex @code{protected} discussion
5106: @cindex @code{private} discussion
5107: Once we have this mechanism, we can also use it for controlling the
5108: visibility of other words: All words defined after
5109: @code{protected} are visible only in the current class and its
5110: descendents. @code{public} restores the compilation
1.21 crook 5111: (i.e. @code{current}) word list that was in effect before. If you
1.5 anton 5112: have several @code{protected}s without an intervening
5113: @code{public} or @code{set-current}, @code{public}
1.21 crook 5114: will restore the compilation word list in effect before the first of
1.5 anton 5115: these @code{protected}s.
5116:
5117: @node Object Interfaces, Objects Implementation, Classes and Scoping, Objects
1.12 anton 5118: @subsubsection Object Interfaces
1.5 anton 5119: @cindex object interfaces
5120: @cindex interfaces for objects
5121:
5122: In this model you can only call selectors defined in the class of the
5123: receiving objects or in one of its ancestors. If you call a selector
5124: with a receiving object that is not in one of these classes, the
5125: result is undefined; if you are lucky, the program crashes
5126: immediately.
5127:
5128: @cindex selectors common to hardly-related classes
5129: Now consider the case when you want to have a selector (or several)
5130: available in two classes: You would have to add the selector to a
5131: common ancestor class, in the worst case to @code{object}. You
5132: may not want to do this, e.g., because someone else is responsible for
5133: this ancestor class.
5134:
5135: The solution for this problem is interfaces. An interface is a
5136: collection of selectors. If a class implements an interface, the
5137: selectors become available to the class and its descendents. A class
5138: can implement an unlimited number of interfaces. For the problem
5139: discussed above, we would define an interface for the selector(s), and
5140: both classes would implement the interface.
5141:
5142: As an example, consider an interface @code{storage} for
5143: writing objects to disk and getting them back, and a class
1.23 ! crook 5144: @code{foo} that implements it. The code would look like this:
1.5 anton 5145:
5146: @cindex @code{interface} usage
5147: @cindex @code{end-interface} usage
5148: @cindex @code{implementation} usage
5149: @example
5150: interface
5151: selector write ( file object -- )
5152: selector read1 ( file object -- )
5153: end-interface storage
5154:
5155: bar class
5156: storage implementation
5157:
5158: ... overrides write
5159: ... overrides read
5160: ...
5161: end-class foo
5162: @end example
5163:
1.23 ! crook 5164: @noindent
! 5165: (I would add a word @code{read} @var{( file -- object )} that uses
1.5 anton 5166: @code{read1} internally, but that's beyond the point illustrated
5167: here.)
5168:
5169: Note that you cannot use @code{protected} in an interface; and
5170: of course you cannot define fields.
5171:
5172: In the Neon model, all selectors are available for all classes;
5173: therefore it does not need interfaces. The price you pay in this model
5174: is slower late binding, and therefore, added complexity to avoid late
5175: binding.
5176:
1.23 ! crook 5177: @node Objects Implementation, Objects Glossary, Object Interfaces, Objects
1.12 anton 5178: @subsubsection @file{objects.fs} Implementation
1.5 anton 5179: @cindex @file{objects.fs} implementation
5180:
5181: @cindex @code{object-map} discussion
5182: An object is a piece of memory, like one of the data structures
5183: described with @code{struct...end-struct}. It has a field
5184: @code{object-map} that points to the method map for the object's
5185: class.
5186:
5187: @cindex method map
5188: @cindex virtual function table
5189: The @emph{method map}@footnote{This is Self terminology; in C++
5190: terminology: virtual function table.} is an array that contains the
1.23 ! crook 5191: execution tokens (@var{xt}s) of the methods for the object's class. Each
! 5192: selector contains an offset into a method map.
1.5 anton 5193:
5194: @cindex @code{selector} implementation, class
5195: @code{selector} is a defining word that uses
1.23 ! crook 5196: @code{CREATE} and @code{DOES>}. The body of the
1.5 anton 5197: selector contains the offset; the @code{does>} action for a
5198: class selector is, basically:
5199:
5200: @example
5201: ( object addr ) @@ over object-map @@ + @@ execute
5202: @end example
5203:
5204: Since @code{object-map} is the first field of the object, it
5205: does not generate any code. As you can see, calling a selector has a
5206: small, constant cost.
5207:
5208: @cindex @code{current-interface} discussion
5209: @cindex class implementation and representation
5210: A class is basically a @code{struct} combined with a method
5211: map. During the class definition the alignment and size of the class
5212: are passed on the stack, just as with @code{struct}s, so
5213: @code{field} can also be used for defining class
5214: fields. However, passing more items on the stack would be
5215: inconvenient, so @code{class} builds a data structure in memory,
5216: which is accessed through the variable
5217: @code{current-interface}. After its definition is complete, the
5218: class is represented on the stack by a pointer (e.g., as parameter for
5219: a child class definition).
5220:
1.23 ! crook 5221: A new class starts off with the alignment and size of its parent,
1.5 anton 5222: and a copy of the parent's method map. Defining new fields extends the
5223: size and alignment; likewise, defining new selectors extends the
1.23 ! crook 5224: method map. @code{overrides} just stores a new @var{xt} in the method
1.5 anton 5225: map at the offset given by the selector.
5226:
5227: @cindex class binding, implementation
1.23 ! crook 5228: Class binding just gets the @var{xt} at the offset given by the selector
1.5 anton 5229: from the class's method map and @code{compile,}s (in the case of
5230: @code{[bind]}) it.
5231:
5232: @cindex @code{this} implementation
5233: @cindex @code{catch} and @code{this}
5234: @cindex @code{this} and @code{catch}
5235: I implemented @code{this} as a @code{value}. At the
5236: start of an @code{m:...;m} method the old @code{this} is
5237: stored to the return stack and restored at the end; and the object on
5238: the TOS is stored @code{TO this}. This technique has one
5239: disadvantage: If the user does not leave the method via
5240: @code{;m}, but via @code{throw} or @code{exit},
5241: @code{this} is not restored (and @code{exit} may
5242: crash). To deal with the @code{throw} problem, I have redefined
5243: @code{catch} to save and restore @code{this}; the same
5244: should be done with any word that can catch an exception. As for
5245: @code{exit}, I simply forbid it (as a replacement, there is
5246: @code{exitm}).
5247:
5248: @cindex @code{inst-var} implementation
5249: @code{inst-var} is just the same as @code{field}, with
5250: a different @code{does>} action:
5251: @example
5252: @@ this +
5253: @end example
5254: Similar for @code{inst-value}.
5255:
5256: @cindex class scoping implementation
1.21 crook 5257: Each class also has a word list that contains the words defined with
1.5 anton 5258: @code{inst-var} and @code{inst-value}, and its protected
5259: words. It also has a pointer to its parent. @code{class} pushes
1.23 ! crook 5260: the word lists of the class and all its ancestors onto the search order stack,
1.5 anton 5261: and @code{end-class} drops them.
5262:
5263: @cindex interface implementation
5264: An interface is like a class without fields, parent and protected
5265: words; i.e., it just has a method map. If a class implements an
5266: interface, its method map contains a pointer to the method map of the
5267: interface. The positive offsets in the map are reserved for class
5268: methods, therefore interface map pointers have negative
5269: offsets. Interfaces have offsets that are unique throughout the
5270: system, unlike class selectors, whose offsets are only unique for the
5271: classes where the selector is available (invokable).
5272:
5273: This structure means that interface selectors have to perform one
5274: indirection more than class selectors to find their method. Their body
5275: contains the interface map pointer offset in the class method map, and
5276: the method offset in the interface method map. The
5277: @code{does>} action for an interface selector is, basically:
5278:
5279: @example
5280: ( object selector-body )
5281: 2dup selector-interface @@ ( object selector-body object interface-offset )
5282: swap object-map @@ + @@ ( object selector-body map )
5283: swap selector-offset @@ + @@ execute
5284: @end example
5285:
5286: where @code{object-map} and @code{selector-offset} are
5287: first fields and generate no code.
5288:
5289: As a concrete example, consider the following code:
5290:
5291: @example
5292: interface
5293: selector if1sel1
5294: selector if1sel2
5295: end-interface if1
5296:
5297: object class
5298: if1 implementation
5299: selector cl1sel1
5300: cell% inst-var cl1iv1
5301:
5302: ' m1 overrides construct
5303: ' m2 overrides if1sel1
5304: ' m3 overrides if1sel2
5305: ' m4 overrides cl1sel2
5306: end-class cl1
5307:
5308: create obj1 object dict-new drop
5309: create obj2 cl1 dict-new drop
5310: @end example
5311:
5312: The data structure created by this code (including the data structure
5313: for @code{object}) is shown in the <a
5314: href="objects-implementation.eps">figure</a>, assuming a cell size of 4.
1.23 ! crook 5315: @comment nac TODO add this diagram..
1.5 anton 5316:
1.23 ! crook 5317: @node Objects Glossary, , Objects Implementation, Objects
1.12 anton 5318: @subsubsection @file{objects.fs} Glossary
1.5 anton 5319: @cindex @file{objects.fs} Glossary
5320:
1.19 anton 5321: doc---objects-bind
5322: doc---objects-<bind>
5323: doc---objects-bind'
5324: doc---objects-[bind]
5325: doc---objects-class
5326: doc---objects-class->map
5327: doc---objects-class-inst-size
5328: doc---objects-class-override!
5329: doc---objects-construct
5330: doc---objects-current'
5331: doc---objects-[current]
5332: doc---objects-current-interface
5333: doc---objects-dict-new
5334: doc---objects-drop-order
5335: doc---objects-end-class
5336: doc---objects-end-class-noname
5337: doc---objects-end-interface
5338: doc---objects-end-interface-noname
5339: doc---objects-exitm
5340: doc---objects-heap-new
5341: doc---objects-implementation
5342: doc---objects-init-object
5343: doc---objects-inst-value
5344: doc---objects-inst-var
5345: doc---objects-interface
5346: doc---objects-;m
5347: doc---objects-m:
5348: doc---objects-method
5349: doc---objects-object
5350: doc---objects-overrides
5351: doc---objects-[parent]
5352: doc---objects-print
5353: doc---objects-protected
5354: doc---objects-public
5355: doc---objects-push-order
5356: doc---objects-selector
5357: doc---objects-this
5358: doc---objects-<to-inst>
5359: doc---objects-[to-inst]
5360: doc---objects-to-this
5361: doc---objects-xt-new
1.5 anton 5362:
5363: @c -------------------------------------------------------------
1.12 anton 5364: @node OOF, Mini-OOF, Objects, Object-oriented Forth
1.23 ! crook 5365: @subsection The @file{oof.fs} model
1.6 pazsan 5366: @cindex oof
5367: @cindex object-oriented programming
5368:
5369: @cindex @file{objects.fs}
5370: @cindex @file{oof.fs}
1.12 anton 5371:
1.23 ! crook 5372: This section describes the @file{oof.fs} packet.
1.6 pazsan 5373:
1.23 ! crook 5374: The packet described in this section has been used in bigFORTH since 1991, and
1.6 pazsan 5375: used for two large applications: a chromatographic system used to
5376: create new medicaments, and a graphic user interface library (MINOS).
5377:
1.12 anton 5378: You can find a description (in German) of @file{oof.fs} in @cite{Object
5379: oriented bigFORTH} by Bernd Paysan, published in @cite{Vierte Dimension}
5380: 10(2), 1994.
5381:
1.6 pazsan 5382: @menu
5383: * Properties of the OOF model::
5384: * Basic OOF Usage::
1.23 ! crook 5385: * The OOF base class::
1.7 pazsan 5386: * Class Declaration::
5387: * Class Implementation::
1.6 pazsan 5388: @end menu
5389:
1.12 anton 5390: @node Properties of the OOF model, Basic OOF Usage, OOF, OOF
1.23 ! crook 5391: @subsubsection Properties of the @file{oof.fs} model
1.6 pazsan 5392: @cindex @file{oof.fs} properties
5393:
5394: @itemize @bullet
5395: @item
5396: This model combines object oriented programming with information
5397: hiding. It helps you writing large application, where scoping is
5398: necessary, because it provides class-oriented scoping.
5399:
5400: @item
5401: Named objects, object pointers, and object arrays can be created,
5402: selector invocation uses the "object selector" syntax. Selector invocation
5403: to objects and/or selectors on the stack is a bit less convenient, but
5404: possible.
5405:
5406: @item
5407: Selector invocation and instance variable usage of the active object is
1.23 ! crook 5408: straightforward, since both make use of the active object.
1.6 pazsan 5409:
5410: @item
5411: Late binding is efficient and easy to use.
5412:
5413: @item
5414: State-smart objects parse selectors. However, extensibility is provided
5415: using a (parsing) selector @code{postpone} and a selector @code{'}.
5416:
5417: @item
5418: An implementation in ANS Forth is available.
5419:
5420: @end itemize
5421:
5422:
1.23 ! crook 5423: @node Basic OOF Usage, The OOF base class, Properties of the OOF model, OOF
! 5424: @subsubsection Basic @file{oof.fs} Usage
1.6 pazsan 5425: @cindex @file{oof.fs} usage
5426:
1.23 ! crook 5427: This section uses the same example as for @code{objects} (@pxref{Basic Objects Usage}).
1.6 pazsan 5428:
5429: You can define a class for graphical objects like this:
5430:
5431: @cindex @code{class} usage
5432: @cindex @code{class;} usage
5433: @cindex @code{method} usage
5434: @example
5435: object class graphical \ "object" is the parent class
5436: method draw ( x y graphical -- )
5437: class;
5438: @end example
5439:
5440: This code defines a class @code{graphical} with an
5441: operation @code{draw}. We can perform the operation
5442: @code{draw} on any @code{graphical} object, e.g.:
5443:
5444: @example
5445: 100 100 t-rex draw
5446: @end example
5447:
1.23 ! crook 5448: @noindent
1.6 pazsan 5449: where @code{t-rex} is an object or object pointer, created with e.g.
1.13 pazsan 5450: @code{graphical : t-rex}.
1.6 pazsan 5451:
5452: @cindex abstract class
5453: How do we create a graphical object? With the present definitions,
5454: we cannot create a useful graphical object. The class
5455: @code{graphical} describes graphical objects in general, but not
5456: any concrete graphical object type (C++ users would call it an
5457: @emph{abstract class}); e.g., there is no method for the selector
5458: @code{draw} in the class @code{graphical}.
5459:
5460: For concrete graphical objects, we define child classes of the
5461: class @code{graphical}, e.g.:
5462:
5463: @example
5464: graphical class circle \ "graphical" is the parent class
5465: cell var circle-radius
5466: how:
5467: : draw ( x y -- )
5468: circle-radius @@ draw-circle ;
5469:
5470: : init ( n-radius -- (
5471: circle-radius ! ;
5472: class;
5473: @end example
5474:
5475: Here we define a class @code{circle} as a child of @code{graphical},
5476: with a field @code{circle-radius}; it defines new methods for the
5477: selectors @code{draw} and @code{init} (@code{init} is defined in
5478: @code{object}, the parent class of @code{graphical}).
5479:
5480: Now we can create a circle in the dictionary with
5481:
5482: @example
5483: 50 circle : my-circle
5484: @end example
5485:
1.23 ! crook 5486: @noindent
1.6 pazsan 5487: @code{:} invokes @code{init}, thus initializing the field
5488: @code{circle-radius} with 50. We can draw this new circle at (100,100)
1.23 ! crook 5489: with:
1.6 pazsan 5490:
5491: @example
5492: 100 100 my-circle draw
5493: @end example
5494:
5495: @cindex selector invocation, restrictions
5496: @cindex class definition, restrictions
1.23 ! crook 5497: Note: You can only invoke a selector if the receiving object belongs to
1.6 pazsan 5498: the class where the selector was defined or one of its descendents;
5499: e.g., you can invoke @code{draw} only for objects belonging to
5500: @code{graphical} or its descendents (e.g., @code{circle}). The scoping
1.7 pazsan 5501: mechanism will check if you try to invoke a selector that is not
1.6 pazsan 5502: defined in this class hierarchy, so you'll get an error at compilation
5503: time.
5504:
5505:
1.23 ! crook 5506: @node The OOF base class, Class Declaration, Basic OOF Usage, OOF
! 5507: @subsubsection The @file{oof.fs} base class
1.6 pazsan 5508: @cindex @file{oof.fs} base class
5509:
5510: When you define a class, you have to specify a parent class. So how do
5511: you start defining classes? There is one class available from the start:
5512: @code{object}. You have to use it as ancestor for all classes. It is the
5513: only class that has no parent. Classes are also objects, except that
5514: they don't have instance variables; class manipulation such as
5515: inheritance or changing definitions of a class is handled through
5516: selectors of the class @code{object}.
5517:
5518: @code{object} provides a number of selectors:
5519:
5520: @itemize @bullet
5521: @item
5522: @code{class} for subclassing, @code{definitions} to add definitions
5523: later on, and @code{class?} to get type informations (is the class a
5524: subclass of the class passed on the stack?).
1.7 pazsan 5525: doc---object-class
5526: doc---object-definitions
5527: doc---object-class?
1.6 pazsan 5528:
5529: @item
1.23 ! crook 5530: @code{init} and @code{dispose} as constructor and destructor of the
1.6 pazsan 5531: object. @code{init} is invocated after the object's memory is allocated,
5532: while @code{dispose} also handles deallocation. Thus if you redefine
5533: @code{dispose}, you have to call the parent's dispose with @code{super
5534: dispose}, too.
1.7 pazsan 5535: doc---object-init
5536: doc---object-dispose
1.6 pazsan 5537:
5538: @item
1.7 pazsan 5539: @code{new}, @code{new[]}, @code{:}, @code{ptr}, @code{asptr}, and
5540: @code{[]} to create named and unnamed objects and object arrays or
5541: object pointers.
5542: doc---object-new
5543: doc---object-new[]
5544: doc---object-:
5545: doc---object-ptr
5546: doc---object-asptr
5547: doc---object-[]
1.6 pazsan 5548:
5549: @item
1.23 ! crook 5550: @code{::} and @code{super} for explicit scoping. You should use explicit
1.6 pazsan 5551: scoping only for super classes or classes with the same set of instance
1.23 ! crook 5552: variables. Explicitly-scoped selectors use early binding.
1.7 pazsan 5553: doc---object-::
5554: doc---object-super
1.6 pazsan 5555:
5556: @item
5557: @code{self} to get the address of the object
1.7 pazsan 5558: doc---object-self
1.6 pazsan 5559:
5560: @item
5561: @code{bind}, @code{bound}, @code{link}, and @code{is} to assign object
5562: pointers and instance defers.
1.7 pazsan 5563: doc---object-bind
5564: doc---object-bound
5565: doc---object-link
5566: doc---object-is
1.6 pazsan 5567:
5568: @item
5569: @code{'} to obtain selector tokens, @code{send} to invocate selectors
5570: form the stack, and @code{postpone} to generate selector invocation code.
1.7 pazsan 5571: doc---object-'
5572: doc---object-postpone
1.6 pazsan 5573:
5574: @item
5575: @code{with} and @code{endwith} to select the active object from the
1.23 ! crook 5576: stack, and enable its scope. Using @code{with} and @code{endwith}
! 5577: also allows you to create code using selector @code{postpone} without being
! 5578: trapped by the state-smart objects.
1.7 pazsan 5579: doc---object-with
5580: doc---object-endwith
1.6 pazsan 5581:
5582: @end itemize
5583:
1.23 ! crook 5584: @node Class Declaration, Class Implementation, The OOF base class, OOF
1.12 anton 5585: @subsubsection Class Declaration
1.7 pazsan 5586: @cindex class declaration
5587:
5588: @itemize @bullet
5589: @item
5590: Instance variables
5591: doc---oof-var
5592:
5593: @item
5594: Object pointers
5595: doc---oof-ptr
5596: doc---oof-asptr
5597:
5598: @item
5599: Instance defers
5600: doc---oof-defer
5601:
5602: @item
5603: Method selectors
5604: doc---oof-early
5605: doc---oof-method
5606:
5607: @item
1.23 ! crook 5608: Class-wide variables
1.7 pazsan 5609: doc---oof-static
5610:
5611: @item
5612: End declaration
5613: doc---oof-how:
5614: doc---oof-class;
5615:
5616: @end itemize
5617:
1.13 pazsan 5618: @c -------------------------------------------------------------
1.12 anton 5619: @node Class Implementation, , Class Declaration, OOF
5620: @subsubsection Class Implementation
1.7 pazsan 5621: @cindex class implementation
5622:
1.13 pazsan 5623: @c -------------------------------------------------------------
1.23 ! crook 5624: @node Mini-OOF, Comparison with other object models, OOF, Object-oriented Forth
! 5625: @subsection The @file{mini-oof.fs} model
1.8 pazsan 5626: @cindex mini-oof
5627:
5628: Gforth's third object oriented Forth package is a 12-liner. It uses a
1.23 ! crook 5629: mixture of the @file{object.fs} and the @file{oof.fs} syntax,
1.13 pazsan 5630: and reduces to the bare minimum of features. This is based on a posting
5631: of Bernd Paysan in comp.arch.
5632:
5633: @menu
1.23 ! crook 5634: * Basic Mini-OOF Usage::
1.13 pazsan 5635: * Mini-OOF Example::
1.20 pazsan 5636: * Mini-OOF Implementation::
1.13 pazsan 5637: @end menu
5638:
5639: @c -------------------------------------------------------------
1.23 ! crook 5640: @node Basic Mini-OOF Usage, Mini-OOF Example, , Mini-OOF
! 5641: @subsubsection Basic @file{mini-oof.fs} Usage
1.13 pazsan 5642: @cindex mini-oof usage
5643:
1.23 ! crook 5644: There is a base class (@code{class}, which allocates one cell
! 5645: for the object pointer) plus seven other words: to define a method, a
! 5646: variable, a class; to end a class, to resolve binding, to allocate an
! 5647: object and to compile a class method.
! 5648: @comment TODO better description of the last one
1.13 pazsan 5649:
1.23 ! crook 5650: doc-object
1.13 pazsan 5651: doc-method
5652: doc-var
5653: doc-class
5654: doc-end-class
5655: doc-defines
5656: doc-new
5657: doc-::
5658:
5659:
5660: @c -------------------------------------------------------------
1.23 ! crook 5661: @node Mini-OOF Example, Mini-OOF Implementation, Basic Mini-OOF Usage, Mini-OOF
1.13 pazsan 5662: @subsubsection Mini-OOF Example
5663: @cindex mini-oof example
5664:
5665: A short example shows how to use this package.
1.23 ! crook 5666: @comment nac TODO could flesh this out with some comments from the Forthwrite article
1.13 pazsan 5667:
5668: @example
5669: object class
5670: method init
5671: method draw
5672: end-class graphical
5673: @end example
5674:
5675: This code defines a class @code{graphical} with an
5676: operation @code{draw}. We can perform the operation
5677: @code{draw} on any @code{graphical} object, e.g.:
5678:
5679: @example
5680: 100 100 t-rex draw
5681: @end example
5682:
5683: where @code{t-rex} is an object or object pointer, created with e.g.
5684: @code{graphical new Constant t-rex}.
5685:
5686: For concrete graphical objects, we define child classes of the
5687: class @code{graphical}, e.g.:
1.8 pazsan 5688:
5689: @example
1.13 pazsan 5690: graphical class
5691: cell var circle-radius
5692: end-class circle \ "graphical" is the parent class
5693:
5694: :noname ( x y -- )
5695: circle-radius @@ draw-circle ; circle defines draw
5696: :noname ( r -- )
5697: circle-radius ! ; circle defines init
5698: @end example
5699:
5700: There is no implicit init method, so we have to define one. The creation
5701: code of the object now has to call init explicitely.
5702:
5703: @example
5704: circle new Constant my-circle
5705: 50 my-circle init
5706: @end example
5707:
5708: It is also possible to add a function to create named objects with
5709: automatic call of @code{init}, given that all objects have @code{init}
1.23 ! crook 5710: on the same place:
1.13 pazsan 5711:
5712: @example
5713: : new: ( .. o "name" -- )
5714: new dup Constant init ;
5715: 80 circle new: large-circle
5716: @end example
5717:
1.23 ! crook 5718: We can draw this new circle at (100,100) with:
1.13 pazsan 5719:
5720: @example
5721: 100 100 my-circle draw
1.8 pazsan 5722: @end example
5723:
1.20 pazsan 5724: @node Mini-OOF Implementation, , Mini-OOF Example, Mini-OOF
1.23 ! crook 5725: @subsubsection @file{mini-oof.fs} Implementation
1.20 pazsan 5726:
1.23 ! crook 5727: Object-oriented systems with late binding typically use a
1.20 pazsan 5728: "vtable"-approach: the first variable in each object is a pointer to a
1.23 ! crook 5729: table, which contains the methods as function pointers. The vtable
! 5730: may also contain other information.
1.20 pazsan 5731:
5732: So first, let's declare methods:
5733:
5734: @example
5735: : method ( m v -- m' v ) Create over , swap cell+ swap
5736: DOES> ( ... o -- ... ) @ over @ + @ execute ;
5737: @end example
5738:
5739: During method declaration, the number of methods and instance
5740: variables is on the stack (in address units). @code{method} creates
5741: one method and increments the method number. To execute a method, it
5742: takes the object, fetches the vtable pointer, adds the offset, and
1.23 ! crook 5743: executes the @var{xt} stored there. Each method takes the object it is
1.20 pazsan 5744: invoked from as top of stack parameter. The method itself should
5745: consume that object.
5746:
5747: Now, we also have to declare instance variables
5748:
5749: @example
5750: : var ( m v size -- m v' ) Create over , +
5751: DOES> ( o -- addr ) @ + ;
5752: @end example
5753:
1.23 ! crook 5754: As before, a word is created with the current offset. Instance
1.20 pazsan 5755: variables can have different sizes (cells, floats, doubles, chars), so
5756: all we do is take the size and add it to the offset. If your machine
5757: has alignment restrictions, put the proper @code{aligned} or
1.23 ! crook 5758: @code{faligned} before the variable, to adjust the variable
1.20 pazsan 5759: offset. That's why it is on the top of stack.
5760:
1.23 ! crook 5761: We need a starting point (the base object) and some syntactic sugar:
1.20 pazsan 5762:
5763: @example
5764: Create object 1 cells , 2 cells ,
5765: : class ( class -- class methods vars ) dup 2@ ;
5766: @end example
5767:
1.23 ! crook 5768: For inheritance, the vtable of the parent object has to be
! 5769: copied when a new, derived class is declared. This gives all the
1.20 pazsan 5770: methods of the parent class, which can be overridden, though.
5771:
5772: @example
5773: : end-class ( class methods vars -- )
5774: Create here >r , dup , 2 cells ?DO ['] noop , 1 cells +LOOP
5775: cell+ dup cell+ r> rot @ 2 cells /string move ;
5776: @end example
5777:
5778: The first line creates the vtable, initialized with
5779: @code{noop}s. The second line is the inheritance mechanism, it
5780: copies the xts from the parent vtable.
5781:
5782: We still have no way to define new methods, let's do that now:
5783:
5784: @example
5785: : defines ( xt class -- ) ' >body @ + ! ;
5786: @end example
5787:
5788: To allocate a new object, we need a word, too:
5789:
5790: @example
5791: : new ( class -- o ) here over @ allot swap over ! ;
5792: @end example
5793:
1.23 ! crook 5794: Sometimes derived classes want to access the method of the
! 5795: parent object. There are two ways to achieve this with Mini-OOF:
1.20 pazsan 5796: first, you could use named words, and second, you could look up the
5797: vtable of the parent object.
5798:
5799: @example
5800: : :: ( class "name" -- ) ' >body @ + @ compile, ;
5801: @end example
5802:
5803:
5804: Nothing can be more confusing than a good example, so here is
1.23 ! crook 5805: one. First let's declare a text object (called
1.20 pazsan 5806: @code{button}), that stores text and position:
5807:
5808: @example
5809: object class
5810: cell var text
5811: cell var len
5812: cell var x
5813: cell var y
5814: method init
5815: method draw
5816: end-class button
5817: @end example
5818:
1.23 ! crook 5819: @noindent
1.20 pazsan 5820: Now, implement the two methods, @code{draw} and @code{init}:
5821:
5822: @example
1.23 ! crook 5823: :noname ( o -- )
! 5824: >r r@ x @ r@ y @ at-xy r@ text @ r> len @ type ;
1.20 pazsan 5825: button defines draw
1.23 ! crook 5826: :noname ( addr u o -- )
! 5827: >r 0 r@ x ! 0 r@ y ! r@ len ! r> text ! ;
1.20 pazsan 5828: button defines init
5829: @end example
5830:
1.23 ! crook 5831: @noindent
! 5832: To demonstrate inheritance, we define a class @code{bold-button}, with no
1.20 pazsan 5833: new data and no new methods.
5834:
5835: @example
5836: button class
5837: end-class bold-button
5838:
5839: : bold 27 emit ." [1m" ;
5840: : normal 27 emit ." [0m" ;
5841:
1.23 ! crook 5842: @noindent
! 5843: The class @code{bold-button} has a different draw method to
! 5844: @code{button}, but the new method is defined in terms of the draw method
! 5845: for @code{button}:
! 5846:
1.20 pazsan 5847: :noname bold [ button :: draw ] normal ; bold-button defines draw
5848: @end example
5849:
1.23 ! crook 5850: @noindent
! 5851: Finally, create two objects and apply methods:
1.20 pazsan 5852:
5853: @example
5854: button new Constant foo
5855: s" thin foo" foo init
5856: page
5857: foo draw
5858: bold-button new Constant bar
5859: s" fat bar" bar init
5860: 1 bar y !
5861: bar draw
5862: @end example
5863:
1.23 ! crook 5864:
! 5865: @node Comparison with other object models, , Mini-OOF, Object-oriented Forth
! 5866: @subsubsection Comparison with other object models
! 5867: @cindex comparison of object models
! 5868: @cindex object models, comparison
! 5869:
! 5870: Many object-oriented Forth extensions have been proposed (@cite{A survey
! 5871: of object-oriented Forths} (SIGPLAN Notices, April 1996) by Bradford
! 5872: J. Rodriguez and W. F. S. Poehlman lists 17). This section discusses the
! 5873: relation of the object models described here to two well-known and two
! 5874: closely-related (by the use of method maps) models.
! 5875:
! 5876: @cindex Neon model
! 5877: The most popular model currently seems to be the Neon model (see
! 5878: @cite{Object-oriented programming in ANS Forth} (Forth Dimensions, March
! 5879: 1997) by Andrew McKewan) but this model has a number of limitations
! 5880: @footnote{A longer version of this critique can be
! 5881: found in @cite{On Standardizing Object-Oriented Forth Extensions} (Forth
! 5882: Dimensions, May 1997) by Anton Ertl.}:
! 5883:
! 5884: @itemize @bullet
! 5885: @item
! 5886: It uses a @code{@emph{selector
! 5887: object}} syntax, which makes it unnatural to pass objects on the
! 5888: stack.
! 5889:
! 5890: @item
! 5891: It requires that the selector parses the input stream (at
! 5892: compile time); this leads to reduced extensibility and to bugs that are+
! 5893: hard to find.
! 5894:
! 5895: @item
! 5896: It allows using every selector to every object;
! 5897: this eliminates the need for classes, but makes it harder to create
! 5898: efficient implementations.
! 5899: @end itemize
! 5900:
! 5901: @cindex Pountain's object-oriented model
! 5902: Another well-known publication is @cite{Object-Oriented Forth} (Academic
! 5903: Press, London, 1987) by Dick Pountain. However, it is not really about
! 5904: object-oriented programming, because it hardly deals with late
! 5905: binding. Instead, it focuses on features like information hiding and
! 5906: overloading that are characteristic of modular languages like Ada (83).
! 5907:
! 5908: @cindex Zsoter's object-oriented model
! 5909: In @cite{Does late binding have to be slow?} (Forth Dimensions 18(1) 1996, pages 31-35)
! 5910: Andras Zsoter describes a model that makes heavy use of an active object
! 5911: (like @code{this} in @file{objects.fs}): The active object is not only
! 5912: used for accessing all fields, but also specifies the receiving object
! 5913: of every selector invocation; you have to change the active object
! 5914: explicitly with @code{@{ ... @}}, whereas in @file{objects.fs} it
! 5915: changes more or less implicitly at @code{m: ... ;m}. Such a change at
! 5916: the method entry point is unnecessary with the Zsoter's model, because
! 5917: the receiving object is the active object already. On the other hand, the explicit
! 5918: change is absolutely necessary in that model, because otherwise no one
! 5919: could ever change the active object. An ANS Forth implementation of this
! 5920: model is available at @url{http://www.forth.org/fig/oopf.html}.
! 5921:
! 5922: @cindex @file{oof.fs}, differences to other models
! 5923: The @file{oof.fs} model combines information hiding and overloading
! 5924: resolution (by keeping names in various word lists) with object-oriented
! 5925: programming. It sets the active object implicitly on method entry, but
! 5926: also allows explicit changing (with @code{>o...o>} or with
! 5927: @code{with...endwith}). It uses parsing and state-smart objects and
! 5928: classes for resolving overloading and for early binding: the object or
! 5929: class parses the selector and determines the method from this. If the
! 5930: selector is not parsed by an object or class, it performs a call to the
! 5931: selector for the active object (late binding), like Zsoter's model.
! 5932: Fields are always accessed through the active object. The big
! 5933: disadvantage of this model is the parsing and the state-smartness, which
! 5934: reduces extensibility and increases the opportunities for subtle bugs;
! 5935: essentially, you are only safe if you never tick or @code{postpone} an
! 5936: object or class (Bernd disagrees, but I (Anton) am not convinced).
! 5937:
! 5938: @cindex @file{mini-oof.fs}, differences to other models
! 5939: The @file{mini-oof.fs} model is quite similar to a very stripped-down version of
! 5940: the @file{objects.fs} model, but syntactically it is a mixture of the @file{objects.fs} and
! 5941: @file{oof.fs} models.
! 5942:
! 5943:
! 5944:
1.6 pazsan 5945: @c -------------------------------------------------------------
1.21 crook 5946: @node Tokens for Words, Word Lists, Object-oriented Forth, Words
1.1 anton 5947: @section Tokens for Words
5948: @cindex tokens for words
5949:
5950: This chapter describes the creation and use of tokens that represent
5951: words on the stack (and in data space).
5952:
5953: Named words have interpretation and compilation semantics. Unnamed words
5954: just have execution semantics.
5955:
1.21 crook 5956: @comment TODO ?normally interpretation semantics are the execution semantics.
5957: @comment this should all be covered in earlier ss
5958:
1.1 anton 5959: @cindex execution token
5960: An @dfn{execution token} represents the execution semantics of an
5961: unnamed word. An execution token occupies one cell. As explained in
1.21 crook 5962: @ref{Supplying names}, the execution token of the last word
5963: defined can be produced with @code{lastxt}.
1.1 anton 5964:
1.21 crook 5965: You can perform the semantics represented by an execution token with:
1.1 anton 5966: doc-execute
1.21 crook 5967: You can compile the word with:
1.1 anton 5968: doc-compile,
5969:
5970: @cindex code field address
5971: @cindex CFA
5972: In Gforth, the abstract data type @emph{execution token} is implemented
5973: as CFA (code field address).
1.21 crook 5974: @comment TODO note that the standard does not say what it represents..
5975: @comment and you cannot necessarily compile it in all Forths (eg native
5976: @comment compilers?).
1.1 anton 5977:
5978: The interpretation semantics of a named word are also represented by an
5979: execution token. You can get it with
5980:
5981: doc-[']
5982: doc-'
5983:
5984: For literals, you use @code{'} in interpreted code and @code{[']} in
5985: compiled code. Gforth's @code{'} and @code{[']} behave somewhat unusual
5986: by complaining about compile-only words. To get an execution token for a
5987: compiling word @var{X}, use @code{COMP' @var{X} drop} or @code{[COMP']
5988: @var{X} drop}.
5989:
5990: @cindex compilation token
5991: The compilation semantics are represented by a @dfn{compilation token}
5992: consisting of two cells: @var{w xt}. The top cell @var{xt} is an
5993: execution token. The compilation semantics represented by the
5994: compilation token can be performed with @code{execute}, which consumes
5995: the whole compilation token, with an additional stack effect determined
5996: by the represented compilation semantics.
5997:
5998: doc-[comp']
5999: doc-comp'
6000:
6001: You can compile the compilation semantics with @code{postpone,}. I.e.,
6002: @code{COMP' @var{word} POSTPONE,} is equivalent to @code{POSTPONE
6003: @var{word}}.
6004:
6005: doc-postpone,
6006:
6007: At present, the @var{w} part of a compilation token is an execution
6008: token, and the @var{xt} part represents either @code{execute} or
6009: @code{compile,}. However, don't rely on that knowledge, unless necessary;
6010: we may introduce unusual compilation tokens in the future (e.g.,
6011: compilation tokens representing the compilation semantics of literals).
6012:
6013: @cindex name token
6014: @cindex name field address
6015: @cindex NFA
6016: Named words are also represented by the @dfn{name token}. The abstract
6017: data type @emph{name token} is implemented as NFA (name field address).
6018:
6019: doc-find-name
6020: doc-name>int
6021: doc-name?int
6022: doc-name>comp
6023: doc-name>string
6024:
1.21 crook 6025: @node Word Lists, Environmental Queries, Tokens for Words, Words
6026: @section Word Lists
6027: @cindex word lists
6028: @cindex name dictionary
6029:
6030: @cindex wid
6031: All definitions other than those created by @code{:noname} have an entry
6032: in the name dictionary. The name dictionary is fragmented into a number
6033: of parts, called @var{word lists}. A word list is identified by a
6034: cell-sized word list identifier (@var{wid}) in much the same way as a
6035: file is identified by a file handle. The numerical value of the wid has
6036: no (portable) meaning, and might change from session to session.
6037:
6038: @cindex compilation word list
6039: At any one time, a single word list is defined as the word list to which
6040: all new definitions will be added -- this is called the @var{compilation
6041: word list}. When Gforth is started, the compilation word list is the
6042: word list called @code{FORTH-WORDLIST}.
6043:
6044: @cindex search order stack
6045: Forth maintains a stack of word lists, representing the @var{search
6046: order}. When the name dictionary is searched (for example, when
6047: attempting to find a word's execution token during compilation), only
6048: those word lists that are currently in the search order are
6049: searched. The most recently-defined word in the word list at the top of
6050: the word list stack is searched first, and the search proceeds until
6051: either the word is located or the oldest definition in the word list at
6052: the bottom of the stack is reached. Definitions of the word may exist in
6053: more than one word lists; the search order determines which version will
6054: be found.
6055:
6056: The ANS Forth Standard "Search order" word set is intended to provide a
6057: set of low-level tools that allow various different schemes to be
6058: implemented. Gforth provides @code{vocabulary}, a traditional Forth
6059: word. @file{compat/vocabulary.fs} provides an implementation in ANS
6060: Standard Forth.
6061:
6062: TODO: locals section refers to here, saying that every word list (aka
6063: vocabulary) has its own methods for searching etc. Need to document that.
6064:
6065: doc-forth-wordlist
6066: doc-definitions
6067: doc-get-current
6068: doc-set-current
6069:
6070: @comment TODO when a defn (like set-order) is instanced twice, the second instance gets documented.
6071: @comment In general that might be fine, but in this example (search.fs) the second instance is an
6072: @comment alias, so it would not naturally have documentation
6073:
6074: doc-get-order
6075: doc-set-order
6076: doc-wordlist
6077: doc-also
6078: doc-forth
6079: doc-only
6080: doc-order
6081: doc-previous
6082:
6083: doc-find
6084: doc-search-wordlist
6085:
6086: doc-words
6087: doc-vlist
6088:
6089: doc-mappedwordlist
6090: doc-root
6091: doc-vocabulary
6092: doc-seal
6093: doc-vocs
6094: doc-current
6095: doc-context
6096:
6097: @menu
6098: * Why use word lists?::
6099: * Word list examples::
6100: @end menu
6101:
6102: @node Why use word lists?, Word list examples, Word Lists, Word Lists
6103: @subsection Why use word lists?
6104: @cindex word lists - why use them?
6105:
6106: There are several reasons for using multiple word lists:
6107:
6108: @itemize @bullet
6109: @item
6110: To improve compilation speed by reducing the number of name dictionary
6111: entries that must be searched. This is achieved by creating a new
6112: word list that contains all of the definitions that are used in the
6113: definition of a Forth system but which would not usually be used by
6114: programs running on that system. That word list would be on the search
6115: list when the Forth system was compiled but would be removed from the
6116: search list for normal operation. This can be a useful technique for
6117: low-performance systems (for example, 8-bit processors in embedded
6118: systems) but is unlikely to be necessary in high-performance desktop
6119: systems.
6120: @item
6121: To prevent a set of words from being used outside the context in which
6122: they are valid. Two classic examples of this are an integrated editor
6123: (all of the edit commands are defined in a separate word list; the
6124: search order is set to the editor word list when the editor is invoked;
6125: the old search order is restored when the editor is terminated) and an
6126: integrated assembler (the op-codes for the machine are defined in a
6127: separate word list which is used when a @code{CODE} word is defined).
6128: @item
6129: To prevent a name-space clash between multiple definitions with the same
6130: name. For example, when building a cross-compiler you might have a word
6131: @code{IF} that generates conditional code for your target system. By
6132: placing this definition in a different word list you can control whether
6133: the host system's @code{IF} or the target system's @code{IF} get used in
6134: any particular context by controlling the order of the word lists on the
6135: search order stack.
6136: @end itemize
6137:
6138: @node Word list examples, ,Why use word lists?, Word Lists
6139: @subsection Word list examples
6140: @cindex word lists - examples
6141:
6142: Here is an example of creating and using a new wordlist using ANS
6143: Standard words:
6144:
6145: @example
6146: wordlist constant my-new-words-wordlist
6147: : my-new-words get-order nip my-new-words-wordlist swap set-order ;
6148:
6149: \ add it to the search order
6150: also my-new-words
6151:
6152: \ alternatively, add it to the search order and make it
6153: \ the compilation word list
6154: also my-new-words definitions
6155: \ type "order" to see the problem
6156: @end example
6157:
6158: The problem with this example is that @code{order} has no way to
6159: associate the name @code{my-new-words} with the wid of the word list (in
6160: Gforth, @code{order} and @code{vocs} will display @code{???} for a wid
6161: that has no associated name). There is no Standard way of associating a
6162: name with a wid.
6163:
6164: In Gforth, this example can be re-coded using @code{vocabulary}, which
6165: associates a name with a wid:
6166:
6167: @example
6168: vocabulary my-new-words
6169:
6170: \ add it to the search order
6171: my-new-words
6172:
6173: \ alternatively, add it to the search order and make it
6174: \ the compilation word list
6175: my-new-words definitions
6176: \ type "order" to see that the problem is solved
6177: @end example
6178:
6179:
6180: @node Environmental Queries, Files, Word Lists, Words
6181: @section Environmental Queries
6182: @cindex environmental queries
6183: @comment TODO more index entries
6184:
6185: The ANS Standard introduced the idea of "environmental queries" as a way
6186: for a program running on a system to determine certain characteristics of the system.
6187: The Standard specifies a number of strings that might be recognised by a system.
6188:
6189: The Standard requires that the name space used for environmental queries
6190: be distinct from the name space used for definitions.
6191:
6192: Typically, environmental queries are supported by creating a set of
6193: definitions in a word set that is @var{only} used during environmental
6194: queries; that is what Gforth does. There is no Standard way of adding
6195: definitions to the set of recognised environmental queries, but any
6196: implementation that supports the loading of optional word sets must have
6197: some mechanism for doing this (after loading the word set, the
6198: associated environmental query string must return @code{true}). In
6199: Gforth, the word set used to honour environmental queries can be
6200: manipulated just like any other word set.
6201:
6202: doc-environment?
6203: doc-environment-wordlist
6204:
6205: doc-gforth
6206: doc-os-class
6207:
6208: Note that, whilst the documentation for (eg) @code{gforth} shows it
6209: returning two items on the stack, querying it using @code{environment?}
6210: will return an additional item; the @code{true} flag that shows that the
6211: string was recognised.
1.1 anton 6212:
1.21 crook 6213: TODO Document the standard strings or note where they are documented herein
6214:
6215: Here are some examples of using environmental queries:
6216:
6217: @example
6218: s" address-unit-bits" environment? 0=
6219: [IF]
6220: cr .( environmental attribute address-units-bits unknown... ) cr
6221: [THEN]
6222:
6223: s" block" environment? [IF] DROP include block.fs [THEN]
6224:
6225: s" gforth" environment? [IF] 2DROP include compat/vocabulary.fs [THEN]
6226:
6227: s" gforth" environment? [IF] .( Gforth version ) TYPE [ELSE] .( Not Gforth..) [THEN]
6228:
6229: @end example
6230:
6231:
6232: Here is an example of adding a definition to the environment word list:
6233:
6234: @example
6235: get-current environment-wordlist set-current
6236: true constant block
6237: true constant block-ext
6238: set-current
6239: @end example
6240:
6241: You can see what definitions are in the environment word list like this:
6242:
6243: @example
6244: get-order 1+ environment-wordlist swap set-order words previous
6245: @end example
6246:
6247:
6248:
6249: @node Files, Including Files, Environmental Queries, Words
1.1 anton 6250: @section Files
6251:
1.20 pazsan 6252: This chapter describes how to operate on files from Forth.
6253:
1.21 crook 6254: Files are opened/created by name and type. The following types are
6255: recognised:
1.20 pazsan 6256:
6257: doc-r/o
6258: doc-r/w
6259: doc-w/o
6260: doc-bin
6261:
1.21 crook 6262: When a file is opened/created, it returns a file identifier,
6263: @var{wfileid} that is used for all other file commands. All file
6264: commands also return a status value, @var{wior}, that is 0 for a
6265: successful operation and an implementation-defined non-zero value in the
6266: case of an error.
1.20 pazsan 6267:
6268: doc-open-file
6269: doc-create-file
6270:
6271: doc-close-file
6272: doc-delete-file
6273: doc-rename-file
6274: doc-read-file
6275: doc-read-line
6276: doc-write-file
1.21 crook 6277: doc-write-line
1.20 pazsan 6278: doc-emit-file
6279: doc-flush-file
6280:
6281: doc-file-status
6282: doc-file-position
6283: doc-reposition-file
6284: doc-file-size
6285: doc-resize-file
6286:
1.12 anton 6287: @node Including Files, Blocks, Files, Words
6288: @section Including Files
6289: @cindex including files
6290:
6291: @menu
6292: * Words for Including::
6293: * Search Path::
1.21 crook 6294: * Forth Search Paths::
1.12 anton 6295: * General Search Paths::
6296: @end menu
6297:
6298: @node Words for Including, Search Path, Including Files, Including Files
6299: @subsection Words for Including
6300:
6301: doc-include-file
6302: doc-included
6303: doc-include
6304:
6305: Usually you want to include a file only if it is not included already
6306: (by, say, another source file):
1.21 crook 6307: @comment TODO describe what happens on error. Describes how the require
6308: @comment stuff works and describe how to clear/reset the history (eg
6309: @comment for debug). Might want to include that in the MARKER example.
1.12 anton 6310:
6311: doc-required
6312: doc-require
6313: doc-needs
6314:
1.21 crook 6315: A definition in ANS Standard Forth for @code{required} is provided in
6316: @file{compat/required.fs}.
6317:
1.12 anton 6318: @cindex stack effect of included files
6319: @cindex including files, stack effect
6320: I recommend that you write your source files such that interpreting them
6321: does not change the stack. This allows using these files with
6322: @code{required} and friends without complications. E.g.,
6323:
6324: @example
6325: 1 require foo.fs drop
6326: @end example
6327:
1.21 crook 6328: @node Search Path, Forth Search Paths, Words for Including, Including Files
1.12 anton 6329: @subsection Search Path
6330: @cindex path for @code{included}
6331: @cindex file search path
6332: @cindex include search path
6333: @cindex search path for files
6334:
1.21 crook 6335: @comment what uses these search paths.. just inc;lude and friends?
1.12 anton 6336: If you specify an absolute filename (i.e., a filename starting with
6337: @file{/} or @file{~}, or with @file{:} in the second position (as in
6338: @samp{C:...})) for @code{included} and friends, that file is included
6339: just as you would expect.
6340:
6341: For relative filenames, Gforth uses a search path similar to Forth's
1.21 crook 6342: search order (@pxref{Word Lists}). It tries to find the given filename in
1.12 anton 6343: the directories present in the path, and includes the first one it
6344: finds.
6345:
6346: If the search path contains the directory @file{.} (as it should), this
6347: refers to the directory that the present file was @code{included}
6348: from. This allows files to include other files relative to their own
6349: position (irrespective of the current working directory or the absolute
6350: position). This feature is essential for libraries consisting of
6351: several files, where a file may include other files from the library.
6352: It corresponds to @code{#include "..."} in C. If the current input
6353: source is not a file, @file{.} refers to the directory of the innermost
6354: file being included, or, if there is no file being included, to the
6355: current working directory.
6356:
6357: Use @file{~+} to refer to the current working directory (as in the
6358: @code{bash}).
6359:
6360: If the filename starts with @file{./}, the search path is not searched
6361: (just as with absolute filenames), and the @file{.} has the same meaning
6362: as described above.
6363:
1.21 crook 6364: @node Forth Search Paths, General Search Paths, Search Path, Including Files
6365: @subsection Forth Search Paths
6366: @cindex search path control - forth
1.12 anton 6367:
6368: The search path is initialized when you start Gforth (@pxref{Invoking
6369: Gforth}). You can display it with
6370:
6371: doc-.fpath
6372:
6373: You can change it later with the following words:
6374:
6375: doc-fpath+
6376: doc-fpath=
6377:
6378: Using fpath and require would look like:
6379:
6380: @example
6381: fpath= /usr/lib/forth/|./
6382:
6383: require timer.fs
6384: @end example
6385:
6386: If you have the need to look for a file in the Forth search path, you could
1.21 crook 6387: use this Gforth feature in your application:
1.12 anton 6388:
6389: doc-open-fpath-file
6390:
1.21 crook 6391: @node General Search Paths, , Forth Search Paths, Including Files
1.12 anton 6392: @subsection General Search Paths
1.21 crook 6393: @cindex search path control - for user applications
1.12 anton 6394:
6395: Your application may need to search files in sevaral directories, like
6396: @code{included} does. For this purpose you can define and use your own
6397: search paths. Create a search path like this:
6398:
6399: @example
1.21 crook 6400: \ Make a buffer for the path:
1.12 anton 6401: create mypath 100 chars , \ maximum length (is checked)
6402: 0 , \ real len
6403: 100 chars allot \ space for path
6404: @end example
6405:
6406: You have the same functions for the forth search path in a generic version
6407: for different paths.
6408:
1.21 crook 6409: Gforth also provides generic equivalents of the Forth search path words:
6410:
6411: doc-.path
1.12 anton 6412: doc-path+
6413: doc-path=
6414: doc-open-path-file
6415:
6416:
6417: @node Blocks, Other I/O, Including Files, Words
1.1 anton 6418: @section Blocks
6419:
1.20 pazsan 6420: This chapter describes how to use block files within Gforth.
6421:
6422: Block files are traditionally means of data and source storage in
6423: Forth. They have been very important in resource-starved computers
6424: without OS in the past. Gforth doesn't encourage to use blocks as
6425: source, and provides blocks only for backward compatibility. The ANS
6426: standard requires blocks to be available when files are.
6427:
1.21 crook 6428: @comment TODO what about errors on open-blocks?
1.20 pazsan 6429: doc-open-blocks
6430: doc-use
1.21 crook 6431: doc-scr
6432: doc-blk
1.20 pazsan 6433: doc-get-block-fid
6434: doc-block-position
6435: doc-update
1.21 crook 6436: doc-save-buffers
1.20 pazsan 6437: doc-save-buffer
1.21 crook 6438: doc-empty-buffers
1.20 pazsan 6439: doc-empty-buffer
6440: doc-flush
6441: doc-get-buffer
1.21 crook 6442: doc---block-block
1.20 pazsan 6443: doc-buffer
6444: doc-updated?
6445: doc-list
6446: doc-load
6447: doc-thru
6448: doc-+load
6449: doc-+thru
6450: doc---block--->
6451: doc-block-included
6452:
1.1 anton 6453: @node Other I/O, Programming Tools, Blocks, Words
6454: @section Other I/O
1.21 crook 6455: @comment TODO more index entries
6456:
6457: @menu
6458: * Simple numeric output:: Predefined formats
6459: * Formatted numeric output:: Formatted (pictured) output
6460: * String Formats:: How Forth stores strings in memory
6461: * Displaying characters and strings:: Other stuff
6462: * Input:: Input
6463: @end menu
6464:
6465: @node Simple numeric output, Formatted numeric output, Other I/O, Other I/O
6466: @subsection Simple numeric output
6467: @cindex Simple numeric output
6468: @comment TODO more index entries
6469:
6470: The simplest output functions are those that display numbers from the
6471: data or floating-point stacks. Floating-point output is always displayed
6472: using base 10. Numbers displayed from the data stack use the value stored
6473: in @code{base}.
6474:
6475: doc-.
6476: doc-dec.
6477: doc-hex.
6478: doc-u.
6479: doc-.r
6480: doc-u.r
6481: doc-d.
6482: doc-ud.
6483: doc-d.r
6484: doc-ud.r
6485: doc-f.
6486: doc-fe.
6487: doc-fs.
6488:
6489: Examples of printing the number 1234.5678E23 in the different floating-point output
6490: formats are shown below:
6491:
6492: @example
6493: f. 123456779999999000000000000.
6494: fe. 123.456779999999E24
6495: fs. 1.23456779999999E26
6496: @end example
6497:
6498:
6499: @node Formatted numeric output, String Formats, Simple numeric output, Other I/O
6500: @subsection Formatted numeric output
6501: @cindex Formatted numeric output
6502: @cindex pictured numeric output
6503: @comment TODO more index entries
6504:
6505: Forth traditionally uses a technique called @var{pictured numeric
6506: output} for formatted printing of integers. In this technique,
6507: digits are extracted from the number (using the current output radix
6508: defined by @code{base}), converted to ASCII codes and appended to a
6509: string that is built in a scratch-pad area of memory
6510: (@pxref{core-idef,Implementation-defined options}). During the extraction
6511: sequence, other arbitrary characters can be appended to the string. The
6512: completed string is specified by an address and length and can
6513: be manipulated (@code{TYPE}ed, copied, modified) under program control.
6514:
6515: All of the words described in the previous section for simple numeric
6516: output are implemented in Gforth using pictured numeric output.
6517:
6518: Three important things to remember about Pictured Numeric Output:
6519:
6520: @itemize @bullet
6521: @item
6522: It always operates on double-precision numbers; to display a single-precision number,
6523: convert it first (@pxref{Double precision} for ways of doing this).
6524: @item
6525: It always treats the double-precision number as though it were unsigned. Refer to
6526: the examples below for ways of printing signed numbers.
6527: @item
6528: The string is built up from right to left; least significant digit first.
6529: @end itemize
6530:
6531: doc-<#
6532: doc-#
6533: doc-#s
6534: doc-hold
6535: doc-sign
6536: doc-#>
6537:
6538: doc-represent
6539:
6540: Here are some examples of using pictured numeric output:
6541:
6542: @example
6543: : my-u. ( u -- )
6544: \ Simplest use of pns.. behaves like Standard u.
6545: 0 \ convert to unsigned double
6546: <# \ start conversion
6547: #s \ convert all digits
6548: #> \ complete conversion
6549: TYPE SPACE ; \ display, with trailing space
6550:
6551: : cents-only ( u -- )
6552: 0 \ convert to unsigned double
6553: <# \ start conversion
6554: # # \ convert two least-significant digits
6555: #> \ complete conversion, discard other digits
6556: TYPE SPACE ; \ display, with trailing space
6557:
6558: : dollars-and-cents ( u -- )
6559: 0 \ convert to unsigned double
6560: <# \ start conversion
6561: # # \ convert two least-significant digits
6562: [char] . hold \ insert decimal point
6563: #s \ convert remaining digits
6564: [char] $ hold \ append currency symbol
6565: #> \ complete conversion
6566: TYPE SPACE ; \ display, with trailing space
6567:
6568: : my-. ( n -- )
6569: \ handling negatives.. behaves like Standard .
6570: s>d \ convert to signed double
6571: swap over dabs \ leave sign byte followed by unsigned double
6572: <# \ start conversion
6573: #s \ convert all digits
6574: rot sign \ get at sign byte, append "-" if needed
6575: #> \ complete conversion
6576: TYPE SPACE ; \ display, with trailing space
6577:
6578: : account. ( n -- )
6579: \ accountants don't like minus signs, they use braces
6580: \ for negative numbers
6581: s>d \ convert to signed double
6582: swap over dabs \ leave sign byte followed by unsigned double
6583: <# \ start conversion
6584: 2 pick \ get copy of sign byte
6585: 0< IF [char] ) hold THEN \ right-most character of output
6586: #s \ convert all digits
6587: rot \ get at sign byte
6588: 0< IF [char] ( hold THEN
6589: #> \ complete conversion
6590: TYPE SPACE ; \ display, with trailing space
6591: @end example
6592:
6593: Here are some examples of using these words:
6594:
6595: @example
6596: 1 my-u. 1
6597: hex -1 my-u. decimal FFFFFFFF
6598: 1 cents-only 01
6599: 1234 cents-only 34
6600: 2 dollars-and-cents $0.02
6601: 1234 dollars-and-cents $12.34
6602: 123 my-. 123
6603: -123 my. -123
6604: 123 account. 123
6605: -456 account. (456)
6606: @end example
6607:
6608:
6609: @node String Formats, Displaying characters and strings, Formatted numeric output, Other I/O
6610: @subsection String Formats
6611: @cindex string formats
6612:
6613: @comment TODO more index entries
6614:
6615: Forth commonly uses two different methods for representing a string:
6616:
6617: @itemize @bullet
6618: @item
6619: @cindex address of counted string
6620: As a @var{counted string}, represented by a c-addr. The char addressed
6621: by c-addr contains a character-count, n, of the string and the string
6622: occupies the subsequent n char addresses in memory.
6623: @item
6624: As cell pair on the stack; c-addr u, where u is the length of the string
6625: in characters, and c-addr is the address of the first byte of the string.
6626: @end itemize
6627:
6628: The ANS Forth Standard encourages the use of the second format when
6629: representing strings on the stack, whilst conceeding that the counted
6630: string format remains useful as a way of storing strings in memory.
6631:
6632: doc-count
6633:
6634: @xref{Memory Blocks} for words that move, copy and search
6635: for strings. @xref{Displaying characters and strings,} for words that
6636: display characters and strings.
6637:
6638:
6639: @node Displaying characters and strings, Input, String Formats, Other I/O
6640: @subsection Displaying characters and strings
6641: @cindex displaying characters and strings
6642: @cindex compiling characters and strings
6643: @cindex cursor control
6644:
6645: @comment TODO more index entries
6646:
6647: This section starts with a glossary of Forth words and ends with a set
6648: of examples.
6649:
6650: doc-bl
6651: doc-space
6652: doc-spaces
6653: doc-emit
1.23 ! crook 6654: doc-toupper
1.21 crook 6655: doc-."
6656: doc-.(
6657: doc-type
6658: doc-cr
6659: doc-at-xy
6660: doc-page
6661: doc-s"
6662: doc-c"
6663: doc-char
6664: doc-[char]
6665: doc-sliteral
6666:
6667: As an example, consider the following text, stored in a file @file{test.fs}:
6668:
6669: @example
6670: .( text-1)
6671: : my-word
6672: ." text-2" cr
6673: .( text-3)
6674: ;
6675:
6676: ." text-4"
6677:
6678: : my-char
6679: [char] ALPHABET emit
6680: char emit
6681: ;
6682: @end example
6683:
6684: When you load this code into Gforth, the following output is generated:
6685:
6686: @example
6687: @kbd{include test.fs} text-1text-3text-4 ok
6688: @end example
6689:
6690: @itemize @bullet
6691: @item
6692: Messages @code{text-1} and @code{text-3} are displayed because @code{.(}
6693: is an immediate word; it behaves in the same way whether it is used inside
6694: or outside a colon definition.
6695: @item
6696: Message @code{text-4} is displayed because of Gforth's added interpretation
6697: semantics for @code{."}.
6698: @item
6699: Message @code{text-2} is @var{not} displayed, because the text interpreter
6700: performs the compilation semantics for @code{."} within the definition of
6701: @code{my-word}.
6702: @end itemize
6703:
6704: Here are some examples of executing @code{my-word} and @code{my-char}:
6705:
6706: @example
6707: my-word text-2
6708: ok
6709: @kbd{my-char fred} Af ok
6710: @kbd{my-char jim} Aj ok
6711: @end example
6712:
6713: @itemize @bullet
6714: @item
6715: Message @code{text-2} is displayed because of the run-time behaviour of
6716: @code{."}.
6717: @item
6718: @code{[char]} compiles the "A" from "ALPHABET" and puts its display code
6719: on the stack at run-time. @code{emit} always displays the character
6720: when @code{my-char} is executed.
6721: @item
6722: @code{char} parses a string at run-time and the second @code{emit} displays
6723: the first character of the string.
6724: @item
6725: If you type @code{see my-char} you can see that @code{[char]} discarded
6726: the text "LPHABET" and only compiled the display code for "A" into the
6727: definition of @code{my-char}.
6728: @end itemize
6729:
6730:
6731:
6732: @node Input, , Displaying characters and strings, Other I/O
6733: @subsection Input
6734: @cindex Input
6735: @comment TODO more index entries
6736:
6737: Blah on traditional and recommended string formats.
6738:
6739: doc--trailing
6740: doc-/string
6741: doc-convert
6742: doc->number
6743: doc->float
6744: doc-accept
6745: doc-query
6746: doc-expect
6747: doc-evaluate
6748: doc-key
6749: doc-key?
6750:
6751: TODO reference the block move stuff elsewhere
6752:
6753: TODO convert and >number might be better in the numeric input section.
6754:
6755: TODO maybe some of these shouldn't be here but should be in a "parsing" section
6756:
1.1 anton 6757:
1.7 pazsan 6758: @node Programming Tools, Assembler and Code Words, Other I/O, Words
1.1 anton 6759: @section Programming Tools
6760: @cindex programming tools
6761:
6762: @menu
6763: * Debugging:: Simple and quick.
6764: * Assertions:: Making your programs self-checking.
1.6 pazsan 6765: * Singlestep Debugger:: Executing your program word by word.
1.1 anton 6766: @end menu
6767:
6768: @node Debugging, Assertions, Programming Tools, Programming Tools
6769: @subsection Debugging
6770: @cindex debugging
6771:
1.21 crook 6772: Languages with a slow edit/compile/link/test development loop tend to
6773: require sophisticated tracing/stepping debuggers to facilate
6774: productive debugging.
1.1 anton 6775:
6776: A much better (faster) way in fast-compiling languages is to add
6777: printing code at well-selected places, let the program run, look at
6778: the output, see where things went wrong, add more printing code, etc.,
6779: until the bug is found.
6780:
1.21 crook 6781: The simple debugging aids provided in @file{debugs.fs}
6782: are meant to support this style of debugging. In addition, there are
6783: words for non-destructively inspecting the stack and memory:
6784:
6785: doc-.s
6786: doc-f.s
6787:
6788: There is a word @code{.r} but it does @var{not} display the return
6789: stack! It is used for formatted numeric output.
6790:
6791: doc-depth
6792: doc-fdepth
6793: doc-clearstack
6794: doc-?
6795: doc-dump
6796:
6797: The word @code{~~} prints debugging information (by default the source
6798: location and the stack contents). It is easy to insert. If you use Emacs
6799: it is also easy to remove (@kbd{C-x ~} in the Emacs Forth mode to
1.1 anton 6800: query-replace them with nothing). The deferred words
6801: @code{printdebugdata} and @code{printdebugline} control the output of
6802: @code{~~}. The default source location output format works well with
6803: Emacs' compilation mode, so you can step through the program at the
6804: source level using @kbd{C-x `} (the advantage over a stepping debugger
6805: is that you can step in any direction and you know where the crash has
6806: happened or where the strange data has occurred).
6807:
6808: Note that the default actions clobber the contents of the pictured
6809: numeric output string, so you should not use @code{~~}, e.g., between
6810: @code{<#} and @code{#>}.
6811:
6812: doc-~~
6813: doc-printdebugdata
6814: doc-printdebugline
6815:
1.21 crook 6816: doc-see
6817: doc-marker
6818:
6819: Here's an example of using @code{marker} at the start of a source file
6820: that you are debugging; it ensures that you only ever have one copy of
6821: the file's definitions compiled at any time:
6822:
6823: @example
6824: [IFDEF] my-code
6825: my-code
6826: [ENDIF]
6827:
6828: marker my-code
6829:
6830: \ .. definitions start here
6831: \ .
6832: \ .
6833: \ end
6834: @end example
6835:
6836:
6837:
1.2 jwilke 6838: @node Assertions, Singlestep Debugger, Debugging, Programming Tools
1.1 anton 6839: @subsection Assertions
6840: @cindex assertions
6841:
6842: It is a good idea to make your programs self-checking, in particular, if
6843: you use an assumption (e.g., that a certain field of a data structure is
6844: never zero) that may become wrong during maintenance. Gforth supports
6845: assertions for this purpose. They are used like this:
6846:
6847: @example
6848: assert( @var{flag} )
6849: @end example
6850:
6851: The code between @code{assert(} and @code{)} should compute a flag, that
6852: should be true if everything is alright and false otherwise. It should
6853: not change anything else on the stack. The overall stack effect of the
6854: assertion is @code{( -- )}. E.g.
6855:
6856: @example
6857: assert( 1 1 + 2 = ) \ what we learn in school
6858: assert( dup 0<> ) \ assert that the top of stack is not zero
6859: assert( false ) \ this code should not be reached
6860: @end example
6861:
6862: The need for assertions is different at different times. During
6863: debugging, we want more checking, in production we sometimes care more
6864: for speed. Therefore, assertions can be turned off, i.e., the assertion
6865: becomes a comment. Depending on the importance of an assertion and the
6866: time it takes to check it, you may want to turn off some assertions and
6867: keep others turned on. Gforth provides several levels of assertions for
6868: this purpose:
6869:
6870: doc-assert0(
6871: doc-assert1(
6872: doc-assert2(
6873: doc-assert3(
6874: doc-assert(
6875: doc-)
6876:
6877: @code{Assert(} is the same as @code{assert1(}. The variable
6878: @code{assert-level} specifies the highest assertions that are turned
6879: on. I.e., at the default @code{assert-level} of one, @code{assert0(} and
6880: @code{assert1(} assertions perform checking, while @code{assert2(} and
6881: @code{assert3(} assertions are treated as comments.
6882:
6883: Note that the @code{assert-level} is evaluated at compile-time, not at
6884: run-time. I.e., you cannot turn assertions on or off at run-time, you
6885: have to set the @code{assert-level} appropriately before compiling a
6886: piece of code. You can compile several pieces of code at several
6887: @code{assert-level}s (e.g., a trusted library at level 1 and newly
6888: written code at level 3).
6889:
6890: doc-assert-level
6891:
6892: If an assertion fails, a message compatible with Emacs' compilation mode
6893: is produced and the execution is aborted (currently with @code{ABORT"}.
6894: If there is interest, we will introduce a special throw code. But if you
6895: intend to @code{catch} a specific condition, using @code{throw} is
6896: probably more appropriate than an assertion).
6897:
1.21 crook 6898: Definitions in ANS Standard Forth for these assertion words are provided
6899: in @file{compat/assert.fs}.
6900:
6901:
1.2 jwilke 6902: @node Singlestep Debugger, , Assertions, Programming Tools
6903: @subsection Singlestep Debugger
6904: @cindex singlestep Debugger
6905: @cindex debugging Singlestep
6906: @cindex @code{dbg}
6907: @cindex @code{BREAK:}
6908: @cindex @code{BREAK"}
6909:
6910: When a new word is created there's often the need to check whether it behaves
1.21 crook 6911: correctly or not. You can do this by typing @code{dbg badword}.
6912:
6913: doc-dbg
6914:
6915: This might look like:
6916:
1.2 jwilke 6917: @example
6918: : badword 0 DO i . LOOP ; ok
6919: 2 dbg badword
6920: : badword
6921: Scanning code...
6922:
6923: Nesting debugger ready!
6924:
6925: 400D4738 8049BC4 0 -> [ 2 ] 00002 00000
6926: 400D4740 8049F68 DO -> [ 0 ]
6927: 400D4744 804A0C8 i -> [ 1 ] 00000
6928: 400D4748 400C5E60 . -> 0 [ 0 ]
6929: 400D474C 8049D0C LOOP -> [ 0 ]
6930: 400D4744 804A0C8 i -> [ 1 ] 00001
6931: 400D4748 400C5E60 . -> 1 [ 0 ]
6932: 400D474C 8049D0C LOOP -> [ 0 ]
6933: 400D4758 804B384 ; -> ok
6934: @end example
6935:
1.5 anton 6936: Each line displayed is one step. You always have to hit return to
6937: execute the next word that is displayed. If you don't want to execute
6938: the next word in a whole, you have to type @kbd{n} for @code{nest}. Here is
6939: an overview what keys are available:
1.2 jwilke 6940:
6941: @table @i
6942:
1.4 anton 6943: @item <return>
1.5 anton 6944: Next; Execute the next word.
1.2 jwilke 6945:
6946: @item n
1.5 anton 6947: Nest; Single step through next word.
1.2 jwilke 6948:
6949: @item u
1.5 anton 6950: Unnest; Stop debugging and execute rest of word. If we got to this word
6951: with nest, continue debugging with the calling word.
1.2 jwilke 6952:
6953: @item d
1.5 anton 6954: Done; Stop debugging and execute rest.
1.2 jwilke 6955:
6956: @item s
1.5 anton 6957: Stopp; Abort immediately.
1.2 jwilke 6958:
6959: @end table
6960:
6961: Debugging large application with this mechanism is very difficult, because
6962: you have to nest very deep into the program before the interesting part
6963: begins. This takes a lot of time.
6964:
6965: To do it more directly put a @code{BREAK:} command into your source code.
6966: When program execution reaches @code{BREAK:} the single step debugger is
6967: invoked and you have all the features described above.
6968:
6969: If you have more than one part to debug it is useful to know where the
6970: program has stopped at the moment. You can do this by the
6971: @code{BREAK" string"} command. This behaves like @code{BREAK:} except that
6972: string is typed out when the ``breakpoint'' is reached.
6973:
1.7 pazsan 6974: @node Assembler and Code Words, Threading Words, Programming Tools, Words
6975: @section Assembler and Code Words
1.1 anton 6976: @cindex assembler
6977: @cindex code words
6978:
6979: Gforth provides some words for defining primitives (words written in
6980: machine code), and for defining the the machine-code equivalent of
6981: @code{DOES>}-based defining words. However, the machine-independent
6982: nature of Gforth poses a few problems: First of all, Gforth runs on
6983: several architectures, so it can provide no standard assembler. What's
6984: worse is that the register allocation not only depends on the processor,
6985: but also on the @code{gcc} version and options used.
6986:
6987: The words that Gforth offers encapsulate some system dependences (e.g., the
6988: header structure), so a system-independent assembler may be used in
6989: Gforth. If you do not have an assembler, you can compile machine code
6990: directly with @code{,} and @code{c,}.
6991:
6992: doc-assembler
6993: doc-code
6994: doc-end-code
6995: doc-;code
6996: doc-flush-icache
6997:
6998: If @code{flush-icache} does not work correctly, @code{code} words
6999: etc. will not work (reliably), either.
7000:
7001: These words are rarely used. Therefore they reside in @code{code.fs},
7002: which is usually not loaded (except @code{flush-icache}, which is always
7003: present). You can load them with @code{require code.fs}.
7004:
7005: @cindex registers of the inner interpreter
7006: In the assembly code you will want to refer to the inner interpreter's
7007: registers (e.g., the data stack pointer) and you may want to use other
7008: registers for temporary storage. Unfortunately, the register allocation
7009: is installation-dependent.
7010:
7011: The easiest solution is to use explicit register declarations
7012: (@pxref{Explicit Reg Vars, , Variables in Specified Registers, gcc.info,
7013: GNU C Manual}) for all of the inner interpreter's registers: You have to
7014: compile Gforth with @code{-DFORCE_REG} (configure option
7015: @code{--enable-force-reg}) and the appropriate declarations must be
7016: present in the @code{machine.h} file (see @code{mips.h} for an example;
7017: you can find a full list of all declarable register symbols with
7018: @code{grep register engine.c}). If you give explicit registers to all
7019: variables that are declared at the beginning of @code{engine()}, you
7020: should be able to use the other caller-saved registers for temporary
7021: storage. Alternatively, you can use the @code{gcc} option
7022: @code{-ffixed-REG} (@pxref{Code Gen Options, , Options for Code
7023: Generation Conventions, gcc.info, GNU C Manual}) to reserve a register
7024: (however, this restriction on register allocation may slow Gforth
7025: significantly).
7026:
7027: If this solution is not viable (e.g., because @code{gcc} does not allow
7028: you to explicitly declare all the registers you need), you have to find
7029: out by looking at the code where the inner interpreter's registers
7030: reside and which registers can be used for temporary storage. You can
7031: get an assembly listing of the engine's code with @code{make engine.s}.
7032:
7033: In any case, it is good practice to abstract your assembly code from the
7034: actual register allocation. E.g., if the data stack pointer resides in
7035: register @code{$17}, create an alias for this register called @code{sp},
7036: and use that in your assembly code.
7037:
7038: @cindex code words, portable
7039: Another option for implementing normal and defining words efficiently
7040: is: adding the wanted functionality to the source of Gforth. For normal
7041: words you just have to edit @file{primitives} (@pxref{Automatic
7042: Generation}), defining words (equivalent to @code{;CODE} words, for fast
1.21 crook 7043: defined words) may require changes in @file{engine.c}, @file{kernel.fs},
1.1 anton 7044: @file{prims2x.fs}, and possibly @file{cross.fs}.
7045:
7046:
1.21 crook 7047: @node Threading Words, Passing Commands to the OS, Assembler and Code Words, Words
1.1 anton 7048: @section Threading Words
7049: @cindex threading words
7050:
7051: @cindex code address
7052: These words provide access to code addresses and other threading stuff
7053: in Gforth (and, possibly, other interpretive Forths). It more or less
7054: abstracts away the differences between direct and indirect threading
7055: (and, for direct threading, the machine dependences). However, at
7056: present this wordset is still incomplete. It is also pretty low-level;
7057: some day it will hopefully be made unnecessary by an internals wordset
7058: that abstracts implementation details away completely.
7059:
1.21 crook 7060: doc-threading-method
1.1 anton 7061: doc->code-address
7062: doc->does-code
7063: doc-code-address!
7064: doc-does-code!
7065: doc-does-handler!
7066: doc-/does-handler
7067:
7068: The code addresses produced by various defining words are produced by
7069: the following words:
7070:
7071: doc-docol:
7072: doc-docon:
7073: doc-dovar:
7074: doc-douser:
7075: doc-dodefer:
7076: doc-dofield:
7077:
7078: You can recognize words defined by a @code{CREATE}...@code{DOES>} word
7079: with @code{>DOES-CODE}. If the word was defined in that way, the value
7080: returned is different from 0 and identifies the @code{DOES>} used by the
7081: defining word.
1.21 crook 7082: @comment TODO should that be "identifies the xt of the DOES> ??
7083:
7084: @node Passing Commands to the OS, Miscellaneous Words, Threading Words, Words
7085: @section Passing Commands to the Operating System
7086: @cindex operating system - passing commands
7087: @cindex shell commands
7088:
7089: Gforth allows you to pass an arbitrary string to the host operating
7090: system shell (if such a thing exists) for execution.
7091:
7092: doc-sh
7093: doc-system
7094: doc-$?
1.23 ! crook 7095: doc-getenv
1.21 crook 7096:
7097:
7098: @node Miscellaneous Words, , Passing Commands to the OS, Words
7099: @section Miscellaneous Words
7100: @cindex miscellaneous words
7101:
7102: These section lists the ANS Standard Forth words that are not documented
7103: elsewhere in this manual. Ultimately, they all need proper homes.
7104:
7105: doc-,
7106: doc-allocate
7107: doc-allot
7108: doc-c,
7109: doc-here
7110: doc-ms
7111: doc-pad
7112: doc-parse
7113: doc-postpone
7114: doc-resize
7115: doc-time&date
7116: doc-unused
7117: doc-word
7118: doc-[compile]
1.23 ! crook 7119: doc-refill
1.21 crook 7120:
7121: These ANS Standard Forth words are not currently implemented in Gforth
7122: (see TODO section on dependencies)
7123:
7124: The following ANS Standard Forth words are not currently supported by Gforth
7125: (@pxref{ANS conformance})
7126:
7127: @code{EDITOR}
7128: @code{EKEY}
7129: @code{EKEY>CHAR}
7130: @code{EKEY?}
7131: @code{EMIT?}
7132: @code{FORGET}
7133:
1.2 jwilke 7134:
1.5 anton 7135: @c ******************************************************************
1.1 anton 7136: @node Tools, ANS conformance, Words, Top
7137: @chapter Tools
7138:
7139: @menu
7140: * ANS Report:: Report the words used, sorted by wordset.
7141: @end menu
7142:
7143: See also @ref{Emacs and Gforth}.
7144:
7145: @node ANS Report, , Tools, Tools
7146: @section @file{ans-report.fs}: Report the words used, sorted by wordset
7147: @cindex @file{ans-report.fs}
7148: @cindex report the words used in your program
7149: @cindex words used in your program
7150:
7151: If you want to label a Forth program as ANS Forth Program, you must
7152: document which wordsets the program uses; for extension wordsets, it is
7153: helpful to list the words the program requires from these wordsets
7154: (because Forth systems are allowed to provide only some words of them).
7155:
7156: The @file{ans-report.fs} tool makes it easy for you to determine which
7157: words from which wordset and which non-ANS words your application
7158: uses. You simply have to include @file{ans-report.fs} before loading the
7159: program you want to check. After loading your program, you can get the
7160: report with @code{print-ans-report}. A typical use is to run this as
7161: batch job like this:
7162: @example
7163: gforth ans-report.fs myprog.fs -e "print-ans-report bye"
7164: @end example
7165:
7166: The output looks like this (for @file{compat/control.fs}):
7167: @example
7168: The program uses the following words
7169: from CORE :
7170: : POSTPONE THEN ; immediate ?dup IF 0=
7171: from BLOCK-EXT :
7172: \
7173: from FILE :
7174: (
7175: @end example
7176:
7177: @subsection Caveats
7178:
7179: Note that @file{ans-report.fs} just checks which words are used, not whether
7180: they are used in an ANS Forth conforming way!
7181:
7182: Some words are defined in several wordsets in the
7183: standard. @file{ans-report.fs} reports them for only one of the
7184: wordsets, and not necessarily the one you expect. It depends on usage
7185: which wordset is the right one to specify. E.g., if you only use the
7186: compilation semantics of @code{S"}, it is a Core word; if you also use
7187: its interpretation semantics, it is a File word.
7188:
7189: @c ******************************************************************
7190: @node ANS conformance, Model, Tools, Top
7191: @chapter ANS conformance
7192: @cindex ANS conformance of Gforth
7193:
7194: To the best of our knowledge, Gforth is an
7195:
7196: ANS Forth System
7197: @itemize @bullet
7198: @item providing the Core Extensions word set
7199: @item providing the Block word set
7200: @item providing the Block Extensions word set
7201: @item providing the Double-Number word set
7202: @item providing the Double-Number Extensions word set
7203: @item providing the Exception word set
7204: @item providing the Exception Extensions word set
7205: @item providing the Facility word set
7206: @item providing @code{MS} and @code{TIME&DATE} from the Facility Extensions word set
7207: @item providing the File Access word set
7208: @item providing the File Access Extensions word set
7209: @item providing the Floating-Point word set
7210: @item providing the Floating-Point Extensions word set
7211: @item providing the Locals word set
7212: @item providing the Locals Extensions word set
7213: @item providing the Memory-Allocation word set
7214: @item providing the Memory-Allocation Extensions word set (that one's easy)
7215: @item providing the Programming-Tools word set
7216: @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
7217: @item providing the Search-Order word set
7218: @item providing the Search-Order Extensions word set
7219: @item providing the String word set
7220: @item providing the String Extensions word set (another easy one)
7221: @end itemize
7222:
7223: @cindex system documentation
7224: In addition, ANS Forth systems are required to document certain
7225: implementation choices. This chapter tries to meet these
7226: requirements. In many cases it gives a way to ask the system for the
7227: information instead of providing the information directly, in
7228: particular, if the information depends on the processor, the operating
7229: system or the installation options chosen, or if they are likely to
7230: change during the maintenance of Gforth.
7231:
7232: @comment The framework for the rest has been taken from pfe.
7233:
7234: @menu
7235: * The Core Words::
7236: * The optional Block word set::
7237: * The optional Double Number word set::
7238: * The optional Exception word set::
7239: * The optional Facility word set::
7240: * The optional File-Access word set::
7241: * The optional Floating-Point word set::
7242: * The optional Locals word set::
7243: * The optional Memory-Allocation word set::
7244: * The optional Programming-Tools word set::
7245: * The optional Search-Order word set::
7246: @end menu
7247:
7248:
7249: @c =====================================================================
7250: @node The Core Words, The optional Block word set, ANS conformance, ANS conformance
7251: @comment node-name, next, previous, up
7252: @section The Core Words
7253: @c =====================================================================
7254: @cindex core words, system documentation
7255: @cindex system documentation, core words
7256:
7257: @menu
7258: * core-idef:: Implementation Defined Options
7259: * core-ambcond:: Ambiguous Conditions
7260: * core-other:: Other System Documentation
7261: @end menu
7262:
7263: @c ---------------------------------------------------------------------
7264: @node core-idef, core-ambcond, The Core Words, The Core Words
7265: @subsection Implementation Defined Options
7266: @c ---------------------------------------------------------------------
7267: @cindex core words, implementation-defined options
7268: @cindex implementation-defined options, core words
7269:
7270:
7271: @table @i
7272: @item (Cell) aligned addresses:
7273: @cindex cell-aligned addresses
7274: @cindex aligned addresses
7275: processor-dependent. Gforth's alignment words perform natural alignment
7276: (e.g., an address aligned for a datum of size 8 is divisible by
7277: 8). Unaligned accesses usually result in a @code{-23 THROW}.
7278:
7279: @item @code{EMIT} and non-graphic characters:
7280: @cindex @code{EMIT} and non-graphic characters
7281: @cindex non-graphic characters and @code{EMIT}
7282: The character is output using the C library function (actually, macro)
7283: @code{putc}.
7284:
7285: @item character editing of @code{ACCEPT} and @code{EXPECT}:
7286: @cindex character editing of @code{ACCEPT} and @code{EXPECT}
7287: @cindex editing in @code{ACCEPT} and @code{EXPECT}
7288: @cindex @code{ACCEPT}, editing
7289: @cindex @code{EXPECT}, editing
7290: This is modeled on the GNU readline library (@pxref{Readline
7291: Interaction, , Command Line Editing, readline, The GNU Readline
7292: Library}) with Emacs-like key bindings. @kbd{Tab} deviates a little by
7293: producing a full word completion every time you type it (instead of
7294: producing the common prefix of all completions).
7295:
7296: @item character set:
7297: @cindex character set
7298: The character set of your computer and display device. Gforth is
7299: 8-bit-clean (but some other component in your system may make trouble).
7300:
7301: @item Character-aligned address requirements:
7302: @cindex character-aligned address requirements
7303: installation-dependent. Currently a character is represented by a C
7304: @code{unsigned char}; in the future we might switch to @code{wchar_t}
7305: (Comments on that requested).
7306:
7307: @item character-set extensions and matching of names:
7308: @cindex character-set extensions and matching of names
7309: @cindex case sensitivity for name lookup
7310: @cindex name lookup, case sensitivity
7311: @cindex locale and case sensitivity
1.21 crook 7312: Any character except the ASCII NUL character can be used in a
1.1 anton 7313: name. Matching is case-insensitive (except in @code{TABLE}s). The
7314: matching is performed using the C function @code{strncasecmp}, whose
7315: function is probably influenced by the locale. E.g., the @code{C} locale
7316: does not know about accents and umlauts, so they are matched
7317: case-sensitively in that locale. For portability reasons it is best to
7318: write programs such that they work in the @code{C} locale. Then one can
7319: use libraries written by a Polish programmer (who might use words
7320: containing ISO Latin-2 encoded characters) and by a French programmer
7321: (ISO Latin-1) in the same program (of course, @code{WORDS} will produce
7322: funny results for some of the words (which ones, depends on the font you
7323: are using)). Also, the locale you prefer may not be available in other
7324: operating systems. Hopefully, Unicode will solve these problems one day.
7325:
7326: @item conditions under which control characters match a space delimiter:
7327: @cindex space delimiters
7328: @cindex control characters as delimiters
7329: If @code{WORD} is called with the space character as a delimiter, all
7330: white-space characters (as identified by the C macro @code{isspace()})
7331: are delimiters. @code{PARSE}, on the other hand, treats space like other
7332: delimiters. @code{PARSE-WORD} treats space like @code{WORD}, but behaves
7333: like @code{PARSE} otherwise. @code{(NAME)}, which is used by the outer
7334: interpreter (aka text interpreter) by default, treats all white-space
7335: characters as delimiters.
7336:
7337: @item format of the control flow stack:
7338: @cindex control flow stack, format
7339: The data stack is used as control flow stack. The size of a control flow
7340: stack item in cells is given by the constant @code{cs-item-size}. At the
7341: time of this writing, an item consists of a (pointer to a) locals list
7342: (third), an address in the code (second), and a tag for identifying the
7343: item (TOS). The following tags are used: @code{defstart},
7344: @code{live-orig}, @code{dead-orig}, @code{dest}, @code{do-dest},
7345: @code{scopestart}.
7346:
7347: @item conversion of digits > 35
7348: @cindex digits > 35
7349: The characters @code{[\]^_'} are the digits with the decimal value
7350: 36@minus{}41. There is no way to input many of the larger digits.
7351:
7352: @item display after input terminates in @code{ACCEPT} and @code{EXPECT}:
7353: @cindex @code{EXPECT}, display after end of input
7354: @cindex @code{ACCEPT}, display after end of input
7355: The cursor is moved to the end of the entered string. If the input is
7356: terminated using the @kbd{Return} key, a space is typed.
7357:
7358: @item exception abort sequence of @code{ABORT"}:
7359: @cindex exception abort sequence of @code{ABORT"}
7360: @cindex @code{ABORT"}, exception abort sequence
7361: The error string is stored into the variable @code{"error} and a
7362: @code{-2 throw} is performed.
7363:
7364: @item input line terminator:
7365: @cindex input line terminator
7366: @cindex line terminator on input
7367: @cindex newline charcter on input
7368: For interactive input, @kbd{C-m} (CR) and @kbd{C-j} (LF) terminate
7369: lines. One of these characters is typically produced when you type the
7370: @kbd{Enter} or @kbd{Return} key.
7371:
7372: @item maximum size of a counted string:
7373: @cindex maximum size of a counted string
7374: @cindex counted string, maximum size
7375: @code{s" /counted-string" environment? drop .}. Currently 255 characters
7376: on all ports, but this may change.
7377:
7378: @item maximum size of a parsed string:
7379: @cindex maximum size of a parsed string
7380: @cindex parsed string, maximum size
7381: Given by the constant @code{/line}. Currently 255 characters.
7382:
7383: @item maximum size of a definition name, in characters:
7384: @cindex maximum size of a definition name, in characters
7385: @cindex name, maximum length
7386: 31
7387:
7388: @item maximum string length for @code{ENVIRONMENT?}, in characters:
7389: @cindex maximum string length for @code{ENVIRONMENT?}, in characters
7390: @cindex @code{ENVIRONMENT?} string length, maximum
7391: 31
7392:
7393: @item method of selecting the user input device:
7394: @cindex user input device, method of selecting
7395: The user input device is the standard input. There is currently no way to
7396: change it from within Gforth. However, the input can typically be
7397: redirected in the command line that starts Gforth.
7398:
7399: @item method of selecting the user output device:
7400: @cindex user output device, method of selecting
7401: @code{EMIT} and @code{TYPE} output to the file-id stored in the value
1.10 anton 7402: @code{outfile-id} (@code{stdout} by default). Gforth uses unbuffered
7403: output when the user output device is a terminal, otherwise the output
7404: is buffered.
1.1 anton 7405:
7406: @item methods of dictionary compilation:
7407: What are we expected to document here?
7408:
7409: @item number of bits in one address unit:
7410: @cindex number of bits in one address unit
7411: @cindex address unit, size in bits
7412: @code{s" address-units-bits" environment? drop .}. 8 in all current
7413: ports.
7414:
7415: @item number representation and arithmetic:
7416: @cindex number representation and arithmetic
7417: Processor-dependent. Binary two's complement on all current ports.
7418:
7419: @item ranges for integer types:
7420: @cindex ranges for integer types
7421: @cindex integer types, ranges
7422: Installation-dependent. Make environmental queries for @code{MAX-N},
7423: @code{MAX-U}, @code{MAX-D} and @code{MAX-UD}. The lower bounds for
7424: unsigned (and positive) types is 0. The lower bound for signed types on
7425: two's complement and one's complement machines machines can be computed
7426: by adding 1 to the upper bound.
7427:
7428: @item read-only data space regions:
7429: @cindex read-only data space regions
7430: @cindex data-space, read-only regions
7431: The whole Forth data space is writable.
7432:
7433: @item size of buffer at @code{WORD}:
7434: @cindex size of buffer at @code{WORD}
7435: @cindex @code{WORD} buffer size
7436: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
7437: shared with the pictured numeric output string. If overwriting
7438: @code{PAD} is acceptable, it is as large as the remaining dictionary
7439: space, although only as much can be sensibly used as fits in a counted
7440: string.
7441:
7442: @item size of one cell in address units:
7443: @cindex cell size
7444: @code{1 cells .}.
7445:
7446: @item size of one character in address units:
7447: @cindex char size
7448: @code{1 chars .}. 1 on all current ports.
7449:
7450: @item size of the keyboard terminal buffer:
7451: @cindex size of the keyboard terminal buffer
7452: @cindex terminal buffer, size
7453: Varies. You can determine the size at a specific time using @code{lp@@
7454: tib - .}. It is shared with the locals stack and TIBs of files that
7455: include the current file. You can change the amount of space for TIBs
7456: and locals stack at Gforth startup with the command line option
7457: @code{-l}.
7458:
7459: @item size of the pictured numeric output buffer:
7460: @cindex size of the pictured numeric output buffer
7461: @cindex pictured numeric output buffer, size
7462: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
7463: shared with @code{WORD}.
7464:
7465: @item size of the scratch area returned by @code{PAD}:
7466: @cindex size of the scratch area returned by @code{PAD}
7467: @cindex @code{PAD} size
7468: The remainder of dictionary space. @code{unused pad here - - .}.
7469:
7470: @item system case-sensitivity characteristics:
7471: @cindex case-sensitivity characteristics
7472: Dictionary searches are case insensitive (except in
7473: @code{TABLE}s). However, as explained above under @i{character-set
7474: extensions}, the matching for non-ASCII characters is determined by the
7475: locale you are using. In the default @code{C} locale all non-ASCII
7476: characters are matched case-sensitively.
7477:
7478: @item system prompt:
7479: @cindex system prompt
7480: @cindex prompt
7481: @code{ ok} in interpret state, @code{ compiled} in compile state.
7482:
7483: @item division rounding:
7484: @cindex division rounding
7485: installation dependent. @code{s" floored" environment? drop .}. We leave
7486: the choice to @code{gcc} (what to use for @code{/}) and to you (whether
7487: to use @code{fm/mod}, @code{sm/rem} or simply @code{/}).
7488:
7489: @item values of @code{STATE} when true:
7490: @cindex @code{STATE} values
7491: -1.
7492:
7493: @item values returned after arithmetic overflow:
7494: On two's complement machines, arithmetic is performed modulo
7495: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
7496: arithmetic (with appropriate mapping for signed types). Division by zero
7497: typically results in a @code{-55 throw} (Floating-point unidentified
7498: fault), although a @code{-10 throw} (divide by zero) would be more
7499: appropriate.
7500:
7501: @item whether the current definition can be found after @t{DOES>}:
7502: @cindex @t{DOES>}, visibility of current definition
7503: No.
7504:
7505: @end table
7506:
7507: @c ---------------------------------------------------------------------
7508: @node core-ambcond, core-other, core-idef, The Core Words
7509: @subsection Ambiguous conditions
7510: @c ---------------------------------------------------------------------
7511: @cindex core words, ambiguous conditions
7512: @cindex ambiguous conditions, core words
7513:
7514: @table @i
7515:
7516: @item a name is neither a word nor a number:
7517: @cindex name not found
7518: @cindex Undefined word
7519: @code{-13 throw} (Undefined word). Actually, @code{-13 bounce}, which
7520: preserves the data and FP stack, so you don't lose more work than
7521: necessary.
7522:
7523: @item a definition name exceeds the maximum length allowed:
7524: @cindex Word name too long
7525: @code{-19 throw} (Word name too long)
7526:
7527: @item addressing a region not inside the various data spaces of the forth system:
7528: @cindex Invalid memory address
7529: The stacks, code space and name space are accessible. Machine code space is
7530: typically readable. Accessing other addresses gives results dependent on
7531: the operating system. On decent systems: @code{-9 throw} (Invalid memory
7532: address).
7533:
7534: @item argument type incompatible with parameter:
7535: @cindex Argument type mismatch
7536: This is usually not caught. Some words perform checks, e.g., the control
7537: flow words, and issue a @code{ABORT"} or @code{-12 THROW} (Argument type
7538: mismatch).
7539:
7540: @item attempting to obtain the execution token of a word with undefined execution semantics:
7541: @cindex Interpreting a compile-only word, for @code{'} etc.
7542: @cindex execution token of words with undefined execution semantics
7543: @code{-14 throw} (Interpreting a compile-only word). In some cases, you
7544: get an execution token for @code{compile-only-error} (which performs a
7545: @code{-14 throw} when executed).
7546:
7547: @item dividing by zero:
7548: @cindex dividing by zero
7549: @cindex floating point unidentified fault, integer division
7550: @cindex divide by zero
7551: typically results in a @code{-55 throw} (floating point unidentified
7552: fault), although a @code{-10 throw} (divide by zero) would be more
7553: appropriate.
7554:
7555: @item insufficient data stack or return stack space:
7556: @cindex insufficient data stack or return stack space
7557: @cindex stack overflow
7558: @cindex Address alignment exception, stack overflow
7559: @cindex Invalid memory address, stack overflow
7560: Depending on the operating system, the installation, and the invocation
7561: of Gforth, this is either checked by the memory management hardware, or
7562: it is not checked. If it is checked, you typically get a @code{-9 throw}
7563: (Invalid memory address) as soon as the overflow happens. If it is not
1.21 crook 7564: checked, overflows typically result in mysterious illegal memory accesses,
1.1 anton 7565: producing @code{-9 throw} (Invalid memory address) or @code{-23 throw}
7566: (Address alignment exception); they might also destroy the internal data
7567: structure of @code{ALLOCATE} and friends, resulting in various errors in
7568: these words.
7569:
7570: @item insufficient space for loop control parameters:
7571: @cindex insufficient space for loop control parameters
7572: like other return stack overflows.
7573:
7574: @item insufficient space in the dictionary:
7575: @cindex insufficient space in the dictionary
7576: @cindex dictionary overflow
1.12 anton 7577: If you try to allot (either directly with @code{allot}, or indirectly
7578: with @code{,}, @code{create} etc.) more memory than available in the
7579: dictionary, you get a @code{-8 throw} (Dictionary overflow). If you try
7580: to access memory beyond the end of the dictionary, the results are
7581: similar to stack overflows.
1.1 anton 7582:
7583: @item interpreting a word with undefined interpretation semantics:
7584: @cindex interpreting a word with undefined interpretation semantics
7585: @cindex Interpreting a compile-only word
7586: For some words, we have defined interpretation semantics. For the
7587: others: @code{-14 throw} (Interpreting a compile-only word).
7588:
7589: @item modifying the contents of the input buffer or a string literal:
7590: @cindex modifying the contents of the input buffer or a string literal
7591: These are located in writable memory and can be modified.
7592:
7593: @item overflow of the pictured numeric output string:
7594: @cindex overflow of the pictured numeric output string
7595: @cindex pictured numeric output string, overflow
7596: Not checked. Runs into the dictionary and destroys it (at least,
7597: partially).
7598:
7599: @item parsed string overflow:
7600: @cindex parsed string overflow
7601: @code{PARSE} cannot overflow. @code{WORD} does not check for overflow.
7602:
7603: @item producing a result out of range:
7604: @cindex result out of range
7605: On two's complement machines, arithmetic is performed modulo
7606: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
7607: arithmetic (with appropriate mapping for signed types). Division by zero
7608: typically results in a @code{-55 throw} (floatingpoint unidentified
7609: fault), although a @code{-10 throw} (divide by zero) would be more
7610: appropriate. @code{convert} and @code{>number} currently overflow
7611: silently.
7612:
7613: @item reading from an empty data or return stack:
7614: @cindex stack empty
7615: @cindex stack underflow
7616: The data stack is checked by the outer (aka text) interpreter after
7617: every word executed. If it has underflowed, a @code{-4 throw} (Stack
7618: underflow) is performed. Apart from that, stacks may be checked or not,
7619: depending on operating system, installation, and invocation. The
7620: consequences of stack underflows are similar to the consequences of
7621: stack overflows. Note that even if the system uses checking (through the
7622: MMU), your program may have to underflow by a significant number of
7623: stack items to trigger the reaction (the reason for this is that the
7624: MMU, and therefore the checking, works with a page-size granularity).
7625:
7626: @item unexpected end of the input buffer, resulting in an attempt to use a zero-length string as a name:
7627: @cindex unexpected end of the input buffer
7628: @cindex zero-length string as a name
7629: @cindex Attempt to use zero-length string as a name
7630: @code{Create} and its descendants perform a @code{-16 throw} (Attempt to
7631: use zero-length string as a name). Words like @code{'} probably will not
7632: find what they search. Note that it is possible to create zero-length
7633: names with @code{nextname} (should it not?).
7634:
7635: @item @code{>IN} greater than input buffer:
7636: @cindex @code{>IN} greater than input buffer
7637: The next invocation of a parsing word returns a string with length 0.
7638:
7639: @item @code{RECURSE} appears after @code{DOES>}:
7640: @cindex @code{RECURSE} appears after @code{DOES>}
7641: Compiles a recursive call to the defining word, not to the defined word.
7642:
7643: @item argument input source different than current input source for @code{RESTORE-INPUT}:
7644: @cindex argument input source different than current input source for @code{RESTORE-INPUT}
7645: @cindex Argument type mismatch, @code{RESTORE-INPUT}
7646: @cindex @code{RESTORE-INPUT}, Argument type mismatch
7647: @code{-12 THROW}. Note that, once an input file is closed (e.g., because
7648: the end of the file was reached), its source-id may be
7649: reused. Therefore, restoring an input source specification referencing a
7650: closed file may lead to unpredictable results instead of a @code{-12
7651: THROW}.
7652:
7653: In the future, Gforth may be able to restore input source specifications
7654: from other than the current input source.
7655:
7656: @item data space containing definitions gets de-allocated:
7657: @cindex data space containing definitions gets de-allocated
7658: Deallocation with @code{allot} is not checked. This typically results in
7659: memory access faults or execution of illegal instructions.
7660:
7661: @item data space read/write with incorrect alignment:
7662: @cindex data space read/write with incorrect alignment
7663: @cindex alignment faults
7664: @cindex Address alignment exception
7665: Processor-dependent. Typically results in a @code{-23 throw} (Address
1.12 anton 7666: alignment exception). Under Linux-Intel on a 486 or later processor with
1.1 anton 7667: alignment turned on, incorrect alignment results in a @code{-9 throw}
7668: (Invalid memory address). There are reportedly some processors with
1.12 anton 7669: alignment restrictions that do not report violations.
1.1 anton 7670:
7671: @item data space pointer not properly aligned, @code{,}, @code{C,}:
7672: @cindex data space pointer not properly aligned, @code{,}, @code{C,}
7673: Like other alignment errors.
7674:
7675: @item less than u+2 stack items (@code{PICK} and @code{ROLL}):
7676: Like other stack underflows.
7677:
7678: @item loop control parameters not available:
7679: @cindex loop control parameters not available
7680: Not checked. The counted loop words simply assume that the top of return
7681: stack items are loop control parameters and behave accordingly.
7682:
7683: @item most recent definition does not have a name (@code{IMMEDIATE}):
7684: @cindex most recent definition does not have a name (@code{IMMEDIATE})
7685: @cindex last word was headerless
7686: @code{abort" last word was headerless"}.
7687:
7688: @item name not defined by @code{VALUE} used by @code{TO}:
7689: @cindex name not defined by @code{VALUE} used by @code{TO}
7690: @cindex @code{TO} on non-@code{VALUE}s
7691: @cindex Invalid name argument, @code{TO}
7692: @code{-32 throw} (Invalid name argument) (unless name is a local or was
7693: defined by @code{CONSTANT}; in the latter case it just changes the constant).
7694:
7695: @item name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}):
7696: @cindex name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]})
7697: @cindex Undefined word, @code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}
7698: @code{-13 throw} (Undefined word)
7699:
7700: @item parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN}):
7701: @cindex parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN})
7702: Gforth behaves as if they were of the same type. I.e., you can predict
7703: the behaviour by interpreting all parameters as, e.g., signed.
7704:
7705: @item @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}:
7706: @cindex @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}
7707: Assume @code{: X POSTPONE TO ; IMMEDIATE}. @code{X} performs the
7708: compilation semantics of @code{TO}.
7709:
7710: @item String longer than a counted string returned by @code{WORD}:
7711: @cindex String longer than a counted string returned by @code{WORD}
7712: @cindex @code{WORD}, string overflow
7713: Not checked. The string will be ok, but the count will, of course,
7714: contain only the least significant bits of the length.
7715:
7716: @item u greater than or equal to the number of bits in a cell (@code{LSHIFT}, @code{RSHIFT}):
7717: @cindex @code{LSHIFT}, large shift counts
7718: @cindex @code{RSHIFT}, large shift counts
7719: Processor-dependent. Typical behaviours are returning 0 and using only
7720: the low bits of the shift count.
7721:
7722: @item word not defined via @code{CREATE}:
7723: @cindex @code{>BODY} of non-@code{CREATE}d words
7724: @code{>BODY} produces the PFA of the word no matter how it was defined.
7725:
7726: @cindex @code{DOES>} of non-@code{CREATE}d words
7727: @code{DOES>} changes the execution semantics of the last defined word no
7728: matter how it was defined. E.g., @code{CONSTANT DOES>} is equivalent to
7729: @code{CREATE , DOES>}.
7730:
7731: @item words improperly used outside @code{<#} and @code{#>}:
7732: Not checked. As usual, you can expect memory faults.
7733:
7734: @end table
7735:
7736:
7737: @c ---------------------------------------------------------------------
7738: @node core-other, , core-ambcond, The Core Words
7739: @subsection Other system documentation
7740: @c ---------------------------------------------------------------------
7741: @cindex other system documentation, core words
7742: @cindex core words, other system documentation
7743:
7744: @table @i
7745: @item nonstandard words using @code{PAD}:
7746: @cindex @code{PAD} use by nonstandard words
7747: None.
7748:
7749: @item operator's terminal facilities available:
7750: @cindex operator's terminal facilities available
7751: After processing the command line, Gforth goes into interactive mode,
7752: and you can give commands to Gforth interactively. The actual facilities
7753: available depend on how you invoke Gforth.
7754:
7755: @item program data space available:
7756: @cindex program data space available
7757: @cindex data space available
7758: @code{UNUSED .} gives the remaining dictionary space. The total
7759: dictionary space can be specified with the @code{-m} switch
7760: (@pxref{Invoking Gforth}) when Gforth starts up.
7761:
7762: @item return stack space available:
7763: @cindex return stack space available
7764: You can compute the total return stack space in cells with
7765: @code{s" RETURN-STACK-CELLS" environment? drop .}. You can specify it at
7766: startup time with the @code{-r} switch (@pxref{Invoking Gforth}).
7767:
7768: @item stack space available:
7769: @cindex stack space available
7770: You can compute the total data stack space in cells with
7771: @code{s" STACK-CELLS" environment? drop .}. You can specify it at
7772: startup time with the @code{-d} switch (@pxref{Invoking Gforth}).
7773:
7774: @item system dictionary space required, in address units:
7775: @cindex system dictionary space required, in address units
7776: Type @code{here forthstart - .} after startup. At the time of this
7777: writing, this gives 80080 (bytes) on a 32-bit system.
7778: @end table
7779:
7780:
7781: @c =====================================================================
7782: @node The optional Block word set, The optional Double Number word set, The Core Words, ANS conformance
7783: @section The optional Block word set
7784: @c =====================================================================
7785: @cindex system documentation, block words
7786: @cindex block words, system documentation
7787:
7788: @menu
7789: * block-idef:: Implementation Defined Options
7790: * block-ambcond:: Ambiguous Conditions
7791: * block-other:: Other System Documentation
7792: @end menu
7793:
7794:
7795: @c ---------------------------------------------------------------------
7796: @node block-idef, block-ambcond, The optional Block word set, The optional Block word set
7797: @subsection Implementation Defined Options
7798: @c ---------------------------------------------------------------------
7799: @cindex implementation-defined options, block words
7800: @cindex block words, implementation-defined options
7801:
7802: @table @i
7803: @item the format for display by @code{LIST}:
7804: @cindex @code{LIST} display format
7805: First the screen number is displayed, then 16 lines of 64 characters,
7806: each line preceded by the line number.
7807:
7808: @item the length of a line affected by @code{\}:
7809: @cindex length of a line affected by @code{\}
7810: @cindex @code{\}, line length in blocks
7811: 64 characters.
7812: @end table
7813:
7814:
7815: @c ---------------------------------------------------------------------
7816: @node block-ambcond, block-other, block-idef, The optional Block word set
7817: @subsection Ambiguous conditions
7818: @c ---------------------------------------------------------------------
7819: @cindex block words, ambiguous conditions
7820: @cindex ambiguous conditions, block words
7821:
7822: @table @i
7823: @item correct block read was not possible:
7824: @cindex block read not possible
7825: Typically results in a @code{throw} of some OS-derived value (between
7826: -512 and -2048). If the blocks file was just not long enough, blanks are
7827: supplied for the missing portion.
7828:
7829: @item I/O exception in block transfer:
7830: @cindex I/O exception in block transfer
7831: @cindex block transfer, I/O exception
7832: Typically results in a @code{throw} of some OS-derived value (between
7833: -512 and -2048).
7834:
7835: @item invalid block number:
7836: @cindex invalid block number
7837: @cindex block number invalid
7838: @code{-35 throw} (Invalid block number)
7839:
7840: @item a program directly alters the contents of @code{BLK}:
7841: @cindex @code{BLK}, altering @code{BLK}
7842: The input stream is switched to that other block, at the same
7843: position. If the storing to @code{BLK} happens when interpreting
7844: non-block input, the system will get quite confused when the block ends.
7845:
7846: @item no current block buffer for @code{UPDATE}:
7847: @cindex @code{UPDATE}, no current block buffer
7848: @code{UPDATE} has no effect.
7849:
7850: @end table
7851:
7852: @c ---------------------------------------------------------------------
7853: @node block-other, , block-ambcond, The optional Block word set
7854: @subsection Other system documentation
7855: @c ---------------------------------------------------------------------
7856: @cindex other system documentation, block words
7857: @cindex block words, other system documentation
7858:
7859: @table @i
7860: @item any restrictions a multiprogramming system places on the use of buffer addresses:
7861: No restrictions (yet).
7862:
7863: @item the number of blocks available for source and data:
7864: depends on your disk space.
7865:
7866: @end table
7867:
7868:
7869: @c =====================================================================
7870: @node The optional Double Number word set, The optional Exception word set, The optional Block word set, ANS conformance
7871: @section The optional Double Number word set
7872: @c =====================================================================
7873: @cindex system documentation, double words
7874: @cindex double words, system documentation
7875:
7876: @menu
7877: * double-ambcond:: Ambiguous Conditions
7878: @end menu
7879:
7880:
7881: @c ---------------------------------------------------------------------
7882: @node double-ambcond, , The optional Double Number word set, The optional Double Number word set
7883: @subsection Ambiguous conditions
7884: @c ---------------------------------------------------------------------
7885: @cindex double words, ambiguous conditions
7886: @cindex ambiguous conditions, double words
7887:
7888: @table @i
7889: @item @var{d} outside of range of @var{n} in @code{D>S}:
7890: @cindex @code{D>S}, @var{d} out of range of @var{n}
7891: The least significant cell of @var{d} is produced.
7892:
7893: @end table
7894:
7895:
7896: @c =====================================================================
7897: @node The optional Exception word set, The optional Facility word set, The optional Double Number word set, ANS conformance
7898: @section The optional Exception word set
7899: @c =====================================================================
7900: @cindex system documentation, exception words
7901: @cindex exception words, system documentation
7902:
7903: @menu
7904: * exception-idef:: Implementation Defined Options
7905: @end menu
7906:
7907:
7908: @c ---------------------------------------------------------------------
7909: @node exception-idef, , The optional Exception word set, The optional Exception word set
7910: @subsection Implementation Defined Options
7911: @c ---------------------------------------------------------------------
7912: @cindex implementation-defined options, exception words
7913: @cindex exception words, implementation-defined options
7914:
7915: @table @i
7916: @item @code{THROW}-codes used in the system:
7917: @cindex @code{THROW}-codes used in the system
7918: The codes -256@minus{}-511 are used for reporting signals. The mapping
7919: from OS signal numbers to throw codes is -256@minus{}@var{signal}. The
7920: codes -512@minus{}-2047 are used for OS errors (for file and memory
7921: allocation operations). The mapping from OS error numbers to throw codes
7922: is -512@minus{}@code{errno}. One side effect of this mapping is that
7923: undefined OS errors produce a message with a strange number; e.g.,
7924: @code{-1000 THROW} results in @code{Unknown error 488} on my system.
7925: @end table
7926:
7927: @c =====================================================================
7928: @node The optional Facility word set, The optional File-Access word set, The optional Exception word set, ANS conformance
7929: @section The optional Facility word set
7930: @c =====================================================================
7931: @cindex system documentation, facility words
7932: @cindex facility words, system documentation
7933:
7934: @menu
7935: * facility-idef:: Implementation Defined Options
7936: * facility-ambcond:: Ambiguous Conditions
7937: @end menu
7938:
7939:
7940: @c ---------------------------------------------------------------------
7941: @node facility-idef, facility-ambcond, The optional Facility word set, The optional Facility word set
7942: @subsection Implementation Defined Options
7943: @c ---------------------------------------------------------------------
7944: @cindex implementation-defined options, facility words
7945: @cindex facility words, implementation-defined options
7946:
7947: @table @i
7948: @item encoding of keyboard events (@code{EKEY}):
7949: @cindex keyboard events, encoding in @code{EKEY}
7950: @cindex @code{EKEY}, encoding of keyboard events
7951: Not yet implemented.
7952:
7953: @item duration of a system clock tick:
7954: @cindex duration of a system clock tick
7955: @cindex clock tick duration
7956: System dependent. With respect to @code{MS}, the time is specified in
7957: microseconds. How well the OS and the hardware implement this, is
7958: another question.
7959:
7960: @item repeatability to be expected from the execution of @code{MS}:
7961: @cindex repeatability to be expected from the execution of @code{MS}
7962: @cindex @code{MS}, repeatability to be expected
7963: System dependent. On Unix, a lot depends on load. If the system is
7964: lightly loaded, and the delay is short enough that Gforth does not get
7965: swapped out, the performance should be acceptable. Under MS-DOS and
7966: other single-tasking systems, it should be good.
7967:
7968: @end table
7969:
7970:
7971: @c ---------------------------------------------------------------------
7972: @node facility-ambcond, , facility-idef, The optional Facility word set
7973: @subsection Ambiguous conditions
7974: @c ---------------------------------------------------------------------
7975: @cindex facility words, ambiguous conditions
7976: @cindex ambiguous conditions, facility words
7977:
7978: @table @i
7979: @item @code{AT-XY} can't be performed on user output device:
7980: @cindex @code{AT-XY} can't be performed on user output device
7981: Largely terminal dependent. No range checks are done on the arguments.
7982: No errors are reported. You may see some garbage appearing, you may see
7983: simply nothing happen.
7984:
7985: @end table
7986:
7987:
7988: @c =====================================================================
7989: @node The optional File-Access word set, The optional Floating-Point word set, The optional Facility word set, ANS conformance
7990: @section The optional File-Access word set
7991: @c =====================================================================
7992: @cindex system documentation, file words
7993: @cindex file words, system documentation
7994:
7995: @menu
7996: * file-idef:: Implementation Defined Options
7997: * file-ambcond:: Ambiguous Conditions
7998: @end menu
7999:
8000: @c ---------------------------------------------------------------------
8001: @node file-idef, file-ambcond, The optional File-Access word set, The optional File-Access word set
8002: @subsection Implementation Defined Options
8003: @c ---------------------------------------------------------------------
8004: @cindex implementation-defined options, file words
8005: @cindex file words, implementation-defined options
8006:
8007: @table @i
8008: @item file access methods used:
8009: @cindex file access methods used
8010: @code{R/O}, @code{R/W} and @code{BIN} work as you would
8011: expect. @code{W/O} translates into the C file opening mode @code{w} (or
8012: @code{wb}): The file is cleared, if it exists, and created, if it does
8013: not (with both @code{open-file} and @code{create-file}). Under Unix
8014: @code{create-file} creates a file with 666 permissions modified by your
8015: umask.
8016:
8017: @item file exceptions:
8018: @cindex file exceptions
8019: The file words do not raise exceptions (except, perhaps, memory access
8020: faults when you pass illegal addresses or file-ids).
8021:
8022: @item file line terminator:
8023: @cindex file line terminator
8024: System-dependent. Gforth uses C's newline character as line
8025: terminator. What the actual character code(s) of this are is
8026: system-dependent.
8027:
8028: @item file name format:
8029: @cindex file name format
8030: System dependent. Gforth just uses the file name format of your OS.
8031:
8032: @item information returned by @code{FILE-STATUS}:
8033: @cindex @code{FILE-STATUS}, returned information
8034: @code{FILE-STATUS} returns the most powerful file access mode allowed
8035: for the file: Either @code{R/O}, @code{W/O} or @code{R/W}. If the file
8036: cannot be accessed, @code{R/O BIN} is returned. @code{BIN} is applicable
8037: along with the returned mode.
8038:
8039: @item input file state after an exception when including source:
8040: @cindex exception when including source
8041: All files that are left via the exception are closed.
8042:
8043: @item @var{ior} values and meaning:
8044: @cindex @var{ior} values and meaning
8045: The @var{ior}s returned by the file and memory allocation words are
8046: intended as throw codes. They typically are in the range
8047: -512@minus{}-2047 of OS errors. The mapping from OS error numbers to
8048: @var{ior}s is -512@minus{}@var{errno}.
8049:
8050: @item maximum depth of file input nesting:
8051: @cindex maximum depth of file input nesting
8052: @cindex file input nesting, maximum depth
8053: limited by the amount of return stack, locals/TIB stack, and the number
8054: of open files available. This should not give you troubles.
8055:
8056: @item maximum size of input line:
8057: @cindex maximum size of input line
8058: @cindex input line size, maximum
8059: @code{/line}. Currently 255.
8060:
8061: @item methods of mapping block ranges to files:
8062: @cindex mapping block ranges to files
8063: @cindex files containing blocks
8064: @cindex blocks in files
8065: By default, blocks are accessed in the file @file{blocks.fb} in the
8066: current working directory. The file can be switched with @code{USE}.
8067:
8068: @item number of string buffers provided by @code{S"}:
8069: @cindex @code{S"}, number of string buffers
8070: 1
8071:
8072: @item size of string buffer used by @code{S"}:
8073: @cindex @code{S"}, size of string buffer
8074: @code{/line}. currently 255.
8075:
8076: @end table
8077:
8078: @c ---------------------------------------------------------------------
8079: @node file-ambcond, , file-idef, The optional File-Access word set
8080: @subsection Ambiguous conditions
8081: @c ---------------------------------------------------------------------
8082: @cindex file words, ambiguous conditions
8083: @cindex ambiguous conditions, file words
8084:
8085: @table @i
8086: @item attempting to position a file outside its boundaries:
8087: @cindex @code{REPOSITION-FILE}, outside the file's boundaries
8088: @code{REPOSITION-FILE} is performed as usual: Afterwards,
8089: @code{FILE-POSITION} returns the value given to @code{REPOSITION-FILE}.
8090:
8091: @item attempting to read from file positions not yet written:
8092: @cindex reading from file positions not yet written
8093: End-of-file, i.e., zero characters are read and no error is reported.
8094:
8095: @item @var{file-id} is invalid (@code{INCLUDE-FILE}):
8096: @cindex @code{INCLUDE-FILE}, @var{file-id} is invalid
8097: An appropriate exception may be thrown, but a memory fault or other
8098: problem is more probable.
8099:
8100: @item I/O exception reading or closing @var{file-id} (@code{INCLUDE-FILE}, @code{INCLUDED}):
8101: @cindex @code{INCLUDE-FILE}, I/O exception reading or closing @var{file-id}
8102: @cindex @code{INCLUDED}, I/O exception reading or closing @var{file-id}
8103: The @var{ior} produced by the operation, that discovered the problem, is
8104: thrown.
8105:
8106: @item named file cannot be opened (@code{INCLUDED}):
8107: @cindex @code{INCLUDED}, named file cannot be opened
8108: The @var{ior} produced by @code{open-file} is thrown.
8109:
8110: @item requesting an unmapped block number:
8111: @cindex unmapped block numbers
8112: There are no unmapped legal block numbers. On some operating systems,
8113: writing a block with a large number may overflow the file system and
8114: have an error message as consequence.
8115:
8116: @item using @code{source-id} when @code{blk} is non-zero:
8117: @cindex @code{SOURCE-ID}, behaviour when @code{BLK} is non-zero
8118: @code{source-id} performs its function. Typically it will give the id of
8119: the source which loaded the block. (Better ideas?)
8120:
8121: @end table
8122:
8123:
8124: @c =====================================================================
8125: @node The optional Floating-Point word set, The optional Locals word set, The optional File-Access word set, ANS conformance
8126: @section The optional Floating-Point word set
8127: @c =====================================================================
8128: @cindex system documentation, floating-point words
8129: @cindex floating-point words, system documentation
8130:
8131: @menu
8132: * floating-idef:: Implementation Defined Options
8133: * floating-ambcond:: Ambiguous Conditions
8134: @end menu
8135:
8136:
8137: @c ---------------------------------------------------------------------
8138: @node floating-idef, floating-ambcond, The optional Floating-Point word set, The optional Floating-Point word set
8139: @subsection Implementation Defined Options
8140: @c ---------------------------------------------------------------------
8141: @cindex implementation-defined options, floating-point words
8142: @cindex floating-point words, implementation-defined options
8143:
8144: @table @i
8145: @item format and range of floating point numbers:
8146: @cindex format and range of floating point numbers
8147: @cindex floating point numbers, format and range
8148: System-dependent; the @code{double} type of C.
8149:
8150: @item results of @code{REPRESENT} when @var{float} is out of range:
8151: @cindex @code{REPRESENT}, results when @var{float} is out of range
8152: System dependent; @code{REPRESENT} is implemented using the C library
8153: function @code{ecvt()} and inherits its behaviour in this respect.
8154:
8155: @item rounding or truncation of floating-point numbers:
8156: @cindex rounding of floating-point numbers
8157: @cindex truncation of floating-point numbers
8158: @cindex floating-point numbers, rounding or truncation
8159: System dependent; the rounding behaviour is inherited from the hosting C
8160: compiler. IEEE-FP-based (i.e., most) systems by default round to
8161: nearest, and break ties by rounding to even (i.e., such that the last
8162: bit of the mantissa is 0).
8163:
8164: @item size of floating-point stack:
8165: @cindex floating-point stack size
8166: @code{s" FLOATING-STACK" environment? drop .} gives the total size of
8167: the floating-point stack (in floats). You can specify this on startup
8168: with the command-line option @code{-f} (@pxref{Invoking Gforth}).
8169:
8170: @item width of floating-point stack:
8171: @cindex floating-point stack width
8172: @code{1 floats}.
8173:
8174: @end table
8175:
8176:
8177: @c ---------------------------------------------------------------------
8178: @node floating-ambcond, , floating-idef, The optional Floating-Point word set
8179: @subsection Ambiguous conditions
8180: @c ---------------------------------------------------------------------
8181: @cindex floating-point words, ambiguous conditions
8182: @cindex ambiguous conditions, floating-point words
8183:
8184: @table @i
8185: @item @code{df@@} or @code{df!} used with an address that is not double-float aligned:
8186: @cindex @code{df@@} or @code{df!} used with an address that is not double-float aligned
8187: System-dependent. Typically results in a @code{-23 THROW} like other
8188: alignment violations.
8189:
8190: @item @code{f@@} or @code{f!} used with an address that is not float aligned:
8191: @cindex @code{f@@} used with an address that is not float aligned
8192: @cindex @code{f!} used with an address that is not float aligned
8193: System-dependent. Typically results in a @code{-23 THROW} like other
8194: alignment violations.
8195:
8196: @item floating-point result out of range:
8197: @cindex floating-point result out of range
8198: System-dependent. Can result in a @code{-55 THROW} (Floating-point
8199: unidentified fault), or can produce a special value representing, e.g.,
8200: Infinity.
8201:
8202: @item @code{sf@@} or @code{sf!} used with an address that is not single-float aligned:
8203: @cindex @code{sf@@} or @code{sf!} used with an address that is not single-float aligned
8204: System-dependent. Typically results in an alignment fault like other
8205: alignment violations.
8206:
8207: @item @code{BASE} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.}):
8208: @cindex @code{BASE} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.})
8209: The floating-point number is converted into decimal nonetheless.
8210:
8211: @item Both arguments are equal to zero (@code{FATAN2}):
8212: @cindex @code{FATAN2}, both arguments are equal to zero
8213: System-dependent. @code{FATAN2} is implemented using the C library
8214: function @code{atan2()}.
8215:
8216: @item Using @code{FTAN} on an argument @var{r1} where cos(@var{r1}) is zero:
8217: @cindex @code{FTAN} on an argument @var{r1} where cos(@var{r1}) is zero
8218: System-dependent. Anyway, typically the cos of @var{r1} will not be zero
8219: because of small errors and the tan will be a very large (or very small)
8220: but finite number.
8221:
8222: @item @var{d} cannot be presented precisely as a float in @code{D>F}:
8223: @cindex @code{D>F}, @var{d} cannot be presented precisely as a float
8224: The result is rounded to the nearest float.
8225:
8226: @item dividing by zero:
8227: @cindex dividing by zero, floating-point
8228: @cindex floating-point dividing by zero
8229: @cindex floating-point unidentified fault, FP divide-by-zero
8230: @code{-55 throw} (Floating-point unidentified fault)
8231:
8232: @item exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@}):
8233: @cindex exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@})
8234: System dependent. On IEEE-FP based systems the number is converted into
8235: an infinity.
8236:
8237: @item @var{float}<1 (@code{FACOSH}):
8238: @cindex @code{FACOSH}, @var{float}<1
8239: @cindex floating-point unidentified fault, @code{FACOSH}
8240: @code{-55 throw} (Floating-point unidentified fault)
8241:
8242: @item @var{float}=<-1 (@code{FLNP1}):
8243: @cindex @code{FLNP1}, @var{float}=<-1
8244: @cindex floating-point unidentified fault, @code{FLNP1}
8245: @code{-55 throw} (Floating-point unidentified fault). On IEEE-FP systems
8246: negative infinity is typically produced for @var{float}=-1.
8247:
8248: @item @var{float}=<0 (@code{FLN}, @code{FLOG}):
8249: @cindex @code{FLN}, @var{float}=<0
8250: @cindex @code{FLOG}, @var{float}=<0
8251: @cindex floating-point unidentified fault, @code{FLN} or @code{FLOG}
8252: @code{-55 throw} (Floating-point unidentified fault). On IEEE-FP systems
8253: negative infinity is typically produced for @var{float}=0.
8254:
8255: @item @var{float}<0 (@code{FASINH}, @code{FSQRT}):
8256: @cindex @code{FASINH}, @var{float}<0
8257: @cindex @code{FSQRT}, @var{float}<0
8258: @cindex floating-point unidentified fault, @code{FASINH} or @code{FSQRT}
8259: @code{-55 throw} (Floating-point unidentified fault). @code{fasinh}
8260: produces values for these inputs on my Linux box (Bug in the C library?)
8261:
8262: @item |@var{float}|>1 (@code{FACOS}, @code{FASIN}, @code{FATANH}):
8263: @cindex @code{FACOS}, |@var{float}|>1
8264: @cindex @code{FASIN}, |@var{float}|>1
8265: @cindex @code{FATANH}, |@var{float}|>1
8266: @cindex floating-point unidentified fault, @code{FACOS}, @code{FASIN} or @code{FATANH}
8267: @code{-55 throw} (Floating-point unidentified fault).
8268:
8269: @item integer part of float cannot be represented by @var{d} in @code{F>D}:
8270: @cindex @code{F>D}, integer part of float cannot be represented by @var{d}
8271: @cindex floating-point unidentified fault, @code{F>D}
8272: @code{-55 throw} (Floating-point unidentified fault).
8273:
8274: @item string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.}):
8275: @cindex string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.})
8276: This does not happen.
8277: @end table
8278:
8279: @c =====================================================================
8280: @node The optional Locals word set, The optional Memory-Allocation word set, The optional Floating-Point word set, ANS conformance
8281: @section The optional Locals word set
8282: @c =====================================================================
8283: @cindex system documentation, locals words
8284: @cindex locals words, system documentation
8285:
8286: @menu
8287: * locals-idef:: Implementation Defined Options
8288: * locals-ambcond:: Ambiguous Conditions
8289: @end menu
8290:
8291:
8292: @c ---------------------------------------------------------------------
8293: @node locals-idef, locals-ambcond, The optional Locals word set, The optional Locals word set
8294: @subsection Implementation Defined Options
8295: @c ---------------------------------------------------------------------
8296: @cindex implementation-defined options, locals words
8297: @cindex locals words, implementation-defined options
8298:
8299: @table @i
8300: @item maximum number of locals in a definition:
8301: @cindex maximum number of locals in a definition
8302: @cindex locals, maximum number in a definition
8303: @code{s" #locals" environment? drop .}. Currently 15. This is a lower
8304: bound, e.g., on a 32-bit machine there can be 41 locals of up to 8
8305: characters. The number of locals in a definition is bounded by the size
8306: of locals-buffer, which contains the names of the locals.
8307:
8308: @end table
8309:
8310:
8311: @c ---------------------------------------------------------------------
8312: @node locals-ambcond, , locals-idef, The optional Locals word set
8313: @subsection Ambiguous conditions
8314: @c ---------------------------------------------------------------------
8315: @cindex locals words, ambiguous conditions
8316: @cindex ambiguous conditions, locals words
8317:
8318: @table @i
8319: @item executing a named local in interpretation state:
8320: @cindex local in interpretation state
8321: @cindex Interpreting a compile-only word, for a local
8322: Locals have no interpretation semantics. If you try to perform the
8323: interpretation semantics, you will get a @code{-14 throw} somewhere
8324: (Interpreting a compile-only word). If you perform the compilation
8325: semantics, the locals access will be compiled (irrespective of state).
8326:
8327: @item @var{name} not defined by @code{VALUE} or @code{(LOCAL)} (@code{TO}):
8328: @cindex name not defined by @code{VALUE} or @code{(LOCAL)} used by @code{TO}
8329: @cindex @code{TO} on non-@code{VALUE}s and non-locals
8330: @cindex Invalid name argument, @code{TO}
8331: @code{-32 throw} (Invalid name argument)
8332:
8333: @end table
8334:
8335:
8336: @c =====================================================================
8337: @node The optional Memory-Allocation word set, The optional Programming-Tools word set, The optional Locals word set, ANS conformance
8338: @section The optional Memory-Allocation word set
8339: @c =====================================================================
8340: @cindex system documentation, memory-allocation words
8341: @cindex memory-allocation words, system documentation
8342:
8343: @menu
8344: * memory-idef:: Implementation Defined Options
8345: @end menu
8346:
8347:
8348: @c ---------------------------------------------------------------------
8349: @node memory-idef, , The optional Memory-Allocation word set, The optional Memory-Allocation word set
8350: @subsection Implementation Defined Options
8351: @c ---------------------------------------------------------------------
8352: @cindex implementation-defined options, memory-allocation words
8353: @cindex memory-allocation words, implementation-defined options
8354:
8355: @table @i
8356: @item values and meaning of @var{ior}:
8357: @cindex @var{ior} values and meaning
8358: The @var{ior}s returned by the file and memory allocation words are
8359: intended as throw codes. They typically are in the range
8360: -512@minus{}-2047 of OS errors. The mapping from OS error numbers to
8361: @var{ior}s is -512@minus{}@var{errno}.
8362:
8363: @end table
8364:
8365: @c =====================================================================
8366: @node The optional Programming-Tools word set, The optional Search-Order word set, The optional Memory-Allocation word set, ANS conformance
8367: @section The optional Programming-Tools word set
8368: @c =====================================================================
8369: @cindex system documentation, programming-tools words
8370: @cindex programming-tools words, system documentation
8371:
8372: @menu
8373: * programming-idef:: Implementation Defined Options
8374: * programming-ambcond:: Ambiguous Conditions
8375: @end menu
8376:
8377:
8378: @c ---------------------------------------------------------------------
8379: @node programming-idef, programming-ambcond, The optional Programming-Tools word set, The optional Programming-Tools word set
8380: @subsection Implementation Defined Options
8381: @c ---------------------------------------------------------------------
8382: @cindex implementation-defined options, programming-tools words
8383: @cindex programming-tools words, implementation-defined options
8384:
8385: @table @i
8386: @item ending sequence for input following @code{;CODE} and @code{CODE}:
8387: @cindex @code{;CODE} ending sequence
8388: @cindex @code{CODE} ending sequence
8389: @code{END-CODE}
8390:
8391: @item manner of processing input following @code{;CODE} and @code{CODE}:
8392: @cindex @code{;CODE}, processing input
8393: @cindex @code{CODE}, processing input
8394: The @code{ASSEMBLER} vocabulary is pushed on the search order stack, and
8395: the input is processed by the text interpreter, (starting) in interpret
8396: state.
8397:
8398: @item search order capability for @code{EDITOR} and @code{ASSEMBLER}:
8399: @cindex @code{ASSEMBLER}, search order capability
8400: The ANS Forth search order word set.
8401:
8402: @item source and format of display by @code{SEE}:
8403: @cindex @code{SEE}, source and format of output
8404: The source for @code{see} is the intermediate code used by the inner
8405: interpreter. The current @code{see} tries to output Forth source code
8406: as well as possible.
8407:
8408: @end table
8409:
8410: @c ---------------------------------------------------------------------
8411: @node programming-ambcond, , programming-idef, The optional Programming-Tools word set
8412: @subsection Ambiguous conditions
8413: @c ---------------------------------------------------------------------
8414: @cindex programming-tools words, ambiguous conditions
8415: @cindex ambiguous conditions, programming-tools words
8416:
8417: @table @i
8418:
1.21 crook 8419: @item deleting the compilation word list (@code{FORGET}):
8420: @cindex @code{FORGET}, deleting the compilation word list
1.1 anton 8421: Not implemented (yet).
8422:
8423: @item fewer than @var{u}+1 items on the control flow stack (@code{CS-PICK}, @code{CS-ROLL}):
8424: @cindex @code{CS-PICK}, fewer than @var{u}+1 items on the control flow stack
8425: @cindex @code{CS-ROLL}, fewer than @var{u}+1 items on the control flow stack
8426: @cindex control-flow stack underflow
8427: This typically results in an @code{abort"} with a descriptive error
8428: message (may change into a @code{-22 throw} (Control structure mismatch)
8429: in the future). You may also get a memory access error. If you are
8430: unlucky, this ambiguous condition is not caught.
8431:
8432: @item @var{name} can't be found (@code{FORGET}):
8433: @cindex @code{FORGET}, @var{name} can't be found
8434: Not implemented (yet).
8435:
8436: @item @var{name} not defined via @code{CREATE}:
8437: @cindex @code{;CODE}, @var{name} not defined via @code{CREATE}
8438: @code{;CODE} behaves like @code{DOES>} in this respect, i.e., it changes
8439: the execution semantics of the last defined word no matter how it was
8440: defined.
8441:
8442: @item @code{POSTPONE} applied to @code{[IF]}:
8443: @cindex @code{POSTPONE} applied to @code{[IF]}
8444: @cindex @code{[IF]} and @code{POSTPONE}
8445: After defining @code{: X POSTPONE [IF] ; IMMEDIATE}. @code{X} is
8446: equivalent to @code{[IF]}.
8447:
8448: @item reaching the end of the input source before matching @code{[ELSE]} or @code{[THEN]}:
8449: @cindex @code{[IF]}, end of the input source before matching @code{[ELSE]} or @code{[THEN]}
8450: Continue in the same state of conditional compilation in the next outer
8451: input source. Currently there is no warning to the user about this.
8452:
8453: @item removing a needed definition (@code{FORGET}):
8454: @cindex @code{FORGET}, removing a needed definition
8455: Not implemented (yet).
8456:
8457: @end table
8458:
8459:
8460: @c =====================================================================
8461: @node The optional Search-Order word set, , The optional Programming-Tools word set, ANS conformance
8462: @section The optional Search-Order word set
8463: @c =====================================================================
8464: @cindex system documentation, search-order words
8465: @cindex search-order words, system documentation
8466:
8467: @menu
8468: * search-idef:: Implementation Defined Options
8469: * search-ambcond:: Ambiguous Conditions
8470: @end menu
8471:
8472:
8473: @c ---------------------------------------------------------------------
8474: @node search-idef, search-ambcond, The optional Search-Order word set, The optional Search-Order word set
8475: @subsection Implementation Defined Options
8476: @c ---------------------------------------------------------------------
8477: @cindex implementation-defined options, search-order words
8478: @cindex search-order words, implementation-defined options
8479:
8480: @table @i
8481: @item maximum number of word lists in search order:
8482: @cindex maximum number of word lists in search order
8483: @cindex search order, maximum depth
8484: @code{s" wordlists" environment? drop .}. Currently 16.
8485:
8486: @item minimum search order:
8487: @cindex minimum search order
8488: @cindex search order, minimum
8489: @code{root root}.
8490:
8491: @end table
8492:
8493: @c ---------------------------------------------------------------------
8494: @node search-ambcond, , search-idef, The optional Search-Order word set
8495: @subsection Ambiguous conditions
8496: @c ---------------------------------------------------------------------
8497: @cindex search-order words, ambiguous conditions
8498: @cindex ambiguous conditions, search-order words
8499:
8500: @table @i
1.21 crook 8501: @item changing the compilation word list (during compilation):
8502: @cindex changing the compilation word list (during compilation)
8503: @cindex compilation word list, change before definition ends
8504: The word is entered into the word list that was the compilation word list
1.1 anton 8505: at the start of the definition. Any changes to the name field (e.g.,
8506: @code{immediate}) or the code field (e.g., when executing @code{DOES>})
8507: are applied to the latest defined word (as reported by @code{last} or
1.21 crook 8508: @code{lastxt}), if possible, irrespective of the compilation word list.
1.1 anton 8509:
8510: @item search order empty (@code{previous}):
8511: @cindex @code{previous}, search order empty
8512: @cindex Vocstack empty, @code{previous}
8513: @code{abort" Vocstack empty"}.
8514:
8515: @item too many word lists in search order (@code{also}):
8516: @cindex @code{also}, too many word lists in search order
8517: @cindex Vocstack full, @code{also}
8518: @code{abort" Vocstack full"}.
8519:
8520: @end table
8521:
8522: @c ***************************************************************
8523: @node Model, Integrating Gforth, ANS conformance, Top
8524: @chapter Model
8525:
8526: This chapter has yet to be written. It will contain information, on
8527: which internal structures you can rely.
8528:
8529: @c ***************************************************************
8530: @node Integrating Gforth, Emacs and Gforth, Model, Top
8531: @chapter Integrating Gforth into C programs
8532:
8533: This is not yet implemented.
8534:
8535: Several people like to use Forth as scripting language for applications
8536: that are otherwise written in C, C++, or some other language.
8537:
8538: The Forth system ATLAST provides facilities for embedding it into
8539: applications; unfortunately it has several disadvantages: most
8540: importantly, it is not based on ANS Forth, and it is apparently dead
8541: (i.e., not developed further and not supported). The facilities
1.21 crook 8542: provided by Gforth in this area are inspired by ATLAST's facilities, so
1.1 anton 8543: making the switch should not be hard.
8544:
8545: We also tried to design the interface such that it can easily be
8546: implemented by other Forth systems, so that we may one day arrive at a
8547: standardized interface. Such a standard interface would allow you to
8548: replace the Forth system without having to rewrite C code.
8549:
8550: You embed the Gforth interpreter by linking with the library
8551: @code{libgforth.a} (give the compiler the option @code{-lgforth}). All
8552: global symbols in this library that belong to the interface, have the
8553: prefix @code{forth_}. (Global symbols that are used internally have the
8554: prefix @code{gforth_}).
8555:
8556: You can include the declarations of Forth types and the functions and
8557: variables of the interface with @code{#include <forth.h>}.
8558:
8559: Types.
8560:
8561: Variables.
8562:
8563: Data and FP Stack pointer. Area sizes.
8564:
8565: functions.
8566:
8567: forth_init(imagefile)
8568: forth_evaluate(string) exceptions?
8569: forth_goto(address) (or forth_execute(xt)?)
8570: forth_continue() (a corountining mechanism)
8571:
8572: Adding primitives.
8573:
8574: No checking.
8575:
8576: Signals?
8577:
8578: Accessing the Stacks
8579:
8580: @node Emacs and Gforth, Image Files, Integrating Gforth, Top
8581: @chapter Emacs and Gforth
8582: @cindex Emacs and Gforth
8583:
8584: @cindex @file{gforth.el}
8585: @cindex @file{forth.el}
8586: @cindex Rydqvist, Goran
8587: @cindex comment editing commands
8588: @cindex @code{\}, editing with Emacs
8589: @cindex debug tracer editing commands
8590: @cindex @code{~~}, removal with Emacs
8591: @cindex Forth mode in Emacs
8592: Gforth comes with @file{gforth.el}, an improved version of
8593: @file{forth.el} by Goran Rydqvist (included in the TILE package). The
8594: improvements are a better (but still not perfect) handling of
8595: indentation. I have also added comment paragraph filling (@kbd{M-q}),
8596: commenting (@kbd{C-x \}) and uncommenting (@kbd{C-u C-x \}) regions and
8597: removing debugging tracers (@kbd{C-x ~}, @pxref{Debugging}). I left the
8598: stuff I do not use alone, even though some of it only makes sense for
8599: TILE. To get a description of these features, enter Forth mode and type
8600: @kbd{C-h m}.
8601:
8602: @cindex source location of error or debugging output in Emacs
8603: @cindex error output, finding the source location in Emacs
8604: @cindex debugging output, finding the source location in Emacs
8605: In addition, Gforth supports Emacs quite well: The source code locations
8606: given in error messages, debugging output (from @code{~~}) and failed
8607: assertion messages are in the right format for Emacs' compilation mode
8608: (@pxref{Compilation, , Running Compilations under Emacs, emacs, Emacs
8609: Manual}) so the source location corresponding to an error or other
8610: message is only a few keystrokes away (@kbd{C-x `} for the next error,
8611: @kbd{C-c C-c} for the error under the cursor).
8612:
8613: @cindex @file{TAGS} file
8614: @cindex @file{etags.fs}
8615: @cindex viewing the source of a word in Emacs
8616: Also, if you @code{include} @file{etags.fs}, a new @file{TAGS} file
8617: (@pxref{Tags, , Tags Tables, emacs, Emacs Manual}) will be produced that
8618: contains the definitions of all words defined afterwards. You can then
8619: find the source for a word using @kbd{M-.}. Note that emacs can use
8620: several tags files at the same time (e.g., one for the Gforth sources
8621: and one for your program, @pxref{Select Tags Table,,Selecting a Tags
8622: Table,emacs, Emacs Manual}). The TAGS file for the preloaded words is
8623: @file{$(datadir)/gforth/$(VERSION)/TAGS} (e.g.,
8624: @file{/usr/local/share/gforth/0.2.0/TAGS}).
8625:
8626: @cindex @file{.emacs}
8627: To get all these benefits, add the following lines to your @file{.emacs}
8628: file:
8629:
8630: @example
8631: (autoload 'forth-mode "gforth.el")
8632: (setq auto-mode-alist (cons '("\\.fs\\'" . forth-mode) auto-mode-alist))
8633: @end example
8634:
8635: @node Image Files, Engine, Emacs and Gforth, Top
8636: @chapter Image Files
8637: @cindex image files
8638: @cindex @code{.fi} files
8639: @cindex precompiled Forth code
8640: @cindex dictionary in persistent form
8641: @cindex persistent form of dictionary
8642:
8643: An image file is a file containing an image of the Forth dictionary,
8644: i.e., compiled Forth code and data residing in the dictionary. By
8645: convention, we use the extension @code{.fi} for image files.
8646:
8647: @menu
1.18 anton 8648: * Image Licensing Issues:: Distribution terms for images.
8649: * Image File Background:: Why have image files?
8650: * Non-Relocatable Image Files:: don't always work.
8651: * Data-Relocatable Image Files:: are better.
1.1 anton 8652: * Fully Relocatable Image Files:: better yet.
1.18 anton 8653: * Stack and Dictionary Sizes:: Setting the default sizes for an image.
8654: * Running Image Files:: @code{gforth -i @var{file}} or @var{file}.
8655: * Modifying the Startup Sequence:: and turnkey applications.
1.1 anton 8656: @end menu
8657:
1.18 anton 8658: @node Image Licensing Issues, Image File Background, Image Files, Image Files
8659: @section Image Licensing Issues
8660: @cindex license for images
8661: @cindex image license
8662:
8663: An image created with @code{gforthmi} (@pxref{gforthmi}) or
8664: @code{savesystem} (@pxref{Non-Relocatable Image Files}) includes the
8665: original image; i.e., according to copyright law it is a derived work of
8666: the original image.
8667:
8668: Since Gforth is distributed under the GNU GPL, the newly created image
8669: falls under the GNU GPL, too. In particular, this means that if you
8670: distribute the image, you have to make all of the sources for the image
8671: available, including those you wrote. For details see @ref{License, ,
8672: GNU General Public License (Section 3)}.
8673:
8674: If you create an image with @code{cross} (@pxref{cross.fs}), the image
8675: contains only code compiled from the sources you gave it; if none of
8676: these sources is under the GPL, the terms discussed above do not apply
8677: to the image. However, if your image needs an engine (a gforth binary)
8678: that is under the GPL, you should make sure that you distribute both in
8679: a way that is at most a @emph{mere aggregation}, if you don't want the
8680: terms of the GPL to apply to the image.
8681:
8682: @node Image File Background, Non-Relocatable Image Files, Image Licensing Issues, Image Files
1.1 anton 8683: @section Image File Background
8684: @cindex image file background
8685:
8686: Our Forth system consists not only of primitives, but also of
8687: definitions written in Forth. Since the Forth compiler itself belongs to
8688: those definitions, it is not possible to start the system with the
8689: primitives and the Forth source alone. Therefore we provide the Forth
8690: code as an image file in nearly executable form. At the start of the
8691: system a C routine loads the image file into memory, optionally
8692: relocates the addresses, then sets up the memory (stacks etc.) according
8693: to information in the image file, and starts executing Forth code.
8694:
8695: The image file variants represent different compromises between the
8696: goals of making it easy to generate image files and making them
8697: portable.
8698:
8699: @cindex relocation at run-time
8700: Win32Forth 3.4 and Mitch Bradleys @code{cforth} use relocation at
8701: run-time. This avoids many of the complications discussed below (image
8702: files are data relocatable without further ado), but costs performance
8703: (one addition per memory access).
8704:
8705: @cindex relocation at load-time
8706: By contrast, our loader performs relocation at image load time. The
8707: loader also has to replace tokens standing for primitive calls with the
8708: appropriate code-field addresses (or code addresses in the case of
8709: direct threading).
8710:
8711: There are three kinds of image files, with different degrees of
8712: relocatability: non-relocatable, data-relocatable, and fully relocatable
8713: image files.
8714:
8715: @cindex image file loader
8716: @cindex relocating loader
8717: @cindex loader for image files
8718: These image file variants have several restrictions in common; they are
8719: caused by the design of the image file loader:
8720:
8721: @itemize @bullet
8722: @item
8723: There is only one segment; in particular, this means, that an image file
8724: cannot represent @code{ALLOCATE}d memory chunks (and pointers to
8725: them). And the contents of the stacks are not represented, either.
8726:
8727: @item
8728: The only kinds of relocation supported are: adding the same offset to
8729: all cells that represent data addresses; and replacing special tokens
8730: with code addresses or with pieces of machine code.
8731:
8732: If any complex computations involving addresses are performed, the
8733: results cannot be represented in the image file. Several applications that
8734: use such computations come to mind:
8735: @itemize @minus
8736: @item
8737: Hashing addresses (or data structures which contain addresses) for table
8738: lookup. If you use Gforth's @code{table}s or @code{wordlist}s for this
8739: purpose, you will have no problem, because the hash tables are
8740: recomputed automatically when the system is started. If you use your own
8741: hash tables, you will have to do something similar.
8742:
8743: @item
8744: There's a cute implementation of doubly-linked lists that uses
8745: @code{XOR}ed addresses. You could represent such lists as singly-linked
8746: in the image file, and restore the doubly-linked representation on
8747: startup.@footnote{In my opinion, though, you should think thrice before
8748: using a doubly-linked list (whatever implementation).}
8749:
8750: @item
8751: The code addresses of run-time routines like @code{docol:} cannot be
8752: represented in the image file (because their tokens would be replaced by
8753: machine code in direct threaded implementations). As a workaround,
8754: compute these addresses at run-time with @code{>code-address} from the
8755: executions tokens of appropriate words (see the definitions of
8756: @code{docol:} and friends in @file{kernel.fs}).
8757:
8758: @item
8759: On many architectures addresses are represented in machine code in some
8760: shifted or mangled form. You cannot put @code{CODE} words that contain
8761: absolute addresses in this form in a relocatable image file. Workarounds
8762: are representing the address in some relative form (e.g., relative to
8763: the CFA, which is present in some register), or loading the address from
8764: a place where it is stored in a non-mangled form.
8765: @end itemize
8766: @end itemize
8767:
8768: @node Non-Relocatable Image Files, Data-Relocatable Image Files, Image File Background, Image Files
8769: @section Non-Relocatable Image Files
8770: @cindex non-relocatable image files
8771: @cindex image files, non-relocatable
8772:
8773: These files are simple memory dumps of the dictionary. They are specific
8774: to the executable (i.e., @file{gforth} file) they were created
8775: with. What's worse, they are specific to the place on which the
8776: dictionary resided when the image was created. Now, there is no
8777: guarantee that the dictionary will reside at the same place the next
8778: time you start Gforth, so there's no guarantee that a non-relocatable
8779: image will work the next time (Gforth will complain instead of crashing,
8780: though).
8781:
8782: You can create a non-relocatable image file with
8783:
8784: doc-savesystem
8785:
8786: @node Data-Relocatable Image Files, Fully Relocatable Image Files, Non-Relocatable Image Files, Image Files
8787: @section Data-Relocatable Image Files
8788: @cindex data-relocatable image files
8789: @cindex image files, data-relocatable
8790:
8791: These files contain relocatable data addresses, but fixed code addresses
8792: (instead of tokens). They are specific to the executable (i.e.,
8793: @file{gforth} file) they were created with. For direct threading on some
8794: architectures (e.g., the i386), data-relocatable images do not work. You
8795: get a data-relocatable image, if you use @file{gforthmi} with a
8796: Gforth binary that is not doubly indirect threaded (@pxref{Fully
8797: Relocatable Image Files}).
8798:
8799: @node Fully Relocatable Image Files, Stack and Dictionary Sizes, Data-Relocatable Image Files, Image Files
8800: @section Fully Relocatable Image Files
8801: @cindex fully relocatable image files
8802: @cindex image files, fully relocatable
8803:
8804: @cindex @file{kern*.fi}, relocatability
8805: @cindex @file{gforth.fi}, relocatability
8806: These image files have relocatable data addresses, and tokens for code
8807: addresses. They can be used with different binaries (e.g., with and
8808: without debugging) on the same machine, and even across machines with
8809: the same data formats (byte order, cell size, floating point
8810: format). However, they are usually specific to the version of Gforth
8811: they were created with. The files @file{gforth.fi} and @file{kernl*.fi}
8812: are fully relocatable.
8813:
8814: There are two ways to create a fully relocatable image file:
8815:
8816: @menu
8817: * gforthmi:: The normal way
8818: * cross.fs:: The hard way
8819: @end menu
8820:
8821: @node gforthmi, cross.fs, Fully Relocatable Image Files, Fully Relocatable Image Files
8822: @subsection @file{gforthmi}
8823: @cindex @file{comp-i.fs}
8824: @cindex @file{gforthmi}
8825:
8826: You will usually use @file{gforthmi}. If you want to create an
8827: image @var{file} that contains everything you would load by invoking
8828: Gforth with @code{gforth @var{options}}, you simply say
8829: @example
8830: gforthmi @var{file} @var{options}
8831: @end example
8832:
8833: E.g., if you want to create an image @file{asm.fi} that has the file
8834: @file{asm.fs} loaded in addition to the usual stuff, you could do it
8835: like this:
8836:
8837: @example
8838: gforthmi asm.fi asm.fs
8839: @end example
8840:
8841: @file{gforthmi} works like this: It produces two non-relocatable
8842: images for different addresses and then compares them. Its output
8843: reflects this: first you see the output (if any) of the two Gforth
8844: invocations that produce the nonrelocatable image files, then you see
8845: the output of the comparing program: It displays the offset used for
8846: data addresses and the offset used for code addresses;
8847: moreover, for each cell that cannot be represented correctly in the
8848: image files, it displays a line like the following one:
8849:
8850: @example
8851: 78DC BFFFFA50 BFFFFA40
8852: @end example
8853:
8854: This means that at offset $78dc from @code{forthstart}, one input image
8855: contains $bffffa50, and the other contains $bffffa40. Since these cells
8856: cannot be represented correctly in the output image, you should examine
8857: these places in the dictionary and verify that these cells are dead
8858: (i.e., not read before they are written).
8859:
8860: @cindex @code{savesystem} during @file{gforthmi}
8861: @cindex @code{bye} during @file{gforthmi}
8862: @cindex doubly indirect threaded code
8863: @cindex environment variable @code{GFORTHD}
8864: @cindex @code{GFORTHD} environment variable
8865: @cindex @code{gforth-ditc}
8866: There are a few wrinkles: After processing the passed @var{options}, the
8867: words @code{savesystem} and @code{bye} must be visible. A special doubly
8868: indirect threaded version of the @file{gforth} executable is used for
8869: creating the nonrelocatable images; you can pass the exact filename of
8870: this executable through the environment variable @code{GFORTHD}
8871: (default: @file{gforth-ditc}); if you pass a version that is not doubly
8872: indirect threaded, you will not get a fully relocatable image, but a
8873: data-relocatable image (because there is no code address offset).
8874:
8875: @node cross.fs, , gforthmi, Fully Relocatable Image Files
8876: @subsection @file{cross.fs}
8877: @cindex @file{cross.fs}
8878: @cindex cross-compiler
8879: @cindex metacompiler
8880:
8881: You can also use @code{cross}, a batch compiler that accepts a Forth-like
8882: programming language. This @code{cross} language has to be documented
8883: yet.
8884:
8885: @cindex target compiler
8886: @code{cross} also allows you to create image files for machines with
8887: different data sizes and data formats than the one used for generating
8888: the image file. You can also use it to create an application image that
8889: does not contain a Forth compiler. These features are bought with
8890: restrictions and inconveniences in programming. E.g., addresses have to
8891: be stored in memory with special words (@code{A!}, @code{A,}, etc.) in
8892: order to make the code relocatable.
8893:
8894:
8895: @node Stack and Dictionary Sizes, Running Image Files, Fully Relocatable Image Files, Image Files
8896: @section Stack and Dictionary Sizes
8897: @cindex image file, stack and dictionary sizes
8898: @cindex dictionary size default
8899: @cindex stack size default
8900:
8901: If you invoke Gforth with a command line flag for the size
8902: (@pxref{Invoking Gforth}), the size you specify is stored in the
8903: dictionary. If you save the dictionary with @code{savesystem} or create
8904: an image with @file{gforthmi}, this size will become the default
8905: for the resulting image file. E.g., the following will create a
1.21 crook 8906: fully relocatable version of @file{gforth.fi} with a 1MB dictionary:
1.1 anton 8907:
8908: @example
8909: gforthmi gforth.fi -m 1M
8910: @end example
8911:
8912: In other words, if you want to set the default size for the dictionary
8913: and the stacks of an image, just invoke @file{gforthmi} with the
8914: appropriate options when creating the image.
8915:
8916: @cindex stack size, cache-friendly
8917: Note: For cache-friendly behaviour (i.e., good performance), you should
8918: make the sizes of the stacks modulo, say, 2K, somewhat different. E.g.,
8919: the default stack sizes are: data: 16k (mod 2k=0); fp: 15.5k (mod
8920: 2k=1.5k); return: 15k(mod 2k=1k); locals: 14.5k (mod 2k=0.5k).
8921:
8922: @node Running Image Files, Modifying the Startup Sequence, Stack and Dictionary Sizes, Image Files
8923: @section Running Image Files
8924: @cindex running image files
8925: @cindex invoking image files
8926: @cindex image file invocation
8927:
8928: @cindex -i, invoke image file
8929: @cindex --image file, invoke image file
8930: You can invoke Gforth with an image file @var{image} instead of the
8931: default @file{gforth.fi} with the @code{-i} flag (@pxref{Invoking Gforth}):
8932: @example
8933: gforth -i @var{image}
8934: @end example
8935:
8936: @cindex executable image file
8937: @cindex image files, executable
8938: If your operating system supports starting scripts with a line of the
8939: form @code{#! ...}, you just have to type the image file name to start
8940: Gforth with this image file (note that the file extension @code{.fi} is
8941: just a convention). I.e., to run Gforth with the image file @var{image},
8942: you can just type @var{image} instead of @code{gforth -i @var{image}}.
8943:
8944: doc-#!
8945:
8946: @node Modifying the Startup Sequence, , Running Image Files, Image Files
8947: @section Modifying the Startup Sequence
8948: @cindex startup sequence for image file
8949: @cindex image file initialization sequence
8950: @cindex initialization sequence of image file
8951:
8952: You can add your own initialization to the startup sequence through the
8953: deferred word
8954:
8955: doc-'cold
8956:
8957: @code{'cold} is invoked just before the image-specific command line
8958: processing (by default, loading files and evaluating (@code{-e}) strings)
8959: starts.
8960:
8961: A sequence for adding your initialization usually looks like this:
8962:
8963: @example
8964: :noname
8965: Defers 'cold \ do other initialization stuff (e.g., rehashing wordlists)
8966: ... \ your stuff
8967: ; IS 'cold
8968: @end example
8969:
8970: @cindex turnkey image files
8971: @cindex image files, turnkey applications
8972: You can make a turnkey image by letting @code{'cold} execute a word
8973: (your turnkey application) that never returns; instead, it exits Gforth
8974: via @code{bye} or @code{throw}.
8975:
8976: @cindex command-line arguments, access
8977: @cindex arguments on the command line, access
8978: You can access the (image-specific) command-line arguments through the
8979: variables @code{argc} and @code{argv}. @code{arg} provides conventient
8980: access to @code{argv}.
8981:
8982: doc-argc
8983: doc-argv
8984: doc-arg
8985:
8986: If @code{'cold} exits normally, Gforth processes the command-line
8987: arguments as files to be loaded and strings to be evaluated. Therefore,
8988: @code{'cold} should remove the arguments it has used in this case.
8989:
8990: @c ******************************************************************
1.13 pazsan 8991: @node Engine, Binding to System Library, Image Files, Top
1.1 anton 8992: @chapter Engine
8993: @cindex engine
8994: @cindex virtual machine
8995:
8996: Reading this section is not necessary for programming with Gforth. It
8997: may be helpful for finding your way in the Gforth sources.
8998:
8999: The ideas in this section have also been published in the papers
9000: @cite{ANS fig/GNU/??? Forth} (in German) by Bernd Paysan, presented at
9001: the Forth-Tagung '93 and @cite{A Portable Forth Engine} by M. Anton
9002: Ertl, presented at EuroForth '93; the latter is available at
9003: @*@url{http://www.complang.tuwien.ac.at/papers/ertl93.ps.Z}.
9004:
9005: @menu
9006: * Portability::
9007: * Threading::
9008: * Primitives::
9009: * Performance::
9010: @end menu
9011:
9012: @node Portability, Threading, Engine, Engine
9013: @section Portability
9014: @cindex engine portability
9015:
9016: One of the main goals of the effort is availability across a wide range
9017: of personal machines. fig-Forth, and, to a lesser extent, F83, achieved
9018: this goal by manually coding the engine in assembly language for several
9019: then-popular processors. This approach is very labor-intensive and the
9020: results are short-lived due to progress in computer architecture.
9021:
9022: @cindex C, using C for the engine
9023: Others have avoided this problem by coding in C, e.g., Mitch Bradley
9024: (cforth), Mikael Patel (TILE) and Dirk Zoller (pfe). This approach is
9025: particularly popular for UNIX-based Forths due to the large variety of
9026: architectures of UNIX machines. Unfortunately an implementation in C
9027: does not mix well with the goals of efficiency and with using
9028: traditional techniques: Indirect or direct threading cannot be expressed
9029: in C, and switch threading, the fastest technique available in C, is
9030: significantly slower. Another problem with C is that it is very
9031: cumbersome to express double integer arithmetic.
9032:
9033: @cindex GNU C for the engine
9034: @cindex long long
9035: Fortunately, there is a portable language that does not have these
9036: limitations: GNU C, the version of C processed by the GNU C compiler
9037: (@pxref{C Extensions, , Extensions to the C Language Family, gcc.info,
9038: GNU C Manual}). Its labels as values feature (@pxref{Labels as Values, ,
9039: Labels as Values, gcc.info, GNU C Manual}) makes direct and indirect
9040: threading possible, its @code{long long} type (@pxref{Long Long, ,
9041: Double-Word Integers, gcc.info, GNU C Manual}) corresponds to Forth's
9042: double numbers@footnote{Unfortunately, long longs are not implemented
9043: properly on all machines (e.g., on alpha-osf1, long longs are only 64
9044: bits, the same size as longs (and pointers), but they should be twice as
1.4 anton 9045: long according to @pxref{Long Long, , Double-Word Integers, gcc.info, GNU
1.1 anton 9046: C Manual}). So, we had to implement doubles in C after all. Still, on
9047: most machines we can use long longs and achieve better performance than
9048: with the emulation package.}. GNU C is available for free on all
9049: important (and many unimportant) UNIX machines, VMS, 80386s running
9050: MS-DOS, the Amiga, and the Atari ST, so a Forth written in GNU C can run
9051: on all these machines.
9052:
9053: Writing in a portable language has the reputation of producing code that
9054: is slower than assembly. For our Forth engine we repeatedly looked at
9055: the code produced by the compiler and eliminated most compiler-induced
9056: inefficiencies by appropriate changes in the source code.
9057:
9058: @cindex explicit register declarations
9059: @cindex --enable-force-reg, configuration flag
9060: @cindex -DFORCE_REG
9061: However, register allocation cannot be portably influenced by the
9062: programmer, leading to some inefficiencies on register-starved
9063: machines. We use explicit register declarations (@pxref{Explicit Reg
9064: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) to
9065: improve the speed on some machines. They are turned on by using the
9066: configuration flag @code{--enable-force-reg} (@code{gcc} switch
9067: @code{-DFORCE_REG}). Unfortunately, this feature not only depends on the
9068: machine, but also on the compiler version: On some machines some
9069: compiler versions produce incorrect code when certain explicit register
9070: declarations are used. So by default @code{-DFORCE_REG} is not used.
9071:
9072: @node Threading, Primitives, Portability, Engine
9073: @section Threading
9074: @cindex inner interpreter implementation
9075: @cindex threaded code implementation
9076:
9077: @cindex labels as values
9078: GNU C's labels as values extension (available since @code{gcc-2.0},
9079: @pxref{Labels as Values, , Labels as Values, gcc.info, GNU C Manual})
9080: makes it possible to take the address of @var{label} by writing
9081: @code{&&@var{label}}. This address can then be used in a statement like
9082: @code{goto *@var{address}}. I.e., @code{goto *&&x} is the same as
9083: @code{goto x}.
9084:
9085: @cindex NEXT, indirect threaded
9086: @cindex indirect threaded inner interpreter
9087: @cindex inner interpreter, indirect threaded
9088: With this feature an indirect threaded NEXT looks like:
9089: @example
9090: cfa = *ip++;
9091: ca = *cfa;
9092: goto *ca;
9093: @end example
9094: @cindex instruction pointer
9095: For those unfamiliar with the names: @code{ip} is the Forth instruction
9096: pointer; the @code{cfa} (code-field address) corresponds to ANS Forths
9097: execution token and points to the code field of the next word to be
9098: executed; The @code{ca} (code address) fetched from there points to some
9099: executable code, e.g., a primitive or the colon definition handler
9100: @code{docol}.
9101:
9102: @cindex NEXT, direct threaded
9103: @cindex direct threaded inner interpreter
9104: @cindex inner interpreter, direct threaded
9105: Direct threading is even simpler:
9106: @example
9107: ca = *ip++;
9108: goto *ca;
9109: @end example
9110:
9111: Of course we have packaged the whole thing neatly in macros called
9112: @code{NEXT} and @code{NEXT1} (the part of NEXT after fetching the cfa).
9113:
9114: @menu
9115: * Scheduling::
9116: * Direct or Indirect Threaded?::
9117: * DOES>::
9118: @end menu
9119:
9120: @node Scheduling, Direct or Indirect Threaded?, Threading, Threading
9121: @subsection Scheduling
9122: @cindex inner interpreter optimization
9123:
9124: There is a little complication: Pipelined and superscalar processors,
9125: i.e., RISC and some modern CISC machines can process independent
9126: instructions while waiting for the results of an instruction. The
9127: compiler usually reorders (schedules) the instructions in a way that
9128: achieves good usage of these delay slots. However, on our first tries
9129: the compiler did not do well on scheduling primitives. E.g., for
9130: @code{+} implemented as
9131: @example
9132: n=sp[0]+sp[1];
9133: sp++;
9134: sp[0]=n;
9135: NEXT;
9136: @end example
9137: the NEXT comes strictly after the other code, i.e., there is nearly no
9138: scheduling. After a little thought the problem becomes clear: The
1.21 crook 9139: compiler cannot know that @code{sp} and @code{ip} point to different
9140: addresses (and the version of @code{gcc} we used would not know it even
9141: if it was possible), so it could not move the load of the cfa above the
9142: store to the TOS. Indeed the pointers could be the same, if code on or
9143: very near the top of stack were executed. In the interest of speed we
9144: chose to forbid this probably unused ``feature'' and helped the compiler
9145: in scheduling: NEXT is divided into the loading part (@code{NEXT_P1})
9146: and the goto part (@code{NEXT_P2}). @code{+} now looks like:
1.1 anton 9147: @example
9148: n=sp[0]+sp[1];
9149: sp++;
9150: NEXT_P1;
9151: sp[0]=n;
9152: NEXT_P2;
9153: @end example
9154: This can be scheduled optimally by the compiler.
9155:
9156: This division can be turned off with the switch @code{-DCISC_NEXT}. This
9157: switch is on by default on machines that do not profit from scheduling
9158: (e.g., the 80386), in order to preserve registers.
9159:
9160: @node Direct or Indirect Threaded?, DOES>, Scheduling, Threading
9161: @subsection Direct or Indirect Threaded?
9162: @cindex threading, direct or indirect?
9163:
9164: @cindex -DDIRECT_THREADED
9165: Both! After packaging the nasty details in macro definitions we
9166: realized that we could switch between direct and indirect threading by
9167: simply setting a compilation flag (@code{-DDIRECT_THREADED}) and
9168: defining a few machine-specific macros for the direct-threading case.
9169: On the Forth level we also offer access words that hide the
9170: differences between the threading methods (@pxref{Threading Words}).
9171:
9172: Indirect threading is implemented completely machine-independently.
9173: Direct threading needs routines for creating jumps to the executable
1.21 crook 9174: code (e.g. to @code{docol} or @code{dodoes}). These routines are inherently
9175: machine-dependent, but they do not amount to many source lines. Therefore,
9176: even porting direct threading to a new machine requires little effort.
1.1 anton 9177:
9178: @cindex --enable-indirect-threaded, configuration flag
9179: @cindex --enable-direct-threaded, configuration flag
9180: The default threading method is machine-dependent. You can enforce a
9181: specific threading method when building Gforth with the configuration
9182: flag @code{--enable-direct-threaded} or
9183: @code{--enable-indirect-threaded}. Note that direct threading is not
9184: supported on all machines.
9185:
9186: @node DOES>, , Direct or Indirect Threaded?, Threading
9187: @subsection DOES>
9188: @cindex @code{DOES>} implementation
9189:
9190: @cindex dodoes routine
9191: @cindex DOES-code
9192: One of the most complex parts of a Forth engine is @code{dodoes}, i.e.,
9193: the chunk of code executed by every word defined by a
9194: @code{CREATE}...@code{DOES>} pair. The main problem here is: How to find
9195: the Forth code to be executed, i.e. the code after the
9196: @code{DOES>} (the DOES-code)? There are two solutions:
9197:
1.21 crook 9198: In fig-Forth the code field points directly to the @code{dodoes} and the
1.1 anton 9199: DOES-code address is stored in the cell after the code address (i.e. at
9200: @code{@var{cfa} cell+}). It may seem that this solution is illegal in
9201: the Forth-79 and all later standards, because in fig-Forth this address
9202: lies in the body (which is illegal in these standards). However, by
9203: making the code field larger for all words this solution becomes legal
9204: again. We use this approach for the indirect threaded version and for
9205: direct threading on some machines. Leaving a cell unused in most words
9206: is a bit wasteful, but on the machines we are targeting this is hardly a
9207: problem. The other reason for having a code field size of two cells is
9208: to avoid having different image files for direct and indirect threaded
9209: systems (direct threaded systems require two-cell code fields on many
9210: machines).
9211:
9212: @cindex DOES-handler
9213: The other approach is that the code field points or jumps to the cell
9214: after @code{DOES}. In this variant there is a jump to @code{dodoes} at
9215: this address (the DOES-handler). @code{dodoes} can then get the
9216: DOES-code address by computing the code address, i.e., the address of
9217: the jump to dodoes, and add the length of that jump field. A variant of
9218: this is to have a call to @code{dodoes} after the @code{DOES>}; then the
9219: return address (which can be found in the return register on RISCs) is
9220: the DOES-code address. Since the two cells available in the code field
9221: are used up by the jump to the code address in direct threading on many
9222: architectures, we use this approach for direct threading on these
9223: architectures. We did not want to add another cell to the code field.
9224:
9225: @node Primitives, Performance, Threading, Engine
9226: @section Primitives
9227: @cindex primitives, implementation
9228: @cindex virtual machine instructions, implementation
9229:
9230: @menu
9231: * Automatic Generation::
9232: * TOS Optimization::
9233: * Produced code::
9234: @end menu
9235:
9236: @node Automatic Generation, TOS Optimization, Primitives, Primitives
9237: @subsection Automatic Generation
9238: @cindex primitives, automatic generation
9239:
9240: @cindex @file{prims2x.fs}
9241: Since the primitives are implemented in a portable language, there is no
9242: longer any need to minimize the number of primitives. On the contrary,
9243: having many primitives has an advantage: speed. In order to reduce the
9244: number of errors in primitives and to make programming them easier, we
9245: provide a tool, the primitive generator (@file{prims2x.fs}), that
9246: automatically generates most (and sometimes all) of the C code for a
9247: primitive from the stack effect notation. The source for a primitive
9248: has the following form:
9249:
9250: @cindex primitive source format
9251: @format
9252: @var{Forth-name} @var{stack-effect} @var{category} [@var{pronounc.}]
9253: [@code{""}@var{glossary entry}@code{""}]
9254: @var{C code}
9255: [@code{:}
9256: @var{Forth code}]
9257: @end format
9258:
9259: The items in brackets are optional. The category and glossary fields
9260: are there for generating the documentation, the Forth code is there
9261: for manual implementations on machines without GNU C. E.g., the source
9262: for the primitive @code{+} is:
9263: @example
9264: + n1 n2 -- n core plus
9265: n = n1+n2;
9266: @end example
9267:
9268: This looks like a specification, but in fact @code{n = n1+n2} is C
9269: code. Our primitive generation tool extracts a lot of information from
9270: the stack effect notations@footnote{We use a one-stack notation, even
9271: though we have separate data and floating-point stacks; The separate
9272: notation can be generated easily from the unified notation.}: The number
9273: of items popped from and pushed on the stack, their type, and by what
9274: name they are referred to in the C code. It then generates a C code
9275: prelude and postlude for each primitive. The final C code for @code{+}
9276: looks like this:
9277:
9278: @example
9279: I_plus: /* + ( n1 n2 -- n ) */ /* label, stack effect */
9280: /* */ /* documentation */
9281: @{
9282: DEF_CA /* definition of variable ca (indirect threading) */
9283: Cell n1; /* definitions of variables */
9284: Cell n2;
9285: Cell n;
9286: n1 = (Cell) sp[1]; /* input */
9287: n2 = (Cell) TOS;
9288: sp += 1; /* stack adjustment */
9289: NAME("+") /* debugging output (with -DDEBUG) */
9290: @{
9291: n = n1+n2; /* C code taken from the source */
9292: @}
9293: NEXT_P1; /* NEXT part 1 */
9294: TOS = (Cell)n; /* output */
9295: NEXT_P2; /* NEXT part 2 */
9296: @}
9297: @end example
9298:
9299: This looks long and inefficient, but the GNU C compiler optimizes quite
9300: well and produces optimal code for @code{+} on, e.g., the R3000 and the
9301: HP RISC machines: Defining the @code{n}s does not produce any code, and
9302: using them as intermediate storage also adds no cost.
9303:
9304: There are also other optimizations, that are not illustrated by this
9305: example: Assignments between simple variables are usually for free (copy
9306: propagation). If one of the stack items is not used by the primitive
9307: (e.g. in @code{drop}), the compiler eliminates the load from the stack
9308: (dead code elimination). On the other hand, there are some things that
9309: the compiler does not do, therefore they are performed by
9310: @file{prims2x.fs}: The compiler does not optimize code away that stores
9311: a stack item to the place where it just came from (e.g., @code{over}).
9312:
9313: While programming a primitive is usually easy, there are a few cases
9314: where the programmer has to take the actions of the generator into
9315: account, most notably @code{?dup}, but also words that do not (always)
9316: fall through to NEXT.
9317:
9318: @node TOS Optimization, Produced code, Automatic Generation, Primitives
9319: @subsection TOS Optimization
9320: @cindex TOS optimization for primitives
9321: @cindex primitives, keeping the TOS in a register
9322:
9323: An important optimization for stack machine emulators, e.g., Forth
9324: engines, is keeping one or more of the top stack items in
9325: registers. If a word has the stack effect @var{in1}...@var{inx} @code{--}
9326: @var{out1}...@var{outy}, keeping the top @var{n} items in registers
9327: @itemize @bullet
9328: @item
9329: is better than keeping @var{n-1} items, if @var{x>=n} and @var{y>=n},
9330: due to fewer loads from and stores to the stack.
9331: @item is slower than keeping @var{n-1} items, if @var{x<>y} and @var{x<n} and
9332: @var{y<n}, due to additional moves between registers.
9333: @end itemize
9334:
9335: @cindex -DUSE_TOS
9336: @cindex -DUSE_NO_TOS
9337: In particular, keeping one item in a register is never a disadvantage,
9338: if there are enough registers. Keeping two items in registers is a
9339: disadvantage for frequent words like @code{?branch}, constants,
9340: variables, literals and @code{i}. Therefore our generator only produces
9341: code that keeps zero or one items in registers. The generated C code
9342: covers both cases; the selection between these alternatives is made at
9343: C-compile time using the switch @code{-DUSE_TOS}. @code{TOS} in the C
9344: code for @code{+} is just a simple variable name in the one-item case,
9345: otherwise it is a macro that expands into @code{sp[0]}. Note that the
9346: GNU C compiler tries to keep simple variables like @code{TOS} in
9347: registers, and it usually succeeds, if there are enough registers.
9348:
9349: @cindex -DUSE_FTOS
9350: @cindex -DUSE_NO_FTOS
9351: The primitive generator performs the TOS optimization for the
9352: floating-point stack, too (@code{-DUSE_FTOS}). For floating-point
9353: operations the benefit of this optimization is even larger:
9354: floating-point operations take quite long on most processors, but can be
9355: performed in parallel with other operations as long as their results are
9356: not used. If the FP-TOS is kept in a register, this works. If
9357: it is kept on the stack, i.e., in memory, the store into memory has to
9358: wait for the result of the floating-point operation, lengthening the
9359: execution time of the primitive considerably.
9360:
9361: The TOS optimization makes the automatic generation of primitives a
9362: bit more complicated. Just replacing all occurrences of @code{sp[0]} by
9363: @code{TOS} is not sufficient. There are some special cases to
9364: consider:
9365: @itemize @bullet
9366: @item In the case of @code{dup ( w -- w w )} the generator must not
9367: eliminate the store to the original location of the item on the stack,
9368: if the TOS optimization is turned on.
9369: @item Primitives with stack effects of the form @code{--}
9370: @var{out1}...@var{outy} must store the TOS to the stack at the start.
9371: Likewise, primitives with the stack effect @var{in1}...@var{inx} @code{--}
9372: must load the TOS from the stack at the end. But for the null stack
9373: effect @code{--} no stores or loads should be generated.
9374: @end itemize
9375:
9376: @node Produced code, , TOS Optimization, Primitives
9377: @subsection Produced code
9378: @cindex primitives, assembly code listing
9379:
9380: @cindex @file{engine.s}
9381: To see what assembly code is produced for the primitives on your machine
9382: with your compiler and your flag settings, type @code{make engine.s} and
9383: look at the resulting file @file{engine.s}.
9384:
9385: @node Performance, , Primitives, Engine
9386: @section Performance
9387: @cindex performance of some Forth interpreters
9388: @cindex engine performance
9389: @cindex benchmarking Forth systems
9390: @cindex Gforth performance
9391:
9392: On RISCs the Gforth engine is very close to optimal; i.e., it is usually
9393: impossible to write a significantly faster engine.
9394:
9395: On register-starved machines like the 386 architecture processors
9396: improvements are possible, because @code{gcc} does not utilize the
9397: registers as well as a human, even with explicit register declarations;
9398: e.g., Bernd Beuster wrote a Forth system fragment in assembly language
9399: and hand-tuned it for the 486; this system is 1.19 times faster on the
9400: Sieve benchmark on a 486DX2/66 than Gforth compiled with
9401: @code{gcc-2.6.3} with @code{-DFORCE_REG}.
9402:
9403: @cindex Win32Forth performance
9404: @cindex NT Forth performance
9405: @cindex eforth performance
9406: @cindex ThisForth performance
9407: @cindex PFE performance
9408: @cindex TILE performance
9409: However, this potential advantage of assembly language implementations
9410: is not necessarily realized in complete Forth systems: We compared
9411: Gforth (direct threaded, compiled with @code{gcc-2.6.3} and
9412: @code{-DFORCE_REG}) with Win32Forth 1.2093, LMI's NT Forth (Beta, May
9413: 1994) and Eforth (with and without peephole (aka pinhole) optimization
9414: of the threaded code); all these systems were written in assembly
9415: language. We also compared Gforth with three systems written in C:
9416: PFE-0.9.14 (compiled with @code{gcc-2.6.3} with the default
9417: configuration for Linux: @code{-O2 -fomit-frame-pointer -DUSE_REGS
1.21 crook 9418: -DUNROLL_NEXT}), ThisForth Beta (compiled with @code{gcc-2.6.3 -O3
9419: -fomit-frame-pointer}; ThisForth employs peephole optimization of the
1.1 anton 9420: threaded code) and TILE (compiled with @code{make opt}). We benchmarked
9421: Gforth, PFE, ThisForth and TILE on a 486DX2/66 under Linux. Kenneth
9422: O'Heskin kindly provided the results for Win32Forth and NT Forth on a
9423: 486DX2/66 with similar memory performance under Windows NT. Marcel
9424: Hendrix ported Eforth to Linux, then extended it to run the benchmarks,
9425: added the peephole optimizer, ran the benchmarks and reported the
9426: results.
9427:
9428: We used four small benchmarks: the ubiquitous Sieve; bubble-sorting and
9429: matrix multiplication come from the Stanford integer benchmarks and have
9430: been translated into Forth by Martin Fraeman; we used the versions
9431: included in the TILE Forth package, but with bigger data set sizes; and
9432: a recursive Fibonacci number computation for benchmarking calling
9433: performance. The following table shows the time taken for the benchmarks
9434: scaled by the time taken by Gforth (in other words, it shows the speedup
9435: factor that Gforth achieved over the other systems).
9436:
9437: @example
9438: relative Win32- NT eforth This-
9439: time Gforth Forth Forth eforth +opt PFE Forth TILE
9440: sieve 1.00 1.39 1.14 1.39 0.85 1.58 3.18 8.58
9441: bubble 1.00 1.31 1.41 1.48 0.88 1.50 3.88
9442: matmul 1.00 1.47 1.35 1.46 0.74 1.58 4.09
9443: fib 1.00 1.52 1.34 1.22 0.86 1.74 2.99 4.30
9444: @end example
9445:
9446: You may find the good performance of Gforth compared with the systems
9447: written in assembly language quite surprising. One important reason for
9448: the disappointing performance of these systems is probably that they are
9449: not written optimally for the 486 (e.g., they use the @code{lods}
9450: instruction). In addition, Win32Forth uses a comfortable, but costly
9451: method for relocating the Forth image: like @code{cforth}, it computes
9452: the actual addresses at run time, resulting in two address computations
9453: per NEXT (@pxref{Image File Background}).
9454:
9455: Only Eforth with the peephole optimizer performs comparable to
9456: Gforth. The speedups achieved with peephole optimization of threaded
9457: code are quite remarkable. Adding a peephole optimizer to Gforth should
9458: cause similar speedups.
9459:
9460: The speedup of Gforth over PFE, ThisForth and TILE can be easily
9461: explained with the self-imposed restriction of the latter systems to
9462: standard C, which makes efficient threading impossible (however, the
1.4 anton 9463: measured implementation of PFE uses a GNU C extension: @pxref{Global Reg
1.1 anton 9464: Vars, , Defining Global Register Variables, gcc.info, GNU C Manual}).
9465: Moreover, current C compilers have a hard time optimizing other aspects
9466: of the ThisForth and the TILE source.
9467:
9468: Note that the performance of Gforth on 386 architecture processors
9469: varies widely with the version of @code{gcc} used. E.g., @code{gcc-2.5.8}
9470: failed to allocate any of the virtual machine registers into real
9471: machine registers by itself and would not work correctly with explicit
9472: register declarations, giving a 1.3 times slower engine (on a 486DX2/66
9473: running the Sieve) than the one measured above.
9474:
9475: Note also that there have been several releases of Win32Forth since the
9476: release presented here, so the results presented here may have little
9477: predictive value for the performance of Win32Forth today.
9478:
9479: @cindex @file{Benchres}
9480: In @cite{Translating Forth to Efficient C} by M. Anton Ertl and Martin
9481: Maierhofer (presented at EuroForth '95), an indirect threaded version of
9482: Gforth is compared with Win32Forth, NT Forth, PFE, and ThisForth; that
9483: version of Gforth is 2%@minus{}8% slower on a 486 than the direct
9484: threaded version used here. The paper available at
9485: @*@url{http://www.complang.tuwien.ac.at/papers/ertl&maierhofer95.ps.gz};
9486: it also contains numbers for some native code systems. You can find a
9487: newer version of these measurements at
9488: @url{http://www.complang.tuwien.ac.at/forth/performance.html}. You can
9489: find numbers for Gforth on various machines in @file{Benchres}.
9490:
1.13 pazsan 9491: @node Binding to System Library, Cross Compiler, Engine, Top
1.14 pazsan 9492: @chapter Binding to System Library
1.13 pazsan 9493:
9494: @node Cross Compiler, Bugs, Binding to System Library, Top
1.14 pazsan 9495: @chapter Cross Compiler
1.13 pazsan 9496:
9497: Cross Compiler
9498:
9499: @menu
9500: * Using the Cross Compiler::
9501: * How the Cross Compiler Works::
9502: @end menu
9503:
1.21 crook 9504: @node Using the Cross Compiler, How the Cross Compiler Works, Cross Compiler, Cross Compiler
1.14 pazsan 9505: @section Using the Cross Compiler
1.13 pazsan 9506:
1.21 crook 9507: @node How the Cross Compiler Works, , Using the Cross Compiler, Cross Compiler
1.14 pazsan 9508: @section How the Cross Compiler Works
1.13 pazsan 9509:
9510: @node Bugs, Origin, Cross Compiler, Top
1.21 crook 9511: @appendix Bugs
1.1 anton 9512: @cindex bug reporting
9513:
1.21 crook 9514: Known bugs are described in the file @file{BUGS} in the Gforth distribution.
1.1 anton 9515:
9516: If you find a bug, please send a bug report to
1.21 crook 9517: @email{bug-gforth@@gnu.ai.mit.edu}. A bug report should include this
9518: information:
9519:
9520: @itemize @bullet
9521: @item
9522: The Gforth version used (it is announced at the start of an
9523: interactive Gforth session).
9524: @item
9525: The machine and operating system (on Unix
9526: systems @code{uname -a} will report this information).
9527: @item
9528: The installation options (send the file @file{config.status}).
9529: @item
9530: A complete list of changes (if any) you (or your installer) have made to the
9531: Gforth sources.
9532: @item
9533: A program (or a sequence of keyboard commands) that reproduces the bug.
9534: @item
9535: A description of what you think constitutes the buggy behaviour.
9536: @end itemize
1.1 anton 9537:
9538: For a thorough guide on reporting bugs read @ref{Bug Reporting, , How
9539: to Report Bugs, gcc.info, GNU C Manual}.
9540:
9541:
1.21 crook 9542: @node Origin, Forth-related information, Bugs, Top
9543: @appendix Authors and Ancestors of Gforth
1.1 anton 9544:
9545: @section Authors and Contributors
9546: @cindex authors of Gforth
9547: @cindex contributors to Gforth
9548:
9549: The Gforth project was started in mid-1992 by Bernd Paysan and Anton
9550: Ertl. The third major author was Jens Wilke. Lennart Benschop (who was
9551: one of Gforth's first users, in mid-1993) and Stuart Ramsden inspired us
9552: with their continuous feedback. Lennart Benshop contributed
9553: @file{glosgen.fs}, while Stuart Ramsden has been working on automatic
9554: support for calling C libraries. Helpful comments also came from Paul
9555: Kleinrubatscher, Christian Pirker, Dirk Zoller, Marcel Hendrix, John
1.12 anton 9556: Wavrik, Barrie Stott, Marc de Groot, and Jorge Acerada. Since the
9557: release of Gforth-0.2.1 there were also helpful comments from many
9558: others; thank you all, sorry for not listing you here (but digging
1.23 ! crook 9559: through my mailbox to extract your names is on my to-do list). Since the
! 9560: release of Gforth-0.4.0 Neal Crook worked on the manual.
1.1 anton 9561:
9562: Gforth also owes a lot to the authors of the tools we used (GCC, CVS,
9563: and autoconf, among others), and to the creators of the Internet: Gforth
1.21 crook 9564: was developed across the Internet, and its authors did not meet
1.20 pazsan 9565: physically for the first 4 years of development.
1.1 anton 9566:
9567: @section Pedigree
9568: @cindex Pedigree of Gforth
9569:
1.20 pazsan 9570: Gforth descends from bigFORTH (1993) and fig-Forth. Gforth and PFE (by
1.1 anton 9571: Dirk Zoller) will cross-fertilize each other. Of course, a significant
9572: part of the design of Gforth was prescribed by ANS Forth.
9573:
1.20 pazsan 9574: Bernd Paysan wrote bigFORTH, a descendent from TurboForth, an unreleased
1.1 anton 9575: 32 bit native code version of VolksForth for the Atari ST, written
9576: mostly by Dietrich Weineck.
9577:
9578: VolksForth descends from F83. It was written by Klaus Schleisiek, Bernd
9579: Pennemann, Georg Rehfeld and Dietrich Weineck for the C64 (called
9580: UltraForth there) in the mid-80s and ported to the Atari ST in 1986.
9581:
9582: Henry Laxen and Mike Perry wrote F83 as a model implementation of the
9583: Forth-83 standard. !! Pedigree? When?
9584:
9585: A team led by Bill Ragsdale implemented fig-Forth on many processors in
9586: 1979. Robert Selzer and Bill Ragsdale developed the original
9587: implementation of fig-Forth for the 6502 based on microForth.
9588:
9589: The principal architect of microForth was Dean Sanderson. microForth was
9590: FORTH, Inc.'s first off-the-shelf product. It was developed in 1976 for
9591: the 1802, and subsequently implemented on the 8080, the 6800 and the
9592: Z80.
9593:
9594: All earlier Forth systems were custom-made, usually by Charles Moore,
9595: who discovered (as he puts it) Forth during the late 60s. The first full
9596: Forth existed in 1971.
9597:
9598: A part of the information in this section comes from @cite{The Evolution
9599: of Forth} by Elizabeth D. Rather, Donald R. Colburn and Charles
9600: H. Moore, presented at the HOPL-II conference and preprinted in SIGPLAN
9601: Notices 28(3), 1993. You can find more historical and genealogical
9602: information about Forth there.
9603:
1.21 crook 9604: @node Forth-related information, Word Index, Origin, Top
9605: @appendix Other Forth-related information
9606: @cindex Forth-related information
9607:
9608: @menu
9609: * Internet resources::
9610: * Books::
9611: * The Forth Interest Group::
9612: * Conferences::
9613: @end menu
9614:
9615:
9616: @node Internet resources, Books, Forth-related information, Forth-related information
9617: @section Internet resources
9618: @cindex Internet resources
9619:
9620: @cindex comp.lang.forth
9621: @cindex frequently asked questions
9622: There is an active newsgroup (comp.lang.forth) discussing Forth and
9623: Forth-related issues. A frequently-asked-questions (FAQ) list
9624: is posted to the newsgroup regulary, and archived at these sites:
9625:
9626: @itemize @bullet
9627: @item
9628: @url{ftp://rtfm.mit.edu/pub/usenet-by-group/comp.lang.forth/}
9629: @item
9630: @url{ftp://ftp.forth.org/pub/Forth/FAQ/}
9631: @end itemize
9632:
9633: The FAQ list should be considered mandatory reading before posting to
9634: the newsgroup.
9635:
9636: Here are some other web sites holding Forth-related material:
9637:
9638: @itemize @bullet
9639: @item
9640: @url{http://www.taygeta.com/forth.html} -- Skip Carter's Forth pages.
9641: @item
9642: @url{http://www.jwdt.com/~paysan/gforth.html} -- the Gforth home page.
9643: @item
9644: @url{http://www.minerva.com/uathena.htm} -- home of ANS Forth Standard.
9645: @item
9646: @url{http://dec.bournemouth.ac.uk/forth/index.html} -- the Forth
9647: Research page, including links to the Journal of Forth Application and
9648: Research (JFAR) and a searchable Forth bibliography.
9649: @end itemize
9650:
9651:
9652: @node Books, The Forth Interest Group, Internet resources, Forth-related information
9653: @section Books
9654: @cindex Books
9655:
9656: As the Standard is relatively new, there are not many books out yet. It
9657: is not recommended to learn Forth by using Gforth and a book that is not
9658: written for ANS Forth, as you will not know your mistakes from the
9659: deviations of the book. However, books based on the Forth-83 standard
9660: should be ok, because ANS Forth is primarily an extension of Forth-83.
9661:
9662: @cindex standard document for ANS Forth
9663: @cindex ANS Forth document
9664: The definite reference if you want to write ANS Forth programs is, of
9665: course, the ANS Forth Standard. It is available in printed form from the
9666: National Standards Institute Sales Department (Tel.: USA (212) 642-4900;
9667: Fax.: USA (212) 302-1286) as document @cite{X3.215-1994} for about
9668: $200. You can also get it from Global Engineering Documents (Tel.: USA
9669: (800) 854-7179; Fax.: (303) 843-9880) for about $300.
9670:
9671: @cite{dpANS6}, the last draft of the standard, which was then submitted
9672: to ANSI for publication is available electronically and for free in some
9673: MS Word format, and it has been converted to HTML
9674: (@url{http://www.taygeta.com/forth/dpans.html}; this is my favourite
9675: format); this HTML version also includes the answers to Requests for
9676: Interpretation (RFIs). Some pointers to these versions can be found
9677: through @*@url{http://www.complang.tuwien.ac.at/projects/forth.html}.
9678:
9679: @cindex introductory book
9680: @cindex book, introductory
9681: @cindex Woehr, Jack: @cite{Forth: The New Model}
9682: @cindex @cite{Forth: The new model} (book)
9683: @cite{Forth: The New Model} by Jack Woehr (Prentice-Hall, 1993) is an
9684: introductory book based on a draft version of the standard. It does not
9685: cover the whole standard. It also contains interesting background
9686: information (Jack Woehr was in the ANS Forth Technical Committee). It is
9687: not appropriate for complete newbies, but programmers experienced in
9688: other languages should find it ok.
9689:
9690: @cindex Conklin, Edward K., and Elizabeth Rather: @cite{Forth Programmer's Handbook}
9691: @cindex Rather, Elizabeth and Edward K. Conklin: @cite{Forth Programmer's Handbook}
9692: @cindex @cite{Forth Programmer's Handbook} (book)
9693: @cite{Forth Programmer's Handbook} by Edward K. Conklin, Elizabeth
9694: D. Rather and the technical staff of Forth, Inc. (Forth, Inc., 1997;
9695: ISBN 0-9662156-0-5) contains little introductory material. The majority
9696: of the book is similar to @ref{Words}, but the book covers most of the
9697: standard words and some non-standard words (whereas this manual is
9698: quite incomplete). In addition, the book contains a chapter on
9699: programming style. The major drawback of this book is that it usually
9700: does not identify what is standard and what is specific to the Forth
9701: system described in the book (probably one of Forth, Inc.'s systems).
9702: Fortunately, many of the non-standard programming practices described in
9703: the book work in Gforth, too. Still, this drawback makes the book
9704: hardly more useful than a pre-ANS book.
9705:
9706: @node The Forth Interest Group, Conferences, Books, Forth-related information
9707: @section The Forth Interest Group
9708: @cindex Forth interest group (FIG)
9709:
9710: The Forth Interest Group (FIG) is a world-wide, non-profit,
9711: member-supported organisation. It publishes a regular magazine and
9712: offers other benefits of membership. You can contact the FIG through
9713: their office email address: @email{office@@forth.org} or by visiting
9714: their web site at @url{http://www.forth.org/}. This web site also
9715: includes links to FIG chapters in other countries and American cities
9716: (@url{http://www.forth.org/chapters.html}).
9717:
9718: @node Conferences, , The Forth Interest Group, Forth-related information
9719: @section Conferences
9720: @cindex Conferences
9721:
9722: There are several regular conferences related to Forth. They are all
9723: well-publicised in FIG magazine and on the comp.lang.forth news group:
9724:
9725: @itemize @bullet
9726: @item
9727: FORML -- the Forth modification laboratory convenes every year near
9728: Monterey, California.
9729: @item
9730: The Rochester Forth Conference -- an annual conference traditionally
9731: held in Rochester, New York.
9732: @item
9733: EuroForth -- this European conference takes place annually.
9734: @end itemize
9735:
9736:
9737: @node Word Index, Concept Index, Forth-related information, Top
1.1 anton 9738: @unnumbered Word Index
9739:
9740: This index is as incomplete as the manual. Each word is listed with
9741: stack effect and wordset.
9742:
9743: @printindex fn
9744:
9745: @node Concept Index, , Word Index, Top
9746: @unnumbered Concept and Word Index
9747:
9748: This index is as incomplete as the manual. Not all entries listed are
9749: present verbatim in the text. Only the names are listed for the words
9750: here.
9751:
9752: @printindex cp
9753:
9754: @contents
9755: @bye
9756:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>