File:  [gforth] / gforth / doc / gforth.ds
Revision 1.89: download - view: text, annotated - select for diffs
Sat Sep 23 18:20:19 2000 UTC (23 years, 7 months ago) by anton
Branches: MAIN
CVS tags: v0-5-0, HEAD
updated NEWS
minor changes

    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: @c POSTPONE, COMPILE, [COMPILE], LITERAL should have their own section
   18: 
   19: @comment %**start of header (This is for running Texinfo on a region.)
   20: @setfilename gforth.info
   21: @settitle Gforth Manual
   22: @dircategory GNU programming tools
   23: @direntry
   24: * Gforth: (gforth).             A fast interpreter for the Forth language.
   25: @end direntry
   26: @c The Texinfo manual also recommends doing this, but for Gforth it may
   27: @c  not make much sense
   28: @c @dircategory Individual utilities
   29: @c @direntry
   30: @c * Gforth: (gforth)Invoking Gforth.      gforth, gforth-fast, gforthmi
   31: @c @end direntry
   32: 
   33: @comment @setchapternewpage odd
   34: @comment TODO this gets left in by HTML converter
   35: @macro progstyle {}
   36: Programming style note:
   37: @end macro
   38: 
   39: @macro assignment {}
   40: @table @i
   41: @item Assignment:
   42: @end macro
   43: @macro endassignment {}
   44: @end table
   45: @end macro
   46: 
   47: @comment %**end of header (This is for running Texinfo on a region.)
   48: 
   49: 
   50: @comment ----------------------------------------------------------
   51: @comment macros for beautifying glossary entries
   52: @comment if these are used, need to strip them out for HTML converter
   53: @comment else they get repeated verbatim in HTML output.
   54: @comment .. not working yet.
   55: 
   56: @macro GLOSS-START {}
   57: @iftex
   58: @ninerm
   59: @end iftex
   60: @end macro
   61: 
   62: @macro GLOSS-END {}
   63: @iftex
   64: @rm
   65: @end iftex
   66: @end macro
   67: 
   68: @comment ----------------------------------------------------------
   69: 
   70: 
   71: @include version.texi
   72: 
   73: @ifnottex
   74: This file documents Gforth @value{VERSION}
   75: 
   76: Copyright @copyright{} 1995--2000 Free Software Foundation, Inc.
   77: 
   78:      Permission is granted to make and distribute verbatim copies of
   79:      this manual provided the copyright notice and this permission notice
   80:      are preserved on all copies.
   81:      
   82: @ignore
   83:      Permission is granted to process this file through TeX and print the
   84:      results, provided the printed document carries a copying permission
   85:      notice identical to this one except for the removal of this paragraph
   86:      (this paragraph not being relevant to the printed manual).
   87:      
   88: @end ignore
   89:      Permission is granted to copy and distribute modified versions of this
   90:      manual under the conditions for verbatim copying, provided also that the
   91:      sections entitled "Distribution" and "General Public License" are
   92:      included exactly as in the original, and provided that the entire
   93:      resulting derived work is distributed under the terms of a permission
   94:      notice identical to this one.
   95:      
   96:      Permission is granted to copy and distribute translations of this manual
   97:      into another language, under the above conditions for modified versions,
   98:      except that the sections entitled "Distribution" and "General Public
   99:      License" may be included in a translation approved by the author instead
  100:      of in the original English.
  101: @end ifnottex
  102: 
  103: @finalout
  104: @titlepage
  105: @sp 10
  106: @center @titlefont{Gforth Manual}
  107: @sp 2
  108: @center for version @value{VERSION}
  109: @sp 2
  110: @center Neal Crook
  111: @center Anton Ertl
  112: @center Bernd Paysan
  113: @center Jens Wilke
  114: @sp 3
  115: @center This manual is permanently under construction and was last updated on 15-Mar-2000
  116: 
  117: @comment  The following two commands start the copyright page.
  118: @page
  119: @vskip 0pt plus 1filll
  120: Copyright @copyright{} 1995--2000 Free Software Foundation, Inc.
  121: 
  122: @comment !! Published by ... or You can get a copy of this manual ...
  123: 
  124:      Permission is granted to make and distribute verbatim copies of
  125:      this manual provided the copyright notice and this permission notice
  126:      are preserved on all copies.
  127:      
  128:      Permission is granted to copy and distribute modified versions of this
  129:      manual under the conditions for verbatim copying, provided also that the
  130:      sections entitled "Distribution" and "General Public License" are
  131:      included exactly as in the original, and provided that the entire
  132:      resulting derived work is distributed under the terms of a permission
  133:      notice identical to this one.
  134:      
  135:      Permission is granted to copy and distribute translations of this manual
  136:      into another language, under the above conditions for modified versions,
  137:      except that the sections entitled "Distribution" and "General Public
  138:      License" may be included in a translation approved by the author instead
  139:      of in the original English.
  140: @end titlepage
  141: 
  142: @node Top, License, (dir), (dir)
  143: @ifnottex
  144: Gforth is a free implementation of ANS Forth available on many
  145: personal machines. This manual corresponds to version @value{VERSION}.
  146: @end ifnottex
  147: 
  148: @menu
  149: * License::                     The GPL
  150: * Goals::                       About the Gforth Project
  151: * Gforth Environment::          Starting (and exiting) Gforth
  152: * Tutorial::                    Hands-on Forth Tutorial
  153: * Introduction::                An introduction to ANS Forth
  154: * Words::                       Forth words available in Gforth
  155: * Error messages::              How to interpret them
  156: * Tools::                       Programming tools
  157: * ANS conformance::             Implementation-defined options etc.
  158: * Standard vs Extensions::      Should I use extensions?
  159: * Model::                       The abstract machine of Gforth
  160: * Integrating Gforth::          Forth as scripting language for applications
  161: * Emacs and Gforth::            The Gforth Mode
  162: * Image Files::                 @code{.fi} files contain compiled code
  163: * Engine::                      The inner interpreter and the primitives
  164: * Binding to System Library::   
  165: * Cross Compiler::              The Cross Compiler
  166: * Bugs::                        How to report them
  167: * Origin::                      Authors and ancestors of Gforth
  168: * Forth-related information::   Books and places to look on the WWW
  169: * Word Index::                  An item for each Forth word
  170: * Concept Index::               A menu covering many topics
  171: 
  172: @detailmenu --- The Detailed Node Listing ---
  173: 
  174: Gforth Environment
  175: 
  176: * Invoking Gforth::             Getting in
  177: * Leaving Gforth::              Getting out
  178: * Command-line editing::        
  179: * Environment variables::       that affect how Gforth starts up
  180: * Gforth Files::                What gets installed and where
  181: * Startup speed::               When 35ms is not fast enough ...
  182: 
  183: Forth Tutorial
  184: 
  185: * Starting Gforth Tutorial::    
  186: * Syntax Tutorial::             
  187: * Crash Course Tutorial::       
  188: * Stack Tutorial::              
  189: * Arithmetics Tutorial::        
  190: * Stack Manipulation Tutorial::  
  191: * Using files for Forth code Tutorial::  
  192: * Comments Tutorial::           
  193: * Colon Definitions Tutorial::  
  194: * Decompilation Tutorial::      
  195: * Stack-Effect Comments Tutorial::  
  196: * Types Tutorial::              
  197: * Factoring Tutorial::          
  198: * Designing the stack effect Tutorial::  
  199: * Local Variables Tutorial::    
  200: * Conditional execution Tutorial::  
  201: * Flags and Comparisons Tutorial::  
  202: * General Loops Tutorial::      
  203: * Counted loops Tutorial::      
  204: * Recursion Tutorial::          
  205: * Leaving definitions or loops Tutorial::  
  206: * Return Stack Tutorial::       
  207: * Memory Tutorial::             
  208: * Characters and Strings Tutorial::  
  209: * Alignment Tutorial::          
  210: * Files Tutorial::              
  211: * Interpretation and Compilation Semantics and Immediacy Tutorial::  
  212: * Execution Tokens Tutorial::   
  213: * Exceptions Tutorial::         
  214: * Defining Words Tutorial::     
  215: * Arrays and Records Tutorial::  
  216: * POSTPONE Tutorial::           
  217: * Literal Tutorial::            
  218: * Advanced macros Tutorial::    
  219: * Compilation Tokens Tutorial::  
  220: * Wordlists and Search Order Tutorial::  
  221: 
  222: An Introduction to ANS Forth
  223: 
  224: * Introducing the Text Interpreter::  
  225: * Stacks and Postfix notation::  
  226: * Your first definition::       
  227: * How does that work?::         
  228: * Forth is written in Forth::   
  229: * Review - elements of a Forth system::  
  230: * Where to go next::            
  231: * Exercises::                   
  232: 
  233: Forth Words
  234: 
  235: * Notation::                    
  236: * Case insensitivity::          
  237: * Comments::                    
  238: * Boolean Flags::               
  239: * Arithmetic::                  
  240: * Stack Manipulation::          
  241: * Memory::                      
  242: * Control Structures::          
  243: * Defining Words::              
  244: * Interpretation and Compilation Semantics::  
  245: * Tokens for Words::            
  246: * Compiling words::             
  247: * The Text Interpreter::        
  248: * Word Lists::                  
  249: * Environmental Queries::       
  250: * Files::                       
  251: * Blocks::                      
  252: * Other I/O::                   
  253: * Locals::                      
  254: * Structures::                  
  255: * Object-oriented Forth::       
  256: * Programming Tools::           
  257: * Assembler and Code Words::    
  258: * Threading Words::             
  259: * Passing Commands to the OS::  
  260: * Keeping track of Time::       
  261: * Miscellaneous Words::         
  262: 
  263: Arithmetic
  264: 
  265: * Single precision::            
  266: * Double precision::            Double-cell integer arithmetic
  267: * Bitwise operations::          
  268: * Numeric comparison::          
  269: * Mixed precision::             Operations with single and double-cell integers
  270: * Floating Point::              
  271: 
  272: Stack Manipulation
  273: 
  274: * Data stack::                  
  275: * Floating point stack::        
  276: * Return stack::                
  277: * Locals stack::                
  278: * Stack pointer manipulation::  
  279: 
  280: Memory
  281: 
  282: * Memory model::                
  283: * Dictionary allocation::       
  284: * Heap Allocation::             
  285: * Memory Access::               
  286: * Address arithmetic::          
  287: * Memory Blocks::               
  288: 
  289: Control Structures
  290: 
  291: * Selection::                   IF ... ELSE ... ENDIF
  292: * Simple Loops::                BEGIN ...
  293: * Counted Loops::               DO
  294: * Arbitrary control structures::  
  295: * Calls and returns::           
  296: * Exception Handling::          
  297: 
  298: Defining Words
  299: 
  300: * CREATE::                      
  301: * Variables::                   Variables and user variables
  302: * Constants::                   
  303: * Values::                      Initialised variables
  304: * Colon Definitions::           
  305: * Anonymous Definitions::       Definitions without names
  306: * Supplying names::             Passing definition names as strings
  307: * User-defined Defining Words::  
  308: * Deferred words::              Allow forward references
  309: * Aliases::                     
  310: 
  311: User-defined Defining Words
  312: 
  313: * CREATE..DOES> applications::  
  314: * CREATE..DOES> details::       
  315: * Advanced does> usage example::  
  316: 
  317: Interpretation and Compilation Semantics
  318: 
  319: * Combined words::              
  320: 
  321: Tokens for Words
  322: 
  323: * Execution token::             represents execution/interpretation semantics
  324: * Compilation token::           represents compilation semantics
  325: * Name token::                  represents named words
  326: 
  327: Compiling words
  328: 
  329: * Literals::                    Compiling data values
  330: * Macros::                      Compiling words
  331: 
  332: The Text Interpreter
  333: 
  334: * Input Sources::               
  335: * Number Conversion::           
  336: * Interpret/Compile states::    
  337: * Interpreter Directives::      
  338: 
  339: Word Lists
  340: 
  341: * Vocabularies::                
  342: * Why use word lists?::         
  343: * Word list example::           
  344: 
  345: Files
  346: 
  347: * Forth source files::          
  348: * General files::               
  349: * Search Paths::                
  350: 
  351: Search Paths
  352: 
  353: * Source Search Paths::         
  354: * General Search Paths::        
  355: 
  356: Other I/O
  357: 
  358: * Simple numeric output::       Predefined formats
  359: * Formatted numeric output::    Formatted (pictured) output
  360: * String Formats::              How Forth stores strings in memory
  361: * Displaying characters and strings::  Other stuff
  362: * Input::                       Input
  363: 
  364: Locals
  365: 
  366: * Gforth locals::               
  367: * ANS Forth locals::            
  368: 
  369: Gforth locals
  370: 
  371: * Where are locals visible by name?::  
  372: * How long do locals live?::    
  373: * Locals programming style::    
  374: * Locals implementation::       
  375: 
  376: Structures
  377: 
  378: * Why explicit structure support?::  
  379: * Structure Usage::             
  380: * Structure Naming Convention::  
  381: * Structure Implementation::    
  382: * Structure Glossary::          
  383: 
  384: Object-oriented Forth
  385: 
  386: * Why object-oriented programming?::  
  387: * Object-Oriented Terminology::  
  388: * Objects::                     
  389: * OOF::                         
  390: * Mini-OOF::                    
  391: * Comparison with other object models::  
  392: 
  393: The @file{objects.fs} model
  394: 
  395: * Properties of the Objects model::  
  396: * Basic Objects Usage::         
  397: * The Objects base class::      
  398: * Creating objects::            
  399: * Object-Oriented Programming Style::  
  400: * Class Binding::               
  401: * Method conveniences::         
  402: * Classes and Scoping::         
  403: * Dividing classes::            
  404: * Object Interfaces::           
  405: * Objects Implementation::      
  406: * Objects Glossary::            
  407: 
  408: The @file{oof.fs} model
  409: 
  410: * Properties of the OOF model::  
  411: * Basic OOF Usage::             
  412: * The OOF base class::          
  413: * Class Declaration::           
  414: * Class Implementation::        
  415: 
  416: The @file{mini-oof.fs} model
  417: 
  418: * Basic Mini-OOF Usage::        
  419: * Mini-OOF Example::            
  420: * Mini-OOF Implementation::     
  421: 
  422: Programming Tools
  423: 
  424: * Examining::                   
  425: * Forgetting words::            
  426: * Debugging::                   Simple and quick.
  427: * Assertions::                  Making your programs self-checking.
  428: * Singlestep Debugger::         Executing your program word by word.
  429: 
  430: Assembler and Code Words
  431: 
  432: * Code and ;code::              
  433: * Common Assembler::            Assembler Syntax
  434: * Common Disassembler::         
  435: * 386 Assembler::               Deviations and special cases
  436: * Alpha Assembler::             Deviations and special cases
  437: * MIPS assembler::              Deviations and special cases
  438: * Other assemblers::            How to write them
  439: 
  440: Tools
  441: 
  442: * ANS Report::                  Report the words used, sorted by wordset.
  443: 
  444: ANS conformance
  445: 
  446: * The Core Words::              
  447: * The optional Block word set::  
  448: * The optional Double Number word set::  
  449: * The optional Exception word set::  
  450: * The optional Facility word set::  
  451: * The optional File-Access word set::  
  452: * The optional Floating-Point word set::  
  453: * The optional Locals word set::  
  454: * The optional Memory-Allocation word set::  
  455: * The optional Programming-Tools word set::  
  456: * The optional Search-Order word set::  
  457: 
  458: The Core Words
  459: 
  460: * core-idef::                   Implementation Defined Options                   
  461: * core-ambcond::                Ambiguous Conditions                
  462: * core-other::                  Other System Documentation                  
  463: 
  464: The optional Block word set
  465: 
  466: * block-idef::                  Implementation Defined Options
  467: * block-ambcond::               Ambiguous Conditions               
  468: * block-other::                 Other System Documentation                 
  469: 
  470: The optional Double Number word set
  471: 
  472: * double-ambcond::              Ambiguous Conditions              
  473: 
  474: The optional Exception word set
  475: 
  476: * exception-idef::              Implementation Defined Options              
  477: 
  478: The optional Facility word set
  479: 
  480: * facility-idef::               Implementation Defined Options               
  481: * facility-ambcond::            Ambiguous Conditions            
  482: 
  483: The optional File-Access word set
  484: 
  485: * file-idef::                   Implementation Defined Options
  486: * file-ambcond::                Ambiguous Conditions                
  487: 
  488: The optional Floating-Point word set
  489: 
  490: * floating-idef::               Implementation Defined Options
  491: * floating-ambcond::            Ambiguous Conditions            
  492: 
  493: The optional Locals word set
  494: 
  495: * locals-idef::                 Implementation Defined Options                 
  496: * locals-ambcond::              Ambiguous Conditions              
  497: 
  498: The optional Memory-Allocation word set
  499: 
  500: * memory-idef::                 Implementation Defined Options                 
  501: 
  502: The optional Programming-Tools word set
  503: 
  504: * programming-idef::            Implementation Defined Options            
  505: * programming-ambcond::         Ambiguous Conditions         
  506: 
  507: The optional Search-Order word set
  508: 
  509: * search-idef::                 Implementation Defined Options                 
  510: * search-ambcond::              Ambiguous Conditions              
  511: 
  512: Image Files
  513: 
  514: * Image Licensing Issues::      Distribution terms for images.
  515: * Image File Background::       Why have image files?
  516: * Non-Relocatable Image Files::  don't always work.
  517: * Data-Relocatable Image Files::  are better.
  518: * Fully Relocatable Image Files::  better yet.
  519: * Stack and Dictionary Sizes::  Setting the default sizes for an image.
  520: * Running Image Files::         @code{gforth -i @i{file}} or @i{file}.
  521: * Modifying the Startup Sequence::  and turnkey applications.
  522: 
  523: Fully Relocatable Image Files
  524: 
  525: * gforthmi::                    The normal way
  526: * cross.fs::                    The hard way
  527: 
  528: Engine
  529: 
  530: * Portability::                 
  531: * Threading::                   
  532: * Primitives::                  
  533: * Performance::                 
  534: 
  535: Threading
  536: 
  537: * Scheduling::                  
  538: * Direct or Indirect Threaded?::  
  539: * DOES>::                       
  540: 
  541: Primitives
  542: 
  543: * Automatic Generation::        
  544: * TOS Optimization::            
  545: * Produced code::               
  546: 
  547: Cross Compiler
  548: 
  549: * Using the Cross Compiler::    
  550: * How the Cross Compiler Works::  
  551: 
  552: @end detailmenu
  553: @end menu
  554: 
  555: @node License, Goals, Top, Top
  556: @unnumbered GNU GENERAL PUBLIC LICENSE
  557: @center Version 2, June 1991
  558: 
  559: @display
  560: Copyright @copyright{} 1989, 1991 Free Software Foundation, Inc.
  561: 59 Temple Place, Suite 330, Boston, MA 02111, USA
  562: 
  563: Everyone is permitted to copy and distribute verbatim copies
  564: of this license document, but changing it is not allowed.
  565: @end display
  566: 
  567: @unnumberedsec Preamble
  568: 
  569:   The licenses for most software are designed to take away your
  570: freedom to share and change it.  By contrast, the GNU General Public
  571: License is intended to guarantee your freedom to share and change free
  572: software---to make sure the software is free for all its users.  This
  573: General Public License applies to most of the Free Software
  574: Foundation's software and to any other program whose authors commit to
  575: using it.  (Some other Free Software Foundation software is covered by
  576: the GNU Library General Public License instead.)  You can apply it to
  577: your programs, too.
  578: 
  579:   When we speak of free software, we are referring to freedom, not
  580: price.  Our General Public Licenses are designed to make sure that you
  581: have the freedom to distribute copies of free software (and charge for
  582: this service if you wish), that you receive source code or can get it
  583: if you want it, that you can change the software or use pieces of it
  584: in new free programs; and that you know you can do these things.
  585: 
  586:   To protect your rights, we need to make restrictions that forbid
  587: anyone to deny you these rights or to ask you to surrender the rights.
  588: These restrictions translate to certain responsibilities for you if you
  589: distribute copies of the software, or if you modify it.
  590: 
  591:   For example, if you distribute copies of such a program, whether
  592: gratis or for a fee, you must give the recipients all the rights that
  593: you have.  You must make sure that they, too, receive or can get the
  594: source code.  And you must show them these terms so they know their
  595: rights.
  596: 
  597:   We protect your rights with two steps: (1) copyright the software, and
  598: (2) offer you this license which gives you legal permission to copy,
  599: distribute and/or modify the software.
  600: 
  601:   Also, for each author's protection and ours, we want to make certain
  602: that everyone understands that there is no warranty for this free
  603: software.  If the software is modified by someone else and passed on, we
  604: want its recipients to know that what they have is not the original, so
  605: that any problems introduced by others will not reflect on the original
  606: authors' reputations.
  607: 
  608:   Finally, any free program is threatened constantly by software
  609: patents.  We wish to avoid the danger that redistributors of a free
  610: program will individually obtain patent licenses, in effect making the
  611: program proprietary.  To prevent this, we have made it clear that any
  612: patent must be licensed for everyone's free use or not licensed at all.
  613: 
  614:   The precise terms and conditions for copying, distribution and
  615: modification follow.
  616: 
  617: @iftex
  618: @unnumberedsec TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
  619: @end iftex
  620: @ifnottex
  621: @center TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
  622: @end ifnottex
  623: 
  624: @enumerate 0
  625: @item
  626: This License applies to any program or other work which contains
  627: a notice placed by the copyright holder saying it may be distributed
  628: under the terms of this General Public License.  The ``Program'', below,
  629: refers to any such program or work, and a ``work based on the Program''
  630: means either the Program or any derivative work under copyright law:
  631: that is to say, a work containing the Program or a portion of it,
  632: either verbatim or with modifications and/or translated into another
  633: language.  (Hereinafter, translation is included without limitation in
  634: the term ``modification''.)  Each licensee is addressed as ``you''.
  635: 
  636: Activities other than copying, distribution and modification are not
  637: covered by this License; they are outside its scope.  The act of
  638: running the Program is not restricted, and the output from the Program
  639: is covered only if its contents constitute a work based on the
  640: Program (independent of having been made by running the Program).
  641: Whether that is true depends on what the Program does.
  642: 
  643: @item
  644: You may copy and distribute verbatim copies of the Program's
  645: source code as you receive it, in any medium, provided that you
  646: conspicuously and appropriately publish on each copy an appropriate
  647: copyright notice and disclaimer of warranty; keep intact all the
  648: notices that refer to this License and to the absence of any warranty;
  649: and give any other recipients of the Program a copy of this License
  650: along with the Program.
  651: 
  652: You may charge a fee for the physical act of transferring a copy, and
  653: you may at your option offer warranty protection in exchange for a fee.
  654: 
  655: @item
  656: You may modify your copy or copies of the Program or any portion
  657: of it, thus forming a work based on the Program, and copy and
  658: distribute such modifications or work under the terms of Section 1
  659: above, provided that you also meet all of these conditions:
  660: 
  661: @enumerate a
  662: @item
  663: You must cause the modified files to carry prominent notices
  664: stating that you changed the files and the date of any change.
  665: 
  666: @item
  667: You must cause any work that you distribute or publish, that in
  668: whole or in part contains or is derived from the Program or any
  669: part thereof, to be licensed as a whole at no charge to all third
  670: parties under the terms of this License.
  671: 
  672: @item
  673: If the modified program normally reads commands interactively
  674: when run, you must cause it, when started running for such
  675: interactive use in the most ordinary way, to print or display an
  676: announcement including an appropriate copyright notice and a
  677: notice that there is no warranty (or else, saying that you provide
  678: a warranty) and that users may redistribute the program under
  679: these conditions, and telling the user how to view a copy of this
  680: License.  (Exception: if the Program itself is interactive but
  681: does not normally print such an announcement, your work based on
  682: the Program is not required to print an announcement.)
  683: @end enumerate
  684: 
  685: These requirements apply to the modified work as a whole.  If
  686: identifiable sections of that work are not derived from the Program,
  687: and can be reasonably considered independent and separate works in
  688: themselves, then this License, and its terms, do not apply to those
  689: sections when you distribute them as separate works.  But when you
  690: distribute the same sections as part of a whole which is a work based
  691: on the Program, the distribution of the whole must be on the terms of
  692: this License, whose permissions for other licensees extend to the
  693: entire whole, and thus to each and every part regardless of who wrote it.
  694: 
  695: Thus, it is not the intent of this section to claim rights or contest
  696: your rights to work written entirely by you; rather, the intent is to
  697: exercise the right to control the distribution of derivative or
  698: collective works based on the Program.
  699: 
  700: In addition, mere aggregation of another work not based on the Program
  701: with the Program (or with a work based on the Program) on a volume of
  702: a storage or distribution medium does not bring the other work under
  703: the scope of this License.
  704: 
  705: @item
  706: You may copy and distribute the Program (or a work based on it,
  707: under Section 2) in object code or executable form under the terms of
  708: Sections 1 and 2 above provided that you also do one of the following:
  709: 
  710: @enumerate a
  711: @item
  712: Accompany it with the complete corresponding machine-readable
  713: source code, which must be distributed under the terms of Sections
  714: 1 and 2 above on a medium customarily used for software interchange; or,
  715: 
  716: @item
  717: Accompany it with a written offer, valid for at least three
  718: years, to give any third party, for a charge no more than your
  719: cost of physically performing source distribution, a complete
  720: machine-readable copy of the corresponding source code, to be
  721: distributed under the terms of Sections 1 and 2 above on a medium
  722: customarily used for software interchange; or,
  723: 
  724: @item
  725: Accompany it with the information you received as to the offer
  726: to distribute corresponding source code.  (This alternative is
  727: allowed only for noncommercial distribution and only if you
  728: received the program in object code or executable form with such
  729: an offer, in accord with Subsection b above.)
  730: @end enumerate
  731: 
  732: The source code for a work means the preferred form of the work for
  733: making modifications to it.  For an executable work, complete source
  734: code means all the source code for all modules it contains, plus any
  735: associated interface definition files, plus the scripts used to
  736: control compilation and installation of the executable.  However, as a
  737: special exception, the source code distributed need not include
  738: anything that is normally distributed (in either source or binary
  739: form) with the major components (compiler, kernel, and so on) of the
  740: operating system on which the executable runs, unless that component
  741: itself accompanies the executable.
  742: 
  743: If distribution of executable or object code is made by offering
  744: access to copy from a designated place, then offering equivalent
  745: access to copy the source code from the same place counts as
  746: distribution of the source code, even though third parties are not
  747: compelled to copy the source along with the object code.
  748: 
  749: @item
  750: You may not copy, modify, sublicense, or distribute the Program
  751: except as expressly provided under this License.  Any attempt
  752: otherwise to copy, modify, sublicense or distribute the Program is
  753: void, and will automatically terminate your rights under this License.
  754: However, parties who have received copies, or rights, from you under
  755: this License will not have their licenses terminated so long as such
  756: parties remain in full compliance.
  757: 
  758: @item
  759: You are not required to accept this License, since you have not
  760: signed it.  However, nothing else grants you permission to modify or
  761: distribute the Program or its derivative works.  These actions are
  762: prohibited by law if you do not accept this License.  Therefore, by
  763: modifying or distributing the Program (or any work based on the
  764: Program), you indicate your acceptance of this License to do so, and
  765: all its terms and conditions for copying, distributing or modifying
  766: the Program or works based on it.
  767: 
  768: @item
  769: Each time you redistribute the Program (or any work based on the
  770: Program), the recipient automatically receives a license from the
  771: original licensor to copy, distribute or modify the Program subject to
  772: these terms and conditions.  You may not impose any further
  773: restrictions on the recipients' exercise of the rights granted herein.
  774: You are not responsible for enforcing compliance by third parties to
  775: this License.
  776: 
  777: @item
  778: If, as a consequence of a court judgment or allegation of patent
  779: infringement or for any other reason (not limited to patent issues),
  780: conditions are imposed on you (whether by court order, agreement or
  781: otherwise) that contradict the conditions of this License, they do not
  782: excuse you from the conditions of this License.  If you cannot
  783: distribute so as to satisfy simultaneously your obligations under this
  784: License and any other pertinent obligations, then as a consequence you
  785: may not distribute the Program at all.  For example, if a patent
  786: license would not permit royalty-free redistribution of the Program by
  787: all those who receive copies directly or indirectly through you, then
  788: the only way you could satisfy both it and this License would be to
  789: refrain entirely from distribution of the Program.
  790: 
  791: If any portion of this section is held invalid or unenforceable under
  792: any particular circumstance, the balance of the section is intended to
  793: apply and the section as a whole is intended to apply in other
  794: circumstances.
  795: 
  796: It is not the purpose of this section to induce you to infringe any
  797: patents or other property right claims or to contest validity of any
  798: such claims; this section has the sole purpose of protecting the
  799: integrity of the free software distribution system, which is
  800: implemented by public license practices.  Many people have made
  801: generous contributions to the wide range of software distributed
  802: through that system in reliance on consistent application of that
  803: system; it is up to the author/donor to decide if he or she is willing
  804: to distribute software through any other system and a licensee cannot
  805: impose that choice.
  806: 
  807: This section is intended to make thoroughly clear what is believed to
  808: be a consequence of the rest of this License.
  809: 
  810: @item
  811: If the distribution and/or use of the Program is restricted in
  812: certain countries either by patents or by copyrighted interfaces, the
  813: original copyright holder who places the Program under this License
  814: may add an explicit geographical distribution limitation excluding
  815: those countries, so that distribution is permitted only in or among
  816: countries not thus excluded.  In such case, this License incorporates
  817: the limitation as if written in the body of this License.
  818: 
  819: @item
  820: The Free Software Foundation may publish revised and/or new versions
  821: of the General Public License from time to time.  Such new versions will
  822: be similar in spirit to the present version, but may differ in detail to
  823: address new problems or concerns.
  824: 
  825: Each version is given a distinguishing version number.  If the Program
  826: specifies a version number of this License which applies to it and ``any
  827: later version'', you have the option of following the terms and conditions
  828: either of that version or of any later version published by the Free
  829: Software Foundation.  If the Program does not specify a version number of
  830: this License, you may choose any version ever published by the Free Software
  831: Foundation.
  832: 
  833: @item
  834: If you wish to incorporate parts of the Program into other free
  835: programs whose distribution conditions are different, write to the author
  836: to ask for permission.  For software which is copyrighted by the Free
  837: Software Foundation, write to the Free Software Foundation; we sometimes
  838: make exceptions for this.  Our decision will be guided by the two goals
  839: of preserving the free status of all derivatives of our free software and
  840: of promoting the sharing and reuse of software generally.
  841: 
  842: @iftex
  843: @heading NO WARRANTY
  844: @end iftex
  845: @ifnottex
  846: @center NO WARRANTY
  847: @end ifnottex
  848: 
  849: @item
  850: BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
  851: FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN
  852: OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
  853: PROVIDE THE PROGRAM ``AS IS'' WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
  854: OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
  855: MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS
  856: TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE
  857: PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
  858: REPAIR OR CORRECTION.
  859: 
  860: @item
  861: IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
  862: WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
  863: REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
  864: INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
  865: OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
  866: TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
  867: YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
  868: PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
  869: POSSIBILITY OF SUCH DAMAGES.
  870: @end enumerate
  871: 
  872: @iftex
  873: @heading END OF TERMS AND CONDITIONS
  874: @end iftex
  875: @ifnottex
  876: @center END OF TERMS AND CONDITIONS
  877: @end ifnottex
  878: 
  879: @page
  880: @unnumberedsec How to Apply These Terms to Your New Programs
  881: 
  882:   If you develop a new program, and you want it to be of the greatest
  883: possible use to the public, the best way to achieve this is to make it
  884: free software which everyone can redistribute and change under these terms.
  885: 
  886:   To do so, attach the following notices to the program.  It is safest
  887: to attach them to the start of each source file to most effectively
  888: convey the exclusion of warranty; and each file should have at least
  889: the ``copyright'' line and a pointer to where the full notice is found.
  890: 
  891: @smallexample
  892: @var{one line to give the program's name and a brief idea of what it does.}
  893: Copyright (C) 19@var{yy}  @var{name of author}
  894: 
  895: This program is free software; you can redistribute it and/or modify 
  896: it under the terms of the GNU General Public License as published by 
  897: the Free Software Foundation; either version 2 of the License, or 
  898: (at your option) any later version.
  899: 
  900: This program is distributed in the hope that it will be useful,
  901: but WITHOUT ANY WARRANTY; without even the implied warranty of
  902: MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  903: GNU General Public License for more details.
  904: 
  905: You should have received a copy of the GNU General Public License
  906: along with this program; if not, write to the Free Software
  907: Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
  908: @end smallexample
  909: 
  910: Also add information on how to contact you by electronic and paper mail.
  911: 
  912: If the program is interactive, make it output a short notice like this
  913: when it starts in an interactive mode:
  914: 
  915: @smallexample
  916: Gnomovision version 69, Copyright (C) 19@var{yy} @var{name of author}
  917: Gnomovision comes with ABSOLUTELY NO WARRANTY; for details
  918: type `show w'.  
  919: This is free software, and you are welcome to redistribute it 
  920: under certain conditions; type `show c' for details.
  921: @end smallexample
  922: 
  923: The hypothetical commands @samp{show w} and @samp{show c} should show
  924: the appropriate parts of the General Public License.  Of course, the
  925: commands you use may be called something other than @samp{show w} and
  926: @samp{show c}; they could even be mouse-clicks or menu items---whatever
  927: suits your program.
  928: 
  929: You should also get your employer (if you work as a programmer) or your
  930: school, if any, to sign a ``copyright disclaimer'' for the program, if
  931: necessary.  Here is a sample; alter the names:
  932: 
  933: @smallexample
  934: Yoyodyne, Inc., hereby disclaims all copyright interest in the program
  935: `Gnomovision' (which makes passes at compilers) written by James Hacker.
  936: 
  937: @var{signature of Ty Coon}, 1 April 1989
  938: Ty Coon, President of Vice
  939: @end smallexample
  940: 
  941: This General Public License does not permit incorporating your program into
  942: proprietary programs.  If your program is a subroutine library, you may
  943: consider it more useful to permit linking proprietary applications with the
  944: library.  If this is what you want to do, use the GNU Library General
  945: Public License instead of this License.
  946: 
  947: @iftex
  948: @unnumbered Preface
  949: @cindex Preface
  950: This manual documents Gforth. Some introductory material is provided for
  951: readers who are unfamiliar with Forth or who are migrating to Gforth
  952: from other Forth compilers. However, this manual is primarily a
  953: reference manual.
  954: @end iftex
  955: 
  956: @comment TODO much more blurb here.
  957: 
  958: @c ******************************************************************
  959: @node Goals, Gforth Environment, License, Top
  960: @comment node-name,     next,           previous, up
  961: @chapter Goals of Gforth
  962: @cindex goals of the Gforth project
  963: The goal of the Gforth Project is to develop a standard model for
  964: ANS Forth. This can be split into several subgoals:
  965: 
  966: @itemize @bullet
  967: @item
  968: Gforth should conform to the ANS Forth Standard.
  969: @item
  970: It should be a model, i.e. it should define all the
  971: implementation-dependent things.
  972: @item
  973: It should become standard, i.e. widely accepted and used. This goal
  974: is the most difficult one.
  975: @end itemize
  976: 
  977: To achieve these goals Gforth should be
  978: @itemize @bullet
  979: @item
  980: Similar to previous models (fig-Forth, F83)
  981: @item
  982: Powerful. It should provide for all the things that are considered
  983: necessary today and even some that are not yet considered necessary.
  984: @item
  985: Efficient. It should not get the reputation of being exceptionally
  986: slow.
  987: @item
  988: Free.
  989: @item
  990: Available on many machines/easy to port.
  991: @end itemize
  992: 
  993: Have we achieved these goals? Gforth conforms to the ANS Forth
  994: standard. It may be considered a model, but we have not yet documented
  995: which parts of the model are stable and which parts we are likely to
  996: change. It certainly has not yet become a de facto standard, but it
  997: appears to be quite popular. It has some similarities to and some
  998: differences from previous models. It has some powerful features, but not
  999: yet everything that we envisioned. We certainly have achieved our
 1000: execution speed goals (@pxref{Performance})@footnote{However, in 1998
 1001: the bar was raised when the major commercial Forth vendors switched to
 1002: native code compilers.}.  It is free and available on many machines.
 1003: 
 1004: @c ******************************************************************
 1005: @node Gforth Environment, Tutorial, Goals, Top
 1006: @chapter Gforth Environment
 1007: @cindex Gforth environment
 1008: 
 1009: Note: ultimately, the Gforth man page will be auto-generated from the
 1010: material in this chapter.
 1011: 
 1012: @menu
 1013: * Invoking Gforth::             Getting in
 1014: * Leaving Gforth::              Getting out
 1015: * Command-line editing::        
 1016: * Environment variables::       that affect how Gforth starts up
 1017: * Gforth Files::                What gets installed and where
 1018: * Startup speed::               When 35ms is not fast enough ...
 1019: @end menu
 1020: 
 1021: For related information about the creation of images see @ref{Image Files}.
 1022: 
 1023: @comment ----------------------------------------------
 1024: @node Invoking Gforth, Leaving Gforth, Gforth Environment, Gforth Environment
 1025: @section Invoking Gforth
 1026: @cindex invoking Gforth
 1027: @cindex running Gforth
 1028: @cindex command-line options
 1029: @cindex options on the command line
 1030: @cindex flags on the command line
 1031: 
 1032: Gforth is made up of two parts; an executable ``engine'' (named
 1033: @file{gforth} or @file{gforth-fast}) and an image file. To start it, you
 1034: will usually just say @code{gforth} -- this automatically loads the
 1035: default image file @file{gforth.fi}. In many other cases the default
 1036: Gforth image will be invoked like this:
 1037: @example
 1038: gforth [file | -e forth-code] ...
 1039: @end example
 1040: @noindent
 1041: This interprets the contents of the files and the Forth code in the order they
 1042: are given.
 1043: 
 1044: In addition to the @file{gforth} engine, there is also an engine called
 1045: @file{gforth-fast}, which is faster, but gives less informative error
 1046: messages (@pxref{Error messages}).  You should use it for debugged,
 1047: performance-critical programs.
 1048: 
 1049: In general, the command line looks like this:
 1050: 
 1051: @example
 1052: gforth[-fast] [engine options] [image options]
 1053: @end example
 1054: 
 1055: The engine options must come before the rest of the command
 1056: line. They are:
 1057: 
 1058: @table @code
 1059: @cindex -i, command-line option
 1060: @cindex --image-file, command-line option
 1061: @item --image-file @i{file}
 1062: @itemx -i @i{file}
 1063: Loads the Forth image @i{file} instead of the default
 1064: @file{gforth.fi} (@pxref{Image Files}).
 1065: 
 1066: @cindex --appl-image, command-line option
 1067: @item --appl-image @i{file}
 1068: Loads the image @i{file} and leaves all further command-line arguments
 1069: to the image (instead of processing them as engine options).  This is
 1070: useful for building executable application images on Unix, built with
 1071: @code{gforthmi --application ...}.
 1072: 
 1073: @cindex --path, command-line option
 1074: @cindex -p, command-line option
 1075: @item --path @i{path}
 1076: @itemx -p @i{path}
 1077: Uses @i{path} for searching the image file and Forth source code files
 1078: instead of the default in the environment variable @code{GFORTHPATH} or
 1079: the path specified at installation time (e.g.,
 1080: @file{/usr/local/share/gforth/0.2.0:.}). A path is given as a list of
 1081: directories, separated by @samp{:} (on Unix) or @samp{;} (on other OSs).
 1082: 
 1083: @cindex --dictionary-size, command-line option
 1084: @cindex -m, command-line option
 1085: @cindex @i{size} parameters for command-line options
 1086: @cindex size of the dictionary and the stacks
 1087: @item --dictionary-size @i{size}
 1088: @itemx -m @i{size}
 1089: Allocate @i{size} space for the Forth dictionary space instead of
 1090: using the default specified in the image (typically 256K). The
 1091: @i{size} specification for this and subsequent options consists of
 1092: an integer and a unit (e.g.,
 1093: @code{4M}). The unit can be one of @code{b} (bytes), @code{e} (element
 1094: size, in this case Cells), @code{k} (kilobytes), @code{M} (Megabytes),
 1095: @code{G} (Gigabytes), and @code{T} (Terabytes). If no unit is specified,
 1096: @code{e} is used.
 1097: 
 1098: @cindex --data-stack-size, command-line option
 1099: @cindex -d, command-line option
 1100: @item --data-stack-size @i{size}
 1101: @itemx -d @i{size}
 1102: Allocate @i{size} space for the data stack instead of using the
 1103: default specified in the image (typically 16K).
 1104: 
 1105: @cindex --return-stack-size, command-line option
 1106: @cindex -r, command-line option
 1107: @item --return-stack-size @i{size}
 1108: @itemx -r @i{size}
 1109: Allocate @i{size} space for the return stack instead of using the
 1110: default specified in the image (typically 15K).
 1111: 
 1112: @cindex --fp-stack-size, command-line option
 1113: @cindex -f, command-line option
 1114: @item --fp-stack-size @i{size}
 1115: @itemx -f @i{size}
 1116: Allocate @i{size} space for the floating point stack instead of
 1117: using the default specified in the image (typically 15.5K). In this case
 1118: the unit specifier @code{e} refers to floating point numbers.
 1119: 
 1120: @cindex --locals-stack-size, command-line option
 1121: @cindex -l, command-line option
 1122: @item --locals-stack-size @i{size}
 1123: @itemx -l @i{size}
 1124: Allocate @i{size} space for the locals stack instead of using the
 1125: default specified in the image (typically 14.5K).
 1126: 
 1127: @cindex -h, command-line option
 1128: @cindex --help, command-line option
 1129: @item --help
 1130: @itemx -h
 1131: Print a message about the command-line options
 1132: 
 1133: @cindex -v, command-line option
 1134: @cindex --version, command-line option
 1135: @item --version
 1136: @itemx -v
 1137: Print version and exit
 1138: 
 1139: @cindex --debug, command-line option
 1140: @item --debug
 1141: Print some information useful for debugging on startup.
 1142: 
 1143: @cindex --offset-image, command-line option
 1144: @item --offset-image
 1145: Start the dictionary at a slightly different position than would be used
 1146: otherwise (useful for creating data-relocatable images,
 1147: @pxref{Data-Relocatable Image Files}).
 1148: 
 1149: @cindex --no-offset-im, command-line option
 1150: @item --no-offset-im
 1151: Start the dictionary at the normal position.
 1152: 
 1153: @cindex --clear-dictionary, command-line option
 1154: @item --clear-dictionary
 1155: Initialize all bytes in the dictionary to 0 before loading the image
 1156: (@pxref{Data-Relocatable Image Files}).
 1157: 
 1158: @cindex --die-on-signal, command-line-option
 1159: @item --die-on-signal
 1160: Normally Gforth handles most signals (e.g., the user interrupt SIGINT,
 1161: or the segmentation violation SIGSEGV) by translating it into a Forth
 1162: @code{THROW}. With this option, Gforth exits if it receives such a
 1163: signal. This option is useful when the engine and/or the image might be
 1164: severely broken (such that it causes another signal before recovering
 1165: from the first); this option avoids endless loops in such cases.
 1166: @end table
 1167: 
 1168: @cindex loading files at startup
 1169: @cindex executing code on startup
 1170: @cindex batch processing with Gforth
 1171: As explained above, the image-specific command-line arguments for the
 1172: default image @file{gforth.fi} consist of a sequence of filenames and
 1173: @code{-e @var{forth-code}} options that are interpreted in the sequence
 1174: in which they are given. The @code{-e @var{forth-code}} or
 1175: @code{--evaluate @var{forth-code}} option evaluates the Forth
 1176: code. This option takes only one argument; if you want to evaluate more
 1177: Forth words, you have to quote them or use @code{-e} several times. To exit
 1178: after processing the command line (instead of entering interactive mode)
 1179: append @code{-e bye} to the command line.
 1180: 
 1181: @cindex versions, invoking other versions of Gforth
 1182: If you have several versions of Gforth installed, @code{gforth} will
 1183: invoke the version that was installed last. @code{gforth-@i{version}}
 1184: invokes a specific version. If your environment contains the variable
 1185: @code{GFORTHPATH}, you may want to override it by using the
 1186: @code{--path} option.
 1187: 
 1188: Not yet implemented:
 1189: On startup the system first executes the system initialization file
 1190: (unless the option @code{--no-init-file} is given; note that the system
 1191: resulting from using this option may not be ANS Forth conformant). Then
 1192: the user initialization file @file{.gforth.fs} is executed, unless the
 1193: option @code{--no-rc} is given; this file is searched for in @file{.},
 1194: then in @file{~}, then in the normal path (see above).
 1195: 
 1196: 
 1197: 
 1198: @comment ----------------------------------------------
 1199: @node Leaving Gforth, Command-line editing, Invoking Gforth, Gforth Environment
 1200: @section Leaving Gforth
 1201: @cindex Gforth - leaving
 1202: @cindex leaving Gforth
 1203: 
 1204: You can leave Gforth by typing @code{bye} or @kbd{Ctrl-d} (at the start
 1205: of a line) or (if you invoked Gforth with the @code{--die-on-signal}
 1206: option) @kbd{Ctrl-c}. When you leave Gforth, all of your definitions and
 1207: data are discarded.  For ways of saving the state of the system before
 1208: leaving Gforth see @ref{Image Files}.
 1209: 
 1210: doc-bye
 1211: 
 1212: 
 1213: @comment ----------------------------------------------
 1214: @node Command-line editing, Environment variables, Leaving Gforth, Gforth Environment
 1215: @section Command-line editing
 1216: @cindex command-line editing
 1217: 
 1218: Gforth maintains a history file that records every line that you type to
 1219: the text interpreter. This file is preserved between sessions, and is
 1220: used to provide a command-line recall facility; if you type @kbd{Ctrl-P}
 1221: repeatedly you can recall successively older commands from this (or
 1222: previous) session(s). The full list of command-line editing facilities is:
 1223: 
 1224: @itemize @bullet
 1225: @item
 1226: @kbd{Ctrl-p} (``previous'') (or up-arrow) to recall successively older
 1227: commands from the history buffer.
 1228: @item
 1229: @kbd{Ctrl-n} (``next'') (or down-arrow) to recall successively newer commands
 1230: from the history buffer.
 1231: @item
 1232: @kbd{Ctrl-f} (or right-arrow) to move the cursor right, non-destructively.
 1233: @item
 1234: @kbd{Ctrl-b} (or left-arrow) to move the cursor left, non-destructively.
 1235: @item
 1236: @kbd{Ctrl-h} (backspace) to delete the character to the left of the cursor,
 1237: closing up the line.
 1238: @item
 1239: @kbd{Ctrl-k} to delete (``kill'') from the cursor to the end of the line.
 1240: @item
 1241: @kbd{Ctrl-a} to move the cursor to the start of the line.
 1242: @item
 1243: @kbd{Ctrl-e} to move the cursor to the end of the line.
 1244: @item
 1245: @key{RET} (@kbd{Ctrl-m}) or @key{LFD} (@kbd{Ctrl-j}) to submit the current
 1246: line.
 1247: @item
 1248: @key{TAB} to step through all possible full-word completions of the word
 1249: currently being typed.
 1250: @item
 1251: @kbd{Ctrl-d} on an empty line line to terminate Gforth (gracefully,
 1252: using @code{bye}). 
 1253: @item
 1254: @kbd{Ctrl-x} (or @code{Ctrl-d} on a non-empty line) to delete the
 1255: character under the cursor.
 1256: @end itemize
 1257: 
 1258: When editing, displayable characters are inserted to the left of the
 1259: cursor position; the line is always in ``insert'' (as opposed to
 1260: ``overstrike'') mode.
 1261: 
 1262: @cindex history file
 1263: @cindex @file{.gforth-history}
 1264: On Unix systems, the history file is @file{~/.gforth-history} by
 1265: default@footnote{i.e. it is stored in the user's home directory.}. You
 1266: can find out the name and location of your history file using:
 1267: 
 1268: @example 
 1269: history-file type \ Unix-class systems
 1270: 
 1271: history-file type \ Other systems
 1272: history-dir  type
 1273: @end example
 1274: 
 1275: If you enter long definitions by hand, you can use a text editor to
 1276: paste them out of the history file into a Forth source file for reuse at
 1277: a later time.
 1278: 
 1279: Gforth never trims the size of the history file, so you should do this
 1280: periodically, if necessary.
 1281: 
 1282: @comment this is all defined in history.fs
 1283: @comment NAC TODO the ctrl-D behaviour can either do a bye or a beep.. how is that option
 1284: @comment chosen?
 1285: 
 1286: 
 1287: @comment ----------------------------------------------
 1288: @node Environment variables, Gforth Files, Command-line editing, Gforth Environment
 1289: @section Environment variables
 1290: @cindex environment variables
 1291: 
 1292: Gforth uses these environment variables:
 1293: 
 1294: @itemize @bullet
 1295: @item
 1296: @cindex @code{GFORTHHIST} -- environment variable
 1297: @code{GFORTHHIST} -- (Unix systems only) specifies the directory in which to
 1298: open/create the history file, @file{.gforth-history}. Default:
 1299: @code{$HOME}.
 1300: 
 1301: @item
 1302: @cindex @code{GFORTHPATH} -- environment variable
 1303: @code{GFORTHPATH} -- specifies the path used when searching for the gforth image file and
 1304: for Forth source-code files.
 1305: 
 1306: @item
 1307: @cindex @code{GFORTH} -- environment variable
 1308: @code{GFORTH} -- used by @file{gforthmi}, @xref{gforthmi}.
 1309: 
 1310: @item
 1311: @cindex @code{GFORTHD} -- environment variable
 1312: @code{GFORTHD} -- used by @file{gforthmi}, @xref{gforthmi}.
 1313: 
 1314: @item
 1315: @cindex @code{TMP}, @code{TEMP} - environment variable
 1316: @code{TMP}, @code{TEMP} - (non-Unix systems only) used as a potential
 1317: location for the history file.
 1318: @end itemize
 1319: 
 1320: @comment also POSIXELY_CORRECT LINES COLUMNS HOME but no interest in
 1321: @comment mentioning these.
 1322: 
 1323: All the Gforth environment variables default to sensible values if they
 1324: are not set.
 1325: 
 1326: 
 1327: @comment ----------------------------------------------
 1328: @node Gforth Files, Startup speed, Environment variables, Gforth Environment
 1329: @section Gforth files
 1330: @cindex Gforth files
 1331: 
 1332: When you install Gforth on a Unix system, it installs files in these
 1333: locations by default:
 1334: 
 1335: @itemize @bullet
 1336: @item
 1337: @file{/usr/local/bin/gforth}
 1338: @item
 1339: @file{/usr/local/bin/gforthmi}
 1340: @item
 1341: @file{/usr/local/man/man1/gforth.1} - man page.
 1342: @item
 1343: @file{/usr/local/info} - the Info version of this manual.
 1344: @item
 1345: @file{/usr/local/lib/gforth/<version>/...} - Gforth @file{.fi} files.
 1346: @item
 1347: @file{/usr/local/share/gforth/<version>/TAGS} - Emacs TAGS file.
 1348: @item
 1349: @file{/usr/local/share/gforth/<version>/...} - Gforth source files.
 1350: @item
 1351: @file{.../emacs/site-lisp/gforth.el} - Emacs gforth mode.
 1352: @end itemize
 1353: 
 1354: You can select different places for installation by using
 1355: @code{configure} options (listed with @code{configure --help}).
 1356: 
 1357: @comment ----------------------------------------------
 1358: @node Startup speed,  , Gforth Files, Gforth Environment
 1359: @section Startup speed
 1360: @cindex Startup speed
 1361: @cindex speed, startup
 1362: 
 1363: If Gforth is used for CGI scripts or in shell scripts, its startup
 1364: speed may become a problem.  On a 300MHz 21064a under Linux-2.2.13 with
 1365: glibc-2.0.7, @code{gforth -e bye} takes about 24.6ms user and 11.3ms
 1366: system time.
 1367: 
 1368: If startup speed is a problem, you may consider the following ways to
 1369: improve it; or you may consider ways to reduce the number of startups
 1370: (for example, by using Fast-CGI).
 1371: 
 1372: The first step to improve startup speed is to statically link Gforth, by
 1373: building it with @code{XLDFLAGS=-static}.  This requires more memory for
 1374: the code and will therefore slow down the first invocation, but
 1375: subsequent invocations avoid the dynamic linking overhead.  Another
 1376: disadvantage is that Gforth won't profit from library upgrades.  As a
 1377: result, @code{gforth-static -e bye} takes about 17.1ms user and
 1378: 8.2ms system time.
 1379: 
 1380: The next step to improve startup speed is to use a non-relocatable image
 1381: (@pxref{Non-Relocatable Image Files}).  You can create this image with
 1382: @code{gforth -e "savesystem gforthnr.fi bye"} and later use it with
 1383: @code{gforth -i gforthnr.fi ...}.  This avoids the relocation overhead
 1384: and a part of the copy-on-write overhead.  The disadvantage is that the
 1385: non-relocatable image does not work if the OS gives Gforth a different
 1386: address for the dictionary, for whatever reason; so you better provide a
 1387: fallback on a relocatable image.  @code{gforth-static -i gforthnr.fi -e
 1388: bye} takes about 15.3ms user and 7.5ms system time.
 1389: 
 1390: The final step is to disable dictionary hashing in Gforth.  Gforth
 1391: builds the hash table on startup, which takes much of the startup
 1392: overhead. You can do this by commenting out the @code{include hash.fs}
 1393: in @file{startup.fs} and everything that requires @file{hash.fs} (at the
 1394: moment @file{table.fs} and @file{ekey.fs}) and then doing @code{make}.
 1395: The disadvantages are that functionality like @code{table} and
 1396: @code{ekey} is missing and that text interpretation (e.g., compiling)
 1397: now takes much longer. So, you should only use this method if there is
 1398: no significant text interpretation to perform (the script should be
 1399: compiled into the image, amongst other things).  @code{gforth-static -i
 1400: gforthnrnh.fi -e bye} takes about 2.1ms user and 6.1ms system time.
 1401: 
 1402: @c ******************************************************************
 1403: @node Tutorial, Introduction, Gforth Environment, Top
 1404: @chapter Forth Tutorial
 1405: @cindex Tutorial
 1406: @cindex Forth Tutorial
 1407: 
 1408: @c Topics from nac's Introduction that could be mentioned:
 1409: @c press <ret> after each line
 1410: @c Prompt
 1411: @c numbers vs. words in dictionary on text interpretation
 1412: @c what happens on redefinition
 1413: @c parsing words (in particular, defining words)
 1414: 
 1415: The difference of this chapter from the Introduction
 1416: (@pxref{Introduction}) is that this tutorial is more fast-paced, should
 1417: be used while sitting in front of a computer, and covers much more
 1418: material, but does not explain how the Forth system works.
 1419: 
 1420: This tutorial can be used with any ANS-compliant Forth; any
 1421: Gforth-specific features are marked as such and you can skip them if you
 1422: work with another Forth.  This tutorial does not explain all features of
 1423: Forth, just enough to get you started and give you some ideas about the
 1424: facilities available in Forth.  Read the rest of the manual and the
 1425: standard when you are through this.
 1426: 
 1427: The intended way to use this tutorial is that you work through it while
 1428: sitting in front of the console, take a look at the examples and predict
 1429: what they will do, then try them out; if the outcome is not as expected,
 1430: find out why (e.g., by trying out variations of the example), so you
 1431: understand what's going on.  There are also some assignments that you
 1432: should solve.
 1433: 
 1434: This tutorial assumes that you have programmed before and know what,
 1435: e.g., a loop is.
 1436: 
 1437: @c !! explain compat library
 1438: 
 1439: @menu
 1440: * Starting Gforth Tutorial::    
 1441: * Syntax Tutorial::             
 1442: * Crash Course Tutorial::       
 1443: * Stack Tutorial::              
 1444: * Arithmetics Tutorial::        
 1445: * Stack Manipulation Tutorial::  
 1446: * Using files for Forth code Tutorial::  
 1447: * Comments Tutorial::           
 1448: * Colon Definitions Tutorial::  
 1449: * Decompilation Tutorial::      
 1450: * Stack-Effect Comments Tutorial::  
 1451: * Types Tutorial::              
 1452: * Factoring Tutorial::          
 1453: * Designing the stack effect Tutorial::  
 1454: * Local Variables Tutorial::    
 1455: * Conditional execution Tutorial::  
 1456: * Flags and Comparisons Tutorial::  
 1457: * General Loops Tutorial::      
 1458: * Counted loops Tutorial::      
 1459: * Recursion Tutorial::          
 1460: * Leaving definitions or loops Tutorial::  
 1461: * Return Stack Tutorial::       
 1462: * Memory Tutorial::             
 1463: * Characters and Strings Tutorial::  
 1464: * Alignment Tutorial::          
 1465: * Files Tutorial::              
 1466: * Interpretation and Compilation Semantics and Immediacy Tutorial::  
 1467: * Execution Tokens Tutorial::   
 1468: * Exceptions Tutorial::         
 1469: * Defining Words Tutorial::     
 1470: * Arrays and Records Tutorial::  
 1471: * POSTPONE Tutorial::           
 1472: * Literal Tutorial::            
 1473: * Advanced macros Tutorial::    
 1474: * Compilation Tokens Tutorial::  
 1475: * Wordlists and Search Order Tutorial::  
 1476: @end menu
 1477: 
 1478: @node Starting Gforth Tutorial, Syntax Tutorial, Tutorial, Tutorial
 1479: @section Starting Gforth
 1480: @cindex starting Gforth tutorial
 1481: You can start Gforth by typing its name:
 1482: 
 1483: @example
 1484: gforth
 1485: @end example
 1486: 
 1487: That puts you into interactive mode; you can leave Gforth by typing
 1488: @code{bye}.  While in Gforth, you can edit the command line and access
 1489: the command line history with cursor keys, similar to bash.
 1490: 
 1491: 
 1492: @node Syntax Tutorial, Crash Course Tutorial, Starting Gforth Tutorial, Tutorial
 1493: @section Syntax
 1494: @cindex syntax tutorial
 1495: 
 1496: A @dfn{word} is a sequence of arbitrary characters (expcept white
 1497: space).  Words are separated by white space.  E.g., each of the
 1498: following lines contains exactly one word:
 1499: 
 1500: @example
 1501: word
 1502: !@@#$%^&*()
 1503: 1234567890
 1504: 5!a
 1505: @end example
 1506: 
 1507: A frequent beginner's error is to leave away necessary white space,
 1508: resulting in an error like @samp{Undefined word}; so if you see such an
 1509: error, check if you have put spaces wherever necessary.
 1510: 
 1511: @example
 1512: ." hello, world" \ correct
 1513: ."hello, world"  \ gives an "Undefined word" error
 1514: @end example
 1515: 
 1516: Gforth and most other Forth systems ignore differences in case (they are
 1517: case-insensitive), i.e., @samp{word} is the same as @samp{Word}.  If
 1518: your system is case-sensitive, you may have to type all the examples
 1519: given here in upper case.
 1520: 
 1521: 
 1522: @node Crash Course Tutorial, Stack Tutorial, Syntax Tutorial, Tutorial
 1523: @section Crash Course
 1524: 
 1525: Type
 1526: 
 1527: @example
 1528: 0 0 !
 1529: here execute
 1530: ' catch >body 20 erase abort
 1531: ' (quit) >body 20 erase
 1532: @end example
 1533: 
 1534: The last two examples are guaranteed to destroy parts of Gforth (and
 1535: most other systems), so you better leave Gforth afterwards (if it has
 1536: not finished by itself).  On some systems you may have to kill gforth
 1537: from outside (e.g., in Unix with @code{kill}).
 1538: 
 1539: Now that you know how to produce crashes (and that there's not much to
 1540: them), let's learn how to produce meaningful programs.
 1541: 
 1542: 
 1543: @node Stack Tutorial, Arithmetics Tutorial, Crash Course Tutorial, Tutorial
 1544: @section Stack
 1545: @cindex stack tutorial
 1546: 
 1547: The most obvious feature of Forth is the stack.  When you type in a
 1548: number, it is pushed on the stack.  You can display the content of the
 1549: stack with @code{.s}.
 1550: 
 1551: @example
 1552: 1 2 .s
 1553: 3 .s
 1554: @end example
 1555: 
 1556: @code{.s} displays the top-of-stack to the right, i.e., the numbers
 1557: appear in @code{.s} output as they appeared in the input.
 1558: 
 1559: You can print the top of stack element with @code{.}.
 1560: 
 1561: @example
 1562: 1 2 3 . . .
 1563: @end example
 1564: 
 1565: In general, words consume their stack arguments (@code{.s} is an
 1566: exception).
 1567: 
 1568: @assignment
 1569: What does the stack contain after @code{5 6 7 .}?
 1570: @endassignment
 1571: 
 1572: 
 1573: @node Arithmetics Tutorial, Stack Manipulation Tutorial, Stack Tutorial, Tutorial
 1574: @section Arithmetics
 1575: @cindex arithmetics tutorial
 1576: 
 1577: The words @code{+}, @code{-}, @code{*}, @code{/}, and @code{mod} always
 1578: operate on the top two stack items:
 1579: 
 1580: @example
 1581: 2 2 .s
 1582: + .s
 1583: .
 1584: 2 1 - .
 1585: 7 3 mod .
 1586: @end example
 1587: 
 1588: The operands of @code{-}, @code{/}, and @code{mod} are in the same order
 1589: as in the corresponding infix expression (this is generally the case in
 1590: Forth).
 1591: 
 1592: Parentheses are superfluous (and not available), because the order of
 1593: the words unambiguously determines the order of evaluation and the
 1594: operands:
 1595: 
 1596: @example
 1597: 3 4 + 5 * .
 1598: 3 4 5 * + .
 1599: @end example
 1600: 
 1601: @assignment
 1602: What are the infix expressions corresponding to the Forth code above?
 1603: Write @code{6-7*8+9} in Forth notation@footnote{This notation is also
 1604: known as Postfix or RPN (Reverse Polish Notation).}.
 1605: @endassignment
 1606: 
 1607: To change the sign, use @code{negate}:
 1608: 
 1609: @example
 1610: 2 negate .
 1611: @end example
 1612: 
 1613: @assignment
 1614: Convert -(-3)*4-5 to Forth.
 1615: @endassignment
 1616: 
 1617: @code{/mod} performs both @code{/} and @code{mod}.
 1618: 
 1619: @example
 1620: 7 3 /mod . .
 1621: @end example
 1622: 
 1623: Reference: @ref{Arithmetic}.
 1624: 
 1625: 
 1626: @node Stack Manipulation Tutorial, Using files for Forth code Tutorial, Arithmetics Tutorial, Tutorial
 1627: @section Stack Manipulation
 1628: @cindex stack manipulation tutorial
 1629: 
 1630: Stack manipulation words rearrange the data on the stack.
 1631: 
 1632: @example
 1633: 1 .s drop .s
 1634: 1 .s dup .s drop drop .s
 1635: 1 2 .s over .s drop drop drop
 1636: 1 2 .s swap .s drop drop
 1637: 1 2 3 .s rot .s drop drop drop
 1638: @end example
 1639: 
 1640: These are the most important stack manipulation words.  There are also
 1641: variants that manipulate twice as many stack items:
 1642: 
 1643: @example
 1644: 1 2 3 4 .s 2swap .s 2drop 2drop
 1645: @end example
 1646: 
 1647: Two more stack manipulation words are:
 1648: 
 1649: @example
 1650: 1 2 .s nip .s drop
 1651: 1 2 .s tuck .s 2drop drop
 1652: @end example
 1653: 
 1654: @assignment
 1655: Replace @code{nip} and @code{tuck} with combinations of other stack
 1656: manipulation words.
 1657: 
 1658: @example
 1659: Given:          How do you get:
 1660: 1 2 3           3 2 1           
 1661: 1 2 3           1 2 3 2                 
 1662: 1 2 3           1 2 3 3                 
 1663: 1 2 3           1 3 3           
 1664: 1 2 3           2 1 3           
 1665: 1 2 3 4         4 3 2 1         
 1666: 1 2 3           1 2 3 1 2 3             
 1667: 1 2 3 4         1 2 3 4 1 2             
 1668: 1 2 3
 1669: 1 2 3           1 2 3 4                 
 1670: 1 2 3           1 3             
 1671: @end example
 1672: @endassignment
 1673: 
 1674: @example
 1675: 5 dup * .
 1676: @end example
 1677: 
 1678: @assignment
 1679: Write 17^3 and 17^4 in Forth, without writing @code{17} more than once.
 1680: Write a piece of Forth code that expects two numbers on the stack
 1681: (@var{a} and @var{b}, with @var{b} on top) and computes
 1682: @code{(a-b)(a+1)}.
 1683: @endassignment
 1684: 
 1685: Reference: @ref{Stack Manipulation}.
 1686: 
 1687: 
 1688: @node Using files for Forth code Tutorial, Comments Tutorial, Stack Manipulation Tutorial, Tutorial
 1689: @section Using files for Forth code
 1690: @cindex loading Forth code, tutorial
 1691: @cindex files containing Forth code, tutorial
 1692: 
 1693: While working at the Forth command line is convenient for one-line
 1694: examples and short one-off code, you probably want to store your source
 1695: code in files for convenient editing and persistence.  You can use your
 1696: favourite editor (Gforth includes Emacs support, @pxref{Emacs and
 1697: Gforth}) to create @var{file} and use
 1698: 
 1699: @example
 1700: s" @var{file}" included
 1701: @end example
 1702: 
 1703: to load it into your Forth system.  The file name extension I use for
 1704: Forth files is @samp{.fs}.
 1705: 
 1706: You can easily start Gforth with some files loaded like this:
 1707: 
 1708: @example
 1709: gforth @var{file1} @var{file2}
 1710: @end example
 1711: 
 1712: If an error occurs during loading these files, Gforth terminates,
 1713: whereas an error during @code{INCLUDED} within Gforth usually gives you
 1714: a Gforth command line.  Starting the Forth system every time gives you a
 1715: clean start every time, without interference from the results of earlier
 1716: tries.
 1717: 
 1718: I often put all the tests in a file, then load the code and run the
 1719: tests with
 1720: 
 1721: @example
 1722: gforth @var{code} @var{tests} -e bye
 1723: @end example
 1724: 
 1725: (often by performing this command with @kbd{C-x C-e} in Emacs).  The
 1726: @code{-e bye} ensures that Gforth terminates afterwards so that I can
 1727: restart this command without ado.
 1728: 
 1729: The advantage of this approach is that the tests can be repeated easily
 1730: every time the program ist changed, making it easy to catch bugs
 1731: introduced by the change.
 1732: 
 1733: Reference: @ref{Forth source files}.
 1734: 
 1735: 
 1736: @node Comments Tutorial, Colon Definitions Tutorial, Using files for Forth code Tutorial, Tutorial
 1737: @section Comments
 1738: @cindex comments tutorial
 1739: 
 1740: @example
 1741: \ That's a comment; it ends at the end of the line
 1742: ( Another comment; it ends here: )  .s
 1743: @end example
 1744: 
 1745: @code{\} and @code{(} are ordinary Forth words and therefore have to be
 1746: separated with white space from the following text.
 1747: 
 1748: @example
 1749: \This gives an "Undefined word" error
 1750: @end example
 1751: 
 1752: The first @code{)} ends a comment started with @code{(}, so you cannot
 1753: nest @code{(}-comments; and you cannot comment out text containing a
 1754: @code{)} with @code{( ... )}@footnote{therefore it's a good idea to
 1755: avoid @code{)} in word names.}.
 1756: 
 1757: I use @code{\}-comments for descriptive text and for commenting out code
 1758: of one or more line; I use @code{(}-comments for describing the stack
 1759: effect, the stack contents, or for commenting out sub-line pieces of
 1760: code.
 1761: 
 1762: The Emacs mode @file{gforth.el} (@pxref{Emacs and Gforth}) supports
 1763: these uses by commenting out a region with @kbd{C-x \}, uncommenting a
 1764: region with @kbd{C-u C-x \}, and filling a @code{\}-commented region
 1765: with @kbd{M-q}.
 1766: 
 1767: Reference: @ref{Comments}.
 1768: 
 1769: 
 1770: @node Colon Definitions Tutorial, Decompilation Tutorial, Comments Tutorial, Tutorial
 1771: @section Colon Definitions
 1772: @cindex colon definitions, tutorial
 1773: @cindex definitions, tutorial
 1774: @cindex procedures, tutorial
 1775: @cindex functions, tutorial
 1776: 
 1777: are similar to procedures and functions in other programming languages.
 1778: 
 1779: @example
 1780: : squared ( n -- n^2 )
 1781:    dup * ;
 1782: 5 squared .
 1783: 7 squared .
 1784: @end example
 1785: 
 1786: @code{:} starts the colon definition; its name is @code{squared}.  The
 1787: following comment describes its stack effect.  The words @code{dup *}
 1788: are not executed, but compiled into the definition.  @code{;} ends the
 1789: colon definition.
 1790: 
 1791: The newly-defined word can be used like any other word, including using
 1792: it in other definitions:
 1793: 
 1794: @example
 1795: : cubed ( n -- n^3 )
 1796:    dup squared * ;
 1797: -5 cubed .
 1798: : fourth-power ( n -- n^4 )
 1799:    squared squared ;
 1800: 3 fourth-power .
 1801: @end example
 1802: 
 1803: @assignment
 1804: Write colon definitions for @code{nip}, @code{tuck}, @code{negate}, and
 1805: @code{/mod} in terms of other Forth words, and check if they work (hint:
 1806: test your tests on the originals first).  Don't let the
 1807: @samp{redefined}-Messages spook you, they are just warnings.
 1808: @endassignment
 1809: 
 1810: Reference: @ref{Colon Definitions}.
 1811: 
 1812: 
 1813: @node Decompilation Tutorial, Stack-Effect Comments Tutorial, Colon Definitions Tutorial, Tutorial
 1814: @section Decompilation
 1815: @cindex decompilation tutorial
 1816: @cindex see tutorial
 1817: 
 1818: You can decompile colon definitions with @code{see}:
 1819: 
 1820: @example
 1821: see squared
 1822: see cubed
 1823: @end example
 1824: 
 1825: In Gforth @code{see} shows you a reconstruction of the source code from
 1826: the executable code.  Informations that were present in the source, but
 1827: not in the executable code, are lost (e.g., comments).
 1828: 
 1829: You can also decompile the predefined words:
 1830: 
 1831: @example
 1832: see .
 1833: see +
 1834: @end example
 1835: 
 1836: 
 1837: @node Stack-Effect Comments Tutorial, Types Tutorial, Decompilation Tutorial, Tutorial
 1838: @section Stack-Effect Comments
 1839: @cindex stack-effect comments, tutorial
 1840: @cindex --, tutorial
 1841: By convention the comment after the name of a definition describes the
 1842: stack effect: The part in from of the @samp{--} describes the state of
 1843: the stack before the execution of the definition, i.e., the parameters
 1844: that are passed into the colon definition; the part behind the @samp{--}
 1845: is the state of the stack after the execution of the definition, i.e.,
 1846: the results of the definition.  The stack comment only shows the top
 1847: stack items that the definition accesses and/or changes.
 1848: 
 1849: You should put a correct stack effect on every definition, even if it is
 1850: just @code{( -- )}.  You should also add some descriptive comment to
 1851: more complicated words (I usually do this in the lines following
 1852: @code{:}).  If you don't do this, your code becomes unreadable (because
 1853: you have to work through every definition before you can undertsand
 1854: any).
 1855: 
 1856: @assignment
 1857: The stack effect of @code{swap} can be written like this: @code{x1 x2 --
 1858: x2 x1}.  Describe the stack effect of @code{-}, @code{drop}, @code{dup},
 1859: @code{over}, @code{rot}, @code{nip}, and @code{tuck}.  Hint: When you
 1860: are done, you can compare your stack effects to those in this manual
 1861: (@pxref{Word Index}).
 1862: @endassignment
 1863: 
 1864: Sometimes programmers put comments at various places in colon
 1865: definitions that describe the contents of the stack at that place (stack
 1866: comments); i.e., they are like the first part of a stack-effect
 1867: comment. E.g.,
 1868: 
 1869: @example
 1870: : cubed ( n -- n^3 )
 1871:    dup squared  ( n n^2 ) * ;
 1872: @end example
 1873: 
 1874: In this case the stack comment is pretty superfluous, because the word
 1875: is simple enough.  If you think it would be a good idea to add such a
 1876: comment to increase readability, you should also consider factoring the
 1877: word into several simpler words (@pxref{Factoring Tutorial,,
 1878: Factoring}), which typically eliminates the need for the stack comment;
 1879: however, if you decide not to refactor it, then having such a comment is
 1880: better than not having it.
 1881: 
 1882: The names of the stack items in stack-effect and stack comments in the
 1883: standard, in this manual, and in many programs specify the type through
 1884: a type prefix, similar to Fortran and Hungarian notation.  The most
 1885: frequent prefixes are:
 1886: 
 1887: @table @code
 1888: @item n
 1889: signed integer
 1890: @item u
 1891: unsigned integer
 1892: @item c
 1893: character
 1894: @item f
 1895: Boolean flags, i.e. @code{false} or @code{true}.
 1896: @item a-addr,a-
 1897: Cell-aligned address
 1898: @item c-addr,c-
 1899: Char-aligned address (note that a Char may have two bytes in Windows NT)
 1900: @item xt
 1901: Execution token, same size as Cell
 1902: @item w,x
 1903: Cell, can contain an integer or an address.  It usually takes 32, 64 or
 1904: 16 bits (depending on your platform and Forth system). A cell is more
 1905: commonly known as machine word, but the term @emph{word} already means
 1906: something different in Forth.
 1907: @item d
 1908: signed double-cell integer
 1909: @item ud
 1910: unsigned double-cell integer
 1911: @item r
 1912: Float (on the FP stack)
 1913: @end table
 1914: 
 1915: You can find a more complete list in @ref{Notation}.
 1916: 
 1917: @assignment
 1918: Write stack-effect comments for all definitions you have written up to
 1919: now.
 1920: @endassignment
 1921: 
 1922: 
 1923: @node Types Tutorial, Factoring Tutorial, Stack-Effect Comments Tutorial, Tutorial
 1924: @section Types
 1925: @cindex types tutorial
 1926: 
 1927: In Forth the names of the operations are not overloaded; so similar
 1928: operations on different types need different names; e.g., @code{+} adds
 1929: integers, and you have to use @code{f+} to add floating-point numbers.
 1930: The following prefixes are often used for related operations on
 1931: different types:
 1932: 
 1933: @table @code
 1934: @item (none)
 1935: signed integer
 1936: @item u
 1937: unsigned integer
 1938: @item c
 1939: character
 1940: @item d
 1941: signed double-cell integer
 1942: @item ud, du
 1943: unsigned double-cell integer
 1944: @item 2
 1945: two cells (not-necessarily double-cell numbers)
 1946: @item m, um
 1947: mixed single-cell and double-cell operations
 1948: @item f
 1949: floating-point (note that in stack comments @samp{f} represents flags,
 1950: and @samp{r} represents FP numbers).
 1951: @end table
 1952: 
 1953: If there are no differences between the signed and the unsigned variant
 1954: (e.g., for @code{+}), there is only the prefix-less variant.
 1955: 
 1956: Forth does not perform type checking, neither at compile time, nor at
 1957: run time.  If you use the wrong oeration, the data are interpreted
 1958: incorrectly:
 1959: 
 1960: @example
 1961: -1 u.
 1962: @end example
 1963: 
 1964: If you have only experience with type-checked languages until now, and
 1965: have heard how important type-checking is, don't panic!  In my
 1966: experience (and that of other Forthers), type errors in Forth code are
 1967: usually easy to find (once you get used to it), the increased vigilance
 1968: of the programmer tends to catch some harder errors in addition to most
 1969: type errors, and you never have to work around the type system, so in
 1970: most situations the lack of type-checking seems to be a win (projects to
 1971: add type checking to Forth have not caught on).
 1972: 
 1973: 
 1974: @node Factoring Tutorial, Designing the stack effect Tutorial, Types Tutorial, Tutorial
 1975: @section Factoring
 1976: @cindex factoring tutorial
 1977: 
 1978: If you try to write longer definitions, you will soon find it hard to
 1979: keep track of the stack contents.  Therefore, good Forth programmers
 1980: tend to write only short definitions (e.g., three lines).  The art of
 1981: finding meaningful short definitions is known as factoring (as in
 1982: factoring polynomials).
 1983: 
 1984: Well-factored programs offer additional advantages: smaller, more
 1985: general words, are easier to test and debug and can be reused more and
 1986: better than larger, specialized words.
 1987: 
 1988: So, if you run into difficulties with stack management, when writing
 1989: code, try to define meaningful factors for the word, and define the word
 1990: in terms of those.  Even if a factor contains only two words, it is
 1991: often helpful.
 1992: 
 1993: Good factoring is not easy, and it takes some practice to get the knack
 1994: for it; but even experienced Forth programmers often don't find the
 1995: right solution right away, but only when rewriting the program.  So, if
 1996: you don't come up with a good solution immediately, keep trying, don't
 1997: despair.
 1998: 
 1999: @c example !!
 2000: 
 2001: 
 2002: @node Designing the stack effect Tutorial, Local Variables Tutorial, Factoring Tutorial, Tutorial
 2003: @section Designing the stack effect
 2004: @cindex Stack effect design, tutorial
 2005: @cindex design of stack effects, tutorial
 2006: 
 2007: In other languages you can use an arbitrary order of parameters for a
 2008: function; and since there is only one result, you don't have to deal with
 2009: the order of results, either.
 2010: 
 2011: In Forth (and other stack-based languages, e.g., Postscript) the
 2012: parameter and result order of a definition is important and should be
 2013: designed well.  The general guideline is to design the stack effect such
 2014: that the word is simple to use in most cases, even if that complicates
 2015: the implementation of the word.  Some concrete rules are:
 2016: 
 2017: @itemize @bullet
 2018: 
 2019: @item
 2020: Words consume all of their parameters (e.g., @code{.}).
 2021: 
 2022: @item
 2023: If there is a convention on the order of parameters (e.g., from
 2024: mathematics or another programming language), stick with it (e.g.,
 2025: @code{-}).
 2026: 
 2027: @item
 2028: If one parameter usually requires only a short computation (e.g., it is
 2029: a constant), pass it on the top of the stack.  Conversely, parameters
 2030: that usually require a long sequence of code to compute should be passed
 2031: as the bottom (i.e., first) parameter.  This makes the code easier to
 2032: read, because reader does not need to keep track of the bottom item
 2033: through a long sequence of code (or, alternatively, through stack
 2034: manipulations). E.g., @code{!} (store, @pxref{Memory}) expects the
 2035: address on top of the stack because it is usually simpler to compute
 2036: than the stored value (often the address is just a variable).
 2037: 
 2038: @item
 2039: Similarly, results that are usually consumed quickly should be returned
 2040: on the top of stack, whereas a result that is often used in long
 2041: computations should be passed as bottom result.  E.g., the file words
 2042: like @code{open-file} return the error code on the top of stack, because
 2043: it is usually consumed quickly by @code{throw}; moreover, the error code
 2044: has to be checked before doing anything with the other results.
 2045: 
 2046: @end itemize
 2047: 
 2048: These rules are just general guidelines, don't lose sight of the overall
 2049: goal to make the words easy to use.  E.g., if the convention rule
 2050: conflicts with the computation-length rule, you might decide in favour
 2051: of the convention if the word will be used rarely, and in favour of the
 2052: computation-length rule if the word will be used frequently (because
 2053: with frequent use the cost of breaking the computation-length rule would
 2054: be quite high, and frequent use makes it easier to remember an
 2055: unconventional order).
 2056: 
 2057: @c example !! structure package
 2058: 
 2059: 
 2060: @node Local Variables Tutorial, Conditional execution Tutorial, Designing the stack effect Tutorial, Tutorial
 2061: @section Local Variables
 2062: @cindex local variables, tutorial
 2063: 
 2064: You can define local variables (@emph{locals}) in a colon definition:
 2065: 
 2066: @example
 2067: : swap @{ a b -- b a @}
 2068:   b a ;
 2069: 1 2 swap .s 2drop
 2070: @end example
 2071: 
 2072: (If your Forth system does not support this syntax, include
 2073: @file{compat/anslocals.fs} first).
 2074: 
 2075: In this example @code{@{ a b -- b a @}} is the locals definition; it
 2076: takes two cells from the stack, puts the top of stack in @code{b} and
 2077: the next stack element in @code{a}.  @code{--} starts a comment ending
 2078: with @code{@}}.  After the locals definition, using the name of the
 2079: local will push its value on the stack.  You can leave the comment
 2080: part (@code{-- b a}) away:
 2081: 
 2082: @example
 2083: : swap ( x1 x2 -- x2 x1 )
 2084:   @{ a b @} b a ;
 2085: @end example
 2086: 
 2087: In Gforth you can have several locals definitions, anywhere in a colon
 2088: definition; in contrast, in a standard program you can have only one
 2089: locals definition per colon definition, and that locals definition must
 2090: be outside any controll structure.
 2091: 
 2092: With locals you can write slightly longer definitions without running
 2093: into stack trouble.  However, I recommend trying to write colon
 2094: definitions without locals for exercise purposes to help you gain the
 2095: essential factoring skills.
 2096: 
 2097: @assignment
 2098: Rewrite your definitions until now with locals
 2099: @endassignment
 2100: 
 2101: Reference: @ref{Locals}.
 2102: 
 2103: 
 2104: @node Conditional execution Tutorial, Flags and Comparisons Tutorial, Local Variables Tutorial, Tutorial
 2105: @section Conditional execution
 2106: @cindex conditionals, tutorial
 2107: @cindex if, tutorial
 2108: 
 2109: In Forth you can use control structures only inside colon definitions.
 2110: An @code{if}-structure looks like this:
 2111: 
 2112: @example
 2113: : abs ( n1 -- +n2 )
 2114:     dup 0 < if
 2115:         negate
 2116:     endif ;
 2117: 5 abs .
 2118: -5 abs .
 2119: @end example
 2120: 
 2121: @code{if} takes a flag from the stack.  If the flag is non-zero (true),
 2122: the following code is performed, otherwise execution continues after the
 2123: @code{endif} (or @code{else}).  @code{<} compares the top two stack
 2124: elements and prioduces a flag:
 2125: 
 2126: @example
 2127: 1 2 < .
 2128: 2 1 < .
 2129: 1 1 < .
 2130: @end example
 2131: 
 2132: Actually the standard name for @code{endif} is @code{then}.  This
 2133: tutorial presents the examples using @code{endif}, because this is often
 2134: less confusing for people familiar with other programming languages
 2135: where @code{then} has a different meaning.  If your system does not have
 2136: @code{endif}, define it with
 2137: 
 2138: @example
 2139: : endif postpone then ; immediate
 2140: @end example
 2141: 
 2142: You can optionally use an @code{else}-part:
 2143: 
 2144: @example
 2145: : min ( n1 n2 -- n )
 2146:   2dup < if
 2147:     drop
 2148:   else
 2149:     nip
 2150:   endif ;
 2151: 2 3 min .
 2152: 3 2 min .
 2153: @end example
 2154: 
 2155: @assignment
 2156: Write @code{min} without @code{else}-part (hint: what's the definition
 2157: of @code{nip}?).
 2158: @endassignment
 2159: 
 2160: Reference: @ref{Selection}.
 2161: 
 2162: 
 2163: @node Flags and Comparisons Tutorial, General Loops Tutorial, Conditional execution Tutorial, Tutorial
 2164: @section Flags and Comparisons
 2165: @cindex flags tutorial
 2166: @cindex comparison tutorial
 2167: 
 2168: In a false-flag all bits are clear (0 when interpreted as integer).  In
 2169: a canonical true-flag all bits are set (-1 as a twos-complement signed
 2170: integer); in many contexts (e.g., @code{if}) any non-zero value is
 2171: treated as true flag.
 2172: 
 2173: @example
 2174: false .
 2175: true .
 2176: true hex u. decimal
 2177: @end example
 2178: 
 2179: Comparison words produce canonical flags:
 2180: 
 2181: @example
 2182: 1 1 = .
 2183: 1 0= .
 2184: 0 1 < .
 2185: 0 0 < .
 2186: -1 1 u< . \ type error, u< interprets -1 as large unsigned number
 2187: -1 1 < .
 2188: @end example
 2189: 
 2190: Gforth supports all combinations of the prefixes @code{0 u d d0 du f f0}
 2191: (or none) and the comparisons @code{= <> < > <= >=}.  Only a part of
 2192: these combinations are standard (for details see the standard,
 2193: @ref{Numeric comparison}, @ref{Floating Point} or @ref{Word Index}).
 2194: 
 2195: You can use @code{and or xor invert} can be used as operations on
 2196: canonical flags.  Actually they are bitwise operations:
 2197: 
 2198: @example
 2199: 1 2 and .
 2200: 1 2 or .
 2201: 1 3 xor .
 2202: 1 invert .
 2203: @end example
 2204: 
 2205: You can convert a zero/non-zero flag into a canonical flag with
 2206: @code{0<>} (and complement it on the way with @code{0=}).
 2207: 
 2208: @example
 2209: 1 0= .
 2210: 1 0<> .
 2211: @end example
 2212: 
 2213: You can use the all-bits-set feature of canonical flags and the bitwise
 2214: operation of the Boolean operations to avoid @code{if}s:
 2215: 
 2216: @example
 2217: : foo ( n1 -- n2 )
 2218:   0= if
 2219:     14
 2220:   else
 2221:     0
 2222:   endif ;
 2223: 0 foo .
 2224: 1 foo .
 2225: 
 2226: : foo ( n1 -- n2 )
 2227:   0= 14 and ;
 2228: 0 foo .
 2229: 1 foo .
 2230: @end example
 2231: 
 2232: @assignment
 2233: Write @code{min} without @code{if}.
 2234: @endassignment
 2235: 
 2236: For reference, see @ref{Boolean Flags}, @ref{Numeric comparison}, and
 2237: @ref{Bitwise operations}.
 2238: 
 2239: 
 2240: @node General Loops Tutorial, Counted loops Tutorial, Flags and Comparisons Tutorial, Tutorial
 2241: @section General Loops
 2242: @cindex loops, indefinite, tutorial
 2243: 
 2244: The endless loop is the most simple one:
 2245: 
 2246: @example
 2247: : endless ( -- )
 2248:   0 begin
 2249:     dup . 1+
 2250:   again ;
 2251: endless
 2252: @end example
 2253: 
 2254: Terminate this loop by pressing @kbd{Ctrl-C} (in Gforth).  @code{begin}
 2255: does nothing at run-time, @code{again} jumps back to @code{begin}.
 2256: 
 2257: A loop with one exit at any place looks like this:
 2258: 
 2259: @example
 2260: : log2 ( +n1 -- n2 )
 2261: \ logarithmus dualis of n1>0, rounded down to the next integer
 2262:   assert( dup 0> )
 2263:   2/ 0 begin
 2264:     over 0> while
 2265:       1+ swap 2/ swap
 2266:   repeat
 2267:   nip ;
 2268: 7 log2 .
 2269: 8 log2 .
 2270: @end example
 2271: 
 2272: At run-time @code{while} consumes a flag; if it is 0, execution
 2273: continues behind the @code{repeat}; if the flag is non-zero, execution
 2274: continues behind the @code{while}.  @code{Repeat} jumps back to
 2275: @code{begin}, just like @code{again}.
 2276: 
 2277: In Forth there are many combinations/abbreviations, like @code{1+}.
 2278: However, @code{2/} is not one of them; it shifts it's argument right by
 2279: one bit (arithmetic shift right):
 2280: 
 2281: @example
 2282: -5 2 / .
 2283: -5 2/ .
 2284: @end example
 2285: 
 2286: @code{assert(} is no standard word, but you can get it on systems other
 2287: then Gforth by including @file{compat/assert.fs}.  You can see what it
 2288: does by trying
 2289: 
 2290: @example
 2291: 0 log2 .
 2292: @end example
 2293: 
 2294: Here's a loop with an exit at the end:
 2295: 
 2296: @example
 2297: : log2 ( +n1 -- n2 )
 2298: \ logarithmus dualis of n1>0, rounded down to the next integer
 2299:   assert( dup 0 > )
 2300:   -1 begin
 2301:     1+ swap 2/ swap
 2302:     over 0 <=
 2303:   until
 2304:   nip ;
 2305: @end example
 2306: 
 2307: @code{Until} consumes a flag; if it is non-zero, execution continues at
 2308: the @code{begin}, otherwise after the @code{until}.
 2309: 
 2310: @assignment
 2311: Write a definition for computing the greatest common divisor.
 2312: @endassignment
 2313: 
 2314: Reference: @ref{Simple Loops}.
 2315: 
 2316: 
 2317: @node Counted loops Tutorial, Recursion Tutorial, General Loops Tutorial, Tutorial
 2318: @section Counted loops
 2319: @cindex loops, counted, tutorial
 2320: 
 2321: @example
 2322: : ^ ( n1 u -- n )
 2323: \ n = the uth power of u1
 2324:   1 swap 0 u+do
 2325:     over *
 2326:   loop
 2327:   nip ;
 2328: 3 2 ^ .
 2329: 4 3 ^ .
 2330: @end example
 2331: 
 2332: @code{U+do} (from @file{compat/loops.fs}, if your Forth system doesn't
 2333: have it) takes two numbers of the stack @code{( u3 u4 -- )}, and then
 2334: performs the code between @code{u+do} and @code{loop} for @code{u3-u4}
 2335: times (or not at all, if @code{u3-u4<0}).
 2336: 
 2337: You can see the stack effect design rules at work in the stack effect of
 2338: the loop start words: Since the start value of the loop is more
 2339: frequently constant than the end value, the start value is passed on
 2340: the top-of-stack.
 2341: 
 2342: You can access the counter of a counted loop with @code{i}:
 2343: 
 2344: @example
 2345: : fac ( u -- u! )
 2346:   1 swap 1+ 1 u+do
 2347:     i *
 2348:   loop ;
 2349: 5 fac .
 2350: 7 fac .
 2351: @end example
 2352: 
 2353: There is also @code{+do}, which expects signed numbers (important for
 2354: deciding whether to enter the loop).
 2355: 
 2356: @assignment
 2357: Write a definition for computing the nth Fibonacci number.
 2358: @endassignment
 2359: 
 2360: You can also use increments other than 1:
 2361: 
 2362: @example
 2363: : up2 ( n1 n2 -- )
 2364:   +do
 2365:     i .
 2366:   2 +loop ;
 2367: 10 0 up2
 2368: 
 2369: : down2 ( n1 n2 -- )
 2370:   -do
 2371:     i .
 2372:   2 -loop ;
 2373: 0 10 down2
 2374: @end example
 2375: 
 2376: Reference: @ref{Counted Loops}.
 2377: 
 2378: 
 2379: @node Recursion Tutorial, Leaving definitions or loops Tutorial, Counted loops Tutorial, Tutorial
 2380: @section Recursion
 2381: @cindex recursion tutorial
 2382: 
 2383: Usually the name of a definition is not visible in the definition; but
 2384: earlier definitions are usually visible:
 2385: 
 2386: @example
 2387: 1 0 / . \ "Floating-point unidentified fault" in Gforth on most platforms
 2388: : / ( n1 n2 -- n )
 2389:   dup 0= if
 2390:     -10 throw \ report division by zero
 2391:   endif
 2392:   /           \ old version
 2393: ;
 2394: 1 0 /
 2395: @end example
 2396: 
 2397: For recursive definitions you can use @code{recursive} (non-standard) or
 2398: @code{recurse}:
 2399: 
 2400: @example
 2401: : fac1 ( n -- n! ) recursive
 2402:  dup 0> if
 2403:    dup 1- fac1 *
 2404:  else
 2405:    drop 1
 2406:  endif ;
 2407: 7 fac1 .
 2408: 
 2409: : fac2 ( n -- n! )
 2410:  dup 0> if
 2411:    dup 1- recurse *
 2412:  else
 2413:    drop 1
 2414:  endif ;
 2415: 8 fac2 .
 2416: @end example
 2417: 
 2418: @assignment
 2419: Write a recursive definition for computing the nth Fibonacci number.
 2420: @endassignment
 2421: 
 2422: Reference (including indirect recursion): @xref{Calls and returns}.
 2423: 
 2424: 
 2425: @node Leaving definitions or loops Tutorial, Return Stack Tutorial, Recursion Tutorial, Tutorial
 2426: @section Leaving definitions or loops
 2427: @cindex leaving definitions, tutorial
 2428: @cindex leaving loops, tutorial
 2429: 
 2430: @code{EXIT} exits the current definition right away.  For every counted
 2431: loop that is left in this way, an @code{UNLOOP} has to be performed
 2432: before the @code{EXIT}:
 2433: 
 2434: @c !! real examples
 2435: @example
 2436: : ...
 2437:  ... u+do
 2438:    ... if
 2439:      ... unloop exit
 2440:    endif
 2441:    ...
 2442:  loop
 2443:  ... ;
 2444: @end example
 2445: 
 2446: @code{LEAVE} leaves the innermost counted loop right away:
 2447: 
 2448: @example
 2449: : ...
 2450:  ... u+do
 2451:    ... if
 2452:      ... leave
 2453:    endif
 2454:    ...
 2455:  loop
 2456:  ... ;
 2457: @end example
 2458: 
 2459: @c !! example
 2460: 
 2461: Reference: @ref{Calls and returns}, @ref{Counted Loops}.
 2462: 
 2463: 
 2464: @node Return Stack Tutorial, Memory Tutorial, Leaving definitions or loops Tutorial, Tutorial
 2465: @section Return Stack
 2466: @cindex return stack tutorial
 2467: 
 2468: In addition to the data stack Forth also has a second stack, the return
 2469: stack; most Forth systems store the return addresses of procedure calls
 2470: there (thus its name).  Programmers can also use this stack:
 2471: 
 2472: @example
 2473: : foo ( n1 n2 -- )
 2474:  .s
 2475:  >r .s
 2476:  r@@ .
 2477:  >r .s
 2478:  r@@ .
 2479:  r> .
 2480:  r@@ .
 2481:  r> . ;
 2482: 1 2 foo
 2483: @end example
 2484: 
 2485: @code{>r} takes an element from the data stack and pushes it onto the
 2486: return stack; conversely, @code{r>} moves an elementm from the return to
 2487: the data stack; @code{r@@} pushes a copy of the top of the return stack
 2488: on the return stack.
 2489: 
 2490: Forth programmers usually use the return stack for storing data
 2491: temporarily, if using the data stack alone would be too complex, and
 2492: factoring and locals are not an option:
 2493: 
 2494: @example
 2495: : 2swap ( x1 x2 x3 x4 -- x3 x4 x1 x2 )
 2496:  rot >r rot r> ;
 2497: @end example
 2498: 
 2499: The return address of the definition and the loop control parameters of
 2500: counted loops usually reside on the return stack, so you have to take
 2501: all items, that you have pushed on the return stack in a colon
 2502: definition or counted loop, from the return stack before the definition
 2503: or loop ends.  You cannot access items that you pushed on the return
 2504: stack outside some definition or loop within the definition of loop.
 2505: 
 2506: If you miscount the return stack items, this usually ends in a crash:
 2507: 
 2508: @example
 2509: : crash ( n -- )
 2510:   >r ;
 2511: 5 crash
 2512: @end example
 2513: 
 2514: You cannot mix using locals and using the return stack (according to the
 2515: standard; Gforth has no problem).  However, they solve the same
 2516: problems, so this shouldn't be an issue.
 2517: 
 2518: @assignment
 2519: Can you rewrite any of the definitions you wrote until now in a better
 2520: way using the return stack?
 2521: @endassignment
 2522: 
 2523: Reference: @ref{Return stack}.
 2524: 
 2525: 
 2526: @node Memory Tutorial, Characters and Strings Tutorial, Return Stack Tutorial, Tutorial
 2527: @section Memory
 2528: @cindex memory access/allocation tutorial
 2529: 
 2530: You can create a global variable @code{v} with
 2531: 
 2532: @example
 2533: variable v ( -- addr )
 2534: @end example
 2535: 
 2536: @code{v} pushes the address of a cell in memory on the stack.  This cell
 2537: was reserved by @code{variable}.  You can use @code{!} (store) to store
 2538: values into this cell and @code{@@} (fetch) to load the value from the
 2539: stack into memory:
 2540: 
 2541: @example
 2542: v .
 2543: 5 v ! .s
 2544: v @@ .
 2545: @end example
 2546: 
 2547: You can see a raw dump of memory with @code{dump}:
 2548: 
 2549: @example
 2550: v 1 cells .s dump
 2551: @end example
 2552: 
 2553: @code{Cells ( n1 -- n2 )} gives you the number of bytes (or, more
 2554: generally, address units (aus)) that @code{n1 cells} occupy.  You can
 2555: also reserve more memory:
 2556: 
 2557: @example
 2558: create v2 20 cells allot
 2559: v2 20 cells dump
 2560: @end example
 2561: 
 2562: creates a word @code{v2} and reserves 20 uninitialized cells; the
 2563: address pushed by @code{v2} points to the start of these 20 cells.  You
 2564: can use address arithmetic to access these cells:
 2565: 
 2566: @example
 2567: 3 v2 5 cells + !
 2568: v2 20 cells dump
 2569: @end example
 2570: 
 2571: You can reserve and initialize memory with @code{,}:
 2572: 
 2573: @example
 2574: create v3
 2575:   5 , 4 , 3 , 2 , 1 ,
 2576: v3 @@ .
 2577: v3 cell+ @@ .
 2578: v3 2 cells + @@ .
 2579: v3 5 cells dump
 2580: @end example
 2581: 
 2582: @assignment
 2583: Write a definition @code{vsum ( addr u -- n )} that computes the sum of
 2584: @code{u} cells, with the first of these cells at @code{addr}, the next
 2585: one at @code{addr cell+} etc.
 2586: @endassignment
 2587: 
 2588: You can also reserve memory without creating a new word:
 2589: 
 2590: @example
 2591: here 10 cells allot .
 2592: here .
 2593: @end example
 2594: 
 2595: @code{Here} pushes the start address of the memory area.  You should
 2596: store it somewhere, or you will have a hard time finding the memory area
 2597: again.
 2598: 
 2599: @code{Allot} manages dictionary memory.  The dictionary memory contains
 2600: the system's data structures for words etc. on Gforth and most other
 2601: Forth systems.  It is managed like a stack: You can free the memory that
 2602: you have just @code{allot}ed with
 2603: 
 2604: @example
 2605: -10 cells allot
 2606: here .
 2607: @end example
 2608: 
 2609: Note that you cannot do this if you have created a new word in the
 2610: meantime (because then your @code{allot}ed memory is no longer on the
 2611: top of the dictionary ``stack'').
 2612: 
 2613: Alternatively, you can use @code{allocate} and @code{free} which allow
 2614: freeing memory in any order:
 2615: 
 2616: @example
 2617: 10 cells allocate throw .s
 2618: 20 cells allocate throw .s
 2619: swap
 2620: free throw
 2621: free throw
 2622: @end example
 2623: 
 2624: The @code{throw}s deal with errors (e.g., out of memory).
 2625: 
 2626: And there is also a
 2627: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
 2628: garbage collector}, which eliminates the need to @code{free} memory
 2629: explicitly.
 2630: 
 2631: Reference: @ref{Memory}.
 2632: 
 2633: 
 2634: @node Characters and Strings Tutorial, Alignment Tutorial, Memory Tutorial, Tutorial
 2635: @section Characters and Strings
 2636: @cindex strings tutorial
 2637: @cindex characters tutorial
 2638: 
 2639: On the stack characters take up a cell, like numbers.  In memory they
 2640: have their own size (one 8-bit byte on most systems), and therefore
 2641: require their own words for memory access:
 2642: 
 2643: @example
 2644: create v4 
 2645:   104 c, 97 c, 108 c, 108 c, 111 c,
 2646: v4 4 chars + c@@ .
 2647: v4 5 chars dump
 2648: @end example
 2649: 
 2650: The preferred representation of strings on the stack is @code{addr
 2651: u-count}, where @code{addr} is the address of the first character and
 2652: @code{u-count} is the number of characters in the string.
 2653: 
 2654: @example
 2655: v4 5 type
 2656: @end example
 2657: 
 2658: You get a string constant with
 2659: 
 2660: @example
 2661: s" hello, world" .s
 2662: type
 2663: @end example
 2664: 
 2665: Make sure you have a space between @code{s"} and the string; @code{s"}
 2666: is a normal Forth word and must be delimited with white space (try what
 2667: happens when you remove the space).
 2668: 
 2669: However, this interpretive use of @code{s"} is quite restricted: the
 2670: string exists only until the next call of @code{s"} (some Forth systems
 2671: keep more than one of these strings, but usually they still have a
 2672: limited lifetime).
 2673: 
 2674: @example
 2675: s" hello," s" world" .s
 2676: type
 2677: type
 2678: @end example
 2679: 
 2680: You can also use @code{s"} in a definition, and the resulting
 2681: strings then live forever (well, for as long as the definition):
 2682: 
 2683: @example
 2684: : foo s" hello," s" world" ;
 2685: foo .s
 2686: type
 2687: type
 2688: @end example
 2689: 
 2690: @assignment
 2691: @code{Emit ( c -- )} types @code{c} as character (not a number).
 2692: Implement @code{type ( addr u -- )}.
 2693: @endassignment
 2694: 
 2695: Reference: @ref{Memory Blocks}.
 2696: 
 2697: 
 2698: @node Alignment Tutorial, Files Tutorial, Characters and Strings Tutorial, Tutorial
 2699: @section Alignment
 2700: @cindex alignment tutorial
 2701: @cindex memory alignment tutorial
 2702: 
 2703: On many processors cells have to be aligned in memory, if you want to
 2704: access them with @code{@@} and @code{!} (and even if the processor does
 2705: not require alignment, access to aligned cells is faster).
 2706: 
 2707: @code{Create} aligns @code{here} (i.e., the place where the next
 2708: allocation will occur, and that the @code{create}d word points to).
 2709: Likewise, the memory produced by @code{allocate} starts at an aligned
 2710: address.  Adding a number of @code{cells} to an aligned address produces
 2711: another aligned address.
 2712: 
 2713: However, address arithmetic involving @code{char+} and @code{chars} can
 2714: create an address that is not cell-aligned.  @code{Aligned ( addr --
 2715: a-addr )} produces the next aligned address:
 2716: 
 2717: @example
 2718: v3 char+ aligned .s @@ .
 2719: v3 char+ .s @@ .
 2720: @end example
 2721: 
 2722: Similarly, @code{align} advances @code{here} to the next aligned
 2723: address:
 2724: 
 2725: @example
 2726: create v5 97 c,
 2727: here .
 2728: align here .
 2729: 1000 ,
 2730: @end example
 2731: 
 2732: Note that you should use aligned addresses even if your processor does
 2733: not require them, if you want your program to be portable.
 2734: 
 2735: Reference: @ref{Address arithmetic}.
 2736: 
 2737: 
 2738: @node Files Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Alignment Tutorial, Tutorial
 2739: @section Files
 2740: @cindex files tutorial
 2741: 
 2742: This section gives a short introduction into how to use files inside
 2743: Forth. It's broken up into five easy steps:
 2744: 
 2745: @enumerate 1
 2746: @item Opened an ASCII text file for input
 2747: @item Opened a file for output
 2748: @item Read input file until string matched (or some other condition matched)
 2749: @item Wrote some lines from input ( modified or not) to output
 2750: @item Closed the files.
 2751: @end enumerate
 2752: 
 2753: @subsection Open file for input
 2754: 
 2755: @example
 2756: s" foo.in"  r/o open-file throw Value fd-in
 2757: @end example
 2758: 
 2759: @subsection Create file for output
 2760: 
 2761: @example
 2762: s" foo.out" w/o create-file throw Value fd-out
 2763: @end example
 2764: 
 2765: The available file modes are r/o for read-only access, r/w for
 2766: read-write access, and w/o for write-only access. You could open both
 2767: files with r/w, too, if you like. All file words return error codes; for
 2768: most applications, it's best to pass there error codes with @code{throw}
 2769: to the outer error handler.
 2770: 
 2771: If you want words for opening and assigning, define them as follows:
 2772: 
 2773: @example
 2774: 0 Value fd-in
 2775: 0 Value fd-out
 2776: : open-input ( addr u -- )  r/o open-file throw to fd-in ;
 2777: : open-output ( addr u -- )  w/o create-file throw to fd-out ;
 2778: @end example
 2779: 
 2780: Usage example:
 2781: 
 2782: @example
 2783: s" foo.in" open-input
 2784: s" foo.out" open-output
 2785: @end example
 2786: 
 2787: @subsection Scan file for a particular line
 2788: 
 2789: @example
 2790: 256 Constant max-line
 2791: Create line-buffer  max-line 2 + allot
 2792: 
 2793: : scan-file ( addr u -- )
 2794:   begin
 2795:       line-buffer max-line fd-in read-line throw
 2796:   while
 2797:          >r 2dup line-buffer r> compare 0=
 2798:      until
 2799:   else
 2800:      drop
 2801:   then
 2802:   2drop ;
 2803: @end example
 2804: 
 2805: @code{read-line ( addr u1 fd -- u2 flag ior )} reads up to u1 bytes into
 2806: the buffer at addr, and returns the number of bytes read, a flag that's
 2807: true when the end of file is reached, and an error code.
 2808: 
 2809: @code{compare ( addr1 u1 addr2 u2 -- n )} compares two strings and
 2810: returns zero if both strings are equal. It returns a positive number if
 2811: the first string is lexically greater, a negative if the second string
 2812: is lexically greater.
 2813: 
 2814: We haven't seen this loop here; it has two exits. Since the @code{while}
 2815: exits with the number of bytes read on the stack, we have to clean up
 2816: that separately; that's after the @code{else}.
 2817: 
 2818: Usage example:
 2819: 
 2820: @example
 2821: s" The text I search is here" scan-file
 2822: @end example
 2823: 
 2824: @subsection Copy input to output
 2825: 
 2826: @example
 2827: : copy-file ( -- )
 2828:   begin
 2829:       line-buffer max-line fd-in read-line throw
 2830:   while
 2831:       line-buffer swap fd-out write-file throw
 2832:   repeat ;
 2833: @end example
 2834: 
 2835: @subsection Close files
 2836: 
 2837: @example
 2838: fd-in close-file throw
 2839: fd-out close-file throw
 2840: @end example
 2841: 
 2842: Likewise, you can put that into definitions, too:
 2843: 
 2844: @example
 2845: : close-input ( -- )  fd-in close-file throw ;
 2846: : close-output ( -- )  fd-out close-file throw ;
 2847: @end example
 2848: 
 2849: @assignment
 2850: How could you modify @code{copy-file} so that it copies until a second line is
 2851: matched? Can you write a program that extracts a section of a text file,
 2852: given the line that starts and the line that terminates that section?
 2853: @endassignment
 2854: 
 2855: @node Interpretation and Compilation Semantics and Immediacy Tutorial, Execution Tokens Tutorial, Files Tutorial, Tutorial
 2856: @section Interpretation and Compilation Semantics and Immediacy
 2857: @cindex semantics tutorial
 2858: @cindex interpretation semantics tutorial
 2859: @cindex compilation semantics tutorial
 2860: @cindex immediate, tutorial
 2861: 
 2862: When a word is compiled, it behaves differently from being interpreted.
 2863: E.g., consider @code{+}:
 2864: 
 2865: @example
 2866: 1 2 + .
 2867: : foo + ;
 2868: @end example
 2869: 
 2870: These two behaviours are known as compilation and interpretation
 2871: semantics.  For normal words (e.g., @code{+}), the compilation semantics
 2872: is to append the interpretation semantics to the currently defined word
 2873: (@code{foo} in the example above).  I.e., when @code{foo} is executed
 2874: later, the interpretation semantics of @code{+} (i.e., adding two
 2875: numbers) will be performed.
 2876: 
 2877: However, there are words with non-default compilation semantics, e.g.,
 2878: the control-flow words like @code{if}.  You can use @code{immediate} to
 2879: change the compilation semantics of the last defined word to be equal to
 2880: the interpretation semantics:
 2881: 
 2882: @example
 2883: : [FOO] ( -- )
 2884:  5 . ; immediate
 2885: 
 2886: [FOO]
 2887: : bar ( -- )
 2888:   [FOO] ;
 2889: bar
 2890: see bar
 2891: @end example
 2892: 
 2893: Two conventions to mark words with non-default compilation semnatics are
 2894: names with brackets (more frequently used) and to write them all in
 2895: upper case (less frequently used).
 2896: 
 2897: In Gforth (and many other systems) you can also remove the
 2898: interpretation semantics with @code{compile-only} (the compilation
 2899: semantics is derived from the original interpretation semantics):
 2900: 
 2901: @example
 2902: : flip ( -- )
 2903:  6 . ; compile-only \ but not immediate
 2904: flip
 2905: 
 2906: : flop ( -- )
 2907:  flip ;
 2908: flop
 2909: @end example
 2910: 
 2911: In this example the interpretation semantics of @code{flop} is equal to
 2912: the original interpretation semantics of @code{flip}.
 2913: 
 2914: The text interpreter has two states: in interpret state, it performs the
 2915: interpretation semantics of words it encounters; in compile state, it
 2916: performs the compilation semantics of these words.
 2917: 
 2918: Among other things, @code{:} switches into compile state, and @code{;}
 2919: switches back to interpret state.  They contain the factors @code{]}
 2920: (switch to compile state) and @code{[} (switch to interpret state), that
 2921: do nothing but switch the state.
 2922: 
 2923: @example
 2924: : xxx ( -- )
 2925:   [ 5 . ]
 2926: ;
 2927: 
 2928: xxx
 2929: see xxx
 2930: @end example
 2931: 
 2932: These brackets are also the source of the naming convention mentioned
 2933: above.
 2934: 
 2935: Reference: @ref{Interpretation and Compilation Semantics}.
 2936: 
 2937: 
 2938: @node Execution Tokens Tutorial, Exceptions Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Tutorial
 2939: @section Execution Tokens
 2940: @cindex execution tokens tutorial
 2941: @cindex XT tutorial
 2942: 
 2943: @code{' word} gives you the execution token (XT) of a word.  The XT is a
 2944: cell representing the interpretation semantics of a word.  You can
 2945: execute this semantics with @code{execute}:
 2946: 
 2947: @example
 2948: ' + .s
 2949: 1 2 rot execute .
 2950: @end example
 2951: 
 2952: The XT is similar to a function pointer in C.  However, parameter
 2953: passing through the stack makes it a little more flexible:
 2954: 
 2955: @example
 2956: : map-array ( ... addr u xt -- ... )
 2957: \ executes xt ( ... x -- ... ) for every element of the array starting
 2958: \ at addr and containing u elements
 2959:   @{ xt @}
 2960:   cells over + swap ?do
 2961:     i @@ xt execute
 2962:   1 cells +loop ;
 2963: 
 2964: create a 3 , 4 , 2 , -1 , 4 ,
 2965: a 5 ' . map-array .s
 2966: 0 a 5 ' + map-array .
 2967: s" max-n" environment? drop .s
 2968: a 5 ' min map-array .
 2969: @end example
 2970: 
 2971: You can use map-array with the XTs of words that consume one element
 2972: more than they produce.  In theory you can also use it with other XTs,
 2973: but the stack effect then depends on the size of the array, which is
 2974: hard to understand.
 2975: 
 2976: Since XTs are cell-sized, you can store them in memory and manipulate
 2977: them on the stack like other cells.  You can also compile the XT into a
 2978: word with @code{compile,}:
 2979: 
 2980: @example
 2981: : foo1 ( n1 n2 -- n )
 2982:    [ ' + compile, ] ;
 2983: see foo
 2984: @end example
 2985: 
 2986: This is non-standard, because @code{compile,} has no compilation
 2987: semantics in the standard, but it works in good Forth systems.  For the
 2988: broken ones, use
 2989: 
 2990: @example
 2991: : [compile,] compile, ; immediate
 2992: 
 2993: : foo1 ( n1 n2 -- n )
 2994:    [ ' + ] [compile,] ;
 2995: see foo
 2996: @end example
 2997: 
 2998: @code{'} is a word with default compilation semantics; it parses the
 2999: next word when its interpretation semantics are executed, not during
 3000: compilation:
 3001: 
 3002: @example
 3003: : foo ( -- xt )
 3004:   ' ;
 3005: see foo
 3006: : bar ( ... "word" -- ... )
 3007:   ' execute ;
 3008: see bar
 3009: 1 2 bar + .
 3010: @end example
 3011: 
 3012: You often want to parse a word during compilation and compile its XT so
 3013: it will be pushed on the stack at run-time.  @code{[']} does this:
 3014: 
 3015: @example
 3016: : xt-+ ( -- xt )
 3017:   ['] + ;
 3018: see xt-+
 3019: 1 2 xt-+ execute .
 3020: @end example
 3021: 
 3022: Many programmers tend to see @code{'} and the word it parses as one
 3023: unit, and expect it to behave like @code{[']} when compiled, and are
 3024: confused by the actual behaviour.  If you are, just remember that the
 3025: Forth system just takes @code{'} as one unit and has no idea that it is
 3026: a parsing word (attempts to convenience programmers in this issue have
 3027: usually resulted in even worse pitfalls, see
 3028: @uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,
 3029: @code{State}-smartness---Why it is evil and How to Exorcise it}).
 3030: 
 3031: Note that the state of the interpreter does not come into play when
 3032: creating and executing XTs.  I.e., even when you execute @code{'} in
 3033: compile state, it still gives you the interpretation semantics.  And
 3034: whatever that state is, @code{execute} performs the semantics
 3035: represented by the XT (i.e., for XTs produced with @code{'} the
 3036: interpretation semantics).
 3037: 
 3038: Reference: @ref{Tokens for Words}.
 3039: 
 3040: 
 3041: @node Exceptions Tutorial, Defining Words Tutorial, Execution Tokens Tutorial, Tutorial
 3042: @section Exceptions
 3043: @cindex exceptions tutorial
 3044: 
 3045: @code{throw ( n -- )} causes an exception unless n is zero.
 3046: 
 3047: @example
 3048: 100 throw .s
 3049: 0 throw .s
 3050: @end example
 3051: 
 3052: @code{catch ( ... xt -- ... n )} behaves similar to @code{execute}, but
 3053: it catches exceptions and pushes the number of the exception on the
 3054: stack (or 0, if the xt executed without exception).  If there was an
 3055: exception, the stacks have the same depth as when entering @code{catch}:
 3056: 
 3057: @example
 3058: .s
 3059: 3 0 ' / catch .s
 3060: 3 2 ' / catch .s
 3061: @end example
 3062: 
 3063: @assignment
 3064: Try the same with @code{execute} instead of @code{catch}.
 3065: @endassignment
 3066: 
 3067: @code{Throw} always jumps to the dynamically next enclosing
 3068: @code{catch}, even if it has to leave several call levels to achieve
 3069: this:
 3070: 
 3071: @example
 3072: : foo 100 throw ;
 3073: : foo1 foo ." after foo" ;
 3074: : bar ['] foo1 catch ;
 3075: bar .
 3076: @end example
 3077: 
 3078: It is often important to restore a value upon leaving a definition, even
 3079: if the definition is left through an exception.  You can ensure this
 3080: like this:
 3081: 
 3082: @example
 3083: : ...
 3084:    save-x
 3085:    ['] word-changing-x catch ( ... n )
 3086:    restore-x
 3087:    ( ... n ) throw ;
 3088: @end example
 3089: 
 3090: Gforth provides an alternative syntax in addition to @code{catch}:
 3091: @code{try ... recover ... endtry}.  If the code between @code{try} and
 3092: @code{recover} has an exception, the stack depths are restored, the
 3093: exception number is pushed on the stack, and the code between
 3094: @code{recover} and @code{endtry} is performed.  E.g., the definition for
 3095: @code{catch} is
 3096: 
 3097: @example
 3098: : catch ( x1 .. xn xt -- y1 .. ym 0 / z1 .. zn error ) \ exception
 3099:   try
 3100:     execute 0
 3101:   recover
 3102:     nip
 3103:   endtry ;
 3104: @end example
 3105: 
 3106: The equivalent to the restoration code above is
 3107: 
 3108: @example
 3109: : ...
 3110:   save-x
 3111:   try
 3112:     word-changing-x
 3113:   end-try
 3114:   restore-x
 3115:   throw ;
 3116: @end example
 3117: 
 3118: As you can see, the @code{recover} part is optional.
 3119: 
 3120: Reference: @ref{Exception Handling}.
 3121: 
 3122: 
 3123: @node Defining Words Tutorial, Arrays and Records Tutorial, Exceptions Tutorial, Tutorial
 3124: @section Defining Words
 3125: @cindex defining words tutorial
 3126: @cindex does> tutorial
 3127: @cindex create...does> tutorial
 3128: 
 3129: @c before semantics?
 3130: 
 3131: @code{:}, @code{create}, and @code{variable} are definition words: They
 3132: define other words.  @code{Constant} is another definition word:
 3133: 
 3134: @example
 3135: 5 constant foo
 3136: foo .
 3137: @end example
 3138: 
 3139: You can also use the prefixes @code{2} (double-cell) and @code{f}
 3140: (floating point) with @code{variable} and @code{constant}.
 3141: 
 3142: You can also define your own defining words.  E.g.:
 3143: 
 3144: @example
 3145: : variable ( "name" -- )
 3146:   create 0 , ;
 3147: @end example
 3148: 
 3149: You can also define defining words that create words that do something
 3150: other than just producing their address:
 3151: 
 3152: @example
 3153: : constant ( n "name" -- )
 3154:   create ,
 3155: does> ( -- n )
 3156:   ( addr ) @@ ;
 3157: 
 3158: 5 constant foo
 3159: foo .
 3160: @end example
 3161: 
 3162: The definition of @code{constant} above ends at the @code{does>}; i.e.,
 3163: @code{does>} replaces @code{;}, but it also does something else: It
 3164: changes the last defined word such that it pushes the address of the
 3165: body of the word and then performs the code after the @code{does>}
 3166: whenever it is called.
 3167: 
 3168: In the example above, @code{constant} uses @code{,} to store 5 into the
 3169: body of @code{foo}.  When @code{foo} executes, it pushes the address of
 3170: the body onto the stack, then (in the code after the @code{does>})
 3171: fetches the 5 from there.
 3172: 
 3173: The stack comment near the @code{does>} reflects the stack effect of the
 3174: defined word, not the stack effect of the code after the @code{does>}
 3175: (the difference is that the code expects the address of the body that
 3176: the stack comment does not show).
 3177: 
 3178: You can use these definition words to do factoring in cases that involve
 3179: (other) definition words.  E.g., a field offset is always added to an
 3180: address.  Instead of defining
 3181: 
 3182: @example
 3183: 2 cells constant offset-field1
 3184: @end example
 3185: 
 3186: and using this like
 3187: 
 3188: @example
 3189: ( addr ) offset-field1 +
 3190: @end example
 3191: 
 3192: you can define a definition word
 3193: 
 3194: @example
 3195: : simple-field ( n "name" -- )
 3196:   create ,
 3197: does> ( n1 -- n1+n )
 3198:   ( addr ) @@ + ;
 3199: @end example
 3200: 
 3201: Definition and use of field offsets now look like this:
 3202: 
 3203: @example
 3204: 2 cells simple-field field1
 3205: create mystruct 4 cells allot
 3206: mystruct .s field1 .s drop
 3207: @end example
 3208: 
 3209: If you want to do something with the word without performing the code
 3210: after the @code{does>}, you can access the body of a @code{create}d word
 3211: with @code{>body ( xt -- addr )}:
 3212: 
 3213: @example
 3214: : value ( n "name" -- )
 3215:   create ,
 3216: does> ( -- n1 )
 3217:   @@ ;
 3218: : to ( n "name" -- )
 3219:   ' >body ! ;
 3220: 
 3221: 5 value foo
 3222: foo .
 3223: 7 to foo
 3224: foo .
 3225: @end example
 3226: 
 3227: @assignment
 3228: Define @code{defer ( "name" -- )}, which creates a word that stores an
 3229: XT (at the start the XT of @code{abort}), and upon execution
 3230: @code{execute}s the XT.  Define @code{is ( xt "name" -- )} that stores
 3231: @code{xt} into @code{name}, a word defined with @code{defer}.  Indirect
 3232: recursion is one application of @code{defer}.
 3233: @endassignment
 3234: 
 3235: Reference: @ref{User-defined Defining Words}.
 3236: 
 3237: 
 3238: @node Arrays and Records Tutorial, POSTPONE Tutorial, Defining Words Tutorial, Tutorial
 3239: @section Arrays and Records
 3240: @cindex arrays tutorial
 3241: @cindex records tutorial
 3242: @cindex structs tutorial
 3243: 
 3244: Forth has no standard words for defining data structures such as arrays
 3245: and records (structs in C terminology), but you can build them yourself
 3246: based on address arithmetic.  You can also define words for defining
 3247: arrays and records (@pxref{Defining Words Tutorial,, Defining Words}).
 3248: 
 3249: One of the first projects a Forth newcomer sets out upon when learning
 3250: about defining words is an array defining word (possibly for
 3251: n-dimensional arrays).  Go ahead and do it, I did it, too; you will
 3252: learn something from it.  However, don't be disappointed when you later
 3253: learn that you have little use for these words (inappropriate use would
 3254: be even worse).  I have not yet found a set of useful array words yet;
 3255: the needs are just too diverse, and named, global arrays (the result of
 3256: naive use of defining words) are often not flexible enough (e.g.,
 3257: consider how to pass them as parameters).  Another such project is a set
 3258: of words to help dealing with strings.
 3259: 
 3260: On the other hand, there is a useful set of record words, and it has
 3261: been defined in @file{compat/struct.fs}; these words are predefined in
 3262: Gforth.  They are explained in depth elsewhere in this manual (see
 3263: @pxref{Structures}).  The @code{simple-field} example above is
 3264: simplified variant of fields in this package.
 3265: 
 3266: 
 3267: @node POSTPONE Tutorial, Literal Tutorial, Arrays and Records Tutorial, Tutorial
 3268: @section @code{POSTPONE}
 3269: @cindex postpone tutorial
 3270: 
 3271: You can compile the compilation semantics (instead of compiling the
 3272: interpretation semantics) of a word with @code{POSTPONE}:
 3273: 
 3274: @example
 3275: : MY-+ ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
 3276:  POSTPONE + ; immediate
 3277: : foo ( n1 n2 -- n )
 3278:  MY-+ ;
 3279: 1 2 foo .
 3280: see foo
 3281: @end example
 3282: 
 3283: During the definition of @code{foo} the text interpreter performs the
 3284: compilation semantics of @code{MY-+}, which performs the compilation
 3285: semantics of @code{+}, i.e., it compiles @code{+} into @code{foo}.
 3286: 
 3287: This example also displays separate stack comments for the compilation
 3288: semantics and for the stack effect of the compiled code.  For words with
 3289: default compilation semantics these stack effects are usually not
 3290: displayed; the stack effect of the compilation semantics is always
 3291: @code{( -- )} for these words, the stack effect for the compiled code is
 3292: the stack effect of the interpretation semantics.
 3293: 
 3294: Note that the state of the interpreter does not come into play when
 3295: performing the compilation semantics in this way.  You can also perform
 3296: it interpretively, e.g.:
 3297: 
 3298: @example
 3299: : foo2 ( n1 n2 -- n )
 3300:  [ MY-+ ] ;
 3301: 1 2 foo .
 3302: see foo
 3303: @end example
 3304: 
 3305: However, there are some broken Forth systems where this does not always
 3306: work, and therefore this practice was been declared non-standard in
 3307: 1999.
 3308: @c !! repair.fs
 3309: 
 3310: Here is another example for using @code{POSTPONE}:
 3311: 
 3312: @example
 3313: : MY-- ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
 3314:  POSTPONE negate POSTPONE + ; immediate compile-only
 3315: : bar ( n1 n2 -- n )
 3316:   MY-- ;
 3317: 2 1 bar .
 3318: see bar
 3319: @end example
 3320: 
 3321: You can define @code{ENDIF} in this way:
 3322: 
 3323: @example
 3324: : ENDIF ( Compilation: orig -- )
 3325:   POSTPONE then ; immediate
 3326: @end example
 3327: 
 3328: @assignment
 3329: Write @code{MY-2DUP} that has compilation semantics equivalent to
 3330: @code{2dup}, but compiles @code{over over}.
 3331: @endassignment
 3332: 
 3333: @c !! @xref{Macros} for reference
 3334: 
 3335: 
 3336: @node Literal Tutorial, Advanced macros Tutorial, POSTPONE Tutorial, Tutorial
 3337: @section @code{Literal}
 3338: @cindex literal tutorial
 3339: 
 3340: You cannot @code{POSTPONE} numbers:
 3341: 
 3342: @example
 3343: : [FOO] POSTPONE 500 ; immediate
 3344: @end example
 3345: 
 3346: Instead, you can use @code{LITERAL (compilation: n --; run-time: -- n )}:
 3347: 
 3348: @example
 3349: : [FOO] ( compilation: --; run-time: -- n )
 3350:   500 POSTPONE literal ; immediate
 3351: 
 3352: : flip [FOO] ;
 3353: flip .
 3354: see flip
 3355: @end example
 3356: 
 3357: @code{LITERAL} consumes a number at compile-time (when it's compilation
 3358: semantics are executed) and pushes it at run-time (when the code it
 3359: compiled is executed).  A frequent use of @code{LITERAL} is to compile a
 3360: number computed at compile time into the current word:
 3361: 
 3362: @example
 3363: : bar ( -- n )
 3364:   [ 2 2 + ] literal ;
 3365: see bar
 3366: @end example
 3367: 
 3368: @assignment
 3369: Write @code{]L} which allows writing the example above as @code{: bar (
 3370: -- n ) [ 2 2 + ]L ;}
 3371: @endassignment
 3372: 
 3373: @c !! @xref{Macros} for reference
 3374: 
 3375: 
 3376: @node Advanced macros Tutorial, Compilation Tokens Tutorial, Literal Tutorial, Tutorial
 3377: @section Advanced macros
 3378: @cindex macros, advanced tutorial
 3379: @cindex run-time code generation, tutorial
 3380: 
 3381: Reconsider @code{map-array} from @ref{Execution Tokens Tutorial,,
 3382: Execution Tokens}.  It frequently performs @code{execute}, a relatively
 3383: expensive operation in some Forth implementations.  You can use
 3384: @code{compile,} and @code{POSTPONE} to eliminate these @code{execute}s
 3385: and produce a word that contains the word to be performed directly:
 3386: 
 3387: @c use ]] ... [[
 3388: @example
 3389: : compile-map-array ( compilation: xt -- ; run-time: ... addr u -- ... )
 3390: \ at run-time, execute xt ( ... x -- ... ) for each element of the
 3391: \ array beginning at addr and containing u elements
 3392:   @{ xt @}
 3393:   POSTPONE cells POSTPONE over POSTPONE + POSTPONE swap POSTPONE ?do
 3394:     POSTPONE i POSTPONE @@ xt compile,
 3395:   1 cells POSTPONE literal POSTPONE +loop ;
 3396: 
 3397: : sum-array ( addr u -- n )
 3398:  0 rot rot [ ' + compile-map-array ] ;
 3399: see sum-array
 3400: a 5 sum-array .
 3401: @end example
 3402: 
 3403: You can use the full power of Forth for generating the code; here's an
 3404: example where the code is generated in a loop:
 3405: 
 3406: @example
 3407: : compile-vmul-step ( compilation: n --; run-time: n1 addr1 -- n2 addr2 )
 3408: \ n2=n1+(addr1)*n, addr2=addr1+cell
 3409:   POSTPONE tuck POSTPONE @@
 3410:   POSTPONE literal POSTPONE * POSTPONE +
 3411:   POSTPONE swap POSTPONE cell+ ;
 3412: 
 3413: : compile-vmul ( compilation: addr1 u -- ; run-time: addr2 -- n )
 3414: \ n=v1*v2 (inner product), where the v_i are represented as addr_i u
 3415:   0 postpone literal postpone swap
 3416:   [ ' compile-vmul-step compile-map-array ]
 3417:   postpone drop ;
 3418: see compile-vmul
 3419: 
 3420: : a-vmul ( addr -- n )
 3421: \ n=a*v, where v is a vector that's as long as a and starts at addr
 3422:  [ a 5 compile-vmul ] ;
 3423: see a-vmul
 3424: a a-vmul .
 3425: @end example
 3426: 
 3427: This example uses @code{compile-map-array} to show off, but you could
 3428: also use @code{map-array} instead (try it now!).
 3429: 
 3430: You can use this technique for efficient multiplication of large
 3431: matrices.  In matrix multiplication, you multiply every line of one
 3432: matrix with every column of the other matrix.  You can generate the code
 3433: for one line once, and use it for every column.  The only downside of
 3434: this technique is that it is cumbersome to recover the memory consumed
 3435: by the generated code when you are done (and in more complicated cases
 3436: it is not possible portably).
 3437: 
 3438: @c !! @xref{Macros} for reference
 3439: 
 3440: 
 3441: @node Compilation Tokens Tutorial, Wordlists and Search Order Tutorial, Advanced macros Tutorial, Tutorial
 3442: @section Compilation Tokens
 3443: @cindex compilation tokens, tutorial
 3444: @cindex CT, tutorial
 3445: 
 3446: This section is Gforth-specific.  You can skip it.
 3447: 
 3448: @code{' word compile,} compiles the interpretation semantics.  For words
 3449: with default compilation semantics this is the same as performing the
 3450: compilation semantics.  To represent the compilation semantics of other
 3451: words (e.g., words like @code{if} that have no interpretation
 3452: semantics), Gforth has the concept of a compilation token (CT,
 3453: consisting of two cells), and words @code{comp'} and @code{[comp']}.
 3454: You can perform the compilation semantics represented by a CT with
 3455: @code{execute}:
 3456: 
 3457: @example
 3458: : foo2 ( n1 n2 -- n )
 3459:    [ comp' + execute ] ;
 3460: see foo
 3461: @end example
 3462: 
 3463: You can compile the compilation semantics represented by a CT with
 3464: @code{postpone,}:
 3465: 
 3466: @example
 3467: : foo3 ( -- )
 3468:   [ comp' + postpone, ] ;
 3469: see foo3
 3470: @end example
 3471: 
 3472: @code{[ comp' word postpone, ]} is equivalent to @code{POSTPONE word}.
 3473: @code{comp'} is particularly useful for words that have no
 3474: interpretation semantics:
 3475: 
 3476: @example
 3477: ' if
 3478: comp' if .s 2drop
 3479: @end example
 3480: 
 3481: Reference: @ref{Tokens for Words}.
 3482: 
 3483: 
 3484: @node Wordlists and Search Order Tutorial,  , Compilation Tokens Tutorial, Tutorial
 3485: @section Wordlists and Search Order
 3486: @cindex wordlists tutorial
 3487: @cindex search order, tutorial
 3488: 
 3489: The dictionary is not just a memory area that allows you to allocate
 3490: memory with @code{allot}, it also contains the Forth words, arranged in
 3491: several wordlists.  When searching for a word in a wordlist,
 3492: conceptually you start searching at the youngest and proceed towards
 3493: older words (in reality most systems nowadays use hash-tables); i.e., if
 3494: you define a word with the same name as an older word, the new word
 3495: shadows the older word.
 3496: 
 3497: Which wordlists are searched in which order is determined by the search
 3498: order.  You can display the search order with @code{order}.  It displays
 3499: first the search order, starting with the wordlist searched first, then
 3500: it displays the wordlist that will contain newly defined words.
 3501: 
 3502: You can create a new, empty wordlist with @code{wordlist ( -- wid )}:
 3503: 
 3504: @example
 3505: wordlist constant mywords
 3506: @end example
 3507: 
 3508: @code{Set-current ( wid -- )} sets the wordlist that will contain newly
 3509: defined words (the @emph{current} wordlist):
 3510: 
 3511: @example
 3512: mywords set-current
 3513: order
 3514: @end example
 3515: 
 3516: Gforth does not display a name for the wordlist in @code{mywords}
 3517: because this wordlist was created anonymously with @code{wordlist}.
 3518: 
 3519: You can get the current wordlist with @code{get-current ( -- wid)}.  If
 3520: you want to put something into a specific wordlist without overall
 3521: effect on the current wordlist, this typically looks like this:
 3522: 
 3523: @example
 3524: get-current mywords set-current ( wid )
 3525: create someword
 3526: ( wid ) set-current
 3527: @end example
 3528: 
 3529: You can write the search order with @code{set-order ( wid1 .. widn n --
 3530: )} and read it with @code{get-order ( -- wid1 .. widn n )}.  The first
 3531: searched wordlist is topmost.
 3532: 
 3533: @example
 3534: get-order mywords swap 1+ set-order
 3535: order
 3536: @end example
 3537: 
 3538: Yes, the order of wordlists in the output of @code{order} is reversed
 3539: from stack comments and the output of @code{.s} and thus unintuitive.
 3540: 
 3541: @assignment
 3542: Define @code{>order ( wid -- )} with adds @code{wid} as first searched
 3543: wordlist to the search order.  Define @code{previous ( -- )}, which
 3544: removes the first searched wordlist from the search order.  Experiment
 3545: with boundary conditions (you will see some crashes or situations that
 3546: are hard or impossible to leave).
 3547: @endassignment
 3548: 
 3549: The search order is a powerful foundation for providing features similar
 3550: to Modula-2 modules and C++ namespaces.  However, trying to modularize
 3551: programs in this way has disadvantages for debugging and reuse/factoring
 3552: that overcome the advantages in my experience (I don't do huge projects,
 3553: though).  These disadvantages are not so clear in other
 3554: languages/programming environments, because these languages are not so
 3555: strong in debugging and reuse.
 3556: 
 3557: @c !! example
 3558: 
 3559: Reference: @ref{Word Lists}.
 3560: 
 3561: @c ******************************************************************
 3562: @node Introduction, Words, Tutorial, Top
 3563: @comment node-name,     next,           previous, up
 3564: @chapter An Introduction to ANS Forth
 3565: @cindex Forth - an introduction
 3566: 
 3567: The difference of this chapter from the Tutorial (@pxref{Tutorial}) is
 3568: that it is slower-paced in its examples, but uses them to dive deep into
 3569: explaining Forth internals (not covered by the Tutorial).  Apart from
 3570: that, this chapter covers far less material.  It is suitable for reading
 3571: without using a computer.
 3572: 
 3573: The primary purpose of this manual is to document Gforth. However, since
 3574: Forth is not a widely-known language and there is a lack of up-to-date
 3575: teaching material, it seems worthwhile to provide some introductory
 3576: material.  For other sources of Forth-related
 3577: information, see @ref{Forth-related information}.
 3578: 
 3579: The examples in this section should work on any ANS Forth; the
 3580: output shown was produced using Gforth. Each example attempts to
 3581: reproduce the exact output that Gforth produces. If you try out the
 3582: examples (and you should), what you should type is shown @kbd{like this}
 3583: and Gforth's response is shown @code{like this}. The single exception is
 3584: that, where the example shows @key{RET} it means that you should
 3585: press the ``carriage return'' key. Unfortunately, some output formats for
 3586: this manual cannot show the difference between @kbd{this} and
 3587: @code{this} which will make trying out the examples harder (but not
 3588: impossible).
 3589: 
 3590: Forth is an unusual language. It provides an interactive development
 3591: environment which includes both an interpreter and compiler. Forth
 3592: programming style encourages you to break a problem down into many
 3593: @cindex factoring
 3594: small fragments (@dfn{factoring}), and then to develop and test each
 3595: fragment interactively. Forth advocates assert that breaking the
 3596: edit-compile-test cycle used by conventional programming languages can
 3597: lead to great productivity improvements.
 3598: 
 3599: @menu
 3600: * Introducing the Text Interpreter::  
 3601: * Stacks and Postfix notation::  
 3602: * Your first definition::       
 3603: * How does that work?::         
 3604: * Forth is written in Forth::   
 3605: * Review - elements of a Forth system::  
 3606: * Where to go next::            
 3607: * Exercises::                   
 3608: @end menu
 3609: 
 3610: @comment ----------------------------------------------
 3611: @node Introducing the Text Interpreter, Stacks and Postfix notation, Introduction, Introduction
 3612: @section Introducing the Text Interpreter
 3613: @cindex text interpreter
 3614: @cindex outer interpreter
 3615: 
 3616: @c IMO this is too detailed and the pace is too slow for
 3617: @c an introduction.  If you know German, take a look at
 3618: @c http://www.complang.tuwien.ac.at/anton/lvas/skriptum-stack.html 
 3619: @c to see how I do it - anton 
 3620: 
 3621: @c nac-> Where I have accepted your comments 100% and modified the text
 3622: @c accordingly, I have deleted your comments. Elsewhere I have added a
 3623: @c response like this to attempt to rationalise what I have done. Of
 3624: @c course, this is a very clumsy mechanism for something that would be
 3625: @c done far more efficiently over a beer. Please delete any dialogue
 3626: @c you consider closed.
 3627: 
 3628: When you invoke the Forth image, you will see a startup banner printed
 3629: and nothing else (if you have Gforth installed on your system, try
 3630: invoking it now, by typing @kbd{gforth@key{RET}}). Forth is now running
 3631: its command line interpreter, which is called the @dfn{Text Interpreter}
 3632: (also known as the @dfn{Outer Interpreter}).  (You will learn a lot
 3633: about the text interpreter as you read through this chapter, for more
 3634: detail @pxref{The Text Interpreter}).
 3635: 
 3636: Although it's not obvious, Forth is actually waiting for your
 3637: input. Type a number and press the @key{RET} key:
 3638: 
 3639: @example
 3640: @kbd{45@key{RET}}  ok
 3641: @end example
 3642: 
 3643: Rather than give you a prompt to invite you to input something, the text
 3644: interpreter prints a status message @i{after} it has processed a line
 3645: of input. The status message in this case (``@code{ ok}'' followed by
 3646: carriage-return) indicates that the text interpreter was able to process
 3647: all of your input successfully. Now type something illegal:
 3648: 
 3649: @example
 3650: @kbd{qwer341@key{RET}}
 3651: :1: Undefined word
 3652: qwer341
 3653: ^^^^^^^
 3654: $400D2BA8 Bounce
 3655: $400DBDA8 no.extensions
 3656: @end example
 3657: 
 3658: The exact text, other than the ``Undefined word'' may differ slightly on
 3659: your system, but the effect is the same; when the text interpreter
 3660: detects an error, it discards any remaining text on a line, resets
 3661: certain internal state and prints an error message. For a detailed description of error messages see @ref{Error
 3662: messages}.
 3663: 
 3664: The text interpreter waits for you to press carriage-return, and then
 3665: processes your input line. Starting at the beginning of the line, it
 3666: breaks the line into groups of characters separated by spaces. For each
 3667: group of characters in turn, it makes two attempts to do something:
 3668: 
 3669: @itemize @bullet
 3670: @item
 3671: @cindex name dictionary
 3672: It tries to treat it as a command. It does this by searching a @dfn{name
 3673: dictionary}. If the group of characters matches an entry in the name
 3674: dictionary, the name dictionary provides the text interpreter with
 3675: information that allows the text interpreter perform some actions. In
 3676: Forth jargon, we say that the group
 3677: @cindex word
 3678: @cindex definition
 3679: @cindex execution token
 3680: @cindex xt
 3681: of characters names a @dfn{word}, that the dictionary search returns an
 3682: @dfn{execution token (xt)} corresponding to the @dfn{definition} of the
 3683: word, and that the text interpreter executes the xt. Often, the terms
 3684: @dfn{word} and @dfn{definition} are used interchangeably.
 3685: @item
 3686: If the text interpreter fails to find a match in the name dictionary, it
 3687: tries to treat the group of characters as a number in the current number
 3688: base (when you start up Forth, the current number base is base 10). If
 3689: the group of characters legitimately represents a number, the text
 3690: interpreter pushes the number onto a stack (we'll learn more about that
 3691: in the next section).
 3692: @end itemize
 3693: 
 3694: If the text interpreter is unable to do either of these things with any
 3695: group of characters, it discards the group of characters and the rest of
 3696: the line, then prints an error message. If the text interpreter reaches
 3697: the end of the line without error, it prints the status message ``@code{ ok}''
 3698: followed by carriage-return.
 3699: 
 3700: This is the simplest command we can give to the text interpreter:
 3701: 
 3702: @example
 3703: @key{RET}  ok
 3704: @end example
 3705: 
 3706: The text interpreter did everything we asked it to do (nothing) without
 3707: an error, so it said that everything is ``@code{ ok}''. Try a slightly longer
 3708: command:
 3709: 
 3710: @example
 3711: @kbd{12 dup fred dup@key{RET}}
 3712: :1: Undefined word
 3713: 12 dup fred dup
 3714:        ^^^^
 3715: $400D2BA8 Bounce
 3716: $400DBDA8 no.extensions
 3717: @end example
 3718: 
 3719: When you press the carriage-return key, the text interpreter starts to
 3720: work its way along the line:
 3721: 
 3722: @itemize @bullet
 3723: @item
 3724: When it gets to the space after the @code{2}, it takes the group of
 3725: characters @code{12} and looks them up in the name
 3726: dictionary@footnote{We can't tell if it found them or not, but assume
 3727: for now that it did not}. There is no match for this group of characters
 3728: in the name dictionary, so it tries to treat them as a number. It is
 3729: able to do this successfully, so it puts the number, 12, ``on the stack''
 3730: (whatever that means).
 3731: @item
 3732: The text interpreter resumes scanning the line and gets the next group
 3733: of characters, @code{dup}. It looks it up in the name dictionary and
 3734: (you'll have to take my word for this) finds it, and executes the word
 3735: @code{dup} (whatever that means).
 3736: @item
 3737: Once again, the text interpreter resumes scanning the line and gets the
 3738: group of characters @code{fred}. It looks them up in the name
 3739: dictionary, but can't find them. It tries to treat them as a number, but
 3740: they don't represent any legal number.
 3741: @end itemize
 3742: 
 3743: At this point, the text interpreter gives up and prints an error
 3744: message. The error message shows exactly how far the text interpreter
 3745: got in processing the line. In particular, it shows that the text
 3746: interpreter made no attempt to do anything with the final character
 3747: group, @code{dup}, even though we have good reason to believe that the
 3748: text interpreter would have no problem looking that word up and
 3749: executing it a second time.
 3750: 
 3751: 
 3752: @comment ----------------------------------------------
 3753: @node Stacks and Postfix notation, Your first definition, Introducing the Text Interpreter, Introduction
 3754: @section Stacks, postfix notation and parameter passing
 3755: @cindex text interpreter
 3756: @cindex outer interpreter
 3757: 
 3758: In procedural programming languages (like C and Pascal), the
 3759: building-block of programs is the @dfn{function} or @dfn{procedure}. These
 3760: functions or procedures are called with @dfn{explicit parameters}. For
 3761: example, in C we might write:
 3762: 
 3763: @example
 3764: total = total + new_volume(length,height,depth);
 3765: @end example
 3766: 
 3767: @noindent
 3768: where new_volume is a function-call to another piece of code, and total,
 3769: length, height and depth are all variables. length, height and depth are
 3770: parameters to the function-call.
 3771: 
 3772: In Forth, the equivalent of the function or procedure is the
 3773: @dfn{definition} and parameters are implicitly passed between
 3774: definitions using a shared stack that is visible to the
 3775: programmer. Although Forth does support variables, the existence of the
 3776: stack means that they are used far less often than in most other
 3777: programming languages. When the text interpreter encounters a number, it
 3778: will place (@dfn{push}) it on the stack. There are several stacks (the
 3779: actual number is implementation-dependent ...) and the particular stack
 3780: used for any operation is implied unambiguously by the operation being
 3781: performed. The stack used for all integer operations is called the @dfn{data
 3782: stack} and, since this is the stack used most commonly, references to
 3783: ``the data stack'' are often abbreviated to ``the stack''.
 3784: 
 3785: The stacks have a last-in, first-out (LIFO) organisation. If you type:
 3786: 
 3787: @example
 3788: @kbd{1 2 3@key{RET}}  ok
 3789: @end example
 3790: 
 3791: Then this instructs the text interpreter to placed three numbers on the
 3792: (data) stack. An analogy for the behaviour of the stack is to take a
 3793: pack of playing cards and deal out the ace (1), 2 and 3 into a pile on
 3794: the table. The 3 was the last card onto the pile (``last-in'') and if
 3795: you take a card off the pile then, unless you're prepared to fiddle a
 3796: bit, the card that you take off will be the 3 (``first-out''). The
 3797: number that will be first-out of the stack is called the @dfn{top of
 3798: stack}, which
 3799: @cindex TOS definition
 3800: is often abbreviated to @dfn{TOS}.
 3801: 
 3802: To understand how parameters are passed in Forth, consider the
 3803: behaviour of the definition @code{+} (pronounced ``plus''). You will not
 3804: be surprised to learn that this definition performs addition. More
 3805: precisely, it adds two number together and produces a result. Where does
 3806: it get the two numbers from? It takes the top two numbers off the
 3807: stack. Where does it place the result? On the stack. You can act-out the
 3808: behaviour of @code{+} with your playing cards like this:
 3809: 
 3810: @itemize @bullet
 3811: @item
 3812: Pick up two cards from the stack on the table
 3813: @item
 3814: Stare at them intently and ask yourself ``what @i{is} the sum of these two
 3815: numbers''
 3816: @item
 3817: Decide that the answer is 5
 3818: @item
 3819: Shuffle the two cards back into the pack and find a 5
 3820: @item
 3821: Put a 5 on the remaining ace that's on the table.
 3822: @end itemize
 3823: 
 3824: If you don't have a pack of cards handy but you do have Forth running,
 3825: you can use the definition @code{.s} to show the current state of the stack,
 3826: without affecting the stack. Type:
 3827: 
 3828: @example
 3829: @kbd{clearstack 1 2 3@key{RET}} ok
 3830: @kbd{.s@key{RET}} <3> 1 2 3  ok
 3831: @end example
 3832: 
 3833: The text interpreter looks up the word @code{clearstack} and executes
 3834: it; it tidies up the stack and removes any entries that may have been
 3835: left on it by earlier examples. The text interpreter pushes each of the
 3836: three numbers in turn onto the stack. Finally, the text interpreter
 3837: looks up the word @code{.s} and executes it. The effect of executing
 3838: @code{.s} is to print the ``<3>'' (the total number of items on the stack)
 3839: followed by a list of all the items on the stack; the item on the far
 3840: right-hand side is the TOS.
 3841: 
 3842: You can now type:
 3843: 
 3844: @example
 3845: @kbd{+ .s@key{RET}} <2> 1 5  ok
 3846: @end example
 3847: 
 3848: @noindent
 3849: which is correct; there are now 2 items on the stack and the result of
 3850: the addition is 5.
 3851: 
 3852: If you're playing with cards, try doing a second addition: pick up the
 3853: two cards, work out that their sum is 6, shuffle them into the pack,
 3854: look for a 6 and place that on the table. You now have just one item on
 3855: the stack. What happens if you try to do a third addition? Pick up the
 3856: first card, pick up the second card -- ah! There is no second card. This
 3857: is called a @dfn{stack underflow} and consitutes an error. If you try to
 3858: do the same thing with Forth it will report an error (probably a Stack
 3859: Underflow or an Invalid Memory Address error).
 3860: 
 3861: The opposite situation to a stack underflow is a @dfn{stack overflow},
 3862: which simply accepts that there is a finite amount of storage space
 3863: reserved for the stack. To stretch the playing card analogy, if you had
 3864: enough packs of cards and you piled the cards up on the table, you would
 3865: eventually be unable to add another card; you'd hit the ceiling. Gforth
 3866: allows you to set the maximum size of the stacks. In general, the only
 3867: time that you will get a stack overflow is because a definition has a
 3868: bug in it and is generating data on the stack uncontrollably.
 3869: 
 3870: There's one final use for the playing card analogy. If you model your
 3871: stack using a pack of playing cards, the maximum number of items on
 3872: your stack will be 52 (I assume you didn't use the Joker). The maximum
 3873: @i{value} of any item on the stack is 13 (the King). In fact, the only
 3874: possible numbers are positive integer numbers 1 through 13; you can't
 3875: have (for example) 0 or 27 or 3.52 or -2. If you change the way you
 3876: think about some of the cards, you can accommodate different
 3877: numbers. For example, you could think of the Jack as representing 0,
 3878: the Queen as representing -1 and the King as representing -2. Your
 3879: @i{range} remains unchanged (you can still only represent a total of 13
 3880: numbers) but the numbers that you can represent are -2 through 10.
 3881: 
 3882: In that analogy, the limit was the amount of information that a single
 3883: stack entry could hold, and Forth has a similar limit. In Forth, the
 3884: size of a stack entry is called a @dfn{cell}. The actual size of a cell is
 3885: implementation dependent and affects the maximum value that a stack
 3886: entry can hold. A Standard Forth provides a cell size of at least
 3887: 16-bits, and most desktop systems use a cell size of 32-bits.
 3888: 
 3889: Forth does not do any type checking for you, so you are free to
 3890: manipulate and combine stack items in any way you wish. A convenient way
 3891: of treating stack items is as 2's complement signed integers, and that
 3892: is what Standard words like @code{+} do. Therefore you can type:
 3893: 
 3894: @example
 3895: @kbd{-5 12 + .s@key{RET}} <1> 7  ok
 3896: @end example
 3897: 
 3898: If you use numbers and definitions like @code{+} in order to turn Forth
 3899: into a great big pocket calculator, you will realise that it's rather
 3900: different from a normal calculator. Rather than typing 2 + 3 = you had
 3901: to type 2 3 + (ignore the fact that you had to use @code{.s} to see the
 3902: result). The terminology used to describe this difference is to say that
 3903: your calculator uses @dfn{Infix Notation} (parameters and operators are
 3904: mixed) whilst Forth uses @dfn{Postfix Notation} (parameters and
 3905: operators are separate), also called @dfn{Reverse Polish Notation}.
 3906: 
 3907: Whilst postfix notation might look confusing to begin with, it has
 3908: several important advantages:
 3909: 
 3910: @itemize @bullet
 3911: @item
 3912: it is unambiguous
 3913: @item
 3914: it is more concise
 3915: @item
 3916: it fits naturally with a stack-based system
 3917: @end itemize
 3918: 
 3919: To examine these claims in more detail, consider these sums:
 3920: 
 3921: @example
 3922: 6 + 5 * 4 =
 3923: 4 * 5 + 6 =
 3924: @end example
 3925: 
 3926: If you're just learning maths or your maths is very rusty, you will
 3927: probably come up with the answer 44 for the first and 26 for the
 3928: second. If you are a bit of a whizz at maths you will remember the
 3929: @i{convention} that multiplication takes precendence over addition, and
 3930: you'd come up with the answer 26 both times. To explain the answer 26
 3931: to someone who got the answer 44, you'd probably rewrite the first sum
 3932: like this:
 3933: 
 3934: @example
 3935: 6 + (5 * 4) =
 3936: @end example
 3937: 
 3938: If what you really wanted was to perform the addition before the
 3939: multiplication, you would have to use parentheses to force it.
 3940: 
 3941: If you did the first two sums on a pocket calculator you would probably
 3942: get the right answers, unless you were very cautious and entered them using
 3943: these keystroke sequences:
 3944: 
 3945: 6 + 5 = * 4 =
 3946: 4 * 5 = + 6 =
 3947: 
 3948: Postfix notation is unambiguous because the order that the operators
 3949: are applied is always explicit; that also means that parentheses are
 3950: never required. The operators are @i{active} (the act of quoting the
 3951: operator makes the operation occur) which removes the need for ``=''.
 3952: 
 3953: The sum 6 + 5 * 4 can be written (in postfix notation) in two
 3954: equivalent ways:
 3955: 
 3956: @example
 3957: 6 5 4 * +      or:
 3958: 5 4 * 6 +
 3959: @end example
 3960: 
 3961: An important thing that you should notice about this notation is that
 3962: the @i{order} of the numbers does not change; if you want to subtract
 3963: 2 from 10 you type @code{10 2 -}.
 3964: 
 3965: The reason that Forth uses postfix notation is very simple to explain: it
 3966: makes the implementation extremely simple, and it follows naturally from
 3967: using the stack as a mechanism for passing parameters. Another way of
 3968: thinking about this is to realise that all Forth definitions are
 3969: @i{active}; they execute as they are encountered by the text
 3970: interpreter. The result of this is that the syntax of Forth is trivially
 3971: simple.
 3972: 
 3973: 
 3974: 
 3975: @comment ----------------------------------------------
 3976: @node Your first definition, How does that work?, Stacks and Postfix notation, Introduction
 3977: @section Your first Forth definition
 3978: @cindex first definition
 3979: 
 3980: Until now, the examples we've seen have been trivial; we've just been
 3981: using Forth as a bigger-than-pocket calculator. Also, each calculation
 3982: we've shown has been a ``one-off'' -- to repeat it we'd need to type it in
 3983: again@footnote{That's not quite true. If you press the up-arrow key on
 3984: your keyboard you should be able to scroll back to any earlier command,
 3985: edit it and re-enter it.} In this section we'll see how to add new
 3986: words to Forth's vocabulary.
 3987: 
 3988: The easiest way to create a new word is to use a @dfn{colon
 3989: definition}. We'll define a few and try them out before worrying too
 3990: much about how they work. Try typing in these examples; be careful to
 3991: copy the spaces accurately:
 3992: 
 3993: @example
 3994: : add-two 2 + . ;
 3995: : greet ." Hello and welcome" ;
 3996: : demo 5 add-two ;
 3997: @end example
 3998: 
 3999: @noindent
 4000: Now try them out:
 4001: 
 4002: @example
 4003: @kbd{greet@key{RET}} Hello and welcome  ok
 4004: @kbd{greet greet@key{RET}} Hello and welcomeHello and welcome  ok
 4005: @kbd{4 add-two@key{RET}} 6  ok
 4006: @kbd{demo@key{RET}} 7  ok
 4007: @kbd{9 greet demo add-two@key{RET}} Hello and welcome7 11  ok
 4008: @end example
 4009: 
 4010: The first new thing that we've introduced here is the pair of words
 4011: @code{:} and @code{;}. These are used to start and terminate a new
 4012: definition, respectively. The first word after the @code{:} is the name
 4013: for the new definition.
 4014: 
 4015: As you can see from the examples, a definition is built up of words that
 4016: have already been defined; Forth makes no distinction between
 4017: definitions that existed when you started the system up, and those that
 4018: you define yourself.
 4019: 
 4020: The examples also introduce the words @code{.} (dot), @code{."}
 4021: (dot-quote) and @code{dup} (dewp). Dot takes the value from the top of
 4022: the stack and displays it. It's like @code{.s} except that it only
 4023: displays the top item of the stack and it is destructive; after it has
 4024: executed, the number is no longer on the stack. There is always one
 4025: space printed after the number, and no spaces before it. Dot-quote
 4026: defines a string (a sequence of characters) that will be printed when
 4027: the word is executed. The string can contain any printable characters
 4028: except @code{"}. A @code{"} has a special function; it is not a Forth
 4029: word but it acts as a delimiter (the way that delimiters work is
 4030: described in the next section). Finally, @code{dup} duplicates the value
 4031: at the top of the stack. Try typing @code{5 dup .s} to see what it does.
 4032: 
 4033: We already know that the text interpreter searches through the
 4034: dictionary to locate names. If you've followed the examples earlier, you
 4035: will already have a definition called @code{add-two}. Lets try modifying
 4036: it by typing in a new definition:
 4037: 
 4038: @example
 4039: @kbd{: add-two dup . ." + 2 =" 2 + . ;@key{RET}} redefined add-two  ok
 4040: @end example
 4041: 
 4042: Forth recognised that we were defining a word that already exists, and
 4043: printed a message to warn us of that fact. Let's try out the new
 4044: definition:
 4045: 
 4046: @example
 4047: @kbd{9 add-two@key{RET}} 9 + 2 =11  ok
 4048: @end example
 4049: 
 4050: @noindent
 4051: All that we've actually done here, though, is to create a new
 4052: definition, with a particular name. The fact that there was already a
 4053: definition with the same name did not make any difference to the way
 4054: that the new definition was created (except that Forth printed a warning
 4055: message). The old definition of add-two still exists (try @code{demo}
 4056: again to see that this is true). Any new definition will use the new
 4057: definition of @code{add-two}, but old definitions continue to use the
 4058: version that already existed at the time that they were @code{compiled}.
 4059: 
 4060: Before you go on to the next section, try defining and redefining some
 4061: words of your own.
 4062: 
 4063: @comment ----------------------------------------------
 4064: @node How does that work?, Forth is written in Forth, Your first definition, Introduction
 4065: @section How does that work?
 4066: @cindex parsing words
 4067: 
 4068: @c That's pretty deep (IMO way too deep) for an introduction. - anton
 4069: 
 4070: @c Is it a good idea to talk about the interpretation semantics of a
 4071: @c number? We don't have an xt to go along with it. - anton
 4072: 
 4073: @c Now that I have eliminated execution semantics, I wonder if it would not
 4074: @c be better to keep them (or add run-time semantics), to make it easier to
 4075: @c explain what compilation semantics usually does. - anton
 4076: 
 4077: @c nac-> I removed the term ``default compilation sematics'' from the
 4078: @c introductory chapter. Removing ``execution semantics'' was making
 4079: @c everything simpler to explain, then I think the use of this term made
 4080: @c everything more complex again. I replaced it with ``default
 4081: @c semantics'' (which is used elsewhere in the manual) by which I mean
 4082: @c ``a definition that has neither the immediate nor the compile-only
 4083: @c flag set''.
 4084: 
 4085: @c anton: I have eliminated default semantics (except in one place where it
 4086: @c means "default interpretation and compilation semantics"), because it
 4087: @c makes no sense in the presence of combined words.  I reverted to
 4088: @c "execution semantics" where necessary.
 4089: 
 4090: @c nac-> I reworded big chunks of the ``how does that work''
 4091: @c section (and, unusually for me, I think I even made it shorter!).  See
 4092: @c what you think -- I know I have not addressed your primary concern
 4093: @c that it is too heavy-going for an introduction. From what I understood
 4094: @c of your course notes it looks as though they might be a good framework. 
 4095: @c Things that I've tried to capture here are some things that came as a
 4096: @c great revelation here when I first understood them. Also, I like the
 4097: @c fact that a very simple code example shows up almost all of the issues
 4098: @c that you need to understand to see how Forth works. That's unique and
 4099: @c worthwhile to emphasise.
 4100: 
 4101: @c anton: I think it's a good idea to present the details, especially those
 4102: @c that you found to be a revelation, and probably the tutorial tries to be
 4103: @c too superficial and does not get some of the things across that make
 4104: @c Forth special.  I do believe that most of the time these things should
 4105: @c be discussed at the end of a section or in separate sections instead of
 4106: @c in the middle of a section (e.g., the stuff you added in "User-defined
 4107: @c defining words" leads in a completely different direction from the rest
 4108: @c of the section).
 4109: 
 4110: Now we're going to take another look at the definition of @code{add-two}
 4111: from the previous section. From our knowledge of the way that the text
 4112: interpreter works, we would have expected this result when we tried to
 4113: define @code{add-two}:
 4114: 
 4115: @example
 4116: @kbd{: add-two 2 + . ;@key{RET}}
 4117:   ^^^^^^^
 4118: Error: Undefined word
 4119: @end example
 4120: 
 4121: The reason that this didn't happen is bound up in the way that @code{:}
 4122: works. The word @code{:} does two special things. The first special
 4123: thing that it does prevents the text interpreter from ever seeing the
 4124: characters @code{add-two}. The text interpreter uses a variable called
 4125: @cindex modifying >IN
 4126: @code{>IN} (pronounced ``to-in'') to keep track of where it is in the
 4127: input line. When it encounters the word @code{:} it behaves in exactly
 4128: the same way as it does for any other word; it looks it up in the name
 4129: dictionary, finds its xt and executes it. When @code{:} executes, it
 4130: looks at the input buffer, finds the word @code{add-two} and advances the
 4131: value of @code{>IN} to point past it. It then does some other stuff
 4132: associated with creating the new definition (including creating an entry
 4133: for @code{add-two} in the name dictionary). When the execution of @code{:}
 4134: completes, control returns to the text interpreter, which is oblivious
 4135: to the fact that it has been tricked into ignoring part of the input
 4136: line.
 4137: 
 4138: @cindex parsing words
 4139: Words like @code{:} -- words that advance the value of @code{>IN} and so
 4140: prevent the text interpreter from acting on the whole of the input line
 4141: -- are called @dfn{parsing words}.
 4142: 
 4143: @cindex @code{state} - effect on the text interpreter
 4144: @cindex text interpreter - effect of state
 4145: The second special thing that @code{:} does is change the value of a
 4146: variable called @code{state}, which affects the way that the text
 4147: interpreter behaves. When Gforth starts up, @code{state} has the value
 4148: 0, and the text interpreter is said to be @dfn{interpreting}. During a
 4149: colon definition (started with @code{:}), @code{state} is set to -1 and
 4150: the text interpreter is said to be @dfn{compiling}.
 4151: 
 4152: In this example, the text interpreter is compiling when it processes the
 4153: string ``@code{2 + . ;}''. It still breaks the string down into
 4154: character sequences in the same way. However, instead of pushing the
 4155: number @code{2} onto the stack, it lays down (@dfn{compiles}) some magic
 4156: into the definition of @code{add-two} that will make the number @code{2} get
 4157: pushed onto the stack when @code{add-two} is @dfn{executed}. Similarly,
 4158: the behaviours of @code{+} and @code{.} are also compiled into the
 4159: definition.
 4160: 
 4161: One category of words don't get compiled. These so-called @dfn{immediate
 4162: words} get executed (performed @i{now}) regardless of whether the text
 4163: interpreter is interpreting or compiling. The word @code{;} is an
 4164: immediate word. Rather than being compiled into the definition, it
 4165: executes. Its effect is to terminate the current definition, which
 4166: includes changing the value of @code{state} back to 0.
 4167: 
 4168: When you execute @code{add-two}, it has a @dfn{run-time effect} that is
 4169: exactly the same as if you had typed @code{2 + . @key{RET}} outside of a
 4170: definition.
 4171: 
 4172: In Forth, every word or number can be described in terms of two
 4173: properties:
 4174: 
 4175: @itemize @bullet
 4176: @item
 4177: @cindex interpretation semantics
 4178: Its @dfn{interpretation semantics} describe how it will behave when the
 4179: text interpreter encounters it in @dfn{interpret} state. The
 4180: interpretation semantics of a word are represented by an @dfn{execution
 4181: token}.
 4182: @item
 4183: @cindex compilation semantics
 4184: Its @dfn{compilation semantics} describe how it will behave when the
 4185: text interpreter encounters it in @dfn{compile} state. The compilation
 4186: semantics of a word are represented in an implementation-dependent way;
 4187: Gforth uses a @dfn{compilation token}.
 4188: @end itemize
 4189: 
 4190: @noindent
 4191: Numbers are always treated in a fixed way:
 4192: 
 4193: @itemize @bullet
 4194: @item
 4195: When the number is @dfn{interpreted}, its behaviour is to push the
 4196: number onto the stack.
 4197: @item
 4198: When the number is @dfn{compiled}, a piece of code is appended to the
 4199: current definition that pushes the number when it runs. (In other words,
 4200: the compilation semantics of a number are to postpone its interpretation
 4201: semantics until the run-time of the definition that it is being compiled
 4202: into.)
 4203: @end itemize
 4204: 
 4205: Words don't behave in such a regular way, but most have @i{default
 4206: semantics} which means that they behave like this:
 4207: 
 4208: @itemize @bullet
 4209: @item
 4210: The @dfn{interpretation semantics} of the word are to do something useful.
 4211: @item
 4212: The @dfn{compilation semantics} of the word are to append its
 4213: @dfn{interpretation semantics} to the current definition (so that its
 4214: run-time behaviour is to do something useful).
 4215: @end itemize
 4216: 
 4217: @cindex immediate words
 4218: The actual behaviour of any particular word can be controlled by using
 4219: the words @code{immediate} and @code{compile-only} when the word is
 4220: defined. These words set flags in the name dictionary entry of the most
 4221: recently defined word, and these flags are retrieved by the text
 4222: interpreter when it finds the word in the name dictionary.
 4223: 
 4224: A word that is marked as @dfn{immediate} has compilation semantics that
 4225: are identical to its interpretation semantics. In other words, it
 4226: behaves like this:
 4227: 
 4228: @itemize @bullet
 4229: @item
 4230: The @dfn{interpretation semantics} of the word are to do something useful.
 4231: @item
 4232: The @dfn{compilation semantics} of the word are to do something useful
 4233: (and actually the same thing); i.e., it is executed during compilation.
 4234: @end itemize
 4235: 
 4236: Marking a word as @dfn{compile-only} prohibits the text interpreter from
 4237: performing the interpretation semantics of the word directly; an attempt
 4238: to do so will generate an error. It is never necessary to use
 4239: @code{compile-only} (and it is not even part of ANS Forth, though it is
 4240: provided by many implementations) but it is good etiquette to apply it
 4241: to a word that will not behave correctly (and might have unexpected
 4242: side-effects) in interpret state. For example, it is only legal to use
 4243: the conditional word @code{IF} within a definition. If you forget this
 4244: and try to use it elsewhere, the fact that (in Gforth) it is marked as
 4245: @code{compile-only} allows the text interpreter to generate a helpful
 4246: error message rather than subjecting you to the consequences of your
 4247: folly.
 4248: 
 4249: This example shows the difference between an immediate and a
 4250: non-immediate word:
 4251: 
 4252: @example
 4253: : show-state state @@ . ;
 4254: : show-state-now show-state ; immediate
 4255: : word1 show-state ;
 4256: : word2 show-state-now ;
 4257: @end example
 4258: 
 4259: The word @code{immediate} after the definition of @code{show-state-now}
 4260: makes that word an immediate word. These definitions introduce a new
 4261: word: @code{@@} (pronounced ``fetch''). This word fetches the value of a
 4262: variable, and leaves it on the stack. Therefore, the behaviour of
 4263: @code{show-state} is to print a number that represents the current value
 4264: of @code{state}.
 4265: 
 4266: When you execute @code{word1}, it prints the number 0, indicating that
 4267: the system is interpreting. When the text interpreter compiled the
 4268: definition of @code{word1}, it encountered @code{show-state} whose
 4269: compilation semantics are to append its interpretation semantics to the
 4270: current definition. When you execute @code{word1}, it performs the
 4271: interpretation semantics of @code{show-state}.  At the time that @code{word1}
 4272: (and therefore @code{show-state}) are executed, the system is
 4273: interpreting.
 4274: 
 4275: When you pressed @key{RET} after entering the definition of @code{word2},
 4276: you should have seen the number -1 printed, followed by ``@code{
 4277: ok}''. When the text interpreter compiled the definition of
 4278: @code{word2}, it encountered @code{show-state-now}, an immediate word,
 4279: whose compilation semantics are therefore to perform its interpretation
 4280: semantics. It is executed straight away (even before the text
 4281: interpreter has moved on to process another group of characters; the
 4282: @code{;} in this example). The effect of executing it are to display the
 4283: value of @code{state} @i{at the time that the definition of}
 4284: @code{word2} @i{is being defined}. Printing -1 demonstrates that the
 4285: system is compiling at this time. If you execute @code{word2} it does
 4286: nothing at all.
 4287: 
 4288: @cindex @code{."}, how it works
 4289: Before leaving the subject of immediate words, consider the behaviour of
 4290: @code{."} in the definition of @code{greet}, in the previous
 4291: section. This word is both a parsing word and an immediate word. Notice
 4292: that there is a space between @code{."} and the start of the text
 4293: @code{Hello and welcome}, but that there is no space between the last
 4294: letter of @code{welcome} and the @code{"} character. The reason for this
 4295: is that @code{."} is a Forth word; it must have a space after it so that
 4296: the text interpreter can identify it. The @code{"} is not a Forth word;
 4297: it is a @dfn{delimiter}. The examples earlier show that, when the string
 4298: is displayed, there is neither a space before the @code{H} nor after the
 4299: @code{e}. Since @code{."} is an immediate word, it executes at the time
 4300: that @code{greet} is defined. When it executes, its behaviour is to
 4301: search forward in the input line looking for the delimiter. When it
 4302: finds the delimiter, it updates @code{>IN} to point past the
 4303: delimiter. It also compiles some magic code into the definition of
 4304: @code{greet}; the xt of a run-time routine that prints a text string. It
 4305: compiles the string @code{Hello and welcome} into memory so that it is
 4306: available to be printed later. When the text interpreter gains control,
 4307: the next word it finds in the input stream is @code{;} and so it
 4308: terminates the definition of @code{greet}.
 4309: 
 4310: 
 4311: @comment ----------------------------------------------
 4312: @node Forth is written in Forth, Review - elements of a Forth system, How does that work?, Introduction
 4313: @section Forth is written in Forth
 4314: @cindex structure of Forth programs
 4315: 
 4316: When you start up a Forth compiler, a large number of definitions
 4317: already exist. In Forth, you develop a new application using bottom-up
 4318: programming techniques to create new definitions that are defined in
 4319: terms of existing definitions. As you create each definition you can
 4320: test and debug it interactively.
 4321: 
 4322: If you have tried out the examples in this section, you will probably
 4323: have typed them in by hand; when you leave Gforth, your definitions will
 4324: be lost. You can avoid this by using a text editor to enter Forth source
 4325: code into a file, and then loading code from the file using
 4326: @code{include} (@pxref{Forth source files}). A Forth source file is
 4327: processed by the text interpreter, just as though you had typed it in by
 4328: hand@footnote{Actually, there are some subtle differences -- see
 4329: @ref{The Text Interpreter}.}.
 4330: 
 4331: Gforth also supports the traditional Forth alternative to using text
 4332: files for program entry (@pxref{Blocks}).
 4333: 
 4334: In common with many, if not most, Forth compilers, most of Gforth is
 4335: actually written in Forth. All of the @file{.fs} files in the
 4336: installation directory@footnote{For example,
 4337: @file{/usr/local/share/gforth...}} are Forth source files, which you can
 4338: study to see examples of Forth programming.
 4339: 
 4340: Gforth maintains a history file that records every line that you type to
 4341: the text interpreter. This file is preserved between sessions, and is
 4342: used to provide a command-line recall facility. If you enter long
 4343: definitions by hand, you can use a text editor to paste them out of the
 4344: history file into a Forth source file for reuse at a later time
 4345: (for more information @pxref{Command-line editing}).
 4346: 
 4347: 
 4348: @comment ----------------------------------------------
 4349: @node Review - elements of a Forth system, Where to go next, Forth is written in Forth, Introduction
 4350: @section Review - elements of a Forth system
 4351: @cindex elements of a Forth system
 4352: 
 4353: To summarise this chapter:
 4354: 
 4355: @itemize @bullet
 4356: @item
 4357: Forth programs use @dfn{factoring} to break a problem down into small
 4358: fragments called @dfn{words} or @dfn{definitions}.
 4359: @item
 4360: Forth program development is an interactive process.
 4361: @item
 4362: The main command loop that accepts input, and controls both
 4363: interpretation and compilation, is called the @dfn{text interpreter}
 4364: (also known as the @dfn{outer interpreter}).
 4365: @item
 4366: Forth has a very simple syntax, consisting of words and numbers
 4367: separated by spaces or carriage-return characters. Any additional syntax
 4368: is imposed by @dfn{parsing words}.
 4369: @item
 4370: Forth uses a stack to pass parameters between words. As a result, it
 4371: uses postfix notation.
 4372: @item
 4373: To use a word that has previously been defined, the text interpreter
 4374: searches for the word in the @dfn{name dictionary}.
 4375: @item
 4376: Words have @dfn{interpretation semantics} and @dfn{compilation semantics}.
 4377: @item
 4378: The text interpreter uses the value of @code{state} to select between
 4379: the use of the @dfn{interpretation semantics} and the  @dfn{compilation
 4380: semantics} of a word that it encounters.
 4381: @item
 4382: The relationship between the @dfn{interpretation semantics} and
 4383: @dfn{compilation semantics} for a word
 4384: depend upon the way in which the word was defined (for example, whether
 4385: it is an @dfn{immediate} word).
 4386: @item
 4387: Forth definitions can be implemented in Forth (called @dfn{high-level
 4388: definitions}) or in some other way (usually a lower-level language and
 4389: as a result often called @dfn{low-level definitions}, @dfn{code
 4390: definitions} or @dfn{primitives}).
 4391: @item
 4392: Many Forth systems are implemented mainly in Forth.
 4393: @end itemize
 4394: 
 4395: 
 4396: @comment ----------------------------------------------
 4397: @node Where to go next, Exercises, Review - elements of a Forth system, Introduction
 4398: @section Where To Go Next
 4399: @cindex where to go next
 4400: 
 4401: Amazing as it may seem, if you have read (and understood) this far, you
 4402: know almost all the fundamentals about the inner workings of a Forth
 4403: system. You certainly know enough to be able to read and understand the
 4404: rest of this manual and the ANS Forth document, to learn more about the
 4405: facilities that Forth in general and Gforth in particular provide. Even
 4406: scarier, you know almost enough to implement your own Forth system.
 4407: However, that's not a good idea just yet... better to try writing some
 4408: programs in Gforth.
 4409: 
 4410: Forth has such a rich vocabulary that it can be hard to know where to
 4411: start in learning it. This section suggests a few sets of words that are
 4412: enough to write small but useful programs. Use the word index in this
 4413: document to learn more about each word, then try it out and try to write
 4414: small definitions using it. Start by experimenting with these words:
 4415: 
 4416: @itemize @bullet
 4417: @item
 4418: Arithmetic: @code{+ - * / /MOD */ ABS INVERT}
 4419: @item
 4420: Comparison: @code{MIN MAX =}
 4421: @item
 4422: Logic: @code{AND OR XOR NOT}
 4423: @item
 4424: Stack manipulation: @code{DUP DROP SWAP OVER}
 4425: @item
 4426: Loops and decisions: @code{IF ELSE ENDIF ?DO I LOOP}
 4427: @item
 4428: Input/Output: @code{. ." EMIT CR KEY}
 4429: @item
 4430: Defining words: @code{: ; CREATE}
 4431: @item
 4432: Memory allocation words: @code{ALLOT ,}
 4433: @item
 4434: Tools: @code{SEE WORDS .S MARKER}
 4435: @end itemize
 4436: 
 4437: When you have mastered those, go on to:
 4438: 
 4439: @itemize @bullet
 4440: @item
 4441: More defining words: @code{VARIABLE CONSTANT VALUE TO CREATE DOES>}
 4442: @item
 4443: Memory access: @code{@@ !}
 4444: @end itemize
 4445: 
 4446: When you have mastered these, there's nothing for it but to read through
 4447: the whole of this manual and find out what you've missed.
 4448: 
 4449: @comment ----------------------------------------------
 4450: @node Exercises,  , Where to go next, Introduction
 4451: @section Exercises
 4452: @cindex exercises
 4453: 
 4454: TODO: provide a set of programming excercises linked into the stuff done
 4455: already and into other sections of the manual. Provide solutions to all
 4456: the exercises in a .fs file in the distribution.
 4457: 
 4458: @c Get some inspiration from Starting Forth and Kelly&Spies.
 4459: 
 4460: @c excercises:
 4461: @c 1. take inches and convert to feet and inches.
 4462: @c 2. take temperature and convert from fahrenheight to celcius;
 4463: @c    may need to care about symmetric vs floored??
 4464: @c 3. take input line and do character substitution
 4465: @c    to encipher or decipher
 4466: @c 4. as above but work on a file for in and out
 4467: @c 5. take input line and convert to pig-latin 
 4468: @c
 4469: @c thing of sets of things to exercise then come up with
 4470: @c problems that need those things.
 4471: 
 4472: 
 4473: @c ******************************************************************
 4474: @node Words, Error messages, Introduction, Top
 4475: @chapter Forth Words
 4476: @cindex words
 4477: 
 4478: @menu
 4479: * Notation::                    
 4480: * Case insensitivity::          
 4481: * Comments::                    
 4482: * Boolean Flags::               
 4483: * Arithmetic::                  
 4484: * Stack Manipulation::          
 4485: * Memory::                      
 4486: * Control Structures::          
 4487: * Defining Words::              
 4488: * Interpretation and Compilation Semantics::  
 4489: * Tokens for Words::            
 4490: * Compiling words::             
 4491: * The Text Interpreter::        
 4492: * Word Lists::                  
 4493: * Environmental Queries::       
 4494: * Files::                       
 4495: * Blocks::                      
 4496: * Other I/O::                   
 4497: * Locals::                      
 4498: * Structures::                  
 4499: * Object-oriented Forth::       
 4500: * Programming Tools::           
 4501: * Assembler and Code Words::    
 4502: * Threading Words::             
 4503: * Passing Commands to the OS::  
 4504: * Keeping track of Time::       
 4505: * Miscellaneous Words::         
 4506: @end menu
 4507: 
 4508: @node Notation, Case insensitivity, Words, Words
 4509: @section Notation
 4510: @cindex notation of glossary entries
 4511: @cindex format of glossary entries
 4512: @cindex glossary notation format
 4513: @cindex word glossary entry format
 4514: 
 4515: The Forth words are described in this section in the glossary notation
 4516: that has become a de-facto standard for Forth texts:
 4517: 
 4518: @format
 4519: @i{word}     @i{Stack effect}   @i{wordset}   @i{pronunciation}
 4520: @end format
 4521: @i{Description}
 4522: 
 4523: @table @var
 4524: @item word
 4525: The name of the word.
 4526: 
 4527: @item Stack effect
 4528: @cindex stack effect
 4529: The stack effect is written in the notation @code{@i{before} --
 4530: @i{after}}, where @i{before} and @i{after} describe the top of
 4531: stack entries before and after the execution of the word. The rest of
 4532: the stack is not touched by the word. The top of stack is rightmost,
 4533: i.e., a stack sequence is written as it is typed in. Note that Gforth
 4534: uses a separate floating point stack, but a unified stack
 4535: notation. Also, return stack effects are not shown in @i{stack
 4536: effect}, but in @i{Description}. The name of a stack item describes
 4537: the type and/or the function of the item. See below for a discussion of
 4538: the types.
 4539: 
 4540: All words have two stack effects: A compile-time stack effect and a
 4541: run-time stack effect. The compile-time stack-effect of most words is
 4542: @i{ -- }. If the compile-time stack-effect of a word deviates from
 4543: this standard behaviour, or the word does other unusual things at
 4544: compile time, both stack effects are shown; otherwise only the run-time
 4545: stack effect is shown.
 4546: 
 4547: @cindex pronounciation of words
 4548: @item pronunciation
 4549: How the word is pronounced.
 4550: 
 4551: @cindex wordset
 4552: @cindex environment wordset
 4553: @item wordset
 4554: The ANS Forth standard is divided into several word sets. A standard
 4555: system need not support all of them. Therefore, in theory, the fewer
 4556: word sets your program uses the more portable it will be. However, we
 4557: suspect that most ANS Forth systems on personal machines will feature
 4558: all word sets. Words that are not defined in ANS Forth have
 4559: @code{gforth} or @code{gforth-internal} as word set. @code{gforth}
 4560: describes words that will work in future releases of Gforth;
 4561: @code{gforth-internal} words are more volatile. Environmental query
 4562: strings are also displayed like words; you can recognize them by the
 4563: @code{environment} in the word set field.
 4564: 
 4565: @item Description
 4566: A description of the behaviour of the word.
 4567: @end table
 4568: 
 4569: @cindex types of stack items
 4570: @cindex stack item types
 4571: The type of a stack item is specified by the character(s) the name
 4572: starts with:
 4573: 
 4574: @table @code
 4575: @item f
 4576: @cindex @code{f}, stack item type
 4577: Boolean flags, i.e. @code{false} or @code{true}.
 4578: @item c
 4579: @cindex @code{c}, stack item type
 4580: Char
 4581: @item w
 4582: @cindex @code{w}, stack item type
 4583: Cell, can contain an integer or an address
 4584: @item n
 4585: @cindex @code{n}, stack item type
 4586: signed integer
 4587: @item u
 4588: @cindex @code{u}, stack item type
 4589: unsigned integer
 4590: @item d
 4591: @cindex @code{d}, stack item type
 4592: double sized signed integer
 4593: @item ud
 4594: @cindex @code{ud}, stack item type
 4595: double sized unsigned integer
 4596: @item r
 4597: @cindex @code{r}, stack item type
 4598: Float (on the FP stack)
 4599: @item a-
 4600: @cindex @code{a_}, stack item type
 4601: Cell-aligned address
 4602: @item c-
 4603: @cindex @code{c_}, stack item type
 4604: Char-aligned address (note that a Char may have two bytes in Windows NT)
 4605: @item f-
 4606: @cindex @code{f_}, stack item type
 4607: Float-aligned address
 4608: @item df-
 4609: @cindex @code{df_}, stack item type
 4610: Address aligned for IEEE double precision float
 4611: @item sf-
 4612: @cindex @code{sf_}, stack item type
 4613: Address aligned for IEEE single precision float
 4614: @item xt
 4615: @cindex @code{xt}, stack item type
 4616: Execution token, same size as Cell
 4617: @item wid
 4618: @cindex @code{wid}, stack item type
 4619: Word list ID, same size as Cell
 4620: @item ior, wior
 4621: @cindex ior type description
 4622: @cindex wior type description
 4623: I/O result code, cell-sized.  In Gforth, you can @code{throw} iors.
 4624: @item f83name
 4625: @cindex @code{f83name}, stack item type
 4626: Pointer to a name structure
 4627: @item "
 4628: @cindex @code{"}, stack item type
 4629: string in the input stream (not on the stack). The terminating character
 4630: is a blank by default. If it is not a blank, it is shown in @code{<>}
 4631: quotes.
 4632: @end table
 4633: 
 4634: @comment ----------------------------------------------
 4635: @node Case insensitivity, Comments, Notation, Words
 4636: @section Case insensitivity
 4637: @cindex case sensitivity
 4638: @cindex upper and lower case
 4639: 
 4640: Gforth is case-insensitive; you can enter definitions and invoke
 4641: Standard words using upper, lower or mixed case (however,
 4642: @pxref{core-idef, Implementation-defined options, Implementation-defined
 4643: options}).
 4644: 
 4645: ANS Forth only @i{requires} implementations to recognise Standard words
 4646: when they are typed entirely in upper case. Therefore, a Standard
 4647: program must use upper case for all Standard words. You can use whatever
 4648: case you like for words that you define, but in a Standard program you
 4649: have to use the words in the same case that you defined them.
 4650: 
 4651: Gforth supports case sensitivity through @code{table}s (case-sensitive
 4652: wordlists, @pxref{Word Lists}).
 4653: 
 4654: Two people have asked how to convert Gforth to be case-sensitive; while
 4655: we think this is a bad idea, you can change all wordlists into tables
 4656: like this:
 4657: 
 4658: @example
 4659: ' table-find forth-wordlist wordlist-map @ !
 4660: @end example
 4661: 
 4662: Note that you now have to type the predefined words in the same case
 4663: that we defined them, which are varying.  You may want to convert them
 4664: to your favourite case before doing this operation (I won't explain how,
 4665: because if you are even contemplating doing this, you'd better have
 4666: enough knowledge of Forth systems to know this already).
 4667: 
 4668: @node Comments, Boolean Flags, Case insensitivity, Words
 4669: @section Comments
 4670: @cindex comments
 4671: 
 4672: Forth supports two styles of comment; the traditional @i{in-line} comment,
 4673: @code{(} and its modern cousin, the @i{comment to end of line}; @code{\}.
 4674: 
 4675: 
 4676: doc-(
 4677: doc-\
 4678: doc-\G
 4679: 
 4680: 
 4681: @node Boolean Flags, Arithmetic, Comments, Words
 4682: @section Boolean Flags
 4683: @cindex Boolean flags
 4684: 
 4685: A Boolean flag is cell-sized. A cell with all bits clear represents the
 4686: flag @code{false} and a flag with all bits set represents the flag
 4687: @code{true}. Words that check a flag (for example, @code{IF}) will treat
 4688: a cell that has @i{any} bit set as @code{true}.
 4689: @c on and off to Memory? 
 4690: @c true and false to "Bitwise operations" or "Numeric comparison"?
 4691: 
 4692: doc-true
 4693: doc-false
 4694: doc-on
 4695: doc-off
 4696: 
 4697: 
 4698: @node Arithmetic, Stack Manipulation, Boolean Flags, Words
 4699: @section Arithmetic
 4700: @cindex arithmetic words
 4701: 
 4702: @cindex division with potentially negative operands
 4703: Forth arithmetic is not checked, i.e., you will not hear about integer
 4704: overflow on addition or multiplication, you may hear about division by
 4705: zero if you are lucky. The operator is written after the operands, but
 4706: the operands are still in the original order. I.e., the infix @code{2-1}
 4707: corresponds to @code{2 1 -}. Forth offers a variety of division
 4708: operators. If you perform division with potentially negative operands,
 4709: you do not want to use @code{/} or @code{/mod} with its undefined
 4710: behaviour, but rather @code{fm/mod} or @code{sm/mod} (probably the
 4711: former, @pxref{Mixed precision}).
 4712: @comment TODO discuss the different division forms and the std approach
 4713: 
 4714: @menu
 4715: * Single precision::            
 4716: * Double precision::            Double-cell integer arithmetic
 4717: * Bitwise operations::          
 4718: * Numeric comparison::          
 4719: * Mixed precision::             Operations with single and double-cell integers
 4720: * Floating Point::              
 4721: @end menu
 4722: 
 4723: @node Single precision, Double precision, Arithmetic, Arithmetic
 4724: @subsection Single precision
 4725: @cindex single precision arithmetic words
 4726: 
 4727: @c !! cell undefined
 4728: 
 4729: By default, numbers in Forth are single-precision integers that are one
 4730: cell in size. They can be signed or unsigned, depending upon how you
 4731: treat them. For the rules used by the text interpreter for recognising
 4732: single-precision integers see @ref{Number Conversion}.
 4733: 
 4734: These words are all defined for signed operands, but some of them also
 4735: work for unsigned numbers: @code{+}, @code{1+}, @code{-}, @code{1-},
 4736: @code{*}.
 4737: 
 4738: doc-+
 4739: doc-1+
 4740: doc--
 4741: doc-1-
 4742: doc-*
 4743: doc-/
 4744: doc-mod
 4745: doc-/mod
 4746: doc-negate
 4747: doc-abs
 4748: doc-min
 4749: doc-max
 4750: doc-floored
 4751: 
 4752: 
 4753: @node Double precision, Bitwise operations, Single precision, Arithmetic
 4754: @subsection Double precision
 4755: @cindex double precision arithmetic words
 4756: 
 4757: For the rules used by the text interpreter for
 4758: recognising double-precision integers, see @ref{Number Conversion}.
 4759: 
 4760: A double precision number is represented by a cell pair, with the most
 4761: significant cell at the TOS. It is trivial to convert an unsigned single
 4762: to a double: simply push a @code{0} onto the TOS. Since numbers are
 4763: represented by Gforth using 2's complement arithmetic, converting a
 4764: signed single to a (signed) double requires sign-extension across the
 4765: most significant cell. This can be achieved using @code{s>d}. The moral
 4766: of the story is that you cannot convert a number without knowing whether
 4767: it represents an unsigned or a signed number.
 4768: 
 4769: These words are all defined for signed operands, but some of them also
 4770: work for unsigned numbers: @code{d+}, @code{d-}.
 4771: 
 4772: doc-s>d
 4773: doc-d>s
 4774: doc-d+
 4775: doc-d-
 4776: doc-dnegate
 4777: doc-dabs
 4778: doc-dmin
 4779: doc-dmax
 4780: 
 4781: 
 4782: @node Bitwise operations, Numeric comparison, Double precision, Arithmetic
 4783: @subsection Bitwise operations
 4784: @cindex bitwise operation words
 4785: 
 4786: 
 4787: doc-and
 4788: doc-or
 4789: doc-xor
 4790: doc-invert
 4791: doc-lshift
 4792: doc-rshift
 4793: doc-2*
 4794: doc-d2*
 4795: doc-2/
 4796: doc-d2/
 4797: 
 4798: 
 4799: @node Numeric comparison, Mixed precision, Bitwise operations, Arithmetic
 4800: @subsection Numeric comparison
 4801: @cindex numeric comparison words
 4802: 
 4803: Note that the words that compare for equality (@code{= <> 0= 0<> d= d<>
 4804: d0= d0<>}) work for for both signed and unsigned numbers.
 4805: 
 4806: doc-<
 4807: doc-<=
 4808: doc-<>
 4809: doc-=
 4810: doc->
 4811: doc->=
 4812: 
 4813: doc-0<
 4814: doc-0<=
 4815: doc-0<>
 4816: doc-0=
 4817: doc-0>
 4818: doc-0>=
 4819: 
 4820: doc-u<
 4821: doc-u<=
 4822: @c u<> and u= exist but are the same as <> and =
 4823: @c doc-u<>
 4824: @c doc-u=
 4825: doc-u>
 4826: doc-u>=
 4827: 
 4828: doc-within
 4829: 
 4830: doc-d<
 4831: doc-d<=
 4832: doc-d<>
 4833: doc-d=
 4834: doc-d>
 4835: doc-d>=
 4836: 
 4837: doc-d0<
 4838: doc-d0<=
 4839: doc-d0<>
 4840: doc-d0=
 4841: doc-d0>
 4842: doc-d0>=
 4843: 
 4844: doc-du<
 4845: doc-du<=
 4846: @c du<> and du= exist but are the same as d<> and d=
 4847: @c doc-du<>
 4848: @c doc-du=
 4849: doc-du>
 4850: doc-du>=
 4851: 
 4852: 
 4853: @node Mixed precision, Floating Point, Numeric comparison, Arithmetic
 4854: @subsection Mixed precision
 4855: @cindex mixed precision arithmetic words
 4856: 
 4857: 
 4858: doc-m+
 4859: doc-*/
 4860: doc-*/mod
 4861: doc-m*
 4862: doc-um*
 4863: doc-m*/
 4864: doc-um/mod
 4865: doc-fm/mod
 4866: doc-sm/rem
 4867: 
 4868: 
 4869: @node Floating Point,  , Mixed precision, Arithmetic
 4870: @subsection Floating Point
 4871: @cindex floating point arithmetic words
 4872: 
 4873: For the rules used by the text interpreter for
 4874: recognising floating-point numbers see @ref{Number Conversion}.
 4875: 
 4876: Gforth has a separate floating point stack, but the documentation uses
 4877: the unified notation.@footnote{It's easy to generate the separate
 4878: notation from that by just separating the floating-point numbers out:
 4879: e.g. @code{( n r1 u r2 -- r3 )} becomes @code{( n u -- ) ( F: r1 r2 --
 4880: r3 )}.}
 4881: 
 4882: @cindex floating-point arithmetic, pitfalls
 4883: Floating point numbers have a number of unpleasant surprises for the
 4884: unwary (e.g., floating point addition is not associative) and even a few
 4885: for the wary. You should not use them unless you know what you are doing
 4886: or you don't care that the results you get are totally bogus. If you
 4887: want to learn about the problems of floating point numbers (and how to
 4888: avoid them), you might start with @cite{David Goldberg,
 4889: @uref{http://www.validgh.com/goldberg/paper.ps,What Every Computer
 4890: Scientist Should Know About Floating-Point Arithmetic}, ACM Computing
 4891: Surveys 23(1):5@minus{}48, March 1991}.
 4892: 
 4893: 
 4894: doc-d>f
 4895: doc-f>d
 4896: doc-f+
 4897: doc-f-
 4898: doc-f*
 4899: doc-f/
 4900: doc-fnegate
 4901: doc-fabs
 4902: doc-fmax
 4903: doc-fmin
 4904: doc-floor
 4905: doc-fround
 4906: doc-f**
 4907: doc-fsqrt
 4908: doc-fexp
 4909: doc-fexpm1
 4910: doc-fln
 4911: doc-flnp1
 4912: doc-flog
 4913: doc-falog
 4914: doc-f2*
 4915: doc-f2/
 4916: doc-1/f
 4917: doc-precision
 4918: doc-set-precision
 4919: 
 4920: @cindex angles in trigonometric operations
 4921: @cindex trigonometric operations
 4922: Angles in floating point operations are given in radians (a full circle
 4923: has 2 pi radians).
 4924: 
 4925: doc-fsin
 4926: doc-fcos
 4927: doc-fsincos
 4928: doc-ftan
 4929: doc-fasin
 4930: doc-facos
 4931: doc-fatan
 4932: doc-fatan2
 4933: doc-fsinh
 4934: doc-fcosh
 4935: doc-ftanh
 4936: doc-fasinh
 4937: doc-facosh
 4938: doc-fatanh
 4939: doc-pi
 4940: 
 4941: @cindex equality of floats
 4942: @cindex floating-point comparisons
 4943: One particular problem with floating-point arithmetic is that comparison
 4944: for equality often fails when you would expect it to succeed.  For this
 4945: reason approximate equality is often preferred (but you still have to
 4946: know what you are doing).  Also note that IEEE NaNs may compare
 4947: differently from what you might expect.  The comparison words are:
 4948: 
 4949: doc-f~rel
 4950: doc-f~abs
 4951: doc-f~
 4952: doc-f=
 4953: doc-f<>
 4954: 
 4955: doc-f<
 4956: doc-f<=
 4957: doc-f>
 4958: doc-f>=
 4959: 
 4960: doc-f0<
 4961: doc-f0<=
 4962: doc-f0<>
 4963: doc-f0=
 4964: doc-f0>
 4965: doc-f0>=
 4966: 
 4967: 
 4968: @node Stack Manipulation, Memory, Arithmetic, Words
 4969: @section Stack Manipulation
 4970: @cindex stack manipulation words
 4971: 
 4972: @cindex floating-point stack in the standard
 4973: Gforth maintains a number of separate stacks:
 4974: 
 4975: @cindex data stack
 4976: @cindex parameter stack
 4977: @itemize @bullet
 4978: @item
 4979: A data stack (also known as the @dfn{parameter stack}) -- for
 4980: characters, cells, addresses, and double cells.
 4981: 
 4982: @cindex floating-point stack
 4983: @item
 4984: A floating point stack -- for holding floating point (FP) numbers.
 4985: 
 4986: @cindex return stack
 4987: @item
 4988: A return stack -- for holding the return addresses of colon
 4989: definitions and other (non-FP) data.
 4990: 
 4991: @cindex locals stack
 4992: @item
 4993: A locals stack -- for holding local variables.
 4994: @end itemize
 4995: 
 4996: @menu
 4997: * Data stack::                  
 4998: * Floating point stack::        
 4999: * Return stack::                
 5000: * Locals stack::                
 5001: * Stack pointer manipulation::  
 5002: @end menu
 5003: 
 5004: @node Data stack, Floating point stack, Stack Manipulation, Stack Manipulation
 5005: @subsection Data stack
 5006: @cindex data stack manipulation words
 5007: @cindex stack manipulations words, data stack
 5008: 
 5009: 
 5010: doc-drop
 5011: doc-nip
 5012: doc-dup
 5013: doc-over
 5014: doc-tuck
 5015: doc-swap
 5016: doc-pick
 5017: doc-rot
 5018: doc--rot
 5019: doc-?dup
 5020: doc-roll
 5021: doc-2drop
 5022: doc-2nip
 5023: doc-2dup
 5024: doc-2over
 5025: doc-2tuck
 5026: doc-2swap
 5027: doc-2rot
 5028: 
 5029: 
 5030: @node Floating point stack, Return stack, Data stack, Stack Manipulation
 5031: @subsection Floating point stack
 5032: @cindex floating-point stack manipulation words
 5033: @cindex stack manipulation words, floating-point stack
 5034: 
 5035: Whilst every sane Forth has a separate floating-point stack, it is not
 5036: strictly required; an ANS Forth system could theoretically keep
 5037: floating-point numbers on the data stack. As an additional difficulty,
 5038: you don't know how many cells a floating-point number takes. It is
 5039: reportedly possible to write words in a way that they work also for a
 5040: unified stack model, but we do not recommend trying it. Instead, just
 5041: say that your program has an environmental dependency on a separate
 5042: floating-point stack.
 5043: 
 5044: doc-floating-stack
 5045: 
 5046: doc-fdrop
 5047: doc-fnip
 5048: doc-fdup
 5049: doc-fover
 5050: doc-ftuck
 5051: doc-fswap
 5052: doc-fpick
 5053: doc-frot
 5054: 
 5055: 
 5056: @node Return stack, Locals stack, Floating point stack, Stack Manipulation
 5057: @subsection Return stack
 5058: @cindex return stack manipulation words
 5059: @cindex stack manipulation words, return stack
 5060: 
 5061: @cindex return stack and locals
 5062: @cindex locals and return stack
 5063: A Forth system is allowed to keep local variables on the
 5064: return stack. This is reasonable, as local variables usually eliminate
 5065: the need to use the return stack explicitly. So, if you want to produce
 5066: a standard compliant program and you are using local variables in a
 5067: word, forget about return stack manipulations in that word (refer to the
 5068: standard document for the exact rules).
 5069: 
 5070: doc->r
 5071: doc-r>
 5072: doc-r@
 5073: doc-rdrop
 5074: doc-2>r
 5075: doc-2r>
 5076: doc-2r@
 5077: doc-2rdrop
 5078: 
 5079: 
 5080: @node Locals stack, Stack pointer manipulation, Return stack, Stack Manipulation
 5081: @subsection Locals stack
 5082: 
 5083: Gforth uses an extra locals stack.  It is described, along with the
 5084: reasons for its existence, in @ref{Locals implementation}.
 5085: 
 5086: @node Stack pointer manipulation,  , Locals stack, Stack Manipulation
 5087: @subsection Stack pointer manipulation
 5088: @cindex stack pointer manipulation words
 5089: 
 5090: @c removed s0 r0 l0 -- they are obsolete aliases for sp0 rp0 lp0
 5091: doc-sp0
 5092: doc-sp@
 5093: doc-sp!
 5094: doc-fp0
 5095: doc-fp@
 5096: doc-fp!
 5097: doc-rp0
 5098: doc-rp@
 5099: doc-rp!
 5100: doc-lp0
 5101: doc-lp@
 5102: doc-lp!
 5103: 
 5104: 
 5105: @node Memory, Control Structures, Stack Manipulation, Words
 5106: @section Memory
 5107: @cindex memory words
 5108: 
 5109: @menu
 5110: * Memory model::                
 5111: * Dictionary allocation::       
 5112: * Heap Allocation::             
 5113: * Memory Access::               
 5114: * Address arithmetic::          
 5115: * Memory Blocks::               
 5116: @end menu
 5117: 
 5118: In addition to the standard Forth memory allocation words, there is also
 5119: a @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
 5120: garbage collector}.
 5121: 
 5122: @node Memory model, Dictionary allocation, Memory, Memory
 5123: @subsection ANS Forth and Gforth memory models
 5124: 
 5125: @c The ANS Forth description is a mess (e.g., is the heap part of
 5126: @c the dictionary?), so let's not stick to closely with it.
 5127: 
 5128: ANS Forth considers a Forth system as consisting of several address
 5129: spaces, of which only @dfn{data space} is managed and accessible with
 5130: the memory words.  Memory not necessarily in data space includes the
 5131: stacks, the code (called code space) and the headers (called name
 5132: space). In Gforth everything is in data space, but the code for the
 5133: primitives is usually read-only.
 5134: 
 5135: Data space is divided into a number of areas: The (data space portion of
 5136: the) dictionary@footnote{Sometimes, the term @dfn{dictionary} is used to
 5137: refer to the search data structure embodied in word lists and headers,
 5138: because it is used for looking up names, just as you would in a
 5139: conventional dictionary.}, the heap, and a number of system-allocated
 5140: buffers.
 5141: 
 5142: @cindex address arithmetic restrictions, ANS vs. Gforth
 5143: @cindex contiguous regions, ANS vs. Gforth
 5144: In ANS Forth data space is also divided into contiguous regions.  You
 5145: can only use address arithmetic within a contiguous region, not between
 5146: them.  Usually each allocation gives you one contiguous region, but the
 5147: dictionary allocation words have additional rules (@pxref{Dictionary
 5148: allocation}).
 5149: 
 5150: Gforth provides one big address space, and address arithmetic can be
 5151: performed between any addresses. However, in the dictionary headers or
 5152: code are interleaved with data, so almost the only contiguous data space
 5153: regions there are those described by ANS Forth as contiguous; but you
 5154: can be sure that the dictionary is allocated towards increasing
 5155: addresses even between contiguous regions.  The memory order of
 5156: allocations in the heap is platform-dependent (and possibly different
 5157: from one run to the next).
 5158: 
 5159: 
 5160: @node Dictionary allocation, Heap Allocation, Memory model, Memory
 5161: @subsection Dictionary allocation
 5162: @cindex reserving data space
 5163: @cindex data space - reserving some
 5164: 
 5165: Dictionary allocation is a stack-oriented allocation scheme, i.e., if
 5166: you want to deallocate X, you also deallocate everything
 5167: allocated after X.
 5168: 
 5169: @cindex contiguous regions in dictionary allocation
 5170: The allocations using the words below are contiguous and grow the region
 5171: towards increasing addresses.  Other words that allocate dictionary
 5172: memory of any kind (i.e., defining words including @code{:noname}) end
 5173: the contiguous region and start a new one.
 5174: 
 5175: In ANS Forth only @code{create}d words are guaranteed to produce an
 5176: address that is the start of the following contiguous region.  In
 5177: particular, the cell allocated by @code{variable} is not guaranteed to
 5178: be contiguous with following @code{allot}ed memory.
 5179: 
 5180: You can deallocate memory by using @code{allot} with a negative argument
 5181: (with some restrictions, see @code{allot}). For larger deallocations use
 5182: @code{marker}.
 5183: 
 5184: 
 5185: doc-here
 5186: doc-unused
 5187: doc-allot
 5188: doc-c,
 5189: doc-f,
 5190: doc-,
 5191: doc-2,
 5192: 
 5193: Memory accesses have to be aligned (@pxref{Address arithmetic}). So of
 5194: course you should allocate memory in an aligned way, too. I.e., before
 5195: allocating allocating a cell, @code{here} must be cell-aligned, etc.
 5196: The words below align @code{here} if it is not already.  Basically it is
 5197: only already aligned for a type, if the last allocation was a multiple
 5198: of the size of this type and if @code{here} was aligned for this type
 5199: before.
 5200: 
 5201: After freshly @code{create}ing a word, @code{here} is @code{align}ed in
 5202: ANS Forth (@code{maxalign}ed in Gforth).
 5203: 
 5204: doc-align
 5205: doc-falign
 5206: doc-sfalign
 5207: doc-dfalign
 5208: doc-maxalign
 5209: doc-cfalign
 5210: 
 5211: 
 5212: @node Heap Allocation, Memory Access, Dictionary allocation, Memory
 5213: @subsection Heap allocation
 5214: @cindex heap allocation
 5215: @cindex dynamic allocation of memory
 5216: @cindex memory-allocation word set
 5217: 
 5218: @cindex contiguous regions and heap allocation
 5219: Heap allocation supports deallocation of allocated memory in any
 5220: order. Dictionary allocation is not affected by it (i.e., it does not
 5221: end a contiguous region). In Gforth, these words are implemented using
 5222: the standard C library calls malloc(), free() and resize().
 5223: 
 5224: The memory region produced by one invocation of @code{allocate} or
 5225: @code{resize} is internally contiguous.  There is no contiguity between
 5226: such a region and any other region (including others allocated from the
 5227: heap).
 5228: 
 5229: doc-allocate
 5230: doc-free
 5231: doc-resize
 5232: 
 5233: 
 5234: @node Memory Access, Address arithmetic, Heap Allocation, Memory
 5235: @subsection Memory Access
 5236: @cindex memory access words
 5237: 
 5238: doc-@
 5239: doc-!
 5240: doc-+!
 5241: doc-c@
 5242: doc-c!
 5243: doc-2@
 5244: doc-2!
 5245: doc-f@
 5246: doc-f!
 5247: doc-sf@
 5248: doc-sf!
 5249: doc-df@
 5250: doc-df!
 5251: 
 5252: 
 5253: @node Address arithmetic, Memory Blocks, Memory Access, Memory
 5254: @subsection Address arithmetic
 5255: @cindex address arithmetic words
 5256: 
 5257: Address arithmetic is the foundation on which you can build data
 5258: structures like arrays, records (@pxref{Structures}) and objects
 5259: (@pxref{Object-oriented Forth}).
 5260: 
 5261: @cindex address unit
 5262: @cindex au (address unit)
 5263: ANS Forth does not specify the sizes of the data types. Instead, it
 5264: offers a number of words for computing sizes and doing address
 5265: arithmetic. Address arithmetic is performed in terms of address units
 5266: (aus); on most systems the address unit is one byte. Note that a
 5267: character may have more than one au, so @code{chars} is no noop (on
 5268: platforms where it is a noop, it compiles to nothing).
 5269: 
 5270: The basic address arithmetic words are @code{+} and @code{-}.  E.g., if
 5271: you have the address of a cell, perform @code{1 cells +}, and you will
 5272: have the address of the next cell.
 5273: 
 5274: @cindex contiguous regions and address arithmetic
 5275: In ANS Forth you can perform address arithmetic only within a contiguous
 5276: region, i.e., if you have an address into one region, you can only add
 5277: and subtract such that the result is still within the region; you can
 5278: only subtract or compare addresses from within the same contiguous
 5279: region.  Reasons: several contiguous regions can be arranged in memory
 5280: in any way; on segmented systems addresses may have unusual
 5281: representations, such that address arithmetic only works within a
 5282: region.  Gforth provides a few more guarantees (linear address space,
 5283: dictionary grows upwards), but in general I have found it easy to stay
 5284: within contiguous regions (exception: computing and comparing to the
 5285: address just beyond the end of an array).
 5286: 
 5287: @cindex alignment of addresses for types
 5288: ANS Forth also defines words for aligning addresses for specific
 5289: types. Many computers require that accesses to specific data types
 5290: must only occur at specific addresses; e.g., that cells may only be
 5291: accessed at addresses divisible by 4. Even if a machine allows unaligned
 5292: accesses, it can usually perform aligned accesses faster. 
 5293: 
 5294: For the performance-conscious: alignment operations are usually only
 5295: necessary during the definition of a data structure, not during the
 5296: (more frequent) accesses to it.
 5297: 
 5298: ANS Forth defines no words for character-aligning addresses. This is not
 5299: an oversight, but reflects the fact that addresses that are not
 5300: char-aligned have no use in the standard and therefore will not be
 5301: created.
 5302: 
 5303: @cindex @code{CREATE} and alignment
 5304: ANS Forth guarantees that addresses returned by @code{CREATE}d words
 5305: are cell-aligned; in addition, Gforth guarantees that these addresses
 5306: are aligned for all purposes.
 5307: 
 5308: Note that the ANS Forth word @code{char} has nothing to do with address
 5309: arithmetic.
 5310: 
 5311: 
 5312: doc-chars
 5313: doc-char+
 5314: doc-cells
 5315: doc-cell+
 5316: doc-cell
 5317: doc-aligned
 5318: doc-floats
 5319: doc-float+
 5320: doc-float
 5321: doc-faligned
 5322: doc-sfloats
 5323: doc-sfloat+
 5324: doc-sfaligned
 5325: doc-dfloats
 5326: doc-dfloat+
 5327: doc-dfaligned
 5328: doc-maxaligned
 5329: doc-cfaligned
 5330: doc-address-unit-bits
 5331: 
 5332: 
 5333: @node Memory Blocks,  , Address arithmetic, Memory
 5334: @subsection Memory Blocks
 5335: @cindex memory block words
 5336: @cindex character strings - moving and copying
 5337: 
 5338: Memory blocks often represent character strings; For ways of storing
 5339: character strings in memory see @ref{String Formats}.  For other
 5340: string-processing words see @ref{Displaying characters and strings}.
 5341: 
 5342: A few of these words work on address unit blocks.  In that case, you
 5343: usually have to insert @code{CHARS} before the word when working on
 5344: character strings.  Most words work on character blocks, and expect a
 5345: char-aligned address.
 5346: 
 5347: When copying characters between overlapping memory regions, use
 5348: @code{chars move} or choose carefully between @code{cmove} and
 5349: @code{cmove>}.
 5350: 
 5351: doc-move
 5352: doc-erase
 5353: doc-cmove
 5354: doc-cmove>
 5355: doc-fill
 5356: doc-blank
 5357: doc-compare
 5358: doc-search
 5359: doc--trailing
 5360: doc-/string
 5361: doc-bounds
 5362: 
 5363: @comment TODO examples
 5364: 
 5365: 
 5366: @node Control Structures, Defining Words, Memory, Words
 5367: @section Control Structures
 5368: @cindex control structures
 5369: 
 5370: Control structures in Forth cannot be used interpretively, only in a
 5371: colon definition@footnote{To be precise, they have no interpretation
 5372: semantics (@pxref{Interpretation and Compilation Semantics}).}. We do
 5373: not like this limitation, but have not seen a satisfying way around it
 5374: yet, although many schemes have been proposed.
 5375: 
 5376: @menu
 5377: * Selection::                   IF ... ELSE ... ENDIF
 5378: * Simple Loops::                BEGIN ...
 5379: * Counted Loops::               DO
 5380: * Arbitrary control structures::  
 5381: * Calls and returns::           
 5382: * Exception Handling::          
 5383: @end menu
 5384: 
 5385: @node Selection, Simple Loops, Control Structures, Control Structures
 5386: @subsection Selection
 5387: @cindex selection control structures
 5388: @cindex control structures for selection
 5389: 
 5390: @cindex @code{IF} control structure
 5391: @example
 5392: @i{flag}
 5393: IF
 5394:   @i{code}
 5395: ENDIF
 5396: @end example
 5397: @noindent
 5398: 
 5399: If @i{flag} is non-zero (as far as @code{IF} etc. are concerned, a cell
 5400: with any bit set represents truth) @i{code} is executed.
 5401: 
 5402: @example
 5403: @i{flag}
 5404: IF
 5405:   @i{code1}
 5406: ELSE
 5407:   @i{code2}
 5408: ENDIF
 5409: @end example
 5410: 
 5411: If @var{flag} is true, @i{code1} is executed, otherwise @i{code2} is
 5412: executed.
 5413: 
 5414: You can use @code{THEN} instead of @code{ENDIF}. Indeed, @code{THEN} is
 5415: standard, and @code{ENDIF} is not, although it is quite popular. We
 5416: recommend using @code{ENDIF}, because it is less confusing for people
 5417: who also know other languages (and is not prone to reinforcing negative
 5418: prejudices against Forth in these people). Adding @code{ENDIF} to a
 5419: system that only supplies @code{THEN} is simple:
 5420: @example
 5421: : ENDIF   POSTPONE then ; immediate
 5422: @end example
 5423: 
 5424: [According to @cite{Webster's New Encyclopedic Dictionary}, @dfn{then
 5425: (adv.)}  has the following meanings:
 5426: @quotation
 5427: ... 2b: following next after in order ... 3d: as a necessary consequence
 5428: (if you were there, then you saw them).
 5429: @end quotation
 5430: Forth's @code{THEN} has the meaning 2b, whereas @code{THEN} in Pascal
 5431: and many other programming languages has the meaning 3d.]
 5432: 
 5433: Gforth also provides the words @code{?DUP-IF} and @code{?DUP-0=-IF}, so
 5434: you can avoid using @code{?dup}. Using these alternatives is also more
 5435: efficient than using @code{?dup}. Definitions in ANS Forth
 5436: for @code{ENDIF}, @code{?DUP-IF} and @code{?DUP-0=-IF} are provided in
 5437: @file{compat/control.fs}.
 5438: 
 5439: @cindex @code{CASE} control structure
 5440: @example
 5441: @i{n}
 5442: CASE
 5443:   @i{n1} OF @i{code1} ENDOF
 5444:   @i{n2} OF @i{code2} ENDOF
 5445:   @dots{}
 5446:   ( n ) @i{default-code} ( n )
 5447: ENDCASE
 5448: @end example
 5449: 
 5450: Executes the first @i{codei}, where the @i{ni} is equal to @i{n}.  If no
 5451: @i{ni} matches, the optional @i{default-code} is executed. The optional
 5452: default case can be added by simply writing the code after the last
 5453: @code{ENDOF}. It may use @i{n}, which is on top of the stack, but must
 5454: not consume it.
 5455: 
 5456: @progstyle
 5457: To keep the code understandable, you should ensure that on all paths
 5458: through a selection construct the stack is changed in the same way
 5459: (wrt. number and types of stack items consumed and pushed).
 5460: 
 5461: @node Simple Loops, Counted Loops, Selection, Control Structures
 5462: @subsection Simple Loops
 5463: @cindex simple loops
 5464: @cindex loops without count 
 5465: 
 5466: @cindex @code{WHILE} loop
 5467: @example
 5468: BEGIN
 5469:   @i{code1}
 5470:   @i{flag}
 5471: WHILE
 5472:   @i{code2}
 5473: REPEAT
 5474: @end example
 5475: 
 5476: @i{code1} is executed and @i{flag} is computed. If it is true,
 5477: @i{code2} is executed and the loop is restarted; If @i{flag} is
 5478: false, execution continues after the @code{REPEAT}.
 5479: 
 5480: @cindex @code{UNTIL} loop
 5481: @example
 5482: BEGIN
 5483:   @i{code}
 5484:   @i{flag}
 5485: UNTIL
 5486: @end example
 5487: 
 5488: @i{code} is executed. The loop is restarted if @code{flag} is false.
 5489: 
 5490: @progstyle
 5491: To keep the code understandable, a complete iteration of the loop should
 5492: not change the number and types of the items on the stacks.
 5493: 
 5494: @cindex endless loop
 5495: @cindex loops, endless
 5496: @example
 5497: BEGIN
 5498:   @i{code}
 5499: AGAIN
 5500: @end example
 5501: 
 5502: This is an endless loop.
 5503: 
 5504: @node Counted Loops, Arbitrary control structures, Simple Loops, Control Structures
 5505: @subsection Counted Loops
 5506: @cindex counted loops
 5507: @cindex loops, counted
 5508: @cindex @code{DO} loops
 5509: 
 5510: The basic counted loop is:
 5511: @example
 5512: @i{limit} @i{start}
 5513: ?DO
 5514:   @i{body}
 5515: LOOP
 5516: @end example
 5517: 
 5518: This performs one iteration for every integer, starting from @i{start}
 5519: and up to, but excluding @i{limit}. The counter, or @i{index}, can be
 5520: accessed with @code{i}. For example, the loop:
 5521: @example
 5522: 10 0 ?DO
 5523:   i .
 5524: LOOP
 5525: @end example
 5526: @noindent
 5527: prints @code{0 1 2 3 4 5 6 7 8 9}
 5528: 
 5529: The index of the innermost loop can be accessed with @code{i}, the index
 5530: of the next loop with @code{j}, and the index of the third loop with
 5531: @code{k}.
 5532: 
 5533: 
 5534: doc-i
 5535: doc-j
 5536: doc-k
 5537: 
 5538: 
 5539: The loop control data are kept on the return stack, so there are some
 5540: restrictions on mixing return stack accesses and counted loop words. In
 5541: particuler, if you put values on the return stack outside the loop, you
 5542: cannot read them inside the loop@footnote{well, not in a way that is
 5543: portable.}. If you put values on the return stack within a loop, you
 5544: have to remove them before the end of the loop and before accessing the
 5545: index of the loop.
 5546: 
 5547: There are several variations on the counted loop:
 5548: 
 5549: @itemize @bullet
 5550: @item
 5551: @code{LEAVE} leaves the innermost counted loop immediately; execution
 5552: continues after the associated @code{LOOP} or @code{NEXT}. For example:
 5553: 
 5554: @example
 5555: 10 0 ?DO  i DUP . 3 = IF LEAVE THEN LOOP
 5556: @end example
 5557: prints @code{0 1 2 3}
 5558: 
 5559: 
 5560: @item
 5561: @code{UNLOOP} prepares for an abnormal loop exit, e.g., via
 5562: @code{EXIT}. @code{UNLOOP} removes the loop control parameters from the
 5563: return stack so @code{EXIT} can get to its return address. For example:
 5564: 
 5565: @example
 5566: : demo 10 0 ?DO i DUP . 3 = IF UNLOOP EXIT THEN LOOP ." Done" ;
 5567: @end example
 5568: prints @code{0 1 2 3}
 5569: 
 5570: 
 5571: @item
 5572: If @i{start} is greater than @i{limit}, a @code{?DO} loop is entered
 5573: (and @code{LOOP} iterates until they become equal by wrap-around
 5574: arithmetic). This behaviour is usually not what you want. Therefore,
 5575: Gforth offers @code{+DO} and @code{U+DO} (as replacements for
 5576: @code{?DO}), which do not enter the loop if @i{start} is greater than
 5577: @i{limit}; @code{+DO} is for signed loop parameters, @code{U+DO} for
 5578: unsigned loop parameters.
 5579: 
 5580: @item
 5581: @code{?DO} can be replaced by @code{DO}. @code{DO} always enters
 5582: the loop, independent of the loop parameters. Do not use @code{DO}, even
 5583: if you know that the loop is entered in any case. Such knowledge tends
 5584: to become invalid during maintenance of a program, and then the
 5585: @code{DO} will make trouble.
 5586: 
 5587: @item
 5588: @code{LOOP} can be replaced with @code{@i{n} +LOOP}; this updates the
 5589: index by @i{n} instead of by 1. The loop is terminated when the border
 5590: between @i{limit-1} and @i{limit} is crossed. E.g.:
 5591: 
 5592: @example
 5593: 4 0 +DO  i .  2 +LOOP
 5594: @end example
 5595: @noindent
 5596: prints @code{0 2}
 5597: 
 5598: @example
 5599: 4 1 +DO  i .  2 +LOOP
 5600: @end example
 5601: @noindent
 5602: prints @code{1 3}
 5603: 
 5604: @item
 5605: @cindex negative increment for counted loops
 5606: @cindex counted loops with negative increment
 5607: The behaviour of @code{@i{n} +LOOP} is peculiar when @i{n} is negative:
 5608: 
 5609: @example
 5610: -1 0 ?DO  i .  -1 +LOOP
 5611: @end example
 5612: @noindent
 5613: prints @code{0 -1}
 5614: 
 5615: @example
 5616: 0 0 ?DO  i .  -1 +LOOP
 5617: @end example
 5618: prints nothing.
 5619: 
 5620: Therefore we recommend avoiding @code{@i{n} +LOOP} with negative
 5621: @i{n}. One alternative is @code{@i{u} -LOOP}, which reduces the
 5622: index by @i{u} each iteration. The loop is terminated when the border
 5623: between @i{limit+1} and @i{limit} is crossed. Gforth also provides
 5624: @code{-DO} and @code{U-DO} for down-counting loops. E.g.:
 5625: 
 5626: @example
 5627: -2 0 -DO  i .  1 -LOOP
 5628: @end example
 5629: @noindent
 5630: prints @code{0 -1}
 5631: 
 5632: @example
 5633: -1 0 -DO  i .  1 -LOOP
 5634: @end example
 5635: @noindent
 5636: prints @code{0}
 5637: 
 5638: @example
 5639: 0 0 -DO  i .  1 -LOOP
 5640: @end example
 5641: @noindent
 5642: prints nothing.
 5643: 
 5644: @end itemize
 5645: 
 5646: Unfortunately, @code{+DO}, @code{U+DO}, @code{-DO}, @code{U-DO} and
 5647: @code{-LOOP} are not defined in ANS Forth. However, an implementation
 5648: for these words that uses only standard words is provided in
 5649: @file{compat/loops.fs}.
 5650: 
 5651: 
 5652: @cindex @code{FOR} loops
 5653: Another counted loop is:
 5654: @example
 5655: @i{n}
 5656: FOR
 5657:   @i{body}
 5658: NEXT
 5659: @end example
 5660: This is the preferred loop of native code compiler writers who are too
 5661: lazy to optimize @code{?DO} loops properly. This loop structure is not
 5662: defined in ANS Forth. In Gforth, this loop iterates @i{n+1} times;
 5663: @code{i} produces values starting with @i{n} and ending with 0. Other
 5664: Forth systems may behave differently, even if they support @code{FOR}
 5665: loops. To avoid problems, don't use @code{FOR} loops.
 5666: 
 5667: @node Arbitrary control structures, Calls and returns, Counted Loops, Control Structures
 5668: @subsection Arbitrary control structures
 5669: @cindex control structures, user-defined
 5670: 
 5671: @cindex control-flow stack
 5672: ANS Forth permits and supports using control structures in a non-nested
 5673: way. Information about incomplete control structures is stored on the
 5674: control-flow stack. This stack may be implemented on the Forth data
 5675: stack, and this is what we have done in Gforth.
 5676: 
 5677: @cindex @code{orig}, control-flow stack item
 5678: @cindex @code{dest}, control-flow stack item
 5679: An @i{orig} entry represents an unresolved forward branch, a @i{dest}
 5680: entry represents a backward branch target. A few words are the basis for
 5681: building any control structure possible (except control structures that
 5682: need storage, like calls, coroutines, and backtracking).
 5683: 
 5684: 
 5685: doc-if
 5686: doc-ahead
 5687: doc-then
 5688: doc-begin
 5689: doc-until
 5690: doc-again
 5691: doc-cs-pick
 5692: doc-cs-roll
 5693: 
 5694: 
 5695: The Standard words @code{CS-PICK} and @code{CS-ROLL} allow you to
 5696: manipulate the control-flow stack in a portable way. Without them, you
 5697: would need to know how many stack items are occupied by a control-flow
 5698: entry (many systems use one cell. In Gforth they currently take three,
 5699: but this may change in the future).
 5700: 
 5701: Some standard control structure words are built from these words:
 5702: 
 5703: 
 5704: doc-else
 5705: doc-while
 5706: doc-repeat
 5707: 
 5708: 
 5709: @noindent
 5710: Gforth adds some more control-structure words:
 5711: 
 5712: 
 5713: doc-endif
 5714: doc-?dup-if
 5715: doc-?dup-0=-if
 5716: 
 5717: 
 5718: @noindent
 5719: Counted loop words constitute a separate group of words:
 5720: 
 5721: 
 5722: doc-?do
 5723: doc-+do
 5724: doc-u+do
 5725: doc--do
 5726: doc-u-do
 5727: doc-do
 5728: doc-for
 5729: doc-loop
 5730: doc-+loop
 5731: doc--loop
 5732: doc-next
 5733: doc-leave
 5734: doc-?leave
 5735: doc-unloop
 5736: doc-done
 5737: 
 5738: 
 5739: The standard does not allow using @code{CS-PICK} and @code{CS-ROLL} on
 5740: @i{do-sys}. Gforth allows it, but it's your job to ensure that for
 5741: every @code{?DO} etc. there is exactly one @code{UNLOOP} on any path
 5742: through the definition (@code{LOOP} etc. compile an @code{UNLOOP} on the
 5743: fall-through path). Also, you have to ensure that all @code{LEAVE}s are
 5744: resolved (by using one of the loop-ending words or @code{DONE}).
 5745: 
 5746: @noindent
 5747: Another group of control structure words are:
 5748: 
 5749: 
 5750: doc-case
 5751: doc-endcase
 5752: doc-of
 5753: doc-endof
 5754: 
 5755: 
 5756: @i{case-sys} and @i{of-sys} cannot be processed using @code{CS-PICK} and
 5757: @code{CS-ROLL}.
 5758: 
 5759: @subsubsection Programming Style
 5760: @cindex control structures programming style
 5761: @cindex programming style, arbitrary control structures
 5762: 
 5763: In order to ensure readability we recommend that you do not create
 5764: arbitrary control structures directly, but define new control structure
 5765: words for the control structure you want and use these words in your
 5766: program. For example, instead of writing:
 5767: 
 5768: @example
 5769: BEGIN
 5770:   ...
 5771: IF [ 1 CS-ROLL ]
 5772:   ...
 5773: AGAIN THEN
 5774: @end example
 5775: 
 5776: @noindent
 5777: we recommend defining control structure words, e.g.,
 5778: 
 5779: @example
 5780: : WHILE ( DEST -- ORIG DEST )
 5781:  POSTPONE IF
 5782:  1 CS-ROLL ; immediate
 5783: 
 5784: : REPEAT ( orig dest -- )
 5785:  POSTPONE AGAIN
 5786:  POSTPONE THEN ; immediate
 5787: @end example
 5788: 
 5789: @noindent
 5790: and then using these to create the control structure:
 5791: 
 5792: @example
 5793: BEGIN
 5794:   ...
 5795: WHILE
 5796:   ...
 5797: REPEAT
 5798: @end example
 5799: 
 5800: That's much easier to read, isn't it? Of course, @code{REPEAT} and
 5801: @code{WHILE} are predefined, so in this example it would not be
 5802: necessary to define them.
 5803: 
 5804: @node Calls and returns, Exception Handling, Arbitrary control structures, Control Structures
 5805: @subsection Calls and returns
 5806: @cindex calling a definition
 5807: @cindex returning from a definition
 5808: 
 5809: @cindex recursive definitions
 5810: A definition can be called simply be writing the name of the definition
 5811: to be called. Normally a definition is invisible during its own
 5812: definition. If you want to write a directly recursive definition, you
 5813: can use @code{recursive} to make the current definition visible, or
 5814: @code{recurse} to call the current definition directly.
 5815: 
 5816: 
 5817: doc-recursive
 5818: doc-recurse
 5819: 
 5820: 
 5821: @comment TODO add example of the two recursion methods
 5822: @quotation
 5823: @progstyle
 5824: I prefer using @code{recursive} to @code{recurse}, because calling the
 5825: definition by name is more descriptive (if the name is well-chosen) than
 5826: the somewhat cryptic @code{recurse}.  E.g., in a quicksort
 5827: implementation, it is much better to read (and think) ``now sort the
 5828: partitions'' than to read ``now do a recursive call''.
 5829: @end quotation
 5830: 
 5831: For mutual recursion, use @code{Defer}red words, like this:
 5832: 
 5833: @example
 5834: Defer foo
 5835: 
 5836: : bar ( ... -- ... )
 5837:  ... foo ... ;
 5838: 
 5839: :noname ( ... -- ... )
 5840:  ... bar ... ;
 5841: IS foo
 5842: @end example
 5843: 
 5844: Deferred words are discussed in more detail in @ref{Deferred words}.
 5845: 
 5846: The current definition returns control to the calling definition when
 5847: the end of the definition is reached or @code{EXIT} is encountered.
 5848: 
 5849: doc-exit
 5850: doc-;s
 5851: 
 5852: 
 5853: @node Exception Handling,  , Calls and returns, Control Structures
 5854: @subsection Exception Handling
 5855: @cindex exceptions
 5856: 
 5857: @c quit is a very bad idea for error handling, 
 5858: @c because it does not translate into a THROW
 5859: @c it also does not belong into this chapter
 5860: 
 5861: If a word detects an error condition that it cannot handle, it can
 5862: @code{throw} an exception.  In the simplest case, this will terminate
 5863: your program, and report an appropriate error.
 5864: 
 5865: doc-throw
 5866: 
 5867: @code{Throw} consumes a cell-sized error number on the stack. There are
 5868: some predefined error numbers in ANS Forth (see @file{errors.fs}).  In
 5869: Gforth (and most other systems) you can use the iors produced by various
 5870: words as error numbers (e.g., a typical use of @code{allocate} is
 5871: @code{allocate throw}).  Gforth also provides the word @code{exception}
 5872: to define your own error numbers (with decent error reporting); an ANS
 5873: Forth version of this word (but without the error messages) is available
 5874: in @code{compat/except.fs}.  And finally, you can use your own error
 5875: numbers (anything outside the range -4095..0), but won't get nice error
 5876: messages, only numbers.  For example, try:
 5877: 
 5878: @example
 5879: -10 throw                    \ ANS defined
 5880: -267 throw                   \ system defined
 5881: s" my error" exception throw \ user defined
 5882: 7 throw                      \ arbitrary number
 5883: @end example
 5884: 
 5885: doc---exception-exception
 5886: 
 5887: A common idiom to @code{THROW} a specific error if a flag is true is
 5888: this:
 5889: 
 5890: @example
 5891: @code{( flag ) 0<> @i{errno} and throw}
 5892: @end example
 5893: 
 5894: Your program can provide exception handlers to catch exceptions.  An
 5895: exception handler can be used to correct the problem, or to clean up
 5896: some data structures and just throw the exception to the next exception
 5897: handler.  Note that @code{throw} jumps to the dynamically innermost
 5898: exception handler.  The system's exception handler is outermost, and just
 5899: prints an error and restarts command-line interpretation (or, in batch
 5900: mode (i.e., while processing the shell command line), leaves Gforth).
 5901: 
 5902: The ANS Forth way to catch exceptions is @code{catch}:
 5903: 
 5904: doc-catch
 5905: 
 5906: The most common use of exception handlers is to clean up the state when
 5907: an error happens.  E.g.,
 5908: 
 5909: @example
 5910: base @ >r hex \ actually the hex should be inside foo, or we h
 5911: ['] foo catch ( nerror|0 )
 5912: r> base !
 5913: ( nerror|0 ) throw \ pass it on
 5914: @end example
 5915: 
 5916: A use of @code{catch} for handling the error @code{myerror} might look
 5917: like this:
 5918: 
 5919: @example
 5920: ['] foo catch
 5921: CASE
 5922:   myerror OF ... ( do something about it ) ENDOF
 5923:   dup throw \ default: pass other errors on, do nothing on non-errors
 5924: ENDCASE
 5925: @end example
 5926: 
 5927: Having to wrap the code into a separate word is often cumbersome,
 5928: therefore Gforth provides an alternative syntax:
 5929: 
 5930: @example
 5931: TRY
 5932:   @i{code1}
 5933: RECOVER     \ optional
 5934:   @i{code2} \ optional
 5935: ENDTRY
 5936: @end example
 5937: 
 5938: This performs @i{Code1}.  If @i{code1} completes normally, execution
 5939: continues after the @code{endtry}.  If @i{Code1} throws, the stacks are
 5940: reset to the state during @code{try}, the throw value is pushed on the
 5941: data stack, and execution constinues at @i{code2}, and finally falls
 5942: through the @code{endtry} into the following code. If there is no
 5943: @code{recover} clause, this works like an empty recover clause.
 5944: 
 5945: doc-try
 5946: doc-recover
 5947: doc-endtry
 5948: 
 5949: The cleanup example from above in this syntax:
 5950: 
 5951: @example
 5952: base @ >r TRY
 5953:   hex foo \ now the hex is placed correctly
 5954:   0       \ value for throw
 5955: ENDTRY
 5956: r> base ! throw
 5957: @end example
 5958: 
 5959: And here's the error handling example:
 5960: 
 5961: @example
 5962: TRY
 5963:   foo
 5964: RECOVER
 5965:   CASE
 5966:     myerror OF ... ( do something about it ) ENDOF
 5967:     throw \ pass other errors on
 5968:   ENDCASE
 5969: ENDTRY
 5970: @end example
 5971: 
 5972: @progstyle
 5973: As usual, you should ensure that the stack depth is statically known at
 5974: the end: either after the @code{throw} for passing on errors, or after
 5975: the @code{ENDTRY} (or, if you use @code{catch}, after the end of the
 5976: selection construct for handling the error).
 5977: 
 5978: There are two alternatives to @code{throw}: @code{Abort"} is conditional
 5979: and you can provide an error message.  @code{Abort} just produces an
 5980: ``Aborted'' error.
 5981: 
 5982: The problem with these words is that exception handlers cannot
 5983: differentiate between different @code{abort"}s; they just look like
 5984: @code{-2 throw} to them (the error message cannot be accessed by
 5985: standard programs).  Similar @code{abort} looks like @code{-1 throw} to
 5986: exception handlers.
 5987: 
 5988: doc-abort"
 5989: doc-abort
 5990: 
 5991: 
 5992: 
 5993: @c -------------------------------------------------------------
 5994: @node Defining Words, Interpretation and Compilation Semantics, Control Structures, Words
 5995: @section Defining Words
 5996: @cindex defining words
 5997: 
 5998: Defining words are used to extend Forth by creating new entries in the dictionary.
 5999: 
 6000: @menu
 6001: * CREATE::                      
 6002: * Variables::                   Variables and user variables
 6003: * Constants::                   
 6004: * Values::                      Initialised variables
 6005: * Colon Definitions::           
 6006: * Anonymous Definitions::       Definitions without names
 6007: * Supplying names::             Passing definition names as strings
 6008: * User-defined Defining Words::  
 6009: * Deferred words::              Allow forward references
 6010: * Aliases::                     
 6011: @end menu
 6012: 
 6013: @node CREATE, Variables, Defining Words, Defining Words
 6014: @subsection @code{CREATE}
 6015: @cindex simple defining words
 6016: @cindex defining words, simple
 6017: 
 6018: Defining words are used to create new entries in the dictionary. The
 6019: simplest defining word is @code{CREATE}. @code{CREATE} is used like
 6020: this:
 6021: 
 6022: @example
 6023: CREATE new-word1
 6024: @end example
 6025: 
 6026: @code{CREATE} is a parsing word, i.e., it takes an argument from the
 6027: input stream (@code{new-word1} in our example).  It generates a
 6028: dictionary entry for @code{new-word1}. When @code{new-word1} is
 6029: executed, all that it does is leave an address on the stack. The address
 6030: represents the value of the data space pointer (@code{HERE}) at the time
 6031: that @code{new-word1} was defined. Therefore, @code{CREATE} is a way of
 6032: associating a name with the address of a region of memory.
 6033: 
 6034: doc-create
 6035: 
 6036: Note that in ANS Forth guarantees only for @code{create} that its body
 6037: is in dictionary data space (i.e., where @code{here}, @code{allot}
 6038: etc. work, @pxref{Dictionary allocation}).  Also, in ANS Forth only
 6039: @code{create}d words can be modified with @code{does>}
 6040: (@pxref{User-defined Defining Words}).  And in ANS Forth @code{>body}
 6041: can only be applied to @code{create}d words.
 6042: 
 6043: By extending this example to reserve some memory in data space, we end
 6044: up with something like a @i{variable}. Here are two different ways to do
 6045: it:
 6046: 
 6047: @example
 6048: CREATE new-word2 1 cells allot  \ reserve 1 cell - initial value undefined
 6049: CREATE new-word3 4 ,            \ reserve 1 cell and initialise it (to 4)
 6050: @end example
 6051: 
 6052: The variable can be examined and modified using @code{@@} (``fetch'') and
 6053: @code{!} (``store'') like this:
 6054: 
 6055: @example
 6056: new-word2 @@ .      \ get address, fetch from it and display
 6057: 1234 new-word2 !   \ new value, get address, store to it
 6058: @end example
 6059: 
 6060: @cindex arrays
 6061: A similar mechanism can be used to create arrays. For example, an
 6062: 80-character text input buffer:
 6063: 
 6064: @example
 6065: CREATE text-buf 80 chars allot
 6066: 
 6067: text-buf 0 chars c@@ \ the 1st character (offset 0)
 6068: text-buf 3 chars c@@ \ the 4th character (offset 3)
 6069: @end example
 6070: 
 6071: You can build arbitrarily complex data structures by allocating
 6072: appropriate areas of memory. For further discussions of this, and to
 6073: learn about some Gforth tools that make it easier,
 6074: @xref{Structures}.
 6075: 
 6076: 
 6077: @node Variables, Constants, CREATE, Defining Words
 6078: @subsection Variables
 6079: @cindex variables
 6080: 
 6081: The previous section showed how a sequence of commands could be used to
 6082: generate a variable.  As a final refinement, the whole code sequence can
 6083: be wrapped up in a defining word (pre-empting the subject of the next
 6084: section), making it easier to create new variables:
 6085: 
 6086: @example
 6087: : myvariableX ( "name" -- a-addr ) CREATE 1 cells allot ;
 6088: : myvariable0 ( "name" -- a-addr ) CREATE 0 , ;
 6089: 
 6090: myvariableX foo \ variable foo starts off with an unknown value
 6091: myvariable0 joe \ whilst joe is initialised to 0
 6092: 
 6093: 45 3 * foo !   \ set foo to 135
 6094: 1234 joe !     \ set joe to 1234
 6095: 3 joe +!       \ increment joe by 3.. to 1237
 6096: @end example
 6097: 
 6098: Not surprisingly, there is no need to define @code{myvariable}, since
 6099: Forth already has a definition @code{Variable}. ANS Forth does not
 6100: guarantee that a @code{Variable} is initialised when it is created
 6101: (i.e., it may behave like @code{myvariableX}). In contrast, Gforth's
 6102: @code{Variable} initialises the variable to 0 (i.e., it behaves exactly
 6103: like @code{myvariable0}). Forth also provides @code{2Variable} and
 6104: @code{fvariable} for double and floating-point variables, respectively
 6105: -- they are initialised to 0. and 0e in Gforth. If you use a @code{Variable} to
 6106: store a boolean, you can use @code{on} and @code{off} to toggle its
 6107: state.
 6108: 
 6109: doc-variable
 6110: doc-2variable
 6111: doc-fvariable
 6112: 
 6113: @cindex user variables
 6114: @cindex user space
 6115: The defining word @code{User} behaves in the same way as @code{Variable}.
 6116: The difference is that it reserves space in @i{user (data) space} rather
 6117: than normal data space. In a Forth system that has a multi-tasker, each
 6118: task has its own set of user variables.
 6119: 
 6120: doc-user
 6121: @c doc-udp
 6122: @c doc-uallot
 6123: 
 6124: @comment TODO is that stuff about user variables strictly correct? Is it
 6125: @comment just terminal tasks that have user variables?
 6126: @comment should document tasker.fs (with some examples) elsewhere
 6127: @comment in this manual, then expand on user space and user variables.
 6128: 
 6129: @node Constants, Values, Variables, Defining Words
 6130: @subsection Constants
 6131: @cindex constants
 6132: 
 6133: @code{Constant} allows you to declare a fixed value and refer to it by
 6134: name. For example:
 6135: 
 6136: @example
 6137: 12 Constant INCHES-PER-FOOT
 6138: 3E+08 fconstant SPEED-O-LIGHT
 6139: @end example
 6140: 
 6141: A @code{Variable} can be both read and written, so its run-time
 6142: behaviour is to supply an address through which its current value can be
 6143: manipulated. In contrast, the value of a @code{Constant} cannot be
 6144: changed once it has been declared@footnote{Well, often it can be -- but
 6145: not in a Standard, portable way. It's safer to use a @code{Value} (read
 6146: on).} so it's not necessary to supply the address -- it is more
 6147: efficient to return the value of the constant directly. That's exactly
 6148: what happens; the run-time effect of a constant is to put its value on
 6149: the top of the stack (You can find one
 6150: way of implementing @code{Constant} in @ref{User-defined Defining Words}).
 6151: 
 6152: Forth also provides @code{2Constant} and @code{fconstant} for defining
 6153: double and floating-point constants, respectively.
 6154: 
 6155: doc-constant
 6156: doc-2constant
 6157: doc-fconstant
 6158: 
 6159: @c that's too deep, and it's not necessarily true for all ANS Forths. - anton
 6160: @c nac-> How could that not be true in an ANS Forth? You can't define a
 6161: @c constant, use it and then delete the definition of the constant..
 6162: 
 6163: @c anton->An ANS Forth system can compile a constant to a literal; On
 6164: @c decompilation you would see only the number, just as if it had been used
 6165: @c in the first place.  The word will stay, of course, but it will only be
 6166: @c used by the text interpreter (no run-time duties, except when it is 
 6167: @c POSTPONEd or somesuch).
 6168: 
 6169: @c nac:
 6170: @c I agree that it's rather deep, but IMO it is an important difference
 6171: @c relative to other programming languages.. often it's annoying: it
 6172: @c certainly changes my programming style relative to C.
 6173: 
 6174: @c anton: In what way?
 6175: 
 6176: Constants in Forth behave differently from their equivalents in other
 6177: programming languages. In other languages, a constant (such as an EQU in
 6178: assembler or a #define in C) only exists at compile-time; in the
 6179: executable program the constant has been translated into an absolute
 6180: number and, unless you are using a symbolic debugger, it's impossible to
 6181: know what abstract thing that number represents. In Forth a constant has
 6182: an entry in the header space and remains there after the code that uses
 6183: it has been defined. In fact, it must remain in the dictionary since it
 6184: has run-time duties to perform. For example:
 6185: 
 6186: @example
 6187: 12 Constant INCHES-PER-FOOT
 6188: : FEET-TO-INCHES ( n1 -- n2 ) INCHES-PER-FOOT * ;
 6189: @end example
 6190: 
 6191: @cindex in-lining of constants
 6192: When @code{FEET-TO-INCHES} is executed, it will in turn execute the xt
 6193: associated with the constant @code{INCHES-PER-FOOT}. If you use
 6194: @code{see} to decompile the definition of @code{FEET-TO-INCHES}, you can
 6195: see that it makes a call to @code{INCHES-PER-FOOT}. Some Forth compilers
 6196: attempt to optimise constants by in-lining them where they are used. You
 6197: can force Gforth to in-line a constant like this:
 6198: 
 6199: @example
 6200: : FEET-TO-INCHES ( n1 -- n2 ) [ INCHES-PER-FOOT ] LITERAL * ;
 6201: @end example
 6202: 
 6203: If you use @code{see} to decompile @i{this} version of
 6204: @code{FEET-TO-INCHES}, you can see that @code{INCHES-PER-FOOT} is no
 6205: longer present. To understand how this works, read
 6206: @ref{Interpret/Compile states}, and @ref{Literals}.
 6207: 
 6208: In-lining constants in this way might improve execution time
 6209: fractionally, and can ensure that a constant is now only referenced at
 6210: compile-time. However, the definition of the constant still remains in
 6211: the dictionary. Some Forth compilers provide a mechanism for controlling
 6212: a second dictionary for holding transient words such that this second
 6213: dictionary can be deleted later in order to recover memory
 6214: space. However, there is no standard way of doing this.
 6215: 
 6216: 
 6217: @node Values, Colon Definitions, Constants, Defining Words
 6218: @subsection Values
 6219: @cindex values
 6220: 
 6221: A @code{Value} behaves like a @code{Constant}, but it can be changed.
 6222: @code{TO} is a parsing word that changes a @code{Values}.  In Gforth
 6223: (not in ANS Forth) you can access (and change) a @code{value} also with
 6224: @code{>body}.
 6225: 
 6226: Here are some
 6227: examples:
 6228: 
 6229: @example
 6230: 12 Value APPLES     \ Define APPLES with an initial value of 12
 6231: 34 TO APPLES        \ Change the value of APPLES. TO is a parsing word
 6232: 1 ' APPLES >body +! \ Increment APPLES.  Non-standard usage.
 6233: APPLES              \ puts 35 on the top of the stack.
 6234: @end example
 6235: 
 6236: doc-value
 6237: doc-to
 6238: 
 6239: 
 6240: 
 6241: @node Colon Definitions, Anonymous Definitions, Values, Defining Words
 6242: @subsection Colon Definitions
 6243: @cindex colon definitions
 6244: 
 6245: @example
 6246: : name ( ... -- ... )
 6247:     word1 word2 word3 ;
 6248: @end example
 6249: 
 6250: @noindent
 6251: Creates a word called @code{name} that, upon execution, executes
 6252: @code{word1 word2 word3}. @code{name} is a @dfn{(colon) definition}.
 6253: 
 6254: The explanation above is somewhat superficial. For simple examples of
 6255: colon definitions see @ref{Your first definition}.  For an in-depth
 6256: discussion of some of the issues involved, @xref{Interpretation and
 6257: Compilation Semantics}.
 6258: 
 6259: doc-:
 6260: doc-;
 6261: 
 6262: 
 6263: @node Anonymous Definitions, Supplying names, Colon Definitions, Defining Words
 6264: @subsection Anonymous Definitions
 6265: @cindex colon definitions
 6266: @cindex defining words without name
 6267: 
 6268: Sometimes you want to define an @dfn{anonymous word}; a word without a
 6269: name. You can do this with:
 6270: 
 6271: doc-:noname
 6272: 
 6273: This leaves the execution token for the word on the stack after the
 6274: closing @code{;}. Here's an example in which a deferred word is
 6275: initialised with an @code{xt} from an anonymous colon definition:
 6276: 
 6277: @example
 6278: Defer deferred
 6279: :noname ( ... -- ... )
 6280:   ... ;
 6281: IS deferred
 6282: @end example
 6283: 
 6284: @noindent
 6285: Gforth provides an alternative way of doing this, using two separate
 6286: words:
 6287: 
 6288: doc-noname
 6289: @cindex execution token of last defined word
 6290: doc-lastxt
 6291: 
 6292: @noindent
 6293: The previous example can be rewritten using @code{noname} and
 6294: @code{lastxt}:
 6295: 
 6296: @example
 6297: Defer deferred
 6298: noname : ( ... -- ... )
 6299:   ... ;
 6300: lastxt IS deferred
 6301: @end example
 6302: 
 6303: @noindent
 6304: @code{noname} works with any defining word, not just @code{:}.
 6305: 
 6306: @code{lastxt} also works when the last word was not defined as
 6307: @code{noname}.  It does not work for combined words, though.  It also has
 6308: the useful property that is is valid as soon as the header for a
 6309: definition has been built. Thus:
 6310: 
 6311: @example
 6312: lastxt . : foo [ lastxt . ] ; ' foo .
 6313: @end example
 6314: 
 6315: @noindent
 6316: prints 3 numbers; the last two are the same.
 6317: 
 6318: @node Supplying names, User-defined Defining Words, Anonymous Definitions, Defining Words
 6319: @subsection Supplying the name of a defined word
 6320: @cindex names for defined words
 6321: @cindex defining words, name given in a string
 6322: 
 6323: By default, a defining word takes the name for the defined word from the
 6324: input stream. Sometimes you want to supply the name from a string. You
 6325: can do this with:
 6326: 
 6327: doc-nextname
 6328: 
 6329: For example:
 6330: 
 6331: @example
 6332: s" foo" nextname create
 6333: @end example
 6334: 
 6335: @noindent
 6336: is equivalent to:
 6337: 
 6338: @example
 6339: create foo
 6340: @end example
 6341: 
 6342: @noindent
 6343: @code{nextname} works with any defining word.
 6344: 
 6345: 
 6346: @node User-defined Defining Words, Deferred words, Supplying names, Defining Words
 6347: @subsection User-defined Defining Words
 6348: @cindex user-defined defining words
 6349: @cindex defining words, user-defined
 6350: 
 6351: You can create a new defining word by wrapping defining-time code around
 6352: an existing defining word and putting the sequence in a colon
 6353: definition. 
 6354: 
 6355: @c anton: This example is very complex and leads in a quite different
 6356: @c direction from the CREATE-DOES> stuff that follows.  It should probably
 6357: @c be done elsewhere, or as a subsubsection of this subsection (or as a
 6358: @c subsection of Defining Words)
 6359: 
 6360: For example, suppose that you have a word @code{stats} that
 6361: gathers statistics about colon definitions given the @i{xt} of the
 6362: definition, and you want every colon definition in your application to
 6363: make a call to @code{stats}. You can define and use a new version of
 6364: @code{:} like this:
 6365: 
 6366: @example
 6367: : stats ( xt -- ) DUP ." (Gathering statistics for " . ." )"
 6368:   ... ;  \ other code
 6369: 
 6370: : my: : lastxt postpone literal ['] stats compile, ;
 6371: 
 6372: my: foo + - ;
 6373: @end example
 6374: 
 6375: When @code{foo} is defined using @code{my:} these steps occur:
 6376: 
 6377: @itemize @bullet
 6378: @item
 6379: @code{my:} is executed.
 6380: @item
 6381: The @code{:} within the definition (the one between @code{my:} and
 6382: @code{lastxt}) is executed, and does just what it always does; it parses
 6383: the input stream for a name, builds a dictionary header for the name
 6384: @code{foo} and switches @code{state} from interpret to compile.
 6385: @item
 6386: The word @code{lastxt} is executed. It puts the @i{xt} for the word that is
 6387: being defined -- @code{foo} -- onto the stack.
 6388: @item
 6389: The code that was produced by @code{postpone literal} is executed; this
 6390: causes the value on the stack to be compiled as a literal in the code
 6391: area of @code{foo}.
 6392: @item
 6393: The code @code{['] stats} compiles a literal into the definition of
 6394: @code{my:}. When @code{compile,} is executed, that literal -- the
 6395: execution token for @code{stats} -- is layed down in the code area of
 6396: @code{foo} , following the literal@footnote{Strictly speaking, the
 6397: mechanism that @code{compile,} uses to convert an @i{xt} into something
 6398: in the code area is implementation-dependent. A threaded implementation
 6399: might spit out the execution token directly whilst another
 6400: implementation might spit out a native code sequence.}.
 6401: @item
 6402: At this point, the execution of @code{my:} is complete, and control
 6403: returns to the text interpreter. The text interpreter is in compile
 6404: state, so subsequent text @code{+ -} is compiled into the definition of
 6405: @code{foo} and the @code{;} terminates the definition as always.
 6406: @end itemize
 6407: 
 6408: You can use @code{see} to decompile a word that was defined using
 6409: @code{my:} and see how it is different from a normal @code{:}
 6410: definition. For example:
 6411: 
 6412: @example
 6413: : bar + - ;  \ like foo but using : rather than my:
 6414: see bar
 6415: : bar
 6416:   + - ;
 6417: see foo
 6418: : foo
 6419:   107645672 stats + - ;
 6420: 
 6421: \ use ' stats . to show that 107645672 is the xt for stats
 6422: @end example
 6423: 
 6424: You can use techniques like this to make new defining words in terms of
 6425: @i{any} existing defining word.
 6426: 
 6427: 
 6428: @cindex defining defining words
 6429: @cindex @code{CREATE} ... @code{DOES>}
 6430: If you want the words defined with your defining words to behave
 6431: differently from words defined with standard defining words, you can
 6432: write your defining word like this:
 6433: 
 6434: @example
 6435: : def-word ( "name" -- )
 6436:     CREATE @i{code1}
 6437: DOES> ( ... -- ... )
 6438:     @i{code2} ;
 6439: 
 6440: def-word name
 6441: @end example
 6442: 
 6443: @cindex child words
 6444: This fragment defines a @dfn{defining word} @code{def-word} and then
 6445: executes it.  When @code{def-word} executes, it @code{CREATE}s a new
 6446: word, @code{name}, and executes the code @i{code1}. The code @i{code2}
 6447: is not executed at this time. The word @code{name} is sometimes called a
 6448: @dfn{child} of @code{def-word}.
 6449: 
 6450: When you execute @code{name}, the address of the body of @code{name} is
 6451: put on the data stack and @i{code2} is executed (the address of the body
 6452: of @code{name} is the address @code{HERE} returns immediately after the
 6453: @code{CREATE}, i.e., the address a @code{create}d word returns by
 6454: default).
 6455: 
 6456: @c anton:
 6457: @c www.dictionary.com says:
 6458: @c at·a·vism: 1.The reappearance of a characteristic in an organism after
 6459: @c several generations of absence, usually caused by the chance
 6460: @c recombination of genes.  2.An individual or a part that exhibits
 6461: @c atavism. Also called throwback.  3.The return of a trait or recurrence
 6462: @c of previous behavior after a period of absence.
 6463: @c
 6464: @c Doesn't seem to fit.
 6465: 
 6466: @c @cindex atavism in child words
 6467: You can use @code{def-word} to define a set of child words that behave
 6468: similarly; they all have a common run-time behaviour determined by
 6469: @i{code2}. Typically, the @i{code1} sequence builds a data area in the
 6470: body of the child word. The structure of the data is common to all
 6471: children of @code{def-word}, but the data values are specific -- and
 6472: private -- to each child word. When a child word is executed, the
 6473: address of its private data area is passed as a parameter on TOS to be
 6474: used and manipulated@footnote{It is legitimate both to read and write to
 6475: this data area.} by @i{code2}.
 6476: 
 6477: The two fragments of code that make up the defining words act (are
 6478: executed) at two completely separate times:
 6479: 
 6480: @itemize @bullet
 6481: @item
 6482: At @i{define time}, the defining word executes @i{code1} to generate a
 6483: child word
 6484: @item
 6485: At @i{child execution time}, when a child word is invoked, @i{code2}
 6486: is executed, using parameters (data) that are private and specific to
 6487: the child word.
 6488: @end itemize
 6489: 
 6490: Another way of understanding the behaviour of @code{def-word} and
 6491: @code{name} is to say that, if you make the following definitions:
 6492: @example
 6493: : def-word1 ( "name" -- )
 6494:     CREATE @i{code1} ;
 6495: 
 6496: : action1 ( ... -- ... )
 6497:     @i{code2} ;
 6498: 
 6499: def-word1 name1
 6500: @end example
 6501: 
 6502: @noindent
 6503: Then using @code{name1 action1} is equivalent to using @code{name}.
 6504: 
 6505: The classic example is that you can define @code{CONSTANT} in this way:
 6506: 
 6507: @example
 6508: : CONSTANT ( w "name" -- )
 6509:     CREATE ,
 6510: DOES> ( -- w )
 6511:     @@ ;
 6512: @end example
 6513: 
 6514: @comment There is a beautiful description of how this works and what
 6515: @comment it does in the Forthwrite 100th edition.. as well as an elegant
 6516: @comment commentary on the Counting Fruits problem.
 6517: 
 6518: When you create a constant with @code{5 CONSTANT five}, a set of
 6519: define-time actions take place; first a new word @code{five} is created,
 6520: then the value 5 is laid down in the body of @code{five} with
 6521: @code{,}. When @code{five} is executed, the address of the body is put on
 6522: the stack, and @code{@@} retrieves the value 5. The word @code{five} has
 6523: no code of its own; it simply contains a data field and a pointer to the
 6524: code that follows @code{DOES>} in its defining word. That makes words
 6525: created in this way very compact.
 6526: 
 6527: The final example in this section is intended to remind you that space
 6528: reserved in @code{CREATE}d words is @i{data} space and therefore can be
 6529: both read and written by a Standard program@footnote{Exercise: use this
 6530: example as a starting point for your own implementation of @code{Value}
 6531: and @code{TO} -- if you get stuck, investigate the behaviour of @code{'} and
 6532: @code{[']}.}:
 6533: 
 6534: @example
 6535: : foo ( "name" -- )
 6536:     CREATE -1 ,
 6537: DOES> ( -- )
 6538:     @@ . ;
 6539: 
 6540: foo first-word
 6541: foo second-word
 6542: 
 6543: 123 ' first-word >BODY !
 6544: @end example
 6545: 
 6546: If @code{first-word} had been a @code{CREATE}d word, we could simply
 6547: have executed it to get the address of its data field. However, since it
 6548: was defined to have @code{DOES>} actions, its execution semantics are to
 6549: perform those @code{DOES>} actions. To get the address of its data field
 6550: it's necessary to use @code{'} to get its xt, then @code{>BODY} to
 6551: translate the xt into the address of the data field.  When you execute
 6552: @code{first-word}, it will display @code{123}. When you execute
 6553: @code{second-word} it will display @code{-1}.
 6554: 
 6555: @cindex stack effect of @code{DOES>}-parts
 6556: @cindex @code{DOES>}-parts, stack effect
 6557: In the examples above the stack comment after the @code{DOES>} specifies
 6558: the stack effect of the defined words, not the stack effect of the
 6559: following code (the following code expects the address of the body on
 6560: the top of stack, which is not reflected in the stack comment). This is
 6561: the convention that I use and recommend (it clashes a bit with using
 6562: locals declarations for stack effect specification, though).
 6563: 
 6564: @menu
 6565: * CREATE..DOES> applications::  
 6566: * CREATE..DOES> details::       
 6567: * Advanced does> usage example::  
 6568: @end menu
 6569: 
 6570: @node CREATE..DOES> applications, CREATE..DOES> details, User-defined Defining Words, User-defined Defining Words
 6571: @subsubsection Applications of @code{CREATE..DOES>}
 6572: @cindex @code{CREATE} ... @code{DOES>}, applications
 6573: 
 6574: You may wonder how to use this feature. Here are some usage patterns:
 6575: 
 6576: @cindex factoring similar colon definitions
 6577: When you see a sequence of code occurring several times, and you can
 6578: identify a meaning, you will factor it out as a colon definition. When
 6579: you see similar colon definitions, you can factor them using
 6580: @code{CREATE..DOES>}. E.g., an assembler usually defines several words
 6581: that look very similar:
 6582: @example
 6583: : ori, ( reg-target reg-source n -- )
 6584:     0 asm-reg-reg-imm ;
 6585: : andi, ( reg-target reg-source n -- )
 6586:     1 asm-reg-reg-imm ;
 6587: @end example
 6588: 
 6589: @noindent
 6590: This could be factored with:
 6591: @example
 6592: : reg-reg-imm ( op-code -- )
 6593:     CREATE ,
 6594: DOES> ( reg-target reg-source n -- )
 6595:     @@ asm-reg-reg-imm ;
 6596: 
 6597: 0 reg-reg-imm ori,
 6598: 1 reg-reg-imm andi,
 6599: @end example
 6600: 
 6601: @cindex currying
 6602: Another view of @code{CREATE..DOES>} is to consider it as a crude way to
 6603: supply a part of the parameters for a word (known as @dfn{currying} in
 6604: the functional language community). E.g., @code{+} needs two
 6605: parameters. Creating versions of @code{+} with one parameter fixed can
 6606: be done like this:
 6607: 
 6608: @example
 6609: : curry+ ( n1 "name" -- )
 6610:     CREATE ,
 6611: DOES> ( n2 -- n1+n2 )
 6612:     @@ + ;
 6613: 
 6614:  3 curry+ 3+
 6615: -2 curry+ 2-
 6616: @end example
 6617: 
 6618: @node CREATE..DOES> details, Advanced does> usage example, CREATE..DOES> applications, User-defined Defining Words
 6619: @subsubsection The gory details of @code{CREATE..DOES>}
 6620: @cindex @code{CREATE} ... @code{DOES>}, details
 6621: 
 6622: doc-does>
 6623: 
 6624: @cindex @code{DOES>} in a separate definition
 6625: This means that you need not use @code{CREATE} and @code{DOES>} in the
 6626: same definition; you can put the @code{DOES>}-part in a separate
 6627: definition. This allows us to, e.g., select among different @code{DOES>}-parts:
 6628: @example
 6629: : does1 
 6630: DOES> ( ... -- ... )
 6631:     ... ;
 6632: 
 6633: : does2
 6634: DOES> ( ... -- ... )
 6635:     ... ;
 6636: 
 6637: : def-word ( ... -- ... )
 6638:     create ...
 6639:     IF
 6640:        does1
 6641:     ELSE
 6642:        does2
 6643:     ENDIF ;
 6644: @end example
 6645: 
 6646: In this example, the selection of whether to use @code{does1} or
 6647: @code{does2} is made at definition-time; at the time that the child word is
 6648: @code{CREATE}d.
 6649: 
 6650: @cindex @code{DOES>} in interpretation state
 6651: In a standard program you can apply a @code{DOES>}-part only if the last
 6652: word was defined with @code{CREATE}. In Gforth, the @code{DOES>}-part
 6653: will override the behaviour of the last word defined in any case. In a
 6654: standard program, you can use @code{DOES>} only in a colon
 6655: definition. In Gforth, you can also use it in interpretation state, in a
 6656: kind of one-shot mode; for example:
 6657: @example
 6658: CREATE name ( ... -- ... )
 6659:   @i{initialization}
 6660: DOES>
 6661:   @i{code} ;
 6662: @end example
 6663: 
 6664: @noindent
 6665: is equivalent to the standard:
 6666: @example
 6667: :noname
 6668: DOES>
 6669:     @i{code} ;
 6670: CREATE name EXECUTE ( ... -- ... )
 6671:     @i{initialization}
 6672: @end example
 6673: 
 6674: doc->body
 6675: 
 6676: @node Advanced does> usage example,  , CREATE..DOES> details, User-defined Defining Words
 6677: @subsubsection Advanced does> usage example
 6678: 
 6679: The MIPS disassembler (@file{arch/mips/disasm.fs}) contains many words
 6680: for disassembling instructions, that follow a very repetetive scheme:
 6681: 
 6682: @example
 6683: :noname @var{disasm-operands} s" @var{inst-name}" type ;
 6684: @var{entry-num} cells @var{table} + !
 6685: @end example
 6686: 
 6687: Of course, this inspires the idea to factor out the commonalities to
 6688: allow a definition like
 6689: 
 6690: @example
 6691: @var{disasm-operands} @var{entry-num} @var{table} define-inst @var{inst-name}
 6692: @end example
 6693: 
 6694: The parameters @var{disasm-operands} and @var{table} are usually
 6695: correlated.  Moreover, before I wrote the disassembler, there already
 6696: existed code that defines instructions like this:
 6697: 
 6698: @example
 6699: @var{entry-num} @var{inst-format} @var{inst-name}
 6700: @end example
 6701: 
 6702: This code comes from the assembler and resides in
 6703: @file{arch/mips/insts.fs}.
 6704: 
 6705: So I had to define the @var{inst-format} words that performed the scheme
 6706: above when executed.  At first I chose to use run-time code-generation:
 6707: 
 6708: @example
 6709: : @var{inst-format} ( entry-num "name" -- ; compiled code: addr w -- )
 6710:   :noname Postpone @var{disasm-operands}
 6711:   name Postpone sliteral Postpone type Postpone ;
 6712:   swap cells @var{table} + ! ;
 6713: @end example
 6714: 
 6715: Note that this supplies the other two parameters of the scheme above.
 6716: 
 6717: An alternative would have been to write this using
 6718: @code{create}/@code{does>}:
 6719: 
 6720: @example
 6721: : @var{inst-format} ( entry-num "name" -- )
 6722:   here name string, ( entry-num c-addr ) \ parse and save "name"
 6723:   noname create , ( entry-num )
 6724:   lastxt swap cells @var{table} + !
 6725: does> ( addr w -- )
 6726:   \ disassemble instruction w at addr
 6727:   @@ >r 
 6728:   @var{disasm-operands}
 6729:   r> count type ;
 6730: @end example
 6731: 
 6732: Somehow the first solution is simpler, mainly because it's simpler to
 6733: shift a string from definition-time to use-time with @code{sliteral}
 6734: than with @code{string,} and friends.
 6735: 
 6736: I wrote a lot of words following this scheme and soon thought about
 6737: factoring out the commonalities among them.  Note that this uses a
 6738: two-level defining word, i.e., a word that defines ordinary defining
 6739: words.
 6740: 
 6741: This time a solution involving @code{postpone} and friends seemed more
 6742: difficult (try it as an exercise), so I decided to use a
 6743: @code{create}/@code{does>} word; since I was already at it, I also used
 6744: @code{create}/@code{does>} for the lower level (try using
 6745: @code{postpone} etc. as an exercise), resulting in the following
 6746: definition:
 6747: 
 6748: @example
 6749: : define-format ( disasm-xt table-xt -- )
 6750:     \ define an instruction format that uses disasm-xt for
 6751:     \ disassembling and enters the defined instructions into table
 6752:     \ table-xt
 6753:     create 2,
 6754: does> ( u "inst" -- )
 6755:     \ defines an anonymous word for disassembling instruction inst,
 6756:     \ and enters it as u-th entry into table-xt
 6757:     2@@ swap here name string, ( u table-xt disasm-xt c-addr ) \ remember string
 6758:     noname create 2,      \ define anonymous word
 6759:     execute lastxt swap ! \ enter xt of defined word into table-xt
 6760: does> ( addr w -- )
 6761:     \ disassemble instruction w at addr
 6762:     2@@ >r ( addr w disasm-xt R: c-addr )
 6763:     execute ( R: c-addr ) \ disassemble operands
 6764:     r> count type ; \ print name 
 6765: @end example
 6766: 
 6767: Note that the tables here (in contrast to above) do the @code{cells +}
 6768: by themselves (that's why you have to pass an xt).  This word is used in
 6769: the following way:
 6770: 
 6771: @example
 6772: ' @var{disasm-operands} ' @var{table} define-format @var{inst-format}
 6773: @end example
 6774: 
 6775: As shown above, the defined instruction format is then used like this:
 6776: 
 6777: @example
 6778: @var{entry-num} @var{inst-format} @var{inst-name}
 6779: @end example
 6780: 
 6781: In terms of currying, this kind of two-level defining word provides the
 6782: parameters in three stages: first @var{disasm-operands} and @var{table},
 6783: then @var{entry-num} and @var{inst-name}, finally @code{addr w}, i.e.,
 6784: the instruction to be disassembled.  
 6785: 
 6786: Of course this did not quite fit all the instruction format names used
 6787: in @file{insts.fs}, so I had to define a few wrappers that conditioned
 6788: the parameters into the right form.
 6789: 
 6790: If you have trouble following this section, don't worry.  First, this is
 6791: involved and takes time (and probably some playing around) to
 6792: understand; second, this is the first two-level
 6793: @code{create}/@code{does>} word I have written in seventeen years of
 6794: Forth; and if I did not have @file{insts.fs} to start with, I may well
 6795: have elected to use just a one-level defining word (with some repeating
 6796: of parameters when using the defining word). So it is not necessary to
 6797: understand this, but it may improve your understanding of Forth.
 6798: 
 6799: 
 6800: @node Deferred words, Aliases, User-defined Defining Words, Defining Words
 6801: @subsection Deferred words
 6802: @cindex deferred words
 6803: 
 6804: The defining word @code{Defer} allows you to define a word by name
 6805: without defining its behaviour; the definition of its behaviour is
 6806: deferred. Here are two situation where this can be useful:
 6807: 
 6808: @itemize @bullet
 6809: @item
 6810: Where you want to allow the behaviour of a word to be altered later, and
 6811: for all precompiled references to the word to change when its behaviour
 6812: is changed.
 6813: @item
 6814: For mutual recursion; @xref{Calls and returns}.
 6815: @end itemize
 6816: 
 6817: In the following example, @code{foo} always invokes the version of
 6818: @code{greet} that prints ``@code{Good morning}'' whilst @code{bar}
 6819: always invokes the version that prints ``@code{Hello}''. There is no way
 6820: of getting @code{foo} to use the later version without re-ordering the
 6821: source code and recompiling it.
 6822: 
 6823: @example
 6824: : greet ." Good morning" ;
 6825: : foo ... greet ... ;
 6826: : greet ." Hello" ;
 6827: : bar ... greet ... ;
 6828: @end example
 6829: 
 6830: This problem can be solved by defining @code{greet} as a @code{Defer}red
 6831: word. The behaviour of a @code{Defer}red word can be defined and
 6832: redefined at any time by using @code{IS} to associate the xt of a
 6833: previously-defined word with it. The previous example becomes:
 6834: 
 6835: @example
 6836: Defer greet ( -- )
 6837: : foo ... greet ... ;
 6838: : bar ... greet ... ;
 6839: : greet1 ( -- ) ." Good morning" ;
 6840: : greet2 ( -- ) ." Hello" ;
 6841: ' greet2 <IS> greet  \ make greet behave like greet2
 6842: @end example
 6843: 
 6844: @progstyle
 6845: You should write a stack comment for every deferred word, and put only
 6846: XTs into deferred words that conform to this stack effect.  Otherwise
 6847: it's too difficult to use the deferred word.
 6848: 
 6849: A deferred word can be used to improve the statistics-gathering example
 6850: from @ref{User-defined Defining Words}; rather than edit the
 6851: application's source code to change every @code{:} to a @code{my:}, do
 6852: this:
 6853: 
 6854: @example
 6855: : real: : ;     \ retain access to the original
 6856: defer :         \ redefine as a deferred word
 6857: ' my: <IS> :      \ use special version of :
 6858: \
 6859: \ load application here
 6860: \
 6861: ' real: <IS> :    \ go back to the original
 6862: @end example
 6863: 
 6864: 
 6865: One thing to note is that @code{<IS>} consumes its name when it is
 6866: executed.  If you want to specify the name at compile time, use
 6867: @code{[IS]}:
 6868: 
 6869: @example
 6870: : set-greet ( xt -- )
 6871:   [IS] greet ;
 6872: 
 6873: ' greet1 set-greet
 6874: @end example
 6875: 
 6876: A deferred word can only inherit execution semantics from the xt
 6877: (because that is all that an xt can represent -- for more discussion of
 6878: this @pxref{Tokens for Words}); by default it will have default
 6879: interpretation and compilation semantics deriving from this execution
 6880: semantics.  However, you can change the interpretation and compilation
 6881: semantics of the deferred word in the usual ways:
 6882: 
 6883: @example
 6884: : bar .... ; compile-only
 6885: Defer fred immediate
 6886: Defer jim
 6887: 
 6888: ' bar <IS> jim  \ jim has default semantics
 6889: ' bar <IS> fred \ fred is immediate
 6890: @end example
 6891: 
 6892: doc-defer
 6893: doc-<is>
 6894: doc-[is]
 6895: doc-is
 6896: @comment TODO document these: what's defers [is]
 6897: doc-what's
 6898: doc-defers
 6899: 
 6900: @c Use @code{words-deferred} to see a list of deferred words.
 6901: 
 6902: Definitions in ANS Forth for @code{defer}, @code{<is>} and @code{[is]}
 6903: are provided in @file{compat/defer.fs}.
 6904: 
 6905: 
 6906: @node Aliases,  , Deferred words, Defining Words
 6907: @subsection Aliases
 6908: @cindex aliases
 6909: 
 6910: The defining word @code{Alias} allows you to define a word by name that
 6911: has the same behaviour as some other word. Here are two situation where
 6912: this can be useful:
 6913: 
 6914: @itemize @bullet
 6915: @item
 6916: When you want access to a word's definition from a different word list
 6917: (for an example of this, see the definition of the @code{Root} word list
 6918: in the Gforth source).
 6919: @item
 6920: When you want to create a synonym; a definition that can be known by
 6921: either of two names (for example, @code{THEN} and @code{ENDIF} are
 6922: aliases).
 6923: @end itemize
 6924: 
 6925: Like deferred words, an alias has default compilation and interpretation
 6926: semantics at the beginning (not the modifications of the other word),
 6927: but you can change them in the usual ways (@code{immediate},
 6928: @code{compile-only}). For example:
 6929: 
 6930: @example
 6931: : foo ... ; immediate
 6932: 
 6933: ' foo Alias bar \ bar is not an immediate word
 6934: ' foo Alias fooby immediate \ fooby is an immediate word
 6935: @end example
 6936: 
 6937: Words that are aliases have the same xt, different headers in the
 6938: dictionary, and consequently different name tokens (@pxref{Tokens for
 6939: Words}) and possibly different immediate flags.  An alias can only have
 6940: default or immediate compilation semantics; you can define aliases for
 6941: combined words with @code{interpret/compile:} -- see @ref{Combined words}.
 6942: 
 6943: doc-alias
 6944: 
 6945: 
 6946: @node Interpretation and Compilation Semantics, Tokens for Words, Defining Words, Words
 6947: @section Interpretation and Compilation Semantics
 6948: @cindex semantics, interpretation and compilation
 6949: 
 6950: @c !! state and ' are used without explanation
 6951: @c example for immediate/compile-only? or is the tutorial enough
 6952: 
 6953: @cindex interpretation semantics
 6954: The @dfn{interpretation semantics} of a (named) word are what the text
 6955: interpreter does when it encounters the word in interpret state. It also
 6956: appears in some other contexts, e.g., the execution token returned by
 6957: @code{' @i{word}} identifies the interpretation semantics of @i{word}
 6958: (in other words, @code{' @i{word} execute} is equivalent to
 6959: interpret-state text interpretation of @code{@i{word}}).
 6960: 
 6961: @cindex compilation semantics
 6962: The @dfn{compilation semantics} of a (named) word are what the text
 6963: interpreter does when it encounters the word in compile state. It also
 6964: appears in other contexts, e.g, @code{POSTPONE @i{word}}
 6965: compiles@footnote{In standard terminology, ``appends to the current
 6966: definition''.} the compilation semantics of @i{word}.
 6967: 
 6968: @cindex execution semantics
 6969: The standard also talks about @dfn{execution semantics}. They are used
 6970: only for defining the interpretation and compilation semantics of many
 6971: words. By default, the interpretation semantics of a word are to
 6972: @code{execute} its execution semantics, and the compilation semantics of
 6973: a word are to @code{compile,} its execution semantics.@footnote{In
 6974: standard terminology: The default interpretation semantics are its
 6975: execution semantics; the default compilation semantics are to append its
 6976: execution semantics to the execution semantics of the current
 6977: definition.}
 6978: 
 6979: Unnamed words (@pxref{Anonymous Definitions}) cannot be encountered by
 6980: the text interpreter, ticked, or @code{postpone}d, so they have no
 6981: interpretation or compilation semantics.  Their behaviour is represented
 6982: by their XT (@pxref{Tokens for Words}), and we call it execution
 6983: semantics, too.
 6984: 
 6985: @comment TODO expand, make it co-operate with new sections on text interpreter.
 6986: 
 6987: @cindex immediate words
 6988: @cindex compile-only words
 6989: You can change the semantics of the most-recently defined word:
 6990: 
 6991: 
 6992: doc-immediate
 6993: doc-compile-only
 6994: doc-restrict
 6995: 
 6996: By convention, words with non-default compilation semantics (e.g.,
 6997: immediate words) often have names surrounded with brackets (e.g.,
 6998: @code{[']}, @pxref{Execution token}).
 6999: 
 7000: Note that ticking (@code{'}) a compile-only word gives an error
 7001: (``Interpreting a compile-only word'').
 7002: 
 7003: @menu
 7004: * Combined words::              
 7005: @end menu
 7006: 
 7007: 
 7008: @node Combined words,  , Interpretation and Compilation Semantics, Interpretation and Compilation Semantics
 7009: @subsection Combined Words
 7010: @cindex combined words
 7011: 
 7012: Gforth allows you to define @dfn{combined words} -- words that have an
 7013: arbitrary combination of interpretation and compilation semantics.
 7014: 
 7015: doc-interpret/compile:
 7016: 
 7017: This feature was introduced for implementing @code{TO} and @code{S"}. I
 7018: recommend that you do not define such words, as cute as they may be:
 7019: they make it hard to get at both parts of the word in some contexts.
 7020: E.g., assume you want to get an execution token for the compilation
 7021: part. Instead, define two words, one that embodies the interpretation
 7022: part, and one that embodies the compilation part.  Once you have done
 7023: that, you can define a combined word with @code{interpret/compile:} for
 7024: the convenience of your users.
 7025: 
 7026: You might try to use this feature to provide an optimizing
 7027: implementation of the default compilation semantics of a word. For
 7028: example, by defining:
 7029: @example
 7030: :noname
 7031:    foo bar ;
 7032: :noname
 7033:    POSTPONE foo POSTPONE bar ;
 7034: interpret/compile: opti-foobar
 7035: @end example
 7036: 
 7037: @noindent
 7038: as an optimizing version of:
 7039: 
 7040: @example
 7041: : foobar
 7042:     foo bar ;
 7043: @end example
 7044: 
 7045: Unfortunately, this does not work correctly with @code{[compile]},
 7046: because @code{[compile]} assumes that the compilation semantics of all
 7047: @code{interpret/compile:} words are non-default. I.e., @code{[compile]
 7048: opti-foobar} would compile compilation semantics, whereas
 7049: @code{[compile] foobar} would compile interpretation semantics.
 7050: 
 7051: @cindex state-smart words (are a bad idea)
 7052: @anchor{state-smartness}
 7053: Some people try to use @dfn{state-smart} words to emulate the feature provided
 7054: by @code{interpret/compile:} (words are state-smart if they check
 7055: @code{STATE} during execution). E.g., they would try to code
 7056: @code{foobar} like this:
 7057: 
 7058: @example
 7059: : foobar
 7060:   STATE @@
 7061:   IF ( compilation state )
 7062:     POSTPONE foo POSTPONE bar
 7063:   ELSE
 7064:     foo bar
 7065:   ENDIF ; immediate
 7066: @end example
 7067: 
 7068: Although this works if @code{foobar} is only processed by the text
 7069: interpreter, it does not work in other contexts (like @code{'} or
 7070: @code{POSTPONE}). E.g., @code{' foobar} will produce an execution token
 7071: for a state-smart word, not for the interpretation semantics of the
 7072: original @code{foobar}; when you execute this execution token (directly
 7073: with @code{EXECUTE} or indirectly through @code{COMPILE,}) in compile
 7074: state, the result will not be what you expected (i.e., it will not
 7075: perform @code{foo bar}). State-smart words are a bad idea. Simply don't
 7076: write them@footnote{For a more detailed discussion of this topic, see
 7077: M. Anton Ertl,
 7078: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,@code{State}-smartness---Why
 7079: it is Evil and How to Exorcise it}}, EuroForth '98.}!
 7080: 
 7081: @cindex defining words with arbitrary semantics combinations
 7082: It is also possible to write defining words that define words with
 7083: arbitrary combinations of interpretation and compilation semantics. In
 7084: general, they look like this:
 7085: 
 7086: @example
 7087: : def-word
 7088:     create-interpret/compile
 7089:     @i{code1}
 7090: interpretation>
 7091:     @i{code2}
 7092: <interpretation
 7093: compilation>
 7094:     @i{code3}
 7095: <compilation ;
 7096: @end example
 7097: 
 7098: For a @i{word} defined with @code{def-word}, the interpretation
 7099: semantics are to push the address of the body of @i{word} and perform
 7100: @i{code2}, and the compilation semantics are to push the address of
 7101: the body of @i{word} and perform @i{code3}. E.g., @code{constant}
 7102: can also be defined like this (except that the defined constants don't
 7103: behave correctly when @code{[compile]}d):
 7104: 
 7105: @example
 7106: : constant ( n "name" -- )
 7107:     create-interpret/compile
 7108:     ,
 7109: interpretation> ( -- n )
 7110:     @@
 7111: <interpretation
 7112: compilation> ( compilation. -- ; run-time. -- n )
 7113:     @@ postpone literal
 7114: <compilation ;
 7115: @end example
 7116: 
 7117: 
 7118: doc-create-interpret/compile
 7119: doc-interpretation>
 7120: doc-<interpretation
 7121: doc-compilation>
 7122: doc-<compilation
 7123: 
 7124: 
 7125: Words defined with @code{interpret/compile:} and
 7126: @code{create-interpret/compile} have an extended header structure that
 7127: differs from other words; however, unless you try to access them with
 7128: plain address arithmetic, you should not notice this. Words for
 7129: accessing the header structure usually know how to deal with this; e.g.,
 7130: @code{'} @i{word} @code{>body} also gives you the body of a word created
 7131: with @code{create-interpret/compile}.
 7132: 
 7133: 
 7134: @c -------------------------------------------------------------
 7135: @node Tokens for Words, Compiling words, Interpretation and Compilation Semantics, Words
 7136: @section Tokens for Words
 7137: @cindex tokens for words
 7138: 
 7139: This section describes the creation and use of tokens that represent
 7140: words.
 7141: 
 7142: @menu
 7143: * Execution token::             represents execution/interpretation semantics
 7144: * Compilation token::           represents compilation semantics
 7145: * Name token::                  represents named words
 7146: @end menu
 7147: 
 7148: @node Execution token, Compilation token, Tokens for Words, Tokens for Words
 7149: @subsection Execution token
 7150: 
 7151: @cindex xt
 7152: @cindex execution token
 7153: An @dfn{execution token} (@i{XT}) represents some behaviour of a word.
 7154: You can use @code{execute} to invoke this behaviour.
 7155: 
 7156: @cindex tick (')
 7157: You can use @code{'} to get an execution token that represents the
 7158: interpretation semantics of a named word:
 7159: 
 7160: @example
 7161: 5 ' .
 7162: execute
 7163: @end example
 7164: 
 7165: doc-'
 7166: 
 7167: @code{'} parses at run-time; there is also a word @code{[']} that parses
 7168: when it is compiled, and compiles the resulting XT:
 7169: 
 7170: @example
 7171: : foo ['] . execute ;
 7172: 5 foo
 7173: : bar ' execute ; \ by contrast,
 7174: 5 bar .           \ ' parses "." when bar executes
 7175: @end example
 7176: 
 7177: doc-[']
 7178: 
 7179: If you want the execution token of @i{word}, write @code{['] @i{word}}
 7180: in compiled code and @code{' @i{word}} in interpreted code.  Gforth's
 7181: @code{'} and @code{[']} behave somewhat unusually by complaining about
 7182: compile-only words (because these words have no interpretation
 7183: semantics).  You might get what you want by using @code{COMP' @i{word}
 7184: DROP} or @code{[COMP'] @i{word} DROP} (for details @pxref{Compilation
 7185: token}).
 7186: 
 7187: Another way to get an XT is @code{:noname} or @code{lastxt}
 7188: (@pxref{Anonymous Definitions}).  For anonymous words this gives an xt
 7189: for the only behaviour the word has (the execution semantics).  For
 7190: named words, @code{lastxt} produces an XT for the same behaviour it
 7191: would produce if the word was defined anonymously.
 7192: 
 7193: @example
 7194: :noname ." hello" ;
 7195: execute
 7196: @end example
 7197: 
 7198: An XT occupies one cell and can be manipulated like any other cell.
 7199: 
 7200: @cindex code field address
 7201: @cindex CFA
 7202: In ANS Forth the XT is just an abstract data type (i.e., defined by the
 7203: operations that produce or consume it).  For old hands: In Gforth, the
 7204: XT is implemented as a code field address (CFA).
 7205: 
 7206: doc-execute
 7207: doc-perform
 7208: 
 7209: @node Compilation token, Name token, Execution token, Tokens for Words
 7210: @subsection Compilation token
 7211: 
 7212: @cindex compilation token
 7213: @cindex CT (compilation token)
 7214: Gforth represents the compilation semantics of a named word by a
 7215: @dfn{compilation token} consisting of two cells: @i{w xt}. The top cell
 7216: @i{xt} is an execution token. The compilation semantics represented by
 7217: the compilation token can be performed with @code{execute}, which
 7218: consumes the whole compilation token, with an additional stack effect
 7219: determined by the represented compilation semantics.
 7220: 
 7221: At present, the @i{w} part of a compilation token is an execution token,
 7222: and the @i{xt} part represents either @code{execute} or
 7223: @code{compile,}@footnote{Depending upon the compilation semantics of the
 7224: word. If the word has default compilation semantics, the @i{xt} will
 7225: represent @code{compile,}. Otherwise (e.g., for immediate words), the
 7226: @i{xt} will represent @code{execute}.}. However, don't rely on that
 7227: knowledge, unless necessary; future versions of Gforth may introduce
 7228: unusual compilation tokens (e.g., a compilation token that represents
 7229: the compilation semantics of a literal).
 7230: 
 7231: You can perform the compilation semantics represented by the compilation
 7232: token with @code{execute}.  You can compile the compilation semantics
 7233: with @code{postpone,}. I.e., @code{COMP' @i{word} postpone,} is
 7234: equivalent to @code{postpone @i{word}}.
 7235: 
 7236: doc-[comp']
 7237: doc-comp'
 7238: doc-postpone,
 7239: 
 7240: @node Name token,  , Compilation token, Tokens for Words
 7241: @subsection Name token
 7242: 
 7243: @cindex name token
 7244: @cindex name field address
 7245: @cindex NFA
 7246: Gforth represents named words by the @dfn{name token}, (@i{nt}). In
 7247: Gforth, the abstract data type @emph{name token} is implemented as a
 7248: name field address (NFA).
 7249: 
 7250: doc-find-name
 7251: doc-name>int
 7252: doc-name?int
 7253: doc-name>comp
 7254: doc-name>string
 7255: 
 7256: @c ----------------------------------------------------------
 7257: @node Compiling words, The Text Interpreter, Tokens for Words, Words
 7258: @section Compiling words
 7259: @cindex compiling words
 7260: @cindex macros
 7261: 
 7262: In contrast to most other languages, Forth has no strict boundary
 7263: between compilation and run-time.  E.g., you can run arbitrary code
 7264: between defining words (or for computing data used by defining words
 7265: like @code{constant}). Moreover, @code{Immediate} (@pxref{Interpretation
 7266: and Compilation Semantics} and @code{[}...@code{]} (see below) allow
 7267: running arbitrary code while compiling a colon definition (exception:
 7268: you must not allot dictionary space).
 7269: 
 7270: @menu
 7271: * Literals::                    Compiling data values
 7272: * Macros::                      Compiling words
 7273: @end menu
 7274: 
 7275: @node Literals, Macros, Compiling words, Compiling words
 7276: @subsection Literals
 7277: @cindex Literals
 7278: 
 7279: The simplest and most frequent example is to compute a literal during
 7280: compilation.  E.g., the following definition prints an array of strings,
 7281: one string per line:
 7282: 
 7283: @example
 7284: : .strings ( addr u -- ) \ gforth
 7285:     2* cells bounds U+DO
 7286: 	cr i 2@@ type
 7287:     2 cells +LOOP ;  
 7288: @end example
 7289: 
 7290: With a simple-minded compiler like Gforth's, this computes @code{2
 7291: cells} on every loop iteration.  You can compute this value once and for
 7292: all at compile time and compile it into the definition like this:
 7293: 
 7294: @example
 7295: : .strings ( addr u -- ) \ gforth
 7296:     2* cells bounds U+DO
 7297: 	cr i 2@@ type
 7298:     [ 2 cells ] literal +LOOP ;  
 7299: @end example
 7300: 
 7301: @code{[} switches the text interpreter to interpret state (you will get
 7302: an @code{ok} prompt if you type this example interactively and insert a
 7303: newline between @code{[} and @code{]}), so it performs the
 7304: interpretation semantics of @code{2 cells}; this computes a number.
 7305: @code{]} switches the text interpreter back into compile state.  It then
 7306: performs @code{Literal}'s compilation semantics, which are to compile
 7307: this number into the current word.  You can decompile the word with
 7308: @code{see .strings} to see the effect on the compiled code.
 7309: 
 7310: You can also optimize the @code{2* cells} into @code{[ 2 cells ] literal
 7311: *} in this way.
 7312: 
 7313: doc-[
 7314: doc-]
 7315: doc-literal
 7316: doc-]L
 7317: 
 7318: There are also words for compiling other data types than single cells as
 7319: literals:
 7320: 
 7321: doc-2literal
 7322: doc-fliteral
 7323: doc-sliteral
 7324: 
 7325: @cindex colon-sys, passing data across @code{:}
 7326: @cindex @code{:}, passing data across
 7327: You might be tempted to pass data from outside a colon definition to the
 7328: inside on the data stack.  This does not work, because @code{:} puhes a
 7329: colon-sys, making stuff below unaccessible.  E.g., this does not work:
 7330: 
 7331: @example
 7332: 5 : foo literal ; \ error: "unstructured"
 7333: @end example
 7334: 
 7335: Instead, you have to pass the value in some other way, e.g., through a
 7336: variable:
 7337: 
 7338: @example
 7339: variable temp
 7340: 5 temp !
 7341: : foo [ temp @@ ] literal ;
 7342: @end example
 7343: 
 7344: 
 7345: @node Macros,  , Literals, Compiling words
 7346: @subsection Macros
 7347: @cindex Macros
 7348: @cindex compiling compilation semantics
 7349: 
 7350: @code{Literal} and friends compile data values into the current
 7351: definition.  You can also write words that compile other words into the
 7352: current definition.  E.g.,
 7353: 
 7354: @example
 7355: : compile-+ ( -- ) \ compiled code: ( n1 n2 -- n )
 7356:   POSTPONE + ;
 7357: 
 7358: : foo ( n1 n2 -- n )
 7359:   [ compile-+ ] ;
 7360: 1 2 foo .
 7361: @end example
 7362: 
 7363: This is equivalent to @code{: foo + ;} (@code{see foo} to check this).
 7364: What happens in this example?  @code{Postpone} compiles the compilation
 7365: semantics of @code{+} into @code{compile-+}; later the text interpreter
 7366: executes @code{compile-+} and thus the compilation semantics of +, which
 7367: compile (the execution semantics of) @code{+} into
 7368: @code{foo}.@footnote{A recent RFI answer requires that compiling words
 7369: should only be executed in compile state, so this example is not
 7370: guaranteed to work on all standard systems, but on any decent system it
 7371: will work.}
 7372: 
 7373: doc-postpone
 7374: doc-[compile]
 7375: 
 7376: Compiling words like @code{compile-+} are usually immediate (or similar)
 7377: so you do not have to switch to interpret state to execute them;
 7378: mopifying the last example accordingly produces:
 7379: 
 7380: @example
 7381: : [compile-+] ( compilation: --; interpretation: -- )
 7382:   \ compiled code: ( n1 n2 -- n )
 7383:   POSTPONE + ; immediate
 7384: 
 7385: : foo ( n1 n2 -- n )
 7386:   [compile-+] ;
 7387: 1 2 foo .
 7388: @end example
 7389: 
 7390: Immediate compiling words are similar to macros in other languages (in
 7391: particular, Lisp).  The important differences to macros in, e.g., C are:
 7392: 
 7393: @itemize @bullet
 7394: 
 7395: @item
 7396: You use the same language for defining and processing macros, not a
 7397: separate preprocessing language and processor.
 7398: 
 7399: @item
 7400: Consequently, the full power of Forth is available in macro definitions.
 7401: E.g., you can perform arbitrarily complex computations, or generate
 7402: different code conditionally or in a loop (e.g., @pxref{Advanced macros
 7403: Tutorial}).  This power is very useful when writing a parser generators
 7404: or other code-generating software.
 7405: 
 7406: @item
 7407: Macros defined using @code{postpone} etc. deal with the language at a
 7408: higher level than strings; name binding happens at macro definition
 7409: time, so you can avoid the pitfalls of name collisions that can happen
 7410: in C macros.  Of course, Forth is a liberal language and also allows to
 7411: shoot yourself in the foot with text-interpreted macros like
 7412: 
 7413: @example
 7414: : [compile-+] s" +" evaluate ; immediate
 7415: @end example
 7416: 
 7417: Apart from binding the name at macro use time, using @code{evaluate}
 7418: also makes your definition @code{state}-smart (@pxref{state-smartness}).
 7419: @end itemize
 7420: 
 7421: You may want the macro to compile a number into a word.  The word to do
 7422: it is @code{literal}, but you have to @code{postpone} it, so its
 7423: compilation semantics take effect when the macro is executed, not when
 7424: it is compiled:
 7425: 
 7426: @example
 7427: : [compile-5] ( -- ) \ compiled code: ( -- n )
 7428:   5 POSTPONE literal ; immediate
 7429: 
 7430: : foo [compile-5] ;
 7431: foo .
 7432: @end example
 7433: 
 7434: You may want to pass parameters to a macro, that the macro should
 7435: compile into the current definition.  If the parameter is a number, then
 7436: you can use @code{postpone literal} (similar for other values).
 7437: 
 7438: If you want to pass a word that is to be compiled, the usual way is to
 7439: pass an execution token and @code{compile,} it:
 7440: 
 7441: @example
 7442: : twice1 ( xt -- ) \ compiled code: ... -- ...
 7443:   dup compile, compile, ;
 7444: 
 7445: : 2+ ( n1 -- n2 )
 7446:   [ ' 1+ twice1 ] ;
 7447: @end example
 7448: 
 7449: doc-compile,
 7450: 
 7451: An alternative available in Gforth, that allows you to pass compile-only
 7452: words as parameters is to use the compilation token (@pxref{Compilation
 7453: token}).  The same example in this technique:
 7454: 
 7455: @example
 7456: : twice ( ... ct -- ... ) \ compiled code: ... -- ...
 7457:   2dup 2>r execute 2r> execute ;
 7458: 
 7459: : 2+ ( n1 -- n2 )
 7460:   [ comp' 1+ twice ] ;
 7461: @end example
 7462: 
 7463: In the example above @code{2>r} and @code{2r>} ensure that @code{twice}
 7464: works even if the executed compilation semantics has an effect on the
 7465: data stack.
 7466: 
 7467: You can also define complete definitions with these words; this provides
 7468: an alternative to using @code{does>} (@pxref{User-defined Defining
 7469: Words}).  E.g., instead of
 7470: 
 7471: @example
 7472: : curry+ ( n1 "name" -- )
 7473:     CREATE ,
 7474: DOES> ( n2 -- n1+n2 )
 7475:     @@ + ;
 7476: @end example
 7477: 
 7478: you could define
 7479: 
 7480: @example
 7481: : curry+ ( n1 "name" -- )
 7482:   \ name execution: ( n2 -- n1+n2 )
 7483:   >r : r> POSTPONE literal POSTPONE + POSTPONE ; ;
 7484: 
 7485: -3 curry+ 3-
 7486: see 3-
 7487: @end example
 7488: 
 7489: The sequence @code{>r : r>} is necessary, because @code{:} puts a
 7490: colon-sys on the data stack that makes everything below it unaccessible.
 7491: 
 7492: This way of writing defining words is sometimes more, sometimes less
 7493: convenient than using @code{does>} (@pxref{Advanced does> usage
 7494: example}).  One advantage of this method is that it can be optimized
 7495: better, because the compiler knows that the value compiled with
 7496: @code{literal} is fixed, whereas the data associated with a
 7497: @code{create}d word can be changed.
 7498: 
 7499: @c ----------------------------------------------------------
 7500: @node The Text Interpreter, Word Lists, Compiling words, Words
 7501: @section  The Text Interpreter
 7502: @cindex interpreter - outer
 7503: @cindex text interpreter
 7504: @cindex outer interpreter
 7505: 
 7506: @c Should we really describe all these ugly details?  IMO the text
 7507: @c interpreter should be much cleaner, but that may not be possible within
 7508: @c ANS Forth. - anton
 7509: @c nac-> I wanted to explain how it works to show how you can exploit
 7510: @c it in your own programs. When I was writing a cross-compiler, figuring out
 7511: @c some of these gory details was very helpful to me. None of the textbooks
 7512: @c I've seen cover it, and the most modern Forth textbook -- Forth Inc's,
 7513: @c seems to positively avoid going into too much detail for some of
 7514: @c the internals.
 7515: 
 7516: @c anton: ok.  I wonder, though, if this is the right place; for some stuff
 7517: @c it is; for the ugly details, I would prefer another place.  I wonder
 7518: @c whether we should have a chapter before "Words" that describes some
 7519: @c basic concepts referred to in words, and a chapter after "Words" that
 7520: @c describes implementation details.
 7521: 
 7522: The text interpreter@footnote{This is an expanded version of the
 7523: material in @ref{Introducing the Text Interpreter}.} is an endless loop
 7524: that processes input from the current input device. It is also called
 7525: the outer interpreter, in contrast to the inner interpreter
 7526: (@pxref{Engine}) which executes the compiled Forth code on interpretive
 7527: implementations.
 7528: 
 7529: @cindex interpret state
 7530: @cindex compile state
 7531: The text interpreter operates in one of two states: @dfn{interpret
 7532: state} and @dfn{compile state}. The current state is defined by the
 7533: aptly-named variable @code{state}.
 7534: 
 7535: This section starts by describing how the text interpreter behaves when
 7536: it is in interpret state, processing input from the user input device --
 7537: the keyboard. This is the mode that a Forth system is in after it starts
 7538: up.
 7539: 
 7540: @cindex input buffer
 7541: @cindex terminal input buffer
 7542: The text interpreter works from an area of memory called the @dfn{input
 7543: buffer}@footnote{When the text interpreter is processing input from the
 7544: keyboard, this area of memory is called the @dfn{terminal input buffer}
 7545: (TIB) and is addressed by the (obsolescent) words @code{TIB} and
 7546: @code{#TIB}.}, which stores your keyboard input when you press the
 7547: @key{RET} key. Starting at the beginning of the input buffer, it skips
 7548: leading spaces (called @dfn{delimiters}) then parses a string (a
 7549: sequence of non-space characters) until it reaches either a space
 7550: character or the end of the buffer. Having parsed a string, it makes two
 7551: attempts to process it:
 7552: 
 7553: @cindex dictionary
 7554: @itemize @bullet
 7555: @item
 7556: It looks for the string in a @dfn{dictionary} of definitions. If the
 7557: string is found, the string names a @dfn{definition} (also known as a
 7558: @dfn{word}) and the dictionary search returns information that allows
 7559: the text interpreter to perform the word's @dfn{interpretation
 7560: semantics}. In most cases, this simply means that the word will be
 7561: executed.
 7562: @item
 7563: If the string is not found in the dictionary, the text interpreter
 7564: attempts to treat it as a number, using the rules described in
 7565: @ref{Number Conversion}. If the string represents a legal number in the
 7566: current radix, the number is pushed onto a parameter stack (the data
 7567: stack for integers, the floating-point stack for floating-point
 7568: numbers).
 7569: @end itemize
 7570: 
 7571: If both attempts fail, or if the word is found in the dictionary but has
 7572: no interpretation semantics@footnote{This happens if the word was
 7573: defined as @code{COMPILE-ONLY}.} the text interpreter discards the
 7574: remainder of the input buffer, issues an error message and waits for
 7575: more input. If one of the attempts succeeds, the text interpreter
 7576: repeats the parsing process until the whole of the input buffer has been
 7577: processed, at which point it prints the status message ``@code{ ok}''
 7578: and waits for more input.
 7579: 
 7580: @c anton: this should be in the input stream subsection (or below it)
 7581: 
 7582: @cindex parse area
 7583: The text interpreter keeps track of its position in the input buffer by
 7584: updating a variable called @code{>IN} (pronounced ``to-in''). The value
 7585: of @code{>IN} starts out as 0, indicating an offset of 0 from the start
 7586: of the input buffer. The region from offset @code{>IN @@} to the end of
 7587: the input buffer is called the @dfn{parse area}@footnote{In other words,
 7588: the text interpreter processes the contents of the input buffer by
 7589: parsing strings from the parse area until the parse area is empty.}.
 7590: This example shows how @code{>IN} changes as the text interpreter parses
 7591: the input buffer:
 7592: 
 7593: @example
 7594: : remaining >IN @@ SOURCE 2 PICK - -ROT + SWAP
 7595:   CR ." ->" TYPE ." <-" ; IMMEDIATE 
 7596: 
 7597: 1 2 3 remaining + remaining . 
 7598: 
 7599: : foo 1 2 3 remaining SWAP remaining ;
 7600: @end example
 7601: 
 7602: @noindent
 7603: The result is:
 7604: 
 7605: @example
 7606: ->+ remaining .<-
 7607: ->.<-5  ok
 7608: 
 7609: ->SWAP remaining ;-<
 7610: ->;<-  ok
 7611: @end example
 7612: 
 7613: @cindex parsing words
 7614: The value of @code{>IN} can also be modified by a word in the input
 7615: buffer that is executed by the text interpreter.  This means that a word
 7616: can ``trick'' the text interpreter into either skipping a section of the
 7617: input buffer@footnote{This is how parsing words work.} or into parsing a
 7618: section twice. For example:
 7619: 
 7620: @example
 7621: : lat ." <<foo>>" ;
 7622: : flat ." <<bar>>" >IN DUP @@ 3 - SWAP ! ;
 7623: @end example
 7624: 
 7625: @noindent
 7626: When @code{flat} is executed, this output is produced@footnote{Exercise
 7627: for the reader: what would happen if the @code{3} were replaced with
 7628: @code{4}?}:
 7629: 
 7630: @example
 7631: <<bar>><<foo>>
 7632: @end example
 7633: 
 7634: This technique can be used to work around some of the interoperability
 7635: problems of parsing words.  Of course, it's better to avoid parsing
 7636: words where possible.
 7637: 
 7638: @noindent
 7639: Two important notes about the behaviour of the text interpreter:
 7640: 
 7641: @itemize @bullet
 7642: @item
 7643: It processes each input string to completion before parsing additional
 7644: characters from the input buffer.
 7645: @item
 7646: It treats the input buffer as a read-only region (and so must your code).
 7647: @end itemize
 7648: 
 7649: @noindent
 7650: When the text interpreter is in compile state, its behaviour changes in
 7651: these ways:
 7652: 
 7653: @itemize @bullet
 7654: @item
 7655: If a parsed string is found in the dictionary, the text interpreter will
 7656: perform the word's @dfn{compilation semantics}. In most cases, this
 7657: simply means that the execution semantics of the word will be appended
 7658: to the current definition.
 7659: @item
 7660: When a number is encountered, it is compiled into the current definition
 7661: (as a literal) rather than being pushed onto a parameter stack.
 7662: @item
 7663: If an error occurs, @code{state} is modified to put the text interpreter
 7664: back into interpret state.
 7665: @item
 7666: Each time a line is entered from the keyboard, Gforth prints
 7667: ``@code{ compiled}'' rather than `` @code{ok}''.
 7668: @end itemize
 7669: 
 7670: @cindex text interpreter - input sources
 7671: When the text interpreter is using an input device other than the
 7672: keyboard, its behaviour changes in these ways:
 7673: 
 7674: @itemize @bullet
 7675: @item
 7676: When the parse area is empty, the text interpreter attempts to refill
 7677: the input buffer from the input source. When the input source is
 7678: exhausted, the input source is set back to the previous input source.
 7679: @item
 7680: It doesn't print out ``@code{ ok}'' or ``@code{ compiled}'' messages each
 7681: time the parse area is emptied.
 7682: @item
 7683: If an error occurs, the input source is set back to the user input
 7684: device.
 7685: @end itemize
 7686: 
 7687: You can read about this in more detail in @ref{Input Sources}.
 7688: 
 7689: doc->in
 7690: doc-source
 7691: 
 7692: doc-tib
 7693: doc-#tib
 7694: 
 7695: 
 7696: @menu
 7697: * Input Sources::               
 7698: * Number Conversion::           
 7699: * Interpret/Compile states::    
 7700: * Interpreter Directives::      
 7701: @end menu
 7702: 
 7703: @node Input Sources, Number Conversion, The Text Interpreter, The Text Interpreter
 7704: @subsection Input Sources
 7705: @cindex input sources
 7706: @cindex text interpreter - input sources
 7707: 
 7708: By default, the text interpreter processes input from the user input
 7709: device (the keyboard) when Forth starts up. The text interpreter can
 7710: process input from any of these sources:
 7711: 
 7712: @itemize @bullet
 7713: @item
 7714: The user input device -- the keyboard.
 7715: @item
 7716: A file, using the words described in @ref{Forth source files}.
 7717: @item
 7718: A block, using the words described in @ref{Blocks}.
 7719: @item
 7720: A text string, using @code{evaluate}.
 7721: @end itemize
 7722: 
 7723: A program can identify the current input device from the values of
 7724: @code{source-id} and @code{blk}.
 7725: 
 7726: 
 7727: doc-source-id
 7728: doc-blk
 7729: 
 7730: doc-save-input
 7731: doc-restore-input
 7732: 
 7733: doc-evaluate
 7734: 
 7735: 
 7736: 
 7737: @node Number Conversion, Interpret/Compile states, Input Sources, The Text Interpreter
 7738: @subsection Number Conversion
 7739: @cindex number conversion
 7740: @cindex double-cell numbers, input format
 7741: @cindex input format for double-cell numbers
 7742: @cindex single-cell numbers, input format
 7743: @cindex input format for single-cell numbers
 7744: @cindex floating-point numbers, input format
 7745: @cindex input format for floating-point numbers
 7746: 
 7747: This section describes the rules that the text interpreter uses when it
 7748: tries to convert a string into a number.
 7749: 
 7750: Let <digit> represent any character that is a legal digit in the current
 7751: number base@footnote{For example, 0-9 when the number base is decimal or
 7752: 0-9, A-F when the number base is hexadecimal.}.
 7753: 
 7754: Let <decimal digit> represent any character in the range 0-9.
 7755: 
 7756: Let @{@i{a b}@} represent the @i{optional} presence of any of the characters
 7757: in the braces (@i{a} or @i{b} or neither).
 7758: 
 7759: Let * represent any number of instances of the previous character
 7760: (including none).
 7761: 
 7762: Let any other character represent itself.
 7763: 
 7764: @noindent
 7765: Now, the conversion rules are:
 7766: 
 7767: @itemize @bullet
 7768: @item
 7769: A string of the form <digit><digit>* is treated as a single-precision
 7770: (cell-sized) positive integer. Examples are 0 123 6784532 32343212343456 42
 7771: @item
 7772: A string of the form -<digit><digit>* is treated as a single-precision
 7773: (cell-sized) negative integer, and is represented using 2's-complement
 7774: arithmetic. Examples are -45 -5681 -0
 7775: @item
 7776: A string of the form <digit><digit>*.<digit>* is treated as a double-precision
 7777: (double-cell-sized) positive integer. Examples are 3465. 3.465 34.65
 7778: (all three of these represent the same number).
 7779: @item
 7780: A string of the form -<digit><digit>*.<digit>* is treated as a
 7781: double-precision (double-cell-sized) negative integer, and is
 7782: represented using 2's-complement arithmetic. Examples are -3465. -3.465
 7783: -34.65 (all three of these represent the same number).
 7784: @item
 7785: A string of the form @{+ -@}<decimal digit>@{.@}<decimal digit>*@{e
 7786: E@}@{+ -@}<decimal digit><decimal digit>* is treated as a floating-point
 7787: number. Examples are 1e 1e0 1.e 1.e0 +1e+0 (which all represent the same
 7788: number) +12.E-4
 7789: @end itemize
 7790: 
 7791: By default, the number base used for integer number conversion is given
 7792: by the contents of the variable @code{base}.  Note that a lot of
 7793: confusion can result from unexpected values of @code{base}.  If you
 7794: change @code{base} anywhere, make sure to save the old value and restore
 7795: it afterwards.  In general I recommend keeping @code{base} decimal, and
 7796: using the prefixes described below for the popular non-decimal bases.
 7797: 
 7798: doc-dpl
 7799: doc-base
 7800: doc-hex
 7801: doc-decimal
 7802: 
 7803: 
 7804: @cindex '-prefix for character strings
 7805: @cindex &-prefix for decimal numbers
 7806: @cindex %-prefix for binary numbers
 7807: @cindex $-prefix for hexadecimal numbers
 7808: Gforth allows you to override the value of @code{base} by using a
 7809: prefix@footnote{Some Forth implementations provide a similar scheme by
 7810: implementing @code{$} etc. as parsing words that process the subsequent
 7811: number in the input stream and push it onto the stack. For example, see
 7812: @cite{Number Conversion and Literals}, by Wil Baden; Forth Dimensions
 7813: 20(3) pages 26--27. In such implementations, unlike in Gforth, a space
 7814: is required between the prefix and the number.} before the first digit
 7815: of an (integer) number. Four prefixes are supported:
 7816: 
 7817: @itemize @bullet
 7818: @item
 7819: @code{&} -- decimal
 7820: @item
 7821: @code{%} -- binary
 7822: @item
 7823: @code{$} -- hexadecimal
 7824: @item
 7825: @code{'} -- base @code{max-char+1}
 7826: @end itemize
 7827: 
 7828: Here are some examples, with the equivalent decimal number shown after
 7829: in braces:
 7830: 
 7831: -$41 (-65), %1001101 (205), %1001.0001 (145 - a double-precision number),
 7832: 'AB (16706; ascii A is 65, ascii B is 66, number is 65*256 + 66),
 7833: 'ab (24930; ascii a is 97, ascii B is 98, number is 97*256 + 98),
 7834: &905 (905), $abc (2478), $ABC (2478).
 7835: 
 7836: @cindex number conversion - traps for the unwary
 7837: @noindent
 7838: Number conversion has a number of traps for the unwary:
 7839: 
 7840: @itemize @bullet
 7841: @item
 7842: You cannot determine the current number base using the code sequence
 7843: @code{base @@ .} -- the number base is always 10 in the current number
 7844: base. Instead, use something like @code{base @@ dec.}
 7845: @item
 7846: If the number base is set to a value greater than 14 (for example,
 7847: hexadecimal), the number 123E4 is ambiguous; the conversion rules allow
 7848: it to be intepreted as either a single-precision integer or a
 7849: floating-point number (Gforth treats it as an integer). The ambiguity
 7850: can be resolved by explicitly stating the sign of the mantissa and/or
 7851: exponent: 123E+4 or +123E4 -- if the number base is decimal, no
 7852: ambiguity arises; either representation will be treated as a
 7853: floating-point number.
 7854: @item
 7855: There is a word @code{bin} but it does @i{not} set the number base!
 7856: It is used to specify file types.
 7857: @item
 7858: ANS Forth requires the @code{.} of a double-precision number to be the
 7859: final character in the string.  Gforth allows the @code{.} to be
 7860: anywhere after the first digit.
 7861: @item
 7862: The number conversion process does not check for overflow.
 7863: @item
 7864: In an ANS Forth program @code{base} is required to be decimal when
 7865: converting floating-point numbers.  In Gforth, number conversion to
 7866: floating-point numbers always uses base &10, irrespective of the value
 7867: of @code{base}.
 7868: @end itemize
 7869: 
 7870: You can read numbers into your programs with the words described in
 7871: @ref{Input}.
 7872: 
 7873: @node Interpret/Compile states, Interpreter Directives, Number Conversion, The Text Interpreter
 7874: @subsection Interpret/Compile states
 7875: @cindex Interpret/Compile states
 7876: 
 7877: A standard program is not permitted to change @code{state}
 7878: explicitly. However, it can change @code{state} implicitly, using the
 7879: words @code{[} and @code{]}. When @code{[} is executed it switches
 7880: @code{state} to interpret state, and therefore the text interpreter
 7881: starts interpreting. When @code{]} is executed it switches @code{state}
 7882: to compile state and therefore the text interpreter starts
 7883: compiling. The most common usage for these words is for switching into
 7884: interpret state and back from within a colon definition; this technique
 7885: can be used to compile a literal (for an example, @pxref{Literals}) or
 7886: for conditional compilation (for an example, @pxref{Interpreter
 7887: Directives}).
 7888: 
 7889: 
 7890: @c This is a bad example: It's non-standard, and it's not necessary.
 7891: @c However, I can't think of a good example for switching into compile
 7892: @c state when there is no current word (@code{state}-smart words are not a
 7893: @c good reason).  So maybe we should use an example for switching into
 7894: @c interpret @code{state} in a colon def. - anton
 7895: @c nac-> I agree. I started out by putting in the example, then realised
 7896: @c that it was non-ANS, so wrote more words around it. I hope this
 7897: @c re-written version is acceptable to you. I do want to keep the example
 7898: @c as it is helpful for showing what is and what is not portable, particularly
 7899: @c where it outlaws a style in common use.
 7900: 
 7901: @c anton: it's more important to show what's portable.  After we have done
 7902: @c that, we can also show what's not.  In any case, I have written a
 7903: @c section Compiling Words which also deals with [ ].
 7904: 
 7905: @code{[} and @code{]} also give you the ability to switch into compile
 7906: state and back, but we cannot think of any useful Standard application
 7907: for this ability. Pre-ANS Forth textbooks have examples like this:
 7908: 
 7909: @example
 7910: : AA ." this is A" ;
 7911: : BB ." this is B" ;
 7912: : CC ." this is C" ;
 7913: 
 7914: create table ] aa bb cc [
 7915: 
 7916: : go ( n -- ) \ n is offset into table.. 0 for 1st entry
 7917:   cells table + @ execute ;
 7918: @end example
 7919: 
 7920: This example builds a jump table; @code{0 go} will display ``@code{this
 7921: is A}''. Using @code{[} and @code{]} in this example is equivalent to
 7922: defining @code{table} like this:
 7923: 
 7924: @example
 7925: create table ' aa COMPILE, ' bb COMPILE, ' cc COMPILE,
 7926: @end example
 7927: 
 7928: The problem with this code is that the definition of @code{table} is not
 7929: portable -- it @i{compile}s execution tokens into code space. Whilst it
 7930: @i{may} work on systems where code space and data space co-incide, the
 7931: Standard only allows data space to be assigned for a @code{CREATE}d
 7932: word. In addition, the Standard only allows @code{@@} to access data
 7933: space, whilst this example is using it to access code space. The only
 7934: portable, Standard way to build this table is to build it in data space,
 7935: like this:
 7936: 
 7937: @example
 7938: create table ' aa , ' bb , ' cc ,
 7939: @end example
 7940: 
 7941: doc-state
 7942: 
 7943: 
 7944: @node Interpreter Directives,  , Interpret/Compile states, The Text Interpreter
 7945: @subsection Interpreter Directives
 7946: @cindex interpreter directives
 7947: @cindex conditional compilation
 7948: 
 7949: These words are usually used in interpret state; typically to control
 7950: which parts of a source file are processed by the text
 7951: interpreter. There are only a few ANS Forth Standard words, but Gforth
 7952: supplements these with a rich set of immediate control structure words
 7953: to compensate for the fact that the non-immediate versions can only be
 7954: used in compile state (@pxref{Control Structures}). Typical usages:
 7955: 
 7956: @example
 7957: FALSE Constant HAVE-ASSEMBLER
 7958: .
 7959: .
 7960: HAVE-ASSEMBLER [IF]
 7961: : ASSEMBLER-FEATURE
 7962:   ...
 7963: ;
 7964: [ENDIF]
 7965: .
 7966: .
 7967: : SEE
 7968:   ... \ general-purpose SEE code
 7969:   [ HAVE-ASSEMBLER [IF] ]
 7970:   ... \ assembler-specific SEE code
 7971:   [ [ENDIF] ]
 7972: ;
 7973: @end example
 7974: 
 7975: 
 7976: doc-[IF]
 7977: doc-[ELSE]
 7978: doc-[THEN]
 7979: doc-[ENDIF]
 7980: 
 7981: doc-[IFDEF]
 7982: doc-[IFUNDEF]
 7983: 
 7984: doc-[?DO]
 7985: doc-[DO]
 7986: doc-[FOR]
 7987: doc-[LOOP]
 7988: doc-[+LOOP]
 7989: doc-[NEXT]
 7990: 
 7991: doc-[BEGIN]
 7992: doc-[UNTIL]
 7993: doc-[AGAIN]
 7994: doc-[WHILE]
 7995: doc-[REPEAT]
 7996: 
 7997: 
 7998: @c -------------------------------------------------------------
 7999: @node Word Lists, Environmental Queries, The Text Interpreter, Words
 8000: @section Word Lists
 8001: @cindex word lists
 8002: @cindex header space
 8003: 
 8004: A wordlist is a list of named words; you can add new words and look up
 8005: words by name (and you can remove words in a restricted way with
 8006: markers).  Every named (and @code{reveal}ed) word is in one wordlist.
 8007: 
 8008: @cindex search order stack
 8009: The text interpreter searches the wordlists present in the search order
 8010: (a stack of wordlists), from the top to the bottom.  Within each
 8011: wordlist, the search starts conceptually at the newest word; i.e., if
 8012: two words in a wordlist have the same name, the newer word is found.
 8013: 
 8014: @cindex compilation word list
 8015: New words are added to the @dfn{compilation wordlist} (aka current
 8016: wordlist).
 8017: 
 8018: @cindex wid
 8019: A word list is identified by a cell-sized word list identifier (@i{wid})
 8020: in much the same way as a file is identified by a file handle. The
 8021: numerical value of the wid has no (portable) meaning, and might change
 8022: from session to session.
 8023: 
 8024: The ANS Forth ``Search order'' word set is intended to provide a set of
 8025: low-level tools that allow various different schemes to be
 8026: implemented. Gforth also provides @code{vocabulary}, a traditional Forth
 8027: word.  @file{compat/vocabulary.fs} provides an implementation in ANS
 8028: Forth.
 8029: 
 8030: @comment TODO: locals section refers to here, saying that every word list (aka
 8031: @comment vocabulary) has its own methods for searching etc. Need to document that.
 8032: @c anton: but better in a separate subsection on wordlist internals
 8033: 
 8034: @comment TODO: document markers, reveal, tables, mappedwordlist
 8035: 
 8036: @comment the gforthman- prefix is used to pick out the true definition of a
 8037: @comment word from the source files, rather than some alias.
 8038: 
 8039: doc-forth-wordlist
 8040: doc-definitions
 8041: doc-get-current
 8042: doc-set-current
 8043: doc-get-order
 8044: doc---gforthman-set-order
 8045: doc-wordlist
 8046: doc-table
 8047: doc->order
 8048: doc-previous
 8049: doc-also
 8050: doc---gforthman-forth
 8051: doc-only
 8052: doc---gforthman-order
 8053: 
 8054: doc-find
 8055: doc-search-wordlist
 8056: 
 8057: doc-words
 8058: doc-vlist
 8059: @c doc-words-deferred
 8060: 
 8061: @c doc-mappedwordlist @c map-structure undefined, implemantation-specific
 8062: doc-root
 8063: doc-vocabulary
 8064: doc-seal
 8065: doc-vocs
 8066: doc-current
 8067: doc-context
 8068: 
 8069: 
 8070: @menu
 8071: * Vocabularies::                
 8072: * Why use word lists?::         
 8073: * Word list example::           
 8074: @end menu
 8075: 
 8076: @node Vocabularies, Why use word lists?, Word Lists, Word Lists
 8077: @subsection Vocabularies
 8078: @cindex Vocabularies, detailed explanation
 8079: 
 8080: Here is an example of creating and using a new wordlist using ANS
 8081: Forth words:
 8082: 
 8083: @example
 8084: wordlist constant my-new-words-wordlist
 8085: : my-new-words get-order nip my-new-words-wordlist swap set-order ;
 8086: 
 8087: \ add it to the search order
 8088: also my-new-words
 8089: 
 8090: \ alternatively, add it to the search order and make it
 8091: \ the compilation word list
 8092: also my-new-words definitions
 8093: \ type "order" to see the problem
 8094: @end example
 8095: 
 8096: The problem with this example is that @code{order} has no way to
 8097: associate the name @code{my-new-words} with the wid of the word list (in
 8098: Gforth, @code{order} and @code{vocs} will display @code{???}  for a wid
 8099: that has no associated name). There is no Standard way of associating a
 8100: name with a wid.
 8101: 
 8102: In Gforth, this example can be re-coded using @code{vocabulary}, which
 8103: associates a name with a wid:
 8104: 
 8105: @example
 8106: vocabulary my-new-words
 8107: 
 8108: \ add it to the search order
 8109: also my-new-words
 8110: 
 8111: \ alternatively, add it to the search order and make it
 8112: \ the compilation word list
 8113: my-new-words definitions
 8114: \ type "order" to see that the problem is solved
 8115: @end example
 8116: 
 8117: 
 8118: @node Why use word lists?, Word list example, Vocabularies, Word Lists
 8119: @subsection Why use word lists?
 8120: @cindex word lists - why use them?
 8121: 
 8122: Here are some reasons why people use wordlists:
 8123: 
 8124: @itemize @bullet
 8125: 
 8126: @c anton: Gforth's hashing implementation makes the search speed
 8127: @c independent from the number of words.  But it is linear with the number
 8128: @c of wordlists that have to be searched, so in effect using more wordlists
 8129: @c actually slows down compilation.
 8130: 
 8131: @c @item
 8132: @c To improve compilation speed by reducing the number of header space
 8133: @c entries that must be searched. This is achieved by creating a new
 8134: @c word list that contains all of the definitions that are used in the
 8135: @c definition of a Forth system but which would not usually be used by
 8136: @c programs running on that system. That word list would be on the search
 8137: @c list when the Forth system was compiled but would be removed from the
 8138: @c search list for normal operation. This can be a useful technique for
 8139: @c low-performance systems (for example, 8-bit processors in embedded
 8140: @c systems) but is unlikely to be necessary in high-performance desktop
 8141: @c systems.
 8142: 
 8143: @item
 8144: To prevent a set of words from being used outside the context in which
 8145: they are valid. Two classic examples of this are an integrated editor
 8146: (all of the edit commands are defined in a separate word list; the
 8147: search order is set to the editor word list when the editor is invoked;
 8148: the old search order is restored when the editor is terminated) and an
 8149: integrated assembler (the op-codes for the machine are defined in a
 8150: separate word list which is used when a @code{CODE} word is defined).
 8151: 
 8152: @item
 8153: To organize the words of an application or library into a user-visible
 8154: set (in @code{forth-wordlist} or some other common wordlist) and a set
 8155: of helper words used just for the implementation (hidden in a separate
 8156: wordlist).  This keeps @code{words}' output smaller, separates
 8157: implementation and interface, and reduces the chance of name conflicts
 8158: within the common wordlist.
 8159: 
 8160: @item
 8161: To prevent a name-space clash between multiple definitions with the same
 8162: name. For example, when building a cross-compiler you might have a word
 8163: @code{IF} that generates conditional code for your target system. By
 8164: placing this definition in a different word list you can control whether
 8165: the host system's @code{IF} or the target system's @code{IF} get used in
 8166: any particular context by controlling the order of the word lists on the
 8167: search order stack.
 8168: 
 8169: @end itemize
 8170: 
 8171: The downsides of using wordlists are:
 8172: 
 8173: @itemize
 8174: 
 8175: @item
 8176: Debugging becomes more cumbersome.
 8177: 
 8178: @item
 8179: Name conflicts worked around with wordlists are still there, and you
 8180: have to arrange the search order carefully to get the desired results;
 8181: if you forget to do that, you get hard-to-find errors (as in any case
 8182: where you read the code differently from the compiler; @code{see} can
 8183: help seeing which of several possible words the name resolves to in such
 8184: cases).  @code{See} displays just the name of the words, not what
 8185: wordlist they belong to, so it might be misleading.  Using unique names
 8186: is a better approach to avoid name conflicts.
 8187: 
 8188: @item
 8189: You have to explicitly undo any changes to the search order.  In many
 8190: cases it would be more convenient if this happened implicitly.  Gforth
 8191: currently does not provide such a feature, but it may do so in the
 8192: future.
 8193: @end itemize
 8194: 
 8195: 
 8196: @node Word list example,  , Why use word lists?, Word Lists
 8197: @subsection Word list example
 8198: @cindex word lists - example
 8199: 
 8200: The following example is from the
 8201: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
 8202: garbage collector} and uses wordlists to separate public words from
 8203: helper words:
 8204: 
 8205: @example
 8206: get-current ( wid )
 8207: vocabulary garbage-collector also garbage-collector definitions
 8208: ... \ define helper words
 8209: ( wid ) set-current \ restore original (i.e., public) compilation wordlist
 8210: ... \ define the public (i.e., API) words
 8211:     \ they can refer to the helper words
 8212: previous \ restore original search order (helper words become invisible)
 8213: @end example
 8214: 
 8215: @c -------------------------------------------------------------
 8216: @node Environmental Queries, Files, Word Lists, Words
 8217: @section Environmental Queries
 8218: @cindex environmental queries
 8219: 
 8220: ANS Forth introduced the idea of ``environmental queries'' as a way
 8221: for a program running on a system to determine certain characteristics of the system.
 8222: The Standard specifies a number of strings that might be recognised by a system.
 8223: 
 8224: The Standard requires that the header space used for environmental queries
 8225: be distinct from the header space used for definitions.
 8226: 
 8227: Typically, environmental queries are supported by creating a set of
 8228: definitions in a word list that is @i{only} used during environmental
 8229: queries; that is what Gforth does. There is no Standard way of adding
 8230: definitions to the set of recognised environmental queries, but any
 8231: implementation that supports the loading of optional word sets must have
 8232: some mechanism for doing this (after loading the word set, the
 8233: associated environmental query string must return @code{true}). In
 8234: Gforth, the word list used to honour environmental queries can be
 8235: manipulated just like any other word list.
 8236: 
 8237: 
 8238: doc-environment?
 8239: doc-environment-wordlist
 8240: 
 8241: doc-gforth
 8242: doc-os-class
 8243: 
 8244: 
 8245: Note that, whilst the documentation for (e.g.) @code{gforth} shows it
 8246: returning two items on the stack, querying it using @code{environment?}
 8247: will return an additional item; the @code{true} flag that shows that the
 8248: string was recognised.
 8249: 
 8250: @comment TODO Document the standard strings or note where they are documented herein
 8251: 
 8252: Here are some examples of using environmental queries:
 8253: 
 8254: @example
 8255: s" address-unit-bits" environment? 0=
 8256: [IF]
 8257:      cr .( environmental attribute address-units-bits unknown... ) cr
 8258: [ELSE]
 8259:      drop \ ensure balanced stack effect
 8260: [THEN]
 8261: 
 8262: \ this might occur in the prelude of a standard program that uses THROW
 8263: s" exception" environment? [IF]
 8264:    0= [IF]
 8265:       : throw abort" exception thrown" ;
 8266:    [THEN]
 8267: [ELSE] \ we don't know, so make sure
 8268:    : throw abort" exception thrown" ;
 8269: [THEN]
 8270: 
 8271: s" gforth" environment? [IF] .( Gforth version ) TYPE
 8272:                         [ELSE] .( Not Gforth..) [THEN]
 8273: 
 8274: \ a program using v*
 8275: s" gforth" environment? [IF]
 8276:   s" 0.5.0" compare 0< [IF] \ v* is a primitive since 0.5.0
 8277:    : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
 8278:      >r swap 2swap swap 0e r> 0 ?DO
 8279:        dup f@ over + 2swap dup f@ f* f+ over + 2swap
 8280:      LOOP
 8281:      2drop 2drop ; 
 8282:   [THEN]
 8283: [ELSE] \ 
 8284:   : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
 8285:   ...
 8286: [THEN]
 8287: @end example
 8288: 
 8289: Here is an example of adding a definition to the environment word list:
 8290: 
 8291: @example
 8292: get-current environment-wordlist set-current
 8293: true constant block
 8294: true constant block-ext
 8295: set-current
 8296: @end example
 8297: 
 8298: You can see what definitions are in the environment word list like this:
 8299: 
 8300: @example
 8301: environment-wordlist >order words previous
 8302: @end example
 8303: 
 8304: 
 8305: @c -------------------------------------------------------------
 8306: @node Files, Blocks, Environmental Queries, Words
 8307: @section Files
 8308: @cindex files
 8309: @cindex I/O - file-handling
 8310: 
 8311: Gforth provides facilities for accessing files that are stored in the
 8312: host operating system's file-system. Files that are processed by Gforth
 8313: can be divided into two categories:
 8314: 
 8315: @itemize @bullet
 8316: @item
 8317: Files that are processed by the Text Interpreter (@dfn{Forth source files}).
 8318: @item
 8319: Files that are processed by some other program (@dfn{general files}).
 8320: @end itemize
 8321: 
 8322: @menu
 8323: * Forth source files::          
 8324: * General files::               
 8325: * Search Paths::                
 8326: @end menu
 8327: 
 8328: @c -------------------------------------------------------------
 8329: @node Forth source files, General files, Files, Files
 8330: @subsection Forth source files
 8331: @cindex including files
 8332: @cindex Forth source files
 8333: 
 8334: The simplest way to interpret the contents of a file is to use one of
 8335: these two formats:
 8336: 
 8337: @example
 8338: include mysource.fs
 8339: s" mysource.fs" included
 8340: @end example
 8341: 
 8342: You usually want to include a file only if it is not included already
 8343: (by, say, another source file). In that case, you can use one of these
 8344: three formats:
 8345: 
 8346: @example
 8347: require mysource.fs
 8348: needs mysource.fs
 8349: s" mysource.fs" required
 8350: @end example
 8351: 
 8352: @cindex stack effect of included files
 8353: @cindex including files, stack effect
 8354: It is good practice to write your source files such that interpreting them
 8355: does not change the stack. Source files designed in this way can be used with
 8356: @code{required} and friends without complications. For example:
 8357: 
 8358: @example
 8359: 1024 require foo.fs drop
 8360: @end example
 8361: 
 8362: Here you want to pass the argument 1024 (e.g., a buffer size) to
 8363: @file{foo.fs}.  Interpreting @file{foo.fs} has the stack effect ( n -- n
 8364: ), which allows its use with @code{require}.  Of course with such
 8365: parameters to required files, you have to ensure that the first
 8366: @code{require} fits for all uses (i.e., @code{require} it early in the
 8367: master load file).
 8368: 
 8369: doc-include-file
 8370: doc-included
 8371: doc-included?
 8372: doc-include
 8373: doc-required
 8374: doc-require
 8375: doc-needs
 8376: @c doc-init-included-files @c internal
 8377: doc-sourcefilename
 8378: doc-sourceline#
 8379: 
 8380: A definition in ANS Forth for @code{required} is provided in
 8381: @file{compat/required.fs}.
 8382: 
 8383: @c -------------------------------------------------------------
 8384: @node General files, Search Paths, Forth source files, Files
 8385: @subsection General files
 8386: @cindex general files
 8387: @cindex file-handling
 8388: 
 8389: Files are opened/created by name and type. The following file access
 8390: methods (FAMs) are recognised:
 8391: 
 8392: @cindex fam (file access method)
 8393: doc-r/o
 8394: doc-r/w
 8395: doc-w/o
 8396: doc-bin
 8397: 
 8398: 
 8399: When a file is opened/created, it returns a file identifier,
 8400: @i{wfileid} that is used for all other file commands. All file
 8401: commands also return a status value, @i{wior}, that is 0 for a
 8402: successful operation and an implementation-defined non-zero value in the
 8403: case of an error.
 8404: 
 8405: 
 8406: doc-open-file
 8407: doc-create-file
 8408: 
 8409: doc-close-file
 8410: doc-delete-file
 8411: doc-rename-file
 8412: doc-read-file
 8413: doc-read-line
 8414: doc-write-file
 8415: doc-write-line
 8416: doc-emit-file
 8417: doc-flush-file
 8418: 
 8419: doc-file-status
 8420: doc-file-position
 8421: doc-reposition-file
 8422: doc-file-size
 8423: doc-resize-file
 8424: 
 8425: 
 8426: @c ---------------------------------------------------------
 8427: @node Search Paths,  , General files, Files
 8428: @subsection Search Paths
 8429: @cindex path for @code{included}
 8430: @cindex file search path
 8431: @cindex @code{include} search path
 8432: @cindex search path for files
 8433: 
 8434: If you specify an absolute filename (i.e., a filename starting with
 8435: @file{/} or @file{~}, or with @file{:} in the second position (as in
 8436: @samp{C:...})) for @code{included} and friends, that file is included
 8437: just as you would expect.
 8438: 
 8439: If the filename starts with @file{./}, this refers to the directory that
 8440: the present file was @code{included} from.  This allows files to include
 8441: other files relative to their own position (irrespective of the current
 8442: working directory or the absolute position).  This feature is essential
 8443: for libraries consisting of several files, where a file may include
 8444: other files from the library.  It corresponds to @code{#include "..."}
 8445: in C. If the current input source is not a file, @file{.} refers to the
 8446: directory of the innermost file being included, or, if there is no file
 8447: being included, to the current working directory.
 8448: 
 8449: For relative filenames (not starting with @file{./}), Gforth uses a
 8450: search path similar to Forth's search order (@pxref{Word Lists}). It
 8451: tries to find the given filename in the directories present in the path,
 8452: and includes the first one it finds. There are separate search paths for
 8453: Forth source files and general files.  If the search path contains the
 8454: directory @file{.}, this refers to the directory of the current file, or
 8455: the working directory, as if the file had been specified with @file{./}.
 8456: 
 8457: Use @file{~+} to refer to the current working directory (as in the
 8458: @code{bash}).
 8459: 
 8460: @c anton: fold the following subsubsections into this subsection?
 8461: 
 8462: @menu
 8463: * Source Search Paths::         
 8464: * General Search Paths::        
 8465: @end menu
 8466: 
 8467: @c ---------------------------------------------------------
 8468: @node Source Search Paths, General Search Paths, Search Paths, Search Paths
 8469: @subsubsection Source Search Paths
 8470: @cindex search path control, source files
 8471: 
 8472: The search path is initialized when you start Gforth (@pxref{Invoking
 8473: Gforth}). You can display it and change it using @code{fpath} in
 8474: combination with the general path handling words.
 8475: 
 8476: doc-fpath
 8477: @c the functionality of the following words is easily available through
 8478: @c   fpath and the general path words.  The may go away.
 8479: @c doc-.fpath
 8480: @c doc-fpath+
 8481: @c doc-fpath=
 8482: @c doc-open-fpath-file
 8483: 
 8484: @noindent
 8485: Here is an example of using @code{fpath} and @code{require}:
 8486: 
 8487: @example
 8488: fpath path= /usr/lib/forth/|./
 8489: require timer.fs
 8490: @end example
 8491: 
 8492: 
 8493: @c ---------------------------------------------------------
 8494: @node General Search Paths,  , Source Search Paths, Search Paths
 8495: @subsubsection General Search Paths
 8496: @cindex search path control, source files
 8497: 
 8498: Your application may need to search files in several directories, like
 8499: @code{included} does. To facilitate this, Gforth allows you to define
 8500: and use your own search paths, by providing generic equivalents of the
 8501: Forth search path words:
 8502: 
 8503: doc-open-path-file
 8504: doc-path-allot
 8505: doc-clear-path
 8506: doc-also-path
 8507: doc-.path
 8508: doc-path+
 8509: doc-path=
 8510: 
 8511: @c anton: better define a word for it, say "path-allot ( ucount -- path-addr )
 8512: 
 8513: Here's an example of creating an empty search path:
 8514: @c
 8515: @example
 8516: create mypath 500 path-allot \ maximum length 500 chars (is checked)
 8517: @end example
 8518: 
 8519: @c -------------------------------------------------------------
 8520: @node Blocks, Other I/O, Files, Words
 8521: @section Blocks
 8522: @cindex I/O - blocks
 8523: @cindex blocks
 8524: 
 8525: When you run Gforth on a modern desk-top computer, it runs under the
 8526: control of an operating system which provides certain services.  One of
 8527: these services is @var{file services}, which allows Forth source code
 8528: and data to be stored in files and read into Gforth (@pxref{Files}).
 8529: 
 8530: Traditionally, Forth has been an important programming language on
 8531: systems where it has interfaced directly to the underlying hardware with
 8532: no intervening operating system. Forth provides a mechanism, called
 8533: @dfn{blocks}, for accessing mass storage on such systems.
 8534: 
 8535: A block is a 1024-byte data area, which can be used to hold data or
 8536: Forth source code. No structure is imposed on the contents of the
 8537: block. A block is identified by its number; blocks are numbered
 8538: contiguously from 1 to an implementation-defined maximum.
 8539: 
 8540: A typical system that used blocks but no operating system might use a
 8541: single floppy-disk drive for mass storage, with the disks formatted to
 8542: provide 256-byte sectors. Blocks would be implemented by assigning the
 8543: first four sectors of the disk to block 1, the second four sectors to
 8544: block 2 and so on, up to the limit of the capacity of the disk. The disk
 8545: would not contain any file system information, just the set of blocks.
 8546: 
 8547: @cindex blocks file
 8548: On systems that do provide file services, blocks are typically
 8549: implemented by storing a sequence of blocks within a single @dfn{blocks
 8550: file}.  The size of the blocks file will be an exact multiple of 1024
 8551: bytes, corresponding to the number of blocks it contains. This is the
 8552: mechanism that Gforth uses.
 8553: 
 8554: @cindex @file{blocks.fb}
 8555: Only one blocks file can be open at a time. If you use block words without
 8556: having specified a blocks file, Gforth defaults to the blocks file
 8557: @file{blocks.fb}. Gforth uses the Forth search path when attempting to
 8558: locate a blocks file (@pxref{Source Search Paths}).
 8559: 
 8560: @cindex block buffers
 8561: When you read and write blocks under program control, Gforth uses a
 8562: number of @dfn{block buffers} as intermediate storage. These buffers are
 8563: not used when you use @code{load} to interpret the contents of a block.
 8564: 
 8565: The behaviour of the block buffers is analagous to that of a cache.
 8566: Each block buffer has three states:
 8567: 
 8568: @itemize @bullet
 8569: @item
 8570: Unassigned
 8571: @item
 8572: Assigned-clean
 8573: @item
 8574: Assigned-dirty
 8575: @end itemize
 8576: 
 8577: Initially, all block buffers are @i{unassigned}. In order to access a
 8578: block, the block (specified by its block number) must be assigned to a
 8579: block buffer.
 8580: 
 8581: The assignment of a block to a block buffer is performed by @code{block}
 8582: or @code{buffer}. Use @code{block} when you wish to modify the existing
 8583: contents of a block. Use @code{buffer} when you don't care about the
 8584: existing contents of the block@footnote{The ANS Forth definition of
 8585: @code{buffer} is intended not to cause disk I/O; if the data associated
 8586: with the particular block is already stored in a block buffer due to an
 8587: earlier @code{block} command, @code{buffer} will return that block
 8588: buffer and the existing contents of the block will be
 8589: available. Otherwise, @code{buffer} will simply assign a new, empty
 8590: block buffer for the block.}.
 8591: 
 8592: Once a block has been assigned to a block buffer using @code{block} or
 8593: @code{buffer}, that block buffer becomes the @i{current block
 8594: buffer}. Data may only be manipulated (read or written) within the
 8595: current block buffer.
 8596: 
 8597: When the contents of the current block buffer has been modified it is
 8598: necessary, @emph{before calling @code{block} or @code{buffer} again}, to
 8599: either abandon the changes (by doing nothing) or mark the block as
 8600: changed (assigned-dirty), using @code{update}. Using @code{update} does
 8601: not change the blocks file; it simply changes a block buffer's state to
 8602: @i{assigned-dirty}.  The block will be written implicitly when it's
 8603: buffer is needed for another block, or explicitly by @code{flush} or
 8604: @code{save-buffers}.
 8605: 
 8606: word @code{Flush} writes all @i{assigned-dirty} blocks back to the
 8607: blocks file on disk. Leaving Gforth with @code{bye} also performs a
 8608: @code{flush}.
 8609: 
 8610: In Gforth, @code{block} and @code{buffer} use a @i{direct-mapped}
 8611: algorithm to assign a block buffer to a block. That means that any
 8612: particular block can only be assigned to one specific block buffer,
 8613: called (for the particular operation) the @i{victim buffer}. If the
 8614: victim buffer is @i{unassigned} or @i{assigned-clean} it is allocated to
 8615: the new block immediately. If it is @i{assigned-dirty} its current
 8616: contents are written back to the blocks file on disk before it is
 8617: allocated to the new block.
 8618: 
 8619: Although no structure is imposed on the contents of a block, it is
 8620: traditional to display the contents as 16 lines each of 64 characters.  A
 8621: block provides a single, continuous stream of input (for example, it
 8622: acts as a single parse area) -- there are no end-of-line characters
 8623: within a block, and no end-of-file character at the end of a
 8624: block. There are two consequences of this:
 8625: 
 8626: @itemize @bullet
 8627: @item
 8628: The last character of one line wraps straight into the first character
 8629: of the following line
 8630: @item
 8631: The word @code{\} -- comment to end of line -- requires special
 8632: treatment; in the context of a block it causes all characters until the
 8633: end of the current 64-character ``line'' to be ignored.
 8634: @end itemize
 8635: 
 8636: In Gforth, when you use @code{block} with a non-existent block number,
 8637: the current blocks file will be extended to the appropriate size and the
 8638: block buffer will be initialised with spaces.
 8639: 
 8640: Gforth includes a simple block editor (type @code{use blocked.fb 0 list}
 8641: for details) but doesn't encourage the use of blocks; the mechanism is
 8642: only provided for backward compatibility -- ANS Forth requires blocks to
 8643: be available when files are.
 8644: 
 8645: Common techniques that are used when working with blocks include:
 8646: 
 8647: @itemize @bullet
 8648: @item
 8649: A screen editor that allows you to edit blocks without leaving the Forth
 8650: environment.
 8651: @item
 8652: Shadow screens; where every code block has an associated block
 8653: containing comments (for example: code in odd block numbers, comments in
 8654: even block numbers). Typically, the block editor provides a convenient
 8655: mechanism to toggle between code and comments.
 8656: @item
 8657: Load blocks; a single block (typically block 1) contains a number of
 8658: @code{thru} commands which @code{load} the whole of the application.
 8659: @end itemize
 8660: 
 8661: See Frank Sergeant's Pygmy Forth to see just how well blocks can be
 8662: integrated into a Forth programming environment.
 8663: 
 8664: @comment TODO what about errors on open-blocks?
 8665: 
 8666: doc-open-blocks
 8667: doc-use
 8668: doc-block-offset
 8669: doc-get-block-fid
 8670: doc-block-position
 8671: 
 8672: doc-list
 8673: doc-scr
 8674: 
 8675: doc---gforthman-block
 8676: doc-buffer
 8677: 
 8678: doc-empty-buffers
 8679: doc-empty-buffer
 8680: doc-update
 8681: doc-updated?
 8682: doc-save-buffers
 8683: doc-save-buffer
 8684: doc-flush
 8685: 
 8686: doc-load
 8687: doc-thru
 8688: doc-+load
 8689: doc-+thru
 8690: doc---gforthman--->
 8691: doc-block-included
 8692: 
 8693: 
 8694: @c -------------------------------------------------------------
 8695: @node Other I/O, Locals, Blocks, Words
 8696: @section Other I/O
 8697: @cindex I/O - keyboard and display
 8698: 
 8699: @menu
 8700: * Simple numeric output::       Predefined formats
 8701: * Formatted numeric output::    Formatted (pictured) output
 8702: * String Formats::              How Forth stores strings in memory
 8703: * Displaying characters and strings::  Other stuff
 8704: * Input::                       Input
 8705: @end menu
 8706: 
 8707: @node Simple numeric output, Formatted numeric output, Other I/O, Other I/O
 8708: @subsection Simple numeric output
 8709: @cindex numeric output - simple/free-format
 8710: 
 8711: The simplest output functions are those that display numbers from the
 8712: data or floating-point stacks. Floating-point output is always displayed
 8713: using base 10. Numbers displayed from the data stack use the value stored
 8714: in @code{base}.
 8715: 
 8716: 
 8717: doc-.
 8718: doc-dec.
 8719: doc-hex.
 8720: doc-u.
 8721: doc-.r
 8722: doc-u.r
 8723: doc-d.
 8724: doc-ud.
 8725: doc-d.r
 8726: doc-ud.r
 8727: doc-f.
 8728: doc-fe.
 8729: doc-fs.
 8730: 
 8731: 
 8732: Examples of printing the number 1234.5678E23 in the different floating-point output
 8733: formats are shown below:
 8734: 
 8735: @example
 8736: f. 123456779999999000000000000.
 8737: fe. 123.456779999999E24
 8738: fs. 1.23456779999999E26
 8739: @end example
 8740: 
 8741: 
 8742: @node Formatted numeric output, String Formats, Simple numeric output, Other I/O
 8743: @subsection Formatted numeric output
 8744: @cindex formatted numeric output
 8745: @cindex pictured numeric output
 8746: @cindex numeric output - formatted
 8747: 
 8748: Forth traditionally uses a technique called @dfn{pictured numeric
 8749: output} for formatted printing of integers.  In this technique, digits
 8750: are extracted from the number (using the current output radix defined by
 8751: @code{base}), converted to ASCII codes and appended to a string that is
 8752: built in a scratch-pad area of memory (@pxref{core-idef,
 8753: Implementation-defined options, Implementation-defined
 8754: options}). Arbitrary characters can be appended to the string during the
 8755: extraction process. The completed string is specified by an address
 8756: and length and can be manipulated (@code{TYPE}ed, copied, modified)
 8757: under program control.
 8758: 
 8759: All of the integer output words described in the previous section
 8760: (@pxref{Simple numeric output}) are implemented in Gforth using pictured
 8761: numeric output.
 8762: 
 8763: Three important things to remember about pictured numeric output:
 8764: 
 8765: @itemize @bullet
 8766: @item
 8767: It always operates on double-precision numbers; to display a
 8768: single-precision number, convert it first (for ways of doing this
 8769: @pxref{Double precision}).
 8770: @item
 8771: It always treats the double-precision number as though it were
 8772: unsigned. The examples below show ways of printing signed numbers.
 8773: @item
 8774: The string is built up from right to left; least significant digit first.
 8775: @end itemize
 8776: 
 8777: 
 8778: doc-<#
 8779: doc-<<#
 8780: doc-#
 8781: doc-#s
 8782: doc-hold
 8783: doc-sign
 8784: doc-#>
 8785: doc-#>>
 8786: 
 8787: doc-represent
 8788: 
 8789: 
 8790: @noindent
 8791: Here are some examples of using pictured numeric output:
 8792: 
 8793: @example
 8794: : my-u. ( u -- )
 8795:   \ Simplest use of pns.. behaves like Standard u. 
 8796:   0              \ convert to unsigned double
 8797:   <<#            \ start conversion
 8798:   #s             \ convert all digits
 8799:   #>             \ complete conversion
 8800:   TYPE SPACE     \ display, with trailing space
 8801:   #>> ;          \ release hold area
 8802: 
 8803: : cents-only ( u -- )
 8804:   0              \ convert to unsigned double
 8805:   <<#            \ start conversion
 8806:   # #            \ convert two least-significant digits
 8807:   #>             \ complete conversion, discard other digits
 8808:   TYPE SPACE     \ display, with trailing space
 8809:   #>> ;          \ release hold area
 8810: 
 8811: : dollars-and-cents ( u -- )
 8812:   0              \ convert to unsigned double
 8813:   <<#            \ start conversion
 8814:   # #            \ convert two least-significant digits
 8815:   [char] . hold  \ insert decimal point
 8816:   #s             \ convert remaining digits
 8817:   [char] $ hold  \ append currency symbol
 8818:   #>             \ complete conversion
 8819:   TYPE SPACE     \ display, with trailing space
 8820:   #>> ;          \ release hold area
 8821: 
 8822: : my-. ( n -- )
 8823:   \ handling negatives.. behaves like Standard .
 8824:   s>d            \ convert to signed double
 8825:   swap over dabs \ leave sign byte followed by unsigned double
 8826:   <<#            \ start conversion
 8827:   #s             \ convert all digits
 8828:   rot sign       \ get at sign byte, append "-" if needed
 8829:   #>             \ complete conversion
 8830:   TYPE SPACE     \ display, with trailing space
 8831:   #>> ;          \ release hold area
 8832: 
 8833: : account. ( n -- )
 8834:   \ accountants don't like minus signs, they use parentheses
 8835:   \ for negative numbers
 8836:   s>d            \ convert to signed double
 8837:   swap over dabs \ leave sign byte followed by unsigned double
 8838:   <<#            \ start conversion
 8839:   2 pick         \ get copy of sign byte
 8840:   0< IF [char] ) hold THEN \ right-most character of output
 8841:   #s             \ convert all digits
 8842:   rot            \ get at sign byte
 8843:   0< IF [char] ( hold THEN
 8844:   #>             \ complete conversion
 8845:   TYPE SPACE     \ display, with trailing space
 8846:   #>> ;          \ release hold area
 8847: 
 8848: @end example
 8849: 
 8850: Here are some examples of using these words:
 8851: 
 8852: @example
 8853: 1 my-u. 1
 8854: hex -1 my-u. decimal FFFFFFFF
 8855: 1 cents-only 01
 8856: 1234 cents-only 34
 8857: 2 dollars-and-cents $0.02
 8858: 1234 dollars-and-cents $12.34
 8859: 123 my-. 123
 8860: -123 my. -123
 8861: 123 account. 123
 8862: -456 account. (456)
 8863: @end example
 8864: 
 8865: 
 8866: @node String Formats, Displaying characters and strings, Formatted numeric output, Other I/O
 8867: @subsection String Formats
 8868: @cindex strings - see character strings
 8869: @cindex character strings - formats
 8870: @cindex I/O - see character strings
 8871: @cindex counted strings
 8872: 
 8873: @c anton: this does not really belong here; maybe the memory section,
 8874: @c  or the principles chapter
 8875: 
 8876: Forth commonly uses two different methods for representing character
 8877: strings:
 8878: 
 8879: @itemize @bullet
 8880: @item
 8881: @cindex address of counted string
 8882: @cindex counted string
 8883: As a @dfn{counted string}, represented by a @i{c-addr}. The char
 8884: addressed by @i{c-addr} contains a character-count, @i{n}, of the
 8885: string and the string occupies the subsequent @i{n} char addresses in
 8886: memory.
 8887: @item
 8888: As cell pair on the stack; @i{c-addr u}, where @i{u} is the length
 8889: of the string in characters, and @i{c-addr} is the address of the
 8890: first byte of the string.
 8891: @end itemize
 8892: 
 8893: ANS Forth encourages the use of the second format when representing
 8894: strings.
 8895: 
 8896: 
 8897: doc-count
 8898: 
 8899: 
 8900: For words that move, copy and search for strings see @ref{Memory
 8901: Blocks}. For words that display characters and strings see
 8902: @ref{Displaying characters and strings}.
 8903: 
 8904: @node Displaying characters and strings, Input, String Formats, Other I/O
 8905: @subsection Displaying characters and strings
 8906: @cindex characters - compiling and displaying
 8907: @cindex character strings - compiling and displaying
 8908: 
 8909: This section starts with a glossary of Forth words and ends with a set
 8910: of examples.
 8911: 
 8912: 
 8913: doc-bl
 8914: doc-space
 8915: doc-spaces
 8916: doc-emit
 8917: doc-toupper
 8918: doc-."
 8919: doc-.(
 8920: doc-type
 8921: doc-typewhite
 8922: doc-cr
 8923: @cindex cursor control
 8924: doc-at-xy
 8925: doc-page
 8926: doc-s"
 8927: doc-c"
 8928: doc-char
 8929: doc-[char]
 8930: 
 8931: 
 8932: @noindent
 8933: As an example, consider the following text, stored in a file @file{test.fs}:
 8934: 
 8935: @example
 8936: .( text-1)
 8937: : my-word
 8938:   ." text-2" cr
 8939:   .( text-3)
 8940: ;
 8941: 
 8942: ." text-4"
 8943: 
 8944: : my-char
 8945:   [char] ALPHABET emit
 8946:   char emit
 8947: ;
 8948: @end example
 8949: 
 8950: When you load this code into Gforth, the following output is generated:
 8951: 
 8952: @example
 8953: @kbd{include test.fs @key{RET}} text-1text-3text-4 ok
 8954: @end example
 8955: 
 8956: @itemize @bullet
 8957: @item
 8958: Messages @code{text-1} and @code{text-3} are displayed because @code{.(} 
 8959: is an immediate word; it behaves in the same way whether it is used inside
 8960: or outside a colon definition.
 8961: @item
 8962: Message @code{text-4} is displayed because of Gforth's added interpretation
 8963: semantics for @code{."}.
 8964: @item
 8965: Message @code{text-2} is @i{not} displayed, because the text interpreter
 8966: performs the compilation semantics for @code{."} within the definition of
 8967: @code{my-word}.
 8968: @end itemize
 8969: 
 8970: Here are some examples of executing @code{my-word} and @code{my-char}:
 8971: 
 8972: @example
 8973: @kbd{my-word @key{RET}} text-2
 8974:  ok
 8975: @kbd{my-char fred @key{RET}} Af ok
 8976: @kbd{my-char jim @key{RET}} Aj ok
 8977: @end example
 8978: 
 8979: @itemize @bullet
 8980: @item
 8981: Message @code{text-2} is displayed because of the run-time behaviour of
 8982: @code{."}.
 8983: @item
 8984: @code{[char]} compiles the ``A'' from ``ALPHABET'' and puts its display code
 8985: on the stack at run-time. @code{emit} always displays the character
 8986: when @code{my-char} is executed.
 8987: @item
 8988: @code{char} parses a string at run-time and the second @code{emit} displays
 8989: the first character of the string.
 8990: @item
 8991: If you type @code{see my-char} you can see that @code{[char]} discarded
 8992: the text ``LPHABET'' and only compiled the display code for ``A'' into the
 8993: definition of @code{my-char}.
 8994: @end itemize
 8995: 
 8996: 
 8997: 
 8998: @node Input,  , Displaying characters and strings, Other I/O
 8999: @subsection Input
 9000: @cindex input
 9001: @cindex I/O - see input
 9002: @cindex parsing a string
 9003: 
 9004: For ways of storing character strings in memory see @ref{String Formats}.
 9005: 
 9006: @comment TODO examples for >number >float accept key key? pad parse word refill
 9007: @comment then index them
 9008: 
 9009: 
 9010: doc-key
 9011: doc-key?
 9012: doc-ekey
 9013: doc-ekey?
 9014: doc-ekey>char
 9015: doc->number
 9016: doc->float
 9017: doc-accept
 9018: doc-pad
 9019: @c anton: these belong in the input stream section
 9020: doc-parse
 9021: doc-word
 9022: doc-sword
 9023: doc-name
 9024: doc-refill
 9025: @comment obsolescent words..
 9026: doc-convert
 9027: doc-query
 9028: doc-expect
 9029: doc-span
 9030: 
 9031: 
 9032: @c -------------------------------------------------------------
 9033: @node Locals, Structures, Other I/O, Words
 9034: @section Locals
 9035: @cindex locals
 9036: 
 9037: Local variables can make Forth programming more enjoyable and Forth
 9038: programs easier to read. Unfortunately, the locals of ANS Forth are
 9039: laden with restrictions. Therefore, we provide not only the ANS Forth
 9040: locals wordset, but also our own, more powerful locals wordset (we
 9041: implemented the ANS Forth locals wordset through our locals wordset).
 9042: 
 9043: The ideas in this section have also been published in M. Anton Ertl,
 9044: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl94l.ps.gz,
 9045: Automatic Scoping of Local Variables}}, EuroForth '94.
 9046: 
 9047: @menu
 9048: * Gforth locals::               
 9049: * ANS Forth locals::            
 9050: @end menu
 9051: 
 9052: @node Gforth locals, ANS Forth locals, Locals, Locals
 9053: @subsection Gforth locals
 9054: @cindex Gforth locals
 9055: @cindex locals, Gforth style
 9056: 
 9057: Locals can be defined with
 9058: 
 9059: @example
 9060: @{ local1 local2 ... -- comment @}
 9061: @end example
 9062: or
 9063: @example
 9064: @{ local1 local2 ... @}
 9065: @end example
 9066: 
 9067: E.g.,
 9068: @example
 9069: : max @{ n1 n2 -- n3 @}
 9070:  n1 n2 > if
 9071:    n1
 9072:  else
 9073:    n2
 9074:  endif ;
 9075: @end example
 9076: 
 9077: The similarity of locals definitions with stack comments is intended. A
 9078: locals definition often replaces the stack comment of a word. The order
 9079: of the locals corresponds to the order in a stack comment and everything
 9080: after the @code{--} is really a comment.
 9081: 
 9082: This similarity has one disadvantage: It is too easy to confuse locals
 9083: declarations with stack comments, causing bugs and making them hard to
 9084: find. However, this problem can be avoided by appropriate coding
 9085: conventions: Do not use both notations in the same program. If you do,
 9086: they should be distinguished using additional means, e.g. by position.
 9087: 
 9088: @cindex types of locals
 9089: @cindex locals types
 9090: The name of the local may be preceded by a type specifier, e.g.,
 9091: @code{F:} for a floating point value:
 9092: 
 9093: @example
 9094: : CX* @{ F: Ar F: Ai F: Br F: Bi -- Cr Ci @}
 9095: \ complex multiplication
 9096:  Ar Br f* Ai Bi f* f-
 9097:  Ar Bi f* Ai Br f* f+ ;
 9098: @end example
 9099: 
 9100: @cindex flavours of locals
 9101: @cindex locals flavours
 9102: @cindex value-flavoured locals
 9103: @cindex variable-flavoured locals
 9104: Gforth currently supports cells (@code{W:}, @code{W^}), doubles
 9105: (@code{D:}, @code{D^}), floats (@code{F:}, @code{F^}) and characters
 9106: (@code{C:}, @code{C^}) in two flavours: a value-flavoured local (defined
 9107: with @code{W:}, @code{D:} etc.) produces its value and can be changed
 9108: with @code{TO}. A variable-flavoured local (defined with @code{W^} etc.)
 9109: produces its address (which becomes invalid when the variable's scope is
 9110: left). E.g., the standard word @code{emit} can be defined in terms of
 9111: @code{type} like this:
 9112: 
 9113: @example
 9114: : emit @{ C^ char* -- @}
 9115:     char* 1 type ;
 9116: @end example
 9117: 
 9118: @cindex default type of locals
 9119: @cindex locals, default type
 9120: A local without type specifier is a @code{W:} local. Both flavours of
 9121: locals are initialized with values from the data or FP stack.
 9122: 
 9123: Currently there is no way to define locals with user-defined data
 9124: structures, but we are working on it.
 9125: 
 9126: Gforth allows defining locals everywhere in a colon definition. This
 9127: poses the following questions:
 9128: 
 9129: @menu
 9130: * Where are locals visible by name?::  
 9131: * How long do locals live?::    
 9132: * Locals programming style::    
 9133: * Locals implementation::       
 9134: @end menu
 9135: 
 9136: @node Where are locals visible by name?, How long do locals live?, Gforth locals, Gforth locals
 9137: @subsubsection Where are locals visible by name?
 9138: @cindex locals visibility
 9139: @cindex visibility of locals
 9140: @cindex scope of locals
 9141: 
 9142: Basically, the answer is that locals are visible where you would expect
 9143: it in block-structured languages, and sometimes a little longer. If you
 9144: want to restrict the scope of a local, enclose its definition in
 9145: @code{SCOPE}...@code{ENDSCOPE}.
 9146: 
 9147: 
 9148: doc-scope
 9149: doc-endscope
 9150: 
 9151: 
 9152: These words behave like control structure words, so you can use them
 9153: with @code{CS-PICK} and @code{CS-ROLL} to restrict the scope in
 9154: arbitrary ways.
 9155: 
 9156: If you want a more exact answer to the visibility question, here's the
 9157: basic principle: A local is visible in all places that can only be
 9158: reached through the definition of the local@footnote{In compiler
 9159: construction terminology, all places dominated by the definition of the
 9160: local.}. In other words, it is not visible in places that can be reached
 9161: without going through the definition of the local. E.g., locals defined
 9162: in @code{IF}...@code{ENDIF} are visible until the @code{ENDIF}, locals
 9163: defined in @code{BEGIN}...@code{UNTIL} are visible after the
 9164: @code{UNTIL} (until, e.g., a subsequent @code{ENDSCOPE}).
 9165: 
 9166: The reasoning behind this solution is: We want to have the locals
 9167: visible as long as it is meaningful. The user can always make the
 9168: visibility shorter by using explicit scoping. In a place that can
 9169: only be reached through the definition of a local, the meaning of a
 9170: local name is clear. In other places it is not: How is the local
 9171: initialized at the control flow path that does not contain the
 9172: definition? Which local is meant, if the same name is defined twice in
 9173: two independent control flow paths?
 9174: 
 9175: This should be enough detail for nearly all users, so you can skip the
 9176: rest of this section. If you really must know all the gory details and
 9177: options, read on.
 9178: 
 9179: In order to implement this rule, the compiler has to know which places
 9180: are unreachable. It knows this automatically after @code{AHEAD},
 9181: @code{AGAIN}, @code{EXIT} and @code{LEAVE}; in other cases (e.g., after
 9182: most @code{THROW}s), you can use the word @code{UNREACHABLE} to tell the
 9183: compiler that the control flow never reaches that place. If
 9184: @code{UNREACHABLE} is not used where it could, the only consequence is
 9185: that the visibility of some locals is more limited than the rule above
 9186: says. If @code{UNREACHABLE} is used where it should not (i.e., if you
 9187: lie to the compiler), buggy code will be produced.
 9188: 
 9189: 
 9190: doc-unreachable
 9191: 
 9192: 
 9193: Another problem with this rule is that at @code{BEGIN}, the compiler
 9194: does not know which locals will be visible on the incoming
 9195: back-edge. All problems discussed in the following are due to this
 9196: ignorance of the compiler (we discuss the problems using @code{BEGIN}
 9197: loops as examples; the discussion also applies to @code{?DO} and other
 9198: loops). Perhaps the most insidious example is:
 9199: @example
 9200: AHEAD
 9201: BEGIN
 9202:   x
 9203: [ 1 CS-ROLL ] THEN
 9204:   @{ x @}
 9205:   ...
 9206: UNTIL
 9207: @end example
 9208: 
 9209: This should be legal according to the visibility rule. The use of
 9210: @code{x} can only be reached through the definition; but that appears
 9211: textually below the use.
 9212: 
 9213: From this example it is clear that the visibility rules cannot be fully
 9214: implemented without major headaches. Our implementation treats common
 9215: cases as advertised and the exceptions are treated in a safe way: The
 9216: compiler makes a reasonable guess about the locals visible after a
 9217: @code{BEGIN}; if it is too pessimistic, the
 9218: user will get a spurious error about the local not being defined; if the
 9219: compiler is too optimistic, it will notice this later and issue a
 9220: warning. In the case above the compiler would complain about @code{x}
 9221: being undefined at its use. You can see from the obscure examples in
 9222: this section that it takes quite unusual control structures to get the
 9223: compiler into trouble, and even then it will often do fine.
 9224: 
 9225: If the @code{BEGIN} is reachable from above, the most optimistic guess
 9226: is that all locals visible before the @code{BEGIN} will also be
 9227: visible after the @code{BEGIN}. This guess is valid for all loops that
 9228: are entered only through the @code{BEGIN}, in particular, for normal
 9229: @code{BEGIN}...@code{WHILE}...@code{REPEAT} and
 9230: @code{BEGIN}...@code{UNTIL} loops and it is implemented in our
 9231: compiler. When the branch to the @code{BEGIN} is finally generated by
 9232: @code{AGAIN} or @code{UNTIL}, the compiler checks the guess and
 9233: warns the user if it was too optimistic:
 9234: @example
 9235: IF
 9236:   @{ x @}
 9237: BEGIN
 9238:   \ x ? 
 9239: [ 1 cs-roll ] THEN
 9240:   ...
 9241: UNTIL
 9242: @end example
 9243: 
 9244: Here, @code{x} lives only until the @code{BEGIN}, but the compiler
 9245: optimistically assumes that it lives until the @code{THEN}. It notices
 9246: this difference when it compiles the @code{UNTIL} and issues a
 9247: warning. The user can avoid the warning, and make sure that @code{x}
 9248: is not used in the wrong area by using explicit scoping:
 9249: @example
 9250: IF
 9251:   SCOPE
 9252:   @{ x @}
 9253:   ENDSCOPE
 9254: BEGIN
 9255: [ 1 cs-roll ] THEN
 9256:   ...
 9257: UNTIL
 9258: @end example
 9259: 
 9260: Since the guess is optimistic, there will be no spurious error messages
 9261: about undefined locals.
 9262: 
 9263: If the @code{BEGIN} is not reachable from above (e.g., after
 9264: @code{AHEAD} or @code{EXIT}), the compiler cannot even make an
 9265: optimistic guess, as the locals visible after the @code{BEGIN} may be
 9266: defined later. Therefore, the compiler assumes that no locals are
 9267: visible after the @code{BEGIN}. However, the user can use
 9268: @code{ASSUME-LIVE} to make the compiler assume that the same locals are
 9269: visible at the BEGIN as at the point where the top control-flow stack
 9270: item was created.
 9271: 
 9272: 
 9273: doc-assume-live
 9274: 
 9275: 
 9276: @noindent
 9277: E.g.,
 9278: @example
 9279: @{ x @}
 9280: AHEAD
 9281: ASSUME-LIVE
 9282: BEGIN
 9283:   x
 9284: [ 1 CS-ROLL ] THEN
 9285:   ...
 9286: UNTIL
 9287: @end example
 9288: 
 9289: Other cases where the locals are defined before the @code{BEGIN} can be
 9290: handled by inserting an appropriate @code{CS-ROLL} before the
 9291: @code{ASSUME-LIVE} (and changing the control-flow stack manipulation
 9292: behind the @code{ASSUME-LIVE}).
 9293: 
 9294: Cases where locals are defined after the @code{BEGIN} (but should be
 9295: visible immediately after the @code{BEGIN}) can only be handled by
 9296: rearranging the loop. E.g., the ``most insidious'' example above can be
 9297: arranged into:
 9298: @example
 9299: BEGIN
 9300:   @{ x @}
 9301:   ... 0=
 9302: WHILE
 9303:   x
 9304: REPEAT
 9305: @end example
 9306: 
 9307: @node How long do locals live?, Locals programming style, Where are locals visible by name?, Gforth locals
 9308: @subsubsection How long do locals live?
 9309: @cindex locals lifetime
 9310: @cindex lifetime of locals
 9311: 
 9312: The right answer for the lifetime question would be: A local lives at
 9313: least as long as it can be accessed. For a value-flavoured local this
 9314: means: until the end of its visibility. However, a variable-flavoured
 9315: local could be accessed through its address far beyond its visibility
 9316: scope. Ultimately, this would mean that such locals would have to be
 9317: garbage collected. Since this entails un-Forth-like implementation
 9318: complexities, I adopted the same cowardly solution as some other
 9319: languages (e.g., C): The local lives only as long as it is visible;
 9320: afterwards its address is invalid (and programs that access it
 9321: afterwards are erroneous).
 9322: 
 9323: @node Locals programming style, Locals implementation, How long do locals live?, Gforth locals
 9324: @subsubsection Locals programming style
 9325: @cindex locals programming style
 9326: @cindex programming style, locals
 9327: 
 9328: The freedom to define locals anywhere has the potential to change
 9329: programming styles dramatically. In particular, the need to use the
 9330: return stack for intermediate storage vanishes. Moreover, all stack
 9331: manipulations (except @code{PICK}s and @code{ROLL}s with run-time
 9332: determined arguments) can be eliminated: If the stack items are in the
 9333: wrong order, just write a locals definition for all of them; then
 9334: write the items in the order you want.
 9335: 
 9336: This seems a little far-fetched and eliminating stack manipulations is
 9337: unlikely to become a conscious programming objective. Still, the number
 9338: of stack manipulations will be reduced dramatically if local variables
 9339: are used liberally (e.g., compare @code{max} (@pxref{Gforth locals}) with
 9340: a traditional implementation of @code{max}).
 9341: 
 9342: This shows one potential benefit of locals: making Forth programs more
 9343: readable. Of course, this benefit will only be realized if the
 9344: programmers continue to honour the principle of factoring instead of
 9345: using the added latitude to make the words longer.
 9346: 
 9347: @cindex single-assignment style for locals
 9348: Using @code{TO} can and should be avoided.  Without @code{TO},
 9349: every value-flavoured local has only a single assignment and many
 9350: advantages of functional languages apply to Forth. I.e., programs are
 9351: easier to analyse, to optimize and to read: It is clear from the
 9352: definition what the local stands for, it does not turn into something
 9353: different later.
 9354: 
 9355: E.g., a definition using @code{TO} might look like this:
 9356: @example
 9357: : strcmp @{ addr1 u1 addr2 u2 -- n @}
 9358:  u1 u2 min 0
 9359:  ?do
 9360:    addr1 c@@ addr2 c@@ -
 9361:    ?dup-if
 9362:      unloop exit
 9363:    then
 9364:    addr1 char+ TO addr1
 9365:    addr2 char+ TO addr2
 9366:  loop
 9367:  u1 u2 - ;
 9368: @end example
 9369: Here, @code{TO} is used to update @code{addr1} and @code{addr2} at
 9370: every loop iteration. @code{strcmp} is a typical example of the
 9371: readability problems of using @code{TO}. When you start reading
 9372: @code{strcmp}, you think that @code{addr1} refers to the start of the
 9373: string. Only near the end of the loop you realize that it is something
 9374: else.
 9375: 
 9376: This can be avoided by defining two locals at the start of the loop that
 9377: are initialized with the right value for the current iteration.
 9378: @example
 9379: : strcmp @{ addr1 u1 addr2 u2 -- n @}
 9380:  addr1 addr2
 9381:  u1 u2 min 0 
 9382:  ?do @{ s1 s2 @}
 9383:    s1 c@@ s2 c@@ -
 9384:    ?dup-if
 9385:      unloop exit
 9386:    then
 9387:    s1 char+ s2 char+
 9388:  loop
 9389:  2drop
 9390:  u1 u2 - ;
 9391: @end example
 9392: Here it is clear from the start that @code{s1} has a different value
 9393: in every loop iteration.
 9394: 
 9395: @node Locals implementation,  , Locals programming style, Gforth locals
 9396: @subsubsection Locals implementation
 9397: @cindex locals implementation
 9398: @cindex implementation of locals
 9399: 
 9400: @cindex locals stack
 9401: Gforth uses an extra locals stack. The most compelling reason for
 9402: this is that the return stack is not float-aligned; using an extra stack
 9403: also eliminates the problems and restrictions of using the return stack
 9404: as locals stack. Like the other stacks, the locals stack grows toward
 9405: lower addresses. A few primitives allow an efficient implementation:
 9406: 
 9407: 
 9408: doc-@local#
 9409: doc-f@local#
 9410: doc-laddr#
 9411: doc-lp+!#
 9412: doc-lp!
 9413: doc->l
 9414: doc-f>l
 9415: 
 9416: 
 9417: In addition to these primitives, some specializations of these
 9418: primitives for commonly occurring inline arguments are provided for
 9419: efficiency reasons, e.g., @code{@@local0} as specialization of
 9420: @code{@@local#} for the inline argument 0. The following compiling words
 9421: compile the right specialized version, or the general version, as
 9422: appropriate:
 9423: 
 9424: 
 9425: doc-compile-@local
 9426: doc-compile-f@local
 9427: doc-compile-lp+!
 9428: 
 9429: 
 9430: Combinations of conditional branches and @code{lp+!#} like
 9431: @code{?branch-lp+!#} (the locals pointer is only changed if the branch
 9432: is taken) are provided for efficiency and correctness in loops.
 9433: 
 9434: A special area in the dictionary space is reserved for keeping the
 9435: local variable names. @code{@{} switches the dictionary pointer to this
 9436: area and @code{@}} switches it back and generates the locals
 9437: initializing code. @code{W:} etc.@ are normal defining words. This
 9438: special area is cleared at the start of every colon definition.
 9439: 
 9440: @cindex word list for defining locals
 9441: A special feature of Gforth's dictionary is used to implement the
 9442: definition of locals without type specifiers: every word list (aka
 9443: vocabulary) has its own methods for searching
 9444: etc. (@pxref{Word Lists}). For the present purpose we defined a word list
 9445: with a special search method: When it is searched for a word, it
 9446: actually creates that word using @code{W:}. @code{@{} changes the search
 9447: order to first search the word list containing @code{@}}, @code{W:} etc.,
 9448: and then the word list for defining locals without type specifiers.
 9449: 
 9450: The lifetime rules support a stack discipline within a colon
 9451: definition: The lifetime of a local is either nested with other locals
 9452: lifetimes or it does not overlap them.
 9453: 
 9454: At @code{BEGIN}, @code{IF}, and @code{AHEAD} no code for locals stack
 9455: pointer manipulation is generated. Between control structure words
 9456: locals definitions can push locals onto the locals stack. @code{AGAIN}
 9457: is the simplest of the other three control flow words. It has to
 9458: restore the locals stack depth of the corresponding @code{BEGIN}
 9459: before branching. The code looks like this:
 9460: @format
 9461: @code{lp+!#} current-locals-size @minus{} dest-locals-size
 9462: @code{branch} <begin>
 9463: @end format
 9464: 
 9465: @code{UNTIL} is a little more complicated: If it branches back, it
 9466: must adjust the stack just like @code{AGAIN}. But if it falls through,
 9467: the locals stack must not be changed. The compiler generates the
 9468: following code:
 9469: @format
 9470: @code{?branch-lp+!#} <begin> current-locals-size @minus{} dest-locals-size
 9471: @end format
 9472: The locals stack pointer is only adjusted if the branch is taken.
 9473: 
 9474: @code{THEN} can produce somewhat inefficient code:
 9475: @format
 9476: @code{lp+!#} current-locals-size @minus{} orig-locals-size
 9477: <orig target>:
 9478: @code{lp+!#} orig-locals-size @minus{} new-locals-size
 9479: @end format
 9480: The second @code{lp+!#} adjusts the locals stack pointer from the
 9481: level at the @i{orig} point to the level after the @code{THEN}. The
 9482: first @code{lp+!#} adjusts the locals stack pointer from the current
 9483: level to the level at the orig point, so the complete effect is an
 9484: adjustment from the current level to the right level after the
 9485: @code{THEN}.
 9486: 
 9487: @cindex locals information on the control-flow stack
 9488: @cindex control-flow stack items, locals information
 9489: In a conventional Forth implementation a dest control-flow stack entry
 9490: is just the target address and an orig entry is just the address to be
 9491: patched. Our locals implementation adds a word list to every orig or dest
 9492: item. It is the list of locals visible (or assumed visible) at the point
 9493: described by the entry. Our implementation also adds a tag to identify
 9494: the kind of entry, in particular to differentiate between live and dead
 9495: (reachable and unreachable) orig entries.
 9496: 
 9497: A few unusual operations have to be performed on locals word lists:
 9498: 
 9499: 
 9500: doc-common-list
 9501: doc-sub-list?
 9502: doc-list-size
 9503: 
 9504: 
 9505: Several features of our locals word list implementation make these
 9506: operations easy to implement: The locals word lists are organised as
 9507: linked lists; the tails of these lists are shared, if the lists
 9508: contain some of the same locals; and the address of a name is greater
 9509: than the address of the names behind it in the list.
 9510: 
 9511: Another important implementation detail is the variable
 9512: @code{dead-code}. It is used by @code{BEGIN} and @code{THEN} to
 9513: determine if they can be reached directly or only through the branch
 9514: that they resolve. @code{dead-code} is set by @code{UNREACHABLE},
 9515: @code{AHEAD}, @code{EXIT} etc., and cleared at the start of a colon
 9516: definition, by @code{BEGIN} and usually by @code{THEN}.
 9517: 
 9518: Counted loops are similar to other loops in most respects, but
 9519: @code{LEAVE} requires special attention: It performs basically the same
 9520: service as @code{AHEAD}, but it does not create a control-flow stack
 9521: entry. Therefore the information has to be stored elsewhere;
 9522: traditionally, the information was stored in the target fields of the
 9523: branches created by the @code{LEAVE}s, by organizing these fields into a
 9524: linked list. Unfortunately, this clever trick does not provide enough
 9525: space for storing our extended control flow information. Therefore, we
 9526: introduce another stack, the leave stack. It contains the control-flow
 9527: stack entries for all unresolved @code{LEAVE}s.
 9528: 
 9529: Local names are kept until the end of the colon definition, even if
 9530: they are no longer visible in any control-flow path. In a few cases
 9531: this may lead to increased space needs for the locals name area, but
 9532: usually less than reclaiming this space would cost in code size.
 9533: 
 9534: 
 9535: @node ANS Forth locals,  , Gforth locals, Locals
 9536: @subsection ANS Forth locals
 9537: @cindex locals, ANS Forth style
 9538: 
 9539: The ANS Forth locals wordset does not define a syntax for locals, but
 9540: words that make it possible to define various syntaxes. One of the
 9541: possible syntaxes is a subset of the syntax we used in the Gforth locals
 9542: wordset, i.e.:
 9543: 
 9544: @example
 9545: @{ local1 local2 ... -- comment @}
 9546: @end example
 9547: @noindent
 9548: or
 9549: @example
 9550: @{ local1 local2 ... @}
 9551: @end example
 9552: 
 9553: The order of the locals corresponds to the order in a stack comment. The
 9554: restrictions are:
 9555: 
 9556: @itemize @bullet
 9557: @item
 9558: Locals can only be cell-sized values (no type specifiers are allowed).
 9559: @item
 9560: Locals can be defined only outside control structures.
 9561: @item
 9562: Locals can interfere with explicit usage of the return stack. For the
 9563: exact (and long) rules, see the standard. If you don't use return stack
 9564: accessing words in a definition using locals, you will be all right. The
 9565: purpose of this rule is to make locals implementation on the return
 9566: stack easier.
 9567: @item
 9568: The whole definition must be in one line.
 9569: @end itemize
 9570: 
 9571: Locals defined in ANS Forth behave like @code{VALUE}s
 9572: (@pxref{Values}). I.e., they are initialized from the stack. Using their
 9573: name produces their value. Their value can be changed using @code{TO}.
 9574: 
 9575: Since the syntax above is supported by Gforth directly, you need not do
 9576: anything to use it. If you want to port a program using this syntax to
 9577: another ANS Forth system, use @file{compat/anslocal.fs} to implement the
 9578: syntax on the other system.
 9579: 
 9580: Note that a syntax shown in the standard, section A.13 looks
 9581: similar, but is quite different in having the order of locals
 9582: reversed. Beware!
 9583: 
 9584: The ANS Forth locals wordset itself consists of one word:
 9585: 
 9586: doc-(local)
 9587: 
 9588: The ANS Forth locals extension wordset defines a syntax using
 9589: @code{locals|}, but it is so awful that we strongly recommend not to use
 9590: it. We have implemented this syntax to make porting to Gforth easy, but
 9591: do not document it here. The problem with this syntax is that the locals
 9592: are defined in an order reversed with respect to the standard stack
 9593: comment notation, making programs harder to read, and easier to misread
 9594: and miswrite. The only merit of this syntax is that it is easy to
 9595: implement using the ANS Forth locals wordset.
 9596: 
 9597: 
 9598: @c ----------------------------------------------------------
 9599: @node Structures, Object-oriented Forth, Locals, Words
 9600: @section  Structures
 9601: @cindex structures
 9602: @cindex records
 9603: 
 9604: This section presents the structure package that comes with Gforth. A
 9605: version of the package implemented in ANS Forth is available in
 9606: @file{compat/struct.fs}. This package was inspired by a posting on
 9607: comp.lang.forth in 1989 (unfortunately I don't remember, by whom;
 9608: possibly John Hayes). A version of this section has been published in
 9609: M. Anton Ertl,
 9610: @uref{http://www.complang.tuwien.ac.at/forth/objects/structs.html, Yet
 9611: Another Forth Structures Package}, Forth Dimensions 19(3), pages
 9612: 13--16. Marcel Hendrix provided helpful comments.
 9613: 
 9614: @menu
 9615: * Why explicit structure support?::  
 9616: * Structure Usage::             
 9617: * Structure Naming Convention::  
 9618: * Structure Implementation::    
 9619: * Structure Glossary::          
 9620: @end menu
 9621: 
 9622: @node Why explicit structure support?, Structure Usage, Structures, Structures
 9623: @subsection Why explicit structure support?
 9624: 
 9625: @cindex address arithmetic for structures
 9626: @cindex structures using address arithmetic
 9627: If we want to use a structure containing several fields, we could simply
 9628: reserve memory for it, and access the fields using address arithmetic
 9629: (@pxref{Address arithmetic}). As an example, consider a structure with
 9630: the following fields
 9631: 
 9632: @table @code
 9633: @item a
 9634: is a float
 9635: @item b
 9636: is a cell
 9637: @item c
 9638: is a float
 9639: @end table
 9640: 
 9641: Given the (float-aligned) base address of the structure we get the
 9642: address of the field
 9643: 
 9644: @table @code
 9645: @item a
 9646: without doing anything further.
 9647: @item b
 9648: with @code{float+}
 9649: @item c
 9650: with @code{float+ cell+ faligned}
 9651: @end table
 9652: 
 9653: It is easy to see that this can become quite tiring. 
 9654: 
 9655: Moreover, it is not very readable, because seeing a
 9656: @code{cell+} tells us neither which kind of structure is
 9657: accessed nor what field is accessed; we have to somehow infer the kind
 9658: of structure, and then look up in the documentation, which field of
 9659: that structure corresponds to that offset.
 9660: 
 9661: Finally, this kind of address arithmetic also causes maintenance
 9662: troubles: If you add or delete a field somewhere in the middle of the
 9663: structure, you have to find and change all computations for the fields
 9664: afterwards.
 9665: 
 9666: So, instead of using @code{cell+} and friends directly, how
 9667: about storing the offsets in constants:
 9668: 
 9669: @example
 9670: 0 constant a-offset
 9671: 0 float+ constant b-offset
 9672: 0 float+ cell+ faligned c-offset
 9673: @end example
 9674: 
 9675: Now we can get the address of field @code{x} with @code{x-offset
 9676: +}. This is much better in all respects. Of course, you still
 9677: have to change all later offset definitions if you add a field. You can
 9678: fix this by declaring the offsets in the following way:
 9679: 
 9680: @example
 9681: 0 constant a-offset
 9682: a-offset float+ constant b-offset
 9683: b-offset cell+ faligned constant c-offset
 9684: @end example
 9685: 
 9686: Since we always use the offsets with @code{+}, we could use a defining
 9687: word @code{cfield} that includes the @code{+} in the action of the
 9688: defined word:
 9689: 
 9690: @example
 9691: : cfield ( n "name" -- )
 9692:     create ,
 9693: does> ( name execution: addr1 -- addr2 )
 9694:     @@ + ;
 9695: 
 9696: 0 cfield a
 9697: 0 a float+ cfield b
 9698: 0 b cell+ faligned cfield c
 9699: @end example
 9700: 
 9701: Instead of @code{x-offset +}, we now simply write @code{x}.
 9702: 
 9703: The structure field words now can be used quite nicely. However,
 9704: their definition is still a bit cumbersome: We have to repeat the
 9705: name, the information about size and alignment is distributed before
 9706: and after the field definitions etc.  The structure package presented
 9707: here addresses these problems.
 9708: 
 9709: @node Structure Usage, Structure Naming Convention, Why explicit structure support?, Structures
 9710: @subsection Structure Usage
 9711: @cindex structure usage
 9712: 
 9713: @cindex @code{field} usage
 9714: @cindex @code{struct} usage
 9715: @cindex @code{end-struct} usage
 9716: You can define a structure for a (data-less) linked list with:
 9717: @example
 9718: struct
 9719:     cell% field list-next
 9720: end-struct list%
 9721: @end example
 9722: 
 9723: With the address of the list node on the stack, you can compute the
 9724: address of the field that contains the address of the next node with
 9725: @code{list-next}. E.g., you can determine the length of a list
 9726: with:
 9727: 
 9728: @example
 9729: : list-length ( list -- n )
 9730: \ "list" is a pointer to the first element of a linked list
 9731: \ "n" is the length of the list
 9732:     0 BEGIN ( list1 n1 )
 9733:         over
 9734:     WHILE ( list1 n1 )
 9735:         1+ swap list-next @@ swap
 9736:     REPEAT
 9737:     nip ;
 9738: @end example
 9739: 
 9740: You can reserve memory for a list node in the dictionary with
 9741: @code{list% %allot}, which leaves the address of the list node on the
 9742: stack. For the equivalent allocation on the heap you can use @code{list%
 9743: %alloc} (or, for an @code{allocate}-like stack effect (i.e., with ior),
 9744: use @code{list% %allocate}). You can get the the size of a list
 9745: node with @code{list% %size} and its alignment with @code{list%
 9746: %alignment}.
 9747: 
 9748: Note that in ANS Forth the body of a @code{create}d word is
 9749: @code{aligned} but not necessarily @code{faligned};
 9750: therefore, if you do a:
 9751: 
 9752: @example
 9753: create @emph{name} foo% %allot drop
 9754: @end example
 9755: 
 9756: @noindent
 9757: then the memory alloted for @code{foo%} is guaranteed to start at the
 9758: body of @code{@emph{name}} only if @code{foo%} contains only character,
 9759: cell and double fields.  Therefore, if your structure contains floats,
 9760: better use
 9761: 
 9762: @example
 9763: foo% %allot constant @emph{name}
 9764: @end example
 9765: 
 9766: @cindex structures containing structures
 9767: You can include a structure @code{foo%} as a field of
 9768: another structure, like this:
 9769: @example
 9770: struct
 9771: ...
 9772:     foo% field ...
 9773: ...
 9774: end-struct ...
 9775: @end example
 9776: 
 9777: @cindex structure extension
 9778: @cindex extended records
 9779: Instead of starting with an empty structure, you can extend an
 9780: existing structure. E.g., a plain linked list without data, as defined
 9781: above, is hardly useful; You can extend it to a linked list of integers,
 9782: like this:@footnote{This feature is also known as @emph{extended
 9783: records}. It is the main innovation in the Oberon language; in other
 9784: words, adding this feature to Modula-2 led Wirth to create a new
 9785: language, write a new compiler etc.  Adding this feature to Forth just
 9786: required a few lines of code.}
 9787: 
 9788: @example
 9789: list%
 9790:     cell% field intlist-int
 9791: end-struct intlist%
 9792: @end example
 9793: 
 9794: @code{intlist%} is a structure with two fields:
 9795: @code{list-next} and @code{intlist-int}.
 9796: 
 9797: @cindex structures containing arrays
 9798: You can specify an array type containing @emph{n} elements of
 9799: type @code{foo%} like this:
 9800: 
 9801: @example
 9802: foo% @emph{n} *
 9803: @end example
 9804: 
 9805: You can use this array type in any place where you can use a normal
 9806: type, e.g., when defining a @code{field}, or with
 9807: @code{%allot}.
 9808: 
 9809: @cindex first field optimization
 9810: The first field is at the base address of a structure and the word for
 9811: this field (e.g., @code{list-next}) actually does not change the address
 9812: on the stack. You may be tempted to leave it away in the interest of
 9813: run-time and space efficiency. This is not necessary, because the
 9814: structure package optimizes this case: If you compile a first-field
 9815: words, no code is generated. So, in the interest of readability and
 9816: maintainability you should include the word for the field when accessing
 9817: the field.
 9818: 
 9819: 
 9820: @node Structure Naming Convention, Structure Implementation, Structure Usage, Structures
 9821: @subsection Structure Naming Convention
 9822: @cindex structure naming convention
 9823: 
 9824: The field names that come to (my) mind are often quite generic, and,
 9825: if used, would cause frequent name clashes. E.g., many structures
 9826: probably contain a @code{counter} field. The structure names
 9827: that come to (my) mind are often also the logical choice for the names
 9828: of words that create such a structure.
 9829: 
 9830: Therefore, I have adopted the following naming conventions: 
 9831: 
 9832: @itemize @bullet
 9833: @cindex field naming convention
 9834: @item
 9835: The names of fields are of the form
 9836: @code{@emph{struct}-@emph{field}}, where
 9837: @code{@emph{struct}} is the basic name of the structure, and
 9838: @code{@emph{field}} is the basic name of the field. You can
 9839: think of field words as converting the (address of the)
 9840: structure into the (address of the) field.
 9841: 
 9842: @cindex structure naming convention
 9843: @item
 9844: The names of structures are of the form
 9845: @code{@emph{struct}%}, where
 9846: @code{@emph{struct}} is the basic name of the structure.
 9847: @end itemize
 9848: 
 9849: This naming convention does not work that well for fields of extended
 9850: structures; e.g., the integer list structure has a field
 9851: @code{intlist-int}, but has @code{list-next}, not
 9852: @code{intlist-next}.
 9853: 
 9854: @node Structure Implementation, Structure Glossary, Structure Naming Convention, Structures
 9855: @subsection Structure Implementation
 9856: @cindex structure implementation
 9857: @cindex implementation of structures
 9858: 
 9859: The central idea in the implementation is to pass the data about the
 9860: structure being built on the stack, not in some global
 9861: variable. Everything else falls into place naturally once this design
 9862: decision is made.
 9863: 
 9864: The type description on the stack is of the form @emph{align
 9865: size}. Keeping the size on the top-of-stack makes dealing with arrays
 9866: very simple.
 9867: 
 9868: @code{field} is a defining word that uses @code{Create}
 9869: and @code{DOES>}. The body of the field contains the offset
 9870: of the field, and the normal @code{DOES>} action is simply:
 9871: 
 9872: @example
 9873: @@ +
 9874: @end example
 9875: 
 9876: @noindent
 9877: i.e., add the offset to the address, giving the stack effect
 9878: @i{addr1 -- addr2} for a field.
 9879: 
 9880: @cindex first field optimization, implementation
 9881: This simple structure is slightly complicated by the optimization
 9882: for fields with offset 0, which requires a different
 9883: @code{DOES>}-part (because we cannot rely on there being
 9884: something on the stack if such a field is invoked during
 9885: compilation). Therefore, we put the different @code{DOES>}-parts
 9886: in separate words, and decide which one to invoke based on the
 9887: offset. For a zero offset, the field is basically a noop; it is
 9888: immediate, and therefore no code is generated when it is compiled.
 9889: 
 9890: @node Structure Glossary,  , Structure Implementation, Structures
 9891: @subsection Structure Glossary
 9892: @cindex structure glossary
 9893: 
 9894: 
 9895: doc-%align
 9896: doc-%alignment
 9897: doc-%alloc
 9898: doc-%allocate
 9899: doc-%allot
 9900: doc-cell%
 9901: doc-char%
 9902: doc-dfloat%
 9903: doc-double%
 9904: doc-end-struct
 9905: doc-field
 9906: doc-float%
 9907: doc-naligned
 9908: doc-sfloat%
 9909: doc-%size
 9910: doc-struct
 9911: 
 9912: 
 9913: @c -------------------------------------------------------------
 9914: @node Object-oriented Forth, Programming Tools, Structures, Words
 9915: @section Object-oriented Forth
 9916: 
 9917: Gforth comes with three packages for object-oriented programming:
 9918: @file{objects.fs}, @file{oof.fs}, and @file{mini-oof.fs}; none of them
 9919: is preloaded, so you have to @code{include} them before use. The most
 9920: important differences between these packages (and others) are discussed
 9921: in @ref{Comparison with other object models}. All packages are written
 9922: in ANS Forth and can be used with any other ANS Forth.
 9923: 
 9924: @menu
 9925: * Why object-oriented programming?::  
 9926: * Object-Oriented Terminology::  
 9927: * Objects::                     
 9928: * OOF::                         
 9929: * Mini-OOF::                    
 9930: * Comparison with other object models::  
 9931: @end menu
 9932: 
 9933: @c ----------------------------------------------------------------
 9934: @node Why object-oriented programming?, Object-Oriented Terminology, Object-oriented Forth, Object-oriented Forth
 9935: @subsection Why object-oriented programming?
 9936: @cindex object-oriented programming motivation
 9937: @cindex motivation for object-oriented programming
 9938: 
 9939: Often we have to deal with several data structures (@emph{objects}),
 9940: that have to be treated similarly in some respects, but differently in
 9941: others. Graphical objects are the textbook example: circles, triangles,
 9942: dinosaurs, icons, and others, and we may want to add more during program
 9943: development. We want to apply some operations to any graphical object,
 9944: e.g., @code{draw} for displaying it on the screen. However, @code{draw}
 9945: has to do something different for every kind of object.
 9946: @comment TODO add some other operations eg perimeter, area
 9947: @comment and tie in to concrete examples later..
 9948: 
 9949: We could implement @code{draw} as a big @code{CASE}
 9950: control structure that executes the appropriate code depending on the
 9951: kind of object to be drawn. This would be not be very elegant, and,
 9952: moreover, we would have to change @code{draw} every time we add
 9953: a new kind of graphical object (say, a spaceship).
 9954: 
 9955: What we would rather do is: When defining spaceships, we would tell
 9956: the system: ``Here's how you @code{draw} a spaceship; you figure
 9957: out the rest''.
 9958: 
 9959: This is the problem that all systems solve that (rightfully) call
 9960: themselves object-oriented; the object-oriented packages presented here
 9961: solve this problem (and not much else).
 9962: @comment TODO ?list properties of oo systems.. oo vs o-based?
 9963: 
 9964: @c ------------------------------------------------------------------------
 9965: @node Object-Oriented Terminology, Objects, Why object-oriented programming?, Object-oriented Forth
 9966: @subsection Object-Oriented Terminology
 9967: @cindex object-oriented terminology
 9968: @cindex terminology for object-oriented programming
 9969: 
 9970: This section is mainly for reference, so you don't have to understand
 9971: all of it right away.  The terminology is mainly Smalltalk-inspired.  In
 9972: short:
 9973: 
 9974: @table @emph
 9975: @cindex class
 9976: @item class
 9977: a data structure definition with some extras.
 9978: 
 9979: @cindex object
 9980: @item object
 9981: an instance of the data structure described by the class definition.
 9982: 
 9983: @cindex instance variables
 9984: @item instance variables
 9985: fields of the data structure.
 9986: 
 9987: @cindex selector
 9988: @cindex method selector
 9989: @cindex virtual function
 9990: @item selector
 9991: (or @emph{method selector}) a word (e.g.,
 9992: @code{draw}) that performs an operation on a variety of data
 9993: structures (classes). A selector describes @emph{what} operation to
 9994: perform. In C++ terminology: a (pure) virtual function.
 9995: 
 9996: @cindex method
 9997: @item method
 9998: the concrete definition that performs the operation
 9999: described by the selector for a specific class. A method specifies
10000: @emph{how} the operation is performed for a specific class.
10001: 
10002: @cindex selector invocation
10003: @cindex message send
10004: @cindex invoking a selector
10005: @item selector invocation
10006: a call of a selector. One argument of the call (the TOS (top-of-stack))
10007: is used for determining which method is used. In Smalltalk terminology:
10008: a message (consisting of the selector and the other arguments) is sent
10009: to the object.
10010: 
10011: @cindex receiving object
10012: @item receiving object
10013: the object used for determining the method executed by a selector
10014: invocation. In the @file{objects.fs} model, it is the object that is on
10015: the TOS when the selector is invoked. (@emph{Receiving} comes from
10016: the Smalltalk @emph{message} terminology.)
10017: 
10018: @cindex child class
10019: @cindex parent class
10020: @cindex inheritance
10021: @item child class
10022: a class that has (@emph{inherits}) all properties (instance variables,
10023: selectors, methods) from a @emph{parent class}. In Smalltalk
10024: terminology: The subclass inherits from the superclass. In C++
10025: terminology: The derived class inherits from the base class.
10026: 
10027: @end table
10028: 
10029: @c If you wonder about the message sending terminology, it comes from
10030: @c a time when each object had it's own task and objects communicated via
10031: @c message passing; eventually the Smalltalk developers realized that
10032: @c they can do most things through simple (indirect) calls. They kept the
10033: @c terminology.
10034: 
10035: @c --------------------------------------------------------------
10036: @node Objects, OOF, Object-Oriented Terminology, Object-oriented Forth
10037: @subsection The @file{objects.fs} model
10038: @cindex objects
10039: @cindex object-oriented programming
10040: 
10041: @cindex @file{objects.fs}
10042: @cindex @file{oof.fs}
10043: 
10044: This section describes the @file{objects.fs} package. This material also
10045: has been published in M. Anton Ertl,
10046: @cite{@uref{http://www.complang.tuwien.ac.at/forth/objects/objects.html,
10047: Yet Another Forth Objects Package}}, Forth Dimensions 19(2), pages
10048: 37--43.
10049: @c McKewan's and Zsoter's packages
10050: 
10051: This section assumes that you have read @ref{Structures}.
10052: 
10053: The techniques on which this model is based have been used to implement
10054: the parser generator, Gray, and have also been used in Gforth for
10055: implementing the various flavours of word lists (hashed or not,
10056: case-sensitive or not, special-purpose word lists for locals etc.).
10057: 
10058: 
10059: @menu
10060: * Properties of the Objects model::  
10061: * Basic Objects Usage::         
10062: * The Objects base class::      
10063: * Creating objects::            
10064: * Object-Oriented Programming Style::  
10065: * Class Binding::               
10066: * Method conveniences::         
10067: * Classes and Scoping::         
10068: * Dividing classes::            
10069: * Object Interfaces::           
10070: * Objects Implementation::      
10071: * Objects Glossary::            
10072: @end menu
10073: 
10074: Marcel Hendrix provided helpful comments on this section.
10075: 
10076: @node Properties of the Objects model, Basic Objects Usage, Objects, Objects
10077: @subsubsection Properties of the @file{objects.fs} model
10078: @cindex @file{objects.fs} properties
10079: 
10080: @itemize @bullet
10081: @item
10082: It is straightforward to pass objects on the stack. Passing
10083: selectors on the stack is a little less convenient, but possible.
10084: 
10085: @item
10086: Objects are just data structures in memory, and are referenced by their
10087: address. You can create words for objects with normal defining words
10088: like @code{constant}. Likewise, there is no difference between instance
10089: variables that contain objects and those that contain other data.
10090: 
10091: @item
10092: Late binding is efficient and easy to use.
10093: 
10094: @item
10095: It avoids parsing, and thus avoids problems with state-smartness
10096: and reduced extensibility; for convenience there are a few parsing
10097: words, but they have non-parsing counterparts. There are also a few
10098: defining words that parse. This is hard to avoid, because all standard
10099: defining words parse (except @code{:noname}); however, such
10100: words are not as bad as many other parsing words, because they are not
10101: state-smart.
10102: 
10103: @item
10104: It does not try to incorporate everything. It does a few things and does
10105: them well (IMO). In particular, this model was not designed to support
10106: information hiding (although it has features that may help); you can use
10107: a separate package for achieving this.
10108: 
10109: @item
10110: It is layered; you don't have to learn and use all features to use this
10111: model. Only a few features are necessary (@pxref{Basic Objects Usage},
10112: @pxref{The Objects base class}, @pxref{Creating objects}.), the others
10113: are optional and independent of each other.
10114: 
10115: @item
10116: An implementation in ANS Forth is available.
10117: 
10118: @end itemize
10119: 
10120: 
10121: @node Basic Objects Usage, The Objects base class, Properties of the Objects model, Objects
10122: @subsubsection Basic @file{objects.fs} Usage
10123: @cindex basic objects usage
10124: @cindex objects, basic usage
10125: 
10126: You can define a class for graphical objects like this:
10127: 
10128: @cindex @code{class} usage
10129: @cindex @code{end-class} usage
10130: @cindex @code{selector} usage
10131: @example
10132: object class \ "object" is the parent class
10133:   selector draw ( x y graphical -- )
10134: end-class graphical
10135: @end example
10136: 
10137: This code defines a class @code{graphical} with an
10138: operation @code{draw}.  We can perform the operation
10139: @code{draw} on any @code{graphical} object, e.g.:
10140: 
10141: @example
10142: 100 100 t-rex draw
10143: @end example
10144: 
10145: @noindent
10146: where @code{t-rex} is a word (say, a constant) that produces a
10147: graphical object.
10148: 
10149: @comment TODO add a 2nd operation eg perimeter.. and use for
10150: @comment a concrete example
10151: 
10152: @cindex abstract class
10153: How do we create a graphical object? With the present definitions,
10154: we cannot create a useful graphical object. The class
10155: @code{graphical} describes graphical objects in general, but not
10156: any concrete graphical object type (C++ users would call it an
10157: @emph{abstract class}); e.g., there is no method for the selector
10158: @code{draw} in the class @code{graphical}.
10159: 
10160: For concrete graphical objects, we define child classes of the
10161: class @code{graphical}, e.g.:
10162: 
10163: @cindex @code{overrides} usage
10164: @cindex @code{field} usage in class definition
10165: @example
10166: graphical class \ "graphical" is the parent class
10167:   cell% field circle-radius
10168: 
10169: :noname ( x y circle -- )
10170:   circle-radius @@ draw-circle ;
10171: overrides draw
10172: 
10173: :noname ( n-radius circle -- )
10174:   circle-radius ! ;
10175: overrides construct
10176: 
10177: end-class circle
10178: @end example
10179: 
10180: Here we define a class @code{circle} as a child of @code{graphical},
10181: with field @code{circle-radius} (which behaves just like a field
10182: (@pxref{Structures}); it defines (using @code{overrides}) new methods
10183: for the selectors @code{draw} and @code{construct} (@code{construct} is
10184: defined in @code{object}, the parent class of @code{graphical}).
10185: 
10186: Now we can create a circle on the heap (i.e.,
10187: @code{allocate}d memory) with:
10188: 
10189: @cindex @code{heap-new} usage
10190: @example
10191: 50 circle heap-new constant my-circle
10192: @end example
10193: 
10194: @noindent
10195: @code{heap-new} invokes @code{construct}, thus
10196: initializing the field @code{circle-radius} with 50. We can draw
10197: this new circle at (100,100) with:
10198: 
10199: @example
10200: 100 100 my-circle draw
10201: @end example
10202: 
10203: @cindex selector invocation, restrictions
10204: @cindex class definition, restrictions
10205: Note: You can only invoke a selector if the object on the TOS
10206: (the receiving object) belongs to the class where the selector was
10207: defined or one of its descendents; e.g., you can invoke
10208: @code{draw} only for objects belonging to @code{graphical}
10209: or its descendents (e.g., @code{circle}).  Immediately before
10210: @code{end-class}, the search order has to be the same as
10211: immediately after @code{class}.
10212: 
10213: @node The Objects base class, Creating objects, Basic Objects Usage, Objects
10214: @subsubsection The @file{object.fs} base class
10215: @cindex @code{object} class
10216: 
10217: When you define a class, you have to specify a parent class.  So how do
10218: you start defining classes? There is one class available from the start:
10219: @code{object}. It is ancestor for all classes and so is the
10220: only class that has no parent. It has two selectors: @code{construct}
10221: and @code{print}.
10222: 
10223: @node Creating objects, Object-Oriented Programming Style, The Objects base class, Objects
10224: @subsubsection Creating objects
10225: @cindex creating objects
10226: @cindex object creation
10227: @cindex object allocation options
10228: 
10229: @cindex @code{heap-new} discussion
10230: @cindex @code{dict-new} discussion
10231: @cindex @code{construct} discussion
10232: You can create and initialize an object of a class on the heap with
10233: @code{heap-new} ( ... class -- object ) and in the dictionary
10234: (allocation with @code{allot}) with @code{dict-new} (
10235: ... class -- object ). Both words invoke @code{construct}, which
10236: consumes the stack items indicated by "..." above.
10237: 
10238: @cindex @code{init-object} discussion
10239: @cindex @code{class-inst-size} discussion
10240: If you want to allocate memory for an object yourself, you can get its
10241: alignment and size with @code{class-inst-size 2@@} ( class --
10242: align size ). Once you have memory for an object, you can initialize
10243: it with @code{init-object} ( ... class object -- );
10244: @code{construct} does only a part of the necessary work.
10245: 
10246: @node Object-Oriented Programming Style, Class Binding, Creating objects, Objects
10247: @subsubsection Object-Oriented Programming Style
10248: @cindex object-oriented programming style
10249: @cindex programming style, object-oriented
10250: 
10251: This section is not exhaustive.
10252: 
10253: @cindex stack effects of selectors
10254: @cindex selectors and stack effects
10255: In general, it is a good idea to ensure that all methods for the
10256: same selector have the same stack effect: when you invoke a selector,
10257: you often have no idea which method will be invoked, so, unless all
10258: methods have the same stack effect, you will not know the stack effect
10259: of the selector invocation.
10260: 
10261: One exception to this rule is methods for the selector
10262: @code{construct}. We know which method is invoked, because we
10263: specify the class to be constructed at the same place. Actually, I
10264: defined @code{construct} as a selector only to give the users a
10265: convenient way to specify initialization. The way it is used, a
10266: mechanism different from selector invocation would be more natural
10267: (but probably would take more code and more space to explain).
10268: 
10269: @node Class Binding, Method conveniences, Object-Oriented Programming Style, Objects
10270: @subsubsection Class Binding
10271: @cindex class binding
10272: @cindex early binding
10273: 
10274: @cindex late binding
10275: Normal selector invocations determine the method at run-time depending
10276: on the class of the receiving object. This run-time selection is called
10277: @i{late binding}.
10278: 
10279: Sometimes it's preferable to invoke a different method. For example,
10280: you might want to use the simple method for @code{print}ing
10281: @code{object}s instead of the possibly long-winded @code{print} method
10282: of the receiver class. You can achieve this by replacing the invocation
10283: of @code{print} with:
10284: 
10285: @cindex @code{[bind]} usage
10286: @example
10287: [bind] object print
10288: @end example
10289: 
10290: @noindent
10291: in compiled code or:
10292: 
10293: @cindex @code{bind} usage
10294: @example
10295: bind object print
10296: @end example
10297: 
10298: @cindex class binding, alternative to
10299: @noindent
10300: in interpreted code. Alternatively, you can define the method with a
10301: name (e.g., @code{print-object}), and then invoke it through the
10302: name. Class binding is just a (often more convenient) way to achieve
10303: the same effect; it avoids name clutter and allows you to invoke
10304: methods directly without naming them first.
10305: 
10306: @cindex superclass binding
10307: @cindex parent class binding
10308: A frequent use of class binding is this: When we define a method
10309: for a selector, we often want the method to do what the selector does
10310: in the parent class, and a little more. There is a special word for
10311: this purpose: @code{[parent]}; @code{[parent]
10312: @emph{selector}} is equivalent to @code{[bind] @emph{parent
10313: selector}}, where @code{@emph{parent}} is the parent
10314: class of the current class. E.g., a method definition might look like:
10315: 
10316: @cindex @code{[parent]} usage
10317: @example
10318: :noname
10319:   dup [parent] foo \ do parent's foo on the receiving object
10320:   ... \ do some more
10321: ; overrides foo
10322: @end example
10323: 
10324: @cindex class binding as optimization
10325: In @cite{Object-oriented programming in ANS Forth} (Forth Dimensions,
10326: March 1997), Andrew McKewan presents class binding as an optimization
10327: technique. I recommend not using it for this purpose unless you are in
10328: an emergency. Late binding is pretty fast with this model anyway, so the
10329: benefit of using class binding is small; the cost of using class binding
10330: where it is not appropriate is reduced maintainability.
10331: 
10332: While we are at programming style questions: You should bind
10333: selectors only to ancestor classes of the receiving object. E.g., say,
10334: you know that the receiving object is of class @code{foo} or its
10335: descendents; then you should bind only to @code{foo} and its
10336: ancestors.
10337: 
10338: @node Method conveniences, Classes and Scoping, Class Binding, Objects
10339: @subsubsection Method conveniences
10340: @cindex method conveniences
10341: 
10342: In a method you usually access the receiving object pretty often.  If
10343: you define the method as a plain colon definition (e.g., with
10344: @code{:noname}), you may have to do a lot of stack
10345: gymnastics. To avoid this, you can define the method with @code{m:
10346: ... ;m}. E.g., you could define the method for
10347: @code{draw}ing a @code{circle} with
10348: 
10349: @cindex @code{this} usage
10350: @cindex @code{m:} usage
10351: @cindex @code{;m} usage
10352: @example
10353: m: ( x y circle -- )
10354:   ( x y ) this circle-radius @@ draw-circle ;m
10355: @end example
10356: 
10357: @cindex @code{exit} in @code{m: ... ;m}
10358: @cindex @code{exitm} discussion
10359: @cindex @code{catch} in @code{m: ... ;m}
10360: When this method is executed, the receiver object is removed from the
10361: stack; you can access it with @code{this} (admittedly, in this
10362: example the use of @code{m: ... ;m} offers no advantage). Note
10363: that I specify the stack effect for the whole method (i.e. including
10364: the receiver object), not just for the code between @code{m:}
10365: and @code{;m}. You cannot use @code{exit} in
10366: @code{m:...;m}; instead, use
10367: @code{exitm}.@footnote{Moreover, for any word that calls
10368: @code{catch} and was defined before loading
10369: @code{objects.fs}, you have to redefine it like I redefined
10370: @code{catch}: @code{: catch this >r catch r> to-this ;}}
10371: 
10372: @cindex @code{inst-var} usage
10373: You will frequently use sequences of the form @code{this
10374: @emph{field}} (in the example above: @code{this
10375: circle-radius}). If you use the field only in this way, you can
10376: define it with @code{inst-var} and eliminate the
10377: @code{this} before the field name. E.g., the @code{circle}
10378: class above could also be defined with:
10379: 
10380: @example
10381: graphical class
10382:   cell% inst-var radius
10383: 
10384: m: ( x y circle -- )
10385:   radius @@ draw-circle ;m
10386: overrides draw
10387: 
10388: m: ( n-radius circle -- )
10389:   radius ! ;m
10390: overrides construct
10391: 
10392: end-class circle
10393: @end example
10394: 
10395: @code{radius} can only be used in @code{circle} and its
10396: descendent classes and inside @code{m:...;m}.
10397: 
10398: @cindex @code{inst-value} usage
10399: You can also define fields with @code{inst-value}, which is
10400: to @code{inst-var} what @code{value} is to
10401: @code{variable}.  You can change the value of such a field with
10402: @code{[to-inst]}.  E.g., we could also define the class
10403: @code{circle} like this:
10404: 
10405: @example
10406: graphical class
10407:   inst-value radius
10408: 
10409: m: ( x y circle -- )
10410:   radius draw-circle ;m
10411: overrides draw
10412: 
10413: m: ( n-radius circle -- )
10414:   [to-inst] radius ;m
10415: overrides construct
10416: 
10417: end-class circle
10418: @end example
10419: 
10420: @c !! :m is easy to confuse with m:.  Another name would be better.
10421: 
10422: @c Finally, you can define named methods with @code{:m}.  One use of this
10423: @c feature is the definition of words that occur only in one class and are
10424: @c not intended to be overridden, but which still need method context
10425: @c (e.g., for accessing @code{inst-var}s).  Another use is for methods that
10426: @c would be bound frequently, if defined anonymously.
10427: 
10428: 
10429: @node Classes and Scoping, Dividing classes, Method conveniences, Objects
10430: @subsubsection Classes and Scoping
10431: @cindex classes and scoping
10432: @cindex scoping and classes
10433: 
10434: Inheritance is frequent, unlike structure extension. This exacerbates
10435: the problem with the field name convention (@pxref{Structure Naming
10436: Convention}): One always has to remember in which class the field was
10437: originally defined; changing a part of the class structure would require
10438: changes for renaming in otherwise unaffected code.
10439: 
10440: @cindex @code{inst-var} visibility
10441: @cindex @code{inst-value} visibility
10442: To solve this problem, I added a scoping mechanism (which was not in my
10443: original charter): A field defined with @code{inst-var} (or
10444: @code{inst-value}) is visible only in the class where it is defined and in
10445: the descendent classes of this class.  Using such fields only makes
10446: sense in @code{m:}-defined methods in these classes anyway.
10447: 
10448: This scoping mechanism allows us to use the unadorned field name,
10449: because name clashes with unrelated words become much less likely.
10450: 
10451: @cindex @code{protected} discussion
10452: @cindex @code{private} discussion
10453: Once we have this mechanism, we can also use it for controlling the
10454: visibility of other words: All words defined after
10455: @code{protected} are visible only in the current class and its
10456: descendents. @code{public} restores the compilation
10457: (i.e. @code{current}) word list that was in effect before. If you
10458: have several @code{protected}s without an intervening
10459: @code{public} or @code{set-current}, @code{public}
10460: will restore the compilation word list in effect before the first of
10461: these @code{protected}s.
10462: 
10463: @node Dividing classes, Object Interfaces, Classes and Scoping, Objects
10464: @subsubsection Dividing classes
10465: @cindex Dividing classes
10466: @cindex @code{methods}...@code{end-methods}
10467: 
10468: You may want to do the definition of methods separate from the
10469: definition of the class, its selectors, fields, and instance variables,
10470: i.e., separate the implementation from the definition.  You can do this
10471: in the following way:
10472: 
10473: @example
10474: graphical class
10475:   inst-value radius
10476: end-class circle
10477: 
10478: ... \ do some other stuff
10479: 
10480: circle methods \ now we are ready
10481: 
10482: m: ( x y circle -- )
10483:   radius draw-circle ;m
10484: overrides draw
10485: 
10486: m: ( n-radius circle -- )
10487:   [to-inst] radius ;m
10488: overrides construct
10489: 
10490: end-methods
10491: @end example
10492: 
10493: You can use several @code{methods}...@code{end-methods} sections.  The
10494: only things you can do to the class in these sections are: defining
10495: methods, and overriding the class's selectors.  You must not define new
10496: selectors or fields.
10497: 
10498: Note that you often have to override a selector before using it.  In
10499: particular, you usually have to override @code{construct} with a new
10500: method before you can invoke @code{heap-new} and friends.  E.g., you
10501: must not create a circle before the @code{overrides construct} sequence
10502: in the example above.
10503: 
10504: @node Object Interfaces, Objects Implementation, Dividing classes, Objects
10505: @subsubsection Object Interfaces
10506: @cindex object interfaces
10507: @cindex interfaces for objects
10508: 
10509: In this model you can only call selectors defined in the class of the
10510: receiving objects or in one of its ancestors. If you call a selector
10511: with a receiving object that is not in one of these classes, the
10512: result is undefined; if you are lucky, the program crashes
10513: immediately.
10514: 
10515: @cindex selectors common to hardly-related classes
10516: Now consider the case when you want to have a selector (or several)
10517: available in two classes: You would have to add the selector to a
10518: common ancestor class, in the worst case to @code{object}. You
10519: may not want to do this, e.g., because someone else is responsible for
10520: this ancestor class.
10521: 
10522: The solution for this problem is interfaces. An interface is a
10523: collection of selectors. If a class implements an interface, the
10524: selectors become available to the class and its descendents. A class
10525: can implement an unlimited number of interfaces. For the problem
10526: discussed above, we would define an interface for the selector(s), and
10527: both classes would implement the interface.
10528: 
10529: As an example, consider an interface @code{storage} for
10530: writing objects to disk and getting them back, and a class
10531: @code{foo} that implements it. The code would look like this:
10532: 
10533: @cindex @code{interface} usage
10534: @cindex @code{end-interface} usage
10535: @cindex @code{implementation} usage
10536: @example
10537: interface
10538:   selector write ( file object -- )
10539:   selector read1 ( file object -- )
10540: end-interface storage
10541: 
10542: bar class
10543:   storage implementation
10544: 
10545: ... overrides write
10546: ... overrides read1
10547: ...
10548: end-class foo
10549: @end example
10550: 
10551: @noindent
10552: (I would add a word @code{read} @i{( file -- object )} that uses
10553: @code{read1} internally, but that's beyond the point illustrated
10554: here.)
10555: 
10556: Note that you cannot use @code{protected} in an interface; and
10557: of course you cannot define fields.
10558: 
10559: In the Neon model, all selectors are available for all classes;
10560: therefore it does not need interfaces. The price you pay in this model
10561: is slower late binding, and therefore, added complexity to avoid late
10562: binding.
10563: 
10564: @node Objects Implementation, Objects Glossary, Object Interfaces, Objects
10565: @subsubsection @file{objects.fs} Implementation
10566: @cindex @file{objects.fs} implementation
10567: 
10568: @cindex @code{object-map} discussion
10569: An object is a piece of memory, like one of the data structures
10570: described with @code{struct...end-struct}. It has a field
10571: @code{object-map} that points to the method map for the object's
10572: class.
10573: 
10574: @cindex method map
10575: @cindex virtual function table
10576: The @emph{method map}@footnote{This is Self terminology; in C++
10577: terminology: virtual function table.} is an array that contains the
10578: execution tokens (@i{xt}s) of the methods for the object's class. Each
10579: selector contains an offset into a method map.
10580: 
10581: @cindex @code{selector} implementation, class
10582: @code{selector} is a defining word that uses
10583: @code{CREATE} and @code{DOES>}. The body of the
10584: selector contains the offset; the @code{DOES>} action for a
10585: class selector is, basically:
10586: 
10587: @example
10588: ( object addr ) @@ over object-map @@ + @@ execute
10589: @end example
10590: 
10591: Since @code{object-map} is the first field of the object, it
10592: does not generate any code. As you can see, calling a selector has a
10593: small, constant cost.
10594: 
10595: @cindex @code{current-interface} discussion
10596: @cindex class implementation and representation
10597: A class is basically a @code{struct} combined with a method
10598: map. During the class definition the alignment and size of the class
10599: are passed on the stack, just as with @code{struct}s, so
10600: @code{field} can also be used for defining class
10601: fields. However, passing more items on the stack would be
10602: inconvenient, so @code{class} builds a data structure in memory,
10603: which is accessed through the variable
10604: @code{current-interface}. After its definition is complete, the
10605: class is represented on the stack by a pointer (e.g., as parameter for
10606: a child class definition).
10607: 
10608: A new class starts off with the alignment and size of its parent,
10609: and a copy of the parent's method map. Defining new fields extends the
10610: size and alignment; likewise, defining new selectors extends the
10611: method map. @code{overrides} just stores a new @i{xt} in the method
10612: map at the offset given by the selector.
10613: 
10614: @cindex class binding, implementation
10615: Class binding just gets the @i{xt} at the offset given by the selector
10616: from the class's method map and @code{compile,}s (in the case of
10617: @code{[bind]}) it.
10618: 
10619: @cindex @code{this} implementation
10620: @cindex @code{catch} and @code{this}
10621: @cindex @code{this} and @code{catch}
10622: I implemented @code{this} as a @code{value}. At the
10623: start of an @code{m:...;m} method the old @code{this} is
10624: stored to the return stack and restored at the end; and the object on
10625: the TOS is stored @code{TO this}. This technique has one
10626: disadvantage: If the user does not leave the method via
10627: @code{;m}, but via @code{throw} or @code{exit},
10628: @code{this} is not restored (and @code{exit} may
10629: crash). To deal with the @code{throw} problem, I have redefined
10630: @code{catch} to save and restore @code{this}; the same
10631: should be done with any word that can catch an exception. As for
10632: @code{exit}, I simply forbid it (as a replacement, there is
10633: @code{exitm}).
10634: 
10635: @cindex @code{inst-var} implementation
10636: @code{inst-var} is just the same as @code{field}, with
10637: a different @code{DOES>} action:
10638: @example
10639: @@ this +
10640: @end example
10641: Similar for @code{inst-value}.
10642: 
10643: @cindex class scoping implementation
10644: Each class also has a word list that contains the words defined with
10645: @code{inst-var} and @code{inst-value}, and its protected
10646: words. It also has a pointer to its parent. @code{class} pushes
10647: the word lists of the class and all its ancestors onto the search order stack,
10648: and @code{end-class} drops them.
10649: 
10650: @cindex interface implementation
10651: An interface is like a class without fields, parent and protected
10652: words; i.e., it just has a method map. If a class implements an
10653: interface, its method map contains a pointer to the method map of the
10654: interface. The positive offsets in the map are reserved for class
10655: methods, therefore interface map pointers have negative
10656: offsets. Interfaces have offsets that are unique throughout the
10657: system, unlike class selectors, whose offsets are only unique for the
10658: classes where the selector is available (invokable).
10659: 
10660: This structure means that interface selectors have to perform one
10661: indirection more than class selectors to find their method. Their body
10662: contains the interface map pointer offset in the class method map, and
10663: the method offset in the interface method map. The
10664: @code{does>} action for an interface selector is, basically:
10665: 
10666: @example
10667: ( object selector-body )
10668: 2dup selector-interface @@ ( object selector-body object interface-offset )
10669: swap object-map @@ + @@ ( object selector-body map )
10670: swap selector-offset @@ + @@ execute
10671: @end example
10672: 
10673: where @code{object-map} and @code{selector-offset} are
10674: first fields and generate no code.
10675: 
10676: As a concrete example, consider the following code:
10677: 
10678: @example
10679: interface
10680:   selector if1sel1
10681:   selector if1sel2
10682: end-interface if1
10683: 
10684: object class
10685:   if1 implementation
10686:   selector cl1sel1
10687:   cell% inst-var cl1iv1
10688: 
10689: ' m1 overrides construct
10690: ' m2 overrides if1sel1
10691: ' m3 overrides if1sel2
10692: ' m4 overrides cl1sel2
10693: end-class cl1
10694: 
10695: create obj1 object dict-new drop
10696: create obj2 cl1    dict-new drop
10697: @end example
10698: 
10699: The data structure created by this code (including the data structure
10700: for @code{object}) is shown in the
10701: @uref{objects-implementation.eps,figure}, assuming a cell size of 4.
10702: @comment TODO add this diagram..
10703: 
10704: @node Objects Glossary,  , Objects Implementation, Objects
10705: @subsubsection @file{objects.fs} Glossary
10706: @cindex @file{objects.fs} Glossary
10707: 
10708: 
10709: doc---objects-bind
10710: doc---objects-<bind>
10711: doc---objects-bind'
10712: doc---objects-[bind]
10713: doc---objects-class
10714: doc---objects-class->map
10715: doc---objects-class-inst-size
10716: doc---objects-class-override!
10717: doc---objects-class-previous
10718: doc---objects-class>order
10719: doc---objects-construct
10720: doc---objects-current'
10721: doc---objects-[current]
10722: doc---objects-current-interface
10723: doc---objects-dict-new
10724: doc---objects-end-class
10725: doc---objects-end-class-noname
10726: doc---objects-end-interface
10727: doc---objects-end-interface-noname
10728: doc---objects-end-methods
10729: doc---objects-exitm
10730: doc---objects-heap-new
10731: doc---objects-implementation
10732: doc---objects-init-object
10733: doc---objects-inst-value
10734: doc---objects-inst-var
10735: doc---objects-interface
10736: doc---objects-m:
10737: doc---objects-:m
10738: doc---objects-;m
10739: doc---objects-method
10740: doc---objects-methods
10741: doc---objects-object
10742: doc---objects-overrides
10743: doc---objects-[parent]
10744: doc---objects-print
10745: doc---objects-protected
10746: doc---objects-public
10747: doc---objects-selector
10748: doc---objects-this
10749: doc---objects-<to-inst>
10750: doc---objects-[to-inst]
10751: doc---objects-to-this
10752: doc---objects-xt-new
10753: 
10754: 
10755: @c -------------------------------------------------------------
10756: @node OOF, Mini-OOF, Objects, Object-oriented Forth
10757: @subsection The @file{oof.fs} model
10758: @cindex oof
10759: @cindex object-oriented programming
10760: 
10761: @cindex @file{objects.fs}
10762: @cindex @file{oof.fs}
10763: 
10764: This section describes the @file{oof.fs} package.
10765: 
10766: The package described in this section has been used in bigFORTH since 1991, and
10767: used for two large applications: a chromatographic system used to
10768: create new medicaments, and a graphic user interface library (MINOS).
10769: 
10770: You can find a description (in German) of @file{oof.fs} in @cite{Object
10771: oriented bigFORTH} by Bernd Paysan, published in @cite{Vierte Dimension}
10772: 10(2), 1994.
10773: 
10774: @menu
10775: * Properties of the OOF model::  
10776: * Basic OOF Usage::             
10777: * The OOF base class::          
10778: * Class Declaration::           
10779: * Class Implementation::        
10780: @end menu
10781: 
10782: @node Properties of the OOF model, Basic OOF Usage, OOF, OOF
10783: @subsubsection Properties of the @file{oof.fs} model
10784: @cindex @file{oof.fs} properties
10785: 
10786: @itemize @bullet
10787: @item
10788: This model combines object oriented programming with information
10789: hiding. It helps you writing large application, where scoping is
10790: necessary, because it provides class-oriented scoping.
10791: 
10792: @item
10793: Named objects, object pointers, and object arrays can be created,
10794: selector invocation uses the ``object selector'' syntax. Selector invocation
10795: to objects and/or selectors on the stack is a bit less convenient, but
10796: possible.
10797: 
10798: @item
10799: Selector invocation and instance variable usage of the active object is
10800: straightforward, since both make use of the active object.
10801: 
10802: @item
10803: Late binding is efficient and easy to use.
10804: 
10805: @item
10806: State-smart objects parse selectors. However, extensibility is provided
10807: using a (parsing) selector @code{postpone} and a selector @code{'}.
10808: 
10809: @item
10810: An implementation in ANS Forth is available.
10811: 
10812: @end itemize
10813: 
10814: 
10815: @node Basic OOF Usage, The OOF base class, Properties of the OOF model, OOF
10816: @subsubsection Basic @file{oof.fs} Usage
10817: @cindex @file{oof.fs} usage
10818: 
10819: This section uses the same example as for @code{objects} (@pxref{Basic Objects Usage}).
10820: 
10821: You can define a class for graphical objects like this:
10822: 
10823: @cindex @code{class} usage
10824: @cindex @code{class;} usage
10825: @cindex @code{method} usage
10826: @example
10827: object class graphical \ "object" is the parent class
10828:   method draw ( x y graphical -- )
10829: class;
10830: @end example
10831: 
10832: This code defines a class @code{graphical} with an
10833: operation @code{draw}.  We can perform the operation
10834: @code{draw} on any @code{graphical} object, e.g.:
10835: 
10836: @example
10837: 100 100 t-rex draw
10838: @end example
10839: 
10840: @noindent
10841: where @code{t-rex} is an object or object pointer, created with e.g.
10842: @code{graphical : t-rex}.
10843: 
10844: @cindex abstract class
10845: How do we create a graphical object? With the present definitions,
10846: we cannot create a useful graphical object. The class
10847: @code{graphical} describes graphical objects in general, but not
10848: any concrete graphical object type (C++ users would call it an
10849: @emph{abstract class}); e.g., there is no method for the selector
10850: @code{draw} in the class @code{graphical}.
10851: 
10852: For concrete graphical objects, we define child classes of the
10853: class @code{graphical}, e.g.:
10854: 
10855: @example
10856: graphical class circle \ "graphical" is the parent class
10857:   cell var circle-radius
10858: how:
10859:   : draw ( x y -- )
10860:     circle-radius @@ draw-circle ;
10861: 
10862:   : init ( n-radius -- (
10863:     circle-radius ! ;
10864: class;
10865: @end example
10866: 
10867: Here we define a class @code{circle} as a child of @code{graphical},
10868: with a field @code{circle-radius}; it defines new methods for the
10869: selectors @code{draw} and @code{init} (@code{init} is defined in
10870: @code{object}, the parent class of @code{graphical}).
10871: 
10872: Now we can create a circle in the dictionary with:
10873: 
10874: @example
10875: 50 circle : my-circle
10876: @end example
10877: 
10878: @noindent
10879: @code{:} invokes @code{init}, thus initializing the field
10880: @code{circle-radius} with 50. We can draw this new circle at (100,100)
10881: with:
10882: 
10883: @example
10884: 100 100 my-circle draw
10885: @end example
10886: 
10887: @cindex selector invocation, restrictions
10888: @cindex class definition, restrictions
10889: Note: You can only invoke a selector if the receiving object belongs to
10890: the class where the selector was defined or one of its descendents;
10891: e.g., you can invoke @code{draw} only for objects belonging to
10892: @code{graphical} or its descendents (e.g., @code{circle}). The scoping
10893: mechanism will check if you try to invoke a selector that is not
10894: defined in this class hierarchy, so you'll get an error at compilation
10895: time.
10896: 
10897: 
10898: @node The OOF base class, Class Declaration, Basic OOF Usage, OOF
10899: @subsubsection The @file{oof.fs} base class
10900: @cindex @file{oof.fs} base class
10901: 
10902: When you define a class, you have to specify a parent class.  So how do
10903: you start defining classes? There is one class available from the start:
10904: @code{object}. You have to use it as ancestor for all classes. It is the
10905: only class that has no parent. Classes are also objects, except that
10906: they don't have instance variables; class manipulation such as
10907: inheritance or changing definitions of a class is handled through
10908: selectors of the class @code{object}.
10909: 
10910: @code{object} provides a number of selectors:
10911: 
10912: @itemize @bullet
10913: @item
10914: @code{class} for subclassing, @code{definitions} to add definitions
10915: later on, and @code{class?} to get type informations (is the class a
10916: subclass of the class passed on the stack?).
10917: 
10918: doc---object-class
10919: doc---object-definitions
10920: doc---object-class?
10921: 
10922: 
10923: @item
10924: @code{init} and @code{dispose} as constructor and destructor of the
10925: object. @code{init} is invocated after the object's memory is allocated,
10926: while @code{dispose} also handles deallocation. Thus if you redefine
10927: @code{dispose}, you have to call the parent's dispose with @code{super
10928: dispose}, too.
10929: 
10930: doc---object-init
10931: doc---object-dispose
10932: 
10933: 
10934: @item
10935: @code{new}, @code{new[]}, @code{:}, @code{ptr}, @code{asptr}, and
10936: @code{[]} to create named and unnamed objects and object arrays or
10937: object pointers.
10938: 
10939: doc---object-new
10940: doc---object-new[]
10941: doc---object-:
10942: doc---object-ptr
10943: doc---object-asptr
10944: doc---object-[]
10945: 
10946: 
10947: @item
10948: @code{::} and @code{super} for explicit scoping. You should use explicit
10949: scoping only for super classes or classes with the same set of instance
10950: variables. Explicitly-scoped selectors use early binding.
10951: 
10952: doc---object-::
10953: doc---object-super
10954: 
10955: 
10956: @item
10957: @code{self} to get the address of the object
10958: 
10959: doc---object-self
10960: 
10961: 
10962: @item
10963: @code{bind}, @code{bound}, @code{link}, and @code{is} to assign object
10964: pointers and instance defers.
10965: 
10966: doc---object-bind
10967: doc---object-bound
10968: doc---object-link
10969: doc---object-is
10970: 
10971: 
10972: @item
10973: @code{'} to obtain selector tokens, @code{send} to invocate selectors
10974: form the stack, and @code{postpone} to generate selector invocation code.
10975: 
10976: doc---object-'
10977: doc---object-postpone
10978: 
10979: 
10980: @item
10981: @code{with} and @code{endwith} to select the active object from the
10982: stack, and enable its scope. Using @code{with} and @code{endwith}
10983: also allows you to create code using selector @code{postpone} without being
10984: trapped by the state-smart objects.
10985: 
10986: doc---object-with
10987: doc---object-endwith
10988: 
10989: 
10990: @end itemize
10991: 
10992: @node Class Declaration, Class Implementation, The OOF base class, OOF
10993: @subsubsection Class Declaration
10994: @cindex class declaration
10995: 
10996: @itemize @bullet
10997: @item
10998: Instance variables
10999: 
11000: doc---oof-var
11001: 
11002: 
11003: @item
11004: Object pointers
11005: 
11006: doc---oof-ptr
11007: doc---oof-asptr
11008: 
11009: 
11010: @item
11011: Instance defers
11012: 
11013: doc---oof-defer
11014: 
11015: 
11016: @item
11017: Method selectors
11018: 
11019: doc---oof-early
11020: doc---oof-method
11021: 
11022: 
11023: @item
11024: Class-wide variables
11025: 
11026: doc---oof-static
11027: 
11028: 
11029: @item
11030: End declaration
11031: 
11032: doc---oof-how:
11033: doc---oof-class;
11034: 
11035: 
11036: @end itemize
11037: 
11038: @c -------------------------------------------------------------
11039: @node Class Implementation,  , Class Declaration, OOF
11040: @subsubsection Class Implementation
11041: @cindex class implementation
11042: 
11043: @c -------------------------------------------------------------
11044: @node Mini-OOF, Comparison with other object models, OOF, Object-oriented Forth
11045: @subsection The @file{mini-oof.fs} model
11046: @cindex mini-oof
11047: 
11048: Gforth's third object oriented Forth package is a 12-liner. It uses a
11049: mixture of the @file{objects.fs} and the @file{oof.fs} syntax,
11050: and reduces to the bare minimum of features. This is based on a posting
11051: of Bernd Paysan in comp.lang.forth.
11052: 
11053: @menu
11054: * Basic Mini-OOF Usage::        
11055: * Mini-OOF Example::            
11056: * Mini-OOF Implementation::     
11057: @end menu
11058: 
11059: @c -------------------------------------------------------------
11060: @node Basic Mini-OOF Usage, Mini-OOF Example, Mini-OOF, Mini-OOF
11061: @subsubsection Basic @file{mini-oof.fs} Usage
11062: @cindex mini-oof usage
11063: 
11064: There is a base class (@code{class}, which allocates one cell for the
11065: object pointer) plus seven other words: to define a method, a variable,
11066: a class; to end a class, to resolve binding, to allocate an object and
11067: to compile a class method.
11068: @comment TODO better description of the last one
11069: 
11070: 
11071: doc-object
11072: doc-method
11073: doc-var
11074: doc-class
11075: doc-end-class
11076: doc-defines
11077: doc-new
11078: doc-::
11079: 
11080: 
11081: 
11082: @c -------------------------------------------------------------
11083: @node Mini-OOF Example, Mini-OOF Implementation, Basic Mini-OOF Usage, Mini-OOF
11084: @subsubsection Mini-OOF Example
11085: @cindex mini-oof example
11086: 
11087: A short example shows how to use this package. This example, in slightly
11088: extended form, is supplied as @file{moof-exm.fs}
11089: @comment TODO could flesh this out with some comments from the Forthwrite article
11090: 
11091: @example
11092: object class
11093:   method init
11094:   method draw
11095: end-class graphical
11096: @end example
11097: 
11098: This code defines a class @code{graphical} with an
11099: operation @code{draw}.  We can perform the operation
11100: @code{draw} on any @code{graphical} object, e.g.:
11101: 
11102: @example
11103: 100 100 t-rex draw
11104: @end example
11105: 
11106: where @code{t-rex} is an object or object pointer, created with e.g.
11107: @code{graphical new Constant t-rex}.
11108: 
11109: For concrete graphical objects, we define child classes of the
11110: class @code{graphical}, e.g.:
11111: 
11112: @example
11113: graphical class
11114:   cell var circle-radius
11115: end-class circle \ "graphical" is the parent class
11116: 
11117: :noname ( x y -- )
11118:   circle-radius @@ draw-circle ; circle defines draw
11119: :noname ( r -- )
11120:   circle-radius ! ; circle defines init
11121: @end example
11122: 
11123: There is no implicit init method, so we have to define one. The creation
11124: code of the object now has to call init explicitely.
11125: 
11126: @example
11127: circle new Constant my-circle
11128: 50 my-circle init
11129: @end example
11130: 
11131: It is also possible to add a function to create named objects with
11132: automatic call of @code{init}, given that all objects have @code{init}
11133: on the same place:
11134: 
11135: @example
11136: : new: ( .. o "name" -- )
11137:     new dup Constant init ;
11138: 80 circle new: large-circle
11139: @end example
11140: 
11141: We can draw this new circle at (100,100) with:
11142: 
11143: @example
11144: 100 100 my-circle draw
11145: @end example
11146: 
11147: @node Mini-OOF Implementation,  , Mini-OOF Example, Mini-OOF
11148: @subsubsection @file{mini-oof.fs} Implementation
11149: 
11150: Object-oriented systems with late binding typically use a
11151: ``vtable''-approach: the first variable in each object is a pointer to a
11152: table, which contains the methods as function pointers. The vtable
11153: may also contain other information.
11154: 
11155: So first, let's declare selectors:
11156: 
11157: @example
11158: : method ( m v "name" -- m' v ) Create  over , swap cell+ swap
11159:   DOES> ( ... o -- ... ) @@ over @@ + @@ execute ;
11160: @end example
11161: 
11162: During selector declaration, the number of selectors and instance
11163: variables is on the stack (in address units). @code{method} creates one
11164: selector and increments the selector number. To execute a selector, it
11165: takes the object, fetches the vtable pointer, adds the offset, and
11166: executes the method @i{xt} stored there. Each selector takes the object
11167: it is invoked with as top of stack parameter; it passes the parameters
11168: (including the object) unchanged to the appropriate method which should
11169: consume that object.
11170: 
11171: Now, we also have to declare instance variables
11172: 
11173: @example
11174: : var ( m v size "name" -- m v' ) Create  over , +
11175:   DOES> ( o -- addr ) @@ + ;
11176: @end example
11177: 
11178: As before, a word is created with the current offset. Instance
11179: variables can have different sizes (cells, floats, doubles, chars), so
11180: all we do is take the size and add it to the offset. If your machine
11181: has alignment restrictions, put the proper @code{aligned} or
11182: @code{faligned} before the variable, to adjust the variable
11183: offset. That's why it is on the top of stack.
11184: 
11185: We need a starting point (the base object) and some syntactic sugar:
11186: 
11187: @example
11188: Create object  1 cells , 2 cells ,
11189: : class ( class -- class selectors vars ) dup 2@@ ;
11190: @end example
11191: 
11192: For inheritance, the vtable of the parent object has to be
11193: copied when a new, derived class is declared. This gives all the
11194: methods of the parent class, which can be overridden, though.
11195: 
11196: @example
11197: : end-class  ( class selectors vars "name" -- )
11198:   Create  here >r , dup , 2 cells ?DO ['] noop , 1 cells +LOOP
11199:   cell+ dup cell+ r> rot @@ 2 cells /string move ;
11200: @end example
11201: 
11202: The first line creates the vtable, initialized with
11203: @code{noop}s. The second line is the inheritance mechanism, it
11204: copies the xts from the parent vtable.
11205: 
11206: We still have no way to define new methods, let's do that now:
11207: 
11208: @example
11209: : defines ( xt class "name" -- ) ' >body @@ + ! ;
11210: @end example
11211: 
11212: To allocate a new object, we need a word, too:
11213: 
11214: @example
11215: : new ( class -- o )  here over @@ allot swap over ! ;
11216: @end example
11217: 
11218: Sometimes derived classes want to access the method of the
11219: parent object. There are two ways to achieve this with Mini-OOF:
11220: first, you could use named words, and second, you could look up the
11221: vtable of the parent object.
11222: 
11223: @example
11224: : :: ( class "name" -- ) ' >body @@ + @@ compile, ;
11225: @end example
11226: 
11227: 
11228: Nothing can be more confusing than a good example, so here is
11229: one. First let's declare a text object (called
11230: @code{button}), that stores text and position:
11231: 
11232: @example
11233: object class
11234:   cell var text
11235:   cell var len
11236:   cell var x
11237:   cell var y
11238:   method init
11239:   method draw
11240: end-class button
11241: @end example
11242: 
11243: @noindent
11244: Now, implement the two methods, @code{draw} and @code{init}:
11245: 
11246: @example
11247: :noname ( o -- )
11248:  >r r@@ x @@ r@@ y @@ at-xy  r@@ text @@ r> len @@ type ;
11249:  button defines draw
11250: :noname ( addr u o -- )
11251:  >r 0 r@@ x ! 0 r@@ y ! r@@ len ! r> text ! ;
11252:  button defines init
11253: @end example
11254: 
11255: @noindent
11256: To demonstrate inheritance, we define a class @code{bold-button}, with no
11257: new data and no new selectors:
11258: 
11259: @example
11260: button class
11261: end-class bold-button
11262: 
11263: : bold   27 emit ." [1m" ;
11264: : normal 27 emit ." [0m" ;
11265: @end example
11266: 
11267: @noindent
11268: The class @code{bold-button} has a different draw method to
11269: @code{button}, but the new method is defined in terms of the draw method
11270: for @code{button}:
11271: 
11272: @example
11273: :noname bold [ button :: draw ] normal ; bold-button defines draw
11274: @end example
11275: 
11276: @noindent
11277: Finally, create two objects and apply selectors:
11278: 
11279: @example
11280: button new Constant foo
11281: s" thin foo" foo init
11282: page
11283: foo draw
11284: bold-button new Constant bar
11285: s" fat bar" bar init
11286: 1 bar y !
11287: bar draw
11288: @end example
11289: 
11290: 
11291: @node Comparison with other object models,  , Mini-OOF, Object-oriented Forth
11292: @subsection Comparison with other object models
11293: @cindex comparison of object models
11294: @cindex object models, comparison
11295: 
11296: Many object-oriented Forth extensions have been proposed (@cite{A survey
11297: of object-oriented Forths} (SIGPLAN Notices, April 1996) by Bradford
11298: J. Rodriguez and W. F. S. Poehlman lists 17). This section discusses the
11299: relation of the object models described here to two well-known and two
11300: closely-related (by the use of method maps) models.  Andras Zsoter
11301: helped us with this section.
11302: 
11303: @cindex Neon model
11304: The most popular model currently seems to be the Neon model (see
11305: @cite{Object-oriented programming in ANS Forth} (Forth Dimensions, March
11306: 1997) by Andrew McKewan) but this model has a number of limitations
11307: @footnote{A longer version of this critique can be
11308: found in @cite{On Standardizing Object-Oriented Forth Extensions} (Forth
11309: Dimensions, May 1997) by Anton Ertl.}:
11310: 
11311: @itemize @bullet
11312: @item
11313: It uses a @code{@emph{selector object}} syntax, which makes it unnatural
11314: to pass objects on the stack.
11315: 
11316: @item
11317: It requires that the selector parses the input stream (at
11318: compile time); this leads to reduced extensibility and to bugs that are
11319: hard to find.
11320: 
11321: @item
11322: It allows using every selector on every object; this eliminates the
11323: need for interfaces, but makes it harder to create efficient
11324: implementations.
11325: @end itemize
11326: 
11327: @cindex Pountain's object-oriented model
11328: Another well-known publication is @cite{Object-Oriented Forth} (Academic
11329: Press, London, 1987) by Dick Pountain. However, it is not really about
11330: object-oriented programming, because it hardly deals with late
11331: binding. Instead, it focuses on features like information hiding and
11332: overloading that are characteristic of modular languages like Ada (83).
11333: 
11334: @cindex Zsoter's object-oriented model
11335: In @uref{http://www.forth.org/oopf.html, Does late binding have to be
11336: slow?} (Forth Dimensions 18(1) 1996, pages 31-35) Andras Zsoter
11337: describes a model that makes heavy use of an active object (like
11338: @code{this} in @file{objects.fs}): The active object is not only used
11339: for accessing all fields, but also specifies the receiving object of
11340: every selector invocation; you have to change the active object
11341: explicitly with @code{@{ ... @}}, whereas in @file{objects.fs} it
11342: changes more or less implicitly at @code{m: ... ;m}. Such a change at
11343: the method entry point is unnecessary with Zsoter's model, because the
11344: receiving object is the active object already. On the other hand, the
11345: explicit change is absolutely necessary in that model, because otherwise
11346: no one could ever change the active object. An ANS Forth implementation
11347: of this model is available through
11348: @uref{http://www.forth.org/oopf.html}.
11349: 
11350: @cindex @file{oof.fs}, differences to other models
11351: The @file{oof.fs} model combines information hiding and overloading
11352: resolution (by keeping names in various word lists) with object-oriented
11353: programming. It sets the active object implicitly on method entry, but
11354: also allows explicit changing (with @code{>o...o>} or with
11355: @code{with...endwith}). It uses parsing and state-smart objects and
11356: classes for resolving overloading and for early binding: the object or
11357: class parses the selector and determines the method from this. If the
11358: selector is not parsed by an object or class, it performs a call to the
11359: selector for the active object (late binding), like Zsoter's model.
11360: Fields are always accessed through the active object. The big
11361: disadvantage of this model is the parsing and the state-smartness, which
11362: reduces extensibility and increases the opportunities for subtle bugs;
11363: essentially, you are only safe if you never tick or @code{postpone} an
11364: object or class (Bernd disagrees, but I (Anton) am not convinced).
11365: 
11366: @cindex @file{mini-oof.fs}, differences to other models
11367: The @file{mini-oof.fs} model is quite similar to a very stripped-down
11368: version of the @file{objects.fs} model, but syntactically it is a
11369: mixture of the @file{objects.fs} and @file{oof.fs} models.
11370: 
11371: 
11372: @c -------------------------------------------------------------
11373: @node Programming Tools, Assembler and Code Words, Object-oriented Forth, Words
11374: @section Programming Tools
11375: @cindex programming tools
11376: 
11377: @c !! move this and assembler down below OO stuff.
11378: 
11379: @menu
11380: * Examining::                   
11381: * Forgetting words::            
11382: * Debugging::                   Simple and quick.
11383: * Assertions::                  Making your programs self-checking.
11384: * Singlestep Debugger::         Executing your program word by word.
11385: @end menu
11386: 
11387: @node Examining, Forgetting words, Programming Tools, Programming Tools
11388: @subsection Examining data and code
11389: @cindex examining data and code
11390: @cindex data examination
11391: @cindex code examination
11392: 
11393: The following words inspect the stack non-destructively:
11394: 
11395: doc-.s
11396: doc-f.s
11397: 
11398: There is a word @code{.r} but it does @i{not} display the return stack!
11399: It is used for formatted numeric output (@pxref{Simple numeric output}).
11400: 
11401: doc-depth
11402: doc-fdepth
11403: doc-clearstack
11404: 
11405: The following words inspect memory.
11406: 
11407: doc-?
11408: doc-dump
11409: 
11410: And finally, @code{see} allows to inspect code:
11411: 
11412: doc-see
11413: doc-xt-see
11414: 
11415: @node Forgetting words, Debugging, Examining, Programming Tools
11416: @subsection Forgetting words
11417: @cindex words, forgetting
11418: @cindex forgeting words
11419: 
11420: @c  anton: other, maybe better places for this subsection: Defining Words;
11421: @c  Dictionary allocation.  At least a reference should be there.
11422: 
11423: Forth allows you to forget words (and everything that was alloted in the
11424: dictonary after them) in a LIFO manner.
11425: 
11426: doc-marker
11427: 
11428: The most common use of this feature is during progam development: when
11429: you change a source file, forget all the words it defined and load it
11430: again (since you also forget everything defined after the source file
11431: was loaded, you have to reload that, too).  Note that effects like
11432: storing to variables and destroyed system words are not undone when you
11433: forget words.  With a system like Gforth, that is fast enough at
11434: starting up and compiling, I find it more convenient to exit and restart
11435: Gforth, as this gives me a clean slate.
11436: 
11437: Here's an example of using @code{marker} at the start of a source file
11438: that you are debugging; it ensures that you only ever have one copy of
11439: the file's definitions compiled at any time:
11440: 
11441: @example
11442: [IFDEF] my-code
11443:     my-code
11444: [ENDIF]
11445: 
11446: marker my-code
11447: init-included-files
11448: 
11449: \ .. definitions start here
11450: \ .
11451: \ .
11452: \ end
11453: @end example
11454: 
11455: 
11456: @node Debugging, Assertions, Forgetting words, Programming Tools
11457: @subsection Debugging
11458: @cindex debugging
11459: 
11460: Languages with a slow edit/compile/link/test development loop tend to
11461: require sophisticated tracing/stepping debuggers to facilate debugging.
11462: 
11463: A much better (faster) way in fast-compiling languages is to add
11464: printing code at well-selected places, let the program run, look at
11465: the output, see where things went wrong, add more printing code, etc.,
11466: until the bug is found.
11467: 
11468: The simple debugging aids provided in @file{debugs.fs}
11469: are meant to support this style of debugging.
11470: 
11471: The word @code{~~} prints debugging information (by default the source
11472: location and the stack contents). It is easy to insert. If you use Emacs
11473: it is also easy to remove (@kbd{C-x ~} in the Emacs Forth mode to
11474: query-replace them with nothing). The deferred words
11475: @code{printdebugdata} and @code{printdebugline} control the output of
11476: @code{~~}. The default source location output format works well with
11477: Emacs' compilation mode, so you can step through the program at the
11478: source level using @kbd{C-x `} (the advantage over a stepping debugger
11479: is that you can step in any direction and you know where the crash has
11480: happened or where the strange data has occurred).
11481: 
11482: doc-~~
11483: doc-printdebugdata
11484: doc-printdebugline
11485: 
11486: @node Assertions, Singlestep Debugger, Debugging, Programming Tools
11487: @subsection Assertions
11488: @cindex assertions
11489: 
11490: It is a good idea to make your programs self-checking, especially if you
11491: make an assumption that may become invalid during maintenance (for
11492: example, that a certain field of a data structure is never zero). Gforth
11493: supports @dfn{assertions} for this purpose. They are used like this:
11494: 
11495: @example
11496: assert( @i{flag} )
11497: @end example
11498: 
11499: The code between @code{assert(} and @code{)} should compute a flag, that
11500: should be true if everything is alright and false otherwise. It should
11501: not change anything else on the stack. The overall stack effect of the
11502: assertion is @code{( -- )}. E.g.
11503: 
11504: @example
11505: assert( 1 1 + 2 = ) \ what we learn in school
11506: assert( dup 0<> ) \ assert that the top of stack is not zero
11507: assert( false ) \ this code should not be reached
11508: @end example
11509: 
11510: The need for assertions is different at different times. During
11511: debugging, we want more checking, in production we sometimes care more
11512: for speed. Therefore, assertions can be turned off, i.e., the assertion
11513: becomes a comment. Depending on the importance of an assertion and the
11514: time it takes to check it, you may want to turn off some assertions and
11515: keep others turned on. Gforth provides several levels of assertions for
11516: this purpose:
11517: 
11518: 
11519: doc-assert0(
11520: doc-assert1(
11521: doc-assert2(
11522: doc-assert3(
11523: doc-assert(
11524: doc-)
11525: 
11526: 
11527: The variable @code{assert-level} specifies the highest assertions that
11528: are turned on. I.e., at the default @code{assert-level} of one,
11529: @code{assert0(} and @code{assert1(} assertions perform checking, while
11530: @code{assert2(} and @code{assert3(} assertions are treated as comments.
11531: 
11532: The value of @code{assert-level} is evaluated at compile-time, not at
11533: run-time. Therefore you cannot turn assertions on or off at run-time;
11534: you have to set the @code{assert-level} appropriately before compiling a
11535: piece of code. You can compile different pieces of code at different
11536: @code{assert-level}s (e.g., a trusted library at level 1 and
11537: newly-written code at level 3).
11538: 
11539: 
11540: doc-assert-level
11541: 
11542: 
11543: If an assertion fails, a message compatible with Emacs' compilation mode
11544: is produced and the execution is aborted (currently with @code{ABORT"}.
11545: If there is interest, we will introduce a special throw code. But if you
11546: intend to @code{catch} a specific condition, using @code{throw} is
11547: probably more appropriate than an assertion).
11548: 
11549: Definitions in ANS Forth for these assertion words are provided
11550: in @file{compat/assert.fs}.
11551: 
11552: 
11553: @node Singlestep Debugger,  , Assertions, Programming Tools
11554: @subsection Singlestep Debugger
11555: @cindex singlestep Debugger
11556: @cindex debugging Singlestep
11557: 
11558: When you create a new word there's often the need to check whether it
11559: behaves correctly or not. You can do this by typing @code{dbg
11560: badword}. A debug session might look like this:
11561: 
11562: @example
11563: : badword 0 DO i . LOOP ;  ok
11564: 2 dbg badword 
11565: : badword  
11566: Scanning code...
11567: 
11568: Nesting debugger ready!
11569: 
11570: 400D4738  8049BC4 0              -> [ 2 ] 00002 00000 
11571: 400D4740  8049F68 DO             -> [ 0 ] 
11572: 400D4744  804A0C8 i              -> [ 1 ] 00000 
11573: 400D4748 400C5E60 .              -> 0 [ 0 ] 
11574: 400D474C  8049D0C LOOP           -> [ 0 ] 
11575: 400D4744  804A0C8 i              -> [ 1 ] 00001 
11576: 400D4748 400C5E60 .              -> 1 [ 0 ] 
11577: 400D474C  8049D0C LOOP           -> [ 0 ] 
11578: 400D4758  804B384 ;              ->  ok
11579: @end example
11580: 
11581: Each line displayed is one step. You always have to hit return to
11582: execute the next word that is displayed. If you don't want to execute
11583: the next word in a whole, you have to type @kbd{n} for @code{nest}. Here is
11584: an overview what keys are available:
11585: 
11586: @table @i
11587: 
11588: @item @key{RET}
11589: Next; Execute the next word.
11590: 
11591: @item n
11592: Nest; Single step through next word.
11593: 
11594: @item u
11595: Unnest; Stop debugging and execute rest of word. If we got to this word
11596: with nest, continue debugging with the calling word.
11597: 
11598: @item d
11599: Done; Stop debugging and execute rest.
11600: 
11601: @item s
11602: Stop; Abort immediately.
11603: 
11604: @end table
11605: 
11606: Debugging large application with this mechanism is very difficult, because
11607: you have to nest very deeply into the program before the interesting part
11608: begins. This takes a lot of time. 
11609: 
11610: To do it more directly put a @code{BREAK:} command into your source code.
11611: When program execution reaches @code{BREAK:} the single step debugger is
11612: invoked and you have all the features described above.
11613: 
11614: If you have more than one part to debug it is useful to know where the
11615: program has stopped at the moment. You can do this by the 
11616: @code{BREAK" string"} command. This behaves like @code{BREAK:} except that
11617: string is typed out when the ``breakpoint'' is reached.
11618: 
11619: 
11620: doc-dbg
11621: doc-break:
11622: doc-break"
11623: 
11624: 
11625: 
11626: @c -------------------------------------------------------------
11627: @node Assembler and Code Words, Threading Words, Programming Tools, Words
11628: @section Assembler and Code Words
11629: @cindex assembler
11630: @cindex code words
11631: 
11632: @menu
11633: * Code and ;code::              
11634: * Common Assembler::            Assembler Syntax
11635: * Common Disassembler::         
11636: * 386 Assembler::               Deviations and special cases
11637: * Alpha Assembler::             Deviations and special cases
11638: * MIPS assembler::              Deviations and special cases
11639: * Other assemblers::            How to write them
11640: @end menu
11641: 
11642: @node Code and ;code, Common Assembler, Assembler and Code Words, Assembler and Code Words
11643: @subsection @code{Code} and @code{;code}
11644: 
11645: Gforth provides some words for defining primitives (words written in
11646: machine code), and for defining the machine-code equivalent of
11647: @code{DOES>}-based defining words. However, the machine-independent
11648: nature of Gforth poses a few problems: First of all, Gforth runs on
11649: several architectures, so it can provide no standard assembler. What's
11650: worse is that the register allocation not only depends on the processor,
11651: but also on the @code{gcc} version and options used.
11652: 
11653: The words that Gforth offers encapsulate some system dependences (e.g.,
11654: the header structure), so a system-independent assembler may be used in
11655: Gforth. If you do not have an assembler, you can compile machine code
11656: directly with @code{,} and @code{c,}@footnote{This isn't portable,
11657: because these words emit stuff in @i{data} space; it works because
11658: Gforth has unified code/data spaces. Assembler isn't likely to be
11659: portable anyway.}.
11660: 
11661: 
11662: doc-assembler
11663: doc-init-asm
11664: doc-code
11665: doc-end-code
11666: doc-;code
11667: doc-flush-icache
11668: 
11669: 
11670: If @code{flush-icache} does not work correctly, @code{code} words
11671: etc. will not work (reliably), either.
11672: 
11673: The typical usage of these @code{code} words can be shown most easily by
11674: analogy to the equivalent high-level defining words:
11675: 
11676: @example
11677: : foo                              code foo
11678:    <high-level Forth words>              <assembler>
11679: ;                                  end-code
11680:                                 
11681: : bar                              : bar
11682:    <high-level Forth words>           <high-level Forth words>
11683:    CREATE                             CREATE
11684:       <high-level Forth words>           <high-level Forth words>
11685:    DOES>                              ;code
11686:       <high-level Forth words>           <assembler>
11687: ;                                  end-code
11688: @end example
11689: 
11690: @c anton: the following stuff is also in "Common Assembler", in less detail.
11691: 
11692: @cindex registers of the inner interpreter
11693: In the assembly code you will want to refer to the inner interpreter's
11694: registers (e.g., the data stack pointer) and you may want to use other
11695: registers for temporary storage. Unfortunately, the register allocation
11696: is installation-dependent.
11697: 
11698: In particular, @code{ip} (Forth instruction pointer) and @code{rp}
11699: (return stack pointer) are in different places in @code{gforth} and
11700: @code{gforth-fast}.  This means that you cannot write a @code{NEXT}
11701: routine that works on both versions; so for doing @code{NEXT}, I
11702: recomment jumping to @code{' noop >code-address}, which contains nothing
11703: but a @code{NEXT}.
11704: 
11705: For general accesses to the inner interpreter's registers, the easiest
11706: solution is to use explicit register declarations (@pxref{Explicit Reg
11707: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) for
11708: all of the inner interpreter's registers: You have to compile Gforth
11709: with @code{-DFORCE_REG} (configure option @code{--enable-force-reg}) and
11710: the appropriate declarations must be present in the @code{machine.h}
11711: file (see @code{mips.h} for an example; you can find a full list of all
11712: declarable register symbols with @code{grep register engine.c}). If you
11713: give explicit registers to all variables that are declared at the
11714: beginning of @code{engine()}, you should be able to use the other
11715: caller-saved registers for temporary storage. Alternatively, you can use
11716: the @code{gcc} option @code{-ffixed-REG} (@pxref{Code Gen Options, ,
11717: Options for Code Generation Conventions, gcc.info, GNU C Manual}) to
11718: reserve a register (however, this restriction on register allocation may
11719: slow Gforth significantly).
11720: 
11721: If this solution is not viable (e.g., because @code{gcc} does not allow
11722: you to explicitly declare all the registers you need), you have to find
11723: out by looking at the code where the inner interpreter's registers
11724: reside and which registers can be used for temporary storage. You can
11725: get an assembly listing of the engine's code with @code{make engine.s}.
11726: 
11727: In any case, it is good practice to abstract your assembly code from the
11728: actual register allocation. E.g., if the data stack pointer resides in
11729: register @code{$17}, create an alias for this register called @code{sp},
11730: and use that in your assembly code.
11731: 
11732: @cindex code words, portable
11733: Another option for implementing normal and defining words efficiently
11734: is to add the desired functionality to the source of Gforth. For normal
11735: words you just have to edit @file{primitives} (@pxref{Automatic
11736: Generation}). Defining words (equivalent to @code{;CODE} words, for fast
11737: defined words) may require changes in @file{engine.c}, @file{kernel.fs},
11738: @file{prims2x.fs}, and possibly @file{cross.fs}.
11739: 
11740: @node Common Assembler, Common Disassembler, Code and ;code, Assembler and Code Words
11741: @subsection Common Assembler
11742: 
11743: The assemblers in Gforth generally use a postfix syntax, i.e., the
11744: instruction name follows the operands.
11745: 
11746: The operands are passed in the usual order (the same that is used in the
11747: manual of the architecture).  Since they all are Forth words, they have
11748: to be separated by spaces; you can also use Forth words to compute the
11749: operands.
11750: 
11751: The instruction names usually end with a @code{,}.  This makes it easier
11752: to visually separate instructions if you put several of them on one
11753: line; it also avoids shadowing other Forth words (e.g., @code{and}).
11754: 
11755: Registers are usually specified by number; e.g., (decimal) @code{11}
11756: specifies registers R11 and F11 on the Alpha architecture (which one,
11757: depends on the instruction).  The usual names are also available, e.g.,
11758: @code{s2} for R11 on Alpha.
11759: 
11760: Control flow is specified similar to normal Forth code (@pxref{Arbitrary
11761: control structures}), with @code{if,}, @code{ahead,}, @code{then,},
11762: @code{begin,}, @code{until,}, @code{again,}, @code{cs-roll},
11763: @code{cs-pick}, @code{else,}, @code{while,}, and @code{repeat,}.  The
11764: conditions are specified in a way specific to each assembler.
11765: 
11766: Note that the register assignments of the Gforth engine can change
11767: between Gforth versions, or even between different compilations of the
11768: same Gforth version (e.g., if you use a different GCC version).  So if
11769: you want to refer to Gforth's registers (e.g., the stack pointer or
11770: TOS), I recommend defining your own words for refering to these
11771: registers, and using them later on; then you can easily adapt to a
11772: changed register assignment.  The stability of the register assignment
11773: is usually better if you build Gforth with @code{--enable-force-reg}.
11774: 
11775: In particular, the return stack pointer and the instruction pointer are
11776: in memory in @code{gforth}, and usually in registers in
11777: @code{gforth-fast}.  The most common use of these registers is to
11778: dispatch to the next word (the @code{next} routine).  A portable way to
11779: do this is to jump to @code{' noop >code-address} (of course, this is
11780: less efficient than integrating the @code{next} code and scheduling it
11781: well).
11782: 
11783: @node  Common Disassembler, 386 Assembler, Common Assembler, Assembler and Code Words
11784: @subsection Common Disassembler
11785: 
11786: You can disassemble a @code{code} word with @code{see}
11787: (@pxref{Debugging}).  You can disassemble a section of memory with
11788: 
11789: doc-disasm
11790: 
11791: The disassembler generally produces output that can be fed into the
11792: assembler (i.e., same syntax, etc.).  It also includes additional
11793: information in comments.  In particular, the address of the instruction
11794: is given in a comment before the instruction.
11795: 
11796: @code{See} may display more or less than the actual code of the word,
11797: because the recognition of the end of the code is unreliable.  You can
11798: use @code{disasm} if it did not display enough.  It may display more, if
11799: the code word is not immediately followed by a named word.  If you have
11800: something else there, you can follow the word with @code{align last @ ,}
11801: to ensure that the end is recognized.
11802: 
11803: @node 386 Assembler, Alpha Assembler, Common Disassembler, Assembler and Code Words
11804: @subsection 386 Assembler
11805: 
11806: The 386 assembler included in Gforth was written by Bernd Paysan, it's
11807: available under GPL, and originally part of bigFORTH.
11808: 
11809: The 386 disassembler included in Gforth was written by Andrew McKewan
11810: and is in the public domain.
11811: 
11812: The disassembler displays code in prefix Intel syntax.
11813: 
11814: The assembler uses a postfix syntax with reversed parameters.
11815: 
11816: The assembler includes all instruction of the Athlon, i.e. 486 core
11817: instructions, Pentium and PPro extensions, floating point, MMX, 3Dnow!,
11818: but not ISSE. It's an integrated 16- and 32-bit assembler. Default is 32
11819: bit, you can switch to 16 bit with .86 and back to 32 bit with .386.
11820: 
11821: There are several prefixes to switch between different operation sizes,
11822: @code{.b} for byte accesses, @code{.w} for word accesses, @code{.d} for
11823: double-word accesses. Addressing modes can be switched with @code{.wa}
11824: for 16 bit addresses, and @code{.da} for 32 bit addresses. You don't
11825: need a prefix for byte register names (@code{AL} et al).
11826: 
11827: For floating point operations, the prefixes are @code{.fs} (IEEE
11828: single), @code{.fl} (IEEE double), @code{.fx} (extended), @code{.fw}
11829: (word), @code{.fd} (double-word), and @code{.fq} (quad-word).
11830: 
11831: The MMX opcodes don't have size prefixes, they are spelled out like in
11832: the Intel assembler. Instead of move from and to memory, there are
11833: PLDQ/PLDD and PSTQ/PSTD.
11834: 
11835: The registers lack the 'e' prefix; even in 32 bit mode, eax is called
11836: ax.  Immediate values are indicated by postfixing them with @code{#},
11837: e.g., @code{3 #}.  Here are some examples of addressing modes:
11838: 
11839: @example
11840: 3 #          \ immediate
11841: 1000 #)      \ absolute
11842: ax           \ register
11843: 100 di d)    \ 100[edi]
11844: 4 bx cx di)  \ 4[ebx][ecx]
11845: di ax *4 i)  \ [edi][eax*4]
11846: 20 ax *4 i#) \ 20[eax*4]
11847: @end example
11848: 
11849: Some example of instructions are:
11850: 
11851: @example
11852: ax bx mov             \ move ebx,eax
11853: 3 # ax mov            \ mov eax,3
11854: 100 di ) ax mov       \ mov eax,100[edi]
11855: 4 bx cx di) ax mov    \ mov eax,4[ebx][ecx]
11856: .w ax bx mov          \ mov bx,ax
11857: @end example
11858: 
11859: The following forms are supported for binary instructions:
11860: 
11861: @example
11862: <reg> <reg> <inst>
11863: <n> # <reg> <inst>
11864: <mem> <reg> <inst>
11865: <reg> <mem> <inst>
11866: @end example
11867: 
11868: Immediate to memory is not supported.  The shift/rotate syntax is:
11869: 
11870: @example
11871: <reg/mem> 1 # shl \ shortens to shift without immediate
11872: <reg/mem> 4 # shl
11873: <reg/mem> cl shl
11874: @end example
11875: 
11876: Precede string instructions (@code{movs} etc.) with @code{.b} to get
11877: the byte version.
11878: 
11879: The control structure words @code{IF} @code{UNTIL} etc. must be preceded
11880: by one of these conditions: @code{vs vc u< u>= 0= 0<> u<= u> 0< 0>= ps
11881: pc < >= <= >}. (Note that most of these words shadow some Forth words
11882: when @code{assembler} is in front of @code{forth} in the search path,
11883: e.g., in @code{code} words).  Currently the control structure words use
11884: one stack item, so you have to use @code{roll} instead of @code{cs-roll}
11885: to shuffle them (you can also use @code{swap} etc.).
11886: 
11887: Here is an example of a @code{code} word (assumes that the stack pointer
11888: is in esi and the TOS is in ebx):
11889: 
11890: @example
11891: code my+ ( n1 n2 -- n )
11892:     4 si D) bx add
11893:     4 # si add
11894:     Next
11895: end-code
11896: @end example
11897: 
11898: @node Alpha Assembler, MIPS assembler, 386 Assembler, Assembler and Code Words
11899: @subsection Alpha Assembler
11900: 
11901: The Alpha assembler and disassembler were originally written by Bernd
11902: Thallner.
11903: 
11904: The register names @code{a0}--@code{a5} are not available to avoid
11905: shadowing hex numbers.
11906: 
11907: Immediate forms of arithmetic instructions are distinguished by a
11908: @code{#} just before the @code{,}, e.g., @code{and#,} (note: @code{lda,}
11909: does not count as arithmetic instruction).
11910: 
11911: You have to specify all operands to an instruction, even those that
11912: other assemblers consider optional, e.g., the destination register for
11913: @code{br,}, or the destination register and hint for @code{jmp,}.
11914: 
11915: You can specify conditions for @code{if,} by removing the first @code{b}
11916: and the trailing @code{,} from a branch with a corresponding name; e.g.,
11917: 
11918: @example
11919: 11 fgt if, \ if F11>0e
11920:   ...
11921: endif,
11922: @end example
11923: 
11924: @code{fbgt,} gives @code{fgt}.  
11925: 
11926: @node MIPS assembler, Other assemblers, Alpha Assembler, Assembler and Code Words
11927: @subsection MIPS assembler
11928: 
11929: The MIPS assembler was originally written by Christian Pirker.
11930: 
11931: Currently the assembler and disassembler only cover the MIPS-I
11932: architecture (R3000), and don't support FP instructions.
11933: 
11934: The register names @code{$a0}--@code{$a3} are not available to avoid
11935: shadowing hex numbers.
11936: 
11937: Because there is no way to distinguish registers from immediate values,
11938: you have to explicitly use the immediate forms of instructions, i.e.,
11939: @code{addiu,}, not just @code{addu,} (@command{as} does this
11940: implicitly).
11941: 
11942: If the architecture manual specifies several formats for the instruction
11943: (e.g., for @code{jalr,}), you usually have to use the one with more
11944: arguments (i.e., two for @code{jalr,}).  When in doubt, see
11945: @code{arch/mips/testasm.fs} for an example of correct use.
11946: 
11947: Branches and jumps in the MIPS architecture have a delay slot.  You have
11948: to fill it yourself (the simplest way is to use @code{nop,}), the
11949: assembler does not do it for you (unlike @command{as}).  Even
11950: @code{if,}, @code{ahead,}, @code{until,}, @code{again,}, @code{while,},
11951: @code{else,} and @code{repeat,} need a delay slot.  Since @code{begin,}
11952: and @code{then,} just specify branch targets, they are not affected.
11953: 
11954: Note that you must not put branches, jumps, or @code{li,} into the delay
11955: slot: @code{li,} may expand to several instructions, and control flow
11956: instructions may not be put into the branch delay slot in any case.
11957: 
11958: For branches the argument specifying the target is a relative address;
11959: You have to add the address of the delay slot to get the absolute
11960: address.
11961: 
11962: The MIPS architecture also has load delay slots and restrictions on
11963: using @code{mfhi,} and @code{mflo,}; you have to order the instructions
11964: yourself to satisfy these restrictions, the assembler does not do it for
11965: you.
11966: 
11967: You can specify the conditions for @code{if,} etc. by taking a
11968: conditional branch and leaving away the @code{b} at the start and the
11969: @code{,} at the end.  E.g.,
11970: 
11971: @example
11972: 4 5 eq if,
11973:   ... \ do something if $4 equals $5
11974: then,
11975: @end example
11976: 
11977: @node Other assemblers,  , MIPS assembler, Assembler and Code Words
11978: @subsection Other assemblers
11979: 
11980: If you want to contribute another assembler/disassembler, please contact
11981: us (@email{bug-gforth@@gnu.org}) to check if we have such an assembler
11982: already.  If you are writing them from scratch, please use a similar
11983: syntax style as the one we use (i.e., postfix, commas at the end of the
11984: instruction names, @pxref{Common Assembler}); make the output of the
11985: disassembler be valid input for the assembler, and keep the style
11986: similar to the style we used.
11987: 
11988: Hints on implementation: The most important part is to have a good test
11989: suite that contains all instructions.  Once you have that, the rest is
11990: easy.  For actual coding you can take a look at
11991: @file{arch/mips/disasm.fs} to get some ideas on how to use data for both
11992: the assembler and disassembler, avoiding redundancy and some potential
11993: bugs.  You can also look at that file (and @pxref{Advanced does> usage
11994: example}) to get ideas how to factor a disassembler.
11995: 
11996: Start with the disassembler, because it's easier to reuse data from the
11997: disassembler for the assembler than the other way round.
11998: 
11999: For the assembler, take a look at @file{arch/alpha/asm.fs}, which shows
12000: how simple it can be.
12001: 
12002: @c -------------------------------------------------------------
12003: @node Threading Words, Passing Commands to the OS, Assembler and Code Words, Words
12004: @section Threading Words
12005: @cindex threading words
12006: 
12007: @cindex code address
12008: These words provide access to code addresses and other threading stuff
12009: in Gforth (and, possibly, other interpretive Forths). It more or less
12010: abstracts away the differences between direct and indirect threading
12011: (and, for direct threading, the machine dependences). However, at
12012: present this wordset is still incomplete. It is also pretty low-level;
12013: some day it will hopefully be made unnecessary by an internals wordset
12014: that abstracts implementation details away completely.
12015: 
12016: The terminology used here stems from indirect threaded Forth systems; in
12017: such a system, the XT of a word is represented by the CFA (code field
12018: address) of a word; the CFA points to a cell that contains the code
12019: address.  The code address is the address of some machine code that
12020: performs the run-time action of invoking the word (e.g., the
12021: @code{dovar:} routine pushes the address of the body of the word (a
12022: variable) on the stack
12023: ).
12024: 
12025: @cindex code address
12026: @cindex code field address
12027: In an indirect threaded Forth, you can get the code address of @i{name}
12028: with @code{' @i{name} @@}; in Gforth you can get it with @code{' @i{name}
12029: >code-address}, independent of the threading method.
12030: 
12031: doc-threading-method
12032: doc->code-address
12033: doc-code-address!
12034: 
12035: @cindex @code{does>}-handler
12036: @cindex @code{does>}-code
12037: For a word defined with @code{DOES>}, the code address usually points to
12038: a jump instruction (the @dfn{does-handler}) that jumps to the dodoes
12039: routine (in Gforth on some platforms, it can also point to the dodoes
12040: routine itself).  What you are typically interested in, though, is
12041: whether a word is a @code{DOES>}-defined word, and what Forth code it
12042: executes; @code{>does-code} tells you that.
12043: 
12044: doc->does-code
12045: 
12046: To create a @code{DOES>}-defined word with the following basic words,
12047: you have to set up a @code{DOES>}-handler with @code{does-handler!};
12048: @code{/does-handler} aus behind you have to place your executable Forth
12049: code.  Finally you have to create a word and modify its behaviour with
12050: @code{does-handler!}.
12051: 
12052: doc-does-code!
12053: doc-does-handler!
12054: doc-/does-handler
12055: 
12056: The code addresses produced by various defining words are produced by
12057: the following words:
12058: 
12059: doc-docol:
12060: doc-docon:
12061: doc-dovar:
12062: doc-douser:
12063: doc-dodefer:
12064: doc-dofield:
12065: 
12066: @c -------------------------------------------------------------
12067: @node Passing Commands to the OS, Keeping track of Time, Threading Words, Words
12068: @section Passing Commands to the Operating System
12069: @cindex operating system - passing commands
12070: @cindex shell commands
12071: 
12072: Gforth allows you to pass an arbitrary string to the host operating
12073: system shell (if such a thing exists) for execution.
12074: 
12075: 
12076: doc-sh
12077: doc-system
12078: doc-$?
12079: doc-getenv
12080: 
12081: 
12082: @c -------------------------------------------------------------
12083: @node Keeping track of Time, Miscellaneous Words, Passing Commands to the OS, Words
12084: @section Keeping track of Time
12085: @cindex time-related words
12086: 
12087: doc-ms
12088: doc-time&date
12089: doc-utime
12090: doc-cputime
12091: 
12092: 
12093: @c -------------------------------------------------------------
12094: @node Miscellaneous Words,  , Keeping track of Time, Words
12095: @section Miscellaneous Words
12096: @cindex miscellaneous words
12097: 
12098: @comment TODO find homes for these
12099: 
12100: These section lists the ANS Forth words that are not documented
12101: elsewhere in this manual. Ultimately, they all need proper homes.
12102: 
12103: doc-quit
12104: 
12105: The following ANS Forth words are not currently supported by Gforth 
12106: (@pxref{ANS conformance}):
12107: 
12108: @code{EDITOR} 
12109: @code{EMIT?} 
12110: @code{FORGET} 
12111: 
12112: @c ******************************************************************
12113: @node Error messages, Tools, Words, Top
12114: @chapter Error messages
12115: @cindex error messages
12116: @cindex backtrace
12117: 
12118: A typical Gforth error message looks like this:
12119: 
12120: @example
12121: in file included from \evaluated string/:-1
12122: in file included from ./yyy.fs:1
12123: ./xxx.fs:4: Invalid memory address
12124: bar
12125: ^^^
12126: Backtrace:
12127: $400E664C @@
12128: $400E6664 foo
12129: @end example
12130: 
12131: The message identifying the error is @code{Invalid memory address}.  The
12132: error happened when text-interpreting line 4 of the file
12133: @file{./xxx.fs}. This line is given (it contains @code{bar}), and the
12134: word on the line where the error happened, is pointed out (with
12135: @code{^^^}).
12136: 
12137: The file containing the error was included in line 1 of @file{./yyy.fs},
12138: and @file{yyy.fs} was included from a non-file (in this case, by giving
12139: @file{yyy.fs} as command-line parameter to Gforth).
12140: 
12141: At the end of the error message you find a return stack dump that can be
12142: interpreted as a backtrace (possibly empty). On top you find the top of
12143: the return stack when the @code{throw} happened, and at the bottom you
12144: find the return stack entry just above the return stack of the topmost
12145: text interpreter.
12146: 
12147: To the right of most return stack entries you see a guess for the word
12148: that pushed that return stack entry as its return address. This gives a
12149: backtrace. In our case we see that @code{bar} called @code{foo}, and
12150: @code{foo} called @code{@@} (and @code{@@} had an @emph{Invalid memory
12151: address} exception).
12152: 
12153: Note that the backtrace is not perfect: We don't know which return stack
12154: entries are return addresses (so we may get false positives); and in
12155: some cases (e.g., for @code{abort"}) we cannot determine from the return
12156: address the word that pushed the return address, so for some return
12157: addresses you see no names in the return stack dump.
12158: 
12159: @cindex @code{catch} and backtraces
12160: The return stack dump represents the return stack at the time when a
12161: specific @code{throw} was executed.  In programs that make use of
12162: @code{catch}, it is not necessarily clear which @code{throw} should be
12163: used for the return stack dump (e.g., consider one @code{throw} that
12164: indicates an error, which is caught, and during recovery another error
12165: happens; which @code{throw} should be used for the stack dump?).  Gforth
12166: presents the return stack dump for the first @code{throw} after the last
12167: executed (not returned-to) @code{catch}; this works well in the usual
12168: case.
12169: 
12170: @cindex @code{gforth-fast} and backtraces
12171: @cindex @code{gforth-fast}, difference from @code{gforth}
12172: @cindex backtraces with @code{gforth-fast}
12173: @cindex return stack dump with @code{gforth-fast}
12174: @code{Gforth} is able to do a return stack dump for throws generated
12175: from primitives (e.g., invalid memory address, stack empty etc.);
12176: @code{gforth-fast} is only able to do a return stack dump from a
12177: directly called @code{throw} (including @code{abort} etc.).  This is the
12178: only difference (apart from a speed factor of between 1.15 (K6-2) and
12179: 2 (21264)) between @code{gforth} and @code{gforth-fast}.  Given an
12180: exception caused by a primitive in @code{gforth-fast}, you will
12181: typically see no return stack dump at all; however, if the exception is
12182: caught by @code{catch} (e.g., for restoring some state), and then
12183: @code{throw}n again, the return stack dump will be for the first such
12184: @code{throw}.
12185: 
12186: @c ******************************************************************
12187: @node Tools, ANS conformance, Error messages, Top
12188: @chapter Tools
12189: 
12190: @menu
12191: * ANS Report::                  Report the words used, sorted by wordset.
12192: @end menu
12193: 
12194: See also @ref{Emacs and Gforth}.
12195: 
12196: @node ANS Report,  , Tools, Tools
12197: @section @file{ans-report.fs}: Report the words used, sorted by wordset
12198: @cindex @file{ans-report.fs}
12199: @cindex report the words used in your program
12200: @cindex words used in your program
12201: 
12202: If you want to label a Forth program as ANS Forth Program, you must
12203: document which wordsets the program uses; for extension wordsets, it is
12204: helpful to list the words the program requires from these wordsets
12205: (because Forth systems are allowed to provide only some words of them).
12206: 
12207: The @file{ans-report.fs} tool makes it easy for you to determine which
12208: words from which wordset and which non-ANS words your application
12209: uses. You simply have to include @file{ans-report.fs} before loading the
12210: program you want to check. After loading your program, you can get the
12211: report with @code{print-ans-report}. A typical use is to run this as
12212: batch job like this:
12213: @example
12214: gforth ans-report.fs myprog.fs -e "print-ans-report bye"
12215: @end example
12216: 
12217: The output looks like this (for @file{compat/control.fs}):
12218: @example
12219: The program uses the following words
12220: from CORE :
12221: : POSTPONE THEN ; immediate ?dup IF 0= 
12222: from BLOCK-EXT :
12223: \ 
12224: from FILE :
12225: ( 
12226: @end example
12227: 
12228: @subsection Caveats
12229: 
12230: Note that @file{ans-report.fs} just checks which words are used, not whether
12231: they are used in an ANS Forth conforming way!
12232: 
12233: Some words are defined in several wordsets in the
12234: standard. @file{ans-report.fs} reports them for only one of the
12235: wordsets, and not necessarily the one you expect. It depends on usage
12236: which wordset is the right one to specify. E.g., if you only use the
12237: compilation semantics of @code{S"}, it is a Core word; if you also use
12238: its interpretation semantics, it is a File word.
12239: 
12240: @c ******************************************************************
12241: @node ANS conformance, Standard vs Extensions, Tools, Top
12242: @chapter ANS conformance
12243: @cindex ANS conformance of Gforth
12244: 
12245: To the best of our knowledge, Gforth is an
12246: 
12247: ANS Forth System
12248: @itemize @bullet
12249: @item providing the Core Extensions word set
12250: @item providing the Block word set
12251: @item providing the Block Extensions word set
12252: @item providing the Double-Number word set
12253: @item providing the Double-Number Extensions word set
12254: @item providing the Exception word set
12255: @item providing the Exception Extensions word set
12256: @item providing the Facility word set
12257: @item providing @code{EKEY}, @code{EKEY>CHAR}, @code{EKEY?}, @code{MS} and @code{TIME&DATE} from the Facility Extensions word set
12258: @item providing the File Access word set
12259: @item providing the File Access Extensions word set
12260: @item providing the Floating-Point word set
12261: @item providing the Floating-Point Extensions word set
12262: @item providing the Locals word set
12263: @item providing the Locals Extensions word set
12264: @item providing the Memory-Allocation word set
12265: @item providing the Memory-Allocation Extensions word set (that one's easy)
12266: @item providing the Programming-Tools word set
12267: @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
12268: @item providing the Search-Order word set
12269: @item providing the Search-Order Extensions word set
12270: @item providing the String word set
12271: @item providing the String Extensions word set (another easy one)
12272: @end itemize
12273: 
12274: @cindex system documentation
12275: In addition, ANS Forth systems are required to document certain
12276: implementation choices. This chapter tries to meet these
12277: requirements. In many cases it gives a way to ask the system for the
12278: information instead of providing the information directly, in
12279: particular, if the information depends on the processor, the operating
12280: system or the installation options chosen, or if they are likely to
12281: change during the maintenance of Gforth.
12282: 
12283: @comment The framework for the rest has been taken from pfe.
12284: 
12285: @menu
12286: * The Core Words::              
12287: * The optional Block word set::  
12288: * The optional Double Number word set::  
12289: * The optional Exception word set::  
12290: * The optional Facility word set::  
12291: * The optional File-Access word set::  
12292: * The optional Floating-Point word set::  
12293: * The optional Locals word set::  
12294: * The optional Memory-Allocation word set::  
12295: * The optional Programming-Tools word set::  
12296: * The optional Search-Order word set::  
12297: @end menu
12298: 
12299: 
12300: @c =====================================================================
12301: @node The Core Words, The optional Block word set, ANS conformance, ANS conformance
12302: @comment  node-name,  next,  previous,  up
12303: @section The Core Words
12304: @c =====================================================================
12305: @cindex core words, system documentation
12306: @cindex system documentation, core words
12307: 
12308: @menu
12309: * core-idef::                   Implementation Defined Options                   
12310: * core-ambcond::                Ambiguous Conditions                
12311: * core-other::                  Other System Documentation                  
12312: @end menu
12313: 
12314: @c ---------------------------------------------------------------------
12315: @node core-idef, core-ambcond, The Core Words, The Core Words
12316: @subsection Implementation Defined Options
12317: @c ---------------------------------------------------------------------
12318: @cindex core words, implementation-defined options
12319: @cindex implementation-defined options, core words
12320: 
12321: 
12322: @table @i
12323: @item (Cell) aligned addresses:
12324: @cindex cell-aligned addresses
12325: @cindex aligned addresses
12326: processor-dependent. Gforth's alignment words perform natural alignment
12327: (e.g., an address aligned for a datum of size 8 is divisible by
12328: 8). Unaligned accesses usually result in a @code{-23 THROW}.
12329: 
12330: @item @code{EMIT} and non-graphic characters:
12331: @cindex @code{EMIT} and non-graphic characters
12332: @cindex non-graphic characters and @code{EMIT}
12333: The character is output using the C library function (actually, macro)
12334: @code{putc}.
12335: 
12336: @item character editing of @code{ACCEPT} and @code{EXPECT}:
12337: @cindex character editing of @code{ACCEPT} and @code{EXPECT}
12338: @cindex editing in @code{ACCEPT} and @code{EXPECT}
12339: @cindex @code{ACCEPT}, editing
12340: @cindex @code{EXPECT}, editing
12341: This is modeled on the GNU readline library (@pxref{Readline
12342: Interaction, , Command Line Editing, readline, The GNU Readline
12343: Library}) with Emacs-like key bindings. @kbd{Tab} deviates a little by
12344: producing a full word completion every time you type it (instead of
12345: producing the common prefix of all completions). @xref{Command-line editing}.
12346: 
12347: @item character set:
12348: @cindex character set
12349: The character set of your computer and display device. Gforth is
12350: 8-bit-clean (but some other component in your system may make trouble).
12351: 
12352: @item Character-aligned address requirements:
12353: @cindex character-aligned address requirements
12354: installation-dependent. Currently a character is represented by a C
12355: @code{unsigned char}; in the future we might switch to @code{wchar_t}
12356: (Comments on that requested).
12357: 
12358: @item character-set extensions and matching of names:
12359: @cindex character-set extensions and matching of names
12360: @cindex case-sensitivity for name lookup
12361: @cindex name lookup, case-sensitivity
12362: @cindex locale and case-sensitivity
12363: Any character except the ASCII NUL character can be used in a
12364: name. Matching is case-insensitive (except in @code{TABLE}s). The
12365: matching is performed using the C library function @code{strncasecmp}, whose
12366: function is probably influenced by the locale. E.g., the @code{C} locale
12367: does not know about accents and umlauts, so they are matched
12368: case-sensitively in that locale. For portability reasons it is best to
12369: write programs such that they work in the @code{C} locale. Then one can
12370: use libraries written by a Polish programmer (who might use words
12371: containing ISO Latin-2 encoded characters) and by a French programmer
12372: (ISO Latin-1) in the same program (of course, @code{WORDS} will produce
12373: funny results for some of the words (which ones, depends on the font you
12374: are using)). Also, the locale you prefer may not be available in other
12375: operating systems. Hopefully, Unicode will solve these problems one day.
12376: 
12377: @item conditions under which control characters match a space delimiter:
12378: @cindex space delimiters
12379: @cindex control characters as delimiters
12380: If @code{WORD} is called with the space character as a delimiter, all
12381: white-space characters (as identified by the C macro @code{isspace()})
12382: are delimiters. @code{PARSE}, on the other hand, treats space like other
12383: delimiters. @code{SWORD} treats space like @code{WORD}, but behaves
12384: like @code{PARSE} otherwise. @code{Name}, which is used by the outer
12385: interpreter (aka text interpreter) by default, treats all white-space
12386: characters as delimiters.
12387: 
12388: @item format of the control-flow stack:
12389: @cindex control-flow stack, format
12390: The data stack is used as control-flow stack. The size of a control-flow
12391: stack item in cells is given by the constant @code{cs-item-size}. At the
12392: time of this writing, an item consists of a (pointer to a) locals list
12393: (third), an address in the code (second), and a tag for identifying the
12394: item (TOS). The following tags are used: @code{defstart},
12395: @code{live-orig}, @code{dead-orig}, @code{dest}, @code{do-dest},
12396: @code{scopestart}.
12397: 
12398: @item conversion of digits > 35
12399: @cindex digits > 35
12400: The characters @code{[\]^_'} are the digits with the decimal value
12401: 36@minus{}41. There is no way to input many of the larger digits.
12402: 
12403: @item display after input terminates in @code{ACCEPT} and @code{EXPECT}:
12404: @cindex @code{EXPECT}, display after end of input
12405: @cindex @code{ACCEPT}, display after end of input
12406: The cursor is moved to the end of the entered string. If the input is
12407: terminated using the @kbd{Return} key, a space is typed.
12408: 
12409: @item exception abort sequence of @code{ABORT"}:
12410: @cindex exception abort sequence of @code{ABORT"}
12411: @cindex @code{ABORT"}, exception abort sequence
12412: The error string is stored into the variable @code{"error} and a
12413: @code{-2 throw} is performed.
12414: 
12415: @item input line terminator:
12416: @cindex input line terminator
12417: @cindex line terminator on input
12418: @cindex newline character on input
12419: For interactive input, @kbd{C-m} (CR) and @kbd{C-j} (LF) terminate
12420: lines. One of these characters is typically produced when you type the
12421: @kbd{Enter} or @kbd{Return} key.
12422: 
12423: @item maximum size of a counted string:
12424: @cindex maximum size of a counted string
12425: @cindex counted string, maximum size
12426: @code{s" /counted-string" environment? drop .}. Currently 255 characters
12427: on all platforms, but this may change.
12428: 
12429: @item maximum size of a parsed string:
12430: @cindex maximum size of a parsed string
12431: @cindex parsed string, maximum size
12432: Given by the constant @code{/line}. Currently 255 characters.
12433: 
12434: @item maximum size of a definition name, in characters:
12435: @cindex maximum size of a definition name, in characters
12436: @cindex name, maximum length
12437: 31
12438: 
12439: @item maximum string length for @code{ENVIRONMENT?}, in characters:
12440: @cindex maximum string length for @code{ENVIRONMENT?}, in characters
12441: @cindex @code{ENVIRONMENT?} string length, maximum
12442: 31
12443: 
12444: @item method of selecting the user input device:
12445: @cindex user input device, method of selecting
12446: The user input device is the standard input. There is currently no way to
12447: change it from within Gforth. However, the input can typically be
12448: redirected in the command line that starts Gforth.
12449: 
12450: @item method of selecting the user output device:
12451: @cindex user output device, method of selecting
12452: @code{EMIT} and @code{TYPE} output to the file-id stored in the value
12453: @code{outfile-id} (@code{stdout} by default). Gforth uses unbuffered
12454: output when the user output device is a terminal, otherwise the output
12455: is buffered.
12456: 
12457: @item methods of dictionary compilation:
12458: What are we expected to document here?
12459: 
12460: @item number of bits in one address unit:
12461: @cindex number of bits in one address unit
12462: @cindex address unit, size in bits
12463: @code{s" address-units-bits" environment? drop .}. 8 in all current
12464: platforms.
12465: 
12466: @item number representation and arithmetic:
12467: @cindex number representation and arithmetic
12468: Processor-dependent. Binary two's complement on all current platforms.
12469: 
12470: @item ranges for integer types:
12471: @cindex ranges for integer types
12472: @cindex integer types, ranges
12473: Installation-dependent. Make environmental queries for @code{MAX-N},
12474: @code{MAX-U}, @code{MAX-D} and @code{MAX-UD}. The lower bounds for
12475: unsigned (and positive) types is 0. The lower bound for signed types on
12476: two's complement and one's complement machines machines can be computed
12477: by adding 1 to the upper bound.
12478: 
12479: @item read-only data space regions:
12480: @cindex read-only data space regions
12481: @cindex data-space, read-only regions
12482: The whole Forth data space is writable.
12483: 
12484: @item size of buffer at @code{WORD}:
12485: @cindex size of buffer at @code{WORD}
12486: @cindex @code{WORD} buffer size
12487: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
12488: shared with the pictured numeric output string. If overwriting
12489: @code{PAD} is acceptable, it is as large as the remaining dictionary
12490: space, although only as much can be sensibly used as fits in a counted
12491: string.
12492: 
12493: @item size of one cell in address units:
12494: @cindex cell size
12495: @code{1 cells .}.
12496: 
12497: @item size of one character in address units:
12498: @cindex char size
12499: @code{1 chars .}. 1 on all current platforms.
12500: 
12501: @item size of the keyboard terminal buffer:
12502: @cindex size of the keyboard terminal buffer
12503: @cindex terminal buffer, size
12504: Varies. You can determine the size at a specific time using @code{lp@@
12505: tib - .}. It is shared with the locals stack and TIBs of files that
12506: include the current file. You can change the amount of space for TIBs
12507: and locals stack at Gforth startup with the command line option
12508: @code{-l}.
12509: 
12510: @item size of the pictured numeric output buffer:
12511: @cindex size of the pictured numeric output buffer
12512: @cindex pictured numeric output buffer, size
12513: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
12514: shared with @code{WORD}.
12515: 
12516: @item size of the scratch area returned by @code{PAD}:
12517: @cindex size of the scratch area returned by @code{PAD}
12518: @cindex @code{PAD} size
12519: The remainder of dictionary space. @code{unused pad here - - .}.
12520: 
12521: @item system case-sensitivity characteristics:
12522: @cindex case-sensitivity characteristics
12523: Dictionary searches are case-insensitive (except in
12524: @code{TABLE}s). However, as explained above under @i{character-set
12525: extensions}, the matching for non-ASCII characters is determined by the
12526: locale you are using. In the default @code{C} locale all non-ASCII
12527: characters are matched case-sensitively.
12528: 
12529: @item system prompt:
12530: @cindex system prompt
12531: @cindex prompt
12532: @code{ ok} in interpret state, @code{ compiled} in compile state.
12533: 
12534: @item division rounding:
12535: @cindex division rounding
12536: installation dependent. @code{s" floored" environment? drop .}. We leave
12537: the choice to @code{gcc} (what to use for @code{/}) and to you (whether
12538: to use @code{fm/mod}, @code{sm/rem} or simply @code{/}).
12539: 
12540: @item values of @code{STATE} when true:
12541: @cindex @code{STATE} values
12542: -1.
12543: 
12544: @item values returned after arithmetic overflow:
12545: On two's complement machines, arithmetic is performed modulo
12546: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
12547: arithmetic (with appropriate mapping for signed types). Division by zero
12548: typically results in a @code{-55 throw} (Floating-point unidentified
12549: fault) or @code{-10 throw} (divide by zero).
12550: 
12551: @item whether the current definition can be found after @t{DOES>}:
12552: @cindex @t{DOES>}, visibility of current definition
12553: No.
12554: 
12555: @end table
12556: 
12557: @c ---------------------------------------------------------------------
12558: @node core-ambcond, core-other, core-idef, The Core Words
12559: @subsection Ambiguous conditions
12560: @c ---------------------------------------------------------------------
12561: @cindex core words, ambiguous conditions
12562: @cindex ambiguous conditions, core words
12563: 
12564: @table @i
12565: 
12566: @item a name is neither a word nor a number:
12567: @cindex name not found
12568: @cindex undefined word
12569: @code{-13 throw} (Undefined word).
12570: 
12571: @item a definition name exceeds the maximum length allowed:
12572: @cindex word name too long
12573: @code{-19 throw} (Word name too long)
12574: 
12575: @item addressing a region not inside the various data spaces of the forth system:
12576: @cindex Invalid memory address
12577: The stacks, code space and header space are accessible. Machine code space is
12578: typically readable. Accessing other addresses gives results dependent on
12579: the operating system. On decent systems: @code{-9 throw} (Invalid memory
12580: address).
12581: 
12582: @item argument type incompatible with parameter:
12583: @cindex argument type mismatch
12584: This is usually not caught. Some words perform checks, e.g., the control
12585: flow words, and issue a @code{ABORT"} or @code{-12 THROW} (Argument type
12586: mismatch).
12587: 
12588: @item attempting to obtain the execution token of a word with undefined execution semantics:
12589: @cindex Interpreting a compile-only word, for @code{'} etc.
12590: @cindex execution token of words with undefined execution semantics
12591: @code{-14 throw} (Interpreting a compile-only word). In some cases, you
12592: get an execution token for @code{compile-only-error} (which performs a
12593: @code{-14 throw} when executed).
12594: 
12595: @item dividing by zero:
12596: @cindex dividing by zero
12597: @cindex floating point unidentified fault, integer division
12598: On some platforms, this produces a @code{-10 throw} (Division by
12599: zero); on other systems, this typically results in a @code{-55 throw}
12600: (Floating-point unidentified fault).
12601: 
12602: @item insufficient data stack or return stack space:
12603: @cindex insufficient data stack or return stack space
12604: @cindex stack overflow
12605: @cindex address alignment exception, stack overflow
12606: @cindex Invalid memory address, stack overflow
12607: Depending on the operating system, the installation, and the invocation
12608: of Gforth, this is either checked by the memory management hardware, or
12609: it is not checked. If it is checked, you typically get a @code{-3 throw}
12610: (Stack overflow), @code{-5 throw} (Return stack overflow), or @code{-9
12611: throw} (Invalid memory address) (depending on the platform and how you
12612: achieved the overflow) as soon as the overflow happens. If it is not
12613: checked, overflows typically result in mysterious illegal memory
12614: accesses, producing @code{-9 throw} (Invalid memory address) or
12615: @code{-23 throw} (Address alignment exception); they might also destroy
12616: the internal data structure of @code{ALLOCATE} and friends, resulting in
12617: various errors in these words.
12618: 
12619: @item insufficient space for loop control parameters:
12620: @cindex insufficient space for loop control parameters
12621: Like other return stack overflows.
12622: 
12623: @item insufficient space in the dictionary:
12624: @cindex insufficient space in the dictionary
12625: @cindex dictionary overflow
12626: If you try to allot (either directly with @code{allot}, or indirectly
12627: with @code{,}, @code{create} etc.) more memory than available in the
12628: dictionary, you get a @code{-8 throw} (Dictionary overflow). If you try
12629: to access memory beyond the end of the dictionary, the results are
12630: similar to stack overflows.
12631: 
12632: @item interpreting a word with undefined interpretation semantics:
12633: @cindex interpreting a word with undefined interpretation semantics
12634: @cindex Interpreting a compile-only word
12635: For some words, we have defined interpretation semantics. For the
12636: others: @code{-14 throw} (Interpreting a compile-only word).
12637: 
12638: @item modifying the contents of the input buffer or a string literal:
12639: @cindex modifying the contents of the input buffer or a string literal
12640: These are located in writable memory and can be modified.
12641: 
12642: @item overflow of the pictured numeric output string:
12643: @cindex overflow of the pictured numeric output string
12644: @cindex pictured numeric output string, overflow
12645: @code{-17 throw} (Pictured numeric ouput string overflow).
12646: 
12647: @item parsed string overflow:
12648: @cindex parsed string overflow
12649: @code{PARSE} cannot overflow. @code{WORD} does not check for overflow.
12650: 
12651: @item producing a result out of range:
12652: @cindex result out of range
12653: On two's complement machines, arithmetic is performed modulo
12654: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
12655: arithmetic (with appropriate mapping for signed types). Division by zero
12656: typically results in a @code{-10 throw} (divide by zero) or @code{-55
12657: throw} (floating point unidentified fault). @code{convert} and
12658: @code{>number} currently overflow silently.
12659: 
12660: @item reading from an empty data or return stack:
12661: @cindex stack empty
12662: @cindex stack underflow
12663: @cindex return stack underflow
12664: The data stack is checked by the outer (aka text) interpreter after
12665: every word executed. If it has underflowed, a @code{-4 throw} (Stack
12666: underflow) is performed. Apart from that, stacks may be checked or not,
12667: depending on operating system, installation, and invocation. If they are
12668: caught by a check, they typically result in @code{-4 throw} (Stack
12669: underflow), @code{-6 throw} (Return stack underflow) or @code{-9 throw}
12670: (Invalid memory address), depending on the platform and which stack
12671: underflows and by how much. Note that even if the system uses checking
12672: (through the MMU), your program may have to underflow by a significant
12673: number of stack items to trigger the reaction (the reason for this is
12674: that the MMU, and therefore the checking, works with a page-size
12675: granularity).  If there is no checking, the symptoms resulting from an
12676: underflow are similar to those from an overflow.  Unbalanced return
12677: stack errors can result in a variety of symptoms, including @code{-9 throw}
12678: (Invalid memory address) and Illegal Instruction (typically @code{-260
12679: throw}).
12680: 
12681: @item unexpected end of the input buffer, resulting in an attempt to use a zero-length string as a name:
12682: @cindex unexpected end of the input buffer
12683: @cindex zero-length string as a name
12684: @cindex Attempt to use zero-length string as a name
12685: @code{Create} and its descendants perform a @code{-16 throw} (Attempt to
12686: use zero-length string as a name). Words like @code{'} probably will not
12687: find what they search. Note that it is possible to create zero-length
12688: names with @code{nextname} (should it not?).
12689: 
12690: @item @code{>IN} greater than input buffer:
12691: @cindex @code{>IN} greater than input buffer
12692: The next invocation of a parsing word returns a string with length 0.
12693: 
12694: @item @code{RECURSE} appears after @code{DOES>}:
12695: @cindex @code{RECURSE} appears after @code{DOES>}
12696: Compiles a recursive call to the defining word, not to the defined word.
12697: 
12698: @item argument input source different than current input source for @code{RESTORE-INPUT}:
12699: @cindex argument input source different than current input source for @code{RESTORE-INPUT}
12700: @cindex argument type mismatch, @code{RESTORE-INPUT}
12701: @cindex @code{RESTORE-INPUT}, Argument type mismatch
12702: @code{-12 THROW}. Note that, once an input file is closed (e.g., because
12703: the end of the file was reached), its source-id may be
12704: reused. Therefore, restoring an input source specification referencing a
12705: closed file may lead to unpredictable results instead of a @code{-12
12706: THROW}.
12707: 
12708: In the future, Gforth may be able to restore input source specifications
12709: from other than the current input source.
12710: 
12711: @item data space containing definitions gets de-allocated:
12712: @cindex data space containing definitions gets de-allocated
12713: Deallocation with @code{allot} is not checked. This typically results in
12714: memory access faults or execution of illegal instructions.
12715: 
12716: @item data space read/write with incorrect alignment:
12717: @cindex data space read/write with incorrect alignment
12718: @cindex alignment faults
12719: @cindex address alignment exception
12720: Processor-dependent. Typically results in a @code{-23 throw} (Address
12721: alignment exception). Under Linux-Intel on a 486 or later processor with
12722: alignment turned on, incorrect alignment results in a @code{-9 throw}
12723: (Invalid memory address). There are reportedly some processors with
12724: alignment restrictions that do not report violations.
12725: 
12726: @item data space pointer not properly aligned, @code{,}, @code{C,}:
12727: @cindex data space pointer not properly aligned, @code{,}, @code{C,}
12728: Like other alignment errors.
12729: 
12730: @item less than u+2 stack items (@code{PICK} and @code{ROLL}):
12731: Like other stack underflows.
12732: 
12733: @item loop control parameters not available:
12734: @cindex loop control parameters not available
12735: Not checked. The counted loop words simply assume that the top of return
12736: stack items are loop control parameters and behave accordingly.
12737: 
12738: @item most recent definition does not have a name (@code{IMMEDIATE}):
12739: @cindex most recent definition does not have a name (@code{IMMEDIATE})
12740: @cindex last word was headerless
12741: @code{abort" last word was headerless"}.
12742: 
12743: @item name not defined by @code{VALUE} used by @code{TO}:
12744: @cindex name not defined by @code{VALUE} used by @code{TO}
12745: @cindex @code{TO} on non-@code{VALUE}s
12746: @cindex Invalid name argument, @code{TO}
12747: @code{-32 throw} (Invalid name argument) (unless name is a local or was
12748: defined by @code{CONSTANT}; in the latter case it just changes the constant).
12749: 
12750: @item name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}):
12751: @cindex name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]})
12752: @cindex undefined word, @code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}
12753: @code{-13 throw} (Undefined word)
12754: 
12755: @item parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN}):
12756: @cindex parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN})
12757: Gforth behaves as if they were of the same type. I.e., you can predict
12758: the behaviour by interpreting all parameters as, e.g., signed.
12759: 
12760: @item @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}:
12761: @cindex @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}
12762: Assume @code{: X POSTPONE TO ; IMMEDIATE}. @code{X} performs the
12763: compilation semantics of @code{TO}.
12764: 
12765: @item String longer than a counted string returned by @code{WORD}:
12766: @cindex string longer than a counted string returned by @code{WORD}
12767: @cindex @code{WORD}, string overflow
12768: Not checked. The string will be ok, but the count will, of course,
12769: contain only the least significant bits of the length.
12770: 
12771: @item u greater than or equal to the number of bits in a cell (@code{LSHIFT}, @code{RSHIFT}):
12772: @cindex @code{LSHIFT}, large shift counts
12773: @cindex @code{RSHIFT}, large shift counts
12774: Processor-dependent. Typical behaviours are returning 0 and using only
12775: the low bits of the shift count.
12776: 
12777: @item word not defined via @code{CREATE}:
12778: @cindex @code{>BODY} of non-@code{CREATE}d words
12779: @code{>BODY} produces the PFA of the word no matter how it was defined.
12780: 
12781: @cindex @code{DOES>} of non-@code{CREATE}d words
12782: @code{DOES>} changes the execution semantics of the last defined word no
12783: matter how it was defined. E.g., @code{CONSTANT DOES>} is equivalent to
12784: @code{CREATE , DOES>}.
12785: 
12786: @item words improperly used outside @code{<#} and @code{#>}:
12787: Not checked. As usual, you can expect memory faults.
12788: 
12789: @end table
12790: 
12791: 
12792: @c ---------------------------------------------------------------------
12793: @node core-other,  , core-ambcond, The Core Words
12794: @subsection Other system documentation
12795: @c ---------------------------------------------------------------------
12796: @cindex other system documentation, core words
12797: @cindex core words, other system documentation
12798: 
12799: @table @i
12800: @item nonstandard words using @code{PAD}:
12801: @cindex @code{PAD} use by nonstandard words
12802: None.
12803: 
12804: @item operator's terminal facilities available:
12805: @cindex operator's terminal facilities available
12806: After processing the OS's command line, Gforth goes into interactive mode,
12807: and you can give commands to Gforth interactively. The actual facilities
12808: available depend on how you invoke Gforth.
12809: 
12810: @item program data space available:
12811: @cindex program data space available
12812: @cindex data space available
12813: @code{UNUSED .} gives the remaining dictionary space. The total
12814: dictionary space can be specified with the @code{-m} switch
12815: (@pxref{Invoking Gforth}) when Gforth starts up.
12816: 
12817: @item return stack space available:
12818: @cindex return stack space available
12819: You can compute the total return stack space in cells with
12820: @code{s" RETURN-STACK-CELLS" environment? drop .}. You can specify it at
12821: startup time with the @code{-r} switch (@pxref{Invoking Gforth}).
12822: 
12823: @item stack space available:
12824: @cindex stack space available
12825: You can compute the total data stack space in cells with
12826: @code{s" STACK-CELLS" environment? drop .}. You can specify it at
12827: startup time with the @code{-d} switch (@pxref{Invoking Gforth}).
12828: 
12829: @item system dictionary space required, in address units:
12830: @cindex system dictionary space required, in address units
12831: Type @code{here forthstart - .} after startup. At the time of this
12832: writing, this gives 80080 (bytes) on a 32-bit system.
12833: @end table
12834: 
12835: 
12836: @c =====================================================================
12837: @node The optional Block word set, The optional Double Number word set, The Core Words, ANS conformance
12838: @section The optional Block word set
12839: @c =====================================================================
12840: @cindex system documentation, block words
12841: @cindex block words, system documentation
12842: 
12843: @menu
12844: * block-idef::                  Implementation Defined Options
12845: * block-ambcond::               Ambiguous Conditions               
12846: * block-other::                 Other System Documentation                 
12847: @end menu
12848: 
12849: 
12850: @c ---------------------------------------------------------------------
12851: @node block-idef, block-ambcond, The optional Block word set, The optional Block word set
12852: @subsection Implementation Defined Options
12853: @c ---------------------------------------------------------------------
12854: @cindex implementation-defined options, block words
12855: @cindex block words, implementation-defined options
12856: 
12857: @table @i
12858: @item the format for display by @code{LIST}:
12859: @cindex @code{LIST} display format
12860: First the screen number is displayed, then 16 lines of 64 characters,
12861: each line preceded by the line number.
12862: 
12863: @item the length of a line affected by @code{\}:
12864: @cindex length of a line affected by @code{\}
12865: @cindex @code{\}, line length in blocks
12866: 64 characters.
12867: @end table
12868: 
12869: 
12870: @c ---------------------------------------------------------------------
12871: @node block-ambcond, block-other, block-idef, The optional Block word set
12872: @subsection Ambiguous conditions
12873: @c ---------------------------------------------------------------------
12874: @cindex block words, ambiguous conditions
12875: @cindex ambiguous conditions, block words
12876: 
12877: @table @i
12878: @item correct block read was not possible:
12879: @cindex block read not possible
12880: Typically results in a @code{throw} of some OS-derived value (between
12881: -512 and -2048). If the blocks file was just not long enough, blanks are
12882: supplied for the missing portion.
12883: 
12884: @item I/O exception in block transfer:
12885: @cindex I/O exception in block transfer
12886: @cindex block transfer, I/O exception
12887: Typically results in a @code{throw} of some OS-derived value (between
12888: -512 and -2048).
12889: 
12890: @item invalid block number:
12891: @cindex invalid block number
12892: @cindex block number invalid
12893: @code{-35 throw} (Invalid block number)
12894: 
12895: @item a program directly alters the contents of @code{BLK}:
12896: @cindex @code{BLK}, altering @code{BLK}
12897: The input stream is switched to that other block, at the same
12898: position. If the storing to @code{BLK} happens when interpreting
12899: non-block input, the system will get quite confused when the block ends.
12900: 
12901: @item no current block buffer for @code{UPDATE}:
12902: @cindex @code{UPDATE}, no current block buffer
12903: @code{UPDATE} has no effect.
12904: 
12905: @end table
12906: 
12907: @c ---------------------------------------------------------------------
12908: @node block-other,  , block-ambcond, The optional Block word set
12909: @subsection Other system documentation
12910: @c ---------------------------------------------------------------------
12911: @cindex other system documentation, block words
12912: @cindex block words, other system documentation
12913: 
12914: @table @i
12915: @item any restrictions a multiprogramming system places on the use of buffer addresses:
12916: No restrictions (yet).
12917: 
12918: @item the number of blocks available for source and data:
12919: depends on your disk space.
12920: 
12921: @end table
12922: 
12923: 
12924: @c =====================================================================
12925: @node The optional Double Number word set, The optional Exception word set, The optional Block word set, ANS conformance
12926: @section The optional Double Number word set
12927: @c =====================================================================
12928: @cindex system documentation, double words
12929: @cindex double words, system documentation
12930: 
12931: @menu
12932: * double-ambcond::              Ambiguous Conditions              
12933: @end menu
12934: 
12935: 
12936: @c ---------------------------------------------------------------------
12937: @node double-ambcond,  , The optional Double Number word set, The optional Double Number word set
12938: @subsection Ambiguous conditions
12939: @c ---------------------------------------------------------------------
12940: @cindex double words, ambiguous conditions
12941: @cindex ambiguous conditions, double words
12942: 
12943: @table @i
12944: @item @i{d} outside of range of @i{n} in @code{D>S}:
12945: @cindex @code{D>S}, @i{d} out of range of @i{n} 
12946: The least significant cell of @i{d} is produced.
12947: 
12948: @end table
12949: 
12950: 
12951: @c =====================================================================
12952: @node The optional Exception word set, The optional Facility word set, The optional Double Number word set, ANS conformance
12953: @section The optional Exception word set
12954: @c =====================================================================
12955: @cindex system documentation, exception words
12956: @cindex exception words, system documentation
12957: 
12958: @menu
12959: * exception-idef::              Implementation Defined Options              
12960: @end menu
12961: 
12962: 
12963: @c ---------------------------------------------------------------------
12964: @node exception-idef,  , The optional Exception word set, The optional Exception word set
12965: @subsection Implementation Defined Options
12966: @c ---------------------------------------------------------------------
12967: @cindex implementation-defined options, exception words
12968: @cindex exception words, implementation-defined options
12969: 
12970: @table @i
12971: @item @code{THROW}-codes used in the system:
12972: @cindex @code{THROW}-codes used in the system
12973: The codes -256@minus{}-511 are used for reporting signals. The mapping
12974: from OS signal numbers to throw codes is -256@minus{}@i{signal}. The
12975: codes -512@minus{}-2047 are used for OS errors (for file and memory
12976: allocation operations). The mapping from OS error numbers to throw codes
12977: is -512@minus{}@code{errno}. One side effect of this mapping is that
12978: undefined OS errors produce a message with a strange number; e.g.,
12979: @code{-1000 THROW} results in @code{Unknown error 488} on my system.
12980: @end table
12981: 
12982: @c =====================================================================
12983: @node The optional Facility word set, The optional File-Access word set, The optional Exception word set, ANS conformance
12984: @section The optional Facility word set
12985: @c =====================================================================
12986: @cindex system documentation, facility words
12987: @cindex facility words, system documentation
12988: 
12989: @menu
12990: * facility-idef::               Implementation Defined Options               
12991: * facility-ambcond::            Ambiguous Conditions            
12992: @end menu
12993: 
12994: 
12995: @c ---------------------------------------------------------------------
12996: @node facility-idef, facility-ambcond, The optional Facility word set, The optional Facility word set
12997: @subsection Implementation Defined Options
12998: @c ---------------------------------------------------------------------
12999: @cindex implementation-defined options, facility words
13000: @cindex facility words, implementation-defined options
13001: 
13002: @table @i
13003: @item encoding of keyboard events (@code{EKEY}):
13004: @cindex keyboard events, encoding in @code{EKEY}
13005: @cindex @code{EKEY}, encoding of keyboard events
13006: Keys corresponding to ASCII characters are encoded as ASCII characters.
13007: Other keys are encoded with the constants @code{k-left}, @code{k-right},
13008: @code{k-up}, @code{k-down}, @code{k-home}, @code{k-end}, @code{k1},
13009: @code{k2}, @code{k3}, @code{k4}, @code{k5}, @code{k6}, @code{k7},
13010: @code{k8}, @code{k9}, @code{k10}, @code{k11}, @code{k12}.
13011: 
13012: 
13013: @item duration of a system clock tick:
13014: @cindex duration of a system clock tick
13015: @cindex clock tick duration
13016: System dependent. With respect to @code{MS}, the time is specified in
13017: microseconds. How well the OS and the hardware implement this, is
13018: another question.
13019: 
13020: @item repeatability to be expected from the execution of @code{MS}:
13021: @cindex repeatability to be expected from the execution of @code{MS}
13022: @cindex @code{MS}, repeatability to be expected
13023: System dependent. On Unix, a lot depends on load. If the system is
13024: lightly loaded, and the delay is short enough that Gforth does not get
13025: swapped out, the performance should be acceptable. Under MS-DOS and
13026: other single-tasking systems, it should be good.
13027: 
13028: @end table
13029: 
13030: 
13031: @c ---------------------------------------------------------------------
13032: @node facility-ambcond,  , facility-idef, The optional Facility word set
13033: @subsection Ambiguous conditions
13034: @c ---------------------------------------------------------------------
13035: @cindex facility words, ambiguous conditions
13036: @cindex ambiguous conditions, facility words
13037: 
13038: @table @i
13039: @item @code{AT-XY} can't be performed on user output device:
13040: @cindex @code{AT-XY} can't be performed on user output device
13041: Largely terminal dependent. No range checks are done on the arguments.
13042: No errors are reported. You may see some garbage appearing, you may see
13043: simply nothing happen.
13044: 
13045: @end table
13046: 
13047: 
13048: @c =====================================================================
13049: @node The optional File-Access word set, The optional Floating-Point word set, The optional Facility word set, ANS conformance
13050: @section The optional File-Access word set
13051: @c =====================================================================
13052: @cindex system documentation, file words
13053: @cindex file words, system documentation
13054: 
13055: @menu
13056: * file-idef::                   Implementation Defined Options
13057: * file-ambcond::                Ambiguous Conditions                
13058: @end menu
13059: 
13060: @c ---------------------------------------------------------------------
13061: @node file-idef, file-ambcond, The optional File-Access word set, The optional File-Access word set
13062: @subsection Implementation Defined Options
13063: @c ---------------------------------------------------------------------
13064: @cindex implementation-defined options, file words
13065: @cindex file words, implementation-defined options
13066: 
13067: @table @i
13068: @item file access methods used:
13069: @cindex file access methods used
13070: @code{R/O}, @code{R/W} and @code{BIN} work as you would
13071: expect. @code{W/O} translates into the C file opening mode @code{w} (or
13072: @code{wb}): The file is cleared, if it exists, and created, if it does
13073: not (with both @code{open-file} and @code{create-file}).  Under Unix
13074: @code{create-file} creates a file with 666 permissions modified by your
13075: umask.
13076: 
13077: @item file exceptions:
13078: @cindex file exceptions
13079: The file words do not raise exceptions (except, perhaps, memory access
13080: faults when you pass illegal addresses or file-ids).
13081: 
13082: @item file line terminator:
13083: @cindex file line terminator
13084: System-dependent. Gforth uses C's newline character as line
13085: terminator. What the actual character code(s) of this are is
13086: system-dependent.
13087: 
13088: @item file name format:
13089: @cindex file name format
13090: System dependent. Gforth just uses the file name format of your OS.
13091: 
13092: @item information returned by @code{FILE-STATUS}:
13093: @cindex @code{FILE-STATUS}, returned information
13094: @code{FILE-STATUS} returns the most powerful file access mode allowed
13095: for the file: Either @code{R/O}, @code{W/O} or @code{R/W}. If the file
13096: cannot be accessed, @code{R/O BIN} is returned. @code{BIN} is applicable
13097: along with the returned mode.
13098: 
13099: @item input file state after an exception when including source:
13100: @cindex exception when including source
13101: All files that are left via the exception are closed.
13102: 
13103: @item @i{ior} values and meaning:
13104: @cindex @i{ior} values and meaning
13105: @cindex @i{wior} values and meaning
13106: The @i{ior}s returned by the file and memory allocation words are
13107: intended as throw codes. They typically are in the range
13108: -512@minus{}-2047 of OS errors.  The mapping from OS error numbers to
13109: @i{ior}s is -512@minus{}@i{errno}.
13110: 
13111: @item maximum depth of file input nesting:
13112: @cindex maximum depth of file input nesting
13113: @cindex file input nesting, maximum depth
13114: limited by the amount of return stack, locals/TIB stack, and the number
13115: of open files available. This should not give you troubles.
13116: 
13117: @item maximum size of input line:
13118: @cindex maximum size of input line
13119: @cindex input line size, maximum
13120: @code{/line}. Currently 255.
13121: 
13122: @item methods of mapping block ranges to files:
13123: @cindex mapping block ranges to files
13124: @cindex files containing blocks
13125: @cindex blocks in files
13126: By default, blocks are accessed in the file @file{blocks.fb} in the
13127: current working directory. The file can be switched with @code{USE}.
13128: 
13129: @item number of string buffers provided by @code{S"}:
13130: @cindex @code{S"}, number of string buffers
13131: 1
13132: 
13133: @item size of string buffer used by @code{S"}:
13134: @cindex @code{S"}, size of string buffer
13135: @code{/line}. currently 255.
13136: 
13137: @end table
13138: 
13139: @c ---------------------------------------------------------------------
13140: @node file-ambcond,  , file-idef, The optional File-Access word set
13141: @subsection Ambiguous conditions
13142: @c ---------------------------------------------------------------------
13143: @cindex file words, ambiguous conditions
13144: @cindex ambiguous conditions, file words
13145: 
13146: @table @i
13147: @item attempting to position a file outside its boundaries:
13148: @cindex @code{REPOSITION-FILE}, outside the file's boundaries
13149: @code{REPOSITION-FILE} is performed as usual: Afterwards,
13150: @code{FILE-POSITION} returns the value given to @code{REPOSITION-FILE}.
13151: 
13152: @item attempting to read from file positions not yet written:
13153: @cindex reading from file positions not yet written
13154: End-of-file, i.e., zero characters are read and no error is reported.
13155: 
13156: @item @i{file-id} is invalid (@code{INCLUDE-FILE}):
13157: @cindex @code{INCLUDE-FILE}, @i{file-id} is invalid 
13158: An appropriate exception may be thrown, but a memory fault or other
13159: problem is more probable.
13160: 
13161: @item I/O exception reading or closing @i{file-id} (@code{INCLUDE-FILE}, @code{INCLUDED}):
13162: @cindex @code{INCLUDE-FILE}, I/O exception reading or closing @i{file-id}
13163: @cindex @code{INCLUDED}, I/O exception reading or closing @i{file-id}
13164: The @i{ior} produced by the operation, that discovered the problem, is
13165: thrown.
13166: 
13167: @item named file cannot be opened (@code{INCLUDED}):
13168: @cindex @code{INCLUDED}, named file cannot be opened
13169: The @i{ior} produced by @code{open-file} is thrown.
13170: 
13171: @item requesting an unmapped block number:
13172: @cindex unmapped block numbers
13173: There are no unmapped legal block numbers. On some operating systems,
13174: writing a block with a large number may overflow the file system and
13175: have an error message as consequence.
13176: 
13177: @item using @code{source-id} when @code{blk} is non-zero:
13178: @cindex @code{SOURCE-ID}, behaviour when @code{BLK} is non-zero
13179: @code{source-id} performs its function. Typically it will give the id of
13180: the source which loaded the block. (Better ideas?)
13181: 
13182: @end table
13183: 
13184: 
13185: @c =====================================================================
13186: @node  The optional Floating-Point word set, The optional Locals word set, The optional File-Access word set, ANS conformance
13187: @section The optional Floating-Point word set
13188: @c =====================================================================
13189: @cindex system documentation, floating-point words
13190: @cindex floating-point words, system documentation
13191: 
13192: @menu
13193: * floating-idef::               Implementation Defined Options
13194: * floating-ambcond::            Ambiguous Conditions            
13195: @end menu
13196: 
13197: 
13198: @c ---------------------------------------------------------------------
13199: @node floating-idef, floating-ambcond, The optional Floating-Point word set, The optional Floating-Point word set
13200: @subsection Implementation Defined Options
13201: @c ---------------------------------------------------------------------
13202: @cindex implementation-defined options, floating-point words
13203: @cindex floating-point words, implementation-defined options
13204: 
13205: @table @i
13206: @item format and range of floating point numbers:
13207: @cindex format and range of floating point numbers
13208: @cindex floating point numbers, format and range
13209: System-dependent; the @code{double} type of C.
13210: 
13211: @item results of @code{REPRESENT} when @i{float} is out of range:
13212: @cindex  @code{REPRESENT}, results when @i{float} is out of range
13213: System dependent; @code{REPRESENT} is implemented using the C library
13214: function @code{ecvt()} and inherits its behaviour in this respect.
13215: 
13216: @item rounding or truncation of floating-point numbers:
13217: @cindex rounding of floating-point numbers
13218: @cindex truncation of floating-point numbers
13219: @cindex floating-point numbers, rounding or truncation
13220: System dependent; the rounding behaviour is inherited from the hosting C
13221: compiler. IEEE-FP-based (i.e., most) systems by default round to
13222: nearest, and break ties by rounding to even (i.e., such that the last
13223: bit of the mantissa is 0).
13224: 
13225: @item size of floating-point stack:
13226: @cindex floating-point stack size
13227: @code{s" FLOATING-STACK" environment? drop .} gives the total size of
13228: the floating-point stack (in floats). You can specify this on startup
13229: with the command-line option @code{-f} (@pxref{Invoking Gforth}).
13230: 
13231: @item width of floating-point stack:
13232: @cindex floating-point stack width 
13233: @code{1 floats}.
13234: 
13235: @end table
13236: 
13237: 
13238: @c ---------------------------------------------------------------------
13239: @node floating-ambcond,  , floating-idef, The optional Floating-Point word set
13240: @subsection Ambiguous conditions
13241: @c ---------------------------------------------------------------------
13242: @cindex floating-point words, ambiguous conditions
13243: @cindex ambiguous conditions, floating-point words
13244: 
13245: @table @i
13246: @item @code{df@@} or @code{df!} used with an address that is not double-float  aligned:
13247: @cindex @code{df@@} or @code{df!} used with an address that is not double-float  aligned
13248: System-dependent. Typically results in a @code{-23 THROW} like other
13249: alignment violations.
13250: 
13251: @item @code{f@@} or @code{f!} used with an address that is not float  aligned:
13252: @cindex @code{f@@} used with an address that is not float aligned
13253: @cindex @code{f!} used with an address that is not float aligned
13254: System-dependent. Typically results in a @code{-23 THROW} like other
13255: alignment violations.
13256: 
13257: @item floating-point result out of range:
13258: @cindex floating-point result out of range
13259: System-dependent. Can result in a @code{-43 throw} (floating point
13260: overflow), @code{-54 throw} (floating point underflow), @code{-41 throw}
13261: (floating point inexact result), @code{-55 THROW} (Floating-point
13262: unidentified fault), or can produce a special value representing, e.g.,
13263: Infinity.
13264: 
13265: @item @code{sf@@} or @code{sf!} used with an address that is not single-float  aligned:
13266: @cindex @code{sf@@} or @code{sf!} used with an address that is not single-float  aligned
13267: System-dependent. Typically results in an alignment fault like other
13268: alignment violations.
13269: 
13270: @item @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.}):
13271: @cindex @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.})
13272: The floating-point number is converted into decimal nonetheless.
13273: 
13274: @item Both arguments are equal to zero (@code{FATAN2}):
13275: @cindex @code{FATAN2}, both arguments are equal to zero
13276: System-dependent. @code{FATAN2} is implemented using the C library
13277: function @code{atan2()}.
13278: 
13279: @item Using @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero:
13280: @cindex @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero
13281: System-dependent. Anyway, typically the cos of @i{r1} will not be zero
13282: because of small errors and the tan will be a very large (or very small)
13283: but finite number.
13284: 
13285: @item @i{d} cannot be presented precisely as a float in @code{D>F}:
13286: @cindex @code{D>F}, @i{d} cannot be presented precisely as a float
13287: The result is rounded to the nearest float.
13288: 
13289: @item dividing by zero:
13290: @cindex dividing by zero, floating-point
13291: @cindex floating-point dividing by zero
13292: @cindex floating-point unidentified fault, FP divide-by-zero
13293: Platform-dependent; can produce an Infinity, NaN, @code{-42 throw}
13294: (floating point divide by zero) or @code{-55 throw} (Floating-point
13295: unidentified fault).
13296: 
13297: @item exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@}):
13298: @cindex exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@})
13299: System dependent. On IEEE-FP based systems the number is converted into
13300: an infinity.
13301: 
13302: @item @i{float}<1 (@code{FACOSH}):
13303: @cindex @code{FACOSH}, @i{float}<1
13304: @cindex floating-point unidentified fault, @code{FACOSH}
13305: Platform-dependent; on IEEE-FP systems typically produces a NaN.
13306: 
13307: @item @i{float}=<-1 (@code{FLNP1}):
13308: @cindex @code{FLNP1}, @i{float}=<-1
13309: @cindex floating-point unidentified fault, @code{FLNP1}
13310: Platform-dependent; on IEEE-FP systems typically produces a NaN (or a
13311: negative infinity for @i{float}=-1).
13312: 
13313: @item @i{float}=<0 (@code{FLN}, @code{FLOG}):
13314: @cindex @code{FLN}, @i{float}=<0
13315: @cindex @code{FLOG}, @i{float}=<0
13316: @cindex floating-point unidentified fault, @code{FLN} or @code{FLOG}
13317: Platform-dependent; on IEEE-FP systems typically produces a NaN (or a
13318: negative infinity for @i{float}=0).
13319: 
13320: @item @i{float}<0 (@code{FASINH}, @code{FSQRT}):
13321: @cindex @code{FASINH}, @i{float}<0
13322: @cindex @code{FSQRT}, @i{float}<0
13323: @cindex floating-point unidentified fault, @code{FASINH} or @code{FSQRT}
13324: Platform-dependent; for @code{fsqrt} this typically gives a NaN, for
13325: @code{fasinh} some platforms produce a NaN, others a number (bug in the
13326: C library?).
13327: 
13328: @item |@i{float}|>1 (@code{FACOS}, @code{FASIN}, @code{FATANH}):
13329: @cindex @code{FACOS}, |@i{float}|>1
13330: @cindex @code{FASIN}, |@i{float}|>1
13331: @cindex @code{FATANH}, |@i{float}|>1
13332: @cindex floating-point unidentified fault, @code{FACOS}, @code{FASIN} or @code{FATANH}
13333: Platform-dependent; IEEE-FP systems typically produce a NaN.
13334: 
13335: @item integer part of float cannot be represented by @i{d} in @code{F>D}:
13336: @cindex @code{F>D}, integer part of float cannot be represented by @i{d}
13337: @cindex floating-point unidentified fault, @code{F>D}
13338: Platform-dependent; typically, some double number is produced and no
13339: error is reported.
13340: 
13341: @item string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.}):
13342: @cindex string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.})
13343: @code{Precision} characters of the numeric output area are used.  If
13344: @code{precision} is too high, these words will smash the data or code
13345: close to @code{here}.
13346: @end table
13347: 
13348: @c =====================================================================
13349: @node  The optional Locals word set, The optional Memory-Allocation word set, The optional Floating-Point word set, ANS conformance
13350: @section The optional Locals word set
13351: @c =====================================================================
13352: @cindex system documentation, locals words
13353: @cindex locals words, system documentation
13354: 
13355: @menu
13356: * locals-idef::                 Implementation Defined Options                 
13357: * locals-ambcond::              Ambiguous Conditions              
13358: @end menu
13359: 
13360: 
13361: @c ---------------------------------------------------------------------
13362: @node locals-idef, locals-ambcond, The optional Locals word set, The optional Locals word set
13363: @subsection Implementation Defined Options
13364: @c ---------------------------------------------------------------------
13365: @cindex implementation-defined options, locals words
13366: @cindex locals words, implementation-defined options
13367: 
13368: @table @i
13369: @item maximum number of locals in a definition:
13370: @cindex maximum number of locals in a definition
13371: @cindex locals, maximum number in a definition
13372: @code{s" #locals" environment? drop .}. Currently 15. This is a lower
13373: bound, e.g., on a 32-bit machine there can be 41 locals of up to 8
13374: characters. The number of locals in a definition is bounded by the size
13375: of locals-buffer, which contains the names of the locals.
13376: 
13377: @end table
13378: 
13379: 
13380: @c ---------------------------------------------------------------------
13381: @node locals-ambcond,  , locals-idef, The optional Locals word set
13382: @subsection Ambiguous conditions
13383: @c ---------------------------------------------------------------------
13384: @cindex locals words, ambiguous conditions
13385: @cindex ambiguous conditions, locals words
13386: 
13387: @table @i
13388: @item executing a named local in interpretation state:
13389: @cindex local in interpretation state
13390: @cindex Interpreting a compile-only word, for a local
13391: Locals have no interpretation semantics. If you try to perform the
13392: interpretation semantics, you will get a @code{-14 throw} somewhere
13393: (Interpreting a compile-only word). If you perform the compilation
13394: semantics, the locals access will be compiled (irrespective of state).
13395: 
13396: @item @i{name} not defined by @code{VALUE} or @code{(LOCAL)} (@code{TO}):
13397: @cindex name not defined by @code{VALUE} or @code{(LOCAL)} used by @code{TO}
13398: @cindex @code{TO} on non-@code{VALUE}s and non-locals
13399: @cindex Invalid name argument, @code{TO}
13400: @code{-32 throw} (Invalid name argument)
13401: 
13402: @end table
13403: 
13404: 
13405: @c =====================================================================
13406: @node  The optional Memory-Allocation word set, The optional Programming-Tools word set, The optional Locals word set, ANS conformance
13407: @section The optional Memory-Allocation word set
13408: @c =====================================================================
13409: @cindex system documentation, memory-allocation words
13410: @cindex memory-allocation words, system documentation
13411: 
13412: @menu
13413: * memory-idef::                 Implementation Defined Options                 
13414: @end menu
13415: 
13416: 
13417: @c ---------------------------------------------------------------------
13418: @node memory-idef,  , The optional Memory-Allocation word set, The optional Memory-Allocation word set
13419: @subsection Implementation Defined Options
13420: @c ---------------------------------------------------------------------
13421: @cindex implementation-defined options, memory-allocation words
13422: @cindex memory-allocation words, implementation-defined options
13423: 
13424: @table @i
13425: @item values and meaning of @i{ior}:
13426: @cindex  @i{ior} values and meaning
13427: The @i{ior}s returned by the file and memory allocation words are
13428: intended as throw codes. They typically are in the range
13429: -512@minus{}-2047 of OS errors.  The mapping from OS error numbers to
13430: @i{ior}s is -512@minus{}@i{errno}.
13431: 
13432: @end table
13433: 
13434: @c =====================================================================
13435: @node  The optional Programming-Tools word set, The optional Search-Order word set, The optional Memory-Allocation word set, ANS conformance
13436: @section The optional Programming-Tools word set
13437: @c =====================================================================
13438: @cindex system documentation, programming-tools words
13439: @cindex programming-tools words, system documentation
13440: 
13441: @menu
13442: * programming-idef::            Implementation Defined Options            
13443: * programming-ambcond::         Ambiguous Conditions         
13444: @end menu
13445: 
13446: 
13447: @c ---------------------------------------------------------------------
13448: @node programming-idef, programming-ambcond, The optional Programming-Tools word set, The optional Programming-Tools word set
13449: @subsection Implementation Defined Options
13450: @c ---------------------------------------------------------------------
13451: @cindex implementation-defined options, programming-tools words
13452: @cindex programming-tools words, implementation-defined options
13453: 
13454: @table @i
13455: @item ending sequence for input following @code{;CODE} and @code{CODE}:
13456: @cindex @code{;CODE} ending sequence
13457: @cindex @code{CODE} ending sequence
13458: @code{END-CODE}
13459: 
13460: @item manner of processing input following @code{;CODE} and @code{CODE}:
13461: @cindex @code{;CODE}, processing input
13462: @cindex @code{CODE}, processing input
13463: The @code{ASSEMBLER} vocabulary is pushed on the search order stack, and
13464: the input is processed by the text interpreter, (starting) in interpret
13465: state.
13466: 
13467: @item search order capability for @code{EDITOR} and @code{ASSEMBLER}:
13468: @cindex @code{ASSEMBLER}, search order capability
13469: The ANS Forth search order word set.
13470: 
13471: @item source and format of display by @code{SEE}:
13472: @cindex @code{SEE}, source and format of output
13473: The source for @code{see} is the executable code used by the inner
13474: interpreter.  The current @code{see} tries to output Forth source code
13475: (and on some platforms, assembly code for primitives) as well as
13476: possible.
13477: 
13478: @end table
13479: 
13480: @c ---------------------------------------------------------------------
13481: @node programming-ambcond,  , programming-idef, The optional Programming-Tools word set
13482: @subsection Ambiguous conditions
13483: @c ---------------------------------------------------------------------
13484: @cindex programming-tools words, ambiguous conditions
13485: @cindex ambiguous conditions, programming-tools words
13486: 
13487: @table @i
13488: 
13489: @item deleting the compilation word list (@code{FORGET}):
13490: @cindex @code{FORGET}, deleting the compilation word list
13491: Not implemented (yet).
13492: 
13493: @item fewer than @i{u}+1 items on the control-flow stack (@code{CS-PICK}, @code{CS-ROLL}):
13494: @cindex @code{CS-PICK}, fewer than @i{u}+1 items on the control flow-stack
13495: @cindex @code{CS-ROLL}, fewer than @i{u}+1 items on the control flow-stack
13496: @cindex control-flow stack underflow
13497: This typically results in an @code{abort"} with a descriptive error
13498: message (may change into a @code{-22 throw} (Control structure mismatch)
13499: in the future). You may also get a memory access error. If you are
13500: unlucky, this ambiguous condition is not caught.
13501: 
13502: @item @i{name} can't be found (@code{FORGET}):
13503: @cindex @code{FORGET}, @i{name} can't be found
13504: Not implemented (yet).
13505: 
13506: @item @i{name} not defined via @code{CREATE}:
13507: @cindex @code{;CODE}, @i{name} not defined via @code{CREATE}
13508: @code{;CODE} behaves like @code{DOES>} in this respect, i.e., it changes
13509: the execution semantics of the last defined word no matter how it was
13510: defined.
13511: 
13512: @item @code{POSTPONE} applied to @code{[IF]}:
13513: @cindex @code{POSTPONE} applied to @code{[IF]}
13514: @cindex @code{[IF]} and @code{POSTPONE}
13515: After defining @code{: X POSTPONE [IF] ; IMMEDIATE}. @code{X} is
13516: equivalent to @code{[IF]}.
13517: 
13518: @item reaching the end of the input source before matching @code{[ELSE]} or @code{[THEN]}:
13519: @cindex @code{[IF]}, end of the input source before matching @code{[ELSE]} or @code{[THEN]}
13520: Continue in the same state of conditional compilation in the next outer
13521: input source. Currently there is no warning to the user about this.
13522: 
13523: @item removing a needed definition (@code{FORGET}):
13524: @cindex @code{FORGET}, removing a needed definition
13525: Not implemented (yet).
13526: 
13527: @end table
13528: 
13529: 
13530: @c =====================================================================
13531: @node  The optional Search-Order word set,  , The optional Programming-Tools word set, ANS conformance
13532: @section The optional Search-Order word set
13533: @c =====================================================================
13534: @cindex system documentation, search-order words
13535: @cindex search-order words, system documentation
13536: 
13537: @menu
13538: * search-idef::                 Implementation Defined Options                 
13539: * search-ambcond::              Ambiguous Conditions              
13540: @end menu
13541: 
13542: 
13543: @c ---------------------------------------------------------------------
13544: @node search-idef, search-ambcond, The optional Search-Order word set, The optional Search-Order word set
13545: @subsection Implementation Defined Options
13546: @c ---------------------------------------------------------------------
13547: @cindex implementation-defined options, search-order words
13548: @cindex search-order words, implementation-defined options
13549: 
13550: @table @i
13551: @item maximum number of word lists in search order:
13552: @cindex maximum number of word lists in search order
13553: @cindex search order, maximum depth
13554: @code{s" wordlists" environment? drop .}. Currently 16.
13555: 
13556: @item minimum search order:
13557: @cindex minimum search order
13558: @cindex search order, minimum
13559: @code{root root}.
13560: 
13561: @end table
13562: 
13563: @c ---------------------------------------------------------------------
13564: @node search-ambcond,  , search-idef, The optional Search-Order word set
13565: @subsection Ambiguous conditions
13566: @c ---------------------------------------------------------------------
13567: @cindex search-order words, ambiguous conditions
13568: @cindex ambiguous conditions, search-order words
13569: 
13570: @table @i
13571: @item changing the compilation word list (during compilation):
13572: @cindex changing the compilation word list (during compilation)
13573: @cindex compilation word list, change before definition ends
13574: The word is entered into the word list that was the compilation word list
13575: at the start of the definition. Any changes to the name field (e.g.,
13576: @code{immediate}) or the code field (e.g., when executing @code{DOES>})
13577: are applied to the latest defined word (as reported by @code{last} or
13578: @code{lastxt}), if possible, irrespective of the compilation word list.
13579: 
13580: @item search order empty (@code{previous}):
13581: @cindex @code{previous}, search order empty
13582: @cindex vocstack empty, @code{previous}
13583: @code{abort" Vocstack empty"}.
13584: 
13585: @item too many word lists in search order (@code{also}):
13586: @cindex @code{also}, too many word lists in search order
13587: @cindex vocstack full, @code{also}
13588: @code{abort" Vocstack full"}.
13589: 
13590: @end table
13591: 
13592: @c ***************************************************************
13593: @node Standard vs Extensions, Model, ANS conformance, Top
13594: @chapter Should I use Gforth extensions?
13595: @cindex Gforth extensions
13596: 
13597: As you read through the rest of this manual, you will see documentation
13598: for @i{Standard} words, and documentation for some appealing Gforth
13599: @i{extensions}. You might ask yourself the question: @i{``Should I
13600: restrict myself to the standard, or should I use the extensions?''}
13601: 
13602: The answer depends on the goals you have for the program you are working
13603: on:
13604: 
13605: @itemize @bullet
13606: 
13607: @item Is it just for yourself or do you want to share it with others?
13608: 
13609: @item
13610: If you want to share it, do the others all use Gforth?
13611: 
13612: @item
13613: If it is just for yourself, do you want to restrict yourself to Gforth?
13614: 
13615: @end itemize
13616: 
13617: If restricting the program to Gforth is ok, then there is no reason not
13618: to use extensions.  It is still a good idea to keep to the standard
13619: where it is easy, in case you want to reuse these parts in another
13620: program that you want to be portable.
13621: 
13622: If you want to be able to port the program to other Forth systems, there
13623: are the following points to consider:
13624: 
13625: @itemize @bullet
13626: 
13627: @item
13628: Most Forth systems that are being maintained support the ANS Forth
13629: standard.  So if your program complies with the standard, it will be
13630: portable among many systems.
13631: 
13632: @item
13633: A number of the Gforth extensions can be implemented in ANS Forth using
13634: public-domain files provided in the @file{compat/} directory. These are
13635: mentioned in the text in passing.  There is no reason not to use these
13636: extensions, your program will still be ANS Forth compliant; just include
13637: the appropriate compat files with your program.
13638: 
13639: @item
13640: The tool @file{ans-report.fs} (@pxref{ANS Report}) makes it easy to
13641: analyse your program and determine what non-Standard words it relies
13642: upon.  However, it does not check whether you use standard words in a
13643: non-standard way.
13644: 
13645: @item
13646: Some techniques are not standardized by ANS Forth, and are hard or
13647: impossible to implement in a standard way, but can be implemented in
13648: most Forth systems easily, and usually in similar ways (e.g., accessing
13649: word headers).  Forth has a rich historical precedent for programmers
13650: taking advantage of implementation-dependent features of their tools
13651: (for example, relying on a knowledge of the dictionary
13652: structure). Sometimes these techniques are necessary to extract every
13653: last bit of performance from the hardware, sometimes they are just a
13654: programming shorthand.
13655: 
13656: @item
13657: Does using a Gforth extension save more work than the porting this part
13658: to other Forth systems (if any) will cost?
13659: 
13660: @item
13661: Is the additional functionality worth the reduction in portability and
13662: the additional porting problems?
13663: 
13664: @end itemize
13665: 
13666: In order to perform these consideratios, you need to know what's
13667: standard and what's not.  This manual generally states if something is
13668: non-standard, but the authoritative source is the
13669: @uref{http://www.taygeta.com/forth/dpans.html,standard document}.
13670: Appendix A of the Standard (@var{Rationale}) provides a valuable insight
13671: into the thought processes of the technical committee.
13672: 
13673: Note also that portability between Forth systems is not the only
13674: portability issue; there is also the issue of portability between
13675: different platforms (processor/OS combinations).
13676: 
13677: @c ***************************************************************
13678: @node Model, Integrating Gforth, Standard vs Extensions, Top
13679: @chapter Model
13680: 
13681: This chapter has yet to be written. It will contain information, on
13682: which internal structures you can rely.
13683: 
13684: @c ***************************************************************
13685: @node Integrating Gforth, Emacs and Gforth, Model, Top
13686: @chapter Integrating Gforth into C programs
13687: 
13688: This is not yet implemented.
13689: 
13690: Several people like to use Forth as scripting language for applications
13691: that are otherwise written in C, C++, or some other language.
13692: 
13693: The Forth system ATLAST provides facilities for embedding it into
13694: applications; unfortunately it has several disadvantages: most
13695: importantly, it is not based on ANS Forth, and it is apparently dead
13696: (i.e., not developed further and not supported). The facilities
13697: provided by Gforth in this area are inspired by ATLAST's facilities, so
13698: making the switch should not be hard.
13699: 
13700: We also tried to design the interface such that it can easily be
13701: implemented by other Forth systems, so that we may one day arrive at a
13702: standardized interface. Such a standard interface would allow you to
13703: replace the Forth system without having to rewrite C code.
13704: 
13705: You embed the Gforth interpreter by linking with the library
13706: @code{libgforth.a} (give the compiler the option @code{-lgforth}).  All
13707: global symbols in this library that belong to the interface, have the
13708: prefix @code{forth_}. (Global symbols that are used internally have the
13709: prefix @code{gforth_}).
13710: 
13711: You can include the declarations of Forth types and the functions and
13712: variables of the interface with @code{#include <forth.h>}.
13713: 
13714: Types.
13715: 
13716: Variables.
13717: 
13718: Data and FP Stack pointer. Area sizes.
13719: 
13720: functions.
13721: 
13722: forth_init(imagefile)
13723: forth_evaluate(string) exceptions?
13724: forth_goto(address) (or forth_execute(xt)?)
13725: forth_continue() (a corountining mechanism)
13726: 
13727: Adding primitives.
13728: 
13729: No checking.
13730: 
13731: Signals?
13732: 
13733: Accessing the Stacks
13734: 
13735: @c ******************************************************************
13736: @node Emacs and Gforth, Image Files, Integrating Gforth, Top
13737: @chapter Emacs and Gforth
13738: @cindex Emacs and Gforth
13739: 
13740: @cindex @file{gforth.el}
13741: @cindex @file{forth.el}
13742: @cindex Rydqvist, Goran
13743: @cindex comment editing commands
13744: @cindex @code{\}, editing with Emacs
13745: @cindex debug tracer editing commands
13746: @cindex @code{~~}, removal with Emacs
13747: @cindex Forth mode in Emacs
13748: Gforth comes with @file{gforth.el}, an improved version of
13749: @file{forth.el} by Goran Rydqvist (included in the TILE package). The
13750: improvements are:
13751: 
13752: @itemize @bullet
13753: @item
13754: A better (but still not perfect) handling of indentation.
13755: @item
13756: Comment paragraph filling (@kbd{M-q})
13757: @item
13758: Commenting (@kbd{C-x \}) and uncommenting (@kbd{C-u C-x \}) of regions
13759: @item
13760: Removal of debugging tracers (@kbd{C-x ~}, @pxref{Debugging}).
13761: @item
13762: Support of the @code{info-lookup} feature for looking up the
13763: documentation of a word.
13764: @end itemize
13765: 
13766: I left the stuff I do not use alone, even though some of it only makes
13767: sense for TILE. To get a description of these features, enter Forth mode
13768: and type @kbd{C-h m}.
13769: 
13770: @cindex source location of error or debugging output in Emacs
13771: @cindex error output, finding the source location in Emacs
13772: @cindex debugging output, finding the source location in Emacs
13773: In addition, Gforth supports Emacs quite well: The source code locations
13774: given in error messages, debugging output (from @code{~~}) and failed
13775: assertion messages are in the right format for Emacs' compilation mode
13776: (@pxref{Compilation, , Running Compilations under Emacs, emacs, Emacs
13777: Manual}) so the source location corresponding to an error or other
13778: message is only a few keystrokes away (@kbd{C-x `} for the next error,
13779: @kbd{C-c C-c} for the error under the cursor).
13780: 
13781: @cindex @file{TAGS} file
13782: @cindex @file{etags.fs}
13783: @cindex viewing the source of a word in Emacs
13784: @cindex @code{require}, placement in files
13785: @cindex @code{include}, placement in files
13786: Also, if you @code{require} @file{etags.fs}, a new @file{TAGS} file will
13787: be produced (@pxref{Tags, , Tags Tables, emacs, Emacs Manual}) that
13788: contains the definitions of all words defined afterwards. You can then
13789: find the source for a word using @kbd{M-.}. Note that emacs can use
13790: several tags files at the same time (e.g., one for the Gforth sources
13791: and one for your program, @pxref{Select Tags Table,,Selecting a Tags
13792: Table,emacs, Emacs Manual}). The TAGS file for the preloaded words is
13793: @file{$(datadir)/gforth/$(VERSION)/TAGS} (e.g.,
13794: @file{/usr/local/share/gforth/0.2.0/TAGS}).  To get the best behaviour
13795: with @file{etags.fs}, you should avoid putting definitions both before
13796: and after @code{require} etc., otherwise you will see the same file
13797: visited several times by commands like @code{tags-search}.
13798: 
13799: @cindex viewing the documentation of a word in Emacs
13800: @cindex context-sensitive help
13801: Moreover, for words documented in this manual, you can look up the
13802: glossary entry quickly by using @kbd{C-h TAB}
13803: (@code{info-lookup-symbol}, @pxref{Documentation, ,Documentation
13804: Commands, emacs, Emacs Manual}).  This feature requires Emacs 20.3 or
13805: later and does not work for words containing @code{:}.
13806: 
13807: 
13808: @cindex @file{.emacs}
13809: To get all these benefits, add the following lines to your @file{.emacs}
13810: file:
13811: 
13812: @example
13813: (autoload 'forth-mode "gforth.el")
13814: (setq auto-mode-alist (cons '("\\.fs\\'" . forth-mode) auto-mode-alist))
13815: @end example
13816: 
13817: @c ******************************************************************
13818: @node Image Files, Engine, Emacs and Gforth, Top
13819: @chapter Image Files
13820: @cindex image file
13821: @cindex @file{.fi} files
13822: @cindex precompiled Forth code
13823: @cindex dictionary in persistent form
13824: @cindex persistent form of dictionary
13825: 
13826: An image file is a file containing an image of the Forth dictionary,
13827: i.e., compiled Forth code and data residing in the dictionary.  By
13828: convention, we use the extension @code{.fi} for image files.
13829: 
13830: @menu
13831: * Image Licensing Issues::      Distribution terms for images.
13832: * Image File Background::       Why have image files?
13833: * Non-Relocatable Image Files::  don't always work.
13834: * Data-Relocatable Image Files::  are better.
13835: * Fully Relocatable Image Files::  better yet.
13836: * Stack and Dictionary Sizes::  Setting the default sizes for an image.
13837: * Running Image Files::         @code{gforth -i @i{file}} or @i{file}.
13838: * Modifying the Startup Sequence::  and turnkey applications.
13839: @end menu
13840: 
13841: @node Image Licensing Issues, Image File Background, Image Files, Image Files
13842: @section Image Licensing Issues
13843: @cindex license for images
13844: @cindex image license
13845: 
13846: An image created with @code{gforthmi} (@pxref{gforthmi}) or
13847: @code{savesystem} (@pxref{Non-Relocatable Image Files}) includes the
13848: original image; i.e., according to copyright law it is a derived work of
13849: the original image.
13850: 
13851: Since Gforth is distributed under the GNU GPL, the newly created image
13852: falls under the GNU GPL, too. In particular, this means that if you
13853: distribute the image, you have to make all of the sources for the image
13854: available, including those you wrote.  For details see @ref{License, ,
13855: GNU General Public License (Section 3)}.
13856: 
13857: If you create an image with @code{cross} (@pxref{cross.fs}), the image
13858: contains only code compiled from the sources you gave it; if none of
13859: these sources is under the GPL, the terms discussed above do not apply
13860: to the image. However, if your image needs an engine (a gforth binary)
13861: that is under the GPL, you should make sure that you distribute both in
13862: a way that is at most a @emph{mere aggregation}, if you don't want the
13863: terms of the GPL to apply to the image.
13864: 
13865: @node Image File Background, Non-Relocatable Image Files, Image Licensing Issues, Image Files
13866: @section Image File Background
13867: @cindex image file background
13868: 
13869: Gforth consists not only of primitives (in the engine), but also of
13870: definitions written in Forth. Since the Forth compiler itself belongs to
13871: those definitions, it is not possible to start the system with the
13872: engine and the Forth source alone. Therefore we provide the Forth
13873: code as an image file in nearly executable form. When Gforth starts up,
13874: a C routine loads the image file into memory, optionally relocates the
13875: addresses, then sets up the memory (stacks etc.) according to
13876: information in the image file, and (finally) starts executing Forth
13877: code.
13878: 
13879: The image file variants represent different compromises between the
13880: goals of making it easy to generate image files and making them
13881: portable.
13882: 
13883: @cindex relocation at run-time
13884: Win32Forth 3.4 and Mitch Bradley's @code{cforth} use relocation at
13885: run-time. This avoids many of the complications discussed below (image
13886: files are data relocatable without further ado), but costs performance
13887: (one addition per memory access).
13888: 
13889: @cindex relocation at load-time
13890: By contrast, the Gforth loader performs relocation at image load time. The
13891: loader also has to replace tokens that represent primitive calls with the
13892: appropriate code-field addresses (or code addresses in the case of
13893: direct threading).
13894: 
13895: There are three kinds of image files, with different degrees of
13896: relocatability: non-relocatable, data-relocatable, and fully relocatable
13897: image files.
13898: 
13899: @cindex image file loader
13900: @cindex relocating loader
13901: @cindex loader for image files
13902: These image file variants have several restrictions in common; they are
13903: caused by the design of the image file loader:
13904: 
13905: @itemize @bullet
13906: @item
13907: There is only one segment; in particular, this means, that an image file
13908: cannot represent @code{ALLOCATE}d memory chunks (and pointers to
13909: them). The contents of the stacks are not represented, either.
13910: 
13911: @item
13912: The only kinds of relocation supported are: adding the same offset to
13913: all cells that represent data addresses; and replacing special tokens
13914: with code addresses or with pieces of machine code.
13915: 
13916: If any complex computations involving addresses are performed, the
13917: results cannot be represented in the image file. Several applications that
13918: use such computations come to mind:
13919: @itemize @minus
13920: @item
13921: Hashing addresses (or data structures which contain addresses) for table
13922: lookup. If you use Gforth's @code{table}s or @code{wordlist}s for this
13923: purpose, you will have no problem, because the hash tables are
13924: recomputed automatically when the system is started. If you use your own
13925: hash tables, you will have to do something similar.
13926: 
13927: @item
13928: There's a cute implementation of doubly-linked lists that uses
13929: @code{XOR}ed addresses. You could represent such lists as singly-linked
13930: in the image file, and restore the doubly-linked representation on
13931: startup.@footnote{In my opinion, though, you should think thrice before
13932: using a doubly-linked list (whatever implementation).}
13933: 
13934: @item
13935: The code addresses of run-time routines like @code{docol:} cannot be
13936: represented in the image file (because their tokens would be replaced by
13937: machine code in direct threaded implementations). As a workaround,
13938: compute these addresses at run-time with @code{>code-address} from the
13939: executions tokens of appropriate words (see the definitions of
13940: @code{docol:} and friends in @file{kernel/getdoers.fs}).
13941: 
13942: @item
13943: On many architectures addresses are represented in machine code in some
13944: shifted or mangled form. You cannot put @code{CODE} words that contain
13945: absolute addresses in this form in a relocatable image file. Workarounds
13946: are representing the address in some relative form (e.g., relative to
13947: the CFA, which is present in some register), or loading the address from
13948: a place where it is stored in a non-mangled form.
13949: @end itemize
13950: @end itemize
13951: 
13952: @node  Non-Relocatable Image Files, Data-Relocatable Image Files, Image File Background, Image Files
13953: @section Non-Relocatable Image Files
13954: @cindex non-relocatable image files
13955: @cindex image file, non-relocatable
13956: 
13957: These files are simple memory dumps of the dictionary. They are specific
13958: to the executable (i.e., @file{gforth} file) they were created
13959: with. What's worse, they are specific to the place on which the
13960: dictionary resided when the image was created. Now, there is no
13961: guarantee that the dictionary will reside at the same place the next
13962: time you start Gforth, so there's no guarantee that a non-relocatable
13963: image will work the next time (Gforth will complain instead of crashing,
13964: though).
13965: 
13966: You can create a non-relocatable image file with
13967: 
13968: 
13969: doc-savesystem
13970: 
13971: 
13972: @node Data-Relocatable Image Files, Fully Relocatable Image Files, Non-Relocatable Image Files, Image Files
13973: @section Data-Relocatable Image Files
13974: @cindex data-relocatable image files
13975: @cindex image file, data-relocatable
13976: 
13977: These files contain relocatable data addresses, but fixed code addresses
13978: (instead of tokens). They are specific to the executable (i.e.,
13979: @file{gforth} file) they were created with. For direct threading on some
13980: architectures (e.g., the i386), data-relocatable images do not work. You
13981: get a data-relocatable image, if you use @file{gforthmi} with a
13982: Gforth binary that is not doubly indirect threaded (@pxref{Fully
13983: Relocatable Image Files}).
13984: 
13985: @node Fully Relocatable Image Files, Stack and Dictionary Sizes, Data-Relocatable Image Files, Image Files
13986: @section Fully Relocatable Image Files
13987: @cindex fully relocatable image files
13988: @cindex image file, fully relocatable
13989: 
13990: @cindex @file{kern*.fi}, relocatability
13991: @cindex @file{gforth.fi}, relocatability
13992: These image files have relocatable data addresses, and tokens for code
13993: addresses. They can be used with different binaries (e.g., with and
13994: without debugging) on the same machine, and even across machines with
13995: the same data formats (byte order, cell size, floating point
13996: format). However, they are usually specific to the version of Gforth
13997: they were created with. The files @file{gforth.fi} and @file{kernl*.fi}
13998: are fully relocatable.
13999: 
14000: There are two ways to create a fully relocatable image file:
14001: 
14002: @menu
14003: * gforthmi::                    The normal way
14004: * cross.fs::                    The hard way
14005: @end menu
14006: 
14007: @node gforthmi, cross.fs, Fully Relocatable Image Files, Fully Relocatable Image Files
14008: @subsection @file{gforthmi}
14009: @cindex @file{comp-i.fs}
14010: @cindex @file{gforthmi}
14011: 
14012: You will usually use @file{gforthmi}. If you want to create an
14013: image @i{file} that contains everything you would load by invoking
14014: Gforth with @code{gforth @i{options}}, you simply say:
14015: @example
14016: gforthmi @i{file} @i{options}
14017: @end example
14018: 
14019: E.g., if you want to create an image @file{asm.fi} that has the file
14020: @file{asm.fs} loaded in addition to the usual stuff, you could do it
14021: like this:
14022: 
14023: @example
14024: gforthmi asm.fi asm.fs
14025: @end example
14026: 
14027: @file{gforthmi} is implemented as a sh script and works like this: It
14028: produces two non-relocatable images for different addresses and then
14029: compares them. Its output reflects this: first you see the output (if
14030: any) of the two Gforth invocations that produce the non-relocatable image
14031: files, then you see the output of the comparing program: It displays the
14032: offset used for data addresses and the offset used for code addresses;
14033: moreover, for each cell that cannot be represented correctly in the
14034: image files, it displays a line like this:
14035: 
14036: @example
14037:      78DC         BFFFFA50         BFFFFA40
14038: @end example
14039: 
14040: This means that at offset $78dc from @code{forthstart}, one input image
14041: contains $bffffa50, and the other contains $bffffa40. Since these cells
14042: cannot be represented correctly in the output image, you should examine
14043: these places in the dictionary and verify that these cells are dead
14044: (i.e., not read before they are written).
14045: 
14046: @cindex --application, @code{gforthmi} option
14047: If you insert the option @code{--application} in front of the image file
14048: name, you will get an image that uses the @code{--appl-image} option
14049: instead of the @code{--image-file} option (@pxref{Invoking
14050: Gforth}). When you execute such an image on Unix (by typing the image
14051: name as command), the Gforth engine will pass all options to the image
14052: instead of trying to interpret them as engine options.
14053: 
14054: If you type @file{gforthmi} with no arguments, it prints some usage
14055: instructions.
14056: 
14057: @cindex @code{savesystem} during @file{gforthmi}
14058: @cindex @code{bye} during @file{gforthmi}
14059: @cindex doubly indirect threaded code
14060: @cindex environment variables
14061: @cindex @code{GFORTHD} -- environment variable
14062: @cindex @code{GFORTH} -- environment variable
14063: @cindex @code{gforth-ditc}
14064: There are a few wrinkles: After processing the passed @i{options}, the
14065: words @code{savesystem} and @code{bye} must be visible. A special doubly
14066: indirect threaded version of the @file{gforth} executable is used for
14067: creating the non-relocatable images; you can pass the exact filename of
14068: this executable through the environment variable @code{GFORTHD}
14069: (default: @file{gforth-ditc}); if you pass a version that is not doubly
14070: indirect threaded, you will not get a fully relocatable image, but a
14071: data-relocatable image (because there is no code address offset). The
14072: normal @file{gforth} executable is used for creating the relocatable
14073: image; you can pass the exact filename of this executable through the
14074: environment variable @code{GFORTH}.
14075: 
14076: @node cross.fs,  , gforthmi, Fully Relocatable Image Files
14077: @subsection @file{cross.fs}
14078: @cindex @file{cross.fs}
14079: @cindex cross-compiler
14080: @cindex metacompiler
14081: @cindex target compiler
14082: 
14083: You can also use @code{cross}, a batch compiler that accepts a Forth-like
14084: programming language (@pxref{Cross Compiler}).
14085: 
14086: @code{cross} allows you to create image files for machines with
14087: different data sizes and data formats than the one used for generating
14088: the image file. You can also use it to create an application image that
14089: does not contain a Forth compiler. These features are bought with
14090: restrictions and inconveniences in programming. E.g., addresses have to
14091: be stored in memory with special words (@code{A!}, @code{A,}, etc.) in
14092: order to make the code relocatable.
14093: 
14094: 
14095: @node Stack and Dictionary Sizes, Running Image Files, Fully Relocatable Image Files, Image Files
14096: @section Stack and Dictionary Sizes
14097: @cindex image file, stack and dictionary sizes
14098: @cindex dictionary size default
14099: @cindex stack size default
14100: 
14101: If you invoke Gforth with a command line flag for the size
14102: (@pxref{Invoking Gforth}), the size you specify is stored in the
14103: dictionary. If you save the dictionary with @code{savesystem} or create
14104: an image with @file{gforthmi}, this size will become the default
14105: for the resulting image file. E.g., the following will create a
14106: fully relocatable version of @file{gforth.fi} with a 1MB dictionary:
14107: 
14108: @example
14109: gforthmi gforth.fi -m 1M
14110: @end example
14111: 
14112: In other words, if you want to set the default size for the dictionary
14113: and the stacks of an image, just invoke @file{gforthmi} with the
14114: appropriate options when creating the image.
14115: 
14116: @cindex stack size, cache-friendly
14117: Note: For cache-friendly behaviour (i.e., good performance), you should
14118: make the sizes of the stacks modulo, say, 2K, somewhat different. E.g.,
14119: the default stack sizes are: data: 16k (mod 2k=0); fp: 15.5k (mod
14120: 2k=1.5k); return: 15k(mod 2k=1k); locals: 14.5k (mod 2k=0.5k).
14121: 
14122: @node Running Image Files, Modifying the Startup Sequence, Stack and Dictionary Sizes, Image Files
14123: @section Running Image Files
14124: @cindex running image files
14125: @cindex invoking image files
14126: @cindex image file invocation
14127: 
14128: @cindex -i, invoke image file
14129: @cindex --image file, invoke image file
14130: You can invoke Gforth with an image file @i{image} instead of the
14131: default @file{gforth.fi} with the @code{-i} flag (@pxref{Invoking Gforth}):
14132: @example
14133: gforth -i @i{image}
14134: @end example
14135: 
14136: @cindex executable image file
14137: @cindex image file, executable
14138: If your operating system supports starting scripts with a line of the
14139: form @code{#! ...}, you just have to type the image file name to start
14140: Gforth with this image file (note that the file extension @code{.fi} is
14141: just a convention). I.e., to run Gforth with the image file @i{image},
14142: you can just type @i{image} instead of @code{gforth -i @i{image}}.
14143: This works because every @code{.fi} file starts with a line of this
14144: format:
14145: 
14146: @example
14147: #! /usr/local/bin/gforth-0.4.0 -i
14148: @end example
14149: 
14150: The file and pathname for the Gforth engine specified on this line is
14151: the specific Gforth executable that it was built against; i.e. the value
14152: of the environment variable @code{GFORTH} at the time that
14153: @file{gforthmi} was executed.
14154: 
14155: You can make use of the same shell capability to make a Forth source
14156: file into an executable. For example, if you place this text in a file:
14157: 
14158: @example
14159: #! /usr/local/bin/gforth
14160: 
14161: ." Hello, world" CR
14162: bye
14163: @end example
14164: 
14165: @noindent
14166: and then make the file executable (chmod +x in Unix), you can run it
14167: directly from the command line. The sequence @code{#!} is used in two
14168: ways; firstly, it is recognised as a ``magic sequence'' by the operating
14169: system@footnote{The Unix kernel actually recognises two types of files:
14170: executable files and files of data, where the data is processed by an
14171: interpreter that is specified on the ``interpreter line'' -- the first
14172: line of the file, starting with the sequence #!. There may be a small
14173: limit (e.g., 32) on the number of characters that may be specified on
14174: the interpreter line.} secondly it is treated as a comment character by
14175: Gforth. Because of the second usage, a space is required between
14176: @code{#!} and the path to the executable (moreover, some Unixes
14177: require the sequence @code{#! /}).
14178: 
14179: The disadvantage of this latter technique, compared with using
14180: @file{gforthmi}, is that it is slightly slower; the Forth source code is
14181: compiled on-the-fly, each time the program is invoked.
14182: 
14183: doc-#!
14184: 
14185: 
14186: @node Modifying the Startup Sequence,  , Running Image Files, Image Files
14187: @section Modifying the Startup Sequence
14188: @cindex startup sequence for image file
14189: @cindex image file initialization sequence
14190: @cindex initialization sequence of image file
14191: 
14192: You can add your own initialization to the startup sequence through the
14193: deferred word @code{'cold}. @code{'cold} is invoked just before the
14194: image-specific command line processing (i.e., loading files and
14195: evaluating (@code{-e}) strings) starts.
14196: 
14197: A sequence for adding your initialization usually looks like this:
14198: 
14199: @example
14200: :noname
14201:     Defers 'cold \ do other initialization stuff (e.g., rehashing wordlists)
14202:     ... \ your stuff
14203: ; IS 'cold
14204: @end example
14205: 
14206: @cindex turnkey image files
14207: @cindex image file, turnkey applications
14208: You can make a turnkey image by letting @code{'cold} execute a word
14209: (your turnkey application) that never returns; instead, it exits Gforth
14210: via @code{bye} or @code{throw}.
14211: 
14212: @cindex command-line arguments, access
14213: @cindex arguments on the command line, access
14214: You can access the (image-specific) command-line arguments through the
14215: variables @code{argc} and @code{argv}. @code{arg} provides convenient
14216: access to @code{argv}.
14217: 
14218: If @code{'cold} exits normally, Gforth processes the command-line
14219: arguments as files to be loaded and strings to be evaluated.  Therefore,
14220: @code{'cold} should remove the arguments it has used in this case.
14221: 
14222: 
14223: 
14224: doc-'cold
14225: doc-argc
14226: doc-argv
14227: doc-arg
14228: 
14229: 
14230: 
14231: @c ******************************************************************
14232: @node Engine, Binding to System Library, Image Files, Top
14233: @chapter Engine
14234: @cindex engine
14235: @cindex virtual machine
14236: 
14237: Reading this chapter is not necessary for programming with Gforth. It
14238: may be helpful for finding your way in the Gforth sources.
14239: 
14240: The ideas in this section have also been published in Bernd Paysan,
14241: @cite{ANS fig/GNU/??? Forth} (in German), Forth-Tagung '93 and M. Anton
14242: Ertl, @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl93.ps.Z, A
14243: Portable Forth Engine}}, EuroForth '93.
14244: 
14245: @menu
14246: * Portability::                 
14247: * Threading::                   
14248: * Primitives::                  
14249: * Performance::                 
14250: @end menu
14251: 
14252: @node Portability, Threading, Engine, Engine
14253: @section Portability
14254: @cindex engine portability
14255: 
14256: An important goal of the Gforth Project is availability across a wide
14257: range of personal machines. fig-Forth, and, to a lesser extent, F83,
14258: achieved this goal by manually coding the engine in assembly language
14259: for several then-popular processors. This approach is very
14260: labor-intensive and the results are short-lived due to progress in
14261: computer architecture.
14262: 
14263: @cindex C, using C for the engine
14264: Others have avoided this problem by coding in C, e.g., Mitch Bradley
14265: (cforth), Mikael Patel (TILE) and Dirk Zoller (pfe). This approach is
14266: particularly popular for UNIX-based Forths due to the large variety of
14267: architectures of UNIX machines. Unfortunately an implementation in C
14268: does not mix well with the goals of efficiency and with using
14269: traditional techniques: Indirect or direct threading cannot be expressed
14270: in C, and switch threading, the fastest technique available in C, is
14271: significantly slower. Another problem with C is that it is very
14272: cumbersome to express double integer arithmetic.
14273: 
14274: @cindex GNU C for the engine
14275: @cindex long long
14276: Fortunately, there is a portable language that does not have these
14277: limitations: GNU C, the version of C processed by the GNU C compiler
14278: (@pxref{C Extensions, , Extensions to the C Language Family, gcc.info,
14279: GNU C Manual}). Its labels as values feature (@pxref{Labels as Values, ,
14280: Labels as Values, gcc.info, GNU C Manual}) makes direct and indirect
14281: threading possible, its @code{long long} type (@pxref{Long Long, ,
14282: Double-Word Integers, gcc.info, GNU C Manual}) corresponds to Forth's
14283: double numbers@footnote{Unfortunately, long longs are not implemented
14284: properly on all machines (e.g., on alpha-osf1, long longs are only 64
14285: bits, the same size as longs (and pointers), but they should be twice as
14286: long according to @pxref{Long Long, , Double-Word Integers, gcc.info, GNU
14287: C Manual}). So, we had to implement doubles in C after all. Still, on
14288: most machines we can use long longs and achieve better performance than
14289: with the emulation package.}. GNU C is available for free on all
14290: important (and many unimportant) UNIX machines, VMS, 80386s running
14291: MS-DOS, the Amiga, and the Atari ST, so a Forth written in GNU C can run
14292: on all these machines.
14293: 
14294: Writing in a portable language has the reputation of producing code that
14295: is slower than assembly. For our Forth engine we repeatedly looked at
14296: the code produced by the compiler and eliminated most compiler-induced
14297: inefficiencies by appropriate changes in the source code.
14298: 
14299: @cindex explicit register declarations
14300: @cindex --enable-force-reg, configuration flag
14301: @cindex -DFORCE_REG
14302: However, register allocation cannot be portably influenced by the
14303: programmer, leading to some inefficiencies on register-starved
14304: machines. We use explicit register declarations (@pxref{Explicit Reg
14305: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) to
14306: improve the speed on some machines. They are turned on by using the
14307: configuration flag @code{--enable-force-reg} (@code{gcc} switch
14308: @code{-DFORCE_REG}). Unfortunately, this feature not only depends on the
14309: machine, but also on the compiler version: On some machines some
14310: compiler versions produce incorrect code when certain explicit register
14311: declarations are used. So by default @code{-DFORCE_REG} is not used.
14312: 
14313: @node Threading, Primitives, Portability, Engine
14314: @section Threading
14315: @cindex inner interpreter implementation
14316: @cindex threaded code implementation
14317: 
14318: @cindex labels as values
14319: GNU C's labels as values extension (available since @code{gcc-2.0},
14320: @pxref{Labels as Values, , Labels as Values, gcc.info, GNU C Manual})
14321: makes it possible to take the address of @i{label} by writing
14322: @code{&&@i{label}}.  This address can then be used in a statement like
14323: @code{goto *@i{address}}. I.e., @code{goto *&&x} is the same as
14324: @code{goto x}.
14325: 
14326: @cindex @code{NEXT}, indirect threaded
14327: @cindex indirect threaded inner interpreter
14328: @cindex inner interpreter, indirect threaded
14329: With this feature an indirect threaded @code{NEXT} looks like:
14330: @example
14331: cfa = *ip++;
14332: ca = *cfa;
14333: goto *ca;
14334: @end example
14335: @cindex instruction pointer
14336: For those unfamiliar with the names: @code{ip} is the Forth instruction
14337: pointer; the @code{cfa} (code-field address) corresponds to ANS Forths
14338: execution token and points to the code field of the next word to be
14339: executed; The @code{ca} (code address) fetched from there points to some
14340: executable code, e.g., a primitive or the colon definition handler
14341: @code{docol}.
14342: 
14343: @cindex @code{NEXT}, direct threaded
14344: @cindex direct threaded inner interpreter
14345: @cindex inner interpreter, direct threaded
14346: Direct threading is even simpler:
14347: @example
14348: ca = *ip++;
14349: goto *ca;
14350: @end example
14351: 
14352: Of course we have packaged the whole thing neatly in macros called
14353: @code{NEXT} and @code{NEXT1} (the part of @code{NEXT} after fetching the cfa).
14354: 
14355: @menu
14356: * Scheduling::                  
14357: * Direct or Indirect Threaded?::  
14358: * DOES>::                       
14359: @end menu
14360: 
14361: @node Scheduling, Direct or Indirect Threaded?, Threading, Threading
14362: @subsection Scheduling
14363: @cindex inner interpreter optimization
14364: 
14365: There is a little complication: Pipelined and superscalar processors,
14366: i.e., RISC and some modern CISC machines can process independent
14367: instructions while waiting for the results of an instruction. The
14368: compiler usually reorders (schedules) the instructions in a way that
14369: achieves good usage of these delay slots. However, on our first tries
14370: the compiler did not do well on scheduling primitives. E.g., for
14371: @code{+} implemented as
14372: @example
14373: n=sp[0]+sp[1];
14374: sp++;
14375: sp[0]=n;
14376: NEXT;
14377: @end example
14378: the @code{NEXT} comes strictly after the other code, i.e., there is
14379: nearly no scheduling. After a little thought the problem becomes clear:
14380: The compiler cannot know that @code{sp} and @code{ip} point to different
14381: addresses (and the version of @code{gcc} we used would not know it even
14382: if it was possible), so it could not move the load of the cfa above the
14383: store to the TOS. Indeed the pointers could be the same, if code on or
14384: very near the top of stack were executed. In the interest of speed we
14385: chose to forbid this probably unused ``feature'' and helped the compiler
14386: in scheduling: @code{NEXT} is divided into several parts:
14387: @code{NEXT_P0}, @code{NEXT_P1} and @code{NEXT_P2}). @code{+} now looks
14388: like:
14389: @example
14390: NEXT_P0;
14391: n=sp[0]+sp[1];
14392: sp++;
14393: NEXT_P1;
14394: sp[0]=n;
14395: NEXT_P2;
14396: @end example
14397: 
14398: There are various schemes that distribute the different operations of
14399: NEXT between these parts in several ways; in general, different schemes
14400: perform best on different processors.  We use a scheme for most
14401: architectures that performs well for most processors of this
14402: architecture; in the furture we may switch to benchmarking and chosing
14403: the scheme on installation time.
14404: 
14405: 
14406: @node Direct or Indirect Threaded?, DOES>, Scheduling, Threading
14407: @subsection Direct or Indirect Threaded?
14408: @cindex threading, direct or indirect?
14409: 
14410: @cindex -DDIRECT_THREADED
14411: Both! After packaging the nasty details in macro definitions we
14412: realized that we could switch between direct and indirect threading by
14413: simply setting a compilation flag (@code{-DDIRECT_THREADED}) and
14414: defining a few machine-specific macros for the direct-threading case.
14415: On the Forth level we also offer access words that hide the
14416: differences between the threading methods (@pxref{Threading Words}).
14417: 
14418: Indirect threading is implemented completely machine-independently.
14419: Direct threading needs routines for creating jumps to the executable
14420: code (e.g. to @code{docol} or @code{dodoes}). These routines are inherently
14421: machine-dependent, but they do not amount to many source lines. Therefore,
14422: even porting direct threading to a new machine requires little effort.
14423: 
14424: @cindex --enable-indirect-threaded, configuration flag
14425: @cindex --enable-direct-threaded, configuration flag
14426: The default threading method is machine-dependent. You can enforce a
14427: specific threading method when building Gforth with the configuration
14428: flag @code{--enable-direct-threaded} or
14429: @code{--enable-indirect-threaded}. Note that direct threading is not
14430: supported on all machines.
14431: 
14432: @node DOES>,  , Direct or Indirect Threaded?, Threading
14433: @subsection DOES>
14434: @cindex @code{DOES>} implementation
14435: 
14436: @cindex @code{dodoes} routine
14437: @cindex @code{DOES>}-code
14438: One of the most complex parts of a Forth engine is @code{dodoes}, i.e.,
14439: the chunk of code executed by every word defined by a
14440: @code{CREATE}...@code{DOES>} pair. The main problem here is: How to find
14441: the Forth code to be executed, i.e. the code after the
14442: @code{DOES>} (the @code{DOES>}-code)? There are two solutions:
14443: 
14444: In fig-Forth the code field points directly to the @code{dodoes} and the
14445: @code{DOES>}-code address is stored in the cell after the code address (i.e. at
14446: @code{@i{CFA} cell+}). It may seem that this solution is illegal in
14447: the Forth-79 and all later standards, because in fig-Forth this address
14448: lies in the body (which is illegal in these standards). However, by
14449: making the code field larger for all words this solution becomes legal
14450: again. We use this approach for the indirect threaded version and for
14451: direct threading on some machines. Leaving a cell unused in most words
14452: is a bit wasteful, but on the machines we are targeting this is hardly a
14453: problem. The other reason for having a code field size of two cells is
14454: to avoid having different image files for direct and indirect threaded
14455: systems (direct threaded systems require two-cell code fields on many
14456: machines).
14457: 
14458: @cindex @code{DOES>}-handler
14459: The other approach is that the code field points or jumps to the cell
14460: after @code{DOES>}. In this variant there is a jump to @code{dodoes} at
14461: this address (the @code{DOES>}-handler). @code{dodoes} can then get the
14462: @code{DOES>}-code address by computing the code address, i.e., the address of
14463: the jump to @code{dodoes}, and add the length of that jump field. A variant of
14464: this is to have a call to @code{dodoes} after the @code{DOES>}; then the
14465: return address (which can be found in the return register on RISCs) is
14466: the @code{DOES>}-code address. Since the two cells available in the code field
14467: are used up by the jump to the code address in direct threading on many
14468: architectures, we use this approach for direct threading on these
14469: architectures. We did not want to add another cell to the code field.
14470: 
14471: @node Primitives, Performance, Threading, Engine
14472: @section Primitives
14473: @cindex primitives, implementation
14474: @cindex virtual machine instructions, implementation
14475: 
14476: @menu
14477: * Automatic Generation::        
14478: * TOS Optimization::            
14479: * Produced code::               
14480: @end menu
14481: 
14482: @node Automatic Generation, TOS Optimization, Primitives, Primitives
14483: @subsection Automatic Generation
14484: @cindex primitives, automatic generation
14485: 
14486: @cindex @file{prims2x.fs}
14487: Since the primitives are implemented in a portable language, there is no
14488: longer any need to minimize the number of primitives. On the contrary,
14489: having many primitives has an advantage: speed. In order to reduce the
14490: number of errors in primitives and to make programming them easier, we
14491: provide a tool, the primitive generator (@file{prims2x.fs}), that
14492: automatically generates most (and sometimes all) of the C code for a
14493: primitive from the stack effect notation.  The source for a primitive
14494: has the following form:
14495: 
14496: @cindex primitive source format
14497: @format
14498: @i{Forth-name}  ( @i{stack-effect} )        @i{category}    [@i{pronounc.}]
14499: [@code{""}@i{glossary entry}@code{""}]
14500: @i{C code}
14501: [@code{:}
14502: @i{Forth code}]
14503: @end format
14504: 
14505: The items in brackets are optional. The category and glossary fields
14506: are there for generating the documentation, the Forth code is there
14507: for manual implementations on machines without GNU C. E.g., the source
14508: for the primitive @code{+} is:
14509: @example
14510: +    ( n1 n2 -- n )   core    plus
14511: n = n1+n2;
14512: @end example
14513: 
14514: This looks like a specification, but in fact @code{n = n1+n2} is C
14515: code. Our primitive generation tool extracts a lot of information from
14516: the stack effect notations@footnote{We use a one-stack notation, even
14517: though we have separate data and floating-point stacks; The separate
14518: notation can be generated easily from the unified notation.}: The number
14519: of items popped from and pushed on the stack, their type, and by what
14520: name they are referred to in the C code. It then generates a C code
14521: prelude and postlude for each primitive. The final C code for @code{+}
14522: looks like this:
14523: 
14524: @example
14525: I_plus: /* + ( n1 n2 -- n ) */  /* label, stack effect */
14526: /*  */                          /* documentation */
14527: NAME("+")                       /* debugging output (with -DDEBUG) */
14528: @{
14529: DEF_CA                          /* definition of variable ca (indirect threading) */
14530: Cell n1;                        /* definitions of variables */
14531: Cell n2;
14532: Cell n;
14533: NEXT_P0;                        /* NEXT part 0 */
14534: n1 = (Cell) sp[1];              /* input */
14535: n2 = (Cell) TOS;
14536: sp += 1;                        /* stack adjustment */
14537: @{
14538: n = n1+n2;                      /* C code taken from the source */
14539: @}
14540: NEXT_P1;                        /* NEXT part 1 */
14541: TOS = (Cell)n;                  /* output */
14542: NEXT_P2;                        /* NEXT part 2 */
14543: @}
14544: @end example
14545: 
14546: This looks long and inefficient, but the GNU C compiler optimizes quite
14547: well and produces optimal code for @code{+} on, e.g., the R3000 and the
14548: HP RISC machines: Defining the @code{n}s does not produce any code, and
14549: using them as intermediate storage also adds no cost.
14550: 
14551: There are also other optimizations that are not illustrated by this
14552: example: assignments between simple variables are usually for free (copy
14553: propagation). If one of the stack items is not used by the primitive
14554: (e.g.  in @code{drop}), the compiler eliminates the load from the stack
14555: (dead code elimination). On the other hand, there are some things that
14556: the compiler does not do, therefore they are performed by
14557: @file{prims2x.fs}: The compiler does not optimize code away that stores
14558: a stack item to the place where it just came from (e.g., @code{over}).
14559: 
14560: While programming a primitive is usually easy, there are a few cases
14561: where the programmer has to take the actions of the generator into
14562: account, most notably @code{?dup}, but also words that do not (always)
14563: fall through to @code{NEXT}.
14564: 
14565: @node TOS Optimization, Produced code, Automatic Generation, Primitives
14566: @subsection TOS Optimization
14567: @cindex TOS optimization for primitives
14568: @cindex primitives, keeping the TOS in a register
14569: 
14570: An important optimization for stack machine emulators, e.g., Forth
14571: engines, is keeping  one or more of the top stack items in
14572: registers.  If a word has the stack effect @i{in1}...@i{inx} @code{--}
14573: @i{out1}...@i{outy}, keeping the top @i{n} items in registers
14574: @itemize @bullet
14575: @item
14576: is better than keeping @i{n-1} items, if @i{x>=n} and @i{y>=n},
14577: due to fewer loads from and stores to the stack.
14578: @item is slower than keeping @i{n-1} items, if @i{x<>y} and @i{x<n} and
14579: @i{y<n}, due to additional moves between registers.
14580: @end itemize
14581: 
14582: @cindex -DUSE_TOS
14583: @cindex -DUSE_NO_TOS
14584: In particular, keeping one item in a register is never a disadvantage,
14585: if there are enough registers. Keeping two items in registers is a
14586: disadvantage for frequent words like @code{?branch}, constants,
14587: variables, literals and @code{i}. Therefore our generator only produces
14588: code that keeps zero or one items in registers. The generated C code
14589: covers both cases; the selection between these alternatives is made at
14590: C-compile time using the switch @code{-DUSE_TOS}. @code{TOS} in the C
14591: code for @code{+} is just a simple variable name in the one-item case,
14592: otherwise it is a macro that expands into @code{sp[0]}. Note that the
14593: GNU C compiler tries to keep simple variables like @code{TOS} in
14594: registers, and it usually succeeds, if there are enough registers.
14595: 
14596: @cindex -DUSE_FTOS
14597: @cindex -DUSE_NO_FTOS
14598: The primitive generator performs the TOS optimization for the
14599: floating-point stack, too (@code{-DUSE_FTOS}). For floating-point
14600: operations the benefit of this optimization is even larger:
14601: floating-point operations take quite long on most processors, but can be
14602: performed in parallel with other operations as long as their results are
14603: not used. If the FP-TOS is kept in a register, this works. If
14604: it is kept on the stack, i.e., in memory, the store into memory has to
14605: wait for the result of the floating-point operation, lengthening the
14606: execution time of the primitive considerably.
14607: 
14608: The TOS optimization makes the automatic generation of primitives a
14609: bit more complicated. Just replacing all occurrences of @code{sp[0]} by
14610: @code{TOS} is not sufficient. There are some special cases to
14611: consider:
14612: @itemize @bullet
14613: @item In the case of @code{dup ( w -- w w )} the generator must not
14614: eliminate the store to the original location of the item on the stack,
14615: if the TOS optimization is turned on.
14616: @item Primitives with stack effects of the form @code{--}
14617: @i{out1}...@i{outy} must store the TOS to the stack at the start.
14618: Likewise, primitives with the stack effect @i{in1}...@i{inx} @code{--}
14619: must load the TOS from the stack at the end. But for the null stack
14620: effect @code{--} no stores or loads should be generated.
14621: @end itemize
14622: 
14623: @node Produced code,  , TOS Optimization, Primitives
14624: @subsection Produced code
14625: @cindex primitives, assembly code listing
14626: 
14627: @cindex @file{engine.s}
14628: To see what assembly code is produced for the primitives on your machine
14629: with your compiler and your flag settings, type @code{make engine.s} and
14630: look at the resulting file @file{engine.s}.  Alternatively, you can also
14631: disassemble the code of primitives with @code{see} on some architectures.
14632: 
14633: @node  Performance,  , Primitives, Engine
14634: @section Performance
14635: @cindex performance of some Forth interpreters
14636: @cindex engine performance
14637: @cindex benchmarking Forth systems
14638: @cindex Gforth performance
14639: 
14640: On RISCs the Gforth engine is very close to optimal; i.e., it is usually
14641: impossible to write a significantly faster engine.
14642: 
14643: On register-starved machines like the 386 architecture processors
14644: improvements are possible, because @code{gcc} does not utilize the
14645: registers as well as a human, even with explicit register declarations;
14646: e.g., Bernd Beuster wrote a Forth system fragment in assembly language
14647: and hand-tuned it for the 486; this system is 1.19 times faster on the
14648: Sieve benchmark on a 486DX2/66 than Gforth compiled with
14649: @code{gcc-2.6.3} with @code{-DFORCE_REG}.  The situation has improved
14650: with gcc-2.95 and gforth-0.4.9; now the most important virtual machine
14651: registers fit in real registers (and we can even afford to use the TOS
14652: optimization), resulting in a speedup of 1.14 on the sieve over the
14653: earlier results.
14654: 
14655: @cindex Win32Forth performance
14656: @cindex NT Forth performance
14657: @cindex eforth performance
14658: @cindex ThisForth performance
14659: @cindex PFE performance
14660: @cindex TILE performance
14661: The potential advantage of assembly language implementations is not
14662: necessarily realized in complete Forth systems: We compared Gforth-0.4.9
14663: (direct threaded, compiled with @code{gcc-2.95.1} and
14664: @code{-DFORCE_REG}) with Win32Forth 1.2093 (newer versions are
14665: reportedly much faster), LMI's NT Forth (Beta, May 1994) and Eforth
14666: (with and without peephole (aka pinhole) optimization of the threaded
14667: code); all these systems were written in assembly language. We also
14668: compared Gforth with three systems written in C: PFE-0.9.14 (compiled
14669: with @code{gcc-2.6.3} with the default configuration for Linux:
14670: @code{-O2 -fomit-frame-pointer -DUSE_REGS -DUNROLL_NEXT}), ThisForth
14671: Beta (compiled with @code{gcc-2.6.3 -O3 -fomit-frame-pointer}; ThisForth
14672: employs peephole optimization of the threaded code) and TILE (compiled
14673: with @code{make opt}). We benchmarked Gforth, PFE, ThisForth and TILE on
14674: a 486DX2/66 under Linux. Kenneth O'Heskin kindly provided the results
14675: for Win32Forth and NT Forth on a 486DX2/66 with similar memory
14676: performance under Windows NT. Marcel Hendrix ported Eforth to Linux,
14677: then extended it to run the benchmarks, added the peephole optimizer,
14678: ran the benchmarks and reported the results.
14679: 
14680: We used four small benchmarks: the ubiquitous Sieve; bubble-sorting and
14681: matrix multiplication come from the Stanford integer benchmarks and have
14682: been translated into Forth by Martin Fraeman; we used the versions
14683: included in the TILE Forth package, but with bigger data set sizes; and
14684: a recursive Fibonacci number computation for benchmarking calling
14685: performance. The following table shows the time taken for the benchmarks
14686: scaled by the time taken by Gforth (in other words, it shows the speedup
14687: factor that Gforth achieved over the other systems).
14688: 
14689: @example
14690: relative      Win32-    NT       eforth       This-      
14691:   time  Gforth Forth Forth eforth  +opt   PFE Forth  TILE
14692: sieve     1.00  1.60  1.32   1.60  0.98  1.82  3.67  9.91
14693: bubble    1.00  1.55  1.66   1.75  1.04  1.78        4.58
14694: matmul    1.00  1.71  1.57   1.69  0.86  1.83        4.74
14695: fib       1.00  1.76  1.54   1.41  1.00  2.01  3.45  4.96
14696: @end example
14697: 
14698: You may be quite surprised by the good performance of Gforth when
14699: compared with systems written in assembly language. One important reason
14700: for the disappointing performance of these other systems is probably
14701: that they are not written optimally for the 486 (e.g., they use the
14702: @code{lods} instruction). In addition, Win32Forth uses a comfortable,
14703: but costly method for relocating the Forth image: like @code{cforth}, it
14704: computes the actual addresses at run time, resulting in two address
14705: computations per @code{NEXT} (@pxref{Image File Background}).
14706: 
14707: Only Eforth with the peephole optimizer performs comparable to
14708: Gforth. The speedups achieved with peephole optimization of threaded
14709: code are quite remarkable. Adding a peephole optimizer to Gforth should
14710: cause similar speedups.
14711: 
14712: The speedup of Gforth over PFE, ThisForth and TILE can be easily
14713: explained with the self-imposed restriction of the latter systems to
14714: standard C, which makes efficient threading impossible (however, the
14715: measured implementation of PFE uses a GNU C extension: @pxref{Global Reg
14716: Vars, , Defining Global Register Variables, gcc.info, GNU C Manual}).
14717: Moreover, current C compilers have a hard time optimizing other aspects
14718: of the ThisForth and the TILE source.
14719: 
14720: The performance of Gforth on 386 architecture processors varies widely
14721: with the version of @code{gcc} used. E.g., @code{gcc-2.5.8} failed to
14722: allocate any of the virtual machine registers into real machine
14723: registers by itself and would not work correctly with explicit register
14724: declarations, giving a 1.5 times slower engine (on a 486DX2/66 running
14725: the Sieve) than the one measured above.
14726: 
14727: Note that there have been several releases of Win32Forth since the
14728: release presented here, so the results presented above may have little
14729: predictive value for the performance of Win32Forth today (results for
14730: the current release on an i486DX2/66 are welcome).
14731: 
14732: @cindex @file{Benchres}
14733: In
14734: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl&maierhofer95.ps.gz,
14735: Translating Forth to Efficient C}} by M. Anton Ertl and Martin
14736: Maierhofer (presented at EuroForth '95), an indirect threaded version of
14737: Gforth is compared with Win32Forth, NT Forth, PFE, ThisForth, and
14738: several native code systems; that version of Gforth is slower on a 486
14739: than the direct threaded version used here. You can find a newer version
14740: of these measurements at
14741: @uref{http://www.complang.tuwien.ac.at/forth/performance.html}. You can
14742: find numbers for Gforth on various machines in @file{Benchres}.
14743: 
14744: @c ******************************************************************
14745: @node Binding to System Library, Cross Compiler, Engine, Top
14746: @chapter Binding to System Library
14747: 
14748: @node Cross Compiler, Bugs, Binding to System Library, Top
14749: @chapter Cross Compiler
14750: @cindex @file{cross.fs}
14751: @cindex cross-compiler
14752: @cindex metacompiler
14753: @cindex target compiler
14754: 
14755: The cross compiler is used to bootstrap a Forth kernel. Since Gforth is
14756: mostly written in Forth, including crucial parts like the outer
14757: interpreter and compiler, it needs compiled Forth code to get
14758: started. The cross compiler allows to create new images for other
14759: architectures, even running under another Forth system.
14760: 
14761: @menu
14762: * Using the Cross Compiler::    
14763: * How the Cross Compiler Works::  
14764: @end menu
14765: 
14766: @node Using the Cross Compiler, How the Cross Compiler Works, Cross Compiler, Cross Compiler
14767: @section Using the Cross Compiler
14768: 
14769: The cross compiler uses a language that resembles Forth, but isn't. The
14770: main difference is that you can execute Forth code after definition,
14771: while you usually can't execute the code compiled by cross, because the
14772: code you are compiling is typically for a different computer than the
14773: one you are compiling on.
14774: 
14775: @c anton: This chapter is somewhat different from waht I would expect: I
14776: @c would expect an explanation of the cross language and how to create an
14777: @c application image with it.  The section explains some aspects of
14778: @c creating a Gforth kernel.
14779: 
14780: The Makefile is already set up to allow you to create kernels for new
14781: architectures with a simple make command. The generic kernels using the
14782: GCC compiled virtual machine are created in the normal build process
14783: with @code{make}. To create a embedded Gforth executable for e.g. the
14784: 8086 processor (running on a DOS machine), type
14785: 
14786: @example
14787: make kernl-8086.fi
14788: @end example
14789: 
14790: This will use the machine description from the @file{arch/8086}
14791: directory to create a new kernel. A machine file may look like that:
14792: 
14793: @example
14794: \ Parameter for target systems                         06oct92py
14795: 
14796:     4 Constant cell             \ cell size in bytes
14797:     2 Constant cell<<           \ cell shift to bytes
14798:     5 Constant cell>bit         \ cell shift to bits
14799:     8 Constant bits/char        \ bits per character
14800:     8 Constant bits/byte        \ bits per byte [default: 8]
14801:     8 Constant float            \ bytes per float
14802:     8 Constant /maxalign        \ maximum alignment in bytes
14803: false Constant bigendian        \ byte order
14804: ( true=big, false=little )
14805: 
14806: include machpc.fs               \ feature list
14807: @end example
14808: 
14809: This part is obligatory for the cross compiler itself, the feature list
14810: is used by the kernel to conditionally compile some features in and out,
14811: depending on whether the target supports these features.
14812: 
14813: There are some optional features, if you define your own primitives,
14814: have an assembler, or need special, nonstandard preparation to make the
14815: boot process work. @code{asm-include} includes an assembler,
14816: @code{prims-include} includes primitives, and @code{>boot} prepares for
14817: booting.
14818: 
14819: @example
14820: : asm-include    ." Include assembler" cr
14821:   s" arch/8086/asm.fs" included ;
14822: 
14823: : prims-include  ." Include primitives" cr
14824:   s" arch/8086/prim.fs" included ;
14825: 
14826: : >boot          ." Prepare booting" cr
14827:   s" ' boot >body into-forth 1+ !" evaluate ;
14828: @end example
14829: 
14830: These words are used as sort of macro during the cross compilation in
14831: the file @file{kernel/main.fs}. Instead of using these macros, it would
14832: be possible --- but more complicated --- to write a new kernel project
14833: file, too.
14834: 
14835: @file{kernel/main.fs} expects the machine description file name on the
14836: stack; the cross compiler itself (@file{cross.fs}) assumes that either
14837: @code{mach-file} leaves a counted string on the stack, or
14838: @code{machine-file} leaves an address, count pair of the filename on the
14839: stack.
14840: 
14841: The feature list is typically controlled using @code{SetValue}, generic
14842: files that are used by several projects can use @code{DefaultValue}
14843: instead. Both functions work like @code{Value}, when the value isn't
14844: defined, but @code{SetValue} works like @code{to} if the value is
14845: defined, and @code{DefaultValue} doesn't set anything, if the value is
14846: defined.
14847: 
14848: @example
14849: \ generic mach file for pc gforth                       03sep97jaw
14850: 
14851: true DefaultValue NIL  \ relocating
14852: 
14853: >ENVIRON
14854: 
14855: true DefaultValue file          \ controls the presence of the
14856:                                 \ file access wordset
14857: true DefaultValue OS            \ flag to indicate a operating system
14858: 
14859: true DefaultValue prims         \ true: primitives are c-code
14860: 
14861: true DefaultValue floating      \ floating point wordset is present
14862: 
14863: true DefaultValue glocals       \ gforth locals are present
14864:                                 \ will be loaded
14865: true DefaultValue dcomps        \ double number comparisons
14866: 
14867: true DefaultValue hash          \ hashing primitives are loaded/present
14868: 
14869: true DefaultValue xconds        \ used together with glocals,
14870:                                 \ special conditionals supporting gforths'
14871:                                 \ local variables
14872: true DefaultValue header        \ save a header information
14873: 
14874: true DefaultValue backtrace     \ enables backtrace code
14875: 
14876: false DefaultValue ec
14877: false DefaultValue crlf
14878: 
14879: cell 2 = [IF] &32 [ELSE] &256 [THEN] KB DefaultValue kernel-size
14880: 
14881: &16 KB          DefaultValue stack-size
14882: &15 KB &512 +   DefaultValue fstack-size
14883: &15 KB          DefaultValue rstack-size
14884: &14 KB &512 +   DefaultValue lstack-size
14885: @end example
14886: 
14887: @node How the Cross Compiler Works,  , Using the Cross Compiler, Cross Compiler
14888: @section How the Cross Compiler Works
14889: 
14890: @node Bugs, Origin, Cross Compiler, Top
14891: @appendix Bugs
14892: @cindex bug reporting
14893: 
14894: Known bugs are described in the file @file{BUGS} in the Gforth distribution.
14895: 
14896: If you find a bug, please send a bug report to
14897: @email{bug-gforth@@gnu.org}. A bug report should include this
14898: information:
14899: 
14900: @itemize @bullet
14901: @item
14902: A program (or a sequence of keyboard commands) that reproduces the bug.
14903: @item
14904: A description of what you think constitutes the buggy behaviour.
14905: @item
14906: The Gforth version used (it is announced at the start of an
14907: interactive Gforth session).
14908: @item
14909: The machine and operating system (on Unix
14910: systems @code{uname -a} will report this information).
14911: @item
14912: The installation options (you can find the configure options at the
14913: start of @file{config.status}) and configuration (@code{configure}
14914: output or @file{config.cache}).
14915: @item
14916: A complete list of changes (if any) you (or your installer) have made to the
14917: Gforth sources.
14918: @end itemize
14919: 
14920: For a thorough guide on reporting bugs read @ref{Bug Reporting, , How
14921: to Report Bugs, gcc.info, GNU C Manual}.
14922: 
14923: 
14924: @node Origin, Forth-related information, Bugs, Top
14925: @appendix Authors and Ancestors of Gforth
14926: 
14927: @section Authors and Contributors
14928: @cindex authors of Gforth
14929: @cindex contributors to Gforth
14930: 
14931: The Gforth project was started in mid-1992 by Bernd Paysan and Anton
14932: Ertl. The third major author was Jens Wilke.  Neal Crook contributed a
14933: lot to the manual.  Assemblers and disassemblers were contributed by
14934: Andrew McKewan, Christian Pirker, and Bernd Thallner.  Lennart Benschop
14935: (who was one of Gforth's first users, in mid-1993) and Stuart Ramsden
14936: inspired us with their continuous feedback. Lennart Benshop contributed
14937: @file{glosgen.fs}, while Stuart Ramsden has been working on automatic
14938: support for calling C libraries. Helpful comments also came from Paul
14939: Kleinrubatscher, Christian Pirker, Dirk Zoller, Marcel Hendrix, John
14940: Wavrik, Barrie Stott, Marc de Groot, Jorge Acerada, Bruce Hoyt, and
14941: Robert Epprecht. Since the release of Gforth-0.2.1 there were also
14942: helpful comments from many others; thank you all, sorry for not listing
14943: you here (but digging through my mailbox to extract your names is on my
14944: to-do list).
14945: 
14946: Gforth also owes a lot to the authors of the tools we used (GCC, CVS,
14947: and autoconf, among others), and to the creators of the Internet: Gforth
14948: was developed across the Internet, and its authors did not meet
14949: physically for the first 4 years of development.
14950: 
14951: @section Pedigree
14952: @cindex pedigree of Gforth
14953: 
14954: Gforth descends from bigFORTH (1993) and fig-Forth.  Of course, a
14955: significant part of the design of Gforth was prescribed by ANS Forth.
14956: 
14957: Bernd Paysan wrote bigFORTH, a descendent from TurboForth, an unreleased
14958: 32 bit native code version of VolksForth for the Atari ST, written
14959: mostly by Dietrich Weineck.
14960: 
14961: VolksForth was written by Klaus Schleisiek, Bernd Pennemann, Georg
14962: Rehfeld and Dietrich Weineck for the C64 (called UltraForth there) in
14963: the mid-80s and ported to the Atari ST in 1986.  It descends from F83.
14964: 
14965: Henry Laxen and Mike Perry wrote F83 as a model implementation of the
14966: Forth-83 standard. !! Pedigree? When?
14967: 
14968: A team led by Bill Ragsdale implemented fig-Forth on many processors in
14969: 1979. Robert Selzer and Bill Ragsdale developed the original
14970: implementation of fig-Forth for the 6502 based on microForth.
14971: 
14972: The principal architect of microForth was Dean Sanderson. microForth was
14973: FORTH, Inc.'s first off-the-shelf product. It was developed in 1976 for
14974: the 1802, and subsequently implemented on the 8080, the 6800 and the
14975: Z80.
14976: 
14977: All earlier Forth systems were custom-made, usually by Charles Moore,
14978: who discovered (as he puts it) Forth during the late 60s. The first full
14979: Forth existed in 1971.
14980: 
14981: A part of the information in this section comes from
14982: @cite{@uref{http://www.forth.com/Content/History/History1.htm,The
14983: Evolution of Forth}} by Elizabeth D. Rather, Donald R. Colburn and
14984: Charles H. Moore, presented at the HOPL-II conference and preprinted in
14985: SIGPLAN Notices 28(3), 1993.  You can find more historical and
14986: genealogical information about Forth there.
14987: 
14988: @c ------------------------------------------------------------------
14989: @node Forth-related information, Word Index, Origin, Top
14990: @appendix Other Forth-related information
14991: @cindex Forth-related information
14992: 
14993: @c anton: I threw most of this stuff out, because it can be found through
14994: @c the FAQ and the FAQ is more likely to be up-to-date.
14995: 
14996: @cindex comp.lang.forth
14997: @cindex frequently asked questions
14998: There is an active news group (comp.lang.forth) discussing Forth
14999: (including Gforth) and Forth-related issues. Its
15000: @uref{http://www.complang.tuwien.ac.at/forth/faq/faq-general-2.html,FAQs}
15001: (frequently asked questions and their answers) contains a lot of
15002: information on Forth.  You should read it before posting to
15003: comp.lang.forth.
15004: 
15005: The ANS Forth standard is most usable in its
15006: @uref{http://www.taygeta.com/forth/dpans.html, HTML form}.
15007: 
15008: @c ------------------------------------------------------------------
15009: @node Word Index, Concept Index, Forth-related information, Top
15010: @unnumbered Word Index
15011: 
15012: This index is a list of Forth words that have ``glossary'' entries
15013: within this manual. Each word is listed with its stack effect and
15014: wordset.
15015: 
15016: @printindex fn
15017: 
15018: @c anton: the name index seems superfluous given the word and concept indices.
15019: 
15020: @c @node Name Index, Concept Index, Word Index, Top
15021: @c @unnumbered Name Index
15022: 
15023: @c This index is a list of Forth words that have ``glossary'' entries
15024: @c within this manual.
15025: 
15026: @c @printindex ky
15027: 
15028: @node Concept Index,  , Word Index, Top
15029: @unnumbered Concept and Word Index
15030: 
15031: Not all entries listed in this index are present verbatim in the
15032: text. This index also duplicates, in abbreviated form, all of the words
15033: listed in the Word Index (only the names are listed for the words here).
15034: 
15035: @printindex cp
15036: 
15037: @contents
15038: @bye
15039: 
15040: 
15041: 

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