File:  [gforth] / gforth / doc / gforth.ds
Revision 1.47: download - view: text, annotated - select for diffs
Fri Mar 17 21:35:32 2000 UTC (24 years, 1 month ago) by crook
Branches: MAIN
CVS tags: HEAD
Re-ordered a couple of sections. Added new section on time. Fixed url
references so they would be real hypertext links in HTML output. Other
minor fixes here and there.

    1: \input texinfo   @c -*-texinfo-*-
    2: @comment The source is gforth.ds, from which gforth.texi is generated
    3: 
    4: @comment TODO: nac29jan99 - a list of things to add in the next edit:
    5: @comment 1. x-ref all ambiguous or implementation-defined features?
    6: @comment 2. Describe the use of Auser Avariable AConstant A, etc.
    7: @comment 3. words in miscellaneous section need a home.
    8: @comment 4. search for TODO for other minor and major works required.
    9: @comment 5. [rats] change all @var to @i in Forth source so that info
   10: @comment    file looks decent.
   11: @c          Not an improvement IMO - anton
   12: @c          and anyway, this should be taken up
   13: @c          with Karl Berry (the texinfo guy) - anton
   14: @comment .. would be useful to have a word that identified all deferred words
   15: @comment should semantics stuff in intro be moved to another section
   16: 
   17: 
   18: @comment %**start of header (This is for running Texinfo on a region.)
   19: @setfilename gforth.info
   20: @settitle Gforth Manual
   21: @dircategory GNU programming tools
   22: @direntry
   23: * Gforth: (gforth).             A fast interpreter for the Forth language.
   24: @end direntry
   25: @comment @setchapternewpage odd
   26: @comment TODO this gets left in by HTML converter
   27: @macro progstyle {}
   28: Programming style note:
   29: @end macro
   30: @comment %**end of header (This is for running Texinfo on a region.)
   31: 
   32: 
   33: @comment ----------------------------------------------------------
   34: @comment macros for beautifying glossary entries
   35: @comment if these are used, need to strip them out for HTML converter
   36: @comment else they get repeated verbatim in HTML output.
   37: @comment .. not working yet.
   38: 
   39: @macro GLOSS-START {}
   40: @iftex
   41: @ninerm
   42: @end iftex
   43: @end macro
   44: 
   45: @macro GLOSS-END {}
   46: @iftex
   47: @rm
   48: @end iftex
   49: @end macro
   50: 
   51: @comment ----------------------------------------------------------
   52: 
   53: 
   54: @include version.texi
   55: 
   56: @ifinfo
   57: This file documents Gforth @value{VERSION}
   58: 
   59: Copyright @copyright{} 1995-1999 Free Software Foundation, Inc.
   60: 
   61:      Permission is granted to make and distribute verbatim copies of
   62:      this manual provided the copyright notice and this permission notice
   63:      are preserved on all copies.
   64:      
   65: @ignore
   66:      Permission is granted to process this file through TeX and print the
   67:      results, provided the printed document carries a copying permission
   68:      notice identical to this one except for the removal of this paragraph
   69:      (this paragraph not being relevant to the printed manual).
   70:      
   71: @end ignore
   72:      Permission is granted to copy and distribute modified versions of this
   73:      manual under the conditions for verbatim copying, provided also that the
   74:      sections entitled "Distribution" and "General Public License" are
   75:      included exactly as in the original, and provided that the entire
   76:      resulting derived work is distributed under the terms of a permission
   77:      notice identical to this one.
   78:      
   79:      Permission is granted to copy and distribute translations of this manual
   80:      into another language, under the above conditions for modified versions,
   81:      except that the sections entitled "Distribution" and "General Public
   82:      License" may be included in a translation approved by the author instead
   83:      of in the original English.
   84: @end ifinfo
   85: 
   86: @finalout
   87: @titlepage
   88: @sp 10
   89: @center @titlefont{Gforth Manual}
   90: @sp 2
   91: @center for version @value{VERSION}
   92: @sp 2
   93: @center Neal Crook
   94: @center Anton Ertl
   95: @center Bernd Paysan
   96: @center Jens Wilke
   97: @sp 3
   98: @center This manual is permanently under construction and was last updated on 15-Mar-2000
   99: 
  100: @comment  The following two commands start the copyright page.
  101: @page
  102: @vskip 0pt plus 1filll
  103: Copyright @copyright{} 1995--1999 Free Software Foundation, Inc.
  104: 
  105: @comment !! Published by ... or You can get a copy of this manual ...
  106: 
  107:      Permission is granted to make and distribute verbatim copies of
  108:      this manual provided the copyright notice and this permission notice
  109:      are preserved on all copies.
  110:      
  111:      Permission is granted to copy and distribute modified versions of this
  112:      manual under the conditions for verbatim copying, provided also that the
  113:      sections entitled "Distribution" and "General Public License" are
  114:      included exactly as in the original, and provided that the entire
  115:      resulting derived work is distributed under the terms of a permission
  116:      notice identical to this one.
  117:      
  118:      Permission is granted to copy and distribute translations of this manual
  119:      into another language, under the above conditions for modified versions,
  120:      except that the sections entitled "Distribution" and "General Public
  121:      License" may be included in a translation approved by the author instead
  122:      of in the original English.
  123: @end titlepage
  124: 
  125: @node Top, License, (dir), (dir)
  126: @ifinfo
  127: Gforth is a free implementation of ANS Forth available on many
  128: personal machines. This manual corresponds to version @value{VERSION}.
  129: @end ifinfo
  130: 
  131: @menu
  132: * License::                     The GPL
  133: * Goals::                       About the Gforth Project
  134: * Gforth Environment::          Starting (and exiting) Gforth
  135: * Introduction::                An introduction to ANS Forth
  136: * Words::                       Forth words available in Gforth
  137: * Error messages::              How to interpret them
  138: * Tools::                       Programming tools
  139: * ANS conformance::             Implementation-defined options etc.
  140: * Model::                       The abstract machine of Gforth
  141: * Integrating Gforth::          Forth as scripting language for applications
  142: * Emacs and Gforth::            The Gforth Mode
  143: * Image Files::                 @code{.fi} files contain compiled code
  144: * Engine::                      The inner interpreter and the primitives
  145: * Binding to System Library::   
  146: * Cross Compiler::              The Cross Compiler
  147: * Bugs::                        How to report them
  148: * Origin::                      Authors and ancestors of Gforth
  149: * Forth-related information::   Books and places to look on the WWW
  150: * Word Index::                  An item for each Forth word
  151: * Name Index::                  Forth words, only names listed
  152: * Concept Index::               A menu covering many topics
  153: 
  154: @detailmenu
  155:  --- The Detailed Node Listing ---
  156: 
  157: Goals of Gforth
  158: 
  159: * Gforth Extensions Sinful?::
  160: 
  161: Gforth Environment
  162: 
  163: * Invoking Gforth::             Getting in
  164: * Leaving Gforth::              Getting out
  165: * Command-line editing::        
  166: * Upper and lower case::
  167: * Environment variables::       ..that affect how Gforth starts up
  168: * Gforth Files::                What gets installed and where
  169: 
  170: An Introduction to ANS Forth
  171: 
  172: * Introducing the Text Interpreter::
  173: * Stacks and Postfix notation::
  174: * Your first definition::
  175: * How does that work?::
  176: * Forth is written in Forth::
  177: * Review - elements of a Forth system::
  178: * Where to go next::
  179: * Exercises::
  180: 
  181: Forth Words
  182: 
  183: * Notation::                    
  184: * Comments::
  185: * Boolean Flags::
  186: * Arithmetic::                  
  187: * Stack Manipulation::          
  188: * Memory::                      
  189: * Control Structures::          
  190: * Defining Words::              
  191: * Interpretation and Compilation Semantics::
  192: * Tokens for Words::            
  193: * The Text Interpreter::
  194: * Word Lists::                   
  195: * Environmental Queries::
  196: * Files::                       
  197: * Blocks::                      
  198: * Other I/O::                   
  199: * Programming Tools::           
  200: * Assembler and Code Words::    
  201: * Threading Words::             
  202: * Locals::                      
  203: * Structures::                  
  204: * Object-oriented Forth::       
  205: * Passing Commands to the OS::
  206: * Keeping track of Time::
  207: * Miscellaneous Words::
  208: 
  209: Arithmetic
  210: 
  211: * Single precision::            
  212: * Bitwise operations::          
  213: * Double precision::            Double-cell integer arithmetic
  214: * Numeric comparison::
  215: * Mixed precision::             Operations with single and double-cell integers
  216: * Floating Point::              
  217: 
  218: Stack Manipulation
  219: 
  220: * Data stack::                  
  221: * Floating point stack::        
  222: * Return stack::                
  223: * Locals stack::                
  224: * Stack pointer manipulation::  
  225: 
  226: Memory
  227: 
  228: * Memory model::                
  229: * Dictionary allocation::       
  230: * Heap Allocation::             
  231: * Memory Access::               
  232: * Address arithmetic::          
  233: * Memory Blocks::               
  234: 
  235: Control Structures
  236: 
  237: * Selection::                   IF ... ELSE ... ENDIF
  238: * Simple Loops::                BEGIN ...
  239: * Counted Loops::               DO
  240: * Arbitrary control structures::
  241: * Calls and returns::
  242: * Exception Handling::          
  243: 
  244: Defining Words
  245: 
  246: * CREATE::
  247: * Variables::                   Variables and user variables
  248: * Constants::
  249: * Values::                      Initialised variables
  250: * Colon Definitions::
  251: * Anonymous Definitions::       Definitions without names
  252: * User-defined Defining Words::
  253: * Deferred words::              Allow forward references
  254: * Aliases::
  255: * Supplying names::
  256: 
  257: Interpretation and Compilation Semantics
  258: 
  259: * Combined words::
  260: 
  261: The Text Interpreter
  262: 
  263: * Input Sources::
  264: * Number Conversion::
  265: * Interpret/Compile states::
  266: * Literals::
  267: * Interpreter Directives::
  268: 
  269: Word Lists
  270: 
  271: * Why use word lists?::
  272: * Word list examples::
  273: 
  274: Files
  275: 
  276: * Forth source files::
  277: * General files::         
  278: * Search Paths::                 
  279: * Forth Search Paths::    
  280: * General Search Paths::        
  281: 
  282: Other I/O
  283: 
  284: * Simple numeric output::       Predefined formats
  285: * Formatted numeric output::    Formatted (pictured) output
  286: * String Formats::              How Forth stores strings in memory
  287: * Displaying characters and strings:: Other stuff
  288: * Input::                       Input
  289: 
  290: Programming Tools
  291: 
  292: * Debugging::                   Simple and quick.
  293: * Assertions::                  Making your programs self-checking.
  294: * Singlestep Debugger::         Executing your program word by word.
  295: 
  296: Locals
  297: 
  298: * Gforth locals::               
  299: * ANS Forth locals::            
  300: 
  301: Gforth locals
  302: 
  303: * Where are locals visible by name?::  
  304: * How long do locals live?::    
  305: * Programming Style::           
  306: * Implementation::              
  307: 
  308: Structures
  309: 
  310: * Why explicit structure support?::  
  311: * Structure Usage::             
  312: * Structure Naming Convention::  
  313: * Structure Implementation::    
  314: * Structure Glossary::          
  315: 
  316: Object-oriented Forth
  317: 
  318: * Why object-oriented programming?::
  319: * Object-Oriented Terminology::
  320: * Objects::
  321: * OOF::
  322: * Mini-OOF::
  323: * Comparison with other object models::  
  324: 
  325: The @file{objects.fs} model
  326: 
  327: * Properties of the Objects model::  
  328: * Basic Objects Usage::         
  329: * The Objects base class::      
  330: * Creating objects::            
  331: * Object-Oriented Programming Style::  
  332: * Class Binding::               
  333: * Method conveniences::         
  334: * Classes and Scoping::         
  335: * Dividing classes::            
  336: * Object Interfaces::           
  337: * Objects Implementation::      
  338: * Objects Glossary::            
  339: 
  340: The @file{oof.fs} model
  341: 
  342: * Properties of the OOF model::
  343: * Basic OOF Usage::
  344: * The OOF base class::
  345: * Class Declaration::
  346: * Class Implementation::
  347: 
  348: The @file{mini-oof.fs} model
  349: 
  350: * Basic Mini-OOF Usage::
  351: * Mini-OOF Example::
  352: * Mini-OOF Implementation::
  353: 
  354: Tools
  355: 
  356: * ANS Report::                  Report the words used, sorted by wordset.
  357: 
  358: ANS conformance
  359: 
  360: * The Core Words::              
  361: * The optional Block word set::  
  362: * The optional Double Number word set::  
  363: * The optional Exception word set::  
  364: * The optional Facility word set::  
  365: * The optional File-Access word set::  
  366: * The optional Floating-Point word set::  
  367: * The optional Locals word set::  
  368: * The optional Memory-Allocation word set::  
  369: * The optional Programming-Tools word set::  
  370: * The optional Search-Order word set::  
  371: 
  372: The Core Words
  373: 
  374: * core-idef::                   Implementation Defined Options                   
  375: * core-ambcond::                Ambiguous Conditions                
  376: * core-other::                  Other System Documentation                  
  377: 
  378: The optional Block word set
  379: 
  380: * block-idef::                  Implementation Defined Options
  381: * block-ambcond::               Ambiguous Conditions               
  382: * block-other::                 Other System Documentation                 
  383: 
  384: The optional Double Number word set
  385: 
  386: * double-ambcond::              Ambiguous Conditions              
  387: 
  388: The optional Exception word set
  389: 
  390: * exception-idef::              Implementation Defined Options              
  391: 
  392: The optional Facility word set
  393: 
  394: * facility-idef::               Implementation Defined Options               
  395: * facility-ambcond::            Ambiguous Conditions            
  396: 
  397: The optional File-Access word set
  398: 
  399: * file-idef::                   Implementation Defined Options
  400: * file-ambcond::                Ambiguous Conditions                
  401: 
  402: The optional Floating-Point word set
  403: 
  404: * floating-idef::               Implementation Defined Options
  405: * floating-ambcond::            Ambiguous Conditions            
  406: 
  407: The optional Locals word set
  408: 
  409: * locals-idef::                 Implementation Defined Options                 
  410: * locals-ambcond::              Ambiguous Conditions              
  411: 
  412: The optional Memory-Allocation word set
  413: 
  414: * memory-idef::                 Implementation Defined Options                 
  415: 
  416: The optional Programming-Tools word set
  417: 
  418: * programming-idef::            Implementation Defined Options            
  419: * programming-ambcond::         Ambiguous Conditions         
  420: 
  421: The optional Search-Order word set
  422: 
  423: * search-idef::                 Implementation Defined Options                 
  424: * search-ambcond::              Ambiguous Conditions              
  425: 
  426: Image Files
  427: 
  428: * Image Licensing Issues::      Distribution terms for images.
  429: * Image File Background::       Why have image files?
  430: * Non-Relocatable Image Files::   don't always work.
  431: * Data-Relocatable Image Files::  are better.
  432: * Fully Relocatable Image Files:: better yet.
  433: * Stack and Dictionary Sizes::  Setting the default sizes for an image.
  434: * Running Image Files::         @code{gforth -i @i{file}} or @i{file}.
  435: * Modifying the Startup Sequence::  and turnkey applications.
  436: 
  437: Fully Relocatable Image Files
  438: 
  439: * gforthmi::                    The normal way
  440: * cross.fs::                    The hard way
  441: 
  442: Engine
  443: 
  444: * Portability::                 
  445: * Threading::                   
  446: * Primitives::                  
  447: * Performance::                 
  448: 
  449: Threading
  450: 
  451: * Scheduling::                  
  452: * Direct or Indirect Threaded?::  
  453: * DOES>::                       
  454: 
  455: Primitives
  456: 
  457: * Automatic Generation::        
  458: * TOS Optimization::            
  459: * Produced code::               
  460: 
  461: Cross Compiler
  462: 
  463: * Using the Cross Compiler::
  464: * How the Cross Compiler Works::
  465: 
  466: Other Forth-related information
  467: 
  468: * Internet resources::
  469: * Books::
  470: * The Forth Interest Group::
  471: * Conferences::
  472: 
  473: @end detailmenu
  474: @end menu
  475: 
  476: @node License, Goals, Top, Top
  477: @unnumbered GNU GENERAL PUBLIC LICENSE
  478: @center Version 2, June 1991
  479: 
  480: @display
  481: Copyright @copyright{} 1989, 1991 Free Software Foundation, Inc.
  482: 675 Mass Ave, Cambridge, MA 02139, USA
  483: 
  484: Everyone is permitted to copy and distribute verbatim copies
  485: of this license document, but changing it is not allowed.
  486: @end display
  487: 
  488: @unnumberedsec Preamble
  489: 
  490:   The licenses for most software are designed to take away your
  491: freedom to share and change it.  By contrast, the GNU General Public
  492: License is intended to guarantee your freedom to share and change free
  493: software---to make sure the software is free for all its users.  This
  494: General Public License applies to most of the Free Software
  495: Foundation's software and to any other program whose authors commit to
  496: using it.  (Some other Free Software Foundation software is covered by
  497: the GNU Library General Public License instead.)  You can apply it to
  498: your programs, too.
  499: 
  500:   When we speak of free software, we are referring to freedom, not
  501: price.  Our General Public Licenses are designed to make sure that you
  502: have the freedom to distribute copies of free software (and charge for
  503: this service if you wish), that you receive source code or can get it
  504: if you want it, that you can change the software or use pieces of it
  505: in new free programs; and that you know you can do these things.
  506: 
  507:   To protect your rights, we need to make restrictions that forbid
  508: anyone to deny you these rights or to ask you to surrender the rights.
  509: These restrictions translate to certain responsibilities for you if you
  510: distribute copies of the software, or if you modify it.
  511: 
  512:   For example, if you distribute copies of such a program, whether
  513: gratis or for a fee, you must give the recipients all the rights that
  514: you have.  You must make sure that they, too, receive or can get the
  515: source code.  And you must show them these terms so they know their
  516: rights.
  517: 
  518:   We protect your rights with two steps: (1) copyright the software, and
  519: (2) offer you this license which gives you legal permission to copy,
  520: distribute and/or modify the software.
  521: 
  522:   Also, for each author's protection and ours, we want to make certain
  523: that everyone understands that there is no warranty for this free
  524: software.  If the software is modified by someone else and passed on, we
  525: want its recipients to know that what they have is not the original, so
  526: that any problems introduced by others will not reflect on the original
  527: authors' reputations.
  528: 
  529:   Finally, any free program is threatened constantly by software
  530: patents.  We wish to avoid the danger that redistributors of a free
  531: program will individually obtain patent licenses, in effect making the
  532: program proprietary.  To prevent this, we have made it clear that any
  533: patent must be licensed for everyone's free use or not licensed at all.
  534: 
  535:   The precise terms and conditions for copying, distribution and
  536: modification follow.
  537: 
  538: @iftex
  539: @unnumberedsec TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
  540: @end iftex
  541: @ifinfo
  542: @center TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
  543: @end ifinfo
  544: 
  545: @enumerate 0
  546: @item
  547: This License applies to any program or other work which contains
  548: a notice placed by the copyright holder saying it may be distributed
  549: under the terms of this General Public License.  The ``Program'', below,
  550: refers to any such program or work, and a ``work based on the Program''
  551: means either the Program or any derivative work under copyright law:
  552: that is to say, a work containing the Program or a portion of it,
  553: either verbatim or with modifications and/or translated into another
  554: language.  (Hereinafter, translation is included without limitation in
  555: the term ``modification''.)  Each licensee is addressed as ``you''.
  556: 
  557: Activities other than copying, distribution and modification are not
  558: covered by this License; they are outside its scope.  The act of
  559: running the Program is not restricted, and the output from the Program
  560: is covered only if its contents constitute a work based on the
  561: Program (independent of having been made by running the Program).
  562: Whether that is true depends on what the Program does.
  563: 
  564: @item
  565: You may copy and distribute verbatim copies of the Program's
  566: source code as you receive it, in any medium, provided that you
  567: conspicuously and appropriately publish on each copy an appropriate
  568: copyright notice and disclaimer of warranty; keep intact all the
  569: notices that refer to this License and to the absence of any warranty;
  570: and give any other recipients of the Program a copy of this License
  571: along with the Program.
  572: 
  573: You may charge a fee for the physical act of transferring a copy, and
  574: you may at your option offer warranty protection in exchange for a fee.
  575: 
  576: @item
  577: You may modify your copy or copies of the Program or any portion
  578: of it, thus forming a work based on the Program, and copy and
  579: distribute such modifications or work under the terms of Section 1
  580: above, provided that you also meet all of these conditions:
  581: 
  582: @enumerate a
  583: @item
  584: You must cause the modified files to carry prominent notices
  585: stating that you changed the files and the date of any change.
  586: 
  587: @item
  588: You must cause any work that you distribute or publish, that in
  589: whole or in part contains or is derived from the Program or any
  590: part thereof, to be licensed as a whole at no charge to all third
  591: parties under the terms of this License.
  592: 
  593: @item
  594: If the modified program normally reads commands interactively
  595: when run, you must cause it, when started running for such
  596: interactive use in the most ordinary way, to print or display an
  597: announcement including an appropriate copyright notice and a
  598: notice that there is no warranty (or else, saying that you provide
  599: a warranty) and that users may redistribute the program under
  600: these conditions, and telling the user how to view a copy of this
  601: License.  (Exception: if the Program itself is interactive but
  602: does not normally print such an announcement, your work based on
  603: the Program is not required to print an announcement.)
  604: @end enumerate
  605: 
  606: These requirements apply to the modified work as a whole.  If
  607: identifiable sections of that work are not derived from the Program,
  608: and can be reasonably considered independent and separate works in
  609: themselves, then this License, and its terms, do not apply to those
  610: sections when you distribute them as separate works.  But when you
  611: distribute the same sections as part of a whole which is a work based
  612: on the Program, the distribution of the whole must be on the terms of
  613: this License, whose permissions for other licensees extend to the
  614: entire whole, and thus to each and every part regardless of who wrote it.
  615: 
  616: Thus, it is not the intent of this section to claim rights or contest
  617: your rights to work written entirely by you; rather, the intent is to
  618: exercise the right to control the distribution of derivative or
  619: collective works based on the Program.
  620: 
  621: In addition, mere aggregation of another work not based on the Program
  622: with the Program (or with a work based on the Program) on a volume of
  623: a storage or distribution medium does not bring the other work under
  624: the scope of this License.
  625: 
  626: @item
  627: You may copy and distribute the Program (or a work based on it,
  628: under Section 2) in object code or executable form under the terms of
  629: Sections 1 and 2 above provided that you also do one of the following:
  630: 
  631: @enumerate a
  632: @item
  633: Accompany it with the complete corresponding machine-readable
  634: source code, which must be distributed under the terms of Sections
  635: 1 and 2 above on a medium customarily used for software interchange; or,
  636: 
  637: @item
  638: Accompany it with a written offer, valid for at least three
  639: years, to give any third party, for a charge no more than your
  640: cost of physically performing source distribution, a complete
  641: machine-readable copy of the corresponding source code, to be
  642: distributed under the terms of Sections 1 and 2 above on a medium
  643: customarily used for software interchange; or,
  644: 
  645: @item
  646: Accompany it with the information you received as to the offer
  647: to distribute corresponding source code.  (This alternative is
  648: allowed only for noncommercial distribution and only if you
  649: received the program in object code or executable form with such
  650: an offer, in accord with Subsection b above.)
  651: @end enumerate
  652: 
  653: The source code for a work means the preferred form of the work for
  654: making modifications to it.  For an executable work, complete source
  655: code means all the source code for all modules it contains, plus any
  656: associated interface definition files, plus the scripts used to
  657: control compilation and installation of the executable.  However, as a
  658: special exception, the source code distributed need not include
  659: anything that is normally distributed (in either source or binary
  660: form) with the major components (compiler, kernel, and so on) of the
  661: operating system on which the executable runs, unless that component
  662: itself accompanies the executable.
  663: 
  664: If distribution of executable or object code is made by offering
  665: access to copy from a designated place, then offering equivalent
  666: access to copy the source code from the same place counts as
  667: distribution of the source code, even though third parties are not
  668: compelled to copy the source along with the object code.
  669: 
  670: @item
  671: You may not copy, modify, sublicense, or distribute the Program
  672: except as expressly provided under this License.  Any attempt
  673: otherwise to copy, modify, sublicense or distribute the Program is
  674: void, and will automatically terminate your rights under this License.
  675: However, parties who have received copies, or rights, from you under
  676: this License will not have their licenses terminated so long as such
  677: parties remain in full compliance.
  678: 
  679: @item
  680: You are not required to accept this License, since you have not
  681: signed it.  However, nothing else grants you permission to modify or
  682: distribute the Program or its derivative works.  These actions are
  683: prohibited by law if you do not accept this License.  Therefore, by
  684: modifying or distributing the Program (or any work based on the
  685: Program), you indicate your acceptance of this License to do so, and
  686: all its terms and conditions for copying, distributing or modifying
  687: the Program or works based on it.
  688: 
  689: @item
  690: Each time you redistribute the Program (or any work based on the
  691: Program), the recipient automatically receives a license from the
  692: original licensor to copy, distribute or modify the Program subject to
  693: these terms and conditions.  You may not impose any further
  694: restrictions on the recipients' exercise of the rights granted herein.
  695: You are not responsible for enforcing compliance by third parties to
  696: this License.
  697: 
  698: @item
  699: If, as a consequence of a court judgment or allegation of patent
  700: infringement or for any other reason (not limited to patent issues),
  701: conditions are imposed on you (whether by court order, agreement or
  702: otherwise) that contradict the conditions of this License, they do not
  703: excuse you from the conditions of this License.  If you cannot
  704: distribute so as to satisfy simultaneously your obligations under this
  705: License and any other pertinent obligations, then as a consequence you
  706: may not distribute the Program at all.  For example, if a patent
  707: license would not permit royalty-free redistribution of the Program by
  708: all those who receive copies directly or indirectly through you, then
  709: the only way you could satisfy both it and this License would be to
  710: refrain entirely from distribution of the Program.
  711: 
  712: If any portion of this section is held invalid or unenforceable under
  713: any particular circumstance, the balance of the section is intended to
  714: apply and the section as a whole is intended to apply in other
  715: circumstances.
  716: 
  717: It is not the purpose of this section to induce you to infringe any
  718: patents or other property right claims or to contest validity of any
  719: such claims; this section has the sole purpose of protecting the
  720: integrity of the free software distribution system, which is
  721: implemented by public license practices.  Many people have made
  722: generous contributions to the wide range of software distributed
  723: through that system in reliance on consistent application of that
  724: system; it is up to the author/donor to decide if he or she is willing
  725: to distribute software through any other system and a licensee cannot
  726: impose that choice.
  727: 
  728: This section is intended to make thoroughly clear what is believed to
  729: be a consequence of the rest of this License.
  730: 
  731: @item
  732: If the distribution and/or use of the Program is restricted in
  733: certain countries either by patents or by copyrighted interfaces, the
  734: original copyright holder who places the Program under this License
  735: may add an explicit geographical distribution limitation excluding
  736: those countries, so that distribution is permitted only in or among
  737: countries not thus excluded.  In such case, this License incorporates
  738: the limitation as if written in the body of this License.
  739: 
  740: @item
  741: The Free Software Foundation may publish revised and/or new versions
  742: of the General Public License from time to time.  Such new versions will
  743: be similar in spirit to the present version, but may differ in detail to
  744: address new problems or concerns.
  745: 
  746: Each version is given a distinguishing version number.  If the Program
  747: specifies a version number of this License which applies to it and ``any
  748: later version'', you have the option of following the terms and conditions
  749: either of that version or of any later version published by the Free
  750: Software Foundation.  If the Program does not specify a version number of
  751: this License, you may choose any version ever published by the Free Software
  752: Foundation.
  753: 
  754: @item
  755: If you wish to incorporate parts of the Program into other free
  756: programs whose distribution conditions are different, write to the author
  757: to ask for permission.  For software which is copyrighted by the Free
  758: Software Foundation, write to the Free Software Foundation; we sometimes
  759: make exceptions for this.  Our decision will be guided by the two goals
  760: of preserving the free status of all derivatives of our free software and
  761: of promoting the sharing and reuse of software generally.
  762: 
  763: @iftex
  764: @heading NO WARRANTY
  765: @end iftex
  766: @ifinfo
  767: @center NO WARRANTY
  768: @end ifinfo
  769: 
  770: @item
  771: BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
  772: FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN
  773: OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
  774: PROVIDE THE PROGRAM ``AS IS'' WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
  775: OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
  776: MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS
  777: TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE
  778: PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
  779: REPAIR OR CORRECTION.
  780: 
  781: @item
  782: IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
  783: WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
  784: REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
  785: INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
  786: OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
  787: TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
  788: YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
  789: PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
  790: POSSIBILITY OF SUCH DAMAGES.
  791: @end enumerate
  792: 
  793: @iftex
  794: @heading END OF TERMS AND CONDITIONS
  795: @end iftex
  796: @ifinfo
  797: @center END OF TERMS AND CONDITIONS
  798: @end ifinfo
  799: 
  800: @page
  801: @unnumberedsec How to Apply These Terms to Your New Programs
  802: 
  803:   If you develop a new program, and you want it to be of the greatest
  804: possible use to the public, the best way to achieve this is to make it
  805: free software which everyone can redistribute and change under these terms.
  806: 
  807:   To do so, attach the following notices to the program.  It is safest
  808: to attach them to the start of each source file to most effectively
  809: convey the exclusion of warranty; and each file should have at least
  810: the ``copyright'' line and a pointer to where the full notice is found.
  811: 
  812: @smallexample
  813: @var{one line to give the program's name and a brief idea of what it does.}
  814: Copyright (C) 19@var{yy}  @var{name of author}
  815: 
  816: This program is free software; you can redistribute it and/or modify 
  817: it under the terms of the GNU General Public License as published by 
  818: the Free Software Foundation; either version 2 of the License, or 
  819: (at your option) any later version.
  820: 
  821: This program is distributed in the hope that it will be useful,
  822: but WITHOUT ANY WARRANTY; without even the implied warranty of
  823: MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  824: GNU General Public License for more details.
  825: 
  826: You should have received a copy of the GNU General Public License
  827: along with this program; if not, write to the Free Software
  828: Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  829: @end smallexample
  830: 
  831: Also add information on how to contact you by electronic and paper mail.
  832: 
  833: If the program is interactive, make it output a short notice like this
  834: when it starts in an interactive mode:
  835: 
  836: @smallexample
  837: Gnomovision version 69, Copyright (C) 19@var{yy} @var{name of author}
  838: Gnomovision comes with ABSOLUTELY NO WARRANTY; for details
  839: type `show w'.  
  840: This is free software, and you are welcome to redistribute it 
  841: under certain conditions; type `show c' for details.
  842: @end smallexample
  843: 
  844: The hypothetical commands @samp{show w} and @samp{show c} should show
  845: the appropriate parts of the General Public License.  Of course, the
  846: commands you use may be called something other than @samp{show w} and
  847: @samp{show c}; they could even be mouse-clicks or menu items---whatever
  848: suits your program.
  849: 
  850: You should also get your employer (if you work as a programmer) or your
  851: school, if any, to sign a ``copyright disclaimer'' for the program, if
  852: necessary.  Here is a sample; alter the names:
  853: 
  854: @smallexample
  855: Yoyodyne, Inc., hereby disclaims all copyright interest in the program
  856: `Gnomovision' (which makes passes at compilers) written by James Hacker.
  857: 
  858: @var{signature of Ty Coon}, 1 April 1989
  859: Ty Coon, President of Vice
  860: @end smallexample
  861: 
  862: This General Public License does not permit incorporating your program into
  863: proprietary programs.  If your program is a subroutine library, you may
  864: consider it more useful to permit linking proprietary applications with the
  865: library.  If this is what you want to do, use the GNU Library General
  866: Public License instead of this License.
  867: 
  868: @iftex
  869: @unnumbered Preface
  870: @cindex Preface
  871: This manual documents Gforth. Some introductory material is provided for
  872: readers who are unfamiliar with Forth or who are migrating to Gforth
  873: from other Forth compilers. However, this manual is primarily a
  874: reference manual.
  875: @end iftex
  876: 
  877: @comment TODO much more blurb here.
  878: 
  879: @c ******************************************************************
  880: @node Goals, Gforth Environment, License, Top
  881: @comment node-name,     next,           previous, up
  882: @chapter Goals of Gforth
  883: @cindex goals of the Gforth project
  884: The goal of the Gforth Project is to develop a standard model for
  885: ANS Forth. This can be split into several subgoals:
  886: 
  887: @itemize @bullet
  888: @item
  889: Gforth should conform to the ANS Forth Standard.
  890: @item
  891: It should be a model, i.e. it should define all the
  892: implementation-dependent things.
  893: @item
  894: It should become standard, i.e. widely accepted and used. This goal
  895: is the most difficult one.
  896: @end itemize
  897: 
  898: To achieve these goals Gforth should be
  899: @itemize @bullet
  900: @item
  901: Similar to previous models (fig-Forth, F83)
  902: @item
  903: Powerful. It should provide for all the things that are considered
  904: necessary today and even some that are not yet considered necessary.
  905: @item
  906: Efficient. It should not get the reputation of being exceptionally
  907: slow.
  908: @item
  909: Free.
  910: @item
  911: Available on many machines/easy to port.
  912: @end itemize
  913: 
  914: Have we achieved these goals? Gforth conforms to the ANS Forth
  915: standard. It may be considered a model, but we have not yet documented
  916: which parts of the model are stable and which parts we are likely to
  917: change. It certainly has not yet become a de facto standard, but it
  918: appears to be quite popular. It has some similarities to and some
  919: differences from previous models. It has some powerful features, but not
  920: yet everything that we envisioned. We certainly have achieved our
  921: execution speed goals (@pxref{Performance}).  It is free and available
  922: on many machines.
  923: 
  924: @menu
  925: * Gforth Extensions Sinful?::
  926: @end menu
  927: 
  928: @node Gforth Extensions Sinful?, , Goals, Goals
  929: @comment node-name,     next,           previous, up
  930: @section Is it a Sin to use Gforth Extensions?
  931: @cindex Gforth extensions
  932: 
  933: If you've been paying attention, you will have realised that there is an
  934: ANS (American National Standard) for Forth. As you read through the rest
  935: of this manual, you will see documentation for @i{Standard} words, and
  936: documentation for some appealing Gforth @i{extensions}. You might ask
  937: yourself the question: @i{``Given that there is a standard, would I be
  938: committing a sin if I use (non-Standard) Gforth extensions?''}
  939: 
  940: The answer to that question is somewhat pragmatic and somewhat
  941: philosophical. Consider these points:
  942: 
  943: @itemize @bullet
  944: @item
  945: A number of the Gforth extensions can be implemented in ANS Forth using
  946: files provided in the @file{compat/} directory. These are mentioned in
  947: the text in passing.
  948: @item
  949: Forth has a rich historical precedent for programmers taking advantage
  950: of implementation-dependent features of their tools (for example,
  951: relying on a knowledge of the dictionary structure). Sometimes these
  952: techniques are necessary to extract every last bit of performance from
  953: the hardware, sometimes they are just a programming shorthand.
  954: @item
  955: The best way to break the rules is to know what the rules are. To learn
  956: the rules, there is no substitute for studying the text of the Standard
  957: itself. In particular, Appendix A of the Standard (@var{Rationale})
  958: provides a valuable insight into the thought processes of the technical
  959: committee.
  960: @item
  961: The best reason to break a rule is because you have to; because it's
  962: more productive to do that, because it makes your code run fast enough
  963: or because you can see no Standard way to achieve what you want to
  964: achieve.
  965: @end itemize
  966: 
  967: The tool @file{ans-report.fs} (@pxref{ANS Report}) makes it easy to
  968: analyse your program and determine what non-Standard definitions it
  969: relies upon.
  970: 
  971: 
  972: @c ******************************************************************
  973: @node Gforth Environment, Introduction, Goals, Top
  974: @chapter Gforth Environment
  975: @cindex Gforth environment
  976: 
  977: Note: ultimately, the Gforth man page will be auto-generated from the
  978: material in this chapter.
  979: 
  980: @menu
  981: * Invoking Gforth::             Getting in
  982: * Leaving Gforth::              Getting out
  983: * Command-line editing::        
  984: * Upper and lower case::
  985: * Environment variables::       ..that affect how Gforth starts up
  986: * Gforth Files::                What gets installed and where
  987: @end menu
  988: 
  989: @xref{Image Files} for related information about the creation of images.
  990: 
  991: @comment ----------------------------------------------
  992: @node Invoking Gforth, Leaving Gforth, ,Gforth Environment
  993: @section Invoking Gforth
  994: @cindex invoking Gforth
  995: @cindex running Gforth
  996: @cindex command-line options
  997: @cindex options on the command line
  998: @cindex flags on the command line
  999: 
 1000: Gforth is made up of two parts; an executable ``engine'' (named
 1001: @file{gforth} or @file{gforth-fast}) and an image file. To start it, you
 1002: will usually just say @code{gforth} -- this automatically loads the
 1003: default image file @file{gforth.fi}. In many other cases the default
 1004: Gforth image will be invoked like this:
 1005: @example
 1006: gforth [file | -e forth-code] ...
 1007: @end example
 1008: @noindent
 1009: This interprets the contents of the files and the Forth code in the order they
 1010: are given.
 1011: 
 1012: In addition to the @file{gforth} engine, there is also an engine called
 1013: @file{gforth-fast}, which is faster, but gives less informative error
 1014: messages (@pxref{Error messages}).
 1015: 
 1016: In general, the command line looks like this:
 1017: 
 1018: @example
 1019: gforth[-fast] [engine options] [image options]
 1020: @end example
 1021: 
 1022: The engine options must come before the rest of the command
 1023: line. They are:
 1024: 
 1025: @table @code
 1026: @cindex -i, command-line option
 1027: @cindex --image-file, command-line option
 1028: @item --image-file @i{file}
 1029: @itemx -i @i{file}
 1030: Loads the Forth image @i{file} instead of the default
 1031: @file{gforth.fi} (@pxref{Image Files}).
 1032: 
 1033: @cindex --appl-image, command-line option
 1034: @item --appl-image @i{file}
 1035: Loads the image @i{file} and leaves all further command-line arguments
 1036: to the image (instead of processing them as options).  This is useful
 1037: for building executable application images on Unix, built with
 1038: @code{gforthmi --application ...}.
 1039: 
 1040: @cindex --path, command-line option
 1041: @cindex -p, command-line option
 1042: @item --path @i{path}
 1043: @itemx -p @i{path}
 1044: Uses @i{path} for searching the image file and Forth source code files
 1045: instead of the default in the environment variable @code{GFORTHPATH} or
 1046: the path specified at installation time (e.g.,
 1047: @file{/usr/local/share/gforth/0.2.0:.}). A path is given as a list of
 1048: directories, separated by @samp{:} (on Unix) or @samp{;} (on other OSs).
 1049: 
 1050: @cindex --dictionary-size, command-line option
 1051: @cindex -m, command-line option
 1052: @cindex @i{size} parameters for command-line options
 1053: @cindex size of the dictionary and the stacks
 1054: @item --dictionary-size @i{size}
 1055: @itemx -m @i{size}
 1056: Allocate @i{size} space for the Forth dictionary space instead of
 1057: using the default specified in the image (typically 256K). The
 1058: @i{size} specification for this and subsequent options consists of
 1059: an integer and a unit (e.g.,
 1060: @code{4M}). The unit can be one of @code{b} (bytes), @code{e} (element
 1061: size, in this case Cells), @code{k} (kilobytes), @code{M} (Megabytes),
 1062: @code{G} (Gigabytes), and @code{T} (Terabytes). If no unit is specified,
 1063: @code{e} is used.
 1064: 
 1065: @cindex --data-stack-size, command-line option
 1066: @cindex -d, command-line option
 1067: @item --data-stack-size @i{size}
 1068: @itemx -d @i{size}
 1069: Allocate @i{size} space for the data stack instead of using the
 1070: default specified in the image (typically 16K).
 1071: 
 1072: @cindex --return-stack-size, command-line option
 1073: @cindex -r, command-line option
 1074: @item --return-stack-size @i{size}
 1075: @itemx -r @i{size}
 1076: Allocate @i{size} space for the return stack instead of using the
 1077: default specified in the image (typically 15K).
 1078: 
 1079: @cindex --fp-stack-size, command-line option
 1080: @cindex -f, command-line option
 1081: @item --fp-stack-size @i{size}
 1082: @itemx -f @i{size}
 1083: Allocate @i{size} space for the floating point stack instead of
 1084: using the default specified in the image (typically 15.5K). In this case
 1085: the unit specifier @code{e} refers to floating point numbers.
 1086: 
 1087: @cindex --locals-stack-size, command-line option
 1088: @cindex -l, command-line option
 1089: @item --locals-stack-size @i{size}
 1090: @itemx -l @i{size}
 1091: Allocate @i{size} space for the locals stack instead of using the
 1092: default specified in the image (typically 14.5K).
 1093: 
 1094: @cindex -h, command-line option
 1095: @cindex --help, command-line option
 1096: @item --help
 1097: @itemx -h
 1098: Print a message about the command-line options
 1099: 
 1100: @cindex -v, command-line option
 1101: @cindex --version, command-line option
 1102: @item --version
 1103: @itemx -v
 1104: Print version and exit
 1105: 
 1106: @cindex --debug, command-line option
 1107: @item --debug
 1108: Print some information useful for debugging on startup.
 1109: 
 1110: @cindex --offset-image, command-line option
 1111: @item --offset-image
 1112: Start the dictionary at a slightly different position than would be used
 1113: otherwise (useful for creating data-relocatable images,
 1114: @pxref{Data-Relocatable Image Files}).
 1115: 
 1116: @cindex --no-offset-im, command-line option
 1117: @item --no-offset-im
 1118: Start the dictionary at the normal position.
 1119: 
 1120: @cindex --clear-dictionary, command-line option
 1121: @item --clear-dictionary
 1122: Initialize all bytes in the dictionary to 0 before loading the image
 1123: (@pxref{Data-Relocatable Image Files}).
 1124: 
 1125: @cindex --die-on-signal, command-line-option
 1126: @item --die-on-signal
 1127: Normally Gforth handles most signals (e.g., the user interrupt SIGINT,
 1128: or the segmentation violation SIGSEGV) by translating it into a Forth
 1129: @code{THROW}. With this option, Gforth exits if it receives such a
 1130: signal. This option is useful when the engine and/or the image might be
 1131: severely broken (such that it causes another signal before recovering
 1132: from the first); this option avoids endless loops in such cases.
 1133: @end table
 1134: 
 1135: @cindex loading files at startup
 1136: @cindex executing code on startup
 1137: @cindex batch processing with Gforth
 1138: As explained above, the image-specific command-line arguments for the
 1139: default image @file{gforth.fi} consist of a sequence of filenames and
 1140: @code{-e @var{forth-code}} options that are interpreted in the sequence
 1141: in which they are given. The @code{-e @var{forth-code}} or
 1142: @code{--evaluate @var{forth-code}} option evaluates the Forth
 1143: code. This option takes only one argument; if you want to evaluate more
 1144: Forth words, you have to quote them or use @code{-e} several times. To exit
 1145: after processing the command line (instead of entering interactive mode)
 1146: append @code{-e bye} to the command line.
 1147: 
 1148: @cindex versions, invoking other versions of Gforth
 1149: If you have several versions of Gforth installed, @code{gforth} will
 1150: invoke the version that was installed last. @code{gforth-@i{version}}
 1151: invokes a specific version. If your environment contains the variable
 1152: @code{GFORTHPATH}, you may want to override it by using the
 1153: @code{--path} option.
 1154: 
 1155: Not yet implemented:
 1156: On startup the system first executes the system initialization file
 1157: (unless the option @code{--no-init-file} is given; note that the system
 1158: resulting from using this option may not be ANS Forth conformant). Then
 1159: the user initialization file @file{.gforth.fs} is executed, unless the
 1160: option @code{--no-rc} is given; this file is first searched in @file{.},
 1161: then in @file{~}, then in the normal path (see above).
 1162: 
 1163: 
 1164: 
 1165: @comment ----------------------------------------------
 1166: @node Leaving Gforth, Command-line editing, Invoking Gforth, Gforth Environment
 1167: @section Leaving Gforth
 1168: @cindex Gforth - leaving
 1169: @cindex leaving Gforth
 1170: 
 1171: You can leave Gforth by typing @code{bye} or @kbd{Ctrl-d} (at the start
 1172: of a line) or (if you invoked Gforth with the @code{--die-on-signal}
 1173: option) @kbd{Ctrl-c}. When you leave Gforth, all of your definitions and
 1174: data are discarded. @xref{Image Files} for ways of saving the state of
 1175: the system before leaving Gforth.
 1176: 
 1177: doc-bye
 1178: 
 1179: 
 1180: @comment ----------------------------------------------
 1181: @node Command-line editing, Upper and lower case,Leaving Gforth,Gforth Environment
 1182: @section Command-line editing
 1183: @cindex command-line editing
 1184: 
 1185: Gforth maintains a history file that records every line that you type to
 1186: the text interpreter. This file is preserved between sessions, and is
 1187: used to provide a command-line recall facility; if you type @kbd{Ctrl-P}
 1188: repeatedly you can recall successively older commands from this (or
 1189: previous) session(s). The full list of command-line editing facilities is:
 1190: 
 1191: @itemize @bullet
 1192: @item
 1193: @kbd{Ctrl-p} (``previous'') (or up-arrow) to recall successively older
 1194: commands from the history buffer.
 1195: @item
 1196: @kbd{Ctrl-n} (``next'') (or down-arrow) to recall successively newer commands
 1197: from the history buffer.
 1198: @item
 1199: @kbd{Ctrl-f} (or right-arrow) to move the cursor right, non-destructively.
 1200: @item
 1201: @kbd{Ctrl-b} (or left-arrow) to move the cursor left, non-destructively.
 1202: @item
 1203: @kbd{Ctrl-h} (backspace) to delete the character to the left of the cursor,
 1204: closing up the line.
 1205: @item
 1206: @kbd{Ctrl-k} to delete (``kill'') from the cursor to the end of the line.
 1207: @item
 1208: @kbd{Ctrl-a} to move the cursor to the start of the line.
 1209: @item
 1210: @kbd{Ctrl-e} to move the cursor to the end of the line.
 1211: @item
 1212: @key{RET} (@kbd{Ctrl-m}) or @key{LFD} (@kbd{Ctrl-j}) to submit the current
 1213: line.
 1214: @item
 1215: @key{TAB} to step through all possible full-word completions of the word
 1216: currently being typed.
 1217: @item
 1218: @kbd{Ctrl-d} at the start of the line to terminate Gforth (gracefully,
 1219: using @code{bye}).
 1220: @end itemize
 1221: 
 1222: When editing, displayable characters are inserted to the left of the
 1223: cursor position; the line is always in ``insert'' (as opposed to
 1224: ``overstrike'') mode.
 1225: 
 1226: @cindex history file
 1227: @cindex @file{.gforth-history}
 1228: On Unix systems, the history file is @file{~/.gforth-history} by
 1229: default@footnote{i.e. it is stored in the user's home directory.}. You
 1230: can find out the name and location of your history file using:
 1231: 
 1232: @example 
 1233: history-file type \ Unix-class systems
 1234: 
 1235: history-file type \ Other systems
 1236: history-dir  type
 1237: @end example
 1238: 
 1239: If you enter long definitions by hand, you can use a text editor to
 1240: paste them out of the history file into a Forth source file for reuse at
 1241: a later time.
 1242: 
 1243: Gforth never trims the size of the history file, so you should do this
 1244: periodically, if necessary.
 1245: 
 1246: @comment this is all defined in history.fs
 1247: @comment NAC TODO the ctrl-D behaviour can either do a bye or a beep.. how is that option
 1248: @comment chosen?
 1249: 
 1250: 
 1251: 
 1252: @comment ----------------------------------------------
 1253: @node Upper and lower case, Environment variables,Command-line editing,Gforth Environment
 1254: @section Upper and lower case
 1255: @cindex case-sensitivity
 1256: @cindex upper and lower case
 1257: 
 1258: Gforth is case-insensitive; you can enter definitions and invoke
 1259: Standard words using upper, lower or mixed case (however,
 1260: @pxref{core-idef, Implementation-defined options, Implementation-defined
 1261: options}).
 1262: 
 1263: ANS Forth only @i{requires} implementations to recognise Standard words
 1264: when they are typed entirely in upper case. Therefore, a Standard
 1265: program must use upper case for all Standard words. You can use whatever
 1266: case you like for words that you define, but in a standard program you
 1267: have to use the words in the same case that you defined them.
 1268: 
 1269: Gforth supports case sensitivity through @code{table}s (case-sensitive
 1270: wordlists, @pxref{Word Lists}).
 1271: 
 1272: Two people have asked how to convert Gforth to case sensitivity; while
 1273: we think this is a bad idea, you can change all wordlists into tables
 1274: like this:
 1275: 
 1276: @example
 1277: ' table-find forth-wordlist wordlist-map @ !
 1278: @end example
 1279: 
 1280: Note that you now have to type the predefined words in the same case
 1281: that we defined them, which are varying.  You may want to convert them
 1282: to your favourite case before doing this operation (I won't explain how,
 1283: because if you are even contemplating to do this, you'd better have
 1284: enough knowledge of Forth systems to know this already).
 1285: 
 1286: @comment ----------------------------------------------
 1287: @node Environment variables, Gforth Files, Upper and lower case,Gforth Environment
 1288: @section Environment variables
 1289: @cindex environment variables
 1290: 
 1291: Gforth uses these environment variables:
 1292: 
 1293: @itemize @bullet
 1294: @item
 1295: @cindex @code{GFORTHHIST} -- environment variable
 1296: @code{GFORTHHIST} -- (Unix systems only) specifies the directory in which to
 1297: open/create the history file, @file{.gforth-history}. Default:
 1298: @code{$HOME}.
 1299: 
 1300: @item
 1301: @cindex @code{GFORTHPATH} -- environment variable
 1302: @code{GFORTHPATH} -- specifies the path used when searching for the gforth image file and
 1303: for Forth source-code files.
 1304: 
 1305: @item
 1306: @cindex @code{GFORTH} -- environment variable
 1307: @code{GFORTH} -- used by @file{gforthmi} @xref{gforthmi}.
 1308: 
 1309: @item
 1310: @cindex @code{GFORTHD} -- environment variable
 1311: @code{GFORTHD} -- used by @file{gforthmi} @xref{gforthmi}.
 1312: 
 1313: @item
 1314: @cindex @code{TMP}, @code{TEMP} - environment variable
 1315: @code{TMP}, @code{TEMP} - (non-Unix systems only) used as a potential
 1316: location for the history file.
 1317: @end itemize
 1318: 
 1319: @comment also POSIXELY_CORRECT LINES COLUMNS HOME but no interest in
 1320: @comment mentioning these.
 1321: 
 1322: All the Gforth environment variables default to sensible values if they
 1323: are not set.
 1324: 
 1325: 
 1326: @comment ----------------------------------------------
 1327: @node Gforth Files, ,Environment variables,Gforth Environment
 1328: @section Gforth files
 1329: @cindex Gforth files
 1330: 
 1331: When you install Gforth on a Unix system, it installs files in these
 1332: locations by default:
 1333: 
 1334: @itemize @bullet
 1335: @item
 1336: @file{/usr/local/bin/gforth}
 1337: @item
 1338: @file{/usr/local/bin/gforthmi}
 1339: @item
 1340: @file{/usr/local/man/man1/gforth.1} - man page.
 1341: @item
 1342: @file{/usr/local/info} - the Info version of this manual.
 1343: @item
 1344: @file{/usr/local/lib/gforth/<version>/...} - Gforth @file{.fi} files.
 1345: @item
 1346: @file{/usr/local/share/gforth/<version>/TAGS} - Emacs TAGS file.
 1347: @item
 1348: @file{/usr/local/share/gforth/<version>/...} - Gforth source files.
 1349: @item
 1350: @file{.../emacs/site-lisp/gforth.el} - Emacs gforth mode.
 1351: @end itemize
 1352: 
 1353: You can select different places for installation by using
 1354: @code{configure} options (listed with @code{configure --help}).
 1355: 
 1356: @c ******************************************************************
 1357: @node Introduction, Words, Gforth Environment, Top
 1358: @comment node-name,     next,           previous, up
 1359: @chapter An Introduction to ANS Forth
 1360: @cindex Forth - an introduction
 1361: 
 1362: The primary purpose of this manual is to document Gforth. However, since
 1363: Forth is not a widely-known language and there is a lack of up-to-date
 1364: teaching material, it seems worthwhile to provide some introductory
 1365: material. @xref{Forth-related information} for other sources of Forth-related
 1366: information.
 1367: 
 1368: The examples in this section should work on any ANS Forth; the
 1369: output shown was produced using Gforth. Each example attempts to
 1370: reproduce the exact output that Gforth produces. If you try out the
 1371: examples (and you should), what you should type is shown @kbd{like this}
 1372: and Gforth's response is shown @code{like this}. The single exception is
 1373: that, where the example shows @key{RET} it means that you should
 1374: press the ``carriage return'' key. Unfortunately, some output formats for
 1375: this manual cannot show the difference between @kbd{this} and
 1376: @code{this} which will make trying out the examples harder (but not
 1377: impossible).
 1378: 
 1379: Forth is an unusual language. It provides an interactive development
 1380: environment which includes both an interpreter and compiler. Forth
 1381: programming style encourages you to break a problem down into many
 1382: @cindex factoring
 1383: small fragments (@dfn{factoring}), and then to develop and test each
 1384: fragment interactively. Forth advocates assert that breaking the
 1385: edit-compile-test cycle used by conventional programming languages can
 1386: lead to great productivity improvements.
 1387: 
 1388: @menu
 1389: * Introducing the Text Interpreter::
 1390: * Stacks and Postfix notation::
 1391: * Your first definition::
 1392: * How does that work?::
 1393: * Forth is written in Forth::
 1394: * Review - elements of a Forth system::
 1395: * Where to go next::
 1396: * Exercises::
 1397: @end menu
 1398: 
 1399: @comment ----------------------------------------------
 1400: @node Introducing the Text Interpreter, Stacks and Postfix notation, Introduction, Introduction
 1401: @section Introducing the Text Interpreter
 1402: @cindex text interpreter
 1403: @cindex outer interpreter
 1404: 
 1405: @c IMO this is too detailed and the pace is too slow for
 1406: @c an introduction.  If you know German, take a look at
 1407: @c http://www.complang.tuwien.ac.at/anton/lvas/skriptum-stack.html 
 1408: @c to see how I do it - anton 
 1409: 
 1410: @c nac-> Where I have accepted your comments 100% and modified the text
 1411: @c accordingly, I have deleted your comments. Elsewhere I have added a
 1412: @c response like this to attempt to rationalise what I have done. Of
 1413: @c course, this is a very clumsy mechanism for something that would be
 1414: @c done far more efficiently over a beer. Please delete any dialogue
 1415: @c you consider closed.
 1416: 
 1417: When you invoke the Forth image, you will see a startup banner printed
 1418: and nothing else (if you have Gforth installed on your system, try
 1419: invoking it now, by typing @kbd{gforth@key{RET}}). Forth is now running
 1420: its command line interpreter, which is called the @dfn{Text Interpreter}
 1421: (also known as the @dfn{Outer Interpreter}).  (You will learn a lot
 1422: about the text interpreter as you read through this chapter, but
 1423: @pxref{The Text Interpreter} for more detail).
 1424: 
 1425: Although it's not obvious, Forth is actually waiting for your
 1426: input. Type a number and press the @key{RET} key:
 1427: 
 1428: @example
 1429: @kbd{45@key{RET}}  ok
 1430: @end example
 1431: 
 1432: Rather than give you a prompt to invite you to input something, the text
 1433: interpreter prints a status message @i{after} it has processed a line
 1434: of input. The status message in this case (``@code{ ok}'' followed by
 1435: carriage-return) indicates that the text interpreter was able to process
 1436: all of your input successfully. Now type something illegal:
 1437: 
 1438: @example
 1439: @kbd{qwer341@key{RET}}
 1440: :1: Undefined word
 1441: qwer341
 1442: ^^^^^^^
 1443: $400D2BA8 Bounce
 1444: $400DBDA8 no.extensions
 1445: @end example
 1446: 
 1447: The exact text, other than the ``Undefined word'' may differ slightly on
 1448: your system, but the effect is the same; when the text interpreter
 1449: detects an error, it discards any remaining text on a line, resets
 1450: certain internal state and prints an error message. @xref{Error
 1451: messages} for a detailed description of error messages.
 1452: 
 1453: The text interpreter waits for you to press carriage-return, and then
 1454: processes your input line. Starting at the beginning of the line, it
 1455: breaks the line into groups of characters separated by spaces. For each
 1456: group of characters in turn, it makes two attempts to do something:
 1457: 
 1458: @itemize @bullet
 1459: @item
 1460: @cindex name dictionary
 1461: It tries to treat it as a command. It does this by searching a @dfn{name
 1462: dictionary}. If the group of characters matches an entry in the name
 1463: dictionary, the name dictionary provides the text interpreter with
 1464: information that allows the text interpreter perform some actions. In
 1465: Forth jargon, we say that the group
 1466: @cindex word
 1467: @cindex definition
 1468: @cindex execution token
 1469: @cindex xt
 1470: of characters names a @dfn{word}, that the dictionary search returns an
 1471: @dfn{execution token (xt)} corresponding to the @dfn{definition} of the
 1472: word, and that the text interpreter executes the xt. Often, the terms
 1473: @dfn{word} and @dfn{definition} are used interchangeably.
 1474: @item
 1475: If the text interpreter fails to find a match in the name dictionary, it
 1476: tries to treat the group of characters as a number in the current number
 1477: base (when you start up Forth, the current number base is base 10). If
 1478: the group of characters legitimately represents a number, the text
 1479: interpreter pushes the number onto a stack (we'll learn more about that
 1480: in the next section).
 1481: @end itemize
 1482: 
 1483: If the text interpreter is unable to do either of these things with any
 1484: group of characters, it discards the group of characters and the rest of
 1485: the line, then prints an error message. If the text interpreter reaches
 1486: the end of the line without error, it prints the status message ``@code{ ok}''
 1487: followed by carriage-return.
 1488: 
 1489: This is the simplest command we can give to the text interpreter:
 1490: 
 1491: @example
 1492: @key{RET}  ok
 1493: @end example
 1494: 
 1495: The text interpreter did everything we asked it to do (nothing) without
 1496: an error, so it said that everything is ``@code{ ok}''. Try a slightly longer
 1497: command:
 1498: 
 1499: @example
 1500: @kbd{12 dup fred dup@key{RET}}
 1501: :1: Undefined word
 1502: 12 dup fred dup
 1503:        ^^^^
 1504: $400D2BA8 Bounce
 1505: $400DBDA8 no.extensions
 1506: @end example
 1507: 
 1508: When you press the carriage-return key, the text interpreter starts to
 1509: work its way along the line:
 1510: 
 1511: @itemize @bullet
 1512: @item
 1513: When it gets to the space after the @code{2}, it takes the group of
 1514: characters @code{12} and looks them up in the name
 1515: dictionary@footnote{We can't tell if it found them or not, but assume
 1516: for now that it did not}. There is no match for this group of characters
 1517: in the name dictionary, so it tries to treat them as a number. It is
 1518: able to do this successfully, so it puts the number, 12, ``on the stack''
 1519: (whatever that means).
 1520: @item
 1521: The text interpreter resumes scanning the line and gets the next group
 1522: of characters, @code{dup}. It looks it up in the name dictionary and
 1523: (you'll have to take my word for this) finds it, and executes the word
 1524: @code{dup} (whatever that means).
 1525: @item
 1526: Once again, the text interpreter resumes scanning the line and gets the
 1527: group of characters @code{fred}. It looks them up in the name
 1528: dictionary, but can't find them. It tries to treat them as a number, but
 1529: they don't represent any legal number.
 1530: @end itemize
 1531: 
 1532: At this point, the text interpreter gives up and prints an error
 1533: message. The error message shows exactly how far the text interpreter
 1534: got in processing the line. In particular, it shows that the text
 1535: interpreter made no attempt to do anything with the final character
 1536: group, @code{dup}, even though we have good reason to believe that the
 1537: text interpreter would have no problem looking that word up and
 1538: executing it a second time.
 1539: 
 1540: 
 1541: @comment ----------------------------------------------
 1542: @node Stacks and Postfix notation, Your first definition, Introducing the Text Interpreter, Introduction
 1543: @section Stacks, postfix notation and parameter passing
 1544: @cindex text interpreter
 1545: @cindex outer interpreter
 1546: 
 1547: In procedural programming languages (like C and Pascal), the
 1548: building-block of programs is the @dfn{function} or @dfn{procedure}. These
 1549: functions or procedures are called with @dfn{explicit parameters}. For
 1550: example, in C we might write:
 1551: 
 1552: @example
 1553: total = total + new_volume(length,height,depth);
 1554: @end example
 1555: 
 1556: @noindent
 1557: where new_volume is a function-call to another piece of code, and total,
 1558: length, height and depth are all variables. length, height and depth are
 1559: parameters to the function-call.
 1560: 
 1561: In Forth, the equivalent of the function or procedure is the
 1562: @dfn{definition} and parameters are implicitly passed between
 1563: definitions using a shared stack that is visible to the
 1564: programmer. Although Forth does support variables, the existence of the
 1565: stack means that they are used far less often than in most other
 1566: programming languages. When the text interpreter encounters a number, it
 1567: will place (@dfn{push}) it on the stack. There are several stacks (the
 1568: actual number is implementation-dependent ...) and the particular stack
 1569: used for any operation is implied unambiguously by the operation being
 1570: performed. The stack used for all integer operations is called the @dfn{data
 1571: stack} and, since this is the stack used most commonly, references to
 1572: ``the data stack'' are often abbreviated to ``the stack''.
 1573: 
 1574: The stacks have a last-in, first-out (LIFO) organisation. If you type:
 1575: 
 1576: @example
 1577: @kbd{1 2 3@key{RET}}  ok
 1578: @end example
 1579: 
 1580: Then this instructs the text interpreter to placed three numbers on the
 1581: (data) stack. An analogy for the behaviour of the stack is to take a
 1582: pack of playing cards and deal out the ace (1), 2 and 3 into a pile on
 1583: the table. The 3 was the last card onto the pile (``last-in'') and if
 1584: you take a card off the pile then, unless you're prepared to fiddle a
 1585: bit, the card that you take off will be the 3 (``first-out''). The
 1586: number that will be first-out of the stack is called the @dfn{top of
 1587: stack}, which
 1588: @cindex TOS definition
 1589: is often abbreviated to @dfn{TOS}.
 1590: 
 1591: To understand how parameters are passed in Forth, consider the
 1592: behaviour of the definition @code{+} (pronounced ``plus''). You will not
 1593: be surprised to learn that this definition performs addition. More
 1594: precisely, it adds two number together and produces a result. Where does
 1595: it get the two numbers from? It takes the top two numbers off the
 1596: stack. Where does it place the result? On the stack. You can act-out the
 1597: behaviour of @code{+} with your playing cards like this:
 1598: 
 1599: @itemize @bullet
 1600: @item
 1601: Pick up two cards from the stack on the table
 1602: @item
 1603: Stare at them intently and ask yourself ``what @i{is} the sum of these two
 1604: numbers''
 1605: @item
 1606: Decide that the answer is 5
 1607: @item
 1608: Shuffle the two cards back into the pack and find a 5
 1609: @item
 1610: Put a 5 on the remaining ace that's on the table.
 1611: @end itemize
 1612: 
 1613: If you don't have a pack of cards handy but you do have Forth running,
 1614: you can use the definition @code{.s} to show the current state of the stack,
 1615: without affecting the stack. Type:
 1616: 
 1617: @example
 1618: @kbd{clearstack 1 2 3@key{RET}} ok
 1619: @kbd{.s@key{RET}} <3> 1 2 3  ok
 1620: @end example
 1621: 
 1622: The text interpreter looks up the word @code{clearstack} and executes
 1623: it; it tidies up the stack and removes any entries that may have been
 1624: left on it by earlier examples. The text interpreter pushes each of the
 1625: three numbers in turn onto the stack. Finally, the text interpreter
 1626: looks up the word @code{.s} and executes it. The effect of executing
 1627: @code{.s} is to print the ``<3>'' (the total number of items on the stack)
 1628: followed by a list of all the items on the stack; the item on the far
 1629: right-hand side is the TOS.
 1630: 
 1631: You can now type:
 1632: 
 1633: @example
 1634: @kbd{+ .s@key{RET}} <2> 1 5  ok
 1635: @end example
 1636: 
 1637: @noindent
 1638: which is correct; there are now 2 items on the stack and the result of
 1639: the addition is 5.
 1640: 
 1641: If you're playing with cards, try doing a second addition: pick up the
 1642: two cards, work out that their sum is 6, shuffle them into the pack,
 1643: look for a 6 and place that on the table. You now have just one item on
 1644: the stack. What happens if you try to do a third addition? Pick up the
 1645: first card, pick up the second card -- ah! There is no second card. This
 1646: is called a @dfn{stack underflow} and consitutes an error. If you try to
 1647: do the same thing with Forth it will report an error (probably a Stack
 1648: Underflow or an Invalid Memory Address error).
 1649: 
 1650: The opposite situation to a stack underflow is a @dfn{stack overflow},
 1651: which simply accepts that there is a finite amount of storage space
 1652: reserved for the stack. To stretch the playing card analogy, if you had
 1653: enough packs of cards and you piled the cards up on the table, you would
 1654: eventually be unable to add another card; you'd hit the ceiling. Gforth
 1655: allows you to set the maximum size of the stacks. In general, the only
 1656: time that you will get a stack overflow is because a definition has a
 1657: bug in it and is generating data on the stack uncontrollably.
 1658: 
 1659: There's one final use for the playing card analogy. If you model your
 1660: stack using a pack of playing cards, the maximum number of items on
 1661: your stack will be 52 (I assume you didn't use the Joker). The maximum
 1662: @i{value} of any item on the stack is 13 (the King). In fact, the only
 1663: possible numbers are positive integer numbers 1 through 13; you can't
 1664: have (for example) 0 or 27 or 3.52 or -2. If you change the way you
 1665: think about some of the cards, you can accommodate different
 1666: numbers. For example, you could think of the Jack as representing 0,
 1667: the Queen as representing -1 and the King as representing -2. Your
 1668: @i{range} remains unchanged (you can still only represent a total of 13
 1669: numbers) but the numbers that you can represent are -2 through 10.
 1670: 
 1671: In that analogy, the limit was the amount of information that a single
 1672: stack entry could hold, and Forth has a similar limit. In Forth, the
 1673: size of a stack entry is called a @dfn{cell}. The actual size of a cell is
 1674: implementation dependent and affects the maximum value that a stack
 1675: entry can hold. A Standard Forth provides a cell size of at least
 1676: 16-bits, and most desktop systems use a cell size of 32-bits.
 1677: 
 1678: Forth does not do any type checking for you, so you are free to
 1679: manipulate and combine stack items in any way you wish. A convenient way
 1680: of treating stack items is as 2's complement signed integers, and that
 1681: is what Standard words like @code{+} do. Therefore you can type:
 1682: 
 1683: @example
 1684: @kbd{-5 12 + .s@key{RET}} <1> 7  ok
 1685: @end example
 1686: 
 1687: If you use numbers and definitions like @code{+} in order to turn Forth
 1688: into a great big pocket calculator, you will realise that it's rather
 1689: different from a normal calculator. Rather than typing 2 + 3 = you had
 1690: to type 2 3 + (ignore the fact that you had to use @code{.s} to see the
 1691: result). The terminology used to describe this difference is to say that
 1692: your calculator uses @dfn{Infix Notation} (parameters and operators are
 1693: mixed) whilst Forth uses @dfn{Postfix Notation} (parameters and
 1694: operators are separate), also called @dfn{Reverse Polish Notation}.
 1695: 
 1696: Whilst postfix notation might look confusing to begin with, it has
 1697: several important advantages:
 1698: 
 1699: @itemize @bullet
 1700: @item
 1701: it is unambiguous
 1702: @item
 1703: it is more concise
 1704: @item
 1705: it fits naturally with a stack-based system
 1706: @end itemize
 1707: 
 1708: To examine these claims in more detail, consider these sums:
 1709: 
 1710: @example
 1711: 6 + 5 * 4 =
 1712: 4 * 5 + 6 =
 1713: @end example
 1714: 
 1715: If you're just learning maths or your maths is very rusty, you will
 1716: probably come up with the answer 44 for the first and 26 for the
 1717: second. If you are a bit of a whizz at maths you will remember the
 1718: @i{convention} that multiplication takes precendence over addition, and
 1719: you'd come up with the answer 26 both times. To explain the answer 26
 1720: to someone who got the answer 44, you'd probably rewrite the first sum
 1721: like this:
 1722: 
 1723: @example
 1724: 6 + (5 * 4) =
 1725: @end example
 1726: 
 1727: If what you really wanted was to perform the addition before the
 1728: multiplication, you would have to use parentheses to force it.
 1729: 
 1730: If you did the first two sums on a pocket calculator you would probably
 1731: get the right answers, unless you were very cautious and entered them using
 1732: these keystroke sequences:
 1733: 
 1734: 6 + 5 = * 4 =
 1735: 4 * 5 = + 6 =
 1736: 
 1737: Postfix notation is unambiguous because the order that the operators
 1738: are applied is always explicit; that also means that parentheses are
 1739: never required. The operators are @i{active} (the act of quoting the
 1740: operator makes the operation occur) which removes the need for ``=''.
 1741: 
 1742: The sum 6 + 5 * 4 can be written (in postfix notation) in two
 1743: equivalent ways:
 1744: 
 1745: @example
 1746: 6 5 4 * +      or:
 1747: 5 4 * 6 +
 1748: @end example
 1749: 
 1750: An important thing that you should notice about this notation is that
 1751: the @i{order} of the numbers does not change; if you want to subtract
 1752: 2 from 10 you type @code{10 2 -}.
 1753: 
 1754: The reason that Forth uses postfix notation is very simple to explain: it
 1755: makes the implementation extremely simple, and it follows naturally from
 1756: using the stack as a mechanism for passing parameters. Another way of
 1757: thinking about this is to realise that all Forth definitions are
 1758: @i{active}; they execute as they are encountered by the text
 1759: interpreter. The result of this is that the syntax of Forth is trivially
 1760: simple.
 1761: 
 1762: 
 1763: 
 1764: @comment ----------------------------------------------
 1765: @node Your first definition, How does that work?, Stacks and Postfix notation, Introduction
 1766: @section Your first Forth definition
 1767: @cindex first definition
 1768: 
 1769: Until now, the examples we've seen have been trivial; we've just been
 1770: using Forth as a bigger-than-pocket calculator. Also, each calculation
 1771: we've shown has been a ``one-off'' -- to repeat it we'd need to type it in
 1772: again@footnote{That's not quite true. If you press the up-arrow key on
 1773: your keyboard you should be able to scroll back to any earlier command,
 1774: edit it and re-enter it.} In this section we'll see how to add new
 1775: words to Forth's vocabulary.
 1776: 
 1777: The easiest way to create a new word is to use a @dfn{colon
 1778: definition}. We'll define a few and try them out before worrying too
 1779: much about how they work. Try typing in these examples; be careful to
 1780: copy the spaces accurately:
 1781: 
 1782: @example
 1783: : add-two 2 + . ;
 1784: : greet ." Hello and welcome" ;
 1785: : demo 5 add-two ;
 1786: @end example
 1787: 
 1788: @noindent
 1789: Now try them out:
 1790: 
 1791: @example
 1792: @kbd{greet@key{RET}} Hello and welcome  ok
 1793: @kbd{greet greet@key{RET}} Hello and welcomeHello and welcome  ok
 1794: @kbd{4 add-two@key{RET}} 6  ok
 1795: @kbd{demo@key{RET}} 7  ok
 1796: @kbd{9 greet demo add-two@key{RET}} Hello and welcome7 11  ok
 1797: @end example
 1798: 
 1799: The first new thing that we've introduced here is the pair of words
 1800: @code{:} and @code{;}. These are used to start and terminate a new
 1801: definition, respectively. The first word after the @code{:} is the name
 1802: for the new definition.
 1803: 
 1804: As you can see from the examples, a definition is built up of words that
 1805: have already been defined; Forth makes no distinction between
 1806: definitions that existed when you started the system up, and those that
 1807: you define yourself.
 1808: 
 1809: The examples also introduce the words @code{.} (dot), @code{."}
 1810: (dot-quote) and @code{dup} (dewp). Dot takes the value from the top of
 1811: the stack and displays it. It's like @code{.s} except that it only
 1812: displays the top item of the stack and it is destructive; after it has
 1813: executed, the number is no longer on the stack. There is always one
 1814: space printed after the number, and no spaces before it. Dot-quote
 1815: defines a string (a sequence of characters) that will be printed when
 1816: the word is executed. The string can contain any printable characters
 1817: except @code{"}. A @code{"} has a special function; it is not a Forth
 1818: word but it acts as a delimiter (the way that delimiters work is
 1819: described in the next section). Finally, @code{dup} duplicates the value
 1820: at the top of the stack. Try typing @code{5 dup .s} to see what it does.
 1821: 
 1822: We already know that the text interpreter searches through the
 1823: dictionary to locate names. If you've followed the examples earlier, you
 1824: will already have a definition called @code{add-two}. Lets try modifying
 1825: it by typing in a new definition:
 1826: 
 1827: @example
 1828: @kbd{: add-two dup . ." + 2 =" 2 + . ;@key{RET}} redefined add-two  ok
 1829: @end example
 1830: 
 1831: Forth recognised that we were defining a word that already exists, and
 1832: printed a message to warn us of that fact. Let's try out the new
 1833: definition:
 1834: 
 1835: @example
 1836: @kbd{9 add-two@key{RET}} 9 + 2 =11  ok
 1837: @end example
 1838: 
 1839: @noindent
 1840: All that we've actually done here, though, is to create a new
 1841: definition, with a particular name. The fact that there was already a
 1842: definition with the same name did not make any difference to the way
 1843: that the new definition was created (except that Forth printed a warning
 1844: message). The old definition of add-two still exists (try @code{demo}
 1845: again to see that this is true). Any new definition will use the new
 1846: definition of @code{add-two}, but old definitions continue to use the
 1847: version that already existed at the time that they were @code{compiled}.
 1848: 
 1849: Before you go on to the next section, try defining and redefining some
 1850: words of your own.
 1851: 
 1852: @comment ----------------------------------------------
 1853: @node How does that work?, Forth is written in Forth, Your first definition, Introduction
 1854: @section How does that work?
 1855: @cindex parsing words
 1856: 
 1857: @c That's pretty deep (IMO way too deep) for an introduction. - anton
 1858: 
 1859: @c Is it a good idea to talk about the interpretation semantics of a
 1860: @c number? We don't have an xt to go along with it. - anton
 1861: 
 1862: @c Now that I have eliminated execution semantics, I wonder if it would not
 1863: @c be better to keep them (or add run-time semantics), to make it easier to
 1864: @c explain what compilation semantics usually does. - anton
 1865: 
 1866: @c nac-> I removed the term ``default compilation sematics'' from the
 1867: @c introductory chapter. Removing ``execution semantics'' was making
 1868: @c everything simpler to explain, then I think the use of this term made
 1869: @c everything more complex again. I replaced it with ``default
 1870: @c semantics'' (which is used elsewhere in the manual) by which I mean
 1871: @c ``a definition that has neither the immediate nor the compile-only
 1872: @c flag set''. I reworded big chunks of the ``how does that work''
 1873: @c section (and, unusually for me, I think I even made it shorter!).  See
 1874: @c what you think -- I know I have not addressed your primary concern
 1875: @c that it is too heavy-going for an introduction. From what I understood
 1876: @c of your course notes it looks as though they might be a good framework. 
 1877: @c Things that I've tried to capture here are some things that came as a
 1878: @c great revelation here when I first understood them. Also, I like the
 1879: @c fact that a very simple code example shows up almost all of the issues
 1880: @c that you need to understand to see how Forth works. That's unique and
 1881: @c worthwhile to emphasise.
 1882: 
 1883: Now we're going to take another look at the definition of @code{add-two}
 1884: from the previous section. From our knowledge of the way that the text
 1885: interpreter works, we would have expected this result when we tried to
 1886: define @code{add-two}:
 1887: 
 1888: @example
 1889: @kbd{: add-two 2 + . ;@key{RET}}
 1890:   ^^^^^^^
 1891: Error: Undefined word
 1892: @end example
 1893: 
 1894: The reason that this didn't happen is bound up in the way that @code{:}
 1895: works. The word @code{:} does two special things. The first special
 1896: thing that it does prevents the text interpreter from ever seeing the
 1897: characters @code{add-two}. The text interpreter uses a variable called
 1898: @cindex modifying >IN
 1899: @code{>IN} (pronounced ``to-in'') to keep track of where it is in the
 1900: input line. When it encounters the word @code{:} it behaves in exactly
 1901: the same way as it does for any other word; it looks it up in the name
 1902: dictionary, finds its xt and executes it. When @code{:} executes, it
 1903: looks at the input buffer, finds the word @code{add-two} and advances the
 1904: value of @code{>IN} to point past it. It then does some other stuff
 1905: associated with creating the new definition (including creating an entry
 1906: for @code{add-two} in the name dictionary). When the execution of @code{:}
 1907: completes, control returns to the text interpreter, which is oblivious
 1908: to the fact that it has been tricked into ignoring part of the input
 1909: line.
 1910: 
 1911: @cindex parsing words
 1912: Words like @code{:} -- words that advance the value of @code{>IN} and so
 1913: prevent the text interpreter from acting on the whole of the input line
 1914: -- are called @dfn{parsing words}.
 1915: 
 1916: @cindex @code{state} - effect on the text interpreter
 1917: @cindex text interpreter - effect of state
 1918: The second special thing that @code{:} does is change the value of a
 1919: variable called @code{state}, which affects the way that the text
 1920: interpreter behaves. When Gforth starts up, @code{state} has the value
 1921: 0, and the text interpreter is said to be @dfn{interpreting}. During a
 1922: colon definition (started with @code{:}), @code{state} is set to -1 and
 1923: the text interpreter is said to be @dfn{compiling}.
 1924: 
 1925: In this example, the text interpreter is compiling when it processes the
 1926: string ``@code{2 + . ;}''. It still breaks the string down into
 1927: character sequences in the same way. However, instead of pushing the
 1928: number @code{2} onto the stack, it lays down (@dfn{compiles}) some magic
 1929: into the definition of @code{add-two} that will make the number @code{2} get
 1930: pushed onto the stack when @code{add-two} is @dfn{executed}. Similarly,
 1931: the behaviours of @code{+} and @code{.} are also compiled into the
 1932: definition.
 1933: 
 1934: One category of words don't get compiled. These so-called @dfn{immediate
 1935: words} get executed (performed @i{now}) regardless of whether the text
 1936: interpreter is interpreting or compiling. The word @code{;} is an
 1937: immediate word. Rather than being compiled into the definition, it
 1938: executes. Its effect is to terminate the current definition, which
 1939: includes changing the value of @code{state} back to 0.
 1940: 
 1941: When you execute @code{add-two}, it has a @dfn{run-time effect} that is
 1942: exactly the same as if you had typed @code{2 + . @key{RET}} outside of a
 1943: definition.
 1944: 
 1945: In Forth, every word or number can be described in terms of two
 1946: properties:
 1947: 
 1948: @itemize @bullet
 1949: @item
 1950: @cindex interpretation semantics
 1951: Its @dfn{interpretation semantics} describe how it will behave when the
 1952: text interpreter encounters it in @dfn{interpret} state. The
 1953: interpretation semantics of a word are represented by an @dfn{execution
 1954: token}.
 1955: @item
 1956: @cindex compilation semantics
 1957: Its @dfn{compilation semantics} describe how it will behave when the
 1958: text interpreter encounters it in @dfn{compile} state. The compilation
 1959: semantics of a word are represented in an implementation-dependent way;
 1960: Gforth uses a @dfn{compilation token}.
 1961: @end itemize
 1962: 
 1963: @noindent
 1964: Numbers are always treated in a fixed way:
 1965: 
 1966: @itemize @bullet
 1967: @item
 1968: When the number is @dfn{interpreted}, its behaviour is to push the
 1969: number onto the stack.
 1970: @item
 1971: When the number is @dfn{compiled}, a piece of code is appended to the
 1972: current definition that pushes the number when it runs. (In other words,
 1973: the compilation semantics of a number are to postpone its interpretation
 1974: semantics until the run-time of the definition that it is being compiled
 1975: into.)
 1976: @end itemize
 1977: 
 1978: Words don't behave in such a regular way, but most have @i{default
 1979: semantics} which means that they behave like this:
 1980: 
 1981: @itemize @bullet
 1982: @item
 1983: The @dfn{interpretation semantics} of the word are to do something useful.
 1984: @item
 1985: The @dfn{compilation semantics} of the word are to append its
 1986: @dfn{interpretation semantics} to the current definition (so that its
 1987: run-time behaviour is to do something useful).
 1988: @end itemize
 1989: 
 1990: @cindex immediate words
 1991: The actual behaviour of any particular word can be controlled by using
 1992: the words @code{immediate} and @code{compile-only} when the word is
 1993: defined. These words set flags in the name dictionary entry of the most
 1994: recently defined word, and these flags are retrieved by the text
 1995: interpreter when it finds the word in the name dictionary.
 1996: 
 1997: A word that is marked as @dfn{immediate} has compilation semantics that
 1998: are identical to its interpretation semantics. In other words, it
 1999: behaves like this:
 2000: 
 2001: @itemize @bullet
 2002: @item
 2003: The @dfn{interpretation semantics} of the word are to do something useful.
 2004: @item
 2005: The @dfn{compilation semantics} of the word are to do something useful
 2006: (and actually the same thing); i.e., it is executed during compilation.
 2007: @end itemize
 2008: 
 2009: Marking a word as @dfn{compile-only} prohibits the text interpreter from
 2010: performing the interpretation semantics of the word directly; an attempt
 2011: to do so will generate an error. It is never necessary to use
 2012: @code{compile-only} (and it is not even part of ANS Forth, though it is
 2013: provided by many implementations) but it is good etiquette to apply it
 2014: to a word that will not behave correctly (and might have unexpected
 2015: side-effects) in interpret state. For example, it is only legal to use
 2016: the conditional word @code{IF} within a definition. If you forget this
 2017: and try to use it elsewhere, the fact that (in Gforth) it is marked as
 2018: @code{compile-only} allows the text interpreter to generate a helpful
 2019: error message rather than subjecting you to the consequences of your
 2020: folly.
 2021: 
 2022: This example shows the difference between an immediate and a
 2023: non-immediate word:
 2024: 
 2025: @example
 2026: : show-state state @@ . ;
 2027: : show-state-now show-state ; immediate
 2028: : word1 show-state ;
 2029: : word2 show-state-now ;
 2030: @end example
 2031: 
 2032: The word @code{immediate} after the definition of @code{show-state-now}
 2033: makes that word an immediate word. These definitions introduce a new
 2034: word: @code{@@} (pronounced ``fetch''). This word fetches the value of a
 2035: variable, and leaves it on the stack. Therefore, the behaviour of
 2036: @code{show-state} is to print a number that represents the current value
 2037: of @code{state}.
 2038: 
 2039: When you execute @code{word1}, it prints the number 0, indicating that
 2040: the system is interpreting. When the text interpreter compiled the
 2041: definition of @code{word1}, it encountered @code{show-state} whose
 2042: compilation semantics are to append its interpretation semantics to the
 2043: current definition. When you execute @code{word1}, it performs the
 2044: interpretation semantics of @code{show-state}.  At the time that @code{word1}
 2045: (and therefore @code{show-state}) are executed, the system is
 2046: interpreting.
 2047: 
 2048: When you pressed @key{RET} after entering the definition of @code{word2},
 2049: you should have seen the number -1 printed, followed by ``@code{
 2050: ok}''. When the text interpreter compiled the definition of
 2051: @code{word2}, it encountered @code{show-state-now}, an immediate word,
 2052: whose compilation semantics are therefore to perform its interpretation
 2053: semantics. It is executed straight away (even before the text
 2054: interpreter has moved on to process another group of characters; the
 2055: @code{;} in this example). The effect of executing it are to display the
 2056: value of @code{state} @i{at the time that the definition of}
 2057: @code{word2} @i{is being defined}. Printing -1 demonstrates that the
 2058: system is compiling at this time. If you execute @code{word2} it does
 2059: nothing at all.
 2060: 
 2061: @cindex @code{."}, how it works
 2062: Before leaving the subject of immediate words, consider the behaviour of
 2063: @code{."} in the definition of @code{greet}, in the previous
 2064: section. This word is both a parsing word and an immediate word. Notice
 2065: that there is a space between @code{."} and the start of the text
 2066: @code{Hello and welcome}, but that there is no space between the last
 2067: letter of @code{welcome} and the @code{"} character. The reason for this
 2068: is that @code{."} is a Forth word; it must have a space after it so that
 2069: the text interpreter can identify it. The @code{"} is not a Forth word;
 2070: it is a @dfn{delimiter}. The examples earlier show that, when the string
 2071: is displayed, there is neither a space before the @code{H} nor after the
 2072: @code{e}. Since @code{."} is an immediate word, it executes at the time
 2073: that @code{greet} is defined. When it executes, its behaviour is to
 2074: search forward in the input line looking for the delimiter. When it
 2075: finds the delimiter, it updates @code{>IN} to point past the
 2076: delimiter. It also compiles some magic code into the definition of
 2077: @code{greet}; the xt of a run-time routine that prints a text string. It
 2078: compiles the string @code{Hello and welcome} into memory so that it is
 2079: available to be printed later. When the text interpreter gains control,
 2080: the next word it finds in the input stream is @code{;} and so it
 2081: terminates the definition of @code{greet}.
 2082: 
 2083: 
 2084: @comment ----------------------------------------------
 2085: @node Forth is written in Forth, Review - elements of a Forth system, How does that work?, Introduction
 2086: @section Forth is written in Forth
 2087: @cindex structure of Forth programs
 2088: 
 2089: When you start up a Forth compiler, a large number of definitions
 2090: already exist. In Forth, you develop a new application using bottom-up
 2091: programming techniques to create new definitions that are defined in
 2092: terms of existing definitions. As you create each definition you can
 2093: test and debug it interactively.
 2094: 
 2095: If you have tried out the examples in this section, you will probably
 2096: have typed them in by hand; when you leave Gforth, your definitions will
 2097: be lost. You can avoid this by using a text editor to enter Forth source
 2098: code into a file, and then loading code from the file using
 2099: @code{include} (@xref{Forth source files}). A Forth source file is
 2100: processed by the text interpreter, just as though you had typed it in by
 2101: hand@footnote{Actually, there are some subtle differences -- see
 2102: @ref{The Text Interpreter}.}.
 2103: 
 2104: Gforth also supports the traditional Forth alternative to using text
 2105: files for program entry (@xref{Blocks}).
 2106: 
 2107: In common with many, if not most, Forth compilers, most of Gforth is
 2108: actually written in Forth. All of the @file{.fs} files in the
 2109: installation directory@footnote{For example,
 2110: @file{/usr/local/share/gforth...}} are Forth source files, which you can
 2111: study to see examples of Forth programming.
 2112: 
 2113: Gforth maintains a history file that records every line that you type to
 2114: the text interpreter. This file is preserved between sessions, and is
 2115: used to provide a command-line recall facility. If you enter long
 2116: definitions by hand, you can use a text editor to paste them out of the
 2117: history file into a Forth source file for reuse at a later time
 2118: (@pxref{Command-line editing} for more information).
 2119: 
 2120: 
 2121: @comment ----------------------------------------------
 2122: @node Review - elements of a Forth system, Where to go next, Forth is written in Forth, Introduction
 2123: @section Review - elements of a Forth system
 2124: @cindex elements of a Forth system
 2125: 
 2126: To summarise this chapter:
 2127: 
 2128: @itemize @bullet
 2129: @item
 2130: Forth programs use @dfn{factoring} to break a problem down into small
 2131: fragments called @dfn{words} or @dfn{definitions}.
 2132: @item
 2133: Forth program development is an interactive process.
 2134: @item
 2135: The main command loop that accepts input, and controls both
 2136: interpretation and compilation, is called the @dfn{text interpreter}
 2137: (also known as the @dfn{outer interpreter}).
 2138: @item
 2139: Forth has a very simple syntax, consisting of words and numbers
 2140: separated by spaces or carriage-return characters. Any additional syntax
 2141: is imposed by @dfn{parsing words}.
 2142: @item
 2143: Forth uses a stack to pass parameters between words. As a result, it
 2144: uses postfix notation.
 2145: @item
 2146: To use a word that has previously been defined, the text interpreter
 2147: searches for the word in the @dfn{name dictionary}.
 2148: @item
 2149: Words have @dfn{interpretation semantics} and @dfn{compilation semantics}.
 2150: @item
 2151: The text interpreter uses the value of @code{state} to select between
 2152: the use of the @dfn{interpretation semantics} and the  @dfn{compilation
 2153: semantics} of a word that it encounters.
 2154: @item
 2155: The relationship between the @dfn{interpretation semantics} and
 2156: @dfn{compilation semantics} for a word
 2157: depend upon the way in which the word was defined (for example, whether
 2158: it is an @dfn{immediate} word).
 2159: @item
 2160: Forth definitions can be implemented in Forth (called @dfn{high-level
 2161: definitions}) or in some other way (usually a lower-level language and
 2162: as a result often called @dfn{low-level definitions}, @dfn{code
 2163: definitions} or @dfn{primitives}).
 2164: @item
 2165: Many Forth systems are implemented mainly in Forth.
 2166: @end itemize
 2167: 
 2168: 
 2169: @comment ----------------------------------------------
 2170: @node Where to go next,Exercises,Review - elements of a Forth system, Introduction
 2171: @section Where To Go Next
 2172: @cindex where to go next
 2173: 
 2174: Amazing as it may seem, if you have read (and understood) this far, you
 2175: know almost all the fundamentals about the inner workings of a Forth
 2176: system. You certainly know enough to be able to read and understand the
 2177: rest of this manual and the ANS Forth document, to learn more about the
 2178: facilities that Forth in general and Gforth in particular provide. Even
 2179: scarier, you know almost enough to implement your own Forth system.
 2180: However, that's not a good idea just yet... better to try writing some
 2181: programs in Gforth.
 2182: 
 2183: Forth has such a rich vocabulary that it can be hard to know where to
 2184: start in learning it. This section suggests a few sets of words that are
 2185: enough to write small but useful programs. Use the word index in this
 2186: document to learn more about each word, then try it out and try to write
 2187: small definitions using it. Start by experimenting with these words:
 2188: 
 2189: @itemize @bullet
 2190: @item
 2191: Arithmetic: @code{+ - * / /MOD */ ABS INVERT}
 2192: @item
 2193: Comparison: @code{MIN MAX =}
 2194: @item
 2195: Logic: @code{AND OR XOR NOT}
 2196: @item
 2197: Stack manipulation: @code{DUP DROP SWAP OVER}
 2198: @item
 2199: Loops and decisions: @code{IF ELSE ENDIF ?DO I LOOP}
 2200: @item
 2201: Input/Output: @code{. ." EMIT CR KEY}
 2202: @item
 2203: Defining words: @code{: ; CREATE}
 2204: @item
 2205: Memory allocation words: @code{ALLOT ,}
 2206: @item
 2207: Tools: @code{SEE WORDS .S MARKER}
 2208: @end itemize
 2209: 
 2210: When you have mastered those, go on to:
 2211: 
 2212: @itemize @bullet
 2213: @item
 2214: More defining words: @code{VARIABLE CONSTANT VALUE TO CREATE DOES>}
 2215: @item
 2216: Memory access: @code{@@ !}
 2217: @end itemize
 2218: 
 2219: When you have mastered these, there's nothing for it but to read through
 2220: the whole of this manual and find out what you've missed.
 2221: 
 2222: @comment ----------------------------------------------
 2223: @node Exercises, ,Where to go next, Introduction
 2224: @section Exercises
 2225: @cindex exercises
 2226: 
 2227: TODO: provide a set of programming excercises linked into the stuff done
 2228: already and into other sections of the manual. Provide solutions to all
 2229: the exercises in a .fs file in the distribution.
 2230: 
 2231: @c Get some inspiration from Starting Forth and Kelly&Spies.
 2232: 
 2233: @c excercises:
 2234: @c 1. take inches and convert to feet and inches.
 2235: @c 2. take temperature and convert from fahrenheight to celcius;
 2236: @c    may need to care about symmetric vs floored??
 2237: @c 3. take input line and do character substitution
 2238: @c    to encipher or decipher
 2239: @c 4. as above but work on a file for in and out
 2240: @c 5. take input line and convert to pig-latin 
 2241: @c
 2242: @c thing of sets of things to exercise then come up with
 2243: @c problems that need those things.
 2244: 
 2245: 
 2246: @c ******************************************************************
 2247: @node Words, Error messages, Introduction, Top
 2248: @chapter Forth Words
 2249: @cindex words
 2250: 
 2251: @menu
 2252: * Notation::                    
 2253: * Comments::
 2254: * Boolean Flags::
 2255: * Arithmetic::                  
 2256: * Stack Manipulation::          
 2257: * Memory::                      
 2258: * Control Structures::          
 2259: * Defining Words::              
 2260: * Interpretation and Compilation Semantics::
 2261: * Tokens for Words::            
 2262: * The Text Interpreter::
 2263: * Word Lists::                   
 2264: * Environmental Queries::
 2265: * Files::                       
 2266: * Blocks::                      
 2267: * Other I/O::                   
 2268: * Programming Tools::           
 2269: * Assembler and Code Words::    
 2270: * Threading Words::             
 2271: * Locals::                      
 2272: * Structures::                  
 2273: * Object-oriented Forth::       
 2274: * Passing Commands to the OS::
 2275: * Keeping track of Time::
 2276: * Miscellaneous Words::
 2277: @end menu
 2278: 
 2279: @node Notation, Comments, Words, Words
 2280: @section Notation
 2281: @cindex notation of glossary entries
 2282: @cindex format of glossary entries
 2283: @cindex glossary notation format
 2284: @cindex word glossary entry format
 2285: 
 2286: The Forth words are described in this section in the glossary notation
 2287: that has become a de-facto standard for Forth texts, i.e.,
 2288: 
 2289: @format
 2290: @i{word}     @i{Stack effect}   @i{wordset}   @i{pronunciation}
 2291: @end format
 2292: @i{Description}
 2293: 
 2294: @table @var
 2295: @item word
 2296: The name of the word.
 2297: 
 2298: @item Stack effect
 2299: @cindex stack effect
 2300: The stack effect is written in the notation @code{@i{before} --
 2301: @i{after}}, where @i{before} and @i{after} describe the top of
 2302: stack entries before and after the execution of the word. The rest of
 2303: the stack is not touched by the word. The top of stack is rightmost,
 2304: i.e., a stack sequence is written as it is typed in. Note that Gforth
 2305: uses a separate floating point stack, but a unified stack
 2306: notation. Also, return stack effects are not shown in @i{stack
 2307: effect}, but in @i{Description}. The name of a stack item describes
 2308: the type and/or the function of the item. See below for a discussion of
 2309: the types.
 2310: 
 2311: All words have two stack effects: A compile-time stack effect and a
 2312: run-time stack effect. The compile-time stack-effect of most words is
 2313: @i{ -- }. If the compile-time stack-effect of a word deviates from
 2314: this standard behaviour, or the word does other unusual things at
 2315: compile time, both stack effects are shown; otherwise only the run-time
 2316: stack effect is shown.
 2317: 
 2318: @cindex pronounciation of words
 2319: @item pronunciation
 2320: How the word is pronounced.
 2321: 
 2322: @cindex wordset
 2323: @item wordset
 2324: The ANS Forth standard is divided into several word sets. A standard
 2325: system need not support all of them. Therefore, in theory, the fewer
 2326: word sets your program uses the more portable it will be. However, we
 2327: suspect that most ANS Forth systems on personal machines will feature
 2328: all word sets. Words that are not defined in ANS Forth have
 2329: @code{gforth} or @code{gforth-internal} as word set. @code{gforth}
 2330: describes words that will work in future releases of Gforth;
 2331: @code{gforth-internal} words are more volatile. Environmental query
 2332: strings are also displayed like words; you can recognize them by the
 2333: @code{environment} in the word set field.
 2334: 
 2335: @item Description
 2336: A description of the behaviour of the word.
 2337: @end table
 2338: 
 2339: @cindex types of stack items
 2340: @cindex stack item types
 2341: The type of a stack item is specified by the character(s) the name
 2342: starts with:
 2343: 
 2344: @table @code
 2345: @item f
 2346: @cindex @code{f}, stack item type
 2347: Boolean flags, i.e. @code{false} or @code{true}.
 2348: @item c
 2349: @cindex @code{c}, stack item type
 2350: Char
 2351: @item w
 2352: @cindex @code{w}, stack item type
 2353: Cell, can contain an integer or an address
 2354: @item n
 2355: @cindex @code{n}, stack item type
 2356: signed integer
 2357: @item u
 2358: @cindex @code{u}, stack item type
 2359: unsigned integer
 2360: @item d
 2361: @cindex @code{d}, stack item type
 2362: double sized signed integer
 2363: @item ud
 2364: @cindex @code{ud}, stack item type
 2365: double sized unsigned integer
 2366: @item r
 2367: @cindex @code{r}, stack item type
 2368: Float (on the FP stack)
 2369: @item a-
 2370: @cindex @code{a_}, stack item type
 2371: Cell-aligned address
 2372: @item c-
 2373: @cindex @code{c_}, stack item type
 2374: Char-aligned address (note that a Char may have two bytes in Windows NT)
 2375: @item f-
 2376: @cindex @code{f_}, stack item type
 2377: Float-aligned address
 2378: @item df-
 2379: @cindex @code{df_}, stack item type
 2380: Address aligned for IEEE double precision float
 2381: @item sf-
 2382: @cindex @code{sf_}, stack item type
 2383: Address aligned for IEEE single precision float
 2384: @item xt
 2385: @cindex @code{xt}, stack item type
 2386: Execution token, same size as Cell
 2387: @item wid
 2388: @cindex @code{wid}, stack item type
 2389: Word list ID, same size as Cell
 2390: @item f83name
 2391: @cindex @code{f83name}, stack item type
 2392: Pointer to a name structure
 2393: @item "
 2394: @cindex @code{"}, stack item type
 2395: string in the input stream (not on the stack). The terminating character
 2396: is a blank by default. If it is not a blank, it is shown in @code{<>}
 2397: quotes.
 2398: @end table
 2399: 
 2400: @node Comments, Boolean Flags, Notation, Words
 2401: @section Comments
 2402: @cindex comments
 2403: 
 2404: Forth supports two styles of comment; the traditional @i{in-line} comment,
 2405: @code{(} and its modern cousin, the @i{comment to end of line}; @code{\}.
 2406: 
 2407: 
 2408: doc-(
 2409: doc-\
 2410: doc-\G
 2411: 
 2412: 
 2413: @node Boolean Flags, Arithmetic, Comments, Words
 2414: @section Boolean Flags
 2415: @cindex Boolean flags
 2416: 
 2417: A Boolean flag is cell-sized. A cell with all bits clear represents the
 2418: flag @code{false} and a flag with all bits set represents the flag
 2419: @code{true}. Words that check a flag (for example, @code{IF}) will treat
 2420: a cell that has @i{any} bit set as @code{true}.
 2421: 
 2422: 
 2423: doc-true
 2424: doc-false
 2425: doc-on
 2426: doc-off
 2427: 
 2428: 
 2429: @node Arithmetic, Stack Manipulation, Boolean Flags, Words
 2430: @section Arithmetic
 2431: @cindex arithmetic words
 2432: 
 2433: @cindex division with potentially negative operands
 2434: Forth arithmetic is not checked, i.e., you will not hear about integer
 2435: overflow on addition or multiplication, you may hear about division by
 2436: zero if you are lucky. The operator is written after the operands, but
 2437: the operands are still in the original order. I.e., the infix @code{2-1}
 2438: corresponds to @code{2 1 -}. Forth offers a variety of division
 2439: operators. If you perform division with potentially negative operands,
 2440: you do not want to use @code{/} or @code{/mod} with its undefined
 2441: behaviour, but rather @code{fm/mod} or @code{sm/mod} (probably the
 2442: former, @pxref{Mixed precision}).
 2443: @comment TODO discuss the different division forms and the std approach
 2444: 
 2445: @menu
 2446: * Single precision::            
 2447: * Bitwise operations::          
 2448: * Double precision::            Double-cell integer arithmetic
 2449: * Numeric comparison::
 2450: * Mixed precision::             Operations with single and double-cell integers
 2451: * Floating Point::              
 2452: @end menu
 2453: 
 2454: @node Single precision, Bitwise operations, Arithmetic, Arithmetic
 2455: @subsection Single precision
 2456: @cindex single precision arithmetic words
 2457: 
 2458: By default, numbers in Forth are single-precision integers that are 1
 2459: cell in size. They can be signed or unsigned, depending upon how you
 2460: treat them. @xref{Number Conversion} for the rules used by the text
 2461: interpreter for recognising single-precision integers.
 2462: 
 2463: 
 2464: doc-+
 2465: doc-1+
 2466: doc--
 2467: doc-1-
 2468: doc-*
 2469: doc-/
 2470: doc-mod
 2471: doc-/mod
 2472: doc-negate
 2473: doc-abs
 2474: doc-min
 2475: doc-max
 2476: doc-d>s
 2477: doc-floored
 2478: 
 2479: 
 2480: @node Bitwise operations, Double precision, Single precision, Arithmetic
 2481: @subsection Bitwise operations
 2482: @cindex bitwise operation words
 2483: 
 2484: 
 2485: doc-and
 2486: doc-or
 2487: doc-xor
 2488: doc-invert
 2489: doc-lshift
 2490: doc-rshift
 2491: doc-2*
 2492: doc-d2*
 2493: doc-2/
 2494: doc-d2/
 2495: 
 2496: 
 2497: @node Double precision, Numeric comparison, Bitwise operations, Arithmetic
 2498: @subsection Double precision
 2499: @cindex double precision arithmetic words
 2500: 
 2501: @xref{Number Conversion} for the rules used by the text interpreter for
 2502: recognising double-precision integers.
 2503: 
 2504: A double precision number is represented by a cell pair, with the most
 2505: significant cell at the TOS. It is trivial to convert an unsigned
 2506: single to an (unsigned) double; simply push a @code{0} onto the
 2507: TOS. Since numbers are represented by Gforth using 2's complement
 2508: arithmetic, converting a signed single to a (signed) double requires
 2509: sign-extension across the most significant cell. This can be achieved
 2510: using @code{s>d}. The moral of the story is that you cannot convert a
 2511: number without knowing whether it represents an unsigned or a
 2512: signed number.
 2513: 
 2514: 
 2515: doc-s>d
 2516: doc-d+
 2517: doc-d-
 2518: doc-dnegate
 2519: doc-dabs
 2520: doc-dmin
 2521: doc-dmax
 2522: 
 2523: 
 2524: @node Numeric comparison, Mixed precision, Double precision, Arithmetic
 2525: @subsection Numeric comparison
 2526: @cindex numeric comparison words
 2527: 
 2528: 
 2529: doc-<
 2530: doc-<=
 2531: doc-<>
 2532: doc-=
 2533: doc->
 2534: doc->=
 2535: 
 2536: doc-0<
 2537: doc-0<=
 2538: doc-0<>
 2539: doc-0=
 2540: doc-0>
 2541: doc-0>=
 2542: 
 2543: doc-u<
 2544: doc-u<=
 2545: @c u<> and u= exist but are the same as <> and =
 2546: @c doc-u<>
 2547: @c doc-u=
 2548: doc-u>
 2549: doc-u>=
 2550: 
 2551: doc-within
 2552: 
 2553: doc-d<
 2554: doc-d<=
 2555: doc-d<>
 2556: doc-d=
 2557: doc-d>
 2558: doc-d>=
 2559: 
 2560: doc-d0<
 2561: doc-d0<=
 2562: doc-d0<>
 2563: doc-d0=
 2564: doc-d0>
 2565: doc-d0>=
 2566: 
 2567: doc-du<
 2568: doc-du<=
 2569: @c du<> and du= exist but are the same as d<> and d=
 2570: @c doc-du<>
 2571: @c doc-du=
 2572: doc-du>
 2573: doc-du>=
 2574: 
 2575: 
 2576: @node Mixed precision, Floating Point, Numeric comparison, Arithmetic
 2577: @subsection Mixed precision
 2578: @cindex mixed precision arithmetic words
 2579: 
 2580: 
 2581: doc-m+
 2582: doc-*/
 2583: doc-*/mod
 2584: doc-m*
 2585: doc-um*
 2586: doc-m*/
 2587: doc-um/mod
 2588: doc-fm/mod
 2589: doc-sm/rem
 2590: 
 2591: 
 2592: @node Floating Point,  , Mixed precision, Arithmetic
 2593: @subsection Floating Point
 2594: @cindex floating point arithmetic words
 2595: 
 2596: @xref{Number Conversion} for the rules used by the text interpreter for
 2597: recognising floating-point numbers.
 2598: 
 2599: Gforth has a separate floating point
 2600: stack, but the documentation uses the unified notation.
 2601: 
 2602: @cindex floating-point arithmetic, pitfalls
 2603: Floating point numbers have a number of unpleasant surprises for the
 2604: unwary (e.g., floating point addition is not associative) and even a few
 2605: for the wary. You should not use them unless you know what you are doing
 2606: or you don't care that the results you get are totally bogus. If you
 2607: want to learn about the problems of floating point numbers (and how to
 2608: avoid them), you might start with @cite{David Goldberg, What Every
 2609: Computer Scientist Should Know About Floating-Point Arithmetic, ACM
 2610: Computing Surveys 23(1):5@minus{}48, March 1991}
 2611: (@uref{http://www.validgh.com/goldberg/paper.ps}).
 2612: 
 2613: 
 2614: doc-d>f
 2615: doc-f>d
 2616: doc-f+
 2617: doc-f-
 2618: doc-f*
 2619: doc-f/
 2620: doc-fnegate
 2621: doc-fabs
 2622: doc-fmax
 2623: doc-fmin
 2624: doc-floor
 2625: doc-fround
 2626: doc-f**
 2627: doc-fsqrt
 2628: doc-fexp
 2629: doc-fexpm1
 2630: doc-fln
 2631: doc-flnp1
 2632: doc-flog
 2633: doc-falog
 2634: doc-f2*
 2635: doc-f2/
 2636: doc-1/f
 2637: doc-precision
 2638: doc-set-precision
 2639: 
 2640: @cindex angles in trigonometric operations
 2641: @cindex trigonometric operations
 2642: Angles in floating point operations are given in radians (a full circle
 2643: has 2 pi radians).
 2644: 
 2645: doc-fsin
 2646: doc-fcos
 2647: doc-fsincos
 2648: doc-ftan
 2649: doc-fasin
 2650: doc-facos
 2651: doc-fatan
 2652: doc-fatan2
 2653: doc-fsinh
 2654: doc-fcosh
 2655: doc-ftanh
 2656: doc-fasinh
 2657: doc-facosh
 2658: doc-fatanh
 2659: doc-pi
 2660: 
 2661: @cindex equality of floats
 2662: @cindex floating-point comparisons
 2663: One particular problem with floating-point arithmetic is that comparison
 2664: for equality often fails when you would expect it to succeed.  For this
 2665: reason approximate equality is often preferred (but you still have to
 2666: know what you are doing).  The comparison words are:
 2667: 
 2668: doc-f~rel
 2669: doc-f~abs
 2670: doc-f=
 2671: doc-f~
 2672: doc-f<>
 2673: 
 2674: doc-f<
 2675: doc-f<=
 2676: doc-f>
 2677: doc-f>=
 2678: 
 2679: doc-f0<
 2680: doc-f0<=
 2681: doc-f0<>
 2682: doc-f0=
 2683: doc-f0>
 2684: doc-f0>=
 2685: 
 2686: 
 2687: @node Stack Manipulation, Memory, Arithmetic, Words
 2688: @section Stack Manipulation
 2689: @cindex stack manipulation words
 2690: 
 2691: @cindex floating-point stack in the standard
 2692: Gforth maintains a number of separate stacks:
 2693: 
 2694: @cindex data stack
 2695: @cindex parameter stack
 2696: @itemize @bullet
 2697: @item
 2698: A data stack (also known as the @dfn{parameter stack}) -- for
 2699: characters, cells, addresses, and double cells.
 2700: 
 2701: @cindex floating-point stack
 2702: @item
 2703: A floating point stack -- for holding floating point (FP) numbers.
 2704: 
 2705: @cindex return stack
 2706: @item
 2707: A return stack -- for holding the return addresses of colon
 2708: definitions and other (non-FP) data.
 2709: 
 2710: @cindex locals stack
 2711: @item
 2712: A locals stack -- for holding local variables.
 2713: @end itemize
 2714: 
 2715: @menu
 2716: * Data stack::                  
 2717: * Floating point stack::        
 2718: * Return stack::                
 2719: * Locals stack::                
 2720: * Stack pointer manipulation::  
 2721: @end menu
 2722: 
 2723: @node Data stack, Floating point stack, Stack Manipulation, Stack Manipulation
 2724: @subsection Data stack
 2725: @cindex data stack manipulation words
 2726: @cindex stack manipulations words, data stack
 2727: 
 2728: 
 2729: doc-drop
 2730: doc-nip
 2731: doc-dup
 2732: doc-over
 2733: doc-tuck
 2734: doc-swap
 2735: doc-pick
 2736: doc-rot
 2737: doc--rot
 2738: doc-?dup
 2739: doc-roll
 2740: doc-2drop
 2741: doc-2nip
 2742: doc-2dup
 2743: doc-2over
 2744: doc-2tuck
 2745: doc-2swap
 2746: doc-2rot
 2747: 
 2748: 
 2749: @node Floating point stack, Return stack, Data stack, Stack Manipulation
 2750: @subsection Floating point stack
 2751: @cindex floating-point stack manipulation words
 2752: @cindex stack manipulation words, floating-point stack
 2753: 
 2754: Whilst every sane Forth has a separate floating-point stack, it is not
 2755: strictly required; an ANS Forth system could theoretically keep
 2756: floating-point numbers on the data stack. As an additional difficulty,
 2757: you don't know how many cells a floating-point number takes. It is
 2758: reportedly possible to write words in a way that they work also for a
 2759: unified stack model, but we do not recommend trying it. Instead, just
 2760: say that your program has an environmental dependency on a separate
 2761: floating-point stack.
 2762: 
 2763: doc-floating-stack
 2764: 
 2765: doc-fdrop
 2766: doc-fnip
 2767: doc-fdup
 2768: doc-fover
 2769: doc-ftuck
 2770: doc-fswap
 2771: doc-fpick
 2772: doc-frot
 2773: 
 2774: 
 2775: @node Return stack, Locals stack, Floating point stack, Stack Manipulation
 2776: @subsection Return stack
 2777: @cindex return stack manipulation words
 2778: @cindex stack manipulation words, return stack
 2779: 
 2780: @cindex return stack and locals
 2781: @cindex locals and return stack
 2782: A Forth system is allowed to keep local variables on the
 2783: return stack. This is reasonable, as local variables usually eliminate
 2784: the need to use the return stack explicitly. So, if you want to produce
 2785: a standard compliant program and you are using local variables in a
 2786: word, forget about return stack manipulations in that word (refer to the
 2787: standard document for the exact rules).
 2788: 
 2789: doc->r
 2790: doc-r>
 2791: doc-r@
 2792: doc-rdrop
 2793: doc-2>r
 2794: doc-2r>
 2795: doc-2r@
 2796: doc-2rdrop
 2797: 
 2798: 
 2799: @node Locals stack, Stack pointer manipulation, Return stack, Stack Manipulation
 2800: @subsection Locals stack
 2801: 
 2802: Gforth uses an extra locals stack. It is described, along with the
 2803: reasons for its existence, in @ref{Implementation,Implementation of locals}.
 2804: 
 2805: @node Stack pointer manipulation,  , Locals stack, Stack Manipulation
 2806: @subsection Stack pointer manipulation
 2807: @cindex stack pointer manipulation words
 2808: 
 2809: @c removed s0 r0 l0 -- they are obsolete aliases for sp0 rp0 lp0
 2810: doc-sp0
 2811: doc-sp@
 2812: doc-sp!
 2813: doc-fp0
 2814: doc-fp@
 2815: doc-fp!
 2816: doc-rp0
 2817: doc-rp@
 2818: doc-rp!
 2819: doc-lp0
 2820: doc-lp@
 2821: doc-lp!
 2822: 
 2823: 
 2824: @node Memory, Control Structures, Stack Manipulation, Words
 2825: @section Memory
 2826: @cindex memory words
 2827: 
 2828: @menu
 2829: * Memory model::                
 2830: * Dictionary allocation::       
 2831: * Heap Allocation::             
 2832: * Memory Access::               
 2833: * Address arithmetic::          
 2834: * Memory Blocks::               
 2835: @end menu
 2836: 
 2837: @node Memory model, Dictionary allocation, Memory, Memory
 2838: @subsection ANS Forth and Gforth memory models
 2839: 
 2840: @c The ANS Forth description is a mess (e.g., is the heap part of
 2841: @c the dictionary?), so let's not stick to closely with it.
 2842: 
 2843: ANS Forth considers a Forth system as consisting of several memories, of
 2844: which only @dfn{data space} is managed and accessible with the memory
 2845: words.  Memory not necessarily in data space includes the stacks, the
 2846: code (called code space) and the headers (called name space). In Gforth
 2847: everything is in data space, but the code for the primitives is usually
 2848: read-only.
 2849: 
 2850: Data space is divided into a number of areas: The (data space portion of
 2851: the) dictionary@footnote{Sometimes, the term @dfn{dictionary} is used to
 2852: refer to the search data structure embodied in word lists and headers,
 2853: because it is used for looking up names, just as you would in a
 2854: conventional dictionary.}, the heap, and a number of system-allocated
 2855: buffers.
 2856: 
 2857: In ANS Forth data space is also divided into contiguous regions.  You
 2858: can only use address arithmetic within a contiguous region, not between
 2859: them.  Usually each allocation gives you one contiguous region, but the
 2860: dictionary allocation words have additional rules (@pxref{Dictionary
 2861: allocation}).
 2862: 
 2863: Gforth provides one big address space, and address arithmetic can be
 2864: performed between any addresses. However, in the dictionary headers or
 2865: code are interleaved with data, so almost the only contiguous data space
 2866: regions there are those described by ANS Forth as contiguous; but you
 2867: can be sure that the dictionary is allocated towards increasing
 2868: addresses even between contiguous regions.  The memory order of
 2869: allocations in the heap is platform-dependent (and possibly different
 2870: from one run to the next).
 2871: 
 2872: @subsubsection ANS Forth dictionary details
 2873: 
 2874: This section is just informative, you can skip it if you are in a hurry.
 2875: 
 2876: When you create a colon definition, the text interpreter compiles the
 2877: code for the definition into the code space and compiles the name
 2878: of the definition into the header space, together with other
 2879: information about the definition (such as its execution token).
 2880: 
 2881: When you create a variable, the execution of @code{Variable} will
 2882: compile some code, assign one cell in data space, and compile the name
 2883: of the variable into the header space.
 2884: 
 2885: @cindex memory regions - relationship between them
 2886: ANS Forth does not specify the relationship between the three memory
 2887: regions, and specifies that a Standard program must not access code or
 2888: data space directly -- it may only access data space directly. In
 2889: addition, the Standard defines what relationships you may and may not
 2890: rely on when allocating regions in data space. These constraints are
 2891: simply a reflection of the many diverse techniques that are used to
 2892: implement Forth systems; understanding and following the requirements of
 2893: the Standard allows you to write portable programs -- programs that run
 2894: in the same way on any of these diverse systems. Another way of looking
 2895: at this is to say that ANS Forth was designed to permit compliant Forth
 2896: systems to be implemented in many diverse ways.
 2897: 
 2898: @cindex memory regions - how they are assigned
 2899: Here are some examples of ways in which name, code and data spaces
 2900: might be assigned in different Forth implementations:
 2901: 
 2902: @itemize @bullet
 2903: @item
 2904: For a Forth system that runs from RAM under a general-purpose operating
 2905: system, it can be convenient to interleave name, code and data spaces in
 2906: a single contiguous memory region. This organisation can be
 2907: memory-efficient (for example, because the relationship between the name
 2908: dictionary entry and the associated code space entry can be
 2909: implicit, rather than requiring an explicit memory pointer to reference
 2910: from the header space and the code space). This is the
 2911: organisation used by Gforth, as this example@footnote{The addresses
 2912: in the example have been truncated to fit it onto the page, and the
 2913: addresses and data shown will not match the output from your system} shows:
 2914: @example
 2915: hex
 2916: variable fred 123456 fred !
 2917: variable jim abcd jim !
 2918: : foo + / - ;
 2919: ' fred 10 - 50 dump 
 2920: ..80: 5C 46 0E 40  84 66 72 65 - 64 20 20 20  20 20 20 20  \F.@.fred       
 2921: ..90: D0 9B 04 08  00 00 00 00 - 56 34 12 00  80 46 0E 40  ........V4...F.@
 2922: ..A0: 83 6A 69 6D  20 20 20 20 - D0 9B 04 08  00 00 00 00  .jim    ........
 2923: ..B0: CD AB 00 00  9C 46 0E 40 - 83 66 6F 6F  20 20 20 20  .....F.@.foo    
 2924: ..C0: 80 9B 04 08  00 00 00 00 - E4 2E 05 08  0C 2F 05 08  ............./..
 2925: @end example
 2926: 
 2927: @item
 2928: For a high-performance system running on a modern RISC processor with a
 2929: modified Harvard architecture (one that has a unified main memory but
 2930: separate instruction and data caches), it is desirable to separate
 2931: processor instructions from processor data. This encourages a high cache
 2932: density and therefore a high cache hit rate. The Forth code space
 2933: is not necessarily made up entirely of processor instructions; its
 2934: nature is dependent upon the Forth implementation. 
 2935: 
 2936: @item
 2937: A Forth compiler that runs on a segmented 8086 processor could be
 2938: designed to interleave the name, code and data spaces within a single
 2939: 64Kbyte segment. A more common implementation choice is to use a
 2940: separate 64Kbyte segment for each region, which provides more memory
 2941: overall but provides an address map in which only the data space is
 2942: accessible.
 2943: 
 2944: @item
 2945: Microprocessors exist that run Forth (or many of the primitives required
 2946: to implement the Forth virtual machine efficiently) directly. On these
 2947: processors, the relationship between name, code and data spaces may be
 2948: imposed as a side-effect of the architecture of the processor.
 2949: 
 2950: @item
 2951: A Forth compiler that executes from ROM on an embedded system needs its
 2952: data space separated from the name and code spaces so that the data
 2953: space can be mapped to a RAM area.
 2954: 
 2955: @item 
 2956: A Forth compiler that runs on an embedded system may have a requirement
 2957: for a small memory footprint. On such a system it can be useful to
 2958: separate the header space from the data and code spaces; once the
 2959: application has been compiled, the header space is no longer
 2960: required@footnote{more strictly speaking, most applications can be
 2961: designed so that this is the case}. The header space can be deleted
 2962: entirely, or could be stored in memory on a remote @i{host} system for
 2963: debug and development purposes. In the latter case, the compiler running
 2964: on the @i{target} system could implement a protocol across a
 2965: communication link that would allow it to interrogate the header space.
 2966: @end itemize
 2967: 
 2968: @node Dictionary allocation, Heap Allocation, Memory model, Memory
 2969: @subsection Dictionary allocation
 2970: @cindex reserving data space
 2971: @cindex data space - reserving some
 2972: 
 2973: Dictionary allocation is a stack-oriented allocation scheme, i.e., if
 2974: you want to deallocate X, you also deallocate everything
 2975: allocated after X.
 2976: 
 2977: The allocations using the words below are contiguous and grow the region
 2978: towards increasing addresses.  Other words that allocate dictionary
 2979: memory of any kind (i.e., defining words including @code{:noname}) end
 2980: the contiguous region and start a new one.
 2981: 
 2982: In ANS Forth only @code{create}d words are guaranteed to produce an
 2983: address that is the start of the following contiguous region.  In
 2984: particular, the cell allocated by @code{variable} is not guaranteed to
 2985: be contiguous with following @code{allot}ed memory.
 2986: 
 2987: You can deallocate memory by using @code{allot} with a negative argument
 2988: (with some restrictions, see @code{allot}). For larger deallocations use
 2989: @code{marker}.
 2990: 
 2991: 
 2992: doc-here
 2993: doc-unused
 2994: doc-allot
 2995: doc-c,
 2996: doc-f,
 2997: doc-,
 2998: doc-2,
 2999: @cindex user space
 3000: doc-udp
 3001: doc-uallot
 3002: 
 3003: Memory accesses have to be aligned (@pxref{Address arithmetic}). So of
 3004: course you should allocate memory in an aligned way, too. I.e., before
 3005: allocating allocating a cell, @code{here} must be cell-aligned, etc.
 3006: The words below align @code{here} if it is not already.  Basically it is
 3007: only already aligned for a type, if the last allocation was a multiple
 3008: of the size of this type and if @code{here} was aligned for this type
 3009: before.
 3010: 
 3011: After freshly @code{create}ing a word, @code{here} is @code{align}ed in
 3012: ANS Forth (@code{maxalign}ed in Gforth).
 3013: 
 3014: doc-align
 3015: doc-falign
 3016: doc-sfalign
 3017: doc-dfalign
 3018: doc-maxalign
 3019: doc-cfalign
 3020: 
 3021: 
 3022: @node Heap Allocation, Memory Access, Dictionary allocation, Memory
 3023: @subsection Heap allocation
 3024: @cindex heap allocation
 3025: @cindex dynamic allocation of memory
 3026: @cindex memory-allocation word set
 3027: 
 3028: Heap allocation supports deallocation of allocated memory in any
 3029: order. Dictionary allocation is not affected by it (i.e., it does not
 3030: end a contiguous region). In Gforth, these words are implemented using
 3031: the standard C library calls malloc(), free() and resize().
 3032: 
 3033: doc-allocate
 3034: doc-free
 3035: doc-resize
 3036: 
 3037: 
 3038: @node Memory Access, Address arithmetic, Heap Allocation, Memory
 3039: @subsection Memory Access
 3040: @cindex memory access words
 3041: 
 3042: 
 3043: doc-@
 3044: doc-!
 3045: doc-+!
 3046: doc-c@
 3047: doc-c!
 3048: doc-2@
 3049: doc-2!
 3050: doc-f@
 3051: doc-f!
 3052: doc-sf@
 3053: doc-sf!
 3054: doc-df@
 3055: doc-df!
 3056: 
 3057: @node Address arithmetic, Memory Blocks, Memory Access, Memory
 3058: @subsection Address arithmetic
 3059: @cindex address arithmetic words
 3060: 
 3061: Address arithmetic is the foundation on which data structures like
 3062: arrays, records (@pxref{Structures}) and objects (@pxref{Object-oriented
 3063: Forth}) are built.
 3064: 
 3065: ANS Forth does not specify the sizes of the data types. Instead, it
 3066: offers a number of words for computing sizes and doing address
 3067: arithmetic. Address arithmetic is performed in terms of address units
 3068: (aus); on most systems the address unit is one byte. Note that a
 3069: character may have more than one au, so @code{chars} is no noop (on
 3070: systems where it is a noop, it compiles to nothing).
 3071: 
 3072: @cindex alignment of addresses for types
 3073: ANS Forth also defines words for aligning addresses for specific
 3074: types. Many computers require that accesses to specific data types
 3075: must only occur at specific addresses; e.g., that cells may only be
 3076: accessed at addresses divisible by 4. Even if a machine allows unaligned
 3077: accesses, it can usually perform aligned accesses faster. 
 3078: 
 3079: For the performance-conscious: alignment operations are usually only
 3080: necessary during the definition of a data structure, not during the
 3081: (more frequent) accesses to it.
 3082: 
 3083: ANS Forth defines no words for character-aligning addresses. This is not
 3084: an oversight, but reflects the fact that addresses that are not
 3085: char-aligned have no use in the standard and therefore will not be
 3086: created.
 3087: 
 3088: @cindex @code{CREATE} and alignment
 3089: ANS Forth guarantees that addresses returned by @code{CREATE}d words
 3090: are cell-aligned; in addition, Gforth guarantees that these addresses
 3091: are aligned for all purposes.
 3092: 
 3093: Note that the ANS Forth word @code{char} has nothing to do with address
 3094: arithmetic.
 3095: 
 3096: 
 3097: doc-chars
 3098: doc-char+
 3099: doc-cells
 3100: doc-cell+
 3101: doc-cell
 3102: doc-aligned
 3103: doc-floats
 3104: doc-float+
 3105: doc-float
 3106: doc-faligned
 3107: doc-sfloats
 3108: doc-sfloat+
 3109: doc-sfaligned
 3110: doc-dfloats
 3111: doc-dfloat+
 3112: doc-dfaligned
 3113: doc-maxaligned
 3114: doc-cfaligned
 3115: doc-address-unit-bits
 3116: 
 3117: 
 3118: @node Memory Blocks,  , Address arithmetic, Memory
 3119: @subsection Memory Blocks
 3120: @cindex memory block words
 3121: @cindex character strings - moving and copying
 3122: 
 3123: Memory blocks often represent character strings; @xref{String Formats}
 3124: for ways of storing character strings in memory. @xref{Displaying
 3125: characters and strings} for other string-processing words.
 3126: 
 3127: Some of these words work on address units. Others work on character
 3128: units (increments of @code{CHAR}), and expect a @code{CHAR}-aligned
 3129: address. Choose the correct operation depending upon your data type.
 3130: 
 3131: When copying characters between overlapping memory regions, choose
 3132: carefully between @code{cmove} and @code{cmove>}.
 3133: 
 3134: You can only use any of these words @i{portably} to access data space.
 3135: 
 3136: @comment TODO - think the naming of the arguments is wrong for move
 3137: @comment well, really it seems to be the Standard that's wrong; it
 3138: @comment describes MOVE as a word that requires a CELL-aligned source
 3139: @comment and destination address but a xtranfer count that need not
 3140: @comment be a multiple of CELL.
 3141: 
 3142: doc-move
 3143: doc-erase
 3144: doc-cmove
 3145: doc-cmove>
 3146: doc-fill
 3147: doc-blank
 3148: doc-compare
 3149: doc-search
 3150: doc--trailing
 3151: doc-/string
 3152: 
 3153: 
 3154: @comment TODO examples
 3155: 
 3156: 
 3157: @node Control Structures, Defining Words, Memory, Words
 3158: @section Control Structures
 3159: @cindex control structures
 3160: 
 3161: Control structures in Forth cannot be used interpretively, only in a
 3162: colon definition@footnote{To be precise, they have no interpretation
 3163: semantics (@pxref{Interpretation and Compilation Semantics}).}. We do
 3164: not like this limitation, but have not seen a satisfying way around it
 3165: yet, although many schemes have been proposed.
 3166: 
 3167: @menu
 3168: * Selection::                   IF ... ELSE ... ENDIF
 3169: * Simple Loops::                BEGIN ...
 3170: * Counted Loops::               DO
 3171: * Arbitrary control structures::
 3172: * Calls and returns::
 3173: * Exception Handling::          
 3174: @end menu
 3175: 
 3176: @node Selection, Simple Loops, Control Structures, Control Structures
 3177: @subsection Selection
 3178: @cindex selection control structures
 3179: @cindex control structures for selection
 3180: 
 3181: @c what's the purpose of all these @i? Maybe we should define a macro
 3182: @c so we can produce logical markup.  - anton
 3183: 
 3184: @c nac-> When I started working on the manual, a mixture of @i and @var
 3185: @c were used inconsistently in code examples and \Glossary entries. These
 3186: @c two behave differently in info format so I decided to standardize on @i.
 3187: @c Logical markup would be better but texi isn't really upto it, and
 3188: @c texi2html just ignores macros.
 3189: @c nac02dec1999-> update: the latest texinfo release can spit out html
 3190: @c and it handles macros, so we could do some logical markup. Unfortunately
 3191: @c texinfo will not split html output, which would be a big pain if you
 3192: @c wanted to put the document on the web, which would be nice.
 3193: 
 3194: @cindex @code{IF} control structure
 3195: @example
 3196: @i{flag}
 3197: IF
 3198:   @i{code}
 3199: ENDIF
 3200: @end example
 3201: @noindent
 3202: 
 3203: If @i{flag} is non-zero (as far as @code{IF} etc. are concerned, a cell
 3204: with any bit set represents truth) @i{code} is executed.
 3205: 
 3206: @example
 3207: @i{flag}
 3208: IF
 3209:   @i{code1}
 3210: ELSE
 3211:   @i{code2}
 3212: ENDIF
 3213: @end example
 3214: 
 3215: If @var{flag} is true, @i{code1} is executed, otherwise @i{code2} is
 3216: executed.
 3217: 
 3218: You can use @code{THEN} instead of @code{ENDIF}. Indeed, @code{THEN} is
 3219: standard, and @code{ENDIF} is not, although it is quite popular. We
 3220: recommend using @code{ENDIF}, because it is less confusing for people
 3221: who also know other languages (and is not prone to reinforcing negative
 3222: prejudices against Forth in these people). Adding @code{ENDIF} to a
 3223: system that only supplies @code{THEN} is simple:
 3224: @example
 3225: : ENDIF   POSTPONE THEN ; immediate
 3226: @end example
 3227: 
 3228: [According to @cite{Webster's New Encyclopedic Dictionary}, @dfn{then
 3229: (adv.)}  has the following meanings:
 3230: @quotation
 3231: ... 2b: following next after in order ... 3d: as a necessary consequence
 3232: (if you were there, then you saw them).
 3233: @end quotation
 3234: Forth's @code{THEN} has the meaning 2b, whereas @code{THEN} in Pascal
 3235: and many other programming languages has the meaning 3d.]
 3236: 
 3237: Gforth also provides the words @code{?DUP-IF} and @code{?DUP-0=-IF}, so
 3238: you can avoid using @code{?dup}. Using these alternatives is also more
 3239: efficient than using @code{?dup}. Definitions in ANS Forth
 3240: for @code{ENDIF}, @code{?DUP-IF} and @code{?DUP-0=-IF} are provided in
 3241: @file{compat/control.fs}.
 3242: 
 3243: @cindex @code{CASE} control structure
 3244: @example
 3245: @i{n}
 3246: CASE
 3247:   @i{n1} OF @i{code1} ENDOF
 3248:   @i{n2} OF @i{code2} ENDOF
 3249:   @dots{}
 3250: ENDCASE
 3251: @end example
 3252: 
 3253: Executes the first @i{codei}, where the @i{ni} is equal to
 3254: @i{n}. A default case can be added by simply writing the code after
 3255: the last @code{ENDOF}. It may use @i{n}, which is on top of the stack,
 3256: but must not consume it.
 3257: 
 3258: @node Simple Loops, Counted Loops, Selection, Control Structures
 3259: @subsection Simple Loops
 3260: @cindex simple loops
 3261: @cindex loops without count 
 3262: 
 3263: @cindex @code{WHILE} loop
 3264: @example
 3265: BEGIN
 3266:   @i{code1}
 3267:   @i{flag}
 3268: WHILE
 3269:   @i{code2}
 3270: REPEAT
 3271: @end example
 3272: 
 3273: @i{code1} is executed and @i{flag} is computed. If it is true,
 3274: @i{code2} is executed and the loop is restarted; If @i{flag} is
 3275: false, execution continues after the @code{REPEAT}.
 3276: 
 3277: @cindex @code{UNTIL} loop
 3278: @example
 3279: BEGIN
 3280:   @i{code}
 3281:   @i{flag}
 3282: UNTIL
 3283: @end example
 3284: 
 3285: @i{code} is executed. The loop is restarted if @code{flag} is false.
 3286: 
 3287: @cindex endless loop
 3288: @cindex loops, endless
 3289: @example
 3290: BEGIN
 3291:   @i{code}
 3292: AGAIN
 3293: @end example
 3294: 
 3295: This is an endless loop.
 3296: 
 3297: @node Counted Loops, Arbitrary control structures, Simple Loops, Control Structures
 3298: @subsection Counted Loops
 3299: @cindex counted loops
 3300: @cindex loops, counted
 3301: @cindex @code{DO} loops
 3302: 
 3303: The basic counted loop is:
 3304: @example
 3305: @i{limit} @i{start}
 3306: ?DO
 3307:   @i{body}
 3308: LOOP
 3309: @end example
 3310: 
 3311: This performs one iteration for every integer, starting from @i{start}
 3312: and up to, but excluding @i{limit}. The counter, or @i{index}, can be
 3313: accessed with @code{i}. For example, the loop:
 3314: @example
 3315: 10 0 ?DO
 3316:   i .
 3317: LOOP
 3318: @end example
 3319: @noindent
 3320: prints @code{0 1 2 3 4 5 6 7 8 9}
 3321: 
 3322: The index of the innermost loop can be accessed with @code{i}, the index
 3323: of the next loop with @code{j}, and the index of the third loop with
 3324: @code{k}.
 3325: 
 3326: 
 3327: doc-i
 3328: doc-j
 3329: doc-k
 3330: 
 3331: 
 3332: The loop control data are kept on the return stack, so there are some
 3333: restrictions on mixing return stack accesses and counted loop words. In
 3334: particuler, if you put values on the return stack outside the loop, you
 3335: cannot read them inside the loop@footnote{well, not in a way that is
 3336: portable.}. If you put values on the return stack within a loop, you
 3337: have to remove them before the end of the loop and before accessing the
 3338: index of the loop.
 3339: 
 3340: There are several variations on the counted loop:
 3341: 
 3342: @itemize @bullet
 3343: @item
 3344: @code{LEAVE} leaves the innermost counted loop immediately; execution
 3345: continues after the associated @code{LOOP} or @code{NEXT}. For example:
 3346: 
 3347: @example
 3348: 10 0 ?DO  i DUP . 3 = IF LEAVE THEN LOOP
 3349: @end example
 3350: prints @code{0 1 2 3}
 3351: 
 3352: 
 3353: @item
 3354: @code{UNLOOP} prepares for an abnormal loop exit, e.g., via
 3355: @code{EXIT}. @code{UNLOOP} removes the loop control parameters from the
 3356: return stack so @code{EXIT} can get to its return address. For example:
 3357: 
 3358: @example
 3359: : demo 10 0 ?DO i DUP . 3 = IF UNLOOP EXIT THEN LOOP ." Done" ;
 3360: @end example
 3361: prints @code{0 1 2 3}
 3362: 
 3363: 
 3364: @item
 3365: If @i{start} is greater than @i{limit}, a @code{?DO} loop is entered
 3366: (and @code{LOOP} iterates until they become equal by wrap-around
 3367: arithmetic). This behaviour is usually not what you want. Therefore,
 3368: Gforth offers @code{+DO} and @code{U+DO} (as replacements for
 3369: @code{?DO}), which do not enter the loop if @i{start} is greater than
 3370: @i{limit}; @code{+DO} is for signed loop parameters, @code{U+DO} for
 3371: unsigned loop parameters.
 3372: 
 3373: @item
 3374: @code{?DO} can be replaced by @code{DO}. @code{DO} always enters
 3375: the loop, independent of the loop parameters. Do not use @code{DO}, even
 3376: if you know that the loop is entered in any case. Such knowledge tends
 3377: to become invalid during maintenance of a program, and then the
 3378: @code{DO} will make trouble.
 3379: 
 3380: @item
 3381: @code{LOOP} can be replaced with @code{@i{n} +LOOP}; this updates the
 3382: index by @i{n} instead of by 1. The loop is terminated when the border
 3383: between @i{limit-1} and @i{limit} is crossed. E.g.:
 3384: 
 3385: @example
 3386: 4 0 +DO  i .  2 +LOOP
 3387: @end example
 3388: @noindent
 3389: prints @code{0 2}
 3390: 
 3391: @example
 3392: 4 1 +DO  i .  2 +LOOP
 3393: @end example
 3394: @noindent
 3395: prints @code{1 3}
 3396: 
 3397: 
 3398: @cindex negative increment for counted loops
 3399: @cindex counted loops with negative increment
 3400: The behaviour of @code{@i{n} +LOOP} is peculiar when @i{n} is negative:
 3401: 
 3402: @example
 3403: -1 0 ?DO  i .  -1 +LOOP
 3404: @end example
 3405: @noindent
 3406: prints @code{0 -1}
 3407: 
 3408: @example
 3409: 0 0 ?DO  i .  -1 +LOOP
 3410: @end example
 3411: prints nothing.
 3412: 
 3413: Therefore we recommend avoiding @code{@i{n} +LOOP} with negative
 3414: @i{n}. One alternative is @code{@i{u} -LOOP}, which reduces the
 3415: index by @i{u} each iteration. The loop is terminated when the border
 3416: between @i{limit+1} and @i{limit} is crossed. Gforth also provides
 3417: @code{-DO} and @code{U-DO} for down-counting loops. E.g.:
 3418: 
 3419: @example
 3420: -2 0 -DO  i .  1 -LOOP
 3421: @end example
 3422: @noindent
 3423: prints @code{0 -1}
 3424: 
 3425: @example
 3426: -1 0 -DO  i .  1 -LOOP
 3427: @end example
 3428: @noindent
 3429: prints @code{0}
 3430: 
 3431: @example
 3432: 0 0 -DO  i .  1 -LOOP
 3433: @end example
 3434: @noindent
 3435: prints nothing.
 3436: 
 3437: @end itemize
 3438: 
 3439: Unfortunately, @code{+DO}, @code{U+DO}, @code{-DO}, @code{U-DO} and
 3440: @code{-LOOP} are not defined in ANS Forth. However, an implementation
 3441: for these words that uses only standard words is provided in
 3442: @file{compat/loops.fs}.
 3443: 
 3444: 
 3445: @cindex @code{FOR} loops
 3446: Another counted loop is:
 3447: @example
 3448: @i{n}
 3449: FOR
 3450:   @i{body}
 3451: NEXT
 3452: @end example
 3453: This is the preferred loop of native code compiler writers who are too
 3454: lazy to optimize @code{?DO} loops properly. This loop structure is not
 3455: defined in ANS Forth. In Gforth, this loop iterates @i{n+1} times;
 3456: @code{i} produces values starting with @i{n} and ending with 0. Other
 3457: Forth systems may behave differently, even if they support @code{FOR}
 3458: loops. To avoid problems, don't use @code{FOR} loops.
 3459: 
 3460: @node Arbitrary control structures, Calls and returns, Counted Loops, Control Structures
 3461: @subsection Arbitrary control structures
 3462: @cindex control structures, user-defined
 3463: 
 3464: @cindex control-flow stack
 3465: ANS Forth permits and supports using control structures in a non-nested
 3466: way. Information about incomplete control structures is stored on the
 3467: control-flow stack. This stack may be implemented on the Forth data
 3468: stack, and this is what we have done in Gforth.
 3469: 
 3470: @cindex @code{orig}, control-flow stack item
 3471: @cindex @code{dest}, control-flow stack item
 3472: An @i{orig} entry represents an unresolved forward branch, a @i{dest}
 3473: entry represents a backward branch target. A few words are the basis for
 3474: building any control structure possible (except control structures that
 3475: need storage, like calls, coroutines, and backtracking).
 3476: 
 3477: 
 3478: doc-if
 3479: doc-ahead
 3480: doc-then
 3481: doc-begin
 3482: doc-until
 3483: doc-again
 3484: doc-cs-pick
 3485: doc-cs-roll
 3486: 
 3487: 
 3488: The Standard words @code{CS-PICK} and @code{CS-ROLL} allow you to
 3489: manipulate the control-flow stack in a portable way. Without them, you
 3490: would need to know how many stack items are occupied by a control-flow
 3491: entry (many systems use one cell. In Gforth they currently take three,
 3492: but this may change in the future).
 3493: 
 3494: Some standard control structure words are built from these words:
 3495: 
 3496: 
 3497: doc-else
 3498: doc-while
 3499: doc-repeat
 3500: 
 3501: 
 3502: @noindent
 3503: Gforth adds some more control-structure words:
 3504: 
 3505: 
 3506: doc-endif
 3507: doc-?dup-if
 3508: doc-?dup-0=-if
 3509: 
 3510: 
 3511: @noindent
 3512: Counted loop words constitute a separate group of words:
 3513: 
 3514: 
 3515: doc-?do
 3516: doc-+do
 3517: doc-u+do
 3518: doc--do
 3519: doc-u-do
 3520: doc-do
 3521: doc-for
 3522: doc-loop
 3523: doc-+loop
 3524: doc--loop
 3525: doc-next
 3526: doc-leave
 3527: doc-?leave
 3528: doc-unloop
 3529: doc-done
 3530: 
 3531: 
 3532: The standard does not allow using @code{CS-PICK} and @code{CS-ROLL} on
 3533: @i{do-sys}. Gforth allows it, but it's your job to ensure that for
 3534: every @code{?DO} etc. there is exactly one @code{UNLOOP} on any path
 3535: through the definition (@code{LOOP} etc. compile an @code{UNLOOP} on the
 3536: fall-through path). Also, you have to ensure that all @code{LEAVE}s are
 3537: resolved (by using one of the loop-ending words or @code{DONE}).
 3538: 
 3539: @noindent
 3540: Another group of control structure words are:
 3541: 
 3542: 
 3543: doc-case
 3544: doc-endcase
 3545: doc-of
 3546: doc-endof
 3547: 
 3548: 
 3549: @i{case-sys} and @i{of-sys} cannot be processed using @code{CS-PICK} and
 3550: @code{CS-ROLL}.
 3551: 
 3552: @subsubsection Programming Style
 3553: @cindex control structures programming style
 3554: @cindex programming style, arbitrary control structures
 3555: 
 3556: In order to ensure readability we recommend that you do not create
 3557: arbitrary control structures directly, but define new control structure
 3558: words for the control structure you want and use these words in your
 3559: program. For example, instead of writing:
 3560: 
 3561: @example
 3562: BEGIN
 3563:   ...
 3564: IF [ 1 CS-ROLL ]
 3565:   ...
 3566: AGAIN THEN
 3567: @end example
 3568: 
 3569: @noindent
 3570: we recommend defining control structure words, e.g.,
 3571: 
 3572: @example
 3573: : WHILE ( DEST -- ORIG DEST )
 3574:  POSTPONE IF
 3575:  1 CS-ROLL ; immediate
 3576: 
 3577: : REPEAT ( orig dest -- )
 3578:  POSTPONE AGAIN
 3579:  POSTPONE THEN ; immediate
 3580: @end example
 3581: 
 3582: @noindent
 3583: and then using these to create the control structure:
 3584: 
 3585: @example
 3586: BEGIN
 3587:   ...
 3588: WHILE
 3589:   ...
 3590: REPEAT
 3591: @end example
 3592: 
 3593: That's much easier to read, isn't it? Of course, @code{REPEAT} and
 3594: @code{WHILE} are predefined, so in this example it would not be
 3595: necessary to define them.
 3596: 
 3597: @node Calls and returns, Exception Handling, Arbitrary control structures, Control Structures
 3598: @subsection Calls and returns
 3599: @cindex calling a definition
 3600: @cindex returning from a definition
 3601: 
 3602: @cindex recursive definitions
 3603: A definition can be called simply be writing the name of the definition
 3604: to be called. Normally a definition is invisible during its own
 3605: definition. If you want to write a directly recursive definition, you
 3606: can use @code{recursive} to make the current definition visible, or
 3607: @code{recurse} to call the current definition directly.
 3608: 
 3609: 
 3610: doc-recursive
 3611: doc-recurse
 3612: 
 3613: 
 3614: @comment TODO add example of the two recursion methods
 3615: @quotation
 3616: @progstyle
 3617: I prefer using @code{recursive} to @code{recurse}, because calling the
 3618: definition by name is more descriptive (if the name is well-chosen) than
 3619: the somewhat cryptic @code{recurse}.  E.g., in a quicksort
 3620: implementation, it is much better to read (and think) ``now sort the
 3621: partitions'' than to read ``now do a recursive call''.
 3622: @end quotation
 3623: 
 3624: For mutual recursion, use @code{Defer}red words, like this:
 3625: 
 3626: @example
 3627: Defer foo
 3628: 
 3629: : bar ( ... -- ... )
 3630:  ... foo ... ;
 3631: 
 3632: :noname ( ... -- ... )
 3633:  ... bar ... ;
 3634: IS foo
 3635: @end example
 3636: 
 3637: Deferred words are discussed in more detail in @ref{Deferred words}.
 3638: 
 3639: The current definition returns control to the calling definition when
 3640: the end of the definition is reached or @code{EXIT} is encountered.
 3641: 
 3642: doc-exit
 3643: doc-;s
 3644: 
 3645: 
 3646: @node Exception Handling,  , Calls and returns, Control Structures
 3647: @subsection Exception Handling
 3648: @cindex exceptions
 3649: 
 3650: If your program detects a fatal error condition, the simplest action
 3651: that it can take is to @code{quit}. This resets the return stack and
 3652: restarts the text interpreter, but does not print any error message.
 3653: 
 3654: The next stage in severity is to execute @code{abort}, which has the
 3655: same effect as @code{quit}, with the addition that it resets the data
 3656: stack.
 3657: 
 3658: A slightly more sophisticated approach is use use @code{abort"}, which
 3659: compiles a string to be used as an error message and does a conditional
 3660: @code{abort} at run-time. For example:
 3661: 
 3662: @example
 3663: @kbd{: checker abort" That flag was true" ." A false flag" ;@key{RET}}  ok
 3664: @kbd{0 checker@key{RET}} A false flag ok
 3665: @kbd{1 checker@key{RET}}
 3666: :1: That flag was true
 3667: 1 checker
 3668:   ^^^^^^^
 3669: $400D1648 throw 
 3670: $400E4660
 3671: @end example
 3672: 
 3673: These simple techniques allow a program to react to a fatal error
 3674: condition, but they are not exactly user-friendly. The ANS Forth
 3675: Exception word set provides the pair of words @code{throw} and
 3676: @code{catch}, which can be used to provide sophisticated error-handling.
 3677: 
 3678: @code{catch} has a similar behaviour to @code{execute}, in that it takes
 3679: an @i{xt} as a parameter and starts execution of the xt. However,
 3680: before passing control to the xt, @code{catch} pushes an
 3681: @dfn{exception frame} onto the @dfn{exception stack}. This exception
 3682: frame is used to restore the system to a known state if a detected error
 3683: occurs during the execution of the xt. A typical way to use @code{catch}
 3684: would be:
 3685: 
 3686: @example
 3687: ... ['] foo catch IF ...
 3688: @end example
 3689: 
 3690: @c TOS is undefined. - anton
 3691: 
 3692: @c nac-> TODO -- I need to look at this example again.
 3693: 
 3694: Whilst @code{foo} executes, it can call other words to any level of
 3695: nesting, as usual.  If @code{foo} (and all the words that it calls)
 3696: execute successfully, control will ultimately pass to the word following
 3697: the @code{catch}, and there will be a 0 at TOS.  However, if any word
 3698: detects an error, it can terminate the execution of @code{foo} by
 3699: pushing a non-zero error code onto the stack and then performing a
 3700: @code{throw}. The execution of @code{throw} will pass control to the
 3701: word following the @code{catch}, but this time the TOS will hold the
 3702: error code. Therefore, the @code{IF} in the example can be used to
 3703: determine whether @code{foo} executed successfully.
 3704: 
 3705: This simple example shows how you can use @code{throw} and @code{catch}
 3706: to ``take over'' exception handling from the system:
 3707: @example
 3708: : my-div ['] / catch if ." DIVIDE ERROR" else ." OK.. " . then ;
 3709: @end example
 3710: 
 3711: The next example is more sophisticated and shows a multi-level
 3712: @code{throw} and @code{catch}. To understand this example, start at the
 3713: definition of @code{top-level} and work backwards:
 3714: 
 3715: @example
 3716: : lowest-level ( -- c )
 3717:     key dup 27 = if
 3718:         1 throw \ ESCAPE key pressed
 3719:     else
 3720:         ." lowest-level successful" CR
 3721:     then
 3722: ;
 3723: 
 3724: : lower-level ( -- c )
 3725:     lowest-level
 3726:     \ at this level consider a CTRL-U to be a fatal error
 3727:     dup 21 = if \ CTRL-U
 3728:         2 throw
 3729:     else
 3730:         ." lower-level successful" CR
 3731:     then
 3732: ;
 3733: 
 3734: : low-level ( -- c )
 3735:     ['] lower-level catch
 3736:     ?dup if
 3737:         \ error occurred - do we recognise it?
 3738:         dup 1 = if
 3739:             \ ESCAPE key pressed.. pretend it was an E
 3740:             [char] E
 3741:         else throw \ propogate the error upwards
 3742:         then
 3743:     then
 3744:     ." low-level successfull" CR
 3745: ;
 3746: 
 3747: : top-level ( -- )
 3748:     CR ['] low-level catch \ CATCH is used like EXECUTE
 3749:     ?dup if \ error occurred..
 3750:         ." Error " . ." occurred - contact your supplier"
 3751:     else
 3752:         ." The '" emit ." ' key was pressed" CR
 3753:     then
 3754: ;
 3755: @end example
 3756: 
 3757: The ANS Forth document assigns @code{throw} codes thus:
 3758: 
 3759: @itemize @bullet
 3760: @item
 3761: codes in the range -1 -- -255 are reserved to be assigned by the
 3762: Standard. Assignments for codes in the range -1 -- -58 are currently
 3763: documented in the Standard. In particular, @code{-1 throw} is equivalent
 3764: to @code{abort} and @code{-2 throw} is equivalent to @code{abort"}.
 3765: @item
 3766: codes in the range -256 -- -4095 are reserved to be assigned by the system.
 3767: @item
 3768: all other codes may be assigned by programs.
 3769: @end itemize
 3770: 
 3771: Gforth provides the word @code{exception} as a mechanism for assigning
 3772: system throw codes to applications. This allows multiple applications to
 3773: co-exist in memory without any clash of @code{throw} codes. A definition
 3774: of @code{exception} in ANS Forth is provided in
 3775: @file{compat/exception.fs}.
 3776: 
 3777: 
 3778: doc-quit
 3779: doc-abort
 3780: doc-abort"
 3781: 
 3782: doc-catch
 3783: doc-throw
 3784: doc---exception-exception
 3785: 
 3786: 
 3787: 
 3788: @c -------------------------------------------------------------
 3789: @node Defining Words, Interpretation and Compilation Semantics, Control Structures, Words
 3790: @section Defining Words
 3791: @cindex defining words
 3792: 
 3793: Defining words are used to extend Forth by creating new entries in the dictionary.
 3794: 
 3795: @menu
 3796: * CREATE::
 3797: * Variables::                   Variables and user variables
 3798: * Constants::
 3799: * Values::                      Initialised variables
 3800: * Colon Definitions::
 3801: * Anonymous Definitions::       Definitions without names
 3802: * User-defined Defining Words::
 3803: * Deferred words::              Allow forward references
 3804: * Aliases::
 3805: * Supplying names::
 3806: @end menu
 3807: 
 3808: @node CREATE, Variables, Defining Words, Defining Words
 3809: @subsection @code{CREATE}
 3810: @cindex simple defining words
 3811: @cindex defining words, simple
 3812: 
 3813: Defining words are used to create new entries in the dictionary. The
 3814: simplest defining word is @code{CREATE}. @code{CREATE} is used like
 3815: this:
 3816: 
 3817: @example
 3818: CREATE new-word1
 3819: @end example
 3820: 
 3821: @code{CREATE} is a parsing word that generates a dictionary entry for
 3822: @code{new-word1}. When @code{new-word1} is executed, all that it does is
 3823: leave an address on the stack. The address represents the value of
 3824: the data space pointer (@code{HERE}) at the time that @code{new-word1}
 3825: was defined. Therefore, @code{CREATE} is a way of associating a name
 3826: with the address of a region of memory.
 3827: 
 3828: doc-create
 3829: 
 3830: By extending this example to reserve some memory in data space, we end
 3831: up with a @i{variable}. Here are two different ways to do it:
 3832: 
 3833: @example
 3834: CREATE new-word2 1 cells allot  \ reserve 1 cell - initial value undefined
 3835: CREATE new-word3 4 ,            \ reserve 1 cell and initialise it (to 4)
 3836: @end example
 3837: 
 3838: The variable can be examined and modified using @code{@@} (``fetch'') and
 3839: @code{!} (``store'') like this:
 3840: 
 3841: @example
 3842: new-word2 @@ .      \ get address, fetch from it and display
 3843: 1234 new-word2 !   \ new value, get address, store to it
 3844: @end example
 3845: 
 3846: @cindex arrays
 3847: A similar mechanism can be used to create arrays. For example, an
 3848: 80-character text input buffer:
 3849: 
 3850: @example
 3851: CREATE text-buf 80 chars allot
 3852: 
 3853: text-buf 0 chars c@@ \ the 1st character (offset 0)
 3854: text-buf 3 chars c@@ \ the 4th character (offset 3)
 3855: @end example
 3856: 
 3857: You can build arbitrarily complex data structures by allocating
 3858: appropriate areas of memory. @xref{Structures} for further discussions
 3859: of this, and to learn about some Gforth tools that make it easier.
 3860: 
 3861: 
 3862: @node Variables, Constants, CREATE, Defining Words
 3863: @subsection Variables
 3864: @cindex variables
 3865: 
 3866: The previous section showed how a sequence of commands could be used to
 3867: generate a variable.  As a final refinement, the whole code sequence can
 3868: be wrapped up in a defining word (pre-empting the subject of the next
 3869: section), making it easier to create new variables:
 3870: 
 3871: @example
 3872: : myvariableX ( "name" -- a-addr ) CREATE 1 cells allot ;
 3873: : myvariable0 ( "name" -- a-addr ) CREATE 0 , ;
 3874: 
 3875: myvariableX foo \ variable foo starts off with an unknown value
 3876: myvariable0 joe \ whilst joe is initialised to 0
 3877: 
 3878: 45 3 * foo !   \ set foo to 135
 3879: 1234 joe !     \ set joe to 1234
 3880: 3 joe +!       \ increment joe by 3.. to 1237
 3881: @end example
 3882: 
 3883: Not surprisingly, there is no need to define @code{myvariable}, since
 3884: Forth already has a definition @code{Variable}. ANS Forth does not
 3885: require a @code{Variable} to be initialised when it is created (i.e., it
 3886: behaves like @code{myvariableX}). In contrast, Gforth's @code{Variable}
 3887: initialises the variable to 0 (i.e., it behaves exactly like
 3888: @code{myvariable0}). Forth also provides @code{2Variable} and
 3889: @code{fvariable} for double and floating-point variables, respectively
 3890: -- both are initialised to 0 in Gforth. If you use a @code{Variable} to
 3891: store a boolean, you can use @code{on} and @code{off} to toggle its
 3892: state.
 3893: 
 3894: doc-variable
 3895: doc-2variable
 3896: doc-fvariable
 3897: 
 3898: @cindex user variables
 3899: @cindex user space
 3900: The defining word @code{User} behaves in the same way as @code{Variable}.
 3901: The difference is that it reserves space in @i{user (data) space} rather
 3902: than normal data space. In a Forth system that has a multi-tasker, each
 3903: task has its own set of user variables.
 3904: 
 3905: doc-user
 3906: 
 3907: @comment TODO is that stuff about user variables strictly correct? Is it
 3908: @comment just terminal tasks that have user variables?
 3909: @comment should document tasker.fs (with some examples) elsewhere
 3910: @comment in this manual, then expand on user space and user variables.
 3911: 
 3912: 
 3913: @node Constants, Values, Variables, Defining Words
 3914: @subsection Constants
 3915: @cindex constants
 3916: 
 3917: @code{Constant} allows you to declare a fixed value and refer to it by
 3918: name. For example:
 3919: 
 3920: @example
 3921: 12 Constant INCHES-PER-FOOT
 3922: 3E+08 fconstant SPEED-O-LIGHT
 3923: @end example
 3924: 
 3925: A @code{Variable} can be both read and written, so its run-time
 3926: behaviour is to supply an address through which its current value can be
 3927: manipulated. In contrast, the value of a @code{Constant} cannot be
 3928: changed once it has been declared@footnote{Well, often it can be -- but
 3929: not in a Standard, portable way. It's safer to use a @code{Value} (read
 3930: on).} so it's not necessary to supply the address -- it is more
 3931: efficient to return the value of the constant directly. That's exactly
 3932: what happens; the run-time effect of a constant is to put its value on
 3933: the top of the stack (@ref{User-defined Defining Words} describes one
 3934: way of implementing @code{Constant}).
 3935: 
 3936: Gforth also provides @code{2Constant} and @code{fconstant} for defining
 3937: double and floating-point constants, respectively.
 3938: 
 3939: doc-constant
 3940: doc-2constant
 3941: doc-fconstant
 3942: 
 3943: @c that's too deep, and it's not necessarily true for all ANS Forths. - anton
 3944: @c nac-> How could that not be true in an ANS Forth? You can't define a
 3945: @c constant, use it and then delete the definition of the constant..
 3946: @c I agree that it's rather deep, but IMO it is an important difference
 3947: @c relative to other programming languages.. often it's annoying: it
 3948: @c certainly changes my programming style relative to C.
 3949: 
 3950: Constants in Forth behave differently from their equivalents in other
 3951: programming languages. In other languages, a constant (such as an EQU in
 3952: assembler or a #define in C) only exists at compile-time; in the
 3953: executable program the constant has been translated into an absolute
 3954: number and, unless you are using a symbolic debugger, it's impossible to
 3955: know what abstract thing that number represents. In Forth a constant has
 3956: an entry in the header space and remains there after the code that uses
 3957: it has been defined. In fact, it must remain in the dictionary since it
 3958: has run-time duties to perform. For example:
 3959: 
 3960: @example
 3961: 12 Constant INCHES-PER-FOOT
 3962: : FEET-TO-INCHES ( n1 -- n2 ) INCHES-PER-FOOT * ;
 3963: @end example
 3964: 
 3965: @cindex in-lining of constants
 3966: When @code{FEET-TO-INCHES} is executed, it will in turn execute the xt
 3967: associated with the constant @code{INCHES-PER-FOOT}. If you use
 3968: @code{see} to decompile the definition of @code{FEET-TO-INCHES}, you can
 3969: see that it makes a call to @code{INCHES-PER-FOOT}. Some Forth compilers
 3970: attempt to optimise constants by in-lining them where they are used. You
 3971: can force Gforth to in-line a constant like this:
 3972: 
 3973: @example
 3974: : FEET-TO-INCHES ( n1 -- n2 ) [ INCHES-PER-FOOT ] LITERAL * ;
 3975: @end example
 3976: 
 3977: If you use @code{see} to decompile @i{this} version of
 3978: @code{FEET-TO-INCHES}, you can see that @code{INCHES-PER-FOOT} is no
 3979: longer present. @xref{Interpret/Compile states} and @ref{Literals} on
 3980: how this works.
 3981: 
 3982: In-lining constants in this way might improve execution time
 3983: fractionally, and can ensure that a constant is now only referenced at
 3984: compile-time. However, the definition of the constant still remains in
 3985: the dictionary. Some Forth compilers provide a mechanism for controlling
 3986: a second dictionary for holding transient words such that this second
 3987: dictionary can be deleted later in order to recover memory
 3988: space. However, there is no standard way of doing this.
 3989: 
 3990: 
 3991: @node Values, Colon Definitions, Constants, Defining Words
 3992: @subsection Values
 3993: @cindex values
 3994: 
 3995: A @code{Value} is like a @code{Variable} but with two important
 3996: differences:
 3997: 
 3998: @itemize @bullet
 3999: @item
 4000: A @code{Value} is initialised when it is declared; like a
 4001: @code{Constant} but unlike a @code{Variable}.
 4002: @item
 4003: A @code{Value} returns its value rather than its address when it is
 4004: executed; i.e., it has the same run-time behaviour as @code{Constant}.
 4005: @end itemize
 4006: 
 4007: A @code{Value} needs an additional word, @code{TO} to allow its value to
 4008: be changed. Here are some examples:
 4009: 
 4010: @example
 4011: 12 Value APPLES \ Define APPLES with an initial value of 12
 4012: 34 TO APPLES    \ Change the value of APPLES. TO is a parsing word
 4013: APPLES          \ puts 34 on the top of the stack.
 4014: @end example
 4015: 
 4016: doc-value
 4017: doc-to
 4018: 
 4019: 
 4020: @node Colon Definitions, Anonymous Definitions, Values, Defining Words
 4021: @subsection Colon Definitions
 4022: @cindex colon definitions
 4023: 
 4024: @example
 4025: : name ( ... -- ... )
 4026:     word1 word2 word3 ;
 4027: @end example
 4028: 
 4029: @noindent
 4030: Creates a word called @code{name} that, upon execution, executes
 4031: @code{word1 word2 word3}. @code{name} is a @dfn{(colon) definition}.
 4032: 
 4033: The explanation above is somewhat superficial. @xref{Your first
 4034: definition} for simple examples of colon definitions, then
 4035: @xref{Interpretation and Compilation Semantics} for an in-depth
 4036: discussion of some of the issues involved.
 4037: 
 4038: doc-:
 4039: doc-;
 4040: 
 4041: 
 4042: @node Anonymous Definitions, User-defined Defining Words, Colon Definitions, Defining Words
 4043: @subsection Anonymous Definitions
 4044: @cindex colon definitions
 4045: @cindex defining words without name
 4046: 
 4047: Sometimes you want to define an @dfn{anonymous word}; a word without a
 4048: name. You can do this with:
 4049: 
 4050: doc-:noname
 4051: 
 4052: This leaves the execution token for the word on the stack after the
 4053: closing @code{;}. Here's an example in which a deferred word is
 4054: initialised with an @code{xt} from an anonymous colon definition:
 4055: 
 4056: @example
 4057: Defer deferred
 4058: :noname ( ... -- ... )
 4059:   ... ;
 4060: IS deferred
 4061: @end example
 4062: 
 4063: @noindent
 4064: Gforth provides an alternative way of doing this, using two separate
 4065: words:
 4066: 
 4067: doc-noname
 4068: @cindex execution token of last defined word
 4069: doc-lastxt
 4070: 
 4071: @noindent
 4072: The previous example can be rewritten using @code{noname} and
 4073: @code{lastxt}:
 4074: 
 4075: @example
 4076: Defer deferred
 4077: noname : ( ... -- ... )
 4078:   ... ;
 4079: lastxt IS deferred
 4080: @end example
 4081: 
 4082: @noindent
 4083: @code{noname} works with any defining word, not just @code{:}.
 4084: 
 4085: @code{lastxt} also works when the last word was not defined as
 4086: @code{noname}. It also has the useful property that is is valid as soon
 4087: as the header for a definition has been built. Thus:
 4088: 
 4089: @example
 4090: lastxt . : foo [ lastxt . ] ; ' foo .
 4091: @end example
 4092: 
 4093: @noindent
 4094: prints 3 numbers; the last two are the same.
 4095: 
 4096: 
 4097: @node User-defined Defining Words, Deferred words, Anonymous Definitions, Defining Words
 4098: @subsection User-defined Defining Words
 4099: @cindex user-defined defining words
 4100: @cindex defining words, user-defined
 4101: 
 4102: You can create a new defining word by wrapping defining-time code around
 4103: an existing defining word and putting the sequence in a colon
 4104: definition. For example, suppose that you have a word @code{stats} that
 4105: gathers statistics about colon definitions given the @i{xt} of the
 4106: definition, and you want every colon definition in your application to
 4107: make a call to @code{stats}. You can define and use a new version of
 4108: @code{:} like this:
 4109: 
 4110: @example
 4111: : stats ( xt -- ) DUP ." (Gathering statistics for " . ." )"
 4112:   ... ;  \ other code
 4113: 
 4114: : my: : lastxt postpone literal ['] stats compile, ;
 4115: 
 4116: my: foo + - ;
 4117: @end example
 4118: 
 4119: When @code{foo} is defined using @code{my:} these steps occur:
 4120: 
 4121: @itemize @bullet
 4122: @item
 4123: @code{my:} is executed.
 4124: @item
 4125: The @code{:} within the definition (the one between @code{my:} and
 4126: @code{lastxt}) is executed, and does just what it always does; it parses
 4127: the input stream for a name, builds a dictionary header for the name
 4128: @code{foo} and switches @code{state} from interpret to compile.
 4129: @item
 4130: The word @code{lastxt} is executed. It puts the @i{xt} for the word that is
 4131: being defined -- @code{foo} -- onto the stack.
 4132: @item
 4133: The code that was produced by @code{postpone literal} is executed; this
 4134: causes the value on the stack to be compiled as a literal in the code
 4135: area of @code{foo}.
 4136: @item
 4137: The code @code{['] stats} compiles a literal into the definition of
 4138: @code{my:}. When @code{compile,} is executed, that literal -- the
 4139: execution token for @code{stats} -- is layed down in the code area of
 4140: @code{foo} , following the literal@footnote{Strictly speaking, the
 4141: mechanism that @code{compile,} uses to convert an @i{xt} into something
 4142: in the code area is implementation-dependent. A threaded implementation
 4143: might spit out the execution token directly whilst another
 4144: implementation might spit out a native code sequence.}.
 4145: @item
 4146: At this point, the execution of @code{my:} is complete, and control
 4147: returns to the text interpreter. The text interpreter is in compile
 4148: state, so subsequent text @code{+ -} is compiled into the definition of
 4149: @code{foo} and the @code{;} terminates the definition as always.
 4150: @end itemize
 4151: 
 4152: You can use @code{see} to decompile a word that was defined using
 4153: @code{my:} and see how it is different from a normal @code{:}
 4154: definition. For example:
 4155: 
 4156: @example
 4157: : bar + - ;  \ like foo but using : rather than my:
 4158: see bar
 4159: : bar
 4160:   + - ;
 4161: see foo
 4162: : foo
 4163:   107645672 stats + - ;
 4164: 
 4165: \ use ' stats . to show that 107645672 is the xt for stats
 4166: @end example
 4167: 
 4168: You can use techniques like this to make new defining words in terms of
 4169: @i{any} existing defining word.
 4170: 
 4171: 
 4172: @cindex defining defining words
 4173: @cindex @code{CREATE} ... @code{DOES>}
 4174: If you want the words defined with your defining words to behave
 4175: differently from words defined with standard defining words, you can
 4176: write your defining word like this:
 4177: 
 4178: @example
 4179: : def-word ( "name" -- )
 4180:     CREATE @i{code1}
 4181: DOES> ( ... -- ... )
 4182:     @i{code2} ;
 4183: 
 4184: def-word name
 4185: @end example
 4186: 
 4187: @cindex child words
 4188: This fragment defines a @dfn{defining word} @code{def-word} and then
 4189: executes it.  When @code{def-word} executes, it @code{CREATE}s a new
 4190: word, @code{name}, and executes the code @i{code1}. The code @i{code2}
 4191: is not executed at this time. The word @code{name} is sometimes called a
 4192: @dfn{child} of @code{def-word}.
 4193: 
 4194: When you execute @code{name}, the address of the body of @code{name} is
 4195: put on the data stack and @i{code2} is executed (the address of the body
 4196: of @code{name} is the address @code{HERE} returns immediately after the
 4197: @code{CREATE}).
 4198: 
 4199: @cindex atavism in child words
 4200: You can use @code{def-word} to define a set of child words that behave
 4201: differently, though atavistically; they all have a common run-time
 4202: behaviour determined by @i{code2}. Typically, the @i{code1} sequence
 4203: builds a data area in the body of the child word. The structure of the
 4204: data is common to all children of @code{def-word}, but the data values
 4205: are specific -- and private -- to each child word. When a child word is
 4206: executed, the address of its private data area is passed as a parameter
 4207: on TOS to be used and manipulated@footnote{It is legitimate both to read
 4208: and write to this data area.} by @i{code2}.
 4209: 
 4210: The two fragments of code that make up the defining words act (are
 4211: executed) at two completely separate times:
 4212: 
 4213: @itemize @bullet
 4214: @item
 4215: At @i{define time}, the defining word executes @i{code1} to generate a
 4216: child word
 4217: @item
 4218: At @i{child execution time}, when a child word is invoked, @i{code2}
 4219: is executed, using parameters (data) that are private and specific to
 4220: the child word.
 4221: @end itemize
 4222: 
 4223: Another way of understanding the behaviour of @code{def-word} and
 4224: @code{name} is to say that, if you make the following definitions:
 4225: @example
 4226: : def-word1 ( "name" -- )
 4227:     CREATE @i{code1} ;
 4228: 
 4229: : action1 ( ... -- ... )
 4230:     @i{code2} ;
 4231: 
 4232: def-word1 name1
 4233: @end example
 4234: 
 4235: @noindent
 4236: Then using @code{name1 action1} is equivalent to using @code{name}.
 4237: 
 4238: The classic example is that you can define @code{CONSTANT} in this way:
 4239: 
 4240: @example
 4241: : CONSTANT ( w "name" -- )
 4242:     CREATE ,
 4243: DOES> ( -- w )
 4244:     @@ ;
 4245: @end example
 4246: 
 4247: @comment There is a beautiful description of how this works and what
 4248: @comment it does in the Forthwrite 100th edition.. as well as an elegant
 4249: @comment commentary on the Counting Fruits problem.
 4250: 
 4251: When you create a constant with @code{5 CONSTANT five}, a set of
 4252: define-time actions take place; first a new word @code{five} is created,
 4253: then the value 5 is laid down in the body of @code{five} with
 4254: @code{,}. When @code{five} is executed, the address of the body is put on
 4255: the stack, and @code{@@} retrieves the value 5. The word @code{five} has
 4256: no code of its own; it simply contains a data field and a pointer to the
 4257: code that follows @code{DOES>} in its defining word. That makes words
 4258: created in this way very compact.
 4259: 
 4260: The final example in this section is intended to remind you that space
 4261: reserved in @code{CREATE}d words is @i{data} space and therefore can be
 4262: both read and written by a Standard program@footnote{Exercise: use this
 4263: example as a starting point for your own implementation of @code{Value}
 4264: and @code{TO} -- if you get stuck, investigate the behaviour of @code{'} and
 4265: @code{[']}.}:
 4266: 
 4267: @example
 4268: : foo ( "name" -- )
 4269:     CREATE -1 ,
 4270: DOES> ( -- )
 4271:     @@ . ;
 4272: 
 4273: foo first-word
 4274: foo second-word
 4275: 
 4276: 123 ' first-word >BODY !
 4277: @end example
 4278: 
 4279: If @code{first-word} had been a @code{CREATE}d word, we could simply
 4280: have executed it to get the address of its data field. However, since it
 4281: was defined to have @code{DOES>} actions, its execution semantics are to
 4282: perform those @code{DOES>} actions. To get the address of its data field
 4283: it's necessary to use @code{'} to get its xt, then @code{>BODY} to
 4284: translate the xt into the address of the data field.  When you execute
 4285: @code{first-word}, it will display @code{123}. When you execute
 4286: @code{second-word} it will display @code{-1}.
 4287: 
 4288: @cindex stack effect of @code{DOES>}-parts
 4289: @cindex @code{DOES>}-parts, stack effect
 4290: In the examples above the stack comment after the @code{DOES>} specifies
 4291: the stack effect of the defined words, not the stack effect of the
 4292: following code (the following code expects the address of the body on
 4293: the top of stack, which is not reflected in the stack comment). This is
 4294: the convention that I use and recommend (it clashes a bit with using
 4295: locals declarations for stack effect specification, though).
 4296: 
 4297: @subsubsection Applications of @code{CREATE..DOES>}
 4298: @cindex @code{CREATE} ... @code{DOES>}, applications
 4299: 
 4300: You may wonder how to use this feature. Here are some usage patterns:
 4301: 
 4302: @cindex factoring similar colon definitions
 4303: When you see a sequence of code occurring several times, and you can
 4304: identify a meaning, you will factor it out as a colon definition. When
 4305: you see similar colon definitions, you can factor them using
 4306: @code{CREATE..DOES>}. E.g., an assembler usually defines several words
 4307: that look very similar:
 4308: @example
 4309: : ori, ( reg-target reg-source n -- )
 4310:     0 asm-reg-reg-imm ;
 4311: : andi, ( reg-target reg-source n -- )
 4312:     1 asm-reg-reg-imm ;
 4313: @end example
 4314: 
 4315: @noindent
 4316: This could be factored with:
 4317: @example
 4318: : reg-reg-imm ( op-code -- )
 4319:     CREATE ,
 4320: DOES> ( reg-target reg-source n -- )
 4321:     @@ asm-reg-reg-imm ;
 4322: 
 4323: 0 reg-reg-imm ori,
 4324: 1 reg-reg-imm andi,
 4325: @end example
 4326: 
 4327: @cindex currying
 4328: Another view of @code{CREATE..DOES>} is to consider it as a crude way to
 4329: supply a part of the parameters for a word (known as @dfn{currying} in
 4330: the functional language community). E.g., @code{+} needs two
 4331: parameters. Creating versions of @code{+} with one parameter fixed can
 4332: be done like this:
 4333: @example
 4334: : curry+ ( n1 -- )
 4335:     CREATE ,
 4336: DOES> ( n2 -- n1+n2 )
 4337:     @@ + ;
 4338: 
 4339:  3 curry+ 3+
 4340: -2 curry+ 2-
 4341: @end example
 4342: 
 4343: @subsubsection The gory details of @code{CREATE..DOES>}
 4344: @cindex @code{CREATE} ... @code{DOES>}, details
 4345: 
 4346: doc-does>
 4347: 
 4348: @cindex @code{DOES>} in a separate definition
 4349: This means that you need not use @code{CREATE} and @code{DOES>} in the
 4350: same definition; you can put the @code{DOES>}-part in a separate
 4351: definition. This allows us to, e.g., select among different @code{DOES>}-parts:
 4352: @example
 4353: : does1 
 4354: DOES> ( ... -- ... )
 4355:     ... ;
 4356: 
 4357: : does2
 4358: DOES> ( ... -- ... )
 4359:     ... ;
 4360: 
 4361: : def-word ( ... -- ... )
 4362:     create ...
 4363:     IF
 4364:        does1
 4365:     ELSE
 4366:        does2
 4367:     ENDIF ;
 4368: @end example
 4369: 
 4370: In this example, the selection of whether to use @code{does1} or
 4371: @code{does2} is made at compile-time; at the time that the child word is
 4372: @code{CREATE}d.
 4373: 
 4374: @cindex @code{DOES>} in interpretation state
 4375: In a standard program you can apply a @code{DOES>}-part only if the last
 4376: word was defined with @code{CREATE}. In Gforth, the @code{DOES>}-part
 4377: will override the behaviour of the last word defined in any case. In a
 4378: standard program, you can use @code{DOES>} only in a colon
 4379: definition. In Gforth, you can also use it in interpretation state, in a
 4380: kind of one-shot mode; for example:
 4381: @example
 4382: CREATE name ( ... -- ... )
 4383:   @i{initialization}
 4384: DOES>
 4385:   @i{code} ;
 4386: @end example
 4387: 
 4388: @noindent
 4389: is equivalent to the standard:
 4390: @example
 4391: :noname
 4392: DOES>
 4393:     @i{code} ;
 4394: CREATE name EXECUTE ( ... -- ... )
 4395:     @i{initialization}
 4396: @end example
 4397: 
 4398: 
 4399: doc->body
 4400: 
 4401: 
 4402: @node Deferred words, Aliases, User-defined Defining Words, Defining Words
 4403: @subsection Deferred words
 4404: @cindex deferred words
 4405: 
 4406: The defining word @code{Defer} allows you to define a word by name
 4407: without defining its behaviour; the definition of its behaviour is
 4408: deferred. Here are two situation where this can be useful:
 4409: 
 4410: @itemize @bullet
 4411: @item
 4412: Where you want to allow the behaviour of a word to be altered later, and
 4413: for all precompiled references to the word to change when its behaviour
 4414: is changed.
 4415: @item
 4416: For mutual recursion; @xref{Calls and returns}.
 4417: @end itemize
 4418: 
 4419: In the following example, @code{foo} always invokes the version of
 4420: @code{greet} that prints ``@code{Good morning}'' whilst @code{bar}
 4421: always invokes the version that prints ``@code{Hello}''. There is no way
 4422: of getting @code{foo} to use the later version without re-ordering the
 4423: source code and recompiling it.
 4424: 
 4425: @example
 4426: : greet ." Good morning" ;
 4427: : foo ... greet ... ;
 4428: : greet ." Hello" ;
 4429: : bar ... greet ... ;
 4430: @end example
 4431: 
 4432: This problem can be solved by defining @code{greet} as a @code{Defer}red
 4433: word. The behaviour of a @code{Defer}red word can be defined and
 4434: redefined at any time by using @code{IS} to associate the xt of a
 4435: previously-defined word with it. The previous example becomes:
 4436: 
 4437: @example
 4438: Defer greet
 4439: : foo ... greet ... ;
 4440: : bar ... greet ... ;
 4441: : greet1 ." Good morning" ;
 4442: : greet2 ." Hello" ;
 4443: ' greet2 <IS> greet  \ make greet behave like greet2
 4444: @end example
 4445: 
 4446: A deferred word can be used to improve the statistics-gathering example
 4447: from @ref{User-defined Defining Words}; rather than edit the
 4448: application's source code to change every @code{:} to a @code{my:}, do
 4449: this:
 4450: 
 4451: @example
 4452: : real: : ;     \ retain access to the original
 4453: defer :         \ redefine as a deferred word
 4454: ' my: IS :      \ use special version of :
 4455: \
 4456: \ load application here
 4457: \
 4458: ' real: IS :    \ go back to the original
 4459: @end example
 4460: 
 4461: 
 4462: One thing to note is that @code{<IS>} consumes its name when it is
 4463: executed.  If you want to specify the name at compile time, use
 4464: @code{[IS]}:
 4465: 
 4466: @example
 4467: : set-greet ( xt -- )
 4468:   [IS] greet ;
 4469: 
 4470: ' greet1 set-greet
 4471: @end example
 4472: 
 4473: A deferred word can only inherit default semantics from the xt (because
 4474: that is all that an xt can represent -- @pxref{Tokens for Words} for
 4475: more discussion of this). However, the semantics of the deferred word
 4476: itself can be modified at the time that it is defined. For example:
 4477: 
 4478: @example
 4479: : bar .... ; compile-only
 4480: Defer fred immediate
 4481: Defer jim
 4482: 
 4483: ' bar <IS> jim  \ jim has default semantics
 4484: ' bar <IS> fred \ fred is immediate
 4485: @end example
 4486: 
 4487: doc-defer
 4488: doc-<is>
 4489: doc-[is]
 4490: doc-is
 4491: @comment TODO document these: what's defers [is]
 4492: doc-what's
 4493: doc-defers
 4494: 
 4495: @c Use @code{words-deferred} to see a list of deferred words.
 4496: 
 4497: Definitions in ANS Forth for @code{defer}, @code{<is>} and @code{[is]}
 4498: are provided in @file{compat/defer.fs}.
 4499: 
 4500: 
 4501: @node Aliases, Supplying names, Deferred words, Defining Words
 4502: @subsection Aliases
 4503: @cindex aliases
 4504: 
 4505: The defining word @code{Alias} allows you to define a word by name that
 4506: has the same behaviour as some other word. Here are two situation where
 4507: this can be useful:
 4508: 
 4509: @itemize @bullet
 4510: @item
 4511: When you want access to a word's definition from a different word list
 4512: (for an example of this, see the definition of the @code{Root} word list
 4513: in the Gforth source).
 4514: @item
 4515: When you want to create a synonym; a definition that can be known by
 4516: either of two names (for example, @code{THEN} and @code{ENDIF} are
 4517: aliases).
 4518: @end itemize
 4519: 
 4520: The word whose behaviour the alias is to inherit is represented by an
 4521: xt. Therefore, the alias only inherits default semantics from its
 4522: ancestor. The semantics of the alias itself can be modified at the time
 4523: that it is defined. For example:
 4524: 
 4525: @example
 4526: : foo ... ; immediate
 4527: 
 4528: ' foo Alias bar \ bar is not an immediate word
 4529: ' foo Alias fooby immediate \ fooby is an immediate word
 4530: @end example
 4531: 
 4532: Words that are aliases have the same xt, different headers in the
 4533: dictionary, and consequently different name tokens (@pxref{Tokens for
 4534: Words}) and possibly different immediate flags.  An alias can only have
 4535: default or immediate compilation semantics; you can define aliases for
 4536: combined words with @code{interpret/compile:} -- see @ref{Combined words}.
 4537: 
 4538: doc-alias
 4539: 
 4540: 
 4541: @node Supplying names, , Aliases, Defining Words
 4542: @subsection Supplying the name of a defined word
 4543: @cindex names for defined words
 4544: @cindex defining words, name given in a string
 4545: 
 4546: By default, a defining word takes the name for the defined word from the
 4547: input stream. Sometimes you want to supply the name from a string. You
 4548: can do this with:
 4549: 
 4550: doc-nextname
 4551: 
 4552: For example:
 4553: 
 4554: @example
 4555: s" foo" nextname create
 4556: @end example
 4557: 
 4558: @noindent
 4559: is equivalent to:
 4560: 
 4561: @example
 4562: create foo
 4563: @end example
 4564: 
 4565: @noindent
 4566: @code{nextname} works with any defining word, not just @code{:}.
 4567: 
 4568: 
 4569: @node Interpretation and Compilation Semantics, Tokens for Words, Defining Words, Words
 4570: @section Interpretation and Compilation Semantics
 4571: @cindex semantics, interpretation and compilation
 4572: 
 4573: @cindex interpretation semantics
 4574: The @dfn{interpretation semantics} of a word are what the text
 4575: interpreter does when it encounters the word in interpret state. It also
 4576: appears in some other contexts, e.g., the execution token returned by
 4577: @code{' @i{word}} identifies the interpretation semantics of
 4578: @i{word} (in other words, @code{' @i{word} execute} is equivalent to
 4579: interpret-state text interpretation of @code{@i{word}}).
 4580: 
 4581: @cindex compilation semantics
 4582: The @dfn{compilation semantics} of a word are what the text interpreter
 4583: does when it encounters the word in compile state. It also appears in
 4584: other contexts, e.g, @code{POSTPONE @i{word}} compiles@footnote{In
 4585: standard terminology, ``appends to the current definition''.} the
 4586: compilation semantics of @i{word}.
 4587: 
 4588: @cindex execution semantics
 4589: The standard also talks about @dfn{execution semantics}. They are used
 4590: only for defining the interpretation and compilation semantics of many
 4591: words. By default, the interpretation semantics of a word are to
 4592: @code{execute} its execution semantics, and the compilation semantics of
 4593: a word are to @code{compile,} its execution semantics.@footnote{In
 4594: standard terminology: The default interpretation semantics are its
 4595: execution semantics; the default compilation semantics are to append its
 4596: execution semantics to the execution semantics of the current
 4597: definition.}
 4598: 
 4599: @comment TODO expand, make it co-operate with new sections on text interpreter.
 4600: 
 4601: @cindex immediate words
 4602: @cindex compile-only words
 4603: You can change the semantics of the most-recently defined word:
 4604: 
 4605: 
 4606: doc-immediate
 4607: doc-compile-only
 4608: doc-restrict
 4609: 
 4610: 
 4611: Note that ticking (@code{'}) a compile-only word gives an error
 4612: (``Interpreting a compile-only word'').
 4613: 
 4614: @menu
 4615: * Combined words::
 4616: @end menu
 4617: 
 4618: @node Combined words, ,Interpretation and Compilation Semantics, Interpretation and Compilation Semantics
 4619: @subsection Combined Words
 4620: @cindex combined words
 4621: 
 4622: Gforth allows you to define @dfn{combined words} -- words that have an
 4623: arbitrary combination of interpretation and compilation semantics.
 4624: 
 4625: 
 4626: doc-interpret/compile:
 4627: 
 4628: 
 4629: This feature was introduced for implementing @code{TO} and @code{S"}. I
 4630: recommend that you do not define such words, as cute as they may be:
 4631: they make it hard to get at both parts of the word in some contexts.
 4632: E.g., assume you want to get an execution token for the compilation
 4633: part. Instead, define two words, one that embodies the interpretation
 4634: part, and one that embodies the compilation part.  Once you have done
 4635: that, you can define a combined word with @code{interpret/compile:} for
 4636: the convenience of your users.
 4637: 
 4638: You might try to use this feature to provide an optimizing
 4639: implementation of the default compilation semantics of a word. For
 4640: example, by defining:
 4641: @example
 4642: :noname
 4643:    foo bar ;
 4644: :noname
 4645:    POSTPONE foo POSTPONE bar ;
 4646: interpret/compile: opti-foobar
 4647: @end example
 4648: 
 4649: @noindent
 4650: as an optimizing version of:
 4651: 
 4652: @example
 4653: : foobar
 4654:     foo bar ;
 4655: @end example
 4656: 
 4657: Unfortunately, this does not work correctly with @code{[compile]},
 4658: because @code{[compile]} assumes that the compilation semantics of all
 4659: @code{interpret/compile:} words are non-default. I.e., @code{[compile]
 4660: opti-foobar} would compile compilation semantics, whereas
 4661: @code{[compile] foobar} would compile interpretation semantics.
 4662: 
 4663: @cindex state-smart words (are a bad idea)
 4664: Some people try to use @dfn{state-smart} words to emulate the feature provided
 4665: by @code{interpret/compile:} (words are state-smart if they check
 4666: @code{STATE} during execution). E.g., they would try to code
 4667: @code{foobar} like this:
 4668: 
 4669: @example
 4670: : foobar
 4671:   STATE @@
 4672:   IF ( compilation state )
 4673:     POSTPONE foo POSTPONE bar
 4674:   ELSE
 4675:     foo bar
 4676:   ENDIF ; immediate
 4677: @end example
 4678: 
 4679: Although this works if @code{foobar} is only processed by the text
 4680: interpreter, it does not work in other contexts (like @code{'} or
 4681: @code{POSTPONE}). E.g., @code{' foobar} will produce an execution token
 4682: for a state-smart word, not for the interpretation semantics of the
 4683: original @code{foobar}; when you execute this execution token (directly
 4684: with @code{EXECUTE} or indirectly through @code{COMPILE,}) in compile
 4685: state, the result will not be what you expected (i.e., it will not
 4686: perform @code{foo bar}). State-smart words are a bad idea. Simply don't
 4687: write them@footnote{For a more detailed discussion of this topic, see
 4688: @cite{@code{State}-smartness -- Why it is Evil and How to Exorcise it} by Anton
 4689: Ertl; presented at EuroForth '98 and available from
 4690: @*@uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz}}!
 4691: 
 4692: @cindex defining words with arbitrary semantics combinations
 4693: It is also possible to write defining words that define words with
 4694: arbitrary combinations of interpretation and compilation semantics. In
 4695: general, they look like this:
 4696: 
 4697: @example
 4698: : def-word
 4699:     create-interpret/compile
 4700:     @i{code1}
 4701: interpretation>
 4702:     @i{code2}
 4703: <interpretation
 4704: compilation>
 4705:     @i{code3}
 4706: <compilation ;
 4707: @end example
 4708: 
 4709: For a @i{word} defined with @code{def-word}, the interpretation
 4710: semantics are to push the address of the body of @i{word} and perform
 4711: @i{code2}, and the compilation semantics are to push the address of
 4712: the body of @i{word} and perform @i{code3}. E.g., @code{constant}
 4713: can also be defined like this (except that the defined constants don't
 4714: behave correctly when @code{[compile]}d):
 4715: 
 4716: @example
 4717: : constant ( n "name" -- )
 4718:     create-interpret/compile
 4719:     ,
 4720: interpretation> ( -- n )
 4721:     @@
 4722: <interpretation
 4723: compilation> ( compilation. -- ; run-time. -- n )
 4724:     @@ postpone literal
 4725: <compilation ;
 4726: @end example
 4727: 
 4728: 
 4729: doc-create-interpret/compile
 4730: doc-interpretation>
 4731: doc-<interpretation
 4732: doc-compilation>
 4733: doc-<compilation
 4734: 
 4735: 
 4736: Words defined with @code{interpret/compile:} and
 4737: @code{create-interpret/compile} have an extended header structure that
 4738: differs from other words; however, unless you try to access them with
 4739: plain address arithmetic, you should not notice this. Words for
 4740: accessing the header structure usually know how to deal with this; e.g.,
 4741: @code{'} @i{word} @code{>body} also gives you the body of a word created
 4742: with @code{create-interpret/compile}.
 4743: 
 4744: 
 4745: doc-postpone
 4746: 
 4747: @comment TODO -- expand glossary text for POSTPONE
 4748: 
 4749: 
 4750: @c -------------------------------------------------------------
 4751: @node Tokens for Words, The Text Interpreter, Interpretation and Compilation Semantics, Words
 4752: @section Tokens for Words
 4753: @cindex tokens for words
 4754: 
 4755: This section describes the creation and use of tokens that represent
 4756: words.
 4757: 
 4758: Named words have information stored in their header space entries to
 4759: indicate any non-default semantics (@pxref{Interpretation and
 4760: Compilation Semantics}). The semantics can be modified, using
 4761: @code{immediate} and/or @code{compile-only}, at the time that the words
 4762: are defined. Unnamed words have (by definition) no header space
 4763: entry, and therefore must have default semantics.
 4764: 
 4765: Named words have interpretation and compilation semantics. Unnamed words
 4766: just have execution semantics.
 4767: 
 4768: @cindex xt
 4769: @cindex execution token
 4770: The execution semantics of an unnamed word are represented by an
 4771: @dfn{execution token} (@i{xt}). As explained in @ref{Supplying names},
 4772: the execution token of the last word defined can be produced with
 4773: @code{lastxt}.
 4774: 
 4775: The interpretation semantics of a named word are also represented by an
 4776: execution token. You can produce the execution token using @code{'} or
 4777: @code{[']}. A simple example shows the difference between the two:
 4778: 
 4779: @example
 4780: : greet ( -- )   ." Hello" ;
 4781: : foo ( -- xt )  ['] greet execute ; \ ['] parses greet at compile-time
 4782: : bar ( -- )     ' execute ; \  '  parses at run-time
 4783: 
 4784: \ the next four lines all do the same thing
 4785: foo
 4786: bar greet
 4787: greet
 4788: ' greet EXECUTE
 4789: @end example
 4790: 
 4791: An execution token occupies one cell.
 4792: @cindex code field address
 4793: @cindex CFA
 4794: In Gforth, the abstract data type @i{execution token} is implemented
 4795: as a code field address (CFA).
 4796: @comment TODO note that the standard does not say what it represents..
 4797: @comment and you cannot necessarily compile it in all Forths (eg native
 4798: @comment compilers?).
 4799: 
 4800: For literals, use @code{'} in interpreted code and @code{[']} in
 4801: compiled code. Gforth's @code{'} and @code{[']} behave somewhat
 4802: unusually by complaining about compile-only words. To get the execution
 4803: token for a compile-only word @i{name}, use @code{COMP' @i{name} DROP}
 4804: or @code{[COMP'] @i{name} DROP}.
 4805: 
 4806: @cindex compilation token
 4807: The compilation semantics of a named word are represented by a
 4808: @dfn{compilation token} consisting of two cells: @i{w xt}. The top cell
 4809: @i{xt} is an execution token. The compilation semantics represented by
 4810: the compilation token can be performed with @code{execute}, which
 4811: consumes the whole compilation token, with an additional stack effect
 4812: determined by the represented compilation semantics.
 4813: 
 4814: At present, the @i{w} part of a compilation token is an execution token,
 4815: and the @i{xt} part represents either @code{execute} or
 4816: @code{compile,}@footnote{Depending upon the compilation semantics of the
 4817: word. If the word has default compilation semantics, the @i{xt} will
 4818: represent @code{compile,}. Otherwise (e.g., for immediate words), the
 4819: @i{xt} will represent @code{execute}.}. However, don't rely on that
 4820: knowledge, unless necessary; future versions of Gforth may introduce
 4821: unusual compilation tokens (e.g., a compilation token that represents
 4822: the compilation semantics of a literal).
 4823: 
 4824: You can compile the compilation semantics with @code{postpone,}. I.e.,
 4825: @code{COMP' @i{word} postpone,} is equivalent to @code{postpone
 4826: @i{word}}.
 4827: 
 4828: @cindex name token
 4829: @cindex name field address
 4830: @cindex NFA
 4831: Named words are also represented by the @dfn{name token}, (@i{nt}). In
 4832: Gforth, the abstract data type @emph{name token} is implemented as a
 4833: name field address (NFA).
 4834: 
 4835: 
 4836: doc-execute
 4837: doc-perform
 4838: doc-compile,
 4839: doc-[']
 4840: doc-'
 4841: doc-[comp']
 4842: doc-comp'
 4843: doc-postpone,
 4844: 
 4845: doc-find-name
 4846: doc-name>int
 4847: doc-name?int
 4848: doc-name>comp
 4849: doc-name>string
 4850: 
 4851: 
 4852: @c ----------------------------------------------------------
 4853: @node The Text Interpreter, Word Lists, Tokens for Words, Words
 4854: @section  The Text Interpreter
 4855: @cindex interpreter - outer
 4856: @cindex text interpreter
 4857: @cindex outer interpreter
 4858: 
 4859: @c Should we really describe all these ugly details?  IMO the text
 4860: @c interpreter should be much cleaner, but that may not be possible within
 4861: @c ANS Forth. - anton
 4862: @c nac-> I wanted to explain how it works to show how you can exploit
 4863: @c it in your own programs. When I was writing a cross-compiler, figuring out
 4864: @c some of these gory details was very helpful to me. None of the textbooks
 4865: @c I've seen cover it, and the most modern Forth textbook -- Forth Inc's,
 4866: @c seems to positively avoid going into too much detail for some of
 4867: @c the internals.
 4868: 
 4869: The text interpreter@footnote{This is an expanded version of the
 4870: material in @ref{Introducing the Text Interpreter}.} is an endless loop
 4871: that processes input from the current input device. It is also called
 4872: the outer interpreter, in contrast to the inner interpreter
 4873: (@pxref{Engine}) which executes the compiled Forth code on interpretive
 4874: implementations.
 4875: 
 4876: @cindex interpret state
 4877: @cindex compile state
 4878: The text interpreter operates in one of two states: @dfn{interpret
 4879: state} and @dfn{compile state}. The current state is defined by the
 4880: aptly-named variable, @code{state}.
 4881: 
 4882: This section starts by describing how the text interpreter behaves when
 4883: it is in interpret state, processing input from the user input device --
 4884: the keyboard. This is the mode that a Forth system is in after it starts
 4885: up.
 4886: 
 4887: @cindex input buffer
 4888: @cindex terminal input buffer
 4889: The text interpreter works from an area of memory called the @dfn{input
 4890: buffer}@footnote{When the text interpreter is processing input from the
 4891: keyboard, this area of memory is called the @dfn{terminal input buffer}
 4892: (TIB) and is addressed by the (obsolescent) words @code{TIB} and
 4893: @code{#TIB}.}, which stores your keyboard input when you press the
 4894: @key{RET} key. Starting at the beginning of the input buffer, it skips
 4895: leading spaces (called @dfn{delimiters}) then parses a string (a
 4896: sequence of non-space characters) until it reaches either a space
 4897: character or the end of the buffer. Having parsed a string, it makes two
 4898: attempts to process it:
 4899: 
 4900: @cindex dictionary
 4901: @itemize @bullet
 4902: @item
 4903: It looks for the string in a @dfn{dictionary} of definitions. If the
 4904: string is found, the string names a @dfn{definition} (also known as a
 4905: @dfn{word}) and the dictionary search returns information that allows
 4906: the text interpreter to perform the word's @dfn{interpretation
 4907: semantics}. In most cases, this simply means that the word will be
 4908: executed.
 4909: @item
 4910: If the string is not found in the dictionary, the text interpreter
 4911: attempts to treat it as a number, using the rules described in
 4912: @ref{Number Conversion}. If the string represents a legal number in the
 4913: current radix, the number is pushed onto a parameter stack (the data
 4914: stack for integers, the floating-point stack for floating-point
 4915: numbers).
 4916: @end itemize
 4917: 
 4918: If both attempts fail, or if the word is found in the dictionary but has
 4919: no interpretation semantics@footnote{This happens if the word was
 4920: defined as @code{COMPILE-ONLY}.} the text interpreter discards the
 4921: remainder of the input buffer, issues an error message and waits for
 4922: more input. If one of the attempts succeeds, the text interpreter
 4923: repeats the parsing process until the whole of the input buffer has been
 4924: processed, at which point it prints the status message ``@code{ ok}''
 4925: and waits for more input.
 4926: 
 4927: @cindex parse area
 4928: The text interpreter keeps track of its position in the input buffer by
 4929: updating a variable called @code{>IN} (pronounced ``to-in''). The value
 4930: of @code{>IN} starts out as 0, indicating an offset of 0 from the start
 4931: of the input buffer. The region from offset @code{>IN @@} to the end of
 4932: the input buffer is called the @dfn{parse area}@footnote{In other words,
 4933: the text interpreter processes the contents of the input buffer by
 4934: parsing strings from the parse area until the parse area is empty.}.
 4935: This example shows how @code{>IN} changes as the text interpreter parses
 4936: the input buffer:
 4937: 
 4938: @example
 4939: : remaining >IN @@ SOURCE 2 PICK - -ROT + SWAP
 4940:   CR ." ->" TYPE ." <-" ; IMMEDIATE 
 4941: 
 4942: 1 2 3 remaining + remaining . 
 4943: 
 4944: : foo 1 2 3 remaining SWAP remaining ;
 4945: @end example
 4946: 
 4947: @noindent
 4948: The result is:
 4949: 
 4950: @example
 4951: ->+ remaining .<-
 4952: ->.<-5  ok
 4953: 
 4954: ->SWAP remaining ;-<
 4955: ->;<-  ok
 4956: @end example
 4957: 
 4958: @cindex parsing words
 4959: The value of @code{>IN} can also be modified by a word in the input
 4960: buffer that is executed by the text interpreter.  This means that a word
 4961: can ``trick'' the text interpreter into either skipping a section of the
 4962: input buffer@footnote{This is how parsing words work.} or into parsing a
 4963: section twice. For example:
 4964: 
 4965: @example
 4966: : lat ." <<lat>>" ;
 4967: : flat ." <<flat>>" >IN DUP @@ 3 - SWAP ! ;
 4968: @end example
 4969: 
 4970: @noindent
 4971: When @code{flat} is executed, this output is produced@footnote{Exercise
 4972: for the reader: what would happen if the @code{3} were replaced with
 4973: @code{4}?}:
 4974: 
 4975: @example
 4976: <<flat>><<lat>>
 4977: @end example
 4978: 
 4979: @noindent
 4980: Two important notes about the behaviour of the text interpreter:
 4981: 
 4982: @itemize @bullet
 4983: @item
 4984: It processes each input string to completion before parsing additional
 4985: characters from the input buffer.
 4986: @item
 4987: It treats the input buffer as a read-only region (and so must your code).
 4988: @end itemize
 4989: 
 4990: @noindent
 4991: When the text interpreter is in compile state, its behaviour changes in
 4992: these ways:
 4993: 
 4994: @itemize @bullet
 4995: @item
 4996: If a parsed string is found in the dictionary, the text interpreter will
 4997: perform the word's @dfn{compilation semantics}. In most cases, this
 4998: simply means that the execution semantics of the word will be appended
 4999: to the current definition.
 5000: @item
 5001: When a number is encountered, it is compiled into the current definition
 5002: (as a literal) rather than being pushed onto a parameter stack.
 5003: @item
 5004: If an error occurs, @code{state} is modified to put the text interpreter
 5005: back into interpret state.
 5006: @item
 5007: Each time a line is entered from the keyboard, Gforth prints
 5008: ``@code{ compiled}'' rather than `` @code{ok}''.
 5009: @end itemize
 5010: 
 5011: @cindex text interpreter - input sources
 5012: When the text interpreter is using an input device other than the
 5013: keyboard, its behaviour changes in these ways:
 5014: 
 5015: @itemize @bullet
 5016: @item
 5017: When the parse area is empty, the text interpreter attempts to refill
 5018: the input buffer from the input source. When the input source is
 5019: exhausted, the input source is set back to the user input device.
 5020: @item
 5021: It doesn't print out ``@code{ ok}'' or ``@code{ compiled}'' messages each
 5022: time the parse area is emptied.
 5023: @item
 5024: If an error occurs, the input source is set back to the user input
 5025: device.
 5026: @end itemize
 5027: 
 5028: @ref{Input Sources} describes this in more detail.
 5029: 
 5030: 
 5031: doc->in
 5032: doc-source
 5033: 
 5034: doc-tib
 5035: doc-#tib
 5036: 
 5037: 
 5038: @menu
 5039: * Input Sources::
 5040: * Number Conversion::
 5041: * Interpret/Compile states::
 5042: * Literals::
 5043: * Interpreter Directives::
 5044: @end menu
 5045: 
 5046: @node Input Sources, Number Conversion, The Text Interpreter, The Text Interpreter
 5047: @subsection Input Sources
 5048: @cindex input sources
 5049: @cindex text interpreter - input sources
 5050: 
 5051: By default, the text interpreter processes input from the user input
 5052: device (the keyboard) when Forth starts up. The text interpreter can
 5053: process input from any of these sources:
 5054: 
 5055: @itemize @bullet
 5056: @item
 5057: The user input device -- the keyboard.
 5058: @item
 5059: A file, using the words described in @ref{Forth source files}.
 5060: @item
 5061: A block, using the words described in @ref{Blocks}.
 5062: @item
 5063: A text string, using @code{evaluate}.
 5064: @end itemize
 5065: 
 5066: A program can identify the current input device from the values of
 5067: @code{source-id} and @code{blk}.
 5068: 
 5069: 
 5070: doc-source-id
 5071: doc-blk
 5072: 
 5073: doc-save-input
 5074: doc-restore-input
 5075: 
 5076: doc-evaluate
 5077: 
 5078: 
 5079: 
 5080: @node Number Conversion, Interpret/Compile states, Input Sources, The Text Interpreter
 5081: @subsection Number Conversion
 5082: @cindex number conversion
 5083: @cindex double-cell numbers, input format
 5084: @cindex input format for double-cell numbers
 5085: @cindex single-cell numbers, input format
 5086: @cindex input format for single-cell numbers
 5087: @cindex floating-point numbers, input format
 5088: @cindex input format for floating-point numbers
 5089: 
 5090: This section describes the rules that the text interpreter uses when it
 5091: tries to convert a string into a number.
 5092: 
 5093: Let <digit> represent any character that is a legal digit in the current
 5094: number base@footnote{For example, 0-9 when the number base is decimal or
 5095: 0-9, A-F when the number base is hexadecimal.}.
 5096: 
 5097: Let <decimal digit> represent any character in the range 0-9.
 5098: 
 5099: Let @{@i{a b}@} represent the @i{optional} presence of any of the characters
 5100: in the braces (@i{a} or @i{b} or neither).
 5101: 
 5102: Let * represent any number of instances of the previous character
 5103: (including none).
 5104: 
 5105: Let any other character represent itself.
 5106: 
 5107: @noindent
 5108: Now, the conversion rules are:
 5109: 
 5110: @itemize @bullet
 5111: @item
 5112: A string of the form <digit><digit>* is treated as a single-precision
 5113: (cell-sized) positive integer. Examples are 0 123 6784532 32343212343456 42
 5114: @item
 5115: A string of the form -<digit><digit>* is treated as a single-precision
 5116: (cell-sized) negative integer, and is represented using 2's-complement
 5117: arithmetic. Examples are -45 -5681 -0
 5118: @item
 5119: A string of the form <digit><digit>*.<digit>* is treated as a double-precision
 5120: (double-cell-sized) positive integer. Examples are 3465. 3.465 34.65
 5121: (all three of these represent the same number).
 5122: @item
 5123: A string of the form -<digit><digit>*.<digit>* is treated as a
 5124: double-precision (double-cell-sized) negative integer, and is
 5125: represented using 2's-complement arithmetic. Examples are -3465. -3.465
 5126: -34.65 (all three of these represent the same number).
 5127: @item
 5128: A string of the form @{+ -@}<decimal digit>@{.@}<decimal digit>*@{e
 5129: E@}@{+ -@}<decimal digit><decimal digit>* is treated as a floating-point
 5130: number. Examples are 1e 1e0 1.e 1.e0 +1e+0 (which all represent the same
 5131: number) +12.E-4
 5132: @end itemize
 5133: 
 5134: By default, the number base used for integer number conversion is given
 5135: by the contents of the variable @code{base}.  Note that a lot of
 5136: confusion can result from unexpected values of @code{base}.  If you
 5137: change @code{base} anywhere, make sure to save the old value and restore
 5138: it afterwards.  In general I recommend keeping @code{base} decimal, and
 5139: using the prefixes described below for the popular non-decimal bases.
 5140: 
 5141: doc-dpl
 5142: doc-base
 5143: doc-hex
 5144: doc-decimal
 5145: 
 5146: 
 5147: @cindex '-prefix for character strings
 5148: @cindex &-prefix for decimal numbers
 5149: @cindex %-prefix for binary numbers
 5150: @cindex $-prefix for hexadecimal numbers
 5151: Gforth allows you to override the value of @code{base} by using a
 5152: prefix@footnote{Some Forth implementations provide a similar scheme by
 5153: implementing @code{$} etc. as parsing words that process the subsequent
 5154: number in the input stream and push it onto the stack. For example, see
 5155: @cite{Number Conversion and Literals}, by Wil Baden; Forth Dimensions
 5156: 20(3) pages 26--27. In such implementations, unlike in Gforth, a space
 5157: is required between the prefix and the number.} before the first digit
 5158: of an (integer) number. Four prefixes are supported:
 5159: 
 5160: @itemize @bullet
 5161: @item
 5162: @code{&} -- decimal
 5163: @item
 5164: @code{%} -- binary
 5165: @item
 5166: @code{$} -- hexadecimal
 5167: @item
 5168: @code{'} -- base @code{max-char+1}
 5169: @end itemize
 5170: 
 5171: Here are some examples, with the equivalent decimal number shown after
 5172: in braces:
 5173: 
 5174: -$41 (-65), %1001101 (205), %1001.0001 (145 - a double-precision number),
 5175: 'AB (16706; ascii A is 65, ascii B is 66, number is 65*256 + 66),
 5176: 'ab (24930; ascii a is 97, ascii B is 98, number is 97*256 + 98),
 5177: &905 (905), $abc (2478), $ABC (2478).
 5178: 
 5179: @cindex number conversion - traps for the unwary
 5180: @noindent
 5181: Number conversion has a number of traps for the unwary:
 5182: 
 5183: @itemize @bullet
 5184: @item
 5185: You cannot determine the current number base using the code sequence
 5186: @code{base @@ .} -- the number base is always 10 in the current number
 5187: base. Instead, use something like @code{base @@ dec.}
 5188: @item
 5189: If the number base is set to a value greater than 14 (for example,
 5190: hexadecimal), the number 123E4 is ambiguous; the conversion rules allow
 5191: it to be intepreted as either a single-precision integer or a
 5192: floating-point number (Gforth treats it as an integer). The ambiguity
 5193: can be resolved by explicitly stating the sign of the mantissa and/or
 5194: exponent: 123E+4 or +123E4 -- if the number base is decimal, no
 5195: ambiguity arises; either representation will be treated as a
 5196: floating-point number.
 5197: @item
 5198: There is a word @code{bin} but it does @i{not} set the number base!
 5199: It is used to specify file types.
 5200: @item
 5201: ANS Forth requires the @code{.} of a double-precision number to
 5202: be the final character in the string. Allowing the @code{.} to be
 5203: anywhere after the first digit is a Gforth extension.
 5204: @item
 5205: The number conversion process does not check for overflow.
 5206: @item
 5207: In Gforth, number conversion to floating-point numbers always use base
 5208: 10, irrespective of the value of @code{base}. In ANS Forth,
 5209: conversion to floating-point numbers whilst the value of
 5210: @code{base} is not 10 is an ambiguous condition.
 5211: @end itemize
 5212: 
 5213: @ref{Input} describes words that you can use to read numbers into your
 5214: programs.
 5215: 
 5216: @node Interpret/Compile states, Literals, Number Conversion, The Text Interpreter
 5217: @subsection Interpret/Compile states
 5218: @cindex Interpret/Compile states
 5219: 
 5220: A standard program is not permitted to change @code{state}
 5221: explicitly. However, it can change @code{state} implicitly, using the
 5222: words @code{[} and @code{]}. When @code{[} is executed it switches
 5223: @code{state} to interpret state, and therefore the text interpreter
 5224: starts interpreting. When @code{]} is executed it switches @code{state}
 5225: to compile state and therefore the text interpreter starts
 5226: compiling. The most common usage for these words is for switching into
 5227: interpret state and back from within a colon definition; this technique
 5228: can be used to compile a literal (@pxref{Literals} for an example) or
 5229: for conditional compilation (@pxref{Interpreter Directives} for an
 5230: example).
 5231: 
 5232: 
 5233: @c This is a bad example: It's non-standard, and it's not necessary.
 5234: @c However, I can't think of a good example for switching into compile
 5235: @c state when there is no current word (@code{state}-smart words are not a
 5236: @c good reason).  So maybe we should use an example for switching into
 5237: @c interpret @code{state} in a colon def. - anton
 5238: @c nac-> I agree. I started out by putting in the example, then realised
 5239: @c that it was non-ANS, so wrote more words around it. I hope this
 5240: @c re-written version is acceptable to you. I do want to keep the example
 5241: @c as it is helpful for showing what is and what is not portable, particularly
 5242: @c where it outlaws a style in common use.
 5243: 
 5244: 
 5245: @code{[} and @code{]} also give you the ability to switch into compile
 5246: state and back, but we cannot think of any useful Standard application
 5247: for this ability. Pre-ANS Forth textbooks have examples like this:
 5248: 
 5249: @example
 5250: : AA ." this is A" ;
 5251: : BB ." this is B" ;
 5252: : CC ." this is C" ;
 5253: 
 5254: create table ] aa bb cc [
 5255: 
 5256: : go ( n -- ) \ n is offset into table.. 0 for 1st entry
 5257:   cells table + @ execute ;
 5258: @end example
 5259: 
 5260: This example builds a jump table; @code{0 go} will display ``@code{this
 5261: is A}''. Using @code{[} and @code{]} in this example is equivalent to
 5262: defining @code{table} like this:
 5263: 
 5264: @example
 5265: create table ' aa COMPILE, ' bb COMPILE, ' cc COMPILE,
 5266: @end example
 5267: 
 5268: The problem with this code is that the definition of @code{table} is not
 5269: portable -- it @i{compile}s execution tokens into code space. Whilst it
 5270: @i{may} work on systems where code space and data space co-incide, the
 5271: Standard only allows data space to be assigned for a @code{CREATE}d
 5272: word. In addition, the Standard only allows @code{@@} to access data
 5273: space, whilst this example is using it to access code space. The only
 5274: portable, Standard way to build this table is to build it in data space,
 5275: like this:
 5276: 
 5277: @example
 5278: create table ' aa , ' bb , ' cc ,
 5279: @end example
 5280: 
 5281: doc-state
 5282: doc-[
 5283: doc-]
 5284: 
 5285: 
 5286: @node Literals, Interpreter Directives, Interpret/Compile states, The Text Interpreter
 5287: @subsection Literals
 5288: @cindex Literals
 5289: 
 5290: Often, you want to use a number within a colon definition. When you do
 5291: this, the text interpreter automatically compiles the number as a
 5292: @i{literal}. A literal is a number whose run-time effect is to be pushed
 5293: onto the stack.  If you had to do some maths to generate the number, you
 5294: might write it like this:
 5295: 
 5296: @example
 5297: : HOUR-TO-SEC ( n1 -- n2 )
 5298:   60 *      \ to minutes
 5299:   60 * ;    \ to seconds
 5300: @end example
 5301: 
 5302: It is very clear what this definition is doing, but it's inefficient
 5303: since it is performing 2 multiples at run-time. An alternative would be
 5304: to write:
 5305: 
 5306: @example
 5307: : HOUR-TO-SEC ( n1 -- n2 )
 5308:   3600 * ;  \ to seconds
 5309: @end example
 5310: 
 5311: Which does the same thing, and has the advantage of using a single
 5312: multiply. Ideally, we'd like the efficiency of the second with the
 5313: readability of the first.
 5314: 
 5315: @code{Literal} allows us to achieve that. It takes a number from the
 5316: stack and lays it down in the current definition just as though the
 5317: number had been typed directly into the definition. Our first attempt
 5318: might look like this:
 5319: 
 5320: @example
 5321: 60          \ mins per hour
 5322: 60 *        \ seconds per minute
 5323: : HOUR-TO-SEC ( n1 -- n2 )
 5324:   Literal * ;  \ to seconds
 5325: @end example
 5326: 
 5327: But this produces the error message @code{unstructured}. What happened?
 5328: The stack notation for @code{:} is (@i{ -- colon-sys}) and the size of
 5329: @i{colon-sys} is implementation-defined. In other words, once we start a
 5330: colon definition we can't portably access anything that was on the stack
 5331: before the definition began@footnote{@cite{Two Problems in ANS Forth},
 5332: by Thomas Worthington; Forth Dimensions 20(2) pages 32--34 describes
 5333: some situations where you might want to access stack items above
 5334: colon-sys, and provides a solution to the problem.}. The correct way of
 5335: solving this problem in this instance is to use @code{[ ]} like this:
 5336: 
 5337: @example
 5338: : HOUR-TO-SEC ( n1 -- n2 )
 5339:   [ 60          \ minutes per hour
 5340:     60 * ]      \ seconds per minute
 5341:   LITERAL * ;   \ to seconds
 5342: @end example
 5343: 
 5344: 
 5345: doc-literal
 5346: doc-]L
 5347: doc-2literal
 5348: doc-fliteral
 5349: 
 5350: 
 5351: @node Interpreter Directives, , Literals, The Text Interpreter
 5352: @subsection Interpreter Directives
 5353: @cindex interpreter directives
 5354: 
 5355: These words are usually used in interpret state; typically to control
 5356: which parts of a source file are processed by the text
 5357: interpreter. There are only a few ANS Forth Standard words, but Gforth
 5358: supplements these with a rich set of immediate control structure words
 5359: to compensate for the fact that the non-immediate versions can only be
 5360: used in compile state (@pxref{Control Structures}). Typical usages:
 5361: 
 5362: @example
 5363: FALSE Constant ASSEMBLER
 5364: .
 5365: .
 5366: ASSEMBLER [IF]
 5367: : ASSEMBLER-FEATURE
 5368:   ...
 5369: ;
 5370: [ENDIF]
 5371: .
 5372: .
 5373: : SEE
 5374:   ... \ general-purpose SEE code
 5375:   [ ASSEMBLER [IF] ]
 5376:   ... \ assembler-specific SEE code
 5377:   [ [ENDIF] ]
 5378: ;
 5379: @end example
 5380: 
 5381: 
 5382: doc-[IF]
 5383: doc-[ELSE]
 5384: doc-[THEN]
 5385: doc-[ENDIF]
 5386: 
 5387: doc-[IFDEF]
 5388: doc-[IFUNDEF]
 5389: 
 5390: doc-[?DO]
 5391: doc-[DO]
 5392: doc-[FOR]
 5393: doc-[LOOP]
 5394: doc-[+LOOP]
 5395: doc-[NEXT]
 5396: 
 5397: doc-[BEGIN]
 5398: doc-[UNTIL]
 5399: doc-[AGAIN]
 5400: doc-[WHILE]
 5401: doc-[REPEAT]
 5402: 
 5403: 
 5404: @c -------------------------------------------------------------
 5405: @node Word Lists, Environmental Queries, The Text Interpreter, Words
 5406: @section Word Lists
 5407: @cindex word lists
 5408: @cindex header space
 5409: 
 5410: A wordlist is a list of named words; you can add new words and look up
 5411: words by name (and you can remove words in a restricted way with
 5412: markers).  Every named (and @code{reveal}ed) word is in one wordlist.
 5413: 
 5414: @cindex search order stack
 5415: The text interpreter searches the wordlists present in the search order
 5416: (a stack of wordlists), from the top to the bottom.  Within each
 5417: wordlist, the search starts conceptually at the newest word; i.e., if
 5418: two words in a wordlist have the same name, the newer word is found.
 5419: 
 5420: @cindex compilation word list
 5421: New words are added to the @dfn{compilation wordlist} (aka current
 5422: wordlist).
 5423: 
 5424: @cindex wid
 5425: A word list is identified by a cell-sized word list identifier (@i{wid})
 5426: in much the same way as a file is identified by a file handle. The
 5427: numerical value of the wid has no (portable) meaning, and might change
 5428: from session to session.
 5429: 
 5430: The ANS Forth ``Search order'' word set is intended to provide a set of
 5431: low-level tools that allow various different schemes to be
 5432: implemented. Gforth provides @code{vocabulary}, a traditional Forth
 5433: word.  @file{compat/vocabulary.fs} provides an implementation in ANS
 5434: Forth.
 5435: 
 5436: @comment TODO: locals section refers to here, saying that every word list (aka
 5437: @comment vocabulary) has its own methods for searching etc. Need to document that.
 5438: 
 5439: @comment TODO: document markers, reveal, tables, mappedwordlist
 5440: 
 5441: @comment the gforthman- prefix is used to pick out the true definition of a
 5442: @comment word from the source files, rather than some alias.
 5443: 
 5444: doc-forth-wordlist
 5445: doc-definitions
 5446: doc-get-current
 5447: doc-set-current
 5448: doc-get-order
 5449: doc---gforthman-set-order
 5450: doc-wordlist
 5451: doc-table
 5452: doc-push-order
 5453: doc-previous
 5454: doc-also
 5455: doc---gforthman-forth
 5456: doc-only
 5457: doc---gforthman-order
 5458: 
 5459: doc-find
 5460: doc-search-wordlist
 5461: 
 5462: doc-words
 5463: doc-vlist
 5464: @c doc-words-deferred
 5465: 
 5466: doc-mappedwordlist
 5467: doc-root
 5468: doc-vocabulary
 5469: doc-seal
 5470: doc-vocs
 5471: doc-current
 5472: doc-context
 5473: 
 5474: 
 5475: @menu
 5476: * Why use word lists?::
 5477: * Word list examples::
 5478: @end menu
 5479: 
 5480: @node Why use word lists?, Word list examples, Word Lists, Word Lists
 5481: @subsection Why use word lists?
 5482: @cindex word lists - why use them?
 5483: 
 5484: Here are some reasons for using multiple word lists:
 5485: 
 5486: @itemize @bullet
 5487: @item
 5488: To improve compilation speed by reducing the number of header space
 5489: entries that must be searched. This is achieved by creating a new
 5490: word list that contains all of the definitions that are used in the
 5491: definition of a Forth system but which would not usually be used by
 5492: programs running on that system. That word list would be on the search
 5493: list when the Forth system was compiled but would be removed from the
 5494: search list for normal operation. This can be a useful technique for
 5495: low-performance systems (for example, 8-bit processors in embedded
 5496: systems) but is unlikely to be necessary in high-performance desktop
 5497: systems.
 5498: @item
 5499: To prevent a set of words from being used outside the context in which
 5500: they are valid. Two classic examples of this are an integrated editor
 5501: (all of the edit commands are defined in a separate word list; the
 5502: search order is set to the editor word list when the editor is invoked;
 5503: the old search order is restored when the editor is terminated) and an
 5504: integrated assembler (the op-codes for the machine are defined in a
 5505: separate word list which is used when a @code{CODE} word is defined).
 5506: @item
 5507: To prevent a name-space clash between multiple definitions with the same
 5508: name. For example, when building a cross-compiler you might have a word
 5509: @code{IF} that generates conditional code for your target system. By
 5510: placing this definition in a different word list you can control whether
 5511: the host system's @code{IF} or the target system's @code{IF} get used in
 5512: any particular context by controlling the order of the word lists on the
 5513: search order stack.
 5514: @end itemize
 5515: 
 5516: @node Word list examples, ,Why use word lists?, Word Lists
 5517: @subsection Word list examples
 5518: @cindex word lists - examples
 5519: 
 5520: Here is an example of creating and using a new wordlist using ANS
 5521: Forth Standard words:
 5522: 
 5523: @example
 5524: wordlist constant my-new-words-wordlist
 5525: : my-new-words get-order nip my-new-words-wordlist swap set-order ;
 5526: 
 5527: \ add it to the search order
 5528: also my-new-words
 5529: 
 5530: \ alternatively, add it to the search order and make it
 5531: \ the compilation word list
 5532: also my-new-words definitions
 5533: \ type "order" to see the problem
 5534: @end example
 5535: 
 5536: The problem with this example is that @code{order} has no way to
 5537: associate the name @code{my-new-words} with the wid of the word list (in
 5538: Gforth, @code{order} and @code{vocs} will display @code{???}  for a wid
 5539: that has no associated name). There is no Standard way of associating a
 5540: name with a wid.
 5541: 
 5542: In Gforth, this example can be re-coded using @code{vocabulary}, which
 5543: associates a name with a wid:
 5544: 
 5545: @example
 5546: vocabulary my-new-words
 5547: 
 5548: \ add it to the search order
 5549: also my-new-words
 5550: 
 5551: \ alternatively, add it to the search order and make it
 5552: \ the compilation word list
 5553: my-new-words definitions
 5554: \ type "order" to see that the problem is solved
 5555: @end example
 5556: 
 5557: @c -------------------------------------------------------------
 5558: @node Environmental Queries, Files, Word Lists, Words
 5559: @section Environmental Queries
 5560: @cindex environmental queries
 5561: 
 5562: ANS Forth introduced the idea of ``environmental queries'' as a way
 5563: for a program running on a system to determine certain characteristics of the system.
 5564: The Standard specifies a number of strings that might be recognised by a system.
 5565: 
 5566: The Standard requires that the header space used for environmental queries
 5567: be distinct from the header space used for definitions.
 5568: 
 5569: Typically, environmental queries are supported by creating a set of
 5570: definitions in a word list that is @i{only} used during environmental
 5571: queries; that is what Gforth does. There is no Standard way of adding
 5572: definitions to the set of recognised environmental queries, but any
 5573: implementation that supports the loading of optional word sets must have
 5574: some mechanism for doing this (after loading the word set, the
 5575: associated environmental query string must return @code{true}). In
 5576: Gforth, the word list used to honour environmental queries can be
 5577: manipulated just like any other word list.
 5578: 
 5579: 
 5580: doc-environment?
 5581: doc-environment-wordlist
 5582: 
 5583: doc-gforth
 5584: doc-os-class
 5585: 
 5586: 
 5587: Note that, whilst the documentation for (e.g.) @code{gforth} shows it
 5588: returning two items on the stack, querying it using @code{environment?}
 5589: will return an additional item; the @code{true} flag that shows that the
 5590: string was recognised.
 5591: 
 5592: @comment TODO Document the standard strings or note where they are documented herein
 5593: 
 5594: Here are some examples of using environmental queries:
 5595: 
 5596: @example
 5597: s" address-unit-bits" environment? 0=
 5598: [IF]
 5599:      cr .( environmental attribute address-units-bits unknown... ) cr
 5600: [THEN]
 5601: 
 5602: s" block" environment? [IF] DROP include block.fs [THEN]
 5603: 
 5604: s" gforth" environment? [IF] 2DROP include compat/vocabulary.fs [THEN]
 5605: 
 5606: s" gforth" environment? [IF] .( Gforth version ) TYPE
 5607:                         [ELSE] .( Not Gforth..) [THEN]
 5608: @end example
 5609: 
 5610: 
 5611: Here is an example of adding a definition to the environment word list:
 5612: 
 5613: @example
 5614: get-current environment-wordlist set-current
 5615: true constant block
 5616: true constant block-ext
 5617: set-current
 5618: @end example
 5619: 
 5620: You can see what definitions are in the environment word list like this:
 5621: 
 5622: @example
 5623: get-order 1+ environment-wordlist swap set-order words previous
 5624: @end example
 5625: 
 5626: 
 5627: @c -------------------------------------------------------------
 5628: @node Files, Blocks, Environmental Queries, Words
 5629: @section Files
 5630: @cindex files
 5631: @cindex I/O - file-handling
 5632: 
 5633: Gforth provides facilities for accessing files that are stored in the
 5634: host operating system's file-system. Files that are processed by Gforth
 5635: can be divided into two categories:
 5636: 
 5637: @itemize @bullet
 5638: @item
 5639: Files that are processed by the Text Interpreter (@dfn{Forth source files}).
 5640: @item
 5641: Files that are processed by some other program (@dfn{general files}).
 5642: @end itemize
 5643: 
 5644: doc-loadfilename
 5645: doc-sourcefilename
 5646: doc-sourceline#
 5647: 
 5648: @menu
 5649: * Forth source files::
 5650: * General files::         
 5651: * Search Paths::                 
 5652: * Forth Search Paths::    
 5653: * General Search Paths::        
 5654: @end menu
 5655: 
 5656: 
 5657: @c -------------------------------------------------------------
 5658: @node Forth source files, General files, Files, Files
 5659: @subsection Forth source files
 5660: @cindex including files
 5661: @cindex Forth source files
 5662: 
 5663: The simplest way to interpret the contents of a file is to use one of
 5664: these two formats:
 5665: 
 5666: @example
 5667: include mysource.fs
 5668: s" mysource.fs" included
 5669: @end example
 5670: 
 5671: Sometimes you want to include a file only if it is not included already
 5672: (by, say, another source file). In that case, you can use one of these
 5673: three formats:
 5674: 
 5675: @example
 5676: require mysource.fs
 5677: needs mysource.fs
 5678: s" mysource.fs" required
 5679: @end example
 5680: 
 5681: @cindex stack effect of included files
 5682: @cindex including files, stack effect
 5683: It is good practice to write your source files such that interpreting them
 5684: does not change the stack. Source files designed in this way can be used with
 5685: @code{required} and friends without complications. For example:
 5686: 
 5687: @example
 5688: 1 require foo.fs drop
 5689: @end example
 5690: 
 5691: 
 5692: doc-include-file
 5693: doc-included
 5694: doc-included?
 5695: doc-include
 5696: doc-required
 5697: doc-require
 5698: doc-needs
 5699: doc-init-included-files
 5700: 
 5701: 
 5702: A definition in ANS Forth for @code{required} is provided in
 5703: @file{compat/required.fs}.
 5704: 
 5705: @c -------------------------------------------------------------
 5706: @node General files, Search Paths, Forth source files, Files
 5707: @subsection General files
 5708: @cindex general files
 5709: @cindex file-handling
 5710: 
 5711: Files are opened/created by name and type. The following types are
 5712: recognised:
 5713: 
 5714: 
 5715: doc-r/o
 5716: doc-r/w
 5717: doc-w/o
 5718: doc-bin
 5719: 
 5720: 
 5721: When a file is opened/created, it returns a file identifier,
 5722: @i{wfileid} that is used for all other file commands. All file
 5723: commands also return a status value, @i{wior}, that is 0 for a
 5724: successful operation and an implementation-defined non-zero value in the
 5725: case of an error.
 5726: 
 5727: 
 5728: doc-open-file
 5729: doc-create-file
 5730: 
 5731: doc-close-file
 5732: doc-delete-file
 5733: doc-rename-file
 5734: doc-read-file
 5735: doc-read-line
 5736: doc-write-file
 5737: doc-write-line
 5738: doc-emit-file
 5739: doc-flush-file
 5740: 
 5741: doc-file-status
 5742: doc-file-position
 5743: doc-reposition-file
 5744: doc-file-size
 5745: doc-resize-file
 5746: 
 5747: 
 5748: @c ---------------------------------------------------------
 5749: @node Search Paths, Forth Search Paths, General files, Files
 5750: @subsection Search Paths
 5751: @cindex path for @code{included}
 5752: @cindex file search path
 5753: @cindex @code{include} search path
 5754: @cindex search path for files
 5755: 
 5756: If you specify an absolute filename (i.e., a filename starting with
 5757: @file{/} or @file{~}, or with @file{:} in the second position (as in
 5758: @samp{C:...})) for @code{included} and friends, that file is included
 5759: just as you would expect.
 5760: 
 5761: For relative filenames, Gforth uses a search path similar to Forth's
 5762: search order (@pxref{Word Lists}). It tries to find the given filename
 5763: in the directories present in the path, and includes the first one it
 5764: finds. There are separate search paths for Forth source files and
 5765: general files.
 5766: 
 5767: If the search path contains the directory @file{.} (as it should), this
 5768: refers to the directory that the present file was @code{included}
 5769: from. This allows files to include other files relative to their own
 5770: position (irrespective of the current working directory or the absolute
 5771: position).  This feature is essential for libraries consisting of
 5772: several files, where a file may include other files from the library.
 5773: It corresponds to @code{#include "..."} in C. If the current input
 5774: source is not a file, @file{.} refers to the directory of the innermost
 5775: file being included, or, if there is no file being included, to the
 5776: current working directory.
 5777: 
 5778: Use @file{~+} to refer to the current working directory (as in the
 5779: @code{bash}).
 5780: 
 5781: If the filename starts with @file{./}, the search path is not searched
 5782: (just as with absolute filenames), and the @file{.} has the same meaning
 5783: as described above.
 5784: 
 5785: @c ---------------------------------------------------------
 5786: @node Forth Search Paths, General Search Paths, Search Paths, Files
 5787: @subsubsection Forth Search Paths
 5788: @cindex search path control - Forth
 5789: 
 5790: The search path is initialized when you start Gforth (@pxref{Invoking
 5791: Gforth}). You can display it and change it using these words:
 5792: 
 5793: 
 5794: doc-.fpath
 5795: doc-fpath+
 5796: doc-fpath=
 5797: doc-open-fpath-file
 5798: 
 5799: 
 5800: @noindent
 5801: Here is an example of using @code{fpath} and @code{require}:
 5802: 
 5803: @example
 5804: fpath= /usr/lib/forth/|./
 5805: require timer.fs
 5806: @end example
 5807: 
 5808: @c ---------------------------------------------------------
 5809: @node General Search Paths,  , Forth Search Paths, Files
 5810: @subsubsection General Search Paths
 5811: @cindex search path control - for user applications
 5812: 
 5813: Your application may need to search files in several directories, like
 5814: @code{included} does. To facilitate this, Gforth allows you to define
 5815: and use your own search paths, by providing generic equivalents of the
 5816: Forth search path words:
 5817: 
 5818: 
 5819: doc-.path
 5820: doc-path+
 5821: doc-path=
 5822: doc-open-path-file
 5823: 
 5824: 
 5825: Here's an example of creating a search path:
 5826: 
 5827: @example
 5828: \ Make a buffer for the path:
 5829: create mypath   100 chars ,     \ maximum length (is checked)
 5830:                 0 ,             \ real len
 5831:                 100 chars allot \ space for path
 5832: @end example
 5833: 
 5834: @c -------------------------------------------------------------
 5835: @node Blocks, Other I/O, Files, Words
 5836: @section Blocks
 5837: @cindex I/O - blocks
 5838: @cindex blocks
 5839: 
 5840: When you run Gforth on a modern desk-top computer, it runs under the
 5841: control of an operating system which provides certain services.  One of
 5842: these services is @var{file services}, which allows Forth source code
 5843: and data to be stored in files and read into Gforth (@pxref{Files}).
 5844: 
 5845: Traditionally, Forth has been an important programming language on
 5846: systems where it has interfaced directly to the underlying hardware with
 5847: no intervening operating system. Forth provides a mechanism, called
 5848: @dfn{blocks}, for accessing mass storage on such systems.
 5849: 
 5850: A block is a 1024-byte data area, which can be used to hold data or
 5851: Forth source code. No structure is imposed on the contents of the
 5852: block. A block is identified by its number; blocks are numbered
 5853: contiguously from 1 to an implementation-defined maximum.
 5854: 
 5855: A typical system that used blocks but no operating system might use a
 5856: single floppy-disk drive for mass storage, with the disks formatted to
 5857: provide 256-byte sectors. Blocks would be implemented by assigning the
 5858: first four sectors of the disk to block 1, the second four sectors to
 5859: block 2 and so on, up to the limit of the capacity of the disk. The disk
 5860: would not contain any file system information, just the set of blocks.
 5861: 
 5862: @cindex blocks file
 5863: On systems that do provide file services, blocks are typically
 5864: implemented by storing a sequence of blocks within a single @dfn{blocks
 5865: file}.  The size of the blocks file will be an exact multiple of 1024
 5866: bytes, corresponding to the number of blocks it contains. This is the
 5867: mechanism that Gforth uses.
 5868: 
 5869: @cindex @file{blocks.fb}
 5870: Only 1 blocks file can be open at a time. If you use block words without
 5871: having specified a blocks file, Gforth defaults to the blocks file
 5872: @file{blocks.fb}. Gforth uses the Forth search path when attempting to
 5873: locate a blocks file (@pxref{Forth Search Paths}).
 5874: 
 5875: @cindex block buffers
 5876: When you read and write blocks under program control, Gforth uses a
 5877: number of @dfn{block buffers} as intermediate storage. These buffers are
 5878: not used when you use @code{load} to interpret the contents of a block.
 5879: 
 5880: The behaviour of the block buffers is directly analagous to that of a
 5881: cache. Each block buffer has three states:
 5882: 
 5883: @itemize @bullet
 5884: @item
 5885: Unassigned
 5886: @item
 5887: Assigned-clean
 5888: @item
 5889: Assigned-dirty
 5890: @end itemize
 5891: 
 5892: Initially, all block buffers are @i{unassigned}. In order to access a
 5893: block, the block (specified by its block number) must be assigned to a
 5894: block buffer.
 5895: 
 5896: The assignment of a block to a block buffer is performed by @code{block}
 5897: or @code{buffer}. Use @code{block} when you wish to modify the existing
 5898: contents of a block. Use @code{buffer} when you don't care about the
 5899: existing contents of the block@footnote{The ANS Forth definition of
 5900: @code{buffer} is intended not to cause disk I/O; if the data associated
 5901: with the particular block is already stored in a block buffer due to an
 5902: earlier @code{block} command, @code{buffer} will return that block
 5903: buffer and the existing contents of the block will be
 5904: available. Otherwise, @code{buffer} will simply assign a new, empty
 5905: block buffer for the block.}.
 5906: 
 5907: Once a block has been assigned to a block buffer using @code{block} or
 5908: @code{buffer}, that block buffer becomes the @i{current block buffer}
 5909: and its state changes to @i{assigned-clean}. Data may only be
 5910: manipulated (read or written) within the current block buffer.
 5911: 
 5912: When the contents of the current block buffer has been modified it is
 5913: necessary, @i{before calling} @code{block} @i{or} @code{buffer}
 5914: @i{again}, to either abandon the changes (by doing nothing) or commit
 5915: the changes, using @code{update}. Using @code{update} does not change
 5916: the blocks file; it simply changes a block buffer's state to
 5917: @i{assigned-dirty}.
 5918: 
 5919: The word @code{flush} causes all @i{assigned-dirty} blocks to be
 5920: written back to the blocks file on disk. Leaving Gforth using @code{bye}
 5921: also causes a @code{flush} to be performed.
 5922: 
 5923: In Gforth, @code{block} and @code{buffer} use a @i{direct-mapped}
 5924: algorithm to assign a block buffer to a block. That means that any
 5925: particular block can only be assigned to one specific block buffer,
 5926: called (for the particular operation) the @i{victim buffer}. If the
 5927: victim buffer is @i{unassigned} or @i{assigned-clean} it is allocated to
 5928: the new block immediately. If it is @i{assigned-dirty} its current
 5929: contents are written back to the blocks file on disk before it is
 5930: allocated to the new block.
 5931: 
 5932: Although no structure is imposed on the contents of a block, it is
 5933: traditional to display the contents as 16 lines each of 64 characters.  A
 5934: block provides a single, continuous stream of input (for example, it
 5935: acts as a single parse area) -- there are no end-of-line characters
 5936: within a block, and no end-of-file character at the end of a
 5937: block. There are two consequences of this:
 5938: 
 5939: @itemize @bullet
 5940: @item
 5941: The last character of one line wraps straight into the first character
 5942: of the following line
 5943: @item
 5944: The word @code{\} -- comment to end of line -- requires special
 5945: treatment; in the context of a block it causes all characters until the
 5946: end of the current 64-character ``line'' to be ignored.
 5947: @end itemize
 5948: 
 5949: In Gforth, when you use @code{block} with a non-existent block number,
 5950: the current blocks file will be extended to the appropriate size and the
 5951: block buffer will be initialised with spaces.
 5952: 
 5953: Gforth includes a simple block editor (type @code{use blocked.fb 0 list}
 5954: for details) but doesn't encourage the use of blocks; the mechanism is
 5955: only provided for backward compatibility -- ANS Forth requires blocks to
 5956: be available when files are.
 5957: 
 5958: Common techniques that are used when working with blocks include:
 5959: 
 5960: @itemize @bullet
 5961: @item
 5962: A screen editor that allows you to edit blocks without leaving the Forth
 5963: environment.
 5964: @item
 5965: Shadow screens; where every code block has an associated block
 5966: containing comments (for example: code in odd block numbers, comments in
 5967: even block numbers). Typically, the block editor provides a convenient
 5968: mechanism to toggle between code and comments.
 5969: @item
 5970: Load blocks; a single block (typically block 1) contains a number of
 5971: @code{thru} commands which @code{load} the whole of the application.
 5972: @end itemize
 5973: 
 5974: See Frank Sergeant's Pygmy Forth to see just how well blocks can be
 5975: integrated into a Forth programming environment.
 5976: 
 5977: @comment TODO what about errors on open-blocks?
 5978: 
 5979: doc-open-blocks
 5980: doc-use
 5981: doc-get-block-fid
 5982: doc-block-position
 5983: 
 5984: doc-scr
 5985: doc-list
 5986: 
 5987: doc---gforthman-block
 5988: doc-buffer
 5989: 
 5990: doc-update
 5991: doc-updated?
 5992: doc-save-buffers
 5993: doc-empty-buffers
 5994: doc-empty-buffer
 5995: doc-flush
 5996: 
 5997: doc-load
 5998: doc-thru
 5999: doc-+load
 6000: doc-+thru
 6001: doc---gforthman--->
 6002: doc-block-included
 6003: 
 6004: 
 6005: @c -------------------------------------------------------------
 6006: @node Other I/O, Programming Tools, Blocks, Words
 6007: @section Other I/O
 6008: @cindex I/O - keyboard and display
 6009: 
 6010: @menu
 6011: * Simple numeric output::       Predefined formats
 6012: * Formatted numeric output::    Formatted (pictured) output
 6013: * String Formats::              How Forth stores strings in memory
 6014: * Displaying characters and strings:: Other stuff
 6015: * Input::                       Input
 6016: @end menu
 6017: 
 6018: @node Simple numeric output, Formatted numeric output, Other I/O, Other I/O
 6019: @subsection Simple numeric output
 6020: @cindex numeric output - simple/free-format
 6021: 
 6022: The simplest output functions are those that display numbers from the
 6023: data or floating-point stacks. Floating-point output is always displayed
 6024: using base 10. Numbers displayed from the data stack use the value stored
 6025: in @code{base}.
 6026: 
 6027: 
 6028: doc-.
 6029: doc-dec.
 6030: doc-hex.
 6031: doc-u.
 6032: doc-.r
 6033: doc-u.r
 6034: doc-d.
 6035: doc-ud.
 6036: doc-d.r
 6037: doc-ud.r
 6038: doc-f.
 6039: doc-fe.
 6040: doc-fs.
 6041: 
 6042: 
 6043: Examples of printing the number 1234.5678E23 in the different floating-point output
 6044: formats are shown below:
 6045: 
 6046: @example
 6047: f. 123456779999999000000000000.
 6048: fe. 123.456779999999E24
 6049: fs. 1.23456779999999E26
 6050: @end example
 6051: 
 6052: 
 6053: @node Formatted numeric output, String Formats, Simple numeric output, Other I/O
 6054: @subsection Formatted numeric output
 6055: @cindex formatted numeric output
 6056: @cindex pictured numeric output
 6057: @cindex numeric output - formatted
 6058: 
 6059: Forth traditionally uses a technique called @dfn{pictured numeric
 6060: output} for formatted printing of integers.  In this technique, digits
 6061: are extracted from the number (using the current output radix defined by
 6062: @code{base}), converted to ASCII codes and appended to a string that is
 6063: built in a scratch-pad area of memory (@pxref{core-idef,
 6064: Implementation-defined options, Implementation-defined
 6065: options}). Arbitrary characters can be appended to the string during the
 6066: extraction process. The completed string is specified by an address
 6067: and length and can be manipulated (@code{TYPE}ed, copied, modified)
 6068: under program control.
 6069: 
 6070: All of the words described in the previous section for simple numeric
 6071: output are implemented in Gforth using pictured numeric output.
 6072: 
 6073: Three important things to remember about pictured numeric output:
 6074: 
 6075: @itemize @bullet
 6076: @item
 6077: It always operates on double-precision numbers; to display a
 6078: single-precision number, convert it first (@pxref{Double precision} for
 6079: ways of doing this).
 6080: @item
 6081: It always treats the double-precision number as though it were
 6082: unsigned. The examples below show ways of printing signed numbers.
 6083: @item
 6084: The string is built up from right to left; least significant digit first.
 6085: @end itemize
 6086: 
 6087: 
 6088: doc-<#
 6089: doc-<<#
 6090: doc-#
 6091: doc-#s
 6092: doc-hold
 6093: doc-sign
 6094: doc-#>
 6095: doc-#>>
 6096: 
 6097: doc-represent
 6098: 
 6099: 
 6100: @noindent
 6101: Here are some examples of using pictured numeric output:
 6102: 
 6103: @example
 6104: : my-u. ( u -- )
 6105:   \ Simplest use of pns.. behaves like Standard u. 
 6106:   0              \ convert to unsigned double
 6107:   <#             \ start conversion
 6108:   #s             \ convert all digits
 6109:   #>             \ complete conversion
 6110:   TYPE SPACE ;   \ display, with trailing space
 6111: 
 6112: : cents-only ( u -- )
 6113:   0              \ convert to unsigned double
 6114:   <#             \ start conversion
 6115:   # #            \ convert two least-significant digits
 6116:   #>             \ complete conversion, discard other digits
 6117:   TYPE SPACE ;   \ display, with trailing space
 6118: 
 6119: : dollars-and-cents ( u -- )
 6120:   0              \ convert to unsigned double
 6121:   <#             \ start conversion
 6122:   # #            \ convert two least-significant digits
 6123:   [char] . hold  \ insert decimal point
 6124:   #s             \ convert remaining digits
 6125:   [char] $ hold  \ append currency symbol
 6126:   #>             \ complete conversion
 6127:   TYPE SPACE ;   \ display, with trailing space
 6128: 
 6129: : my-. ( n -- )
 6130:   \ handling negatives.. behaves like Standard .
 6131:   s>d            \ convert to signed double
 6132:   swap over dabs \ leave sign byte followed by unsigned double
 6133:   <#             \ start conversion
 6134:   #s             \ convert all digits
 6135:   rot sign       \ get at sign byte, append "-" if needed
 6136:   #>             \ complete conversion
 6137:   TYPE SPACE ;   \ display, with trailing space
 6138: 
 6139: : account. ( n -- )
 6140:   \ accountants don't like minus signs, they use braces
 6141:   \ for negative numbers
 6142:   s>d            \ convert to signed double
 6143:   swap over dabs \ leave sign byte followed by unsigned double
 6144:   <#             \ start conversion
 6145:   2 pick         \ get copy of sign byte
 6146:   0< IF [char] ) hold THEN \ right-most character of output
 6147:   #s             \ convert all digits
 6148:   rot            \ get at sign byte
 6149:   0< IF [char] ( hold THEN
 6150:   #>             \ complete conversion
 6151:   TYPE SPACE ;   \ display, with trailing space
 6152: @end example
 6153: 
 6154: Here are some examples of using these words:
 6155: 
 6156: @example
 6157: 1 my-u. 1
 6158: hex -1 my-u. decimal FFFFFFFF
 6159: 1 cents-only 01
 6160: 1234 cents-only 34
 6161: 2 dollars-and-cents $0.02
 6162: 1234 dollars-and-cents $12.34
 6163: 123 my-. 123
 6164: -123 my. -123
 6165: 123 account. 123
 6166: -456 account. (456)
 6167: @end example
 6168: 
 6169: 
 6170: @node String Formats, Displaying characters and strings, Formatted numeric output, Other I/O
 6171: @subsection String Formats
 6172: @cindex strings - see character strings
 6173: @cindex character strings - formats
 6174: @cindex I/O - see character strings
 6175: 
 6176: Forth commonly uses two different methods for representing character
 6177: strings:
 6178: 
 6179: @itemize @bullet
 6180: @item
 6181: @cindex address of counted string
 6182: @cindex counted string
 6183: As a @dfn{counted string}, represented by a @i{c-addr}. The char
 6184: addressed by @i{c-addr} contains a character-count, @i{n}, of the
 6185: string and the string occupies the subsequent @i{n} char addresses in
 6186: memory.
 6187: @item
 6188: As cell pair on the stack; @i{c-addr u}, where @i{u} is the length
 6189: of the string in characters, and @i{c-addr} is the address of the
 6190: first byte of the string.
 6191: @end itemize
 6192: 
 6193: ANS Forth encourages the use of the second format when representing
 6194: strings on the stack, whilst conceeding that the counted string format
 6195: remains useful as a way of storing strings in memory.
 6196: 
 6197: 
 6198: doc-count
 6199: 
 6200: 
 6201: @xref{Memory Blocks} for words that move, copy and search
 6202: for strings. @xref{Displaying characters and strings,} for words that
 6203: display characters and strings.
 6204: 
 6205: 
 6206: @node Displaying characters and strings, Input, String Formats, Other I/O
 6207: @subsection Displaying characters and strings
 6208: @cindex characters - compiling and displaying
 6209: @cindex character strings - compiling and displaying
 6210: 
 6211: This section starts with a glossary of Forth words and ends with a set
 6212: of examples.
 6213: 
 6214: 
 6215: doc-bl
 6216: doc-space
 6217: doc-spaces
 6218: doc-emit
 6219: doc-toupper
 6220: doc-."
 6221: doc-.(
 6222: doc-type
 6223: doc-typewhite
 6224: doc-cr
 6225: @cindex cursor control
 6226: doc-at-xy
 6227: doc-page
 6228: doc-s"
 6229: doc-c"
 6230: doc-char
 6231: doc-[char]
 6232: doc-sliteral
 6233: 
 6234: 
 6235: @noindent
 6236: As an example, consider the following text, stored in a file @file{test.fs}:
 6237: 
 6238: @example
 6239: .( text-1)
 6240: : my-word
 6241:   ." text-2" cr
 6242:   .( text-3)
 6243: ;
 6244: 
 6245: ." text-4"
 6246: 
 6247: : my-char
 6248:   [char] ALPHABET emit
 6249:   char emit
 6250: ;
 6251: @end example
 6252: 
 6253: When you load this code into Gforth, the following output is generated:
 6254: 
 6255: @example
 6256: @kbd{include test.fs @key{RET}} text-1text-3text-4 ok
 6257: @end example
 6258: 
 6259: @itemize @bullet
 6260: @item
 6261: Messages @code{text-1} and @code{text-3} are displayed because @code{.(} 
 6262: is an immediate word; it behaves in the same way whether it is used inside
 6263: or outside a colon definition.
 6264: @item
 6265: Message @code{text-4} is displayed because of Gforth's added interpretation
 6266: semantics for @code{."}.
 6267: @item
 6268: Message @code{text-2} is @i{not} displayed, because the text interpreter
 6269: performs the compilation semantics for @code{."} within the definition of
 6270: @code{my-word}.
 6271: @end itemize
 6272: 
 6273: Here are some examples of executing @code{my-word} and @code{my-char}:
 6274: 
 6275: @example
 6276: @kbd{my-word @key{RET}} text-2
 6277:  ok
 6278: @kbd{my-char fred @key{RET}} Af ok
 6279: @kbd{my-char jim @key{RET}} Aj ok
 6280: @end example
 6281: 
 6282: @itemize @bullet
 6283: @item
 6284: Message @code{text-2} is displayed because of the run-time behaviour of
 6285: @code{."}.
 6286: @item
 6287: @code{[char]} compiles the ``A'' from ``ALPHABET'' and puts its display code
 6288: on the stack at run-time. @code{emit} always displays the character
 6289: when @code{my-char} is executed.
 6290: @item
 6291: @code{char} parses a string at run-time and the second @code{emit} displays
 6292: the first character of the string.
 6293: @item
 6294: If you type @code{see my-char} you can see that @code{[char]} discarded
 6295: the text ``LPHABET'' and only compiled the display code for ``A'' into the
 6296: definition of @code{my-char}.
 6297: @end itemize
 6298: 
 6299: 
 6300: 
 6301: @node Input, , Displaying characters and strings, Other I/O
 6302: @subsection Input
 6303: @cindex input
 6304: @cindex I/O - see input
 6305: @cindex parsing a string
 6306: 
 6307: @xref{String Formats} for ways of storing character strings in memory.
 6308: 
 6309: @comment TODO examples for >number >float accept key key? pad parse word refill
 6310: @comment then index them
 6311: 
 6312: 
 6313: doc-key
 6314: doc-key?
 6315: doc-ekey
 6316: doc-ekey?
 6317: doc-ekey>char
 6318: doc->number
 6319: doc->float
 6320: doc-accept
 6321: doc-pad
 6322: doc-parse
 6323: doc-word
 6324: doc-sword
 6325: doc-(name)
 6326: doc-refill
 6327: @comment obsolescent words..
 6328: doc-convert
 6329: doc-query
 6330: doc-expect
 6331: doc-span
 6332: 
 6333: 
 6334: 
 6335: @c -------------------------------------------------------------
 6336: @node Programming Tools, Assembler and Code Words, Other I/O, Words
 6337: @section Programming Tools
 6338: @cindex programming tools
 6339: 
 6340: @menu
 6341: * Debugging::                   Simple and quick.
 6342: * Assertions::                  Making your programs self-checking.
 6343: * Singlestep Debugger::         Executing your program word by word.
 6344: @end menu
 6345: 
 6346: @node Debugging, Assertions, Programming Tools, Programming Tools
 6347: @subsection Debugging
 6348: @cindex debugging
 6349: 
 6350: Languages with a slow edit/compile/link/test development loop tend to
 6351: require sophisticated tracing/stepping debuggers to facilate
 6352: productive debugging.
 6353: 
 6354: A much better (faster) way in fast-compiling languages is to add
 6355: printing code at well-selected places, let the program run, look at
 6356: the output, see where things went wrong, add more printing code, etc.,
 6357: until the bug is found.
 6358: 
 6359: The simple debugging aids provided in @file{debugs.fs}
 6360: are meant to support this style of debugging. In addition, there are
 6361: words for non-destructively inspecting the stack and memory:
 6362: 
 6363: 
 6364: doc-.s
 6365: doc-f.s
 6366: 
 6367: 
 6368: There is a word @code{.r} but it does @i{not} display the return
 6369: stack! It is used for formatted numeric output.
 6370: 
 6371: 
 6372: doc-depth
 6373: doc-fdepth
 6374: doc-clearstack
 6375: doc-?
 6376: doc-dump
 6377: 
 6378: 
 6379: The word @code{~~} prints debugging information (by default the source
 6380: location and the stack contents). It is easy to insert. If you use Emacs
 6381: it is also easy to remove (@kbd{C-x ~} in the Emacs Forth mode to
 6382: query-replace them with nothing). The deferred words
 6383: @code{printdebugdata} and @code{printdebugline} control the output of
 6384: @code{~~}. The default source location output format works well with
 6385: Emacs' compilation mode, so you can step through the program at the
 6386: source level using @kbd{C-x `} (the advantage over a stepping debugger
 6387: is that you can step in any direction and you know where the crash has
 6388: happened or where the strange data has occurred).
 6389: 
 6390: The default actions of @code{~~} clobber the contents of the pictured
 6391: numeric output string, so you should not use @code{~~}, e.g., between
 6392: @code{<#} and @code{#>}.
 6393: 
 6394: 
 6395: doc-~~
 6396: doc-printdebugdata
 6397: doc-printdebugline
 6398: 
 6399: doc-see
 6400: doc-marker
 6401: 
 6402: 
 6403: Here's an example of using @code{marker} at the start of a source file
 6404: that you are debugging; it ensures that you only ever have one copy of
 6405: the file's definitions compiled at any time:
 6406: 
 6407: @example
 6408: [IFDEF] my-code
 6409:     my-code
 6410: [ENDIF]
 6411: 
 6412: marker my-code
 6413: init-included-files
 6414: 
 6415: \ .. definitions start here
 6416: \ .
 6417: \ .
 6418: \ end
 6419: @end example
 6420: 
 6421: 
 6422: 
 6423: @node Assertions, Singlestep Debugger, Debugging, Programming Tools
 6424: @subsection Assertions
 6425: @cindex assertions
 6426: 
 6427: It is a good idea to make your programs self-checking, especially if you
 6428: make an assumption that may become invalid during maintenance (for
 6429: example, that a certain field of a data structure is never zero). Gforth
 6430: supports @dfn{assertions} for this purpose. They are used like this:
 6431: 
 6432: @example
 6433: assert( @i{flag} )
 6434: @end example
 6435: 
 6436: The code between @code{assert(} and @code{)} should compute a flag, that
 6437: should be true if everything is alright and false otherwise. It should
 6438: not change anything else on the stack. The overall stack effect of the
 6439: assertion is @code{( -- )}. E.g.
 6440: 
 6441: @example
 6442: assert( 1 1 + 2 = ) \ what we learn in school
 6443: assert( dup 0<> ) \ assert that the top of stack is not zero
 6444: assert( false ) \ this code should not be reached
 6445: @end example
 6446: 
 6447: The need for assertions is different at different times. During
 6448: debugging, we want more checking, in production we sometimes care more
 6449: for speed. Therefore, assertions can be turned off, i.e., the assertion
 6450: becomes a comment. Depending on the importance of an assertion and the
 6451: time it takes to check it, you may want to turn off some assertions and
 6452: keep others turned on. Gforth provides several levels of assertions for
 6453: this purpose:
 6454: 
 6455: 
 6456: doc-assert0(
 6457: doc-assert1(
 6458: doc-assert2(
 6459: doc-assert3(
 6460: doc-assert(
 6461: doc-)
 6462: 
 6463: 
 6464: The variable @code{assert-level} specifies the highest assertions that
 6465: are turned on. I.e., at the default @code{assert-level} of one,
 6466: @code{assert0(} and @code{assert1(} assertions perform checking, while
 6467: @code{assert2(} and @code{assert3(} assertions are treated as comments.
 6468: 
 6469: The value of @code{assert-level} is evaluated at compile-time, not at
 6470: run-time. Therefore you cannot turn assertions on or off at run-time;
 6471: you have to set the @code{assert-level} appropriately before compiling a
 6472: piece of code. You can compile different pieces of code at different
 6473: @code{assert-level}s (e.g., a trusted library at level 1 and
 6474: newly-written code at level 3).
 6475: 
 6476: 
 6477: doc-assert-level
 6478: 
 6479: 
 6480: If an assertion fails, a message compatible with Emacs' compilation mode
 6481: is produced and the execution is aborted (currently with @code{ABORT"}.
 6482: If there is interest, we will introduce a special throw code. But if you
 6483: intend to @code{catch} a specific condition, using @code{throw} is
 6484: probably more appropriate than an assertion).
 6485: 
 6486: Definitions in ANS Forth for these assertion words are provided
 6487: in @file{compat/assert.fs}.
 6488: 
 6489: 
 6490: @node Singlestep Debugger, , Assertions, Programming Tools
 6491: @subsection Singlestep Debugger
 6492: @cindex singlestep Debugger
 6493: @cindex debugging Singlestep
 6494: 
 6495: When you create a new word there's often the need to check whether it
 6496: behaves correctly or not. You can do this by typing @code{dbg
 6497: badword}. A debug session might look like this:
 6498: 
 6499: @example
 6500: : badword 0 DO i . LOOP ;  ok
 6501: 2 dbg badword 
 6502: : badword  
 6503: Scanning code...
 6504: 
 6505: Nesting debugger ready!
 6506: 
 6507: 400D4738  8049BC4 0              -> [ 2 ] 00002 00000 
 6508: 400D4740  8049F68 DO             -> [ 0 ] 
 6509: 400D4744  804A0C8 i              -> [ 1 ] 00000 
 6510: 400D4748 400C5E60 .              -> 0 [ 0 ] 
 6511: 400D474C  8049D0C LOOP           -> [ 0 ] 
 6512: 400D4744  804A0C8 i              -> [ 1 ] 00001 
 6513: 400D4748 400C5E60 .              -> 1 [ 0 ] 
 6514: 400D474C  8049D0C LOOP           -> [ 0 ] 
 6515: 400D4758  804B384 ;              ->  ok
 6516: @end example
 6517: 
 6518: Each line displayed is one step. You always have to hit return to
 6519: execute the next word that is displayed. If you don't want to execute
 6520: the next word in a whole, you have to type @kbd{n} for @code{nest}. Here is
 6521: an overview what keys are available:
 6522: 
 6523: @table @i
 6524: 
 6525: @item @key{RET}
 6526: Next; Execute the next word.
 6527: 
 6528: @item n
 6529: Nest; Single step through next word.
 6530: 
 6531: @item u
 6532: Unnest; Stop debugging and execute rest of word. If we got to this word
 6533: with nest, continue debugging with the calling word.
 6534: 
 6535: @item d
 6536: Done; Stop debugging and execute rest.
 6537: 
 6538: @item s
 6539: Stop; Abort immediately.
 6540: 
 6541: @end table
 6542: 
 6543: Debugging large application with this mechanism is very difficult, because
 6544: you have to nest very deeply into the program before the interesting part
 6545: begins. This takes a lot of time. 
 6546: 
 6547: To do it more directly put a @code{BREAK:} command into your source code.
 6548: When program execution reaches @code{BREAK:} the single step debugger is
 6549: invoked and you have all the features described above.
 6550: 
 6551: If you have more than one part to debug it is useful to know where the
 6552: program has stopped at the moment. You can do this by the 
 6553: @code{BREAK" string"} command. This behaves like @code{BREAK:} except that
 6554: string is typed out when the ``breakpoint'' is reached.
 6555: 
 6556: 
 6557: doc-dbg
 6558: doc-break:
 6559: doc-break"
 6560: 
 6561: 
 6562: 
 6563: @c -------------------------------------------------------------
 6564: @node Assembler and Code Words, Threading Words, Programming Tools, Words
 6565: @section Assembler and Code Words
 6566: @cindex assembler
 6567: @cindex code words
 6568: 
 6569: Gforth provides some words for defining primitives (words written in
 6570: machine code), and for defining the machine-code equivalent of
 6571: @code{DOES>}-based defining words. However, the machine-independent
 6572: nature of Gforth poses a few problems: First of all, Gforth runs on
 6573: several architectures, so it can provide no standard assembler. What's
 6574: worse is that the register allocation not only depends on the processor,
 6575: but also on the @code{gcc} version and options used.
 6576: 
 6577: The words that Gforth offers encapsulate some system dependences (e.g.,
 6578: the header structure), so a system-independent assembler may be used in
 6579: Gforth. If you do not have an assembler, you can compile machine code
 6580: directly with @code{,} and @code{c,}@footnote{This isn't portable,
 6581: because these words emit stuff in @i{data} space; it works because
 6582: Gforth has unified code/data spaces. Assembler isn't likely to be
 6583: portable anyway.}.
 6584: 
 6585: 
 6586: doc-assembler
 6587: doc-init-asm
 6588: doc-code
 6589: doc-end-code
 6590: doc-;code
 6591: doc-flush-icache
 6592: 
 6593: 
 6594: If @code{flush-icache} does not work correctly, @code{code} words
 6595: etc. will not work (reliably), either.
 6596: 
 6597: The typical usage of these @code{code} words can be shown most easily by
 6598: analogy to the equivalent high-level defining words:
 6599: 
 6600: @example
 6601: : foo                                        code foo
 6602:    <high-level Forth words>                        <assembler>
 6603: ;                                            end-code
 6604: 
 6605: : bar                                        : bar
 6606:    <high-level Forth words>                     <high-level Forth words>
 6607:    CREATE                                       CREATE
 6608:       <high-level Forth words>                     <high-level Forth words>
 6609:    DOES>                                        ;code
 6610:       <high-level Forth words>                     <assembler>
 6611: ;                                            end-code
 6612: @end example
 6613: 
 6614: @code{flush-icache} is always present. The other words are rarely used
 6615: and reside in @code{code.fs}, which is usually not loaded. You can load
 6616: it with @code{require code.fs}.
 6617: 
 6618: @cindex registers of the inner interpreter
 6619: In the assembly code you will want to refer to the inner interpreter's
 6620: registers (e.g., the data stack pointer) and you may want to use other
 6621: registers for temporary storage. Unfortunately, the register allocation
 6622: is installation-dependent.
 6623: 
 6624: The easiest solution is to use explicit register declarations
 6625: (@pxref{Explicit Reg Vars, , Variables in Specified Registers, gcc.info,
 6626: GNU C Manual}) for all of the inner interpreter's registers: You have to
 6627: compile Gforth with @code{-DFORCE_REG} (configure option
 6628: @code{--enable-force-reg}) and the appropriate declarations must be
 6629: present in the @code{machine.h} file (see @code{mips.h} for an example;
 6630: you can find a full list of all declarable register symbols with
 6631: @code{grep register engine.c}). If you give explicit registers to all
 6632: variables that are declared at the beginning of @code{engine()}, you
 6633: should be able to use the other caller-saved registers for temporary
 6634: storage. Alternatively, you can use the @code{gcc} option
 6635: @code{-ffixed-REG} (@pxref{Code Gen Options, , Options for Code
 6636: Generation Conventions, gcc.info, GNU C Manual}) to reserve a register
 6637: (however, this restriction on register allocation may slow Gforth
 6638: significantly).
 6639: 
 6640: If this solution is not viable (e.g., because @code{gcc} does not allow
 6641: you to explicitly declare all the registers you need), you have to find
 6642: out by looking at the code where the inner interpreter's registers
 6643: reside and which registers can be used for temporary storage. You can
 6644: get an assembly listing of the engine's code with @code{make engine.s}.
 6645: 
 6646: In any case, it is good practice to abstract your assembly code from the
 6647: actual register allocation. E.g., if the data stack pointer resides in
 6648: register @code{$17}, create an alias for this register called @code{sp},
 6649: and use that in your assembly code.
 6650: 
 6651: @cindex code words, portable
 6652: Another option for implementing normal and defining words efficiently
 6653: is to add the desired functionality to the source of Gforth. For normal
 6654: words you just have to edit @file{primitives} (@pxref{Automatic
 6655: Generation}). Defining words (equivalent to @code{;CODE} words, for fast
 6656: defined words) may require changes in @file{engine.c}, @file{kernel.fs},
 6657: @file{prims2x.fs}, and possibly @file{cross.fs}.
 6658: 
 6659: 
 6660: @c -------------------------------------------------------------
 6661: @node Threading Words, Locals, Assembler and Code Words, Words
 6662: @section Threading Words
 6663: @cindex threading words
 6664: 
 6665: @cindex code address
 6666: These words provide access to code addresses and other threading stuff
 6667: in Gforth (and, possibly, other interpretive Forths). It more or less
 6668: abstracts away the differences between direct and indirect threading
 6669: (and, for direct threading, the machine dependences). However, at
 6670: present this wordset is still incomplete. It is also pretty low-level;
 6671: some day it will hopefully be made unnecessary by an internals wordset
 6672: that abstracts implementation details away completely.
 6673: 
 6674: 
 6675: doc-threading-method
 6676: doc->code-address
 6677: doc->does-code
 6678: doc-code-address!
 6679: doc-does-code!
 6680: doc-does-handler!
 6681: doc-/does-handler
 6682: 
 6683: 
 6684: The code addresses produced by various defining words are produced by
 6685: the following words:
 6686: 
 6687: 
 6688: doc-docol:
 6689: doc-docon:
 6690: doc-dovar:
 6691: doc-douser:
 6692: doc-dodefer:
 6693: doc-dofield:
 6694: 
 6695: 
 6696: You can recognize words defined by a @code{CREATE}...@code{DOES>} word
 6697: with @code{>does-code}. If the word was defined in that way, the value
 6698: returned is non-zero and identifies the @code{DOES>} used by the
 6699: defining word.
 6700: @comment TODO should that be ``identifies the xt of the DOES> ??''
 6701: 
 6702: @c -------------------------------------------------------------
 6703: @node Locals, Structures, Threading Words, Words
 6704: @section Locals
 6705: @cindex locals
 6706: 
 6707: Local variables can make Forth programming more enjoyable and Forth
 6708: programs easier to read. Unfortunately, the locals of ANS Forth are
 6709: laden with restrictions. Therefore, we provide not only the ANS Forth
 6710: locals wordset, but also our own, more powerful locals wordset (we
 6711: implemented the ANS Forth locals wordset through our locals wordset).
 6712: 
 6713: The ideas in this section have also been published in the paper
 6714: @cite{Automatic Scoping of Local Variables} by M. Anton Ertl, presented
 6715: at EuroForth '94; it is available at
 6716: @*@uref{http://www.complang.tuwien.ac.at/papers/ertl94l.ps.gz}.
 6717: 
 6718: @menu
 6719: * Gforth locals::               
 6720: * ANS Forth locals::            
 6721: @end menu
 6722: 
 6723: @node Gforth locals, ANS Forth locals, Locals, Locals
 6724: @subsection Gforth locals
 6725: @cindex Gforth locals
 6726: @cindex locals, Gforth style
 6727: 
 6728: Locals can be defined with
 6729: 
 6730: @example
 6731: @{ local1 local2 ... -- comment @}
 6732: @end example
 6733: or
 6734: @example
 6735: @{ local1 local2 ... @}
 6736: @end example
 6737: 
 6738: E.g.,
 6739: @example
 6740: : max @{ n1 n2 -- n3 @}
 6741:  n1 n2 > if
 6742:    n1
 6743:  else
 6744:    n2
 6745:  endif ;
 6746: @end example
 6747: 
 6748: The similarity of locals definitions with stack comments is intended. A
 6749: locals definition often replaces the stack comment of a word. The order
 6750: of the locals corresponds to the order in a stack comment and everything
 6751: after the @code{--} is really a comment.
 6752: 
 6753: This similarity has one disadvantage: It is too easy to confuse locals
 6754: declarations with stack comments, causing bugs and making them hard to
 6755: find. However, this problem can be avoided by appropriate coding
 6756: conventions: Do not use both notations in the same program. If you do,
 6757: they should be distinguished using additional means, e.g. by position.
 6758: 
 6759: @cindex types of locals
 6760: @cindex locals types
 6761: The name of the local may be preceded by a type specifier, e.g.,
 6762: @code{F:} for a floating point value:
 6763: 
 6764: @example
 6765: : CX* @{ F: Ar F: Ai F: Br F: Bi -- Cr Ci @}
 6766: \ complex multiplication
 6767:  Ar Br f* Ai Bi f* f-
 6768:  Ar Bi f* Ai Br f* f+ ;
 6769: @end example
 6770: 
 6771: @cindex flavours of locals
 6772: @cindex locals flavours
 6773: @cindex value-flavoured locals
 6774: @cindex variable-flavoured locals
 6775: Gforth currently supports cells (@code{W:}, @code{W^}), doubles
 6776: (@code{D:}, @code{D^}), floats (@code{F:}, @code{F^}) and characters
 6777: (@code{C:}, @code{C^}) in two flavours: a value-flavoured local (defined
 6778: with @code{W:}, @code{D:} etc.) produces its value and can be changed
 6779: with @code{TO}. A variable-flavoured local (defined with @code{W^} etc.)
 6780: produces its address (which becomes invalid when the variable's scope is
 6781: left). E.g., the standard word @code{emit} can be defined in terms of
 6782: @code{type} like this:
 6783: 
 6784: @example
 6785: : emit @{ C^ char* -- @}
 6786:     char* 1 type ;
 6787: @end example
 6788: 
 6789: @cindex default type of locals
 6790: @cindex locals, default type
 6791: A local without type specifier is a @code{W:} local. Both flavours of
 6792: locals are initialized with values from the data or FP stack.
 6793: 
 6794: Currently there is no way to define locals with user-defined data
 6795: structures, but we are working on it.
 6796: 
 6797: Gforth allows defining locals everywhere in a colon definition. This
 6798: poses the following questions:
 6799: 
 6800: @menu
 6801: * Where are locals visible by name?::  
 6802: * How long do locals live?::    
 6803: * Programming Style::           
 6804: * Implementation::              
 6805: @end menu
 6806: 
 6807: @node Where are locals visible by name?, How long do locals live?, Gforth locals, Gforth locals
 6808: @subsubsection Where are locals visible by name?
 6809: @cindex locals visibility
 6810: @cindex visibility of locals
 6811: @cindex scope of locals
 6812: 
 6813: Basically, the answer is that locals are visible where you would expect
 6814: it in block-structured languages, and sometimes a little longer. If you
 6815: want to restrict the scope of a local, enclose its definition in
 6816: @code{SCOPE}...@code{ENDSCOPE}.
 6817: 
 6818: 
 6819: doc-scope
 6820: doc-endscope
 6821: 
 6822: 
 6823: These words behave like control structure words, so you can use them
 6824: with @code{CS-PICK} and @code{CS-ROLL} to restrict the scope in
 6825: arbitrary ways.
 6826: 
 6827: If you want a more exact answer to the visibility question, here's the
 6828: basic principle: A local is visible in all places that can only be
 6829: reached through the definition of the local@footnote{In compiler
 6830: construction terminology, all places dominated by the definition of the
 6831: local.}. In other words, it is not visible in places that can be reached
 6832: without going through the definition of the local. E.g., locals defined
 6833: in @code{IF}...@code{ENDIF} are visible until the @code{ENDIF}, locals
 6834: defined in @code{BEGIN}...@code{UNTIL} are visible after the
 6835: @code{UNTIL} (until, e.g., a subsequent @code{ENDSCOPE}).
 6836: 
 6837: The reasoning behind this solution is: We want to have the locals
 6838: visible as long as it is meaningful. The user can always make the
 6839: visibility shorter by using explicit scoping. In a place that can
 6840: only be reached through the definition of a local, the meaning of a
 6841: local name is clear. In other places it is not: How is the local
 6842: initialized at the control flow path that does not contain the
 6843: definition? Which local is meant, if the same name is defined twice in
 6844: two independent control flow paths?
 6845: 
 6846: This should be enough detail for nearly all users, so you can skip the
 6847: rest of this section. If you really must know all the gory details and
 6848: options, read on.
 6849: 
 6850: In order to implement this rule, the compiler has to know which places
 6851: are unreachable. It knows this automatically after @code{AHEAD},
 6852: @code{AGAIN}, @code{EXIT} and @code{LEAVE}; in other cases (e.g., after
 6853: most @code{THROW}s), you can use the word @code{UNREACHABLE} to tell the
 6854: compiler that the control flow never reaches that place. If
 6855: @code{UNREACHABLE} is not used where it could, the only consequence is
 6856: that the visibility of some locals is more limited than the rule above
 6857: says. If @code{UNREACHABLE} is used where it should not (i.e., if you
 6858: lie to the compiler), buggy code will be produced.
 6859: 
 6860: 
 6861: doc-unreachable
 6862: 
 6863: 
 6864: Another problem with this rule is that at @code{BEGIN}, the compiler
 6865: does not know which locals will be visible on the incoming
 6866: back-edge. All problems discussed in the following are due to this
 6867: ignorance of the compiler (we discuss the problems using @code{BEGIN}
 6868: loops as examples; the discussion also applies to @code{?DO} and other
 6869: loops). Perhaps the most insidious example is:
 6870: @example
 6871: AHEAD
 6872: BEGIN
 6873:   x
 6874: [ 1 CS-ROLL ] THEN
 6875:   @{ x @}
 6876:   ...
 6877: UNTIL
 6878: @end example
 6879: 
 6880: This should be legal according to the visibility rule. The use of
 6881: @code{x} can only be reached through the definition; but that appears
 6882: textually below the use.
 6883: 
 6884: From this example it is clear that the visibility rules cannot be fully
 6885: implemented without major headaches. Our implementation treats common
 6886: cases as advertised and the exceptions are treated in a safe way: The
 6887: compiler makes a reasonable guess about the locals visible after a
 6888: @code{BEGIN}; if it is too pessimistic, the
 6889: user will get a spurious error about the local not being defined; if the
 6890: compiler is too optimistic, it will notice this later and issue a
 6891: warning. In the case above the compiler would complain about @code{x}
 6892: being undefined at its use. You can see from the obscure examples in
 6893: this section that it takes quite unusual control structures to get the
 6894: compiler into trouble, and even then it will often do fine.
 6895: 
 6896: If the @code{BEGIN} is reachable from above, the most optimistic guess
 6897: is that all locals visible before the @code{BEGIN} will also be
 6898: visible after the @code{BEGIN}. This guess is valid for all loops that
 6899: are entered only through the @code{BEGIN}, in particular, for normal
 6900: @code{BEGIN}...@code{WHILE}...@code{REPEAT} and
 6901: @code{BEGIN}...@code{UNTIL} loops and it is implemented in our
 6902: compiler. When the branch to the @code{BEGIN} is finally generated by
 6903: @code{AGAIN} or @code{UNTIL}, the compiler checks the guess and
 6904: warns the user if it was too optimistic:
 6905: @example
 6906: IF
 6907:   @{ x @}
 6908: BEGIN
 6909:   \ x ? 
 6910: [ 1 cs-roll ] THEN
 6911:   ...
 6912: UNTIL
 6913: @end example
 6914: 
 6915: Here, @code{x} lives only until the @code{BEGIN}, but the compiler
 6916: optimistically assumes that it lives until the @code{THEN}. It notices
 6917: this difference when it compiles the @code{UNTIL} and issues a
 6918: warning. The user can avoid the warning, and make sure that @code{x}
 6919: is not used in the wrong area by using explicit scoping:
 6920: @example
 6921: IF
 6922:   SCOPE
 6923:   @{ x @}
 6924:   ENDSCOPE
 6925: BEGIN
 6926: [ 1 cs-roll ] THEN
 6927:   ...
 6928: UNTIL
 6929: @end example
 6930: 
 6931: Since the guess is optimistic, there will be no spurious error messages
 6932: about undefined locals.
 6933: 
 6934: If the @code{BEGIN} is not reachable from above (e.g., after
 6935: @code{AHEAD} or @code{EXIT}), the compiler cannot even make an
 6936: optimistic guess, as the locals visible after the @code{BEGIN} may be
 6937: defined later. Therefore, the compiler assumes that no locals are
 6938: visible after the @code{BEGIN}. However, the user can use
 6939: @code{ASSUME-LIVE} to make the compiler assume that the same locals are
 6940: visible at the BEGIN as at the point where the top control-flow stack
 6941: item was created.
 6942: 
 6943: 
 6944: doc-assume-live
 6945: 
 6946: 
 6947: @noindent
 6948: E.g.,
 6949: @example
 6950: @{ x @}
 6951: AHEAD
 6952: ASSUME-LIVE
 6953: BEGIN
 6954:   x
 6955: [ 1 CS-ROLL ] THEN
 6956:   ...
 6957: UNTIL
 6958: @end example
 6959: 
 6960: Other cases where the locals are defined before the @code{BEGIN} can be
 6961: handled by inserting an appropriate @code{CS-ROLL} before the
 6962: @code{ASSUME-LIVE} (and changing the control-flow stack manipulation
 6963: behind the @code{ASSUME-LIVE}).
 6964: 
 6965: Cases where locals are defined after the @code{BEGIN} (but should be
 6966: visible immediately after the @code{BEGIN}) can only be handled by
 6967: rearranging the loop. E.g., the ``most insidious'' example above can be
 6968: arranged into:
 6969: @example
 6970: BEGIN
 6971:   @{ x @}
 6972:   ... 0=
 6973: WHILE
 6974:   x
 6975: REPEAT
 6976: @end example
 6977: 
 6978: @node How long do locals live?, Programming Style, Where are locals visible by name?, Gforth locals
 6979: @subsubsection How long do locals live?
 6980: @cindex locals lifetime
 6981: @cindex lifetime of locals
 6982: 
 6983: The right answer for the lifetime question would be: A local lives at
 6984: least as long as it can be accessed. For a value-flavoured local this
 6985: means: until the end of its visibility. However, a variable-flavoured
 6986: local could be accessed through its address far beyond its visibility
 6987: scope. Ultimately, this would mean that such locals would have to be
 6988: garbage collected. Since this entails un-Forth-like implementation
 6989: complexities, I adopted the same cowardly solution as some other
 6990: languages (e.g., C): The local lives only as long as it is visible;
 6991: afterwards its address is invalid (and programs that access it
 6992: afterwards are erroneous).
 6993: 
 6994: @node Programming Style, Implementation, How long do locals live?, Gforth locals
 6995: @subsubsection Programming Style
 6996: @cindex locals programming style
 6997: @cindex programming style, locals
 6998: 
 6999: The freedom to define locals anywhere has the potential to change
 7000: programming styles dramatically. In particular, the need to use the
 7001: return stack for intermediate storage vanishes. Moreover, all stack
 7002: manipulations (except @code{PICK}s and @code{ROLL}s with run-time
 7003: determined arguments) can be eliminated: If the stack items are in the
 7004: wrong order, just write a locals definition for all of them; then
 7005: write the items in the order you want.
 7006: 
 7007: This seems a little far-fetched and eliminating stack manipulations is
 7008: unlikely to become a conscious programming objective. Still, the number
 7009: of stack manipulations will be reduced dramatically if local variables
 7010: are used liberally (e.g., compare @code{max} in @ref{Gforth locals} with
 7011: a traditional implementation of @code{max}).
 7012: 
 7013: This shows one potential benefit of locals: making Forth programs more
 7014: readable. Of course, this benefit will only be realized if the
 7015: programmers continue to honour the principle of factoring instead of
 7016: using the added latitude to make the words longer.
 7017: 
 7018: @cindex single-assignment style for locals
 7019: Using @code{TO} can and should be avoided.  Without @code{TO},
 7020: every value-flavoured local has only a single assignment and many
 7021: advantages of functional languages apply to Forth. I.e., programs are
 7022: easier to analyse, to optimize and to read: It is clear from the
 7023: definition what the local stands for, it does not turn into something
 7024: different later.
 7025: 
 7026: E.g., a definition using @code{TO} might look like this:
 7027: @example
 7028: : strcmp @{ addr1 u1 addr2 u2 -- n @}
 7029:  u1 u2 min 0
 7030:  ?do
 7031:    addr1 c@@ addr2 c@@ -
 7032:    ?dup-if
 7033:      unloop exit
 7034:    then
 7035:    addr1 char+ TO addr1
 7036:    addr2 char+ TO addr2
 7037:  loop
 7038:  u1 u2 - ;
 7039: @end example
 7040: Here, @code{TO} is used to update @code{addr1} and @code{addr2} at
 7041: every loop iteration. @code{strcmp} is a typical example of the
 7042: readability problems of using @code{TO}. When you start reading
 7043: @code{strcmp}, you think that @code{addr1} refers to the start of the
 7044: string. Only near the end of the loop you realize that it is something
 7045: else.
 7046: 
 7047: This can be avoided by defining two locals at the start of the loop that
 7048: are initialized with the right value for the current iteration.
 7049: @example
 7050: : strcmp @{ addr1 u1 addr2 u2 -- n @}
 7051:  addr1 addr2
 7052:  u1 u2 min 0 
 7053:  ?do @{ s1 s2 @}
 7054:    s1 c@@ s2 c@@ -
 7055:    ?dup-if
 7056:      unloop exit
 7057:    then
 7058:    s1 char+ s2 char+
 7059:  loop
 7060:  2drop
 7061:  u1 u2 - ;
 7062: @end example
 7063: Here it is clear from the start that @code{s1} has a different value
 7064: in every loop iteration.
 7065: 
 7066: @node Implementation,  , Programming Style, Gforth locals
 7067: @subsubsection Implementation
 7068: @cindex locals implementation
 7069: @cindex implementation of locals
 7070: 
 7071: @cindex locals stack
 7072: Gforth uses an extra locals stack. The most compelling reason for
 7073: this is that the return stack is not float-aligned; using an extra stack
 7074: also eliminates the problems and restrictions of using the return stack
 7075: as locals stack. Like the other stacks, the locals stack grows toward
 7076: lower addresses. A few primitives allow an efficient implementation:
 7077: 
 7078: 
 7079: doc-@local#
 7080: doc-f@local#
 7081: doc-laddr#
 7082: doc-lp+!#
 7083: doc-lp!
 7084: doc->l
 7085: doc-f>l
 7086: 
 7087: 
 7088: In addition to these primitives, some specializations of these
 7089: primitives for commonly occurring inline arguments are provided for
 7090: efficiency reasons, e.g., @code{@@local0} as specialization of
 7091: @code{@@local#} for the inline argument 0. The following compiling words
 7092: compile the right specialized version, or the general version, as
 7093: appropriate:
 7094: 
 7095: 
 7096: doc-compile-@local
 7097: doc-compile-f@local
 7098: doc-compile-lp+!
 7099: 
 7100: 
 7101: Combinations of conditional branches and @code{lp+!#} like
 7102: @code{?branch-lp+!#} (the locals pointer is only changed if the branch
 7103: is taken) are provided for efficiency and correctness in loops.
 7104: 
 7105: A special area in the dictionary space is reserved for keeping the
 7106: local variable names. @code{@{} switches the dictionary pointer to this
 7107: area and @code{@}} switches it back and generates the locals
 7108: initializing code. @code{W:} etc.@ are normal defining words. This
 7109: special area is cleared at the start of every colon definition.
 7110: 
 7111: @cindex word list for defining locals
 7112: A special feature of Gforth's dictionary is used to implement the
 7113: definition of locals without type specifiers: every word list (aka
 7114: vocabulary) has its own methods for searching
 7115: etc. (@pxref{Word Lists}). For the present purpose we defined a word list
 7116: with a special search method: When it is searched for a word, it
 7117: actually creates that word using @code{W:}. @code{@{} changes the search
 7118: order to first search the word list containing @code{@}}, @code{W:} etc.,
 7119: and then the word list for defining locals without type specifiers.
 7120: 
 7121: The lifetime rules support a stack discipline within a colon
 7122: definition: The lifetime of a local is either nested with other locals
 7123: lifetimes or it does not overlap them.
 7124: 
 7125: At @code{BEGIN}, @code{IF}, and @code{AHEAD} no code for locals stack
 7126: pointer manipulation is generated. Between control structure words
 7127: locals definitions can push locals onto the locals stack. @code{AGAIN}
 7128: is the simplest of the other three control flow words. It has to
 7129: restore the locals stack depth of the corresponding @code{BEGIN}
 7130: before branching. The code looks like this:
 7131: @format
 7132: @code{lp+!#} current-locals-size @minus{} dest-locals-size
 7133: @code{branch} <begin>
 7134: @end format
 7135: 
 7136: @code{UNTIL} is a little more complicated: If it branches back, it
 7137: must adjust the stack just like @code{AGAIN}. But if it falls through,
 7138: the locals stack must not be changed. The compiler generates the
 7139: following code:
 7140: @format
 7141: @code{?branch-lp+!#} <begin> current-locals-size @minus{} dest-locals-size
 7142: @end format
 7143: The locals stack pointer is only adjusted if the branch is taken.
 7144: 
 7145: @code{THEN} can produce somewhat inefficient code:
 7146: @format
 7147: @code{lp+!#} current-locals-size @minus{} orig-locals-size
 7148: <orig target>:
 7149: @code{lp+!#} orig-locals-size @minus{} new-locals-size
 7150: @end format
 7151: The second @code{lp+!#} adjusts the locals stack pointer from the
 7152: level at the @i{orig} point to the level after the @code{THEN}. The
 7153: first @code{lp+!#} adjusts the locals stack pointer from the current
 7154: level to the level at the orig point, so the complete effect is an
 7155: adjustment from the current level to the right level after the
 7156: @code{THEN}.
 7157: 
 7158: @cindex locals information on the control-flow stack
 7159: @cindex control-flow stack items, locals information
 7160: In a conventional Forth implementation a dest control-flow stack entry
 7161: is just the target address and an orig entry is just the address to be
 7162: patched. Our locals implementation adds a word list to every orig or dest
 7163: item. It is the list of locals visible (or assumed visible) at the point
 7164: described by the entry. Our implementation also adds a tag to identify
 7165: the kind of entry, in particular to differentiate between live and dead
 7166: (reachable and unreachable) orig entries.
 7167: 
 7168: A few unusual operations have to be performed on locals word lists:
 7169: 
 7170: 
 7171: doc-common-list
 7172: doc-sub-list?
 7173: doc-list-size
 7174: 
 7175: 
 7176: Several features of our locals word list implementation make these
 7177: operations easy to implement: The locals word lists are organised as
 7178: linked lists; the tails of these lists are shared, if the lists
 7179: contain some of the same locals; and the address of a name is greater
 7180: than the address of the names behind it in the list.
 7181: 
 7182: Another important implementation detail is the variable
 7183: @code{dead-code}. It is used by @code{BEGIN} and @code{THEN} to
 7184: determine if they can be reached directly or only through the branch
 7185: that they resolve. @code{dead-code} is set by @code{UNREACHABLE},
 7186: @code{AHEAD}, @code{EXIT} etc., and cleared at the start of a colon
 7187: definition, by @code{BEGIN} and usually by @code{THEN}.
 7188: 
 7189: Counted loops are similar to other loops in most respects, but
 7190: @code{LEAVE} requires special attention: It performs basically the same
 7191: service as @code{AHEAD}, but it does not create a control-flow stack
 7192: entry. Therefore the information has to be stored elsewhere;
 7193: traditionally, the information was stored in the target fields of the
 7194: branches created by the @code{LEAVE}s, by organizing these fields into a
 7195: linked list. Unfortunately, this clever trick does not provide enough
 7196: space for storing our extended control flow information. Therefore, we
 7197: introduce another stack, the leave stack. It contains the control-flow
 7198: stack entries for all unresolved @code{LEAVE}s.
 7199: 
 7200: Local names are kept until the end of the colon definition, even if
 7201: they are no longer visible in any control-flow path. In a few cases
 7202: this may lead to increased space needs for the locals name area, but
 7203: usually less than reclaiming this space would cost in code size.
 7204: 
 7205: 
 7206: @node ANS Forth locals,  , Gforth locals, Locals
 7207: @subsection ANS Forth locals
 7208: @cindex locals, ANS Forth style
 7209: 
 7210: The ANS Forth locals wordset does not define a syntax for locals, but
 7211: words that make it possible to define various syntaxes. One of the
 7212: possible syntaxes is a subset of the syntax we used in the Gforth locals
 7213: wordset, i.e.:
 7214: 
 7215: @example
 7216: @{ local1 local2 ... -- comment @}
 7217: @end example
 7218: @noindent
 7219: or
 7220: @example
 7221: @{ local1 local2 ... @}
 7222: @end example
 7223: 
 7224: The order of the locals corresponds to the order in a stack comment. The
 7225: restrictions are:
 7226: 
 7227: @itemize @bullet
 7228: @item
 7229: Locals can only be cell-sized values (no type specifiers are allowed).
 7230: @item
 7231: Locals can be defined only outside control structures.
 7232: @item
 7233: Locals can interfere with explicit usage of the return stack. For the
 7234: exact (and long) rules, see the standard. If you don't use return stack
 7235: accessing words in a definition using locals, you will be all right. The
 7236: purpose of this rule is to make locals implementation on the return
 7237: stack easier.
 7238: @item
 7239: The whole definition must be in one line.
 7240: @end itemize
 7241: 
 7242: Locals defined in this way behave like @code{VALUE}s
 7243: (@xref{Values}). I.e., they are initialized from the stack. Using their
 7244: name produces their value. Their value can be changed using @code{TO}.
 7245: 
 7246: Since this syntax is supported by Gforth directly, you need not do
 7247: anything to use it. If you want to port a program using this syntax to
 7248: another ANS Forth system, use @file{compat/anslocal.fs} to implement the
 7249: syntax on the other system.
 7250: 
 7251: Note that a syntax shown in the standard, section A.13 looks
 7252: similar, but is quite different in having the order of locals
 7253: reversed. Beware!
 7254: 
 7255: The ANS Forth locals wordset itself consists of a word:
 7256: 
 7257: 
 7258: doc-(local)
 7259: 
 7260: 
 7261: The ANS Forth locals extension wordset defines a syntax using @code{locals|}, but it is so
 7262: awful that we strongly recommend not to use it. We have implemented this
 7263: syntax to make porting to Gforth easy, but do not document it here. The
 7264: problem with this syntax is that the locals are defined in an order
 7265: reversed with respect to the standard stack comment notation, making
 7266: programs harder to read, and easier to misread and miswrite. The only
 7267: merit of this syntax is that it is easy to implement using the ANS Forth
 7268: locals wordset.
 7269: 
 7270: 
 7271: @c ----------------------------------------------------------
 7272: @node Structures, Object-oriented Forth, Locals, Words
 7273: @section  Structures
 7274: @cindex structures
 7275: @cindex records
 7276: 
 7277: This section presents the structure package that comes with Gforth. A
 7278: version of the package implemented in ANS Forth is available in
 7279: @file{compat/struct.fs}. This package was inspired by a posting on
 7280: comp.lang.forth in 1989 (unfortunately I don't remember, by whom;
 7281: possibly John Hayes). A version of this section has been published in
 7282: ???. Marcel Hendrix provided helpful comments.
 7283: 
 7284: @menu
 7285: * Why explicit structure support?::  
 7286: * Structure Usage::             
 7287: * Structure Naming Convention::  
 7288: * Structure Implementation::    
 7289: * Structure Glossary::          
 7290: @end menu
 7291: 
 7292: @node Why explicit structure support?, Structure Usage, Structures, Structures
 7293: @subsection Why explicit structure support?
 7294: 
 7295: @cindex address arithmetic for structures
 7296: @cindex structures using address arithmetic
 7297: If we want to use a structure containing several fields, we could simply
 7298: reserve memory for it, and access the fields using address arithmetic
 7299: (@pxref{Address arithmetic}). As an example, consider a structure with
 7300: the following fields
 7301: 
 7302: @table @code
 7303: @item a
 7304: is a float
 7305: @item b
 7306: is a cell
 7307: @item c
 7308: is a float
 7309: @end table
 7310: 
 7311: Given the (float-aligned) base address of the structure we get the
 7312: address of the field
 7313: 
 7314: @table @code
 7315: @item a
 7316: without doing anything further.
 7317: @item b
 7318: with @code{float+}
 7319: @item c
 7320: with @code{float+ cell+ faligned}
 7321: @end table
 7322: 
 7323: It is easy to see that this can become quite tiring. 
 7324: 
 7325: Moreover, it is not very readable, because seeing a
 7326: @code{cell+} tells us neither which kind of structure is
 7327: accessed nor what field is accessed; we have to somehow infer the kind
 7328: of structure, and then look up in the documentation, which field of
 7329: that structure corresponds to that offset.
 7330: 
 7331: Finally, this kind of address arithmetic also causes maintenance
 7332: troubles: If you add or delete a field somewhere in the middle of the
 7333: structure, you have to find and change all computations for the fields
 7334: afterwards.
 7335: 
 7336: So, instead of using @code{cell+} and friends directly, how
 7337: about storing the offsets in constants:
 7338: 
 7339: @example
 7340: 0 constant a-offset
 7341: 0 float+ constant b-offset
 7342: 0 float+ cell+ faligned c-offset
 7343: @end example
 7344: 
 7345: Now we can get the address of field @code{x} with @code{x-offset
 7346: +}. This is much better in all respects. Of course, you still
 7347: have to change all later offset definitions if you add a field. You can
 7348: fix this by declaring the offsets in the following way:
 7349: 
 7350: @example
 7351: 0 constant a-offset
 7352: a-offset float+ constant b-offset
 7353: b-offset cell+ faligned constant c-offset
 7354: @end example
 7355: 
 7356: Since we always use the offsets with @code{+}, we could use a defining
 7357: word @code{cfield} that includes the @code{+} in the action of the
 7358: defined word:
 7359: 
 7360: @example
 7361: : cfield ( n "name" -- )
 7362:     create ,
 7363: does> ( name execution: addr1 -- addr2 )
 7364:     @@ + ;
 7365: 
 7366: 0 cfield a
 7367: 0 a float+ cfield b
 7368: 0 b cell+ faligned cfield c
 7369: @end example
 7370: 
 7371: Instead of @code{x-offset +}, we now simply write @code{x}.
 7372: 
 7373: The structure field words now can be used quite nicely. However,
 7374: their definition is still a bit cumbersome: We have to repeat the
 7375: name, the information about size and alignment is distributed before
 7376: and after the field definitions etc.  The structure package presented
 7377: here addresses these problems.
 7378: 
 7379: @node Structure Usage, Structure Naming Convention, Why explicit structure support?, Structures
 7380: @subsection Structure Usage
 7381: @cindex structure usage
 7382: 
 7383: @cindex @code{field} usage
 7384: @cindex @code{struct} usage
 7385: @cindex @code{end-struct} usage
 7386: You can define a structure for a (data-less) linked list with:
 7387: @example
 7388: struct
 7389:     cell% field list-next
 7390: end-struct list%
 7391: @end example
 7392: 
 7393: With the address of the list node on the stack, you can compute the
 7394: address of the field that contains the address of the next node with
 7395: @code{list-next}. E.g., you can determine the length of a list
 7396: with:
 7397: 
 7398: @example
 7399: : list-length ( list -- n )
 7400: \ "list" is a pointer to the first element of a linked list
 7401: \ "n" is the length of the list
 7402:     0 BEGIN ( list1 n1 )
 7403:         over
 7404:     WHILE ( list1 n1 )
 7405:         1+ swap list-next @@ swap
 7406:     REPEAT
 7407:     nip ;
 7408: @end example
 7409: 
 7410: You can reserve memory for a list node in the dictionary with
 7411: @code{list% %allot}, which leaves the address of the list node on the
 7412: stack. For the equivalent allocation on the heap you can use @code{list%
 7413: %alloc} (or, for an @code{allocate}-like stack effect (i.e., with ior),
 7414: use @code{list% %allocate}). You can get the the size of a list
 7415: node with @code{list% %size} and its alignment with @code{list%
 7416: %alignment}.
 7417: 
 7418: Note that in ANS Forth the body of a @code{create}d word is
 7419: @code{aligned} but not necessarily @code{faligned};
 7420: therefore, if you do a:
 7421: @example
 7422: create @emph{name} foo% %allot
 7423: @end example
 7424: 
 7425: @noindent
 7426: then the memory alloted for @code{foo%} is
 7427: guaranteed to start at the body of @code{@emph{name}} only if
 7428: @code{foo%} contains only character, cell and double fields.
 7429: 
 7430: @cindex structures containing structures
 7431: You can include a structure @code{foo%} as a field of
 7432: another structure, like this:
 7433: @example
 7434: struct
 7435: ...
 7436:     foo% field ...
 7437: ...
 7438: end-struct ...
 7439: @end example
 7440: 
 7441: @cindex structure extension
 7442: @cindex extended records
 7443: Instead of starting with an empty structure, you can extend an
 7444: existing structure. E.g., a plain linked list without data, as defined
 7445: above, is hardly useful; You can extend it to a linked list of integers,
 7446: like this:@footnote{This feature is also known as @emph{extended
 7447: records}. It is the main innovation in the Oberon language; in other
 7448: words, adding this feature to Modula-2 led Wirth to create a new
 7449: language, write a new compiler etc.  Adding this feature to Forth just
 7450: required a few lines of code.}
 7451: 
 7452: @example
 7453: list%
 7454:     cell% field intlist-int
 7455: end-struct intlist%
 7456: @end example
 7457: 
 7458: @code{intlist%} is a structure with two fields:
 7459: @code{list-next} and @code{intlist-int}.
 7460: 
 7461: @cindex structures containing arrays
 7462: You can specify an array type containing @emph{n} elements of
 7463: type @code{foo%} like this:
 7464: 
 7465: @example
 7466: foo% @emph{n} *
 7467: @end example
 7468: 
 7469: You can use this array type in any place where you can use a normal
 7470: type, e.g., when defining a @code{field}, or with
 7471: @code{%allot}.
 7472: 
 7473: @cindex first field optimization
 7474: The first field is at the base address of a structure and the word
 7475: for this field (e.g., @code{list-next}) actually does not change
 7476: the address on the stack. You may be tempted to leave it away in the
 7477: interest of run-time and space efficiency. This is not necessary,
 7478: because the structure package optimizes this case and compiling such
 7479: words does not generate any code. So, in the interest of readability
 7480: and maintainability you should include the word for the field when
 7481: accessing the field.
 7482: 
 7483: @node Structure Naming Convention, Structure Implementation, Structure Usage, Structures
 7484: @subsection Structure Naming Convention
 7485: @cindex structure naming convention
 7486: 
 7487: The field names that come to (my) mind are often quite generic, and,
 7488: if used, would cause frequent name clashes. E.g., many structures
 7489: probably contain a @code{counter} field. The structure names
 7490: that come to (my) mind are often also the logical choice for the names
 7491: of words that create such a structure.
 7492: 
 7493: Therefore, I have adopted the following naming conventions: 
 7494: 
 7495: @itemize @bullet
 7496: @cindex field naming convention
 7497: @item
 7498: The names of fields are of the form
 7499: @code{@emph{struct}-@emph{field}}, where
 7500: @code{@emph{struct}} is the basic name of the structure, and
 7501: @code{@emph{field}} is the basic name of the field. You can
 7502: think of field words as converting the (address of the)
 7503: structure into the (address of the) field.
 7504: 
 7505: @cindex structure naming convention
 7506: @item
 7507: The names of structures are of the form
 7508: @code{@emph{struct}%}, where
 7509: @code{@emph{struct}} is the basic name of the structure.
 7510: @end itemize
 7511: 
 7512: This naming convention does not work that well for fields of extended
 7513: structures; e.g., the integer list structure has a field
 7514: @code{intlist-int}, but has @code{list-next}, not
 7515: @code{intlist-next}.
 7516: 
 7517: @node Structure Implementation, Structure Glossary, Structure Naming Convention, Structures
 7518: @subsection Structure Implementation
 7519: @cindex structure implementation
 7520: @cindex implementation of structures
 7521: 
 7522: The central idea in the implementation is to pass the data about the
 7523: structure being built on the stack, not in some global
 7524: variable. Everything else falls into place naturally once this design
 7525: decision is made.
 7526: 
 7527: The type description on the stack is of the form @emph{align
 7528: size}. Keeping the size on the top-of-stack makes dealing with arrays
 7529: very simple.
 7530: 
 7531: @code{field} is a defining word that uses @code{Create}
 7532: and @code{DOES>}. The body of the field contains the offset
 7533: of the field, and the normal @code{DOES>} action is simply:
 7534: 
 7535: @example
 7536: @ +
 7537: @end example
 7538: 
 7539: @noindent
 7540: i.e., add the offset to the address, giving the stack effect
 7541: @i{addr1 -- addr2} for a field.
 7542: 
 7543: @cindex first field optimization, implementation
 7544: This simple structure is slightly complicated by the optimization
 7545: for fields with offset 0, which requires a different
 7546: @code{DOES>}-part (because we cannot rely on there being
 7547: something on the stack if such a field is invoked during
 7548: compilation). Therefore, we put the different @code{DOES>}-parts
 7549: in separate words, and decide which one to invoke based on the
 7550: offset. For a zero offset, the field is basically a noop; it is
 7551: immediate, and therefore no code is generated when it is compiled.
 7552: 
 7553: @node Structure Glossary,  , Structure Implementation, Structures
 7554: @subsection Structure Glossary
 7555: @cindex structure glossary
 7556: 
 7557: 
 7558: doc-%align
 7559: doc-%alignment
 7560: doc-%alloc
 7561: doc-%allocate
 7562: doc-%allot
 7563: doc-cell%
 7564: doc-char%
 7565: doc-dfloat%
 7566: doc-double%
 7567: doc-end-struct
 7568: doc-field
 7569: doc-float%
 7570: doc-naligned
 7571: doc-sfloat%
 7572: doc-%size
 7573: doc-struct
 7574: 
 7575: 
 7576: @c -------------------------------------------------------------
 7577: @node Object-oriented Forth, Passing Commands to the OS, Structures, Words
 7578: @section Object-oriented Forth
 7579: 
 7580: Gforth comes with three packages for object-oriented programming:
 7581: @file{objects.fs}, @file{oof.fs}, and @file{mini-oof.fs}; none of them
 7582: is preloaded, so you have to @code{include} them before use. The most
 7583: important differences between these packages (and others) are discussed
 7584: in @ref{Comparison with other object models}. All packages are written
 7585: in ANS Forth and can be used with any other ANS Forth.
 7586: 
 7587: @menu
 7588: * Why object-oriented programming?::
 7589: * Object-Oriented Terminology::
 7590: * Objects::
 7591: * OOF::
 7592: * Mini-OOF::
 7593: * Comparison with other object models::  
 7594: @end menu
 7595: 
 7596: 
 7597: @node Why object-oriented programming?, Object-Oriented Terminology, , Object-oriented Forth
 7598: @subsubsection Why object-oriented programming?
 7599: @cindex object-oriented programming motivation
 7600: @cindex motivation for object-oriented programming
 7601: 
 7602: Often we have to deal with several data structures (@emph{objects}),
 7603: that have to be treated similarly in some respects, but differently in
 7604: others. Graphical objects are the textbook example: circles, triangles,
 7605: dinosaurs, icons, and others, and we may want to add more during program
 7606: development. We want to apply some operations to any graphical object,
 7607: e.g., @code{draw} for displaying it on the screen. However, @code{draw}
 7608: has to do something different for every kind of object.
 7609: @comment TODO add some other operations eg perimeter, area
 7610: @comment and tie in to concrete examples later..
 7611: 
 7612: We could implement @code{draw} as a big @code{CASE}
 7613: control structure that executes the appropriate code depending on the
 7614: kind of object to be drawn. This would be not be very elegant, and,
 7615: moreover, we would have to change @code{draw} every time we add
 7616: a new kind of graphical object (say, a spaceship).
 7617: 
 7618: What we would rather do is: When defining spaceships, we would tell
 7619: the system: ``Here's how you @code{draw} a spaceship; you figure
 7620: out the rest''.
 7621: 
 7622: This is the problem that all systems solve that (rightfully) call
 7623: themselves object-oriented; the object-oriented packages presented here
 7624: solve this problem (and not much else).
 7625: @comment TODO ?list properties of oo systems.. oo vs o-based?
 7626: 
 7627: @node Object-Oriented Terminology, Objects, Why object-oriented programming?, Object-oriented Forth
 7628: @subsubsection Object-Oriented Terminology
 7629: @cindex object-oriented terminology
 7630: @cindex terminology for object-oriented programming
 7631: 
 7632: This section is mainly for reference, so you don't have to understand
 7633: all of it right away.  The terminology is mainly Smalltalk-inspired.  In
 7634: short:
 7635: 
 7636: @table @emph
 7637: @cindex class
 7638: @item class
 7639: a data structure definition with some extras.
 7640: 
 7641: @cindex object
 7642: @item object
 7643: an instance of the data structure described by the class definition.
 7644: 
 7645: @cindex instance variables
 7646: @item instance variables
 7647: fields of the data structure.
 7648: 
 7649: @cindex selector
 7650: @cindex method selector
 7651: @cindex virtual function
 7652: @item selector
 7653: (or @emph{method selector}) a word (e.g.,
 7654: @code{draw}) that performs an operation on a variety of data
 7655: structures (classes). A selector describes @emph{what} operation to
 7656: perform. In C++ terminology: a (pure) virtual function.
 7657: 
 7658: @cindex method
 7659: @item method
 7660: the concrete definition that performs the operation
 7661: described by the selector for a specific class. A method specifies
 7662: @emph{how} the operation is performed for a specific class.
 7663: 
 7664: @cindex selector invocation
 7665: @cindex message send
 7666: @cindex invoking a selector
 7667: @item selector invocation
 7668: a call of a selector. One argument of the call (the TOS (top-of-stack))
 7669: is used for determining which method is used. In Smalltalk terminology:
 7670: a message (consisting of the selector and the other arguments) is sent
 7671: to the object.
 7672: 
 7673: @cindex receiving object
 7674: @item receiving object
 7675: the object used for determining the method executed by a selector
 7676: invocation. In the @file{objects.fs} model, it is the object that is on
 7677: the TOS when the selector is invoked. (@emph{Receiving} comes from
 7678: the Smalltalk @emph{message} terminology.)
 7679: 
 7680: @cindex child class
 7681: @cindex parent class
 7682: @cindex inheritance
 7683: @item child class
 7684: a class that has (@emph{inherits}) all properties (instance variables,
 7685: selectors, methods) from a @emph{parent class}. In Smalltalk
 7686: terminology: The subclass inherits from the superclass. In C++
 7687: terminology: The derived class inherits from the base class.
 7688: 
 7689: @end table
 7690: 
 7691: @c If you wonder about the message sending terminology, it comes from
 7692: @c a time when each object had it's own task and objects communicated via
 7693: @c message passing; eventually the Smalltalk developers realized that
 7694: @c they can do most things through simple (indirect) calls. They kept the
 7695: @c terminology.
 7696: 
 7697: 
 7698: @node Objects, OOF, Object-Oriented Terminology, Object-oriented Forth
 7699: @subsection The @file{objects.fs} model
 7700: @cindex objects
 7701: @cindex object-oriented programming
 7702: 
 7703: @cindex @file{objects.fs}
 7704: @cindex @file{oof.fs}
 7705: 
 7706: This section describes the @file{objects.fs} package. This material also
 7707: has been published in @cite{Yet Another Forth Objects Package} by Anton
 7708: Ertl and appeared in Forth Dimensions 19(2), pages 37--43
 7709: (@uref{http://www.complang.tuwien.ac.at/forth/objects/objects.html}).
 7710: @c McKewan's and Zsoter's packages
 7711: 
 7712: This section assumes that you have read @ref{Structures}.
 7713: 
 7714: The techniques on which this model is based have been used to implement
 7715: the parser generator, Gray, and have also been used in Gforth for
 7716: implementing the various flavours of word lists (hashed or not,
 7717: case-sensitive or not, special-purpose word lists for locals etc.).
 7718: 
 7719: 
 7720: @menu
 7721: * Properties of the Objects model::  
 7722: * Basic Objects Usage::         
 7723: * The Objects base class::      
 7724: * Creating objects::            
 7725: * Object-Oriented Programming Style::  
 7726: * Class Binding::               
 7727: * Method conveniences::         
 7728: * Classes and Scoping::         
 7729: * Dividing classes::            
 7730: * Object Interfaces::           
 7731: * Objects Implementation::      
 7732: * Objects Glossary::            
 7733: @end menu
 7734: 
 7735: Marcel Hendrix provided helpful comments on this section. Andras Zsoter
 7736: and Bernd Paysan helped me with the related works section.
 7737: 
 7738: @node Properties of the Objects model, Basic Objects Usage, Objects, Objects
 7739: @subsubsection Properties of the @file{objects.fs} model
 7740: @cindex @file{objects.fs} properties
 7741: 
 7742: @itemize @bullet
 7743: @item
 7744: It is straightforward to pass objects on the stack. Passing
 7745: selectors on the stack is a little less convenient, but possible.
 7746: 
 7747: @item
 7748: Objects are just data structures in memory, and are referenced by their
 7749: address. You can create words for objects with normal defining words
 7750: like @code{constant}. Likewise, there is no difference between instance
 7751: variables that contain objects and those that contain other data.
 7752: 
 7753: @item
 7754: Late binding is efficient and easy to use.
 7755: 
 7756: @item
 7757: It avoids parsing, and thus avoids problems with state-smartness
 7758: and reduced extensibility; for convenience there are a few parsing
 7759: words, but they have non-parsing counterparts. There are also a few
 7760: defining words that parse. This is hard to avoid, because all standard
 7761: defining words parse (except @code{:noname}); however, such
 7762: words are not as bad as many other parsing words, because they are not
 7763: state-smart.
 7764: 
 7765: @item
 7766: It does not try to incorporate everything. It does a few things and does
 7767: them well (IMO). In particular, this model was not designed to support
 7768: information hiding (although it has features that may help); you can use
 7769: a separate package for achieving this.
 7770: 
 7771: @item
 7772: It is layered; you don't have to learn and use all features to use this
 7773: model. Only a few features are necessary (@xref{Basic Objects Usage},
 7774: @xref{The Objects base class}, @xref{Creating objects}.), the others
 7775: are optional and independent of each other.
 7776: 
 7777: @item
 7778: An implementation in ANS Forth is available.
 7779: 
 7780: @end itemize
 7781: 
 7782: 
 7783: @node Basic Objects Usage, The Objects base class, Properties of the Objects model, Objects
 7784: @subsubsection Basic @file{objects.fs} Usage
 7785: @cindex basic objects usage
 7786: @cindex objects, basic usage
 7787: 
 7788: You can define a class for graphical objects like this:
 7789: 
 7790: @cindex @code{class} usage
 7791: @cindex @code{end-class} usage
 7792: @cindex @code{selector} usage
 7793: @example
 7794: object class \ "object" is the parent class
 7795:   selector draw ( x y graphical -- )
 7796: end-class graphical
 7797: @end example
 7798: 
 7799: This code defines a class @code{graphical} with an
 7800: operation @code{draw}.  We can perform the operation
 7801: @code{draw} on any @code{graphical} object, e.g.:
 7802: 
 7803: @example
 7804: 100 100 t-rex draw
 7805: @end example
 7806: 
 7807: @noindent
 7808: where @code{t-rex} is a word (say, a constant) that produces a
 7809: graphical object.
 7810: 
 7811: @comment TODO add a 2nd operation eg perimeter.. and use for
 7812: @comment a concrete example
 7813: 
 7814: @cindex abstract class
 7815: How do we create a graphical object? With the present definitions,
 7816: we cannot create a useful graphical object. The class
 7817: @code{graphical} describes graphical objects in general, but not
 7818: any concrete graphical object type (C++ users would call it an
 7819: @emph{abstract class}); e.g., there is no method for the selector
 7820: @code{draw} in the class @code{graphical}.
 7821: 
 7822: For concrete graphical objects, we define child classes of the
 7823: class @code{graphical}, e.g.:
 7824: 
 7825: @cindex @code{overrides} usage
 7826: @cindex @code{field} usage in class definition
 7827: @example
 7828: graphical class \ "graphical" is the parent class
 7829:   cell% field circle-radius
 7830: 
 7831: :noname ( x y circle -- )
 7832:   circle-radius @@ draw-circle ;
 7833: overrides draw
 7834: 
 7835: :noname ( n-radius circle -- )
 7836:   circle-radius ! ;
 7837: overrides construct
 7838: 
 7839: end-class circle
 7840: @end example
 7841: 
 7842: Here we define a class @code{circle} as a child of @code{graphical},
 7843: with field @code{circle-radius} (which behaves just like a field
 7844: (@pxref{Structures}); it defines (using @code{overrides}) new methods
 7845: for the selectors @code{draw} and @code{construct} (@code{construct} is
 7846: defined in @code{object}, the parent class of @code{graphical}).
 7847: 
 7848: Now we can create a circle on the heap (i.e.,
 7849: @code{allocate}d memory) with:
 7850: 
 7851: @cindex @code{heap-new} usage
 7852: @example
 7853: 50 circle heap-new constant my-circle
 7854: @end example
 7855: 
 7856: @noindent
 7857: @code{heap-new} invokes @code{construct}, thus
 7858: initializing the field @code{circle-radius} with 50. We can draw
 7859: this new circle at (100,100) with:
 7860: 
 7861: @example
 7862: 100 100 my-circle draw
 7863: @end example
 7864: 
 7865: @cindex selector invocation, restrictions
 7866: @cindex class definition, restrictions
 7867: Note: You can only invoke a selector if the object on the TOS
 7868: (the receiving object) belongs to the class where the selector was
 7869: defined or one of its descendents; e.g., you can invoke
 7870: @code{draw} only for objects belonging to @code{graphical}
 7871: or its descendents (e.g., @code{circle}).  Immediately before
 7872: @code{end-class}, the search order has to be the same as
 7873: immediately after @code{class}.
 7874: 
 7875: @node The Objects base class, Creating objects, Basic Objects Usage, Objects
 7876: @subsubsection The @file{object.fs} base class
 7877: @cindex @code{object} class
 7878: 
 7879: When you define a class, you have to specify a parent class.  So how do
 7880: you start defining classes? There is one class available from the start:
 7881: @code{object}. It is ancestor for all classes and so is the
 7882: only class that has no parent. It has two selectors: @code{construct}
 7883: and @code{print}.
 7884: 
 7885: @node Creating objects, Object-Oriented Programming Style, The Objects base class, Objects
 7886: @subsubsection Creating objects
 7887: @cindex creating objects
 7888: @cindex object creation
 7889: @cindex object allocation options
 7890: 
 7891: @cindex @code{heap-new} discussion
 7892: @cindex @code{dict-new} discussion
 7893: @cindex @code{construct} discussion
 7894: You can create and initialize an object of a class on the heap with
 7895: @code{heap-new} ( ... class -- object ) and in the dictionary
 7896: (allocation with @code{allot}) with @code{dict-new} (
 7897: ... class -- object ). Both words invoke @code{construct}, which
 7898: consumes the stack items indicated by "..." above.
 7899: 
 7900: @cindex @code{init-object} discussion
 7901: @cindex @code{class-inst-size} discussion
 7902: If you want to allocate memory for an object yourself, you can get its
 7903: alignment and size with @code{class-inst-size 2@@} ( class --
 7904: align size ). Once you have memory for an object, you can initialize
 7905: it with @code{init-object} ( ... class object -- );
 7906: @code{construct} does only a part of the necessary work.
 7907: 
 7908: @node Object-Oriented Programming Style, Class Binding, Creating objects, Objects
 7909: @subsubsection Object-Oriented Programming Style
 7910: @cindex object-oriented programming style
 7911: @cindex programming style, object-oriented
 7912: 
 7913: This section is not exhaustive.
 7914: 
 7915: @cindex stack effects of selectors
 7916: @cindex selectors and stack effects
 7917: In general, it is a good idea to ensure that all methods for the
 7918: same selector have the same stack effect: when you invoke a selector,
 7919: you often have no idea which method will be invoked, so, unless all
 7920: methods have the same stack effect, you will not know the stack effect
 7921: of the selector invocation.
 7922: 
 7923: One exception to this rule is methods for the selector
 7924: @code{construct}. We know which method is invoked, because we
 7925: specify the class to be constructed at the same place. Actually, I
 7926: defined @code{construct} as a selector only to give the users a
 7927: convenient way to specify initialization. The way it is used, a
 7928: mechanism different from selector invocation would be more natural
 7929: (but probably would take more code and more space to explain).
 7930: 
 7931: @node Class Binding, Method conveniences, Object-Oriented Programming Style, Objects
 7932: @subsubsection Class Binding
 7933: @cindex class binding
 7934: @cindex early binding
 7935: 
 7936: @cindex late binding
 7937: Normal selector invocations determine the method at run-time depending
 7938: on the class of the receiving object. This run-time selection is called
 7939: @i{late binding}.
 7940: 
 7941: Sometimes it's preferable to invoke a different method. For example,
 7942: you might want to use the simple method for @code{print}ing
 7943: @code{object}s instead of the possibly long-winded @code{print} method
 7944: of the receiver class. You can achieve this by replacing the invocation
 7945: of @code{print} with:
 7946: 
 7947: @cindex @code{[bind]} usage
 7948: @example
 7949: [bind] object print
 7950: @end example
 7951: 
 7952: @noindent
 7953: in compiled code or:
 7954: 
 7955: @cindex @code{bind} usage
 7956: @example
 7957: bind object print
 7958: @end example
 7959: 
 7960: @cindex class binding, alternative to
 7961: @noindent
 7962: in interpreted code. Alternatively, you can define the method with a
 7963: name (e.g., @code{print-object}), and then invoke it through the
 7964: name. Class binding is just a (often more convenient) way to achieve
 7965: the same effect; it avoids name clutter and allows you to invoke
 7966: methods directly without naming them first.
 7967: 
 7968: @cindex superclass binding
 7969: @cindex parent class binding
 7970: A frequent use of class binding is this: When we define a method
 7971: for a selector, we often want the method to do what the selector does
 7972: in the parent class, and a little more. There is a special word for
 7973: this purpose: @code{[parent]}; @code{[parent]
 7974: @emph{selector}} is equivalent to @code{[bind] @emph{parent
 7975: selector}}, where @code{@emph{parent}} is the parent
 7976: class of the current class. E.g., a method definition might look like:
 7977: 
 7978: @cindex @code{[parent]} usage
 7979: @example
 7980: :noname
 7981:   dup [parent] foo \ do parent's foo on the receiving object
 7982:   ... \ do some more
 7983: ; overrides foo
 7984: @end example
 7985: 
 7986: @cindex class binding as optimization
 7987: In @cite{Object-oriented programming in ANS Forth} (Forth Dimensions,
 7988: March 1997), Andrew McKewan presents class binding as an optimization
 7989: technique. I recommend not using it for this purpose unless you are in
 7990: an emergency. Late binding is pretty fast with this model anyway, so the
 7991: benefit of using class binding is small; the cost of using class binding
 7992: where it is not appropriate is reduced maintainability.
 7993: 
 7994: While we are at programming style questions: You should bind
 7995: selectors only to ancestor classes of the receiving object. E.g., say,
 7996: you know that the receiving object is of class @code{foo} or its
 7997: descendents; then you should bind only to @code{foo} and its
 7998: ancestors.
 7999: 
 8000: @node Method conveniences, Classes and Scoping, Class Binding, Objects
 8001: @subsubsection Method conveniences
 8002: @cindex method conveniences
 8003: 
 8004: In a method you usually access the receiving object pretty often.  If
 8005: you define the method as a plain colon definition (e.g., with
 8006: @code{:noname}), you may have to do a lot of stack
 8007: gymnastics. To avoid this, you can define the method with @code{m:
 8008: ... ;m}. E.g., you could define the method for
 8009: @code{draw}ing a @code{circle} with
 8010: 
 8011: @cindex @code{this} usage
 8012: @cindex @code{m:} usage
 8013: @cindex @code{;m} usage
 8014: @example
 8015: m: ( x y circle -- )
 8016:   ( x y ) this circle-radius @@ draw-circle ;m
 8017: @end example
 8018: 
 8019: @cindex @code{exit} in @code{m: ... ;m}
 8020: @cindex @code{exitm} discussion
 8021: @cindex @code{catch} in @code{m: ... ;m}
 8022: When this method is executed, the receiver object is removed from the
 8023: stack; you can access it with @code{this} (admittedly, in this
 8024: example the use of @code{m: ... ;m} offers no advantage). Note
 8025: that I specify the stack effect for the whole method (i.e. including
 8026: the receiver object), not just for the code between @code{m:}
 8027: and @code{;m}. You cannot use @code{exit} in
 8028: @code{m:...;m}; instead, use
 8029: @code{exitm}.@footnote{Moreover, for any word that calls
 8030: @code{catch} and was defined before loading
 8031: @code{objects.fs}, you have to redefine it like I redefined
 8032: @code{catch}: @code{: catch this >r catch r> to-this ;}}
 8033: 
 8034: @cindex @code{inst-var} usage
 8035: You will frequently use sequences of the form @code{this
 8036: @emph{field}} (in the example above: @code{this
 8037: circle-radius}). If you use the field only in this way, you can
 8038: define it with @code{inst-var} and eliminate the
 8039: @code{this} before the field name. E.g., the @code{circle}
 8040: class above could also be defined with:
 8041: 
 8042: @example
 8043: graphical class
 8044:   cell% inst-var radius
 8045: 
 8046: m: ( x y circle -- )
 8047:   radius @@ draw-circle ;m
 8048: overrides draw
 8049: 
 8050: m: ( n-radius circle -- )
 8051:   radius ! ;m
 8052: overrides construct
 8053: 
 8054: end-class circle
 8055: @end example
 8056: 
 8057: @code{radius} can only be used in @code{circle} and its
 8058: descendent classes and inside @code{m:...;m}.
 8059: 
 8060: @cindex @code{inst-value} usage
 8061: You can also define fields with @code{inst-value}, which is
 8062: to @code{inst-var} what @code{value} is to
 8063: @code{variable}.  You can change the value of such a field with
 8064: @code{[to-inst]}.  E.g., we could also define the class
 8065: @code{circle} like this:
 8066: 
 8067: @example
 8068: graphical class
 8069:   inst-value radius
 8070: 
 8071: m: ( x y circle -- )
 8072:   radius draw-circle ;m
 8073: overrides draw
 8074: 
 8075: m: ( n-radius circle -- )
 8076:   [to-inst] radius ;m
 8077: overrides construct
 8078: 
 8079: end-class circle
 8080: @end example
 8081: 
 8082: Finally, you can define named methods with @code{:m}.  One use of this
 8083: feature is the definition of words that occur only in one class and are
 8084: not intended to be overridden, but which still need method context
 8085: (e.g., for accessing @code{inst-var}s).  Another use is for methods that
 8086: would be bound frequently, if defined anonymously.
 8087: 
 8088: 
 8089: @node Classes and Scoping, Dividing classes, Method conveniences, Objects
 8090: @subsubsection Classes and Scoping
 8091: @cindex classes and scoping
 8092: @cindex scoping and classes
 8093: 
 8094: Inheritance is frequent, unlike structure extension. This exacerbates
 8095: the problem with the field name convention (@pxref{Structure Naming
 8096: Convention}): One always has to remember in which class the field was
 8097: originally defined; changing a part of the class structure would require
 8098: changes for renaming in otherwise unaffected code.
 8099: 
 8100: @cindex @code{inst-var} visibility
 8101: @cindex @code{inst-value} visibility
 8102: To solve this problem, I added a scoping mechanism (which was not in my
 8103: original charter): A field defined with @code{inst-var} (or
 8104: @code{inst-value}) is visible only in the class where it is defined and in
 8105: the descendent classes of this class.  Using such fields only makes
 8106: sense in @code{m:}-defined methods in these classes anyway.
 8107: 
 8108: This scoping mechanism allows us to use the unadorned field name,
 8109: because name clashes with unrelated words become much less likely.
 8110: 
 8111: @cindex @code{protected} discussion
 8112: @cindex @code{private} discussion
 8113: Once we have this mechanism, we can also use it for controlling the
 8114: visibility of other words: All words defined after
 8115: @code{protected} are visible only in the current class and its
 8116: descendents. @code{public} restores the compilation
 8117: (i.e. @code{current}) word list that was in effect before. If you
 8118: have several @code{protected}s without an intervening
 8119: @code{public} or @code{set-current}, @code{public}
 8120: will restore the compilation word list in effect before the first of
 8121: these @code{protected}s.
 8122: 
 8123: @node Dividing classes, Object Interfaces, Classes and Scoping, Objects
 8124: @subsubsection Dividing classes
 8125: @cindex Dividing classes
 8126: @cindex @code{methods}...@code{end-methods}
 8127: 
 8128: You may want to do the definition of methods separate from the
 8129: definition of the class, its selectors, fields, and instance variables,
 8130: i.e., separate the implementation from the definition.  You can do this
 8131: in the following way:
 8132: 
 8133: @example
 8134: graphical class
 8135:   inst-value radius
 8136: end-class circle
 8137: 
 8138: ... \ do some other stuff
 8139: 
 8140: circle methods \ now we are ready
 8141: 
 8142: m: ( x y circle -- )
 8143:   radius draw-circle ;m
 8144: overrides draw
 8145: 
 8146: m: ( n-radius circle -- )
 8147:   [to-inst] radius ;m
 8148: overrides construct
 8149: 
 8150: end-methods
 8151: @end example
 8152: 
 8153: You can use several @code{methods}...@code{end-methods} sections.  The
 8154: only things you can do to the class in these sections are: defining
 8155: methods, and overriding the class's selectors.  You must not define new
 8156: selectors or fields.
 8157: 
 8158: Note that you often have to override a selector before using it.  In
 8159: particular, you usually have to override @code{construct} with a new
 8160: method before you can invoke @code{heap-new} and friends.  E.g., you
 8161: must not create a circle before the @code{overrides construct} sequence
 8162: in the example above.
 8163: 
 8164: @node Object Interfaces, Objects Implementation, Dividing classes, Objects
 8165: @subsubsection Object Interfaces
 8166: @cindex object interfaces
 8167: @cindex interfaces for objects
 8168: 
 8169: In this model you can only call selectors defined in the class of the
 8170: receiving objects or in one of its ancestors. If you call a selector
 8171: with a receiving object that is not in one of these classes, the
 8172: result is undefined; if you are lucky, the program crashes
 8173: immediately.
 8174: 
 8175: @cindex selectors common to hardly-related classes
 8176: Now consider the case when you want to have a selector (or several)
 8177: available in two classes: You would have to add the selector to a
 8178: common ancestor class, in the worst case to @code{object}. You
 8179: may not want to do this, e.g., because someone else is responsible for
 8180: this ancestor class.
 8181: 
 8182: The solution for this problem is interfaces. An interface is a
 8183: collection of selectors. If a class implements an interface, the
 8184: selectors become available to the class and its descendents. A class
 8185: can implement an unlimited number of interfaces. For the problem
 8186: discussed above, we would define an interface for the selector(s), and
 8187: both classes would implement the interface.
 8188: 
 8189: As an example, consider an interface @code{storage} for
 8190: writing objects to disk and getting them back, and a class
 8191: @code{foo} that implements it. The code would look like this:
 8192: 
 8193: @cindex @code{interface} usage
 8194: @cindex @code{end-interface} usage
 8195: @cindex @code{implementation} usage
 8196: @example
 8197: interface
 8198:   selector write ( file object -- )
 8199:   selector read1 ( file object -- )
 8200: end-interface storage
 8201: 
 8202: bar class
 8203:   storage implementation
 8204: 
 8205: ... overrides write
 8206: ... overrides read1
 8207: ...
 8208: end-class foo
 8209: @end example
 8210: 
 8211: @noindent
 8212: (I would add a word @code{read} @i{( file -- object )} that uses
 8213: @code{read1} internally, but that's beyond the point illustrated
 8214: here.)
 8215: 
 8216: Note that you cannot use @code{protected} in an interface; and
 8217: of course you cannot define fields.
 8218: 
 8219: In the Neon model, all selectors are available for all classes;
 8220: therefore it does not need interfaces. The price you pay in this model
 8221: is slower late binding, and therefore, added complexity to avoid late
 8222: binding.
 8223: 
 8224: @node Objects Implementation, Objects Glossary, Object Interfaces, Objects
 8225: @subsubsection @file{objects.fs} Implementation
 8226: @cindex @file{objects.fs} implementation
 8227: 
 8228: @cindex @code{object-map} discussion
 8229: An object is a piece of memory, like one of the data structures
 8230: described with @code{struct...end-struct}. It has a field
 8231: @code{object-map} that points to the method map for the object's
 8232: class.
 8233: 
 8234: @cindex method map
 8235: @cindex virtual function table
 8236: The @emph{method map}@footnote{This is Self terminology; in C++
 8237: terminology: virtual function table.} is an array that contains the
 8238: execution tokens (@i{xt}s) of the methods for the object's class. Each
 8239: selector contains an offset into a method map.
 8240: 
 8241: @cindex @code{selector} implementation, class
 8242: @code{selector} is a defining word that uses
 8243: @code{CREATE} and @code{DOES>}. The body of the
 8244: selector contains the offset; the @code{DOES>} action for a
 8245: class selector is, basically:
 8246: 
 8247: @example
 8248: ( object addr ) @@ over object-map @@ + @@ execute
 8249: @end example
 8250: 
 8251: Since @code{object-map} is the first field of the object, it
 8252: does not generate any code. As you can see, calling a selector has a
 8253: small, constant cost.
 8254: 
 8255: @cindex @code{current-interface} discussion
 8256: @cindex class implementation and representation
 8257: A class is basically a @code{struct} combined with a method
 8258: map. During the class definition the alignment and size of the class
 8259: are passed on the stack, just as with @code{struct}s, so
 8260: @code{field} can also be used for defining class
 8261: fields. However, passing more items on the stack would be
 8262: inconvenient, so @code{class} builds a data structure in memory,
 8263: which is accessed through the variable
 8264: @code{current-interface}. After its definition is complete, the
 8265: class is represented on the stack by a pointer (e.g., as parameter for
 8266: a child class definition).
 8267: 
 8268: A new class starts off with the alignment and size of its parent,
 8269: and a copy of the parent's method map. Defining new fields extends the
 8270: size and alignment; likewise, defining new selectors extends the
 8271: method map. @code{overrides} just stores a new @i{xt} in the method
 8272: map at the offset given by the selector.
 8273: 
 8274: @cindex class binding, implementation
 8275: Class binding just gets the @i{xt} at the offset given by the selector
 8276: from the class's method map and @code{compile,}s (in the case of
 8277: @code{[bind]}) it.
 8278: 
 8279: @cindex @code{this} implementation
 8280: @cindex @code{catch} and @code{this}
 8281: @cindex @code{this} and @code{catch}
 8282: I implemented @code{this} as a @code{value}. At the
 8283: start of an @code{m:...;m} method the old @code{this} is
 8284: stored to the return stack and restored at the end; and the object on
 8285: the TOS is stored @code{TO this}. This technique has one
 8286: disadvantage: If the user does not leave the method via
 8287: @code{;m}, but via @code{throw} or @code{exit},
 8288: @code{this} is not restored (and @code{exit} may
 8289: crash). To deal with the @code{throw} problem, I have redefined
 8290: @code{catch} to save and restore @code{this}; the same
 8291: should be done with any word that can catch an exception. As for
 8292: @code{exit}, I simply forbid it (as a replacement, there is
 8293: @code{exitm}).
 8294: 
 8295: @cindex @code{inst-var} implementation
 8296: @code{inst-var} is just the same as @code{field}, with
 8297: a different @code{DOES>} action:
 8298: @example
 8299: @@ this +
 8300: @end example
 8301: Similar for @code{inst-value}.
 8302: 
 8303: @cindex class scoping implementation
 8304: Each class also has a word list that contains the words defined with
 8305: @code{inst-var} and @code{inst-value}, and its protected
 8306: words. It also has a pointer to its parent. @code{class} pushes
 8307: the word lists of the class and all its ancestors onto the search order stack,
 8308: and @code{end-class} drops them.
 8309: 
 8310: @cindex interface implementation
 8311: An interface is like a class without fields, parent and protected
 8312: words; i.e., it just has a method map. If a class implements an
 8313: interface, its method map contains a pointer to the method map of the
 8314: interface. The positive offsets in the map are reserved for class
 8315: methods, therefore interface map pointers have negative
 8316: offsets. Interfaces have offsets that are unique throughout the
 8317: system, unlike class selectors, whose offsets are only unique for the
 8318: classes where the selector is available (invokable).
 8319: 
 8320: This structure means that interface selectors have to perform one
 8321: indirection more than class selectors to find their method. Their body
 8322: contains the interface map pointer offset in the class method map, and
 8323: the method offset in the interface method map. The
 8324: @code{does>} action for an interface selector is, basically:
 8325: 
 8326: @example
 8327: ( object selector-body )
 8328: 2dup selector-interface @@ ( object selector-body object interface-offset )
 8329: swap object-map @@ + @@ ( object selector-body map )
 8330: swap selector-offset @@ + @@ execute
 8331: @end example
 8332: 
 8333: where @code{object-map} and @code{selector-offset} are
 8334: first fields and generate no code.
 8335: 
 8336: As a concrete example, consider the following code:
 8337: 
 8338: @example
 8339: interface
 8340:   selector if1sel1
 8341:   selector if1sel2
 8342: end-interface if1
 8343: 
 8344: object class
 8345:   if1 implementation
 8346:   selector cl1sel1
 8347:   cell% inst-var cl1iv1
 8348: 
 8349: ' m1 overrides construct
 8350: ' m2 overrides if1sel1
 8351: ' m3 overrides if1sel2
 8352: ' m4 overrides cl1sel2
 8353: end-class cl1
 8354: 
 8355: create obj1 object dict-new drop
 8356: create obj2 cl1    dict-new drop
 8357: @end example
 8358: 
 8359: The data structure created by this code (including the data structure
 8360: for @code{object}) is shown in the <a
 8361: href="objects-implementation.eps">figure</a>, assuming a cell size of 4.
 8362: @comment TODO add this diagram..
 8363: 
 8364: @node Objects Glossary,  , Objects Implementation, Objects
 8365: @subsubsection @file{objects.fs} Glossary
 8366: @cindex @file{objects.fs} Glossary
 8367: 
 8368: 
 8369: doc---objects-bind
 8370: doc---objects-<bind>
 8371: doc---objects-bind'
 8372: doc---objects-[bind]
 8373: doc---objects-class
 8374: doc---objects-class->map
 8375: doc---objects-class-inst-size
 8376: doc---objects-class-override!
 8377: doc---objects-construct
 8378: doc---objects-current'
 8379: doc---objects-[current]
 8380: doc---objects-current-interface
 8381: doc---objects-dict-new
 8382: doc---objects-drop-order
 8383: doc---objects-end-class
 8384: doc---objects-end-class-noname
 8385: doc---objects-end-interface
 8386: doc---objects-end-interface-noname
 8387: doc---objects-end-methods
 8388: doc---objects-exitm
 8389: doc---objects-heap-new
 8390: doc---objects-implementation
 8391: doc---objects-init-object
 8392: doc---objects-inst-value
 8393: doc---objects-inst-var
 8394: doc---objects-interface
 8395: doc---objects-m:
 8396: doc---objects-:m
 8397: doc---objects-;m
 8398: doc---objects-method
 8399: doc---objects-methods
 8400: doc---objects-object
 8401: doc---objects-overrides
 8402: doc---objects-[parent]
 8403: doc---objects-print
 8404: doc---objects-protected
 8405: doc---objects-public
 8406: doc---objects-push-order
 8407: doc---objects-selector
 8408: doc---objects-this
 8409: doc---objects-<to-inst>
 8410: doc---objects-[to-inst]
 8411: doc---objects-to-this
 8412: doc---objects-xt-new
 8413: 
 8414: 
 8415: @c -------------------------------------------------------------
 8416: @node OOF, Mini-OOF, Objects, Object-oriented Forth
 8417: @subsection The @file{oof.fs} model
 8418: @cindex oof
 8419: @cindex object-oriented programming
 8420: 
 8421: @cindex @file{objects.fs}
 8422: @cindex @file{oof.fs}
 8423: 
 8424: This section describes the @file{oof.fs} package.
 8425: 
 8426: The package described in this section has been used in bigFORTH since 1991, and
 8427: used for two large applications: a chromatographic system used to
 8428: create new medicaments, and a graphic user interface library (MINOS).
 8429: 
 8430: You can find a description (in German) of @file{oof.fs} in @cite{Object
 8431: oriented bigFORTH} by Bernd Paysan, published in @cite{Vierte Dimension}
 8432: 10(2), 1994.
 8433: 
 8434: @menu
 8435: * Properties of the OOF model::
 8436: * Basic OOF Usage::
 8437: * The OOF base class::
 8438: * Class Declaration::
 8439: * Class Implementation::
 8440: @end menu
 8441: 
 8442: @node Properties of the OOF model, Basic OOF Usage, OOF, OOF
 8443: @subsubsection Properties of the @file{oof.fs} model
 8444: @cindex @file{oof.fs} properties
 8445: 
 8446: @itemize @bullet
 8447: @item
 8448: This model combines object oriented programming with information
 8449: hiding. It helps you writing large application, where scoping is
 8450: necessary, because it provides class-oriented scoping.
 8451: 
 8452: @item
 8453: Named objects, object pointers, and object arrays can be created,
 8454: selector invocation uses the ``object selector'' syntax. Selector invocation
 8455: to objects and/or selectors on the stack is a bit less convenient, but
 8456: possible.
 8457: 
 8458: @item
 8459: Selector invocation and instance variable usage of the active object is
 8460: straightforward, since both make use of the active object.
 8461: 
 8462: @item
 8463: Late binding is efficient and easy to use.
 8464: 
 8465: @item
 8466: State-smart objects parse selectors. However, extensibility is provided
 8467: using a (parsing) selector @code{postpone} and a selector @code{'}.
 8468: 
 8469: @item
 8470: An implementation in ANS Forth is available.
 8471: 
 8472: @end itemize
 8473: 
 8474: 
 8475: @node Basic OOF Usage, The OOF base class, Properties of the OOF model, OOF
 8476: @subsubsection Basic @file{oof.fs} Usage
 8477: @cindex @file{oof.fs} usage
 8478: 
 8479: This section uses the same example as for @code{objects} (@pxref{Basic Objects Usage}).
 8480: 
 8481: You can define a class for graphical objects like this:
 8482: 
 8483: @cindex @code{class} usage
 8484: @cindex @code{class;} usage
 8485: @cindex @code{method} usage
 8486: @example
 8487: object class graphical \ "object" is the parent class
 8488:   method draw ( x y graphical -- )
 8489: class;
 8490: @end example
 8491: 
 8492: This code defines a class @code{graphical} with an
 8493: operation @code{draw}.  We can perform the operation
 8494: @code{draw} on any @code{graphical} object, e.g.:
 8495: 
 8496: @example
 8497: 100 100 t-rex draw
 8498: @end example
 8499: 
 8500: @noindent
 8501: where @code{t-rex} is an object or object pointer, created with e.g.
 8502: @code{graphical : t-rex}.
 8503: 
 8504: @cindex abstract class
 8505: How do we create a graphical object? With the present definitions,
 8506: we cannot create a useful graphical object. The class
 8507: @code{graphical} describes graphical objects in general, but not
 8508: any concrete graphical object type (C++ users would call it an
 8509: @emph{abstract class}); e.g., there is no method for the selector
 8510: @code{draw} in the class @code{graphical}.
 8511: 
 8512: For concrete graphical objects, we define child classes of the
 8513: class @code{graphical}, e.g.:
 8514: 
 8515: @example
 8516: graphical class circle \ "graphical" is the parent class
 8517:   cell var circle-radius
 8518: how:
 8519:   : draw ( x y -- )
 8520:     circle-radius @@ draw-circle ;
 8521: 
 8522:   : init ( n-radius -- (
 8523:     circle-radius ! ;
 8524: class;
 8525: @end example
 8526: 
 8527: Here we define a class @code{circle} as a child of @code{graphical},
 8528: with a field @code{circle-radius}; it defines new methods for the
 8529: selectors @code{draw} and @code{init} (@code{init} is defined in
 8530: @code{object}, the parent class of @code{graphical}).
 8531: 
 8532: Now we can create a circle in the dictionary with:
 8533: 
 8534: @example
 8535: 50 circle : my-circle
 8536: @end example
 8537: 
 8538: @noindent
 8539: @code{:} invokes @code{init}, thus initializing the field
 8540: @code{circle-radius} with 50. We can draw this new circle at (100,100)
 8541: with:
 8542: 
 8543: @example
 8544: 100 100 my-circle draw
 8545: @end example
 8546: 
 8547: @cindex selector invocation, restrictions
 8548: @cindex class definition, restrictions
 8549: Note: You can only invoke a selector if the receiving object belongs to
 8550: the class where the selector was defined or one of its descendents;
 8551: e.g., you can invoke @code{draw} only for objects belonging to
 8552: @code{graphical} or its descendents (e.g., @code{circle}). The scoping
 8553: mechanism will check if you try to invoke a selector that is not
 8554: defined in this class hierarchy, so you'll get an error at compilation
 8555: time.
 8556: 
 8557: 
 8558: @node The OOF base class, Class Declaration, Basic OOF Usage, OOF
 8559: @subsubsection The @file{oof.fs} base class
 8560: @cindex @file{oof.fs} base class
 8561: 
 8562: When you define a class, you have to specify a parent class.  So how do
 8563: you start defining classes? There is one class available from the start:
 8564: @code{object}. You have to use it as ancestor for all classes. It is the
 8565: only class that has no parent. Classes are also objects, except that
 8566: they don't have instance variables; class manipulation such as
 8567: inheritance or changing definitions of a class is handled through
 8568: selectors of the class @code{object}.
 8569: 
 8570: @code{object} provides a number of selectors:
 8571: 
 8572: @itemize @bullet
 8573: @item
 8574: @code{class} for subclassing, @code{definitions} to add definitions
 8575: later on, and @code{class?} to get type informations (is the class a
 8576: subclass of the class passed on the stack?).
 8577: 
 8578: doc---object-class
 8579: doc---object-definitions
 8580: doc---object-class?
 8581: 
 8582: 
 8583: @item
 8584: @code{init} and @code{dispose} as constructor and destructor of the
 8585: object. @code{init} is invocated after the object's memory is allocated,
 8586: while @code{dispose} also handles deallocation. Thus if you redefine
 8587: @code{dispose}, you have to call the parent's dispose with @code{super
 8588: dispose}, too.
 8589: 
 8590: doc---object-init
 8591: doc---object-dispose
 8592: 
 8593: 
 8594: @item
 8595: @code{new}, @code{new[]}, @code{:}, @code{ptr}, @code{asptr}, and
 8596: @code{[]} to create named and unnamed objects and object arrays or
 8597: object pointers.
 8598: 
 8599: doc---object-new
 8600: doc---object-new[]
 8601: doc---object-:
 8602: doc---object-ptr
 8603: doc---object-asptr
 8604: doc---object-[]
 8605: 
 8606: 
 8607: @item
 8608: @code{::} and @code{super} for explicit scoping. You should use explicit
 8609: scoping only for super classes or classes with the same set of instance
 8610: variables. Explicitly-scoped selectors use early binding.
 8611: 
 8612: doc---object-::
 8613: doc---object-super
 8614: 
 8615: 
 8616: @item
 8617: @code{self} to get the address of the object
 8618: 
 8619: doc---object-self
 8620: 
 8621: 
 8622: @item
 8623: @code{bind}, @code{bound}, @code{link}, and @code{is} to assign object
 8624: pointers and instance defers.
 8625: 
 8626: doc---object-bind
 8627: doc---object-bound
 8628: doc---object-link
 8629: doc---object-is
 8630: 
 8631: 
 8632: @item
 8633: @code{'} to obtain selector tokens, @code{send} to invocate selectors
 8634: form the stack, and @code{postpone} to generate selector invocation code.
 8635: 
 8636: doc---object-'
 8637: doc---object-postpone
 8638: 
 8639: 
 8640: @item
 8641: @code{with} and @code{endwith} to select the active object from the
 8642: stack, and enable its scope. Using @code{with} and @code{endwith}
 8643: also allows you to create code using selector @code{postpone} without being
 8644: trapped by the state-smart objects.
 8645: 
 8646: doc---object-with
 8647: doc---object-endwith
 8648: 
 8649: 
 8650: @end itemize
 8651: 
 8652: @node Class Declaration, Class Implementation, The OOF base class, OOF
 8653: @subsubsection Class Declaration
 8654: @cindex class declaration
 8655: 
 8656: @itemize @bullet
 8657: @item
 8658: Instance variables
 8659: 
 8660: doc---oof-var
 8661: 
 8662: 
 8663: @item
 8664: Object pointers
 8665: 
 8666: doc---oof-ptr
 8667: doc---oof-asptr
 8668: 
 8669: 
 8670: @item
 8671: Instance defers
 8672: 
 8673: doc---oof-defer
 8674: 
 8675: 
 8676: @item
 8677: Method selectors
 8678: 
 8679: doc---oof-early
 8680: doc---oof-method
 8681: 
 8682: 
 8683: @item
 8684: Class-wide variables
 8685: 
 8686: doc---oof-static
 8687: 
 8688: 
 8689: @item
 8690: End declaration
 8691: 
 8692: doc---oof-how:
 8693: doc---oof-class;
 8694: 
 8695: 
 8696: @end itemize
 8697: 
 8698: @c -------------------------------------------------------------
 8699: @node Class Implementation,  , Class Declaration, OOF
 8700: @subsubsection Class Implementation
 8701: @cindex class implementation
 8702: 
 8703: @c -------------------------------------------------------------
 8704: @node Mini-OOF, Comparison with other object models, OOF, Object-oriented Forth
 8705: @subsection The @file{mini-oof.fs} model
 8706: @cindex mini-oof
 8707: 
 8708: Gforth's third object oriented Forth package is a 12-liner. It uses a
 8709: mixture of the @file{object.fs} and the @file{oof.fs} syntax,
 8710: and reduces to the bare minimum of features. This is based on a posting
 8711: of Bernd Paysan in comp.arch.
 8712: 
 8713: @menu
 8714: * Basic Mini-OOF Usage::
 8715: * Mini-OOF Example::
 8716: * Mini-OOF Implementation::
 8717: @end menu
 8718: 
 8719: @c -------------------------------------------------------------
 8720: @node Basic Mini-OOF Usage, Mini-OOF Example, , Mini-OOF
 8721: @subsubsection Basic @file{mini-oof.fs} Usage
 8722: @cindex mini-oof usage
 8723: 
 8724: There is a base class (@code{class}, which allocates one cell for the
 8725: object pointer) plus seven other words: to define a method, a variable,
 8726: a class; to end a class, to resolve binding, to allocate an object and
 8727: to compile a class method.
 8728: @comment TODO better description of the last one
 8729: 
 8730: 
 8731: doc-object
 8732: doc-method
 8733: doc-var
 8734: doc-class
 8735: doc-end-class
 8736: doc-defines
 8737: doc-new
 8738: doc-::
 8739: 
 8740: 
 8741: 
 8742: @c -------------------------------------------------------------
 8743: @node Mini-OOF Example, Mini-OOF Implementation, Basic Mini-OOF Usage, Mini-OOF
 8744: @subsubsection Mini-OOF Example
 8745: @cindex mini-oof example
 8746: 
 8747: A short example shows how to use this package. This example, in slightly
 8748: extended form, is supplied as @file{moof-exm.fs}
 8749: @comment TODO could flesh this out with some comments from the Forthwrite article
 8750: 
 8751: @example
 8752: object class
 8753:   method init
 8754:   method draw
 8755: end-class graphical
 8756: @end example
 8757: 
 8758: This code defines a class @code{graphical} with an
 8759: operation @code{draw}.  We can perform the operation
 8760: @code{draw} on any @code{graphical} object, e.g.:
 8761: 
 8762: @example
 8763: 100 100 t-rex draw
 8764: @end example
 8765: 
 8766: where @code{t-rex} is an object or object pointer, created with e.g.
 8767: @code{graphical new Constant t-rex}.
 8768: 
 8769: For concrete graphical objects, we define child classes of the
 8770: class @code{graphical}, e.g.:
 8771: 
 8772: @example
 8773: graphical class
 8774:   cell var circle-radius
 8775: end-class circle \ "graphical" is the parent class
 8776: 
 8777: :noname ( x y -- )
 8778:   circle-radius @@ draw-circle ; circle defines draw
 8779: :noname ( r -- )
 8780:   circle-radius ! ; circle defines init
 8781: @end example
 8782: 
 8783: There is no implicit init method, so we have to define one. The creation
 8784: code of the object now has to call init explicitely.
 8785: 
 8786: @example
 8787: circle new Constant my-circle
 8788: 50 my-circle init
 8789: @end example
 8790: 
 8791: It is also possible to add a function to create named objects with
 8792: automatic call of @code{init}, given that all objects have @code{init}
 8793: on the same place:
 8794: 
 8795: @example
 8796: : new: ( .. o "name" -- )
 8797:     new dup Constant init ;
 8798: 80 circle new: large-circle
 8799: @end example
 8800: 
 8801: We can draw this new circle at (100,100) with:
 8802: 
 8803: @example
 8804: 100 100 my-circle draw
 8805: @end example
 8806: 
 8807: @node Mini-OOF Implementation, , Mini-OOF Example, Mini-OOF
 8808: @subsubsection @file{mini-oof.fs} Implementation
 8809: 
 8810: Object-oriented systems with late binding typically use a
 8811: ``vtable''-approach: the first variable in each object is a pointer to a
 8812: table, which contains the methods as function pointers. The vtable
 8813: may also contain other information.
 8814: 
 8815: So first, let's declare methods:
 8816: 
 8817: @example
 8818: : method ( m v -- m' v ) Create  over , swap cell+ swap
 8819:   DOES> ( ... o -- ... ) @ over @ + @ execute ;
 8820: @end example
 8821: 
 8822: During method declaration, the number of methods and instance
 8823: variables is on the stack (in address units). @code{method} creates
 8824: one method and increments the method number. To execute a method, it
 8825: takes the object, fetches the vtable pointer, adds the offset, and
 8826: executes the @i{xt} stored there. Each method takes the object it is
 8827: invoked from as top of stack parameter. The method itself should
 8828: consume that object.
 8829: 
 8830: Now, we also have to declare instance variables
 8831: 
 8832: @example
 8833: : var ( m v size -- m v' ) Create  over , +
 8834:   DOES> ( o -- addr ) @ + ;
 8835: @end example
 8836: 
 8837: As before, a word is created with the current offset. Instance
 8838: variables can have different sizes (cells, floats, doubles, chars), so
 8839: all we do is take the size and add it to the offset. If your machine
 8840: has alignment restrictions, put the proper @code{aligned} or
 8841: @code{faligned} before the variable, to adjust the variable
 8842: offset. That's why it is on the top of stack.
 8843: 
 8844: We need a starting point (the base object) and some syntactic sugar:
 8845: 
 8846: @example
 8847: Create object  1 cells , 2 cells ,
 8848: : class ( class -- class methods vars ) dup 2@ ;
 8849: @end example
 8850: 
 8851: For inheritance, the vtable of the parent object has to be
 8852: copied when a new, derived class is declared. This gives all the
 8853: methods of the parent class, which can be overridden, though.
 8854: 
 8855: @example
 8856: : end-class  ( class methods vars -- )
 8857:   Create  here >r , dup , 2 cells ?DO ['] noop , 1 cells +LOOP
 8858:   cell+ dup cell+ r> rot @ 2 cells /string move ;
 8859: @end example
 8860: 
 8861: The first line creates the vtable, initialized with
 8862: @code{noop}s. The second line is the inheritance mechanism, it
 8863: copies the xts from the parent vtable.
 8864: 
 8865: We still have no way to define new methods, let's do that now:
 8866: 
 8867: @example
 8868: : defines ( xt class -- ) ' >body @ + ! ;
 8869: @end example
 8870: 
 8871: To allocate a new object, we need a word, too:
 8872: 
 8873: @example
 8874: : new ( class -- o )  here over @ allot swap over ! ;
 8875: @end example
 8876: 
 8877: Sometimes derived classes want to access the method of the
 8878: parent object. There are two ways to achieve this with Mini-OOF:
 8879: first, you could use named words, and second, you could look up the
 8880: vtable of the parent object.
 8881: 
 8882: @example
 8883: : :: ( class "name" -- ) ' >body @ + @ compile, ;
 8884: @end example
 8885: 
 8886: 
 8887: Nothing can be more confusing than a good example, so here is
 8888: one. First let's declare a text object (called
 8889: @code{button}), that stores text and position:
 8890: 
 8891: @example
 8892: object class
 8893:   cell var text
 8894:   cell var len
 8895:   cell var x
 8896:   cell var y
 8897:   method init
 8898:   method draw
 8899: end-class button
 8900: @end example
 8901: 
 8902: @noindent
 8903: Now, implement the two methods, @code{draw} and @code{init}:
 8904: 
 8905: @example
 8906: :noname ( o -- )
 8907:  >r r@ x @ r@ y @ at-xy  r@ text @ r> len @ type ;
 8908:  button defines draw
 8909: :noname ( addr u o -- )
 8910:  >r 0 r@ x ! 0 r@ y ! r@ len ! r> text ! ;
 8911:  button defines init
 8912: @end example
 8913: 
 8914: @noindent
 8915: To demonstrate inheritance, we define a class @code{bold-button}, with no
 8916: new data and no new methods:
 8917: 
 8918: @example
 8919: button class
 8920: end-class bold-button
 8921: 
 8922: : bold   27 emit ." [1m" ;
 8923: : normal 27 emit ." [0m" ;
 8924: @end example
 8925: 
 8926: @noindent
 8927: The class @code{bold-button} has a different draw method to
 8928: @code{button}, but the new method is defined in terms of the draw method
 8929: for @code{button}:
 8930: 
 8931: @example
 8932: :noname bold [ button :: draw ] normal ; bold-button defines draw
 8933: @end example
 8934: 
 8935: @noindent
 8936: Finally, create two objects and apply methods:
 8937: 
 8938: @example
 8939: button new Constant foo
 8940: s" thin foo" foo init
 8941: page
 8942: foo draw
 8943: bold-button new Constant bar
 8944: s" fat bar" bar init
 8945: 1 bar y !
 8946: bar draw
 8947: @end example
 8948: 
 8949: 
 8950: @node Comparison with other object models, , Mini-OOF, Object-oriented Forth
 8951: @subsubsection Comparison with other object models
 8952: @cindex comparison of object models
 8953: @cindex object models, comparison
 8954: 
 8955: Many object-oriented Forth extensions have been proposed (@cite{A survey
 8956: of object-oriented Forths} (SIGPLAN Notices, April 1996) by Bradford
 8957: J. Rodriguez and W. F. S. Poehlman lists 17). This section discusses the
 8958: relation of the object models described here to two well-known and two
 8959: closely-related (by the use of method maps) models.
 8960: 
 8961: @cindex Neon model
 8962: The most popular model currently seems to be the Neon model (see
 8963: @cite{Object-oriented programming in ANS Forth} (Forth Dimensions, March
 8964: 1997) by Andrew McKewan) but this model has a number of limitations
 8965: @footnote{A longer version of this critique can be
 8966: found in @cite{On Standardizing Object-Oriented Forth Extensions} (Forth
 8967: Dimensions, May 1997) by Anton Ertl.}:
 8968: 
 8969: @itemize @bullet
 8970: @item
 8971: It uses a @code{@emph{selector
 8972: object}} syntax, which makes it unnatural to pass objects on the
 8973: stack.
 8974: 
 8975: @item
 8976: It requires that the selector parses the input stream (at
 8977: compile time); this leads to reduced extensibility and to bugs that are+
 8978: hard to find.
 8979: 
 8980: @item
 8981: It allows using every selector to every object;
 8982: this eliminates the need for classes, but makes it harder to create
 8983: efficient implementations. 
 8984: @end itemize
 8985: 
 8986: @cindex Pountain's object-oriented model
 8987: Another well-known publication is @cite{Object-Oriented Forth} (Academic
 8988: Press, London, 1987) by Dick Pountain. However, it is not really about
 8989: object-oriented programming, because it hardly deals with late
 8990: binding. Instead, it focuses on features like information hiding and
 8991: overloading that are characteristic of modular languages like Ada (83).
 8992: 
 8993: @cindex Zsoter's object-oriented model
 8994: In @cite{Does late binding have to be slow?} (Forth Dimensions 18(1) 1996, pages 31-35)
 8995: Andras Zsoter describes a model that makes heavy use of an active object
 8996: (like @code{this} in @file{objects.fs}): The active object is not only
 8997: used for accessing all fields, but also specifies the receiving object
 8998: of every selector invocation; you have to change the active object
 8999: explicitly with @code{@{ ... @}}, whereas in @file{objects.fs} it
 9000: changes more or less implicitly at @code{m: ... ;m}. Such a change at
 9001: the method entry point is unnecessary with the Zsoter's model, because
 9002: the receiving object is the active object already. On the other hand, the explicit
 9003: change is absolutely necessary in that model, because otherwise no one
 9004: could ever change the active object. An ANS Forth implementation of this
 9005: model is available at @uref{http://www.forth.org/fig/oopf.html}.
 9006: 
 9007: @cindex @file{oof.fs}, differences to other models
 9008: The @file{oof.fs} model combines information hiding and overloading
 9009: resolution (by keeping names in various word lists) with object-oriented
 9010: programming. It sets the active object implicitly on method entry, but
 9011: also allows explicit changing (with @code{>o...o>} or with
 9012: @code{with...endwith}). It uses parsing and state-smart objects and
 9013: classes for resolving overloading and for early binding: the object or
 9014: class parses the selector and determines the method from this. If the
 9015: selector is not parsed by an object or class, it performs a call to the
 9016: selector for the active object (late binding), like Zsoter's model.
 9017: Fields are always accessed through the active object. The big
 9018: disadvantage of this model is the parsing and the state-smartness, which
 9019: reduces extensibility and increases the opportunities for subtle bugs;
 9020: essentially, you are only safe if you never tick or @code{postpone} an
 9021: object or class (Bernd disagrees, but I (Anton) am not convinced).
 9022: 
 9023: @cindex @file{mini-oof.fs}, differences to other models
 9024: The @file{mini-oof.fs} model is quite similar to a very stripped-down version of
 9025: the @file{objects.fs} model, but syntactically it is a mixture of the @file{objects.fs} and
 9026: @file{oof.fs} models.
 9027: 
 9028: @c -------------------------------------------------------------
 9029: @node Passing Commands to the OS, Keeping track of Time, Object-oriented Forth, Words
 9030: @section Passing Commands to the Operating System
 9031: @cindex operating system - passing commands
 9032: @cindex shell commands
 9033: 
 9034: Gforth allows you to pass an arbitrary string to the host operating
 9035: system shell (if such a thing exists) for execution.
 9036: 
 9037: 
 9038: doc-sh
 9039: doc-system
 9040: doc-$?
 9041: doc-getenv
 9042: 
 9043: 
 9044: @c -------------------------------------------------------------
 9045: @node Keeping track of Time, Miscellaneous Words, Passing Commands to the OS, Words
 9046: @section Keeping track of Time
 9047: @cindex time-related words
 9048: 
 9049: Gforth implements time-related operations by making calls to the C
 9050: library function, @code{gettimeofday}.
 9051: 
 9052: doc-ms
 9053: doc-time&date
 9054: 
 9055: 
 9056: 
 9057: @c -------------------------------------------------------------
 9058: @node Miscellaneous Words,  , Keeping track of Time, Words
 9059: @section Miscellaneous Words
 9060: @cindex miscellaneous words
 9061: 
 9062: @comment TODO find homes for these
 9063: 
 9064: These section lists the ANS Forth words that are not documented
 9065: elsewhere in this manual. Ultimately, they all need proper homes.
 9066: 
 9067: doc-[compile]
 9068: 
 9069: 
 9070: The following ANS Forth words are not currently supported by Gforth 
 9071: (@pxref{ANS conformance}):
 9072: 
 9073: @code{EDITOR} 
 9074: @code{EMIT?} 
 9075: @code{FORGET} 
 9076: 
 9077: @c ******************************************************************
 9078: @node Error messages, Tools, Words, Top
 9079: @chapter Error messages
 9080: @cindex error messages
 9081: @cindex backtrace
 9082: 
 9083: A typical Gforth error message looks like this:
 9084: 
 9085: @example
 9086: in file included from :-1
 9087: in file included from ./yyy.fs:1
 9088: ./xxx.fs:4: Invalid memory address
 9089: bar
 9090: ^^^
 9091: $400E664C @@
 9092: $400E6664 foo
 9093: @end example
 9094: 
 9095: The message identifying the error is @code{Invalid memory address}.  The
 9096: error happened when text-interpreting line 4 of the file
 9097: @file{./xxx.fs}. This line is given (it contains @code{bar}), and the
 9098: word on the line where the error happened, is pointed out (with
 9099: @code{^^^}).
 9100: 
 9101: The file containing the error was included in line 1 of @file{./yyy.fs},
 9102: and @file{yyy.fs} was included from a non-file (in this case, by giving
 9103: @file{yyy.fs} as command-line parameter to Gforth).
 9104: 
 9105: At the end of the error message you find a return stack dump that can be
 9106: interpreted as a backtrace (possibly empty). On top you find the top of
 9107: the return stack when the @code{throw} happened, and at the bottom you
 9108: find the return stack entry just above the return stack of the topmost
 9109: text interpreter.
 9110: 
 9111: To the right of most return stack entries you see a guess for the word
 9112: that pushed that return stack entry as its return address. This gives a
 9113: backtrace. In our case we see that @code{bar} called @code{foo}, and
 9114: @code{foo} called @code{@@} (and @code{@@} had an @emph{Invalid memory
 9115: address} exception).
 9116: 
 9117: Note that the backtrace is not perfect: We don't know which return stack
 9118: entries are return addresses (so we may get false positives); and in
 9119: some cases (e.g., for @code{abort"}) we cannot determine from the return
 9120: address the word that pushed the return address, so for some return
 9121: addresses you see no names in the return stack dump.
 9122: 
 9123: @cindex @code{catch} and backtraces
 9124: The return stack dump represents the return stack at the time when a
 9125: specific @code{throw} was executed.  In programs that make use of
 9126: @code{catch}, it is not necessarily clear which @code{throw} should be
 9127: used for the return stack dump (e.g., consider one @code{throw} that
 9128: indicates an error, which is caught, and during recovery another error
 9129: happens; which @code{throw} should be used for the stack dump?).  Gforth
 9130: presents the return stack dump for the first @code{throw} after the last
 9131: executed (not returned-to) @code{catch}; this works well in the usual
 9132: case.
 9133: 
 9134: @cindex @code{gforth-fast} and backtraces
 9135: @cindex @code{gforth-fast}, difference from @code{gforth}
 9136: @cindex backtraces with @code{gforth-fast}
 9137: @cindex return stack dump with @code{gforth-fast}
 9138: @code{gforth} is able to do a return stack dump for throws generated
 9139: from primitives (e.g., invalid memory address, stack empty etc.);
 9140: @code{gforth-fast} is only able to do a return stack dump from a
 9141: directly called @code{throw} (including @code{abort} etc.).  This is the
 9142: only difference (apart from a speed factor of between 1.15 (K6-2) and
 9143: 1.6 (21164A)) between @code{gforth} and @code{gforth-fast}.  Given an
 9144: exception caused by a primitive in @code{gforth-fast}, you will
 9145: typically see no return stack dump at all; however, if the exception is
 9146: caught by @code{catch} (e.g., for restoring some state), and then
 9147: @code{throw}n again, the return stack dump will be for the first such
 9148: @code{throw}.
 9149: 
 9150: @c ******************************************************************
 9151: @node Tools, ANS conformance, Error messages, Top
 9152: @chapter Tools
 9153: 
 9154: @menu
 9155: * ANS Report::                  Report the words used, sorted by wordset.
 9156: @end menu
 9157: 
 9158: See also @ref{Emacs and Gforth}.
 9159: 
 9160: @node ANS Report,  , Tools, Tools
 9161: @section @file{ans-report.fs}: Report the words used, sorted by wordset
 9162: @cindex @file{ans-report.fs}
 9163: @cindex report the words used in your program
 9164: @cindex words used in your program
 9165: 
 9166: If you want to label a Forth program as ANS Forth Program, you must
 9167: document which wordsets the program uses; for extension wordsets, it is
 9168: helpful to list the words the program requires from these wordsets
 9169: (because Forth systems are allowed to provide only some words of them).
 9170: 
 9171: The @file{ans-report.fs} tool makes it easy for you to determine which
 9172: words from which wordset and which non-ANS words your application
 9173: uses. You simply have to include @file{ans-report.fs} before loading the
 9174: program you want to check. After loading your program, you can get the
 9175: report with @code{print-ans-report}. A typical use is to run this as
 9176: batch job like this:
 9177: @example
 9178: gforth ans-report.fs myprog.fs -e "print-ans-report bye"
 9179: @end example
 9180: 
 9181: The output looks like this (for @file{compat/control.fs}):
 9182: @example
 9183: The program uses the following words
 9184: from CORE :
 9185: : POSTPONE THEN ; immediate ?dup IF 0= 
 9186: from BLOCK-EXT :
 9187: \ 
 9188: from FILE :
 9189: ( 
 9190: @end example
 9191: 
 9192: @subsection Caveats
 9193: 
 9194: Note that @file{ans-report.fs} just checks which words are used, not whether
 9195: they are used in an ANS Forth conforming way!
 9196: 
 9197: Some words are defined in several wordsets in the
 9198: standard. @file{ans-report.fs} reports them for only one of the
 9199: wordsets, and not necessarily the one you expect. It depends on usage
 9200: which wordset is the right one to specify. E.g., if you only use the
 9201: compilation semantics of @code{S"}, it is a Core word; if you also use
 9202: its interpretation semantics, it is a File word.
 9203: 
 9204: @c ******************************************************************
 9205: @node ANS conformance, Model, Tools, Top
 9206: @chapter ANS conformance
 9207: @cindex ANS conformance of Gforth
 9208: 
 9209: To the best of our knowledge, Gforth is an
 9210: 
 9211: ANS Forth System
 9212: @itemize @bullet
 9213: @item providing the Core Extensions word set
 9214: @item providing the Block word set
 9215: @item providing the Block Extensions word set
 9216: @item providing the Double-Number word set
 9217: @item providing the Double-Number Extensions word set
 9218: @item providing the Exception word set
 9219: @item providing the Exception Extensions word set
 9220: @item providing the Facility word set
 9221: @item providing @code{EKEY}, @code{EKEY>CHAR}, @code{EKEY?}, @code{MS} and @code{TIME&DATE} from the Facility Extensions word set
 9222: @item providing the File Access word set
 9223: @item providing the File Access Extensions word set
 9224: @item providing the Floating-Point word set
 9225: @item providing the Floating-Point Extensions word set
 9226: @item providing the Locals word set
 9227: @item providing the Locals Extensions word set
 9228: @item providing the Memory-Allocation word set
 9229: @item providing the Memory-Allocation Extensions word set (that one's easy)
 9230: @item providing the Programming-Tools word set
 9231: @item providing @code{;CODE}, @code{AHEAD}, @code{ASSEMBLER}, @code{BYE}, @code{CODE}, @code{CS-PICK}, @code{CS-ROLL}, @code{STATE}, @code{[ELSE]}, @code{[IF]}, @code{[THEN]} from the Programming-Tools Extensions word set
 9232: @item providing the Search-Order word set
 9233: @item providing the Search-Order Extensions word set
 9234: @item providing the String word set
 9235: @item providing the String Extensions word set (another easy one)
 9236: @end itemize
 9237: 
 9238: @cindex system documentation
 9239: In addition, ANS Forth systems are required to document certain
 9240: implementation choices. This chapter tries to meet these
 9241: requirements. In many cases it gives a way to ask the system for the
 9242: information instead of providing the information directly, in
 9243: particular, if the information depends on the processor, the operating
 9244: system or the installation options chosen, or if they are likely to
 9245: change during the maintenance of Gforth.
 9246: 
 9247: @comment The framework for the rest has been taken from pfe.
 9248: 
 9249: @menu
 9250: * The Core Words::              
 9251: * The optional Block word set::  
 9252: * The optional Double Number word set::  
 9253: * The optional Exception word set::  
 9254: * The optional Facility word set::  
 9255: * The optional File-Access word set::  
 9256: * The optional Floating-Point word set::  
 9257: * The optional Locals word set::  
 9258: * The optional Memory-Allocation word set::  
 9259: * The optional Programming-Tools word set::  
 9260: * The optional Search-Order word set::  
 9261: @end menu
 9262: 
 9263: 
 9264: @c =====================================================================
 9265: @node The Core Words, The optional Block word set, ANS conformance, ANS conformance
 9266: @comment  node-name,  next,  previous,  up
 9267: @section The Core Words
 9268: @c =====================================================================
 9269: @cindex core words, system documentation
 9270: @cindex system documentation, core words
 9271: 
 9272: @menu
 9273: * core-idef::                   Implementation Defined Options                   
 9274: * core-ambcond::                Ambiguous Conditions                
 9275: * core-other::                  Other System Documentation                  
 9276: @end menu
 9277: 
 9278: @c ---------------------------------------------------------------------
 9279: @node core-idef, core-ambcond, The Core Words, The Core Words
 9280: @subsection Implementation Defined Options
 9281: @c ---------------------------------------------------------------------
 9282: @cindex core words, implementation-defined options
 9283: @cindex implementation-defined options, core words
 9284: 
 9285: 
 9286: @table @i
 9287: @item (Cell) aligned addresses:
 9288: @cindex cell-aligned addresses
 9289: @cindex aligned addresses
 9290: processor-dependent. Gforth's alignment words perform natural alignment
 9291: (e.g., an address aligned for a datum of size 8 is divisible by
 9292: 8). Unaligned accesses usually result in a @code{-23 THROW}.
 9293: 
 9294: @item @code{EMIT} and non-graphic characters:
 9295: @cindex @code{EMIT} and non-graphic characters
 9296: @cindex non-graphic characters and @code{EMIT}
 9297: The character is output using the C library function (actually, macro)
 9298: @code{putc}.
 9299: 
 9300: @item character editing of @code{ACCEPT} and @code{EXPECT}:
 9301: @cindex character editing of @code{ACCEPT} and @code{EXPECT}
 9302: @cindex editing in @code{ACCEPT} and @code{EXPECT}
 9303: @cindex @code{ACCEPT}, editing
 9304: @cindex @code{EXPECT}, editing
 9305: This is modeled on the GNU readline library (@pxref{Readline
 9306: Interaction, , Command Line Editing, readline, The GNU Readline
 9307: Library}) with Emacs-like key bindings. @kbd{Tab} deviates a little by
 9308: producing a full word completion every time you type it (instead of
 9309: producing the common prefix of all completions). @xref{Command-line editing}.
 9310: 
 9311: @item character set:
 9312: @cindex character set
 9313: The character set of your computer and display device. Gforth is
 9314: 8-bit-clean (but some other component in your system may make trouble).
 9315: 
 9316: @item Character-aligned address requirements:
 9317: @cindex character-aligned address requirements
 9318: installation-dependent. Currently a character is represented by a C
 9319: @code{unsigned char}; in the future we might switch to @code{wchar_t}
 9320: (Comments on that requested).
 9321: 
 9322: @item character-set extensions and matching of names:
 9323: @cindex character-set extensions and matching of names
 9324: @cindex case-sensitivity for name lookup
 9325: @cindex name lookup, case-sensitivity
 9326: @cindex locale and case-sensitivity
 9327: Any character except the ASCII NUL character can be used in a
 9328: name. Matching is case-insensitive (except in @code{TABLE}s). The
 9329: matching is performed using the C library function @code{strncasecmp}, whose
 9330: function is probably influenced by the locale. E.g., the @code{C} locale
 9331: does not know about accents and umlauts, so they are matched
 9332: case-sensitively in that locale. For portability reasons it is best to
 9333: write programs such that they work in the @code{C} locale. Then one can
 9334: use libraries written by a Polish programmer (who might use words
 9335: containing ISO Latin-2 encoded characters) and by a French programmer
 9336: (ISO Latin-1) in the same program (of course, @code{WORDS} will produce
 9337: funny results for some of the words (which ones, depends on the font you
 9338: are using)). Also, the locale you prefer may not be available in other
 9339: operating systems. Hopefully, Unicode will solve these problems one day.
 9340: 
 9341: @item conditions under which control characters match a space delimiter:
 9342: @cindex space delimiters
 9343: @cindex control characters as delimiters
 9344: If @code{WORD} is called with the space character as a delimiter, all
 9345: white-space characters (as identified by the C macro @code{isspace()})
 9346: are delimiters. @code{PARSE}, on the other hand, treats space like other
 9347: delimiters. @code{SWORD} treats space like @code{WORD}, but behaves
 9348: like @code{PARSE} otherwise. @code{(NAME)}, which is used by the outer
 9349: interpreter (aka text interpreter) by default, treats all white-space
 9350: characters as delimiters.
 9351: 
 9352: @item format of the control-flow stack:
 9353: @cindex control-flow stack, format
 9354: The data stack is used as control-flow stack. The size of a control-flow
 9355: stack item in cells is given by the constant @code{cs-item-size}. At the
 9356: time of this writing, an item consists of a (pointer to a) locals list
 9357: (third), an address in the code (second), and a tag for identifying the
 9358: item (TOS). The following tags are used: @code{defstart},
 9359: @code{live-orig}, @code{dead-orig}, @code{dest}, @code{do-dest},
 9360: @code{scopestart}.
 9361: 
 9362: @item conversion of digits > 35
 9363: @cindex digits > 35
 9364: The characters @code{[\]^_'} are the digits with the decimal value
 9365: 36@minus{}41. There is no way to input many of the larger digits.
 9366: 
 9367: @item display after input terminates in @code{ACCEPT} and @code{EXPECT}:
 9368: @cindex @code{EXPECT}, display after end of input
 9369: @cindex @code{ACCEPT}, display after end of input
 9370: The cursor is moved to the end of the entered string. If the input is
 9371: terminated using the @kbd{Return} key, a space is typed.
 9372: 
 9373: @item exception abort sequence of @code{ABORT"}:
 9374: @cindex exception abort sequence of @code{ABORT"}
 9375: @cindex @code{ABORT"}, exception abort sequence
 9376: The error string is stored into the variable @code{"error} and a
 9377: @code{-2 throw} is performed.
 9378: 
 9379: @item input line terminator:
 9380: @cindex input line terminator
 9381: @cindex line terminator on input
 9382: @cindex newline character on input
 9383: For interactive input, @kbd{C-m} (CR) and @kbd{C-j} (LF) terminate
 9384: lines. One of these characters is typically produced when you type the
 9385: @kbd{Enter} or @kbd{Return} key.
 9386: 
 9387: @item maximum size of a counted string:
 9388: @cindex maximum size of a counted string
 9389: @cindex counted string, maximum size
 9390: @code{s" /counted-string" environment? drop .}. Currently 255 characters
 9391: on all ports, but this may change.
 9392: 
 9393: @item maximum size of a parsed string:
 9394: @cindex maximum size of a parsed string
 9395: @cindex parsed string, maximum size
 9396: Given by the constant @code{/line}. Currently 255 characters.
 9397: 
 9398: @item maximum size of a definition name, in characters:
 9399: @cindex maximum size of a definition name, in characters
 9400: @cindex name, maximum length
 9401: 31
 9402: 
 9403: @item maximum string length for @code{ENVIRONMENT?}, in characters:
 9404: @cindex maximum string length for @code{ENVIRONMENT?}, in characters
 9405: @cindex @code{ENVIRONMENT?} string length, maximum
 9406: 31
 9407: 
 9408: @item method of selecting the user input device:
 9409: @cindex user input device, method of selecting
 9410: The user input device is the standard input. There is currently no way to
 9411: change it from within Gforth. However, the input can typically be
 9412: redirected in the command line that starts Gforth.
 9413: 
 9414: @item method of selecting the user output device:
 9415: @cindex user output device, method of selecting
 9416: @code{EMIT} and @code{TYPE} output to the file-id stored in the value
 9417: @code{outfile-id} (@code{stdout} by default). Gforth uses unbuffered
 9418: output when the user output device is a terminal, otherwise the output
 9419: is buffered.
 9420: 
 9421: @item methods of dictionary compilation:
 9422: What are we expected to document here?
 9423: 
 9424: @item number of bits in one address unit:
 9425: @cindex number of bits in one address unit
 9426: @cindex address unit, size in bits
 9427: @code{s" address-units-bits" environment? drop .}. 8 in all current
 9428: ports.
 9429: 
 9430: @item number representation and arithmetic:
 9431: @cindex number representation and arithmetic
 9432: Processor-dependent. Binary two's complement on all current ports.
 9433: 
 9434: @item ranges for integer types:
 9435: @cindex ranges for integer types
 9436: @cindex integer types, ranges
 9437: Installation-dependent. Make environmental queries for @code{MAX-N},
 9438: @code{MAX-U}, @code{MAX-D} and @code{MAX-UD}. The lower bounds for
 9439: unsigned (and positive) types is 0. The lower bound for signed types on
 9440: two's complement and one's complement machines machines can be computed
 9441: by adding 1 to the upper bound.
 9442: 
 9443: @item read-only data space regions:
 9444: @cindex read-only data space regions
 9445: @cindex data-space, read-only regions
 9446: The whole Forth data space is writable.
 9447: 
 9448: @item size of buffer at @code{WORD}:
 9449: @cindex size of buffer at @code{WORD}
 9450: @cindex @code{WORD} buffer size
 9451: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
 9452: shared with the pictured numeric output string. If overwriting
 9453: @code{PAD} is acceptable, it is as large as the remaining dictionary
 9454: space, although only as much can be sensibly used as fits in a counted
 9455: string.
 9456: 
 9457: @item size of one cell in address units:
 9458: @cindex cell size
 9459: @code{1 cells .}.
 9460: 
 9461: @item size of one character in address units:
 9462: @cindex char size
 9463: @code{1 chars .}. 1 on all current ports.
 9464: 
 9465: @item size of the keyboard terminal buffer:
 9466: @cindex size of the keyboard terminal buffer
 9467: @cindex terminal buffer, size
 9468: Varies. You can determine the size at a specific time using @code{lp@@
 9469: tib - .}. It is shared with the locals stack and TIBs of files that
 9470: include the current file. You can change the amount of space for TIBs
 9471: and locals stack at Gforth startup with the command line option
 9472: @code{-l}.
 9473: 
 9474: @item size of the pictured numeric output buffer:
 9475: @cindex size of the pictured numeric output buffer
 9476: @cindex pictured numeric output buffer, size
 9477: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
 9478: shared with @code{WORD}.
 9479: 
 9480: @item size of the scratch area returned by @code{PAD}:
 9481: @cindex size of the scratch area returned by @code{PAD}
 9482: @cindex @code{PAD} size
 9483: The remainder of dictionary space. @code{unused pad here - - .}.
 9484: 
 9485: @item system case-sensitivity characteristics:
 9486: @cindex case-sensitivity characteristics
 9487: Dictionary searches are case-insensitive (except in
 9488: @code{TABLE}s). However, as explained above under @i{character-set
 9489: extensions}, the matching for non-ASCII characters is determined by the
 9490: locale you are using. In the default @code{C} locale all non-ASCII
 9491: characters are matched case-sensitively.
 9492: 
 9493: @item system prompt:
 9494: @cindex system prompt
 9495: @cindex prompt
 9496: @code{ ok} in interpret state, @code{ compiled} in compile state.
 9497: 
 9498: @item division rounding:
 9499: @cindex division rounding
 9500: installation dependent. @code{s" floored" environment? drop .}. We leave
 9501: the choice to @code{gcc} (what to use for @code{/}) and to you (whether
 9502: to use @code{fm/mod}, @code{sm/rem} or simply @code{/}).
 9503: 
 9504: @item values of @code{STATE} when true:
 9505: @cindex @code{STATE} values
 9506: -1.
 9507: 
 9508: @item values returned after arithmetic overflow:
 9509: On two's complement machines, arithmetic is performed modulo
 9510: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
 9511: arithmetic (with appropriate mapping for signed types). Division by zero
 9512: typically results in a @code{-55 throw} (Floating-point unidentified
 9513: fault), although a @code{-10 throw} (divide by zero) would be more
 9514: appropriate.
 9515: 
 9516: @item whether the current definition can be found after @t{DOES>}:
 9517: @cindex @t{DOES>}, visibility of current definition
 9518: No.
 9519: 
 9520: @end table
 9521: 
 9522: @c ---------------------------------------------------------------------
 9523: @node core-ambcond, core-other, core-idef, The Core Words
 9524: @subsection Ambiguous conditions
 9525: @c ---------------------------------------------------------------------
 9526: @cindex core words, ambiguous conditions
 9527: @cindex ambiguous conditions, core words
 9528: 
 9529: @table @i
 9530: 
 9531: @item a name is neither a word nor a number:
 9532: @cindex name not found
 9533: @cindex undefined word
 9534: @code{-13 throw} (Undefined word). Actually, @code{-13 bounce}, which
 9535: preserves the data and FP stack, so you don't lose more work than
 9536: necessary.
 9537: 
 9538: @item a definition name exceeds the maximum length allowed:
 9539: @cindex word name too long
 9540: @code{-19 throw} (Word name too long)
 9541: 
 9542: @item addressing a region not inside the various data spaces of the forth system:
 9543: @cindex Invalid memory address
 9544: The stacks, code space and header space are accessible. Machine code space is
 9545: typically readable. Accessing other addresses gives results dependent on
 9546: the operating system. On decent systems: @code{-9 throw} (Invalid memory
 9547: address).
 9548: 
 9549: @item argument type incompatible with parameter:
 9550: @cindex argument type mismatch
 9551: This is usually not caught. Some words perform checks, e.g., the control
 9552: flow words, and issue a @code{ABORT"} or @code{-12 THROW} (Argument type
 9553: mismatch).
 9554: 
 9555: @item attempting to obtain the execution token of a word with undefined execution semantics:
 9556: @cindex Interpreting a compile-only word, for @code{'} etc.
 9557: @cindex execution token of words with undefined execution semantics
 9558: @code{-14 throw} (Interpreting a compile-only word). In some cases, you
 9559: get an execution token for @code{compile-only-error} (which performs a
 9560: @code{-14 throw} when executed).
 9561: 
 9562: @item dividing by zero:
 9563: @cindex dividing by zero
 9564: @cindex floating point unidentified fault, integer division
 9565: On better platforms, this produces a @code{-10 throw} (Division by
 9566: zero); on other systems, this typically results in a @code{-55 throw}
 9567: (Floating-point unidentified fault).
 9568: 
 9569: @item insufficient data stack or return stack space:
 9570: @cindex insufficient data stack or return stack space
 9571: @cindex stack overflow
 9572: @cindex address alignment exception, stack overflow
 9573: @cindex Invalid memory address, stack overflow
 9574: Depending on the operating system, the installation, and the invocation
 9575: of Gforth, this is either checked by the memory management hardware, or
 9576: it is not checked. If it is checked, you typically get a @code{-3 throw}
 9577: (Stack overflow), @code{-5 throw} (Return stack overflow), or @code{-9
 9578: throw} (Invalid memory address) (depending on the platform and how you
 9579: achieved the overflow) as soon as the overflow happens. If it is not
 9580: checked, overflows typically result in mysterious illegal memory
 9581: accesses, producing @code{-9 throw} (Invalid memory address) or
 9582: @code{-23 throw} (Address alignment exception); they might also destroy
 9583: the internal data structure of @code{ALLOCATE} and friends, resulting in
 9584: various errors in these words.
 9585: 
 9586: @item insufficient space for loop control parameters:
 9587: @cindex insufficient space for loop control parameters
 9588: like other return stack overflows.
 9589: 
 9590: @item insufficient space in the dictionary:
 9591: @cindex insufficient space in the dictionary
 9592: @cindex dictionary overflow
 9593: If you try to allot (either directly with @code{allot}, or indirectly
 9594: with @code{,}, @code{create} etc.) more memory than available in the
 9595: dictionary, you get a @code{-8 throw} (Dictionary overflow). If you try
 9596: to access memory beyond the end of the dictionary, the results are
 9597: similar to stack overflows.
 9598: 
 9599: @item interpreting a word with undefined interpretation semantics:
 9600: @cindex interpreting a word with undefined interpretation semantics
 9601: @cindex Interpreting a compile-only word
 9602: For some words, we have defined interpretation semantics. For the
 9603: others: @code{-14 throw} (Interpreting a compile-only word).
 9604: 
 9605: @item modifying the contents of the input buffer or a string literal:
 9606: @cindex modifying the contents of the input buffer or a string literal
 9607: These are located in writable memory and can be modified.
 9608: 
 9609: @item overflow of the pictured numeric output string:
 9610: @cindex overflow of the pictured numeric output string
 9611: @cindex pictured numeric output string, overflow
 9612: @code{-17 throw} (Pictured numeric ouput string overflow).
 9613: 
 9614: @item parsed string overflow:
 9615: @cindex parsed string overflow
 9616: @code{PARSE} cannot overflow. @code{WORD} does not check for overflow.
 9617: 
 9618: @item producing a result out of range:
 9619: @cindex result out of range
 9620: On two's complement machines, arithmetic is performed modulo
 9621: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
 9622: arithmetic (with appropriate mapping for signed types). Division by zero
 9623: typically results in a @code{-10 throw} (divide by zero) or @code{-55
 9624: throw} (floating point unidentified fault). @code{convert} and
 9625: @code{>number} currently overflow silently.
 9626: 
 9627: @item reading from an empty data or return stack:
 9628: @cindex stack empty
 9629: @cindex stack underflow
 9630: @cindex return stack underflow
 9631: The data stack is checked by the outer (aka text) interpreter after
 9632: every word executed. If it has underflowed, a @code{-4 throw} (Stack
 9633: underflow) is performed. Apart from that, stacks may be checked or not,
 9634: depending on operating system, installation, and invocation. If they are
 9635: caught by a check, they typically result in @code{-4 throw} (Stack
 9636: underflow), @code{-6 throw} (Return stack underflow) or @code{-9 throw}
 9637: (Invalid memory address), depending on the platform and which stack
 9638: underflows and by how much. Note that even if the system uses checking
 9639: (through the MMU), your program may have to underflow by a significant
 9640: number of stack items to trigger the reaction (the reason for this is
 9641: that the MMU, and therefore the checking, works with a page-size
 9642: granularity).  If there is no checking, the symptoms resulting from an
 9643: underflow are similar to those from an overflow.  Unbalanced return
 9644: stack errors result in a variaty of symptoms, including @code{-9 throw}
 9645: (Invalid memory address) and Illegal Instruction (typically @code{-260
 9646: throw}).
 9647: 
 9648: @item unexpected end of the input buffer, resulting in an attempt to use a zero-length string as a name:
 9649: @cindex unexpected end of the input buffer
 9650: @cindex zero-length string as a name
 9651: @cindex Attempt to use zero-length string as a name
 9652: @code{Create} and its descendants perform a @code{-16 throw} (Attempt to
 9653: use zero-length string as a name). Words like @code{'} probably will not
 9654: find what they search. Note that it is possible to create zero-length
 9655: names with @code{nextname} (should it not?).
 9656: 
 9657: @item @code{>IN} greater than input buffer:
 9658: @cindex @code{>IN} greater than input buffer
 9659: The next invocation of a parsing word returns a string with length 0.
 9660: 
 9661: @item @code{RECURSE} appears after @code{DOES>}:
 9662: @cindex @code{RECURSE} appears after @code{DOES>}
 9663: Compiles a recursive call to the defining word, not to the defined word.
 9664: 
 9665: @item argument input source different than current input source for @code{RESTORE-INPUT}:
 9666: @cindex argument input source different than current input source for @code{RESTORE-INPUT}
 9667: @cindex argument type mismatch, @code{RESTORE-INPUT}
 9668: @cindex @code{RESTORE-INPUT}, Argument type mismatch
 9669: @code{-12 THROW}. Note that, once an input file is closed (e.g., because
 9670: the end of the file was reached), its source-id may be
 9671: reused. Therefore, restoring an input source specification referencing a
 9672: closed file may lead to unpredictable results instead of a @code{-12
 9673: THROW}.
 9674: 
 9675: In the future, Gforth may be able to restore input source specifications
 9676: from other than the current input source.
 9677: 
 9678: @item data space containing definitions gets de-allocated:
 9679: @cindex data space containing definitions gets de-allocated
 9680: Deallocation with @code{allot} is not checked. This typically results in
 9681: memory access faults or execution of illegal instructions.
 9682: 
 9683: @item data space read/write with incorrect alignment:
 9684: @cindex data space read/write with incorrect alignment
 9685: @cindex alignment faults
 9686: @cindex address alignment exception
 9687: Processor-dependent. Typically results in a @code{-23 throw} (Address
 9688: alignment exception). Under Linux-Intel on a 486 or later processor with
 9689: alignment turned on, incorrect alignment results in a @code{-9 throw}
 9690: (Invalid memory address). There are reportedly some processors with
 9691: alignment restrictions that do not report violations.
 9692: 
 9693: @item data space pointer not properly aligned, @code{,}, @code{C,}:
 9694: @cindex data space pointer not properly aligned, @code{,}, @code{C,}
 9695: Like other alignment errors.
 9696: 
 9697: @item less than u+2 stack items (@code{PICK} and @code{ROLL}):
 9698: Like other stack underflows.
 9699: 
 9700: @item loop control parameters not available:
 9701: @cindex loop control parameters not available
 9702: Not checked. The counted loop words simply assume that the top of return
 9703: stack items are loop control parameters and behave accordingly.
 9704: 
 9705: @item most recent definition does not have a name (@code{IMMEDIATE}):
 9706: @cindex most recent definition does not have a name (@code{IMMEDIATE})
 9707: @cindex last word was headerless
 9708: @code{abort" last word was headerless"}.
 9709: 
 9710: @item name not defined by @code{VALUE} used by @code{TO}:
 9711: @cindex name not defined by @code{VALUE} used by @code{TO}
 9712: @cindex @code{TO} on non-@code{VALUE}s
 9713: @cindex Invalid name argument, @code{TO}
 9714: @code{-32 throw} (Invalid name argument) (unless name is a local or was
 9715: defined by @code{CONSTANT}; in the latter case it just changes the constant).
 9716: 
 9717: @item name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}):
 9718: @cindex name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]})
 9719: @cindex undefined word, @code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}
 9720: @code{-13 throw} (Undefined word)
 9721: 
 9722: @item parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN}):
 9723: @cindex parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN})
 9724: Gforth behaves as if they were of the same type. I.e., you can predict
 9725: the behaviour by interpreting all parameters as, e.g., signed.
 9726: 
 9727: @item @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}:
 9728: @cindex @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}
 9729: Assume @code{: X POSTPONE TO ; IMMEDIATE}. @code{X} performs the
 9730: compilation semantics of @code{TO}.
 9731: 
 9732: @item String longer than a counted string returned by @code{WORD}:
 9733: @cindex string longer than a counted string returned by @code{WORD}
 9734: @cindex @code{WORD}, string overflow
 9735: Not checked. The string will be ok, but the count will, of course,
 9736: contain only the least significant bits of the length.
 9737: 
 9738: @item u greater than or equal to the number of bits in a cell (@code{LSHIFT}, @code{RSHIFT}):
 9739: @cindex @code{LSHIFT}, large shift counts
 9740: @cindex @code{RSHIFT}, large shift counts
 9741: Processor-dependent. Typical behaviours are returning 0 and using only
 9742: the low bits of the shift count.
 9743: 
 9744: @item word not defined via @code{CREATE}:
 9745: @cindex @code{>BODY} of non-@code{CREATE}d words
 9746: @code{>BODY} produces the PFA of the word no matter how it was defined.
 9747: 
 9748: @cindex @code{DOES>} of non-@code{CREATE}d words
 9749: @code{DOES>} changes the execution semantics of the last defined word no
 9750: matter how it was defined. E.g., @code{CONSTANT DOES>} is equivalent to
 9751: @code{CREATE , DOES>}.
 9752: 
 9753: @item words improperly used outside @code{<#} and @code{#>}:
 9754: Not checked. As usual, you can expect memory faults.
 9755: 
 9756: @end table
 9757: 
 9758: 
 9759: @c ---------------------------------------------------------------------
 9760: @node core-other,  , core-ambcond, The Core Words
 9761: @subsection Other system documentation
 9762: @c ---------------------------------------------------------------------
 9763: @cindex other system documentation, core words
 9764: @cindex core words, other system documentation
 9765: 
 9766: @table @i
 9767: @item nonstandard words using @code{PAD}:
 9768: @cindex @code{PAD} use by nonstandard words
 9769: None.
 9770: 
 9771: @item operator's terminal facilities available:
 9772: @cindex operator's terminal facilities available
 9773: After processing the command line, Gforth goes into interactive mode,
 9774: and you can give commands to Gforth interactively. The actual facilities
 9775: available depend on how you invoke Gforth.
 9776: 
 9777: @item program data space available:
 9778: @cindex program data space available
 9779: @cindex data space available
 9780: @code{UNUSED .} gives the remaining dictionary space. The total
 9781: dictionary space can be specified with the @code{-m} switch
 9782: (@pxref{Invoking Gforth}) when Gforth starts up.
 9783: 
 9784: @item return stack space available:
 9785: @cindex return stack space available
 9786: You can compute the total return stack space in cells with
 9787: @code{s" RETURN-STACK-CELLS" environment? drop .}. You can specify it at
 9788: startup time with the @code{-r} switch (@pxref{Invoking Gforth}).
 9789: 
 9790: @item stack space available:
 9791: @cindex stack space available
 9792: You can compute the total data stack space in cells with
 9793: @code{s" STACK-CELLS" environment? drop .}. You can specify it at
 9794: startup time with the @code{-d} switch (@pxref{Invoking Gforth}).
 9795: 
 9796: @item system dictionary space required, in address units:
 9797: @cindex system dictionary space required, in address units
 9798: Type @code{here forthstart - .} after startup. At the time of this
 9799: writing, this gives 80080 (bytes) on a 32-bit system.
 9800: @end table
 9801: 
 9802: 
 9803: @c =====================================================================
 9804: @node The optional Block word set, The optional Double Number word set, The Core Words, ANS conformance
 9805: @section The optional Block word set
 9806: @c =====================================================================
 9807: @cindex system documentation, block words
 9808: @cindex block words, system documentation
 9809: 
 9810: @menu
 9811: * block-idef::                  Implementation Defined Options
 9812: * block-ambcond::               Ambiguous Conditions               
 9813: * block-other::                 Other System Documentation                 
 9814: @end menu
 9815: 
 9816: 
 9817: @c ---------------------------------------------------------------------
 9818: @node block-idef, block-ambcond, The optional Block word set, The optional Block word set
 9819: @subsection Implementation Defined Options
 9820: @c ---------------------------------------------------------------------
 9821: @cindex implementation-defined options, block words
 9822: @cindex block words, implementation-defined options
 9823: 
 9824: @table @i
 9825: @item the format for display by @code{LIST}:
 9826: @cindex @code{LIST} display format
 9827: First the screen number is displayed, then 16 lines of 64 characters,
 9828: each line preceded by the line number.
 9829: 
 9830: @item the length of a line affected by @code{\}:
 9831: @cindex length of a line affected by @code{\}
 9832: @cindex @code{\}, line length in blocks
 9833: 64 characters.
 9834: @end table
 9835: 
 9836: 
 9837: @c ---------------------------------------------------------------------
 9838: @node block-ambcond, block-other, block-idef, The optional Block word set
 9839: @subsection Ambiguous conditions
 9840: @c ---------------------------------------------------------------------
 9841: @cindex block words, ambiguous conditions
 9842: @cindex ambiguous conditions, block words
 9843: 
 9844: @table @i
 9845: @item correct block read was not possible:
 9846: @cindex block read not possible
 9847: Typically results in a @code{throw} of some OS-derived value (between
 9848: -512 and -2048). If the blocks file was just not long enough, blanks are
 9849: supplied for the missing portion.
 9850: 
 9851: @item I/O exception in block transfer:
 9852: @cindex I/O exception in block transfer
 9853: @cindex block transfer, I/O exception
 9854: Typically results in a @code{throw} of some OS-derived value (between
 9855: -512 and -2048).
 9856: 
 9857: @item invalid block number:
 9858: @cindex invalid block number
 9859: @cindex block number invalid
 9860: @code{-35 throw} (Invalid block number)
 9861: 
 9862: @item a program directly alters the contents of @code{BLK}:
 9863: @cindex @code{BLK}, altering @code{BLK}
 9864: The input stream is switched to that other block, at the same
 9865: position. If the storing to @code{BLK} happens when interpreting
 9866: non-block input, the system will get quite confused when the block ends.
 9867: 
 9868: @item no current block buffer for @code{UPDATE}:
 9869: @cindex @code{UPDATE}, no current block buffer
 9870: @code{UPDATE} has no effect.
 9871: 
 9872: @end table
 9873: 
 9874: @c ---------------------------------------------------------------------
 9875: @node block-other,  , block-ambcond, The optional Block word set
 9876: @subsection Other system documentation
 9877: @c ---------------------------------------------------------------------
 9878: @cindex other system documentation, block words
 9879: @cindex block words, other system documentation
 9880: 
 9881: @table @i
 9882: @item any restrictions a multiprogramming system places on the use of buffer addresses:
 9883: No restrictions (yet).
 9884: 
 9885: @item the number of blocks available for source and data:
 9886: depends on your disk space.
 9887: 
 9888: @end table
 9889: 
 9890: 
 9891: @c =====================================================================
 9892: @node The optional Double Number word set, The optional Exception word set, The optional Block word set, ANS conformance
 9893: @section The optional Double Number word set
 9894: @c =====================================================================
 9895: @cindex system documentation, double words
 9896: @cindex double words, system documentation
 9897: 
 9898: @menu
 9899: * double-ambcond::              Ambiguous Conditions              
 9900: @end menu
 9901: 
 9902: 
 9903: @c ---------------------------------------------------------------------
 9904: @node double-ambcond,  , The optional Double Number word set, The optional Double Number word set
 9905: @subsection Ambiguous conditions
 9906: @c ---------------------------------------------------------------------
 9907: @cindex double words, ambiguous conditions
 9908: @cindex ambiguous conditions, double words
 9909: 
 9910: @table @i
 9911: @item @i{d} outside of range of @i{n} in @code{D>S}:
 9912: @cindex @code{D>S}, @i{d} out of range of @i{n} 
 9913: The least significant cell of @i{d} is produced.
 9914: 
 9915: @end table
 9916: 
 9917: 
 9918: @c =====================================================================
 9919: @node The optional Exception word set, The optional Facility word set, The optional Double Number word set, ANS conformance
 9920: @section The optional Exception word set
 9921: @c =====================================================================
 9922: @cindex system documentation, exception words
 9923: @cindex exception words, system documentation
 9924: 
 9925: @menu
 9926: * exception-idef::              Implementation Defined Options              
 9927: @end menu
 9928: 
 9929: 
 9930: @c ---------------------------------------------------------------------
 9931: @node exception-idef,  , The optional Exception word set, The optional Exception word set
 9932: @subsection Implementation Defined Options
 9933: @c ---------------------------------------------------------------------
 9934: @cindex implementation-defined options, exception words
 9935: @cindex exception words, implementation-defined options
 9936: 
 9937: @table @i
 9938: @item @code{THROW}-codes used in the system:
 9939: @cindex @code{THROW}-codes used in the system
 9940: The codes -256@minus{}-511 are used for reporting signals. The mapping
 9941: from OS signal numbers to throw codes is -256@minus{}@i{signal}. The
 9942: codes -512@minus{}-2047 are used for OS errors (for file and memory
 9943: allocation operations). The mapping from OS error numbers to throw codes
 9944: is -512@minus{}@code{errno}. One side effect of this mapping is that
 9945: undefined OS errors produce a message with a strange number; e.g.,
 9946: @code{-1000 THROW} results in @code{Unknown error 488} on my system.
 9947: @end table
 9948: 
 9949: @c =====================================================================
 9950: @node The optional Facility word set, The optional File-Access word set, The optional Exception word set, ANS conformance
 9951: @section The optional Facility word set
 9952: @c =====================================================================
 9953: @cindex system documentation, facility words
 9954: @cindex facility words, system documentation
 9955: 
 9956: @menu
 9957: * facility-idef::               Implementation Defined Options               
 9958: * facility-ambcond::            Ambiguous Conditions            
 9959: @end menu
 9960: 
 9961: 
 9962: @c ---------------------------------------------------------------------
 9963: @node facility-idef, facility-ambcond, The optional Facility word set, The optional Facility word set
 9964: @subsection Implementation Defined Options
 9965: @c ---------------------------------------------------------------------
 9966: @cindex implementation-defined options, facility words
 9967: @cindex facility words, implementation-defined options
 9968: 
 9969: @table @i
 9970: @item encoding of keyboard events (@code{EKEY}):
 9971: @cindex keyboard events, encoding in @code{EKEY}
 9972: @cindex @code{EKEY}, encoding of keyboard events
 9973: Keys corresponding to ASCII characters are encoded as ASCII characters.
 9974: Other keys are encoded with the constants @code{k-left}, @code{k-right},
 9975: @code{k-up}, @code{k-down}, @code{k-home}, @code{k-end}, @code{k1},
 9976: @code{k2}, @code{k3}, @code{k4}, @code{k5}, @code{k6}, @code{k7},
 9977: @code{k8}, @code{k9}, @code{k10}, @code{k11}, @code{k12}.
 9978: 
 9979: 
 9980: @item duration of a system clock tick:
 9981: @cindex duration of a system clock tick
 9982: @cindex clock tick duration
 9983: System dependent. With respect to @code{MS}, the time is specified in
 9984: microseconds. How well the OS and the hardware implement this, is
 9985: another question.
 9986: 
 9987: @item repeatability to be expected from the execution of @code{MS}:
 9988: @cindex repeatability to be expected from the execution of @code{MS}
 9989: @cindex @code{MS}, repeatability to be expected
 9990: System dependent. On Unix, a lot depends on load. If the system is
 9991: lightly loaded, and the delay is short enough that Gforth does not get
 9992: swapped out, the performance should be acceptable. Under MS-DOS and
 9993: other single-tasking systems, it should be good.
 9994: 
 9995: @end table
 9996: 
 9997: 
 9998: @c ---------------------------------------------------------------------
 9999: @node facility-ambcond,  , facility-idef, The optional Facility word set
10000: @subsection Ambiguous conditions
10001: @c ---------------------------------------------------------------------
10002: @cindex facility words, ambiguous conditions
10003: @cindex ambiguous conditions, facility words
10004: 
10005: @table @i
10006: @item @code{AT-XY} can't be performed on user output device:
10007: @cindex @code{AT-XY} can't be performed on user output device
10008: Largely terminal dependent. No range checks are done on the arguments.
10009: No errors are reported. You may see some garbage appearing, you may see
10010: simply nothing happen.
10011: 
10012: @end table
10013: 
10014: 
10015: @c =====================================================================
10016: @node The optional File-Access word set, The optional Floating-Point word set, The optional Facility word set, ANS conformance
10017: @section The optional File-Access word set
10018: @c =====================================================================
10019: @cindex system documentation, file words
10020: @cindex file words, system documentation
10021: 
10022: @menu
10023: * file-idef::                   Implementation Defined Options
10024: * file-ambcond::                Ambiguous Conditions                
10025: @end menu
10026: 
10027: @c ---------------------------------------------------------------------
10028: @node file-idef, file-ambcond, The optional File-Access word set, The optional File-Access word set
10029: @subsection Implementation Defined Options
10030: @c ---------------------------------------------------------------------
10031: @cindex implementation-defined options, file words
10032: @cindex file words, implementation-defined options
10033: 
10034: @table @i
10035: @item file access methods used:
10036: @cindex file access methods used
10037: @code{R/O}, @code{R/W} and @code{BIN} work as you would
10038: expect. @code{W/O} translates into the C file opening mode @code{w} (or
10039: @code{wb}): The file is cleared, if it exists, and created, if it does
10040: not (with both @code{open-file} and @code{create-file}).  Under Unix
10041: @code{create-file} creates a file with 666 permissions modified by your
10042: umask.
10043: 
10044: @item file exceptions:
10045: @cindex file exceptions
10046: The file words do not raise exceptions (except, perhaps, memory access
10047: faults when you pass illegal addresses or file-ids).
10048: 
10049: @item file line terminator:
10050: @cindex file line terminator
10051: System-dependent. Gforth uses C's newline character as line
10052: terminator. What the actual character code(s) of this are is
10053: system-dependent.
10054: 
10055: @item file name format:
10056: @cindex file name format
10057: System dependent. Gforth just uses the file name format of your OS.
10058: 
10059: @item information returned by @code{FILE-STATUS}:
10060: @cindex @code{FILE-STATUS}, returned information
10061: @code{FILE-STATUS} returns the most powerful file access mode allowed
10062: for the file: Either @code{R/O}, @code{W/O} or @code{R/W}. If the file
10063: cannot be accessed, @code{R/O BIN} is returned. @code{BIN} is applicable
10064: along with the returned mode.
10065: 
10066: @item input file state after an exception when including source:
10067: @cindex exception when including source
10068: All files that are left via the exception are closed.
10069: 
10070: @item @i{ior} values and meaning:
10071: @cindex @i{ior} values and meaning
10072: The @i{ior}s returned by the file and memory allocation words are
10073: intended as throw codes. They typically are in the range
10074: -512@minus{}-2047 of OS errors.  The mapping from OS error numbers to
10075: @i{ior}s is -512@minus{}@i{errno}.
10076: 
10077: @item maximum depth of file input nesting:
10078: @cindex maximum depth of file input nesting
10079: @cindex file input nesting, maximum depth
10080: limited by the amount of return stack, locals/TIB stack, and the number
10081: of open files available. This should not give you troubles.
10082: 
10083: @item maximum size of input line:
10084: @cindex maximum size of input line
10085: @cindex input line size, maximum
10086: @code{/line}. Currently 255.
10087: 
10088: @item methods of mapping block ranges to files:
10089: @cindex mapping block ranges to files
10090: @cindex files containing blocks
10091: @cindex blocks in files
10092: By default, blocks are accessed in the file @file{blocks.fb} in the
10093: current working directory. The file can be switched with @code{USE}.
10094: 
10095: @item number of string buffers provided by @code{S"}:
10096: @cindex @code{S"}, number of string buffers
10097: 1
10098: 
10099: @item size of string buffer used by @code{S"}:
10100: @cindex @code{S"}, size of string buffer
10101: @code{/line}. currently 255.
10102: 
10103: @end table
10104: 
10105: @c ---------------------------------------------------------------------
10106: @node file-ambcond,  , file-idef, The optional File-Access word set
10107: @subsection Ambiguous conditions
10108: @c ---------------------------------------------------------------------
10109: @cindex file words, ambiguous conditions
10110: @cindex ambiguous conditions, file words
10111: 
10112: @table @i
10113: @item attempting to position a file outside its boundaries:
10114: @cindex @code{REPOSITION-FILE}, outside the file's boundaries
10115: @code{REPOSITION-FILE} is performed as usual: Afterwards,
10116: @code{FILE-POSITION} returns the value given to @code{REPOSITION-FILE}.
10117: 
10118: @item attempting to read from file positions not yet written:
10119: @cindex reading from file positions not yet written
10120: End-of-file, i.e., zero characters are read and no error is reported.
10121: 
10122: @item @i{file-id} is invalid (@code{INCLUDE-FILE}):
10123: @cindex @code{INCLUDE-FILE}, @i{file-id} is invalid 
10124: An appropriate exception may be thrown, but a memory fault or other
10125: problem is more probable.
10126: 
10127: @item I/O exception reading or closing @i{file-id} (@code{INCLUDE-FILE}, @code{INCLUDED}):
10128: @cindex @code{INCLUDE-FILE}, I/O exception reading or closing @i{file-id}
10129: @cindex @code{INCLUDED}, I/O exception reading or closing @i{file-id}
10130: The @i{ior} produced by the operation, that discovered the problem, is
10131: thrown.
10132: 
10133: @item named file cannot be opened (@code{INCLUDED}):
10134: @cindex @code{INCLUDED}, named file cannot be opened
10135: The @i{ior} produced by @code{open-file} is thrown.
10136: 
10137: @item requesting an unmapped block number:
10138: @cindex unmapped block numbers
10139: There are no unmapped legal block numbers. On some operating systems,
10140: writing a block with a large number may overflow the file system and
10141: have an error message as consequence.
10142: 
10143: @item using @code{source-id} when @code{blk} is non-zero:
10144: @cindex @code{SOURCE-ID}, behaviour when @code{BLK} is non-zero
10145: @code{source-id} performs its function. Typically it will give the id of
10146: the source which loaded the block. (Better ideas?)
10147: 
10148: @end table
10149: 
10150: 
10151: @c =====================================================================
10152: @node  The optional Floating-Point word set, The optional Locals word set, The optional File-Access word set, ANS conformance
10153: @section The optional Floating-Point word set
10154: @c =====================================================================
10155: @cindex system documentation, floating-point words
10156: @cindex floating-point words, system documentation
10157: 
10158: @menu
10159: * floating-idef::               Implementation Defined Options
10160: * floating-ambcond::            Ambiguous Conditions            
10161: @end menu
10162: 
10163: 
10164: @c ---------------------------------------------------------------------
10165: @node floating-idef, floating-ambcond, The optional Floating-Point word set, The optional Floating-Point word set
10166: @subsection Implementation Defined Options
10167: @c ---------------------------------------------------------------------
10168: @cindex implementation-defined options, floating-point words
10169: @cindex floating-point words, implementation-defined options
10170: 
10171: @table @i
10172: @item format and range of floating point numbers:
10173: @cindex format and range of floating point numbers
10174: @cindex floating point numbers, format and range
10175: System-dependent; the @code{double} type of C.
10176: 
10177: @item results of @code{REPRESENT} when @i{float} is out of range:
10178: @cindex  @code{REPRESENT}, results when @i{float} is out of range
10179: System dependent; @code{REPRESENT} is implemented using the C library
10180: function @code{ecvt()} and inherits its behaviour in this respect.
10181: 
10182: @item rounding or truncation of floating-point numbers:
10183: @cindex rounding of floating-point numbers
10184: @cindex truncation of floating-point numbers
10185: @cindex floating-point numbers, rounding or truncation
10186: System dependent; the rounding behaviour is inherited from the hosting C
10187: compiler. IEEE-FP-based (i.e., most) systems by default round to
10188: nearest, and break ties by rounding to even (i.e., such that the last
10189: bit of the mantissa is 0).
10190: 
10191: @item size of floating-point stack:
10192: @cindex floating-point stack size
10193: @code{s" FLOATING-STACK" environment? drop .} gives the total size of
10194: the floating-point stack (in floats). You can specify this on startup
10195: with the command-line option @code{-f} (@pxref{Invoking Gforth}).
10196: 
10197: @item width of floating-point stack:
10198: @cindex floating-point stack width 
10199: @code{1 floats}.
10200: 
10201: @end table
10202: 
10203: 
10204: @c ---------------------------------------------------------------------
10205: @node floating-ambcond,  , floating-idef, The optional Floating-Point word set
10206: @subsection Ambiguous conditions
10207: @c ---------------------------------------------------------------------
10208: @cindex floating-point words, ambiguous conditions
10209: @cindex ambiguous conditions, floating-point words
10210: 
10211: @table @i
10212: @item @code{df@@} or @code{df!} used with an address that is not double-float  aligned:
10213: @cindex @code{df@@} or @code{df!} used with an address that is not double-float  aligned
10214: System-dependent. Typically results in a @code{-23 THROW} like other
10215: alignment violations.
10216: 
10217: @item @code{f@@} or @code{f!} used with an address that is not float  aligned:
10218: @cindex @code{f@@} used with an address that is not float aligned
10219: @cindex @code{f!} used with an address that is not float aligned
10220: System-dependent. Typically results in a @code{-23 THROW} like other
10221: alignment violations.
10222: 
10223: @item floating-point result out of range:
10224: @cindex floating-point result out of range
10225: System-dependent. Can result in a @code{-55 THROW} (Floating-point
10226: unidentified fault), or can produce a special value representing, e.g.,
10227: Infinity.
10228: 
10229: @item @code{sf@@} or @code{sf!} used with an address that is not single-float  aligned:
10230: @cindex @code{sf@@} or @code{sf!} used with an address that is not single-float  aligned
10231: System-dependent. Typically results in an alignment fault like other
10232: alignment violations.
10233: 
10234: @item @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.}):
10235: @cindex @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.})
10236: The floating-point number is converted into decimal nonetheless.
10237: 
10238: @item Both arguments are equal to zero (@code{FATAN2}):
10239: @cindex @code{FATAN2}, both arguments are equal to zero
10240: System-dependent. @code{FATAN2} is implemented using the C library
10241: function @code{atan2()}.
10242: 
10243: @item Using @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero:
10244: @cindex @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero
10245: System-dependent. Anyway, typically the cos of @i{r1} will not be zero
10246: because of small errors and the tan will be a very large (or very small)
10247: but finite number.
10248: 
10249: @item @i{d} cannot be presented precisely as a float in @code{D>F}:
10250: @cindex @code{D>F}, @i{d} cannot be presented precisely as a float
10251: The result is rounded to the nearest float.
10252: 
10253: @item dividing by zero:
10254: @cindex dividing by zero, floating-point
10255: @cindex floating-point dividing by zero
10256: @cindex floating-point unidentified fault, FP divide-by-zero
10257: @code{-55 throw} (Floating-point unidentified fault)
10258: 
10259: @item exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@}):
10260: @cindex exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@})
10261: System dependent. On IEEE-FP based systems the number is converted into
10262: an infinity.
10263: 
10264: @item @i{float}<1 (@code{FACOSH}):
10265: @cindex @code{FACOSH}, @i{float}<1
10266: @cindex floating-point unidentified fault, @code{FACOSH}
10267: @code{-55 throw} (Floating-point unidentified fault)
10268: 
10269: @item @i{float}=<-1 (@code{FLNP1}):
10270: @cindex @code{FLNP1}, @i{float}=<-1
10271: @cindex floating-point unidentified fault, @code{FLNP1}
10272: @code{-55 throw} (Floating-point unidentified fault). On IEEE-FP systems
10273: negative infinity is typically produced for @i{float}=-1.
10274: 
10275: @item @i{float}=<0 (@code{FLN}, @code{FLOG}):
10276: @cindex @code{FLN}, @i{float}=<0
10277: @cindex @code{FLOG}, @i{float}=<0
10278: @cindex floating-point unidentified fault, @code{FLN} or @code{FLOG}
10279: @code{-55 throw} (Floating-point unidentified fault). On IEEE-FP systems
10280: negative infinity is typically produced for @i{float}=0.
10281: 
10282: @item @i{float}<0 (@code{FASINH}, @code{FSQRT}):
10283: @cindex @code{FASINH}, @i{float}<0
10284: @cindex @code{FSQRT}, @i{float}<0
10285: @cindex floating-point unidentified fault, @code{FASINH} or @code{FSQRT}
10286: @code{-55 throw} (Floating-point unidentified fault). @code{fasinh}
10287: produces values for these inputs on my Linux box (Bug in the C library?)
10288: 
10289: @item |@i{float}|>1 (@code{FACOS}, @code{FASIN}, @code{FATANH}):
10290: @cindex @code{FACOS}, |@i{float}|>1
10291: @cindex @code{FASIN}, |@i{float}|>1
10292: @cindex @code{FATANH}, |@i{float}|>1
10293: @cindex floating-point unidentified fault, @code{FACOS}, @code{FASIN} or @code{FATANH}
10294: @code{-55 throw} (Floating-point unidentified fault).
10295: 
10296: @item integer part of float cannot be represented by @i{d} in @code{F>D}:
10297: @cindex @code{F>D}, integer part of float cannot be represented by @i{d}
10298: @cindex floating-point unidentified fault, @code{F>D}
10299: @code{-55 throw} (Floating-point unidentified fault).
10300: 
10301: @item string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.}):
10302: @cindex string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.})
10303: This does not happen.
10304: @end table
10305: 
10306: @c =====================================================================
10307: @node  The optional Locals word set, The optional Memory-Allocation word set, The optional Floating-Point word set, ANS conformance
10308: @section The optional Locals word set
10309: @c =====================================================================
10310: @cindex system documentation, locals words
10311: @cindex locals words, system documentation
10312: 
10313: @menu
10314: * locals-idef::                 Implementation Defined Options                 
10315: * locals-ambcond::              Ambiguous Conditions              
10316: @end menu
10317: 
10318: 
10319: @c ---------------------------------------------------------------------
10320: @node locals-idef, locals-ambcond, The optional Locals word set, The optional Locals word set
10321: @subsection Implementation Defined Options
10322: @c ---------------------------------------------------------------------
10323: @cindex implementation-defined options, locals words
10324: @cindex locals words, implementation-defined options
10325: 
10326: @table @i
10327: @item maximum number of locals in a definition:
10328: @cindex maximum number of locals in a definition
10329: @cindex locals, maximum number in a definition
10330: @code{s" #locals" environment? drop .}. Currently 15. This is a lower
10331: bound, e.g., on a 32-bit machine there can be 41 locals of up to 8
10332: characters. The number of locals in a definition is bounded by the size
10333: of locals-buffer, which contains the names of the locals.
10334: 
10335: @end table
10336: 
10337: 
10338: @c ---------------------------------------------------------------------
10339: @node locals-ambcond,  , locals-idef, The optional Locals word set
10340: @subsection Ambiguous conditions
10341: @c ---------------------------------------------------------------------
10342: @cindex locals words, ambiguous conditions
10343: @cindex ambiguous conditions, locals words
10344: 
10345: @table @i
10346: @item executing a named local in interpretation state:
10347: @cindex local in interpretation state
10348: @cindex Interpreting a compile-only word, for a local
10349: Locals have no interpretation semantics. If you try to perform the
10350: interpretation semantics, you will get a @code{-14 throw} somewhere
10351: (Interpreting a compile-only word). If you perform the compilation
10352: semantics, the locals access will be compiled (irrespective of state).
10353: 
10354: @item @i{name} not defined by @code{VALUE} or @code{(LOCAL)} (@code{TO}):
10355: @cindex name not defined by @code{VALUE} or @code{(LOCAL)} used by @code{TO}
10356: @cindex @code{TO} on non-@code{VALUE}s and non-locals
10357: @cindex Invalid name argument, @code{TO}
10358: @code{-32 throw} (Invalid name argument)
10359: 
10360: @end table
10361: 
10362: 
10363: @c =====================================================================
10364: @node  The optional Memory-Allocation word set, The optional Programming-Tools word set, The optional Locals word set, ANS conformance
10365: @section The optional Memory-Allocation word set
10366: @c =====================================================================
10367: @cindex system documentation, memory-allocation words
10368: @cindex memory-allocation words, system documentation
10369: 
10370: @menu
10371: * memory-idef::                 Implementation Defined Options                 
10372: @end menu
10373: 
10374: 
10375: @c ---------------------------------------------------------------------
10376: @node memory-idef,  , The optional Memory-Allocation word set, The optional Memory-Allocation word set
10377: @subsection Implementation Defined Options
10378: @c ---------------------------------------------------------------------
10379: @cindex implementation-defined options, memory-allocation words
10380: @cindex memory-allocation words, implementation-defined options
10381: 
10382: @table @i
10383: @item values and meaning of @i{ior}:
10384: @cindex  @i{ior} values and meaning
10385: The @i{ior}s returned by the file and memory allocation words are
10386: intended as throw codes. They typically are in the range
10387: -512@minus{}-2047 of OS errors.  The mapping from OS error numbers to
10388: @i{ior}s is -512@minus{}@i{errno}.
10389: 
10390: @end table
10391: 
10392: @c =====================================================================
10393: @node  The optional Programming-Tools word set, The optional Search-Order word set, The optional Memory-Allocation word set, ANS conformance
10394: @section The optional Programming-Tools word set
10395: @c =====================================================================
10396: @cindex system documentation, programming-tools words
10397: @cindex programming-tools words, system documentation
10398: 
10399: @menu
10400: * programming-idef::            Implementation Defined Options            
10401: * programming-ambcond::         Ambiguous Conditions         
10402: @end menu
10403: 
10404: 
10405: @c ---------------------------------------------------------------------
10406: @node programming-idef, programming-ambcond, The optional Programming-Tools word set, The optional Programming-Tools word set
10407: @subsection Implementation Defined Options
10408: @c ---------------------------------------------------------------------
10409: @cindex implementation-defined options, programming-tools words
10410: @cindex programming-tools words, implementation-defined options
10411: 
10412: @table @i
10413: @item ending sequence for input following @code{;CODE} and @code{CODE}:
10414: @cindex @code{;CODE} ending sequence
10415: @cindex @code{CODE} ending sequence
10416: @code{END-CODE}
10417: 
10418: @item manner of processing input following @code{;CODE} and @code{CODE}:
10419: @cindex @code{;CODE}, processing input
10420: @cindex @code{CODE}, processing input
10421: The @code{ASSEMBLER} vocabulary is pushed on the search order stack, and
10422: the input is processed by the text interpreter, (starting) in interpret
10423: state.
10424: 
10425: @item search order capability for @code{EDITOR} and @code{ASSEMBLER}:
10426: @cindex @code{ASSEMBLER}, search order capability
10427: The ANS Forth search order word set.
10428: 
10429: @item source and format of display by @code{SEE}:
10430: @cindex @code{SEE}, source and format of output
10431: The source for @code{see} is the intermediate code used by the inner
10432: interpreter.  The current @code{see} tries to output Forth source code
10433: as well as possible.
10434: 
10435: @end table
10436: 
10437: @c ---------------------------------------------------------------------
10438: @node programming-ambcond,  , programming-idef, The optional Programming-Tools word set
10439: @subsection Ambiguous conditions
10440: @c ---------------------------------------------------------------------
10441: @cindex programming-tools words, ambiguous conditions
10442: @cindex ambiguous conditions, programming-tools words
10443: 
10444: @table @i
10445: 
10446: @item deleting the compilation word list (@code{FORGET}):
10447: @cindex @code{FORGET}, deleting the compilation word list
10448: Not implemented (yet).
10449: 
10450: @item fewer than @i{u}+1 items on the control-flow stack (@code{CS-PICK}, @code{CS-ROLL}):
10451: @cindex @code{CS-PICK}, fewer than @i{u}+1 items on the control flow-stack
10452: @cindex @code{CS-ROLL}, fewer than @i{u}+1 items on the control flow-stack
10453: @cindex control-flow stack underflow
10454: This typically results in an @code{abort"} with a descriptive error
10455: message (may change into a @code{-22 throw} (Control structure mismatch)
10456: in the future). You may also get a memory access error. If you are
10457: unlucky, this ambiguous condition is not caught.
10458: 
10459: @item @i{name} can't be found (@code{FORGET}):
10460: @cindex @code{FORGET}, @i{name} can't be found
10461: Not implemented (yet).
10462: 
10463: @item @i{name} not defined via @code{CREATE}:
10464: @cindex @code{;CODE}, @i{name} not defined via @code{CREATE}
10465: @code{;CODE} behaves like @code{DOES>} in this respect, i.e., it changes
10466: the execution semantics of the last defined word no matter how it was
10467: defined.
10468: 
10469: @item @code{POSTPONE} applied to @code{[IF]}:
10470: @cindex @code{POSTPONE} applied to @code{[IF]}
10471: @cindex @code{[IF]} and @code{POSTPONE}
10472: After defining @code{: X POSTPONE [IF] ; IMMEDIATE}. @code{X} is
10473: equivalent to @code{[IF]}.
10474: 
10475: @item reaching the end of the input source before matching @code{[ELSE]} or @code{[THEN]}:
10476: @cindex @code{[IF]}, end of the input source before matching @code{[ELSE]} or @code{[THEN]}
10477: Continue in the same state of conditional compilation in the next outer
10478: input source. Currently there is no warning to the user about this.
10479: 
10480: @item removing a needed definition (@code{FORGET}):
10481: @cindex @code{FORGET}, removing a needed definition
10482: Not implemented (yet).
10483: 
10484: @end table
10485: 
10486: 
10487: @c =====================================================================
10488: @node  The optional Search-Order word set,  , The optional Programming-Tools word set, ANS conformance
10489: @section The optional Search-Order word set
10490: @c =====================================================================
10491: @cindex system documentation, search-order words
10492: @cindex search-order words, system documentation
10493: 
10494: @menu
10495: * search-idef::                 Implementation Defined Options                 
10496: * search-ambcond::              Ambiguous Conditions              
10497: @end menu
10498: 
10499: 
10500: @c ---------------------------------------------------------------------
10501: @node search-idef, search-ambcond, The optional Search-Order word set, The optional Search-Order word set
10502: @subsection Implementation Defined Options
10503: @c ---------------------------------------------------------------------
10504: @cindex implementation-defined options, search-order words
10505: @cindex search-order words, implementation-defined options
10506: 
10507: @table @i
10508: @item maximum number of word lists in search order:
10509: @cindex maximum number of word lists in search order
10510: @cindex search order, maximum depth
10511: @code{s" wordlists" environment? drop .}. Currently 16.
10512: 
10513: @item minimum search order:
10514: @cindex minimum search order
10515: @cindex search order, minimum
10516: @code{root root}.
10517: 
10518: @end table
10519: 
10520: @c ---------------------------------------------------------------------
10521: @node search-ambcond,  , search-idef, The optional Search-Order word set
10522: @subsection Ambiguous conditions
10523: @c ---------------------------------------------------------------------
10524: @cindex search-order words, ambiguous conditions
10525: @cindex ambiguous conditions, search-order words
10526: 
10527: @table @i
10528: @item changing the compilation word list (during compilation):
10529: @cindex changing the compilation word list (during compilation)
10530: @cindex compilation word list, change before definition ends
10531: The word is entered into the word list that was the compilation word list
10532: at the start of the definition. Any changes to the name field (e.g.,
10533: @code{immediate}) or the code field (e.g., when executing @code{DOES>})
10534: are applied to the latest defined word (as reported by @code{last} or
10535: @code{lastxt}), if possible, irrespective of the compilation word list.
10536: 
10537: @item search order empty (@code{previous}):
10538: @cindex @code{previous}, search order empty
10539: @cindex vocstack empty, @code{previous}
10540: @code{abort" Vocstack empty"}.
10541: 
10542: @item too many word lists in search order (@code{also}):
10543: @cindex @code{also}, too many word lists in search order
10544: @cindex vocstack full, @code{also}
10545: @code{abort" Vocstack full"}.
10546: 
10547: @end table
10548: 
10549: @c ***************************************************************
10550: @node Model, Integrating Gforth, ANS conformance, Top
10551: @chapter Model
10552: 
10553: This chapter has yet to be written. It will contain information, on
10554: which internal structures you can rely.
10555: 
10556: @c ***************************************************************
10557: @node Integrating Gforth, Emacs and Gforth, Model, Top
10558: @chapter Integrating Gforth into C programs
10559: 
10560: This is not yet implemented.
10561: 
10562: Several people like to use Forth as scripting language for applications
10563: that are otherwise written in C, C++, or some other language.
10564: 
10565: The Forth system ATLAST provides facilities for embedding it into
10566: applications; unfortunately it has several disadvantages: most
10567: importantly, it is not based on ANS Forth, and it is apparently dead
10568: (i.e., not developed further and not supported). The facilities
10569: provided by Gforth in this area are inspired by ATLAST's facilities, so
10570: making the switch should not be hard.
10571: 
10572: We also tried to design the interface such that it can easily be
10573: implemented by other Forth systems, so that we may one day arrive at a
10574: standardized interface. Such a standard interface would allow you to
10575: replace the Forth system without having to rewrite C code.
10576: 
10577: You embed the Gforth interpreter by linking with the library
10578: @code{libgforth.a} (give the compiler the option @code{-lgforth}).  All
10579: global symbols in this library that belong to the interface, have the
10580: prefix @code{forth_}. (Global symbols that are used internally have the
10581: prefix @code{gforth_}).
10582: 
10583: You can include the declarations of Forth types and the functions and
10584: variables of the interface with @code{#include <forth.h>}.
10585: 
10586: Types.
10587: 
10588: Variables.
10589: 
10590: Data and FP Stack pointer. Area sizes.
10591: 
10592: functions.
10593: 
10594: forth_init(imagefile)
10595: forth_evaluate(string) exceptions?
10596: forth_goto(address) (or forth_execute(xt)?)
10597: forth_continue() (a corountining mechanism)
10598: 
10599: Adding primitives.
10600: 
10601: No checking.
10602: 
10603: Signals?
10604: 
10605: Accessing the Stacks
10606: 
10607: @c ******************************************************************
10608: @node Emacs and Gforth, Image Files, Integrating Gforth, Top
10609: @chapter Emacs and Gforth
10610: @cindex Emacs and Gforth
10611: 
10612: @cindex @file{gforth.el}
10613: @cindex @file{forth.el}
10614: @cindex Rydqvist, Goran
10615: @cindex comment editing commands
10616: @cindex @code{\}, editing with Emacs
10617: @cindex debug tracer editing commands
10618: @cindex @code{~~}, removal with Emacs
10619: @cindex Forth mode in Emacs
10620: Gforth comes with @file{gforth.el}, an improved version of
10621: @file{forth.el} by Goran Rydqvist (included in the TILE package). The
10622: improvements are:
10623: 
10624: @itemize @bullet
10625: @item
10626: A better (but still not perfect) handling of indentation.
10627: @item
10628: Comment paragraph filling (@kbd{M-q})
10629: @item
10630: Commenting (@kbd{C-x \}) and uncommenting (@kbd{C-u C-x \}) of regions
10631: @item
10632: Removal of debugging tracers (@kbd{C-x ~}, @pxref{Debugging}).
10633: @item
10634: Support of the @code{info-lookup} feature for looking up the
10635: documentation of a word.
10636: @end itemize
10637: 
10638: I left the stuff I do not use alone, even though some of it only makes
10639: sense for TILE. To get a description of these features, enter Forth mode
10640: and type @kbd{C-h m}.
10641: 
10642: @cindex source location of error or debugging output in Emacs
10643: @cindex error output, finding the source location in Emacs
10644: @cindex debugging output, finding the source location in Emacs
10645: In addition, Gforth supports Emacs quite well: The source code locations
10646: given in error messages, debugging output (from @code{~~}) and failed
10647: assertion messages are in the right format for Emacs' compilation mode
10648: (@pxref{Compilation, , Running Compilations under Emacs, emacs, Emacs
10649: Manual}) so the source location corresponding to an error or other
10650: message is only a few keystrokes away (@kbd{C-x `} for the next error,
10651: @kbd{C-c C-c} for the error under the cursor).
10652: 
10653: @cindex @file{TAGS} file
10654: @cindex @file{etags.fs}
10655: @cindex viewing the source of a word in Emacs
10656: @cindex @code{require}, placement in files
10657: @cindex @code{include}, placement in files
10658: Also, if you @code{require} @file{etags.fs}, a new @file{TAGS} file will
10659: be produced (@pxref{Tags, , Tags Tables, emacs, Emacs Manual}) that
10660: contains the definitions of all words defined afterwards. You can then
10661: find the source for a word using @kbd{M-.}. Note that emacs can use
10662: several tags files at the same time (e.g., one for the Gforth sources
10663: and one for your program, @pxref{Select Tags Table,,Selecting a Tags
10664: Table,emacs, Emacs Manual}). The TAGS file for the preloaded words is
10665: @file{$(datadir)/gforth/$(VERSION)/TAGS} (e.g.,
10666: @file{/usr/local/share/gforth/0.2.0/TAGS}).  To get the best behaviour
10667: with @file{etags.fs}, you should avoid putting definitions both before
10668: and after @code{require} etc., otherwise you will see the same file
10669: visited several times by commands like @code{tags-search}.
10670: 
10671: @cindex viewing the documentation of a word in Emacs
10672: @cindex context-sensitive help
10673: Moreover, for words documented in this manual, you can look up the
10674: glossary entry quickly by using @kbd{C-h TAB}
10675: (@code{info-lookup-symbol}, see @pxref{Documentation, ,Documentation
10676: Commands, emacs, Emacs Manual}).  This feature requires Emacs 20.3 or
10677: later and does not work for words containing @code{:}.
10678: 
10679: 
10680: @cindex @file{.emacs}
10681: To get all these benefits, add the following lines to your @file{.emacs}
10682: file:
10683: 
10684: @example
10685: (autoload 'forth-mode "gforth.el")
10686: (setq auto-mode-alist (cons '("\\.fs\\'" . forth-mode) auto-mode-alist))
10687: @end example
10688: 
10689: @c ******************************************************************
10690: @node Image Files, Engine, Emacs and Gforth, Top
10691: @chapter Image Files
10692: @cindex image file
10693: @cindex @file{.fi} files
10694: @cindex precompiled Forth code
10695: @cindex dictionary in persistent form
10696: @cindex persistent form of dictionary
10697: 
10698: An image file is a file containing an image of the Forth dictionary,
10699: i.e., compiled Forth code and data residing in the dictionary.  By
10700: convention, we use the extension @code{.fi} for image files.
10701: 
10702: @menu
10703: * Image Licensing Issues::      Distribution terms for images.
10704: * Image File Background::       Why have image files?
10705: * Non-Relocatable Image Files::   don't always work.
10706: * Data-Relocatable Image Files::  are better.
10707: * Fully Relocatable Image Files:: better yet.
10708: * Stack and Dictionary Sizes::  Setting the default sizes for an image.
10709: * Running Image Files::         @code{gforth -i @i{file}} or @i{file}.
10710: * Modifying the Startup Sequence::  and turnkey applications.
10711: @end menu
10712: 
10713: @node Image Licensing Issues, Image File Background, Image Files, Image Files
10714: @section Image Licensing Issues
10715: @cindex license for images
10716: @cindex image license
10717: 
10718: An image created with @code{gforthmi} (@pxref{gforthmi}) or
10719: @code{savesystem} (@pxref{Non-Relocatable Image Files}) includes the
10720: original image; i.e., according to copyright law it is a derived work of
10721: the original image.
10722: 
10723: Since Gforth is distributed under the GNU GPL, the newly created image
10724: falls under the GNU GPL, too. In particular, this means that if you
10725: distribute the image, you have to make all of the sources for the image
10726: available, including those you wrote.  For details see @ref{License, ,
10727: GNU General Public License (Section 3)}.
10728: 
10729: If you create an image with @code{cross} (@pxref{cross.fs}), the image
10730: contains only code compiled from the sources you gave it; if none of
10731: these sources is under the GPL, the terms discussed above do not apply
10732: to the image. However, if your image needs an engine (a gforth binary)
10733: that is under the GPL, you should make sure that you distribute both in
10734: a way that is at most a @emph{mere aggregation}, if you don't want the
10735: terms of the GPL to apply to the image.
10736: 
10737: @node Image File Background, Non-Relocatable Image Files, Image Licensing Issues, Image Files
10738: @section Image File Background
10739: @cindex image file background
10740: 
10741: Our Forth system consists not only of primitives, but also of
10742: definitions written in Forth. Since the Forth compiler itself belongs to
10743: those definitions, it is not possible to start the system with the
10744: primitives and the Forth source alone. Therefore we provide the Forth
10745: code as an image file in nearly executable form. When Gforth starts up,
10746: a C routine loads the image file into memory, optionally relocates the
10747: addresses, then sets up the memory (stacks etc.) according to
10748: information in the image file, and (finally) starts executing Forth
10749: code.
10750: 
10751: The image file variants represent different compromises between the
10752: goals of making it easy to generate image files and making them
10753: portable.
10754: 
10755: @cindex relocation at run-time
10756: Win32Forth 3.4 and Mitch Bradley's @code{cforth} use relocation at
10757: run-time. This avoids many of the complications discussed below (image
10758: files are data relocatable without further ado), but costs performance
10759: (one addition per memory access).
10760: 
10761: @cindex relocation at load-time
10762: By contrast, the Gforth loader performs relocation at image load time. The
10763: loader also has to replace tokens that represent primitive calls with the
10764: appropriate code-field addresses (or code addresses in the case of
10765: direct threading).
10766: 
10767: There are three kinds of image files, with different degrees of
10768: relocatability: non-relocatable, data-relocatable, and fully relocatable
10769: image files.
10770: 
10771: @cindex image file loader
10772: @cindex relocating loader
10773: @cindex loader for image files
10774: These image file variants have several restrictions in common; they are
10775: caused by the design of the image file loader:
10776: 
10777: @itemize @bullet
10778: @item
10779: There is only one segment; in particular, this means, that an image file
10780: cannot represent @code{ALLOCATE}d memory chunks (and pointers to
10781: them). The contents of the stacks are not represented, either.
10782: 
10783: @item
10784: The only kinds of relocation supported are: adding the same offset to
10785: all cells that represent data addresses; and replacing special tokens
10786: with code addresses or with pieces of machine code.
10787: 
10788: If any complex computations involving addresses are performed, the
10789: results cannot be represented in the image file. Several applications that
10790: use such computations come to mind:
10791: @itemize @minus
10792: @item
10793: Hashing addresses (or data structures which contain addresses) for table
10794: lookup. If you use Gforth's @code{table}s or @code{wordlist}s for this
10795: purpose, you will have no problem, because the hash tables are
10796: recomputed automatically when the system is started. If you use your own
10797: hash tables, you will have to do something similar.
10798: 
10799: @item
10800: There's a cute implementation of doubly-linked lists that uses
10801: @code{XOR}ed addresses. You could represent such lists as singly-linked
10802: in the image file, and restore the doubly-linked representation on
10803: startup.@footnote{In my opinion, though, you should think thrice before
10804: using a doubly-linked list (whatever implementation).}
10805: 
10806: @item
10807: The code addresses of run-time routines like @code{docol:} cannot be
10808: represented in the image file (because their tokens would be replaced by
10809: machine code in direct threaded implementations). As a workaround,
10810: compute these addresses at run-time with @code{>code-address} from the
10811: executions tokens of appropriate words (see the definitions of
10812: @code{docol:} and friends in @file{kernel.fs}).
10813: 
10814: @item
10815: On many architectures addresses are represented in machine code in some
10816: shifted or mangled form. You cannot put @code{CODE} words that contain
10817: absolute addresses in this form in a relocatable image file. Workarounds
10818: are representing the address in some relative form (e.g., relative to
10819: the CFA, which is present in some register), or loading the address from
10820: a place where it is stored in a non-mangled form.
10821: @end itemize
10822: @end itemize
10823: 
10824: @node  Non-Relocatable Image Files, Data-Relocatable Image Files, Image File Background, Image Files
10825: @section Non-Relocatable Image Files
10826: @cindex non-relocatable image files
10827: @cindex image file, non-relocatable
10828: 
10829: These files are simple memory dumps of the dictionary. They are specific
10830: to the executable (i.e., @file{gforth} file) they were created
10831: with. What's worse, they are specific to the place on which the
10832: dictionary resided when the image was created. Now, there is no
10833: guarantee that the dictionary will reside at the same place the next
10834: time you start Gforth, so there's no guarantee that a non-relocatable
10835: image will work the next time (Gforth will complain instead of crashing,
10836: though).
10837: 
10838: You can create a non-relocatable image file with
10839: 
10840: 
10841: doc-savesystem
10842: 
10843: 
10844: @node Data-Relocatable Image Files, Fully Relocatable Image Files, Non-Relocatable Image Files, Image Files
10845: @section Data-Relocatable Image Files
10846: @cindex data-relocatable image files
10847: @cindex image file, data-relocatable
10848: 
10849: These files contain relocatable data addresses, but fixed code addresses
10850: (instead of tokens). They are specific to the executable (i.e.,
10851: @file{gforth} file) they were created with. For direct threading on some
10852: architectures (e.g., the i386), data-relocatable images do not work. You
10853: get a data-relocatable image, if you use @file{gforthmi} with a
10854: Gforth binary that is not doubly indirect threaded (@pxref{Fully
10855: Relocatable Image Files}).
10856: 
10857: @node Fully Relocatable Image Files, Stack and Dictionary Sizes, Data-Relocatable Image Files, Image Files
10858: @section Fully Relocatable Image Files
10859: @cindex fully relocatable image files
10860: @cindex image file, fully relocatable
10861: 
10862: @cindex @file{kern*.fi}, relocatability
10863: @cindex @file{gforth.fi}, relocatability
10864: These image files have relocatable data addresses, and tokens for code
10865: addresses. They can be used with different binaries (e.g., with and
10866: without debugging) on the same machine, and even across machines with
10867: the same data formats (byte order, cell size, floating point
10868: format). However, they are usually specific to the version of Gforth
10869: they were created with. The files @file{gforth.fi} and @file{kernl*.fi}
10870: are fully relocatable.
10871: 
10872: There are two ways to create a fully relocatable image file:
10873: 
10874: @menu
10875: * gforthmi::                    The normal way
10876: * cross.fs::                    The hard way
10877: @end menu
10878: 
10879: @node gforthmi, cross.fs, Fully Relocatable Image Files, Fully Relocatable Image Files
10880: @subsection @file{gforthmi}
10881: @cindex @file{comp-i.fs}
10882: @cindex @file{gforthmi}
10883: 
10884: You will usually use @file{gforthmi}. If you want to create an
10885: image @i{file} that contains everything you would load by invoking
10886: Gforth with @code{gforth @i{options}}, you simply say:
10887: @example
10888: gforthmi @i{file} @i{options}
10889: @end example
10890: 
10891: E.g., if you want to create an image @file{asm.fi} that has the file
10892: @file{asm.fs} loaded in addition to the usual stuff, you could do it
10893: like this:
10894: 
10895: @example
10896: gforthmi asm.fi asm.fs
10897: @end example
10898: 
10899: @file{gforthmi} is implemented as a sh script and works like this: It
10900: produces two non-relocatable images for different addresses and then
10901: compares them. Its output reflects this: first you see the output (if
10902: any) of the two Gforth invocations that produce the nonrelocatable image
10903: files, then you see the output of the comparing program: It displays the
10904: offset used for data addresses and the offset used for code addresses;
10905: moreover, for each cell that cannot be represented correctly in the
10906: image files, it displays a line like this:
10907: 
10908: @example
10909:      78DC         BFFFFA50         BFFFFA40
10910: @end example
10911: 
10912: This means that at offset $78dc from @code{forthstart}, one input image
10913: contains $bffffa50, and the other contains $bffffa40. Since these cells
10914: cannot be represented correctly in the output image, you should examine
10915: these places in the dictionary and verify that these cells are dead
10916: (i.e., not read before they are written).
10917: 
10918: @cindex --application, @code{gforthmi} option
10919: If you insert the option @code{--application} in front of the image file
10920: name, you will get an image that uses the @code{--appl-image} option
10921: instead of the @code{--image-file} option (@pxref{Invoking
10922: Gforth}). When you execute such an image on Unix (by typing the image
10923: name as command), the Gforth engine will pass all options to the image
10924: instead of trying to interpret them as engine options.
10925: 
10926: If you type @file{gforthmi} with no arguments, it prints some usage
10927: instructions.
10928: 
10929: @cindex @code{savesystem} during @file{gforthmi}
10930: @cindex @code{bye} during @file{gforthmi}
10931: @cindex doubly indirect threaded code
10932: @cindex environment variables
10933: @cindex @code{GFORTHD} -- environment variable
10934: @cindex @code{GFORTH} -- environment variable
10935: @cindex @code{gforth-ditc}
10936: There are a few wrinkles: After processing the passed @i{options}, the
10937: words @code{savesystem} and @code{bye} must be visible. A special doubly
10938: indirect threaded version of the @file{gforth} executable is used for
10939: creating the nonrelocatable images; you can pass the exact filename of
10940: this executable through the environment variable @code{GFORTHD}
10941: (default: @file{gforth-ditc}); if you pass a version that is not doubly
10942: indirect threaded, you will not get a fully relocatable image, but a
10943: data-relocatable image (because there is no code address offset). The
10944: normal @file{gforth} executable is used for creating the relocatable
10945: image; you can pass the exact filename of this executable through the
10946: environment variable @code{GFORTH}.
10947: 
10948: @node cross.fs,  , gforthmi, Fully Relocatable Image Files
10949: @subsection @file{cross.fs}
10950: @cindex @file{cross.fs}
10951: @cindex cross-compiler
10952: @cindex metacompiler
10953: @cindex target compiler
10954: 
10955: You can also use @code{cross}, a batch compiler that accepts a Forth-like
10956: programming language (@pxref{Cross Compiler}).
10957: 
10958: @code{cross} allows you to create image files for machines with
10959: different data sizes and data formats than the one used for generating
10960: the image file. You can also use it to create an application image that
10961: does not contain a Forth compiler. These features are bought with
10962: restrictions and inconveniences in programming. E.g., addresses have to
10963: be stored in memory with special words (@code{A!}, @code{A,}, etc.) in
10964: order to make the code relocatable.
10965: 
10966: 
10967: @node Stack and Dictionary Sizes, Running Image Files, Fully Relocatable Image Files, Image Files
10968: @section Stack and Dictionary Sizes
10969: @cindex image file, stack and dictionary sizes
10970: @cindex dictionary size default
10971: @cindex stack size default
10972: 
10973: If you invoke Gforth with a command line flag for the size
10974: (@pxref{Invoking Gforth}), the size you specify is stored in the
10975: dictionary. If you save the dictionary with @code{savesystem} or create
10976: an image with @file{gforthmi}, this size will become the default
10977: for the resulting image file. E.g., the following will create a
10978: fully relocatable version of @file{gforth.fi} with a 1MB dictionary:
10979: 
10980: @example
10981: gforthmi gforth.fi -m 1M
10982: @end example
10983: 
10984: In other words, if you want to set the default size for the dictionary
10985: and the stacks of an image, just invoke @file{gforthmi} with the
10986: appropriate options when creating the image.
10987: 
10988: @cindex stack size, cache-friendly
10989: Note: For cache-friendly behaviour (i.e., good performance), you should
10990: make the sizes of the stacks modulo, say, 2K, somewhat different. E.g.,
10991: the default stack sizes are: data: 16k (mod 2k=0); fp: 15.5k (mod
10992: 2k=1.5k); return: 15k(mod 2k=1k); locals: 14.5k (mod 2k=0.5k).
10993: 
10994: @node Running Image Files, Modifying the Startup Sequence, Stack and Dictionary Sizes, Image Files
10995: @section Running Image Files
10996: @cindex running image files
10997: @cindex invoking image files
10998: @cindex image file invocation
10999: 
11000: @cindex -i, invoke image file
11001: @cindex --image file, invoke image file
11002: You can invoke Gforth with an image file @i{image} instead of the
11003: default @file{gforth.fi} with the @code{-i} flag (@pxref{Invoking Gforth}):
11004: @example
11005: gforth -i @i{image}
11006: @end example
11007: 
11008: @cindex executable image file
11009: @cindex image file, executable
11010: If your operating system supports starting scripts with a line of the
11011: form @code{#! ...}, you just have to type the image file name to start
11012: Gforth with this image file (note that the file extension @code{.fi} is
11013: just a convention). I.e., to run Gforth with the image file @i{image},
11014: you can just type @i{image} instead of @code{gforth -i @i{image}}.
11015: This works because every @code{.fi} file starts with a line of this
11016: format:
11017: 
11018: @example
11019: #! /usr/local/bin/gforth-0.4.0 -i
11020: @end example
11021: 
11022: The file and pathname for the Gforth engine specified on this line is
11023: the specific Gforth executable that it was built against; i.e. the value
11024: of the environment variable @code{GFORTH} at the time that
11025: @file{gforthmi} was executed.
11026: 
11027: You can make use of the same shell capability to make a Forth source
11028: file into an executable. For example, if you place this text in a file:
11029: 
11030: @example
11031: #! /usr/local/bin/gforth
11032: 
11033: ." Hello, world" CR
11034: bye
11035: @end example
11036: 
11037: @noindent
11038: and then make the file executable (chmod +x in Unix), you can run it
11039: directly from the command line. The sequence @code{#!} is used in two
11040: ways; firstly, it is recognised as a ``magic sequence'' by the operating
11041: system@footnote{The Unix kernel actually recognises two types of files:
11042: executable files and files of data, where the data is processed by an
11043: interpreter that is specified on the ``interpreter line'' -- the first
11044: line of the file, starting with the sequence #!. There may be a small
11045: limit (e.g., 32) on the number of characters that may be specified on
11046: the interpreter line.} secondly it is treated as a comment character by
11047: Gforth. Because of the second usage, a space is required between
11048: @code{#!} and the path to the executable.
11049: 
11050: The disadvantage of this latter technique, compared with using
11051: @file{gforthmi}, is that it is slower; the Forth source code is compiled
11052: on-the-fly, each time the program is invoked.
11053: 
11054: 
11055: doc-#!
11056: 
11057: 
11058: @node Modifying the Startup Sequence,  , Running Image Files, Image Files
11059: @section Modifying the Startup Sequence
11060: @cindex startup sequence for image file
11061: @cindex image file initialization sequence
11062: @cindex initialization sequence of image file
11063: 
11064: You can add your own initialization to the startup sequence through the
11065: deferred word @code{'cold}. @code{'cold} is invoked just before the
11066: image-specific command line processing (by default, loading files and
11067: evaluating (@code{-e}) strings) starts.
11068: 
11069: A sequence for adding your initialization usually looks like this:
11070: 
11071: @example
11072: :noname
11073:     Defers 'cold \ do other initialization stuff (e.g., rehashing wordlists)
11074:     ... \ your stuff
11075: ; IS 'cold
11076: @end example
11077: 
11078: @cindex turnkey image files
11079: @cindex image file, turnkey applications
11080: You can make a turnkey image by letting @code{'cold} execute a word
11081: (your turnkey application) that never returns; instead, it exits Gforth
11082: via @code{bye} or @code{throw}.
11083: 
11084: @cindex command-line arguments, access
11085: @cindex arguments on the command line, access
11086: You can access the (image-specific) command-line arguments through the
11087: variables @code{argc} and @code{argv}. @code{arg} provides convenient
11088: access to @code{argv}.
11089: 
11090: If @code{'cold} exits normally, Gforth processes the command-line
11091: arguments as files to be loaded and strings to be evaluated.  Therefore,
11092: @code{'cold} should remove the arguments it has used in this case.
11093: 
11094: 
11095: 
11096: doc-'cold
11097: doc-argc
11098: doc-argv
11099: doc-arg
11100: 
11101: 
11102: 
11103: @c ******************************************************************
11104: @node Engine, Binding to System Library, Image Files, Top
11105: @chapter Engine
11106: @cindex engine
11107: @cindex virtual machine
11108: 
11109: Reading this chapter is not necessary for programming with Gforth. It
11110: may be helpful for finding your way in the Gforth sources.
11111: 
11112: The ideas in this section have also been published in the papers
11113: @cite{ANS fig/GNU/??? Forth} (in German) by Bernd Paysan, presented at
11114: the Forth-Tagung '93 and @cite{A Portable Forth Engine} by M. Anton
11115: Ertl, presented at EuroForth '93; the latter is available at
11116: @*@uref{http://www.complang.tuwien.ac.at/papers/ertl93.ps.Z}.
11117: 
11118: @menu
11119: * Portability::                 
11120: * Threading::                   
11121: * Primitives::                  
11122: * Performance::                 
11123: @end menu
11124: 
11125: @node Portability, Threading, Engine, Engine
11126: @section Portability
11127: @cindex engine portability
11128: 
11129: An important goal of the Gforth Project is availability across a wide
11130: range of personal machines. fig-Forth, and, to a lesser extent, F83,
11131: achieved this goal by manually coding the engine in assembly language
11132: for several then-popular processors. This approach is very
11133: labor-intensive and the results are short-lived due to progress in
11134: computer architecture.
11135: 
11136: @cindex C, using C for the engine
11137: Others have avoided this problem by coding in C, e.g., Mitch Bradley
11138: (cforth), Mikael Patel (TILE) and Dirk Zoller (pfe). This approach is
11139: particularly popular for UNIX-based Forths due to the large variety of
11140: architectures of UNIX machines. Unfortunately an implementation in C
11141: does not mix well with the goals of efficiency and with using
11142: traditional techniques: Indirect or direct threading cannot be expressed
11143: in C, and switch threading, the fastest technique available in C, is
11144: significantly slower. Another problem with C is that it is very
11145: cumbersome to express double integer arithmetic.
11146: 
11147: @cindex GNU C for the engine
11148: @cindex long long
11149: Fortunately, there is a portable language that does not have these
11150: limitations: GNU C, the version of C processed by the GNU C compiler
11151: (@pxref{C Extensions, , Extensions to the C Language Family, gcc.info,
11152: GNU C Manual}). Its labels as values feature (@pxref{Labels as Values, ,
11153: Labels as Values, gcc.info, GNU C Manual}) makes direct and indirect
11154: threading possible, its @code{long long} type (@pxref{Long Long, ,
11155: Double-Word Integers, gcc.info, GNU C Manual}) corresponds to Forth's
11156: double numbers@footnote{Unfortunately, long longs are not implemented
11157: properly on all machines (e.g., on alpha-osf1, long longs are only 64
11158: bits, the same size as longs (and pointers), but they should be twice as
11159: long according to @pxref{Long Long, , Double-Word Integers, gcc.info, GNU
11160: C Manual}). So, we had to implement doubles in C after all. Still, on
11161: most machines we can use long longs and achieve better performance than
11162: with the emulation package.}. GNU C is available for free on all
11163: important (and many unimportant) UNIX machines, VMS, 80386s running
11164: MS-DOS, the Amiga, and the Atari ST, so a Forth written in GNU C can run
11165: on all these machines.
11166: 
11167: Writing in a portable language has the reputation of producing code that
11168: is slower than assembly. For our Forth engine we repeatedly looked at
11169: the code produced by the compiler and eliminated most compiler-induced
11170: inefficiencies by appropriate changes in the source code.
11171: 
11172: @cindex explicit register declarations
11173: @cindex --enable-force-reg, configuration flag
11174: @cindex -DFORCE_REG
11175: However, register allocation cannot be portably influenced by the
11176: programmer, leading to some inefficiencies on register-starved
11177: machines. We use explicit register declarations (@pxref{Explicit Reg
11178: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) to
11179: improve the speed on some machines. They are turned on by using the
11180: configuration flag @code{--enable-force-reg} (@code{gcc} switch
11181: @code{-DFORCE_REG}). Unfortunately, this feature not only depends on the
11182: machine, but also on the compiler version: On some machines some
11183: compiler versions produce incorrect code when certain explicit register
11184: declarations are used. So by default @code{-DFORCE_REG} is not used.
11185: 
11186: @node Threading, Primitives, Portability, Engine
11187: @section Threading
11188: @cindex inner interpreter implementation
11189: @cindex threaded code implementation
11190: 
11191: @cindex labels as values
11192: GNU C's labels as values extension (available since @code{gcc-2.0},
11193: @pxref{Labels as Values, , Labels as Values, gcc.info, GNU C Manual})
11194: makes it possible to take the address of @i{label} by writing
11195: @code{&&@i{label}}.  This address can then be used in a statement like
11196: @code{goto *@i{address}}. I.e., @code{goto *&&x} is the same as
11197: @code{goto x}.
11198: 
11199: @cindex @code{NEXT}, indirect threaded
11200: @cindex indirect threaded inner interpreter
11201: @cindex inner interpreter, indirect threaded
11202: With this feature an indirect threaded @code{NEXT} looks like:
11203: @example
11204: cfa = *ip++;
11205: ca = *cfa;
11206: goto *ca;
11207: @end example
11208: @cindex instruction pointer
11209: For those unfamiliar with the names: @code{ip} is the Forth instruction
11210: pointer; the @code{cfa} (code-field address) corresponds to ANS Forths
11211: execution token and points to the code field of the next word to be
11212: executed; The @code{ca} (code address) fetched from there points to some
11213: executable code, e.g., a primitive or the colon definition handler
11214: @code{docol}.
11215: 
11216: @cindex @code{NEXT}, direct threaded
11217: @cindex direct threaded inner interpreter
11218: @cindex inner interpreter, direct threaded
11219: Direct threading is even simpler:
11220: @example
11221: ca = *ip++;
11222: goto *ca;
11223: @end example
11224: 
11225: Of course we have packaged the whole thing neatly in macros called
11226: @code{NEXT} and @code{NEXT1} (the part of @code{NEXT} after fetching the cfa).
11227: 
11228: @menu
11229: * Scheduling::                  
11230: * Direct or Indirect Threaded?::  
11231: * DOES>::                       
11232: @end menu
11233: 
11234: @node Scheduling, Direct or Indirect Threaded?, Threading, Threading
11235: @subsection Scheduling
11236: @cindex inner interpreter optimization
11237: 
11238: There is a little complication: Pipelined and superscalar processors,
11239: i.e., RISC and some modern CISC machines can process independent
11240: instructions while waiting for the results of an instruction. The
11241: compiler usually reorders (schedules) the instructions in a way that
11242: achieves good usage of these delay slots. However, on our first tries
11243: the compiler did not do well on scheduling primitives. E.g., for
11244: @code{+} implemented as
11245: @example
11246: n=sp[0]+sp[1];
11247: sp++;
11248: sp[0]=n;
11249: NEXT;
11250: @end example
11251: the @code{NEXT} comes strictly after the other code, i.e., there is nearly no
11252: scheduling. After a little thought the problem becomes clear: The
11253: compiler cannot know that @code{sp} and @code{ip} point to different
11254: addresses (and the version of @code{gcc} we used would not know it even
11255: if it was possible), so it could not move the load of the cfa above the
11256: store to the TOS. Indeed the pointers could be the same, if code on or
11257: very near the top of stack were executed. In the interest of speed we
11258: chose to forbid this probably unused ``feature'' and helped the compiler
11259: in scheduling: @code{NEXT} is divided into the loading part (@code{NEXT_P1})
11260: and the goto part (@code{NEXT_P2}). @code{+} now looks like:
11261: @example
11262: n=sp[0]+sp[1];
11263: sp++;
11264: NEXT_P1;
11265: sp[0]=n;
11266: NEXT_P2;
11267: @end example
11268: This can be scheduled optimally by the compiler.
11269: 
11270: This division can be turned off with the switch @code{-DCISC_NEXT}. This
11271: switch is on by default on machines that do not profit from scheduling
11272: (e.g., the 80386), in order to preserve registers.
11273: 
11274: @node Direct or Indirect Threaded?, DOES>, Scheduling, Threading
11275: @subsection Direct or Indirect Threaded?
11276: @cindex threading, direct or indirect?
11277: 
11278: @cindex -DDIRECT_THREADED
11279: Both! After packaging the nasty details in macro definitions we
11280: realized that we could switch between direct and indirect threading by
11281: simply setting a compilation flag (@code{-DDIRECT_THREADED}) and
11282: defining a few machine-specific macros for the direct-threading case.
11283: On the Forth level we also offer access words that hide the
11284: differences between the threading methods (@pxref{Threading Words}).
11285: 
11286: Indirect threading is implemented completely machine-independently.
11287: Direct threading needs routines for creating jumps to the executable
11288: code (e.g. to @code{docol} or @code{dodoes}). These routines are inherently
11289: machine-dependent, but they do not amount to many source lines. Therefore,
11290: even porting direct threading to a new machine requires little effort.
11291: 
11292: @cindex --enable-indirect-threaded, configuration flag
11293: @cindex --enable-direct-threaded, configuration flag
11294: The default threading method is machine-dependent. You can enforce a
11295: specific threading method when building Gforth with the configuration
11296: flag @code{--enable-direct-threaded} or
11297: @code{--enable-indirect-threaded}. Note that direct threading is not
11298: supported on all machines.
11299: 
11300: @node DOES>,  , Direct or Indirect Threaded?, Threading
11301: @subsection DOES>
11302: @cindex @code{DOES>} implementation
11303: 
11304: @cindex @code{dodoes} routine
11305: @cindex @code{DOES>}-code
11306: One of the most complex parts of a Forth engine is @code{dodoes}, i.e.,
11307: the chunk of code executed by every word defined by a
11308: @code{CREATE}...@code{DOES>} pair. The main problem here is: How to find
11309: the Forth code to be executed, i.e. the code after the
11310: @code{DOES>} (the @code{DOES>}-code)? There are two solutions:
11311: 
11312: In fig-Forth the code field points directly to the @code{dodoes} and the
11313: @code{DOES>}-code address is stored in the cell after the code address (i.e. at
11314: @code{@i{CFA} cell+}). It may seem that this solution is illegal in
11315: the Forth-79 and all later standards, because in fig-Forth this address
11316: lies in the body (which is illegal in these standards). However, by
11317: making the code field larger for all words this solution becomes legal
11318: again. We use this approach for the indirect threaded version and for
11319: direct threading on some machines. Leaving a cell unused in most words
11320: is a bit wasteful, but on the machines we are targeting this is hardly a
11321: problem. The other reason for having a code field size of two cells is
11322: to avoid having different image files for direct and indirect threaded
11323: systems (direct threaded systems require two-cell code fields on many
11324: machines).
11325: 
11326: @cindex @code{DOES>}-handler
11327: The other approach is that the code field points or jumps to the cell
11328: after @code{DOES>}. In this variant there is a jump to @code{dodoes} at
11329: this address (the @code{DOES>}-handler). @code{dodoes} can then get the
11330: @code{DOES>}-code address by computing the code address, i.e., the address of
11331: the jump to @code{dodoes}, and add the length of that jump field. A variant of
11332: this is to have a call to @code{dodoes} after the @code{DOES>}; then the
11333: return address (which can be found in the return register on RISCs) is
11334: the @code{DOES>}-code address. Since the two cells available in the code field
11335: are used up by the jump to the code address in direct threading on many
11336: architectures, we use this approach for direct threading on these
11337: architectures. We did not want to add another cell to the code field.
11338: 
11339: @node Primitives, Performance, Threading, Engine
11340: @section Primitives
11341: @cindex primitives, implementation
11342: @cindex virtual machine instructions, implementation
11343: 
11344: @menu
11345: * Automatic Generation::        
11346: * TOS Optimization::            
11347: * Produced code::               
11348: @end menu
11349: 
11350: @node Automatic Generation, TOS Optimization, Primitives, Primitives
11351: @subsection Automatic Generation
11352: @cindex primitives, automatic generation
11353: 
11354: @cindex @file{prims2x.fs}
11355: Since the primitives are implemented in a portable language, there is no
11356: longer any need to minimize the number of primitives. On the contrary,
11357: having many primitives has an advantage: speed. In order to reduce the
11358: number of errors in primitives and to make programming them easier, we
11359: provide a tool, the primitive generator (@file{prims2x.fs}), that
11360: automatically generates most (and sometimes all) of the C code for a
11361: primitive from the stack effect notation.  The source for a primitive
11362: has the following form:
11363: 
11364: @cindex primitive source format
11365: @format
11366: @i{Forth-name}  @i{stack-effect}        @i{category}    [@i{pronounc.}]
11367: [@code{""}@i{glossary entry}@code{""}]
11368: @i{C code}
11369: [@code{:}
11370: @i{Forth code}]
11371: @end format
11372: 
11373: The items in brackets are optional. The category and glossary fields
11374: are there for generating the documentation, the Forth code is there
11375: for manual implementations on machines without GNU C. E.g., the source
11376: for the primitive @code{+} is:
11377: @example
11378: +    n1 n2 -- n    core    plus
11379: n = n1+n2;
11380: @end example
11381: 
11382: This looks like a specification, but in fact @code{n = n1+n2} is C
11383: code. Our primitive generation tool extracts a lot of information from
11384: the stack effect notations@footnote{We use a one-stack notation, even
11385: though we have separate data and floating-point stacks; The separate
11386: notation can be generated easily from the unified notation.}: The number
11387: of items popped from and pushed on the stack, their type, and by what
11388: name they are referred to in the C code. It then generates a C code
11389: prelude and postlude for each primitive. The final C code for @code{+}
11390: looks like this:
11391: 
11392: @example
11393: I_plus: /* + ( n1 n2 -- n ) */  /* label, stack effect */
11394: /*  */                          /* documentation */
11395: @{
11396: DEF_CA                          /* definition of variable ca (indirect threading) */
11397: Cell n1;                        /* definitions of variables */
11398: Cell n2;
11399: Cell n;
11400: n1 = (Cell) sp[1];              /* input */
11401: n2 = (Cell) TOS;
11402: sp += 1;                        /* stack adjustment */
11403: NAME("+")                       /* debugging output (with -DDEBUG) */
11404: @{
11405: n = n1+n2;                      /* C code taken from the source */
11406: @}
11407: NEXT_P1;                        /* NEXT part 1 */
11408: TOS = (Cell)n;                  /* output */
11409: NEXT_P2;                        /* NEXT part 2 */
11410: @}
11411: @end example
11412: 
11413: This looks long and inefficient, but the GNU C compiler optimizes quite
11414: well and produces optimal code for @code{+} on, e.g., the R3000 and the
11415: HP RISC machines: Defining the @code{n}s does not produce any code, and
11416: using them as intermediate storage also adds no cost.
11417: 
11418: There are also other optimizations that are not illustrated by this
11419: example: assignments between simple variables are usually for free (copy
11420: propagation). If one of the stack items is not used by the primitive
11421: (e.g.  in @code{drop}), the compiler eliminates the load from the stack
11422: (dead code elimination). On the other hand, there are some things that
11423: the compiler does not do, therefore they are performed by
11424: @file{prims2x.fs}: The compiler does not optimize code away that stores
11425: a stack item to the place where it just came from (e.g., @code{over}).
11426: 
11427: While programming a primitive is usually easy, there are a few cases
11428: where the programmer has to take the actions of the generator into
11429: account, most notably @code{?dup}, but also words that do not (always)
11430: fall through to @code{NEXT}.
11431: 
11432: @node TOS Optimization, Produced code, Automatic Generation, Primitives
11433: @subsection TOS Optimization
11434: @cindex TOS optimization for primitives
11435: @cindex primitives, keeping the TOS in a register
11436: 
11437: An important optimization for stack machine emulators, e.g., Forth
11438: engines, is keeping  one or more of the top stack items in
11439: registers.  If a word has the stack effect @i{in1}...@i{inx} @code{--}
11440: @i{out1}...@i{outy}, keeping the top @i{n} items in registers
11441: @itemize @bullet
11442: @item
11443: is better than keeping @i{n-1} items, if @i{x>=n} and @i{y>=n},
11444: due to fewer loads from and stores to the stack.
11445: @item is slower than keeping @i{n-1} items, if @i{x<>y} and @i{x<n} and
11446: @i{y<n}, due to additional moves between registers.
11447: @end itemize
11448: 
11449: @cindex -DUSE_TOS
11450: @cindex -DUSE_NO_TOS
11451: In particular, keeping one item in a register is never a disadvantage,
11452: if there are enough registers. Keeping two items in registers is a
11453: disadvantage for frequent words like @code{?branch}, constants,
11454: variables, literals and @code{i}. Therefore our generator only produces
11455: code that keeps zero or one items in registers. The generated C code
11456: covers both cases; the selection between these alternatives is made at
11457: C-compile time using the switch @code{-DUSE_TOS}. @code{TOS} in the C
11458: code for @code{+} is just a simple variable name in the one-item case,
11459: otherwise it is a macro that expands into @code{sp[0]}. Note that the
11460: GNU C compiler tries to keep simple variables like @code{TOS} in
11461: registers, and it usually succeeds, if there are enough registers.
11462: 
11463: @cindex -DUSE_FTOS
11464: @cindex -DUSE_NO_FTOS
11465: The primitive generator performs the TOS optimization for the
11466: floating-point stack, too (@code{-DUSE_FTOS}). For floating-point
11467: operations the benefit of this optimization is even larger:
11468: floating-point operations take quite long on most processors, but can be
11469: performed in parallel with other operations as long as their results are
11470: not used. If the FP-TOS is kept in a register, this works. If
11471: it is kept on the stack, i.e., in memory, the store into memory has to
11472: wait for the result of the floating-point operation, lengthening the
11473: execution time of the primitive considerably.
11474: 
11475: The TOS optimization makes the automatic generation of primitives a
11476: bit more complicated. Just replacing all occurrences of @code{sp[0]} by
11477: @code{TOS} is not sufficient. There are some special cases to
11478: consider:
11479: @itemize @bullet
11480: @item In the case of @code{dup ( w -- w w )} the generator must not
11481: eliminate the store to the original location of the item on the stack,
11482: if the TOS optimization is turned on.
11483: @item Primitives with stack effects of the form @code{--}
11484: @i{out1}...@i{outy} must store the TOS to the stack at the start.
11485: Likewise, primitives with the stack effect @i{in1}...@i{inx} @code{--}
11486: must load the TOS from the stack at the end. But for the null stack
11487: effect @code{--} no stores or loads should be generated.
11488: @end itemize
11489: 
11490: @node Produced code,  , TOS Optimization, Primitives
11491: @subsection Produced code
11492: @cindex primitives, assembly code listing
11493: 
11494: @cindex @file{engine.s}
11495: To see what assembly code is produced for the primitives on your machine
11496: with your compiler and your flag settings, type @code{make engine.s} and
11497: look at the resulting file @file{engine.s}.
11498: 
11499: @node  Performance,  , Primitives, Engine
11500: @section Performance
11501: @cindex performance of some Forth interpreters
11502: @cindex engine performance
11503: @cindex benchmarking Forth systems
11504: @cindex Gforth performance
11505: 
11506: On RISCs the Gforth engine is very close to optimal; i.e., it is usually
11507: impossible to write a significantly faster engine.
11508: 
11509: On register-starved machines like the 386 architecture processors
11510: improvements are possible, because @code{gcc} does not utilize the
11511: registers as well as a human, even with explicit register declarations;
11512: e.g., Bernd Beuster wrote a Forth system fragment in assembly language
11513: and hand-tuned it for the 486; this system is 1.19 times faster on the
11514: Sieve benchmark on a 486DX2/66 than Gforth compiled with
11515: @code{gcc-2.6.3} with @code{-DFORCE_REG}.  The situation has improved
11516: with gcc-2.95 and gforth-0.4.9; now the most important virtual machine
11517: registers fit in real registers (and we can even afford to use the TOS
11518: optimization), resulting in a speedup of 1.14 on the sieve over the
11519: earlier results.
11520: 
11521: @cindex Win32Forth performance
11522: @cindex NT Forth performance
11523: @cindex eforth performance
11524: @cindex ThisForth performance
11525: @cindex PFE performance
11526: @cindex TILE performance
11527: The potential advantage of assembly language implementations
11528: is not necessarily realized in complete Forth systems: We compared
11529: Gforth-0.4.9 (direct threaded, compiled with @code{gcc-2.95.1} and
11530: @code{-DFORCE_REG}) with Win32Forth 1.2093, LMI's NT Forth (Beta, May
11531: 1994) and Eforth (with and without peephole (aka pinhole) optimization
11532: of the threaded code); all these systems were written in assembly
11533: language. We also compared Gforth with three systems written in C:
11534: PFE-0.9.14 (compiled with @code{gcc-2.6.3} with the default
11535: configuration for Linux: @code{-O2 -fomit-frame-pointer -DUSE_REGS
11536: -DUNROLL_NEXT}), ThisForth Beta (compiled with @code{gcc-2.6.3 -O3
11537: -fomit-frame-pointer}; ThisForth employs peephole optimization of the
11538: threaded code) and TILE (compiled with @code{make opt}). We benchmarked
11539: Gforth, PFE, ThisForth and TILE on a 486DX2/66 under Linux. Kenneth
11540: O'Heskin kindly provided the results for Win32Forth and NT Forth on a
11541: 486DX2/66 with similar memory performance under Windows NT. Marcel
11542: Hendrix ported Eforth to Linux, then extended it to run the benchmarks,
11543: added the peephole optimizer, ran the benchmarks and reported the
11544: results.
11545: 
11546: We used four small benchmarks: the ubiquitous Sieve; bubble-sorting and
11547: matrix multiplication come from the Stanford integer benchmarks and have
11548: been translated into Forth by Martin Fraeman; we used the versions
11549: included in the TILE Forth package, but with bigger data set sizes; and
11550: a recursive Fibonacci number computation for benchmarking calling
11551: performance. The following table shows the time taken for the benchmarks
11552: scaled by the time taken by Gforth (in other words, it shows the speedup
11553: factor that Gforth achieved over the other systems).
11554: 
11555: @example
11556: relative      Win32-    NT       eforth       This-      
11557:   time  Gforth Forth Forth eforth  +opt   PFE Forth  TILE
11558: sieve     1.00  1.58  1.30   1.58  0.97  1.80  3.63  9.79
11559: bubble    1.00  1.55  1.67   1.75  1.04  1.78        4.59
11560: matmul    1.00  1.67  1.53   1.66  0.84  1.79        4.63
11561: fib       1.00  1.75  1.53   1.40  0.99  1.99  3.43  4.93
11562: @end example
11563: 
11564: You may be quite surprised by the good performance of Gforth when
11565: compared with systems written in assembly language. One important reason
11566: for the disappointing performance of these other systems is probably
11567: that they are not written optimally for the 486 (e.g., they use the
11568: @code{lods} instruction). In addition, Win32Forth uses a comfortable,
11569: but costly method for relocating the Forth image: like @code{cforth}, it
11570: computes the actual addresses at run time, resulting in two address
11571: computations per @code{NEXT} (@pxref{Image File Background}).
11572: 
11573: Only Eforth with the peephole optimizer performs comparable to
11574: Gforth. The speedups achieved with peephole optimization of threaded
11575: code are quite remarkable. Adding a peephole optimizer to Gforth should
11576: cause similar speedups.
11577: 
11578: The speedup of Gforth over PFE, ThisForth and TILE can be easily
11579: explained with the self-imposed restriction of the latter systems to
11580: standard C, which makes efficient threading impossible (however, the
11581: measured implementation of PFE uses a GNU C extension: @pxref{Global Reg
11582: Vars, , Defining Global Register Variables, gcc.info, GNU C Manual}).
11583: Moreover, current C compilers have a hard time optimizing other aspects
11584: of the ThisForth and the TILE source.
11585: 
11586: The performance of Gforth on 386 architecture processors varies widely
11587: with the version of @code{gcc} used. E.g., @code{gcc-2.5.8} failed to
11588: allocate any of the virtual machine registers into real machine
11589: registers by itself and would not work correctly with explicit register
11590: declarations, giving a 1.5 times slower engine (on a 486DX2/66 running
11591: the Sieve) than the one measured above.
11592: 
11593: Note that there have been several releases of Win32Forth since the
11594: release presented here, so the results presented above may have little
11595: predictive value for the performance of Win32Forth today (results for
11596: the current release on an i486DX2/66 are welcome).
11597: 
11598: @cindex @file{Benchres}
11599: In @cite{Translating Forth to Efficient C} by M. Anton Ertl and Martin
11600: Maierhofer (presented at EuroForth '95), an indirect threaded version of
11601: Gforth is compared with Win32Forth, NT Forth, PFE, and ThisForth; that
11602: version of Gforth is slower on a 486 than the direct threaded version
11603: used here. The paper available at
11604: @*@uref{http://www.complang.tuwien.ac.at/papers/ertl&maierhofer95.ps.gz};
11605: it also contains numbers for some native code systems. You can find a
11606: newer version of these measurements at
11607: @uref{http://www.complang.tuwien.ac.at/forth/performance.html}. You can
11608: find numbers for Gforth on various machines in @file{Benchres}.
11609: 
11610: @c ******************************************************************
11611: @node Binding to System Library, Cross Compiler, Engine, Top
11612: @chapter Binding to System Library
11613: 
11614: @node Cross Compiler, Bugs, Binding to System Library, Top
11615: @chapter Cross Compiler
11616: @cindex @file{cross.fs}
11617: @cindex cross-compiler
11618: @cindex metacompiler
11619: @cindex target compiler
11620: 
11621: The cross compiler is used to bootstrap a Forth kernel. Since Gforth is
11622: mostly written in Forth, including crucial parts like the outer
11623: interpreter and compiler, it needs compiled Forth code to get
11624: started. The cross compiler allows to create new images for other
11625: architectures, even running under another Forth system.
11626: 
11627: @menu
11628: * Using the Cross Compiler::
11629: * How the Cross Compiler Works::
11630: @end menu
11631: 
11632: @node Using the Cross Compiler, How the Cross Compiler Works, Cross Compiler, Cross Compiler
11633: @section Using the Cross Compiler
11634: 
11635: The cross compiler uses a language that resembles Forth, but isn't. The
11636: main difference is that you can execute Forth code after definition,
11637: while you usually can't execute the code compiled by cross, because the
11638: code you are compiling is typically for a different computer than the
11639: one you are compiling on.
11640: 
11641: The Makefile is already set up to allow you to create kernels for new
11642: architectures with a simple make command. The generic kernels using the
11643: GCC compiled virtual machine are created in the normal build process
11644: with @code{make}. To create a embedded Gforth executable for e.g. the
11645: 8086 processor (running on a DOS machine), type
11646: 
11647: @example
11648: make kernl-8086.fi
11649: @end example
11650: 
11651: This will use the machine description from the @file{arch/8086}
11652: directory to create a new kernel. A machine file may look like that:
11653: 
11654: @example
11655: \ Parameter for target systems                         06oct92py
11656: 
11657:     4 Constant cell             \ cell size in bytes
11658:     2 Constant cell<<           \ cell shift to bytes
11659:     5 Constant cell>bit         \ cell shift to bits
11660:     8 Constant bits/char        \ bits per character
11661:     8 Constant bits/byte        \ bits per byte [default: 8]
11662:     8 Constant float            \ bytes per float
11663:     8 Constant /maxalign        \ maximum alignment in bytes
11664: false Constant bigendian        \ byte order
11665: ( true=big, false=little )
11666: 
11667: include machpc.fs               \ feature list
11668: @end example
11669: 
11670: This part is obligatory for the cross compiler itself, the feature list
11671: is used by the kernel to conditionally compile some features in and out,
11672: depending on whether the target supports these features.
11673: 
11674: There are some optional features, if you define your own primitives,
11675: have an assembler, or need special, nonstandard preparation to make the
11676: boot process work. @code{asm-include} include an assembler,
11677: @code{prims-include} includes primitives, and @code{>boot} prepares for
11678: booting.
11679: 
11680: @example
11681: : asm-include    ." Include assembler" cr
11682:   s" arch/8086/asm.fs" included ;
11683: 
11684: : prims-include  ." Include primitives" cr
11685:   s" arch/8086/prim.fs" included ;
11686: 
11687: : >boot          ." Prepare booting" cr
11688:   s" ' boot >body into-forth 1+ !" evaluate ;
11689: @end example
11690: 
11691: These words are used as sort of macro during the cross compilation in
11692: the file @file{kernel/main.fs}. Instead of using this macros, it would
11693: be possible --- but more complicated --- to write a new kernel project
11694: file, too.
11695: 
11696: @file{kernel/main.fs} expects the machine description file name on the
11697: stack; the cross compiler itself (@file{cross.fs}) assumes that either
11698: @code{mach-file} leaves a counted string on the stack, or
11699: @code{machine-file} leaves an address, count pair of the filename on the
11700: stack.
11701: 
11702: The feature list is typically controlled using @code{SetValue}, generic
11703: files that are used by several projects can use @code{DefaultValue}
11704: instead. Both functions work like @code{Value}, when the value isn't
11705: defined, but @code{SetValue} works like @code{to} if the value is
11706: defined, and @code{DefaultValue} doesn't set anything, if the value is
11707: defined.
11708: 
11709: @example
11710: \ generic mach file for pc gforth                       03sep97jaw
11711: 
11712: true DefaultValue NIL  \ relocating
11713: 
11714: >ENVIRON
11715: 
11716: true DefaultValue file          \ controls the presence of the
11717:                                 \ file access wordset
11718: true DefaultValue OS            \ flag to indicate a operating system
11719: 
11720: true DefaultValue prims         \ true: primitives are c-code
11721: 
11722: true DefaultValue floating      \ floating point wordset is present
11723: 
11724: true DefaultValue glocals       \ gforth locals are present
11725:                                 \ will be loaded
11726: true DefaultValue dcomps        \ double number comparisons
11727: 
11728: true DefaultValue hash          \ hashing primitives are loaded/present
11729: 
11730: true DefaultValue xconds        \ used together with glocals,
11731:                                 \ special conditionals supporting gforths'
11732:                                 \ local variables
11733: true DefaultValue header        \ save a header information
11734: 
11735: true DefaultValue backtrace     \ enables backtrace code
11736: 
11737: false DefaultValue ec
11738: false DefaultValue crlf
11739: 
11740: cell 2 = [IF] &32 [ELSE] &256 [THEN] KB DefaultValue kernel-size
11741: 
11742: &16 KB          DefaultValue stack-size
11743: &15 KB &512 +   DefaultValue fstack-size
11744: &15 KB          DefaultValue rstack-size
11745: &14 KB &512 +   DefaultValue lstack-size
11746: @end example
11747: 
11748: @node How the Cross Compiler Works, , Using the Cross Compiler, Cross Compiler
11749: @section How the Cross Compiler Works
11750: 
11751: @node Bugs, Origin, Cross Compiler, Top
11752: @appendix Bugs
11753: @cindex bug reporting
11754: 
11755: Known bugs are described in the file @file{BUGS} in the Gforth distribution.
11756: 
11757: If you find a bug, please send a bug report to
11758: @email{bug-gforth@@gnu.org}. A bug report should include this
11759: information:
11760: 
11761: @itemize @bullet
11762: @item
11763: The Gforth version used (it is announced at the start of an
11764: interactive Gforth session).
11765: @item
11766: The machine and operating system (on Unix
11767: systems @code{uname -a} will report this information).
11768: @item
11769: The installation options (send the file @file{config.status}).
11770: @item
11771: A complete list of changes (if any) you (or your installer) have made to the
11772: Gforth sources.
11773: @item
11774: A program (or a sequence of keyboard commands) that reproduces the bug.
11775: @item
11776: A description of what you think constitutes the buggy behaviour.
11777: @end itemize
11778: 
11779: For a thorough guide on reporting bugs read @ref{Bug Reporting, , How
11780: to Report Bugs, gcc.info, GNU C Manual}.
11781: 
11782: 
11783: @node Origin, Forth-related information, Bugs, Top
11784: @appendix Authors and Ancestors of Gforth
11785: 
11786: @section Authors and Contributors
11787: @cindex authors of Gforth
11788: @cindex contributors to Gforth
11789: 
11790: The Gforth project was started in mid-1992 by Bernd Paysan and Anton
11791: Ertl. The third major author was Jens Wilke.  Lennart Benschop (who was
11792: one of Gforth's first users, in mid-1993) and Stuart Ramsden inspired us
11793: with their continuous feedback. Lennart Benshop contributed
11794: @file{glosgen.fs}, while Stuart Ramsden has been working on automatic
11795: support for calling C libraries. Helpful comments also came from Paul
11796: Kleinrubatscher, Christian Pirker, Dirk Zoller, Marcel Hendrix, John
11797: Wavrik, Barrie Stott, Marc de Groot, and Jorge Acerada. Since the
11798: release of Gforth-0.2.1 there were also helpful comments from many
11799: others; thank you all, sorry for not listing you here (but digging
11800: through my mailbox to extract your names is on my to-do list). Since the
11801: release of Gforth-0.4.0 Neal Crook worked on the manual.
11802: 
11803: Gforth also owes a lot to the authors of the tools we used (GCC, CVS,
11804: and autoconf, among others), and to the creators of the Internet: Gforth
11805: was developed across the Internet, and its authors did not meet
11806: physically for the first 4 years of development.
11807: 
11808: @section Pedigree
11809: @cindex pedigree of Gforth
11810: 
11811: Gforth descends from bigFORTH (1993) and fig-Forth. Gforth and PFE (by
11812: Dirk Zoller) will cross-fertilize each other. Of course, a significant
11813: part of the design of Gforth was prescribed by ANS Forth.
11814: 
11815: Bernd Paysan wrote bigFORTH, a descendent from TurboForth, an unreleased
11816: 32 bit native code version of VolksForth for the Atari ST, written
11817: mostly by Dietrich Weineck.
11818: 
11819: VolksForth descends from F83. It was written by Klaus Schleisiek, Bernd
11820: Pennemann, Georg Rehfeld and Dietrich Weineck for the C64 (called
11821: UltraForth there) in the mid-80s and ported to the Atari ST in 1986.
11822: 
11823: Henry Laxen and Mike Perry wrote F83 as a model implementation of the
11824: Forth-83 standard. !! Pedigree? When?
11825: 
11826: A team led by Bill Ragsdale implemented fig-Forth on many processors in
11827: 1979. Robert Selzer and Bill Ragsdale developed the original
11828: implementation of fig-Forth for the 6502 based on microForth.
11829: 
11830: The principal architect of microForth was Dean Sanderson. microForth was
11831: FORTH, Inc.'s first off-the-shelf product. It was developed in 1976 for
11832: the 1802, and subsequently implemented on the 8080, the 6800 and the
11833: Z80.
11834: 
11835: All earlier Forth systems were custom-made, usually by Charles Moore,
11836: who discovered (as he puts it) Forth during the late 60s. The first full
11837: Forth existed in 1971.
11838: 
11839: A part of the information in this section comes from @cite{The Evolution
11840: of Forth} by Elizabeth D. Rather, Donald R. Colburn and Charles
11841: H. Moore, presented at the HOPL-II conference and preprinted in SIGPLAN
11842: Notices 28(3), 1993.  You can find more historical and genealogical
11843: information about Forth there.
11844: 
11845: @node Forth-related information, Word Index, Origin, Top
11846: @appendix Other Forth-related information
11847: @cindex Forth-related information
11848: 
11849: @menu
11850: * Internet resources::
11851: * Books::
11852: * The Forth Interest Group::
11853: * Conferences::
11854: @end menu
11855: 
11856: 
11857: @node Internet resources, Books, Forth-related information, Forth-related information
11858: @section Internet resources
11859: @cindex internet resources
11860: 
11861: @cindex comp.lang.forth
11862: @cindex frequently asked questions
11863: There is an active news group (comp.lang.forth) discussing Forth and
11864: Forth-related issues. A frequently-asked-questions (FAQ) list
11865: is posted to the news group regularly, and archived at these sites:
11866: 
11867: @itemize @bullet
11868: @item
11869: @uref{ftp://rtfm.mit.edu/pub/usenet-by-group/comp.lang.forth/}
11870: @item
11871: @uref{ftp://ftp.forth.org/pub/Forth/FAQ/}
11872: @end itemize
11873: 
11874: The FAQ list should be considered mandatory reading before posting to
11875: the news group.
11876: 
11877: Here are some other web sites holding Forth-related material:
11878: 
11879: @itemize @bullet
11880: @item
11881: @uref{http://www.taygeta.com/forth.html} -- Skip Carter's Forth pages.
11882: @item
11883: @uref{http://www.jwdt.com/~paysan/gforth.html} -- the Gforth home page.
11884: @item
11885: @uref{http://www.minerva.com/uathena.htm} -- home of ANS Forth Standard.
11886: @item
11887: @uref{http://dec.bournemouth.ac.uk/forth/index.html} -- the Forth
11888: Research page, including links to the Journal of Forth Application and
11889: Research (JFAR) and a searchable Forth bibliography.
11890: @end itemize
11891: 
11892: 
11893: @node Books, The Forth Interest Group, Internet resources, Forth-related information
11894: @section Books
11895: @cindex books on Forth
11896: 
11897: As the Standard is relatively new, there are not many books out yet. It
11898: is not recommended to learn Forth by using Gforth and a book that is not
11899: written for ANS Forth, as you will not know your mistakes from the
11900: deviations of the book. However, books based on the Forth-83 standard
11901: should be ok, because ANS Forth is primarily an extension of Forth-83.
11902: Refer to the Forth FAQ for details of Forth-related books.
11903: 
11904: @cindex standard document for ANS Forth
11905: @cindex ANS Forth document
11906: The definite reference if you want to write ANS Forth programs is, of
11907: course, the ANS Forth document. It is available in printed form from the
11908: National Standards Institute Sales Department (Tel.: USA (212) 642-4900;
11909: Fax.: USA (212) 302-1286) as document @cite{X3.215-1994} for about
11910: $200. You can also get it from Global Engineering Documents (Tel.: USA
11911: (800) 854-7179; Fax.: (303) 843-9880) for about $300.
11912: 
11913: @cite{dpANS6}, the last draft of the standard, which was then submitted
11914: to ANSI for publication is available electronically and for free in some
11915: MS Word format, and it has been converted to HTML
11916: (@uref{http://www.taygeta.com/forth/dpans.html}; this HTML version also
11917: includes the answers to Requests for Interpretation (RFIs). Some
11918: pointers to these versions can be found through
11919: @*@uref{http://www.complang.tuwien.ac.at/projects/forth.html}.
11920: 
11921: 
11922: @node The Forth Interest Group, Conferences, Books, Forth-related information
11923: @section The Forth Interest Group
11924: @cindex Forth interest group (FIG)
11925: 
11926: The Forth Interest Group (FIG) is a world-wide, non-profit,
11927: member-supported organisation. It publishes a regular magazine,
11928: @var{FORTH Dimensions}, and offers other benefits of membership. You can
11929: contact the FIG through their office email address:
11930: @email{office@@forth.org} or by visiting their web site at
11931: @uref{http://www.forth.org/}. This web site also includes links to FIG
11932: chapters in other countries and American cities
11933: (@uref{http://www.forth.org/chapters.html}).
11934: 
11935: @node Conferences, , The Forth Interest Group, Forth-related information
11936: @section Conferences
11937: @cindex Conferences
11938: 
11939: There are several regular conferences related to Forth. They are all
11940: well-publicised in @var{FORTH Dimensions} and on the comp.lang.forth
11941: news group:
11942: 
11943: @itemize @bullet
11944: @item
11945: FORML -- the Forth modification laboratory convenes every year near
11946: Monterey, California.
11947: @item
11948: The Rochester Forth Conference -- an annual conference traditionally
11949: held in Rochester, New York.
11950: @item
11951: EuroForth -- this European conference takes place annually.
11952: @end itemize
11953: 
11954: 
11955: @node Word Index, Name Index, Forth-related information, Top
11956: @unnumbered Word Index
11957: 
11958: This index is a list of Forth words that have ``glossary'' entries
11959: within this manual. Each word is listed with its stack effect and
11960: wordset.
11961: 
11962: @printindex fn
11963: 
11964: @node Name Index, Concept Index, Word Index, Top
11965: @unnumbered Name Index
11966: 
11967: This index is a list of Forth words that have ``glossary'' entries
11968: within this manual.
11969: 
11970: @printindex ky
11971: 
11972: @node Concept Index,  , Name Index, Top
11973: @unnumbered Concept and Word Index
11974: 
11975: Not all entries listed in this index are present verbatim in the
11976: text. This index also duplicates, in abbreviated form, all of the words
11977: listed in the Word Index (only the names are listed for the words here).
11978: 
11979: @printindex cp
11980: 
11981: @contents
11982: @bye
11983: 

FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>