| @c Not an improvement IMO - anton |
@c Not an improvement IMO - anton |
| @c and anyway, this should be taken up |
@c and anyway, this should be taken up |
| @c with Karl Berry (the texinfo guy) - anton |
@c with Karl Berry (the texinfo guy) - anton |
| |
@c |
| |
@c Karl Berry writes: |
| |
@c If they don't like the all-caps for @var Info output, all I can say is |
| |
@c that it's always been that way, and the usage of all-caps for |
| |
@c metavariables has a long tradition. I think it's best to just let it be |
| |
@c what it is, for the sake of consistency among manuals. |
| |
@c |
| @comment .. would be useful to have a word that identified all deferred words |
@comment .. would be useful to have a word that identified all deferred words |
| @comment should semantics stuff in intro be moved to another section |
@comment should semantics stuff in intro be moved to another section |
| |
|
| |
|
| @comment %**start of header (This is for running Texinfo on a region.) |
@comment %**start of header (This is for running Texinfo on a region.) |
| @setfilename gforth.info |
@setfilename gforth.info |
| |
@include version.texi |
| @settitle Gforth Manual |
@settitle Gforth Manual |
| @dircategory GNU programming tools |
@c @syncodeindex pg cp |
| @direntry |
|
| * Gforth: (gforth). A fast interpreter for the Forth language. |
|
| @end direntry |
|
| @c The Texinfo manual also recommends doing this, but for Gforth it may |
|
| @c not make much sense |
|
| @c @dircategory Individual utilities |
|
| @c @direntry |
|
| @c * Gforth: (gforth)Invoking Gforth. gforth, gforth-fast, gforthmi |
|
| @c @end direntry |
|
| |
|
| @comment @setchapternewpage odd |
|
| @comment TODO this gets left in by HTML converter |
|
| @macro progstyle {} |
@macro progstyle {} |
| Programming style note: |
Programming style note: |
| @end macro |
@end macro |
| @end table |
@end table |
| @end macro |
@end macro |
| |
|
| @comment %**end of header (This is for running Texinfo on a region.) |
|
| |
|
| |
|
| @comment ---------------------------------------------------------- |
|
| @comment macros for beautifying glossary entries |
@comment macros for beautifying glossary entries |
| @comment if these are used, need to strip them out for HTML converter |
|
| @comment else they get repeated verbatim in HTML output. |
|
| @comment .. not working yet. |
|
| |
|
| @macro GLOSS-START {} |
@macro GLOSS-START {} |
| @iftex |
@iftex |
| @ninerm |
@ninerm |
| @end iftex |
@end iftex |
| @end macro |
@end macro |
| |
|
| @comment ---------------------------------------------------------- |
@comment %**end of header (This is for running Texinfo on a region.) |
| |
@copying |
| |
This manual is for Gforth (version @value{VERSION}, @value{UPDATED}), |
| @include version.texi |
a fast and portable implementation of the ANS Forth language. It |
| |
serves as reference manual, but it also contains an introduction to |
| |
Forth and a Forth tutorial. |
| |
|
| @ifnottex |
Copyright @copyright{} 1995, 1996, 1997, 1998, 2000, 2003, 2004,2005,2006,2007 Free Software Foundation, Inc. |
| This file documents Gforth @value{VERSION} |
|
| |
|
| Copyright @copyright{} 1995--2000 Free Software Foundation, Inc. |
@quotation |
| |
Permission is granted to copy, distribute and/or modify this document |
| |
under the terms of the GNU Free Documentation License, Version 1.1 or |
| |
any later version published by the Free Software Foundation; with no |
| |
Invariant Sections, with the Front-Cover texts being ``A GNU Manual,'' |
| |
and with the Back-Cover Texts as in (a) below. A copy of the |
| |
license is included in the section entitled ``GNU Free Documentation |
| |
License.'' |
| |
|
| |
(a) The FSF's Back-Cover Text is: ``You have freedom to copy and modify |
| |
this GNU Manual, like GNU software. Copies published by the Free |
| |
Software Foundation raise funds for GNU development.'' |
| |
@end quotation |
| |
@end copying |
| |
|
| Permission is granted to make and distribute verbatim copies of |
@dircategory Software development |
| this manual provided the copyright notice and this permission notice |
@direntry |
| are preserved on all copies. |
* Gforth: (gforth). A fast interpreter for the Forth language. |
| |
@end direntry |
| @ignore |
@c The Texinfo manual also recommends doing this, but for Gforth it may |
| Permission is granted to process this file through TeX and print the |
@c not make much sense |
| results, provided the printed document carries a copying permission |
@c @dircategory Individual utilities |
| notice identical to this one except for the removal of this paragraph |
@c @direntry |
| (this paragraph not being relevant to the printed manual). |
@c * Gforth: (gforth)Invoking Gforth. gforth, gforth-fast, gforthmi |
| |
@c @end direntry |
| @end ignore |
|
| Permission is granted to copy and distribute modified versions of this |
|
| manual under the conditions for verbatim copying, provided also that the |
|
| sections entitled "Distribution" and "General Public License" are |
|
| included exactly as in the original, and provided that the entire |
|
| resulting derived work is distributed under the terms of a permission |
|
| notice identical to this one. |
|
| |
|
| Permission is granted to copy and distribute translations of this manual |
|
| into another language, under the above conditions for modified versions, |
|
| except that the sections entitled "Distribution" and "General Public |
|
| License" may be included in a translation approved by the author instead |
|
| of in the original English. |
|
| @end ifnottex |
|
| |
|
| @finalout |
|
| @titlepage |
@titlepage |
| @sp 10 |
@title Gforth |
| @center @titlefont{Gforth Manual} |
@subtitle for version @value{VERSION}, @value{UPDATED} |
| @sp 2 |
@author Neal Crook |
| @center for version @value{VERSION} |
@author Anton Ertl |
| @sp 2 |
@author David Kuehling |
| @center Neal Crook |
@author Bernd Paysan |
| @center Anton Ertl |
@author Jens Wilke |
| @center Bernd Paysan |
|
| @center Jens Wilke |
|
| @sp 3 |
|
| @center This manual is permanently under construction and was last updated on 15-Mar-2000 |
|
| |
|
| @comment The following two commands start the copyright page. |
|
| @page |
@page |
| @vskip 0pt plus 1filll |
@vskip 0pt plus 1filll |
| Copyright @copyright{} 1995--2000 Free Software Foundation, Inc. |
@insertcopying |
| |
|
| @comment !! Published by ... or You can get a copy of this manual ... |
|
| |
|
| Permission is granted to make and distribute verbatim copies of |
|
| this manual provided the copyright notice and this permission notice |
|
| are preserved on all copies. |
|
| |
|
| Permission is granted to copy and distribute modified versions of this |
|
| manual under the conditions for verbatim copying, provided also that the |
|
| sections entitled "Distribution" and "General Public License" are |
|
| included exactly as in the original, and provided that the entire |
|
| resulting derived work is distributed under the terms of a permission |
|
| notice identical to this one. |
|
| |
|
| Permission is granted to copy and distribute translations of this manual |
|
| into another language, under the above conditions for modified versions, |
|
| except that the sections entitled "Distribution" and "General Public |
|
| License" may be included in a translation approved by the author instead |
|
| of in the original English. |
|
| @end titlepage |
@end titlepage |
| |
|
| @node Top, License, (dir), (dir) |
@contents |
| |
|
| @ifnottex |
@ifnottex |
| Gforth is a free implementation of ANS Forth available on many |
@node Top, Goals, (dir), (dir) |
| personal machines. This manual corresponds to version @value{VERSION}. |
@top Gforth |
| |
|
| |
@insertcopying |
| @end ifnottex |
@end ifnottex |
| |
|
| @menu |
@menu |
| * License:: The GPL |
|
| * Goals:: About the Gforth Project |
* Goals:: About the Gforth Project |
| * Gforth Environment:: Starting (and exiting) Gforth |
* Gforth Environment:: Starting (and exiting) Gforth |
| * Tutorial:: Hands-on Forth Tutorial |
* Tutorial:: Hands-on Forth Tutorial |
| * Emacs and Gforth:: The Gforth Mode |
* Emacs and Gforth:: The Gforth Mode |
| * Image Files:: @code{.fi} files contain compiled code |
* Image Files:: @code{.fi} files contain compiled code |
| * Engine:: The inner interpreter and the primitives |
* Engine:: The inner interpreter and the primitives |
| * Binding to System Library:: |
|
| * Cross Compiler:: The Cross Compiler |
* Cross Compiler:: The Cross Compiler |
| * Bugs:: How to report them |
* Bugs:: How to report them |
| * Origin:: Authors and ancestors of Gforth |
* Origin:: Authors and ancestors of Gforth |
| * Forth-related information:: Books and places to look on the WWW |
* Forth-related information:: Books and places to look on the WWW |
| |
* Licenses:: |
| * Word Index:: An item for each Forth word |
* Word Index:: An item for each Forth word |
| * Name Index:: Forth words, only names listed |
|
| * Concept Index:: A menu covering many topics |
* Concept Index:: A menu covering many topics |
| |
|
| @detailmenu --- The Detailed Node Listing --- |
@detailmenu |
| |
--- The Detailed Node Listing --- |
| |
|
| Gforth Environment |
Gforth Environment |
| |
|
| * Command-line editing:: |
* Command-line editing:: |
| * Environment variables:: that affect how Gforth starts up |
* Environment variables:: that affect how Gforth starts up |
| * Gforth Files:: What gets installed and where |
* Gforth Files:: What gets installed and where |
| |
* Gforth in pipes:: |
| * Startup speed:: When 35ms is not fast enough ... |
* Startup speed:: When 35ms is not fast enough ... |
| |
|
| Forth Tutorial |
Forth Tutorial |
| * Memory Tutorial:: |
* Memory Tutorial:: |
| * Characters and Strings Tutorial:: |
* Characters and Strings Tutorial:: |
| * Alignment Tutorial:: |
* Alignment Tutorial:: |
| |
* Floating Point Tutorial:: |
| |
* Files Tutorial:: |
| * Interpretation and Compilation Semantics and Immediacy Tutorial:: |
* Interpretation and Compilation Semantics and Immediacy Tutorial:: |
| * Execution Tokens Tutorial:: |
* Execution Tokens Tutorial:: |
| * Exceptions Tutorial:: |
* Exceptions Tutorial:: |
| * Defining Words:: |
* Defining Words:: |
| * Interpretation and Compilation Semantics:: |
* Interpretation and Compilation Semantics:: |
| * Tokens for Words:: |
* Tokens for Words:: |
| |
* Compiling words:: |
| * The Text Interpreter:: |
* The Text Interpreter:: |
| |
* The Input Stream:: |
| * Word Lists:: |
* Word Lists:: |
| * Environmental Queries:: |
* Environmental Queries:: |
| * Files:: |
* Files:: |
| * Blocks:: |
* Blocks:: |
| * Other I/O:: |
* Other I/O:: |
| |
* OS command line arguments:: |
| * Locals:: |
* Locals:: |
| * Structures:: |
* Structures:: |
| * Object-oriented Forth:: |
* Object-oriented Forth:: |
| * Programming Tools:: |
* Programming Tools:: |
| |
* C Interface:: |
| * Assembler and Code Words:: |
* Assembler and Code Words:: |
| * Threading Words:: |
* Threading Words:: |
| * Passing Commands to the OS:: |
* Passing Commands to the OS:: |
| * Anonymous Definitions:: Definitions without names |
* Anonymous Definitions:: Definitions without names |
| * Supplying names:: Passing definition names as strings |
* Supplying names:: Passing definition names as strings |
| * User-defined Defining Words:: |
* User-defined Defining Words:: |
| * Deferred words:: Allow forward references |
* Deferred Words:: Allow forward references |
| * Aliases:: |
* Aliases:: |
| |
|
| User-defined Defining Words |
User-defined Defining Words |
| * CREATE..DOES> applications:: |
* CREATE..DOES> applications:: |
| * CREATE..DOES> details:: |
* CREATE..DOES> details:: |
| * Advanced does> usage example:: |
* Advanced does> usage example:: |
| |
* Const-does>:: |
| |
|
| Interpretation and Compilation Semantics |
Interpretation and Compilation Semantics |
| |
|
| * Compilation token:: represents compilation semantics |
* Compilation token:: represents compilation semantics |
| * Name token:: represents named words |
* Name token:: represents named words |
| |
|
| |
Compiling words |
| |
|
| |
* Literals:: Compiling data values |
| |
* Macros:: Compiling words |
| |
|
| The Text Interpreter |
The Text Interpreter |
| |
|
| * Input Sources:: |
* Input Sources:: |
| * Number Conversion:: |
* Number Conversion:: |
| * Interpret/Compile states:: |
* Interpret/Compile states:: |
| * Literals:: |
|
| * Interpreter Directives:: |
* Interpreter Directives:: |
| |
|
| Word Lists |
Word Lists |
| |
|
| * Forth source files:: |
* Forth source files:: |
| * General files:: |
* General files:: |
| |
* Redirection:: |
| * Search Paths:: |
* Search Paths:: |
| |
|
| Search Paths |
Search Paths |
| * Formatted numeric output:: Formatted (pictured) output |
* Formatted numeric output:: Formatted (pictured) output |
| * String Formats:: How Forth stores strings in memory |
* String Formats:: How Forth stores strings in memory |
| * Displaying characters and strings:: Other stuff |
* Displaying characters and strings:: Other stuff |
| * Input:: Input |
* Terminal output:: Cursor positioning etc. |
| |
* Single-key input:: |
| |
* Line input and conversion:: |
| |
* Pipes:: How to create your own pipes |
| |
* Xchars and Unicode:: Non-ASCII characters |
| |
|
| Locals |
Locals |
| |
|
| * Structure Naming Convention:: |
* Structure Naming Convention:: |
| * Structure Implementation:: |
* Structure Implementation:: |
| * Structure Glossary:: |
* Structure Glossary:: |
| |
* Forth200x Structures:: |
| |
|
| Object-oriented Forth |
Object-oriented Forth |
| |
|
| |
|
| Programming Tools |
Programming Tools |
| |
|
| * Examining:: |
* Examining:: Data and Code. |
| * Forgetting words:: |
* Forgetting words:: Usually before reloading. |
| * Debugging:: Simple and quick. |
* Debugging:: Simple and quick. |
| * Assertions:: Making your programs self-checking. |
* Assertions:: Making your programs self-checking. |
| * Singlestep Debugger:: Executing your program word by word. |
* Singlestep Debugger:: Executing your program word by word. |
| |
|
| |
C Interface |
| |
|
| |
* Calling C Functions:: |
| |
* Declaring C Functions:: |
| |
* Calling C function pointers:: |
| |
* Callbacks:: |
| |
* C interface internals:: |
| |
* Low-Level C Interface Words:: |
| |
|
| Assembler and Code Words |
Assembler and Code Words |
| |
|
| * Code and ;code:: |
* Code and ;code:: |
| * 386 Assembler:: Deviations and special cases |
* 386 Assembler:: Deviations and special cases |
| * Alpha Assembler:: Deviations and special cases |
* Alpha Assembler:: Deviations and special cases |
| * MIPS assembler:: Deviations and special cases |
* MIPS assembler:: Deviations and special cases |
| |
* PowerPC assembler:: Deviations and special cases |
| |
* ARM Assembler:: Deviations and special cases |
| * Other assemblers:: How to write them |
* Other assemblers:: How to write them |
| |
|
| Tools |
Tools |
| |
|
| * ANS Report:: Report the words used, sorted by wordset. |
* ANS Report:: Report the words used, sorted by wordset. |
| |
* Stack depth changes:: Where does this stack item come from? |
| |
|
| ANS conformance |
ANS conformance |
| |
|
| * search-idef:: Implementation Defined Options |
* search-idef:: Implementation Defined Options |
| * search-ambcond:: Ambiguous Conditions |
* search-ambcond:: Ambiguous Conditions |
| |
|
| |
Emacs and Gforth |
| |
|
| |
* Installing gforth.el:: Making Emacs aware of Forth. |
| |
* Emacs Tags:: Viewing the source of a word in Emacs. |
| |
* Hilighting:: Making Forth code look prettier. |
| |
* Auto-Indentation:: Customizing auto-indentation. |
| |
* Blocks Files:: Reading and writing blocks files. |
| |
|
| Image Files |
Image Files |
| |
|
| * Image Licensing Issues:: Distribution terms for images. |
* Image Licensing Issues:: Distribution terms for images. |
| |
|
| * Scheduling:: |
* Scheduling:: |
| * Direct or Indirect Threaded?:: |
* Direct or Indirect Threaded?:: |
| |
* Dynamic Superinstructions:: |
| * DOES>:: |
* DOES>:: |
| |
|
| Primitives |
Primitives |
| * Using the Cross Compiler:: |
* Using the Cross Compiler:: |
| * How the Cross Compiler Works:: |
* How the Cross Compiler Works:: |
| |
|
| Other Forth-related information |
Licenses |
| |
|
| * Internet resources:: |
* GNU Free Documentation License:: License for copying this manual. |
| * Books:: |
* Copying:: GPL (for copying this software). |
| * The Forth Interest Group:: |
|
| * Conferences:: |
|
| |
|
| @end detailmenu |
@end detailmenu |
| @end menu |
@end menu |
| |
|
| @node License, Goals, Top, Top |
@c ---------------------------------------------------------- |
| @unnumbered GNU GENERAL PUBLIC LICENSE |
|
| @center Version 2, June 1991 |
|
| |
|
| @display |
|
| Copyright @copyright{} 1989, 1991 Free Software Foundation, Inc. |
|
| 675 Mass Ave, Cambridge, MA 02139, USA |
|
| |
|
| Everyone is permitted to copy and distribute verbatim copies |
|
| of this license document, but changing it is not allowed. |
|
| @end display |
|
| |
|
| @unnumberedsec Preamble |
|
| |
|
| The licenses for most software are designed to take away your |
|
| freedom to share and change it. By contrast, the GNU General Public |
|
| License is intended to guarantee your freedom to share and change free |
|
| software---to make sure the software is free for all its users. This |
|
| General Public License applies to most of the Free Software |
|
| Foundation's software and to any other program whose authors commit to |
|
| using it. (Some other Free Software Foundation software is covered by |
|
| the GNU Library General Public License instead.) You can apply it to |
|
| your programs, too. |
|
| |
|
| When we speak of free software, we are referring to freedom, not |
|
| price. Our General Public Licenses are designed to make sure that you |
|
| have the freedom to distribute copies of free software (and charge for |
|
| this service if you wish), that you receive source code or can get it |
|
| if you want it, that you can change the software or use pieces of it |
|
| in new free programs; and that you know you can do these things. |
|
| |
|
| To protect your rights, we need to make restrictions that forbid |
|
| anyone to deny you these rights or to ask you to surrender the rights. |
|
| These restrictions translate to certain responsibilities for you if you |
|
| distribute copies of the software, or if you modify it. |
|
| |
|
| For example, if you distribute copies of such a program, whether |
|
| gratis or for a fee, you must give the recipients all the rights that |
|
| you have. You must make sure that they, too, receive or can get the |
|
| source code. And you must show them these terms so they know their |
|
| rights. |
|
| |
|
| We protect your rights with two steps: (1) copyright the software, and |
|
| (2) offer you this license which gives you legal permission to copy, |
|
| distribute and/or modify the software. |
|
| |
|
| Also, for each author's protection and ours, we want to make certain |
|
| that everyone understands that there is no warranty for this free |
|
| software. If the software is modified by someone else and passed on, we |
|
| want its recipients to know that what they have is not the original, so |
|
| that any problems introduced by others will not reflect on the original |
|
| authors' reputations. |
|
| |
|
| Finally, any free program is threatened constantly by software |
|
| patents. We wish to avoid the danger that redistributors of a free |
|
| program will individually obtain patent licenses, in effect making the |
|
| program proprietary. To prevent this, we have made it clear that any |
|
| patent must be licensed for everyone's free use or not licensed at all. |
|
| |
|
| The precise terms and conditions for copying, distribution and |
|
| modification follow. |
|
| |
|
| @iftex |
|
| @unnumberedsec TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION |
|
| @end iftex |
|
| @ifnottex |
|
| @center TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION |
|
| @end ifnottex |
|
| |
|
| @enumerate 0 |
|
| @item |
|
| This License applies to any program or other work which contains |
|
| a notice placed by the copyright holder saying it may be distributed |
|
| under the terms of this General Public License. The ``Program'', below, |
|
| refers to any such program or work, and a ``work based on the Program'' |
|
| means either the Program or any derivative work under copyright law: |
|
| that is to say, a work containing the Program or a portion of it, |
|
| either verbatim or with modifications and/or translated into another |
|
| language. (Hereinafter, translation is included without limitation in |
|
| the term ``modification''.) Each licensee is addressed as ``you''. |
|
| |
|
| Activities other than copying, distribution and modification are not |
|
| covered by this License; they are outside its scope. The act of |
|
| running the Program is not restricted, and the output from the Program |
|
| is covered only if its contents constitute a work based on the |
|
| Program (independent of having been made by running the Program). |
|
| Whether that is true depends on what the Program does. |
|
| |
|
| @item |
|
| You may copy and distribute verbatim copies of the Program's |
|
| source code as you receive it, in any medium, provided that you |
|
| conspicuously and appropriately publish on each copy an appropriate |
|
| copyright notice and disclaimer of warranty; keep intact all the |
|
| notices that refer to this License and to the absence of any warranty; |
|
| and give any other recipients of the Program a copy of this License |
|
| along with the Program. |
|
| |
|
| You may charge a fee for the physical act of transferring a copy, and |
|
| you may at your option offer warranty protection in exchange for a fee. |
|
| |
|
| @item |
|
| You may modify your copy or copies of the Program or any portion |
|
| of it, thus forming a work based on the Program, and copy and |
|
| distribute such modifications or work under the terms of Section 1 |
|
| above, provided that you also meet all of these conditions: |
|
| |
|
| @enumerate a |
|
| @item |
|
| You must cause the modified files to carry prominent notices |
|
| stating that you changed the files and the date of any change. |
|
| |
|
| @item |
|
| You must cause any work that you distribute or publish, that in |
|
| whole or in part contains or is derived from the Program or any |
|
| part thereof, to be licensed as a whole at no charge to all third |
|
| parties under the terms of this License. |
|
| |
|
| @item |
|
| If the modified program normally reads commands interactively |
|
| when run, you must cause it, when started running for such |
|
| interactive use in the most ordinary way, to print or display an |
|
| announcement including an appropriate copyright notice and a |
|
| notice that there is no warranty (or else, saying that you provide |
|
| a warranty) and that users may redistribute the program under |
|
| these conditions, and telling the user how to view a copy of this |
|
| License. (Exception: if the Program itself is interactive but |
|
| does not normally print such an announcement, your work based on |
|
| the Program is not required to print an announcement.) |
|
| @end enumerate |
|
| |
|
| These requirements apply to the modified work as a whole. If |
|
| identifiable sections of that work are not derived from the Program, |
|
| and can be reasonably considered independent and separate works in |
|
| themselves, then this License, and its terms, do not apply to those |
|
| sections when you distribute them as separate works. But when you |
|
| distribute the same sections as part of a whole which is a work based |
|
| on the Program, the distribution of the whole must be on the terms of |
|
| this License, whose permissions for other licensees extend to the |
|
| entire whole, and thus to each and every part regardless of who wrote it. |
|
| |
|
| Thus, it is not the intent of this section to claim rights or contest |
|
| your rights to work written entirely by you; rather, the intent is to |
|
| exercise the right to control the distribution of derivative or |
|
| collective works based on the Program. |
|
| |
|
| In addition, mere aggregation of another work not based on the Program |
|
| with the Program (or with a work based on the Program) on a volume of |
|
| a storage or distribution medium does not bring the other work under |
|
| the scope of this License. |
|
| |
|
| @item |
|
| You may copy and distribute the Program (or a work based on it, |
|
| under Section 2) in object code or executable form under the terms of |
|
| Sections 1 and 2 above provided that you also do one of the following: |
|
| |
|
| @enumerate a |
|
| @item |
|
| Accompany it with the complete corresponding machine-readable |
|
| source code, which must be distributed under the terms of Sections |
|
| 1 and 2 above on a medium customarily used for software interchange; or, |
|
| |
|
| @item |
|
| Accompany it with a written offer, valid for at least three |
|
| years, to give any third party, for a charge no more than your |
|
| cost of physically performing source distribution, a complete |
|
| machine-readable copy of the corresponding source code, to be |
|
| distributed under the terms of Sections 1 and 2 above on a medium |
|
| customarily used for software interchange; or, |
|
| |
|
| @item |
|
| Accompany it with the information you received as to the offer |
|
| to distribute corresponding source code. (This alternative is |
|
| allowed only for noncommercial distribution and only if you |
|
| received the program in object code or executable form with such |
|
| an offer, in accord with Subsection b above.) |
|
| @end enumerate |
|
| |
|
| The source code for a work means the preferred form of the work for |
|
| making modifications to it. For an executable work, complete source |
|
| code means all the source code for all modules it contains, plus any |
|
| associated interface definition files, plus the scripts used to |
|
| control compilation and installation of the executable. However, as a |
|
| special exception, the source code distributed need not include |
|
| anything that is normally distributed (in either source or binary |
|
| form) with the major components (compiler, kernel, and so on) of the |
|
| operating system on which the executable runs, unless that component |
|
| itself accompanies the executable. |
|
| |
|
| If distribution of executable or object code is made by offering |
|
| access to copy from a designated place, then offering equivalent |
|
| access to copy the source code from the same place counts as |
|
| distribution of the source code, even though third parties are not |
|
| compelled to copy the source along with the object code. |
|
| |
|
| @item |
|
| You may not copy, modify, sublicense, or distribute the Program |
|
| except as expressly provided under this License. Any attempt |
|
| otherwise to copy, modify, sublicense or distribute the Program is |
|
| void, and will automatically terminate your rights under this License. |
|
| However, parties who have received copies, or rights, from you under |
|
| this License will not have their licenses terminated so long as such |
|
| parties remain in full compliance. |
|
| |
|
| @item |
|
| You are not required to accept this License, since you have not |
|
| signed it. However, nothing else grants you permission to modify or |
|
| distribute the Program or its derivative works. These actions are |
|
| prohibited by law if you do not accept this License. Therefore, by |
|
| modifying or distributing the Program (or any work based on the |
|
| Program), you indicate your acceptance of this License to do so, and |
|
| all its terms and conditions for copying, distributing or modifying |
|
| the Program or works based on it. |
|
| |
|
| @item |
|
| Each time you redistribute the Program (or any work based on the |
|
| Program), the recipient automatically receives a license from the |
|
| original licensor to copy, distribute or modify the Program subject to |
|
| these terms and conditions. You may not impose any further |
|
| restrictions on the recipients' exercise of the rights granted herein. |
|
| You are not responsible for enforcing compliance by third parties to |
|
| this License. |
|
| |
|
| @item |
|
| If, as a consequence of a court judgment or allegation of patent |
|
| infringement or for any other reason (not limited to patent issues), |
|
| conditions are imposed on you (whether by court order, agreement or |
|
| otherwise) that contradict the conditions of this License, they do not |
|
| excuse you from the conditions of this License. If you cannot |
|
| distribute so as to satisfy simultaneously your obligations under this |
|
| License and any other pertinent obligations, then as a consequence you |
|
| may not distribute the Program at all. For example, if a patent |
|
| license would not permit royalty-free redistribution of the Program by |
|
| all those who receive copies directly or indirectly through you, then |
|
| the only way you could satisfy both it and this License would be to |
|
| refrain entirely from distribution of the Program. |
|
| |
|
| If any portion of this section is held invalid or unenforceable under |
|
| any particular circumstance, the balance of the section is intended to |
|
| apply and the section as a whole is intended to apply in other |
|
| circumstances. |
|
| |
|
| It is not the purpose of this section to induce you to infringe any |
|
| patents or other property right claims or to contest validity of any |
|
| such claims; this section has the sole purpose of protecting the |
|
| integrity of the free software distribution system, which is |
|
| implemented by public license practices. Many people have made |
|
| generous contributions to the wide range of software distributed |
|
| through that system in reliance on consistent application of that |
|
| system; it is up to the author/donor to decide if he or she is willing |
|
| to distribute software through any other system and a licensee cannot |
|
| impose that choice. |
|
| |
|
| This section is intended to make thoroughly clear what is believed to |
|
| be a consequence of the rest of this License. |
|
| |
|
| @item |
|
| If the distribution and/or use of the Program is restricted in |
|
| certain countries either by patents or by copyrighted interfaces, the |
|
| original copyright holder who places the Program under this License |
|
| may add an explicit geographical distribution limitation excluding |
|
| those countries, so that distribution is permitted only in or among |
|
| countries not thus excluded. In such case, this License incorporates |
|
| the limitation as if written in the body of this License. |
|
| |
|
| @item |
|
| The Free Software Foundation may publish revised and/or new versions |
|
| of the General Public License from time to time. Such new versions will |
|
| be similar in spirit to the present version, but may differ in detail to |
|
| address new problems or concerns. |
|
| |
|
| Each version is given a distinguishing version number. If the Program |
|
| specifies a version number of this License which applies to it and ``any |
|
| later version'', you have the option of following the terms and conditions |
|
| either of that version or of any later version published by the Free |
|
| Software Foundation. If the Program does not specify a version number of |
|
| this License, you may choose any version ever published by the Free Software |
|
| Foundation. |
|
| |
|
| @item |
|
| If you wish to incorporate parts of the Program into other free |
|
| programs whose distribution conditions are different, write to the author |
|
| to ask for permission. For software which is copyrighted by the Free |
|
| Software Foundation, write to the Free Software Foundation; we sometimes |
|
| make exceptions for this. Our decision will be guided by the two goals |
|
| of preserving the free status of all derivatives of our free software and |
|
| of promoting the sharing and reuse of software generally. |
|
| |
|
| @iftex |
|
| @heading NO WARRANTY |
|
| @end iftex |
|
| @ifnottex |
|
| @center NO WARRANTY |
|
| @end ifnottex |
|
| |
|
| @item |
|
| BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY |
|
| FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN |
|
| OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES |
|
| PROVIDE THE PROGRAM ``AS IS'' WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED |
|
| OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF |
|
| MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS |
|
| TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE |
|
| PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, |
|
| REPAIR OR CORRECTION. |
|
| |
|
| @item |
|
| IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING |
|
| WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR |
|
| REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, |
|
| INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING |
|
| OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED |
|
| TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY |
|
| YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER |
|
| PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE |
|
| POSSIBILITY OF SUCH DAMAGES. |
|
| @end enumerate |
|
| |
|
| @iftex |
|
| @heading END OF TERMS AND CONDITIONS |
|
| @end iftex |
|
| @ifnottex |
|
| @center END OF TERMS AND CONDITIONS |
|
| @end ifnottex |
|
| |
|
| @page |
|
| @unnumberedsec How to Apply These Terms to Your New Programs |
|
| |
|
| If you develop a new program, and you want it to be of the greatest |
|
| possible use to the public, the best way to achieve this is to make it |
|
| free software which everyone can redistribute and change under these terms. |
|
| |
|
| To do so, attach the following notices to the program. It is safest |
|
| to attach them to the start of each source file to most effectively |
|
| convey the exclusion of warranty; and each file should have at least |
|
| the ``copyright'' line and a pointer to where the full notice is found. |
|
| |
|
| @smallexample |
|
| @var{one line to give the program's name and a brief idea of what it does.} |
|
| Copyright (C) 19@var{yy} @var{name of author} |
|
| |
|
| This program is free software; you can redistribute it and/or modify |
|
| it under the terms of the GNU General Public License as published by |
|
| the Free Software Foundation; either version 2 of the License, or |
|
| (at your option) any later version. |
|
| |
|
| This program is distributed in the hope that it will be useful, |
|
| but WITHOUT ANY WARRANTY; without even the implied warranty of |
|
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
|
| GNU General Public License for more details. |
|
| |
|
| You should have received a copy of the GNU General Public License |
|
| along with this program; if not, write to the Free Software |
|
| Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. |
|
| @end smallexample |
|
| |
|
| Also add information on how to contact you by electronic and paper mail. |
|
| |
|
| If the program is interactive, make it output a short notice like this |
|
| when it starts in an interactive mode: |
|
| |
|
| @smallexample |
|
| Gnomovision version 69, Copyright (C) 19@var{yy} @var{name of author} |
|
| Gnomovision comes with ABSOLUTELY NO WARRANTY; for details |
|
| type `show w'. |
|
| This is free software, and you are welcome to redistribute it |
|
| under certain conditions; type `show c' for details. |
|
| @end smallexample |
|
| |
|
| The hypothetical commands @samp{show w} and @samp{show c} should show |
|
| the appropriate parts of the General Public License. Of course, the |
|
| commands you use may be called something other than @samp{show w} and |
|
| @samp{show c}; they could even be mouse-clicks or menu items---whatever |
|
| suits your program. |
|
| |
|
| You should also get your employer (if you work as a programmer) or your |
|
| school, if any, to sign a ``copyright disclaimer'' for the program, if |
|
| necessary. Here is a sample; alter the names: |
|
| |
|
| @smallexample |
|
| Yoyodyne, Inc., hereby disclaims all copyright interest in the program |
|
| `Gnomovision' (which makes passes at compilers) written by James Hacker. |
|
| |
|
| @var{signature of Ty Coon}, 1 April 1989 |
|
| Ty Coon, President of Vice |
|
| @end smallexample |
|
| |
|
| This General Public License does not permit incorporating your program into |
|
| proprietary programs. If your program is a subroutine library, you may |
|
| consider it more useful to permit linking proprietary applications with the |
|
| library. If this is what you want to do, use the GNU Library General |
|
| Public License instead of this License. |
|
| |
|
| @iftex |
@iftex |
| @unnumbered Preface |
@unnumbered Preface |
| @cindex Preface |
@cindex Preface |
| @comment TODO much more blurb here. |
@comment TODO much more blurb here. |
| |
|
| @c ****************************************************************** |
@c ****************************************************************** |
| @node Goals, Gforth Environment, License, Top |
@node Goals, Gforth Environment, Top, Top |
| @comment node-name, next, previous, up |
@comment node-name, next, previous, up |
| @chapter Goals of Gforth |
@chapter Goals of Gforth |
| @cindex goals of the Gforth project |
@cindex goals of the Gforth project |
| * Command-line editing:: |
* Command-line editing:: |
| * Environment variables:: that affect how Gforth starts up |
* Environment variables:: that affect how Gforth starts up |
| * Gforth Files:: What gets installed and where |
* Gforth Files:: What gets installed and where |
| |
* Gforth in pipes:: |
| * Startup speed:: When 35ms is not fast enough ... |
* Startup speed:: When 35ms is not fast enough ... |
| @end menu |
@end menu |
| |
|
| @cindex flags on the command line |
@cindex flags on the command line |
| |
|
| Gforth is made up of two parts; an executable ``engine'' (named |
Gforth is made up of two parts; an executable ``engine'' (named |
| @file{gforth} or @file{gforth-fast}) and an image file. To start it, you |
@command{gforth} or @command{gforth-fast}) and an image file. To start it, you |
| will usually just say @code{gforth} -- this automatically loads the |
will usually just say @code{gforth} -- this automatically loads the |
| default image file @file{gforth.fi}. In many other cases the default |
default image file @file{gforth.fi}. In many other cases the default |
| Gforth image will be invoked like this: |
Gforth image will be invoked like this: |
| This interprets the contents of the files and the Forth code in the order they |
This interprets the contents of the files and the Forth code in the order they |
| are given. |
are given. |
| |
|
| In addition to the @file{gforth} engine, there is also an engine called |
In addition to the @command{gforth} engine, there is also an engine |
| @file{gforth-fast}, which is faster, but gives less informative error |
called @command{gforth-fast}, which is faster, but gives less |
| messages (@pxref{Error messages}). |
informative error messages (@pxref{Error messages}) and may catch some |
| |
errors (in particular, stack underflows and integer division errors) |
| |
later or not at all. You should use it for debugged, |
| |
performance-critical programs. |
| |
|
| |
Moreover, there is an engine called @command{gforth-itc}, which is |
| |
useful in some backwards-compatibility situations (@pxref{Direct or |
| |
Indirect Threaded?}). |
| |
|
| In general, the command line looks like this: |
In general, the command line looks like this: |
| |
|
| Allocate @i{size} space for the locals stack instead of using the |
Allocate @i{size} space for the locals stack instead of using the |
| default specified in the image (typically 14.5K). |
default specified in the image (typically 14.5K). |
| |
|
| |
@cindex --vm-commit, command-line option |
| |
@cindex overcommit memory for dictionary and stacks |
| |
@cindex memory overcommit for dictionary and stacks |
| |
@item --vm-commit |
| |
Normally, Gforth tries to start up even if there is not enough virtual |
| |
memory for the dictionary and the stacks (using @code{MAP_NORESERVE} |
| |
on OSs that support it); so you can ask for a really big dictionary |
| |
and/or stacks, and as long as you don't use more virtual memory than |
| |
is available, everything will be fine (but if you use more, processes |
| |
get killed). With this option you just use the default allocation |
| |
policy of the OS; for OSs that don't overcommit (e.g., Solaris), this |
| |
means that you cannot and should not ask for as big dictionary and |
| |
stacks, but once Gforth successfully starts up, out-of-memory won't |
| |
kill it. |
| |
|
| @cindex -h, command-line option |
@cindex -h, command-line option |
| @cindex --help, command-line option |
@cindex --help, command-line option |
| @item --help |
@item --help |
| signal. This option is useful when the engine and/or the image might be |
signal. This option is useful when the engine and/or the image might be |
| severely broken (such that it causes another signal before recovering |
severely broken (such that it causes another signal before recovering |
| from the first); this option avoids endless loops in such cases. |
from the first); this option avoids endless loops in such cases. |
| |
|
| |
@cindex --no-dynamic, command-line option |
| |
@cindex --dynamic, command-line option |
| |
@item --no-dynamic |
| |
@item --dynamic |
| |
Disable or enable dynamic superinstructions with replication |
| |
(@pxref{Dynamic Superinstructions}). |
| |
|
| |
@cindex --no-super, command-line option |
| |
@item --no-super |
| |
Disable dynamic superinstructions, use just dynamic replication; this is |
| |
useful if you want to patch threaded code (@pxref{Dynamic |
| |
Superinstructions}). |
| |
|
| |
@cindex --ss-number, command-line option |
| |
@item --ss-number=@var{N} |
| |
Use only the first @var{N} static superinstructions compiled into the |
| |
engine (default: use them all; note that only @code{gforth-fast} has |
| |
any). This option is useful for measuring the performance impact of |
| |
static superinstructions. |
| |
|
| |
@cindex --ss-min-..., command-line options |
| |
@item --ss-min-codesize |
| |
@item --ss-min-ls |
| |
@item --ss-min-lsu |
| |
@item --ss-min-nexts |
| |
Use specified metric for determining the cost of a primitive or static |
| |
superinstruction for static superinstruction selection. @code{Codesize} |
| |
is the native code size of the primive or static superinstruction, |
| |
@code{ls} is the number of loads and stores, @code{lsu} is the number of |
| |
loads, stores, and updates, and @code{nexts} is the number of dispatches |
| |
(not taking dynamic superinstructions into account), i.e. every |
| |
primitive or static superinstruction has cost 1. Default: |
| |
@code{codesize} if you use dynamic code generation, otherwise |
| |
@code{nexts}. |
| |
|
| |
@cindex --ss-greedy, command-line option |
| |
@item --ss-greedy |
| |
This option is useful for measuring the performance impact of static |
| |
superinstructions. By default, an optimal shortest-path algorithm is |
| |
used for selecting static superinstructions. With @option{--ss-greedy} |
| |
this algorithm is modified to assume that anything after the static |
| |
superinstruction currently under consideration is not combined into |
| |
static superinstructions. With @option{--ss-min-nexts} this produces |
| |
the same result as a greedy algorithm that always selects the longest |
| |
superinstruction available at the moment. E.g., if there are |
| |
superinstructions AB and BCD, then for the sequence A B C D the optimal |
| |
algorithm will select A BCD and the greedy algorithm will select AB C D. |
| |
|
| |
@cindex --print-metrics, command-line option |
| |
@item --print-metrics |
| |
Prints some metrics used during static superinstruction selection: |
| |
@code{code size} is the actual size of the dynamically generated code. |
| |
@code{Metric codesize} is the sum of the codesize metrics as seen by |
| |
static superinstruction selection; there is a difference from @code{code |
| |
size}, because not all primitives and static superinstructions are |
| |
compiled into dynamically generated code, and because of markers. The |
| |
other metrics correspond to the @option{ss-min-...} options. This |
| |
option is useful for evaluating the effects of the @option{--ss-...} |
| |
options. |
| |
|
| @end table |
@end table |
| |
|
| @cindex loading files at startup |
@cindex loading files at startup |
| default image @file{gforth.fi} consist of a sequence of filenames and |
default image @file{gforth.fi} consist of a sequence of filenames and |
| @code{-e @var{forth-code}} options that are interpreted in the sequence |
@code{-e @var{forth-code}} options that are interpreted in the sequence |
| in which they are given. The @code{-e @var{forth-code}} or |
in which they are given. The @code{-e @var{forth-code}} or |
| @code{--evaluate @var{forth-code}} option evaluates the Forth |
@code{--evaluate @var{forth-code}} option evaluates the Forth code. This |
| code. This option takes only one argument; if you want to evaluate more |
option takes only one argument; if you want to evaluate more Forth |
| Forth words, you have to quote them or use @code{-e} several times. To exit |
words, you have to quote them or use @code{-e} several times. To exit |
| after processing the command line (instead of entering interactive mode) |
after processing the command line (instead of entering interactive mode) |
| append @code{-e bye} to the command line. |
append @code{-e bye} to the command line. You can also process the |
| |
command-line arguments with a Forth program (@pxref{OS command line |
| |
arguments}). |
| |
|
| @cindex versions, invoking other versions of Gforth |
@cindex versions, invoking other versions of Gforth |
| If you have several versions of Gforth installed, @code{gforth} will |
If you have several versions of Gforth installed, @code{gforth} will |
| for Forth source-code files. |
for Forth source-code files. |
| |
|
| @item |
@item |
| |
@cindex @code{LANG} -- environment variable |
| |
@code{LANG} -- see @code{LC_CTYPE} |
| |
|
| |
@item |
| |
@cindex @code{LC_ALL} -- environment variable |
| |
@code{LC_ALL} -- see @code{LC_CTYPE} |
| |
|
| |
@item |
| |
@cindex @code{LC_CTYPE} -- environment variable |
| |
@code{LC_CTYPE} -- If this variable contains ``UTF-8'' on Gforth |
| |
startup, Gforth uses the UTF-8 encoding for strings internally and |
| |
expects its input and produces its output in UTF-8 encoding, otherwise |
| |
the encoding is 8bit (see @pxref{Xchars and Unicode}). If this |
| |
environment variable is unset, Gforth looks in @code{LC_ALL}, and if |
| |
that is unset, in @code{LANG}. |
| |
|
| |
@item |
| |
@cindex @code{GFORTHSYSTEMPREFIX} -- environment variable |
| |
|
| |
@code{GFORTHSYSTEMPREFIX} -- specifies what to prepend to the argument |
| |
of @code{system} before passing it to C's @code{system()}. Default: |
| |
@code{"./$COMSPEC /c "} on Windows, @code{""} on other OSs. The prefix |
| |
and the command are directly concatenated, so if a space between them is |
| |
necessary, append it to the prefix. |
| |
|
| |
@item |
| @cindex @code{GFORTH} -- environment variable |
@cindex @code{GFORTH} -- environment variable |
| @code{GFORTH} -- used by @file{gforthmi}, @xref{gforthmi}. |
@code{GFORTH} -- used by @file{gforthmi}, @xref{gforthmi}. |
| |
|
| |
|
| |
|
| @comment ---------------------------------------------- |
@comment ---------------------------------------------- |
| @node Gforth Files, Startup speed, Environment variables, Gforth Environment |
@node Gforth Files, Gforth in pipes, Environment variables, Gforth Environment |
| @section Gforth files |
@section Gforth files |
| @cindex Gforth files |
@cindex Gforth files |
| |
|
| @code{configure} options (listed with @code{configure --help}). |
@code{configure} options (listed with @code{configure --help}). |
| |
|
| @comment ---------------------------------------------- |
@comment ---------------------------------------------- |
| @node Startup speed, , Gforth Files, Gforth Environment |
@node Gforth in pipes, Startup speed, Gforth Files, Gforth Environment |
| |
@section Gforth in pipes |
| |
@cindex pipes, Gforth as part of |
| |
|
| |
Gforth can be used in pipes created elsewhere (described here). It can |
| |
also create pipes on its own (@pxref{Pipes}). |
| |
|
| |
@cindex input from pipes |
| |
If you pipe into Gforth, your program should read with @code{read-file} |
| |
or @code{read-line} from @code{stdin} (@pxref{General files}). |
| |
@code{Key} does not recognize the end of input. Words like |
| |
@code{accept} echo the input and are therefore usually not useful for |
| |
reading from a pipe. You have to invoke the Forth program with an OS |
| |
command-line option, as you have no chance to use the Forth command line |
| |
(the text interpreter would try to interpret the pipe input). |
| |
|
| |
@cindex output in pipes |
| |
You can output to a pipe with @code{type}, @code{emit}, @code{cr} etc. |
| |
|
| |
@cindex silent exiting from Gforth |
| |
When you write to a pipe that has been closed at the other end, Gforth |
| |
receives a SIGPIPE signal (``pipe broken''). Gforth translates this |
| |
into the exception @code{broken-pipe-error}. If your application does |
| |
not catch that exception, the system catches it and exits, usually |
| |
silently (unless you were working on the Forth command line; then it |
| |
prints an error message and exits). This is usually the desired |
| |
behaviour. |
| |
|
| |
If you do not like this behaviour, you have to catch the exception |
| |
yourself, and react to it. |
| |
|
| |
Here's an example of an invocation of Gforth that is usable in a pipe: |
| |
|
| |
@example |
| |
gforth -e ": foo begin pad dup 10 stdin read-file throw dup while \ |
| |
type repeat ; foo bye" |
| |
@end example |
| |
|
| |
This example just copies the input verbatim to the output. A very |
| |
simple pipe containing this example looks like this: |
| |
|
| |
@example |
| |
cat startup.fs | |
| |
gforth -e ": foo begin pad dup 80 stdin read-file throw dup while \ |
| |
type repeat ; foo bye"| |
| |
head |
| |
@end example |
| |
|
| |
@cindex stderr and pipes |
| |
Pipes involving Gforth's @code{stderr} output do not work. |
| |
|
| |
@comment ---------------------------------------------- |
| |
@node Startup speed, , Gforth in pipes, Gforth Environment |
| @section Startup speed |
@section Startup speed |
| @cindex Startup speed |
@cindex Startup speed |
| @cindex speed, startup |
@cindex speed, startup |
| improve it; or you may consider ways to reduce the number of startups |
improve it; or you may consider ways to reduce the number of startups |
| (for example, by using Fast-CGI). |
(for example, by using Fast-CGI). |
| |
|
| The first step to improve startup speed is to statically link Gforth, by |
An easy step that influences Gforth startup speed is the use of the |
| |
@option{--no-dynamic} option; this decreases image loading speed, but |
| |
increases compile-time and run-time. |
| |
|
| |
Another step to improve startup speed is to statically link Gforth, by |
| building it with @code{XLDFLAGS=-static}. This requires more memory for |
building it with @code{XLDFLAGS=-static}. This requires more memory for |
| the code and will therefore slow down the first invocation, but |
the code and will therefore slow down the first invocation, but |
| subsequent invocations avoid the dynamic linking overhead. Another |
subsequent invocations avoid the dynamic linking overhead. Another |
| @c what happens on redefinition |
@c what happens on redefinition |
| @c parsing words (in particular, defining words) |
@c parsing words (in particular, defining words) |
| |
|
| |
The difference of this chapter from the Introduction |
| |
(@pxref{Introduction}) is that this tutorial is more fast-paced, should |
| |
be used while sitting in front of a computer, and covers much more |
| |
material, but does not explain how the Forth system works. |
| |
|
| This tutorial can be used with any ANS-compliant Forth; any |
This tutorial can be used with any ANS-compliant Forth; any |
| Gforth-specific features are marked as such and you can skip them if you |
Gforth-specific features are marked as such and you can skip them if you |
| work with another Forth. This tutorial does not explain all features of |
work with another Forth. This tutorial does not explain all features of |
| * Memory Tutorial:: |
* Memory Tutorial:: |
| * Characters and Strings Tutorial:: |
* Characters and Strings Tutorial:: |
| * Alignment Tutorial:: |
* Alignment Tutorial:: |
| |
* Floating Point Tutorial:: |
| |
* Files Tutorial:: |
| * Interpretation and Compilation Semantics and Immediacy Tutorial:: |
* Interpretation and Compilation Semantics and Immediacy Tutorial:: |
| * Execution Tokens Tutorial:: |
* Execution Tokens Tutorial:: |
| * Exceptions Tutorial:: |
* Exceptions Tutorial:: |
| @section Syntax |
@section Syntax |
| @cindex syntax tutorial |
@cindex syntax tutorial |
| |
|
| A @dfn{word} is a sequence of arbitrary characters (expcept white |
A @dfn{word} is a sequence of arbitrary characters (except white |
| space). Words are separated by white space. E.g., each of the |
space). Words are separated by white space. E.g., each of the |
| following lines contains exactly one word: |
following lines contains exactly one word: |
| |
|
| In general, words consume their stack arguments (@code{.s} is an |
In general, words consume their stack arguments (@code{.s} is an |
| exception). |
exception). |
| |
|
| @assignment |
@quotation Assignment |
| What does the stack contain after @code{5 6 7 .}? |
What does the stack contain after @code{5 6 7 .}? |
| @endassignment |
@end quotation |
| |
|
| |
|
| @node Arithmetics Tutorial, Stack Manipulation Tutorial, Stack Tutorial, Tutorial |
@node Arithmetics Tutorial, Stack Manipulation Tutorial, Stack Tutorial, Tutorial |
| 3 4 5 * + . |
3 4 5 * + . |
| @end example |
@end example |
| |
|
| @assignment |
@quotation Assignment |
| What are the infix expressions corresponding to the Forth code above? |
What are the infix expressions corresponding to the Forth code above? |
| Write @code{6-7*8+9} in Forth notation@footnote{This notation is also |
Write @code{6-7*8+9} in Forth notation@footnote{This notation is also |
| known as Postfix or RPN (Reverse Polish Notation).}. |
known as Postfix or RPN (Reverse Polish Notation).}. |
| @endassignment |
@end quotation |
| |
|
| To change the sign, use @code{negate}: |
To change the sign, use @code{negate}: |
| |
|
| 2 negate . |
2 negate . |
| @end example |
@end example |
| |
|
| @assignment |
@quotation Assignment |
| Convert -(-3)*4-5 to Forth. |
Convert -(-3)*4-5 to Forth. |
| @endassignment |
@end quotation |
| |
|
| @code{/mod} performs both @code{/} and @code{mod}. |
@code{/mod} performs both @code{/} and @code{mod}. |
| |
|
| 1 2 .s tuck .s 2drop drop |
1 2 .s tuck .s 2drop drop |
| @end example |
@end example |
| |
|
| @assignment |
@quotation Assignment |
| Replace @code{nip} and @code{tuck} with combinations of other stack |
Replace @code{nip} and @code{tuck} with combinations of other stack |
| manipulation words. |
manipulation words. |
| |
|
| 1 2 3 1 2 3 4 |
1 2 3 1 2 3 4 |
| 1 2 3 1 3 |
1 2 3 1 3 |
| @end example |
@end example |
| @endassignment |
@end quotation |
| |
|
| @example |
@example |
| 5 dup * . |
5 dup * . |
| @end example |
@end example |
| |
|
| @assignment |
@quotation Assignment |
| Write 17^3 and 17^4 in Forth, without writing @code{17} more than once. |
Write 17^3 and 17^4 in Forth, without writing @code{17} more than once. |
| Write a piece of Forth code that expects two numbers on the stack |
Write a piece of Forth code that expects two numbers on the stack |
| (@var{a} and @var{b}, with @var{b} on top) and computes |
(@var{a} and @var{b}, with @var{b} on top) and computes |
| @code{(a-b)(a+1)}. |
@code{(a-b)(a+1)}. |
| @endassignment |
@end quotation |
| |
|
| Reference: @ref{Stack Manipulation}. |
Reference: @ref{Stack Manipulation}. |
| |
|
| examples and short one-off code, you probably want to store your source |
examples and short one-off code, you probably want to store your source |
| code in files for convenient editing and persistence. You can use your |
code in files for convenient editing and persistence. You can use your |
| favourite editor (Gforth includes Emacs support, @pxref{Emacs and |
favourite editor (Gforth includes Emacs support, @pxref{Emacs and |
| Gforth}) to create @var{file} and use |
Gforth}) to create @var{file.fs} and use |
| |
|
| @example |
@example |
| s" @var{file}" included |
s" @var{file.fs}" included |
| @end example |
@end example |
| |
|
| to load it into your Forth system. The file name extension I use for |
to load it into your Forth system. The file name extension I use for |
| You can easily start Gforth with some files loaded like this: |
You can easily start Gforth with some files loaded like this: |
| |
|
| @example |
@example |
| gforth @var{file1} @var{file2} |
gforth @var{file1.fs} @var{file2.fs} |
| @end example |
@end example |
| |
|
| If an error occurs during loading these files, Gforth terminates, |
If an error occurs during loading these files, Gforth terminates, |
| tests with |
tests with |
| |
|
| @example |
@example |
| gforth @var{code} @var{tests} -e bye |
gforth @var{code.fs} @var{tests.fs} -e bye |
| @end example |
@end example |
| |
|
| (often by performing this command with @kbd{C-x C-e} in Emacs). The |
(often by performing this command with @kbd{C-x C-e} in Emacs). The |
| 3 fourth-power . |
3 fourth-power . |
| @end example |
@end example |
| |
|
| @assignment |
@quotation Assignment |
| Write colon definitions for @code{nip}, @code{tuck}, @code{negate}, and |
Write colon definitions for @code{nip}, @code{tuck}, @code{negate}, and |
| @code{/mod} in terms of other Forth words, and check if they work (hint: |
@code{/mod} in terms of other Forth words, and check if they work (hint: |
| test your tests on the originals first). Don't let the |
test your tests on the originals first). Don't let the |
| @samp{redefined}-Messages spook you, they are just warnings. |
@samp{redefined}-Messages spook you, they are just warnings. |
| @endassignment |
@end quotation |
| |
|
| Reference: @ref{Colon Definitions}. |
Reference: @ref{Colon Definitions}. |
| |
|
| @cindex stack-effect comments, tutorial |
@cindex stack-effect comments, tutorial |
| @cindex --, tutorial |
@cindex --, tutorial |
| By convention the comment after the name of a definition describes the |
By convention the comment after the name of a definition describes the |
| stack effect: The part in from of the @samp{--} describes the state of |
stack effect: The part in front of the @samp{--} describes the state of |
| the stack before the execution of the definition, i.e., the parameters |
the stack before the execution of the definition, i.e., the parameters |
| that are passed into the colon definition; the part behind the @samp{--} |
that are passed into the colon definition; the part behind the @samp{--} |
| is the state of the stack after the execution of the definition, i.e., |
is the state of the stack after the execution of the definition, i.e., |
| just @code{( -- )}. You should also add some descriptive comment to |
just @code{( -- )}. You should also add some descriptive comment to |
| more complicated words (I usually do this in the lines following |
more complicated words (I usually do this in the lines following |
| @code{:}). If you don't do this, your code becomes unreadable (because |
@code{:}). If you don't do this, your code becomes unreadable (because |
| you have to work through every definition before you can undertsand |
you have to work through every definition before you can understand |
| any). |
any). |
| |
|
| @assignment |
@quotation Assignment |
| The stack effect of @code{swap} can be written like this: @code{x1 x2 -- |
The stack effect of @code{swap} can be written like this: @code{x1 x2 -- |
| x2 x1}. Describe the stack effect of @code{-}, @code{drop}, @code{dup}, |
x2 x1}. Describe the stack effect of @code{-}, @code{drop}, @code{dup}, |
| @code{over}, @code{rot}, @code{nip}, and @code{tuck}. Hint: When you |
@code{over}, @code{rot}, @code{nip}, and @code{tuck}. Hint: When you |
| are done, you can compare your stack effects to those in this manual |
are done, you can compare your stack effects to those in this manual |
| (@pxref{Word Index}). |
(@pxref{Word Index}). |
| @endassignment |
@end quotation |
| |
|
| Sometimes programmers put comments at various places in colon |
Sometimes programmers put comments at various places in colon |
| definitions that describe the contents of the stack at that place (stack |
definitions that describe the contents of the stack at that place (stack |
| |
|
| You can find a more complete list in @ref{Notation}. |
You can find a more complete list in @ref{Notation}. |
| |
|
| @assignment |
@quotation Assignment |
| Write stack-effect comments for all definitions you have written up to |
Write stack-effect comments for all definitions you have written up to |
| now. |
now. |
| @endassignment |
@end quotation |
| |
|
| |
|
| @node Types Tutorial, Factoring Tutorial, Stack-Effect Comments Tutorial, Tutorial |
@node Types Tutorial, Factoring Tutorial, Stack-Effect Comments Tutorial, Tutorial |
| function; and since there is only one result, you don't have to deal with |
function; and since there is only one result, you don't have to deal with |
| the order of results, either. |
the order of results, either. |
| |
|
| In Forth (and other stack-based languages, e.g., Postscript) the |
In Forth (and other stack-based languages, e.g., PostScript) the |
| parameter and result order of a definition is important and should be |
parameter and result order of a definition is important and should be |
| designed well. The general guideline is to design the stack effect such |
designed well. The general guideline is to design the stack effect such |
| that the word is simple to use in most cases, even if that complicates |
that the word is simple to use in most cases, even if that complicates |
| a constant), pass it on the top of the stack. Conversely, parameters |
a constant), pass it on the top of the stack. Conversely, parameters |
| that usually require a long sequence of code to compute should be passed |
that usually require a long sequence of code to compute should be passed |
| as the bottom (i.e., first) parameter. This makes the code easier to |
as the bottom (i.e., first) parameter. This makes the code easier to |
| read, because reader does not need to keep track of the bottom item |
read, because the reader does not need to keep track of the bottom item |
| through a long sequence of code (or, alternatively, through stack |
through a long sequence of code (or, alternatively, through stack |
| manipulations). E.g., @code{!} (store, @pxref{Memory}) expects the |
manipulations). E.g., @code{!} (store, @pxref{Memory}) expects the |
| address on top of the stack because it is usually simpler to compute |
address on top of the stack because it is usually simpler to compute |
| @end example |
@end example |
| |
|
| (If your Forth system does not support this syntax, include |
(If your Forth system does not support this syntax, include |
| @file{compat/anslocals.fs} first). |
@file{compat/anslocal.fs} first). |
| |
|
| In this example @code{@{ a b -- b a @}} is the locals definition; it |
In this example @code{@{ a b -- b a @}} is the locals definition; it |
| takes two cells from the stack, puts the top of stack in @code{b} and |
takes two cells from the stack, puts the top of stack in @code{b} and |
| In Gforth you can have several locals definitions, anywhere in a colon |
In Gforth you can have several locals definitions, anywhere in a colon |
| definition; in contrast, in a standard program you can have only one |
definition; in contrast, in a standard program you can have only one |
| locals definition per colon definition, and that locals definition must |
locals definition per colon definition, and that locals definition must |
| be outside any controll structure. |
be outside any control structure. |
| |
|
| With locals you can write slightly longer definitions without running |
With locals you can write slightly longer definitions without running |
| into stack trouble. However, I recommend trying to write colon |
into stack trouble. However, I recommend trying to write colon |
| definitions without locals for exercise purposes to help you gain the |
definitions without locals for exercise purposes to help you gain the |
| essential factoring skills. |
essential factoring skills. |
| |
|
| @assignment |
@quotation Assignment |
| Rewrite your definitions until now with locals |
Rewrite your definitions until now with locals |
| @endassignment |
@end quotation |
| |
|
| Reference: @ref{Locals}. |
Reference: @ref{Locals}. |
| |
|
| @code{if} takes a flag from the stack. If the flag is non-zero (true), |
@code{if} takes a flag from the stack. If the flag is non-zero (true), |
| the following code is performed, otherwise execution continues after the |
the following code is performed, otherwise execution continues after the |
| @code{endif} (or @code{else}). @code{<} compares the top two stack |
@code{endif} (or @code{else}). @code{<} compares the top two stack |
| elements and prioduces a flag: |
elements and produces a flag: |
| |
|
| @example |
@example |
| 1 2 < . |
1 2 < . |
| 3 2 min . |
3 2 min . |
| @end example |
@end example |
| |
|
| @assignment |
@quotation Assignment |
| Write @code{min} without @code{else}-part (hint: what's the definition |
Write @code{min} without @code{else}-part (hint: what's the definition |
| of @code{nip}?). |
of @code{nip}?). |
| @endassignment |
@end quotation |
| |
|
| Reference: @ref{Selection}. |
Reference: @ref{Selection}. |
| |
|
| these combinations are standard (for details see the standard, |
these combinations are standard (for details see the standard, |
| @ref{Numeric comparison}, @ref{Floating Point} or @ref{Word Index}). |
@ref{Numeric comparison}, @ref{Floating Point} or @ref{Word Index}). |
| |
|
| You can use @code{and or xor invert} can be used as operations on |
You can use @code{and or xor invert} as operations on canonical flags. |
| canonical flags. Actually they are bitwise operations: |
Actually they are bitwise operations: |
| |
|
| @example |
@example |
| 1 2 and . |
1 2 and . |
| 1 foo . |
1 foo . |
| @end example |
@end example |
| |
|
| @assignment |
@quotation Assignment |
| Write @code{min} without @code{if}. |
Write @code{min} without @code{if}. |
| @endassignment |
@end quotation |
| |
|
| For reference, see @ref{Boolean Flags}, @ref{Numeric comparison}, and |
For reference, see @ref{Boolean Flags}, @ref{Numeric comparison}, and |
| @ref{Bitwise operations}. |
@ref{Bitwise operations}. |
| @code{begin}, just like @code{again}. |
@code{begin}, just like @code{again}. |
| |
|
| In Forth there are many combinations/abbreviations, like @code{1+}. |
In Forth there are many combinations/abbreviations, like @code{1+}. |
| However, @code{2/} is not one of them; it shifts it's argument right by |
However, @code{2/} is not one of them; it shifts its argument right by |
| one bit (arithmetic shift right): |
one bit (arithmetic shift right): |
| |
|
| @example |
@example |
| @code{Until} consumes a flag; if it is non-zero, execution continues at |
@code{Until} consumes a flag; if it is non-zero, execution continues at |
| the @code{begin}, otherwise after the @code{until}. |
the @code{begin}, otherwise after the @code{until}. |
| |
|
| @assignment |
@quotation Assignment |
| Write a definition for computing the greatest common divisor. |
Write a definition for computing the greatest common divisor. |
| @endassignment |
@end quotation |
| |
|
| Reference: @ref{Simple Loops}. |
Reference: @ref{Simple Loops}. |
| |
|
| |
|
| @example |
@example |
| : ^ ( n1 u -- n ) |
: ^ ( n1 u -- n ) |
| \ n = the uth power of u1 |
\ n = the uth power of n1 |
| 1 swap 0 u+do |
1 swap 0 u+do |
| over * |
over * |
| loop |
loop |
| There is also @code{+do}, which expects signed numbers (important for |
There is also @code{+do}, which expects signed numbers (important for |
| deciding whether to enter the loop). |
deciding whether to enter the loop). |
| |
|
| @assignment |
@quotation Assignment |
| Write a definition for computing the nth Fibonacci number. |
Write a definition for computing the nth Fibonacci number. |
| @endassignment |
@end quotation |
| |
|
| You can also use increments other than 1: |
You can also use increments other than 1: |
| |
|
| earlier definitions are usually visible: |
earlier definitions are usually visible: |
| |
|
| @example |
@example |
| 1 0 / . \ "Floating-point unidentified fault" in Gforth on most platforms |
1 0 / . \ "Floating-point unidentified fault" in Gforth on some platforms |
| : / ( n1 n2 -- n ) |
: / ( n1 n2 -- n ) |
| dup 0= if |
dup 0= if |
| -10 throw \ report division by zero |
-10 throw \ report division by zero |
| 8 fac2 . |
8 fac2 . |
| @end example |
@end example |
| |
|
| @assignment |
@quotation Assignment |
| Write a recursive definition for computing the nth Fibonacci number. |
Write a recursive definition for computing the nth Fibonacci number. |
| @endassignment |
@end quotation |
| |
|
| Reference (including indirect recursion): @xref{Calls and returns}. |
Reference (including indirect recursion): @xref{Calls and returns}. |
| |
|
| @code{>r} takes an element from the data stack and pushes it onto the |
@code{>r} takes an element from the data stack and pushes it onto the |
| return stack; conversely, @code{r>} moves an elementm from the return to |
return stack; conversely, @code{r>} moves an elementm from the return to |
| the data stack; @code{r@@} pushes a copy of the top of the return stack |
the data stack; @code{r@@} pushes a copy of the top of the return stack |
| on the return stack. |
on the data stack. |
| |
|
| Forth programmers usually use the return stack for storing data |
Forth programmers usually use the return stack for storing data |
| temporarily, if using the data stack alone would be too complex, and |
temporarily, if using the data stack alone would be too complex, and |
| standard; Gforth has no problem). However, they solve the same |
standard; Gforth has no problem). However, they solve the same |
| problems, so this shouldn't be an issue. |
problems, so this shouldn't be an issue. |
| |
|
| @assignment |
@quotation Assignment |
| Can you rewrite any of the definitions you wrote until now in a better |
Can you rewrite any of the definitions you wrote until now in a better |
| way using the return stack? |
way using the return stack? |
| @endassignment |
@end quotation |
| |
|
| Reference: @ref{Return stack}. |
Reference: @ref{Return stack}. |
| |
|
| v3 5 cells dump |
v3 5 cells dump |
| @end example |
@end example |
| |
|
| @assignment |
@quotation Assignment |
| Write a definition @code{vsum ( addr u -- n )} that computes the sum of |
Write a definition @code{vsum ( addr u -- n )} that computes the sum of |
| @code{u} cells, with the first of these cells at @code{addr}, the next |
@code{u} cells, with the first of these cells at @code{addr}, the next |
| one at @code{addr cell+} etc. |
one at @code{addr cell+} etc. |
| @endassignment |
@end quotation |
| |
|
| You can also reserve memory without creating a new word: |
You can also reserve memory without creating a new word: |
| |
|
| type |
type |
| @end example |
@end example |
| |
|
| @assignment |
@quotation Assignment |
| @code{Emit ( c -- )} types @code{c} as character (not a number). |
@code{Emit ( c -- )} types @code{c} as character (not a number). |
| Implement @code{type ( addr u -- )}. |
Implement @code{type ( addr u -- )}. |
| @endassignment |
@end quotation |
| |
|
| Reference: @ref{Memory Blocks}. |
Reference: @ref{Memory Blocks}. |
| |
|
| |
|
| @node Alignment Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Characters and Strings Tutorial, Tutorial |
@node Alignment Tutorial, Floating Point Tutorial, Characters and Strings Tutorial, Tutorial |
| @section Alignment |
@section Alignment |
| @cindex alignment tutorial |
@cindex alignment tutorial |
| @cindex memory alignment tutorial |
@cindex memory alignment tutorial |
| |
|
| Reference: @ref{Address arithmetic}. |
Reference: @ref{Address arithmetic}. |
| |
|
| |
@node Floating Point Tutorial, Files Tutorial, Alignment Tutorial, Tutorial |
| |
@section Floating Point |
| |
@cindex floating point tutorial |
| |
@cindex FP tutorial |
| |
|
| |
Floating-point (FP) numbers and arithmetic in Forth works mostly as one |
| |
might expect, but there are a few things worth noting: |
| |
|
| |
The first point is not specific to Forth, but so important and yet not |
| |
universally known that I mention it here: FP numbers are not reals. |
| |
Many properties (e.g., arithmetic laws) that reals have and that one |
| |
expects of all kinds of numbers do not hold for FP numbers. If you |
| |
want to use FP computations, you should learn about their problems and |
| |
how to avoid them; a good starting point is @cite{David Goldberg, |
| |
@uref{http://docs.sun.com/source/806-3568/ncg_goldberg.html,What Every |
| |
Computer Scientist Should Know About Floating-Point Arithmetic}, ACM |
| |
Computing Surveys 23(1):5@minus{}48, March 1991}. |
| |
|
| |
In Forth source code literal FP numbers need an exponent, e.g., |
| |
@code{1e0}; this can also be written shorter as @code{1e}, |
| |
@code{+1.0e+0}, and many variations in between. The reason for this |
| |
is that, for historical reasons, Forth interprets a decimal point |
| |
alone (e.g., @code{1.}) as indicating a double-cell integer. Another |
| |
requirement for literal FP numbers is that the current base is |
| |
decimal; with a hex base @code{1e} is interpreted as an integer. |
| |
|
| |
Forth has a separate stack for FP numbers.@footnote{Theoretically, an |
| |
ANS Forth system may implement the FP stack on the data stack, but |
| |
virtually all systems implement a separate FP stack; and programming |
| |
in a way that accommodates all models is so cumbersome that nobody |
| |
does it.} One advantage of this model is that cells are not in the |
| |
way when accessing FP values, and vice versa. Forth has a set of |
| |
words for manipulating the FP stack: @code{fdup fswap fdrop fover |
| |
frot} and (non-standard) @code{fnip ftuck fpick}. |
| |
|
| |
FP arithmetic words are prefixed with @code{F}. There is the usual |
| |
set @code{f+ f- f* f/ f** fnegate} as well as a number of words for |
| |
other functions, e.g., @code{fsqrt fsin fln fmin}. One word that you |
| |
might expect is @code{f=}; but @code{f=} is non-standard, because FP |
| |
computation results are usually inaccurate, so exact comparison is |
| |
usually a mistake, and one should use approximate comparison. |
| |
Unfortunately, @code{f~}, the standard word for that purpose, is not |
| |
well designed, so Gforth provides @code{f~abs} and @code{f~rel} as |
| |
well. |
| |
|
| |
And of course there are words for accessing FP numbers in memory |
| |
(@code{f@@ f!}), and for address arithmetic (@code{floats float+ |
| |
faligned}). There are also variants of these words with an @code{sf} |
| |
and @code{df} prefix for accessing IEEE format single-precision and |
| |
double-precision numbers in memory; their main purpose is for |
| |
accessing external FP data (e.g., that has been read from or will be |
| |
written to a file). |
| |
|
| |
Here is an example of a dot-product word and its use: |
| |
|
| |
@example |
| |
: v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r ) |
| |
>r swap 2swap swap 0e r> 0 ?DO |
| |
dup f@@ over + 2swap dup f@@ f* f+ over + 2swap |
| |
LOOP |
| |
2drop 2drop ; |
| |
|
| |
create v 1.23e f, 4.56e f, 7.89e f, |
| |
|
| |
v 1 floats v 1 floats 3 v* f. |
| |
@end example |
| |
|
| |
@quotation Assignment |
| |
Write a program to solve a quadratic equation. Then read @cite{Henry |
| |
G. Baker, |
| |
@uref{http://home.pipeline.com/~hbaker1/sigplannotices/sigcol05.ps.gz,You |
| |
Could Learn a Lot from a Quadratic}, ACM SIGPLAN Notices, |
| |
33(1):30@minus{}39, January 1998}, and see if you can improve your |
| |
program. Finally, find a test case where the original and the |
| |
improved version produce different results. |
| |
@end quotation |
| |
|
| |
Reference: @ref{Floating Point}; @ref{Floating point stack}; |
| |
@ref{Number Conversion}; @ref{Memory Access}; @ref{Address |
| |
arithmetic}. |
| |
|
| |
@node Files Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Floating Point Tutorial, Tutorial |
| |
@section Files |
| |
@cindex files tutorial |
| |
|
| |
This section gives a short introduction into how to use files inside |
| |
Forth. It's broken up into five easy steps: |
| |
|
| |
@enumerate 1 |
| |
@item Opened an ASCII text file for input |
| |
@item Opened a file for output |
| |
@item Read input file until string matched (or some other condition matched) |
| |
@item Wrote some lines from input ( modified or not) to output |
| |
@item Closed the files. |
| |
@end enumerate |
| |
|
| |
Reference: @ref{General files}. |
| |
|
| |
@subsection Open file for input |
| |
|
| |
@example |
| |
s" foo.in" r/o open-file throw Value fd-in |
| |
@end example |
| |
|
| |
@subsection Create file for output |
| |
|
| |
@example |
| |
s" foo.out" w/o create-file throw Value fd-out |
| |
@end example |
| |
|
| |
The available file modes are r/o for read-only access, r/w for |
| |
read-write access, and w/o for write-only access. You could open both |
| |
files with r/w, too, if you like. All file words return error codes; for |
| |
most applications, it's best to pass there error codes with @code{throw} |
| |
to the outer error handler. |
| |
|
| |
If you want words for opening and assigning, define them as follows: |
| |
|
| |
@example |
| |
0 Value fd-in |
| |
0 Value fd-out |
| |
: open-input ( addr u -- ) r/o open-file throw to fd-in ; |
| |
: open-output ( addr u -- ) w/o create-file throw to fd-out ; |
| |
@end example |
| |
|
| |
Usage example: |
| |
|
| |
@example |
| |
s" foo.in" open-input |
| |
s" foo.out" open-output |
| |
@end example |
| |
|
| |
@subsection Scan file for a particular line |
| |
|
| |
@example |
| |
256 Constant max-line |
| |
Create line-buffer max-line 2 + allot |
| |
|
| |
: scan-file ( addr u -- ) |
| |
begin |
| |
line-buffer max-line fd-in read-line throw |
| |
while |
| |
>r 2dup line-buffer r> compare 0= |
| |
until |
| |
else |
| |
drop |
| |
then |
| |
2drop ; |
| |
@end example |
| |
|
| |
@code{read-line ( addr u1 fd -- u2 flag ior )} reads up to u1 bytes into |
| |
the buffer at addr, and returns the number of bytes read, a flag that is |
| |
false when the end of file is reached, and an error code. |
| |
|
| |
@code{compare ( addr1 u1 addr2 u2 -- n )} compares two strings and |
| |
returns zero if both strings are equal. It returns a positive number if |
| |
the first string is lexically greater, a negative if the second string |
| |
is lexically greater. |
| |
|
| |
We haven't seen this loop here; it has two exits. Since the @code{while} |
| |
exits with the number of bytes read on the stack, we have to clean up |
| |
that separately; that's after the @code{else}. |
| |
|
| |
Usage example: |
| |
|
| |
@example |
| |
s" The text I search is here" scan-file |
| |
@end example |
| |
|
| |
@subsection Copy input to output |
| |
|
| |
@example |
| |
: copy-file ( -- ) |
| |
begin |
| |
line-buffer max-line fd-in read-line throw |
| |
while |
| |
line-buffer swap fd-out write-line throw |
| |
repeat ; |
| |
@end example |
| |
@c !! does not handle long lines, no newline at end of file |
| |
|
| |
@subsection Close files |
| |
|
| |
@example |
| |
fd-in close-file throw |
| |
fd-out close-file throw |
| |
@end example |
| |
|
| |
Likewise, you can put that into definitions, too: |
| |
|
| |
@example |
| |
: close-input ( -- ) fd-in close-file throw ; |
| |
: close-output ( -- ) fd-out close-file throw ; |
| |
@end example |
| |
|
| |
@quotation Assignment |
| |
How could you modify @code{copy-file} so that it copies until a second line is |
| |
matched? Can you write a program that extracts a section of a text file, |
| |
given the line that starts and the line that terminates that section? |
| |
@end quotation |
| |
|
| @node Interpretation and Compilation Semantics and Immediacy Tutorial, Execution Tokens Tutorial, Alignment Tutorial, Tutorial |
@node Interpretation and Compilation Semantics and Immediacy Tutorial, Execution Tokens Tutorial, Files Tutorial, Tutorial |
| @section Interpretation and Compilation Semantics and Immediacy |
@section Interpretation and Compilation Semantics and Immediacy |
| @cindex semantics tutorial |
@cindex semantics tutorial |
| @cindex interpretation semantics tutorial |
@cindex interpretation semantics tutorial |
| 3 2 ' / catch .s |
3 2 ' / catch .s |
| @end example |
@end example |
| |
|
| @assignment |
@quotation Assignment |
| Try the same with @code{execute} instead of @code{catch}. |
Try the same with @code{execute} instead of @code{catch}. |
| @endassignment |
@end quotation |
| |
|
| @code{Throw} always jumps to the dynamically next enclosing |
@code{Throw} always jumps to the dynamically next enclosing |
| @code{catch}, even if it has to leave several call levels to achieve |
@code{catch}, even if it has to leave several call levels to achieve |
| ( ... n ) throw ; |
( ... n ) throw ; |
| @end example |
@end example |
| |
|
| Gforth provides an alternative syntax in addition to @code{catch}: |
However, this is still not safe against, e.g., the user pressing |
| @code{try ... recover ... endtry}. If the code between @code{try} and |
@kbd{Ctrl-C} when execution is between the @code{catch} and |
| @code{recover} has an exception, the stack depths are restored, the |
@code{restore-x}. |
| exception number is pushed on the stack, and the code between |
|
| @code{recover} and @code{endtry} is performed. E.g., the definition for |
Gforth provides an alternative exception handling syntax that is safe |
| @code{catch} is |
against such cases: @code{try ... restore ... endtry}. If the code |
| |
between @code{try} and @code{endtry} has an exception, the stack |
| @example |
depths are restored, the exception number is pushed on the stack, and |
| : catch ( x1 .. xn xt -- y1 .. ym 0 / z1 .. zn error ) \ exception |
the execution continues right after @code{restore}. |
| try |
|
| execute 0 |
|
| recover |
|
| nip |
|
| endtry ; |
|
| @end example |
|
| |
|
| The equivalent to the restoration code above is |
The safer equivalent to the restoration code above is |
| |
|
| @example |
@example |
| : ... |
: ... |
| save-x |
save-x |
| try |
try |
| word-changing-x |
word-changing-x 0 |
| end-try |
restore |
| restore-x |
restore-x |
| |
endtry |
| throw ; |
throw ; |
| @end example |
@end example |
| |
|
| As you can see, the @code{recover} part is optional. |
|
| |
|
| Reference: @ref{Exception Handling}. |
Reference: @ref{Exception Handling}. |
| |
|
| |
|
| foo . |
foo . |
| @end example |
@end example |
| |
|
| @assignment |
@quotation Assignment |
| Define @code{defer ( "name" -- )}, which creates a word that stores an |
Define @code{defer ( "name" -- )}, which creates a word that stores an |
| XT (at the start the XT of @code{abort}), and upon execution |
XT (at the start the XT of @code{abort}), and upon execution |
| @code{execute}s the XT. Define @code{is ( xt "name" -- )} that stores |
@code{execute}s the XT. Define @code{is ( xt "name" -- )} that stores |
| @code{xt} into @code{name}, a word defined with @code{defer}. Indirect |
@code{xt} into @code{name}, a word defined with @code{defer}. Indirect |
| recursion is one application of @code{defer}. |
recursion is one application of @code{defer}. |
| @endassignment |
@end quotation |
| |
|
| Reference: @ref{User-defined Defining Words}. |
Reference: @ref{User-defined Defining Words}. |
| |
|
| POSTPONE then ; immediate |
POSTPONE then ; immediate |
| @end example |
@end example |
| |
|
| @assignment |
@quotation Assignment |
| Write @code{MY-2DUP} that has compilation semantics equivalent to |
Write @code{MY-2DUP} that has compilation semantics equivalent to |
| @code{2dup}, but compiles @code{over over}. |
@code{2dup}, but compiles @code{over over}. |
| @endassignment |
@end quotation |
| |
|
| @c !! @xref{Macros} for reference |
@c !! @xref{Macros} for reference |
| |
|
| see bar |
see bar |
| @end example |
@end example |
| |
|
| @assignment |
@quotation Assignment |
| Write @code{]L} which allows writing the example above as @code{: bar ( |
Write @code{]L} which allows writing the example above as @code{: bar ( |
| -- n ) [ 2 2 + ]L ;} |
-- n ) [ 2 2 + ]L ;} |
| @endassignment |
@end quotation |
| |
|
| @c !! @xref{Macros} for reference |
@c !! @xref{Macros} for reference |
| |
|
| Yes, the order of wordlists in the output of @code{order} is reversed |
Yes, the order of wordlists in the output of @code{order} is reversed |
| from stack comments and the output of @code{.s} and thus unintuitive. |
from stack comments and the output of @code{.s} and thus unintuitive. |
| |
|
| @assignment |
@quotation Assignment |
| Define @code{>order ( wid -- )} with adds @code{wid} as first searched |
Define @code{>order ( wid -- )} with adds @code{wid} as first searched |
| wordlist to the search order. Define @code{previous ( -- )}, which |
wordlist to the search order. Define @code{previous ( -- )}, which |
| removes the first searched wordlist from the search order. Experiment |
removes the first searched wordlist from the search order. Experiment |
| with boundary conditions (you will see some crashes or situations that |
with boundary conditions (you will see some crashes or situations that |
| are hard or impossible to leave). |
are hard or impossible to leave). |
| @endassignment |
@end quotation |
| |
|
| The search order is a powerful foundation for providing features similar |
The search order is a powerful foundation for providing features similar |
| to Modula-2 modules and C++ namespaces. However, trying to modularize |
to Modula-2 modules and C++ namespaces. However, trying to modularize |
| programs in this way has disadvantages for debugging and reuse/factoring |
programs in this way has disadvantages for debugging and reuse/factoring |
| that overcome the advantages in my experience (I don't do huge projects, |
that overcome the advantages in my experience (I don't do huge projects, |
| though). These disadvantages are not so clear in other |
though). These disadvantages are not so clear in other |
| languages/programming environments, because these langauges are not so |
languages/programming environments, because these languages are not so |
| strong in debugging and reuse. |
strong in debugging and reuse. |
| |
|
| @c !! example |
@c !! example |
| @chapter An Introduction to ANS Forth |
@chapter An Introduction to ANS Forth |
| @cindex Forth - an introduction |
@cindex Forth - an introduction |
| |
|
| |
The difference of this chapter from the Tutorial (@pxref{Tutorial}) is |
| |
that it is slower-paced in its examples, but uses them to dive deep into |
| |
explaining Forth internals (not covered by the Tutorial). Apart from |
| |
that, this chapter covers far less material. It is suitable for reading |
| |
without using a computer. |
| |
|
| The primary purpose of this manual is to document Gforth. However, since |
The primary purpose of this manual is to document Gforth. However, since |
| Forth is not a widely-known language and there is a lack of up-to-date |
Forth is not a widely-known language and there is a lack of up-to-date |
| teaching material, it seems worthwhile to provide some introductory |
teaching material, it seems worthwhile to provide some introductory |
| |
|
| @example |
@example |
| @kbd{qwer341@key{RET}} |
@kbd{qwer341@key{RET}} |
| :1: Undefined word |
*the terminal*:2: Undefined word |
| qwer341 |
>>>qwer341<<< |
| ^^^^^^^ |
Backtrace: |
| $400D2BA8 Bounce |
$2A95B42A20 throw |
| $400DBDA8 no.extensions |
$2A95B57FB8 no.extensions |
| @end example |
@end example |
| |
|
| The exact text, other than the ``Undefined word'' may differ slightly on |
The exact text, other than the ``Undefined word'' may differ slightly |
| your system, but the effect is the same; when the text interpreter |
on your system, but the effect is the same; when the text interpreter |
| detects an error, it discards any remaining text on a line, resets |
detects an error, it discards any remaining text on a line, resets |
| certain internal state and prints an error message. For a detailed description of error messages see @ref{Error |
certain internal state and prints an error message. For a detailed |
| messages}. |
description of error messages see @ref{Error messages}. |
| |
|
| The text interpreter waits for you to press carriage-return, and then |
The text interpreter waits for you to press carriage-return, and then |
| processes your input line. Starting at the beginning of the line, it |
processes your input line. Starting at the beginning of the line, it |
| |
|
| @example |
@example |
| @kbd{12 dup fred dup@key{RET}} |
@kbd{12 dup fred dup@key{RET}} |
| :1: Undefined word |
*the terminal*:3: Undefined word |
| 12 dup fred dup |
12 dup >>>fred<<< dup |
| ^^^^ |
Backtrace: |
| $400D2BA8 Bounce |
$2A95B42A20 throw |
| $400DBDA8 no.extensions |
$2A95B57FB8 no.extensions |
| @end example |
@end example |
| |
|
| When you press the carriage-return key, the text interpreter starts to |
When you press the carriage-return key, the text interpreter starts to |
| without affecting the stack. Type: |
without affecting the stack. Type: |
| |
|
| @example |
@example |
| @kbd{clearstack 1 2 3@key{RET}} ok |
@kbd{clearstacks 1 2 3@key{RET}} ok |
| @kbd{.s@key{RET}} <3> 1 2 3 ok |
@kbd{.s@key{RET}} <3> 1 2 3 ok |
| @end example |
@end example |
| |
|
| The text interpreter looks up the word @code{clearstack} and executes |
The text interpreter looks up the word @code{clearstacks} and executes |
| it; it tidies up the stack and removes any entries that may have been |
it; it tidies up the stacks and removes any entries that may have been |
| left on it by earlier examples. The text interpreter pushes each of the |
left on it by earlier examples. The text interpreter pushes each of the |
| three numbers in turn onto the stack. Finally, the text interpreter |
three numbers in turn onto the stack. Finally, the text interpreter |
| looks up the word @code{.s} and executes it. The effect of executing |
looks up the word @code{.s} and executes it. The effect of executing |
| the stack. What happens if you try to do a third addition? Pick up the |
the stack. What happens if you try to do a third addition? Pick up the |
| first card, pick up the second card -- ah! There is no second card. This |
first card, pick up the second card -- ah! There is no second card. This |
| is called a @dfn{stack underflow} and consitutes an error. If you try to |
is called a @dfn{stack underflow} and consitutes an error. If you try to |
| do the same thing with Forth it will report an error (probably a Stack |
do the same thing with Forth it often reports an error (probably a Stack |
| Underflow or an Invalid Memory Address error). |
Underflow or an Invalid Memory Address error). |
| |
|
| The opposite situation to a stack underflow is a @dfn{stack overflow}, |
The opposite situation to a stack underflow is a @dfn{stack overflow}, |
| @c everything more complex again. I replaced it with ``default |
@c everything more complex again. I replaced it with ``default |
| @c semantics'' (which is used elsewhere in the manual) by which I mean |
@c semantics'' (which is used elsewhere in the manual) by which I mean |
| @c ``a definition that has neither the immediate nor the compile-only |
@c ``a definition that has neither the immediate nor the compile-only |
| @c flag set''. I reworded big chunks of the ``how does that work'' |
@c flag set''. |
| |
|
| |
@c anton: I have eliminated default semantics (except in one place where it |
| |
@c means "default interpretation and compilation semantics"), because it |
| |
@c makes no sense in the presence of combined words. I reverted to |
| |
@c "execution semantics" where necessary. |
| |
|
| |
@c nac-> I reworded big chunks of the ``how does that work'' |
| @c section (and, unusually for me, I think I even made it shorter!). See |
@c section (and, unusually for me, I think I even made it shorter!). See |
| @c what you think -- I know I have not addressed your primary concern |
@c what you think -- I know I have not addressed your primary concern |
| @c that it is too heavy-going for an introduction. From what I understood |
@c that it is too heavy-going for an introduction. From what I understood |
| @c that you need to understand to see how Forth works. That's unique and |
@c that you need to understand to see how Forth works. That's unique and |
| @c worthwhile to emphasise. |
@c worthwhile to emphasise. |
| |
|
| |
@c anton: I think it's a good idea to present the details, especially those |
| |
@c that you found to be a revelation, and probably the tutorial tries to be |
| |
@c too superficial and does not get some of the things across that make |
| |
@c Forth special. I do believe that most of the time these things should |
| |
@c be discussed at the end of a section or in separate sections instead of |
| |
@c in the middle of a section (e.g., the stuff you added in "User-defined |
| |
@c defining words" leads in a completely different direction from the rest |
| |
@c of the section). |
| |
|
| Now we're going to take another look at the definition of @code{add-two} |
Now we're going to take another look at the definition of @code{add-two} |
| from the previous section. From our knowledge of the way that the text |
from the previous section. From our knowledge of the way that the text |
| interpreter works, we would have expected this result when we tried to |
interpreter works, we would have expected this result when we tried to |
| |
|
| @example |
@example |
| @kbd{: add-two 2 + . ;@key{RET}} |
@kbd{: add-two 2 + . ;@key{RET}} |
| ^^^^^^^ |
*the terminal*:4: Undefined word |
| Error: Undefined word |
: >>>add-two<<< 2 + . ; |
| @end example |
@end example |
| |
|
| The reason that this didn't happen is bound up in the way that @code{:} |
The reason that this didn't happen is bound up in the way that @code{:} |
| * Defining Words:: |
* Defining Words:: |
| * Interpretation and Compilation Semantics:: |
* Interpretation and Compilation Semantics:: |
| * Tokens for Words:: |
* Tokens for Words:: |
| |
* Compiling words:: |
| * The Text Interpreter:: |
* The Text Interpreter:: |
| |
* The Input Stream:: |
| * Word Lists:: |
* Word Lists:: |
| * Environmental Queries:: |
* Environmental Queries:: |
| * Files:: |
* Files:: |
| * Blocks:: |
* Blocks:: |
| * Other I/O:: |
* Other I/O:: |
| |
* OS command line arguments:: |
| * Locals:: |
* Locals:: |
| * Structures:: |
* Structures:: |
| * Object-oriented Forth:: |
* Object-oriented Forth:: |
| * Programming Tools:: |
* Programming Tools:: |
| |
* C Interface:: |
| * Assembler and Code Words:: |
* Assembler and Code Words:: |
| * Threading Words:: |
* Threading Words:: |
| * Passing Commands to the OS:: |
* Passing Commands to the OS:: |
| |
|
| doc-+ |
doc-+ |
| doc-1+ |
doc-1+ |
| |
doc-under+ |
| doc-- |
doc-- |
| doc-1- |
doc-1- |
| doc-* |
doc-* |
| |
|
| @cindex floating-point arithmetic, pitfalls |
@cindex floating-point arithmetic, pitfalls |
| Floating point numbers have a number of unpleasant surprises for the |
Floating point numbers have a number of unpleasant surprises for the |
| unwary (e.g., floating point addition is not associative) and even a few |
unwary (e.g., floating point addition is not associative) and even a |
| for the wary. You should not use them unless you know what you are doing |
few for the wary. You should not use them unless you know what you are |
| or you don't care that the results you get are totally bogus. If you |
doing or you don't care that the results you get are totally bogus. If |
| want to learn about the problems of floating point numbers (and how to |
you want to learn about the problems of floating point numbers (and |
| avoid them), you might start with @cite{David Goldberg, |
how to avoid them), you might start with @cite{David Goldberg, |
| @uref{http://www.validgh.com/goldberg/paper.ps,What Every Computer |
@uref{http://docs.sun.com/source/806-3568/ncg_goldberg.html,What Every |
| Scientist Should Know About Floating-Point Arithmetic}, ACM Computing |
Computer Scientist Should Know About Floating-Point Arithmetic}, ACM |
| Surveys 23(1):5@minus{}48, March 1991}. |
Computing Surveys 23(1):5@minus{}48, March 1991}. |
| |
|
| |
|
| doc-d>f |
doc-d>f |
| doc-sf! |
doc-sf! |
| doc-df@ |
doc-df@ |
| doc-df! |
doc-df! |
| |
doc-sw@ |
| |
doc-uw@ |
| |
doc-w! |
| |
doc-sl@ |
| |
doc-ul@ |
| |
doc-l! |
| |
|
| @node Address arithmetic, Memory Blocks, Memory Access, Memory |
@node Address arithmetic, Memory Blocks, Memory Access, Memory |
| @subsection Address arithmetic |
@subsection Address arithmetic |
| doc-maxaligned |
doc-maxaligned |
| doc-cfaligned |
doc-cfaligned |
| doc-address-unit-bits |
doc-address-unit-bits |
| |
doc-/w |
| |
doc-/l |
| |
|
| @node Memory Blocks, , Address arithmetic, Memory |
@node Memory Blocks, , Address arithmetic, Memory |
| @subsection Memory Blocks |
@subsection Memory Blocks |
| doc-fill |
doc-fill |
| doc-blank |
doc-blank |
| doc-compare |
doc-compare |
| |
doc-str= |
| |
doc-str< |
| |
doc-string-prefix? |
| doc-search |
doc-search |
| doc--trailing |
doc--trailing |
| doc-/string |
doc-/string |
| |
doc-bounds |
| |
doc-pad |
| |
|
| @comment TODO examples |
@comment TODO examples |
| |
|
| prejudices against Forth in these people). Adding @code{ENDIF} to a |
prejudices against Forth in these people). Adding @code{ENDIF} to a |
| system that only supplies @code{THEN} is simple: |
system that only supplies @code{THEN} is simple: |
| @example |
@example |
| : ENDIF POSTPONE THEN ; immediate |
: ENDIF POSTPONE then ; immediate |
| @end example |
@end example |
| |
|
| [According to @cite{Webster's New Encyclopedic Dictionary}, @dfn{then |
[According to @cite{Webster's New Encyclopedic Dictionary}, @dfn{then |
| @i{n2} OF @i{code2} ENDOF |
@i{n2} OF @i{code2} ENDOF |
| @dots{} |
@dots{} |
| ( n ) @i{default-code} ( n ) |
( n ) @i{default-code} ( n ) |
| ENDCASE |
ENDCASE ( ) |
| @end example |
@end example |
| |
|
| Executes the first @i{codei}, where the @i{ni} is equal to @i{n}. If no |
Executes the first @i{codei}, where the @i{ni} is equal to @i{n}. If |
| @i{ni} matches, the optional @i{default-code} is executed. The optional |
no @i{ni} matches, the optional @i{default-code} is executed. The |
| default case can be added by simply writing the code after the last |
optional default case can be added by simply writing the code after |
| @code{ENDOF}. It may use @i{n}, which is on top of the stack, but must |
the last @code{ENDOF}. It may use @i{n}, which is on top of the stack, |
| not consume it. |
but must not consume it. The value @i{n} is consumed by this |
| |
construction (either by a OF that matches, or by the ENDCASE, if no OF |
| |
matches). |
| |
|
| @progstyle |
@progstyle |
| To keep the code understandable, you should ensure that on all paths |
To keep the code understandable, you should ensure that you change the |
| through a selection construct the stack is changed in the same way |
stack in the same way (wrt. number and types of stack items consumed |
| (wrt. number and types of stack items consumed and pushed). |
and pushed) on all paths through a selection construct. |
| |
|
| @node Simple Loops, Counted Loops, Selection, Control Structures |
@node Simple Loops, Counted Loops, Selection, Control Structures |
| @subsection Simple Loops |
@subsection Simple Loops |
| IS foo |
IS foo |
| @end example |
@end example |
| |
|
| Deferred words are discussed in more detail in @ref{Deferred words}. |
Deferred words are discussed in more detail in @ref{Deferred Words}. |
| |
|
| The current definition returns control to the calling definition when |
The current definition returns control to the calling definition when |
| the end of the definition is reached or @code{EXIT} is encountered. |
the end of the definition is reached or @code{EXIT} is encountered. |
| The ANS Forth way to catch exceptions is @code{catch}: |
The ANS Forth way to catch exceptions is @code{catch}: |
| |
|
| doc-catch |
doc-catch |
| |
doc-nothrow |
| |
|
| The most common use of exception handlers is to clean up the state when |
The most common use of exception handlers is to clean up the state when |
| an error happens. E.g., |
an error happens. E.g., |
| @example |
@example |
| ['] foo catch |
['] foo catch |
| CASE |
CASE |
| myerror OF ... ( do something about it ) ENDOF |
myerror OF ... ( do something about it ) nothrow ENDOF |
| dup throw \ default: pass other errors on, do nothing on non-errors |
dup throw \ default: pass other errors on, do nothing on non-errors |
| ENDCASE |
ENDCASE |
| @end example |
@end example |
| @example |
@example |
| TRY |
TRY |
| @i{code1} |
@i{code1} |
| RECOVER \ optional |
IFERROR |
| @i{code2} \ optional |
@i{code2} |
| |
THEN |
| |
@i{code3} |
| ENDTRY |
ENDTRY |
| @end example |
@end example |
| |
|
| This performs @i{Code1}. If @i{code1} completes normally, execution |
This performs @i{code1}. If @i{code1} completes normally, execution |
| continues after the @code{endtry}. If @i{Code1} throws, the stacks are |
continues with @i{code3}. If @i{code1} or there is an exception |
| reset to the state during @code{try}, the throw value is pushed on the |
before @code{endtry}, the stacks are reset to the state during |
| data stack, and execution constinues at @i{code2}, and finally falls |
@code{try}, the throw value is pushed on the data stack, and execution |
| through the @code{endtry} into the following code. If there is no |
constinues at @i{code2}, and finally falls through the @i{code3}. |
| @code{recover} clause, this works like an empty recover clause. |
|
| |
|
| doc-try |
doc-try |
| doc-recover |
|
| doc-endtry |
doc-endtry |
| |
doc-iferror |
| |
|
| |
If you don't need @i{code2}, you can write @code{restore} instead of |
| |
@code{iferror then}: |
| |
|
| |
@example |
| |
TRY |
| |
@i{code1} |
| |
RESTORE |
| |
@i{code3} |
| |
ENDTRY |
| |
@end example |
| |
|
| |
@cindex unwind-protect |
| The cleanup example from above in this syntax: |
The cleanup example from above in this syntax: |
| |
|
| @example |
@example |
| base @ >r TRY |
base @@ @{ oldbase @} |
| |
TRY |
| hex foo \ now the hex is placed correctly |
hex foo \ now the hex is placed correctly |
| 0 \ value for throw |
0 \ value for throw |
| |
RESTORE |
| |
oldbase base ! |
| ENDTRY |
ENDTRY |
| r> base ! throw |
throw |
| @end example |
@end example |
| |
|
| And here's the error handling example: |
An additional advantage of this variant is that an exception between |
| |
@code{restore} and @code{endtry} (e.g., from the user pressing |
| |
@kbd{Ctrl-C}) restarts the execution of the code after @code{restore}, |
| |
so the base will be restored under all circumstances. |
| |
|
| |
However, you have to ensure that this code does not cause an exception |
| |
itself, otherwise the @code{iferror}/@code{restore} code will loop. |
| |
Moreover, you should also make sure that the stack contents needed by |
| |
the @code{iferror}/@code{restore} code exist everywhere between |
| |
@code{try} and @code{endtry}; in our example this is achived by |
| |
putting the data in a local before the @code{try} (you cannot use the |
| |
return stack because the exception frame (@i{sys1}) is in the way |
| |
there). |
| |
|
| |
This kind of usage corresponds to Lisp's @code{unwind-protect}. |
| |
|
| |
@cindex @code{recover} (old Gforth versions) |
| |
If you do not want this exception-restarting behaviour, you achieve |
| |
this as follows: |
| |
|
| @example |
@example |
| TRY |
TRY |
| foo |
@i{code1} |
| |
ENDTRY-IFERROR |
| |
@i{code2} |
| |
THEN |
| |
@end example |
| |
|
| |
If there is an exception in @i{code1}, then @i{code2} is executed, |
| |
otherwise execution continues behind the @code{then} (or in a possible |
| |
@code{else} branch). This corresponds to the construct |
| |
|
| |
@example |
| |
TRY |
| |
@i{code1} |
| RECOVER |
RECOVER |
| |
@i{code2} |
| |
ENDTRY |
| |
@end example |
| |
|
| |
in Gforth before version 0.7. So you can directly replace |
| |
@code{recover}-using code; however, we recommend that you check if it |
| |
would not be better to use one of the other @code{try} variants while |
| |
you are at it. |
| |
|
| |
To ease the transition, Gforth provides two compatibility files: |
| |
@file{endtry-iferror.fs} provides the @code{try ... endtry-iferror |
| |
... then} syntax (but not @code{iferror} or @code{restore}) for old |
| |
systems; @file{recover-endtry.fs} provides the @code{try ... recover |
| |
... endtry} syntax on new systems, so you can use that file as a |
| |
stopgap to run old programs. Both files work on any system (they just |
| |
do nothing if the system already has the syntax it implements), so you |
| |
can unconditionally @code{require} one of these files, even if you use |
| |
a mix old and new systems. |
| |
|
| |
doc-restore |
| |
doc-endtry-iferror |
| |
|
| |
Here's the error handling example: |
| |
|
| |
@example |
| |
TRY |
| |
foo |
| |
ENDTRY-IFERROR |
| CASE |
CASE |
| myerror OF ... ( do something about it ) ENDOF |
myerror OF ... ( do something about it ) nothrow ENDOF |
| throw \ pass other errors on |
throw \ pass other errors on |
| ENDCASE |
ENDCASE |
| ENDTRY |
THEN |
| @end example |
@end example |
| |
|
| @progstyle |
@progstyle |
| * Anonymous Definitions:: Definitions without names |
* Anonymous Definitions:: Definitions without names |
| * Supplying names:: Passing definition names as strings |
* Supplying names:: Passing definition names as strings |
| * User-defined Defining Words:: |
* User-defined Defining Words:: |
| * Deferred words:: Allow forward references |
* Deferred Words:: Allow forward references |
| * Aliases:: |
* Aliases:: |
| @end menu |
@end menu |
| |
|
| @example |
@example |
| CREATE text-buf 80 chars allot |
CREATE text-buf 80 chars allot |
| |
|
| text-buf 0 chars c@@ \ the 1st character (offset 0) |
text-buf 0 chars + c@@ \ the 1st character (offset 0) |
| text-buf 3 chars c@@ \ the 4th character (offset 3) |
text-buf 3 chars + c@@ \ the 4th character (offset 3) |
| @end example |
@end example |
| |
|
| You can build arbitrarily complex data structures by allocating |
You can build arbitrarily complex data structures by allocating |
| |
|
| doc-noname |
doc-noname |
| @cindex execution token of last defined word |
@cindex execution token of last defined word |
| doc-lastxt |
doc-latestxt |
| |
|
| @noindent |
@noindent |
| The previous example can be rewritten using @code{noname} and |
The previous example can be rewritten using @code{noname} and |
| @code{lastxt}: |
@code{latestxt}: |
| |
|
| @example |
@example |
| Defer deferred |
Defer deferred |
| noname : ( ... -- ... ) |
noname : ( ... -- ... ) |
| ... ; |
... ; |
| lastxt IS deferred |
latestxt IS deferred |
| @end example |
@end example |
| |
|
| @noindent |
@noindent |
| @code{noname} works with any defining word, not just @code{:}. |
@code{noname} works with any defining word, not just @code{:}. |
| |
|
| @code{lastxt} also works when the last word was not defined as |
@code{latestxt} also works when the last word was not defined as |
| @code{noname}. It does not work for combined words, though. It also has |
@code{noname}. It does not work for combined words, though. It also has |
| the useful property that is is valid as soon as the header for a |
the useful property that is is valid as soon as the header for a |
| definition has been built. Thus: |
definition has been built. Thus: |
| |
|
| @example |
@example |
| lastxt . : foo [ lastxt . ] ; ' foo . |
latestxt . : foo [ latestxt . ] ; ' foo . |
| @end example |
@end example |
| |
|
| @noindent |
@noindent |
| @code{nextname} works with any defining word. |
@code{nextname} works with any defining word. |
| |
|
| |
|
| @node User-defined Defining Words, Deferred words, Supplying names, Defining Words |
@node User-defined Defining Words, Deferred Words, Supplying names, Defining Words |
| @subsection User-defined Defining Words |
@subsection User-defined Defining Words |
| @cindex user-defined defining words |
@cindex user-defined defining words |
| @cindex defining words, user-defined |
@cindex defining words, user-defined |
| : stats ( xt -- ) DUP ." (Gathering statistics for " . ." )" |
: stats ( xt -- ) DUP ." (Gathering statistics for " . ." )" |
| ... ; \ other code |
... ; \ other code |
| |
|
| : my: : lastxt postpone literal ['] stats compile, ; |
: my: : latestxt postpone literal ['] stats compile, ; |
| |
|
| my: foo + - ; |
my: foo + - ; |
| @end example |
@end example |
| @code{my:} is executed. |
@code{my:} is executed. |
| @item |
@item |
| The @code{:} within the definition (the one between @code{my:} and |
The @code{:} within the definition (the one between @code{my:} and |
| @code{lastxt}) is executed, and does just what it always does; it parses |
@code{latestxt}) is executed, and does just what it always does; it parses |
| the input stream for a name, builds a dictionary header for the name |
the input stream for a name, builds a dictionary header for the name |
| @code{foo} and switches @code{state} from interpret to compile. |
@code{foo} and switches @code{state} from interpret to compile. |
| @item |
@item |
| The word @code{lastxt} is executed. It puts the @i{xt} for the word that is |
The word @code{latestxt} is executed. It puts the @i{xt} for the word that is |
| being defined -- @code{foo} -- onto the stack. |
being defined -- @code{foo} -- onto the stack. |
| @item |
@item |
| The code that was produced by @code{postpone literal} is executed; this |
The code that was produced by @code{postpone literal} is executed; this |
| : foo |
: foo |
| 107645672 stats + - ; |
107645672 stats + - ; |
| |
|
| \ use ' stats . to show that 107645672 is the xt for stats |
\ use ' foo . to show that 107645672 is the xt for foo |
| @end example |
@end example |
| |
|
| You can use techniques like this to make new defining words in terms of |
You can use techniques like this to make new defining words in terms of |
| * CREATE..DOES> applications:: |
* CREATE..DOES> applications:: |
| * CREATE..DOES> details:: |
* CREATE..DOES> details:: |
| * Advanced does> usage example:: |
* Advanced does> usage example:: |
| |
* Const-does>:: |
| @end menu |
@end menu |
| |
|
| @node CREATE..DOES> applications, CREATE..DOES> details, User-defined Defining Words, User-defined Defining Words |
@node CREATE..DOES> applications, CREATE..DOES> details, User-defined Defining Words, User-defined Defining Words |
| the functional language community). E.g., @code{+} needs two |
the functional language community). E.g., @code{+} needs two |
| parameters. Creating versions of @code{+} with one parameter fixed can |
parameters. Creating versions of @code{+} with one parameter fixed can |
| be done like this: |
be done like this: |
| |
|
| @example |
@example |
| : curry+ ( n1 -- ) |
: curry+ ( n1 "name" -- ) |
| CREATE , |
CREATE , |
| DOES> ( n2 -- n1+n2 ) |
DOES> ( n2 -- n1+n2 ) |
| @@ + ; |
@@ + ; |
| -2 curry+ 2- |
-2 curry+ 2- |
| @end example |
@end example |
| |
|
| |
|
| @node CREATE..DOES> details, Advanced does> usage example, CREATE..DOES> applications, User-defined Defining Words |
@node CREATE..DOES> details, Advanced does> usage example, CREATE..DOES> applications, User-defined Defining Words |
| @subsubsection The gory details of @code{CREATE..DOES>} |
@subsubsection The gory details of @code{CREATE..DOES>} |
| @cindex @code{CREATE} ... @code{DOES>}, details |
@cindex @code{CREATE} ... @code{DOES>}, details |
| |
|
| doc->body |
doc->body |
| |
|
| @node Advanced does> usage example, , CREATE..DOES> details, User-defined Defining Words |
@node Advanced does> usage example, Const-does>, CREATE..DOES> details, User-defined Defining Words |
| @subsubsection Advanced does> usage example |
@subsubsection Advanced does> usage example |
| |
|
| The MIPS disassembler (@file{arch/mips/disasm.fs}) contains many words |
The MIPS disassembler (@file{arch/mips/disasm.fs}) contains many words |
| : @var{inst-format} ( entry-num "name" -- ) |
: @var{inst-format} ( entry-num "name" -- ) |
| here name string, ( entry-num c-addr ) \ parse and save "name" |
here name string, ( entry-num c-addr ) \ parse and save "name" |
| noname create , ( entry-num ) |
noname create , ( entry-num ) |
| lastxt swap cells @var{table} + ! |
latestxt swap cells @var{table} + ! |
| does> ( addr w -- ) |
does> ( addr w -- ) |
| \ disassemble instruction w at addr |
\ disassemble instruction w at addr |
| @@ >r |
@@ >r |
| \ and enters it as u-th entry into table-xt |
\ and enters it as u-th entry into table-xt |
| 2@@ swap here name string, ( u table-xt disasm-xt c-addr ) \ remember string |
2@@ swap here name string, ( u table-xt disasm-xt c-addr ) \ remember string |
| noname create 2, \ define anonymous word |
noname create 2, \ define anonymous word |
| execute lastxt swap ! \ enter xt of defined word into table-xt |
execute latestxt swap ! \ enter xt of defined word into table-xt |
| does> ( addr w -- ) |
does> ( addr w -- ) |
| \ disassemble instruction w at addr |
\ disassemble instruction w at addr |
| 2@@ >r ( addr w disasm-xt R: c-addr ) |
2@@ >r ( addr w disasm-xt R: c-addr ) |
| understand this, but it may improve your understanding of Forth. |
understand this, but it may improve your understanding of Forth. |
| |
|
| |
|
| @node Deferred words, Aliases, User-defined Defining Words, Defining Words |
@node Const-does>, , Advanced does> usage example, User-defined Defining Words |
| @subsection Deferred words |
@subsubsection @code{Const-does>} |
| @cindex deferred words |
|
| |
|
| The defining word @code{Defer} allows you to define a word by name |
A frequent use of @code{create}...@code{does>} is for transferring some |
| without defining its behaviour; the definition of its behaviour is |
values from definition-time to run-time. Gforth supports this use with |
| deferred. Here are two situation where this can be useful: |
|
| |
|
| @itemize @bullet |
doc-const-does> |
| @item |
|
| Where you want to allow the behaviour of a word to be altered later, and |
|
| for all precompiled references to the word to change when its behaviour |
|
| is changed. |
|
| @item |
|
| For mutual recursion; @xref{Calls and returns}. |
|
| @end itemize |
|
| |
|
| In the following example, @code{foo} always invokes the version of |
A typical use of this word is: |
| @code{greet} that prints ``@code{Good morning}'' whilst @code{bar} |
|
| always invokes the version that prints ``@code{Hello}''. There is no way |
@example |
| |
: curry+ ( n1 "name" -- ) |
| |
1 0 CONST-DOES> ( n2 -- n1+n2 ) |
| |
+ ; |
| |
|
| |
3 curry+ 3+ |
| |
@end example |
| |
|
| |
Here the @code{1 0} means that 1 cell and 0 floats are transferred from |
| |
definition to run-time. |
| |
|
| |
The advantages of using @code{const-does>} are: |
| |
|
| |
@itemize |
| |
|
| |
@item |
| |
You don't have to deal with storing and retrieving the values, i.e., |
| |
your program becomes more writable and readable. |
| |
|
| |
@item |
| |
When using @code{does>}, you have to introduce a @code{@@} that cannot |
| |
be optimized away (because you could change the data using |
| |
@code{>body}...@code{!}); @code{const-does>} avoids this problem. |
| |
|
| |
@end itemize |
| |
|
| |
An ANS Forth implementation of @code{const-does>} is available in |
| |
@file{compat/const-does.fs}. |
| |
|
| |
|
| |
@node Deferred Words, Aliases, User-defined Defining Words, Defining Words |
| |
@subsection Deferred Words |
| |
@cindex deferred words |
| |
|
| |
The defining word @code{Defer} allows you to define a word by name |
| |
without defining its behaviour; the definition of its behaviour is |
| |
deferred. Here are two situation where this can be useful: |
| |
|
| |
@itemize @bullet |
| |
@item |
| |
Where you want to allow the behaviour of a word to be altered later, and |
| |
for all precompiled references to the word to change when its behaviour |
| |
is changed. |
| |
@item |
| |
For mutual recursion; @xref{Calls and returns}. |
| |
@end itemize |
| |
|
| |
In the following example, @code{foo} always invokes the version of |
| |
@code{greet} that prints ``@code{Good morning}'' whilst @code{bar} |
| |
always invokes the version that prints ``@code{Hello}''. There is no way |
| of getting @code{foo} to use the later version without re-ordering the |
of getting @code{foo} to use the later version without re-ordering the |
| source code and recompiling it. |
source code and recompiling it. |
| |
|
| : bar ... greet ... ; |
: bar ... greet ... ; |
| : greet1 ( -- ) ." Good morning" ; |
: greet1 ( -- ) ." Good morning" ; |
| : greet2 ( -- ) ." Hello" ; |
: greet2 ( -- ) ." Hello" ; |
| ' greet2 <IS> greet \ make greet behave like greet2 |
' greet2 IS greet \ make greet behave like greet2 |
| @end example |
@end example |
| |
|
| @progstyle |
@progstyle |
| @example |
@example |
| : real: : ; \ retain access to the original |
: real: : ; \ retain access to the original |
| defer : \ redefine as a deferred word |
defer : \ redefine as a deferred word |
| ' my: <IS> : \ use special version of : |
' my: IS : \ use special version of : |
| \ |
\ |
| \ load application here |
\ load application here |
| \ |
\ |
| ' real: <IS> : \ go back to the original |
' real: IS : \ go back to the original |
| @end example |
@end example |
| |
|
| |
|
| One thing to note is that @code{<IS>} consumes its name when it is |
One thing to note is that @code{IS} has special compilation semantics, |
| executed. If you want to specify the name at compile time, use |
such that it parses the name at compile time (like @code{TO}): |
| @code{[IS]}: |
|
| |
|
| @example |
@example |
| : set-greet ( xt -- ) |
: set-greet ( xt -- ) |
| [IS] greet ; |
IS greet ; |
| |
|
| ' greet1 set-greet |
' greet1 set-greet |
| @end example |
@end example |
| |
|
| |
In situations where @code{IS} does not fit, use @code{defer!} instead. |
| |
|
| A deferred word can only inherit execution semantics from the xt |
A deferred word can only inherit execution semantics from the xt |
| (because that is all that an xt can represent -- for more discussion of |
(because that is all that an xt can represent -- for more discussion of |
| this @pxref{Tokens for Words}); by default it will have default |
this @pxref{Tokens for Words}); by default it will have default |
| semantics of the deferred word in the usual ways: |
semantics of the deferred word in the usual ways: |
| |
|
| @example |
@example |
| : bar .... ; compile-only |
: bar .... ; immediate |
| Defer fred immediate |
Defer fred immediate |
| Defer jim |
Defer jim |
| |
|
| ' bar <IS> jim \ jim has default semantics |
' bar IS jim \ jim has default semantics |
| ' bar <IS> fred \ fred is immediate |
' bar IS fred \ fred is immediate |
| @end example |
@end example |
| |
|
| doc-defer |
doc-defer |
| doc-<is> |
doc-defer! |
| doc-[is] |
|
| doc-is |
doc-is |
| |
doc-defer@ |
| |
doc-action-of |
| @comment TODO document these: what's defers [is] |
@comment TODO document these: what's defers [is] |
| doc-what's |
|
| doc-defers |
doc-defers |
| |
|
| @c Use @code{words-deferred} to see a list of deferred words. |
@c Use @code{words-deferred} to see a list of deferred words. |
| |
|
| Definitions in ANS Forth for @code{defer}, @code{<is>} and @code{[is]} |
Definitions of these words (except @code{defers}) in ANS Forth are |
| are provided in @file{compat/defer.fs}. |
provided in @file{compat/defer.fs}. |
| |
|
| |
|
| @node Aliases, , Deferred words, Defining Words |
@node Aliases, , Deferred Words, Defining Words |
| @subsection Aliases |
@subsection Aliases |
| @cindex aliases |
@cindex aliases |
| |
|
| doc-compile-only |
doc-compile-only |
| doc-restrict |
doc-restrict |
| |
|
| |
By convention, words with non-default compilation semantics (e.g., |
| |
immediate words) often have names surrounded with brackets (e.g., |
| |
@code{[']}, @pxref{Execution token}). |
| |
|
| Note that ticking (@code{'}) a compile-only word gives an error |
Note that ticking (@code{'}) a compile-only word gives an error |
| (``Interpreting a compile-only word''). |
(``Interpreting a compile-only word''). |
| @code{[compile] foobar} would compile interpretation semantics. |
@code{[compile] foobar} would compile interpretation semantics. |
| |
|
| @cindex state-smart words (are a bad idea) |
@cindex state-smart words (are a bad idea) |
| |
@anchor{state-smartness} |
| Some people try to use @dfn{state-smart} words to emulate the feature provided |
Some people try to use @dfn{state-smart} words to emulate the feature provided |
| by @code{interpret/compile:} (words are state-smart if they check |
by @code{interpret/compile:} (words are state-smart if they check |
| @code{STATE} during execution). E.g., they would try to code |
@code{STATE} during execution). E.g., they would try to code |
| with @code{create-interpret/compile}. |
with @code{create-interpret/compile}. |
| |
|
| |
|
| doc-postpone |
|
| |
|
| @comment TODO -- expand glossary text for POSTPONE |
|
| |
|
| |
|
| @c ------------------------------------------------------------- |
@c ------------------------------------------------------------- |
| @node Tokens for Words, The Text Interpreter, Interpretation and Compilation Semantics, Words |
@node Tokens for Words, Compiling words, Interpretation and Compilation Semantics, Words |
| @section Tokens for Words |
@section Tokens for Words |
| @cindex tokens for words |
@cindex tokens for words |
| |
|
| interpretation semantics of a named word: |
interpretation semantics of a named word: |
| |
|
| @example |
@example |
| 5 ' . |
5 ' . ( n xt ) |
| execute |
execute ( ) \ execute the xt (i.e., ".") |
| @end example |
@end example |
| |
|
| doc-' |
doc-' |
| DROP} or @code{[COMP'] @i{word} DROP} (for details @pxref{Compilation |
DROP} or @code{[COMP'] @i{word} DROP} (for details @pxref{Compilation |
| token}). |
token}). |
| |
|
| Another way to get an XT is @code{:noname} or @code{lastxt} |
Another way to get an XT is @code{:noname} or @code{latestxt} |
| (@pxref{Anonymous Definitions}). For anonymous words this gives an xt |
(@pxref{Anonymous Definitions}). For anonymous words this gives an xt |
| for the only behaviour the word has (the execution semantics). For |
for the only behaviour the word has (the execution semantics). For |
| named words, @code{lastxt} produces an XT for the same behaviour it |
named words, @code{latestxt} produces an XT for the same behaviour it |
| would produce if the word was defined anonymously. |
would produce if the word was defined anonymously. |
| |
|
| @example |
@example |
| operations that produce or consume it). For old hands: In Gforth, the |
operations that produce or consume it). For old hands: In Gforth, the |
| XT is implemented as a code field address (CFA). |
XT is implemented as a code field address (CFA). |
| |
|
| @c !! discuss "compile," some more (or in Macros). |
|
| |
|
| doc-execute |
doc-execute |
| doc-perform |
doc-perform |
| doc-compile, |
|
| |
|
| @node Compilation token, Name token, Execution token, Tokens for Words |
@node Compilation token, Name token, Execution token, Tokens for Words |
| @subsection Compilation token |
@subsection Compilation token |
| @subsection Name token |
@subsection Name token |
| |
|
| @cindex name token |
@cindex name token |
| |
Gforth represents named words by the @dfn{name token}, (@i{nt}). Name |
| |
token is an abstract data type that occurs as argument or result of the |
| |
words below. |
| |
|
| |
@c !! put this elswhere? |
| @cindex name field address |
@cindex name field address |
| @cindex NFA |
@cindex NFA |
| Gforth represents named words by the @dfn{name token}, (@i{nt}). In |
The closest thing to the nt in older Forth systems is the name field |
| Gforth, the abstract data type @emph{name token} is implemented as a |
address (NFA), but there are significant differences: in older Forth |
| name field address (NFA). |
systems each word had a unique NFA, LFA, CFA and PFA (in this order, or |
| |
LFA, NFA, CFA, PFA) and there were words for getting from one to the |
| |
next. In contrast, in Gforth 0@dots{}n nts correspond to one xt; there |
| |
is a link field in the structure identified by the name token, but |
| |
searching usually uses a hash table external to these structures; the |
| |
name in Gforth has a cell-wide count-and-flags field, and the nt is not |
| |
implemented as the address of that count field. |
| |
|
| doc-find-name |
doc-find-name |
| |
doc-latest |
| |
doc->name |
| doc-name>int |
doc-name>int |
| doc-name?int |
doc-name?int |
| doc-name>comp |
doc-name>comp |
| doc-name>string |
doc-name>string |
| |
doc-id. |
| |
doc-.name |
| |
doc-.id |
| |
|
| |
@c ---------------------------------------------------------- |
| |
@node Compiling words, The Text Interpreter, Tokens for Words, Words |
| |
@section Compiling words |
| |
@cindex compiling words |
| |
@cindex macros |
| |
|
| |
In contrast to most other languages, Forth has no strict boundary |
| |
between compilation and run-time. E.g., you can run arbitrary code |
| |
between defining words (or for computing data used by defining words |
| |
like @code{constant}). Moreover, @code{Immediate} (@pxref{Interpretation |
| |
and Compilation Semantics} and @code{[}...@code{]} (see below) allow |
| |
running arbitrary code while compiling a colon definition (exception: |
| |
you must not allot dictionary space). |
| |
|
| |
@menu |
| |
* Literals:: Compiling data values |
| |
* Macros:: Compiling words |
| |
@end menu |
| |
|
| |
@node Literals, Macros, Compiling words, Compiling words |
| |
@subsection Literals |
| |
@cindex Literals |
| |
|
| |
The simplest and most frequent example is to compute a literal during |
| |
compilation. E.g., the following definition prints an array of strings, |
| |
one string per line: |
| |
|
| |
@example |
| |
: .strings ( addr u -- ) \ gforth |
| |
2* cells bounds U+DO |
| |
cr i 2@@ type |
| |
2 cells +LOOP ; |
| |
@end example |
| |
|
| |
With a simple-minded compiler like Gforth's, this computes @code{2 |
| |
cells} on every loop iteration. You can compute this value once and for |
| |
all at compile time and compile it into the definition like this: |
| |
|
| |
@example |
| |
: .strings ( addr u -- ) \ gforth |
| |
2* cells bounds U+DO |
| |
cr i 2@@ type |
| |
[ 2 cells ] literal +LOOP ; |
| |
@end example |
| |
|
| |
@code{[} switches the text interpreter to interpret state (you will get |
| |
an @code{ok} prompt if you type this example interactively and insert a |
| |
newline between @code{[} and @code{]}), so it performs the |
| |
interpretation semantics of @code{2 cells}; this computes a number. |
| |
@code{]} switches the text interpreter back into compile state. It then |
| |
performs @code{Literal}'s compilation semantics, which are to compile |
| |
this number into the current word. You can decompile the word with |
| |
@code{see .strings} to see the effect on the compiled code. |
| |
|
| |
You can also optimize the @code{2* cells} into @code{[ 2 cells ] literal |
| |
*} in this way. |
| |
|
| |
doc-[ |
| |
doc-] |
| |
doc-literal |
| |
doc-]L |
| |
|
| |
There are also words for compiling other data types than single cells as |
| |
literals: |
| |
|
| |
doc-2literal |
| |
doc-fliteral |
| |
doc-sliteral |
| |
|
| |
@cindex colon-sys, passing data across @code{:} |
| |
@cindex @code{:}, passing data across |
| |
You might be tempted to pass data from outside a colon definition to the |
| |
inside on the data stack. This does not work, because @code{:} puhes a |
| |
colon-sys, making stuff below unaccessible. E.g., this does not work: |
| |
|
| |
@example |
| |
5 : foo literal ; \ error: "unstructured" |
| |
@end example |
| |
|
| |
Instead, you have to pass the value in some other way, e.g., through a |
| |
variable: |
| |
|
| |
@example |
| |
variable temp |
| |
5 temp ! |
| |
: foo [ temp @@ ] literal ; |
| |
@end example |
| |
|
| |
|
| |
@node Macros, , Literals, Compiling words |
| |
@subsection Macros |
| |
@cindex Macros |
| |
@cindex compiling compilation semantics |
| |
|
| |
@code{Literal} and friends compile data values into the current |
| |
definition. You can also write words that compile other words into the |
| |
current definition. E.g., |
| |
|
| |
@example |
| |
: compile-+ ( -- ) \ compiled code: ( n1 n2 -- n ) |
| |
POSTPONE + ; |
| |
|
| |
: foo ( n1 n2 -- n ) |
| |
[ compile-+ ] ; |
| |
1 2 foo . |
| |
@end example |
| |
|
| |
This is equivalent to @code{: foo + ;} (@code{see foo} to check this). |
| |
What happens in this example? @code{Postpone} compiles the compilation |
| |
semantics of @code{+} into @code{compile-+}; later the text interpreter |
| |
executes @code{compile-+} and thus the compilation semantics of +, which |
| |
compile (the execution semantics of) @code{+} into |
| |
@code{foo}.@footnote{A recent RFI answer requires that compiling words |
| |
should only be executed in compile state, so this example is not |
| |
guaranteed to work on all standard systems, but on any decent system it |
| |
will work.} |
| |
|
| |
doc-postpone |
| |
doc-[compile] |
| |
|
| |
Compiling words like @code{compile-+} are usually immediate (or similar) |
| |
so you do not have to switch to interpret state to execute them; |
| |
mopifying the last example accordingly produces: |
| |
|
| |
@example |
| |
: [compile-+] ( compilation: --; interpretation: -- ) |
| |
\ compiled code: ( n1 n2 -- n ) |
| |
POSTPONE + ; immediate |
| |
|
| |
: foo ( n1 n2 -- n ) |
| |
[compile-+] ; |
| |
1 2 foo . |
| |
@end example |
| |
|
| |
Immediate compiling words are similar to macros in other languages (in |
| |
particular, Lisp). The important differences to macros in, e.g., C are: |
| |
|
| |
@itemize @bullet |
| |
|
| |
@item |
| |
You use the same language for defining and processing macros, not a |
| |
separate preprocessing language and processor. |
| |
|
| |
@item |
| |
Consequently, the full power of Forth is available in macro definitions. |
| |
E.g., you can perform arbitrarily complex computations, or generate |
| |
different code conditionally or in a loop (e.g., @pxref{Advanced macros |
| |
Tutorial}). This power is very useful when writing a parser generators |
| |
or other code-generating software. |
| |
|
| |
@item |
| |
Macros defined using @code{postpone} etc. deal with the language at a |
| |
higher level than strings; name binding happens at macro definition |
| |
time, so you can avoid the pitfalls of name collisions that can happen |
| |
in C macros. Of course, Forth is a liberal language and also allows to |
| |
shoot yourself in the foot with text-interpreted macros like |
| |
|
| |
@example |
| |
: [compile-+] s" +" evaluate ; immediate |
| |
@end example |
| |
|
| |
Apart from binding the name at macro use time, using @code{evaluate} |
| |
also makes your definition @code{state}-smart (@pxref{state-smartness}). |
| |
@end itemize |
| |
|
| |
You may want the macro to compile a number into a word. The word to do |
| |
it is @code{literal}, but you have to @code{postpone} it, so its |
| |
compilation semantics take effect when the macro is executed, not when |
| |
it is compiled: |
| |
|
| |
@example |
| |
: [compile-5] ( -- ) \ compiled code: ( -- n ) |
| |
5 POSTPONE literal ; immediate |
| |
|
| |
: foo [compile-5] ; |
| |
foo . |
| |
@end example |
| |
|
| |
You may want to pass parameters to a macro, that the macro should |
| |
compile into the current definition. If the parameter is a number, then |
| |
you can use @code{postpone literal} (similar for other values). |
| |
|
| |
If you want to pass a word that is to be compiled, the usual way is to |
| |
pass an execution token and @code{compile,} it: |
| |
|
| |
@example |
| |
: twice1 ( xt -- ) \ compiled code: ... -- ... |
| |
dup compile, compile, ; |
| |
|
| |
: 2+ ( n1 -- n2 ) |
| |
[ ' 1+ twice1 ] ; |
| |
@end example |
| |
|
| |
doc-compile, |
| |
|
| |
An alternative available in Gforth, that allows you to pass compile-only |
| |
words as parameters is to use the compilation token (@pxref{Compilation |
| |
token}). The same example in this technique: |
| |
|
| |
@example |
| |
: twice ( ... ct -- ... ) \ compiled code: ... -- ... |
| |
2dup 2>r execute 2r> execute ; |
| |
|
| |
: 2+ ( n1 -- n2 ) |
| |
[ comp' 1+ twice ] ; |
| |
@end example |
| |
|
| |
In the example above @code{2>r} and @code{2r>} ensure that @code{twice} |
| |
works even if the executed compilation semantics has an effect on the |
| |
data stack. |
| |
|
| |
You can also define complete definitions with these words; this provides |
| |
an alternative to using @code{does>} (@pxref{User-defined Defining |
| |
Words}). E.g., instead of |
| |
|
| |
@example |
| |
: curry+ ( n1 "name" -- ) |
| |
CREATE , |
| |
DOES> ( n2 -- n1+n2 ) |
| |
@@ + ; |
| |
@end example |
| |
|
| |
you could define |
| |
|
| |
@example |
| |
: curry+ ( n1 "name" -- ) |
| |
\ name execution: ( n2 -- n1+n2 ) |
| |
>r : r> POSTPONE literal POSTPONE + POSTPONE ; ; |
| |
|
| |
-3 curry+ 3- |
| |
see 3- |
| |
@end example |
| |
|
| |
The sequence @code{>r : r>} is necessary, because @code{:} puts a |
| |
colon-sys on the data stack that makes everything below it unaccessible. |
| |
|
| |
This way of writing defining words is sometimes more, sometimes less |
| |
convenient than using @code{does>} (@pxref{Advanced does> usage |
| |
example}). One advantage of this method is that it can be optimized |
| |
better, because the compiler knows that the value compiled with |
| |
@code{literal} is fixed, whereas the data associated with a |
| |
@code{create}d word can be changed. |
| |
|
| @c ---------------------------------------------------------- |
@c ---------------------------------------------------------- |
| @node The Text Interpreter, Word Lists, Tokens for Words, Words |
@node The Text Interpreter, The Input Stream, Compiling words, Words |
| @section The Text Interpreter |
@section The Text Interpreter |
| @cindex interpreter - outer |
@cindex interpreter - outer |
| @cindex text interpreter |
@cindex text interpreter |
| * Input Sources:: |
* Input Sources:: |
| * Number Conversion:: |
* Number Conversion:: |
| * Interpret/Compile states:: |
* Interpret/Compile states:: |
| * Literals:: |
|
| * Interpreter Directives:: |
* Interpreter Directives:: |
| @end menu |
@end menu |
| |
|
| doc-restore-input |
doc-restore-input |
| |
|
| doc-evaluate |
doc-evaluate |
| |
doc-query |
| |
|
| |
|
| |
|
| number) +12.E-4 |
number) +12.E-4 |
| @end itemize |
@end itemize |
| |
|
| By default, the number base used for integer number conversion is given |
By default, the number base used for integer number conversion is |
| by the contents of the variable @code{base}. Note that a lot of |
given by the contents of the variable @code{base}. Note that a lot of |
| confusion can result from unexpected values of @code{base}. If you |
confusion can result from unexpected values of @code{base}. If you |
| change @code{base} anywhere, make sure to save the old value and restore |
change @code{base} anywhere, make sure to save the old value and |
| it afterwards. In general I recommend keeping @code{base} decimal, and |
restore it afterwards; better yet, use @code{base-execute}, which does |
| |
this for you. In general I recommend keeping @code{base} decimal, and |
| using the prefixes described below for the popular non-decimal bases. |
using the prefixes described below for the popular non-decimal bases. |
| |
|
| doc-dpl |
doc-dpl |
| |
doc-base-execute |
| doc-base |
doc-base |
| doc-hex |
doc-hex |
| doc-decimal |
doc-decimal |
| |
|
| |
|
| @cindex '-prefix for character strings |
@cindex '-prefix for character strings |
| @cindex &-prefix for decimal numbers |
@cindex &-prefix for decimal numbers |
| |
@cindex #-prefix for decimal numbers |
| @cindex %-prefix for binary numbers |
@cindex %-prefix for binary numbers |
| @cindex $-prefix for hexadecimal numbers |
@cindex $-prefix for hexadecimal numbers |
| |
@cindex 0x-prefix for hexadecimal numbers |
| Gforth allows you to override the value of @code{base} by using a |
Gforth allows you to override the value of @code{base} by using a |
| prefix@footnote{Some Forth implementations provide a similar scheme by |
prefix@footnote{Some Forth implementations provide a similar scheme by |
| implementing @code{$} etc. as parsing words that process the subsequent |
implementing @code{$} etc. as parsing words that process the subsequent |
| @cite{Number Conversion and Literals}, by Wil Baden; Forth Dimensions |
@cite{Number Conversion and Literals}, by Wil Baden; Forth Dimensions |
| 20(3) pages 26--27. In such implementations, unlike in Gforth, a space |
20(3) pages 26--27. In such implementations, unlike in Gforth, a space |
| is required between the prefix and the number.} before the first digit |
is required between the prefix and the number.} before the first digit |
| of an (integer) number. Four prefixes are supported: |
of an (integer) number. The following prefixes are supported: |
| |
|
| @itemize @bullet |
@itemize @bullet |
| @item |
@item |
| @code{&} -- decimal |
@code{&} -- decimal |
| @item |
@item |
| |
@code{#} -- decimal |
| |
@item |
| @code{%} -- binary |
@code{%} -- binary |
| @item |
@item |
| @code{$} -- hexadecimal |
@code{$} -- hexadecimal |
| @item |
@item |
| @code{'} -- base @code{max-char+1} |
@code{0x} -- hexadecimal, if base<33. |
| |
@item |
| |
@code{'} -- numeric value (e.g., ASCII code) of next character; an |
| |
optional @code{'} may be present after the character. |
| @end itemize |
@end itemize |
| |
|
| Here are some examples, with the equivalent decimal number shown after |
Here are some examples, with the equivalent decimal number shown after |
| in braces: |
in braces: |
| |
|
| -$41 (-65), %1001101 (205), %1001.0001 (145 - a double-precision number), |
-$41 (-65), %1001101 (205), %1001.0001 (145 - a double-precision number), |
| 'AB (16706; ascii A is 65, ascii B is 66, number is 65*256 + 66), |
'A (65), |
| 'ab (24930; ascii a is 97, ascii B is 98, number is 97*256 + 98), |
-'a' (-97), |
| &905 (905), $abc (2478), $ABC (2478). |
&905 (905), $abc (2478), $ABC (2478). |
| |
|
| @cindex number conversion - traps for the unwary |
@cindex number conversion - traps for the unwary |
| @end itemize |
@end itemize |
| |
|
| You can read numbers into your programs with the words described in |
You can read numbers into your programs with the words described in |
| @ref{Input}. |
@ref{Line input and conversion}. |
| |
|
| @node Interpret/Compile states, Literals, Number Conversion, The Text Interpreter |
@node Interpret/Compile states, Interpreter Directives, Number Conversion, The Text Interpreter |
| @subsection Interpret/Compile states |
@subsection Interpret/Compile states |
| @cindex Interpret/Compile states |
@cindex Interpret/Compile states |
| |
|
| @c where it outlaws a style in common use. |
@c where it outlaws a style in common use. |
| |
|
| @c anton: it's more important to show what's portable. After we have done |
@c anton: it's more important to show what's portable. After we have done |
| @c that, we can also show what's not. In any case, I intend to write a |
@c that, we can also show what's not. In any case, I have written a |
| @c section Macros (or so) which will also deal with [ ]. |
@c section Compiling Words which also deals with [ ]. |
| |
|
| @code{[} and @code{]} also give you the ability to switch into compile |
|
| state and back, but we cannot think of any useful Standard application |
|
| for this ability. Pre-ANS Forth textbooks have examples like this: |
|
| |
|
| @example |
|
| : AA ." this is A" ; |
|
| : BB ." this is B" ; |
|
| : CC ." this is C" ; |
|
| |
|
| create table ] aa bb cc [ |
|
| |
|
| : go ( n -- ) \ n is offset into table.. 0 for 1st entry |
|
| cells table + @ execute ; |
|
| @end example |
|
| |
|
| This example builds a jump table; @code{0 go} will display ``@code{this |
|
| is A}''. Using @code{[} and @code{]} in this example is equivalent to |
|
| defining @code{table} like this: |
|
| |
|
| @example |
|
| create table ' aa COMPILE, ' bb COMPILE, ' cc COMPILE, |
|
| @end example |
|
| |
|
| The problem with this code is that the definition of @code{table} is not |
|
| portable -- it @i{compile}s execution tokens into code space. Whilst it |
|
| @i{may} work on systems where code space and data space co-incide, the |
|
| Standard only allows data space to be assigned for a @code{CREATE}d |
|
| word. In addition, the Standard only allows @code{@@} to access data |
|
| space, whilst this example is using it to access code space. The only |
|
| portable, Standard way to build this table is to build it in data space, |
|
| like this: |
|
| |
|
| @example |
|
| create table ' aa , ' bb , ' cc , |
|
| @end example |
|
| |
|
| doc-state |
|
| doc-[ |
|
| doc-] |
|
| |
|
| |
|
| @node Literals, Interpreter Directives, Interpret/Compile states, The Text Interpreter |
|
| @subsection Literals |
|
| @cindex Literals |
|
| |
|
| Often, you want to use a number within a colon definition. When you do |
@c !! The following example does not work in Gforth 0.5.9 or later. |
| this, the text interpreter automatically compiles the number as a |
|
| @i{literal}. A literal is a number whose run-time effect is to be pushed |
|
| onto the stack. If you had to do some maths to generate the number, you |
|
| might write it like this: |
|
| |
|
| @example |
@c @code{[} and @code{]} also give you the ability to switch into compile |
| : HOUR-TO-SEC ( n1 -- n2 ) |
@c state and back, but we cannot think of any useful Standard application |
| 60 * \ to minutes |
@c for this ability. Pre-ANS Forth textbooks have examples like this: |
| 60 * ; \ to seconds |
|
| @end example |
|
| |
|
| It is very clear what this definition is doing, but it's inefficient |
@c @example |
| since it is performing 2 multiples at run-time. An alternative would be |
@c : AA ." this is A" ; |
| to write: |
@c : BB ." this is B" ; |
| |
@c : CC ." this is C" ; |
| |
|
| @example |
@c create table ] aa bb cc [ |
| : HOUR-TO-SEC ( n1 -- n2 ) |
|
| 3600 * ; \ to seconds |
|
| @end example |
|
| |
|
| Which does the same thing, and has the advantage of using a single |
|
| multiply. Ideally, we'd like the efficiency of the second with the |
|
| readability of the first. |
|
| |
|
| @code{Literal} allows us to achieve that. It takes a number from the |
@c : go ( n -- ) \ n is offset into table.. 0 for 1st entry |
| stack and lays it down in the current definition just as though the |
@c cells table + @@ execute ; |
| number had been typed directly into the definition. Our first attempt |
@c @end example |
| might look like this: |
|
| |
|
| @example |
@c This example builds a jump table; @code{0 go} will display ``@code{this |
| 60 \ mins per hour |
@c is A}''. Using @code{[} and @code{]} in this example is equivalent to |
| 60 * \ seconds per minute |
@c defining @code{table} like this: |
| : HOUR-TO-SEC ( n1 -- n2 ) |
|
| Literal * ; \ to seconds |
|
| @end example |
|
| |
|
| But this produces the error message @code{unstructured}. What happened? |
@c @example |
| The stack notation for @code{:} is (@i{ -- colon-sys}) and the size of |
@c create table ' aa COMPILE, ' bb COMPILE, ' cc COMPILE, |
| @i{colon-sys} is implementation-defined. In other words, once we start a |
@c @end example |
| colon definition we can't portably access anything that was on the stack |
|
| before the definition began@footnote{@cite{Two Problems in ANS Forth}, |
|
| by Thomas Worthington; Forth Dimensions 20(2) pages 32--34 describes |
|
| some situations where you might want to access stack items above |
|
| colon-sys, and provides a solution to the problem.}. The correct way of |
|
| solving this problem in this instance is to use @code{[ ]} like this: |
|
| |
|
| @example |
@c The problem with this code is that the definition of @code{table} is not |
| : HOUR-TO-SEC ( n1 -- n2 ) |
@c portable -- it @i{compile}s execution tokens into code space. Whilst it |
| [ 60 \ minutes per hour |
@c @i{may} work on systems where code space and data space co-incide, the |
| 60 * ] \ seconds per minute |
@c Standard only allows data space to be assigned for a @code{CREATE}d |
| LITERAL * ; \ to seconds |
@c word. In addition, the Standard only allows @code{@@} to access data |
| @end example |
@c space, whilst this example is using it to access code space. The only |
| |
@c portable, Standard way to build this table is to build it in data space, |
| |
@c like this: |
| |
|
| |
@c @example |
| |
@c create table ' aa , ' bb , ' cc , |
| |
@c @end example |
| |
|
| doc-literal |
@c doc-state |
| doc-]L |
|
| doc-2literal |
|
| doc-fliteral |
|
| |
|
| |
|
| @node Interpreter Directives, , Literals, The Text Interpreter |
@node Interpreter Directives, , Interpret/Compile states, The Text Interpreter |
| @subsection Interpreter Directives |
@subsection Interpreter Directives |
| @cindex interpreter directives |
@cindex interpreter directives |
| @cindex conditional compilation |
@cindex conditional compilation |
| |
|
| |
|
| @c ------------------------------------------------------------- |
@c ------------------------------------------------------------- |
| @node Word Lists, Environmental Queries, The Text Interpreter, Words |
@node The Input Stream, Word Lists, The Text Interpreter, Words |
| |
@section The Input Stream |
| |
@cindex input stream |
| |
|
| |
@c !! integrate this better with the "Text Interpreter" section |
| |
The text interpreter reads from the input stream, which can come from |
| |
several sources (@pxref{Input Sources}). Some words, in particular |
| |
defining words, but also words like @code{'}, read parameters from the |
| |
input stream instead of from the stack. |
| |
|
| |
Such words are called parsing words, because they parse the input |
| |
stream. Parsing words are hard to use in other words, because it is |
| |
hard to pass program-generated parameters through the input stream. |
| |
They also usually have an unintuitive combination of interpretation and |
| |
compilation semantics when implemented naively, leading to various |
| |
approaches that try to produce a more intuitive behaviour |
| |
(@pxref{Combined words}). |
| |
|
| |
It should be obvious by now that parsing words are a bad idea. If you |
| |
want to implement a parsing word for convenience, also provide a factor |
| |
of the word that does not parse, but takes the parameters on the stack. |
| |
To implement the parsing word on top if it, you can use the following |
| |
words: |
| |
|
| |
@c anton: these belong in the input stream section |
| |
doc-parse |
| |
doc-parse-name |
| |
doc-parse-word |
| |
doc-name |
| |
doc-word |
| |
doc-refill |
| |
|
| |
Conversely, if you have the bad luck (or lack of foresight) to have to |
| |
deal with parsing words without having such factors, how do you pass a |
| |
string that is not in the input stream to it? |
| |
|
| |
doc-execute-parsing |
| |
|
| |
A definition of this word in ANS Forth is provided in |
| |
@file{compat/execute-parsing.fs}. |
| |
|
| |
If you want to run a parsing word on a file, the following word should |
| |
help: |
| |
|
| |
doc-execute-parsing-file |
| |
|
| |
@c ------------------------------------------------------------- |
| |
@node Word Lists, Environmental Queries, The Input Stream, Words |
| @section Word Lists |
@section Word Lists |
| @cindex word lists |
@cindex word lists |
| @cindex header space |
@cindex header space |
| doc-get-current |
doc-get-current |
| doc-set-current |
doc-set-current |
| doc-get-order |
doc-get-order |
| doc---gforthman-set-order |
doc-set-order |
| doc-wordlist |
doc-wordlist |
| doc-table |
doc-table |
| doc-push-order |
doc->order |
| doc-previous |
doc-previous |
| doc-also |
doc-also |
| doc---gforthman-forth |
doc-forth |
| doc-only |
doc-only |
| doc---gforthman-order |
doc-order |
| |
|
| doc-find |
doc-find |
| doc-search-wordlist |
doc-search-wordlist |
| s" 0.5.0" compare 0< [IF] \ v* is a primitive since 0.5.0 |
s" 0.5.0" compare 0< [IF] \ v* is a primitive since 0.5.0 |
| : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r ) |
: v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r ) |
| >r swap 2swap swap 0e r> 0 ?DO |
>r swap 2swap swap 0e r> 0 ?DO |
| dup f@ over + 2swap dup f@ f* f+ over + 2swap |
dup f@@ over + 2swap dup f@@ f* f+ over + 2swap |
| LOOP |
LOOP |
| 2drop 2drop ; |
2drop 2drop ; |
| [THEN] |
[THEN] |
| You can see what definitions are in the environment word list like this: |
You can see what definitions are in the environment word list like this: |
| |
|
| @example |
@example |
| environment-wordlist push-order words previous |
environment-wordlist >order words previous |
| @end example |
@end example |
| |
|
| |
|
| @menu |
@menu |
| * Forth source files:: |
* Forth source files:: |
| * General files:: |
* General files:: |
| |
* Redirection:: |
| * Search Paths:: |
* Search Paths:: |
| @end menu |
@end menu |
| |
|
| doc-require |
doc-require |
| doc-needs |
doc-needs |
| @c doc-init-included-files @c internal |
@c doc-init-included-files @c internal |
| @c doc-loadfilename @c internal word |
|
| doc-sourcefilename |
doc-sourcefilename |
| doc-sourceline# |
doc-sourceline# |
| |
|
| @file{compat/required.fs}. |
@file{compat/required.fs}. |
| |
|
| @c ------------------------------------------------------------- |
@c ------------------------------------------------------------- |
| @node General files, Search Paths, Forth source files, Files |
@node General files, Redirection, Forth source files, Files |
| @subsection General files |
@subsection General files |
| @cindex general files |
@cindex general files |
| @cindex file-handling |
@cindex file-handling |
| doc-rename-file |
doc-rename-file |
| doc-read-file |
doc-read-file |
| doc-read-line |
doc-read-line |
| |
doc-key-file |
| |
doc-key?-file |
| doc-write-file |
doc-write-file |
| doc-write-line |
doc-write-line |
| doc-emit-file |
doc-emit-file |
| doc-file-size |
doc-file-size |
| doc-resize-file |
doc-resize-file |
| |
|
| |
doc-slurp-file |
| |
doc-slurp-fid |
| |
doc-stdin |
| |
doc-stdout |
| |
doc-stderr |
| |
|
| @c --------------------------------------------------------- |
@c --------------------------------------------------------- |
| @node Search Paths, , General files, Files |
@node Redirection, Search Paths, General files, Files |
| |
@subsection Redirection |
| |
@cindex Redirection |
| |
@cindex Input Redirection |
| |
@cindex Output Redirection |
| |
|
| |
You can redirect the output of @code{type} and @code{emit} and all the |
| |
words that use them (all output words that don't have an explicit |
| |
target file) to an arbitrary file with the @code{outfile-execute}, |
| |
used like this: |
| |
|
| |
@example |
| |
: some-warning ( n -- ) |
| |
cr ." warning# " . ; |
| |
|
| |
: print-some-warning ( n -- ) |
| |
['] some-warning stderr outfile-execute ; |
| |
@end example |
| |
|
| |
After @code{some-warning} is executed, the original output direction |
| |
is restored; this construct is safe against exceptions. Similarly, |
| |
there is @code{infile-execute} for redirecting the input of @code{key} |
| |
and its users (any input word that does not take a file explicitly). |
| |
|
| |
doc-outfile-execute |
| |
doc-infile-execute |
| |
|
| |
If you do not want to redirect the input or output to a file, you can |
| |
also make use of the fact that @code{key}, @code{emit} and @code{type} |
| |
are deferred words (@pxref{Deferred Words}). However, in that case |
| |
you have to worry about the restoration and the protection against |
| |
exceptions yourself; also, note that for redirecting the output in |
| |
this way, you have to redirect both @code{emit} and @code{type}. |
| |
|
| |
@c --------------------------------------------------------- |
| |
@node Search Paths, , Redirection, Files |
| @subsection Search Paths |
@subsection Search Paths |
| @cindex path for @code{included} |
@cindex path for @code{included} |
| @cindex file search path |
@cindex file search path |
| doc-list |
doc-list |
| doc-scr |
doc-scr |
| |
|
| doc---gforthman-block |
doc-block |
| doc-buffer |
doc-buffer |
| |
|
| doc-empty-buffers |
doc-empty-buffers |
| |
|
| |
|
| @c ------------------------------------------------------------- |
@c ------------------------------------------------------------- |
| @node Other I/O, Locals, Blocks, Words |
@node Other I/O, OS command line arguments, Blocks, Words |
| @section Other I/O |
@section Other I/O |
| @cindex I/O - keyboard and display |
@cindex I/O - keyboard and display |
| |
|
| * Formatted numeric output:: Formatted (pictured) output |
* Formatted numeric output:: Formatted (pictured) output |
| * String Formats:: How Forth stores strings in memory |
* String Formats:: How Forth stores strings in memory |
| * Displaying characters and strings:: Other stuff |
* Displaying characters and strings:: Other stuff |
| * Input:: Input |
* Terminal output:: Cursor positioning etc. |
| |
* Single-key input:: |
| |
* Line input and conversion:: |
| |
* Pipes:: How to create your own pipes |
| |
* Xchars and Unicode:: Non-ASCII characters |
| @end menu |
@end menu |
| |
|
| @node Simple numeric output, Formatted numeric output, Other I/O, Other I/O |
@node Simple numeric output, Formatted numeric output, Other I/O, Other I/O |
| doc-f. |
doc-f. |
| doc-fe. |
doc-fe. |
| doc-fs. |
doc-fs. |
| |
doc-f.rdp |
| |
|
| Examples of printing the number 1234.5678E23 in the different floating-point output |
Examples of printing the number 1234.5678E23 in the different floating-point output |
| formats are shown below: |
formats are shown below: |
| doc-#>> |
doc-#>> |
| |
|
| doc-represent |
doc-represent |
| |
doc-f>str-rdp |
| |
doc-f>buf-rdp |
| |
|
| |
|
| @noindent |
@noindent |
| Blocks}. For words that display characters and strings see |
Blocks}. For words that display characters and strings see |
| @ref{Displaying characters and strings}. |
@ref{Displaying characters and strings}. |
| |
|
| @node Displaying characters and strings, Input, String Formats, Other I/O |
@node Displaying characters and strings, Terminal output, String Formats, Other I/O |
| @subsection Displaying characters and strings |
@subsection Displaying characters and strings |
| @cindex characters - compiling and displaying |
@cindex characters - compiling and displaying |
| @cindex character strings - compiling and displaying |
@cindex character strings - compiling and displaying |
| This section starts with a glossary of Forth words and ends with a set |
This section starts with a glossary of Forth words and ends with a set |
| of examples. |
of examples. |
| |
|
| |
|
| doc-bl |
doc-bl |
| doc-space |
doc-space |
| doc-spaces |
doc-spaces |
| doc-toupper |
doc-toupper |
| doc-." |
doc-." |
| doc-.( |
doc-.( |
| |
doc-.\" |
| doc-type |
doc-type |
| doc-typewhite |
doc-typewhite |
| doc-cr |
doc-cr |
| @cindex cursor control |
@cindex cursor control |
| doc-at-xy |
|
| doc-page |
|
| doc-s" |
doc-s" |
| |
doc-s\" |
| doc-c" |
doc-c" |
| doc-char |
doc-char |
| doc-[char] |
doc-[char] |
| doc-sliteral |
|
| |
|
| |
|
| @noindent |
@noindent |
| @end itemize |
@end itemize |
| |
|
| |
|
| |
@node Terminal output, Single-key input, Displaying characters and strings, Other I/O |
| |
@subsection Terminal output |
| |
@cindex output to terminal |
| |
@cindex terminal output |
| |
|
| |
If you are outputting to a terminal, you may want to control the |
| |
positioning of the cursor: |
| |
@cindex cursor positioning |
| |
|
| @node Input, , Displaying characters and strings, Other I/O |
doc-at-xy |
| @subsection Input |
|
| @cindex input |
|
| @cindex I/O - see input |
|
| @cindex parsing a string |
|
| |
|
| For ways of storing character strings in memory see @ref{String Formats}. |
In order to know where to position the cursor, it is often helpful to |
| |
know the size of the screen: |
| |
@cindex terminal size |
| |
|
| @comment TODO examples for >number >float accept key key? pad parse word refill |
doc-form |
| @comment then index them |
|
| |
And sometimes you want to use: |
| |
@cindex clear screen |
| |
|
| |
doc-page |
| |
|
| |
Note that on non-terminals you should use @code{12 emit}, not |
| |
@code{page}, to get a form feed. |
| |
|
| |
|
| |
@node Single-key input, Line input and conversion, Terminal output, Other I/O |
| |
@subsection Single-key input |
| |
@cindex single-key input |
| |
@cindex input, single-key |
| |
|
| |
If you want to get a single printable character, you can use |
| |
@code{key}; to check whether a character is available for @code{key}, |
| |
you can use @code{key?}. |
| |
|
| doc-key |
doc-key |
| doc-key? |
doc-key? |
| |
|
| |
If you want to process a mix of printable and non-printable |
| |
characters, you can do that with @code{ekey} and friends. @code{Ekey} |
| |
produces a keyboard event that you have to convert into a character |
| |
with @code{ekey>char} or into a key identifier with @code{ekey>fkey}. |
| |
|
| |
Typical code for using EKEY looks like this: |
| |
|
| |
@example |
| |
ekey ekey>char if ( c ) |
| |
... \ do something with the character |
| |
else ekey>fkey if ( key-id ) |
| |
case |
| |
k-up of ... endof |
| |
k-f1 of ... endof |
| |
k-left k-shift-mask or k-ctrl-mask or of ... endof |
| |
... |
| |
endcase |
| |
else ( keyboard-event ) |
| |
drop \ just ignore an unknown keyboard event type |
| |
then then |
| |
@end example |
| |
|
| doc-ekey |
doc-ekey |
| doc-ekey? |
|
| doc-ekey>char |
doc-ekey>char |
| |
doc-ekey>fkey |
| |
doc-ekey? |
| |
|
| |
The key identifiers for cursor keys are: |
| |
|
| |
doc-k-left |
| |
doc-k-right |
| |
doc-k-up |
| |
doc-k-down |
| |
doc-k-home |
| |
doc-k-end |
| |
doc-k-prior |
| |
doc-k-next |
| |
doc-k-insert |
| |
doc-k-delete |
| |
|
| |
The key identifiers for function keys (aka keypad keys) are: |
| |
|
| |
doc-k-f1 |
| |
doc-k-f2 |
| |
doc-k-f3 |
| |
doc-k-f4 |
| |
doc-k-f5 |
| |
doc-k-f6 |
| |
doc-k-f7 |
| |
doc-k-f8 |
| |
doc-k-f9 |
| |
doc-k-f10 |
| |
doc-k-f11 |
| |
doc-k-f12 |
| |
|
| |
Note that @code{k-f11} and @code{k-f12} are not as widely available. |
| |
|
| |
You can combine these key identifiers with masks for various shift keys: |
| |
|
| |
doc-k-shift-mask |
| |
doc-k-ctrl-mask |
| |
doc-k-alt-mask |
| |
|
| |
Note that, even if a Forth system has @code{ekey>fkey} and the key |
| |
identifier words, the keys are not necessarily available or it may not |
| |
necessarily be able to report all the keys and all the possible |
| |
combinations with shift masks. Therefore, write your programs in such |
| |
a way that they are still useful even if the keys and key combinations |
| |
cannot be pressed or are not recognized. |
| |
|
| |
Examples: Older keyboards often do not have an F11 and F12 key. If |
| |
you run Gforth in an xterm, the xterm catches a number of combinations |
| |
(e.g., @key{Shift-Up}), and never passes it to Gforth. Finally, |
| |
Gforth currently does not recognize and report combinations with |
| |
multiple shift keys (so the @key{shift-ctrl-left} case in the example |
| |
above would never be entered). |
| |
|
| |
Gforth recognizes various keys available on ANSI terminals (in MS-DOS |
| |
you need the ANSI.SYS driver to get that behaviour); it works by |
| |
recognizing the escape sequences that ANSI terminals send when such a |
| |
key is pressed. If you have a terminal that sends other escape |
| |
sequences, you will not get useful results on Gforth. Other Forth |
| |
systems may work in a different way. |
| |
|
| |
|
| |
@node Line input and conversion, Pipes, Single-key input, Other I/O |
| |
@subsection Line input and conversion |
| |
@cindex line input from terminal |
| |
@cindex input, linewise from terminal |
| |
@cindex convertin strings to numbers |
| |
@cindex I/O - see input |
| |
|
| |
For ways of storing character strings in memory see @ref{String Formats}. |
| |
|
| |
@comment TODO examples for >number >float accept key key? pad parse word refill |
| |
@comment then index them |
| |
|
| |
Words for inputting one line from the keyboard: |
| |
|
| |
doc-accept |
| |
doc-edit-line |
| |
|
| |
Conversion words: |
| |
|
| |
doc-s>number? |
| |
doc-s>unumber? |
| doc->number |
doc->number |
| doc->float |
doc->float |
| doc-accept |
|
| doc-pad |
|
| @c anton: these belong in the input stream section |
|
| doc-parse |
|
| doc-word |
|
| doc-sword |
|
| doc-name |
|
| doc-refill |
|
| @comment obsolescent words.. |
@comment obsolescent words.. |
| |
Obsolescent input and conversion words: |
| |
|
| doc-convert |
doc-convert |
| doc-query |
|
| doc-expect |
doc-expect |
| doc-span |
doc-span |
| |
|
| |
|
| |
@node Pipes, Xchars and Unicode, Line input and conversion, Other I/O |
| |
@subsection Pipes |
| |
@cindex pipes, creating your own |
| |
|
| |
In addition to using Gforth in pipes created by other processes |
| |
(@pxref{Gforth in pipes}), you can create your own pipe with |
| |
@code{open-pipe}, and read from or write to it. |
| |
|
| |
doc-open-pipe |
| |
doc-close-pipe |
| |
|
| |
If you write to a pipe, Gforth can throw a @code{broken-pipe-error}; if |
| |
you don't catch this exception, Gforth will catch it and exit, usually |
| |
silently (@pxref{Gforth in pipes}). Since you probably do not want |
| |
this, you should wrap a @code{catch} or @code{try} block around the code |
| |
from @code{open-pipe} to @code{close-pipe}, so you can deal with the |
| |
problem yourself, and then return to regular processing. |
| |
|
| |
doc-broken-pipe-error |
| |
|
| |
@node Xchars and Unicode, , Pipes, Other I/O |
| |
@subsection Xchars and Unicode |
| |
|
| |
ASCII is only appropriate for the English language. Most western |
| |
languages however fit somewhat into the Forth frame, since a byte is |
| |
sufficient to encode the few special characters in each (though not |
| |
always the same encoding can be used; latin-1 is most widely used, |
| |
though). For other languages, different char-sets have to be used, |
| |
several of them variable-width. Most prominent representant is |
| |
UTF-8. Let's call these extended characters xchars. The primitive |
| |
fixed-size characters stored as bytes are called pchars in this |
| |
section. |
| |
|
| |
The xchar words add a few data types: |
| |
|
| |
@itemize |
| |
|
| |
@item |
| |
@var{xc} is an extended char (xchar) on the stack. It occupies one cell, |
| |
and is a subset of unsigned cell. Note: UTF-8 can not store more that |
| |
31 bits; on 16 bit systems, only the UCS16 subset of the UTF-8 |
| |
character set can be used. |
| |
|
| |
@item |
| |
@var{xc-addr} is the address of an xchar in memory. Alignment |
| |
requirements are the same as @var{c-addr}. The memory representation of an |
| |
xchar differs from the stack representation, and depends on the |
| |
encoding used. An xchar may use a variable number of pchars in memory. |
| |
|
| |
@item |
| |
@var{xc-addr} @var{u} is a buffer of xchars in memory, starting at |
| |
@var{xc-addr}, @var{u} pchars long. |
| |
|
| |
@end itemize |
| |
|
| |
doc-xc-size |
| |
doc-x-size |
| |
doc-xc@+ |
| |
doc-xc!+ |
| |
doc-xc!+? |
| |
doc-xchar+ |
| |
doc-xchar- |
| |
doc-+x/string |
| |
doc-x\string- |
| |
doc--trailing-garbage |
| |
doc-x-width |
| |
doc-xkey |
| |
doc-xemit |
| |
|
| |
There's a new environment query |
| |
|
| |
doc-xchar-encoding |
| |
|
| |
@node OS command line arguments, Locals, Other I/O, Words |
| |
@section OS command line arguments |
| |
@cindex OS command line arguments |
| |
@cindex command line arguments, OS |
| |
@cindex arguments, OS command line |
| |
|
| |
The usual way to pass arguments to Gforth programs on the command line |
| |
is via the @option{-e} option, e.g. |
| |
|
| |
@example |
| |
gforth -e "123 456" foo.fs -e bye |
| |
@end example |
| |
|
| |
However, you may want to interpret the command-line arguments directly. |
| |
In that case, you can access the (image-specific) command-line arguments |
| |
through @code{next-arg}: |
| |
|
| |
doc-next-arg |
| |
|
| |
Here's an example program @file{echo.fs} for @code{next-arg}: |
| |
|
| |
@example |
| |
: echo ( -- ) |
| |
begin |
| |
next-arg 2dup 0 0 d<> while |
| |
type space |
| |
repeat |
| |
2drop ; |
| |
|
| |
echo cr bye |
| |
@end example |
| |
|
| |
This can be invoked with |
| |
|
| |
@example |
| |
gforth echo.fs hello world |
| |
@end example |
| |
|
| |
and it will print |
| |
|
| |
@example |
| |
hello world |
| |
@end example |
| |
|
| |
The next lower level of dealing with the OS command line are the |
| |
following words: |
| |
|
| |
doc-arg |
| |
doc-shift-args |
| |
|
| |
Finally, at the lowest level Gforth provides the following words: |
| |
|
| |
doc-argc |
| |
doc-argv |
| |
|
| @c ------------------------------------------------------------- |
@c ------------------------------------------------------------- |
| @node Locals, Structures, Other I/O, Words |
@node Locals, Structures, OS command line arguments, Words |
| @section Locals |
@section Locals |
| @cindex locals |
@cindex locals |
| |
|
| appropriate: |
appropriate: |
| |
|
| |
|
| doc-compile-@local |
@c doc-compile-@local |
| doc-compile-f@local |
@c doc-compile-f@local |
| doc-compile-lp+! |
doc-compile-lp+! |
| |
|
| |
|
| * Structure Naming Convention:: |
* Structure Naming Convention:: |
| * Structure Implementation:: |
* Structure Implementation:: |
| * Structure Glossary:: |
* Structure Glossary:: |
| |
* Forth200x Structures:: |
| @end menu |
@end menu |
| |
|
| @node Why explicit structure support?, Structure Usage, Structures, Structures |
@node Why explicit structure support?, Structure Usage, Structures, Structures |
| offset. For a zero offset, the field is basically a noop; it is |
offset. For a zero offset, the field is basically a noop; it is |
| immediate, and therefore no code is generated when it is compiled. |
immediate, and therefore no code is generated when it is compiled. |
| |
|
| @node Structure Glossary, , Structure Implementation, Structures |
@node Structure Glossary, Forth200x Structures, Structure Implementation, Structures |
| @subsection Structure Glossary |
@subsection Structure Glossary |
| @cindex structure glossary |
@cindex structure glossary |
| |
|
| doc-struct |
doc-struct |
| |
|
| |
|
| |
@node Forth200x Structures, , Structure Glossary, Structures |
| |
@subsection Forth200x Structures |
| |
@cindex Structures in Forth200x |
| |
|
| |
The Forth 200x standard defines a slightly less convenient form of |
| |
structures. In general (when using @code{field+}, you have to perform |
| |
the alignment yourself, but there are a number of convenience words |
| |
(e.g., @code{field:} that perform the alignment for you. |
| |
|
| |
A typical usage example is: |
| |
|
| |
@example |
| |
0 |
| |
field: s-a |
| |
faligned 2 floats +field s-b |
| |
constant s-struct |
| |
@end example |
| |
|
| |
An alternative way of writing this structure is: |
| |
|
| |
@example |
| |
begin-structure s-struct |
| |
field: s-a |
| |
faligned 2 floats +field s-b |
| |
end-structure |
| |
@end example |
| |
|
| |
doc-begin-structure |
| |
doc-end-structure |
| |
doc-+field |
| |
doc-cfield: |
| |
doc-field: |
| |
doc-2field: |
| |
doc-ffield: |
| |
doc-sffield: |
| |
doc-dffield: |
| |
|
| @c ------------------------------------------------------------- |
@c ------------------------------------------------------------- |
| @node Object-oriented Forth, Programming Tools, Structures, Words |
@node Object-oriented Forth, Programming Tools, Structures, Words |
| @section Object-oriented Forth |
@section Object-oriented Forth |
| doc---objects-class->map |
doc---objects-class->map |
| doc---objects-class-inst-size |
doc---objects-class-inst-size |
| doc---objects-class-override! |
doc---objects-class-override! |
| |
doc---objects-class-previous |
| |
doc---objects-class>order |
| doc---objects-construct |
doc---objects-construct |
| doc---objects-current' |
doc---objects-current' |
| doc---objects-[current] |
doc---objects-[current] |
| doc---objects-current-interface |
doc---objects-current-interface |
| doc---objects-dict-new |
doc---objects-dict-new |
| doc---objects-drop-order |
|
| doc---objects-end-class |
doc---objects-end-class |
| doc---objects-end-class-noname |
doc---objects-end-class-noname |
| doc---objects-end-interface |
doc---objects-end-interface |
| doc---objects-print |
doc---objects-print |
| doc---objects-protected |
doc---objects-protected |
| doc---objects-public |
doc---objects-public |
| @c !! push-order conflicts |
|
| doc---objects-push-order |
|
| doc---objects-selector |
doc---objects-selector |
| doc---objects-this |
doc---objects-this |
| doc---objects-<to-inst> |
doc---objects-<to-inst> |
| @cindex @code{method} usage |
@cindex @code{method} usage |
| @example |
@example |
| object class graphical \ "object" is the parent class |
object class graphical \ "object" is the parent class |
| method draw ( x y graphical -- ) |
method draw ( x y -- ) |
| class; |
class; |
| @end example |
@end example |
| |
|
| : draw ( x y -- ) |
: draw ( x y -- ) |
| circle-radius @@ draw-circle ; |
circle-radius @@ draw-circle ; |
| |
|
| : init ( n-radius -- ( |
: init ( n-radius -- ) |
| circle-radius ! ; |
circle-radius ! ; |
| class; |
class; |
| @end example |
@end example |
| @cindex mini-oof |
@cindex mini-oof |
| |
|
| Gforth's third object oriented Forth package is a 12-liner. It uses a |
Gforth's third object oriented Forth package is a 12-liner. It uses a |
| mixture of the @file{object.fs} and the @file{oof.fs} syntax, |
mixture of the @file{objects.fs} and the @file{oof.fs} syntax, |
| and reduces to the bare minimum of features. This is based on a posting |
and reduces to the bare minimum of features. This is based on a posting |
| of Bernd Paysan in comp.lang.forth. |
of Bernd Paysan in comp.lang.forth. |
| |
|
| table, which contains the methods as function pointers. The vtable |
table, which contains the methods as function pointers. The vtable |
| may also contain other information. |
may also contain other information. |
| |
|
| So first, let's declare methods: |
So first, let's declare selectors: |
| |
|
| @example |
@example |
| : method ( m v -- m' v ) Create over , swap cell+ swap |
: method ( m v "name" -- m' v ) Create over , swap cell+ swap |
| DOES> ( ... o -- ... ) @@ over @@ + @@ execute ; |
DOES> ( ... o -- ... ) @@ over @@ + @@ execute ; |
| @end example |
@end example |
| |
|
| During method declaration, the number of methods and instance |
During selector declaration, the number of selectors and instance |
| variables is on the stack (in address units). @code{method} creates |
variables is on the stack (in address units). @code{method} creates one |
| one method and increments the method number. To execute a method, it |
selector and increments the selector number. To execute a selector, it |
| takes the object, fetches the vtable pointer, adds the offset, and |
takes the object, fetches the vtable pointer, adds the offset, and |
| executes the @i{xt} stored there. Each method takes the object it is |
executes the method @i{xt} stored there. Each selector takes the object |
| invoked from as top of stack parameter. The method itself should |
it is invoked with as top of stack parameter; it passes the parameters |
| |
(including the object) unchanged to the appropriate method which should |
| consume that object. |
consume that object. |
| |
|
| Now, we also have to declare instance variables |
Now, we also have to declare instance variables |
| |
|
| @example |
@example |
| : var ( m v size -- m v' ) Create over , + |
: var ( m v size "name" -- m v' ) Create over , + |
| DOES> ( o -- addr ) @@ + ; |
DOES> ( o -- addr ) @@ + ; |
| @end example |
@end example |
| |
|
| |
|
| @example |
@example |
| Create object 1 cells , 2 cells , |
Create object 1 cells , 2 cells , |
| : class ( class -- class methods vars ) dup 2@@ ; |
: class ( class -- class selectors vars ) dup 2@@ ; |
| @end example |
@end example |
| |
|
| For inheritance, the vtable of the parent object has to be |
For inheritance, the vtable of the parent object has to be |
| methods of the parent class, which can be overridden, though. |
methods of the parent class, which can be overridden, though. |
| |
|
| @example |
@example |
| : end-class ( class methods vars -- ) |
: end-class ( class selectors vars "name" -- ) |
| Create here >r , dup , 2 cells ?DO ['] noop , 1 cells +LOOP |
Create here >r , dup , 2 cells ?DO ['] noop , 1 cells +LOOP |
| cell+ dup cell+ r> rot @@ 2 cells /string move ; |
cell+ dup cell+ r> rot @@ 2 cells /string move ; |
| @end example |
@end example |
| We still have no way to define new methods, let's do that now: |
We still have no way to define new methods, let's do that now: |
| |
|
| @example |
@example |
| : defines ( xt class -- ) ' >body @@ + ! ; |
: defines ( xt class "name" -- ) ' >body @@ + ! ; |
| @end example |
@end example |
| |
|
| To allocate a new object, we need a word, too: |
To allocate a new object, we need a word, too: |
| |
|
| @noindent |
@noindent |
| To demonstrate inheritance, we define a class @code{bold-button}, with no |
To demonstrate inheritance, we define a class @code{bold-button}, with no |
| new data and no new methods: |
new data and no new selectors: |
| |
|
| @example |
@example |
| button class |
button class |
| @end example |
@end example |
| |
|
| @noindent |
@noindent |
| Finally, create two objects and apply methods: |
Finally, create two objects and apply selectors: |
| |
|
| @example |
@example |
| button new Constant foo |
button new Constant foo |
| |
|
| @item |
@item |
| It requires that the selector parses the input stream (at |
It requires that the selector parses the input stream (at |
| compile time); this leads to reduced extensibility and to bugs that are+ |
compile time); this leads to reduced extensibility and to bugs that are |
| hard to find. |
hard to find. |
| |
|
| @item |
@item |
| It allows using every selector to every object; |
It allows using every selector on every object; this eliminates the |
| this eliminates the need for classes, but makes it harder to create |
need for interfaces, but makes it harder to create efficient |
| efficient implementations. |
implementations. |
| @end itemize |
@end itemize |
| |
|
| @cindex Pountain's object-oriented model |
@cindex Pountain's object-oriented model |
| overloading that are characteristic of modular languages like Ada (83). |
overloading that are characteristic of modular languages like Ada (83). |
| |
|
| @cindex Zsoter's object-oriented model |
@cindex Zsoter's object-oriented model |
| In @cite{Does late binding have to be slow?} (Forth Dimensions 18(1) |
In @uref{http://www.forth.org/oopf.html, Does late binding have to be |
| 1996, pages 31-35) Andras Zsoter describes a model that makes heavy use |
slow?} (Forth Dimensions 18(1) 1996, pages 31-35) Andras Zsoter |
| of an active object (like @code{this} in @file{objects.fs}): The active |
describes a model that makes heavy use of an active object (like |
| object is not only used for accessing all fields, but also specifies the |
@code{this} in @file{objects.fs}): The active object is not only used |
| receiving object of every selector invocation; you have to change the |
for accessing all fields, but also specifies the receiving object of |
| active object explicitly with @code{@{ ... @}}, whereas in |
every selector invocation; you have to change the active object |
| @file{objects.fs} it changes more or less implicitly at @code{m: |
explicitly with @code{@{ ... @}}, whereas in @file{objects.fs} it |
| ... ;m}. Such a change at the method entry point is unnecessary with the |
changes more or less implicitly at @code{m: ... ;m}. Such a change at |
| Zsoter's model, because the receiving object is the active object |
the method entry point is unnecessary with Zsoter's model, because the |
| already. On the other hand, the explicit change is absolutely necessary |
receiving object is the active object already. On the other hand, the |
| in that model, because otherwise no one could ever change the active |
explicit change is absolutely necessary in that model, because otherwise |
| object. An ANS Forth implementation of this model is available at |
no one could ever change the active object. An ANS Forth implementation |
| @uref{http://www.forth.org/fig/oopf.html}. |
of this model is available through |
| |
@uref{http://www.forth.org/oopf.html}. |
| |
|
| @cindex @file{oof.fs}, differences to other models |
@cindex @file{oof.fs}, differences to other models |
| The @file{oof.fs} model combines information hiding and overloading |
The @file{oof.fs} model combines information hiding and overloading |
| |
|
| |
|
| @c ------------------------------------------------------------- |
@c ------------------------------------------------------------- |
| @node Programming Tools, Assembler and Code Words, Object-oriented Forth, Words |
@node Programming Tools, C Interface, Object-oriented Forth, Words |
| @section Programming Tools |
@section Programming Tools |
| @cindex programming tools |
@cindex programming tools |
| |
|
| @c !! move this and assembler down below OO stuff. |
@c !! move this and assembler down below OO stuff. |
| |
|
| @menu |
@menu |
| * Examining:: |
* Examining:: Data and Code. |
| * Forgetting words:: |
* Forgetting words:: Usually before reloading. |
| * Debugging:: Simple and quick. |
* Debugging:: Simple and quick. |
| * Assertions:: Making your programs self-checking. |
* Assertions:: Making your programs self-checking. |
| * Singlestep Debugger:: Executing your program word by word. |
* Singlestep Debugger:: Executing your program word by word. |
| |
|
| doc-.s |
doc-.s |
| doc-f.s |
doc-f.s |
| |
doc-maxdepth-.s |
| |
|
| There is a word @code{.r} but it does @i{not} display the return stack! |
There is a word @code{.r} but it does @i{not} display the return stack! |
| It is used for formatted numeric output (@pxref{Simple numeric output}). |
It is used for formatted numeric output (@pxref{Simple numeric output}). |
| doc-depth |
doc-depth |
| doc-fdepth |
doc-fdepth |
| doc-clearstack |
doc-clearstack |
| |
doc-clearstacks |
| |
|
| The following words inspect memory. |
The following words inspect memory. |
| |
|
| |
|
| doc-see |
doc-see |
| doc-xt-see |
doc-xt-see |
| |
doc-simple-see |
| |
doc-simple-see-range |
| |
doc-see-code |
| |
doc-see-code-range |
| |
|
| @node Forgetting words, Debugging, Examining, Programming Tools |
@node Forgetting words, Debugging, Examining, Programming Tools |
| @subsection Forgetting words |
@subsection Forgetting words |
| location and the stack contents). It is easy to insert. If you use Emacs |
location and the stack contents). It is easy to insert. If you use Emacs |
| it is also easy to remove (@kbd{C-x ~} in the Emacs Forth mode to |
it is also easy to remove (@kbd{C-x ~} in the Emacs Forth mode to |
| query-replace them with nothing). The deferred words |
query-replace them with nothing). The deferred words |
| @code{printdebugdata} and @code{printdebugline} control the output of |
@code{printdebugdata} and @code{.debugline} control the output of |
| @code{~~}. The default source location output format works well with |
@code{~~}. The default source location output format works well with |
| Emacs' compilation mode, so you can step through the program at the |
Emacs' compilation mode, so you can step through the program at the |
| source level using @kbd{C-x `} (the advantage over a stepping debugger |
source level using @kbd{C-x `} (the advantage over a stepping debugger |
| |
|
| doc-~~ |
doc-~~ |
| doc-printdebugdata |
doc-printdebugdata |
| doc-printdebugline |
doc-.debugline |
| |
|
| |
@cindex filenames in @code{~~} output |
| |
@code{~~} (and assertions) will usually print the wrong file name if a |
| |
marker is executed in the same file after their occurance. They will |
| |
print @samp{*somewhere*} as file name if a marker is executed in the |
| |
same file before their occurance. |
| |
|
| |
|
| @node Assertions, Singlestep Debugger, Debugging, Programming Tools |
@node Assertions, Singlestep Debugger, Debugging, Programming Tools |
| @subsection Assertions |
@subsection Assertions |
| newly-written code at level 3). |
newly-written code at level 3). |
| |
|
| |
|
| doc-assert-level |
doc-assert-level |
| |
|
| |
|
| |
If an assertion fails, a message compatible with Emacs' compilation mode |
| |
is produced and the execution is aborted (currently with @code{ABORT"}. |
| |
If there is interest, we will introduce a special throw code. But if you |
| |
intend to @code{catch} a specific condition, using @code{throw} is |
| |
probably more appropriate than an assertion). |
| |
|
| |
@cindex filenames in assertion output |
| |
Assertions (and @code{~~}) will usually print the wrong file name if a |
| |
marker is executed in the same file after their occurance. They will |
| |
print @samp{*somewhere*} as file name if a marker is executed in the |
| |
same file before their occurance. |
| |
|
| |
Definitions in ANS Forth for these assertion words are provided |
| |
in @file{compat/assert.fs}. |
| |
|
| |
|
| |
@node Singlestep Debugger, , Assertions, Programming Tools |
| |
@subsection Singlestep Debugger |
| |
@cindex singlestep Debugger |
| |
@cindex debugging Singlestep |
| |
|
| |
The singlestep debugger works only with the engine @code{gforth-itc}. |
| |
|
| |
When you create a new word there's often the need to check whether it |
| |
behaves correctly or not. You can do this by typing @code{dbg |
| |
badword}. A debug session might look like this: |
| |
|
| |
@example |
| |
: badword 0 DO i . LOOP ; ok |
| |
2 dbg badword |
| |
: badword |
| |
Scanning code... |
| |
|
| |
Nesting debugger ready! |
| |
|
| |
400D4738 8049BC4 0 -> [ 2 ] 00002 00000 |
| |
400D4740 8049F68 DO -> [ 0 ] |
| |
400D4744 804A0C8 i -> [ 1 ] 00000 |
| |
400D4748 400C5E60 . -> 0 [ 0 ] |
| |
400D474C 8049D0C LOOP -> [ 0 ] |
| |
400D4744 804A0C8 i -> [ 1 ] 00001 |
| |
400D4748 400C5E60 . -> 1 [ 0 ] |
| |
400D474C 8049D0C LOOP -> [ 0 ] |
| |
400D4758 804B384 ; -> ok |
| |
@end example |
| |
|
| |
Each line displayed is one step. You always have to hit return to |
| |
execute the next word that is displayed. If you don't want to execute |
| |
the next word in a whole, you have to type @kbd{n} for @code{nest}. Here is |
| |
an overview what keys are available: |
| |
|
| |
@table @i |
| |
|
| |
@item @key{RET} |
| |
Next; Execute the next word. |
| |
|
| |
@item n |
| |
Nest; Single step through next word. |
| |
|
| |
@item u |
| |
Unnest; Stop debugging and execute rest of word. If we got to this word |
| |
with nest, continue debugging with the calling word. |
| |
|
| |
@item d |
| |
Done; Stop debugging and execute rest. |
| |
|
| |
@item s |
| |
Stop; Abort immediately. |
| |
|
| |
@end table |
| |
|
| |
Debugging large application with this mechanism is very difficult, because |
| |
you have to nest very deeply into the program before the interesting part |
| |
begins. This takes a lot of time. |
| |
|
| |
To do it more directly put a @code{BREAK:} command into your source code. |
| |
When program execution reaches @code{BREAK:} the single step debugger is |
| |
invoked and you have all the features described above. |
| |
|
| |
If you have more than one part to debug it is useful to know where the |
| |
program has stopped at the moment. You can do this by the |
| |
@code{BREAK" string"} command. This behaves like @code{BREAK:} except that |
| |
string is typed out when the ``breakpoint'' is reached. |
| |
|
| |
|
| |
doc-dbg |
| |
doc-break: |
| |
doc-break" |
| |
|
| |
@c ------------------------------------------------------------ |
| |
@node C Interface, Assembler and Code Words, Programming Tools, Words |
| |
@section C Interface |
| |
@cindex C interface |
| |
@cindex foreign language interface |
| |
@cindex interface to C functions |
| |
|
| |
Note that the C interface is not yet complete; callbacks are missing, |
| |
as well as a way of declaring structs, unions, and their fields. |
| |
|
| |
@menu |
| |
* Calling C Functions:: |
| |
* Declaring C Functions:: |
| |
* Calling C function pointers:: |
| |
* Declaring libraries:: |
| |
* Callbacks:: |
| |
* C interface internals:: |
| |
* Low-Level C Interface Words:: |
| |
@end menu |
| |
|
| |
@node Calling C Functions, Declaring C Functions, C Interface, C Interface |
| |
@subsection Calling C functions |
| |
@cindex C functions, calls to |
| |
@cindex calling C functions |
| |
|
| |
Once a C function is declared (see @pxref{Declaring C Functions}), you |
| |
can call it as follows: You push the arguments on the stack(s), and |
| |
then call the word for the C function. The arguments have to be |
| |
pushed in the same order as the arguments appear in the C |
| |
documentation (i.e., the first argument is deepest on the stack). |
| |
Integer and pointer arguments have to be pushed on the data stack, |
| |
floating-point arguments on the FP stack; these arguments are consumed |
| |
by the called C function. |
| |
|
| |
On returning from the C function, the return value, if any, resides on |
| |
the appropriate stack: an integer return value is pushed on the data |
| |
stack, an FP return value on the FP stack, and a void return value |
| |
results in not pushing anything. Note that most C functions have a |
| |
return value, even if that is often not used in C; in Forth, you have |
| |
to @code{drop} this return value explicitly if you do not use it. |
| |
|
| |
The C interface automatically converts between the C type and the |
| |
Forth type as necessary, on a best-effort basis (in some cases, there |
| |
may be some loss). |
| |
|
| |
As an example, consider the POSIX function @code{lseek()}: |
| |
|
| |
@example |
| |
off_t lseek(int fd, off_t offset, int whence); |
| |
@end example |
| |
|
| |
This function takes three integer arguments, and returns an integer |
| |
argument, so a Forth call for setting the current file offset to the |
| |
start of the file could look like this: |
| |
|
| |
@example |
| |
fd @@ 0 SEEK_SET lseek -1 = if |
| |
... \ error handling |
| |
then |
| |
@end example |
| |
|
| |
You might be worried that an @code{off_t} does not fit into a cell, so |
| |
you could not pass larger offsets to lseek, and might get only a part |
| |
of the return values. In that case, in your declaration of the |
| |
function (@pxref{Declaring C Functions}) you should declare it to use |
| |
double-cells for the off_t argument and return value, and maybe give |
| |
the resulting Forth word a different name, like @code{dlseek}; the |
| |
result could be called like this: |
| |
|
| |
@example |
| |
fd @@ 0. SEEK_SET dlseek -1. d= if |
| |
... \ error handling |
| |
then |
| |
@end example |
| |
|
| |
Passing and returning structs or unions is currently not supported by |
| |
our interface@footnote{If you know the calling convention of your C |
| |
compiler, you usually can call such functions in some way, but that |
| |
way is usually not portable between platforms, and sometimes not even |
| |
between C compilers.}. |
| |
|
| |
Calling functions with a variable number of arguments (@emph{variadic} |
| |
functions, e.g., @code{printf()}) is only supported by having you |
| |
declare one function-calling word for each argument pattern, and |
| |
calling the appropriate word for the desired pattern. |
| |
|
| |
|
| |
|
| |
@node Declaring C Functions, Calling C function pointers, Calling C Functions, C Interface |
| |
@subsection Declaring C Functions |
| |
@cindex C functions, declarations |
| |
@cindex declaring C functions |
| |
|
| |
Before you can call @code{lseek} or @code{dlseek}, you have to declare |
| |
it. The declaration consists of two parts: |
| |
|
| |
@table @b |
| |
|
| |
@item The C part |
| |
is the C declaration of the function, or more typically and portably, |
| |
a C-style @code{#include} of a file that contains the declaration of |
| |
the C function. |
| |
|
| |
@item The Forth part |
| |
declares the Forth types of the parameters and the Forth word name |
| |
corresponding to the C function. |
| |
|
| |
@end table |
| |
|
| |
For the words @code{lseek} and @code{dlseek} mentioned earlier, the |
| |
declarations are: |
| |
|
| |
@example |
| |
\c #define _FILE_OFFSET_BITS 64 |
| |
\c #include <sys/types.h> |
| |
\c #include <unistd.h> |
| |
c-function lseek lseek n n n -- n |
| |
c-function dlseek lseek n d n -- d |
| |
@end example |
| |
|
| |
The C part of the declarations is prefixed by @code{\c}, and the rest |
| |
of the line is ordinary C code. You can use as many lines of C |
| |
declarations as you like, and they are visible for all further |
| |
function declarations. |
| |
|
| |
The Forth part declares each interface word with @code{c-function}, |
| |
followed by the Forth name of the word, the C name of the called |
| |
function, and the stack effect of the word. The stack effect contains |
| |
an arbitrary number of types of parameters, then @code{--}, and then |
| |
exactly one type for the return value. The possible types are: |
| |
|
| |
@table @code |
| |
|
| |
@item n |
| |
single-cell integer |
| |
|
| |
@item a |
| |
address (single-cell) |
| |
|
| |
@item d |
| |
double-cell integer |
| |
|
| |
@item r |
| |
floating-point value |
| |
|
| |
@item func |
| |
C function pointer |
| |
|
| |
@item void |
| |
no value (used as return type for void functions) |
| |
|
| |
@end table |
| |
|
| |
@cindex variadic C functions |
| |
|
| |
To deal with variadic C functions, you can declare one Forth word for |
| |
every pattern you want to use, e.g.: |
| |
|
| |
@example |
| |
\c #include <stdio.h> |
| |
c-function printf-nr printf a n r -- n |
| |
c-function printf-rn printf a r n -- n |
| |
@end example |
| |
|
| |
Note that with C functions declared as variadic (or if you don't |
| |
provide a prototype), the C interface has no C type to convert to, so |
| |
no automatic conversion happens, which may lead to portability |
| |
problems in some cases. In such cases you can perform the conversion |
| |
explicitly on the C level, e.g., as follows: |
| |
|
| If an assertion fails, a message compatible with Emacs' compilation mode |
@example |
| is produced and the execution is aborted (currently with @code{ABORT"}. |
\c #define printfll(s,ll) printf(s,(long long)ll) |
| If there is interest, we will introduce a special throw code. But if you |
c-function printfll printfll a n -- n |
| intend to @code{catch} a specific condition, using @code{throw} is |
@end example |
| probably more appropriate than an assertion). |
|
| |
|
| Definitions in ANS Forth for these assertion words are provided |
Here, instead of calling @code{printf()} directly, we define a macro |
| in @file{compat/assert.fs}. |
that casts (converts) the Forth single-cell integer into a |
| |
C @code{long long} before calling @code{printf()}. |
| |
|
| |
doc-\c |
| |
doc-c-function |
| |
|
| @node Singlestep Debugger, , Assertions, Programming Tools |
In order to work, this C interface invokes GCC at run-time and uses |
| @subsection Singlestep Debugger |
dynamic linking. If these features are not available, there are |
| @cindex singlestep Debugger |
other, less convenient and less portable C interfaces in @file{lib.fs} |
| @cindex debugging Singlestep |
and @file{oldlib.fs}. These interfaces are mostly undocumented and |
| |
mostly incompatible with each other and with the documented C |
| |
interface; you can find some examples for the @file{lib.fs} interface |
| |
in @file{lib.fs}. |
| |
|
| When you create a new word there's often the need to check whether it |
|
| behaves correctly or not. You can do this by typing @code{dbg |
@node Calling C function pointers, Declaring libraries, Declaring C Functions, C Interface |
| badword}. A debug session might look like this: |
@subsection Calling C function pointers from Forth |
| |
@cindex C function pointers, calling from Forth |
| |
|
| |
If you come across a C function pointer (e.g., in some C-constructed |
| |
structure) and want to call it from your Forth program, you can also |
| |
use the features explained until now to achieve that, as follows: |
| |
|
| |
Let us assume that there is a C function pointer type @code{func1} |
| |
defined in some header file @file{func1.h}, and you know that these |
| |
functions take one integer argument and return an integer result; and |
| |
you want to call functions through such pointers. Just define |
| |
|
| @example |
@example |
| : badword 0 DO i . LOOP ; ok |
\c #include <func1.h> |
| 2 dbg badword |
\c #define call_func1(par1,fptr) ((func1)fptr)(par1) |
| : badword |
c-function call-func1 call_func1 n func -- n |
| Scanning code... |
@end example |
| |
|
| Nesting debugger ready! |
and then you can call a function pointed to by, say @code{func1a} as |
| |
follows: |
| |
|
| 400D4738 8049BC4 0 -> [ 2 ] 00002 00000 |
@example |
| 400D4740 8049F68 DO -> [ 0 ] |
-5 func1a call-func1 . |
| 400D4744 804A0C8 i -> [ 1 ] 00000 |
|
| 400D4748 400C5E60 . -> 0 [ 0 ] |
|
| 400D474C 8049D0C LOOP -> [ 0 ] |
|
| 400D4744 804A0C8 i -> [ 1 ] 00001 |
|
| 400D4748 400C5E60 . -> 1 [ 0 ] |
|
| 400D474C 8049D0C LOOP -> [ 0 ] |
|
| 400D4758 804B384 ; -> ok |
|
| @end example |
@end example |
| |
|
| Each line displayed is one step. You always have to hit return to |
In the C part, @code{call_func} is defined as a macro to avoid having |
| execute the next word that is displayed. If you don't want to execute |
to declare the exact parameter and return types, so the C compiler |
| the next word in a whole, you have to type @kbd{n} for @code{nest}. Here is |
knows them from the declaration of @code{func1}. |
| an overview what keys are available: |
|
| |
|
| @table @i |
The Forth word @code{call-func1} is similar to @code{execute}, except |
| |
that it takes a C @code{func1} pointer instead of a Forth execution |
| |
token, and it is specific to @code{func1} pointers. For each type of |
| |
function pointer you want to call from Forth, you have to define |
| |
a separate calling word. |
| |
|
| @item @key{RET} |
|
| Next; Execute the next word. |
|
| |
|
| @item n |
@node Declaring libraries, Callbacks, Calling C function pointers, C Interface |
| Nest; Single step through next word. |
@subsection Declaring libraries |
| |
@cindex Shared libraries in C interface |
| |
@cindex Dynamically linked libraries in C interface |
| |
@cindex Libraries in C interface |
| |
|
| @item u |
For calling some C functions, you need to link with a specific library |
| Unnest; Stop debugging and execute rest of word. If we got to this word |
that contains that library. E.g., the @code{sin} function requires |
| with nest, continue debugging with the calling word. |
linking a special library by using the command line switch @code{-lm}. |
| |
In our C iterface you do the equivalent thing by calling |
| |
@code{add-lib} as follows: |
| |
|
| @item d |
@example |
| Done; Stop debugging and execute rest. |
clear-libs |
| |
s" m" add-lib |
| |
\c #include <math.h> |
| |
c-function sin sin r -- r |
| |
@end example |
| |
|
| @item s |
First, you clear any libraries that may have been declared earlier |
| Stop; Abort immediately. |
(you don't need them for @code{sin}); then you add the @code{m} |
| |
library (actually @code{libm.so} or somesuch) to the currently |
| |
declared libraries; you can add as many as you need. Finally you |
| |
declare the function as shown above. Typically you will use the same |
| |
set of library declarations for many function declarations; you need |
| |
to write only one set for that, right at the beginning. |
| |
|
| @end table |
doc-clear-libs |
| |
doc-add-lib |
| |
|
| Debugging large application with this mechanism is very difficult, because |
|
| you have to nest very deeply into the program before the interesting part |
|
| begins. This takes a lot of time. |
|
| |
|
| To do it more directly put a @code{BREAK:} command into your source code. |
@node Callbacks, C interface internals, Declaring libraries, C Interface |
| When program execution reaches @code{BREAK:} the single step debugger is |
@subsection Callbacks |
| invoked and you have all the features described above. |
@cindex Callback functions written in Forth |
| |
@cindex C function pointers to Forth words |
| |
|
| If you have more than one part to debug it is useful to know where the |
Callbacks are not yet supported by the documented C interface. You |
| program has stopped at the moment. You can do this by the |
can use the undocumented @file{lib.fs} interface for callbacks. |
| @code{BREAK" string"} command. This behaves like @code{BREAK:} except that |
|
| string is typed out when the ``breakpoint'' is reached. |
|
| |
|
| |
In some cases you have to pass a function pointer to a C function, |
| |
i.e., the library wants to call back to your application (and the |
| |
pointed-to function is called a callback function). You can pass the |
| |
address of an existing C function (that you get with @code{lib-sym}, |
| |
@pxref{Low-Level C Interface Words}), but if there is no appropriate C |
| |
function, you probably want to define the function as a Forth word. |
| |
|
| doc-dbg |
@c I don't understand the existing callback interface from the example - anton |
| doc-break: |
|
| doc-break" |
|
| |
|
| |
|
| |
@c > > Und dann gibt's noch die fptr-Deklaration, die einem |
| |
@c > > C-Funktionspointer entspricht (Deklaration gleich wie bei |
| |
@c > > Library-Funktionen, nur ohne den C-Namen, Aufruf mit der |
| |
@c > > C-Funktionsadresse auf dem TOS). |
| |
@c > |
| |
@c > Ja, da bin ich dann ausgestiegen, weil ich aus dem Beispiel nicht |
| |
@c > gesehen habe, wozu das gut ist. |
| |
@c |
| |
@c Irgendwie muss ich den Callback ja testen. Und es soll ja auch |
| |
@c vorkommen, dass man von irgendwelchen kranken Interfaces einen |
| |
@c Funktionspointer übergeben bekommt, den man dann bei Gelegenheit |
| |
@c aufrufen muss. Also kann man den deklarieren, und das damit deklarierte |
| |
@c Wort verhält sich dann wie ein EXECUTE für alle C-Funktionen mit |
| |
@c demselben Prototyp. |
| |
|
| |
|
| |
@node C interface internals, Low-Level C Interface Words, Callbacks, C Interface |
| |
@subsection How the C interface works |
| |
|
| |
The documented C interface works by generating a C code out of the |
| |
declarations. |
| |
|
| |
In particular, for every Forth word declared with @code{c-function}, |
| |
it generates a wrapper function in C that takes the Forth data from |
| |
the Forth stacks, and calls the target C function with these data as |
| |
arguments. The C compiler then performs an implicit conversion |
| |
between the Forth type from the stack, and the C type for the |
| |
parameter, which is given by the C function prototype. After the C |
| |
function returns, the return value is likewise implicitly converted to |
| |
a Forth type and written back on the stack. |
| |
|
| |
The @code{\c} lines are literally included in the C code (but without |
| |
the @code{\c}), and provide the necessary declarations so that the C |
| |
compiler knows the C types and has enough information to perform the |
| |
conversion. |
| |
|
| |
These wrapper functions are eventually compiled and dynamically linked |
| |
into Gforth, and then they can be called. |
| |
|
| |
The libraries added with @code{add-lib} are used in the compile |
| |
command line to specify dependent libraries with @code{-l@var{lib}}, |
| |
causing these libraries to be dynamically linked when the wrapper |
| |
function is linked. |
| |
|
| |
|
| |
@node Low-Level C Interface Words, , C interface internals, C Interface |
| |
@subsection Low-Level C Interface Words |
| |
|
| |
doc-open-lib |
| |
doc-lib-sym |
| |
doc-call-c |
| |
|
| @c ------------------------------------------------------------- |
@c ------------------------------------------------------------- |
| @node Assembler and Code Words, Threading Words, Programming Tools, Words |
@node Assembler and Code Words, Threading Words, C Interface, Words |
| @section Assembler and Code Words |
@section Assembler and Code Words |
| @cindex assembler |
@cindex assembler |
| @cindex code words |
@cindex code words |
| * 386 Assembler:: Deviations and special cases |
* 386 Assembler:: Deviations and special cases |
| * Alpha Assembler:: Deviations and special cases |
* Alpha Assembler:: Deviations and special cases |
| * MIPS assembler:: Deviations and special cases |
* MIPS assembler:: Deviations and special cases |
| |
* PowerPC assembler:: Deviations and special cases |
| |
* ARM Assembler:: Deviations and special cases |
| * Other assemblers:: How to write them |
* Other assemblers:: How to write them |
| @end menu |
@end menu |
| |
|
| is installation-dependent. |
is installation-dependent. |
| |
|
| In particular, @code{ip} (Forth instruction pointer) and @code{rp} |
In particular, @code{ip} (Forth instruction pointer) and @code{rp} |
| (return stack pointer) are in different places in @code{gforth} and |
(return stack pointer) may be in different places in @code{gforth} and |
| @code{gforth-fast}. This means that you cannot write a @code{NEXT} |
@code{gforth-fast}, or different installations. This means that you |
| routine that works on both versions; so for doing @code{NEXT}, I |
cannot write a @code{NEXT} routine that works reliably on both versions |
| recomment jumping to @code{' noop >code-address}, which contains nothing |
or different installations; so for doing @code{NEXT}, I recommend |
| but a @code{NEXT}. |
jumping to @code{' noop >code-address}, which contains nothing but a |
| |
@code{NEXT}. |
| |
|
| For general accesses to the inner interpreter's registers, the easiest |
For general accesses to the inner interpreter's registers, the easiest |
| solution is to use explicit register declarations (@pxref{Explicit Reg |
solution is to use explicit register declarations (@pxref{Explicit Reg |
| changed register assignment. The stability of the register assignment |
changed register assignment. The stability of the register assignment |
| is usually better if you build Gforth with @code{--enable-force-reg}. |
is usually better if you build Gforth with @code{--enable-force-reg}. |
| |
|
| In particular, the return stack pointer and the instruction pointer are |
The most common use of these registers is to dispatch to the next word |
| in memory in @code{gforth}, and usually in registers in |
(the @code{next} routine). A portable way to do this is to jump to |
| @code{gforth-fast}. The most common use of these registers is to |
@code{' noop >code-address} (of course, this is less efficient than |
| dispatch to the next word (the @code{next} routine). A portable way to |
integrating the @code{next} code and scheduling it well). |
| do this is to jump to @code{' noop >code-address} (of course, this is |
|
| less efficient than integrating the @code{next} code and scheduling it |
Another difference between Gforth version is that the top of stack is |
| well). |
kept in memory in @code{gforth} and, on most platforms, in a register in |
| |
@code{gforth-fast}. |
| |
|
| @node Common Disassembler, 386 Assembler, Common Assembler, Assembler and Code Words |
@node Common Disassembler, 386 Assembler, Common Assembler, Assembler and Code Words |
| @subsection Common Disassembler |
@subsection Common Disassembler |
| |
@cindex disassembler, general |
| |
@cindex gdb disassembler |
| |
|
| You can disassemble a @code{code} word with @code{see} |
You can disassemble a @code{code} word with @code{see} |
| (@pxref{Debugging}). You can disassemble a section of memory with |
(@pxref{Debugging}). You can disassemble a section of memory with |
| |
|
| doc-disasm |
doc-discode |
| |
|
| |
There are two kinds of disassembler for Gforth: The Forth disassembler |
| |
(available on some CPUs) and the gdb disassembler (available on |
| |
platforms with @command{gdb} and @command{mktemp}). If both are |
| |
available, the Forth disassembler is used by default. If you prefer |
| |
the gdb disassembler, say |
| |
|
| The disassembler generally produces output that can be fed into the |
@example |
| |
' disasm-gdb is discode |
| |
@end example |
| |
|
| |
If neither is available, @code{discode} performs @code{dump}. |
| |
|
| |
The Forth disassembler generally produces output that can be fed into the |
| assembler (i.e., same syntax, etc.). It also includes additional |
assembler (i.e., same syntax, etc.). It also includes additional |
| information in comments. In particular, the address of the instruction |
information in comments. In particular, the address of the instruction |
| is given in a comment before the instruction. |
is given in a comment before the instruction. |
| |
|
| |
The gdb disassembler produces output in the same format as the gdb |
| |
@code{disassemble} command (@pxref{Machine Code,,Source and machine |
| |
code,gdb,Debugging with GDB}), in the default flavour (AT&T syntax for |
| |
the 386 and AMD64 architectures). |
| |
|
| @code{See} may display more or less than the actual code of the word, |
@code{See} may display more or less than the actual code of the word, |
| because the recognition of the end of the code is unreliable. You can |
because the recognition of the end of the code is unreliable. You can |
| use @code{disasm} if it did not display enough. It may display more, if |
use @code{discode} if it did not display enough. It may display more, if |
| the code word is not immediately followed by a named word. If you have |
the code word is not immediately followed by a named word. If you have |
| something else there, you can follow the word with @code{align last @ ,} |
something else there, you can follow the word with @code{align latest ,} |
| to ensure that the end is recognized. |
to ensure that the end is recognized. |
| |
|
| @node 386 Assembler, Alpha Assembler, Common Disassembler, Assembler and Code Words |
@node 386 Assembler, Alpha Assembler, Common Disassembler, Assembler and Code Words |
| The 386 disassembler included in Gforth was written by Andrew McKewan |
The 386 disassembler included in Gforth was written by Andrew McKewan |
| and is in the public domain. |
and is in the public domain. |
| |
|
| The disassembler displays code in prefix Intel syntax. |
The disassembler displays code in an Intel-like prefix syntax. |
| |
|
| The assembler uses a postfix syntax with reversed parameters. |
The assembler uses a postfix syntax with reversed parameters. |
| |
|
| |
|
| The registers lack the 'e' prefix; even in 32 bit mode, eax is called |
The registers lack the 'e' prefix; even in 32 bit mode, eax is called |
| ax. Immediate values are indicated by postfixing them with @code{#}, |
ax. Immediate values are indicated by postfixing them with @code{#}, |
| e.g., @code{3 #}. Here are some examples of addressing modes: |
e.g., @code{3 #}. Here are some examples of addressing modes in various |
| |
syntaxes: |
| |
|
| @example |
@example |
| 3 # \ immediate |
Gforth Intel (NASM) AT&T (gas) Name |
| ax \ register |
.w ax ax %ax register (16 bit) |
| 100 di d) \ 100[edi] |
ax eax %eax register (32 bit) |
| 4 bx cx di) \ 4[ebx][ecx] |
3 # offset 3 $3 immediate |
| di ax *4 i) \ [edi][eax*4] |
1000 #) byte ptr 1000 1000 displacement |
| 20 ax *4 i#) \ 20[eax*4] |
bx ) [ebx] (%ebx) base |
| @end example |
100 di d) 100[edi] 100(%edi) base+displacement |
| |
20 ax *4 i#) 20[eax*4] 20(,%eax,4) (index*scale)+displacement |
| |
di ax *4 i) [edi][eax*4] (%edi,%eax,4) base+(index*scale) |
| |
4 bx cx di) 4[ebx][ecx] 4(%ebx,%ecx) base+index+displacement |
| |
12 sp ax *2 di) 12[esp][eax*2] 12(%esp,%eax,2) base+(index*scale)+displacement |
| |
@end example |
| |
|
| |
You can use @code{L)} and @code{LI)} instead of @code{D)} and |
| |
@code{DI)} to enforce 32-bit displacement fields (useful for |
| |
later patching). |
| |
|
| Some example of instructions are: |
Some example of instructions are: |
| |
|
| @example |
@example |
| ax bx mov \ move ebx,eax |
ax bx mov \ move ebx,eax |
| 3 # ax mov \ mov eax,3 |
3 # ax mov \ mov eax,3 |
| 100 di ) ax mov \ mov eax,100[edi] |
100 di d) ax mov \ mov eax,100[edi] |
| 4 bx cx di) ax mov \ mov eax,4[ebx][ecx] |
4 bx cx di) ax mov \ mov eax,4[ebx][ecx] |
| .w ax bx mov \ mov bx,ax |
.w ax bx mov \ mov bx,ax |
| @end example |
@end example |
| <n> # <reg> <inst> |
<n> # <reg> <inst> |
| <mem> <reg> <inst> |
<mem> <reg> <inst> |
| <reg> <mem> <inst> |
<reg> <mem> <inst> |
| |
<n> # <mem> <inst> |
| @end example |
@end example |
| |
|
| Immediate to memory is not supported. The shift/rotate syntax is: |
The shift/rotate syntax is: |
| |
|
| @example |
@example |
| <reg/mem> 1 # shl \ shortens to shift without immediate |
<reg/mem> 1 # shl \ shortens to shift without immediate |
| end-code |
end-code |
| @end example |
@end example |
| |
|
| |
|
| @node Alpha Assembler, MIPS assembler, 386 Assembler, Assembler and Code Words |
@node Alpha Assembler, MIPS assembler, 386 Assembler, Assembler and Code Words |
| @subsection Alpha Assembler |
@subsection Alpha Assembler |
| |
|
| |
|
| @code{fbgt,} gives @code{fgt}. |
@code{fbgt,} gives @code{fgt}. |
| |
|
| @node MIPS assembler, Other assemblers, Alpha Assembler, Assembler and Code Words |
@node MIPS assembler, PowerPC assembler, Alpha Assembler, Assembler and Code Words |
| @subsection MIPS assembler |
@subsection MIPS assembler |
| |
|
| The MIPS assembler was originally written by Christian Pirker. |
The MIPS assembler was originally written by Christian Pirker. |
| then, |
then, |
| @end example |
@end example |
| |
|
| @node Other assemblers, , MIPS assembler, Assembler and Code Words |
|
| |
@node PowerPC assembler, ARM Assembler, MIPS assembler, Assembler and Code Words |
| |
@subsection PowerPC assembler |
| |
|
| |
The PowerPC assembler and disassembler were contributed by Michal |
| |
Revucky. |
| |
|
| |
This assembler does not follow the convention of ending mnemonic names |
| |
with a ``,'', so some mnemonic names shadow regular Forth words (in |
| |
particular: @code{and or xor fabs}); so if you want to use the Forth |
| |
words, you have to make them visible first, e.g., with @code{also |
| |
forth}. |
| |
|
| |
Registers are referred to by their number, e.g., @code{9} means the |
| |
integer register 9 or the FP register 9 (depending on the |
| |
instruction). |
| |
|
| |
Because there is no way to distinguish registers from immediate values, |
| |
you have to explicitly use the immediate forms of instructions, i.e., |
| |
@code{addi,}, not just @code{add,}. |
| |
|
| |
The assembler and disassembler usually support the most general form |
| |
of an instruction, but usually not the shorter forms (especially for |
| |
branches). |
| |
|
| |
|
| |
@node ARM Assembler, Other assemblers, PowerPC assembler, Assembler and Code Words |
| |
@subsection ARM Assembler |
| |
|
| |
The ARM assembler included in Gforth was written from scratch by David |
| |
Kuehling. |
| |
|
| |
The assembler includes all instruction of ARM architecture version 4, |
| |
but does not (yet) have support for Thumb instructions. It also lacks |
| |
support for any co-processors. |
| |
|
| |
The assembler uses a postfix syntax with the target operand specified |
| |
last. For load/store instructions the last operand will be the |
| |
register(s) to be loaded from/stored to. |
| |
|
| |
Registers are specified by their names @code{r0} through @code{r15}, |
| |
with the aliases @code{pc}, @code{lr}, @code{sp}, @code{ip} and |
| |
@code{fp} provided for convenience. Note that @code{ip} means intra |
| |
procedure call scratch register (@code{r12}) and does not refer to the |
| |
instruction pointer. |
| |
|
| |
Condition codes can be specified anywhere in the instruction, but will |
| |
be most readable if specified just in front of the mnemonic. The 'S' |
| |
flag is not a separate word, but encoded into instruction mnemonics, |
| |
ie. just use @code{adds,} instead of @code{add,} if you want the |
| |
status register to be updated. |
| |
|
| |
The following table lists the syntax of operands for general |
| |
instructions: |
| |
|
| |
@example |
| |
Gforth normal assembler description |
| |
123 # #123 immediate |
| |
r12 r12 register |
| |
r12 4 #LSL r12, LSL #4 shift left by immediate |
| |
r12 r1 #LSL r12, LSL r1 shift left by register |
| |
r12 4 #LSR r12, LSR #4 shift right by immediate |
| |
r12 r1 #LSR r12, LSR r1 shift right by register |
| |
r12 4 #ASR r12, ASR #4 arithmetic shift right |
| |
r12 r1 #ASR r12, ASR r1 ... by register |
| |
r12 4 #ROR r12, ROR #4 rotate right by immediate |
| |
r12 r1 #ROR r12, ROR r1 ... by register |
| |
r12 RRX r12, RRX rotate right with extend by 1 |
| |
@end example |
| |
|
| |
Memory operand syntax is listed in this table: |
| |
|
| |
@example |
| |
Gforth normal assembler description |
| |
r4 ] [r4] register |
| |
r4 4 #] [r4, #+4] register with immediate offset |
| |
r4 -4 #] [r4, #-4] with negative offset |
| |
r4 r1 +] [r4, +r1] register with register offset |
| |
r4 r1 -] [r4, -r1] with negated register offset |
| |
r4 r1 2 #LSL -] [r4, -r1, LSL #2] with negated and shifted offset |
| |
r4 4 #]! [r4, #+4]! immediate preincrement |
| |
r4 r1 +]! [r4, +r1]! register preincrement |
| |
r4 r1 -]! [r4, +r1]! register predecrement |
| |
r4 r1 2 #LSL +]! [r4, +r1, LSL #2]! shifted preincrement |
| |
r4 -4 ]# [r4], #-4 immediate postdecrement |
| |
r4 r1 ]+ [r4], r1 register postincrement |
| |
r4 r1 ]- [r4], -r1 register postdecrement |
| |
r4 r1 2 #LSL ]- [r4], -r1, LSL #2 shifted postdecrement |
| |
' xyz >body [#] xyz PC-relative addressing |
| |
@end example |
| |
|
| |
Register lists for load/store multiple instructions are started and |
| |
terminated by using the words @code{@{} and @code{@}} |
| |
respectivly. Between braces, register names can be listed one by one, |
| |
or register ranges can be formed by using the postfix operator |
| |
@code{r-r}. The @code{^} flag is not encoded in the register list |
| |
operand, but instead directly encoded into the instruction mnemonic, |
| |
ie. use @code{^ldm,} and @code{^stm,}. |
| |
|
| |
Addressing modes for load/store multiple are not encoded as |
| |
instruction suffixes, but instead specified after the register that |
| |
supplies the address. Use one of @code{DA}, @code{IA}, @code{DB}, |
| |
@code{IB}, @code{DA!}, @code{IA!}, @code{DB!} or @code{IB!}. |
| |
|
| |
The following table gives some examples: |
| |
|
| |
@example |
| |
Gforth normal assembler |
| |
@{ r0 r7 r8 @} r4 ia stm, stmia @{r0,r7,r8@}, r4 |
| |
@{ r0 r7 r8 @} r4 db! ldm, ldmdb @{r0,r7,r8@}, r4! |
| |
@{ r0 r15 r-r @} sp ia! ^ldm, ldmfd @{r0-r15@}^, sp! |
| |
@end example |
| |
|
| |
Conditions for control structure words are specified in front of a |
| |
word: |
| |
|
| |
@example |
| |
r1 r2 cmp, \ compare r1 and r2 |
| |
eq if, \ equal? |
| |
... \ code executed if r1 == r2 |
| |
then, |
| |
@end example |
| |
|
| |
Here is an example of a @code{code} word (assumes that the stack |
| |
pointer is in @code{r9}, and that @code{r2} and @code{r3} can be |
| |
clobbered): |
| |
|
| |
@example |
| |
code my+ ( n1 n2 -- n3 ) |
| |
r9 IA! @{ r2 r3 @} ldm, \ pop r2 = n2, r3 = n1 |
| |
r2 r3 r3 add, \ r3 = n2+n1 |
| |
r9 -4 #]! r3 str, \ push r3 |
| |
next, |
| |
end-code |
| |
@end example |
| |
|
| |
Look at @file{arch/arm/asm-example.fs} for more examples. |
| |
|
| |
@node Other assemblers, , ARM Assembler, Assembler and Code Words |
| @subsection Other assemblers |
@subsection Other assemblers |
| |
|
| If you want to contribute another assembler/disassembler, please contact |
If you want to contribute another assembler/disassembler, please contact |
| us (@email{bug-gforth@@gnu.org}) to check if we have such an assembler |
us (@email{anton@@mips.complang.tuwien.ac.at}) to check if we have such |
| already. If you are writing them from scratch, please use a similar |
an assembler already. If you are writing them from scratch, please use |
| syntax style as the one we use (i.e., postfix, commas at the end of the |
a similar syntax style as the one we use (i.e., postfix, commas at the |
| instruction names, @pxref{Common Assembler}); make the output of the |
end of the instruction names, @pxref{Common Assembler}); make the output |
| disassembler be valid input for the assembler, and keep the style |
of the disassembler be valid input for the assembler, and keep the style |
| similar to the style we used. |
similar to the style we used. |
| |
|
| Hints on implementation: The most important part is to have a good test |
Hints on implementation: The most important part is to have a good test |
| For the assembler, take a look at @file{arch/alpha/asm.fs}, which shows |
For the assembler, take a look at @file{arch/alpha/asm.fs}, which shows |
| how simple it can be. |
how simple it can be. |
| |
|
| |
|
| |
|
| |
|
| @c ------------------------------------------------------------- |
@c ------------------------------------------------------------- |
| @node Threading Words, Passing Commands to the OS, Assembler and Code Words, Words |
@node Threading Words, Passing Commands to the OS, Assembler and Code Words, Words |
| @section Threading Words |
@section Threading Words |
| doc-dodefer: |
doc-dodefer: |
| doc-dofield: |
doc-dofield: |
| |
|
| |
@cindex definer |
| |
The following two words generalize @code{>code-address}, |
| |
@code{>does-code}, @code{code-address!}, and @code{does-code!}: |
| |
|
| |
doc->definer |
| |
doc-definer! |
| |
|
| @c ------------------------------------------------------------- |
@c ------------------------------------------------------------- |
| @node Passing Commands to the OS, Keeping track of Time, Threading Words, Words |
@node Passing Commands to the OS, Keeping track of Time, Threading Words, Words |
| @section Passing Commands to the Operating System |
@section Passing Commands to the Operating System |
| Gforth allows you to pass an arbitrary string to the host operating |
Gforth allows you to pass an arbitrary string to the host operating |
| system shell (if such a thing exists) for execution. |
system shell (if such a thing exists) for execution. |
| |
|
| |
|
| doc-sh |
doc-sh |
| doc-system |
doc-system |
| doc-$? |
doc-$? |
| doc-getenv |
doc-getenv |
| |
|
| |
|
| @c ------------------------------------------------------------- |
@c ------------------------------------------------------------- |
| @node Keeping track of Time, Miscellaneous Words, Passing Commands to the OS, Words |
@node Keeping track of Time, Miscellaneous Words, Passing Commands to the OS, Words |
| @section Keeping track of Time |
@section Keeping track of Time |
| @cindex time-related words |
@cindex time-related words |
| |
|
| Gforth implements time-related operations by making calls to the C |
|
| library function, @code{gettimeofday}. |
|
| |
|
| doc-ms |
doc-ms |
| doc-time&date |
doc-time&date |
| |
doc-utime |
| |
doc-cputime |
| |
|
| |
|
| @c ------------------------------------------------------------- |
@c ------------------------------------------------------------- |
| These section lists the ANS Forth words that are not documented |
These section lists the ANS Forth words that are not documented |
| elsewhere in this manual. Ultimately, they all need proper homes. |
elsewhere in this manual. Ultimately, they all need proper homes. |
| |
|
| doc-[compile] |
|
| doc-quit |
doc-quit |
| |
|
| The following ANS Forth words are not currently supported by Gforth |
The following ANS Forth words are not currently supported by Gforth |
| A typical Gforth error message looks like this: |
A typical Gforth error message looks like this: |
| |
|
| @example |
@example |
| in file included from :-1 |
in file included from \evaluated string/:-1 |
| in file included from ./yyy.fs:1 |
in file included from ./yyy.fs:1 |
| ./xxx.fs:4: Invalid memory address |
./xxx.fs:4: Invalid memory address |
| bar |
>>>bar<<< |
| ^^^ |
Backtrace: |
| $400E664C @@ |
$400E664C @@ |
| $400E6664 foo |
$400E6664 foo |
| @end example |
@end example |
| error happened when text-interpreting line 4 of the file |
error happened when text-interpreting line 4 of the file |
| @file{./xxx.fs}. This line is given (it contains @code{bar}), and the |
@file{./xxx.fs}. This line is given (it contains @code{bar}), and the |
| word on the line where the error happened, is pointed out (with |
word on the line where the error happened, is pointed out (with |
| @code{^^^}). |
@code{>>>} and @code{<<<}). |
| |
|
| The file containing the error was included in line 1 of @file{./yyy.fs}, |
The file containing the error was included in line 1 of @file{./yyy.fs}, |
| and @file{yyy.fs} was included from a non-file (in this case, by giving |
and @file{yyy.fs} was included from a non-file (in this case, by giving |
| @code{catch}, it is not necessarily clear which @code{throw} should be |
@code{catch}, it is not necessarily clear which @code{throw} should be |
| used for the return stack dump (e.g., consider one @code{throw} that |
used for the return stack dump (e.g., consider one @code{throw} that |
| indicates an error, which is caught, and during recovery another error |
indicates an error, which is caught, and during recovery another error |
| happens; which @code{throw} should be used for the stack dump?). Gforth |
happens; which @code{throw} should be used for the stack dump?). |
| presents the return stack dump for the first @code{throw} after the last |
Gforth presents the return stack dump for the first @code{throw} after |
| executed (not returned-to) @code{catch}; this works well in the usual |
the last executed (not returned-to) @code{catch} or @code{nothrow}; |
| case. |
this works well in the usual case. To get the right backtrace, you |
| |
usually want to insert @code{nothrow} or @code{['] false catch drop} |
| |
after a @code{catch} if the error is not rethrown. |
| |
|
| @cindex @code{gforth-fast} and backtraces |
@cindex @code{gforth-fast} and backtraces |
| @cindex @code{gforth-fast}, difference from @code{gforth} |
@cindex @code{gforth-fast}, difference from @code{gforth} |
| @cindex backtraces with @code{gforth-fast} |
@cindex backtraces with @code{gforth-fast} |
| @cindex return stack dump with @code{gforth-fast} |
@cindex return stack dump with @code{gforth-fast} |
| @code{gforth} is able to do a return stack dump for throws generated |
@code{Gforth} is able to do a return stack dump for throws generated |
| from primitives (e.g., invalid memory address, stack empty etc.); |
from primitives (e.g., invalid memory address, stack empty etc.); |
| @code{gforth-fast} is only able to do a return stack dump from a |
@code{gforth-fast} is only able to do a return stack dump from a |
| directly called @code{throw} (including @code{abort} etc.). This is the |
directly called @code{throw} (including @code{abort} etc.). Given an |
| only difference (apart from a speed factor of between 1.15 (K6-2) and |
|
| 2 (21264)) between @code{gforth} and @code{gforth-fast}. Given an |
|
| exception caused by a primitive in @code{gforth-fast}, you will |
exception caused by a primitive in @code{gforth-fast}, you will |
| typically see no return stack dump at all; however, if the exception is |
typically see no return stack dump at all; however, if the exception is |
| caught by @code{catch} (e.g., for restoring some state), and then |
caught by @code{catch} (e.g., for restoring some state), and then |
| |
|
| @menu |
@menu |
| * ANS Report:: Report the words used, sorted by wordset. |
* ANS Report:: Report the words used, sorted by wordset. |
| |
* Stack depth changes:: Where does this stack item come from? |
| @end menu |
@end menu |
| |
|
| See also @ref{Emacs and Gforth}. |
See also @ref{Emacs and Gforth}. |
| |
|
| @node ANS Report, , Tools, Tools |
@node ANS Report, Stack depth changes, Tools, Tools |
| @section @file{ans-report.fs}: Report the words used, sorted by wordset |
@section @file{ans-report.fs}: Report the words used, sorted by wordset |
| @cindex @file{ans-report.fs} |
@cindex @file{ans-report.fs} |
| @cindex report the words used in your program |
@cindex report the words used in your program |
| compilation semantics of @code{S"}, it is a Core word; if you also use |
compilation semantics of @code{S"}, it is a Core word; if you also use |
| its interpretation semantics, it is a File word. |
its interpretation semantics, it is a File word. |
| |
|
| |
|
| |
@node Stack depth changes, , ANS Report, Tools |
| |
@section Stack depth changes during interpretation |
| |
@cindex @file{depth-changes.fs} |
| |
@cindex depth changes during interpretation |
| |
@cindex stack depth changes during interpretation |
| |
@cindex items on the stack after interpretation |
| |
|
| |
Sometimes you notice that, after loading a file, there are items left |
| |
on the stack. The tool @file{depth-changes.fs} helps you find out |
| |
quickly where in the file these stack items are coming from. |
| |
|
| |
The simplest way of using @file{depth-changes.fs} is to include it |
| |
before the file(s) you want to check, e.g.: |
| |
|
| |
@example |
| |
gforth depth-changes.fs my-file.fs |
| |
@end example |
| |
|
| |
This will compare the stack depths of the data and FP stack at every |
| |
empty line (in interpretation state) against these depths at the last |
| |
empty line (in interpretation state). If the depths are not equal, |
| |
the position in the file and the stack contents are printed with |
| |
@code{~~} (@pxref{Debugging}). This indicates that a stack depth |
| |
change has occured in the paragraph of non-empty lines before the |
| |
indicated line. It is a good idea to leave an empty line at the end |
| |
of the file, so the last paragraph is checked, too. |
| |
|
| |
Checking only at empty lines usually works well, but sometimes you |
| |
have big blocks of non-empty lines (e.g., when building a big table), |
| |
and you want to know where in this block the stack depth changed. You |
| |
can check all interpreted lines with |
| |
|
| |
@example |
| |
gforth depth-changes.fs -e "' all-lines is depth-changes-filter" my-file.fs |
| |
@end example |
| |
|
| |
This checks the stack depth at every end-of-line. So the depth change |
| |
occured in the line reported by the @code{~~} (not in the line |
| |
before). |
| |
|
| |
Note that, while this offers better accuracy in indicating where the |
| |
stack depth changes, it will often report many intentional stack depth |
| |
changes (e.g., when an interpreted computation stretches across |
| |
several lines). You can suppress the checking of some lines by |
| |
putting backslashes at the end of these lines (not followed by white |
| |
space), and using |
| |
|
| |
@example |
| |
gforth depth-changes.fs -e "' most-lines is depth-changes-filter" my-file.fs |
| |
@end example |
| |
|
| @c ****************************************************************** |
@c ****************************************************************** |
| @node ANS conformance, Standard vs Extensions, Tools, Top |
@node ANS conformance, Standard vs Extensions, Tools, Top |
| @chapter ANS conformance |
@chapter ANS conformance |
| @item providing the String Extensions word set (another easy one) |
@item providing the String Extensions word set (another easy one) |
| @end itemize |
@end itemize |
| |
|
| |
Gforth has the following environmental restrictions: |
| |
|
| |
@cindex environmental restrictions |
| |
@itemize @bullet |
| |
@item |
| |
While processing the OS command line, if an exception is not caught, |
| |
Gforth exits with a non-zero exit code instyead of performing QUIT. |
| |
|
| |
@item |
| |
When an @code{throw} is performed after a @code{query}, Gforth does not |
| |
allways restore the input source specification in effect at the |
| |
corresponding catch. |
| |
|
| |
@end itemize |
| |
|
| |
|
| @cindex system documentation |
@cindex system documentation |
| In addition, ANS Forth systems are required to document certain |
In addition, ANS Forth systems are required to document certain |
| implementation choices. This chapter tries to meet these |
implementation choices. This chapter tries to meet these |
| @item conditions under which control characters match a space delimiter: |
@item conditions under which control characters match a space delimiter: |
| @cindex space delimiters |
@cindex space delimiters |
| @cindex control characters as delimiters |
@cindex control characters as delimiters |
| If @code{WORD} is called with the space character as a delimiter, all |
If @code{word} is called with the space character as a delimiter, all |
| white-space characters (as identified by the C macro @code{isspace()}) |
white-space characters (as identified by the C macro @code{isspace()}) |
| are delimiters. @code{PARSE}, on the other hand, treats space like other |
are delimiters. @code{Parse}, on the other hand, treats space like other |
| delimiters. @code{SWORD} treats space like @code{WORD}, but behaves |
delimiters. @code{Parse-name}, which is used by the outer |
| like @code{PARSE} otherwise. @code{(NAME)}, which is used by the outer |
|
| interpreter (aka text interpreter) by default, treats all white-space |
interpreter (aka text interpreter) by default, treats all white-space |
| characters as delimiters. |
characters as delimiters. |
| |
|
| @cindex maximum size of a counted string |
@cindex maximum size of a counted string |
| @cindex counted string, maximum size |
@cindex counted string, maximum size |
| @code{s" /counted-string" environment? drop .}. Currently 255 characters |
@code{s" /counted-string" environment? drop .}. Currently 255 characters |
| on all ports, but this may change. |
on all platforms, but this may change. |
| |
|
| @item maximum size of a parsed string: |
@item maximum size of a parsed string: |
| @cindex maximum size of a parsed string |
@cindex maximum size of a parsed string |
| @item maximum size of a definition name, in characters: |
@item maximum size of a definition name, in characters: |
| @cindex maximum size of a definition name, in characters |
@cindex maximum size of a definition name, in characters |
| @cindex name, maximum length |
@cindex name, maximum length |
| 31 |
MAXU/8 |
| |
|
| @item maximum string length for @code{ENVIRONMENT?}, in characters: |
@item maximum string length for @code{ENVIRONMENT?}, in characters: |
| @cindex maximum string length for @code{ENVIRONMENT?}, in characters |
@cindex maximum string length for @code{ENVIRONMENT?}, in characters |
| @cindex @code{ENVIRONMENT?} string length, maximum |
@cindex @code{ENVIRONMENT?} string length, maximum |
| 31 |
MAXU/8 |
| |
|
| @item method of selecting the user input device: |
@item method of selecting the user input device: |
| @cindex user input device, method of selecting |
@cindex user input device, method of selecting |
| @cindex number of bits in one address unit |
@cindex number of bits in one address unit |
| @cindex address unit, size in bits |
@cindex address unit, size in bits |
| @code{s" address-units-bits" environment? drop .}. 8 in all current |
@code{s" address-units-bits" environment? drop .}. 8 in all current |
| ports. |
platforms. |
| |
|
| @item number representation and arithmetic: |
@item number representation and arithmetic: |
| @cindex number representation and arithmetic |
@cindex number representation and arithmetic |
| Processor-dependent. Binary two's complement on all current ports. |
Processor-dependent. Binary two's complement on all current platforms. |
| |
|
| @item ranges for integer types: |
@item ranges for integer types: |
| @cindex ranges for integer types |
@cindex ranges for integer types |
| |
|
| @item size of one character in address units: |
@item size of one character in address units: |
| @cindex char size |
@cindex char size |
| @code{1 chars .}. 1 on all current ports. |
@code{1 chars .}. 1 on all current platforms. |
| |
|
| @item size of the keyboard terminal buffer: |
@item size of the keyboard terminal buffer: |
| @cindex size of the keyboard terminal buffer |
@cindex size of the keyboard terminal buffer |
| |
|
| @item division rounding: |
@item division rounding: |
| @cindex division rounding |
@cindex division rounding |
| installation dependent. @code{s" floored" environment? drop .}. We leave |
The ordinary division words @code{/ mod /mod */ */mod} perform floored |
| the choice to @code{gcc} (what to use for @code{/}) and to you (whether |
division (with the default installation of Gforth). You can check |
| to use @code{fm/mod}, @code{sm/rem} or simply @code{/}). |
this with @code{s" floored" environment? drop .}. If you write |
| |
programs that need a specific division rounding, best use |
| |
@code{fm/mod} or @code{sm/rem} for portability. |
| |
|
| @item values of @code{STATE} when true: |
@item values of @code{STATE} when true: |
| @cindex @code{STATE} values |
@cindex @code{STATE} values |
| @item values returned after arithmetic overflow: |
@item values returned after arithmetic overflow: |
| On two's complement machines, arithmetic is performed modulo |
On two's complement machines, arithmetic is performed modulo |
| 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double |
2**bits-per-cell for single arithmetic and 4**bits-per-cell for double |
| arithmetic (with appropriate mapping for signed types). Division by zero |
arithmetic (with appropriate mapping for signed types). Division by |
| typically results in a @code{-55 throw} (Floating-point unidentified |
zero typically results in a @code{-55 throw} (Floating-point |
| fault), although a @code{-10 throw} (divide by zero) would be more |
unidentified fault) or @code{-10 throw} (divide by zero). Integer |
| appropriate. |
division overflow can result in these throws, or in @code{-11 throw}; |
| |
in @code{gforth-fast} division overflow and divide by zero may also |
| |
result in returning bogus results without producing an exception. |
| |
|
| @item whether the current definition can be found after @t{DOES>}: |
@item whether the current definition can be found after @t{DOES>}: |
| @cindex @t{DOES>}, visibility of current definition |
@cindex @t{DOES>}, visibility of current definition |
| @item a name is neither a word nor a number: |
@item a name is neither a word nor a number: |
| @cindex name not found |
@cindex name not found |
| @cindex undefined word |
@cindex undefined word |
| @code{-13 throw} (Undefined word). Actually, @code{-13 bounce}, which |
@code{-13 throw} (Undefined word). |
| preserves the data and FP stack, so you don't lose more work than |
|
| necessary. |
|
| |
|
| @item a definition name exceeds the maximum length allowed: |
@item a definition name exceeds the maximum length allowed: |
| @cindex word name too long |
@cindex word name too long |
| @item dividing by zero: |
@item dividing by zero: |
| @cindex dividing by zero |
@cindex dividing by zero |
| @cindex floating point unidentified fault, integer division |
@cindex floating point unidentified fault, integer division |
| On better platforms, this produces a @code{-10 throw} (Division by |
On some platforms, this produces a @code{-10 throw} (Division by |
| zero); on other systems, this typically results in a @code{-55 throw} |
zero); on other systems, this typically results in a @code{-55 throw} |
| (Floating-point unidentified fault). |
(Floating-point unidentified fault). |
| |
|
| |
|
| @item insufficient space for loop control parameters: |
@item insufficient space for loop control parameters: |
| @cindex insufficient space for loop control parameters |
@cindex insufficient space for loop control parameters |
| like other return stack overflows. |
Like other return stack overflows. |
| |
|
| @item insufficient space in the dictionary: |
@item insufficient space in the dictionary: |
| @cindex insufficient space in the dictionary |
@cindex insufficient space in the dictionary |
| @cindex result out of range |
@cindex result out of range |
| On two's complement machines, arithmetic is performed modulo |
On two's complement machines, arithmetic is performed modulo |
| 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double |
2**bits-per-cell for single arithmetic and 4**bits-per-cell for double |
| arithmetic (with appropriate mapping for signed types). Division by zero |
arithmetic (with appropriate mapping for signed types). Division by |
| typically results in a @code{-10 throw} (divide by zero) or @code{-55 |
zero typically results in a @code{-10 throw} (divide by zero) or |
| throw} (floating point unidentified fault). @code{convert} and |
@code{-55 throw} (floating point unidentified fault). Overflow on |
| |
division may result in these errors or in @code{-11 throw} (result out |
| |
of range). @code{Gforth-fast} may silently produce bogus results on |
| |
division overflow or division by zero. @code{Convert} and |
| @code{>number} currently overflow silently. |
@code{>number} currently overflow silently. |
| |
|
| @item reading from an empty data or return stack: |
@item reading from an empty data or return stack: |
| that the MMU, and therefore the checking, works with a page-size |
that the MMU, and therefore the checking, works with a page-size |
| granularity). If there is no checking, the symptoms resulting from an |
granularity). If there is no checking, the symptoms resulting from an |
| underflow are similar to those from an overflow. Unbalanced return |
underflow are similar to those from an overflow. Unbalanced return |
| stack errors result in a variaty of symptoms, including @code{-9 throw} |
stack errors can result in a variety of symptoms, including @code{-9 throw} |
| (Invalid memory address) and Illegal Instruction (typically @code{-260 |
(Invalid memory address) and Illegal Instruction (typically @code{-260 |
| throw}). |
throw}). |
| |
|
| |
|
| @item operator's terminal facilities available: |
@item operator's terminal facilities available: |
| @cindex operator's terminal facilities available |
@cindex operator's terminal facilities available |
| After processing the command line, Gforth goes into interactive mode, |
After processing the OS's command line, Gforth goes into interactive mode, |
| and you can give commands to Gforth interactively. The actual facilities |
and you can give commands to Gforth interactively. The actual facilities |
| available depend on how you invoke Gforth. |
available depend on how you invoke Gforth. |
| |
|
| |
|
| @item floating-point result out of range: |
@item floating-point result out of range: |
| @cindex floating-point result out of range |
@cindex floating-point result out of range |
| System-dependent. Can result in a @code{-55 THROW} (Floating-point |
System-dependent. Can result in a @code{-43 throw} (floating point |
| |
overflow), @code{-54 throw} (floating point underflow), @code{-41 throw} |
| |
(floating point inexact result), @code{-55 THROW} (Floating-point |
| unidentified fault), or can produce a special value representing, e.g., |
unidentified fault), or can produce a special value representing, e.g., |
| Infinity. |
Infinity. |
| |
|
| @cindex dividing by zero, floating-point |
@cindex dividing by zero, floating-point |
| @cindex floating-point dividing by zero |
@cindex floating-point dividing by zero |
| @cindex floating-point unidentified fault, FP divide-by-zero |
@cindex floating-point unidentified fault, FP divide-by-zero |
| @code{-55 throw} (Floating-point unidentified fault) |
Platform-dependent; can produce an Infinity, NaN, @code{-42 throw} |
| |
(floating point divide by zero) or @code{-55 throw} (Floating-point |
| |
unidentified fault). |
| |
|
| @item exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@}): |
@item exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@}): |
| @cindex exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@}) |
@cindex exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@}) |
| @item @i{float}<1 (@code{FACOSH}): |
@item @i{float}<1 (@code{FACOSH}): |
| @cindex @code{FACOSH}, @i{float}<1 |
@cindex @code{FACOSH}, @i{float}<1 |
| @cindex floating-point unidentified fault, @code{FACOSH} |
@cindex floating-point unidentified fault, @code{FACOSH} |
| @code{-55 throw} (Floating-point unidentified fault) |
Platform-dependent; on IEEE-FP systems typically produces a NaN. |
| |
|
| @item @i{float}=<-1 (@code{FLNP1}): |
@item @i{float}=<-1 (@code{FLNP1}): |
| @cindex @code{FLNP1}, @i{float}=<-1 |
@cindex @code{FLNP1}, @i{float}=<-1 |
| @cindex floating-point unidentified fault, @code{FLNP1} |
@cindex floating-point unidentified fault, @code{FLNP1} |
| @code{-55 throw} (Floating-point unidentified fault). On IEEE-FP systems |
Platform-dependent; on IEEE-FP systems typically produces a NaN (or a |
| negative infinity is typically produced for @i{float}=-1. |
negative infinity for @i{float}=-1). |
| |
|
| @item @i{float}=<0 (@code{FLN}, @code{FLOG}): |
@item @i{float}=<0 (@code{FLN}, @code{FLOG}): |
| @cindex @code{FLN}, @i{float}=<0 |
@cindex @code{FLN}, @i{float}=<0 |
| @cindex @code{FLOG}, @i{float}=<0 |
@cindex @code{FLOG}, @i{float}=<0 |
| @cindex floating-point unidentified fault, @code{FLN} or @code{FLOG} |
@cindex floating-point unidentified fault, @code{FLN} or @code{FLOG} |
| @code{-55 throw} (Floating-point unidentified fault). On IEEE-FP systems |
Platform-dependent; on IEEE-FP systems typically produces a NaN (or a |
| negative infinity is typically produced for @i{float}=0. |
negative infinity for @i{float}=0). |
| |
|
| @item @i{float}<0 (@code{FASINH}, @code{FSQRT}): |
@item @i{float}<0 (@code{FASINH}, @code{FSQRT}): |
| @cindex @code{FASINH}, @i{float}<0 |
@cindex @code{FASINH}, @i{float}<0 |
| @cindex @code{FSQRT}, @i{float}<0 |
@cindex @code{FSQRT}, @i{float}<0 |
| @cindex floating-point unidentified fault, @code{FASINH} or @code{FSQRT} |
@cindex floating-point unidentified fault, @code{FASINH} or @code{FSQRT} |
| @code{-55 throw} (Floating-point unidentified fault). @code{fasinh} |
Platform-dependent; for @code{fsqrt} this typically gives a NaN, for |
| produces values for these inputs on my Linux box (Bug in the C library?) |
@code{fasinh} some platforms produce a NaN, others a number (bug in the |
| |
C library?). |
| |
|
| @item |@i{float}|>1 (@code{FACOS}, @code{FASIN}, @code{FATANH}): |
@item |@i{float}|>1 (@code{FACOS}, @code{FASIN}, @code{FATANH}): |
| @cindex @code{FACOS}, |@i{float}|>1 |
@cindex @code{FACOS}, |@i{float}|>1 |
| @cindex @code{FASIN}, |@i{float}|>1 |
@cindex @code{FASIN}, |@i{float}|>1 |
| @cindex @code{FATANH}, |@i{float}|>1 |
@cindex @code{FATANH}, |@i{float}|>1 |
| @cindex floating-point unidentified fault, @code{FACOS}, @code{FASIN} or @code{FATANH} |
@cindex floating-point unidentified fault, @code{FACOS}, @code{FASIN} or @code{FATANH} |
| @code{-55 throw} (Floating-point unidentified fault). |
Platform-dependent; IEEE-FP systems typically produce a NaN. |
| |
|
| @item integer part of float cannot be represented by @i{d} in @code{F>D}: |
@item integer part of float cannot be represented by @i{d} in @code{F>D}: |
| @cindex @code{F>D}, integer part of float cannot be represented by @i{d} |
@cindex @code{F>D}, integer part of float cannot be represented by @i{d} |
| @cindex floating-point unidentified fault, @code{F>D} |
@cindex floating-point unidentified fault, @code{F>D} |
| @code{-55 throw} (Floating-point unidentified fault). |
Platform-dependent; typically, some double number is produced and no |
| |
error is reported. |
| |
|
| @item string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.}): |
@item string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.}): |
| @cindex string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.}) |
@cindex string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.}) |
| This does not happen. |
@code{Precision} characters of the numeric output area are used. If |
| |
@code{precision} is too high, these words will smash the data or code |
| |
close to @code{here}. |
| @end table |
@end table |
| |
|
| @c ===================================================================== |
@c ===================================================================== |
| |
|
| @item source and format of display by @code{SEE}: |
@item source and format of display by @code{SEE}: |
| @cindex @code{SEE}, source and format of output |
@cindex @code{SEE}, source and format of output |
| The source for @code{see} is the intermediate code used by the inner |
The source for @code{see} is the executable code used by the inner |
| interpreter. The current @code{see} tries to output Forth source code |
interpreter. The current @code{see} tries to output Forth source code |
| as well as possible. |
(and on some platforms, assembly code for primitives) as well as |
| |
possible. |
| |
|
| @end table |
@end table |
| |
|
| The word is entered into the word list that was the compilation word list |
The word is entered into the word list that was the compilation word list |
| at the start of the definition. Any changes to the name field (e.g., |
at the start of the definition. Any changes to the name field (e.g., |
| @code{immediate}) or the code field (e.g., when executing @code{DOES>}) |
@code{immediate}) or the code field (e.g., when executing @code{DOES>}) |
| are applied to the latest defined word (as reported by @code{last} or |
are applied to the latest defined word (as reported by @code{latest} or |
| @code{lastxt}), if possible, irrespective of the compilation word list. |
@code{latestxt}), if possible, irrespective of the compilation word list. |
| |
|
| @item search order empty (@code{previous}): |
@item search order empty (@code{previous}): |
| @cindex @code{previous}, search order empty |
@cindex @code{previous}, search order empty |
| |
|
| In order to perform these consideratios, you need to know what's |
In order to perform these consideratios, you need to know what's |
| standard and what's not. This manual generally states if something is |
standard and what's not. This manual generally states if something is |
| non-standard, but the authoritative source is the standard document. |
non-standard, but the authoritative source is the |
| |
@uref{http://www.taygeta.com/forth/dpans.html,standard document}. |
| Appendix A of the Standard (@var{Rationale}) provides a valuable insight |
Appendix A of the Standard (@var{Rationale}) provides a valuable insight |
| into the thought processes of the technical committee. |
into the thought processes of the technical committee. |
| |
|
| @cindex @file{gforth.el} |
@cindex @file{gforth.el} |
| @cindex @file{forth.el} |
@cindex @file{forth.el} |
| @cindex Rydqvist, Goran |
@cindex Rydqvist, Goran |
| |
@cindex Kuehling, David |
| @cindex comment editing commands |
@cindex comment editing commands |
| @cindex @code{\}, editing with Emacs |
@cindex @code{\}, editing with Emacs |
| @cindex debug tracer editing commands |
@cindex debug tracer editing commands |
| @cindex @code{~~}, removal with Emacs |
@cindex @code{~~}, removal with Emacs |
| @cindex Forth mode in Emacs |
@cindex Forth mode in Emacs |
| |
|
| Gforth comes with @file{gforth.el}, an improved version of |
Gforth comes with @file{gforth.el}, an improved version of |
| @file{forth.el} by Goran Rydqvist (included in the TILE package). The |
@file{forth.el} by Goran Rydqvist (included in the TILE package). The |
| improvements are: |
improvements are: |
| |
|
| @itemize @bullet |
@itemize @bullet |
| @item |
@item |
| A better (but still not perfect) handling of indentation. |
A better handling of indentation. |
| |
@item |
| |
A custom hilighting engine for Forth-code. |
| @item |
@item |
| Comment paragraph filling (@kbd{M-q}) |
Comment paragraph filling (@kbd{M-q}) |
| @item |
@item |
| @item |
@item |
| Support of the @code{info-lookup} feature for looking up the |
Support of the @code{info-lookup} feature for looking up the |
| documentation of a word. |
documentation of a word. |
| |
@item |
| |
Support for reading and writing blocks files. |
| @end itemize |
@end itemize |
| |
|
| I left the stuff I do not use alone, even though some of it only makes |
To get a basic description of these features, enter Forth mode and |
| sense for TILE. To get a description of these features, enter Forth mode |
type @kbd{C-h m}. |
| and type @kbd{C-h m}. |
|
| |
|
| @cindex source location of error or debugging output in Emacs |
@cindex source location of error or debugging output in Emacs |
| @cindex error output, finding the source location in Emacs |
@cindex error output, finding the source location in Emacs |
| message is only a few keystrokes away (@kbd{C-x `} for the next error, |
message is only a few keystrokes away (@kbd{C-x `} for the next error, |
| @kbd{C-c C-c} for the error under the cursor). |
@kbd{C-c C-c} for the error under the cursor). |
| |
|
| |
@cindex viewing the documentation of a word in Emacs |
| |
@cindex context-sensitive help |
| |
Moreover, for words documented in this manual, you can look up the |
| |
glossary entry quickly by using @kbd{C-h TAB} |
| |
(@code{info-lookup-symbol}, @pxref{Documentation, ,Documentation |
| |
Commands, emacs, Emacs Manual}). This feature requires Emacs 20.3 or |
| |
later and does not work for words containing @code{:}. |
| |
|
| |
@menu |
| |
* Installing gforth.el:: Making Emacs aware of Forth. |
| |
* Emacs Tags:: Viewing the source of a word in Emacs. |
| |
* Hilighting:: Making Forth code look prettier. |
| |
* Auto-Indentation:: Customizing auto-indentation. |
| |
* Blocks Files:: Reading and writing blocks files. |
| |
@end menu |
| |
|
| |
@c ---------------------------------- |
| |
@node Installing gforth.el, Emacs Tags, Emacs and Gforth, Emacs and Gforth |
| |
@section Installing gforth.el |
| |
@cindex @file{.emacs} |
| |
@cindex @file{gforth.el}, installation |
| |
To make the features from @file{gforth.el} available in Emacs, add |
| |
the following lines to your @file{.emacs} file: |
| |
|
| |
@example |
| |
(autoload 'forth-mode "gforth.el") |
| |
(setq auto-mode-alist (cons '("\\.fs\\'" . forth-mode) |
| |
auto-mode-alist)) |
| |
(autoload 'forth-block-mode "gforth.el") |
| |
(setq auto-mode-alist (cons '("\\.fb\\'" . forth-block-mode) |
| |
auto-mode-alist)) |
| |
(add-hook 'forth-mode-hook (function (lambda () |
| |
;; customize variables here: |
| |
(setq forth-indent-level 4) |
| |
(setq forth-minor-indent-level 2) |
| |
(setq forth-hilight-level 3) |
| |
;;; ... |
| |
))) |
| |
@end example |
| |
|
| |
@c ---------------------------------- |
| |
@node Emacs Tags, Hilighting, Installing gforth.el, Emacs and Gforth |
| |
@section Emacs Tags |
| @cindex @file{TAGS} file |
@cindex @file{TAGS} file |
| @cindex @file{etags.fs} |
@cindex @file{etags.fs} |
| @cindex viewing the source of a word in Emacs |
@cindex viewing the source of a word in Emacs |
| @cindex @code{require}, placement in files |
@cindex @code{require}, placement in files |
| @cindex @code{include}, placement in files |
@cindex @code{include}, placement in files |
| Also, if you @code{require} @file{etags.fs}, a new @file{TAGS} file will |
If you @code{require} @file{etags.fs}, a new @file{TAGS} file will be |
| be produced (@pxref{Tags, , Tags Tables, emacs, Emacs Manual}) that |
produced (@pxref{Tags, , Tags Tables, emacs, Emacs Manual}) that |
| contains the definitions of all words defined afterwards. You can then |
contains the definitions of all words defined afterwards. You can then |
| find the source for a word using @kbd{M-.}. Note that emacs can use |
find the source for a word using @kbd{M-.}. Note that Emacs can use |
| several tags files at the same time (e.g., one for the Gforth sources |
several tags files at the same time (e.g., one for the Gforth sources |
| and one for your program, @pxref{Select Tags Table,,Selecting a Tags |
and one for your program, @pxref{Select Tags Table,,Selecting a Tags |
| Table,emacs, Emacs Manual}). The TAGS file for the preloaded words is |
Table,emacs, Emacs Manual}). The TAGS file for the preloaded words is |
| and after @code{require} etc., otherwise you will see the same file |
and after @code{require} etc., otherwise you will see the same file |
| visited several times by commands like @code{tags-search}. |
visited several times by commands like @code{tags-search}. |
| |
|
| @cindex viewing the documentation of a word in Emacs |
@c ---------------------------------- |
| @cindex context-sensitive help |
@node Hilighting, Auto-Indentation, Emacs Tags, Emacs and Gforth |
| Moreover, for words documented in this manual, you can look up the |
@section Hilighting |
| glossary entry quickly by using @kbd{C-h TAB} |
@cindex hilighting Forth code in Emacs |
| (@code{info-lookup-symbol}, see @pxref{Documentation, ,Documentation |
@cindex highlighting Forth code in Emacs |
| Commands, emacs, Emacs Manual}). This feature requires Emacs 20.3 or |
@file{gforth.el} comes with a custom source hilighting engine. When |
| later and does not work for words containing @code{:}. |
you open a file in @code{forth-mode}, it will be completely parsed, |
| |
assigning faces to keywords, comments, strings etc. While you edit |
| |
the file, modified regions get parsed and updated on-the-fly. |
| |
|
| |
Use the variable `forth-hilight-level' to change the level of |
| |
decoration from 0 (no hilighting at all) to 3 (the default). Even if |
| |
you set the hilighting level to 0, the parser will still work in the |
| |
background, collecting information about whether regions of text are |
| |
``compiled'' or ``interpreted''. Those information are required for |
| |
auto-indentation to work properly. Set `forth-disable-parser' to |
| |
non-nil if your computer is too slow to handle parsing. This will |
| |
have an impact on the smartness of the auto-indentation engine, |
| |
though. |
| |
|
| |
Sometimes Forth sources define new features that should be hilighted, |
| |
new control structures, defining-words etc. You can use the variable |
| |
`forth-custom-words' to make @code{forth-mode} hilight additional |
| |
words and constructs. See the docstring of `forth-words' for details |
| |
(in Emacs, type @kbd{C-h v forth-words}). |
| |
|
| |
`forth-custom-words' is meant to be customized in your |
| |
@file{.emacs} file. To customize hilighing in a file-specific manner, |
| |
set `forth-local-words' in a local-variables section at the end of |
| |
your source file (@pxref{Local Variables in Files,, Variables, emacs, Emacs Manual}). |
| |
|
| |
Example: |
| |
@example |
| |
0 [IF] |
| |
Local Variables: |
| |
forth-local-words: |
| |
((("t:") definition-starter (font-lock-keyword-face . 1) |
| |
"[ \t\n]" t name (font-lock-function-name-face . 3)) |
| |
((";t") definition-ender (font-lock-keyword-face . 1))) |
| |
End: |
| |
[THEN] |
| |
@end example |
| |
|
| |
@c ---------------------------------- |
| |
@node Auto-Indentation, Blocks Files, Hilighting, Emacs and Gforth |
| |
@section Auto-Indentation |
| |
@cindex auto-indentation of Forth code in Emacs |
| |
@cindex indentation of Forth code in Emacs |
| |
@code{forth-mode} automatically tries to indent lines in a smart way, |
| |
whenever you type @key{TAB} or break a line with @kbd{C-m}. |
| |
|
| |
Simple customization can be achieved by setting |
| |
`forth-indent-level' and `forth-minor-indent-level' in your |
| |
@file{.emacs} file. For historical reasons @file{gforth.el} indents |
| |
per default by multiples of 4 columns. To use the more traditional |
| |
3-column indentation, add the following lines to your @file{.emacs}: |
| |
|
| |
@example |
| |
(add-hook 'forth-mode-hook (function (lambda () |
| |
;; customize variables here: |
| |
(setq forth-indent-level 3) |
| |
(setq forth-minor-indent-level 1) |
| |
))) |
| |
@end example |
| |
|
| |
If you want indentation to recognize non-default words, customize it |
| |
by setting `forth-custom-indent-words' in your @file{.emacs}. See the |
| |
docstring of `forth-indent-words' for details (in Emacs, type @kbd{C-h |
| |
v forth-indent-words}). |
| |
|
| |
To customize indentation in a file-specific manner, set |
| |
`forth-local-indent-words' in a local-variables section at the end of |
| |
your source file (@pxref{Local Variables in Files, Variables,,emacs, |
| |
Emacs Manual}). |
| |
|
| |
Example: |
| |
@example |
| |
0 [IF] |
| |
Local Variables: |
| |
forth-local-indent-words: |
| |
((("t:") (0 . 2) (0 . 2)) |
| |
((";t") (-2 . 0) (0 . -2))) |
| |
End: |
| |
[THEN] |
| |
@end example |
| |
|
| |
@c ---------------------------------- |
| |
@node Blocks Files, , Auto-Indentation, Emacs and Gforth |
| |
@section Blocks Files |
| |
@cindex blocks files, use with Emacs |
| |
@code{forth-mode} Autodetects blocks files by checking whether the |
| |
length of the first line exceeds 1023 characters. It then tries to |
| |
convert the file into normal text format. When you save the file, it |
| |
will be written to disk as normal stream-source file. |
| |
|
| @cindex @file{.emacs} |
If you want to write blocks files, use @code{forth-blocks-mode}. It |
| To get all these benefits, add the following lines to your @file{.emacs} |
inherits all the features from @code{forth-mode}, plus some additions: |
| file: |
|
| |
|
| @example |
@itemize @bullet |
| (autoload 'forth-mode "gforth.el") |
@item |
| (setq auto-mode-alist (cons '("\\.fs\\'" . forth-mode) auto-mode-alist)) |
Files are written to disk in blocks file format. |
| @end example |
@item |
| |
Screen numbers are displayed in the mode line (enumerated beginning |
| |
with the value of `forth-block-base') |
| |
@item |
| |
Warnings are displayed when lines exceed 64 characters. |
| |
@item |
| |
The beginning of the currently edited block is marked with an |
| |
overlay-arrow. |
| |
@end itemize |
| |
|
| |
There are some restrictions you should be aware of. When you open a |
| |
blocks file that contains tabulator or newline characters, these |
| |
characters will be translated into spaces when the file is written |
| |
back to disk. If tabs or newlines are encountered during blocks file |
| |
reading, an error is output to the echo area. So have a look at the |
| |
`*Messages*' buffer, when Emacs' bell rings during reading. |
| |
|
| |
Please consult the docstring of @code{forth-blocks-mode} for more |
| |
information by typing @kbd{C-h v forth-blocks-mode}). |
| |
|
| @c ****************************************************************** |
@c ****************************************************************** |
| @node Image Files, Engine, Emacs and Gforth, Top |
@node Image Files, Engine, Emacs and Gforth, Top |
| Since Gforth is distributed under the GNU GPL, the newly created image |
Since Gforth is distributed under the GNU GPL, the newly created image |
| falls under the GNU GPL, too. In particular, this means that if you |
falls under the GNU GPL, too. In particular, this means that if you |
| distribute the image, you have to make all of the sources for the image |
distribute the image, you have to make all of the sources for the image |
| available, including those you wrote. For details see @ref{License, , |
available, including those you wrote. For details see @ref{Copying, , |
| GNU General Public License (Section 3)}. |
GNU General Public License (Section 3)}. |
| |
|
| If you create an image with @code{cross} (@pxref{cross.fs}), the image |
If you create an image with @code{cross} (@pxref{cross.fs}), the image |
| @section Image File Background |
@section Image File Background |
| @cindex image file background |
@cindex image file background |
| |
|
| Our Forth system consists not only of primitives, but also of |
Gforth consists not only of primitives (in the engine), but also of |
| definitions written in Forth. Since the Forth compiler itself belongs to |
definitions written in Forth. Since the Forth compiler itself belongs to |
| those definitions, it is not possible to start the system with the |
those definitions, it is not possible to start the system with the |
| primitives and the Forth source alone. Therefore we provide the Forth |
engine and the Forth source alone. Therefore we provide the Forth |
| code as an image file in nearly executable form. When Gforth starts up, |
code as an image file in nearly executable form. When Gforth starts up, |
| a C routine loads the image file into memory, optionally relocates the |
a C routine loads the image file into memory, optionally relocates the |
| addresses, then sets up the memory (stacks etc.) according to |
addresses, then sets up the memory (stacks etc.) according to |
| machine code in direct threaded implementations). As a workaround, |
machine code in direct threaded implementations). As a workaround, |
| compute these addresses at run-time with @code{>code-address} from the |
compute these addresses at run-time with @code{>code-address} from the |
| executions tokens of appropriate words (see the definitions of |
executions tokens of appropriate words (see the definitions of |
| @code{docol:} and friends in @file{kernel.fs}). |
@code{docol:} and friends in @file{kernel/getdoers.fs}). |
| |
|
| @item |
@item |
| On many architectures addresses are represented in machine code in some |
On many architectures addresses are represented in machine code in some |
| limit (e.g., 32) on the number of characters that may be specified on |
limit (e.g., 32) on the number of characters that may be specified on |
| the interpreter line.} secondly it is treated as a comment character by |
the interpreter line.} secondly it is treated as a comment character by |
| Gforth. Because of the second usage, a space is required between |
Gforth. Because of the second usage, a space is required between |
| @code{#!} and the path to the executable. |
@code{#!} and the path to the executable (moreover, some Unixes |
| |
require the sequence @code{#! /}). |
| |
|
| The disadvantage of this latter technique, compared with using |
The disadvantage of this latter technique, compared with using |
| @file{gforthmi}, is that it is slower; the Forth source code is compiled |
@file{gforthmi}, is that it is slightly slower; the Forth source code is |
| on-the-fly, each time the program is invoked. |
compiled on-the-fly, each time the program is invoked. |
| |
|
| |
|
| doc-#! |
doc-#! |
| |
|
| @cindex image file initialization sequence |
@cindex image file initialization sequence |
| @cindex initialization sequence of image file |
@cindex initialization sequence of image file |
| |
|
| You can add your own initialization to the startup sequence through the |
You can add your own initialization to the startup sequence of an image |
| deferred word @code{'cold}. @code{'cold} is invoked just before the |
through the deferred word @code{'cold}. @code{'cold} is invoked just |
| image-specific command line processing (by default, loading files and |
before the image-specific command line processing (i.e., loading files |
| evaluating (@code{-e}) strings) starts. |
and evaluating (@code{-e}) strings) starts. |
| |
|
| A sequence for adding your initialization usually looks like this: |
A sequence for adding your initialization usually looks like this: |
| |
|
| ; IS 'cold |
; IS 'cold |
| @end example |
@end example |
| |
|
| |
After @code{'cold}, Gforth processes the image options |
| |
(@pxref{Invoking Gforth}), and then it performs @code{bootmessage}, |
| |
another deferred word. This normally prints Gforth's startup message |
| |
and does nothing else. |
| |
|
| @cindex turnkey image files |
@cindex turnkey image files |
| @cindex image file, turnkey applications |
@cindex image file, turnkey applications |
| You can make a turnkey image by letting @code{'cold} execute a word |
So, if you want to make a turnkey image (i.e., an image for an |
| (your turnkey application) that never returns; instead, it exits Gforth |
application instead of an extended Forth system), you can do this in |
| via @code{bye} or @code{throw}. |
two ways: |
| |
|
| @cindex command-line arguments, access |
@itemize @bullet |
| @cindex arguments on the command line, access |
|
| You can access the (image-specific) command-line arguments through the |
|
| variables @code{argc} and @code{argv}. @code{arg} provides convenient |
|
| access to @code{argv}. |
|
| |
|
| If @code{'cold} exits normally, Gforth processes the command-line |
|
| arguments as files to be loaded and strings to be evaluated. Therefore, |
|
| @code{'cold} should remove the arguments it has used in this case. |
|
| |
|
| |
@item |
| |
If you want to do your interpretation of the OS command-line |
| |
arguments, hook into @code{'cold}. In that case you probably also |
| |
want to build the image with @code{gforthmi --application} |
| |
(@pxref{gforthmi}) to keep the engine from processing OS command line |
| |
options. You can then do your own command-line processing with |
| |
@code{next-arg} |
| |
|
| |
@item |
| |
If you want to have the normal Gforth processing of OS command-line |
| |
arguments, hook into @code{bootmessage}. |
| |
|
| doc-'cold |
@end itemize |
| doc-argc |
|
| doc-argv |
|
| doc-arg |
|
| |
|
| |
In either case, you probably do not want the word that you execute in |
| |
these hooks to exit normally, but use @code{bye} or @code{throw}. |
| |
Otherwise the Gforth startup process would continue and eventually |
| |
present the Forth command line to the user. |
| |
|
| |
doc-'cold |
| |
doc-bootmessage |
| |
|
| @c ****************************************************************** |
@c ****************************************************************** |
| @node Engine, Binding to System Library, Image Files, Top |
@node Engine, Cross Compiler, Image Files, Top |
| @chapter Engine |
@chapter Engine |
| @cindex engine |
@cindex engine |
| @cindex virtual machine |
@cindex virtual machine |
| Reading this chapter is not necessary for programming with Gforth. It |
Reading this chapter is not necessary for programming with Gforth. It |
| may be helpful for finding your way in the Gforth sources. |
may be helpful for finding your way in the Gforth sources. |
| |
|
| The ideas in this section have also been published in Bernd Paysan, |
The ideas in this section have also been published in the following |
| @cite{ANS fig/GNU/??? Forth} (in German), Forth-Tagung '93 and M. Anton |
papers: Bernd Paysan, @cite{ANS fig/GNU/??? Forth} (in German), |
| Ertl, @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl93.ps.Z, A |
Forth-Tagung '93; M. Anton Ertl, |
| Portable Forth Engine}}, EuroForth '93. |
@cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl93.ps.Z, A |
| |
Portable Forth Engine}}, EuroForth '93; M. Anton Ertl, |
| |
@cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl02.ps.gz, |
| |
Threaded code variations and optimizations (extended version)}}, |
| |
Forth-Tagung '02. |
| |
|
| @menu |
@menu |
| * Portability:: |
* Portability:: |
| Labels as Values, gcc.info, GNU C Manual}) makes direct and indirect |
Labels as Values, gcc.info, GNU C Manual}) makes direct and indirect |
| threading possible, its @code{long long} type (@pxref{Long Long, , |
threading possible, its @code{long long} type (@pxref{Long Long, , |
| Double-Word Integers, gcc.info, GNU C Manual}) corresponds to Forth's |
Double-Word Integers, gcc.info, GNU C Manual}) corresponds to Forth's |
| double numbers@footnote{Unfortunately, long longs are not implemented |
double numbers on many systems. GNU C is freely available on all |
| properly on all machines (e.g., on alpha-osf1, long longs are only 64 |
|
| bits, the same size as longs (and pointers), but they should be twice as |
|
| long according to @pxref{Long Long, , Double-Word Integers, gcc.info, GNU |
|
| C Manual}). So, we had to implement doubles in C after all. Still, on |
|
| most machines we can use long longs and achieve better performance than |
|
| with the emulation package.}. GNU C is available for free on all |
|
| important (and many unimportant) UNIX machines, VMS, 80386s running |
important (and many unimportant) UNIX machines, VMS, 80386s running |
| MS-DOS, the Amiga, and the Atari ST, so a Forth written in GNU C can run |
MS-DOS, the Amiga, and the Atari ST, so a Forth written in GNU C can run |
| on all these machines. |
on all these machines. |
| @menu |
@menu |
| * Scheduling:: |
* Scheduling:: |
| * Direct or Indirect Threaded?:: |
* Direct or Indirect Threaded?:: |
| |
* Dynamic Superinstructions:: |
| * DOES>:: |
* DOES>:: |
| @end menu |
@end menu |
| |
|
| sp[0]=n; |
sp[0]=n; |
| NEXT; |
NEXT; |
| @end example |
@end example |
| the @code{NEXT} comes strictly after the other code, i.e., there is nearly no |
the @code{NEXT} comes strictly after the other code, i.e., there is |
| scheduling. After a little thought the problem becomes clear: The |
nearly no scheduling. After a little thought the problem becomes clear: |
| compiler cannot know that @code{sp} and @code{ip} point to different |
The compiler cannot know that @code{sp} and @code{ip} point to different |
| addresses (and the version of @code{gcc} we used would not know it even |
addresses (and the version of @code{gcc} we used would not know it even |
| if it was possible), so it could not move the load of the cfa above the |
if it was possible), so it could not move the load of the cfa above the |
| store to the TOS. Indeed the pointers could be the same, if code on or |
store to the TOS. Indeed the pointers could be the same, if code on or |
| very near the top of stack were executed. In the interest of speed we |
very near the top of stack were executed. In the interest of speed we |
| chose to forbid this probably unused ``feature'' and helped the compiler |
chose to forbid this probably unused ``feature'' and helped the compiler |
| in scheduling: @code{NEXT} is divided into the loading part (@code{NEXT_P1}) |
in scheduling: @code{NEXT} is divided into several parts: |
| and the goto part (@code{NEXT_P2}). @code{+} now looks like: |
@code{NEXT_P0}, @code{NEXT_P1} and @code{NEXT_P2}). @code{+} now looks |
| |
like: |
| @example |
@example |
| |
NEXT_P0; |
| n=sp[0]+sp[1]; |
n=sp[0]+sp[1]; |
| sp++; |
sp++; |
| NEXT_P1; |
NEXT_P1; |
| sp[0]=n; |
sp[0]=n; |
| NEXT_P2; |
NEXT_P2; |
| @end example |
@end example |
| This can be scheduled optimally by the compiler. |
|
| |
|
| This division can be turned off with the switch @code{-DCISC_NEXT}. This |
There are various schemes that distribute the different operations of |
| switch is on by default on machines that do not profit from scheduling |
NEXT between these parts in several ways; in general, different schemes |
| (e.g., the 80386), in order to preserve registers. |
perform best on different processors. We use a scheme for most |
| |
architectures that performs well for most processors of this |
| |
architecture; in the future we may switch to benchmarking and chosing |
| |
the scheme on installation time. |
| |
|
| |
|
| @node Direct or Indirect Threaded?, DOES>, Scheduling, Threading |
@node Direct or Indirect Threaded?, Dynamic Superinstructions, Scheduling, Threading |
| @subsection Direct or Indirect Threaded? |
@subsection Direct or Indirect Threaded? |
| @cindex threading, direct or indirect? |
@cindex threading, direct or indirect? |
| |
|
| @cindex -DDIRECT_THREADED |
Threaded forth code consists of references to primitives (simple machine |
| Both! After packaging the nasty details in macro definitions we |
code routines like @code{+}) and to non-primitives (e.g., colon |
| realized that we could switch between direct and indirect threading by |
definitions, variables, constants); for a specific class of |
| simply setting a compilation flag (@code{-DDIRECT_THREADED}) and |
non-primitives (e.g., variables) there is one code routine (e.g., |
| defining a few machine-specific macros for the direct-threading case. |
@code{dovar}), but each variable needs a separate reference to its data. |
| On the Forth level we also offer access words that hide the |
|
| differences between the threading methods (@pxref{Threading Words}). |
Traditionally Forth has been implemented as indirect threaded code, |
| |
because this allows to use only one cell to reference a non-primitive |
| Indirect threading is implemented completely machine-independently. |
(basically you point to the data, and find the code address there). |
| Direct threading needs routines for creating jumps to the executable |
|
| code (e.g. to @code{docol} or @code{dodoes}). These routines are inherently |
@cindex primitive-centric threaded code |
| machine-dependent, but they do not amount to many source lines. Therefore, |
However, threaded code in Gforth (since 0.6.0) uses two cells for |
| even porting direct threading to a new machine requires little effort. |
non-primitives, one for the code address, and one for the data address; |
| |
the data pointer is an immediate argument for the virtual machine |
| @cindex --enable-indirect-threaded, configuration flag |
instruction represented by the code address. We call this |
| @cindex --enable-direct-threaded, configuration flag |
@emph{primitive-centric} threaded code, because all code addresses point |
| The default threading method is machine-dependent. You can enforce a |
to simple primitives. E.g., for a variable, the code address is for |
| specific threading method when building Gforth with the configuration |
@code{lit} (also used for integer literals like @code{99}). |
| flag @code{--enable-direct-threaded} or |
|
| @code{--enable-indirect-threaded}. Note that direct threading is not |
Primitive-centric threaded code allows us to use (faster) direct |
| supported on all machines. |
threading as dispatch method, completely portably (direct threaded code |
| |
in Gforth before 0.6.0 required architecture-specific code). It also |
| |
eliminates the performance problems related to I-cache consistency that |
| |
386 implementations have with direct threaded code, and allows |
| |
additional optimizations. |
| |
|
| |
@cindex hybrid direct/indirect threaded code |
| |
There is a catch, however: the @var{xt} parameter of @code{execute} can |
| |
occupy only one cell, so how do we pass non-primitives with their code |
| |
@emph{and} data addresses to them? Our answer is to use indirect |
| |
threaded dispatch for @code{execute} and other words that use a |
| |
single-cell xt. So, normal threaded code in colon definitions uses |
| |
direct threading, and @code{execute} and similar words, which dispatch |
| |
to xts on the data stack, use indirect threaded code. We call this |
| |
@emph{hybrid direct/indirect} threaded code. |
| |
|
| |
@cindex engines, gforth vs. gforth-fast vs. gforth-itc |
| |
@cindex gforth engine |
| |
@cindex gforth-fast engine |
| |
The engines @command{gforth} and @command{gforth-fast} use hybrid |
| |
direct/indirect threaded code. This means that with these engines you |
| |
cannot use @code{,} to compile an xt. Instead, you have to use |
| |
@code{compile,}. |
| |
|
| |
@cindex gforth-itc engine |
| |
If you want to compile xts with @code{,}, use @command{gforth-itc}. |
| |
This engine uses plain old indirect threaded code. It still compiles in |
| |
a primitive-centric style, so you cannot use @code{compile,} instead of |
| |
@code{,} (e.g., for producing tables of xts with @code{] word1 word2 |
| |
... [}). If you want to do that, you have to use @command{gforth-itc} |
| |
and execute @code{' , is compile,}. Your program can check if it is |
| |
running on a hybrid direct/indirect threaded engine or a pure indirect |
| |
threaded engine with @code{threading-method} (@pxref{Threading Words}). |
| |
|
| |
|
| |
@node Dynamic Superinstructions, DOES>, Direct or Indirect Threaded?, Threading |
| |
@subsection Dynamic Superinstructions |
| |
@cindex Dynamic superinstructions with replication |
| |
@cindex Superinstructions |
| |
@cindex Replication |
| |
|
| |
The engines @command{gforth} and @command{gforth-fast} use another |
| |
optimization: Dynamic superinstructions with replication. As an |
| |
example, consider the following colon definition: |
| |
|
| |
@example |
| |
: squared ( n1 -- n2 ) |
| |
dup * ; |
| |
@end example |
| |
|
| |
Gforth compiles this into the threaded code sequence |
| |
|
| |
@example |
| |
dup |
| |
* |
| |
;s |
| |
@end example |
| |
|
| |
In normal direct threaded code there is a code address occupying one |
| |
cell for each of these primitives. Each code address points to a |
| |
machine code routine, and the interpreter jumps to this machine code in |
| |
order to execute the primitive. The routines for these three |
| |
primitives are (in @command{gforth-fast} on the 386): |
| |
|
| |
@example |
| |
Code dup |
| |
( $804B950 ) add esi , # -4 \ $83 $C6 $FC |
| |
( $804B953 ) add ebx , # 4 \ $83 $C3 $4 |
| |
( $804B956 ) mov dword ptr 4 [esi] , ecx \ $89 $4E $4 |
| |
( $804B959 ) jmp dword ptr FC [ebx] \ $FF $63 $FC |
| |
end-code |
| |
Code * |
| |
( $804ACC4 ) mov eax , dword ptr 4 [esi] \ $8B $46 $4 |
| |
( $804ACC7 ) add esi , # 4 \ $83 $C6 $4 |
| |
( $804ACCA ) add ebx , # 4 \ $83 $C3 $4 |
| |
( $804ACCD ) imul ecx , eax \ $F $AF $C8 |
| |
( $804ACD0 ) jmp dword ptr FC [ebx] \ $FF $63 $FC |
| |
end-code |
| |
Code ;s |
| |
( $804A693 ) mov eax , dword ptr [edi] \ $8B $7 |
| |
( $804A695 ) add edi , # 4 \ $83 $C7 $4 |
| |
( $804A698 ) lea ebx , dword ptr 4 [eax] \ $8D $58 $4 |
| |
( $804A69B ) jmp dword ptr FC [ebx] \ $FF $63 $FC |
| |
end-code |
| |
@end example |
| |
|
| |
With dynamic superinstructions and replication the compiler does not |
| |
just lay down the threaded code, but also copies the machine code |
| |
fragments, usually without the jump at the end. |
| |
|
| |
@example |
| |
( $4057D27D ) add esi , # -4 \ $83 $C6 $FC |
| |
( $4057D280 ) add ebx , # 4 \ $83 $C3 $4 |
| |
( $4057D283 ) mov dword ptr 4 [esi] , ecx \ $89 $4E $4 |
| |
( $4057D286 ) mov eax , dword ptr 4 [esi] \ $8B $46 $4 |
| |
( $4057D289 ) add esi , # 4 \ $83 $C6 $4 |
| |
( $4057D28C ) add ebx , # 4 \ $83 $C3 $4 |
| |
( $4057D28F ) imul ecx , eax \ $F $AF $C8 |
| |
( $4057D292 ) mov eax , dword ptr [edi] \ $8B $7 |
| |
( $4057D294 ) add edi , # 4 \ $83 $C7 $4 |
| |
( $4057D297 ) lea ebx , dword ptr 4 [eax] \ $8D $58 $4 |
| |
( $4057D29A ) jmp dword ptr FC [ebx] \ $FF $63 $FC |
| |
@end example |
| |
|
| |
Only when a threaded-code control-flow change happens (e.g., in |
| |
@code{;s}), the jump is appended. This optimization eliminates many of |
| |
these jumps and makes the rest much more predictable. The speedup |
| |
depends on the processor and the application; on the Athlon and Pentium |
| |
III this optimization typically produces a speedup by a factor of 2. |
| |
|
| |
The code addresses in the direct-threaded code are set to point to the |
| |
appropriate points in the copied machine code, in this example like |
| |
this: |
| |
|
| @node DOES>, , Direct or Indirect Threaded?, Threading |
@example |
| |
primitive code address |
| |
dup $4057D27D |
| |
* $4057D286 |
| |
;s $4057D292 |
| |
@end example |
| |
|
| |
Thus there can be threaded-code jumps to any place in this piece of |
| |
code. This also simplifies decompilation quite a bit. |
| |
|
| |
@cindex --no-dynamic command-line option |
| |
@cindex --no-super command-line option |
| |
You can disable this optimization with @option{--no-dynamic}. You can |
| |
use the copying without eliminating the jumps (i.e., dynamic |
| |
replication, but without superinstructions) with @option{--no-super}; |
| |
this gives the branch prediction benefit alone; the effect on |
| |
performance depends on the CPU; on the Athlon and Pentium III the |
| |
speedup is a little less than for dynamic superinstructions with |
| |
replication. |
| |
|
| |
@cindex patching threaded code |
| |
One use of these options is if you want to patch the threaded code. |
| |
With superinstructions, many of the dispatch jumps are eliminated, so |
| |
patching often has no effect. These options preserve all the dispatch |
| |
jumps. |
| |
|
| |
@cindex --dynamic command-line option |
| |
On some machines dynamic superinstructions are disabled by default, |
| |
because it is unsafe on these machines. However, if you feel |
| |
adventurous, you can enable it with @option{--dynamic}. |
| |
|
| |
@node DOES>, , Dynamic Superinstructions, Threading |
| @subsection DOES> |
@subsection DOES> |
| @cindex @code{DOES>} implementation |
@cindex @code{DOES>} implementation |
| |
|
| @cindex @code{DOES>}-code |
@cindex @code{DOES>}-code |
| One of the most complex parts of a Forth engine is @code{dodoes}, i.e., |
One of the most complex parts of a Forth engine is @code{dodoes}, i.e., |
| the chunk of code executed by every word defined by a |
the chunk of code executed by every word defined by a |
| @code{CREATE}...@code{DOES>} pair. The main problem here is: How to find |
@code{CREATE}...@code{DOES>} pair; actually with primitive-centric code, |
| the Forth code to be executed, i.e. the code after the |
this is only needed if the xt of the word is @code{execute}d. The main |
| @code{DOES>} (the @code{DOES>}-code)? There are two solutions: |
problem here is: How to find the Forth code to be executed, i.e. the |
| |
code after the @code{DOES>} (the @code{DOES>}-code)? There are two |
| |
solutions: |
| |
|
| In fig-Forth the code field points directly to the @code{dodoes} and the |
In fig-Forth the code field points directly to the @code{dodoes} and the |
| @code{DOES>}-code address is stored in the cell after the code address (i.e. at |
@code{DOES>}-code address is stored in the cell after the code address |
| @code{@i{CFA} cell+}). It may seem that this solution is illegal in |
(i.e. at @code{@i{CFA} cell+}). It may seem that this solution is |
| the Forth-79 and all later standards, because in fig-Forth this address |
illegal in the Forth-79 and all later standards, because in fig-Forth |
| lies in the body (which is illegal in these standards). However, by |
this address lies in the body (which is illegal in these |
| making the code field larger for all words this solution becomes legal |
standards). However, by making the code field larger for all words this |
| again. We use this approach for the indirect threaded version and for |
solution becomes legal again. We use this approach. Leaving a cell |
| direct threading on some machines. Leaving a cell unused in most words |
unused in most words is a bit wasteful, but on the machines we are |
| is a bit wasteful, but on the machines we are targeting this is hardly a |
targeting this is hardly a problem. |
| problem. The other reason for having a code field size of two cells is |
|
| to avoid having different image files for direct and indirect threaded |
|
| systems (direct threaded systems require two-cell code fields on many |
|
| machines). |
|
| |
|
| @cindex @code{DOES>}-handler |
|
| The other approach is that the code field points or jumps to the cell |
|
| after @code{DOES>}. In this variant there is a jump to @code{dodoes} at |
|
| this address (the @code{DOES>}-handler). @code{dodoes} can then get the |
|
| @code{DOES>}-code address by computing the code address, i.e., the address of |
|
| the jump to @code{dodoes}, and add the length of that jump field. A variant of |
|
| this is to have a call to @code{dodoes} after the @code{DOES>}; then the |
|
| return address (which can be found in the return register on RISCs) is |
|
| the @code{DOES>}-code address. Since the two cells available in the code field |
|
| are used up by the jump to the code address in direct threading on many |
|
| architectures, we use this approach for direct threading on these |
|
| architectures. We did not want to add another cell to the code field. |
|
| |
|
| @node Primitives, Performance, Threading, Engine |
@node Primitives, Performance, Threading, Engine |
| @section Primitives |
@section Primitives |
| @cindex primitives, automatic generation |
@cindex primitives, automatic generation |
| |
|
| @cindex @file{prims2x.fs} |
@cindex @file{prims2x.fs} |
| |
|
| Since the primitives are implemented in a portable language, there is no |
Since the primitives are implemented in a portable language, there is no |
| longer any need to minimize the number of primitives. On the contrary, |
longer any need to minimize the number of primitives. On the contrary, |
| having many primitives has an advantage: speed. In order to reduce the |
having many primitives has an advantage: speed. In order to reduce the |
| number of errors in primitives and to make programming them easier, we |
number of errors in primitives and to make programming them easier, we |
| provide a tool, the primitive generator (@file{prims2x.fs}), that |
provide a tool, the primitive generator (@file{prims2x.fs} aka Vmgen, |
| automatically generates most (and sometimes all) of the C code for a |
@pxref{Top, Vmgen, Introduction, vmgen, Vmgen}), that automatically |
| primitive from the stack effect notation. The source for a primitive |
generates most (and sometimes all) of the C code for a primitive from |
| has the following form: |
the stack effect notation. The source for a primitive has the following |
| |
form: |
| |
|
| @cindex primitive source format |
@cindex primitive source format |
| @format |
@format |
| @example |
@example |
| I_plus: /* + ( n1 n2 -- n ) */ /* label, stack effect */ |
I_plus: /* + ( n1 n2 -- n ) */ /* label, stack effect */ |
| /* */ /* documentation */ |
/* */ /* documentation */ |
| |
NAME("+") /* debugging output (with -DDEBUG) */ |
| @{ |
@{ |
| DEF_CA /* definition of variable ca (indirect threading) */ |
DEF_CA /* definition of variable ca (indirect threading) */ |
| Cell n1; /* definitions of variables */ |
Cell n1; /* definitions of variables */ |
| Cell n2; |
Cell n2; |
| Cell n; |
Cell n; |
| |
NEXT_P0; /* NEXT part 0 */ |
| n1 = (Cell) sp[1]; /* input */ |
n1 = (Cell) sp[1]; /* input */ |
| n2 = (Cell) TOS; |
n2 = (Cell) TOS; |
| sp += 1; /* stack adjustment */ |
sp += 1; /* stack adjustment */ |
| NAME("+") /* debugging output (with -DDEBUG) */ |
|
| @{ |
@{ |
| n = n1+n2; /* C code taken from the source */ |
n = n1+n2; /* C code taken from the source */ |
| @} |
@} |
| account, most notably @code{?dup}, but also words that do not (always) |
account, most notably @code{?dup}, but also words that do not (always) |
| fall through to @code{NEXT}. |
fall through to @code{NEXT}. |
| |
|
| |
For more information |
| |
|
| @node TOS Optimization, Produced code, Automatic Generation, Primitives |
@node TOS Optimization, Produced code, Automatic Generation, Primitives |
| @subsection TOS Optimization |
@subsection TOS Optimization |
| @cindex TOS optimization for primitives |
@cindex TOS optimization for primitives |
| @cindex @file{engine.s} |
@cindex @file{engine.s} |
| To see what assembly code is produced for the primitives on your machine |
To see what assembly code is produced for the primitives on your machine |
| with your compiler and your flag settings, type @code{make engine.s} and |
with your compiler and your flag settings, type @code{make engine.s} and |
| look at the resulting file @file{engine.s}. |
look at the resulting file @file{engine.s}. Alternatively, you can also |
| |
disassemble the code of primitives with @code{see} on some architectures. |
| |
|
| @node Performance, , Primitives, Engine |
@node Performance, , Primitives, Engine |
| @section Performance |
@section Performance |
| @cindex Gforth performance |
@cindex Gforth performance |
| |
|
| On RISCs the Gforth engine is very close to optimal; i.e., it is usually |
On RISCs the Gforth engine is very close to optimal; i.e., it is usually |
| impossible to write a significantly faster engine. |
impossible to write a significantly faster threaded-code engine. |
| |
|
| On register-starved machines like the 386 architecture processors |
On register-starved machines like the 386 architecture processors |
| improvements are possible, because @code{gcc} does not utilize the |
improvements are possible, because @code{gcc} does not utilize the |
| with gcc-2.95 and gforth-0.4.9; now the most important virtual machine |
with gcc-2.95 and gforth-0.4.9; now the most important virtual machine |
| registers fit in real registers (and we can even afford to use the TOS |
registers fit in real registers (and we can even afford to use the TOS |
| optimization), resulting in a speedup of 1.14 on the sieve over the |
optimization), resulting in a speedup of 1.14 on the sieve over the |
| earlier results. |
earlier results. And dynamic superinstructions provide another speedup |
| |
(but only around a factor 1.2 on the 486). |
| |
|
| @cindex Win32Forth performance |
@cindex Win32Forth performance |
| @cindex NT Forth performance |
@cindex NT Forth performance |
| @cindex ThisForth performance |
@cindex ThisForth performance |
| @cindex PFE performance |
@cindex PFE performance |
| @cindex TILE performance |
@cindex TILE performance |
| The potential advantage of assembly language implementations |
The potential advantage of assembly language implementations is not |
| is not necessarily realized in complete Forth systems: We compared |
necessarily realized in complete Forth systems: We compared Gforth-0.5.9 |
| Gforth-0.4.9 (direct threaded, compiled with @code{gcc-2.95.1} and |
(direct threaded, compiled with @code{gcc-2.95.1} and |
| @code{-DFORCE_REG}) with Win32Forth 1.2093, LMI's NT Forth (Beta, May |
@code{-DFORCE_REG}) with Win32Forth 1.2093 (newer versions are |
| 1994) and Eforth (with and without peephole (aka pinhole) optimization |
reportedly much faster), LMI's NT Forth (Beta, May 1994) and Eforth |
| of the threaded code); all these systems were written in assembly |
(with and without peephole (aka pinhole) optimization of the threaded |
| language. We also compared Gforth with three systems written in C: |
code); all these systems were written in assembly language. We also |
| PFE-0.9.14 (compiled with @code{gcc-2.6.3} with the default |
compared Gforth with three systems written in C: PFE-0.9.14 (compiled |
| configuration for Linux: @code{-O2 -fomit-frame-pointer -DUSE_REGS |
with @code{gcc-2.6.3} with the default configuration for Linux: |
| -DUNROLL_NEXT}), ThisForth Beta (compiled with @code{gcc-2.6.3 -O3 |
@code{-O2 -fomit-frame-pointer -DUSE_REGS -DUNROLL_NEXT}), ThisForth |
| -fomit-frame-pointer}; ThisForth employs peephole optimization of the |
Beta (compiled with @code{gcc-2.6.3 -O3 -fomit-frame-pointer}; ThisForth |
| threaded code) and TILE (compiled with @code{make opt}). We benchmarked |
employs peephole optimization of the threaded code) and TILE (compiled |
| Gforth, PFE, ThisForth and TILE on a 486DX2/66 under Linux. Kenneth |
with @code{make opt}). We benchmarked Gforth, PFE, ThisForth and TILE on |
| O'Heskin kindly provided the results for Win32Forth and NT Forth on a |
a 486DX2/66 under Linux. Kenneth O'Heskin kindly provided the results |
| 486DX2/66 with similar memory performance under Windows NT. Marcel |
for Win32Forth and NT Forth on a 486DX2/66 with similar memory |
| Hendrix ported Eforth to Linux, then extended it to run the benchmarks, |
performance under Windows NT. Marcel Hendrix ported Eforth to Linux, |
| added the peephole optimizer, ran the benchmarks and reported the |
then extended it to run the benchmarks, added the peephole optimizer, |
| results. |
ran the benchmarks and reported the results. |
| |
|
| We used four small benchmarks: the ubiquitous Sieve; bubble-sorting and |
We used four small benchmarks: the ubiquitous Sieve; bubble-sorting and |
| matrix multiplication come from the Stanford integer benchmarks and have |
matrix multiplication come from the Stanford integer benchmarks and have |
| @example |
@example |
| relative Win32- NT eforth This- |
relative Win32- NT eforth This- |
| time Gforth Forth Forth eforth +opt PFE Forth TILE |
time Gforth Forth Forth eforth +opt PFE Forth TILE |
| sieve 1.00 1.58 1.30 1.58 0.97 1.80 3.63 9.79 |
sieve 1.00 2.16 1.78 2.16 1.32 2.46 4.96 13.37 |
| bubble 1.00 1.55 1.67 1.75 1.04 1.78 4.59 |
bubble 1.00 1.93 2.07 2.18 1.29 2.21 5.70 |
| matmul 1.00 1.67 1.53 1.66 0.84 1.79 4.63 |
matmul 1.00 1.92 1.76 1.90 0.96 2.06 5.32 |
| fib 1.00 1.75 1.53 1.40 0.99 1.99 3.43 4.93 |
fib 1.00 2.32 2.03 1.86 1.31 2.64 4.55 6.54 |
| @end example |
@end example |
| |
|
| You may be quite surprised by the good performance of Gforth when |
You may be quite surprised by the good performance of Gforth when |
| computes the actual addresses at run time, resulting in two address |
computes the actual addresses at run time, resulting in two address |
| computations per @code{NEXT} (@pxref{Image File Background}). |
computations per @code{NEXT} (@pxref{Image File Background}). |
| |
|
| Only Eforth with the peephole optimizer performs comparable to |
|
| Gforth. The speedups achieved with peephole optimization of threaded |
|
| code are quite remarkable. Adding a peephole optimizer to Gforth should |
|
| cause similar speedups. |
|
| |
|
| The speedup of Gforth over PFE, ThisForth and TILE can be easily |
The speedup of Gforth over PFE, ThisForth and TILE can be easily |
| explained with the self-imposed restriction of the latter systems to |
explained with the self-imposed restriction of the latter systems to |
| standard C, which makes efficient threading impossible (however, the |
standard C, which makes efficient threading impossible (however, the |
| with the version of @code{gcc} used. E.g., @code{gcc-2.5.8} failed to |
with the version of @code{gcc} used. E.g., @code{gcc-2.5.8} failed to |
| allocate any of the virtual machine registers into real machine |
allocate any of the virtual machine registers into real machine |
| registers by itself and would not work correctly with explicit register |
registers by itself and would not work correctly with explicit register |
| declarations, giving a 1.5 times slower engine (on a 486DX2/66 running |
declarations, giving a significantly slower engine (on a 486DX2/66 |
| the Sieve) than the one measured above. |
running the Sieve) than the one measured above. |
| |
|
| Note that there have been several releases of Win32Forth since the |
Note that there have been several releases of Win32Forth since the |
| release presented here, so the results presented above may have little |
release presented here, so the results presented above may have little |
| Maierhofer (presented at EuroForth '95), an indirect threaded version of |
Maierhofer (presented at EuroForth '95), an indirect threaded version of |
| Gforth is compared with Win32Forth, NT Forth, PFE, ThisForth, and |
Gforth is compared with Win32Forth, NT Forth, PFE, ThisForth, and |
| several native code systems; that version of Gforth is slower on a 486 |
several native code systems; that version of Gforth is slower on a 486 |
| than the direct threaded version used here. You can find a newer version |
than the version used here. You can find a newer version of these |
| of these measurements at |
measurements at |
| @uref{http://www.complang.tuwien.ac.at/forth/performance.html}. You can |
@uref{http://www.complang.tuwien.ac.at/forth/performance.html}. You can |
| find numbers for Gforth on various machines in @file{Benchres}. |
find numbers for Gforth on various machines in @file{Benchres}. |
| |
|
| @c ****************************************************************** |
@c ****************************************************************** |
| @node Binding to System Library, Cross Compiler, Engine, Top |
@c @node Binding to System Library, Cross Compiler, Engine, Top |
| @chapter Binding to System Library |
@c @chapter Binding to System Library |
| |
|
| @node Cross Compiler, Bugs, Binding to System Library, Top |
@c **************************************************************** |
| |
@node Cross Compiler, Bugs, Engine, Top |
| @chapter Cross Compiler |
@chapter Cross Compiler |
| @cindex @file{cross.fs} |
@cindex @file{cross.fs} |
| @cindex cross-compiler |
@cindex cross-compiler |
| code you are compiling is typically for a different computer than the |
code you are compiling is typically for a different computer than the |
| one you are compiling on. |
one you are compiling on. |
| |
|
| |
@c anton: This chapter is somewhat different from waht I would expect: I |
| |
@c would expect an explanation of the cross language and how to create an |
| |
@c application image with it. The section explains some aspects of |
| |
@c creating a Gforth kernel. |
| |
|
| The Makefile is already set up to allow you to create kernels for new |
The Makefile is already set up to allow you to create kernels for new |
| architectures with a simple make command. The generic kernels using the |
architectures with a simple make command. The generic kernels using the |
| GCC compiled virtual machine are created in the normal build process |
GCC compiled virtual machine are created in the normal build process |
| |
|
| There are some optional features, if you define your own primitives, |
There are some optional features, if you define your own primitives, |
| have an assembler, or need special, nonstandard preparation to make the |
have an assembler, or need special, nonstandard preparation to make the |
| boot process work. @code{asm-include} include an assembler, |
boot process work. @code{asm-include} includes an assembler, |
| @code{prims-include} includes primitives, and @code{>boot} prepares for |
@code{prims-include} includes primitives, and @code{>boot} prepares for |
| booting. |
booting. |
| |
|
| @end example |
@end example |
| |
|
| These words are used as sort of macro during the cross compilation in |
These words are used as sort of macro during the cross compilation in |
| the file @file{kernel/main.fs}. Instead of using this macros, it would |
the file @file{kernel/main.fs}. Instead of using these macros, it would |
| be possible --- but more complicated --- to write a new kernel project |
be possible --- but more complicated --- to write a new kernel project |
| file, too. |
file, too. |
| |
|
| |
|
| Known bugs are described in the file @file{BUGS} in the Gforth distribution. |
Known bugs are described in the file @file{BUGS} in the Gforth distribution. |
| |
|
| If you find a bug, please send a bug report to |
If you find a bug, please submit a bug report through |
| @email{bug-gforth@@gnu.org}. A bug report should include this |
@uref{https://savannah.gnu.org/bugs/?func=addbug&group=gforth}. |
| information: |
|
| |
|
| @itemize @bullet |
@itemize @bullet |
| @item |
@item |
| |
A program (or a sequence of keyboard commands) that reproduces the bug. |
| |
@item |
| |
A description of what you think constitutes the buggy behaviour. |
| |
@item |
| The Gforth version used (it is announced at the start of an |
The Gforth version used (it is announced at the start of an |
| interactive Gforth session). |
interactive Gforth session). |
| @item |
@item |
| The machine and operating system (on Unix |
The machine and operating system (on Unix |
| systems @code{uname -a} will report this information). |
systems @code{uname -a} will report this information). |
| @item |
@item |
| The installation options (send the file @file{config.status}). |
The installation options (you can find the configure options at the |
| |
start of @file{config.status}) and configuration (@code{configure} |
| |
output or @file{config.cache}). |
| @item |
@item |
| A complete list of changes (if any) you (or your installer) have made to the |
A complete list of changes (if any) you (or your installer) have made to the |
| Gforth sources. |
Gforth sources. |
| @item |
|
| A program (or a sequence of keyboard commands) that reproduces the bug. |
|
| @item |
|
| A description of what you think constitutes the buggy behaviour. |
|
| @end itemize |
@end itemize |
| |
|
| For a thorough guide on reporting bugs read @ref{Bug Reporting, , How |
For a thorough guide on reporting bugs read @ref{Bug Reporting, , How |
| @cindex contributors to Gforth |
@cindex contributors to Gforth |
| |
|
| The Gforth project was started in mid-1992 by Bernd Paysan and Anton |
The Gforth project was started in mid-1992 by Bernd Paysan and Anton |
| Ertl. The third major author was Jens Wilke. Lennart Benschop (who was |
Ertl. The third major author was Jens Wilke. Neal Crook contributed a |
| one of Gforth's first users, in mid-1993) and Stuart Ramsden inspired us |
lot to the manual. Assemblers and disassemblers were contributed by |
| with their continuous feedback. Lennart Benshop contributed |
Andrew McKewan, Christian Pirker, Bernd Thallner, and Michal Revucky. |
| @file{glosgen.fs}, while Stuart Ramsden has been working on automatic |
Lennart Benschop (who was one of Gforth's first users, in mid-1993) |
| support for calling C libraries. Helpful comments also came from Paul |
and Stuart Ramsden inspired us with their continuous feedback. Lennart |
| Kleinrubatscher, Christian Pirker, Dirk Zoller, Marcel Hendrix, John |
Benshop contributed @file{glosgen.fs}, while Stuart Ramsden has been |
| Wavrik, Barrie Stott, Marc de Groot, Jorge Acerada, Bruce Hoyt, and |
working on automatic support for calling C libraries. Helpful comments |
| Robert Epprecht. Since the release of Gforth-0.2.1 there were also |
also came from Paul Kleinrubatscher, Christian Pirker, Dirk Zoller, |
| helpful comments from many others; thank you all, sorry for not listing |
Marcel Hendrix, John Wavrik, Barrie Stott, Marc de Groot, Jorge |
| you here (but digging through my mailbox to extract your names is on my |
Acerada, Bruce Hoyt, Robert Epprecht, Dennis Ruffer and David |
| to-do list). Since the release of Gforth-0.4.0 Neal Crook worked on the |
N. Williams. Since the release of Gforth-0.2.1 there were also helpful |
| manual. |
comments from many others; thank you all, sorry for not listing you |
| |
here (but digging through my mailbox to extract your names is on my |
| |
to-do list). |
| |
|
| Gforth also owes a lot to the authors of the tools we used (GCC, CVS, |
Gforth also owes a lot to the authors of the tools we used (GCC, CVS, |
| and autoconf, among others), and to the creators of the Internet: Gforth |
and autoconf, among others), and to the creators of the Internet: Gforth |
| @section Pedigree |
@section Pedigree |
| @cindex pedigree of Gforth |
@cindex pedigree of Gforth |
| |
|
| Gforth descends from bigFORTH (1993) and fig-Forth. Gforth and PFE (by |
Gforth descends from bigFORTH (1993) and fig-Forth. Of course, a |
| Dirk Zoller) will cross-fertilize each other. Of course, a significant |
significant part of the design of Gforth was prescribed by ANS Forth. |
| part of the design of Gforth was prescribed by ANS Forth. |
|
| |
|
| Bernd Paysan wrote bigFORTH, a descendent from TurboForth, an unreleased |
Bernd Paysan wrote bigFORTH, a descendent from TurboForth, an unreleased |
| 32 bit native code version of VolksForth for the Atari ST, written |
32 bit native code version of VolksForth for the Atari ST, written |
| mostly by Dietrich Weineck. |
mostly by Dietrich Weineck. |
| |
|
| VolksForth descends from F83. It was written by Klaus Schleisiek, Bernd |
VolksForth was written by Klaus Schleisiek, Bernd Pennemann, Georg |
| Pennemann, Georg Rehfeld and Dietrich Weineck for the C64 (called |
Rehfeld and Dietrich Weineck for the C64 (called UltraForth there) in |
| UltraForth there) in the mid-80s and ported to the Atari ST in 1986. |
the mid-80s and ported to the Atari ST in 1986. It descends from fig-Forth. |
| |
|
| Henry Laxen and Mike Perry wrote F83 as a model implementation of the |
@c Henry Laxen and Mike Perry wrote F83 as a model implementation of the |
| Forth-83 standard. !! Pedigree? When? |
@c Forth-83 standard. !! Pedigree? When? |
| |
|
| A team led by Bill Ragsdale implemented fig-Forth on many processors in |
A team led by Bill Ragsdale implemented fig-Forth on many processors in |
| 1979. Robert Selzer and Bill Ragsdale developed the original |
1979. Robert Selzer and Bill Ragsdale developed the original |
| who discovered (as he puts it) Forth during the late 60s. The first full |
who discovered (as he puts it) Forth during the late 60s. The first full |
| Forth existed in 1971. |
Forth existed in 1971. |
| |
|
| A part of the information in this section comes from @cite{The Evolution |
A part of the information in this section comes from |
| of Forth} by Elizabeth D. Rather, Donald R. Colburn and Charles |
@cite{@uref{http://www.forth.com/Content/History/History1.htm,The |
| H. Moore, presented at the HOPL-II conference and preprinted in SIGPLAN |
Evolution of Forth}} by Elizabeth D. Rather, Donald R. Colburn and |
| Notices 28(3), 1993. You can find more historical and genealogical |
Charles H. Moore, presented at the HOPL-II conference and preprinted |
| information about Forth there. |
in SIGPLAN Notices 28(3), 1993. You can find more historical and |
| |
genealogical information about Forth there. For a more general (and |
| |
graphical) Forth family tree look see |
| |
@cite{@uref{http://www.complang.tuwien.ac.at/forth/family-tree/}, |
| |
Forth Family Tree and Timeline}. |
| |
|
| @node Forth-related information, Word Index, Origin, Top |
@c ------------------------------------------------------------------ |
| |
@node Forth-related information, Licenses, Origin, Top |
| @appendix Other Forth-related information |
@appendix Other Forth-related information |
| @cindex Forth-related information |
@cindex Forth-related information |
| |
|
| @menu |
@c anton: I threw most of this stuff out, because it can be found through |
| * Internet resources:: |
@c the FAQ and the FAQ is more likely to be up-to-date. |
| * Books:: |
|
| * The Forth Interest Group:: |
|
| * Conferences:: |
|
| @end menu |
|
| |
|
| |
|
| @node Internet resources, Books, Forth-related information, Forth-related information |
|
| @section Internet resources |
|
| @cindex internet resources |
|
| |
|
| @cindex comp.lang.forth |
@cindex comp.lang.forth |
| @cindex frequently asked questions |
@cindex frequently asked questions |
| There is an active news group (comp.lang.forth) discussing Forth and |
There is an active news group (comp.lang.forth) discussing Forth |
| Forth-related issues. A frequently-asked-questions (FAQ) list |
(including Gforth) and Forth-related issues. Its |
| is posted to the news group regularly, and archived at these sites: |
@uref{http://www.complang.tuwien.ac.at/forth/faq/faq-general-2.html,FAQs} |
| |
(frequently asked questions and their answers) contains a lot of |
| @itemize @bullet |
information on Forth. You should read it before posting to |
| @item |
comp.lang.forth. |
| @uref{ftp://rtfm.mit.edu/pub/usenet-by-group/comp.lang.forth/} |
|
| @item |
|
| @uref{ftp://ftp.forth.org/pub/Forth/FAQ/} |
|
| @end itemize |
|
| |
|
| The FAQ list should be considered mandatory reading before posting to |
|
| the news group. |
|
| |
|
| Here are some other web sites holding Forth-related material: |
|
| |
|
| @itemize @bullet |
|
| @item |
|
| @uref{http://www.taygeta.com/forth.html} -- Skip Carter's Forth pages. |
|
| @item |
|
| @uref{http://www.jwdt.com/~paysan/gforth.html} -- the Gforth home page. |
|
| @item |
|
| @uref{http://www.minerva.com/uathena.htm} -- home of ANS Forth Standard. |
|
| @item |
|
| @uref{http://dec.bournemouth.ac.uk/forth/index.html} -- the Forth |
|
| Research page, including links to the Journal of Forth Application and |
|
| Research (JFAR) and a searchable Forth bibliography. |
|
| @end itemize |
|
| |
|
| |
|
| @node Books, The Forth Interest Group, Internet resources, Forth-related information |
The ANS Forth standard is most usable in its |
| @section Books |
@uref{http://www.taygeta.com/forth/dpans.html, HTML form}. |
| @cindex books on Forth |
|
| |
|
| As the Standard is relatively new, there are not many books out yet. It |
@c --------------------------------------------------- |
| is not recommended to learn Forth by using Gforth and a book that is not |
@node Licenses, Word Index, Forth-related information, Top |
| written for ANS Forth, as you will not know your mistakes from the |
@appendix Licenses |
| deviations of the book. However, books based on the Forth-83 standard |
|
| should be ok, because ANS Forth is primarily an extension of Forth-83. |
|
| Refer to the Forth FAQ for details of Forth-related books. |
|
| |
|
| @cindex standard document for ANS Forth |
@menu |
| @cindex ANS Forth document |
* GNU Free Documentation License:: License for copying this manual. |
| The definite reference if you want to write ANS Forth programs is, of |
* Copying:: GPL (for copying this software). |
| course, the ANS Forth document. It is available in printed form from the |
@end menu |
| National Standards Institute Sales Department (Tel.: USA (212) 642-4900; |
|
| Fax.: USA (212) 302-1286) as document @cite{X3.215-1994} for about |
|
| $200. You can also get it from Global Engineering Documents (Tel.: USA |
|
| (800) 854-7179; Fax.: (303) 843-9880) for about $300. |
|
| |
|
| @cite{dpANS6}, the last draft of the standard, which was then submitted |
|
| to ANSI for publication is available electronically and for free in some |
|
| MS Word format, and it has been converted to HTML |
|
| (@uref{http://www.taygeta.com/forth/dpans.html}; this HTML version also |
|
| includes the answers to Requests for Interpretation (RFIs). Some |
|
| pointers to these versions can be found through |
|
| @*@uref{http://www.complang.tuwien.ac.at/projects/forth.html}. |
|
| |
|
| |
|
| @node The Forth Interest Group, Conferences, Books, Forth-related information |
|
| @section The Forth Interest Group |
|
| @cindex Forth interest group (FIG) |
|
| |
|
| The Forth Interest Group (FIG) is a world-wide, non-profit, |
|
| member-supported organisation. It publishes a regular magazine, |
|
| @var{FORTH Dimensions}, and offers other benefits of membership. You can |
|
| contact the FIG through their office email address: |
|
| @email{office@@forth.org} or by visiting their web site at |
|
| @uref{http://www.forth.org/}. This web site also includes links to FIG |
|
| chapters in other countries and American cities |
|
| (@uref{http://www.forth.org/chapters.html}). |
|
| |
|
| @node Conferences, , The Forth Interest Group, Forth-related information |
@node GNU Free Documentation License, Copying, Licenses, Licenses |
| @section Conferences |
@appendixsec GNU Free Documentation License |
| @cindex Conferences |
@include fdl.texi |
| |
|
| There are several regular conferences related to Forth. They are all |
@node Copying, , GNU Free Documentation License, Licenses |
| well-publicised in @var{FORTH Dimensions} and on the comp.lang.forth |
@appendixsec GNU GENERAL PUBLIC LICENSE |
| news group: |
@include gpl.texi |
| |
|
| @itemize @bullet |
|
| @item |
|
| FORML -- the Forth modification laboratory convenes every year near |
|
| Monterey, California. |
|
| @item |
|
| The Rochester Forth Conference -- an annual conference traditionally |
|
| held in Rochester, New York. |
|
| @item |
|
| EuroForth -- this European conference takes place annually. |
|
| @end itemize |
|
| |
|
| |
|
| @node Word Index, Name Index, Forth-related information, Top |
@c ------------------------------------------------------------------ |
| |
@node Word Index, Concept Index, Licenses, Top |
| @unnumbered Word Index |
@unnumbered Word Index |
| |
|
| This index is a list of Forth words that have ``glossary'' entries |
This index is a list of Forth words that have ``glossary'' entries |
| |
|
| @printindex fn |
@printindex fn |
| |
|
| @node Name Index, Concept Index, Word Index, Top |
@c anton: the name index seems superfluous given the word and concept indices. |
| @unnumbered Name Index |
|
| |
|
| This index is a list of Forth words that have ``glossary'' entries |
@c @node Name Index, Concept Index, Word Index, Top |
| within this manual. |
@c @unnumbered Name Index |
| |
|
| @printindex ky |
@c This index is a list of Forth words that have ``glossary'' entries |
| |
@c within this manual. |
| |
|
| @node Concept Index, , Name Index, Top |
@c @printindex ky |
| |
|
| |
@c ------------------------------------------------------- |
| |
@node Concept Index, , Word Index, Top |
| @unnumbered Concept and Word Index |
@unnumbered Concept and Word Index |
| |
|
| Not all entries listed in this index are present verbatim in the |
Not all entries listed in this index are present verbatim in the |
| |
|
| @printindex cp |
@printindex cp |
| |
|
| @contents |
|
| @bye |
@bye |
| |
|
| |
|
| |
|