File:  [gforth] / gforth / doc / gforth.ds
Revision 1.70: download - view: text, annotated - select for diffs
Mon Aug 14 19:15:55 2000 UTC (23 years, 8 months ago) by pazsan
Branches: MAIN
CVS tags: HEAD
Added conditions to the new primitives (floating)
Fixed prims2x.fs to accept comments after the last primitive
Fixed newline Forth definition
Small docs fixes

    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: * Name Index::                  Forth words, only names listed
  171: * Concept Index::               A menu covering many topics
  172: 
  173: @detailmenu --- The Detailed Node Listing ---
  174: 
  175: Gforth Environment
  176: 
  177: * Invoking Gforth::             Getting in
  178: * Leaving Gforth::              Getting out
  179: * Command-line editing::        
  180: * Environment variables::       that affect how Gforth starts up
  181: * Gforth Files::                What gets installed and where
  182: * Startup speed::               When 35ms is not fast enough ...
  183: 
  184: Forth Tutorial
  185: 
  186: * Starting Gforth Tutorial::    
  187: * Syntax Tutorial::             
  188: * Crash Course Tutorial::       
  189: * Stack Tutorial::              
  190: * Arithmetics Tutorial::        
  191: * Stack Manipulation Tutorial::  
  192: * Using files for Forth code Tutorial::  
  193: * Comments Tutorial::           
  194: * Colon Definitions Tutorial::  
  195: * Decompilation Tutorial::      
  196: * Stack-Effect Comments Tutorial::  
  197: * Types Tutorial::              
  198: * Factoring Tutorial::          
  199: * Designing the stack effect Tutorial::  
  200: * Local Variables Tutorial::    
  201: * Conditional execution Tutorial::  
  202: * Flags and Comparisons Tutorial::  
  203: * General Loops Tutorial::      
  204: * Counted loops Tutorial::      
  205: * Recursion Tutorial::          
  206: * Leaving definitions or loops Tutorial::  
  207: * Return Stack Tutorial::       
  208: * Memory Tutorial::             
  209: * Characters and Strings Tutorial::  
  210: * Alignment 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: * The Text Interpreter::        
  247: * Word Lists::                  
  248: * Environmental Queries::       
  249: * Files::                       
  250: * Blocks::                      
  251: * Other I/O::                   
  252: * Programming Tools::           
  253: * Assembler and Code Words::    
  254: * Threading Words::             
  255: * Locals::                      
  256: * Structures::                  
  257: * Object-oriented Forth::       
  258: * Passing Commands to the OS::  
  259: * Keeping track of Time::       
  260: * Miscellaneous Words::         
  261: 
  262: Arithmetic
  263: 
  264: * Single precision::            
  265: * Double precision::            Double-cell integer arithmetic
  266: * Bitwise operations::          
  267: * Numeric comparison::          
  268: * Mixed precision::             Operations with single and double-cell integers
  269: * Floating Point::              
  270: 
  271: Stack Manipulation
  272: 
  273: * Data stack::                  
  274: * Floating point stack::        
  275: * Return stack::                
  276: * Locals stack::                
  277: * Stack pointer manipulation::  
  278: 
  279: Memory
  280: 
  281: * Memory model::                
  282: * Dictionary allocation::       
  283: * Heap Allocation::             
  284: * Memory Access::               
  285: * Address arithmetic::          
  286: * Memory Blocks::               
  287: 
  288: Control Structures
  289: 
  290: * Selection::                   IF ... ELSE ... ENDIF
  291: * Simple Loops::                BEGIN ...
  292: * Counted Loops::               DO
  293: * Arbitrary control structures::  
  294: * Calls and returns::           
  295: * Exception Handling::          
  296: 
  297: Defining Words
  298: 
  299: * CREATE::                      
  300: * Variables::                   Variables and user variables
  301: * Constants::                   
  302: * Values::                      Initialised variables
  303: * Colon Definitions::           
  304: * Anonymous Definitions::       Definitions without names
  305: * Supplying names::             
  306: * User-defined Defining Words::  
  307: * Deferred words::              Allow forward references
  308: * Aliases::                     
  309: 
  310: User-defined Defining Words
  311: 
  312: * CREATE..DOES> applications::  
  313: * CREATE..DOES> details::       
  314: * Advanced does> usage example::  
  315: 
  316: Interpretation and Compilation Semantics
  317: 
  318: * Combined words::              
  319: 
  320: The Text Interpreter
  321: 
  322: * Input Sources::               
  323: * Number Conversion::           
  324: * Interpret/Compile states::    
  325: * Literals::                    
  326: * Interpreter Directives::      
  327: 
  328: Word Lists
  329: 
  330: * Why use word lists?::         
  331: * Word list examples::          
  332: 
  333: Files
  334: 
  335: * Forth source files::          
  336: * General files::               
  337: * Search Paths::                
  338: 
  339: Search Paths
  340: 
  341: * Forth Search Paths::          
  342: * General Search Paths::        
  343: 
  344: Other I/O
  345: 
  346: * Simple numeric output::       Predefined formats
  347: * Formatted numeric output::    Formatted (pictured) output
  348: * String Formats::              How Forth stores strings in memory
  349: * Displaying characters and strings::  Other stuff
  350: * Input::                       Input
  351: 
  352: Programming Tools
  353: 
  354: * Debugging::                   Simple and quick.
  355: * Assertions::                  Making your programs self-checking.
  356: * Singlestep Debugger::         Executing your program word by word.
  357: 
  358: Assembler and Code Words
  359: 
  360: * Code and ;code::              
  361: * Common Assembler::            Assembler Syntax
  362: * Common Disassembler::         
  363: * 386 Assembler::               Deviations and special cases
  364: * Alpha Assembler::             Deviations and special cases
  365: * MIPS assembler::              Deviations and special cases
  366: * Other assemblers::            How to write them
  367: 
  368: Locals
  369: 
  370: * Gforth locals::               
  371: * ANS Forth locals::            
  372: 
  373: Gforth locals
  374: 
  375: * Where are locals visible by name?::  
  376: * How long do locals live?::    
  377: * Programming Style::           
  378: * Implementation::              
  379: 
  380: Structures
  381: 
  382: * Why explicit structure support?::  
  383: * Structure Usage::             
  384: * Structure Naming Convention::  
  385: * Structure Implementation::    
  386: * Structure Glossary::          
  387: 
  388: Object-oriented Forth
  389: 
  390: * Why object-oriented programming?::  
  391: * Object-Oriented Terminology::  
  392: * Objects::                     
  393: * OOF::                         
  394: * Mini-OOF::                    
  395: * Comparison with other object models::  
  396: 
  397: The @file{objects.fs} model
  398: 
  399: * Properties of the Objects model::  
  400: * Basic Objects Usage::         
  401: * The Objects base class::      
  402: * Creating objects::            
  403: * Object-Oriented Programming Style::  
  404: * Class Binding::               
  405: * Method conveniences::         
  406: * Classes and Scoping::         
  407: * Dividing classes::            
  408: * Object Interfaces::           
  409: * Objects Implementation::      
  410: * Objects Glossary::            
  411: 
  412: The @file{oof.fs} model
  413: 
  414: * Properties of the OOF model::  
  415: * Basic OOF Usage::             
  416: * The OOF base class::          
  417: * Class Declaration::           
  418: * Class Implementation::        
  419: 
  420: The @file{mini-oof.fs} model
  421: 
  422: * Basic Mini-OOF Usage::        
  423: * Mini-OOF Example::            
  424: * Mini-OOF Implementation::     
  425: 
  426: Tools
  427: 
  428: * ANS Report::                  Report the words used, sorted by wordset.
  429: 
  430: ANS conformance
  431: 
  432: * The Core Words::              
  433: * The optional Block word set::  
  434: * The optional Double Number word set::  
  435: * The optional Exception word set::  
  436: * The optional Facility word set::  
  437: * The optional File-Access word set::  
  438: * The optional Floating-Point word set::  
  439: * The optional Locals word set::  
  440: * The optional Memory-Allocation word set::  
  441: * The optional Programming-Tools word set::  
  442: * The optional Search-Order word set::  
  443: 
  444: The Core Words
  445: 
  446: * core-idef::                   Implementation Defined Options                   
  447: * core-ambcond::                Ambiguous Conditions                
  448: * core-other::                  Other System Documentation                  
  449: 
  450: The optional Block word set
  451: 
  452: * block-idef::                  Implementation Defined Options
  453: * block-ambcond::               Ambiguous Conditions               
  454: * block-other::                 Other System Documentation                 
  455: 
  456: The optional Double Number word set
  457: 
  458: * double-ambcond::              Ambiguous Conditions              
  459: 
  460: The optional Exception word set
  461: 
  462: * exception-idef::              Implementation Defined Options              
  463: 
  464: The optional Facility word set
  465: 
  466: * facility-idef::               Implementation Defined Options               
  467: * facility-ambcond::            Ambiguous Conditions            
  468: 
  469: The optional File-Access word set
  470: 
  471: * file-idef::                   Implementation Defined Options
  472: * file-ambcond::                Ambiguous Conditions                
  473: 
  474: The optional Floating-Point word set
  475: 
  476: * floating-idef::               Implementation Defined Options
  477: * floating-ambcond::            Ambiguous Conditions            
  478: 
  479: The optional Locals word set
  480: 
  481: * locals-idef::                 Implementation Defined Options                 
  482: * locals-ambcond::              Ambiguous Conditions              
  483: 
  484: The optional Memory-Allocation word set
  485: 
  486: * memory-idef::                 Implementation Defined Options                 
  487: 
  488: The optional Programming-Tools word set
  489: 
  490: * programming-idef::            Implementation Defined Options            
  491: * programming-ambcond::         Ambiguous Conditions         
  492: 
  493: The optional Search-Order word set
  494: 
  495: * search-idef::                 Implementation Defined Options                 
  496: * search-ambcond::              Ambiguous Conditions              
  497: 
  498: Image Files
  499: 
  500: * Image Licensing Issues::      Distribution terms for images.
  501: * Image File Background::       Why have image files?
  502: * Non-Relocatable Image Files::  don't always work.
  503: * Data-Relocatable Image Files::  are better.
  504: * Fully Relocatable Image Files::  better yet.
  505: * Stack and Dictionary Sizes::  Setting the default sizes for an image.
  506: * Running Image Files::         @code{gforth -i @i{file}} or @i{file}.
  507: * Modifying the Startup Sequence::  and turnkey applications.
  508: 
  509: Fully Relocatable Image Files
  510: 
  511: * gforthmi::                    The normal way
  512: * cross.fs::                    The hard way
  513: 
  514: Engine
  515: 
  516: * Portability::                 
  517: * Threading::                   
  518: * Primitives::                  
  519: * Performance::                 
  520: 
  521: Threading
  522: 
  523: * Scheduling::                  
  524: * Direct or Indirect Threaded?::  
  525: * DOES>::                       
  526: 
  527: Primitives
  528: 
  529: * Automatic Generation::        
  530: * TOS Optimization::            
  531: * Produced code::               
  532: 
  533: Cross Compiler
  534: 
  535: * Using the Cross Compiler::    
  536: * How the Cross Compiler Works::  
  537: 
  538: Other Forth-related information
  539: 
  540: * Internet resources::          
  541: * Books::                       
  542: * The Forth Interest Group::    
  543: * Conferences::                 
  544: 
  545: @end detailmenu
  546: @end menu
  547: 
  548: @node License, Goals, Top, Top
  549: @unnumbered GNU GENERAL PUBLIC LICENSE
  550: @center Version 2, June 1991
  551: 
  552: @display
  553: Copyright @copyright{} 1989, 1991 Free Software Foundation, Inc.
  554: 675 Mass Ave, Cambridge, MA 02139, USA
  555: 
  556: Everyone is permitted to copy and distribute verbatim copies
  557: of this license document, but changing it is not allowed.
  558: @end display
  559: 
  560: @unnumberedsec Preamble
  561: 
  562:   The licenses for most software are designed to take away your
  563: freedom to share and change it.  By contrast, the GNU General Public
  564: License is intended to guarantee your freedom to share and change free
  565: software---to make sure the software is free for all its users.  This
  566: General Public License applies to most of the Free Software
  567: Foundation's software and to any other program whose authors commit to
  568: using it.  (Some other Free Software Foundation software is covered by
  569: the GNU Library General Public License instead.)  You can apply it to
  570: your programs, too.
  571: 
  572:   When we speak of free software, we are referring to freedom, not
  573: price.  Our General Public Licenses are designed to make sure that you
  574: have the freedom to distribute copies of free software (and charge for
  575: this service if you wish), that you receive source code or can get it
  576: if you want it, that you can change the software or use pieces of it
  577: in new free programs; and that you know you can do these things.
  578: 
  579:   To protect your rights, we need to make restrictions that forbid
  580: anyone to deny you these rights or to ask you to surrender the rights.
  581: These restrictions translate to certain responsibilities for you if you
  582: distribute copies of the software, or if you modify it.
  583: 
  584:   For example, if you distribute copies of such a program, whether
  585: gratis or for a fee, you must give the recipients all the rights that
  586: you have.  You must make sure that they, too, receive or can get the
  587: source code.  And you must show them these terms so they know their
  588: rights.
  589: 
  590:   We protect your rights with two steps: (1) copyright the software, and
  591: (2) offer you this license which gives you legal permission to copy,
  592: distribute and/or modify the software.
  593: 
  594:   Also, for each author's protection and ours, we want to make certain
  595: that everyone understands that there is no warranty for this free
  596: software.  If the software is modified by someone else and passed on, we
  597: want its recipients to know that what they have is not the original, so
  598: that any problems introduced by others will not reflect on the original
  599: authors' reputations.
  600: 
  601:   Finally, any free program is threatened constantly by software
  602: patents.  We wish to avoid the danger that redistributors of a free
  603: program will individually obtain patent licenses, in effect making the
  604: program proprietary.  To prevent this, we have made it clear that any
  605: patent must be licensed for everyone's free use or not licensed at all.
  606: 
  607:   The precise terms and conditions for copying, distribution and
  608: modification follow.
  609: 
  610: @iftex
  611: @unnumberedsec TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
  612: @end iftex
  613: @ifnottex
  614: @center TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
  615: @end ifnottex
  616: 
  617: @enumerate 0
  618: @item
  619: This License applies to any program or other work which contains
  620: a notice placed by the copyright holder saying it may be distributed
  621: under the terms of this General Public License.  The ``Program'', below,
  622: refers to any such program or work, and a ``work based on the Program''
  623: means either the Program or any derivative work under copyright law:
  624: that is to say, a work containing the Program or a portion of it,
  625: either verbatim or with modifications and/or translated into another
  626: language.  (Hereinafter, translation is included without limitation in
  627: the term ``modification''.)  Each licensee is addressed as ``you''.
  628: 
  629: Activities other than copying, distribution and modification are not
  630: covered by this License; they are outside its scope.  The act of
  631: running the Program is not restricted, and the output from the Program
  632: is covered only if its contents constitute a work based on the
  633: Program (independent of having been made by running the Program).
  634: Whether that is true depends on what the Program does.
  635: 
  636: @item
  637: You may copy and distribute verbatim copies of the Program's
  638: source code as you receive it, in any medium, provided that you
  639: conspicuously and appropriately publish on each copy an appropriate
  640: copyright notice and disclaimer of warranty; keep intact all the
  641: notices that refer to this License and to the absence of any warranty;
  642: and give any other recipients of the Program a copy of this License
  643: along with the Program.
  644: 
  645: You may charge a fee for the physical act of transferring a copy, and
  646: you may at your option offer warranty protection in exchange for a fee.
  647: 
  648: @item
  649: You may modify your copy or copies of the Program or any portion
  650: of it, thus forming a work based on the Program, and copy and
  651: distribute such modifications or work under the terms of Section 1
  652: above, provided that you also meet all of these conditions:
  653: 
  654: @enumerate a
  655: @item
  656: You must cause the modified files to carry prominent notices
  657: stating that you changed the files and the date of any change.
  658: 
  659: @item
  660: You must cause any work that you distribute or publish, that in
  661: whole or in part contains or is derived from the Program or any
  662: part thereof, to be licensed as a whole at no charge to all third
  663: parties under the terms of this License.
  664: 
  665: @item
  666: If the modified program normally reads commands interactively
  667: when run, you must cause it, when started running for such
  668: interactive use in the most ordinary way, to print or display an
  669: announcement including an appropriate copyright notice and a
  670: notice that there is no warranty (or else, saying that you provide
  671: a warranty) and that users may redistribute the program under
  672: these conditions, and telling the user how to view a copy of this
  673: License.  (Exception: if the Program itself is interactive but
  674: does not normally print such an announcement, your work based on
  675: the Program is not required to print an announcement.)
  676: @end enumerate
  677: 
  678: These requirements apply to the modified work as a whole.  If
  679: identifiable sections of that work are not derived from the Program,
  680: and can be reasonably considered independent and separate works in
  681: themselves, then this License, and its terms, do not apply to those
  682: sections when you distribute them as separate works.  But when you
  683: distribute the same sections as part of a whole which is a work based
  684: on the Program, the distribution of the whole must be on the terms of
  685: this License, whose permissions for other licensees extend to the
  686: entire whole, and thus to each and every part regardless of who wrote it.
  687: 
  688: Thus, it is not the intent of this section to claim rights or contest
  689: your rights to work written entirely by you; rather, the intent is to
  690: exercise the right to control the distribution of derivative or
  691: collective works based on the Program.
  692: 
  693: In addition, mere aggregation of another work not based on the Program
  694: with the Program (or with a work based on the Program) on a volume of
  695: a storage or distribution medium does not bring the other work under
  696: the scope of this License.
  697: 
  698: @item
  699: You may copy and distribute the Program (or a work based on it,
  700: under Section 2) in object code or executable form under the terms of
  701: Sections 1 and 2 above provided that you also do one of the following:
  702: 
  703: @enumerate a
  704: @item
  705: Accompany it with the complete corresponding machine-readable
  706: source code, which must be distributed under the terms of Sections
  707: 1 and 2 above on a medium customarily used for software interchange; or,
  708: 
  709: @item
  710: Accompany it with a written offer, valid for at least three
  711: years, to give any third party, for a charge no more than your
  712: cost of physically performing source distribution, a complete
  713: machine-readable copy of the corresponding source code, to be
  714: distributed under the terms of Sections 1 and 2 above on a medium
  715: customarily used for software interchange; or,
  716: 
  717: @item
  718: Accompany it with the information you received as to the offer
  719: to distribute corresponding source code.  (This alternative is
  720: allowed only for noncommercial distribution and only if you
  721: received the program in object code or executable form with such
  722: an offer, in accord with Subsection b above.)
  723: @end enumerate
  724: 
  725: The source code for a work means the preferred form of the work for
  726: making modifications to it.  For an executable work, complete source
  727: code means all the source code for all modules it contains, plus any
  728: associated interface definition files, plus the scripts used to
  729: control compilation and installation of the executable.  However, as a
  730: special exception, the source code distributed need not include
  731: anything that is normally distributed (in either source or binary
  732: form) with the major components (compiler, kernel, and so on) of the
  733: operating system on which the executable runs, unless that component
  734: itself accompanies the executable.
  735: 
  736: If distribution of executable or object code is made by offering
  737: access to copy from a designated place, then offering equivalent
  738: access to copy the source code from the same place counts as
  739: distribution of the source code, even though third parties are not
  740: compelled to copy the source along with the object code.
  741: 
  742: @item
  743: You may not copy, modify, sublicense, or distribute the Program
  744: except as expressly provided under this License.  Any attempt
  745: otherwise to copy, modify, sublicense or distribute the Program is
  746: void, and will automatically terminate your rights under this License.
  747: However, parties who have received copies, or rights, from you under
  748: this License will not have their licenses terminated so long as such
  749: parties remain in full compliance.
  750: 
  751: @item
  752: You are not required to accept this License, since you have not
  753: signed it.  However, nothing else grants you permission to modify or
  754: distribute the Program or its derivative works.  These actions are
  755: prohibited by law if you do not accept this License.  Therefore, by
  756: modifying or distributing the Program (or any work based on the
  757: Program), you indicate your acceptance of this License to do so, and
  758: all its terms and conditions for copying, distributing or modifying
  759: the Program or works based on it.
  760: 
  761: @item
  762: Each time you redistribute the Program (or any work based on the
  763: Program), the recipient automatically receives a license from the
  764: original licensor to copy, distribute or modify the Program subject to
  765: these terms and conditions.  You may not impose any further
  766: restrictions on the recipients' exercise of the rights granted herein.
  767: You are not responsible for enforcing compliance by third parties to
  768: this License.
  769: 
  770: @item
  771: If, as a consequence of a court judgment or allegation of patent
  772: infringement or for any other reason (not limited to patent issues),
  773: conditions are imposed on you (whether by court order, agreement or
  774: otherwise) that contradict the conditions of this License, they do not
  775: excuse you from the conditions of this License.  If you cannot
  776: distribute so as to satisfy simultaneously your obligations under this
  777: License and any other pertinent obligations, then as a consequence you
  778: may not distribute the Program at all.  For example, if a patent
  779: license would not permit royalty-free redistribution of the Program by
  780: all those who receive copies directly or indirectly through you, then
  781: the only way you could satisfy both it and this License would be to
  782: refrain entirely from distribution of the Program.
  783: 
  784: If any portion of this section is held invalid or unenforceable under
  785: any particular circumstance, the balance of the section is intended to
  786: apply and the section as a whole is intended to apply in other
  787: circumstances.
  788: 
  789: It is not the purpose of this section to induce you to infringe any
  790: patents or other property right claims or to contest validity of any
  791: such claims; this section has the sole purpose of protecting the
  792: integrity of the free software distribution system, which is
  793: implemented by public license practices.  Many people have made
  794: generous contributions to the wide range of software distributed
  795: through that system in reliance on consistent application of that
  796: system; it is up to the author/donor to decide if he or she is willing
  797: to distribute software through any other system and a licensee cannot
  798: impose that choice.
  799: 
  800: This section is intended to make thoroughly clear what is believed to
  801: be a consequence of the rest of this License.
  802: 
  803: @item
  804: If the distribution and/or use of the Program is restricted in
  805: certain countries either by patents or by copyrighted interfaces, the
  806: original copyright holder who places the Program under this License
  807: may add an explicit geographical distribution limitation excluding
  808: those countries, so that distribution is permitted only in or among
  809: countries not thus excluded.  In such case, this License incorporates
  810: the limitation as if written in the body of this License.
  811: 
  812: @item
  813: The Free Software Foundation may publish revised and/or new versions
  814: of the General Public License from time to time.  Such new versions will
  815: be similar in spirit to the present version, but may differ in detail to
  816: address new problems or concerns.
  817: 
  818: Each version is given a distinguishing version number.  If the Program
  819: specifies a version number of this License which applies to it and ``any
  820: later version'', you have the option of following the terms and conditions
  821: either of that version or of any later version published by the Free
  822: Software Foundation.  If the Program does not specify a version number of
  823: this License, you may choose any version ever published by the Free Software
  824: Foundation.
  825: 
  826: @item
  827: If you wish to incorporate parts of the Program into other free
  828: programs whose distribution conditions are different, write to the author
  829: to ask for permission.  For software which is copyrighted by the Free
  830: Software Foundation, write to the Free Software Foundation; we sometimes
  831: make exceptions for this.  Our decision will be guided by the two goals
  832: of preserving the free status of all derivatives of our free software and
  833: of promoting the sharing and reuse of software generally.
  834: 
  835: @iftex
  836: @heading NO WARRANTY
  837: @end iftex
  838: @ifnottex
  839: @center NO WARRANTY
  840: @end ifnottex
  841: 
  842: @item
  843: BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
  844: FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN
  845: OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
  846: PROVIDE THE PROGRAM ``AS IS'' WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
  847: OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
  848: MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS
  849: TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE
  850: PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
  851: REPAIR OR CORRECTION.
  852: 
  853: @item
  854: IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
  855: WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
  856: REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
  857: INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
  858: OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
  859: TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
  860: YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
  861: PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
  862: POSSIBILITY OF SUCH DAMAGES.
  863: @end enumerate
  864: 
  865: @iftex
  866: @heading END OF TERMS AND CONDITIONS
  867: @end iftex
  868: @ifnottex
  869: @center END OF TERMS AND CONDITIONS
  870: @end ifnottex
  871: 
  872: @page
  873: @unnumberedsec How to Apply These Terms to Your New Programs
  874: 
  875:   If you develop a new program, and you want it to be of the greatest
  876: possible use to the public, the best way to achieve this is to make it
  877: free software which everyone can redistribute and change under these terms.
  878: 
  879:   To do so, attach the following notices to the program.  It is safest
  880: to attach them to the start of each source file to most effectively
  881: convey the exclusion of warranty; and each file should have at least
  882: the ``copyright'' line and a pointer to where the full notice is found.
  883: 
  884: @smallexample
  885: @var{one line to give the program's name and a brief idea of what it does.}
  886: Copyright (C) 19@var{yy}  @var{name of author}
  887: 
  888: This program is free software; you can redistribute it and/or modify 
  889: it under the terms of the GNU General Public License as published by 
  890: the Free Software Foundation; either version 2 of the License, or 
  891: (at your option) any later version.
  892: 
  893: This program is distributed in the hope that it will be useful,
  894: but WITHOUT ANY WARRANTY; without even the implied warranty of
  895: MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  896: GNU General Public License for more details.
  897: 
  898: You should have received a copy of the GNU General Public License
  899: along with this program; if not, write to the Free Software
  900: Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  901: @end smallexample
  902: 
  903: Also add information on how to contact you by electronic and paper mail.
  904: 
  905: If the program is interactive, make it output a short notice like this
  906: when it starts in an interactive mode:
  907: 
  908: @smallexample
  909: Gnomovision version 69, Copyright (C) 19@var{yy} @var{name of author}
  910: Gnomovision comes with ABSOLUTELY NO WARRANTY; for details
  911: type `show w'.  
  912: This is free software, and you are welcome to redistribute it 
  913: under certain conditions; type `show c' for details.
  914: @end smallexample
  915: 
  916: The hypothetical commands @samp{show w} and @samp{show c} should show
  917: the appropriate parts of the General Public License.  Of course, the
  918: commands you use may be called something other than @samp{show w} and
  919: @samp{show c}; they could even be mouse-clicks or menu items---whatever
  920: suits your program.
  921: 
  922: You should also get your employer (if you work as a programmer) or your
  923: school, if any, to sign a ``copyright disclaimer'' for the program, if
  924: necessary.  Here is a sample; alter the names:
  925: 
  926: @smallexample
  927: Yoyodyne, Inc., hereby disclaims all copyright interest in the program
  928: `Gnomovision' (which makes passes at compilers) written by James Hacker.
  929: 
  930: @var{signature of Ty Coon}, 1 April 1989
  931: Ty Coon, President of Vice
  932: @end smallexample
  933: 
  934: This General Public License does not permit incorporating your program into
  935: proprietary programs.  If your program is a subroutine library, you may
  936: consider it more useful to permit linking proprietary applications with the
  937: library.  If this is what you want to do, use the GNU Library General
  938: Public License instead of this License.
  939: 
  940: @iftex
  941: @unnumbered Preface
  942: @cindex Preface
  943: This manual documents Gforth. Some introductory material is provided for
  944: readers who are unfamiliar with Forth or who are migrating to Gforth
  945: from other Forth compilers. However, this manual is primarily a
  946: reference manual.
  947: @end iftex
  948: 
  949: @comment TODO much more blurb here.
  950: 
  951: @c ******************************************************************
  952: @node Goals, Gforth Environment, License, Top
  953: @comment node-name,     next,           previous, up
  954: @chapter Goals of Gforth
  955: @cindex goals of the Gforth project
  956: The goal of the Gforth Project is to develop a standard model for
  957: ANS Forth. This can be split into several subgoals:
  958: 
  959: @itemize @bullet
  960: @item
  961: Gforth should conform to the ANS Forth Standard.
  962: @item
  963: It should be a model, i.e. it should define all the
  964: implementation-dependent things.
  965: @item
  966: It should become standard, i.e. widely accepted and used. This goal
  967: is the most difficult one.
  968: @end itemize
  969: 
  970: To achieve these goals Gforth should be
  971: @itemize @bullet
  972: @item
  973: Similar to previous models (fig-Forth, F83)
  974: @item
  975: Powerful. It should provide for all the things that are considered
  976: necessary today and even some that are not yet considered necessary.
  977: @item
  978: Efficient. It should not get the reputation of being exceptionally
  979: slow.
  980: @item
  981: Free.
  982: @item
  983: Available on many machines/easy to port.
  984: @end itemize
  985: 
  986: Have we achieved these goals? Gforth conforms to the ANS Forth
  987: standard. It may be considered a model, but we have not yet documented
  988: which parts of the model are stable and which parts we are likely to
  989: change. It certainly has not yet become a de facto standard, but it
  990: appears to be quite popular. It has some similarities to and some
  991: differences from previous models. It has some powerful features, but not
  992: yet everything that we envisioned. We certainly have achieved our
  993: execution speed goals (@pxref{Performance})@footnote{However, in 1998
  994: the bar was raised when the major commercial Forth vendors switched to
  995: native code compilers.}.  It is free and available on many machines.
  996: 
  997: @c ******************************************************************
  998: @node Gforth Environment, Tutorial, Goals, Top
  999: @chapter Gforth Environment
 1000: @cindex Gforth environment
 1001: 
 1002: Note: ultimately, the Gforth man page will be auto-generated from the
 1003: material in this chapter.
 1004: 
 1005: @menu
 1006: * Invoking Gforth::             Getting in
 1007: * Leaving Gforth::              Getting out
 1008: * Command-line editing::        
 1009: * Environment variables::       that affect how Gforth starts up
 1010: * Gforth Files::                What gets installed and where
 1011: * Startup speed::               When 35ms is not fast enough ...
 1012: @end menu
 1013: 
 1014: For related information about the creation of images see @ref{Image Files}.
 1015: 
 1016: @comment ----------------------------------------------
 1017: @node Invoking Gforth, Leaving Gforth, Gforth Environment, Gforth Environment
 1018: @section Invoking Gforth
 1019: @cindex invoking Gforth
 1020: @cindex running Gforth
 1021: @cindex command-line options
 1022: @cindex options on the command line
 1023: @cindex flags on the command line
 1024: 
 1025: Gforth is made up of two parts; an executable ``engine'' (named
 1026: @file{gforth} or @file{gforth-fast}) and an image file. To start it, you
 1027: will usually just say @code{gforth} -- this automatically loads the
 1028: default image file @file{gforth.fi}. In many other cases the default
 1029: Gforth image will be invoked like this:
 1030: @example
 1031: gforth [file | -e forth-code] ...
 1032: @end example
 1033: @noindent
 1034: This interprets the contents of the files and the Forth code in the order they
 1035: are given.
 1036: 
 1037: In addition to the @file{gforth} engine, there is also an engine called
 1038: @file{gforth-fast}, which is faster, but gives less informative error
 1039: messages (@pxref{Error messages}).
 1040: 
 1041: In general, the command line looks like this:
 1042: 
 1043: @example
 1044: gforth[-fast] [engine options] [image options]
 1045: @end example
 1046: 
 1047: The engine options must come before the rest of the command
 1048: line. They are:
 1049: 
 1050: @table @code
 1051: @cindex -i, command-line option
 1052: @cindex --image-file, command-line option
 1053: @item --image-file @i{file}
 1054: @itemx -i @i{file}
 1055: Loads the Forth image @i{file} instead of the default
 1056: @file{gforth.fi} (@pxref{Image Files}).
 1057: 
 1058: @cindex --appl-image, command-line option
 1059: @item --appl-image @i{file}
 1060: Loads the image @i{file} and leaves all further command-line arguments
 1061: to the image (instead of processing them as engine options).  This is
 1062: useful for building executable application images on Unix, built with
 1063: @code{gforthmi --application ...}.
 1064: 
 1065: @cindex --path, command-line option
 1066: @cindex -p, command-line option
 1067: @item --path @i{path}
 1068: @itemx -p @i{path}
 1069: Uses @i{path} for searching the image file and Forth source code files
 1070: instead of the default in the environment variable @code{GFORTHPATH} or
 1071: the path specified at installation time (e.g.,
 1072: @file{/usr/local/share/gforth/0.2.0:.}). A path is given as a list of
 1073: directories, separated by @samp{:} (on Unix) or @samp{;} (on other OSs).
 1074: 
 1075: @cindex --dictionary-size, command-line option
 1076: @cindex -m, command-line option
 1077: @cindex @i{size} parameters for command-line options
 1078: @cindex size of the dictionary and the stacks
 1079: @item --dictionary-size @i{size}
 1080: @itemx -m @i{size}
 1081: Allocate @i{size} space for the Forth dictionary space instead of
 1082: using the default specified in the image (typically 256K). The
 1083: @i{size} specification for this and subsequent options consists of
 1084: an integer and a unit (e.g.,
 1085: @code{4M}). The unit can be one of @code{b} (bytes), @code{e} (element
 1086: size, in this case Cells), @code{k} (kilobytes), @code{M} (Megabytes),
 1087: @code{G} (Gigabytes), and @code{T} (Terabytes). If no unit is specified,
 1088: @code{e} is used.
 1089: 
 1090: @cindex --data-stack-size, command-line option
 1091: @cindex -d, command-line option
 1092: @item --data-stack-size @i{size}
 1093: @itemx -d @i{size}
 1094: Allocate @i{size} space for the data stack instead of using the
 1095: default specified in the image (typically 16K).
 1096: 
 1097: @cindex --return-stack-size, command-line option
 1098: @cindex -r, command-line option
 1099: @item --return-stack-size @i{size}
 1100: @itemx -r @i{size}
 1101: Allocate @i{size} space for the return stack instead of using the
 1102: default specified in the image (typically 15K).
 1103: 
 1104: @cindex --fp-stack-size, command-line option
 1105: @cindex -f, command-line option
 1106: @item --fp-stack-size @i{size}
 1107: @itemx -f @i{size}
 1108: Allocate @i{size} space for the floating point stack instead of
 1109: using the default specified in the image (typically 15.5K). In this case
 1110: the unit specifier @code{e} refers to floating point numbers.
 1111: 
 1112: @cindex --locals-stack-size, command-line option
 1113: @cindex -l, command-line option
 1114: @item --locals-stack-size @i{size}
 1115: @itemx -l @i{size}
 1116: Allocate @i{size} space for the locals stack instead of using the
 1117: default specified in the image (typically 14.5K).
 1118: 
 1119: @cindex -h, command-line option
 1120: @cindex --help, command-line option
 1121: @item --help
 1122: @itemx -h
 1123: Print a message about the command-line options
 1124: 
 1125: @cindex -v, command-line option
 1126: @cindex --version, command-line option
 1127: @item --version
 1128: @itemx -v
 1129: Print version and exit
 1130: 
 1131: @cindex --debug, command-line option
 1132: @item --debug
 1133: Print some information useful for debugging on startup.
 1134: 
 1135: @cindex --offset-image, command-line option
 1136: @item --offset-image
 1137: Start the dictionary at a slightly different position than would be used
 1138: otherwise (useful for creating data-relocatable images,
 1139: @pxref{Data-Relocatable Image Files}).
 1140: 
 1141: @cindex --no-offset-im, command-line option
 1142: @item --no-offset-im
 1143: Start the dictionary at the normal position.
 1144: 
 1145: @cindex --clear-dictionary, command-line option
 1146: @item --clear-dictionary
 1147: Initialize all bytes in the dictionary to 0 before loading the image
 1148: (@pxref{Data-Relocatable Image Files}).
 1149: 
 1150: @cindex --die-on-signal, command-line-option
 1151: @item --die-on-signal
 1152: Normally Gforth handles most signals (e.g., the user interrupt SIGINT,
 1153: or the segmentation violation SIGSEGV) by translating it into a Forth
 1154: @code{THROW}. With this option, Gforth exits if it receives such a
 1155: signal. This option is useful when the engine and/or the image might be
 1156: severely broken (such that it causes another signal before recovering
 1157: from the first); this option avoids endless loops in such cases.
 1158: @end table
 1159: 
 1160: @cindex loading files at startup
 1161: @cindex executing code on startup
 1162: @cindex batch processing with Gforth
 1163: As explained above, the image-specific command-line arguments for the
 1164: default image @file{gforth.fi} consist of a sequence of filenames and
 1165: @code{-e @var{forth-code}} options that are interpreted in the sequence
 1166: in which they are given. The @code{-e @var{forth-code}} or
 1167: @code{--evaluate @var{forth-code}} option evaluates the Forth
 1168: code. This option takes only one argument; if you want to evaluate more
 1169: Forth words, you have to quote them or use @code{-e} several times. To exit
 1170: after processing the command line (instead of entering interactive mode)
 1171: append @code{-e bye} to the command line.
 1172: 
 1173: @cindex versions, invoking other versions of Gforth
 1174: If you have several versions of Gforth installed, @code{gforth} will
 1175: invoke the version that was installed last. @code{gforth-@i{version}}
 1176: invokes a specific version. If your environment contains the variable
 1177: @code{GFORTHPATH}, you may want to override it by using the
 1178: @code{--path} option.
 1179: 
 1180: Not yet implemented:
 1181: On startup the system first executes the system initialization file
 1182: (unless the option @code{--no-init-file} is given; note that the system
 1183: resulting from using this option may not be ANS Forth conformant). Then
 1184: the user initialization file @file{.gforth.fs} is executed, unless the
 1185: option @code{--no-rc} is given; this file is searched for in @file{.},
 1186: then in @file{~}, then in the normal path (see above).
 1187: 
 1188: 
 1189: 
 1190: @comment ----------------------------------------------
 1191: @node Leaving Gforth, Command-line editing, Invoking Gforth, Gforth Environment
 1192: @section Leaving Gforth
 1193: @cindex Gforth - leaving
 1194: @cindex leaving Gforth
 1195: 
 1196: You can leave Gforth by typing @code{bye} or @kbd{Ctrl-d} (at the start
 1197: of a line) or (if you invoked Gforth with the @code{--die-on-signal}
 1198: option) @kbd{Ctrl-c}. When you leave Gforth, all of your definitions and
 1199: data are discarded.  For ways of saving the state of the system before
 1200: leaving Gforth see @ref{Image Files}.
 1201: 
 1202: doc-bye
 1203: 
 1204: 
 1205: @comment ----------------------------------------------
 1206: @node Command-line editing, Environment variables, Leaving Gforth, Gforth Environment
 1207: @section Command-line editing
 1208: @cindex command-line editing
 1209: 
 1210: Gforth maintains a history file that records every line that you type to
 1211: the text interpreter. This file is preserved between sessions, and is
 1212: used to provide a command-line recall facility; if you type @kbd{Ctrl-P}
 1213: repeatedly you can recall successively older commands from this (or
 1214: previous) session(s). The full list of command-line editing facilities is:
 1215: 
 1216: @itemize @bullet
 1217: @item
 1218: @kbd{Ctrl-p} (``previous'') (or up-arrow) to recall successively older
 1219: commands from the history buffer.
 1220: @item
 1221: @kbd{Ctrl-n} (``next'') (or down-arrow) to recall successively newer commands
 1222: from the history buffer.
 1223: @item
 1224: @kbd{Ctrl-f} (or right-arrow) to move the cursor right, non-destructively.
 1225: @item
 1226: @kbd{Ctrl-b} (or left-arrow) to move the cursor left, non-destructively.
 1227: @item
 1228: @kbd{Ctrl-h} (backspace) to delete the character to the left of the cursor,
 1229: closing up the line.
 1230: @item
 1231: @kbd{Ctrl-k} to delete (``kill'') from the cursor to the end of the line.
 1232: @item
 1233: @kbd{Ctrl-a} to move the cursor to the start of the line.
 1234: @item
 1235: @kbd{Ctrl-e} to move the cursor to the end of the line.
 1236: @item
 1237: @key{RET} (@kbd{Ctrl-m}) or @key{LFD} (@kbd{Ctrl-j}) to submit the current
 1238: line.
 1239: @item
 1240: @key{TAB} to step through all possible full-word completions of the word
 1241: currently being typed.
 1242: @item
 1243: @kbd{Ctrl-d} on an empty line line to terminate Gforth (gracefully,
 1244: using @code{bye}). 
 1245: @item
 1246: @kbd{Ctrl-x} (or @code{Ctrl-d} on a non-empty line) to delete the
 1247: character under the cursor.
 1248: @end itemize
 1249: 
 1250: When editing, displayable characters are inserted to the left of the
 1251: cursor position; the line is always in ``insert'' (as opposed to
 1252: ``overstrike'') mode.
 1253: 
 1254: @cindex history file
 1255: @cindex @file{.gforth-history}
 1256: On Unix systems, the history file is @file{~/.gforth-history} by
 1257: default@footnote{i.e. it is stored in the user's home directory.}. You
 1258: can find out the name and location of your history file using:
 1259: 
 1260: @example 
 1261: history-file type \ Unix-class systems
 1262: 
 1263: history-file type \ Other systems
 1264: history-dir  type
 1265: @end example
 1266: 
 1267: If you enter long definitions by hand, you can use a text editor to
 1268: paste them out of the history file into a Forth source file for reuse at
 1269: a later time.
 1270: 
 1271: Gforth never trims the size of the history file, so you should do this
 1272: periodically, if necessary.
 1273: 
 1274: @comment this is all defined in history.fs
 1275: @comment NAC TODO the ctrl-D behaviour can either do a bye or a beep.. how is that option
 1276: @comment chosen?
 1277: 
 1278: 
 1279: @comment ----------------------------------------------
 1280: @node Environment variables, Gforth Files, Command-line editing, Gforth Environment
 1281: @section Environment variables
 1282: @cindex environment variables
 1283: 
 1284: Gforth uses these environment variables:
 1285: 
 1286: @itemize @bullet
 1287: @item
 1288: @cindex @code{GFORTHHIST} -- environment variable
 1289: @code{GFORTHHIST} -- (Unix systems only) specifies the directory in which to
 1290: open/create the history file, @file{.gforth-history}. Default:
 1291: @code{$HOME}.
 1292: 
 1293: @item
 1294: @cindex @code{GFORTHPATH} -- environment variable
 1295: @code{GFORTHPATH} -- specifies the path used when searching for the gforth image file and
 1296: for Forth source-code files.
 1297: 
 1298: @item
 1299: @cindex @code{GFORTH} -- environment variable
 1300: @code{GFORTH} -- used by @file{gforthmi}, @xref{gforthmi}.
 1301: 
 1302: @item
 1303: @cindex @code{GFORTHD} -- environment variable
 1304: @code{GFORTHD} -- used by @file{gforthmi}, @xref{gforthmi}.
 1305: 
 1306: @item
 1307: @cindex @code{TMP}, @code{TEMP} - environment variable
 1308: @code{TMP}, @code{TEMP} - (non-Unix systems only) used as a potential
 1309: location for the history file.
 1310: @end itemize
 1311: 
 1312: @comment also POSIXELY_CORRECT LINES COLUMNS HOME but no interest in
 1313: @comment mentioning these.
 1314: 
 1315: All the Gforth environment variables default to sensible values if they
 1316: are not set.
 1317: 
 1318: 
 1319: @comment ----------------------------------------------
 1320: @node Gforth Files, Startup speed, Environment variables, Gforth Environment
 1321: @section Gforth files
 1322: @cindex Gforth files
 1323: 
 1324: When you install Gforth on a Unix system, it installs files in these
 1325: locations by default:
 1326: 
 1327: @itemize @bullet
 1328: @item
 1329: @file{/usr/local/bin/gforth}
 1330: @item
 1331: @file{/usr/local/bin/gforthmi}
 1332: @item
 1333: @file{/usr/local/man/man1/gforth.1} - man page.
 1334: @item
 1335: @file{/usr/local/info} - the Info version of this manual.
 1336: @item
 1337: @file{/usr/local/lib/gforth/<version>/...} - Gforth @file{.fi} files.
 1338: @item
 1339: @file{/usr/local/share/gforth/<version>/TAGS} - Emacs TAGS file.
 1340: @item
 1341: @file{/usr/local/share/gforth/<version>/...} - Gforth source files.
 1342: @item
 1343: @file{.../emacs/site-lisp/gforth.el} - Emacs gforth mode.
 1344: @end itemize
 1345: 
 1346: You can select different places for installation by using
 1347: @code{configure} options (listed with @code{configure --help}).
 1348: 
 1349: @comment ----------------------------------------------
 1350: @node Startup speed,  , Gforth Files, Gforth Environment
 1351: @section Startup speed
 1352: @cindex Startup speed
 1353: @cindex speed, startup
 1354: 
 1355: If Gforth is used for CGI scripts or in shell scripts, its startup
 1356: speed may become a problem.  On a 300MHz 21064a under Linux-2.2.13 with
 1357: glibc-2.0.7, @code{gforth -e bye} takes about 24.6ms user and 11.3ms
 1358: system time.
 1359: 
 1360: If startup speed is a problem, you may consider the following ways to
 1361: improve it; or you may consider ways to reduce the number of startups
 1362: (for example, by using Fast-CGI).
 1363: 
 1364: The first step to improve startup speed is to statically link Gforth, by
 1365: building it with @code{XLDFLAGS=-static}.  This requires more memory for
 1366: the code and will therefore slow down the first invocation, but
 1367: subsequent invocations avoid the dynamic linking overhead.  Another
 1368: disadvantage is that Gforth won't profit from library upgrades.  As a
 1369: result, @code{gforth-static -e bye} takes about 17.1ms user and
 1370: 8.2ms system time.
 1371: 
 1372: The next step to improve startup speed is to use a non-relocatable image
 1373: (@pxref{Non-Relocatable Image Files}).  You can create this image with
 1374: @code{gforth -e "savesystem gforthnr.fi bye"} and later use it with
 1375: @code{gforth -i gforthnr.fi ...}.  This avoids the relocation overhead
 1376: and a part of the copy-on-write overhead.  The disadvantage is that the
 1377: non-relocatable image does not work if the OS gives Gforth a different
 1378: address for the dictionary, for whatever reason; so you better provide a
 1379: fallback on a relocatable image.  @code{gforth-static -i gforthnr.fi -e
 1380: bye} takes about 15.3ms user and 7.5ms system time.
 1381: 
 1382: The final step is to disable dictionary hashing in Gforth.  Gforth
 1383: builds the hash table on startup, which takes much of the startup
 1384: overhead. You can do this by commenting out the @code{include hash.fs}
 1385: in @file{startup.fs} and everything that requires @file{hash.fs} (at the
 1386: moment @file{table.fs} and @file{ekey.fs}) and then doing @code{make}.
 1387: The disadvantages are that functionality like @code{table} and
 1388: @code{ekey} is missing and that text interpretation (e.g., compiling)
 1389: now takes much longer. So, you should only use this method if there is
 1390: no significant text interpretation to perform (the script should be
 1391: compiled into the image, amongst other things).  @code{gforth-static -i
 1392: gforthnrnh.fi -e bye} takes about 2.1ms user and 6.1ms system time.
 1393: 
 1394: @c ******************************************************************
 1395: @node Tutorial, Introduction, Gforth Environment, Top
 1396: @chapter Forth Tutorial
 1397: @cindex Tutorial
 1398: @cindex Forth Tutorial
 1399: 
 1400: @c Topics from nac's Introduction that could be mentioned:
 1401: @c press <ret> after each line
 1402: @c Prompt
 1403: @c numbers vs. words in dictionary on text interpretation
 1404: @c what happens on redefinition
 1405: @c parsing words (in particular, defining words)
 1406: 
 1407: This tutorial can be used with any ANS-compliant Forth; any
 1408: Gforth-specific features are marked as such and you can skip them if you
 1409: work with another Forth.  This tutorial does not explain all features of
 1410: Forth, just enough to get you started and give you some ideas about the
 1411: facilities available in Forth.  Read the rest of the manual and the
 1412: standard when you are through this.
 1413: 
 1414: The intended way to use this tutorial is that you work through it while
 1415: sitting in front of the console, take a look at the examples and predict
 1416: what they will do, then try them out; if the outcome is not as expected,
 1417: find out why (e.g., by trying out variations of the example), so you
 1418: understand what's going on.  There are also some assignments that you
 1419: should solve.
 1420: 
 1421: This tutorial assumes that you have programmed before and know what,
 1422: e.g., a loop is.
 1423: 
 1424: @c !! explain compat library
 1425: 
 1426: @menu
 1427: * Starting Gforth Tutorial::    
 1428: * Syntax Tutorial::             
 1429: * Crash Course Tutorial::       
 1430: * Stack Tutorial::              
 1431: * Arithmetics Tutorial::        
 1432: * Stack Manipulation Tutorial::  
 1433: * Using files for Forth code Tutorial::  
 1434: * Comments Tutorial::           
 1435: * Colon Definitions Tutorial::  
 1436: * Decompilation Tutorial::      
 1437: * Stack-Effect Comments Tutorial::  
 1438: * Types Tutorial::              
 1439: * Factoring Tutorial::          
 1440: * Designing the stack effect Tutorial::  
 1441: * Local Variables Tutorial::    
 1442: * Conditional execution Tutorial::  
 1443: * Flags and Comparisons Tutorial::  
 1444: * General Loops Tutorial::      
 1445: * Counted loops Tutorial::      
 1446: * Recursion Tutorial::          
 1447: * Leaving definitions or loops Tutorial::  
 1448: * Return Stack Tutorial::       
 1449: * Memory Tutorial::             
 1450: * Characters and Strings Tutorial::  
 1451: * Alignment Tutorial::          
 1452: * Interpretation and Compilation Semantics and Immediacy Tutorial::  
 1453: * Execution Tokens Tutorial::   
 1454: * Exceptions Tutorial::         
 1455: * Defining Words Tutorial::     
 1456: * Arrays and Records Tutorial::  
 1457: * POSTPONE Tutorial::           
 1458: * Literal Tutorial::            
 1459: * Advanced macros Tutorial::    
 1460: * Compilation Tokens Tutorial::  
 1461: * Wordlists and Search Order Tutorial::  
 1462: @end menu
 1463: 
 1464: @node Starting Gforth Tutorial, Syntax Tutorial, Tutorial, Tutorial
 1465: @section Starting Gforth
 1466: @cindex starting Gforth tutorial
 1467: You can start Gforth by typing its name:
 1468: 
 1469: @example
 1470: gforth
 1471: @end example
 1472: 
 1473: That puts you into interactive mode; you can leave Gforth by typing
 1474: @code{bye}.  While in Gforth, you can edit the command line and access
 1475: the command line history with cursor keys, similar to bash.
 1476: 
 1477: 
 1478: @node Syntax Tutorial, Crash Course Tutorial, Starting Gforth Tutorial, Tutorial
 1479: @section Syntax
 1480: @cindex syntax tutorial
 1481: 
 1482: A @dfn{word} is a sequence of arbitrary characters (expcept white
 1483: space).  Words are separated by white space.  E.g., each of the
 1484: following lines contains exactly one word:
 1485: 
 1486: @example
 1487: word
 1488: !@@#$%^&*()
 1489: 1234567890
 1490: 5!a
 1491: @end example
 1492: 
 1493: A frequent beginner's error is to leave away necessary white space,
 1494: resulting in an error like @samp{Undefined word}; so if you see such an
 1495: error, check if you have put spaces wherever necessary.
 1496: 
 1497: @example
 1498: ." hello, world" \ correct
 1499: ."hello, world"  \ gives an "Undefined word" error
 1500: @end example
 1501: 
 1502: Gforth and most other Forth systems ignore differences in case (they are
 1503: case-insensitive), i.e., @samp{word} is the same as @samp{Word}.  If
 1504: your system is case-sensitive, you may have to type all the examples
 1505: given here in upper case.
 1506: 
 1507: 
 1508: @node Crash Course Tutorial, Stack Tutorial, Syntax Tutorial, Tutorial
 1509: @section Crash Course
 1510: 
 1511: Type
 1512: 
 1513: @example
 1514: 0 0 !
 1515: here execute
 1516: ' catch >body 20 erase abort
 1517: ' (quit) >body 20 erase
 1518: @end example
 1519: 
 1520: The last two examples are guaranteed to destroy parts of Gforth (and
 1521: most other systems), so you better leave Gforth afterwards (if it has
 1522: not finished by itself).  On some systems you may have to kill gforth
 1523: from outside (e.g., in Unix with @code{kill}).
 1524: 
 1525: Now that you know how to produce crashes (and that there's not much to
 1526: them), let's learn how to produce meaningful programs.
 1527: 
 1528: 
 1529: @node Stack Tutorial, Arithmetics Tutorial, Crash Course Tutorial, Tutorial
 1530: @section Stack
 1531: @cindex stack tutorial
 1532: 
 1533: The most obvious feature of Forth is the stack.  When you type in a
 1534: number, it is pushed on the stack.  You can display the content of the
 1535: stack with @code{.s}.
 1536: 
 1537: @example
 1538: 1 2 .s
 1539: 3 .s
 1540: @end example
 1541: 
 1542: @code{.s} displays the top-of-stack to the right, i.e., the numbers
 1543: appear in @code{.s} output as they appeared in the input.
 1544: 
 1545: You can print the top of stack element with @code{.}.
 1546: 
 1547: @example
 1548: 1 2 3 . . .
 1549: @end example
 1550: 
 1551: In general, words consume their stack arguments (@code{.s} is an
 1552: exception).
 1553: 
 1554: @assignment
 1555: What does the stack contain after @code{5 6 7 .}?
 1556: @endassignment
 1557: 
 1558: 
 1559: @node Arithmetics Tutorial, Stack Manipulation Tutorial, Stack Tutorial, Tutorial
 1560: @section Arithmetics
 1561: @cindex arithmetics tutorial
 1562: 
 1563: The words @code{+}, @code{-}, @code{*}, @code{/}, and @code{mod} always
 1564: operate on the top two stack items:
 1565: 
 1566: @example
 1567: 2 2 .s
 1568: + .s
 1569: .
 1570: 2 1 - .
 1571: 7 3 mod .
 1572: @end example
 1573: 
 1574: The operands of @code{-}, @code{/}, and @code{mod} are in the same order
 1575: as in the corresponding infix expression (this is generally the case in
 1576: Forth).
 1577: 
 1578: Parentheses are superfluous (and not available), because the order of
 1579: the words unambiguously determines the order of evaluation and the
 1580: operands:
 1581: 
 1582: @example
 1583: 3 4 + 5 * .
 1584: 3 4 5 * + .
 1585: @end example
 1586: 
 1587: @assignment
 1588: What are the infix expressions corresponding to the Forth code above?
 1589: Write @code{6-7*8+9} in Forth notation@footnote{This notation is also
 1590: known as Postfix or RPN (Reverse Polish Notation).}.
 1591: @endassignment
 1592: 
 1593: To change the sign, use @code{negate}:
 1594: 
 1595: @example
 1596: 2 negate .
 1597: @end example
 1598: 
 1599: @assignment
 1600: Convert -(-3)*4-5 to Forth.
 1601: @endassignment
 1602: 
 1603: @code{/mod} performs both @code{/} and @code{mod}.
 1604: 
 1605: @example
 1606: 7 3 /mod . .
 1607: @end example
 1608: 
 1609: Reference: @ref{Arithmetic}.
 1610: 
 1611: 
 1612: @node Stack Manipulation Tutorial, Using files for Forth code Tutorial, Arithmetics Tutorial, Tutorial
 1613: @section Stack Manipulation
 1614: @cindex stack manipulation tutorial
 1615: 
 1616: Stack manipulation words rearrange the data on the stack.
 1617: 
 1618: @example
 1619: 1 .s drop .s
 1620: 1 .s dup .s drop drop .s
 1621: 1 2 .s over .s drop drop drop
 1622: 1 2 .s swap .s drop drop
 1623: 1 2 3 .s rot .s drop drop drop
 1624: @end example
 1625: 
 1626: These are the most important stack manipulation words.  There are also
 1627: variants that manipulate twice as many stack items:
 1628: 
 1629: @example
 1630: 1 2 3 4 .s 2swap .s 2drop 2drop
 1631: @end example
 1632: 
 1633: Two more stack manipulation words are:
 1634: 
 1635: @example
 1636: 1 2 .s nip .s drop
 1637: 1 2 .s tuck .s 2drop drop
 1638: @end example
 1639: 
 1640: @assignment
 1641: Replace @code{nip} and @code{tuck} with combinations of other stack
 1642: manipulation words.
 1643: 
 1644: @example
 1645: Given:          How do you get:
 1646: 1 2 3           3 2 1           
 1647: 1 2 3           1 2 3 2                 
 1648: 1 2 3           1 2 3 3                 
 1649: 1 2 3           1 3 3           
 1650: 1 2 3           2 1 3           
 1651: 1 2 3 4         4 3 2 1         
 1652: 1 2 3           1 2 3 1 2 3             
 1653: 1 2 3 4         1 2 3 4 1 2             
 1654: 1 2 3
 1655: 1 2 3           1 2 3 4                 
 1656: 1 2 3           1 3             
 1657: @end example
 1658: @endassignment
 1659: 
 1660: @example
 1661: 5 dup * .
 1662: @end example
 1663: 
 1664: @assignment
 1665: Write 17^3 and 17^4 in Forth, without writing @code{17} more than once.
 1666: Write a piece of Forth code that expects two numbers on the stack
 1667: (@var{a} and @var{b}, with @var{b} on top) and computes
 1668: @code{(a-b)(a+1)}.
 1669: @endassignment
 1670: 
 1671: Reference: @ref{Stack Manipulation}.
 1672: 
 1673: 
 1674: @node Using files for Forth code Tutorial, Comments Tutorial, Stack Manipulation Tutorial, Tutorial
 1675: @section Using files for Forth code
 1676: @cindex loading Forth code, tutorial
 1677: @cindex files containing Forth code, tutorial
 1678: 
 1679: While working at the Forth command line is convenient for one-line
 1680: examples and short one-off code, you probably want to store your source
 1681: code in files for convenient editing and persistence.  You can use your
 1682: favourite editor (Gforth includes Emacs support, @pxref{Emacs and
 1683: Gforth}) to create @var{file} and use
 1684: 
 1685: @example
 1686: s" @var{file}" included
 1687: @end example
 1688: 
 1689: to load it into your Forth system.  The file name extension I use for
 1690: Forth files is @samp{.fs}.
 1691: 
 1692: You can easily start Gforth with some files loaded like this:
 1693: 
 1694: @example
 1695: gforth @var{file1} @var{file2}
 1696: @end example
 1697: 
 1698: If an error occurs during loading these files, Gforth terminates,
 1699: whereas an error during @code{INCLUDED} within Gforth usually gives you
 1700: a Gforth command line.  Starting the Forth system every time gives you a
 1701: clean start every time, without interference from the results of earlier
 1702: tries.
 1703: 
 1704: I often put all the tests in a file, then load the code and run the
 1705: tests with
 1706: 
 1707: @example
 1708: gforth @var{code} @var{tests} -e bye
 1709: @end example
 1710: 
 1711: (often by performing this command with @kbd{C-x C-e} in Emacs).  The
 1712: @code{-e bye} ensures that Gforth terminates afterwards so that I can
 1713: restart this command without ado.
 1714: 
 1715: The advantage of this approach is that the tests can be repeated easily
 1716: every time the program ist changed, making it easy to catch bugs
 1717: introduced by the change.
 1718: 
 1719: Reference: @ref{Forth source files}.
 1720: 
 1721: 
 1722: @node Comments Tutorial, Colon Definitions Tutorial, Using files for Forth code Tutorial, Tutorial
 1723: @section Comments
 1724: @cindex comments tutorial
 1725: 
 1726: @example
 1727: \ That's a comment; it ends at the end of the line
 1728: ( Another comment; it ends here: )  .s
 1729: @end example
 1730: 
 1731: @code{\} and @code{(} are ordinary Forth words and therefore have to be
 1732: separated with white space from the following text.
 1733: 
 1734: @example
 1735: \This gives an "Undefined word" error
 1736: @end example
 1737: 
 1738: The first @code{)} ends a comment started with @code{(}, so you cannot
 1739: nest @code{(}-comments; and you cannot comment out text containing a
 1740: @code{)} with @code{( ... )}@footnote{therefore it's a good idea to
 1741: avoid @code{)} in word names.}.
 1742: 
 1743: I use @code{\}-comments for descriptive text and for commenting out code
 1744: of one or more line; I use @code{(}-comments for describing the stack
 1745: effect, the stack contents, or for commenting out sub-line pieces of
 1746: code.
 1747: 
 1748: The Emacs mode @file{gforth.el} (@pxref{Emacs and Gforth}) supports
 1749: these uses by commenting out a region with @kbd{C-x \}, uncommenting a
 1750: region with @kbd{C-u C-x \}, and filling a @code{\}-commented region
 1751: with @kbd{M-q}.
 1752: 
 1753: Reference: @ref{Comments}.
 1754: 
 1755: 
 1756: @node Colon Definitions Tutorial, Decompilation Tutorial, Comments Tutorial, Tutorial
 1757: @section Colon Definitions
 1758: @cindex colon definitions, tutorial
 1759: @cindex definitions, tutorial
 1760: @cindex procedures, tutorial
 1761: @cindex functions, tutorial
 1762: 
 1763: are similar to procedures and functions in other programming languages.
 1764: 
 1765: @example
 1766: : squared ( n -- n^2 )
 1767:    dup * ;
 1768: 5 squared .
 1769: 7 squared .
 1770: @end example
 1771: 
 1772: @code{:} starts the colon definition; its name is @code{squared}.  The
 1773: following comment describes its stack effect.  The words @code{dup *}
 1774: are not executed, but compiled into the definition.  @code{;} ends the
 1775: colon definition.
 1776: 
 1777: The newly-defined word can be used like any other word, including using
 1778: it in other definitions:
 1779: 
 1780: @example
 1781: : cubed ( n -- n^3 )
 1782:    dup squared * ;
 1783: -5 cubed .
 1784: : fourth-power ( n -- n^4 )
 1785:    squared squared ;
 1786: 3 fourth-power .
 1787: @end example
 1788: 
 1789: @assignment
 1790: Write colon definitions for @code{nip}, @code{tuck}, @code{negate}, and
 1791: @code{/mod} in terms of other Forth words, and check if they work (hint:
 1792: test your tests on the originals first).  Don't let the
 1793: @samp{redefined}-Messages spook you, they are just warnings.
 1794: @endassignment
 1795: 
 1796: Reference: @ref{Colon Definitions}.
 1797: 
 1798: 
 1799: @node Decompilation Tutorial, Stack-Effect Comments Tutorial, Colon Definitions Tutorial, Tutorial
 1800: @section Decompilation
 1801: @cindex decompilation tutorial
 1802: @cindex see tutorial
 1803: 
 1804: You can decompile colon definitions with @code{see}:
 1805: 
 1806: @example
 1807: see squared
 1808: see cubed
 1809: @end example
 1810: 
 1811: In Gforth @code{see} shows you a reconstruction of the source code from
 1812: the executable code.  Informations that were present in the source, but
 1813: not in the executable code, are lost (e.g., comments).
 1814: 
 1815: You can also decompile the predefined words:
 1816: 
 1817: @example
 1818: see .
 1819: see +
 1820: @end example
 1821: 
 1822: 
 1823: @node Stack-Effect Comments Tutorial, Types Tutorial, Decompilation Tutorial, Tutorial
 1824: @section Stack-Effect Comments
 1825: @cindex stack-effect comments, tutorial
 1826: @cindex --, tutorial
 1827: By convention the comment after the name of a definition describes the
 1828: stack effect: The part in from of the @samp{--} describes the state of
 1829: the stack before the execution of the definition, i.e., the parameters
 1830: that are passed into the colon definition; the part behind the @samp{--}
 1831: is the state of the stack after the execution of the definition, i.e.,
 1832: the results of the definition.  The stack comment only shows the top
 1833: stack items that the definition accesses and/or changes.
 1834: 
 1835: You should put a correct stack effect on every definition, even if it is
 1836: just @code{( -- )}.  You should also add some descriptive comment to
 1837: more complicated words (I usually do this in the lines following
 1838: @code{:}).  If you don't do this, your code becomes unreadable (because
 1839: you have to work through every definition before you can undertsand
 1840: any).
 1841: 
 1842: @assignment
 1843: The stack effect of @code{swap} can be written like this: @code{x1 x2 --
 1844: x2 x1}.  Describe the stack effect of @code{-}, @code{drop}, @code{dup},
 1845: @code{over}, @code{rot}, @code{nip}, and @code{tuck}.  Hint: When you
 1846: are done, you can compare your stack effects to those in this manual
 1847: (@pxref{Word Index}).
 1848: @endassignment
 1849: 
 1850: Sometimes programmers put comments at various places in colon
 1851: definitions that describe the contents of the stack at that place (stack
 1852: comments); i.e., they are like the first part of a stack-effect
 1853: comment. E.g.,
 1854: 
 1855: @example
 1856: : cubed ( n -- n^3 )
 1857:    dup squared  ( n n^2 ) * ;
 1858: @end example
 1859: 
 1860: In this case the stack comment is pretty superfluous, because the word
 1861: is simple enough.  If you think it would be a good idea to add such a
 1862: comment to increase readability, you should also consider factoring the
 1863: word into several simpler words (@pxref{Factoring Tutorial,,
 1864: Factoring}), which typically eliminates the need for the stack comment;
 1865: however, if you decide not to refactor it, then having such a comment is
 1866: better than not having it.
 1867: 
 1868: The names of the stack items in stack-effect and stack comments in the
 1869: standard, in this manual, and in many programs specify the type through
 1870: a type prefix, similar to Fortran and Hungarian notation.  The most
 1871: frequent prefixes are:
 1872: 
 1873: @table @code
 1874: @item n
 1875: signed integer
 1876: @item u
 1877: unsigned integer
 1878: @item c
 1879: character
 1880: @item f
 1881: Boolean flags, i.e. @code{false} or @code{true}.
 1882: @item a-addr,a-
 1883: Cell-aligned address
 1884: @item c-addr,c-
 1885: Char-aligned address (note that a Char may have two bytes in Windows NT)
 1886: @item xt
 1887: Execution token, same size as Cell
 1888: @item w,x
 1889: Cell, can contain an integer or an address.  It usually takes 32, 64 or
 1890: 16 bits (depending on your platform and Forth system). A cell is more
 1891: commonly known as machine word, but the term @emph{word} already means
 1892: something different in Forth.
 1893: @item d
 1894: signed double-cell integer
 1895: @item ud
 1896: unsigned double-cell integer
 1897: @item r
 1898: Float (on the FP stack)
 1899: @end table
 1900: 
 1901: You can find a more complete list in @ref{Notation}.
 1902: 
 1903: @assignment
 1904: Write stack-effect comments for all definitions you have written up to
 1905: now.
 1906: @endassignment
 1907: 
 1908: 
 1909: @node Types Tutorial, Factoring Tutorial, Stack-Effect Comments Tutorial, Tutorial
 1910: @section Types
 1911: @cindex types tutorial
 1912: 
 1913: In Forth the names of the operations are not overloaded; so similar
 1914: operations on different types need different names; e.g., @code{+} adds
 1915: integers, and you have to use @code{f+} to add floating-point numbers.
 1916: The following prefixes are often used for related operations on
 1917: different types:
 1918: 
 1919: @table @code
 1920: @item (none)
 1921: signed integer
 1922: @item u
 1923: unsigned integer
 1924: @item c
 1925: character
 1926: @item d
 1927: signed double-cell integer
 1928: @item ud, du
 1929: unsigned double-cell integer
 1930: @item 2
 1931: two cells (not-necessarily double-cell numbers)
 1932: @item m, um
 1933: mixed single-cell and double-cell operations
 1934: @item f
 1935: floating-point (note that in stack comments @samp{f} represents flags,
 1936: and @samp{r} represents FP numbers).
 1937: @end table
 1938: 
 1939: If there are no differences between the signed and the unsigned variant
 1940: (e.g., for @code{+}), there is only the prefix-less variant.
 1941: 
 1942: Forth does not perform type checking, neither at compile time, nor at
 1943: run time.  If you use the wrong oeration, the data are interpreted
 1944: incorrectly:
 1945: 
 1946: @example
 1947: -1 u.
 1948: @end example
 1949: 
 1950: If you have only experience with type-checked languages until now, and
 1951: have heard how important type-checking is, don't panic!  In my
 1952: experience (and that of other Forthers), type errors in Forth code are
 1953: usually easy to find (once you get used to it), the increased vigilance
 1954: of the programmer tends to catch some harder errors in addition to most
 1955: type errors, and you never have to work around the type system, so in
 1956: most situations the lack of type-checking seems to be a win (projects to
 1957: add type checking to Forth have not caught on).
 1958: 
 1959: 
 1960: @node Factoring Tutorial, Designing the stack effect Tutorial, Types Tutorial, Tutorial
 1961: @section Factoring
 1962: @cindex factoring tutorial
 1963: 
 1964: If you try to write longer definitions, you will soon find it hard to
 1965: keep track of the stack contents.  Therefore, good Forth programmers
 1966: tend to write only short definitions (e.g., three lines).  The art of
 1967: finding meaningful short definitions is known as factoring (as in
 1968: factoring polynomials).
 1969: 
 1970: Well-factored programs offer additional advantages: smaller, more
 1971: general words, are easier to test and debug and can be reused more and
 1972: better than larger, specialized words.
 1973: 
 1974: So, if you run into difficulties with stack management, when writing
 1975: code, try to define meaningful factors for the word, and define the word
 1976: in terms of those.  Even if a factor contains only two words, it is
 1977: often helpful.
 1978: 
 1979: Good factoring is not easy, and it takes some practice to get the knack
 1980: for it; but even experienced Forth programmers often don't find the
 1981: right solution right away, but only when rewriting the program.  So, if
 1982: you don't come up with a good solution immediately, keep trying, don't
 1983: despair.
 1984: 
 1985: @c example !!
 1986: 
 1987: 
 1988: @node Designing the stack effect Tutorial, Local Variables Tutorial, Factoring Tutorial, Tutorial
 1989: @section Designing the stack effect
 1990: @cindex Stack effect design, tutorial
 1991: @cindex design of stack effects, tutorial
 1992: 
 1993: In other languages you can use an arbitrary order of parameters for a
 1994: function; and since there is only one result, you don't have to deal with
 1995: the order of results, either.
 1996: 
 1997: In Forth (and other stack-based languages, e.g., Postscript) the
 1998: parameter and result order of a definition is important and should be
 1999: designed well.  The general guideline is to design the stack effect such
 2000: that the word is simple to use in most cases, even if that complicates
 2001: the implementation of the word.  Some concrete rules are:
 2002: 
 2003: @itemize @bullet
 2004: 
 2005: @item
 2006: Words consume all of their parameters (e.g., @code{.}).
 2007: 
 2008: @item
 2009: If there is a convention on the order of parameters (e.g., from
 2010: mathematics or another programming language), stick with it (e.g.,
 2011: @code{-}).
 2012: 
 2013: @item
 2014: If one parameter usually requires only a short computation (e.g., it is
 2015: a constant), pass it on the top of the stack.  Conversely, parameters
 2016: that usually require a long sequence of code to compute should be passed
 2017: as the bottom (i.e., first) parameter.  This makes the code easier to
 2018: read, because reader does not need to keep track of the bottom item
 2019: through a long sequence of code (or, alternatively, through stack
 2020: manipulations). E.g., @code{!} (store, @pxref{Memory}) expects the
 2021: address on top of the stack because it is usually simpler to compute
 2022: than the stored value (often the address is just a variable).
 2023: 
 2024: @item
 2025: Similarly, results that are usually consumed quickly should be returned
 2026: on the top of stack, whereas a result that is often used in long
 2027: computations should be passed as bottom result.  E.g., the file words
 2028: like @code{open-file} return the error code on the top of stack, because
 2029: it is usually consumed quickly by @code{throw}; moreover, the error code
 2030: has to be checked before doing anything with the other results.
 2031: 
 2032: @end itemize
 2033: 
 2034: These rules are just general guidelines, don't lose sight of the overall
 2035: goal to make the words easy to use.  E.g., if the convention rule
 2036: conflicts with the computation-length rule, you might decide in favour
 2037: of the convention if the word will be used rarely, and in favour of the
 2038: computation-length rule if the word will be used frequently (because
 2039: with frequent use the cost of breaking the computation-length rule would
 2040: be quite high, and frequent use makes it easier to remember an
 2041: unconventional order).
 2042: 
 2043: @c example !! structure package
 2044: 
 2045: 
 2046: @node Local Variables Tutorial, Conditional execution Tutorial, Designing the stack effect Tutorial, Tutorial
 2047: @section Local Variables
 2048: @cindex local variables, tutorial
 2049: 
 2050: You can define local variables (@emph{locals}) in a colon definition:
 2051: 
 2052: @example
 2053: : swap @{ a b -- b a @}
 2054:   b a ;
 2055: 1 2 swap .s 2drop
 2056: @end example
 2057: 
 2058: (If your Forth system does not support this syntax, include
 2059: @file{compat/anslocals.fs} first).
 2060: 
 2061: In this example @code{@{ a b -- b a @}} is the locals definition; it
 2062: takes two cells from the stack, puts the top of stack in @code{b} and
 2063: the next stack element in @code{a}.  @code{--} starts a comment ending
 2064: with @code{@}}.  After the locals definition, using the name of the
 2065: local will push its value on the stack.  You can leave the comment
 2066: part (@code{-- b a}) away:
 2067: 
 2068: @example
 2069: : swap ( x1 x2 -- x2 x1 )
 2070:   @{ a b @} b a ;
 2071: @end example
 2072: 
 2073: In Gforth you can have several locals definitions, anywhere in a colon
 2074: definition; in contrast, in a standard program you can have only one
 2075: locals definition per colon definition, and that locals definition must
 2076: be outside any controll structure.
 2077: 
 2078: With locals you can write slightly longer definitions without running
 2079: into stack trouble.  However, I recommend trying to write colon
 2080: definitions without locals for exercise purposes to help you gain the
 2081: essential factoring skills.
 2082: 
 2083: @assignment
 2084: Rewrite your definitions until now with locals
 2085: @endassignment
 2086: 
 2087: Reference: @ref{Locals}.
 2088: 
 2089: 
 2090: @node Conditional execution Tutorial, Flags and Comparisons Tutorial, Local Variables Tutorial, Tutorial
 2091: @section Conditional execution
 2092: @cindex conditionals, tutorial
 2093: @cindex if, tutorial
 2094: 
 2095: In Forth you can use control structures only inside colon definitions.
 2096: An @code{if}-structure looks like this:
 2097: 
 2098: @example
 2099: : abs ( n1 -- +n2 )
 2100:     dup 0 < if
 2101:         negate
 2102:     endif ;
 2103: 5 abs .
 2104: -5 abs .
 2105: @end example
 2106: 
 2107: @code{if} takes a flag from the stack.  If the flag is non-zero (true),
 2108: the following code is performed, otherwise execution continues after the
 2109: @code{endif} (or @code{else}).  @code{<} compares the top two stack
 2110: elements and prioduces a flag:
 2111: 
 2112: @example
 2113: 1 2 < .
 2114: 2 1 < .
 2115: 1 1 < .
 2116: @end example
 2117: 
 2118: Actually the standard name for @code{endif} is @code{then}.  This
 2119: tutorial presents the examples using @code{endif}, because this is often
 2120: less confusing for people familiar with other programming languages
 2121: where @code{then} has a different meaning.  If your system does not have
 2122: @code{endif}, define it with
 2123: 
 2124: @example
 2125: : endif postpone then ; immediate
 2126: @end example
 2127: 
 2128: You can optionally use an @code{else}-part:
 2129: 
 2130: @example
 2131: : min ( n1 n2 -- n )
 2132:   2dup < if
 2133:     drop
 2134:   else
 2135:     nip
 2136:   endif ;
 2137: 2 3 min .
 2138: 3 2 min .
 2139: @end example
 2140: 
 2141: @assignment
 2142: Write @code{min} without @code{else}-part (hint: what's the definition
 2143: of @code{nip}?).
 2144: @endassignment
 2145: 
 2146: Reference: @ref{Selection}.
 2147: 
 2148: 
 2149: @node Flags and Comparisons Tutorial, General Loops Tutorial, Conditional execution Tutorial, Tutorial
 2150: @section Flags and Comparisons
 2151: @cindex flags tutorial
 2152: @cindex comparison tutorial
 2153: 
 2154: In a false-flag all bits are clear (0 when interpreted as integer).  In
 2155: a canonical true-flag all bits are set (-1 as a twos-complement signed
 2156: integer); in many contexts (e.g., @code{if}) any non-zero value is
 2157: treated as true flag.
 2158: 
 2159: @example
 2160: false .
 2161: true .
 2162: true hex u. decimal
 2163: @end example
 2164: 
 2165: Comparison words produce canonical flags:
 2166: 
 2167: @example
 2168: 1 1 = .
 2169: 1 0= .
 2170: 0 1 < .
 2171: 0 0 < .
 2172: -1 1 u< . \ type error, u< interprets -1 as large unsigned number
 2173: -1 1 < .
 2174: @end example
 2175: 
 2176: Gforth supports all combinations of the prefixes @code{0 u d d0 du f f0}
 2177: (or none) and the comparisons @code{= <> < > <= >=}.  Only a part of
 2178: these combinations are standard (for details see the standard,
 2179: @ref{Numeric comparison}, @ref{Floating Point} or @ref{Word Index}).
 2180: 
 2181: You can use @code{and or xor invert} can be used as operations on
 2182: canonical flags.  Actually they are bitwise operations:
 2183: 
 2184: @example
 2185: 1 2 and .
 2186: 1 2 or .
 2187: 1 3 xor .
 2188: 1 invert .
 2189: @end example
 2190: 
 2191: You can convert a zero/non-zero flag into a canonical flag with
 2192: @code{0<>} (and complement it on the way with @code{0=}).
 2193: 
 2194: @example
 2195: 1 0= .
 2196: 1 0<> .
 2197: @end example
 2198: 
 2199: You can use the all-bits-set feature of canonical flags and the bitwise
 2200: operation of the Boolean operations to avoid @code{if}s:
 2201: 
 2202: @example
 2203: : foo ( n1 -- n2 )
 2204:   0= if
 2205:     14
 2206:   else
 2207:     0
 2208:   endif ;
 2209: 0 foo .
 2210: 1 foo .
 2211: 
 2212: : foo ( n1 -- n2 )
 2213:   0= 14 and ;
 2214: 0 foo .
 2215: 1 foo .
 2216: @end example
 2217: 
 2218: @assignment
 2219: Write @code{min} without @code{if}.
 2220: @endassignment
 2221: 
 2222: For reference, see @ref{Boolean Flags}, @ref{Numeric comparison}, and
 2223: @ref{Bitwise operations}.
 2224: 
 2225: 
 2226: @node General Loops Tutorial, Counted loops Tutorial, Flags and Comparisons Tutorial, Tutorial
 2227: @section General Loops
 2228: @cindex loops, indefinite, tutorial
 2229: 
 2230: The endless loop is the most simple one:
 2231: 
 2232: @example
 2233: : endless ( -- )
 2234:   0 begin
 2235:     dup . 1+
 2236:   again ;
 2237: endless
 2238: @end example
 2239: 
 2240: Terminate this loop by pressing @kbd{Ctrl-C} (in Gforth).  @code{begin}
 2241: does nothing at run-time, @code{again} jumps back to @code{begin}.
 2242: 
 2243: A loop with one exit at any place looks like this:
 2244: 
 2245: @example
 2246: : log2 ( +n1 -- n2 )
 2247: \ logarithmus dualis of n1>0, rounded down to the next integer
 2248:   assert( dup 0> )
 2249:   2/ 0 begin
 2250:     over 0> while
 2251:       1+ swap 2/ swap
 2252:   repeat
 2253:   nip ;
 2254: 7 log2 .
 2255: 8 log2 .
 2256: @end example
 2257: 
 2258: At run-time @code{while} consumes a flag; if it is 0, execution
 2259: continues behind the @code{repeat}; if the flag is non-zero, execution
 2260: continues behind the @code{while}.  @code{Repeat} jumps back to
 2261: @code{begin}, just like @code{again}.
 2262: 
 2263: In Forth there are many combinations/abbreviations, like @code{1+}.
 2264: However, @code{2/} is not one of them; it shifts it's argument right by
 2265: one bit (arithmetic shift right):
 2266: 
 2267: @example
 2268: -5 2 / .
 2269: -5 2/ .
 2270: @end example
 2271: 
 2272: @code{assert(} is no standard word, but you can get it on systems other
 2273: then Gforth by including @file{compat/assert.fs}.  You can see what it
 2274: does by trying
 2275: 
 2276: @example
 2277: 0 log2 .
 2278: @end example
 2279: 
 2280: Here's a loop with an exit at the end:
 2281: 
 2282: @example
 2283: : log2 ( +n1 -- n2 )
 2284: \ logarithmus dualis of n1>0, rounded down to the next integer
 2285:   assert( dup 0 > )
 2286:   -1 begin
 2287:     1+ swap 2/ swap
 2288:     over 0 <=
 2289:   until
 2290:   nip ;
 2291: @end example
 2292: 
 2293: @code{Until} consumes a flag; if it is non-zero, execution continues at
 2294: the @code{begin}, otherwise after the @code{until}.
 2295: 
 2296: @assignment
 2297: Write a definition for computing the greatest common divisor.
 2298: @endassignment
 2299: 
 2300: Reference: @ref{Simple Loops}.
 2301: 
 2302: 
 2303: @node Counted loops Tutorial, Recursion Tutorial, General Loops Tutorial, Tutorial
 2304: @section Counted loops
 2305: @cindex loops, counted, tutorial
 2306: 
 2307: @example
 2308: : ^ ( n1 u -- n )
 2309: \ n = the uth power of u1
 2310:   1 swap 0 u+do
 2311:     over *
 2312:   loop
 2313:   nip ;
 2314: 3 2 ^ .
 2315: 4 3 ^ .
 2316: @end example
 2317: 
 2318: @code{U+do} (from @file{compat/loops.fs}, if your Forth system doesn't
 2319: have it) takes two numbers of the stack @code{( u3 u4 -- )}, and then
 2320: performs the code between @code{u+do} and @code{loop} for @code{u3-u4}
 2321: times (or not at all, if @code{u3-u4<0}).
 2322: 
 2323: You can see the stack effect design rules at work in the stack effect of
 2324: the loop start words: Since the start value of the loop is more
 2325: frequently constant than the end value, the start value is passed on
 2326: the top-of-stack.
 2327: 
 2328: You can access the counter of a counted loop with @code{i}:
 2329: 
 2330: @example
 2331: : fac ( u -- u! )
 2332:   1 swap 1+ 1 u+do
 2333:     i *
 2334:   loop ;
 2335: 5 fac .
 2336: 7 fac .
 2337: @end example
 2338: 
 2339: There is also @code{+do}, which expects signed numbers (important for
 2340: deciding whether to enter the loop).
 2341: 
 2342: @assignment
 2343: Write a definition for computing the nth Fibonacci number.
 2344: @endassignment
 2345: 
 2346: You can also use increments other than 1:
 2347: 
 2348: @example
 2349: : up2 ( n1 n2 -- )
 2350:   +do
 2351:     i .
 2352:   2 +loop ;
 2353: 10 0 up2
 2354: 
 2355: : down2 ( n1 n2 -- )
 2356:   -do
 2357:     i .
 2358:   2 -loop ;
 2359: 0 10 down2
 2360: @end example
 2361: 
 2362: Reference: @ref{Counted Loops}.
 2363: 
 2364: 
 2365: @node Recursion Tutorial, Leaving definitions or loops Tutorial, Counted loops Tutorial, Tutorial
 2366: @section Recursion
 2367: @cindex recursion tutorial
 2368: 
 2369: Usually the name of a definition is not visible in the definition; but
 2370: earlier definitions are usually visible:
 2371: 
 2372: @example
 2373: 1 0 / . \ "Floating-point unidentified fault" in Gforth on most platforms
 2374: : / ( n1 n2 -- n )
 2375:   dup 0= if
 2376:     -10 throw \ report division by zero
 2377:   endif
 2378:   /           \ old version
 2379: ;
 2380: 1 0 /
 2381: @end example
 2382: 
 2383: For recursive definitions you can use @code{recursive} (non-standard) or
 2384: @code{recurse}:
 2385: 
 2386: @example
 2387: : fac1 ( n -- n! ) recursive
 2388:  dup 0> if
 2389:    dup 1- fac1 *
 2390:  else
 2391:    drop 1
 2392:  endif ;
 2393: 7 fac1 .
 2394: 
 2395: : fac2 ( n -- n! )
 2396:  dup 0> if
 2397:    dup 1- recurse *
 2398:  else
 2399:    drop 1
 2400:  endif ;
 2401: 8 fac2 .
 2402: @end example
 2403: 
 2404: @assignment
 2405: Write a recursive definition for computing the nth Fibonacci number.
 2406: @endassignment
 2407: 
 2408: Reference (including indirect recursion): @xref{Calls and returns}.
 2409: 
 2410: 
 2411: @node Leaving definitions or loops Tutorial, Return Stack Tutorial, Recursion Tutorial, Tutorial
 2412: @section Leaving definitions or loops
 2413: @cindex leaving definitions, tutorial
 2414: @cindex leaving loops, tutorial
 2415: 
 2416: @code{EXIT} exits the current definition right away.  For every counted
 2417: loop that is left in this way, an @code{UNLOOP} has to be performed
 2418: before the @code{EXIT}:
 2419: 
 2420: @c !! real examples
 2421: @example
 2422: : ...
 2423:  ... u+do
 2424:    ... if
 2425:      ... unloop exit
 2426:    endif
 2427:    ...
 2428:  loop
 2429:  ... ;
 2430: @end example
 2431: 
 2432: @code{LEAVE} leaves the innermost counted loop right away:
 2433: 
 2434: @example
 2435: : ...
 2436:  ... u+do
 2437:    ... if
 2438:      ... leave
 2439:    endif
 2440:    ...
 2441:  loop
 2442:  ... ;
 2443: @end example
 2444: 
 2445: @c !! example
 2446: 
 2447: Reference: @ref{Calls and returns}, @ref{Counted Loops}.
 2448: 
 2449: 
 2450: @node Return Stack Tutorial, Memory Tutorial, Leaving definitions or loops Tutorial, Tutorial
 2451: @section Return Stack
 2452: @cindex return stack tutorial
 2453: 
 2454: In addition to the data stack Forth also has a second stack, the return
 2455: stack; most Forth systems store the return addresses of procedure calls
 2456: there (thus its name).  Programmers can also use this stack:
 2457: 
 2458: @example
 2459: : foo ( n1 n2 -- )
 2460:  .s
 2461:  >r .s
 2462:  r@@ .
 2463:  >r .s
 2464:  r@@ .
 2465:  r> .
 2466:  r@@ .
 2467:  r> . ;
 2468: 1 2 foo
 2469: @end example
 2470: 
 2471: @code{>r} takes an element from the data stack and pushes it onto the
 2472: return stack; conversely, @code{r>} moves an elementm from the return to
 2473: the data stack; @code{r@@} pushes a copy of the top of the return stack
 2474: on the return stack.
 2475: 
 2476: Forth programmers usually use the return stack for storing data
 2477: temporarily, if using the data stack alone would be too complex, and
 2478: factoring and locals are not an option:
 2479: 
 2480: @example
 2481: : 2swap ( x1 x2 x3 x4 -- x3 x4 x1 x2 )
 2482:  rot >r rot r> ;
 2483: @end example
 2484: 
 2485: The return address of the definition and the loop control parameters of
 2486: counted loops usually reside on the return stack, so you have to take
 2487: all items, that you have pushed on the return stack in a colon
 2488: definition or counted loop, from the return stack before the definition
 2489: or loop ends.  You cannot access items that you pushed on the return
 2490: stack outside some definition or loop within the definition of loop.
 2491: 
 2492: If you miscount the return stack items, this usually ends in a crash:
 2493: 
 2494: @example
 2495: : crash ( n -- )
 2496:   >r ;
 2497: 5 crash
 2498: @end example
 2499: 
 2500: You cannot mix using locals and using the return stack (according to the
 2501: standard; Gforth has no problem).  However, they solve the same
 2502: problems, so this shouldn't be an issue.
 2503: 
 2504: @assignment
 2505: Can you rewrite any of the definitions you wrote until now in a better
 2506: way using the return stack?
 2507: @endassignment
 2508: 
 2509: Reference: @ref{Return stack}.
 2510: 
 2511: 
 2512: @node Memory Tutorial, Characters and Strings Tutorial, Return Stack Tutorial, Tutorial
 2513: @section Memory
 2514: @cindex memory access/allocation tutorial
 2515: 
 2516: You can create a global variable @code{v} with
 2517: 
 2518: @example
 2519: variable v ( -- addr )
 2520: @end example
 2521: 
 2522: @code{v} pushes the address of a cell in memory on the stack.  This cell
 2523: was reserved by @code{variable}.  You can use @code{!} (store) to store
 2524: values into this cell and @code{@@} (fetch) to load the value from the
 2525: stack into memory:
 2526: 
 2527: @example
 2528: v .
 2529: 5 v ! .s
 2530: v @@ .
 2531: @end example
 2532: 
 2533: You can see a raw dump of memory with @code{dump}:
 2534: 
 2535: @example
 2536: v 1 cells .s dump
 2537: @end example
 2538: 
 2539: @code{Cells ( n1 -- n2 )} gives you the number of bytes (or, more
 2540: generally, address units (aus)) that @code{n1 cells} occupy.  You can
 2541: also reserve more memory:
 2542: 
 2543: @example
 2544: create v2 20 cells allot
 2545: v2 20 cells dump
 2546: @end example
 2547: 
 2548: creates a word @code{v2} and reserves 20 uninitialized cells; the
 2549: address pushed by @code{v2} points to the start of these 20 cells.  You
 2550: can use address arithmetic to access these cells:
 2551: 
 2552: @example
 2553: 3 v2 5 cells + !
 2554: v2 20 cells dump
 2555: @end example
 2556: 
 2557: You can reserve and initialize memory with @code{,}:
 2558: 
 2559: @example
 2560: create v3
 2561:   5 , 4 , 3 , 2 , 1 ,
 2562: v3 @@ .
 2563: v3 cell+ @@ .
 2564: v3 2 cells + @@ .
 2565: v3 5 cells dump
 2566: @end example
 2567: 
 2568: @assignment
 2569: Write a definition @code{vsum ( addr u -- n )} that computes the sum of
 2570: @code{u} cells, with the first of these cells at @code{addr}, the next
 2571: one at @code{addr cell+} etc.
 2572: @endassignment
 2573: 
 2574: You can also reserve memory without creating a new word:
 2575: 
 2576: @example
 2577: here 10 cells allot .
 2578: here .
 2579: @end example
 2580: 
 2581: @code{Here} pushes the start address of the memory area.  You should
 2582: store it somewhere, or you will have a hard time finding the memory area
 2583: again.
 2584: 
 2585: @code{Allot} manages dictionary memory.  The dictionary memory contains
 2586: the system's data structures for words etc. on Gforth and most other
 2587: Forth systems.  It is managed like a stack: You can free the memory that
 2588: you have just @code{allot}ed with
 2589: 
 2590: @example
 2591: -10 cells allot
 2592: here .
 2593: @end example
 2594: 
 2595: Note that you cannot do this if you have created a new word in the
 2596: meantime (because then your @code{allot}ed memory is no longer on the
 2597: top of the dictionary ``stack'').
 2598: 
 2599: Alternatively, you can use @code{allocate} and @code{free} which allow
 2600: freeing memory in any order:
 2601: 
 2602: @example
 2603: 10 cells allocate throw .s
 2604: 20 cells allocate throw .s
 2605: swap
 2606: free throw
 2607: free throw
 2608: @end example
 2609: 
 2610: The @code{throw}s deal with errors (e.g., out of memory).
 2611: 
 2612: And there is also a
 2613: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
 2614: garbage collector}, which eliminates the need to @code{free} memory
 2615: explicitly.
 2616: 
 2617: Reference: @ref{Memory}.
 2618: 
 2619: 
 2620: @node Characters and Strings Tutorial, Alignment Tutorial, Memory Tutorial, Tutorial
 2621: @section Characters and Strings
 2622: @cindex strings tutorial
 2623: @cindex characters tutorial
 2624: 
 2625: On the stack characters take up a cell, like numbers.  In memory they
 2626: have their own size (one 8-bit byte on most systems), and therefore
 2627: require their own words for memory access:
 2628: 
 2629: @example
 2630: create v4 
 2631:   104 c, 97 c, 108 c, 108 c, 111 c,
 2632: v4 4 chars + c@@ .
 2633: v4 5 chars dump
 2634: @end example
 2635: 
 2636: The preferred representation of strings on the stack is @code{addr
 2637: u-count}, where @code{addr} is the address of the first character and
 2638: @code{u-count} is the number of characters in the string.
 2639: 
 2640: @example
 2641: v4 5 type
 2642: @end example
 2643: 
 2644: You get a string constant with
 2645: 
 2646: @example
 2647: s" hello, world" .s
 2648: type
 2649: @end example
 2650: 
 2651: Make sure you have a space between @code{s"} and the string; @code{s"}
 2652: is a normal Forth word and must be delimited with white space (try what
 2653: happens when you remove the space).
 2654: 
 2655: However, this interpretive use of @code{s"} is quite restricted: the
 2656: string exists only until the next call of @code{s"} (some Forth systems
 2657: keep more than one of these strings, but usually they still have a
 2658: limited lifetime).
 2659: 
 2660: @example
 2661: s" hello," s" world" .s
 2662: type
 2663: type
 2664: @end example
 2665: 
 2666: You can also use @code{s"} in a definition, and the resulting
 2667: strings then live forever (well, for as long as the definition):
 2668: 
 2669: @example
 2670: : foo s" hello," s" world" ;
 2671: foo .s
 2672: type
 2673: type
 2674: @end example
 2675: 
 2676: @assignment
 2677: @code{Emit ( c -- )} types @code{c} as character (not a number).
 2678: Implement @code{type ( addr u -- )}.
 2679: @endassignment
 2680: 
 2681: Reference: @ref{Memory Blocks}.
 2682: 
 2683: 
 2684: @node Alignment Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Characters and Strings Tutorial, Tutorial
 2685: @section Alignment
 2686: @cindex alignment tutorial
 2687: @cindex memory alignment tutorial
 2688: 
 2689: On many processors cells have to be aligned in memory, if you want to
 2690: access them with @code{@@} and @code{!} (and even if the processor does
 2691: not require alignment, access to aligned cells is faster).
 2692: 
 2693: @code{Create} aligns @code{here} (i.e., the place where the next
 2694: allocation will occur, and that the @code{create}d word points to).
 2695: Likewise, the memory produced by @code{allocate} starts at an aligned
 2696: address.  Adding a number of @code{cells} to an aligned address produces
 2697: another aligned address.
 2698: 
 2699: However, address arithmetic involving @code{char+} and @code{chars} can
 2700: create an address that is not cell-aligned.  @code{Aligned ( addr --
 2701: a-addr )} produces the next aligned address:
 2702: 
 2703: @example
 2704: v3 char+ aligned .s @@ .
 2705: v3 char+ .s @@ .
 2706: @end example
 2707: 
 2708: Similarly, @code{align} advances @code{here} to the next aligned
 2709: address:
 2710: 
 2711: @example
 2712: create v5 97 c,
 2713: here .
 2714: align here .
 2715: 1000 ,
 2716: @end example
 2717: 
 2718: Note that you should use aligned addresses even if your processor does
 2719: not require them, if you want your program to be portable.
 2720: 
 2721: Reference: @ref{Address arithmetic}.
 2722: 
 2723: 
 2724: @node Interpretation and Compilation Semantics and Immediacy Tutorial, Execution Tokens Tutorial, Alignment Tutorial, Tutorial
 2725: @section Interpretation and Compilation Semantics and Immediacy
 2726: @cindex semantics tutorial
 2727: @cindex interpretation semantics tutorial
 2728: @cindex compilation semantics tutorial
 2729: @cindex immediate, tutorial
 2730: 
 2731: When a word is compiled, it behaves differently from being interpreted.
 2732: E.g., consider @code{+}:
 2733: 
 2734: @example
 2735: 1 2 + .
 2736: : foo + ;
 2737: @end example
 2738: 
 2739: These two behaviours are known as compilation and interpretation
 2740: semantics.  For normal words (e.g., @code{+}), the compilation semantics
 2741: is to append the interpretation semantics to the currently defined word
 2742: (@code{foo} in the example above).  I.e., when @code{foo} is executed
 2743: later, the interpretation semantics of @code{+} (i.e., adding two
 2744: numbers) will be performed.
 2745: 
 2746: However, there are words with non-default compilation semantics, e.g.,
 2747: the control-flow words like @code{if}.  You can use @code{immediate} to
 2748: change the compilation semantics of the last defined word to be equal to
 2749: the interpretation semantics:
 2750: 
 2751: @example
 2752: : [FOO] ( -- )
 2753:  5 . ; immediate
 2754: 
 2755: [FOO]
 2756: : bar ( -- )
 2757:   [FOO] ;
 2758: bar
 2759: see bar
 2760: @end example
 2761: 
 2762: Two conventions to mark words with non-default compilation semnatics are
 2763: names with brackets (more frequently used) and to write them all in
 2764: upper case (less frequently used).
 2765: 
 2766: In Gforth (and many other systems) you can also remove the
 2767: interpretation semantics with @code{compile-only} (the compilation
 2768: semantics is derived from the original interpretation semantics):
 2769: 
 2770: @example
 2771: : flip ( -- )
 2772:  6 . ; compile-only \ but not immediate
 2773: flip
 2774: 
 2775: : flop ( -- )
 2776:  flip ;
 2777: flop
 2778: @end example
 2779: 
 2780: In this example the interpretation semantics of @code{flop} is equal to
 2781: the original interpretation semantics of @code{flip}.
 2782: 
 2783: The text interpreter has two states: in interpret state, it performs the
 2784: interpretation semantics of words it encounters; in compile state, it
 2785: performs the compilation semantics of these words.
 2786: 
 2787: Among other things, @code{:} switches into compile state, and @code{;}
 2788: switches back to interpret state.  They contain the factors @code{]}
 2789: (switch to compile state) and @code{[} (switch to interpret state), that
 2790: do nothing but switch the state.
 2791: 
 2792: @example
 2793: : xxx ( -- )
 2794:   [ 5 . ]
 2795: ;
 2796: 
 2797: xxx
 2798: see xxx
 2799: @end example
 2800: 
 2801: These brackets are also the source of the naming convention mentioned
 2802: above.
 2803: 
 2804: Reference: @ref{Interpretation and Compilation Semantics}.
 2805: 
 2806: 
 2807: @node Execution Tokens Tutorial, Exceptions Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Tutorial
 2808: @section Execution Tokens
 2809: @cindex execution tokens tutorial
 2810: @cindex XT tutorial
 2811: 
 2812: @code{' word} gives you the execution token (XT) of a word.  The XT is a
 2813: cell representing the interpretation semantics of a word.  You can
 2814: execute this semantics with @code{execute}:
 2815: 
 2816: @example
 2817: ' + .s
 2818: 1 2 rot execute .
 2819: @end example
 2820: 
 2821: The XT is similar to a function pointer in C.  However, parameter
 2822: passing through the stack makes it a little more flexible:
 2823: 
 2824: @example
 2825: : map-array ( ... addr u xt -- ... )
 2826: \ executes xt ( ... x -- ... ) for every element of the array starting
 2827: \ at addr and containing u elements
 2828:   @{ xt @}
 2829:   cells over + swap ?do
 2830:     i @@ xt execute
 2831:   1 cells +loop ;
 2832: 
 2833: create a 3 , 4 , 2 , -1 , 4 ,
 2834: a 5 ' . map-array .s
 2835: 0 a 5 ' + map-array .
 2836: s" max-n" environment? drop .s
 2837: a 5 ' min map-array .
 2838: @end example
 2839: 
 2840: You can use map-array with the XTs of words that consume one element
 2841: more than they produce.  In theory you can also use it with other XTs,
 2842: but the stack effect then depends on the size of the array, which is
 2843: hard to understand.
 2844: 
 2845: Since XTs are cell-sized, you can store them in memory and manipulate
 2846: them on the stack like other cells.  You can also compile the XT into a
 2847: word with @code{compile,}:
 2848: 
 2849: @example
 2850: : foo1 ( n1 n2 -- n )
 2851:    [ ' + compile, ] ;
 2852: see foo
 2853: @end example
 2854: 
 2855: This is non-standard, because @code{compile,} has no compilation
 2856: semantics in the standard, but it works in good Forth systems.  For the
 2857: broken ones, use
 2858: 
 2859: @example
 2860: : [compile,] compile, ; immediate
 2861: 
 2862: : foo1 ( n1 n2 -- n )
 2863:    [ ' + ] [compile,] ;
 2864: see foo
 2865: @end example
 2866: 
 2867: @code{'} is a word with default compilation semantics; it parses the
 2868: next word when its interpretation semantics are executed, not during
 2869: compilation:
 2870: 
 2871: @example
 2872: : foo ( -- xt )
 2873:   ' ;
 2874: see foo
 2875: : bar ( ... "word" -- ... )
 2876:   ' execute ;
 2877: see bar
 2878: 1 2 bar + .
 2879: @end example
 2880: 
 2881: You often want to parse a word during compilation and compile its XT so
 2882: it will be pushed on the stack at run-time.  @code{[']} does this:
 2883: 
 2884: @example
 2885: : xt-+ ( -- xt )
 2886:   ['] + ;
 2887: see xt-+
 2888: 1 2 xt-+ execute .
 2889: @end example
 2890: 
 2891: Many programmers tend to see @code{'} and the word it parses as one
 2892: unit, and expect it to behave like @code{[']} when compiled, and are
 2893: confused by the actual behaviour.  If you are, just remember that the
 2894: Forth system just takes @code{'} as one unit and has no idea that it is
 2895: a parsing word (attempts to convenience programmers in this issue have
 2896: usually resulted in even worse pitfalls, see
 2897: @uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,
 2898: @code{State}-smartness---Why it is evil and How to Exorcise it}).
 2899: 
 2900: Note that the state of the interpreter does not come into play when
 2901: creating and executing XTs.  I.e., even when you execute @code{'} in
 2902: compile state, it still gives you the interpretation semantics.  And
 2903: whatever that state is, @code{execute} performs the semantics
 2904: represented by the XT (i.e., for XTs produced with @code{'} the
 2905: interpretation semantics).
 2906: 
 2907: Reference: @ref{Tokens for Words}.
 2908: 
 2909: 
 2910: @node Exceptions Tutorial, Defining Words Tutorial, Execution Tokens Tutorial, Tutorial
 2911: @section Exceptions
 2912: @cindex exceptions tutorial
 2913: 
 2914: @code{throw ( n -- )} causes an exception unless n is zero.
 2915: 
 2916: @example
 2917: 100 throw .s
 2918: 0 throw .s
 2919: @end example
 2920: 
 2921: @code{catch ( ... xt -- ... n )} behaves similar to @code{execute}, but
 2922: it catches exceptions and pushes the number of the exception on the
 2923: stack (or 0, if the xt executed without exception).  If there was an
 2924: exception, the stacks have the same depth as when entering @code{catch}:
 2925: 
 2926: @example
 2927: .s
 2928: 3 0 ' / catch .s
 2929: 3 2 ' / catch .s
 2930: @end example
 2931: 
 2932: @assignment
 2933: Try the same with @code{execute} instead of @code{catch}.
 2934: @endassignment
 2935: 
 2936: @code{Throw} always jumps to the dynamically next enclosing
 2937: @code{catch}, even if it has to leave several call levels to achieve
 2938: this:
 2939: 
 2940: @example
 2941: : foo 100 throw ;
 2942: : foo1 foo ." after foo" ;
 2943: : bar ['] foo1 catch ;
 2944: bar .
 2945: @end example
 2946: 
 2947: It is often important to restore a value upon leaving a definition, even
 2948: if the definition is left through an exception.  You can ensure this
 2949: like this:
 2950: 
 2951: @example
 2952: : ...
 2953:    save-x
 2954:    ['] word-changing-x catch ( ... n )
 2955:    restore-x
 2956:    ( ... n ) throw ;
 2957: @end example
 2958: 
 2959: Gforth provides an alternative syntax in addition to @code{catch}:
 2960: @code{try ... recover ... endtry}.  If the code between @code{try} and
 2961: @code{recover} has an exception, the stack depths are restored, the
 2962: exception number is pushed on the stack, and the code between
 2963: @code{recover} and @code{endtry} is performed.  E.g., the definition for
 2964: @code{catch} is
 2965: 
 2966: @example
 2967: : catch ( x1 .. xn xt -- y1 .. ym 0 / z1 .. zn error ) \ exception
 2968:   try
 2969:     execute 0
 2970:   recover
 2971:     nip
 2972:   endtry ;
 2973: @end example
 2974: 
 2975: The equivalent to the restoration code above is
 2976: 
 2977: @example
 2978: : ...
 2979:   save-x
 2980:   try
 2981:     word-changing-x
 2982:   end-try
 2983:   restore-x
 2984:   throw ;
 2985: @end example
 2986: 
 2987: As you can see, the @code{recover} part is optional.
 2988: 
 2989: Reference: @ref{Exception Handling}.
 2990: 
 2991: 
 2992: @node Defining Words Tutorial, Arrays and Records Tutorial, Exceptions Tutorial, Tutorial
 2993: @section Defining Words
 2994: @cindex defining words tutorial
 2995: @cindex does> tutorial
 2996: @cindex create...does> tutorial
 2997: 
 2998: @c before semantics?
 2999: 
 3000: @code{:}, @code{create}, and @code{variable} are definition words: They
 3001: define other words.  @code{Constant} is another definition word:
 3002: 
 3003: @example
 3004: 5 constant foo
 3005: foo .
 3006: @end example
 3007: 
 3008: You can also use the prefixes @code{2} (double-cell) and @code{f}
 3009: (floating point) with @code{variable} and @code{constant}.
 3010: 
 3011: You can also define your own defining words.  E.g.:
 3012: 
 3013: @example
 3014: : variable ( "name" -- )
 3015:   create 0 , ;
 3016: @end example
 3017: 
 3018: You can also define defining words that create words that do something
 3019: other than just producing their address:
 3020: 
 3021: @example
 3022: : constant ( n "name" -- )
 3023:   create ,
 3024: does> ( -- n )
 3025:   ( addr ) @@ ;
 3026: 
 3027: 5 constant foo
 3028: foo .
 3029: @end example
 3030: 
 3031: The definition of @code{constant} above ends at the @code{does>}; i.e.,
 3032: @code{does>} replaces @code{;}, but it also does something else: It
 3033: changes the last defined word such that it pushes the address of the
 3034: body of the word and then performs the code after the @code{does>}
 3035: whenever it is called.
 3036: 
 3037: In the example above, @code{constant} uses @code{,} to store 5 into the
 3038: body of @code{foo}.  When @code{foo} executes, it pushes the address of
 3039: the body onto the stack, then (in the code after the @code{does>})
 3040: fetches the 5 from there.
 3041: 
 3042: The stack comment near the @code{does>} reflects the stack effect of the
 3043: defined word, not the stack effect of the code after the @code{does>}
 3044: (the difference is that the code expects the address of the body that
 3045: the stack comment does not show).
 3046: 
 3047: You can use these definition words to do factoring in cases that involve
 3048: (other) definition words.  E.g., a field offset is always added to an
 3049: address.  Instead of defining
 3050: 
 3051: @example
 3052: 2 cells constant offset-field1
 3053: @end example
 3054: 
 3055: and using this like
 3056: 
 3057: @example
 3058: ( addr ) offset-field1 +
 3059: @end example
 3060: 
 3061: you can define a definition word
 3062: 
 3063: @example
 3064: : simple-field ( n "name" -- )
 3065:   create ,
 3066: does> ( n1 -- n1+n )
 3067:   ( addr ) @@ + ;
 3068: @end example
 3069: 
 3070: Definition and use of field offsets now look like this:
 3071: 
 3072: @example
 3073: 2 cells simple-field field1
 3074: create mystruct 4 cells allot
 3075: mystruct .s field1 .s drop
 3076: @end example
 3077: 
 3078: If you want to do something with the word without performing the code
 3079: after the @code{does>}, you can access the body of a @code{create}d word
 3080: with @code{>body ( xt -- addr )}:
 3081: 
 3082: @example
 3083: : value ( n "name" -- )
 3084:   create ,
 3085: does> ( -- n1 )
 3086:   @@ ;
 3087: : to ( n "name" -- )
 3088:   ' >body ! ;
 3089: 
 3090: 5 value foo
 3091: foo .
 3092: 7 to foo
 3093: foo .
 3094: @end example
 3095: 
 3096: @assignment
 3097: Define @code{defer ( "name" -- )}, which creates a word that stores an
 3098: XT (at the start the XT of @code{abort}), and upon execution
 3099: @code{execute}s the XT.  Define @code{is ( xt "name" -- )} that stores
 3100: @code{xt} into @code{name}, a word defined with @code{defer}.  Indirect
 3101: recursion is one application of @code{defer}.
 3102: @endassignment
 3103: 
 3104: Reference: @ref{User-defined Defining Words}.
 3105: 
 3106: 
 3107: @node Arrays and Records Tutorial, POSTPONE Tutorial, Defining Words Tutorial, Tutorial
 3108: @section Arrays and Records
 3109: @cindex arrays tutorial
 3110: @cindex records tutorial
 3111: @cindex structs tutorial
 3112: 
 3113: Forth has no standard words for defining data structures such as arrays
 3114: and records (structs in C terminology), but you can build them yourself
 3115: based on address arithmetic.  You can also define words for defining
 3116: arrays and records (@pxref{Defining Words Tutorial,, Defining Words}).
 3117: 
 3118: One of the first projects a Forth newcomer sets out upon when learning
 3119: about defining words is an array defining word (possibly for
 3120: n-dimensional arrays).  Go ahead and do it, I did it, too; you will
 3121: learn something from it.  However, don't be disappointed when you later
 3122: learn that you have little use for these words (inappropriate use would
 3123: be even worse).  I have not yet found a set of useful array words yet;
 3124: the needs are just too diverse, and named, global arrays (the result of
 3125: naive use of defining words) are often not flexible enough (e.g.,
 3126: consider how to pass them as parameters).  Another such project is a set
 3127: of words to help dealing with strings.
 3128: 
 3129: On the other hand, there is a useful set of record words, and it has
 3130: been defined in @file{compat/struct.fs}; these words are predefined in
 3131: Gforth.  They are explained in depth elsewhere in this manual (see
 3132: @pxref{Structures}).  The @code{simple-field} example above is
 3133: simplified variant of fields in this package.
 3134: 
 3135: 
 3136: @node POSTPONE Tutorial, Literal Tutorial, Arrays and Records Tutorial, Tutorial
 3137: @section @code{POSTPONE}
 3138: @cindex postpone tutorial
 3139: 
 3140: You can compile the compilation semantics (instead of compiling the
 3141: interpretation semantics) of a word with @code{POSTPONE}:
 3142: 
 3143: @example
 3144: : MY-+ ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
 3145:  POSTPONE + ; immediate
 3146: : foo ( n1 n2 -- n )
 3147:  MY-+ ;
 3148: 1 2 foo .
 3149: see foo
 3150: @end example
 3151: 
 3152: During the definition of @code{foo} the text interpreter performs the
 3153: compilation semantics of @code{MY-+}, which performs the compilation
 3154: semantics of @code{+}, i.e., it compiles @code{+} into @code{foo}.
 3155: 
 3156: This example also displays separate stack comments for the compilation
 3157: semantics and for the stack effect of the compiled code.  For words with
 3158: default compilation semantics these stack effects are usually not
 3159: displayed; the stack effect of the compilation semantics is always
 3160: @code{( -- )} for these words, the stack effect for the compiled code is
 3161: the stack effect of the interpretation semantics.
 3162: 
 3163: Note that the state of the interpreter does not come into play when
 3164: performing the compilation semantics in this way.  You can also perform
 3165: it interpretively, e.g.:
 3166: 
 3167: @example
 3168: : foo2 ( n1 n2 -- n )
 3169:  [ MY-+ ] ;
 3170: 1 2 foo .
 3171: see foo
 3172: @end example
 3173: 
 3174: However, there are some broken Forth systems where this does not always
 3175: work, and therefore this practice was been declared non-standard in
 3176: 1999.
 3177: @c !! repair.fs
 3178: 
 3179: Here is another example for using @code{POSTPONE}:
 3180: 
 3181: @example
 3182: : MY-- ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
 3183:  POSTPONE negate POSTPONE + ; immediate compile-only
 3184: : bar ( n1 n2 -- n )
 3185:   MY-- ;
 3186: 2 1 bar .
 3187: see bar
 3188: @end example
 3189: 
 3190: You can define @code{ENDIF} in this way:
 3191: 
 3192: @example
 3193: : ENDIF ( Compilation: orig -- )
 3194:   POSTPONE then ; immediate
 3195: @end example
 3196: 
 3197: @assignment
 3198: Write @code{MY-2DUP} that has compilation semantics equivalent to
 3199: @code{2dup}, but compiles @code{over over}.
 3200: @endassignment
 3201: 
 3202: @c !! @xref{Macros} for reference
 3203: 
 3204: 
 3205: @node Literal Tutorial, Advanced macros Tutorial, POSTPONE Tutorial, Tutorial
 3206: @section @code{Literal}
 3207: @cindex literal tutorial
 3208: 
 3209: You cannot @code{POSTPONE} numbers:
 3210: 
 3211: @example
 3212: : [FOO] POSTPONE 500 ; immediate
 3213: @end example
 3214: 
 3215: Instead, you can use @code{LITERAL (compilation: n --; run-time: -- n )}:
 3216: 
 3217: @example
 3218: : [FOO] ( compilation: --; run-time: -- n )
 3219:   500 POSTPONE literal ; immediate
 3220: 
 3221: : flip [FOO] ;
 3222: flip .
 3223: see flip
 3224: @end example
 3225: 
 3226: @code{LITERAL} consumes a number at compile-time (when it's compilation
 3227: semantics are executed) and pushes it at run-time (when the code it
 3228: compiled is executed).  A frequent use of @code{LITERAL} is to compile a
 3229: number computed at compile time into the current word:
 3230: 
 3231: @example
 3232: : bar ( -- n )
 3233:   [ 2 2 + ] literal ;
 3234: see bar
 3235: @end example
 3236: 
 3237: @assignment
 3238: Write @code{]L} which allows writing the example above as @code{: bar (
 3239: -- n ) [ 2 2 + ]L ;}
 3240: @endassignment
 3241: 
 3242: @c !! @xref{Macros} for reference
 3243: 
 3244: 
 3245: @node Advanced macros Tutorial, Compilation Tokens Tutorial, Literal Tutorial, Tutorial
 3246: @section Advanced macros
 3247: @cindex macros, advanced tutorial
 3248: @cindex run-time code generation, tutorial
 3249: 
 3250: Reconsider @code{map-array} from @ref{Execution Tokens Tutorial,,
 3251: Execution Tokens}.  It frequently performs @code{execute}, a relatively
 3252: expensive operation in some Forth implementations.  You can use
 3253: @code{compile,} and @code{POSTPONE} to eliminate these @code{execute}s
 3254: and produce a word that contains the word to be performed directly:
 3255: 
 3256: @c use ]] ... [[
 3257: @example
 3258: : compile-map-array ( compilation: xt -- ; run-time: ... addr u -- ... )
 3259: \ at run-time, execute xt ( ... x -- ... ) for each element of the
 3260: \ array beginning at addr and containing u elements
 3261:   @{ xt @}
 3262:   POSTPONE cells POSTPONE over POSTPONE + POSTPONE swap POSTPONE ?do
 3263:     POSTPONE i POSTPONE @@ xt compile,
 3264:   1 cells POSTPONE literal POSTPONE +loop ;
 3265: 
 3266: : sum-array ( addr u -- n )
 3267:  0 rot rot [ ' + compile-map-array ] ;
 3268: see sum-array
 3269: a 5 sum-array .
 3270: @end example
 3271: 
 3272: You can use the full power of Forth for generating the code; here's an
 3273: example where the code is generated in a loop:
 3274: 
 3275: @example
 3276: : compile-vmul-step ( compilation: n --; run-time: n1 addr1 -- n2 addr2 )
 3277: \ n2=n1+(addr1)*n, addr2=addr1+cell
 3278:   POSTPONE tuck POSTPONE @@
 3279:   POSTPONE literal POSTPONE * POSTPONE +
 3280:   POSTPONE swap POSTPONE cell+ ;
 3281: 
 3282: : compile-vmul ( compilation: addr1 u -- ; run-time: addr2 -- n )
 3283: \ n=v1*v2 (inner product), where the v_i are represented as addr_i u
 3284:   0 postpone literal postpone swap
 3285:   [ ' compile-vmul-step compile-map-array ]
 3286:   postpone drop ;
 3287: see compile-vmul
 3288: 
 3289: : a-vmul ( addr -- n )
 3290: \ n=a*v, where v is a vector that's as long as a and starts at addr
 3291:  [ a 5 compile-vmul ] ;
 3292: see a-vmul
 3293: a a-vmul .
 3294: @end example
 3295: 
 3296: This example uses @code{compile-map-array} to show off, but you could
 3297: also use @code{map-array} instead (try it now!).
 3298: 
 3299: You can use this technique for efficient multiplication of large
 3300: matrices.  In matrix multiplication, you multiply every line of one
 3301: matrix with every column of the other matrix.  You can generate the code
 3302: for one line once, and use it for every column.  The only downside of
 3303: this technique is that it is cumbersome to recover the memory consumed
 3304: by the generated code when you are done (and in more complicated cases
 3305: it is not possible portably).
 3306: 
 3307: @c !! @xref{Macros} for reference
 3308: 
 3309: 
 3310: @node Compilation Tokens Tutorial, Wordlists and Search Order Tutorial, Advanced macros Tutorial, Tutorial
 3311: @section Compilation Tokens
 3312: @cindex compilation tokens, tutorial
 3313: @cindex CT, tutorial
 3314: 
 3315: This section is Gforth-specific.  You can skip it.
 3316: 
 3317: @code{' word compile,} compiles the interpretation semantics.  For words
 3318: with default compilation semantics this is the same as performing the
 3319: compilation semantics.  To represent the compilation semantics of other
 3320: words (e.g., words like @code{if} that have no interpretation
 3321: semantics), Gforth has the concept of a compilation token (CT,
 3322: consisting of two cells), and words @code{comp'} and @code{[comp']}.
 3323: You can perform the compilation semantics represented by a CT with
 3324: @code{execute}:
 3325: 
 3326: @example
 3327: : foo2 ( n1 n2 -- n )
 3328:    [ comp' + execute ] ;
 3329: see foo
 3330: @end example
 3331: 
 3332: You can compile the compilation semantics represented by a CT with
 3333: @code{postpone,}:
 3334: 
 3335: @example
 3336: : foo3 ( -- )
 3337:   [ comp' + postpone, ] ;
 3338: see foo3
 3339: @end example
 3340: 
 3341: @code{[ comp' word postpone, ]} is equivalent to @code{POSTPONE word}.
 3342: @code{comp'} is particularly useful for words that have no
 3343: interpretation semantics:
 3344: 
 3345: @example
 3346: ' if
 3347: comp' if .s 2drop
 3348: @end example
 3349: 
 3350: Reference: @ref{Tokens for Words}.
 3351: 
 3352: 
 3353: @node Wordlists and Search Order Tutorial,  , Compilation Tokens Tutorial, Tutorial
 3354: @section Wordlists and Search Order
 3355: @cindex wordlists tutorial
 3356: @cindex search order, tutorial
 3357: 
 3358: The dictionary is not just a memory area that allows you to allocate
 3359: memory with @code{allot}, it also contains the Forth words, arranged in
 3360: several wordlists.  When searching for a word in a wordlist,
 3361: conceptually you start searching at the youngest and proceed towards
 3362: older words (in reality most systems nowadays use hash-tables); i.e., if
 3363: you define a word with the same name as an older word, the new word
 3364: shadows the older word.
 3365: 
 3366: Which wordlists are searched in which order is determined by the search
 3367: order.  You can display the search order with @code{order}.  It displays
 3368: first the search order, starting with the wordlist searched first, then
 3369: it displays the wordlist that will contain newly defined words.
 3370: 
 3371: You can create a new, empty wordlist with @code{wordlist ( -- wid )}:
 3372: 
 3373: @example
 3374: wordlist constant mywords
 3375: @end example
 3376: 
 3377: @code{Set-current ( wid -- )} sets the wordlist that will contain newly
 3378: defined words (the @emph{current} wordlist):
 3379: 
 3380: @example
 3381: mywords set-current
 3382: order
 3383: @end example
 3384: 
 3385: Gforth does not display a name for the wordlist in @code{mywords}
 3386: because this wordlist was created anonymously with @code{wordlist}.
 3387: 
 3388: You can get the current wordlist with @code{get-current ( -- wid)}.  If
 3389: you want to put something into a specific wordlist without overall
 3390: effect on the current wordlist, this typically looks like this:
 3391: 
 3392: @example
 3393: get-current mywords set-current ( wid )
 3394: create someword
 3395: ( wid ) set-current
 3396: @end example
 3397: 
 3398: You can write the search order with @code{set-order ( wid1 .. widn n --
 3399: )} and read it with @code{get-order ( -- wid1 .. widn n )}.  The first
 3400: searched wordlist is topmost.
 3401: 
 3402: @example
 3403: get-order mywords swap 1+ set-order
 3404: order
 3405: @end example
 3406: 
 3407: Yes, the order of wordlists in the output of @code{order} is reversed
 3408: from stack comments and the output of @code{.s} and thus unintuitive.
 3409: 
 3410: @assignment
 3411: Define @code{>order ( wid -- )} with adds @code{wid} as first searched
 3412: wordlist to the search order.  Define @code{previous ( -- )}, which
 3413: removes the first searched wordlist from the search order.  Experiment
 3414: with boundary conditions (you will see some crashes or situations that
 3415: are hard or impossible to leave).
 3416: @endassignment
 3417: 
 3418: The search order is a powerful foundation for providing features similar
 3419: to Modula-2 modules and C++ namespaces.  However, trying to modularize
 3420: programs in this way has disadvantages for debugging and reuse/factoring
 3421: that overcome the advantages in my experience (I don't do huge projects,
 3422: though).  These disadvantages are not so clear in other
 3423: languages/programming environments, because these langauges are not so
 3424: strong in debugging and reuse.
 3425: 
 3426: @c !! example
 3427: 
 3428: Reference: @ref{Word Lists}.
 3429: 
 3430: @c ******************************************************************
 3431: @node Introduction, Words, Tutorial, Top
 3432: @comment node-name,     next,           previous, up
 3433: @chapter An Introduction to ANS Forth
 3434: @cindex Forth - an introduction
 3435: 
 3436: The primary purpose of this manual is to document Gforth. However, since
 3437: Forth is not a widely-known language and there is a lack of up-to-date
 3438: teaching material, it seems worthwhile to provide some introductory
 3439: material.  For other sources of Forth-related
 3440: information, see @ref{Forth-related information}.
 3441: 
 3442: The examples in this section should work on any ANS Forth; the
 3443: output shown was produced using Gforth. Each example attempts to
 3444: reproduce the exact output that Gforth produces. If you try out the
 3445: examples (and you should), what you should type is shown @kbd{like this}
 3446: and Gforth's response is shown @code{like this}. The single exception is
 3447: that, where the example shows @key{RET} it means that you should
 3448: press the ``carriage return'' key. Unfortunately, some output formats for
 3449: this manual cannot show the difference between @kbd{this} and
 3450: @code{this} which will make trying out the examples harder (but not
 3451: impossible).
 3452: 
 3453: Forth is an unusual language. It provides an interactive development
 3454: environment which includes both an interpreter and compiler. Forth
 3455: programming style encourages you to break a problem down into many
 3456: @cindex factoring
 3457: small fragments (@dfn{factoring}), and then to develop and test each
 3458: fragment interactively. Forth advocates assert that breaking the
 3459: edit-compile-test cycle used by conventional programming languages can
 3460: lead to great productivity improvements.
 3461: 
 3462: @menu
 3463: * Introducing the Text Interpreter::  
 3464: * Stacks and Postfix notation::  
 3465: * Your first definition::       
 3466: * How does that work?::         
 3467: * Forth is written in Forth::   
 3468: * Review - elements of a Forth system::  
 3469: * Where to go next::            
 3470: * Exercises::                   
 3471: @end menu
 3472: 
 3473: @comment ----------------------------------------------
 3474: @node Introducing the Text Interpreter, Stacks and Postfix notation, Introduction, Introduction
 3475: @section Introducing the Text Interpreter
 3476: @cindex text interpreter
 3477: @cindex outer interpreter
 3478: 
 3479: @c IMO this is too detailed and the pace is too slow for
 3480: @c an introduction.  If you know German, take a look at
 3481: @c http://www.complang.tuwien.ac.at/anton/lvas/skriptum-stack.html 
 3482: @c to see how I do it - anton 
 3483: 
 3484: @c nac-> Where I have accepted your comments 100% and modified the text
 3485: @c accordingly, I have deleted your comments. Elsewhere I have added a
 3486: @c response like this to attempt to rationalise what I have done. Of
 3487: @c course, this is a very clumsy mechanism for something that would be
 3488: @c done far more efficiently over a beer. Please delete any dialogue
 3489: @c you consider closed.
 3490: 
 3491: When you invoke the Forth image, you will see a startup banner printed
 3492: and nothing else (if you have Gforth installed on your system, try
 3493: invoking it now, by typing @kbd{gforth@key{RET}}). Forth is now running
 3494: its command line interpreter, which is called the @dfn{Text Interpreter}
 3495: (also known as the @dfn{Outer Interpreter}).  (You will learn a lot
 3496: about the text interpreter as you read through this chapter, for more
 3497: detail @pxref{The Text Interpreter}).
 3498: 
 3499: Although it's not obvious, Forth is actually waiting for your
 3500: input. Type a number and press the @key{RET} key:
 3501: 
 3502: @example
 3503: @kbd{45@key{RET}}  ok
 3504: @end example
 3505: 
 3506: Rather than give you a prompt to invite you to input something, the text
 3507: interpreter prints a status message @i{after} it has processed a line
 3508: of input. The status message in this case (``@code{ ok}'' followed by
 3509: carriage-return) indicates that the text interpreter was able to process
 3510: all of your input successfully. Now type something illegal:
 3511: 
 3512: @example
 3513: @kbd{qwer341@key{RET}}
 3514: :1: Undefined word
 3515: qwer341
 3516: ^^^^^^^
 3517: $400D2BA8 Bounce
 3518: $400DBDA8 no.extensions
 3519: @end example
 3520: 
 3521: The exact text, other than the ``Undefined word'' may differ slightly on
 3522: your system, but the effect is the same; when the text interpreter
 3523: detects an error, it discards any remaining text on a line, resets
 3524: certain internal state and prints an error message. For a detailed description of error messages see @ref{Error
 3525: messages}.
 3526: 
 3527: The text interpreter waits for you to press carriage-return, and then
 3528: processes your input line. Starting at the beginning of the line, it
 3529: breaks the line into groups of characters separated by spaces. For each
 3530: group of characters in turn, it makes two attempts to do something:
 3531: 
 3532: @itemize @bullet
 3533: @item
 3534: @cindex name dictionary
 3535: It tries to treat it as a command. It does this by searching a @dfn{name
 3536: dictionary}. If the group of characters matches an entry in the name
 3537: dictionary, the name dictionary provides the text interpreter with
 3538: information that allows the text interpreter perform some actions. In
 3539: Forth jargon, we say that the group
 3540: @cindex word
 3541: @cindex definition
 3542: @cindex execution token
 3543: @cindex xt
 3544: of characters names a @dfn{word}, that the dictionary search returns an
 3545: @dfn{execution token (xt)} corresponding to the @dfn{definition} of the
 3546: word, and that the text interpreter executes the xt. Often, the terms
 3547: @dfn{word} and @dfn{definition} are used interchangeably.
 3548: @item
 3549: If the text interpreter fails to find a match in the name dictionary, it
 3550: tries to treat the group of characters as a number in the current number
 3551: base (when you start up Forth, the current number base is base 10). If
 3552: the group of characters legitimately represents a number, the text
 3553: interpreter pushes the number onto a stack (we'll learn more about that
 3554: in the next section).
 3555: @end itemize
 3556: 
 3557: If the text interpreter is unable to do either of these things with any
 3558: group of characters, it discards the group of characters and the rest of
 3559: the line, then prints an error message. If the text interpreter reaches
 3560: the end of the line without error, it prints the status message ``@code{ ok}''
 3561: followed by carriage-return.
 3562: 
 3563: This is the simplest command we can give to the text interpreter:
 3564: 
 3565: @example
 3566: @key{RET}  ok
 3567: @end example
 3568: 
 3569: The text interpreter did everything we asked it to do (nothing) without
 3570: an error, so it said that everything is ``@code{ ok}''. Try a slightly longer
 3571: command:
 3572: 
 3573: @example
 3574: @kbd{12 dup fred dup@key{RET}}
 3575: :1: Undefined word
 3576: 12 dup fred dup
 3577:        ^^^^
 3578: $400D2BA8 Bounce
 3579: $400DBDA8 no.extensions
 3580: @end example
 3581: 
 3582: When you press the carriage-return key, the text interpreter starts to
 3583: work its way along the line:
 3584: 
 3585: @itemize @bullet
 3586: @item
 3587: When it gets to the space after the @code{2}, it takes the group of
 3588: characters @code{12} and looks them up in the name
 3589: dictionary@footnote{We can't tell if it found them or not, but assume
 3590: for now that it did not}. There is no match for this group of characters
 3591: in the name dictionary, so it tries to treat them as a number. It is
 3592: able to do this successfully, so it puts the number, 12, ``on the stack''
 3593: (whatever that means).
 3594: @item
 3595: The text interpreter resumes scanning the line and gets the next group
 3596: of characters, @code{dup}. It looks it up in the name dictionary and
 3597: (you'll have to take my word for this) finds it, and executes the word
 3598: @code{dup} (whatever that means).
 3599: @item
 3600: Once again, the text interpreter resumes scanning the line and gets the
 3601: group of characters @code{fred}. It looks them up in the name
 3602: dictionary, but can't find them. It tries to treat them as a number, but
 3603: they don't represent any legal number.
 3604: @end itemize
 3605: 
 3606: At this point, the text interpreter gives up and prints an error
 3607: message. The error message shows exactly how far the text interpreter
 3608: got in processing the line. In particular, it shows that the text
 3609: interpreter made no attempt to do anything with the final character
 3610: group, @code{dup}, even though we have good reason to believe that the
 3611: text interpreter would have no problem looking that word up and
 3612: executing it a second time.
 3613: 
 3614: 
 3615: @comment ----------------------------------------------
 3616: @node Stacks and Postfix notation, Your first definition, Introducing the Text Interpreter, Introduction
 3617: @section Stacks, postfix notation and parameter passing
 3618: @cindex text interpreter
 3619: @cindex outer interpreter
 3620: 
 3621: In procedural programming languages (like C and Pascal), the
 3622: building-block of programs is the @dfn{function} or @dfn{procedure}. These
 3623: functions or procedures are called with @dfn{explicit parameters}. For
 3624: example, in C we might write:
 3625: 
 3626: @example
 3627: total = total + new_volume(length,height,depth);
 3628: @end example
 3629: 
 3630: @noindent
 3631: where new_volume is a function-call to another piece of code, and total,
 3632: length, height and depth are all variables. length, height and depth are
 3633: parameters to the function-call.
 3634: 
 3635: In Forth, the equivalent of the function or procedure is the
 3636: @dfn{definition} and parameters are implicitly passed between
 3637: definitions using a shared stack that is visible to the
 3638: programmer. Although Forth does support variables, the existence of the
 3639: stack means that they are used far less often than in most other
 3640: programming languages. When the text interpreter encounters a number, it
 3641: will place (@dfn{push}) it on the stack. There are several stacks (the
 3642: actual number is implementation-dependent ...) and the particular stack
 3643: used for any operation is implied unambiguously by the operation being
 3644: performed. The stack used for all integer operations is called the @dfn{data
 3645: stack} and, since this is the stack used most commonly, references to
 3646: ``the data stack'' are often abbreviated to ``the stack''.
 3647: 
 3648: The stacks have a last-in, first-out (LIFO) organisation. If you type:
 3649: 
 3650: @example
 3651: @kbd{1 2 3@key{RET}}  ok
 3652: @end example
 3653: 
 3654: Then this instructs the text interpreter to placed three numbers on the
 3655: (data) stack. An analogy for the behaviour of the stack is to take a
 3656: pack of playing cards and deal out the ace (1), 2 and 3 into a pile on
 3657: the table. The 3 was the last card onto the pile (``last-in'') and if
 3658: you take a card off the pile then, unless you're prepared to fiddle a
 3659: bit, the card that you take off will be the 3 (``first-out''). The
 3660: number that will be first-out of the stack is called the @dfn{top of
 3661: stack}, which
 3662: @cindex TOS definition
 3663: is often abbreviated to @dfn{TOS}.
 3664: 
 3665: To understand how parameters are passed in Forth, consider the
 3666: behaviour of the definition @code{+} (pronounced ``plus''). You will not
 3667: be surprised to learn that this definition performs addition. More
 3668: precisely, it adds two number together and produces a result. Where does
 3669: it get the two numbers from? It takes the top two numbers off the
 3670: stack. Where does it place the result? On the stack. You can act-out the
 3671: behaviour of @code{+} with your playing cards like this:
 3672: 
 3673: @itemize @bullet
 3674: @item
 3675: Pick up two cards from the stack on the table
 3676: @item
 3677: Stare at them intently and ask yourself ``what @i{is} the sum of these two
 3678: numbers''
 3679: @item
 3680: Decide that the answer is 5
 3681: @item
 3682: Shuffle the two cards back into the pack and find a 5
 3683: @item
 3684: Put a 5 on the remaining ace that's on the table.
 3685: @end itemize
 3686: 
 3687: If you don't have a pack of cards handy but you do have Forth running,
 3688: you can use the definition @code{.s} to show the current state of the stack,
 3689: without affecting the stack. Type:
 3690: 
 3691: @example
 3692: @kbd{clearstack 1 2 3@key{RET}} ok
 3693: @kbd{.s@key{RET}} <3> 1 2 3  ok
 3694: @end example
 3695: 
 3696: The text interpreter looks up the word @code{clearstack} and executes
 3697: it; it tidies up the stack and removes any entries that may have been
 3698: left on it by earlier examples. The text interpreter pushes each of the
 3699: three numbers in turn onto the stack. Finally, the text interpreter
 3700: looks up the word @code{.s} and executes it. The effect of executing
 3701: @code{.s} is to print the ``<3>'' (the total number of items on the stack)
 3702: followed by a list of all the items on the stack; the item on the far
 3703: right-hand side is the TOS.
 3704: 
 3705: You can now type:
 3706: 
 3707: @example
 3708: @kbd{+ .s@key{RET}} <2> 1 5  ok
 3709: @end example
 3710: 
 3711: @noindent
 3712: which is correct; there are now 2 items on the stack and the result of
 3713: the addition is 5.
 3714: 
 3715: If you're playing with cards, try doing a second addition: pick up the
 3716: two cards, work out that their sum is 6, shuffle them into the pack,
 3717: look for a 6 and place that on the table. You now have just one item on
 3718: the stack. What happens if you try to do a third addition? Pick up the
 3719: first card, pick up the second card -- ah! There is no second card. This
 3720: is called a @dfn{stack underflow} and consitutes an error. If you try to
 3721: do the same thing with Forth it will report an error (probably a Stack
 3722: Underflow or an Invalid Memory Address error).
 3723: 
 3724: The opposite situation to a stack underflow is a @dfn{stack overflow},
 3725: which simply accepts that there is a finite amount of storage space
 3726: reserved for the stack. To stretch the playing card analogy, if you had
 3727: enough packs of cards and you piled the cards up on the table, you would
 3728: eventually be unable to add another card; you'd hit the ceiling. Gforth
 3729: allows you to set the maximum size of the stacks. In general, the only
 3730: time that you will get a stack overflow is because a definition has a
 3731: bug in it and is generating data on the stack uncontrollably.
 3732: 
 3733: There's one final use for the playing card analogy. If you model your
 3734: stack using a pack of playing cards, the maximum number of items on
 3735: your stack will be 52 (I assume you didn't use the Joker). The maximum
 3736: @i{value} of any item on the stack is 13 (the King). In fact, the only
 3737: possible numbers are positive integer numbers 1 through 13; you can't
 3738: have (for example) 0 or 27 or 3.52 or -2. If you change the way you
 3739: think about some of the cards, you can accommodate different
 3740: numbers. For example, you could think of the Jack as representing 0,
 3741: the Queen as representing -1 and the King as representing -2. Your
 3742: @i{range} remains unchanged (you can still only represent a total of 13
 3743: numbers) but the numbers that you can represent are -2 through 10.
 3744: 
 3745: In that analogy, the limit was the amount of information that a single
 3746: stack entry could hold, and Forth has a similar limit. In Forth, the
 3747: size of a stack entry is called a @dfn{cell}. The actual size of a cell is
 3748: implementation dependent and affects the maximum value that a stack
 3749: entry can hold. A Standard Forth provides a cell size of at least
 3750: 16-bits, and most desktop systems use a cell size of 32-bits.
 3751: 
 3752: Forth does not do any type checking for you, so you are free to
 3753: manipulate and combine stack items in any way you wish. A convenient way
 3754: of treating stack items is as 2's complement signed integers, and that
 3755: is what Standard words like @code{+} do. Therefore you can type:
 3756: 
 3757: @example
 3758: @kbd{-5 12 + .s@key{RET}} <1> 7  ok
 3759: @end example
 3760: 
 3761: If you use numbers and definitions like @code{+} in order to turn Forth
 3762: into a great big pocket calculator, you will realise that it's rather
 3763: different from a normal calculator. Rather than typing 2 + 3 = you had
 3764: to type 2 3 + (ignore the fact that you had to use @code{.s} to see the
 3765: result). The terminology used to describe this difference is to say that
 3766: your calculator uses @dfn{Infix Notation} (parameters and operators are
 3767: mixed) whilst Forth uses @dfn{Postfix Notation} (parameters and
 3768: operators are separate), also called @dfn{Reverse Polish Notation}.
 3769: 
 3770: Whilst postfix notation might look confusing to begin with, it has
 3771: several important advantages:
 3772: 
 3773: @itemize @bullet
 3774: @item
 3775: it is unambiguous
 3776: @item
 3777: it is more concise
 3778: @item
 3779: it fits naturally with a stack-based system
 3780: @end itemize
 3781: 
 3782: To examine these claims in more detail, consider these sums:
 3783: 
 3784: @example
 3785: 6 + 5 * 4 =
 3786: 4 * 5 + 6 =
 3787: @end example
 3788: 
 3789: If you're just learning maths or your maths is very rusty, you will
 3790: probably come up with the answer 44 for the first and 26 for the
 3791: second. If you are a bit of a whizz at maths you will remember the
 3792: @i{convention} that multiplication takes precendence over addition, and
 3793: you'd come up with the answer 26 both times. To explain the answer 26
 3794: to someone who got the answer 44, you'd probably rewrite the first sum
 3795: like this:
 3796: 
 3797: @example
 3798: 6 + (5 * 4) =
 3799: @end example
 3800: 
 3801: If what you really wanted was to perform the addition before the
 3802: multiplication, you would have to use parentheses to force it.
 3803: 
 3804: If you did the first two sums on a pocket calculator you would probably
 3805: get the right answers, unless you were very cautious and entered them using
 3806: these keystroke sequences:
 3807: 
 3808: 6 + 5 = * 4 =
 3809: 4 * 5 = + 6 =
 3810: 
 3811: Postfix notation is unambiguous because the order that the operators
 3812: are applied is always explicit; that also means that parentheses are
 3813: never required. The operators are @i{active} (the act of quoting the
 3814: operator makes the operation occur) which removes the need for ``=''.
 3815: 
 3816: The sum 6 + 5 * 4 can be written (in postfix notation) in two
 3817: equivalent ways:
 3818: 
 3819: @example
 3820: 6 5 4 * +      or:
 3821: 5 4 * 6 +
 3822: @end example
 3823: 
 3824: An important thing that you should notice about this notation is that
 3825: the @i{order} of the numbers does not change; if you want to subtract
 3826: 2 from 10 you type @code{10 2 -}.
 3827: 
 3828: The reason that Forth uses postfix notation is very simple to explain: it
 3829: makes the implementation extremely simple, and it follows naturally from
 3830: using the stack as a mechanism for passing parameters. Another way of
 3831: thinking about this is to realise that all Forth definitions are
 3832: @i{active}; they execute as they are encountered by the text
 3833: interpreter. The result of this is that the syntax of Forth is trivially
 3834: simple.
 3835: 
 3836: 
 3837: 
 3838: @comment ----------------------------------------------
 3839: @node Your first definition, How does that work?, Stacks and Postfix notation, Introduction
 3840: @section Your first Forth definition
 3841: @cindex first definition
 3842: 
 3843: Until now, the examples we've seen have been trivial; we've just been
 3844: using Forth as a bigger-than-pocket calculator. Also, each calculation
 3845: we've shown has been a ``one-off'' -- to repeat it we'd need to type it in
 3846: again@footnote{That's not quite true. If you press the up-arrow key on
 3847: your keyboard you should be able to scroll back to any earlier command,
 3848: edit it and re-enter it.} In this section we'll see how to add new
 3849: words to Forth's vocabulary.
 3850: 
 3851: The easiest way to create a new word is to use a @dfn{colon
 3852: definition}. We'll define a few and try them out before worrying too
 3853: much about how they work. Try typing in these examples; be careful to
 3854: copy the spaces accurately:
 3855: 
 3856: @example
 3857: : add-two 2 + . ;
 3858: : greet ." Hello and welcome" ;
 3859: : demo 5 add-two ;
 3860: @end example
 3861: 
 3862: @noindent
 3863: Now try them out:
 3864: 
 3865: @example
 3866: @kbd{greet@key{RET}} Hello and welcome  ok
 3867: @kbd{greet greet@key{RET}} Hello and welcomeHello and welcome  ok
 3868: @kbd{4 add-two@key{RET}} 6  ok
 3869: @kbd{demo@key{RET}} 7  ok
 3870: @kbd{9 greet demo add-two@key{RET}} Hello and welcome7 11  ok
 3871: @end example
 3872: 
 3873: The first new thing that we've introduced here is the pair of words
 3874: @code{:} and @code{;}. These are used to start and terminate a new
 3875: definition, respectively. The first word after the @code{:} is the name
 3876: for the new definition.
 3877: 
 3878: As you can see from the examples, a definition is built up of words that
 3879: have already been defined; Forth makes no distinction between
 3880: definitions that existed when you started the system up, and those that
 3881: you define yourself.
 3882: 
 3883: The examples also introduce the words @code{.} (dot), @code{."}
 3884: (dot-quote) and @code{dup} (dewp). Dot takes the value from the top of
 3885: the stack and displays it. It's like @code{.s} except that it only
 3886: displays the top item of the stack and it is destructive; after it has
 3887: executed, the number is no longer on the stack. There is always one
 3888: space printed after the number, and no spaces before it. Dot-quote
 3889: defines a string (a sequence of characters) that will be printed when
 3890: the word is executed. The string can contain any printable characters
 3891: except @code{"}. A @code{"} has a special function; it is not a Forth
 3892: word but it acts as a delimiter (the way that delimiters work is
 3893: described in the next section). Finally, @code{dup} duplicates the value
 3894: at the top of the stack. Try typing @code{5 dup .s} to see what it does.
 3895: 
 3896: We already know that the text interpreter searches through the
 3897: dictionary to locate names. If you've followed the examples earlier, you
 3898: will already have a definition called @code{add-two}. Lets try modifying
 3899: it by typing in a new definition:
 3900: 
 3901: @example
 3902: @kbd{: add-two dup . ." + 2 =" 2 + . ;@key{RET}} redefined add-two  ok
 3903: @end example
 3904: 
 3905: Forth recognised that we were defining a word that already exists, and
 3906: printed a message to warn us of that fact. Let's try out the new
 3907: definition:
 3908: 
 3909: @example
 3910: @kbd{9 add-two@key{RET}} 9 + 2 =11  ok
 3911: @end example
 3912: 
 3913: @noindent
 3914: All that we've actually done here, though, is to create a new
 3915: definition, with a particular name. The fact that there was already a
 3916: definition with the same name did not make any difference to the way
 3917: that the new definition was created (except that Forth printed a warning
 3918: message). The old definition of add-two still exists (try @code{demo}
 3919: again to see that this is true). Any new definition will use the new
 3920: definition of @code{add-two}, but old definitions continue to use the
 3921: version that already existed at the time that they were @code{compiled}.
 3922: 
 3923: Before you go on to the next section, try defining and redefining some
 3924: words of your own.
 3925: 
 3926: @comment ----------------------------------------------
 3927: @node How does that work?, Forth is written in Forth, Your first definition, Introduction
 3928: @section How does that work?
 3929: @cindex parsing words
 3930: 
 3931: @c That's pretty deep (IMO way too deep) for an introduction. - anton
 3932: 
 3933: @c Is it a good idea to talk about the interpretation semantics of a
 3934: @c number? We don't have an xt to go along with it. - anton
 3935: 
 3936: @c Now that I have eliminated execution semantics, I wonder if it would not
 3937: @c be better to keep them (or add run-time semantics), to make it easier to
 3938: @c explain what compilation semantics usually does. - anton
 3939: 
 3940: @c nac-> I removed the term ``default compilation sematics'' from the
 3941: @c introductory chapter. Removing ``execution semantics'' was making
 3942: @c everything simpler to explain, then I think the use of this term made
 3943: @c everything more complex again. I replaced it with ``default
 3944: @c semantics'' (which is used elsewhere in the manual) by which I mean
 3945: @c ``a definition that has neither the immediate nor the compile-only
 3946: @c flag set''. I reworded big chunks of the ``how does that work''
 3947: @c section (and, unusually for me, I think I even made it shorter!).  See
 3948: @c what you think -- I know I have not addressed your primary concern
 3949: @c that it is too heavy-going for an introduction. From what I understood
 3950: @c of your course notes it looks as though they might be a good framework. 
 3951: @c Things that I've tried to capture here are some things that came as a
 3952: @c great revelation here when I first understood them. Also, I like the
 3953: @c fact that a very simple code example shows up almost all of the issues
 3954: @c that you need to understand to see how Forth works. That's unique and
 3955: @c worthwhile to emphasise.
 3956: 
 3957: Now we're going to take another look at the definition of @code{add-two}
 3958: from the previous section. From our knowledge of the way that the text
 3959: interpreter works, we would have expected this result when we tried to
 3960: define @code{add-two}:
 3961: 
 3962: @example
 3963: @kbd{: add-two 2 + . ;@key{RET}}
 3964:   ^^^^^^^
 3965: Error: Undefined word
 3966: @end example
 3967: 
 3968: The reason that this didn't happen is bound up in the way that @code{:}
 3969: works. The word @code{:} does two special things. The first special
 3970: thing that it does prevents the text interpreter from ever seeing the
 3971: characters @code{add-two}. The text interpreter uses a variable called
 3972: @cindex modifying >IN
 3973: @code{>IN} (pronounced ``to-in'') to keep track of where it is in the
 3974: input line. When it encounters the word @code{:} it behaves in exactly
 3975: the same way as it does for any other word; it looks it up in the name
 3976: dictionary, finds its xt and executes it. When @code{:} executes, it
 3977: looks at the input buffer, finds the word @code{add-two} and advances the
 3978: value of @code{>IN} to point past it. It then does some other stuff
 3979: associated with creating the new definition (including creating an entry
 3980: for @code{add-two} in the name dictionary). When the execution of @code{:}
 3981: completes, control returns to the text interpreter, which is oblivious
 3982: to the fact that it has been tricked into ignoring part of the input
 3983: line.
 3984: 
 3985: @cindex parsing words
 3986: Words like @code{:} -- words that advance the value of @code{>IN} and so
 3987: prevent the text interpreter from acting on the whole of the input line
 3988: -- are called @dfn{parsing words}.
 3989: 
 3990: @cindex @code{state} - effect on the text interpreter
 3991: @cindex text interpreter - effect of state
 3992: The second special thing that @code{:} does is change the value of a
 3993: variable called @code{state}, which affects the way that the text
 3994: interpreter behaves. When Gforth starts up, @code{state} has the value
 3995: 0, and the text interpreter is said to be @dfn{interpreting}. During a
 3996: colon definition (started with @code{:}), @code{state} is set to -1 and
 3997: the text interpreter is said to be @dfn{compiling}.
 3998: 
 3999: In this example, the text interpreter is compiling when it processes the
 4000: string ``@code{2 + . ;}''. It still breaks the string down into
 4001: character sequences in the same way. However, instead of pushing the
 4002: number @code{2} onto the stack, it lays down (@dfn{compiles}) some magic
 4003: into the definition of @code{add-two} that will make the number @code{2} get
 4004: pushed onto the stack when @code{add-two} is @dfn{executed}. Similarly,
 4005: the behaviours of @code{+} and @code{.} are also compiled into the
 4006: definition.
 4007: 
 4008: One category of words don't get compiled. These so-called @dfn{immediate
 4009: words} get executed (performed @i{now}) regardless of whether the text
 4010: interpreter is interpreting or compiling. The word @code{;} is an
 4011: immediate word. Rather than being compiled into the definition, it
 4012: executes. Its effect is to terminate the current definition, which
 4013: includes changing the value of @code{state} back to 0.
 4014: 
 4015: When you execute @code{add-two}, it has a @dfn{run-time effect} that is
 4016: exactly the same as if you had typed @code{2 + . @key{RET}} outside of a
 4017: definition.
 4018: 
 4019: In Forth, every word or number can be described in terms of two
 4020: properties:
 4021: 
 4022: @itemize @bullet
 4023: @item
 4024: @cindex interpretation semantics
 4025: Its @dfn{interpretation semantics} describe how it will behave when the
 4026: text interpreter encounters it in @dfn{interpret} state. The
 4027: interpretation semantics of a word are represented by an @dfn{execution
 4028: token}.
 4029: @item
 4030: @cindex compilation semantics
 4031: Its @dfn{compilation semantics} describe how it will behave when the
 4032: text interpreter encounters it in @dfn{compile} state. The compilation
 4033: semantics of a word are represented in an implementation-dependent way;
 4034: Gforth uses a @dfn{compilation token}.
 4035: @end itemize
 4036: 
 4037: @noindent
 4038: Numbers are always treated in a fixed way:
 4039: 
 4040: @itemize @bullet
 4041: @item
 4042: When the number is @dfn{interpreted}, its behaviour is to push the
 4043: number onto the stack.
 4044: @item
 4045: When the number is @dfn{compiled}, a piece of code is appended to the
 4046: current definition that pushes the number when it runs. (In other words,
 4047: the compilation semantics of a number are to postpone its interpretation
 4048: semantics until the run-time of the definition that it is being compiled
 4049: into.)
 4050: @end itemize
 4051: 
 4052: Words don't behave in such a regular way, but most have @i{default
 4053: semantics} which means that they behave like this:
 4054: 
 4055: @itemize @bullet
 4056: @item
 4057: The @dfn{interpretation semantics} of the word are to do something useful.
 4058: @item
 4059: The @dfn{compilation semantics} of the word are to append its
 4060: @dfn{interpretation semantics} to the current definition (so that its
 4061: run-time behaviour is to do something useful).
 4062: @end itemize
 4063: 
 4064: @cindex immediate words
 4065: The actual behaviour of any particular word can be controlled by using
 4066: the words @code{immediate} and @code{compile-only} when the word is
 4067: defined. These words set flags in the name dictionary entry of the most
 4068: recently defined word, and these flags are retrieved by the text
 4069: interpreter when it finds the word in the name dictionary.
 4070: 
 4071: A word that is marked as @dfn{immediate} has compilation semantics that
 4072: are identical to its interpretation semantics. In other words, it
 4073: behaves like this:
 4074: 
 4075: @itemize @bullet
 4076: @item
 4077: The @dfn{interpretation semantics} of the word are to do something useful.
 4078: @item
 4079: The @dfn{compilation semantics} of the word are to do something useful
 4080: (and actually the same thing); i.e., it is executed during compilation.
 4081: @end itemize
 4082: 
 4083: Marking a word as @dfn{compile-only} prohibits the text interpreter from
 4084: performing the interpretation semantics of the word directly; an attempt
 4085: to do so will generate an error. It is never necessary to use
 4086: @code{compile-only} (and it is not even part of ANS Forth, though it is
 4087: provided by many implementations) but it is good etiquette to apply it
 4088: to a word that will not behave correctly (and might have unexpected
 4089: side-effects) in interpret state. For example, it is only legal to use
 4090: the conditional word @code{IF} within a definition. If you forget this
 4091: and try to use it elsewhere, the fact that (in Gforth) it is marked as
 4092: @code{compile-only} allows the text interpreter to generate a helpful
 4093: error message rather than subjecting you to the consequences of your
 4094: folly.
 4095: 
 4096: This example shows the difference between an immediate and a
 4097: non-immediate word:
 4098: 
 4099: @example
 4100: : show-state state @@ . ;
 4101: : show-state-now show-state ; immediate
 4102: : word1 show-state ;
 4103: : word2 show-state-now ;
 4104: @end example
 4105: 
 4106: The word @code{immediate} after the definition of @code{show-state-now}
 4107: makes that word an immediate word. These definitions introduce a new
 4108: word: @code{@@} (pronounced ``fetch''). This word fetches the value of a
 4109: variable, and leaves it on the stack. Therefore, the behaviour of
 4110: @code{show-state} is to print a number that represents the current value
 4111: of @code{state}.
 4112: 
 4113: When you execute @code{word1}, it prints the number 0, indicating that
 4114: the system is interpreting. When the text interpreter compiled the
 4115: definition of @code{word1}, it encountered @code{show-state} whose
 4116: compilation semantics are to append its interpretation semantics to the
 4117: current definition. When you execute @code{word1}, it performs the
 4118: interpretation semantics of @code{show-state}.  At the time that @code{word1}
 4119: (and therefore @code{show-state}) are executed, the system is
 4120: interpreting.
 4121: 
 4122: When you pressed @key{RET} after entering the definition of @code{word2},
 4123: you should have seen the number -1 printed, followed by ``@code{
 4124: ok}''. When the text interpreter compiled the definition of
 4125: @code{word2}, it encountered @code{show-state-now}, an immediate word,
 4126: whose compilation semantics are therefore to perform its interpretation
 4127: semantics. It is executed straight away (even before the text
 4128: interpreter has moved on to process another group of characters; the
 4129: @code{;} in this example). The effect of executing it are to display the
 4130: value of @code{state} @i{at the time that the definition of}
 4131: @code{word2} @i{is being defined}. Printing -1 demonstrates that the
 4132: system is compiling at this time. If you execute @code{word2} it does
 4133: nothing at all.
 4134: 
 4135: @cindex @code{."}, how it works
 4136: Before leaving the subject of immediate words, consider the behaviour of
 4137: @code{."} in the definition of @code{greet}, in the previous
 4138: section. This word is both a parsing word and an immediate word. Notice
 4139: that there is a space between @code{."} and the start of the text
 4140: @code{Hello and welcome}, but that there is no space between the last
 4141: letter of @code{welcome} and the @code{"} character. The reason for this
 4142: is that @code{."} is a Forth word; it must have a space after it so that
 4143: the text interpreter can identify it. The @code{"} is not a Forth word;
 4144: it is a @dfn{delimiter}. The examples earlier show that, when the string
 4145: is displayed, there is neither a space before the @code{H} nor after the
 4146: @code{e}. Since @code{."} is an immediate word, it executes at the time
 4147: that @code{greet} is defined. When it executes, its behaviour is to
 4148: search forward in the input line looking for the delimiter. When it
 4149: finds the delimiter, it updates @code{>IN} to point past the
 4150: delimiter. It also compiles some magic code into the definition of
 4151: @code{greet}; the xt of a run-time routine that prints a text string. It
 4152: compiles the string @code{Hello and welcome} into memory so that it is
 4153: available to be printed later. When the text interpreter gains control,
 4154: the next word it finds in the input stream is @code{;} and so it
 4155: terminates the definition of @code{greet}.
 4156: 
 4157: 
 4158: @comment ----------------------------------------------
 4159: @node Forth is written in Forth, Review - elements of a Forth system, How does that work?, Introduction
 4160: @section Forth is written in Forth
 4161: @cindex structure of Forth programs
 4162: 
 4163: When you start up a Forth compiler, a large number of definitions
 4164: already exist. In Forth, you develop a new application using bottom-up
 4165: programming techniques to create new definitions that are defined in
 4166: terms of existing definitions. As you create each definition you can
 4167: test and debug it interactively.
 4168: 
 4169: If you have tried out the examples in this section, you will probably
 4170: have typed them in by hand; when you leave Gforth, your definitions will
 4171: be lost. You can avoid this by using a text editor to enter Forth source
 4172: code into a file, and then loading code from the file using
 4173: @code{include} (@pxref{Forth source files}). A Forth source file is
 4174: processed by the text interpreter, just as though you had typed it in by
 4175: hand@footnote{Actually, there are some subtle differences -- see
 4176: @ref{The Text Interpreter}.}.
 4177: 
 4178: Gforth also supports the traditional Forth alternative to using text
 4179: files for program entry (@pxref{Blocks}).
 4180: 
 4181: In common with many, if not most, Forth compilers, most of Gforth is
 4182: actually written in Forth. All of the @file{.fs} files in the
 4183: installation directory@footnote{For example,
 4184: @file{/usr/local/share/gforth...}} are Forth source files, which you can
 4185: study to see examples of Forth programming.
 4186: 
 4187: Gforth maintains a history file that records every line that you type to
 4188: the text interpreter. This file is preserved between sessions, and is
 4189: used to provide a command-line recall facility. If you enter long
 4190: definitions by hand, you can use a text editor to paste them out of the
 4191: history file into a Forth source file for reuse at a later time
 4192: (for more information @pxref{Command-line editing}).
 4193: 
 4194: 
 4195: @comment ----------------------------------------------
 4196: @node Review - elements of a Forth system, Where to go next, Forth is written in Forth, Introduction
 4197: @section Review - elements of a Forth system
 4198: @cindex elements of a Forth system
 4199: 
 4200: To summarise this chapter:
 4201: 
 4202: @itemize @bullet
 4203: @item
 4204: Forth programs use @dfn{factoring} to break a problem down into small
 4205: fragments called @dfn{words} or @dfn{definitions}.
 4206: @item
 4207: Forth program development is an interactive process.
 4208: @item
 4209: The main command loop that accepts input, and controls both
 4210: interpretation and compilation, is called the @dfn{text interpreter}
 4211: (also known as the @dfn{outer interpreter}).
 4212: @item
 4213: Forth has a very simple syntax, consisting of words and numbers
 4214: separated by spaces or carriage-return characters. Any additional syntax
 4215: is imposed by @dfn{parsing words}.
 4216: @item
 4217: Forth uses a stack to pass parameters between words. As a result, it
 4218: uses postfix notation.
 4219: @item
 4220: To use a word that has previously been defined, the text interpreter
 4221: searches for the word in the @dfn{name dictionary}.
 4222: @item
 4223: Words have @dfn{interpretation semantics} and @dfn{compilation semantics}.
 4224: @item
 4225: The text interpreter uses the value of @code{state} to select between
 4226: the use of the @dfn{interpretation semantics} and the  @dfn{compilation
 4227: semantics} of a word that it encounters.
 4228: @item
 4229: The relationship between the @dfn{interpretation semantics} and
 4230: @dfn{compilation semantics} for a word
 4231: depend upon the way in which the word was defined (for example, whether
 4232: it is an @dfn{immediate} word).
 4233: @item
 4234: Forth definitions can be implemented in Forth (called @dfn{high-level
 4235: definitions}) or in some other way (usually a lower-level language and
 4236: as a result often called @dfn{low-level definitions}, @dfn{code
 4237: definitions} or @dfn{primitives}).
 4238: @item
 4239: Many Forth systems are implemented mainly in Forth.
 4240: @end itemize
 4241: 
 4242: 
 4243: @comment ----------------------------------------------
 4244: @node Where to go next, Exercises, Review - elements of a Forth system, Introduction
 4245: @section Where To Go Next
 4246: @cindex where to go next
 4247: 
 4248: Amazing as it may seem, if you have read (and understood) this far, you
 4249: know almost all the fundamentals about the inner workings of a Forth
 4250: system. You certainly know enough to be able to read and understand the
 4251: rest of this manual and the ANS Forth document, to learn more about the
 4252: facilities that Forth in general and Gforth in particular provide. Even
 4253: scarier, you know almost enough to implement your own Forth system.
 4254: However, that's not a good idea just yet... better to try writing some
 4255: programs in Gforth.
 4256: 
 4257: Forth has such a rich vocabulary that it can be hard to know where to
 4258: start in learning it. This section suggests a few sets of words that are
 4259: enough to write small but useful programs. Use the word index in this
 4260: document to learn more about each word, then try it out and try to write
 4261: small definitions using it. Start by experimenting with these words:
 4262: 
 4263: @itemize @bullet
 4264: @item
 4265: Arithmetic: @code{+ - * / /MOD */ ABS INVERT}
 4266: @item
 4267: Comparison: @code{MIN MAX =}
 4268: @item
 4269: Logic: @code{AND OR XOR NOT}
 4270: @item
 4271: Stack manipulation: @code{DUP DROP SWAP OVER}
 4272: @item
 4273: Loops and decisions: @code{IF ELSE ENDIF ?DO I LOOP}
 4274: @item
 4275: Input/Output: @code{. ." EMIT CR KEY}
 4276: @item
 4277: Defining words: @code{: ; CREATE}
 4278: @item
 4279: Memory allocation words: @code{ALLOT ,}
 4280: @item
 4281: Tools: @code{SEE WORDS .S MARKER}
 4282: @end itemize
 4283: 
 4284: When you have mastered those, go on to:
 4285: 
 4286: @itemize @bullet
 4287: @item
 4288: More defining words: @code{VARIABLE CONSTANT VALUE TO CREATE DOES>}
 4289: @item
 4290: Memory access: @code{@@ !}
 4291: @end itemize
 4292: 
 4293: When you have mastered these, there's nothing for it but to read through
 4294: the whole of this manual and find out what you've missed.
 4295: 
 4296: @comment ----------------------------------------------
 4297: @node Exercises,  , Where to go next, Introduction
 4298: @section Exercises
 4299: @cindex exercises
 4300: 
 4301: TODO: provide a set of programming excercises linked into the stuff done
 4302: already and into other sections of the manual. Provide solutions to all
 4303: the exercises in a .fs file in the distribution.
 4304: 
 4305: @c Get some inspiration from Starting Forth and Kelly&Spies.
 4306: 
 4307: @c excercises:
 4308: @c 1. take inches and convert to feet and inches.
 4309: @c 2. take temperature and convert from fahrenheight to celcius;
 4310: @c    may need to care about symmetric vs floored??
 4311: @c 3. take input line and do character substitution
 4312: @c    to encipher or decipher
 4313: @c 4. as above but work on a file for in and out
 4314: @c 5. take input line and convert to pig-latin 
 4315: @c
 4316: @c thing of sets of things to exercise then come up with
 4317: @c problems that need those things.
 4318: 
 4319: 
 4320: @c ******************************************************************
 4321: @node Words, Error messages, Introduction, Top
 4322: @chapter Forth Words
 4323: @cindex words
 4324: 
 4325: @menu
 4326: * Notation::                    
 4327: * Case insensitivity::          
 4328: * Comments::                    
 4329: * Boolean Flags::               
 4330: * Arithmetic::                  
 4331: * Stack Manipulation::          
 4332: * Memory::                      
 4333: * Control Structures::          
 4334: * Defining Words::              
 4335: * Interpretation and Compilation Semantics::  
 4336: * Tokens for Words::            
 4337: * The Text Interpreter::        
 4338: * Word Lists::                  
 4339: * Environmental Queries::       
 4340: * Files::                       
 4341: * Blocks::                      
 4342: * Other I/O::                   
 4343: * Programming Tools::           
 4344: * Assembler and Code Words::    
 4345: * Threading Words::             
 4346: * Locals::                      
 4347: * Structures::                  
 4348: * Object-oriented Forth::       
 4349: * Passing Commands to the OS::  
 4350: * Keeping track of Time::       
 4351: * Miscellaneous Words::         
 4352: @end menu
 4353: 
 4354: @node Notation, Case insensitivity, Words, Words
 4355: @section Notation
 4356: @cindex notation of glossary entries
 4357: @cindex format of glossary entries
 4358: @cindex glossary notation format
 4359: @cindex word glossary entry format
 4360: 
 4361: The Forth words are described in this section in the glossary notation
 4362: that has become a de-facto standard for Forth texts:
 4363: 
 4364: @format
 4365: @i{word}     @i{Stack effect}   @i{wordset}   @i{pronunciation}
 4366: @end format
 4367: @i{Description}
 4368: 
 4369: @table @var
 4370: @item word
 4371: The name of the word.
 4372: 
 4373: @item Stack effect
 4374: @cindex stack effect
 4375: The stack effect is written in the notation @code{@i{before} --
 4376: @i{after}}, where @i{before} and @i{after} describe the top of
 4377: stack entries before and after the execution of the word. The rest of
 4378: the stack is not touched by the word. The top of stack is rightmost,
 4379: i.e., a stack sequence is written as it is typed in. Note that Gforth
 4380: uses a separate floating point stack, but a unified stack
 4381: notation. Also, return stack effects are not shown in @i{stack
 4382: effect}, but in @i{Description}. The name of a stack item describes
 4383: the type and/or the function of the item. See below for a discussion of
 4384: the types.
 4385: 
 4386: All words have two stack effects: A compile-time stack effect and a
 4387: run-time stack effect. The compile-time stack-effect of most words is
 4388: @i{ -- }. If the compile-time stack-effect of a word deviates from
 4389: this standard behaviour, or the word does other unusual things at
 4390: compile time, both stack effects are shown; otherwise only the run-time
 4391: stack effect is shown.
 4392: 
 4393: @cindex pronounciation of words
 4394: @item pronunciation
 4395: How the word is pronounced.
 4396: 
 4397: @cindex wordset
 4398: @cindex environment wordset
 4399: @item wordset
 4400: The ANS Forth standard is divided into several word sets. A standard
 4401: system need not support all of them. Therefore, in theory, the fewer
 4402: word sets your program uses the more portable it will be. However, we
 4403: suspect that most ANS Forth systems on personal machines will feature
 4404: all word sets. Words that are not defined in ANS Forth have
 4405: @code{gforth} or @code{gforth-internal} as word set. @code{gforth}
 4406: describes words that will work in future releases of Gforth;
 4407: @code{gforth-internal} words are more volatile. Environmental query
 4408: strings are also displayed like words; you can recognize them by the
 4409: @code{environment} in the word set field.
 4410: 
 4411: @item Description
 4412: A description of the behaviour of the word.
 4413: @end table
 4414: 
 4415: @cindex types of stack items
 4416: @cindex stack item types
 4417: The type of a stack item is specified by the character(s) the name
 4418: starts with:
 4419: 
 4420: @table @code
 4421: @item f
 4422: @cindex @code{f}, stack item type
 4423: Boolean flags, i.e. @code{false} or @code{true}.
 4424: @item c
 4425: @cindex @code{c}, stack item type
 4426: Char
 4427: @item w
 4428: @cindex @code{w}, stack item type
 4429: Cell, can contain an integer or an address
 4430: @item n
 4431: @cindex @code{n}, stack item type
 4432: signed integer
 4433: @item u
 4434: @cindex @code{u}, stack item type
 4435: unsigned integer
 4436: @item d
 4437: @cindex @code{d}, stack item type
 4438: double sized signed integer
 4439: @item ud
 4440: @cindex @code{ud}, stack item type
 4441: double sized unsigned integer
 4442: @item r
 4443: @cindex @code{r}, stack item type
 4444: Float (on the FP stack)
 4445: @item a-
 4446: @cindex @code{a_}, stack item type
 4447: Cell-aligned address
 4448: @item c-
 4449: @cindex @code{c_}, stack item type
 4450: Char-aligned address (note that a Char may have two bytes in Windows NT)
 4451: @item f-
 4452: @cindex @code{f_}, stack item type
 4453: Float-aligned address
 4454: @item df-
 4455: @cindex @code{df_}, stack item type
 4456: Address aligned for IEEE double precision float
 4457: @item sf-
 4458: @cindex @code{sf_}, stack item type
 4459: Address aligned for IEEE single precision float
 4460: @item xt
 4461: @cindex @code{xt}, stack item type
 4462: Execution token, same size as Cell
 4463: @item wid
 4464: @cindex @code{wid}, stack item type
 4465: Word list ID, same size as Cell
 4466: @item ior, wior
 4467: @cindex ior type description
 4468: @cindex wior type description
 4469: I/O result code, cell-sized.  In Gforth, you can @code{throw} iors.
 4470: @item f83name
 4471: @cindex @code{f83name}, stack item type
 4472: Pointer to a name structure
 4473: @item "
 4474: @cindex @code{"}, stack item type
 4475: string in the input stream (not on the stack). The terminating character
 4476: is a blank by default. If it is not a blank, it is shown in @code{<>}
 4477: quotes.
 4478: @end table
 4479: 
 4480: @comment ----------------------------------------------
 4481: @node Case insensitivity, Comments, Notation, Words
 4482: @section Case insensitivity
 4483: @cindex case sensitivity
 4484: @cindex upper and lower case
 4485: 
 4486: Gforth is case-insensitive; you can enter definitions and invoke
 4487: Standard words using upper, lower or mixed case (however,
 4488: @pxref{core-idef, Implementation-defined options, Implementation-defined
 4489: options}).
 4490: 
 4491: ANS Forth only @i{requires} implementations to recognise Standard words
 4492: when they are typed entirely in upper case. Therefore, a Standard
 4493: program must use upper case for all Standard words. You can use whatever
 4494: case you like for words that you define, but in a Standard program you
 4495: have to use the words in the same case that you defined them.
 4496: 
 4497: Gforth supports case sensitivity through @code{table}s (case-sensitive
 4498: wordlists, @pxref{Word Lists}).
 4499: 
 4500: Two people have asked how to convert Gforth to be case-sensitive; while
 4501: we think this is a bad idea, you can change all wordlists into tables
 4502: like this:
 4503: 
 4504: @example
 4505: ' table-find forth-wordlist wordlist-map @ !
 4506: @end example
 4507: 
 4508: Note that you now have to type the predefined words in the same case
 4509: that we defined them, which are varying.  You may want to convert them
 4510: to your favourite case before doing this operation (I won't explain how,
 4511: because if you are even contemplating doing this, you'd better have
 4512: enough knowledge of Forth systems to know this already).
 4513: 
 4514: @node Comments, Boolean Flags, Case insensitivity, Words
 4515: @section Comments
 4516: @cindex comments
 4517: 
 4518: Forth supports two styles of comment; the traditional @i{in-line} comment,
 4519: @code{(} and its modern cousin, the @i{comment to end of line}; @code{\}.
 4520: 
 4521: 
 4522: doc-(
 4523: doc-\
 4524: doc-\G
 4525: 
 4526: 
 4527: @node Boolean Flags, Arithmetic, Comments, Words
 4528: @section Boolean Flags
 4529: @cindex Boolean flags
 4530: 
 4531: A Boolean flag is cell-sized. A cell with all bits clear represents the
 4532: flag @code{false} and a flag with all bits set represents the flag
 4533: @code{true}. Words that check a flag (for example, @code{IF}) will treat
 4534: a cell that has @i{any} bit set as @code{true}.
 4535: @c on and off to Memory? 
 4536: @c true and false to "Bitwise operations" or "Numeric comparison"?
 4537: 
 4538: doc-true
 4539: doc-false
 4540: doc-on
 4541: doc-off
 4542: 
 4543: 
 4544: @node Arithmetic, Stack Manipulation, Boolean Flags, Words
 4545: @section Arithmetic
 4546: @cindex arithmetic words
 4547: 
 4548: @cindex division with potentially negative operands
 4549: Forth arithmetic is not checked, i.e., you will not hear about integer
 4550: overflow on addition or multiplication, you may hear about division by
 4551: zero if you are lucky. The operator is written after the operands, but
 4552: the operands are still in the original order. I.e., the infix @code{2-1}
 4553: corresponds to @code{2 1 -}. Forth offers a variety of division
 4554: operators. If you perform division with potentially negative operands,
 4555: you do not want to use @code{/} or @code{/mod} with its undefined
 4556: behaviour, but rather @code{fm/mod} or @code{sm/mod} (probably the
 4557: former, @pxref{Mixed precision}).
 4558: @comment TODO discuss the different division forms and the std approach
 4559: 
 4560: @menu
 4561: * Single precision::            
 4562: * Double precision::            Double-cell integer arithmetic
 4563: * Bitwise operations::          
 4564: * Numeric comparison::          
 4565: * Mixed precision::             Operations with single and double-cell integers
 4566: * Floating Point::              
 4567: @end menu
 4568: 
 4569: @node Single precision, Double precision, Arithmetic, Arithmetic
 4570: @subsection Single precision
 4571: @cindex single precision arithmetic words
 4572: 
 4573: @c !! cell undefined
 4574: 
 4575: By default, numbers in Forth are single-precision integers that are one
 4576: cell in size. They can be signed or unsigned, depending upon how you
 4577: treat them. For the rules used by the text interpreter for recognising
 4578: single-precision integers see @ref{Number Conversion}.
 4579: 
 4580: These words are all defined for signed operands, but some of them also
 4581: work for unsigned numbers: @code{+}, @code{1+}, @code{-}, @code{1-},
 4582: @code{*}.
 4583: 
 4584: doc-+
 4585: doc-1+
 4586: doc--
 4587: doc-1-
 4588: doc-*
 4589: doc-/
 4590: doc-mod
 4591: doc-/mod
 4592: doc-negate
 4593: doc-abs
 4594: doc-min
 4595: doc-max
 4596: doc-floored
 4597: 
 4598: 
 4599: @node Double precision, Bitwise operations, Single precision, Arithmetic
 4600: @subsection Double precision
 4601: @cindex double precision arithmetic words
 4602: 
 4603: For the rules used by the text interpreter for
 4604: recognising double-precision integers, see @ref{Number Conversion}.
 4605: 
 4606: A double precision number is represented by a cell pair, with the most
 4607: significant cell at the TOS. It is trivial to convert an unsigned single
 4608: to a double: simply push a @code{0} onto the TOS. Since numbers are
 4609: represented by Gforth using 2's complement arithmetic, converting a
 4610: signed single to a (signed) double requires sign-extension across the
 4611: most significant cell. This can be achieved using @code{s>d}. The moral
 4612: of the story is that you cannot convert a number without knowing whether
 4613: it represents an unsigned or a signed number.
 4614: 
 4615: These words are all defined for signed operands, but some of them also
 4616: work for unsigned numbers: @code{d+}, @code{d-}.
 4617: 
 4618: doc-s>d
 4619: doc-d>s
 4620: doc-d+
 4621: doc-d-
 4622: doc-dnegate
 4623: doc-dabs
 4624: doc-dmin
 4625: doc-dmax
 4626: 
 4627: 
 4628: @node Bitwise operations, Numeric comparison, Double precision, Arithmetic
 4629: @subsection Bitwise operations
 4630: @cindex bitwise operation words
 4631: 
 4632: 
 4633: doc-and
 4634: doc-or
 4635: doc-xor
 4636: doc-invert
 4637: doc-lshift
 4638: doc-rshift
 4639: doc-2*
 4640: doc-d2*
 4641: doc-2/
 4642: doc-d2/
 4643: 
 4644: 
 4645: @node Numeric comparison, Mixed precision, Bitwise operations, Arithmetic
 4646: @subsection Numeric comparison
 4647: @cindex numeric comparison words
 4648: 
 4649: Note that the words that compare for equality (@code{= <> 0= 0<> d= d<>
 4650: d0= d0<>}) work for for both signed and unsigned numbers.
 4651: 
 4652: doc-<
 4653: doc-<=
 4654: doc-<>
 4655: doc-=
 4656: doc->
 4657: doc->=
 4658: 
 4659: doc-0<
 4660: doc-0<=
 4661: doc-0<>
 4662: doc-0=
 4663: doc-0>
 4664: doc-0>=
 4665: 
 4666: doc-u<
 4667: doc-u<=
 4668: @c u<> and u= exist but are the same as <> and =
 4669: @c doc-u<>
 4670: @c doc-u=
 4671: doc-u>
 4672: doc-u>=
 4673: 
 4674: doc-within
 4675: 
 4676: doc-d<
 4677: doc-d<=
 4678: doc-d<>
 4679: doc-d=
 4680: doc-d>
 4681: doc-d>=
 4682: 
 4683: doc-d0<
 4684: doc-d0<=
 4685: doc-d0<>
 4686: doc-d0=
 4687: doc-d0>
 4688: doc-d0>=
 4689: 
 4690: doc-du<
 4691: doc-du<=
 4692: @c du<> and du= exist but are the same as d<> and d=
 4693: @c doc-du<>
 4694: @c doc-du=
 4695: doc-du>
 4696: doc-du>=
 4697: 
 4698: 
 4699: @node Mixed precision, Floating Point, Numeric comparison, Arithmetic
 4700: @subsection Mixed precision
 4701: @cindex mixed precision arithmetic words
 4702: 
 4703: 
 4704: doc-m+
 4705: doc-*/
 4706: doc-*/mod
 4707: doc-m*
 4708: doc-um*
 4709: doc-m*/
 4710: doc-um/mod
 4711: doc-fm/mod
 4712: doc-sm/rem
 4713: 
 4714: 
 4715: @node Floating Point,  , Mixed precision, Arithmetic
 4716: @subsection Floating Point
 4717: @cindex floating point arithmetic words
 4718: 
 4719: For the rules used by the text interpreter for
 4720: recognising floating-point numbers see @ref{Number Conversion}.
 4721: 
 4722: Gforth has a separate floating point stack, but the documentation uses
 4723: the unified notation.@footnote{It's easy to generate the separate
 4724: notation from that by just separating the floating-point numbers out:
 4725: e.g. @code{( n r1 u r2 -- r3 )} becomes @code{( n u -- ) ( F: r1 r2 --
 4726: r3 )}.}
 4727: 
 4728: @cindex floating-point arithmetic, pitfalls
 4729: Floating point numbers have a number of unpleasant surprises for the
 4730: unwary (e.g., floating point addition is not associative) and even a few
 4731: for the wary. You should not use them unless you know what you are doing
 4732: or you don't care that the results you get are totally bogus. If you
 4733: want to learn about the problems of floating point numbers (and how to
 4734: avoid them), you might start with @cite{David Goldberg,
 4735: @uref{http://www.validgh.com/goldberg/paper.ps,What Every Computer
 4736: Scientist Should Know About Floating-Point Arithmetic}, ACM Computing
 4737: Surveys 23(1):5@minus{}48, March 1991}.
 4738: 
 4739: 
 4740: doc-d>f
 4741: doc-f>d
 4742: doc-f+
 4743: doc-f-
 4744: doc-f*
 4745: doc-f/
 4746: doc-fnegate
 4747: doc-fabs
 4748: doc-fmax
 4749: doc-fmin
 4750: doc-floor
 4751: doc-fround
 4752: doc-f**
 4753: doc-fsqrt
 4754: doc-fexp
 4755: doc-fexpm1
 4756: doc-fln
 4757: doc-flnp1
 4758: doc-flog
 4759: doc-falog
 4760: doc-f2*
 4761: doc-f2/
 4762: doc-1/f
 4763: doc-precision
 4764: doc-set-precision
 4765: 
 4766: @cindex angles in trigonometric operations
 4767: @cindex trigonometric operations
 4768: Angles in floating point operations are given in radians (a full circle
 4769: has 2 pi radians).
 4770: 
 4771: doc-fsin
 4772: doc-fcos
 4773: doc-fsincos
 4774: doc-ftan
 4775: doc-fasin
 4776: doc-facos
 4777: doc-fatan
 4778: doc-fatan2
 4779: doc-fsinh
 4780: doc-fcosh
 4781: doc-ftanh
 4782: doc-fasinh
 4783: doc-facosh
 4784: doc-fatanh
 4785: doc-pi
 4786: 
 4787: @cindex equality of floats
 4788: @cindex floating-point comparisons
 4789: One particular problem with floating-point arithmetic is that comparison
 4790: for equality often fails when you would expect it to succeed.  For this
 4791: reason approximate equality is often preferred (but you still have to
 4792: know what you are doing).  Also note that IEEE NaNs may compare
 4793: differently from what you might expect.  The comparison words are:
 4794: 
 4795: doc-f~rel
 4796: doc-f~abs
 4797: doc-f~
 4798: doc-f=
 4799: doc-f<>
 4800: 
 4801: doc-f<
 4802: doc-f<=
 4803: doc-f>
 4804: doc-f>=
 4805: 
 4806: doc-f0<
 4807: doc-f0<=
 4808: doc-f0<>
 4809: doc-f0=
 4810: doc-f0>
 4811: doc-f0>=
 4812: 
 4813: 
 4814: @node Stack Manipulation, Memory, Arithmetic, Words
 4815: @section Stack Manipulation
 4816: @cindex stack manipulation words
 4817: 
 4818: @cindex floating-point stack in the standard
 4819: Gforth maintains a number of separate stacks:
 4820: 
 4821: @cindex data stack
 4822: @cindex parameter stack
 4823: @itemize @bullet
 4824: @item
 4825: A data stack (also known as the @dfn{parameter stack}) -- for
 4826: characters, cells, addresses, and double cells.
 4827: 
 4828: @cindex floating-point stack
 4829: @item
 4830: A floating point stack -- for holding floating point (FP) numbers.
 4831: 
 4832: @cindex return stack
 4833: @item
 4834: A return stack -- for holding the return addresses of colon
 4835: definitions and other (non-FP) data.
 4836: 
 4837: @cindex locals stack
 4838: @item
 4839: A locals stack -- for holding local variables.
 4840: @end itemize
 4841: 
 4842: @menu
 4843: * Data stack::                  
 4844: * Floating point stack::        
 4845: * Return stack::                
 4846: * Locals stack::                
 4847: * Stack pointer manipulation::  
 4848: @end menu
 4849: 
 4850: @node Data stack, Floating point stack, Stack Manipulation, Stack Manipulation
 4851: @subsection Data stack
 4852: @cindex data stack manipulation words
 4853: @cindex stack manipulations words, data stack
 4854: 
 4855: 
 4856: doc-drop
 4857: doc-nip
 4858: doc-dup
 4859: doc-over
 4860: doc-tuck
 4861: doc-swap
 4862: doc-pick
 4863: doc-rot
 4864: doc--rot
 4865: doc-?dup
 4866: doc-roll
 4867: doc-2drop
 4868: doc-2nip
 4869: doc-2dup
 4870: doc-2over
 4871: doc-2tuck
 4872: doc-2swap
 4873: doc-2rot
 4874: 
 4875: 
 4876: @node Floating point stack, Return stack, Data stack, Stack Manipulation
 4877: @subsection Floating point stack
 4878: @cindex floating-point stack manipulation words
 4879: @cindex stack manipulation words, floating-point stack
 4880: 
 4881: Whilst every sane Forth has a separate floating-point stack, it is not
 4882: strictly required; an ANS Forth system could theoretically keep
 4883: floating-point numbers on the data stack. As an additional difficulty,
 4884: you don't know how many cells a floating-point number takes. It is
 4885: reportedly possible to write words in a way that they work also for a
 4886: unified stack model, but we do not recommend trying it. Instead, just
 4887: say that your program has an environmental dependency on a separate
 4888: floating-point stack.
 4889: 
 4890: doc-floating-stack
 4891: 
 4892: doc-fdrop
 4893: doc-fnip
 4894: doc-fdup
 4895: doc-fover
 4896: doc-ftuck
 4897: doc-fswap
 4898: doc-fpick
 4899: doc-frot
 4900: 
 4901: 
 4902: @node Return stack, Locals stack, Floating point stack, Stack Manipulation
 4903: @subsection Return stack
 4904: @cindex return stack manipulation words
 4905: @cindex stack manipulation words, return stack
 4906: 
 4907: @cindex return stack and locals
 4908: @cindex locals and return stack
 4909: A Forth system is allowed to keep local variables on the
 4910: return stack. This is reasonable, as local variables usually eliminate
 4911: the need to use the return stack explicitly. So, if you want to produce
 4912: a standard compliant program and you are using local variables in a
 4913: word, forget about return stack manipulations in that word (refer to the
 4914: standard document for the exact rules).
 4915: 
 4916: doc->r
 4917: doc-r>
 4918: doc-r@
 4919: doc-rdrop
 4920: doc-2>r
 4921: doc-2r>
 4922: doc-2r@
 4923: doc-2rdrop
 4924: 
 4925: 
 4926: @node Locals stack, Stack pointer manipulation, Return stack, Stack Manipulation
 4927: @subsection Locals stack
 4928: 
 4929: Gforth uses an extra locals stack. It is described, along with the
 4930: reasons for its existence, in @ref{Implementation,Implementation of locals}.
 4931: 
 4932: @node Stack pointer manipulation,  , Locals stack, Stack Manipulation
 4933: @subsection Stack pointer manipulation
 4934: @cindex stack pointer manipulation words
 4935: 
 4936: @c removed s0 r0 l0 -- they are obsolete aliases for sp0 rp0 lp0
 4937: doc-sp0
 4938: doc-sp@
 4939: doc-sp!
 4940: doc-fp0
 4941: doc-fp@
 4942: doc-fp!
 4943: doc-rp0
 4944: doc-rp@
 4945: doc-rp!
 4946: doc-lp0
 4947: doc-lp@
 4948: doc-lp!
 4949: 
 4950: 
 4951: @node Memory, Control Structures, Stack Manipulation, Words
 4952: @section Memory
 4953: @cindex memory words
 4954: 
 4955: @menu
 4956: * Memory model::                
 4957: * Dictionary allocation::       
 4958: * Heap Allocation::             
 4959: * Memory Access::               
 4960: * Address arithmetic::          
 4961: * Memory Blocks::               
 4962: @end menu
 4963: 
 4964: In addition to the standard Forth memory allocation words, there is also
 4965: a @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
 4966: garbage collector}.
 4967: 
 4968: @node Memory model, Dictionary allocation, Memory, Memory
 4969: @subsection ANS Forth and Gforth memory models
 4970: 
 4971: @c The ANS Forth description is a mess (e.g., is the heap part of
 4972: @c the dictionary?), so let's not stick to closely with it.
 4973: 
 4974: ANS Forth considers a Forth system as consisting of several address
 4975: spaces, of which only @dfn{data space} is managed and accessible with
 4976: the memory words.  Memory not necessarily in data space includes the
 4977: stacks, the code (called code space) and the headers (called name
 4978: space). In Gforth everything is in data space, but the code for the
 4979: primitives is usually read-only.
 4980: 
 4981: Data space is divided into a number of areas: The (data space portion of
 4982: the) dictionary@footnote{Sometimes, the term @dfn{dictionary} is used to
 4983: refer to the search data structure embodied in word lists and headers,
 4984: because it is used for looking up names, just as you would in a
 4985: conventional dictionary.}, the heap, and a number of system-allocated
 4986: buffers.
 4987: 
 4988: @cindex address arithmetic restrictions, ANS vs. Gforth
 4989: @cindex contiguous regions, ANS vs. Gforth
 4990: In ANS Forth data space is also divided into contiguous regions.  You
 4991: can only use address arithmetic within a contiguous region, not between
 4992: them.  Usually each allocation gives you one contiguous region, but the
 4993: dictionary allocation words have additional rules (@pxref{Dictionary
 4994: allocation}).
 4995: 
 4996: Gforth provides one big address space, and address arithmetic can be
 4997: performed between any addresses. However, in the dictionary headers or
 4998: code are interleaved with data, so almost the only contiguous data space
 4999: regions there are those described by ANS Forth as contiguous; but you
 5000: can be sure that the dictionary is allocated towards increasing
 5001: addresses even between contiguous regions.  The memory order of
 5002: allocations in the heap is platform-dependent (and possibly different
 5003: from one run to the next).
 5004: 
 5005: 
 5006: @node Dictionary allocation, Heap Allocation, Memory model, Memory
 5007: @subsection Dictionary allocation
 5008: @cindex reserving data space
 5009: @cindex data space - reserving some
 5010: 
 5011: Dictionary allocation is a stack-oriented allocation scheme, i.e., if
 5012: you want to deallocate X, you also deallocate everything
 5013: allocated after X.
 5014: 
 5015: @cindex contiguous regions in dictionary allocation
 5016: The allocations using the words below are contiguous and grow the region
 5017: towards increasing addresses.  Other words that allocate dictionary
 5018: memory of any kind (i.e., defining words including @code{:noname}) end
 5019: the contiguous region and start a new one.
 5020: 
 5021: In ANS Forth only @code{create}d words are guaranteed to produce an
 5022: address that is the start of the following contiguous region.  In
 5023: particular, the cell allocated by @code{variable} is not guaranteed to
 5024: be contiguous with following @code{allot}ed memory.
 5025: 
 5026: You can deallocate memory by using @code{allot} with a negative argument
 5027: (with some restrictions, see @code{allot}). For larger deallocations use
 5028: @code{marker}.
 5029: 
 5030: 
 5031: doc-here
 5032: doc-unused
 5033: doc-allot
 5034: doc-c,
 5035: doc-f,
 5036: doc-,
 5037: doc-2,
 5038: 
 5039: Memory accesses have to be aligned (@pxref{Address arithmetic}). So of
 5040: course you should allocate memory in an aligned way, too. I.e., before
 5041: allocating allocating a cell, @code{here} must be cell-aligned, etc.
 5042: The words below align @code{here} if it is not already.  Basically it is
 5043: only already aligned for a type, if the last allocation was a multiple
 5044: of the size of this type and if @code{here} was aligned for this type
 5045: before.
 5046: 
 5047: After freshly @code{create}ing a word, @code{here} is @code{align}ed in
 5048: ANS Forth (@code{maxalign}ed in Gforth).
 5049: 
 5050: doc-align
 5051: doc-falign
 5052: doc-sfalign
 5053: doc-dfalign
 5054: doc-maxalign
 5055: doc-cfalign
 5056: 
 5057: 
 5058: @node Heap Allocation, Memory Access, Dictionary allocation, Memory
 5059: @subsection Heap allocation
 5060: @cindex heap allocation
 5061: @cindex dynamic allocation of memory
 5062: @cindex memory-allocation word set
 5063: 
 5064: @cindex contiguous regions and heap allocation
 5065: Heap allocation supports deallocation of allocated memory in any
 5066: order. Dictionary allocation is not affected by it (i.e., it does not
 5067: end a contiguous region). In Gforth, these words are implemented using
 5068: the standard C library calls malloc(), free() and resize().
 5069: 
 5070: The memory region produced by one invocation of @code{allocate} or
 5071: @code{resize} is internally contiguous.  There is no contiguity between
 5072: such a region and any other region (including others allocated from the
 5073: heap).
 5074: 
 5075: doc-allocate
 5076: doc-free
 5077: doc-resize
 5078: 
 5079: 
 5080: @node Memory Access, Address arithmetic, Heap Allocation, Memory
 5081: @subsection Memory Access
 5082: @cindex memory access words
 5083: 
 5084: doc-@
 5085: doc-!
 5086: doc-+!
 5087: doc-c@
 5088: doc-c!
 5089: doc-2@
 5090: doc-2!
 5091: doc-f@
 5092: doc-f!
 5093: doc-sf@
 5094: doc-sf!
 5095: doc-df@
 5096: doc-df!
 5097: 
 5098: 
 5099: @node Address arithmetic, Memory Blocks, Memory Access, Memory
 5100: @subsection Address arithmetic
 5101: @cindex address arithmetic words
 5102: 
 5103: Address arithmetic is the foundation on which you can build data
 5104: structures like arrays, records (@pxref{Structures}) and objects
 5105: (@pxref{Object-oriented Forth}).
 5106: 
 5107: @cindex address unit
 5108: @cindex au (address unit)
 5109: ANS Forth does not specify the sizes of the data types. Instead, it
 5110: offers a number of words for computing sizes and doing address
 5111: arithmetic. Address arithmetic is performed in terms of address units
 5112: (aus); on most systems the address unit is one byte. Note that a
 5113: character may have more than one au, so @code{chars} is no noop (on
 5114: platforms where it is a noop, it compiles to nothing).
 5115: 
 5116: The basic address arithmetic words are @code{+} and @code{-}.  E.g., if
 5117: you have the address of a cell, perform @code{1 cells +}, and you will
 5118: have the address of the next cell.
 5119: 
 5120: @cindex contiguous regions and address arithmetic
 5121: In ANS Forth you can perform address arithmetic only within a contiguous
 5122: region, i.e., if you have an address into one region, you can only add
 5123: and subtract such that the result is still within the region; you can
 5124: only subtract or compare addresses from within the same contiguous
 5125: region.  Reasons: several contiguous regions can be arranged in memory
 5126: in any way; on segmented systems addresses may have unusual
 5127: representations, such that address arithmetic only works within a
 5128: region.  Gforth provides a few more guarantees (linear address space,
 5129: dictionary grows upwards), but in general I have found it easy to stay
 5130: within contiguous regions (exception: computing and comparing to the
 5131: address just beyond the end of an array).
 5132: 
 5133: @cindex alignment of addresses for types
 5134: ANS Forth also defines words for aligning addresses for specific
 5135: types. Many computers require that accesses to specific data types
 5136: must only occur at specific addresses; e.g., that cells may only be
 5137: accessed at addresses divisible by 4. Even if a machine allows unaligned
 5138: accesses, it can usually perform aligned accesses faster. 
 5139: 
 5140: For the performance-conscious: alignment operations are usually only
 5141: necessary during the definition of a data structure, not during the
 5142: (more frequent) accesses to it.
 5143: 
 5144: ANS Forth defines no words for character-aligning addresses. This is not
 5145: an oversight, but reflects the fact that addresses that are not
 5146: char-aligned have no use in the standard and therefore will not be
 5147: created.
 5148: 
 5149: @cindex @code{CREATE} and alignment
 5150: ANS Forth guarantees that addresses returned by @code{CREATE}d words
 5151: are cell-aligned; in addition, Gforth guarantees that these addresses
 5152: are aligned for all purposes.
 5153: 
 5154: Note that the ANS Forth word @code{char} has nothing to do with address
 5155: arithmetic.
 5156: 
 5157: 
 5158: doc-chars
 5159: doc-char+
 5160: doc-cells
 5161: doc-cell+
 5162: doc-cell
 5163: doc-aligned
 5164: doc-floats
 5165: doc-float+
 5166: doc-float
 5167: doc-faligned
 5168: doc-sfloats
 5169: doc-sfloat+
 5170: doc-sfaligned
 5171: doc-dfloats
 5172: doc-dfloat+
 5173: doc-dfaligned
 5174: doc-maxaligned
 5175: doc-cfaligned
 5176: doc-address-unit-bits
 5177: 
 5178: 
 5179: @node Memory Blocks,  , Address arithmetic, Memory
 5180: @subsection Memory Blocks
 5181: @cindex memory block words
 5182: @cindex character strings - moving and copying
 5183: 
 5184: Memory blocks often represent character strings; For ways of storing
 5185: character strings in memory see @ref{String Formats}.  For other
 5186: string-processing words see @ref{Displaying characters and strings}.
 5187: 
 5188: A few of these words work on address unit blocks.  In that case, you
 5189: usually have to insert @code{CHARS} before the word when working on
 5190: character strings.  Most words work on character blocks, and expect a
 5191: char-aligned address.
 5192: 
 5193: When copying characters between overlapping memory regions, use
 5194: @code{chars move} or choose carefully between @code{cmove} and
 5195: @code{cmove>}.
 5196: 
 5197: doc-move
 5198: doc-erase
 5199: doc-cmove
 5200: doc-cmove>
 5201: doc-fill
 5202: doc-blank
 5203: doc-compare
 5204: doc-search
 5205: doc--trailing
 5206: doc-/string
 5207: 
 5208: 
 5209: @comment TODO examples
 5210: 
 5211: 
 5212: @node Control Structures, Defining Words, Memory, Words
 5213: @section Control Structures
 5214: @cindex control structures
 5215: 
 5216: Control structures in Forth cannot be used interpretively, only in a
 5217: colon definition@footnote{To be precise, they have no interpretation
 5218: semantics (@pxref{Interpretation and Compilation Semantics}).}. We do
 5219: not like this limitation, but have not seen a satisfying way around it
 5220: yet, although many schemes have been proposed.
 5221: 
 5222: @menu
 5223: * Selection::                   IF ... ELSE ... ENDIF
 5224: * Simple Loops::                BEGIN ...
 5225: * Counted Loops::               DO
 5226: * Arbitrary control structures::  
 5227: * Calls and returns::           
 5228: * Exception Handling::          
 5229: @end menu
 5230: 
 5231: @node Selection, Simple Loops, Control Structures, Control Structures
 5232: @subsection Selection
 5233: @cindex selection control structures
 5234: @cindex control structures for selection
 5235: 
 5236: @cindex @code{IF} control structure
 5237: @example
 5238: @i{flag}
 5239: IF
 5240:   @i{code}
 5241: ENDIF
 5242: @end example
 5243: @noindent
 5244: 
 5245: If @i{flag} is non-zero (as far as @code{IF} etc. are concerned, a cell
 5246: with any bit set represents truth) @i{code} is executed.
 5247: 
 5248: @example
 5249: @i{flag}
 5250: IF
 5251:   @i{code1}
 5252: ELSE
 5253:   @i{code2}
 5254: ENDIF
 5255: @end example
 5256: 
 5257: If @var{flag} is true, @i{code1} is executed, otherwise @i{code2} is
 5258: executed.
 5259: 
 5260: You can use @code{THEN} instead of @code{ENDIF}. Indeed, @code{THEN} is
 5261: standard, and @code{ENDIF} is not, although it is quite popular. We
 5262: recommend using @code{ENDIF}, because it is less confusing for people
 5263: who also know other languages (and is not prone to reinforcing negative
 5264: prejudices against Forth in these people). Adding @code{ENDIF} to a
 5265: system that only supplies @code{THEN} is simple:
 5266: @example
 5267: : ENDIF   POSTPONE THEN ; immediate
 5268: @end example
 5269: 
 5270: [According to @cite{Webster's New Encyclopedic Dictionary}, @dfn{then
 5271: (adv.)}  has the following meanings:
 5272: @quotation
 5273: ... 2b: following next after in order ... 3d: as a necessary consequence
 5274: (if you were there, then you saw them).
 5275: @end quotation
 5276: Forth's @code{THEN} has the meaning 2b, whereas @code{THEN} in Pascal
 5277: and many other programming languages has the meaning 3d.]
 5278: 
 5279: Gforth also provides the words @code{?DUP-IF} and @code{?DUP-0=-IF}, so
 5280: you can avoid using @code{?dup}. Using these alternatives is also more
 5281: efficient than using @code{?dup}. Definitions in ANS Forth
 5282: for @code{ENDIF}, @code{?DUP-IF} and @code{?DUP-0=-IF} are provided in
 5283: @file{compat/control.fs}.
 5284: 
 5285: @cindex @code{CASE} control structure
 5286: @example
 5287: @i{n}
 5288: CASE
 5289:   @i{n1} OF @i{code1} ENDOF
 5290:   @i{n2} OF @i{code2} ENDOF
 5291:   @dots{}
 5292:   ( n ) @i{default-code} ( n )
 5293: ENDCASE
 5294: @end example
 5295: 
 5296: Executes the first @i{codei}, where the @i{ni} is equal to @i{n}.  If no
 5297: @i{ni} matches, the optional @i{default-code} is executed. The optional
 5298: default case can be added by simply writing the code after the last
 5299: @code{ENDOF}. It may use @i{n}, which is on top of the stack, but must
 5300: not consume it.
 5301: 
 5302: @progstyle
 5303: To keep the code understandable, you should ensure that on all paths
 5304: through a selection construct the stack is changed in the same way
 5305: (wrt. number and types of stack items consumed and pushed).
 5306: 
 5307: @node Simple Loops, Counted Loops, Selection, Control Structures
 5308: @subsection Simple Loops
 5309: @cindex simple loops
 5310: @cindex loops without count 
 5311: 
 5312: @cindex @code{WHILE} loop
 5313: @example
 5314: BEGIN
 5315:   @i{code1}
 5316:   @i{flag}
 5317: WHILE
 5318:   @i{code2}
 5319: REPEAT
 5320: @end example
 5321: 
 5322: @i{code1} is executed and @i{flag} is computed. If it is true,
 5323: @i{code2} is executed and the loop is restarted; If @i{flag} is
 5324: false, execution continues after the @code{REPEAT}.
 5325: 
 5326: @cindex @code{UNTIL} loop
 5327: @example
 5328: BEGIN
 5329:   @i{code}
 5330:   @i{flag}
 5331: UNTIL
 5332: @end example
 5333: 
 5334: @i{code} is executed. The loop is restarted if @code{flag} is false.
 5335: 
 5336: @progstyle
 5337: To keep the code understandable, a complete iteration of the loop should
 5338: not change the number and types of the items on the stacks.
 5339: 
 5340: @cindex endless loop
 5341: @cindex loops, endless
 5342: @example
 5343: BEGIN
 5344:   @i{code}
 5345: AGAIN
 5346: @end example
 5347: 
 5348: This is an endless loop.
 5349: 
 5350: @node Counted Loops, Arbitrary control structures, Simple Loops, Control Structures
 5351: @subsection Counted Loops
 5352: @cindex counted loops
 5353: @cindex loops, counted
 5354: @cindex @code{DO} loops
 5355: 
 5356: The basic counted loop is:
 5357: @example
 5358: @i{limit} @i{start}
 5359: ?DO
 5360:   @i{body}
 5361: LOOP
 5362: @end example
 5363: 
 5364: This performs one iteration for every integer, starting from @i{start}
 5365: and up to, but excluding @i{limit}. The counter, or @i{index}, can be
 5366: accessed with @code{i}. For example, the loop:
 5367: @example
 5368: 10 0 ?DO
 5369:   i .
 5370: LOOP
 5371: @end example
 5372: @noindent
 5373: prints @code{0 1 2 3 4 5 6 7 8 9}
 5374: 
 5375: The index of the innermost loop can be accessed with @code{i}, the index
 5376: of the next loop with @code{j}, and the index of the third loop with
 5377: @code{k}.
 5378: 
 5379: 
 5380: doc-i
 5381: doc-j
 5382: doc-k
 5383: 
 5384: 
 5385: The loop control data are kept on the return stack, so there are some
 5386: restrictions on mixing return stack accesses and counted loop words. In
 5387: particuler, if you put values on the return stack outside the loop, you
 5388: cannot read them inside the loop@footnote{well, not in a way that is
 5389: portable.}. If you put values on the return stack within a loop, you
 5390: have to remove them before the end of the loop and before accessing the
 5391: index of the loop.
 5392: 
 5393: There are several variations on the counted loop:
 5394: 
 5395: @itemize @bullet
 5396: @item
 5397: @code{LEAVE} leaves the innermost counted loop immediately; execution
 5398: continues after the associated @code{LOOP} or @code{NEXT}. For example:
 5399: 
 5400: @example
 5401: 10 0 ?DO  i DUP . 3 = IF LEAVE THEN LOOP
 5402: @end example
 5403: prints @code{0 1 2 3}
 5404: 
 5405: 
 5406: @item
 5407: @code{UNLOOP} prepares for an abnormal loop exit, e.g., via
 5408: @code{EXIT}. @code{UNLOOP} removes the loop control parameters from the
 5409: return stack so @code{EXIT} can get to its return address. For example:
 5410: 
 5411: @example
 5412: : demo 10 0 ?DO i DUP . 3 = IF UNLOOP EXIT THEN LOOP ." Done" ;
 5413: @end example
 5414: prints @code{0 1 2 3}
 5415: 
 5416: 
 5417: @item
 5418: If @i{start} is greater than @i{limit}, a @code{?DO} loop is entered
 5419: (and @code{LOOP} iterates until they become equal by wrap-around
 5420: arithmetic). This behaviour is usually not what you want. Therefore,
 5421: Gforth offers @code{+DO} and @code{U+DO} (as replacements for
 5422: @code{?DO}), which do not enter the loop if @i{start} is greater than
 5423: @i{limit}; @code{+DO} is for signed loop parameters, @code{U+DO} for
 5424: unsigned loop parameters.
 5425: 
 5426: @item
 5427: @code{?DO} can be replaced by @code{DO}. @code{DO} always enters
 5428: the loop, independent of the loop parameters. Do not use @code{DO}, even
 5429: if you know that the loop is entered in any case. Such knowledge tends
 5430: to become invalid during maintenance of a program, and then the
 5431: @code{DO} will make trouble.
 5432: 
 5433: @item
 5434: @code{LOOP} can be replaced with @code{@i{n} +LOOP}; this updates the
 5435: index by @i{n} instead of by 1. The loop is terminated when the border
 5436: between @i{limit-1} and @i{limit} is crossed. E.g.:
 5437: 
 5438: @example
 5439: 4 0 +DO  i .  2 +LOOP
 5440: @end example
 5441: @noindent
 5442: prints @code{0 2}
 5443: 
 5444: @example
 5445: 4 1 +DO  i .  2 +LOOP
 5446: @end example
 5447: @noindent
 5448: prints @code{1 3}
 5449: 
 5450: @item
 5451: @cindex negative increment for counted loops
 5452: @cindex counted loops with negative increment
 5453: The behaviour of @code{@i{n} +LOOP} is peculiar when @i{n} is negative:
 5454: 
 5455: @example
 5456: -1 0 ?DO  i .  -1 +LOOP
 5457: @end example
 5458: @noindent
 5459: prints @code{0 -1}
 5460: 
 5461: @example
 5462: 0 0 ?DO  i .  -1 +LOOP
 5463: @end example
 5464: prints nothing.
 5465: 
 5466: Therefore we recommend avoiding @code{@i{n} +LOOP} with negative
 5467: @i{n}. One alternative is @code{@i{u} -LOOP}, which reduces the
 5468: index by @i{u} each iteration. The loop is terminated when the border
 5469: between @i{limit+1} and @i{limit} is crossed. Gforth also provides
 5470: @code{-DO} and @code{U-DO} for down-counting loops. E.g.:
 5471: 
 5472: @example
 5473: -2 0 -DO  i .  1 -LOOP
 5474: @end example
 5475: @noindent
 5476: prints @code{0 -1}
 5477: 
 5478: @example
 5479: -1 0 -DO  i .  1 -LOOP
 5480: @end example
 5481: @noindent
 5482: prints @code{0}
 5483: 
 5484: @example
 5485: 0 0 -DO  i .  1 -LOOP
 5486: @end example
 5487: @noindent
 5488: prints nothing.
 5489: 
 5490: @end itemize
 5491: 
 5492: Unfortunately, @code{+DO}, @code{U+DO}, @code{-DO}, @code{U-DO} and
 5493: @code{-LOOP} are not defined in ANS Forth. However, an implementation
 5494: for these words that uses only standard words is provided in
 5495: @file{compat/loops.fs}.
 5496: 
 5497: 
 5498: @cindex @code{FOR} loops
 5499: Another counted loop is:
 5500: @example
 5501: @i{n}
 5502: FOR
 5503:   @i{body}
 5504: NEXT
 5505: @end example
 5506: This is the preferred loop of native code compiler writers who are too
 5507: lazy to optimize @code{?DO} loops properly. This loop structure is not
 5508: defined in ANS Forth. In Gforth, this loop iterates @i{n+1} times;
 5509: @code{i} produces values starting with @i{n} and ending with 0. Other
 5510: Forth systems may behave differently, even if they support @code{FOR}
 5511: loops. To avoid problems, don't use @code{FOR} loops.
 5512: 
 5513: @node Arbitrary control structures, Calls and returns, Counted Loops, Control Structures
 5514: @subsection Arbitrary control structures
 5515: @cindex control structures, user-defined
 5516: 
 5517: @cindex control-flow stack
 5518: ANS Forth permits and supports using control structures in a non-nested
 5519: way. Information about incomplete control structures is stored on the
 5520: control-flow stack. This stack may be implemented on the Forth data
 5521: stack, and this is what we have done in Gforth.
 5522: 
 5523: @cindex @code{orig}, control-flow stack item
 5524: @cindex @code{dest}, control-flow stack item
 5525: An @i{orig} entry represents an unresolved forward branch, a @i{dest}
 5526: entry represents a backward branch target. A few words are the basis for
 5527: building any control structure possible (except control structures that
 5528: need storage, like calls, coroutines, and backtracking).
 5529: 
 5530: 
 5531: doc-if
 5532: doc-ahead
 5533: doc-then
 5534: doc-begin
 5535: doc-until
 5536: doc-again
 5537: doc-cs-pick
 5538: doc-cs-roll
 5539: 
 5540: 
 5541: The Standard words @code{CS-PICK} and @code{CS-ROLL} allow you to
 5542: manipulate the control-flow stack in a portable way. Without them, you
 5543: would need to know how many stack items are occupied by a control-flow
 5544: entry (many systems use one cell. In Gforth they currently take three,
 5545: but this may change in the future).
 5546: 
 5547: Some standard control structure words are built from these words:
 5548: 
 5549: 
 5550: doc-else
 5551: doc-while
 5552: doc-repeat
 5553: 
 5554: 
 5555: @noindent
 5556: Gforth adds some more control-structure words:
 5557: 
 5558: 
 5559: doc-endif
 5560: doc-?dup-if
 5561: doc-?dup-0=-if
 5562: 
 5563: 
 5564: @noindent
 5565: Counted loop words constitute a separate group of words:
 5566: 
 5567: 
 5568: doc-?do
 5569: doc-+do
 5570: doc-u+do
 5571: doc--do
 5572: doc-u-do
 5573: doc-do
 5574: doc-for
 5575: doc-loop
 5576: doc-+loop
 5577: doc--loop
 5578: doc-next
 5579: doc-leave
 5580: doc-?leave
 5581: doc-unloop
 5582: doc-done
 5583: 
 5584: 
 5585: The standard does not allow using @code{CS-PICK} and @code{CS-ROLL} on
 5586: @i{do-sys}. Gforth allows it, but it's your job to ensure that for
 5587: every @code{?DO} etc. there is exactly one @code{UNLOOP} on any path
 5588: through the definition (@code{LOOP} etc. compile an @code{UNLOOP} on the
 5589: fall-through path). Also, you have to ensure that all @code{LEAVE}s are
 5590: resolved (by using one of the loop-ending words or @code{DONE}).
 5591: 
 5592: @noindent
 5593: Another group of control structure words are:
 5594: 
 5595: 
 5596: doc-case
 5597: doc-endcase
 5598: doc-of
 5599: doc-endof
 5600: 
 5601: 
 5602: @i{case-sys} and @i{of-sys} cannot be processed using @code{CS-PICK} and
 5603: @code{CS-ROLL}.
 5604: 
 5605: @subsubsection Programming Style
 5606: @cindex control structures programming style
 5607: @cindex programming style, arbitrary control structures
 5608: 
 5609: In order to ensure readability we recommend that you do not create
 5610: arbitrary control structures directly, but define new control structure
 5611: words for the control structure you want and use these words in your
 5612: program. For example, instead of writing:
 5613: 
 5614: @example
 5615: BEGIN
 5616:   ...
 5617: IF [ 1 CS-ROLL ]
 5618:   ...
 5619: AGAIN THEN
 5620: @end example
 5621: 
 5622: @noindent
 5623: we recommend defining control structure words, e.g.,
 5624: 
 5625: @example
 5626: : WHILE ( DEST -- ORIG DEST )
 5627:  POSTPONE IF
 5628:  1 CS-ROLL ; immediate
 5629: 
 5630: : REPEAT ( orig dest -- )
 5631:  POSTPONE AGAIN
 5632:  POSTPONE THEN ; immediate
 5633: @end example
 5634: 
 5635: @noindent
 5636: and then using these to create the control structure:
 5637: 
 5638: @example
 5639: BEGIN
 5640:   ...
 5641: WHILE
 5642:   ...
 5643: REPEAT
 5644: @end example
 5645: 
 5646: That's much easier to read, isn't it? Of course, @code{REPEAT} and
 5647: @code{WHILE} are predefined, so in this example it would not be
 5648: necessary to define them.
 5649: 
 5650: @node Calls and returns, Exception Handling, Arbitrary control structures, Control Structures
 5651: @subsection Calls and returns
 5652: @cindex calling a definition
 5653: @cindex returning from a definition
 5654: 
 5655: @cindex recursive definitions
 5656: A definition can be called simply be writing the name of the definition
 5657: to be called. Normally a definition is invisible during its own
 5658: definition. If you want to write a directly recursive definition, you
 5659: can use @code{recursive} to make the current definition visible, or
 5660: @code{recurse} to call the current definition directly.
 5661: 
 5662: 
 5663: doc-recursive
 5664: doc-recurse
 5665: 
 5666: 
 5667: @comment TODO add example of the two recursion methods
 5668: @quotation
 5669: @progstyle
 5670: I prefer using @code{recursive} to @code{recurse}, because calling the
 5671: definition by name is more descriptive (if the name is well-chosen) than
 5672: the somewhat cryptic @code{recurse}.  E.g., in a quicksort
 5673: implementation, it is much better to read (and think) ``now sort the
 5674: partitions'' than to read ``now do a recursive call''.
 5675: @end quotation
 5676: 
 5677: For mutual recursion, use @code{Defer}red words, like this:
 5678: 
 5679: @example
 5680: Defer foo
 5681: 
 5682: : bar ( ... -- ... )
 5683:  ... foo ... ;
 5684: 
 5685: :noname ( ... -- ... )
 5686:  ... bar ... ;
 5687: IS foo
 5688: @end example
 5689: 
 5690: Deferred words are discussed in more detail in @ref{Deferred words}.
 5691: 
 5692: The current definition returns control to the calling definition when
 5693: the end of the definition is reached or @code{EXIT} is encountered.
 5694: 
 5695: doc-exit
 5696: doc-;s
 5697: 
 5698: 
 5699: @node Exception Handling,  , Calls and returns, Control Structures
 5700: @subsection Exception Handling
 5701: @cindex exceptions
 5702: 
 5703: @c quit is a very bad idea for error handling, 
 5704: @c because it does not translate into a THROW
 5705: @c it also does not belong into this chapter
 5706: 
 5707: If a word detects an error condition that it cannot handle, it can
 5708: @code{throw} an exception.  In the simplest case, this will terminate
 5709: your program, and report an appropriate error.
 5710: 
 5711: doc-throw
 5712: 
 5713: @code{Throw} consumes a cell-sized error number on the stack. There are
 5714: some predefined error numbers in ANS Forth (see @file{errors.fs}).  In
 5715: Gforth (and most other systems) you can use the iors produced by various
 5716: words as error numbers (e.g., a typical use of @code{allocate} is
 5717: @code{allocate throw}).  Gforth also provides the word @code{exception}
 5718: to define your own error numbers (with decent error reporting); an ANS
 5719: Forth version of this word (but without the error messages) is available
 5720: in @code{compat/except.fs}.  And finally, you can use your own error
 5721: numbers (anything outside the range -4095..0), but won't get nice error
 5722: messages, only numbers.  For example, try:
 5723: 
 5724: @example
 5725: -10 throw                    \ ANS defined
 5726: -267 throw                   \ system defined
 5727: s" my error" exception throw \ user defined
 5728: 7 throw                      \ arbitrary number
 5729: @end example
 5730: 
 5731: doc---exception-exception
 5732: 
 5733: A common idiom to @code{THROW} a specific error if a flag is true is
 5734: this:
 5735: 
 5736: @example
 5737: @code{( flag ) 0<> @i{errno} and throw}
 5738: @end example
 5739: 
 5740: Your program can provide exception handlers to catch exceptions.  An
 5741: exception handler can be used to correct the problem, or to clean up
 5742: some data structures and just throw the exception to the next exception
 5743: handler.  Note that @code{throw} jumps to the dynamically innermost
 5744: exception handler.  The system's exception handler is outermost, and just
 5745: prints an error and restarts command-line interpretation (or, in batch
 5746: mode (i.e., while processing the shell command line), leaves Gforth).
 5747: 
 5748: The ANS Forth way to catch exceptions is @code{catch}:
 5749: 
 5750: doc-catch
 5751: 
 5752: The most common use of exception handlers is to clean up the state when
 5753: an error happens.  E.g.,
 5754: 
 5755: @example
 5756: base @ >r hex \ actually the hex should be inside foo, or we h
 5757: ['] foo catch ( nerror|0 )
 5758: r> base !
 5759: ( nerror|0 ) throw \ pass it on
 5760: @end example
 5761: 
 5762: A use of @code{catch} for handling the error @code{myerror} might look
 5763: like this:
 5764: 
 5765: @example
 5766: ['] foo catch
 5767: CASE
 5768:   myerror OF ... ( do something about it ) ENDOF
 5769:   dup throw \ default: pass other errors on, do nothing on non-errors
 5770: ENDCASE
 5771: @end example
 5772: 
 5773: Having to wrap the code into a separate word is often cumbersome,
 5774: therefore Gforth provides an alternative syntax:
 5775: 
 5776: @example
 5777: TRY
 5778:   @i{code1}
 5779: RECOVER     \ optional
 5780:   @i{code2} \ optional
 5781: ENDTRY
 5782: @end example
 5783: 
 5784: This performs @i{Code1}.  If @i{code1} completes normally, execution
 5785: continues after the @code{endtry}.  If @i{Code1} throws, the stacks are
 5786: reset to the state during @code{try}, the throw value is pushed on the
 5787: data stack, and execution constinues at @i{code2}, and finally falls
 5788: through the @code{endtry} into the following code. If there is no
 5789: @code{recover} clause, this works like an empty recover clause.
 5790: 
 5791: doc-try
 5792: doc-recover
 5793: doc-endtry
 5794: 
 5795: The cleanup example from above in this syntax:
 5796: 
 5797: @example
 5798: base @ >r TRY
 5799:   hex foo \ now the hex is placed correctly
 5800:   0       \ value for throw
 5801: ENDTRY
 5802: r> base ! throw
 5803: @end example
 5804: 
 5805: And here's the error handling example:
 5806: 
 5807: @example
 5808: TRY
 5809:   foo
 5810: RECOVER
 5811:   CASE
 5812:     myerror OF ... ( do something about it ) ENDOF
 5813:     throw \ pass other errors on
 5814:   ENDCASE
 5815: ENDTRY
 5816: @end example
 5817: 
 5818: @progstyle
 5819: As usual, you should ensure that the stack depth is statically known at
 5820: the end: either after the @code{throw} for passing on errors, or after
 5821: the @code{ENDTRY} (or, if you use @code{catch}, after the end of the
 5822: selection construct for handling the error).
 5823: 
 5824: There are two alternatives to @code{throw}: @code{Abort"} is conditional
 5825: and you can provide an error message.  @code{Abort} just produces an
 5826: ``Aborted'' error.
 5827: 
 5828: The problem with these words is that exception handlers cannot
 5829: differentiate between different @code{abort"}s; they just look like
 5830: @code{-2 throw} to them (the error message cannot be accessed by
 5831: standard programs).  Similar @code{abort} looks like @code{-1 throw} to
 5832: exception handlers.
 5833: 
 5834: doc-abort"
 5835: doc-abort
 5836: 
 5837: 
 5838: 
 5839: @c -------------------------------------------------------------
 5840: @node Defining Words, Interpretation and Compilation Semantics, Control Structures, Words
 5841: @section Defining Words
 5842: @cindex defining words
 5843: 
 5844: Defining words are used to extend Forth by creating new entries in the dictionary.
 5845: 
 5846: @menu
 5847: * CREATE::                      
 5848: * Variables::                   Variables and user variables
 5849: * Constants::                   
 5850: * Values::                      Initialised variables
 5851: * Colon Definitions::           
 5852: * Anonymous Definitions::       Definitions without names
 5853: * Supplying names::             Passing definition names as strings
 5854: * User-defined Defining Words::  
 5855: * Deferred words::              Allow forward references
 5856: * Aliases::                     
 5857: @end menu
 5858: 
 5859: @node CREATE, Variables, Defining Words, Defining Words
 5860: @subsection @code{CREATE}
 5861: @cindex simple defining words
 5862: @cindex defining words, simple
 5863: 
 5864: Defining words are used to create new entries in the dictionary. The
 5865: simplest defining word is @code{CREATE}. @code{CREATE} is used like
 5866: this:
 5867: 
 5868: @example
 5869: CREATE new-word1
 5870: @end example
 5871: 
 5872: @code{CREATE} is a parsing word, i.e., it takes an argument from the
 5873: input stream (@code{new-word1} in our example).  It generates a
 5874: dictionary entry for @code{new-word1}. When @code{new-word1} is
 5875: executed, all that it does is leave an address on the stack. The address
 5876: represents the value of the data space pointer (@code{HERE}) at the time
 5877: that @code{new-word1} was defined. Therefore, @code{CREATE} is a way of
 5878: associating a name with the address of a region of memory.
 5879: 
 5880: doc-create
 5881: 
 5882: Note that in ANS Forth guarantees only for @code{create} that its body
 5883: is in dictionary data space (i.e., where @code{here}, @code{allot}
 5884: etc. work, @pxref{Dictionary allocation}).  Also, in ANS Forth only
 5885: @code{create}d words can be modified with @code{does>}
 5886: (@pxref{User-defined Defining Words}).  And in ANS Forth @code{>body}
 5887: can only be applied to @code{create}d words.
 5888: 
 5889: By extending this example to reserve some memory in data space, we end
 5890: up with something like a @i{variable}. Here are two different ways to do
 5891: it:
 5892: 
 5893: @example
 5894: CREATE new-word2 1 cells allot  \ reserve 1 cell - initial value undefined
 5895: CREATE new-word3 4 ,            \ reserve 1 cell and initialise it (to 4)
 5896: @end example
 5897: 
 5898: The variable can be examined and modified using @code{@@} (``fetch'') and
 5899: @code{!} (``store'') like this:
 5900: 
 5901: @example
 5902: new-word2 @@ .      \ get address, fetch from it and display
 5903: 1234 new-word2 !   \ new value, get address, store to it
 5904: @end example
 5905: 
 5906: @cindex arrays
 5907: A similar mechanism can be used to create arrays. For example, an
 5908: 80-character text input buffer:
 5909: 
 5910: @example
 5911: CREATE text-buf 80 chars allot
 5912: 
 5913: text-buf 0 chars c@@ \ the 1st character (offset 0)
 5914: text-buf 3 chars c@@ \ the 4th character (offset 3)
 5915: @end example
 5916: 
 5917: You can build arbitrarily complex data structures by allocating
 5918: appropriate areas of memory. For further discussions of this, and to
 5919: learn about some Gforth tools that make it easier,
 5920: @xref{Structures}.
 5921: 
 5922: 
 5923: @node Variables, Constants, CREATE, Defining Words
 5924: @subsection Variables
 5925: @cindex variables
 5926: 
 5927: The previous section showed how a sequence of commands could be used to
 5928: generate a variable.  As a final refinement, the whole code sequence can
 5929: be wrapped up in a defining word (pre-empting the subject of the next
 5930: section), making it easier to create new variables:
 5931: 
 5932: @example
 5933: : myvariableX ( "name" -- a-addr ) CREATE 1 cells allot ;
 5934: : myvariable0 ( "name" -- a-addr ) CREATE 0 , ;
 5935: 
 5936: myvariableX foo \ variable foo starts off with an unknown value
 5937: myvariable0 joe \ whilst joe is initialised to 0
 5938: 
 5939: 45 3 * foo !   \ set foo to 135
 5940: 1234 joe !     \ set joe to 1234
 5941: 3 joe +!       \ increment joe by 3.. to 1237
 5942: @end example
 5943: 
 5944: Not surprisingly, there is no need to define @code{myvariable}, since
 5945: Forth already has a definition @code{Variable}. ANS Forth does not
 5946: guarantee that a @code{Variable} is initialised when it is created
 5947: (i.e., it may behave like @code{myvariableX}). In contrast, Gforth's
 5948: @code{Variable} initialises the variable to 0 (i.e., it behaves exactly
 5949: like @code{myvariable0}). Forth also provides @code{2Variable} and
 5950: @code{fvariable} for double and floating-point variables, respectively
 5951: -- they are initialised to 0. and 0e in Gforth. If you use a @code{Variable} to
 5952: store a boolean, you can use @code{on} and @code{off} to toggle its
 5953: state.
 5954: 
 5955: doc-variable
 5956: doc-2variable
 5957: doc-fvariable
 5958: 
 5959: @cindex user variables
 5960: @cindex user space
 5961: The defining word @code{User} behaves in the same way as @code{Variable}.
 5962: The difference is that it reserves space in @i{user (data) space} rather
 5963: than normal data space. In a Forth system that has a multi-tasker, each
 5964: task has its own set of user variables.
 5965: 
 5966: doc-user
 5967: @c doc-udp
 5968: @c doc-uallot
 5969: 
 5970: @comment TODO is that stuff about user variables strictly correct? Is it
 5971: @comment just terminal tasks that have user variables?
 5972: @comment should document tasker.fs (with some examples) elsewhere
 5973: @comment in this manual, then expand on user space and user variables.
 5974: 
 5975: @node Constants, Values, Variables, Defining Words
 5976: @subsection Constants
 5977: @cindex constants
 5978: 
 5979: @code{Constant} allows you to declare a fixed value and refer to it by
 5980: name. For example:
 5981: 
 5982: @example
 5983: 12 Constant INCHES-PER-FOOT
 5984: 3E+08 fconstant SPEED-O-LIGHT
 5985: @end example
 5986: 
 5987: A @code{Variable} can be both read and written, so its run-time
 5988: behaviour is to supply an address through which its current value can be
 5989: manipulated. In contrast, the value of a @code{Constant} cannot be
 5990: changed once it has been declared@footnote{Well, often it can be -- but
 5991: not in a Standard, portable way. It's safer to use a @code{Value} (read
 5992: on).} so it's not necessary to supply the address -- it is more
 5993: efficient to return the value of the constant directly. That's exactly
 5994: what happens; the run-time effect of a constant is to put its value on
 5995: the top of the stack (You can find one
 5996: way of implementing @code{Constant} in @ref{User-defined Defining Words}).
 5997: 
 5998: Forth also provides @code{2Constant} and @code{fconstant} for defining
 5999: double and floating-point constants, respectively.
 6000: 
 6001: doc-constant
 6002: doc-2constant
 6003: doc-fconstant
 6004: 
 6005: @c that's too deep, and it's not necessarily true for all ANS Forths. - anton
 6006: @c nac-> How could that not be true in an ANS Forth? You can't define a
 6007: @c constant, use it and then delete the definition of the constant..
 6008: 
 6009: @c anton->An ANS Forth system can compile a constant to a literal; On
 6010: @c decompilation you would see only the number, just as if it had been used
 6011: @c in the first place.  The word will stay, of course, but it will only be
 6012: @c used by the text interpreter (no run-time duties, except when it is 
 6013: @c POSTPONEd or somesuch).
 6014: 
 6015: @c nac:
 6016: @c I agree that it's rather deep, but IMO it is an important difference
 6017: @c relative to other programming languages.. often it's annoying: it
 6018: @c certainly changes my programming style relative to C.
 6019: 
 6020: @c anton: In what way?
 6021: 
 6022: Constants in Forth behave differently from their equivalents in other
 6023: programming languages. In other languages, a constant (such as an EQU in
 6024: assembler or a #define in C) only exists at compile-time; in the
 6025: executable program the constant has been translated into an absolute
 6026: number and, unless you are using a symbolic debugger, it's impossible to
 6027: know what abstract thing that number represents. In Forth a constant has
 6028: an entry in the header space and remains there after the code that uses
 6029: it has been defined. In fact, it must remain in the dictionary since it
 6030: has run-time duties to perform. For example:
 6031: 
 6032: @example
 6033: 12 Constant INCHES-PER-FOOT
 6034: : FEET-TO-INCHES ( n1 -- n2 ) INCHES-PER-FOOT * ;
 6035: @end example
 6036: 
 6037: @cindex in-lining of constants
 6038: When @code{FEET-TO-INCHES} is executed, it will in turn execute the xt
 6039: associated with the constant @code{INCHES-PER-FOOT}. If you use
 6040: @code{see} to decompile the definition of @code{FEET-TO-INCHES}, you can
 6041: see that it makes a call to @code{INCHES-PER-FOOT}. Some Forth compilers
 6042: attempt to optimise constants by in-lining them where they are used. You
 6043: can force Gforth to in-line a constant like this:
 6044: 
 6045: @example
 6046: : FEET-TO-INCHES ( n1 -- n2 ) [ INCHES-PER-FOOT ] LITERAL * ;
 6047: @end example
 6048: 
 6049: If you use @code{see} to decompile @i{this} version of
 6050: @code{FEET-TO-INCHES}, you can see that @code{INCHES-PER-FOOT} is no
 6051: longer present. To understand how this works, read
 6052: @ref{Interpret/Compile states}, and @ref{Literals}.
 6053: 
 6054: In-lining constants in this way might improve execution time
 6055: fractionally, and can ensure that a constant is now only referenced at
 6056: compile-time. However, the definition of the constant still remains in
 6057: the dictionary. Some Forth compilers provide a mechanism for controlling
 6058: a second dictionary for holding transient words such that this second
 6059: dictionary can be deleted later in order to recover memory
 6060: space. However, there is no standard way of doing this.
 6061: 
 6062: 
 6063: @node Values, Colon Definitions, Constants, Defining Words
 6064: @subsection Values
 6065: @cindex values
 6066: 
 6067: A @code{Value} behaves like a @code{Constant}, but it can be changed.
 6068: @code{TO} is a parsing word that changes a @code{Values}.  In Gforth
 6069: (not in ANS Forth) you can access (and change) a @code{value} also with
 6070: @code{>body}.
 6071: 
 6072: Here are some
 6073: examples:
 6074: 
 6075: @example
 6076: 12 Value APPLES     \ Define APPLES with an initial value of 12
 6077: 34 TO APPLES        \ Change the value of APPLES. TO is a parsing word
 6078: 1 ' APPLES >body +! \ Increment APPLES.  Non-standard usage.
 6079: APPLES              \ puts 35 on the top of the stack.
 6080: @end example
 6081: 
 6082: doc-value
 6083: doc-to
 6084: 
 6085: 
 6086: 
 6087: @node Colon Definitions, Anonymous Definitions, Values, Defining Words
 6088: @subsection Colon Definitions
 6089: @cindex colon definitions
 6090: 
 6091: @example
 6092: : name ( ... -- ... )
 6093:     word1 word2 word3 ;
 6094: @end example
 6095: 
 6096: @noindent
 6097: Creates a word called @code{name} that, upon execution, executes
 6098: @code{word1 word2 word3}. @code{name} is a @dfn{(colon) definition}.
 6099: 
 6100: The explanation above is somewhat superficial. For simple examples of
 6101: colon definitions see @ref{Your first definition}.  For an in-depth
 6102: discussion of some of the issues involved, @xref{Interpretation and
 6103: Compilation Semantics}.
 6104: 
 6105: doc-:
 6106: doc-;
 6107: 
 6108: 
 6109: @node Anonymous Definitions, Supplying names, Colon Definitions, Defining Words
 6110: @subsection Anonymous Definitions
 6111: @cindex colon definitions
 6112: @cindex defining words without name
 6113: 
 6114: Sometimes you want to define an @dfn{anonymous word}; a word without a
 6115: name. You can do this with:
 6116: 
 6117: doc-:noname
 6118: 
 6119: This leaves the execution token for the word on the stack after the
 6120: closing @code{;}. Here's an example in which a deferred word is
 6121: initialised with an @code{xt} from an anonymous colon definition:
 6122: 
 6123: @example
 6124: Defer deferred
 6125: :noname ( ... -- ... )
 6126:   ... ;
 6127: IS deferred
 6128: @end example
 6129: 
 6130: @noindent
 6131: Gforth provides an alternative way of doing this, using two separate
 6132: words:
 6133: 
 6134: doc-noname
 6135: @cindex execution token of last defined word
 6136: doc-lastxt
 6137: 
 6138: @noindent
 6139: The previous example can be rewritten using @code{noname} and
 6140: @code{lastxt}:
 6141: 
 6142: @example
 6143: Defer deferred
 6144: noname : ( ... -- ... )
 6145:   ... ;
 6146: lastxt IS deferred
 6147: @end example
 6148: 
 6149: @noindent
 6150: @code{noname} works with any defining word, not just @code{:}.
 6151: 
 6152: @code{lastxt} also works when the last word was not defined as
 6153: @code{noname}. It also has the useful property that is is valid as soon
 6154: as the header for a definition has been built. Thus:
 6155: 
 6156: @example
 6157: lastxt . : foo [ lastxt . ] ; ' foo .
 6158: @end example
 6159: 
 6160: @noindent
 6161: prints 3 numbers; the last two are the same.
 6162: 
 6163: @node Supplying names, User-defined Defining Words, Anonymous Definitions, Defining Words
 6164: @subsection Supplying the name of a defined word
 6165: @cindex names for defined words
 6166: @cindex defining words, name given in a string
 6167: 
 6168: By default, a defining word takes the name for the defined word from the
 6169: input stream. Sometimes you want to supply the name from a string. You
 6170: can do this with:
 6171: 
 6172: doc-nextname
 6173: 
 6174: For example:
 6175: 
 6176: @example
 6177: s" foo" nextname create
 6178: @end example
 6179: 
 6180: @noindent
 6181: is equivalent to:
 6182: 
 6183: @example
 6184: create foo
 6185: @end example
 6186: 
 6187: @noindent
 6188: @code{nextname} works with any defining word.
 6189: 
 6190: 
 6191: @node User-defined Defining Words, Deferred words, Supplying names, Defining Words
 6192: @subsection User-defined Defining Words
 6193: @cindex user-defined defining words
 6194: @cindex defining words, user-defined
 6195: 
 6196: You can create a new defining word by wrapping defining-time code around
 6197: an existing defining word and putting the sequence in a colon
 6198: definition. 
 6199: 
 6200: @c anton: This example is very complex and leads in a quite different
 6201: @c direction from the CREATE-DOES> stuff that follows.  It should probably
 6202: @c be done elsewhere, or as a subsubsection of this subsection (or as a
 6203: @c subsection of Defining Words)
 6204: 
 6205: For example, suppose that you have a word @code{stats} that
 6206: gathers statistics about colon definitions given the @i{xt} of the
 6207: definition, and you want every colon definition in your application to
 6208: make a call to @code{stats}. You can define and use a new version of
 6209: @code{:} like this:
 6210: 
 6211: @example
 6212: : stats ( xt -- ) DUP ." (Gathering statistics for " . ." )"
 6213:   ... ;  \ other code
 6214: 
 6215: : my: : lastxt postpone literal ['] stats compile, ;
 6216: 
 6217: my: foo + - ;
 6218: @end example
 6219: 
 6220: When @code{foo} is defined using @code{my:} these steps occur:
 6221: 
 6222: @itemize @bullet
 6223: @item
 6224: @code{my:} is executed.
 6225: @item
 6226: The @code{:} within the definition (the one between @code{my:} and
 6227: @code{lastxt}) is executed, and does just what it always does; it parses
 6228: the input stream for a name, builds a dictionary header for the name
 6229: @code{foo} and switches @code{state} from interpret to compile.
 6230: @item
 6231: The word @code{lastxt} is executed. It puts the @i{xt} for the word that is
 6232: being defined -- @code{foo} -- onto the stack.
 6233: @item
 6234: The code that was produced by @code{postpone literal} is executed; this
 6235: causes the value on the stack to be compiled as a literal in the code
 6236: area of @code{foo}.
 6237: @item
 6238: The code @code{['] stats} compiles a literal into the definition of
 6239: @code{my:}. When @code{compile,} is executed, that literal -- the
 6240: execution token for @code{stats} -- is layed down in the code area of
 6241: @code{foo} , following the literal@footnote{Strictly speaking, the
 6242: mechanism that @code{compile,} uses to convert an @i{xt} into something
 6243: in the code area is implementation-dependent. A threaded implementation
 6244: might spit out the execution token directly whilst another
 6245: implementation might spit out a native code sequence.}.
 6246: @item
 6247: At this point, the execution of @code{my:} is complete, and control
 6248: returns to the text interpreter. The text interpreter is in compile
 6249: state, so subsequent text @code{+ -} is compiled into the definition of
 6250: @code{foo} and the @code{;} terminates the definition as always.
 6251: @end itemize
 6252: 
 6253: You can use @code{see} to decompile a word that was defined using
 6254: @code{my:} and see how it is different from a normal @code{:}
 6255: definition. For example:
 6256: 
 6257: @example
 6258: : bar + - ;  \ like foo but using : rather than my:
 6259: see bar
 6260: : bar
 6261:   + - ;
 6262: see foo
 6263: : foo
 6264:   107645672 stats + - ;
 6265: 
 6266: \ use ' stats . to show that 107645672 is the xt for stats
 6267: @end example
 6268: 
 6269: You can use techniques like this to make new defining words in terms of
 6270: @i{any} existing defining word.
 6271: 
 6272: 
 6273: @cindex defining defining words
 6274: @cindex @code{CREATE} ... @code{DOES>}
 6275: If you want the words defined with your defining words to behave
 6276: differently from words defined with standard defining words, you can
 6277: write your defining word like this:
 6278: 
 6279: @example
 6280: : def-word ( "name" -- )
 6281:     CREATE @i{code1}
 6282: DOES> ( ... -- ... )
 6283:     @i{code2} ;
 6284: 
 6285: def-word name
 6286: @end example
 6287: 
 6288: @cindex child words
 6289: This fragment defines a @dfn{defining word} @code{def-word} and then
 6290: executes it.  When @code{def-word} executes, it @code{CREATE}s a new
 6291: word, @code{name}, and executes the code @i{code1}. The code @i{code2}
 6292: is not executed at this time. The word @code{name} is sometimes called a
 6293: @dfn{child} of @code{def-word}.
 6294: 
 6295: When you execute @code{name}, the address of the body of @code{name} is
 6296: put on the data stack and @i{code2} is executed (the address of the body
 6297: of @code{name} is the address @code{HERE} returns immediately after the
 6298: @code{CREATE}, i.e., the address a @code{create}d word returns by
 6299: default).
 6300: 
 6301: @c anton:
 6302: @c www.dictionary.com says:
 6303: @c at·a·vism: 1.The reappearance of a characteristic in an organism after
 6304: @c several generations of absence, usually caused by the chance
 6305: @c recombination of genes.  2.An individual or a part that exhibits
 6306: @c atavism. Also called throwback.  3.The return of a trait or recurrence
 6307: @c of previous behavior after a period of absence.
 6308: @c
 6309: @c Doesn't seem to fit.
 6310: 
 6311: @c @cindex atavism in child words
 6312: You can use @code{def-word} to define a set of child words that behave
 6313: similarly; they all have a common run-time behaviour determined by
 6314: @i{code2}. Typically, the @i{code1} sequence builds a data area in the
 6315: body of the child word. The structure of the data is common to all
 6316: children of @code{def-word}, but the data values are specific -- and
 6317: private -- to each child word. When a child word is executed, the
 6318: address of its private data area is passed as a parameter on TOS to be
 6319: used and manipulated@footnote{It is legitimate both to read and write to
 6320: this data area.} by @i{code2}.
 6321: 
 6322: The two fragments of code that make up the defining words act (are
 6323: executed) at two completely separate times:
 6324: 
 6325: @itemize @bullet
 6326: @item
 6327: At @i{define time}, the defining word executes @i{code1} to generate a
 6328: child word
 6329: @item
 6330: At @i{child execution time}, when a child word is invoked, @i{code2}
 6331: is executed, using parameters (data) that are private and specific to
 6332: the child word.
 6333: @end itemize
 6334: 
 6335: Another way of understanding the behaviour of @code{def-word} and
 6336: @code{name} is to say that, if you make the following definitions:
 6337: @example
 6338: : def-word1 ( "name" -- )
 6339:     CREATE @i{code1} ;
 6340: 
 6341: : action1 ( ... -- ... )
 6342:     @i{code2} ;
 6343: 
 6344: def-word1 name1
 6345: @end example
 6346: 
 6347: @noindent
 6348: Then using @code{name1 action1} is equivalent to using @code{name}.
 6349: 
 6350: The classic example is that you can define @code{CONSTANT} in this way:
 6351: 
 6352: @example
 6353: : CONSTANT ( w "name" -- )
 6354:     CREATE ,
 6355: DOES> ( -- w )
 6356:     @@ ;
 6357: @end example
 6358: 
 6359: @comment There is a beautiful description of how this works and what
 6360: @comment it does in the Forthwrite 100th edition.. as well as an elegant
 6361: @comment commentary on the Counting Fruits problem.
 6362: 
 6363: When you create a constant with @code{5 CONSTANT five}, a set of
 6364: define-time actions take place; first a new word @code{five} is created,
 6365: then the value 5 is laid down in the body of @code{five} with
 6366: @code{,}. When @code{five} is executed, the address of the body is put on
 6367: the stack, and @code{@@} retrieves the value 5. The word @code{five} has
 6368: no code of its own; it simply contains a data field and a pointer to the
 6369: code that follows @code{DOES>} in its defining word. That makes words
 6370: created in this way very compact.
 6371: 
 6372: The final example in this section is intended to remind you that space
 6373: reserved in @code{CREATE}d words is @i{data} space and therefore can be
 6374: both read and written by a Standard program@footnote{Exercise: use this
 6375: example as a starting point for your own implementation of @code{Value}
 6376: and @code{TO} -- if you get stuck, investigate the behaviour of @code{'} and
 6377: @code{[']}.}:
 6378: 
 6379: @example
 6380: : foo ( "name" -- )
 6381:     CREATE -1 ,
 6382: DOES> ( -- )
 6383:     @@ . ;
 6384: 
 6385: foo first-word
 6386: foo second-word
 6387: 
 6388: 123 ' first-word >BODY !
 6389: @end example
 6390: 
 6391: If @code{first-word} had been a @code{CREATE}d word, we could simply
 6392: have executed it to get the address of its data field. However, since it
 6393: was defined to have @code{DOES>} actions, its execution semantics are to
 6394: perform those @code{DOES>} actions. To get the address of its data field
 6395: it's necessary to use @code{'} to get its xt, then @code{>BODY} to
 6396: translate the xt into the address of the data field.  When you execute
 6397: @code{first-word}, it will display @code{123}. When you execute
 6398: @code{second-word} it will display @code{-1}.
 6399: 
 6400: @cindex stack effect of @code{DOES>}-parts
 6401: @cindex @code{DOES>}-parts, stack effect
 6402: In the examples above the stack comment after the @code{DOES>} specifies
 6403: the stack effect of the defined words, not the stack effect of the
 6404: following code (the following code expects the address of the body on
 6405: the top of stack, which is not reflected in the stack comment). This is
 6406: the convention that I use and recommend (it clashes a bit with using
 6407: locals declarations for stack effect specification, though).
 6408: 
 6409: @menu
 6410: * CREATE..DOES> applications::  
 6411: * CREATE..DOES> details::       
 6412: * Advanced does> usage example::  
 6413: @end menu
 6414: 
 6415: @node CREATE..DOES> applications, CREATE..DOES> details, User-defined Defining Words, User-defined Defining Words
 6416: @subsubsection Applications of @code{CREATE..DOES>}
 6417: @cindex @code{CREATE} ... @code{DOES>}, applications
 6418: 
 6419: You may wonder how to use this feature. Here are some usage patterns:
 6420: 
 6421: @cindex factoring similar colon definitions
 6422: When you see a sequence of code occurring several times, and you can
 6423: identify a meaning, you will factor it out as a colon definition. When
 6424: you see similar colon definitions, you can factor them using
 6425: @code{CREATE..DOES>}. E.g., an assembler usually defines several words
 6426: that look very similar:
 6427: @example
 6428: : ori, ( reg-target reg-source n -- )
 6429:     0 asm-reg-reg-imm ;
 6430: : andi, ( reg-target reg-source n -- )
 6431:     1 asm-reg-reg-imm ;
 6432: @end example
 6433: 
 6434: @noindent
 6435: This could be factored with:
 6436: @example
 6437: : reg-reg-imm ( op-code -- )
 6438:     CREATE ,
 6439: DOES> ( reg-target reg-source n -- )
 6440:     @@ asm-reg-reg-imm ;
 6441: 
 6442: 0 reg-reg-imm ori,
 6443: 1 reg-reg-imm andi,
 6444: @end example
 6445: 
 6446: @cindex currying
 6447: Another view of @code{CREATE..DOES>} is to consider it as a crude way to
 6448: supply a part of the parameters for a word (known as @dfn{currying} in
 6449: the functional language community). E.g., @code{+} needs two
 6450: parameters. Creating versions of @code{+} with one parameter fixed can
 6451: be done like this:
 6452: @example
 6453: : curry+ ( n1 -- )
 6454:     CREATE ,
 6455: DOES> ( n2 -- n1+n2 )
 6456:     @@ + ;
 6457: 
 6458:  3 curry+ 3+
 6459: -2 curry+ 2-
 6460: @end example
 6461: 
 6462: @node CREATE..DOES> details, Advanced does> usage example, CREATE..DOES> applications, User-defined Defining Words
 6463: @subsubsection The gory details of @code{CREATE..DOES>}
 6464: @cindex @code{CREATE} ... @code{DOES>}, details
 6465: 
 6466: doc-does>
 6467: 
 6468: @cindex @code{DOES>} in a separate definition
 6469: This means that you need not use @code{CREATE} and @code{DOES>} in the
 6470: same definition; you can put the @code{DOES>}-part in a separate
 6471: definition. This allows us to, e.g., select among different @code{DOES>}-parts:
 6472: @example
 6473: : does1 
 6474: DOES> ( ... -- ... )
 6475:     ... ;
 6476: 
 6477: : does2
 6478: DOES> ( ... -- ... )
 6479:     ... ;
 6480: 
 6481: : def-word ( ... -- ... )
 6482:     create ...
 6483:     IF
 6484:        does1
 6485:     ELSE
 6486:        does2
 6487:     ENDIF ;
 6488: @end example
 6489: 
 6490: In this example, the selection of whether to use @code{does1} or
 6491: @code{does2} is made at definition-time; at the time that the child word is
 6492: @code{CREATE}d.
 6493: 
 6494: @cindex @code{DOES>} in interpretation state
 6495: In a standard program you can apply a @code{DOES>}-part only if the last
 6496: word was defined with @code{CREATE}. In Gforth, the @code{DOES>}-part
 6497: will override the behaviour of the last word defined in any case. In a
 6498: standard program, you can use @code{DOES>} only in a colon
 6499: definition. In Gforth, you can also use it in interpretation state, in a
 6500: kind of one-shot mode; for example:
 6501: @example
 6502: CREATE name ( ... -- ... )
 6503:   @i{initialization}
 6504: DOES>
 6505:   @i{code} ;
 6506: @end example
 6507: 
 6508: @noindent
 6509: is equivalent to the standard:
 6510: @example
 6511: :noname
 6512: DOES>
 6513:     @i{code} ;
 6514: CREATE name EXECUTE ( ... -- ... )
 6515:     @i{initialization}
 6516: @end example
 6517: 
 6518: doc->body
 6519: 
 6520: @node Advanced does> usage example,  , CREATE..DOES> details, User-defined Defining Words
 6521: @subsubsection Advanced does> usage example
 6522: 
 6523: The MIPS disassembler (@file{arch/mips/disasm.fs}) contains many words
 6524: for disassembling instructions, that follow a very repetetive scheme:
 6525: 
 6526: @example
 6527: :noname @var{disasm-operands} s" @var{inst-name}" type ;
 6528: @var{entry-num} cells @var{table} + !
 6529: @end example
 6530: 
 6531: Of course, this inspires the idea to factor out the commonalities to
 6532: allow a definition like
 6533: 
 6534: @example
 6535: @var{disasm-operands} @var{entry-num} @var{table} define-inst @var{inst-name}
 6536: @end example
 6537: 
 6538: The parameters @var{disasm-operands} and @var{table} are usually
 6539: correlated.  Moreover, before I wrote the disassembler, there already
 6540: existed code that defines instructions like this:
 6541: 
 6542: @example
 6543: @var{entry-num} @var{inst-format} @var{inst-name}
 6544: @end example
 6545: 
 6546: This code comes from the assembler and resides in
 6547: @file{arch/mips/insts.fs}.
 6548: 
 6549: So I had to define the @var{inst-format} words that performed the scheme
 6550: above when executed.  At first I chose to use run-time code-generation:
 6551: 
 6552: @example
 6553: : @var{inst-format} ( entry-num "name" -- ; compiled code: addr w -- )
 6554:   :noname Postpone @var{disasm-operands}
 6555:   name Postpone sliteral Postpone type Postpone ;
 6556:   swap cells @var{table} + ! ;
 6557: @end example
 6558: 
 6559: Note that this supplies the other two parameters of the scheme above.
 6560: 
 6561: An alternative would have been to write this using
 6562: @code{create}/@code{does>}:
 6563: 
 6564: @example
 6565: : @var{inst-format} ( entry-num "name" -- )
 6566:   here name string, ( entry-num c-addr ) \ parse and save "name"
 6567:   noname create , ( entry-num )
 6568:   lastxt swap cells @var{table} + !
 6569: does> ( addr w -- )
 6570:   \ disassemble instruction w at addr
 6571:   @@ >r 
 6572:   @var{disasm-operands}
 6573:   r> count type ;
 6574: @end example
 6575: 
 6576: Somehow the first solution is simpler, mainly because it's simpler to
 6577: shift a string from definition-time to use-time with @code{sliteral}
 6578: than with @code{string,} and friends.
 6579: 
 6580: I wrote a lot of words following this scheme and soon thought about
 6581: factoring out the commonalities among them.  Note that this uses a
 6582: two-level defining word, i.e., a word that defines ordinary defining
 6583: words.
 6584: 
 6585: This time a solution involving @code{postpone} and friends seemed more
 6586: difficult (try it as an exercise), so I decided to use a
 6587: @code{create}/@code{does>} word; since I was already at it, I also used
 6588: @code{create}/@code{does>} for the lower level (try using
 6589: @code{postpone} etc. as an exercise), resulting in the following
 6590: definition:
 6591: 
 6592: @example
 6593: : define-format ( disasm-xt table-xt -- )
 6594:     \ define an instruction format that uses disasm-xt for
 6595:     \ disassembling and enters the defined instructions into table
 6596:     \ table-xt
 6597:     create 2,
 6598: does> ( u "inst" -- )
 6599:     \ defines an anonymous word for disassembling instruction inst,
 6600:     \ and enters it as u-th entry into table-xt
 6601:     2@@ swap here name string, ( u table-xt disasm-xt c-addr ) \ remember string
 6602:     noname create 2,      \ define anonymous word
 6603:     execute lastxt swap ! \ enter xt of defined word into table-xt
 6604: does> ( addr w -- )
 6605:     \ disassemble instruction w at addr
 6606:     2@@ >r ( addr w disasm-xt R: c-addr )
 6607:     execute ( R: c-addr ) \ disassemble operands
 6608:     r> count type ; \ print name 
 6609: @end example
 6610: 
 6611: Note that the tables here (in contrast to above) do the @code{cells +}
 6612: by themselves (that's why you have to pass an xt).  This word is used in
 6613: the following way:
 6614: 
 6615: @example
 6616: ' @var{disasm-operands} ' @var{table} define-format @var{inst-format}
 6617: @end example
 6618: 
 6619: In terms of currying, this kind of two-level defining word provides the
 6620: parameters in three stages: first @var{disasm-operands} and @var{table},
 6621: then @var{entry-num} and @var{inst-name}, finally @code{addr w}, i.e.,
 6622: the instruction to be disassembled.  
 6623: 
 6624: Of course this did not quite fit all the instruction format names used
 6625: in @file{insts.fs}, so I had to define a few wrappers that conditioned
 6626: the parameters into the right form.
 6627: 
 6628: If you have trouble following this section, don't worry.  First, this is
 6629: involved and takes time (and probably some playing around) to
 6630: understand; second, this is the first two-level
 6631: @code{create}/@code{does>} word I have written in seventeen years of
 6632: Forth; and if I did not have @file{insts.fs} to start with, I may well
 6633: have elected to use just a one-level defining word (with some repeating
 6634: of parameters when using the defining word). So it is not necessary to
 6635: understand this, but it may improve your understanding of Forth.
 6636: 
 6637: 
 6638: @node Deferred words, Aliases, User-defined Defining Words, Defining Words
 6639: @subsection Deferred words
 6640: @cindex deferred words
 6641: 
 6642: The defining word @code{Defer} allows you to define a word by name
 6643: without defining its behaviour; the definition of its behaviour is
 6644: deferred. Here are two situation where this can be useful:
 6645: 
 6646: @itemize @bullet
 6647: @item
 6648: Where you want to allow the behaviour of a word to be altered later, and
 6649: for all precompiled references to the word to change when its behaviour
 6650: is changed.
 6651: @item
 6652: For mutual recursion; @xref{Calls and returns}.
 6653: @end itemize
 6654: 
 6655: In the following example, @code{foo} always invokes the version of
 6656: @code{greet} that prints ``@code{Good morning}'' whilst @code{bar}
 6657: always invokes the version that prints ``@code{Hello}''. There is no way
 6658: of getting @code{foo} to use the later version without re-ordering the
 6659: source code and recompiling it.
 6660: 
 6661: @example
 6662: : greet ." Good morning" ;
 6663: : foo ... greet ... ;
 6664: : greet ." Hello" ;
 6665: : bar ... greet ... ;
 6666: @end example
 6667: 
 6668: This problem can be solved by defining @code{greet} as a @code{Defer}red
 6669: word. The behaviour of a @code{Defer}red word can be defined and
 6670: redefined at any time by using @code{IS} to associate the xt of a
 6671: previously-defined word with it. The previous example becomes:
 6672: 
 6673: @example
 6674: Defer greet ( -- )
 6675: : foo ... greet ... ;
 6676: : bar ... greet ... ;
 6677: : greet1 ( -- ) ." Good morning" ;
 6678: : greet2 ( -- ) ." Hello" ;
 6679: ' greet2 <IS> greet  \ make greet behave like greet2
 6680: @end example
 6681: 
 6682: @progstyle
 6683: You should write a stack comment for every deferred word, and put only
 6684: XTs into deferred words that conform to this stack effect.  Otherwise
 6685: it's too difficult to use the deferred word.
 6686: 
 6687: A deferred word can be used to improve the statistics-gathering example
 6688: from @ref{User-defined Defining Words}; rather than edit the
 6689: application's source code to change every @code{:} to a @code{my:}, do
 6690: this:
 6691: 
 6692: @example
 6693: : real: : ;     \ retain access to the original
 6694: defer :         \ redefine as a deferred word
 6695: ' my: <IS> :      \ use special version of :
 6696: \
 6697: \ load application here
 6698: \
 6699: ' real: <IS> :    \ go back to the original
 6700: @end example
 6701: 
 6702: 
 6703: One thing to note is that @code{<IS>} consumes its name when it is
 6704: executed.  If you want to specify the name at compile time, use
 6705: @code{[IS]}:
 6706: 
 6707: @example
 6708: : set-greet ( xt -- )
 6709:   [IS] greet ;
 6710: 
 6711: ' greet1 set-greet
 6712: @end example
 6713: 
 6714: A deferred word can only inherit execution semantics from the xt
 6715: (because that is all that an xt can represent -- for more discussion of
 6716: this @pxref{Tokens for Words}); by default it will have default
 6717: interpretation and compilation semantics deriving from this execution
 6718: semantics.  However, you can change the interpretation and compilation
 6719: semantics of the deferred word in the usual ways:
 6720: 
 6721: @example
 6722: : bar .... ; compile-only
 6723: Defer fred immediate
 6724: Defer jim
 6725: 
 6726: ' bar <IS> jim  \ jim has default semantics
 6727: ' bar <IS> fred \ fred is immediate
 6728: @end example
 6729: 
 6730: doc-defer
 6731: doc-<is>
 6732: doc-[is]
 6733: doc-is
 6734: @comment TODO document these: what's defers [is]
 6735: doc-what's
 6736: doc-defers
 6737: 
 6738: @c Use @code{words-deferred} to see a list of deferred words.
 6739: 
 6740: Definitions in ANS Forth for @code{defer}, @code{<is>} and @code{[is]}
 6741: are provided in @file{compat/defer.fs}.
 6742: 
 6743: 
 6744: @node Aliases,  , Deferred words, Defining Words
 6745: @subsection Aliases
 6746: @cindex aliases
 6747: 
 6748: The defining word @code{Alias} allows you to define a word by name that
 6749: has the same behaviour as some other word. Here are two situation where
 6750: this can be useful:
 6751: 
 6752: @itemize @bullet
 6753: @item
 6754: When you want access to a word's definition from a different word list
 6755: (for an example of this, see the definition of the @code{Root} word list
 6756: in the Gforth source).
 6757: @item
 6758: When you want to create a synonym; a definition that can be known by
 6759: either of two names (for example, @code{THEN} and @code{ENDIF} are
 6760: aliases).
 6761: @end itemize
 6762: 
 6763: Like deferred words, an alias has default compilation and interpretation
 6764: semantics at the beginning (not the modifications of the other word),
 6765: but you can change them in the usual ways (@code{immediate},
 6766: @code{compile-only}). For example:
 6767: 
 6768: @example
 6769: : foo ... ; immediate
 6770: 
 6771: ' foo Alias bar \ bar is not an immediate word
 6772: ' foo Alias fooby immediate \ fooby is an immediate word
 6773: @end example
 6774: 
 6775: Words that are aliases have the same xt, different headers in the
 6776: dictionary, and consequently different name tokens (@pxref{Tokens for
 6777: Words}) and possibly different immediate flags.  An alias can only have
 6778: default or immediate compilation semantics; you can define aliases for
 6779: combined words with @code{interpret/compile:} -- see @ref{Combined words}.
 6780: 
 6781: doc-alias
 6782: 
 6783: 
 6784: @node Interpretation and Compilation Semantics, Tokens for Words, Defining Words, Words
 6785: @section Interpretation and Compilation Semantics
 6786: @cindex semantics, interpretation and compilation
 6787: 
 6788: @cindex interpretation semantics
 6789: The @dfn{interpretation semantics} of a word are what the text
 6790: interpreter does when it encounters the word in interpret state. It also
 6791: appears in some other contexts, e.g., the execution token returned by
 6792: @code{' @i{word}} identifies the interpretation semantics of
 6793: @i{word} (in other words, @code{' @i{word} execute} is equivalent to
 6794: interpret-state text interpretation of @code{@i{word}}).
 6795: 
 6796: @cindex compilation semantics
 6797: The @dfn{compilation semantics} of a word are what the text interpreter
 6798: does when it encounters the word in compile state. It also appears in
 6799: other contexts, e.g, @code{POSTPONE @i{word}} compiles@footnote{In
 6800: standard terminology, ``appends to the current definition''.} the
 6801: compilation semantics of @i{word}.
 6802: 
 6803: @cindex execution semantics
 6804: The standard also talks about @dfn{execution semantics}. They are used
 6805: only for defining the interpretation and compilation semantics of many
 6806: words. By default, the interpretation semantics of a word are to
 6807: @code{execute} its execution semantics, and the compilation semantics of
 6808: a word are to @code{compile,} its execution semantics.@footnote{In
 6809: standard terminology: The default interpretation semantics are its
 6810: execution semantics; the default compilation semantics are to append its
 6811: execution semantics to the execution semantics of the current
 6812: definition.}
 6813: 
 6814: @comment TODO expand, make it co-operate with new sections on text interpreter.
 6815: 
 6816: @cindex immediate words
 6817: @cindex compile-only words
 6818: You can change the semantics of the most-recently defined word:
 6819: 
 6820: 
 6821: doc-immediate
 6822: doc-compile-only
 6823: doc-restrict
 6824: 
 6825: 
 6826: Note that ticking (@code{'}) a compile-only word gives an error
 6827: (``Interpreting a compile-only word'').
 6828: 
 6829: @menu
 6830: * Combined words::              
 6831: @end menu
 6832: 
 6833: @node Combined words,  , Interpretation and Compilation Semantics, Interpretation and Compilation Semantics
 6834: @subsection Combined Words
 6835: @cindex combined words
 6836: 
 6837: Gforth allows you to define @dfn{combined words} -- words that have an
 6838: arbitrary combination of interpretation and compilation semantics.
 6839: 
 6840: 
 6841: doc-interpret/compile:
 6842: 
 6843: 
 6844: This feature was introduced for implementing @code{TO} and @code{S"}. I
 6845: recommend that you do not define such words, as cute as they may be:
 6846: they make it hard to get at both parts of the word in some contexts.
 6847: E.g., assume you want to get an execution token for the compilation
 6848: part. Instead, define two words, one that embodies the interpretation
 6849: part, and one that embodies the compilation part.  Once you have done
 6850: that, you can define a combined word with @code{interpret/compile:} for
 6851: the convenience of your users.
 6852: 
 6853: You might try to use this feature to provide an optimizing
 6854: implementation of the default compilation semantics of a word. For
 6855: example, by defining:
 6856: @example
 6857: :noname
 6858:    foo bar ;
 6859: :noname
 6860:    POSTPONE foo POSTPONE bar ;
 6861: interpret/compile: opti-foobar
 6862: @end example
 6863: 
 6864: @noindent
 6865: as an optimizing version of:
 6866: 
 6867: @example
 6868: : foobar
 6869:     foo bar ;
 6870: @end example
 6871: 
 6872: Unfortunately, this does not work correctly with @code{[compile]},
 6873: because @code{[compile]} assumes that the compilation semantics of all
 6874: @code{interpret/compile:} words are non-default. I.e., @code{[compile]
 6875: opti-foobar} would compile compilation semantics, whereas
 6876: @code{[compile] foobar} would compile interpretation semantics.
 6877: 
 6878: @cindex state-smart words (are a bad idea)
 6879: Some people try to use @dfn{state-smart} words to emulate the feature provided
 6880: by @code{interpret/compile:} (words are state-smart if they check
 6881: @code{STATE} during execution). E.g., they would try to code
 6882: @code{foobar} like this:
 6883: 
 6884: @example
 6885: : foobar
 6886:   STATE @@
 6887:   IF ( compilation state )
 6888:     POSTPONE foo POSTPONE bar
 6889:   ELSE
 6890:     foo bar
 6891:   ENDIF ; immediate
 6892: @end example
 6893: 
 6894: Although this works if @code{foobar} is only processed by the text
 6895: interpreter, it does not work in other contexts (like @code{'} or
 6896: @code{POSTPONE}). E.g., @code{' foobar} will produce an execution token
 6897: for a state-smart word, not for the interpretation semantics of the
 6898: original @code{foobar}; when you execute this execution token (directly
 6899: with @code{EXECUTE} or indirectly through @code{COMPILE,}) in compile
 6900: state, the result will not be what you expected (i.e., it will not
 6901: perform @code{foo bar}). State-smart words are a bad idea. Simply don't
 6902: write them@footnote{For a more detailed discussion of this topic, see
 6903: M. Anton Ertl,
 6904: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,@code{State}-smartness---Why
 6905: it is Evil and How to Exorcise it}}, EuroForth '98.}!
 6906: 
 6907: @cindex defining words with arbitrary semantics combinations
 6908: It is also possible to write defining words that define words with
 6909: arbitrary combinations of interpretation and compilation semantics. In
 6910: general, they look like this:
 6911: 
 6912: @example
 6913: : def-word
 6914:     create-interpret/compile
 6915:     @i{code1}
 6916: interpretation>
 6917:     @i{code2}
 6918: <interpretation
 6919: compilation>
 6920:     @i{code3}
 6921: <compilation ;
 6922: @end example
 6923: 
 6924: For a @i{word} defined with @code{def-word}, the interpretation
 6925: semantics are to push the address of the body of @i{word} and perform
 6926: @i{code2}, and the compilation semantics are to push the address of
 6927: the body of @i{word} and perform @i{code3}. E.g., @code{constant}
 6928: can also be defined like this (except that the defined constants don't
 6929: behave correctly when @code{[compile]}d):
 6930: 
 6931: @example
 6932: : constant ( n "name" -- )
 6933:     create-interpret/compile
 6934:     ,
 6935: interpretation> ( -- n )
 6936:     @@
 6937: <interpretation
 6938: compilation> ( compilation. -- ; run-time. -- n )
 6939:     @@ postpone literal
 6940: <compilation ;
 6941: @end example
 6942: 
 6943: 
 6944: doc-create-interpret/compile
 6945: doc-interpretation>
 6946: doc-<interpretation
 6947: doc-compilation>
 6948: doc-<compilation
 6949: 
 6950: 
 6951: Words defined with @code{interpret/compile:} and
 6952: @code{create-interpret/compile} have an extended header structure that
 6953: differs from other words; however, unless you try to access them with
 6954: plain address arithmetic, you should not notice this. Words for
 6955: accessing the header structure usually know how to deal with this; e.g.,
 6956: @code{'} @i{word} @code{>body} also gives you the body of a word created
 6957: with @code{create-interpret/compile}.
 6958: 
 6959: 
 6960: doc-postpone
 6961: 
 6962: @comment TODO -- expand glossary text for POSTPONE
 6963: 
 6964: 
 6965: @c -------------------------------------------------------------
 6966: @node Tokens for Words, The Text Interpreter, Interpretation and Compilation Semantics, Words
 6967: @section Tokens for Words
 6968: @cindex tokens for words
 6969: 
 6970: This section describes the creation and use of tokens that represent
 6971: words.
 6972: 
 6973: Named words have information stored in their header space entries to
 6974: indicate any non-default semantics (@pxref{Interpretation and
 6975: Compilation Semantics}). The semantics can be modified, using
 6976: @code{immediate} and/or @code{compile-only}, at the time that the words
 6977: are defined. Unnamed words have (by definition) no header space
 6978: entry, and therefore must have default semantics.
 6979: 
 6980: Named words have interpretation and compilation semantics. Unnamed words
 6981: just have execution semantics.
 6982: 
 6983: @cindex xt
 6984: @cindex execution token
 6985: The execution semantics of an unnamed word are represented by an
 6986: @dfn{execution token} (@i{xt}). As explained in @ref{Supplying names},
 6987: the execution token of the last word defined can be produced with
 6988: @code{lastxt}.
 6989: 
 6990: The interpretation semantics of a named word are also represented by an
 6991: execution token. You can produce the execution token using @code{'} or
 6992: @code{[']}. A simple example shows the difference between the two:
 6993: 
 6994: @example
 6995: : greet ( -- )   ." Hello" ;
 6996: : foo ( -- xt )  ['] greet execute ; \ ['] parses greet at compile-time
 6997: : bar ( -- )     ' execute ; \  '  parses at run-time
 6998: 
 6999: \ the next four lines all do the same thing
 7000: foo
 7001: bar greet
 7002: greet
 7003: ' greet EXECUTE
 7004: @end example
 7005: 
 7006: An execution token occupies one cell.
 7007: @cindex code field address
 7008: @cindex CFA
 7009: In Gforth, the abstract data type @i{execution token} is implemented
 7010: as a code field address (CFA).
 7011: @comment TODO note that the standard does not say what it represents..
 7012: @comment and you cannot necessarily compile it in all Forths (eg native
 7013: @comment compilers?).
 7014: 
 7015: For literals, use @code{'} in interpreted code and @code{[']} in
 7016: compiled code. Gforth's @code{'} and @code{[']} behave somewhat
 7017: unusually by complaining about compile-only words. To get the execution
 7018: token for a compile-only word @i{name}, use @code{COMP' @i{name} DROP}
 7019: or @code{[COMP'] @i{name} DROP}.
 7020: 
 7021: @cindex compilation token
 7022: The compilation semantics of a named word are represented by a
 7023: @dfn{compilation token} consisting of two cells: @i{w xt}. The top cell
 7024: @i{xt} is an execution token. The compilation semantics represented by
 7025: the compilation token can be performed with @code{execute}, which
 7026: consumes the whole compilation token, with an additional stack effect
 7027: determined by the represented compilation semantics.
 7028: 
 7029: At present, the @i{w} part of a compilation token is an execution token,
 7030: and the @i{xt} part represents either @code{execute} or
 7031: @code{compile,}@footnote{Depending upon the compilation semantics of the
 7032: word. If the word has default compilation semantics, the @i{xt} will
 7033: represent @code{compile,}. Otherwise (e.g., for immediate words), the
 7034: @i{xt} will represent @code{execute}.}. However, don't rely on that
 7035: knowledge, unless necessary; future versions of Gforth may introduce
 7036: unusual compilation tokens (e.g., a compilation token that represents
 7037: the compilation semantics of a literal).
 7038: 
 7039: You can compile the compilation semantics with @code{postpone,}. I.e.,
 7040: @code{COMP' @i{word} postpone,} is equivalent to @code{postpone
 7041: @i{word}}.
 7042: 
 7043: @cindex name token
 7044: @cindex name field address
 7045: @cindex NFA
 7046: Named words are also represented by the @dfn{name token}, (@i{nt}). In
 7047: Gforth, the abstract data type @emph{name token} is implemented as a
 7048: name field address (NFA).
 7049: 
 7050: 
 7051: doc-execute
 7052: doc-perform
 7053: doc-compile,
 7054: doc-[']
 7055: doc-'
 7056: doc-[comp']
 7057: doc-comp'
 7058: doc-postpone,
 7059: 
 7060: doc-find-name
 7061: doc-name>int
 7062: doc-name?int
 7063: doc-name>comp
 7064: doc-name>string
 7065: 
 7066: 
 7067: @c ----------------------------------------------------------
 7068: @node The Text Interpreter, Word Lists, Tokens for Words, Words
 7069: @section  The Text Interpreter
 7070: @cindex interpreter - outer
 7071: @cindex text interpreter
 7072: @cindex outer interpreter
 7073: 
 7074: @c Should we really describe all these ugly details?  IMO the text
 7075: @c interpreter should be much cleaner, but that may not be possible within
 7076: @c ANS Forth. - anton
 7077: @c nac-> I wanted to explain how it works to show how you can exploit
 7078: @c it in your own programs. When I was writing a cross-compiler, figuring out
 7079: @c some of these gory details was very helpful to me. None of the textbooks
 7080: @c I've seen cover it, and the most modern Forth textbook -- Forth Inc's,
 7081: @c seems to positively avoid going into too much detail for some of
 7082: @c the internals.
 7083: 
 7084: The text interpreter@footnote{This is an expanded version of the
 7085: material in @ref{Introducing the Text Interpreter}.} is an endless loop
 7086: that processes input from the current input device. It is also called
 7087: the outer interpreter, in contrast to the inner interpreter
 7088: (@pxref{Engine}) which executes the compiled Forth code on interpretive
 7089: implementations.
 7090: 
 7091: @cindex interpret state
 7092: @cindex compile state
 7093: The text interpreter operates in one of two states: @dfn{interpret
 7094: state} and @dfn{compile state}. The current state is defined by the
 7095: aptly-named variable, @code{state}.
 7096: 
 7097: This section starts by describing how the text interpreter behaves when
 7098: it is in interpret state, processing input from the user input device --
 7099: the keyboard. This is the mode that a Forth system is in after it starts
 7100: up.
 7101: 
 7102: @cindex input buffer
 7103: @cindex terminal input buffer
 7104: The text interpreter works from an area of memory called the @dfn{input
 7105: buffer}@footnote{When the text interpreter is processing input from the
 7106: keyboard, this area of memory is called the @dfn{terminal input buffer}
 7107: (TIB) and is addressed by the (obsolescent) words @code{TIB} and
 7108: @code{#TIB}.}, which stores your keyboard input when you press the
 7109: @key{RET} key. Starting at the beginning of the input buffer, it skips
 7110: leading spaces (called @dfn{delimiters}) then parses a string (a
 7111: sequence of non-space characters) until it reaches either a space
 7112: character or the end of the buffer. Having parsed a string, it makes two
 7113: attempts to process it:
 7114: 
 7115: @cindex dictionary
 7116: @itemize @bullet
 7117: @item
 7118: It looks for the string in a @dfn{dictionary} of definitions. If the
 7119: string is found, the string names a @dfn{definition} (also known as a
 7120: @dfn{word}) and the dictionary search returns information that allows
 7121: the text interpreter to perform the word's @dfn{interpretation
 7122: semantics}. In most cases, this simply means that the word will be
 7123: executed.
 7124: @item
 7125: If the string is not found in the dictionary, the text interpreter
 7126: attempts to treat it as a number, using the rules described in
 7127: @ref{Number Conversion}. If the string represents a legal number in the
 7128: current radix, the number is pushed onto a parameter stack (the data
 7129: stack for integers, the floating-point stack for floating-point
 7130: numbers).
 7131: @end itemize
 7132: 
 7133: If both attempts fail, or if the word is found in the dictionary but has
 7134: no interpretation semantics@footnote{This happens if the word was
 7135: defined as @code{COMPILE-ONLY}.} the text interpreter discards the
 7136: remainder of the input buffer, issues an error message and waits for
 7137: more input. If one of the attempts succeeds, the text interpreter
 7138: repeats the parsing process until the whole of the input buffer has been
 7139: processed, at which point it prints the status message ``@code{ ok}''
 7140: and waits for more input.
 7141: 
 7142: @cindex parse area
 7143: The text interpreter keeps track of its position in the input buffer by
 7144: updating a variable called @code{>IN} (pronounced ``to-in''). The value
 7145: of @code{>IN} starts out as 0, indicating an offset of 0 from the start
 7146: of the input buffer. The region from offset @code{>IN @@} to the end of
 7147: the input buffer is called the @dfn{parse area}@footnote{In other words,
 7148: the text interpreter processes the contents of the input buffer by
 7149: parsing strings from the parse area until the parse area is empty.}.
 7150: This example shows how @code{>IN} changes as the text interpreter parses
 7151: the input buffer:
 7152: 
 7153: @example
 7154: : remaining >IN @@ SOURCE 2 PICK - -ROT + SWAP
 7155:   CR ." ->" TYPE ." <-" ; IMMEDIATE 
 7156: 
 7157: 1 2 3 remaining + remaining . 
 7158: 
 7159: : foo 1 2 3 remaining SWAP remaining ;
 7160: @end example
 7161: 
 7162: @noindent
 7163: The result is:
 7164: 
 7165: @example
 7166: ->+ remaining .<-
 7167: ->.<-5  ok
 7168: 
 7169: ->SWAP remaining ;-<
 7170: ->;<-  ok
 7171: @end example
 7172: 
 7173: @cindex parsing words
 7174: The value of @code{>IN} can also be modified by a word in the input
 7175: buffer that is executed by the text interpreter.  This means that a word
 7176: can ``trick'' the text interpreter into either skipping a section of the
 7177: input buffer@footnote{This is how parsing words work.} or into parsing a
 7178: section twice. For example:
 7179: 
 7180: @example
 7181: : lat ." <<lat>>" ;
 7182: : flat ." <<flat>>" >IN DUP @@ 3 - SWAP ! ;
 7183: @end example
 7184: 
 7185: @noindent
 7186: When @code{flat} is executed, this output is produced@footnote{Exercise
 7187: for the reader: what would happen if the @code{3} were replaced with
 7188: @code{4}?}:
 7189: 
 7190: @example
 7191: <<flat>><<lat>>
 7192: @end example
 7193: 
 7194: @noindent
 7195: Two important notes about the behaviour of the text interpreter:
 7196: 
 7197: @itemize @bullet
 7198: @item
 7199: It processes each input string to completion before parsing additional
 7200: characters from the input buffer.
 7201: @item
 7202: It treats the input buffer as a read-only region (and so must your code).
 7203: @end itemize
 7204: 
 7205: @noindent
 7206: When the text interpreter is in compile state, its behaviour changes in
 7207: these ways:
 7208: 
 7209: @itemize @bullet
 7210: @item
 7211: If a parsed string is found in the dictionary, the text interpreter will
 7212: perform the word's @dfn{compilation semantics}. In most cases, this
 7213: simply means that the execution semantics of the word will be appended
 7214: to the current definition.
 7215: @item
 7216: When a number is encountered, it is compiled into the current definition
 7217: (as a literal) rather than being pushed onto a parameter stack.
 7218: @item
 7219: If an error occurs, @code{state} is modified to put the text interpreter
 7220: back into interpret state.
 7221: @item
 7222: Each time a line is entered from the keyboard, Gforth prints
 7223: ``@code{ compiled}'' rather than `` @code{ok}''.
 7224: @end itemize
 7225: 
 7226: @cindex text interpreter - input sources
 7227: When the text interpreter is using an input device other than the
 7228: keyboard, its behaviour changes in these ways:
 7229: 
 7230: @itemize @bullet
 7231: @item
 7232: When the parse area is empty, the text interpreter attempts to refill
 7233: the input buffer from the input source. When the input source is
 7234: exhausted, the input source is set back to the user input device.
 7235: @item
 7236: It doesn't print out ``@code{ ok}'' or ``@code{ compiled}'' messages each
 7237: time the parse area is emptied.
 7238: @item
 7239: If an error occurs, the input source is set back to the user input
 7240: device.
 7241: @end itemize
 7242: 
 7243: You can read about this in more detail in @ref{Input Sources}.
 7244: 
 7245: doc->in
 7246: doc-source
 7247: 
 7248: doc-tib
 7249: doc-#tib
 7250: 
 7251: 
 7252: @menu
 7253: * Input Sources::               
 7254: * Number Conversion::           
 7255: * Interpret/Compile states::    
 7256: * Literals::                    
 7257: * Interpreter Directives::      
 7258: @end menu
 7259: 
 7260: @node Input Sources, Number Conversion, The Text Interpreter, The Text Interpreter
 7261: @subsection Input Sources
 7262: @cindex input sources
 7263: @cindex text interpreter - input sources
 7264: 
 7265: By default, the text interpreter processes input from the user input
 7266: device (the keyboard) when Forth starts up. The text interpreter can
 7267: process input from any of these sources:
 7268: 
 7269: @itemize @bullet
 7270: @item
 7271: The user input device -- the keyboard.
 7272: @item
 7273: A file, using the words described in @ref{Forth source files}.
 7274: @item
 7275: A block, using the words described in @ref{Blocks}.
 7276: @item
 7277: A text string, using @code{evaluate}.
 7278: @end itemize
 7279: 
 7280: A program can identify the current input device from the values of
 7281: @code{source-id} and @code{blk}.
 7282: 
 7283: 
 7284: doc-source-id
 7285: doc-blk
 7286: 
 7287: doc-save-input
 7288: doc-restore-input
 7289: 
 7290: doc-evaluate
 7291: 
 7292: 
 7293: 
 7294: @node Number Conversion, Interpret/Compile states, Input Sources, The Text Interpreter
 7295: @subsection Number Conversion
 7296: @cindex number conversion
 7297: @cindex double-cell numbers, input format
 7298: @cindex input format for double-cell numbers
 7299: @cindex single-cell numbers, input format
 7300: @cindex input format for single-cell numbers
 7301: @cindex floating-point numbers, input format
 7302: @cindex input format for floating-point numbers
 7303: 
 7304: This section describes the rules that the text interpreter uses when it
 7305: tries to convert a string into a number.
 7306: 
 7307: Let <digit> represent any character that is a legal digit in the current
 7308: number base@footnote{For example, 0-9 when the number base is decimal or
 7309: 0-9, A-F when the number base is hexadecimal.}.
 7310: 
 7311: Let <decimal digit> represent any character in the range 0-9.
 7312: 
 7313: Let @{@i{a b}@} represent the @i{optional} presence of any of the characters
 7314: in the braces (@i{a} or @i{b} or neither).
 7315: 
 7316: Let * represent any number of instances of the previous character
 7317: (including none).
 7318: 
 7319: Let any other character represent itself.
 7320: 
 7321: @noindent
 7322: Now, the conversion rules are:
 7323: 
 7324: @itemize @bullet
 7325: @item
 7326: A string of the form <digit><digit>* is treated as a single-precision
 7327: (cell-sized) positive integer. Examples are 0 123 6784532 32343212343456 42
 7328: @item
 7329: A string of the form -<digit><digit>* is treated as a single-precision
 7330: (cell-sized) negative integer, and is represented using 2's-complement
 7331: arithmetic. Examples are -45 -5681 -0
 7332: @item
 7333: A string of the form <digit><digit>*.<digit>* is treated as a double-precision
 7334: (double-cell-sized) positive integer. Examples are 3465. 3.465 34.65
 7335: (all three of these represent the same number).
 7336: @item
 7337: A string of the form -<digit><digit>*.<digit>* is treated as a
 7338: double-precision (double-cell-sized) negative integer, and is
 7339: represented using 2's-complement arithmetic. Examples are -3465. -3.465
 7340: -34.65 (all three of these represent the same number).
 7341: @item
 7342: A string of the form @{+ -@}<decimal digit>@{.@}<decimal digit>*@{e
 7343: E@}@{+ -@}<decimal digit><decimal digit>* is treated as a floating-point
 7344: number. Examples are 1e 1e0 1.e 1.e0 +1e+0 (which all represent the same
 7345: number) +12.E-4
 7346: @end itemize
 7347: 
 7348: By default, the number base used for integer number conversion is given
 7349: by the contents of the variable @code{base}.  Note that a lot of
 7350: confusion can result from unexpected values of @code{base}.  If you
 7351: change @code{base} anywhere, make sure to save the old value and restore
 7352: it afterwards.  In general I recommend keeping @code{base} decimal, and
 7353: using the prefixes described below for the popular non-decimal bases.
 7354: 
 7355: doc-dpl
 7356: doc-base
 7357: doc-hex
 7358: doc-decimal
 7359: 
 7360: 
 7361: @cindex '-prefix for character strings
 7362: @cindex &-prefix for decimal numbers
 7363: @cindex %-prefix for binary numbers
 7364: @cindex $-prefix for hexadecimal numbers
 7365: Gforth allows you to override the value of @code{base} by using a
 7366: prefix@footnote{Some Forth implementations provide a similar scheme by
 7367: implementing @code{$} etc. as parsing words that process the subsequent
 7368: number in the input stream and push it onto the stack. For example, see
 7369: @cite{Number Conversion and Literals}, by Wil Baden; Forth Dimensions
 7370: 20(3) pages 26--27. In such implementations, unlike in Gforth, a space
 7371: is required between the prefix and the number.} before the first digit
 7372: of an (integer) number. Four prefixes are supported:
 7373: 
 7374: @itemize @bullet
 7375: @item
 7376: @code{&} -- decimal
 7377: @item
 7378: @code{%} -- binary
 7379: @item
 7380: @code{$} -- hexadecimal
 7381: @item
 7382: @code{'} -- base @code{max-char+1}
 7383: @end itemize
 7384: 
 7385: Here are some examples, with the equivalent decimal number shown after
 7386: in braces:
 7387: 
 7388: -$41 (-65), %1001101 (205), %1001.0001 (145 - a double-precision number),
 7389: 'AB (16706; ascii A is 65, ascii B is 66, number is 65*256 + 66),
 7390: 'ab (24930; ascii a is 97, ascii B is 98, number is 97*256 + 98),
 7391: &905 (905), $abc (2478), $ABC (2478).
 7392: 
 7393: @cindex number conversion - traps for the unwary
 7394: @noindent
 7395: Number conversion has a number of traps for the unwary:
 7396: 
 7397: @itemize @bullet
 7398: @item
 7399: You cannot determine the current number base using the code sequence
 7400: @code{base @@ .} -- the number base is always 10 in the current number
 7401: base. Instead, use something like @code{base @@ dec.}
 7402: @item
 7403: If the number base is set to a value greater than 14 (for example,
 7404: hexadecimal), the number 123E4 is ambiguous; the conversion rules allow
 7405: it to be intepreted as either a single-precision integer or a
 7406: floating-point number (Gforth treats it as an integer). The ambiguity
 7407: can be resolved by explicitly stating the sign of the mantissa and/or
 7408: exponent: 123E+4 or +123E4 -- if the number base is decimal, no
 7409: ambiguity arises; either representation will be treated as a
 7410: floating-point number.
 7411: @item
 7412: There is a word @code{bin} but it does @i{not} set the number base!
 7413: It is used to specify file types.
 7414: @item
 7415: ANS Forth requires the @code{.} of a double-precision number to
 7416: be the final character in the string. Allowing the @code{.} to be
 7417: anywhere after the first digit is a Gforth extension.
 7418: @item
 7419: The number conversion process does not check for overflow.
 7420: @item
 7421: In Gforth, number conversion to floating-point numbers always use base
 7422: 10, irrespective of the value of @code{base}. In ANS Forth,
 7423: conversion to floating-point numbers whilst the value of
 7424: @code{base} is not 10 is an ambiguous condition.
 7425: @end itemize
 7426: 
 7427: You can read numbers into your programs with the words described in
 7428: @ref{Input}.
 7429: 
 7430: @node Interpret/Compile states, Literals, Number Conversion, The Text Interpreter
 7431: @subsection Interpret/Compile states
 7432: @cindex Interpret/Compile states
 7433: 
 7434: A standard program is not permitted to change @code{state}
 7435: explicitly. However, it can change @code{state} implicitly, using the
 7436: words @code{[} and @code{]}. When @code{[} is executed it switches
 7437: @code{state} to interpret state, and therefore the text interpreter
 7438: starts interpreting. When @code{]} is executed it switches @code{state}
 7439: to compile state and therefore the text interpreter starts
 7440: compiling. The most common usage for these words is for switching into
 7441: interpret state and back from within a colon definition; this technique
 7442: can be used to compile a literal (for an example, @pxref{Literals}) or
 7443: for conditional compilation (for an example, @pxref{Interpreter
 7444: Directives}).
 7445: 
 7446: 
 7447: @c This is a bad example: It's non-standard, and it's not necessary.
 7448: @c However, I can't think of a good example for switching into compile
 7449: @c state when there is no current word (@code{state}-smart words are not a
 7450: @c good reason).  So maybe we should use an example for switching into
 7451: @c interpret @code{state} in a colon def. - anton
 7452: @c nac-> I agree. I started out by putting in the example, then realised
 7453: @c that it was non-ANS, so wrote more words around it. I hope this
 7454: @c re-written version is acceptable to you. I do want to keep the example
 7455: @c as it is helpful for showing what is and what is not portable, particularly
 7456: @c where it outlaws a style in common use.
 7457: 
 7458: 
 7459: @code{[} and @code{]} also give you the ability to switch into compile
 7460: state and back, but we cannot think of any useful Standard application
 7461: for this ability. Pre-ANS Forth textbooks have examples like this:
 7462: 
 7463: @example
 7464: : AA ." this is A" ;
 7465: : BB ." this is B" ;
 7466: : CC ." this is C" ;
 7467: 
 7468: create table ] aa bb cc [
 7469: 
 7470: : go ( n -- ) \ n is offset into table.. 0 for 1st entry
 7471:   cells table + @ execute ;
 7472: @end example
 7473: 
 7474: This example builds a jump table; @code{0 go} will display ``@code{this
 7475: is A}''. Using @code{[} and @code{]} in this example is equivalent to
 7476: defining @code{table} like this:
 7477: 
 7478: @example
 7479: create table ' aa COMPILE, ' bb COMPILE, ' cc COMPILE,
 7480: @end example
 7481: 
 7482: The problem with this code is that the definition of @code{table} is not
 7483: portable -- it @i{compile}s execution tokens into code space. Whilst it
 7484: @i{may} work on systems where code space and data space co-incide, the
 7485: Standard only allows data space to be assigned for a @code{CREATE}d
 7486: word. In addition, the Standard only allows @code{@@} to access data
 7487: space, whilst this example is using it to access code space. The only
 7488: portable, Standard way to build this table is to build it in data space,
 7489: like this:
 7490: 
 7491: @example
 7492: create table ' aa , ' bb , ' cc ,
 7493: @end example
 7494: 
 7495: doc-state
 7496: doc-[
 7497: doc-]
 7498: 
 7499: 
 7500: @node Literals, Interpreter Directives, Interpret/Compile states, The Text Interpreter
 7501: @subsection Literals
 7502: @cindex Literals
 7503: 
 7504: Often, you want to use a number within a colon definition. When you do
 7505: this, the text interpreter automatically compiles the number as a
 7506: @i{literal}. A literal is a number whose run-time effect is to be pushed
 7507: onto the stack.  If you had to do some maths to generate the number, you
 7508: might write it like this:
 7509: 
 7510: @example
 7511: : HOUR-TO-SEC ( n1 -- n2 )
 7512:   60 *      \ to minutes
 7513:   60 * ;    \ to seconds
 7514: @end example
 7515: 
 7516: It is very clear what this definition is doing, but it's inefficient
 7517: since it is performing 2 multiples at run-time. An alternative would be
 7518: to write:
 7519: 
 7520: @example
 7521: : HOUR-TO-SEC ( n1 -- n2 )
 7522:   3600 * ;  \ to seconds
 7523: @end example
 7524: 
 7525: Which does the same thing, and has the advantage of using a single
 7526: multiply. Ideally, we'd like the efficiency of the second with the
 7527: readability of the first.
 7528: 
 7529: @code{Literal} allows us to achieve that. It takes a number from the
 7530: stack and lays it down in the current definition just as though the
 7531: number had been typed directly into the definition. Our first attempt
 7532: might look like this:
 7533: 
 7534: @example
 7535: 60          \ mins per hour
 7536: 60 *        \ seconds per minute
 7537: : HOUR-TO-SEC ( n1 -- n2 )
 7538:   Literal * ;  \ to seconds
 7539: @end example
 7540: 
 7541: But this produces the error message @code{unstructured}. What happened?
 7542: The stack notation for @code{:} is (@i{ -- colon-sys}) and the size of
 7543: @i{colon-sys} is implementation-defined. In other words, once we start a
 7544: colon definition we can't portably access anything that was on the stack
 7545: before the definition began@footnote{@cite{Two Problems in ANS Forth},
 7546: by Thomas Worthington; Forth Dimensions 20(2) pages 32--34 describes
 7547: some situations where you might want to access stack items above
 7548: colon-sys, and provides a solution to the problem.}. The correct way of
 7549: solving this problem in this instance is to use @code{[ ]} like this:
 7550: 
 7551: @example
 7552: : HOUR-TO-SEC ( n1 -- n2 )
 7553:   [ 60          \ minutes per hour
 7554:     60 * ]      \ seconds per minute
 7555:   LITERAL * ;   \ to seconds
 7556: @end example
 7557: 
 7558: 
 7559: doc-literal
 7560: doc-]L
 7561: doc-2literal
 7562: doc-fliteral
 7563: 
 7564: 
 7565: @node Interpreter Directives,  , Literals, The Text Interpreter
 7566: @subsection Interpreter Directives
 7567: @cindex interpreter directives
 7568: 
 7569: These words are usually used in interpret state; typically to control
 7570: which parts of a source file are processed by the text
 7571: interpreter. There are only a few ANS Forth Standard words, but Gforth
 7572: supplements these with a rich set of immediate control structure words
 7573: to compensate for the fact that the non-immediate versions can only be
 7574: used in compile state (@pxref{Control Structures}). Typical usages:
 7575: 
 7576: @example
 7577: FALSE Constant ASSEMBLER
 7578: .
 7579: .
 7580: ASSEMBLER [IF]
 7581: : ASSEMBLER-FEATURE
 7582:   ...
 7583: ;
 7584: [ENDIF]
 7585: .
 7586: .
 7587: : SEE
 7588:   ... \ general-purpose SEE code
 7589:   [ ASSEMBLER [IF] ]
 7590:   ... \ assembler-specific SEE code
 7591:   [ [ENDIF] ]
 7592: ;
 7593: @end example
 7594: 
 7595: 
 7596: doc-[IF]
 7597: doc-[ELSE]
 7598: doc-[THEN]
 7599: doc-[ENDIF]
 7600: 
 7601: doc-[IFDEF]
 7602: doc-[IFUNDEF]
 7603: 
 7604: doc-[?DO]
 7605: doc-[DO]
 7606: doc-[FOR]
 7607: doc-[LOOP]
 7608: doc-[+LOOP]
 7609: doc-[NEXT]
 7610: 
 7611: doc-[BEGIN]
 7612: doc-[UNTIL]
 7613: doc-[AGAIN]
 7614: doc-[WHILE]
 7615: doc-[REPEAT]
 7616: 
 7617: 
 7618: @c -------------------------------------------------------------
 7619: @node Word Lists, Environmental Queries, The Text Interpreter, Words
 7620: @section Word Lists
 7621: @cindex word lists
 7622: @cindex header space
 7623: 
 7624: A wordlist is a list of named words; you can add new words and look up
 7625: words by name (and you can remove words in a restricted way with
 7626: markers).  Every named (and @code{reveal}ed) word is in one wordlist.
 7627: 
 7628: @cindex search order stack
 7629: The text interpreter searches the wordlists present in the search order
 7630: (a stack of wordlists), from the top to the bottom.  Within each
 7631: wordlist, the search starts conceptually at the newest word; i.e., if
 7632: two words in a wordlist have the same name, the newer word is found.
 7633: 
 7634: @cindex compilation word list
 7635: New words are added to the @dfn{compilation wordlist} (aka current
 7636: wordlist).
 7637: 
 7638: @cindex wid
 7639: A word list is identified by a cell-sized word list identifier (@i{wid})
 7640: in much the same way as a file is identified by a file handle. The
 7641: numerical value of the wid has no (portable) meaning, and might change
 7642: from session to session.
 7643: 
 7644: The ANS Forth ``Search order'' word set is intended to provide a set of
 7645: low-level tools that allow various different schemes to be
 7646: implemented. Gforth provides @code{vocabulary}, a traditional Forth
 7647: word.  @file{compat/vocabulary.fs} provides an implementation in ANS
 7648: Forth.
 7649: 
 7650: @comment TODO: locals section refers to here, saying that every word list (aka
 7651: @comment vocabulary) has its own methods for searching etc. Need to document that.
 7652: 
 7653: @comment TODO: document markers, reveal, tables, mappedwordlist
 7654: 
 7655: @comment the gforthman- prefix is used to pick out the true definition of a
 7656: @comment word from the source files, rather than some alias.
 7657: 
 7658: doc-forth-wordlist
 7659: doc-definitions
 7660: doc-get-current
 7661: doc-set-current
 7662: doc-get-order
 7663: doc---gforthman-set-order
 7664: doc-wordlist
 7665: doc-table
 7666: doc-push-order
 7667: doc-previous
 7668: doc-also
 7669: doc---gforthman-forth
 7670: doc-only
 7671: doc---gforthman-order
 7672: 
 7673: doc-find
 7674: doc-search-wordlist
 7675: 
 7676: doc-words
 7677: doc-vlist
 7678: @c doc-words-deferred
 7679: 
 7680: doc-mappedwordlist
 7681: doc-root
 7682: doc-vocabulary
 7683: doc-seal
 7684: doc-vocs
 7685: doc-current
 7686: doc-context
 7687: 
 7688: 
 7689: @menu
 7690: * Why use word lists?::         
 7691: * Word list examples::          
 7692: @end menu
 7693: 
 7694: @node Why use word lists?, Word list examples, Word Lists, Word Lists
 7695: @subsection Why use word lists?
 7696: @cindex word lists - why use them?
 7697: 
 7698: Here are some reasons for using multiple word lists:
 7699: 
 7700: @itemize @bullet
 7701: @item
 7702: To improve compilation speed by reducing the number of header space
 7703: entries that must be searched. This is achieved by creating a new
 7704: word list that contains all of the definitions that are used in the
 7705: definition of a Forth system but which would not usually be used by
 7706: programs running on that system. That word list would be on the search
 7707: list when the Forth system was compiled but would be removed from the
 7708: search list for normal operation. This can be a useful technique for
 7709: low-performance systems (for example, 8-bit processors in embedded
 7710: systems) but is unlikely to be necessary in high-performance desktop
 7711: systems.
 7712: @item
 7713: To prevent a set of words from being used outside the context in which
 7714: they are valid. Two classic examples of this are an integrated editor
 7715: (all of the edit commands are defined in a separate word list; the
 7716: search order is set to the editor word list when the editor is invoked;
 7717: the old search order is restored when the editor is terminated) and an
 7718: integrated assembler (the op-codes for the machine are defined in a
 7719: separate word list which is used when a @code{CODE} word is defined).
 7720: @item
 7721: To prevent a name-space clash between multiple definitions with the same
 7722: name. For example, when building a cross-compiler you might have a word
 7723: @code{IF} that generates conditional code for your target system. By
 7724: placing this definition in a different word list you can control whether
 7725: the host system's @code{IF} or the target system's @code{IF} get used in
 7726: any particular context by controlling the order of the word lists on the
 7727: search order stack.
 7728: @end itemize
 7729: 
 7730: @node Word list examples,  , Why use word lists?, Word Lists
 7731: @subsection Word list examples
 7732: @cindex word lists - examples
 7733: 
 7734: Here is an example of creating and using a new wordlist using ANS
 7735: Forth Standard words:
 7736: 
 7737: @example
 7738: wordlist constant my-new-words-wordlist
 7739: : my-new-words get-order nip my-new-words-wordlist swap set-order ;
 7740: 
 7741: \ add it to the search order
 7742: also my-new-words
 7743: 
 7744: \ alternatively, add it to the search order and make it
 7745: \ the compilation word list
 7746: also my-new-words definitions
 7747: \ type "order" to see the problem
 7748: @end example
 7749: 
 7750: The problem with this example is that @code{order} has no way to
 7751: associate the name @code{my-new-words} with the wid of the word list (in
 7752: Gforth, @code{order} and @code{vocs} will display @code{???}  for a wid
 7753: that has no associated name). There is no Standard way of associating a
 7754: name with a wid.
 7755: 
 7756: In Gforth, this example can be re-coded using @code{vocabulary}, which
 7757: associates a name with a wid:
 7758: 
 7759: @example
 7760: vocabulary my-new-words
 7761: 
 7762: \ add it to the search order
 7763: also my-new-words
 7764: 
 7765: \ alternatively, add it to the search order and make it
 7766: \ the compilation word list
 7767: my-new-words definitions
 7768: \ type "order" to see that the problem is solved
 7769: @end example
 7770: 
 7771: @c -------------------------------------------------------------
 7772: @node Environmental Queries, Files, Word Lists, Words
 7773: @section Environmental Queries
 7774: @cindex environmental queries
 7775: 
 7776: ANS Forth introduced the idea of ``environmental queries'' as a way
 7777: for a program running on a system to determine certain characteristics of the system.
 7778: The Standard specifies a number of strings that might be recognised by a system.
 7779: 
 7780: The Standard requires that the header space used for environmental queries
 7781: be distinct from the header space used for definitions.
 7782: 
 7783: Typically, environmental queries are supported by creating a set of
 7784: definitions in a word list that is @i{only} used during environmental
 7785: queries; that is what Gforth does. There is no Standard way of adding
 7786: definitions to the set of recognised environmental queries, but any
 7787: implementation that supports the loading of optional word sets must have
 7788: some mechanism for doing this (after loading the word set, the
 7789: associated environmental query string must return @code{true}). In
 7790: Gforth, the word list used to honour environmental queries can be
 7791: manipulated just like any other word list.
 7792: 
 7793: 
 7794: doc-environment?
 7795: doc-environment-wordlist
 7796: 
 7797: doc-gforth
 7798: doc-os-class
 7799: 
 7800: 
 7801: Note that, whilst the documentation for (e.g.) @code{gforth} shows it
 7802: returning two items on the stack, querying it using @code{environment?}
 7803: will return an additional item; the @code{true} flag that shows that the
 7804: string was recognised.
 7805: 
 7806: @comment TODO Document the standard strings or note where they are documented herein
 7807: 
 7808: Here are some examples of using environmental queries:
 7809: 
 7810: @example
 7811: s" address-unit-bits" environment? 0=
 7812: [IF]
 7813:      cr .( environmental attribute address-units-bits unknown... ) cr
 7814: [THEN]
 7815: 
 7816: s" block" environment? [IF] DROP include block.fs [THEN]
 7817: 
 7818: s" gforth" environment? [IF] 2DROP include compat/vocabulary.fs [THEN]
 7819: 
 7820: s" gforth" environment? [IF] .( Gforth version ) TYPE
 7821:                         [ELSE] .( Not Gforth..) [THEN]
 7822: @end example
 7823: 
 7824: 
 7825: Here is an example of adding a definition to the environment word list:
 7826: 
 7827: @example
 7828: get-current environment-wordlist set-current
 7829: true constant block
 7830: true constant block-ext
 7831: set-current
 7832: @end example
 7833: 
 7834: You can see what definitions are in the environment word list like this:
 7835: 
 7836: @example
 7837: get-order 1+ environment-wordlist swap set-order words previous
 7838: @end example
 7839: 
 7840: 
 7841: @c -------------------------------------------------------------
 7842: @node Files, Blocks, Environmental Queries, Words
 7843: @section Files
 7844: @cindex files
 7845: @cindex I/O - file-handling
 7846: 
 7847: Gforth provides facilities for accessing files that are stored in the
 7848: host operating system's file-system. Files that are processed by Gforth
 7849: can be divided into two categories:
 7850: 
 7851: @itemize @bullet
 7852: @item
 7853: Files that are processed by the Text Interpreter (@dfn{Forth source files}).
 7854: @item
 7855: Files that are processed by some other program (@dfn{general files}).
 7856: @end itemize
 7857: 
 7858: doc-loadfilename
 7859: doc-sourcefilename
 7860: doc-sourceline#
 7861: 
 7862: @menu
 7863: * Forth source files::          
 7864: * General files::               
 7865: * Search Paths::                
 7866: @end menu
 7867: 
 7868: 
 7869: @c -------------------------------------------------------------
 7870: @node Forth source files, General files, Files, Files
 7871: @subsection Forth source files
 7872: @cindex including files
 7873: @cindex Forth source files
 7874: 
 7875: The simplest way to interpret the contents of a file is to use one of
 7876: these two formats:
 7877: 
 7878: @example
 7879: include mysource.fs
 7880: s" mysource.fs" included
 7881: @end example
 7882: 
 7883: Sometimes you want to include a file only if it is not included already
 7884: (by, say, another source file). In that case, you can use one of these
 7885: three formats:
 7886: 
 7887: @example
 7888: require mysource.fs
 7889: needs mysource.fs
 7890: s" mysource.fs" required
 7891: @end example
 7892: 
 7893: @cindex stack effect of included files
 7894: @cindex including files, stack effect
 7895: It is good practice to write your source files such that interpreting them
 7896: does not change the stack. Source files designed in this way can be used with
 7897: @code{required} and friends without complications. For example:
 7898: 
 7899: @example
 7900: 1 require foo.fs drop
 7901: @end example
 7902: 
 7903: 
 7904: doc-include-file
 7905: doc-included
 7906: doc-included?
 7907: doc-include
 7908: doc-required
 7909: doc-require
 7910: doc-needs
 7911: doc-init-included-files
 7912: 
 7913: 
 7914: A definition in ANS Forth for @code{required} is provided in
 7915: @file{compat/required.fs}.
 7916: 
 7917: @c -------------------------------------------------------------
 7918: @node General files, Search Paths, Forth source files, Files
 7919: @subsection General files
 7920: @cindex general files
 7921: @cindex file-handling
 7922: 
 7923: Files are opened/created by name and type. The following types are
 7924: recognised:
 7925: 
 7926: 
 7927: doc-r/o
 7928: doc-r/w
 7929: doc-w/o
 7930: doc-bin
 7931: 
 7932: 
 7933: When a file is opened/created, it returns a file identifier,
 7934: @i{wfileid} that is used for all other file commands. All file
 7935: commands also return a status value, @i{wior}, that is 0 for a
 7936: successful operation and an implementation-defined non-zero value in the
 7937: case of an error.
 7938: 
 7939: 
 7940: doc-open-file
 7941: doc-create-file
 7942: 
 7943: doc-close-file
 7944: doc-delete-file
 7945: doc-rename-file
 7946: doc-read-file
 7947: doc-read-line
 7948: doc-write-file
 7949: doc-write-line
 7950: doc-emit-file
 7951: doc-flush-file
 7952: 
 7953: doc-file-status
 7954: doc-file-position
 7955: doc-reposition-file
 7956: doc-file-size
 7957: doc-resize-file
 7958: 
 7959: 
 7960: @c ---------------------------------------------------------
 7961: @node Search Paths,  , General files, Files
 7962: @subsection Search Paths
 7963: @cindex path for @code{included}
 7964: @cindex file search path
 7965: @cindex @code{include} search path
 7966: @cindex search path for files
 7967: 
 7968: If you specify an absolute filename (i.e., a filename starting with
 7969: @file{/} or @file{~}, or with @file{:} in the second position (as in
 7970: @samp{C:...})) for @code{included} and friends, that file is included
 7971: just as you would expect.
 7972: 
 7973: For relative filenames, Gforth uses a search path similar to Forth's
 7974: search order (@pxref{Word Lists}). It tries to find the given filename
 7975: in the directories present in the path, and includes the first one it
 7976: finds. There are separate search paths for Forth source files and
 7977: general files.
 7978: 
 7979: If the search path contains the directory @file{.} (as it should), this
 7980: refers to the directory that the present file was @code{included}
 7981: from. This allows files to include other files relative to their own
 7982: position (irrespective of the current working directory or the absolute
 7983: position).  This feature is essential for libraries consisting of
 7984: several files, where a file may include other files from the library.
 7985: It corresponds to @code{#include "..."} in C. If the current input
 7986: source is not a file, @file{.} refers to the directory of the innermost
 7987: file being included, or, if there is no file being included, to the
 7988: current working directory.
 7989: 
 7990: Use @file{~+} to refer to the current working directory (as in the
 7991: @code{bash}).
 7992: 
 7993: If the filename starts with @file{./}, the search path is not searched
 7994: (just as with absolute filenames), and the @file{.} has the same meaning
 7995: as described above.
 7996: 
 7997: @menu
 7998: * Forth Search Paths::          
 7999: * General Search Paths::        
 8000: @end menu
 8001: 
 8002: @c ---------------------------------------------------------
 8003: @node Forth Search Paths, General Search Paths, Search Paths, Search Paths
 8004: @subsubsection Forth Search Paths
 8005: @cindex search path control - Forth
 8006: 
 8007: The search path is initialized when you start Gforth (@pxref{Invoking
 8008: Gforth}). You can display it and change it using these words:
 8009: 
 8010: 
 8011: doc-.fpath
 8012: doc-fpath+
 8013: doc-fpath=
 8014: doc-open-fpath-file
 8015: 
 8016: 
 8017: @noindent
 8018: Here is an example of using @code{fpath} and @code{require}:
 8019: 
 8020: @example
 8021: fpath= /usr/lib/forth/|./
 8022: require timer.fs
 8023: @end example
 8024: 
 8025: @c ---------------------------------------------------------
 8026: @node General Search Paths,  , Forth Search Paths, Search Paths
 8027: @subsubsection General Search Paths
 8028: @cindex search path control - for user applications
 8029: 
 8030: Your application may need to search files in several directories, like
 8031: @code{included} does. To facilitate this, Gforth allows you to define
 8032: and use your own search paths, by providing generic equivalents of the
 8033: Forth search path words:
 8034: 
 8035: 
 8036: doc-.path
 8037: doc-path+
 8038: doc-path=
 8039: doc-open-path-file
 8040: 
 8041: 
 8042: Here's an example of creating a search path:
 8043: 
 8044: @example
 8045: \ Make a buffer for the path:
 8046: create mypath   100 chars ,     \ maximum length (is checked)
 8047:                 0 ,             \ real len
 8048:                 100 chars allot \ space for path
 8049: @end example
 8050: 
 8051: @c -------------------------------------------------------------
 8052: @node Blocks, Other I/O, Files, Words
 8053: @section Blocks
 8054: @cindex I/O - blocks
 8055: @cindex blocks
 8056: 
 8057: When you run Gforth on a modern desk-top computer, it runs under the
 8058: control of an operating system which provides certain services.  One of
 8059: these services is @var{file services}, which allows Forth source code
 8060: and data to be stored in files and read into Gforth (@pxref{Files}).
 8061: 
 8062: Traditionally, Forth has been an important programming language on
 8063: systems where it has interfaced directly to the underlying hardware with
 8064: no intervening operating system. Forth provides a mechanism, called
 8065: @dfn{blocks}, for accessing mass storage on such systems.
 8066: 
 8067: A block is a 1024-byte data area, which can be used to hold data or
 8068: Forth source code. No structure is imposed on the contents of the
 8069: block. A block is identified by its number; blocks are numbered
 8070: contiguously from 1 to an implementation-defined maximum.
 8071: 
 8072: A typical system that used blocks but no operating system might use a
 8073: single floppy-disk drive for mass storage, with the disks formatted to
 8074: provide 256-byte sectors. Blocks would be implemented by assigning the
 8075: first four sectors of the disk to block 1, the second four sectors to
 8076: block 2 and so on, up to the limit of the capacity of the disk. The disk
 8077: would not contain any file system information, just the set of blocks.
 8078: 
 8079: @cindex blocks file
 8080: On systems that do provide file services, blocks are typically
 8081: implemented by storing a sequence of blocks within a single @dfn{blocks
 8082: file}.  The size of the blocks file will be an exact multiple of 1024
 8083: bytes, corresponding to the number of blocks it contains. This is the
 8084: mechanism that Gforth uses.
 8085: 
 8086: @cindex @file{blocks.fb}
 8087: Only 1 blocks file can be open at a time. If you use block words without
 8088: having specified a blocks file, Gforth defaults to the blocks file
 8089: @file{blocks.fb}. Gforth uses the Forth search path when attempting to
 8090: locate a blocks file (@pxref{Forth Search Paths}).
 8091: 
 8092: @cindex block buffers
 8093: When you read and write blocks under program control, Gforth uses a
 8094: number of @dfn{block buffers} as intermediate storage. These buffers are
 8095: not used when you use @code{load} to interpret the contents of a block.
 8096: 
 8097: The behaviour of the block buffers is directly analagous to that of a
 8098: cache. Each block buffer has three states:
 8099: 
 8100: @itemize @bullet
 8101: @item
 8102: Unassigned
 8103: @item
 8104: Assigned-clean
 8105: @item
 8106: Assigned-dirty
 8107: @end itemize
 8108: 
 8109: Initially, all block buffers are @i{unassigned}. In order to access a
 8110: block, the block (specified by its block number) must be assigned to a
 8111: block buffer.
 8112: 
 8113: The assignment of a block to a block buffer is performed by @code{block}
 8114: or @code{buffer}. Use @code{block} when you wish to modify the existing
 8115: contents of a block. Use @code{buffer} when you don't care about the
 8116: existing contents of the block@footnote{The ANS Forth definition of
 8117: @code{buffer} is intended not to cause disk I/O; if the data associated
 8118: with the particular block is already stored in a block buffer due to an
 8119: earlier @code{block} command, @code{buffer} will return that block
 8120: buffer and the existing contents of the block will be
 8121: available. Otherwise, @code{buffer} will simply assign a new, empty
 8122: block buffer for the block.}.
 8123: 
 8124: Once a block has been assigned to a block buffer using @code{block} or
 8125: @code{buffer}, that block buffer becomes the @i{current block buffer}
 8126: and its state changes to @i{assigned-clean}. Data may only be
 8127: manipulated (read or written) within the current block buffer.
 8128: 
 8129: When the contents of the current block buffer has been modified it is
 8130: necessary, @emph{before calling @code{block} or @code{buffer} again}, to
 8131: either abandon the changes (by doing nothing) or commit the changes,
 8132: using @code{update}. Using @code{update} does not change the blocks
 8133: file; it simply changes a block buffer's state to @i{assigned-dirty}.
 8134: 
 8135: The word @code{flush} causes all @i{assigned-dirty} blocks to be
 8136: written back to the blocks file on disk. Leaving Gforth using @code{bye}
 8137: also causes a @code{flush} to be performed.
 8138: 
 8139: In Gforth, @code{block} and @code{buffer} use a @i{direct-mapped}
 8140: algorithm to assign a block buffer to a block. That means that any
 8141: particular block can only be assigned to one specific block buffer,
 8142: called (for the particular operation) the @i{victim buffer}. If the
 8143: victim buffer is @i{unassigned} or @i{assigned-clean} it is allocated to
 8144: the new block immediately. If it is @i{assigned-dirty} its current
 8145: contents are written back to the blocks file on disk before it is
 8146: allocated to the new block.
 8147: 
 8148: Although no structure is imposed on the contents of a block, it is
 8149: traditional to display the contents as 16 lines each of 64 characters.  A
 8150: block provides a single, continuous stream of input (for example, it
 8151: acts as a single parse area) -- there are no end-of-line characters
 8152: within a block, and no end-of-file character at the end of a
 8153: block. There are two consequences of this:
 8154: 
 8155: @itemize @bullet
 8156: @item
 8157: The last character of one line wraps straight into the first character
 8158: of the following line
 8159: @item
 8160: The word @code{\} -- comment to end of line -- requires special
 8161: treatment; in the context of a block it causes all characters until the
 8162: end of the current 64-character ``line'' to be ignored.
 8163: @end itemize
 8164: 
 8165: In Gforth, when you use @code{block} with a non-existent block number,
 8166: the current blocks file will be extended to the appropriate size and the
 8167: block buffer will be initialised with spaces.
 8168: 
 8169: Gforth includes a simple block editor (type @code{use blocked.fb 0 list}
 8170: for details) but doesn't encourage the use of blocks; the mechanism is
 8171: only provided for backward compatibility -- ANS Forth requires blocks to
 8172: be available when files are.
 8173: 
 8174: Common techniques that are used when working with blocks include:
 8175: 
 8176: @itemize @bullet
 8177: @item
 8178: A screen editor that allows you to edit blocks without leaving the Forth
 8179: environment.
 8180: @item
 8181: Shadow screens; where every code block has an associated block
 8182: containing comments (for example: code in odd block numbers, comments in
 8183: even block numbers). Typically, the block editor provides a convenient
 8184: mechanism to toggle between code and comments.
 8185: @item
 8186: Load blocks; a single block (typically block 1) contains a number of
 8187: @code{thru} commands which @code{load} the whole of the application.
 8188: @end itemize
 8189: 
 8190: See Frank Sergeant's Pygmy Forth to see just how well blocks can be
 8191: integrated into a Forth programming environment.
 8192: 
 8193: @comment TODO what about errors on open-blocks?
 8194: 
 8195: doc-open-blocks
 8196: doc-use
 8197: doc-get-block-fid
 8198: doc-block-position
 8199: 
 8200: doc-scr
 8201: doc-list
 8202: 
 8203: doc---gforthman-block
 8204: doc-buffer
 8205: 
 8206: doc-update
 8207: doc-updated?
 8208: doc-save-buffers
 8209: doc-empty-buffers
 8210: doc-empty-buffer
 8211: doc-flush
 8212: 
 8213: doc-load
 8214: doc-thru
 8215: doc-+load
 8216: doc-+thru
 8217: doc---gforthman--->
 8218: doc-block-included
 8219: 
 8220: 
 8221: @c -------------------------------------------------------------
 8222: @node Other I/O, Programming Tools, Blocks, Words
 8223: @section Other I/O
 8224: @cindex I/O - keyboard and display
 8225: 
 8226: @menu
 8227: * Simple numeric output::       Predefined formats
 8228: * Formatted numeric output::    Formatted (pictured) output
 8229: * String Formats::              How Forth stores strings in memory
 8230: * Displaying characters and strings::  Other stuff
 8231: * Input::                       Input
 8232: @end menu
 8233: 
 8234: @node Simple numeric output, Formatted numeric output, Other I/O, Other I/O
 8235: @subsection Simple numeric output
 8236: @cindex numeric output - simple/free-format
 8237: 
 8238: The simplest output functions are those that display numbers from the
 8239: data or floating-point stacks. Floating-point output is always displayed
 8240: using base 10. Numbers displayed from the data stack use the value stored
 8241: in @code{base}.
 8242: 
 8243: 
 8244: doc-.
 8245: doc-dec.
 8246: doc-hex.
 8247: doc-u.
 8248: doc-.r
 8249: doc-u.r
 8250: doc-d.
 8251: doc-ud.
 8252: doc-d.r
 8253: doc-ud.r
 8254: doc-f.
 8255: doc-fe.
 8256: doc-fs.
 8257: 
 8258: 
 8259: Examples of printing the number 1234.5678E23 in the different floating-point output
 8260: formats are shown below:
 8261: 
 8262: @example
 8263: f. 123456779999999000000000000.
 8264: fe. 123.456779999999E24
 8265: fs. 1.23456779999999E26
 8266: @end example
 8267: 
 8268: 
 8269: @node Formatted numeric output, String Formats, Simple numeric output, Other I/O
 8270: @subsection Formatted numeric output
 8271: @cindex formatted numeric output
 8272: @cindex pictured numeric output
 8273: @cindex numeric output - formatted
 8274: 
 8275: Forth traditionally uses a technique called @dfn{pictured numeric
 8276: output} for formatted printing of integers.  In this technique, digits
 8277: are extracted from the number (using the current output radix defined by
 8278: @code{base}), converted to ASCII codes and appended to a string that is
 8279: built in a scratch-pad area of memory (@pxref{core-idef,
 8280: Implementation-defined options, Implementation-defined
 8281: options}). Arbitrary characters can be appended to the string during the
 8282: extraction process. The completed string is specified by an address
 8283: and length and can be manipulated (@code{TYPE}ed, copied, modified)
 8284: under program control.
 8285: 
 8286: All of the words described in the previous section for simple numeric
 8287: output are implemented in Gforth using pictured numeric output.
 8288: 
 8289: Three important things to remember about pictured numeric output:
 8290: 
 8291: @itemize @bullet
 8292: @item
 8293: It always operates on double-precision numbers; to display a
 8294: single-precision number, convert it first (for ways of doing this
 8295: @pxref{Double precision}).
 8296: @item
 8297: It always treats the double-precision number as though it were
 8298: unsigned. The examples below show ways of printing signed numbers.
 8299: @item
 8300: The string is built up from right to left; least significant digit first.
 8301: @end itemize
 8302: 
 8303: 
 8304: doc-<#
 8305: doc-<<#
 8306: doc-#
 8307: doc-#s
 8308: doc-hold
 8309: doc-sign
 8310: doc-#>
 8311: doc-#>>
 8312: 
 8313: doc-represent
 8314: 
 8315: 
 8316: @noindent
 8317: Here are some examples of using pictured numeric output:
 8318: 
 8319: @example
 8320: : my-u. ( u -- )
 8321:   \ Simplest use of pns.. behaves like Standard u. 
 8322:   0              \ convert to unsigned double
 8323:   <#             \ start conversion
 8324:   #s             \ convert all digits
 8325:   #>             \ complete conversion
 8326:   TYPE SPACE ;   \ display, with trailing space
 8327: 
 8328: : cents-only ( u -- )
 8329:   0              \ convert to unsigned double
 8330:   <#             \ start conversion
 8331:   # #            \ convert two least-significant digits
 8332:   #>             \ complete conversion, discard other digits
 8333:   TYPE SPACE ;   \ display, with trailing space
 8334: 
 8335: : dollars-and-cents ( u -- )
 8336:   0              \ convert to unsigned double
 8337:   <#             \ start conversion
 8338:   # #            \ convert two least-significant digits
 8339:   [char] . hold  \ insert decimal point
 8340:   #s             \ convert remaining digits
 8341:   [char] $ hold  \ append currency symbol
 8342:   #>             \ complete conversion
 8343:   TYPE SPACE ;   \ display, with trailing space
 8344: 
 8345: : my-. ( n -- )
 8346:   \ handling negatives.. behaves like Standard .
 8347:   s>d            \ convert to signed double
 8348:   swap over dabs \ leave sign byte followed by unsigned double
 8349:   <#             \ start conversion
 8350:   #s             \ convert all digits
 8351:   rot sign       \ get at sign byte, append "-" if needed
 8352:   #>             \ complete conversion
 8353:   TYPE SPACE ;   \ display, with trailing space
 8354: 
 8355: : account. ( n -- )
 8356:   \ accountants don't like minus signs, they use braces
 8357:   \ for negative numbers
 8358:   s>d            \ convert to signed double
 8359:   swap over dabs \ leave sign byte followed by unsigned double
 8360:   <#             \ start conversion
 8361:   2 pick         \ get copy of sign byte
 8362:   0< IF [char] ) hold THEN \ right-most character of output
 8363:   #s             \ convert all digits
 8364:   rot            \ get at sign byte
 8365:   0< IF [char] ( hold THEN
 8366:   #>             \ complete conversion
 8367:   TYPE SPACE ;   \ display, with trailing space
 8368: @end example
 8369: 
 8370: Here are some examples of using these words:
 8371: 
 8372: @example
 8373: 1 my-u. 1
 8374: hex -1 my-u. decimal FFFFFFFF
 8375: 1 cents-only 01
 8376: 1234 cents-only 34
 8377: 2 dollars-and-cents $0.02
 8378: 1234 dollars-and-cents $12.34
 8379: 123 my-. 123
 8380: -123 my. -123
 8381: 123 account. 123
 8382: -456 account. (456)
 8383: @end example
 8384: 
 8385: 
 8386: @node String Formats, Displaying characters and strings, Formatted numeric output, Other I/O
 8387: @subsection String Formats
 8388: @cindex strings - see character strings
 8389: @cindex character strings - formats
 8390: @cindex I/O - see character strings
 8391: 
 8392: Forth commonly uses two different methods for representing character
 8393: strings:
 8394: 
 8395: @itemize @bullet
 8396: @item
 8397: @cindex address of counted string
 8398: @cindex counted string
 8399: As a @dfn{counted string}, represented by a @i{c-addr}. The char
 8400: addressed by @i{c-addr} contains a character-count, @i{n}, of the
 8401: string and the string occupies the subsequent @i{n} char addresses in
 8402: memory.
 8403: @item
 8404: As cell pair on the stack; @i{c-addr u}, where @i{u} is the length
 8405: of the string in characters, and @i{c-addr} is the address of the
 8406: first byte of the string.
 8407: @end itemize
 8408: 
 8409: ANS Forth encourages the use of the second format when representing
 8410: strings on the stack, whilst conceeding that the counted string format
 8411: remains useful as a way of storing strings in memory.
 8412: 
 8413: 
 8414: doc-count
 8415: 
 8416: 
 8417: For words that move, copy and search for strings see @ref{Memory
 8418: Blocks}. For words that display characters and strings see
 8419: @ref{Displaying characters and strings}.
 8420: 
 8421: @node Displaying characters and strings, Input, String Formats, Other I/O
 8422: @subsection Displaying characters and strings
 8423: @cindex characters - compiling and displaying
 8424: @cindex character strings - compiling and displaying
 8425: 
 8426: This section starts with a glossary of Forth words and ends with a set
 8427: of examples.
 8428: 
 8429: 
 8430: doc-bl
 8431: doc-space
 8432: doc-spaces
 8433: doc-emit
 8434: doc-toupper
 8435: doc-."
 8436: doc-.(
 8437: doc-type
 8438: doc-typewhite
 8439: doc-cr
 8440: @cindex cursor control
 8441: doc-at-xy
 8442: doc-page
 8443: doc-s"
 8444: doc-c"
 8445: doc-char
 8446: doc-[char]
 8447: doc-sliteral
 8448: 
 8449: 
 8450: @noindent
 8451: As an example, consider the following text, stored in a file @file{test.fs}:
 8452: 
 8453: @example
 8454: .( text-1)
 8455: : my-word
 8456:   ." text-2" cr
 8457:   .( text-3)
 8458: ;
 8459: 
 8460: ." text-4"
 8461: 
 8462: : my-char
 8463:   [char] ALPHABET emit
 8464:   char emit
 8465: ;
 8466: @end example
 8467: 
 8468: When you load this code into Gforth, the following output is generated:
 8469: 
 8470: @example
 8471: @kbd{include test.fs @key{RET}} text-1text-3text-4 ok
 8472: @end example
 8473: 
 8474: @itemize @bullet
 8475: @item
 8476: Messages @code{text-1} and @code{text-3} are displayed because @code{.(} 
 8477: is an immediate word; it behaves in the same way whether it is used inside
 8478: or outside a colon definition.
 8479: @item
 8480: Message @code{text-4} is displayed because of Gforth's added interpretation
 8481: semantics for @code{."}.
 8482: @item
 8483: Message @code{text-2} is @i{not} displayed, because the text interpreter
 8484: performs the compilation semantics for @code{."} within the definition of
 8485: @code{my-word}.
 8486: @end itemize
 8487: 
 8488: Here are some examples of executing @code{my-word} and @code{my-char}:
 8489: 
 8490: @example
 8491: @kbd{my-word @key{RET}} text-2
 8492:  ok
 8493: @kbd{my-char fred @key{RET}} Af ok
 8494: @kbd{my-char jim @key{RET}} Aj ok
 8495: @end example
 8496: 
 8497: @itemize @bullet
 8498: @item
 8499: Message @code{text-2} is displayed because of the run-time behaviour of
 8500: @code{."}.
 8501: @item
 8502: @code{[char]} compiles the ``A'' from ``ALPHABET'' and puts its display code
 8503: on the stack at run-time. @code{emit} always displays the character
 8504: when @code{my-char} is executed.
 8505: @item
 8506: @code{char} parses a string at run-time and the second @code{emit} displays
 8507: the first character of the string.
 8508: @item
 8509: If you type @code{see my-char} you can see that @code{[char]} discarded
 8510: the text ``LPHABET'' and only compiled the display code for ``A'' into the
 8511: definition of @code{my-char}.
 8512: @end itemize
 8513: 
 8514: 
 8515: 
 8516: @node Input,  , Displaying characters and strings, Other I/O
 8517: @subsection Input
 8518: @cindex input
 8519: @cindex I/O - see input
 8520: @cindex parsing a string
 8521: 
 8522: For ways of storing character strings in memory see @ref{String Formats}.
 8523: 
 8524: @comment TODO examples for >number >float accept key key? pad parse word refill
 8525: @comment then index them
 8526: 
 8527: 
 8528: doc-key
 8529: doc-key?
 8530: doc-ekey
 8531: doc-ekey?
 8532: doc-ekey>char
 8533: doc->number
 8534: doc->float
 8535: doc-accept
 8536: doc-pad
 8537: doc-parse
 8538: doc-word
 8539: doc-sword
 8540: doc-(name)
 8541: doc-refill
 8542: @comment obsolescent words..
 8543: doc-convert
 8544: doc-query
 8545: doc-expect
 8546: doc-span
 8547: 
 8548: 
 8549: 
 8550: @c -------------------------------------------------------------
 8551: @node Programming Tools, Assembler and Code Words, Other I/O, Words
 8552: @section Programming Tools
 8553: @cindex programming tools
 8554: 
 8555: @menu
 8556: * Debugging::                   Simple and quick.
 8557: * Assertions::                  Making your programs self-checking.
 8558: * Singlestep Debugger::         Executing your program word by word.
 8559: @end menu
 8560: 
 8561: @node Debugging, Assertions, Programming Tools, Programming Tools
 8562: @subsection Debugging
 8563: @cindex debugging
 8564: 
 8565: Languages with a slow edit/compile/link/test development loop tend to
 8566: require sophisticated tracing/stepping debuggers to facilate
 8567: productive debugging.
 8568: 
 8569: A much better (faster) way in fast-compiling languages is to add
 8570: printing code at well-selected places, let the program run, look at
 8571: the output, see where things went wrong, add more printing code, etc.,
 8572: until the bug is found.
 8573: 
 8574: The simple debugging aids provided in @file{debugs.fs}
 8575: are meant to support this style of debugging. In addition, there are
 8576: words for non-destructively inspecting the stack and memory:
 8577: 
 8578: 
 8579: doc-.s
 8580: doc-f.s
 8581: 
 8582: 
 8583: There is a word @code{.r} but it does @i{not} display the return
 8584: stack! It is used for formatted numeric output.
 8585: 
 8586: 
 8587: doc-depth
 8588: doc-fdepth
 8589: doc-clearstack
 8590: doc-?
 8591: doc-dump
 8592: 
 8593: 
 8594: The word @code{~~} prints debugging information (by default the source
 8595: location and the stack contents). It is easy to insert. If you use Emacs
 8596: it is also easy to remove (@kbd{C-x ~} in the Emacs Forth mode to
 8597: query-replace them with nothing). The deferred words
 8598: @code{printdebugdata} and @code{printdebugline} control the output of
 8599: @code{~~}. The default source location output format works well with
 8600: Emacs' compilation mode, so you can step through the program at the
 8601: source level using @kbd{C-x `} (the advantage over a stepping debugger
 8602: is that you can step in any direction and you know where the crash has
 8603: happened or where the strange data has occurred).
 8604: 
 8605: The default actions of @code{~~} clobber the contents of the pictured
 8606: numeric output string, so you should not use @code{~~}, e.g., between
 8607: @code{<#} and @code{#>}.
 8608: 
 8609: 
 8610: doc-~~
 8611: doc-printdebugdata
 8612: doc-printdebugline
 8613: 
 8614: doc-see
 8615: doc-marker
 8616: 
 8617: 
 8618: Here's an example of using @code{marker} at the start of a source file
 8619: that you are debugging; it ensures that you only ever have one copy of
 8620: the file's definitions compiled at any time:
 8621: 
 8622: @example
 8623: [IFDEF] my-code
 8624:     my-code
 8625: [ENDIF]
 8626: 
 8627: marker my-code
 8628: init-included-files
 8629: 
 8630: \ .. definitions start here
 8631: \ .
 8632: \ .
 8633: \ end
 8634: @end example
 8635: 
 8636: 
 8637: 
 8638: @node Assertions, Singlestep Debugger, Debugging, Programming Tools
 8639: @subsection Assertions
 8640: @cindex assertions
 8641: 
 8642: It is a good idea to make your programs self-checking, especially if you
 8643: make an assumption that may become invalid during maintenance (for
 8644: example, that a certain field of a data structure is never zero). Gforth
 8645: supports @dfn{assertions} for this purpose. They are used like this:
 8646: 
 8647: @example
 8648: assert( @i{flag} )
 8649: @end example
 8650: 
 8651: The code between @code{assert(} and @code{)} should compute a flag, that
 8652: should be true if everything is alright and false otherwise. It should
 8653: not change anything else on the stack. The overall stack effect of the
 8654: assertion is @code{( -- )}. E.g.
 8655: 
 8656: @example
 8657: assert( 1 1 + 2 = ) \ what we learn in school
 8658: assert( dup 0<> ) \ assert that the top of stack is not zero
 8659: assert( false ) \ this code should not be reached
 8660: @end example
 8661: 
 8662: The need for assertions is different at different times. During
 8663: debugging, we want more checking, in production we sometimes care more
 8664: for speed. Therefore, assertions can be turned off, i.e., the assertion
 8665: becomes a comment. Depending on the importance of an assertion and the
 8666: time it takes to check it, you may want to turn off some assertions and
 8667: keep others turned on. Gforth provides several levels of assertions for
 8668: this purpose:
 8669: 
 8670: 
 8671: doc-assert0(
 8672: doc-assert1(
 8673: doc-assert2(
 8674: doc-assert3(
 8675: doc-assert(
 8676: doc-)
 8677: 
 8678: 
 8679: The variable @code{assert-level} specifies the highest assertions that
 8680: are turned on. I.e., at the default @code{assert-level} of one,
 8681: @code{assert0(} and @code{assert1(} assertions perform checking, while
 8682: @code{assert2(} and @code{assert3(} assertions are treated as comments.
 8683: 
 8684: The value of @code{assert-level} is evaluated at compile-time, not at
 8685: run-time. Therefore you cannot turn assertions on or off at run-time;
 8686: you have to set the @code{assert-level} appropriately before compiling a
 8687: piece of code. You can compile different pieces of code at different
 8688: @code{assert-level}s (e.g., a trusted library at level 1 and
 8689: newly-written code at level 3).
 8690: 
 8691: 
 8692: doc-assert-level
 8693: 
 8694: 
 8695: If an assertion fails, a message compatible with Emacs' compilation mode
 8696: is produced and the execution is aborted (currently with @code{ABORT"}.
 8697: If there is interest, we will introduce a special throw code. But if you
 8698: intend to @code{catch} a specific condition, using @code{throw} is
 8699: probably more appropriate than an assertion).
 8700: 
 8701: Definitions in ANS Forth for these assertion words are provided
 8702: in @file{compat/assert.fs}.
 8703: 
 8704: 
 8705: @node Singlestep Debugger,  , Assertions, Programming Tools
 8706: @subsection Singlestep Debugger
 8707: @cindex singlestep Debugger
 8708: @cindex debugging Singlestep
 8709: 
 8710: When you create a new word there's often the need to check whether it
 8711: behaves correctly or not. You can do this by typing @code{dbg
 8712: badword}. A debug session might look like this:
 8713: 
 8714: @example
 8715: : badword 0 DO i . LOOP ;  ok
 8716: 2 dbg badword 
 8717: : badword  
 8718: Scanning code...
 8719: 
 8720: Nesting debugger ready!
 8721: 
 8722: 400D4738  8049BC4 0              -> [ 2 ] 00002 00000 
 8723: 400D4740  8049F68 DO             -> [ 0 ] 
 8724: 400D4744  804A0C8 i              -> [ 1 ] 00000 
 8725: 400D4748 400C5E60 .              -> 0 [ 0 ] 
 8726: 400D474C  8049D0C LOOP           -> [ 0 ] 
 8727: 400D4744  804A0C8 i              -> [ 1 ] 00001 
 8728: 400D4748 400C5E60 .              -> 1 [ 0 ] 
 8729: 400D474C  8049D0C LOOP           -> [ 0 ] 
 8730: 400D4758  804B384 ;              ->  ok
 8731: @end example
 8732: 
 8733: Each line displayed is one step. You always have to hit return to
 8734: execute the next word that is displayed. If you don't want to execute
 8735: the next word in a whole, you have to type @kbd{n} for @code{nest}. Here is
 8736: an overview what keys are available:
 8737: 
 8738: @table @i
 8739: 
 8740: @item @key{RET}
 8741: Next; Execute the next word.
 8742: 
 8743: @item n
 8744: Nest; Single step through next word.
 8745: 
 8746: @item u
 8747: Unnest; Stop debugging and execute rest of word. If we got to this word
 8748: with nest, continue debugging with the calling word.
 8749: 
 8750: @item d
 8751: Done; Stop debugging and execute rest.
 8752: 
 8753: @item s
 8754: Stop; Abort immediately.
 8755: 
 8756: @end table
 8757: 
 8758: Debugging large application with this mechanism is very difficult, because
 8759: you have to nest very deeply into the program before the interesting part
 8760: begins. This takes a lot of time. 
 8761: 
 8762: To do it more directly put a @code{BREAK:} command into your source code.
 8763: When program execution reaches @code{BREAK:} the single step debugger is
 8764: invoked and you have all the features described above.
 8765: 
 8766: If you have more than one part to debug it is useful to know where the
 8767: program has stopped at the moment. You can do this by the 
 8768: @code{BREAK" string"} command. This behaves like @code{BREAK:} except that
 8769: string is typed out when the ``breakpoint'' is reached.
 8770: 
 8771: 
 8772: doc-dbg
 8773: doc-break:
 8774: doc-break"
 8775: 
 8776: 
 8777: 
 8778: @c -------------------------------------------------------------
 8779: @node Assembler and Code Words, Threading Words, Programming Tools, Words
 8780: @section Assembler and Code Words
 8781: @cindex assembler
 8782: @cindex code words
 8783: 
 8784: @menu
 8785: * Code and ;code::              
 8786: * Common Assembler::            Assembler Syntax
 8787: * Common Disassembler::         
 8788: * 386 Assembler::               Deviations and special cases
 8789: * Alpha Assembler::             Deviations and special cases
 8790: * MIPS assembler::              Deviations and special cases
 8791: * Other assemblers::            How to write them
 8792: @end menu
 8793: 
 8794: @node Code and ;code, Common Assembler, Assembler and Code Words, Assembler and Code Words
 8795: @subsection @code{Code} and @code{;code}
 8796: 
 8797: Gforth provides some words for defining primitives (words written in
 8798: machine code), and for defining the machine-code equivalent of
 8799: @code{DOES>}-based defining words. However, the machine-independent
 8800: nature of Gforth poses a few problems: First of all, Gforth runs on
 8801: several architectures, so it can provide no standard assembler. What's
 8802: worse is that the register allocation not only depends on the processor,
 8803: but also on the @code{gcc} version and options used.
 8804: 
 8805: The words that Gforth offers encapsulate some system dependences (e.g.,
 8806: the header structure), so a system-independent assembler may be used in
 8807: Gforth. If you do not have an assembler, you can compile machine code
 8808: directly with @code{,} and @code{c,}@footnote{This isn't portable,
 8809: because these words emit stuff in @i{data} space; it works because
 8810: Gforth has unified code/data spaces. Assembler isn't likely to be
 8811: portable anyway.}.
 8812: 
 8813: 
 8814: doc-assembler
 8815: doc-init-asm
 8816: doc-code
 8817: doc-end-code
 8818: doc-;code
 8819: doc-flush-icache
 8820: 
 8821: 
 8822: If @code{flush-icache} does not work correctly, @code{code} words
 8823: etc. will not work (reliably), either.
 8824: 
 8825: The typical usage of these @code{code} words can be shown most easily by
 8826: analogy to the equivalent high-level defining words:
 8827: 
 8828: @example
 8829: : foo                              code foo
 8830:    <high-level Forth words>              <assembler>
 8831: ;                                  end-code
 8832:                                 
 8833: : bar                              : bar
 8834:    <high-level Forth words>           <high-level Forth words>
 8835:    CREATE                             CREATE
 8836:       <high-level Forth words>           <high-level Forth words>
 8837:    DOES>                              ;code
 8838:       <high-level Forth words>           <assembler>
 8839: ;                                  end-code
 8840: @end example
 8841: 
 8842: @code{flush-icache} is always present. The other words are rarely used
 8843: and reside in @code{code.fs}, which is usually not loaded. You can load
 8844: it with @code{require code.fs}.
 8845: 
 8846: @cindex registers of the inner interpreter
 8847: In the assembly code you will want to refer to the inner interpreter's
 8848: registers (e.g., the data stack pointer) and you may want to use other
 8849: registers for temporary storage. Unfortunately, the register allocation
 8850: is installation-dependent.
 8851: 
 8852: The easiest solution is to use explicit register declarations
 8853: (@pxref{Explicit Reg Vars, , Variables in Specified Registers, gcc.info,
 8854: GNU C Manual}) for all of the inner interpreter's registers: You have to
 8855: compile Gforth with @code{-DFORCE_REG} (configure option
 8856: @code{--enable-force-reg}) and the appropriate declarations must be
 8857: present in the @code{machine.h} file (see @code{mips.h} for an example;
 8858: you can find a full list of all declarable register symbols with
 8859: @code{grep register engine.c}). If you give explicit registers to all
 8860: variables that are declared at the beginning of @code{engine()}, you
 8861: should be able to use the other caller-saved registers for temporary
 8862: storage. Alternatively, you can use the @code{gcc} option
 8863: @code{-ffixed-REG} (@pxref{Code Gen Options, , Options for Code
 8864: Generation Conventions, gcc.info, GNU C Manual}) to reserve a register
 8865: (however, this restriction on register allocation may slow Gforth
 8866: significantly).
 8867: 
 8868: If this solution is not viable (e.g., because @code{gcc} does not allow
 8869: you to explicitly declare all the registers you need), you have to find
 8870: out by looking at the code where the inner interpreter's registers
 8871: reside and which registers can be used for temporary storage. You can
 8872: get an assembly listing of the engine's code with @code{make engine.s}.
 8873: 
 8874: In any case, it is good practice to abstract your assembly code from the
 8875: actual register allocation. E.g., if the data stack pointer resides in
 8876: register @code{$17}, create an alias for this register called @code{sp},
 8877: and use that in your assembly code.
 8878: 
 8879: @cindex code words, portable
 8880: Another option for implementing normal and defining words efficiently
 8881: is to add the desired functionality to the source of Gforth. For normal
 8882: words you just have to edit @file{primitives} (@pxref{Automatic
 8883: Generation}). Defining words (equivalent to @code{;CODE} words, for fast
 8884: defined words) may require changes in @file{engine.c}, @file{kernel.fs},
 8885: @file{prims2x.fs}, and possibly @file{cross.fs}.
 8886: 
 8887: @node Common Assembler, Common Disassembler, Code and ;code, Assembler and Code Words
 8888: @subsection Common Assembler
 8889: 
 8890: The assemblers in Gforth generally use a postfix syntax, i.e., the
 8891: instruction name follows the operands.
 8892: 
 8893: The operands are passed in the usual order (the same that is used in the
 8894: manual of the architecture).  Since they all are Forth words, they have
 8895: to be separated by spaces; you can also use Forth words to compute the
 8896: operands.
 8897: 
 8898: The instruction names usually end with a @code{,}.  This makes it easier
 8899: to visually separate instructions if you put several of them on one
 8900: line; it also avoids shadowing other Forth words (e.g., @code{and}).
 8901: 
 8902: Registers are usually specified by number; e.g., (decimal) @code{11}
 8903: specifies registers R11 and F11 on the Alpha architecture (which one,
 8904: depends on the instruction).  The usual names are also available, e.g.,
 8905: @code{s2} for R11 on Alpha.
 8906: 
 8907: Control flow is specified similar to normal Forth code (@pxref{Arbitrary
 8908: control structures}), with @code{if,}, @code{ahead,}, @code{then,},
 8909: @code{begin,}, @code{until,}, @code{again,}, @code{cs-roll},
 8910: @code{cs-pick}, @code{else,}, @code{while,}, and @code{repeat,}.  The
 8911: conditions are specified in a way specific to each assembler.
 8912: 
 8913: Note that the register assignments of the Gforth engine can change
 8914: between Gforth versions, or even between different compilations of the
 8915: same Gforth version (e.g., if you use a different GCC version).  So if
 8916: you want to refer to Gforth's registers (e.g., the stack pointer or
 8917: TOS), I recommend defining your own words for refering to these
 8918: registers, and using them later on; then you can easily adapt to a
 8919: changed register assignment.  The stability of the register assignment
 8920: is usually better if you build Gforth with @code{--enable-force-reg}.
 8921: 
 8922: In particular, the resturn stack pointer and the instruction pointer are
 8923: in memory in @code{gforth}, and usually in registers in
 8924: @code{gforth-fast}.  The most common use of these registers is to
 8925: dispatch to the next word (the @code{next} routine).  A portable way to
 8926: do this is to jump to @code{' noop >code-address} (of course, this is
 8927: less efficient than integrating the @code{next} code and scheduling it
 8928: well).
 8929: 
 8930: @node  Common Disassembler, 386 Assembler, Common Assembler, Assembler and Code Words
 8931: @subsection Common Disassembler
 8932: 
 8933: You can disassemble a @code{code} word with @code{see}
 8934: (@pxref{Debugging}).  You can disassemble a section of memory with
 8935: 
 8936: doc-disasm
 8937: 
 8938: The disassembler generally produces output that can be fed into the
 8939: assembler (i.e., same syntax, etc.).  It also includes additional
 8940: information in comments.  In particular, the address of the instruction
 8941: is given in a comment before the instruction.
 8942: 
 8943: @code{See} may display more or less than the actual code of the word,
 8944: because the recognition of the end of the code is unreliable.  You can
 8945: use @code{disasm} if it did not display enough.  It may display more, if
 8946: the code word is not immediately followed by a named word.  If you have
 8947: something else there, you can follow the word with @code{align last @ ,}
 8948: to ensure that the end is recognized.
 8949: 
 8950: @node 386 Assembler, Alpha Assembler, Common Disassembler, Assembler and Code Words
 8951: @subsection 386 Assembler
 8952: 
 8953: The 386 assembler included in Gforth was written by Bernd Paysan, it's
 8954: available under GPL, and originally part of bigFORTH.
 8955: 
 8956: The 386 disassembler included in Gforth was written by Andrew McKewan
 8957: and is in the public domain.
 8958: 
 8959: The disassembler displays code in prefix Intel syntax.
 8960: 
 8961: The assembler uses a postfix syntax with reversed parameters.
 8962: 
 8963: The assembler includes all instruction of the Athlon, i.e. 486 core
 8964: instructions, Pentium and PPro extensions, floating point, MMX, 3Dnow!,
 8965: but not ISSE. It's an integrated 16- and 32-bit assembler. Default is 32
 8966: bit, you can switch to 16 bit with .86 and back to 32 bit with .386.
 8967: 
 8968: There are several prefixes to switch between different operation sizes,
 8969: @code{.b} for byte accesses, @code{.w} for word accesses, @code{.d} for
 8970: double-word accesses. Addressing modes can be switched with @code{.wa}
 8971: for 16 bit addresses, and @code{.da} for 32 bit addresses. You don't
 8972: need a prefix for byte register names (@code{AL} et al).
 8973: 
 8974: For floating point operations, the prefixes are @code{.fs} (IEEE
 8975: single), @code{.fl} (IEEE double), @code{.fx} (extended), @code{.fw}
 8976: (word), @code{.fd} (double-word), and @code{.fq} (quad-word).
 8977: 
 8978: The MMX opcodes don't have size prefixes, they are spelled out like in
 8979: the Intel assembler. Instead of move from and to memory, there are
 8980: PLDQ/PLDD and PSTQ/PSTD.
 8981: 
 8982: The registers lack the 'e' prefix; even in 32 bit mode, eax is called
 8983: ax.  Immediate values are indicated by postfixing them with @code{#},
 8984: e.g., @code{3 #}.  Here are some examples of addressing modes:
 8985: 
 8986: @example
 8987: 3 #          \ immediate
 8988: ax           \ register
 8989: 100 di d)    \ 100[edi]
 8990: 4 bx cx di)  \ 4[ebx][ecx]
 8991: di ax *4 i)  \ [edi][eax*4]
 8992: 20 ax *4 i#) \ 20[eax*4]
 8993: @end example
 8994: 
 8995: Some example of instructions are:
 8996: 
 8997: @example
 8998: ax bx mov             \ move ebx,eax
 8999: 3 # ax mov            \ mov eax,3
 9000: 100 di ) ax mov       \ mov eax,100[edi]
 9001: 4 bx cx di) ax mov    \ mov eax,4[ebx][ecx]
 9002: .w ax bx mov          \ mov bx,ax
 9003: @end example
 9004: 
 9005: The following forms are supported for binary instructions:
 9006: 
 9007: @example
 9008: <reg> <reg> <inst>
 9009: <n> # <reg> <inst>
 9010: <mem> <reg> <inst>
 9011: <reg> <mem> <inst>
 9012: @end example
 9013: 
 9014: Immediate to memory is not supported.  The shift/rotate syntax is:
 9015: 
 9016: @example
 9017: <reg/mem> 1 # shl \ shortens to shift without immediate
 9018: <reg/mem> 4 # shl
 9019: <reg/mem> cl shl
 9020: @end example
 9021: 
 9022: Precede string instructions (@code{movs} etc.) with @code{.b} to get
 9023: the byte version.
 9024: 
 9025: The control structure words @code{IF} @code{UNTIL} etc. must be preceded
 9026: by one of these conditions: @code{vs vc u< u>= 0= 0<> u<= u> 0< 0>= ps
 9027: pc < >= <= >}. (Note that most of these words shadow some Forth words
 9028: when @code{assembler} is in front of @code{forth} in the search path,
 9029: e.g., in @code{code} words).  Currently the control structure words use
 9030: one stack item, so you have to use @code{roll} instead of @code{cs-roll}
 9031: to shuffle them (you can also use @code{swap} etc.).
 9032: 
 9033: Here is an example of a @code{code} word (assumes that the stack pointer
 9034: is in esi and the TOS is in ebx):
 9035: 
 9036: @example
 9037: code my+ ( n1 n2 -- n )
 9038:     4 si D) bx add
 9039:     4 # si add
 9040:     Next
 9041: end-code
 9042: @end example
 9043: 
 9044: @node Alpha Assembler, MIPS assembler, 386 Assembler, Assembler and Code Words
 9045: @subsection Alpha Assembler
 9046: 
 9047: The Alpha assembler and disassembler were originally written by Bernd
 9048: Thallner.
 9049: 
 9050: The register names @code{a0}--@code{a5} are not available to avoid
 9051: shadowing hex numbers.
 9052: 
 9053: Immediate forms of arithmetic instructions are distinguished by a
 9054: @code{#} just before the @code{,}, e.g., @code{and#,} (note: @code{lda,}
 9055: does not count as arithmetic instruction).
 9056: 
 9057: You have to specify all operands to an instruction, even those that
 9058: other assemblers consider optional, e.g., the destination register for
 9059: @code{br,}, or the destination register and hint for @code{jmp,}.
 9060: 
 9061: You can specify conditions for @code{if,} by removing the first @code{b}
 9062: and the trailing @code{,} from a branch with a corresponding name; e.g.,
 9063: 
 9064: @example
 9065: 11 fgt if, \ if F11>0e
 9066:   ...
 9067: endif,
 9068: @end example
 9069: 
 9070: @code{fbgt,} gives @code{fgt}.  
 9071: 
 9072: @node MIPS assembler, Other assemblers, Alpha Assembler, Assembler and Code Words
 9073: @subsection MIPS assembler
 9074: 
 9075: The MIPS assembler was originally written by Christian Pirker.
 9076: 
 9077: Currently the assembler and disassembler only cover the MIPS-I
 9078: architecture (R3000), and don't support FP instructions.
 9079: 
 9080: The register names @code{$a0}--@code{$a3} are not available to avoid
 9081: shadowing hex numbers.
 9082: 
 9083: Because there is no way to distinguish registers from immediate values,
 9084: you have to explicitly use the immediate forms of instructions, i.e.,
 9085: @code{addiu,}, not just @code{addu,} (@command{as} does this
 9086: implicitly).
 9087: 
 9088: If the architecture manual specifies several formats for the instruction
 9089: (e.g., for @code{jalr,}), you usually have to use the one with more
 9090: arguments (i.e., two for @code{jalr,}).  When in doubt, see
 9091: @code{arch/mips/testasm.fs} for an example of correct use.
 9092: 
 9093: Branches and jumps in the MIPS architecture have a delay slot.  You have
 9094: to fill it yourself (the simplest way is to use @code{nop,}), the
 9095: assembler does not do it for you (unlike @command{as}).  Even
 9096: @code{if,}, @code{ahead,}, @code{until,}, @code{again,}, @code{while,},
 9097: @code{else,} and @code{repeat,} need a delay slot.  Since @code{begin,}
 9098: and @code{then,} just specify branch targets, they are not affected.
 9099: 
 9100: Note that you must not put branches, jumps, or @code{li,} into the delay
 9101: slot: @code{li,} may expand to several instructions, and control flow
 9102: instructions may not be put into the branch delay slot in any case.
 9103: 
 9104: For branches the argument specifying the target is a relative address;
 9105: You have to add the address of the delay slot to get the absolute
 9106: address.
 9107: 
 9108: The MIPS architecture also has load delay slots and restrictions on
 9109: using @code{mfhi,} and @code{mflo,}; you have to order the instructions
 9110: yourself to satisfy these restrictions, the assembler does not do it for
 9111: you.
 9112: 
 9113: You can specify the conditions for @code{if,} etc. by taking a
 9114: conditional branch and leaving away the @code{b} at the start and the
 9115: @code{,} at the end.  E.g.,
 9116: 
 9117: @example
 9118: 4 5 eq if,
 9119:   ... \ do something if $4 equals $5
 9120: then,
 9121: @end example
 9122: 
 9123: @node Other assemblers,  , MIPS assembler, Assembler and Code Words
 9124: @subsection Other assemblers
 9125: 
 9126: If you want to contribute another assembler/disassembler, please contact
 9127: us (@email{bug-gforth@@gnu.org}) to check if we have such an assembler
 9128: already.  If you are writing them from scratch, please use a similar
 9129: syntax style as the one we use (i.e., postfix, commas at the end of the
 9130: instruction names, @pxref{Common Assembler}); make the output of the
 9131: disassembler be valid input for the assembler, and keep the style
 9132: similar to the style we used.
 9133: 
 9134: Hints on implementation: The most important part is to have a good test
 9135: suite that contains all instructions.  Once you have that, the rest is
 9136: easy.  For actual coding you can take a look at
 9137: @file{arch/mips/disasm.fs} to get some ideas on how to use data for both
 9138: the assembler and disassembler, avoiding redundancy and some potential
 9139: bugs.  You can also look at that file (and @pxref{Advanced does> usage
 9140: example}) to get ideas how to factor a disassembler.
 9141: 
 9142: Start with the disassembler, because it's easier to reuse data from the
 9143: disassembler for the assembler than the other way round.
 9144: 
 9145: For the assembler, take a look at @file{arch/alpha/asm.fs}, which shows
 9146: how simple it can be.
 9147: 
 9148: @c -------------------------------------------------------------
 9149: @node Threading Words, Locals, Assembler and Code Words, Words
 9150: @section Threading Words
 9151: @cindex threading words
 9152: 
 9153: @cindex code address
 9154: These words provide access to code addresses and other threading stuff
 9155: in Gforth (and, possibly, other interpretive Forths). It more or less
 9156: abstracts away the differences between direct and indirect threading
 9157: (and, for direct threading, the machine dependences). However, at
 9158: present this wordset is still incomplete. It is also pretty low-level;
 9159: some day it will hopefully be made unnecessary by an internals wordset
 9160: that abstracts implementation details away completely.
 9161: 
 9162: 
 9163: doc-threading-method
 9164: doc->code-address
 9165: doc->does-code
 9166: doc-code-address!
 9167: doc-does-code!
 9168: doc-does-handler!
 9169: doc-/does-handler
 9170: 
 9171: 
 9172: The code addresses produced by various defining words are produced by
 9173: the following words:
 9174: 
 9175: 
 9176: doc-docol:
 9177: doc-docon:
 9178: doc-dovar:
 9179: doc-douser:
 9180: doc-dodefer:
 9181: doc-dofield:
 9182: 
 9183: 
 9184: You can recognize words defined by a @code{CREATE}...@code{DOES>} word
 9185: with @code{>does-code}. If the word was defined in that way, the value
 9186: returned is non-zero and identifies the @code{DOES>} used by the
 9187: defining word.
 9188: @comment TODO should that be ``identifies the xt of the DOES> ??''
 9189: 
 9190: @c -------------------------------------------------------------
 9191: @node Locals, Structures, Threading Words, Words
 9192: @section Locals
 9193: @cindex locals
 9194: 
 9195: Local variables can make Forth programming more enjoyable and Forth
 9196: programs easier to read. Unfortunately, the locals of ANS Forth are
 9197: laden with restrictions. Therefore, we provide not only the ANS Forth
 9198: locals wordset, but also our own, more powerful locals wordset (we
 9199: implemented the ANS Forth locals wordset through our locals wordset).
 9200: 
 9201: The ideas in this section have also been published in M. Anton Ertl,
 9202: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl94l.ps.gz,
 9203: Automatic Scoping of Local Variables}}, EuroForth '94.
 9204: 
 9205: @menu
 9206: * Gforth locals::               
 9207: * ANS Forth locals::            
 9208: @end menu
 9209: 
 9210: @node Gforth locals, ANS Forth locals, Locals, Locals
 9211: @subsection Gforth locals
 9212: @cindex Gforth locals
 9213: @cindex locals, Gforth style
 9214: 
 9215: Locals can be defined with
 9216: 
 9217: @example
 9218: @{ local1 local2 ... -- comment @}
 9219: @end example
 9220: or
 9221: @example
 9222: @{ local1 local2 ... @}
 9223: @end example
 9224: 
 9225: E.g.,
 9226: @example
 9227: : max @{ n1 n2 -- n3 @}
 9228:  n1 n2 > if
 9229:    n1
 9230:  else
 9231:    n2
 9232:  endif ;
 9233: @end example
 9234: 
 9235: The similarity of locals definitions with stack comments is intended. A
 9236: locals definition often replaces the stack comment of a word. The order
 9237: of the locals corresponds to the order in a stack comment and everything
 9238: after the @code{--} is really a comment.
 9239: 
 9240: This similarity has one disadvantage: It is too easy to confuse locals
 9241: declarations with stack comments, causing bugs and making them hard to
 9242: find. However, this problem can be avoided by appropriate coding
 9243: conventions: Do not use both notations in the same program. If you do,
 9244: they should be distinguished using additional means, e.g. by position.
 9245: 
 9246: @cindex types of locals
 9247: @cindex locals types
 9248: The name of the local may be preceded by a type specifier, e.g.,
 9249: @code{F:} for a floating point value:
 9250: 
 9251: @example
 9252: : CX* @{ F: Ar F: Ai F: Br F: Bi -- Cr Ci @}
 9253: \ complex multiplication
 9254:  Ar Br f* Ai Bi f* f-
 9255:  Ar Bi f* Ai Br f* f+ ;
 9256: @end example
 9257: 
 9258: @cindex flavours of locals
 9259: @cindex locals flavours
 9260: @cindex value-flavoured locals
 9261: @cindex variable-flavoured locals
 9262: Gforth currently supports cells (@code{W:}, @code{W^}), doubles
 9263: (@code{D:}, @code{D^}), floats (@code{F:}, @code{F^}) and characters
 9264: (@code{C:}, @code{C^}) in two flavours: a value-flavoured local (defined
 9265: with @code{W:}, @code{D:} etc.) produces its value and can be changed
 9266: with @code{TO}. A variable-flavoured local (defined with @code{W^} etc.)
 9267: produces its address (which becomes invalid when the variable's scope is
 9268: left). E.g., the standard word @code{emit} can be defined in terms of
 9269: @code{type} like this:
 9270: 
 9271: @example
 9272: : emit @{ C^ char* -- @}
 9273:     char* 1 type ;
 9274: @end example
 9275: 
 9276: @cindex default type of locals
 9277: @cindex locals, default type
 9278: A local without type specifier is a @code{W:} local. Both flavours of
 9279: locals are initialized with values from the data or FP stack.
 9280: 
 9281: Currently there is no way to define locals with user-defined data
 9282: structures, but we are working on it.
 9283: 
 9284: Gforth allows defining locals everywhere in a colon definition. This
 9285: poses the following questions:
 9286: 
 9287: @menu
 9288: * Where are locals visible by name?::  
 9289: * How long do locals live?::    
 9290: * Programming Style::           
 9291: * Implementation::              
 9292: @end menu
 9293: 
 9294: @node Where are locals visible by name?, How long do locals live?, Gforth locals, Gforth locals
 9295: @subsubsection Where are locals visible by name?
 9296: @cindex locals visibility
 9297: @cindex visibility of locals
 9298: @cindex scope of locals
 9299: 
 9300: Basically, the answer is that locals are visible where you would expect
 9301: it in block-structured languages, and sometimes a little longer. If you
 9302: want to restrict the scope of a local, enclose its definition in
 9303: @code{SCOPE}...@code{ENDSCOPE}.
 9304: 
 9305: 
 9306: doc-scope
 9307: doc-endscope
 9308: 
 9309: 
 9310: These words behave like control structure words, so you can use them
 9311: with @code{CS-PICK} and @code{CS-ROLL} to restrict the scope in
 9312: arbitrary ways.
 9313: 
 9314: If you want a more exact answer to the visibility question, here's the
 9315: basic principle: A local is visible in all places that can only be
 9316: reached through the definition of the local@footnote{In compiler
 9317: construction terminology, all places dominated by the definition of the
 9318: local.}. In other words, it is not visible in places that can be reached
 9319: without going through the definition of the local. E.g., locals defined
 9320: in @code{IF}...@code{ENDIF} are visible until the @code{ENDIF}, locals
 9321: defined in @code{BEGIN}...@code{UNTIL} are visible after the
 9322: @code{UNTIL} (until, e.g., a subsequent @code{ENDSCOPE}).
 9323: 
 9324: The reasoning behind this solution is: We want to have the locals
 9325: visible as long as it is meaningful. The user can always make the
 9326: visibility shorter by using explicit scoping. In a place that can
 9327: only be reached through the definition of a local, the meaning of a
 9328: local name is clear. In other places it is not: How is the local
 9329: initialized at the control flow path that does not contain the
 9330: definition? Which local is meant, if the same name is defined twice in
 9331: two independent control flow paths?
 9332: 
 9333: This should be enough detail for nearly all users, so you can skip the
 9334: rest of this section. If you really must know all the gory details and
 9335: options, read on.
 9336: 
 9337: In order to implement this rule, the compiler has to know which places
 9338: are unreachable. It knows this automatically after @code{AHEAD},
 9339: @code{AGAIN}, @code{EXIT} and @code{LEAVE}; in other cases (e.g., after
 9340: most @code{THROW}s), you can use the word @code{UNREACHABLE} to tell the
 9341: compiler that the control flow never reaches that place. If
 9342: @code{UNREACHABLE} is not used where it could, the only consequence is
 9343: that the visibility of some locals is more limited than the rule above
 9344: says. If @code{UNREACHABLE} is used where it should not (i.e., if you
 9345: lie to the compiler), buggy code will be produced.
 9346: 
 9347: 
 9348: doc-unreachable
 9349: 
 9350: 
 9351: Another problem with this rule is that at @code{BEGIN}, the compiler
 9352: does not know which locals will be visible on the incoming
 9353: back-edge. All problems discussed in the following are due to this
 9354: ignorance of the compiler (we discuss the problems using @code{BEGIN}
 9355: loops as examples; the discussion also applies to @code{?DO} and other
 9356: loops). Perhaps the most insidious example is:
 9357: @example
 9358: AHEAD
 9359: BEGIN
 9360:   x
 9361: [ 1 CS-ROLL ] THEN
 9362:   @{ x @}
 9363:   ...
 9364: UNTIL
 9365: @end example
 9366: 
 9367: This should be legal according to the visibility rule. The use of
 9368: @code{x} can only be reached through the definition; but that appears
 9369: textually below the use.
 9370: 
 9371: From this example it is clear that the visibility rules cannot be fully
 9372: implemented without major headaches. Our implementation treats common
 9373: cases as advertised and the exceptions are treated in a safe way: The
 9374: compiler makes a reasonable guess about the locals visible after a
 9375: @code{BEGIN}; if it is too pessimistic, the
 9376: user will get a spurious error about the local not being defined; if the
 9377: compiler is too optimistic, it will notice this later and issue a
 9378: warning. In the case above the compiler would complain about @code{x}
 9379: being undefined at its use. You can see from the obscure examples in
 9380: this section that it takes quite unusual control structures to get the
 9381: compiler into trouble, and even then it will often do fine.
 9382: 
 9383: If the @code{BEGIN} is reachable from above, the most optimistic guess
 9384: is that all locals visible before the @code{BEGIN} will also be
 9385: visible after the @code{BEGIN}. This guess is valid for all loops that
 9386: are entered only through the @code{BEGIN}, in particular, for normal
 9387: @code{BEGIN}...@code{WHILE}...@code{REPEAT} and
 9388: @code{BEGIN}...@code{UNTIL} loops and it is implemented in our
 9389: compiler. When the branch to the @code{BEGIN} is finally generated by
 9390: @code{AGAIN} or @code{UNTIL}, the compiler checks the guess and
 9391: warns the user if it was too optimistic:
 9392: @example
 9393: IF
 9394:   @{ x @}
 9395: BEGIN
 9396:   \ x ? 
 9397: [ 1 cs-roll ] THEN
 9398:   ...
 9399: UNTIL
 9400: @end example
 9401: 
 9402: Here, @code{x} lives only until the @code{BEGIN}, but the compiler
 9403: optimistically assumes that it lives until the @code{THEN}. It notices
 9404: this difference when it compiles the @code{UNTIL} and issues a
 9405: warning. The user can avoid the warning, and make sure that @code{x}
 9406: is not used in the wrong area by using explicit scoping:
 9407: @example
 9408: IF
 9409:   SCOPE
 9410:   @{ x @}
 9411:   ENDSCOPE
 9412: BEGIN
 9413: [ 1 cs-roll ] THEN
 9414:   ...
 9415: UNTIL
 9416: @end example
 9417: 
 9418: Since the guess is optimistic, there will be no spurious error messages
 9419: about undefined locals.
 9420: 
 9421: If the @code{BEGIN} is not reachable from above (e.g., after
 9422: @code{AHEAD} or @code{EXIT}), the compiler cannot even make an
 9423: optimistic guess, as the locals visible after the @code{BEGIN} may be
 9424: defined later. Therefore, the compiler assumes that no locals are
 9425: visible after the @code{BEGIN}. However, the user can use
 9426: @code{ASSUME-LIVE} to make the compiler assume that the same locals are
 9427: visible at the BEGIN as at the point where the top control-flow stack
 9428: item was created.
 9429: 
 9430: 
 9431: doc-assume-live
 9432: 
 9433: 
 9434: @noindent
 9435: E.g.,
 9436: @example
 9437: @{ x @}
 9438: AHEAD
 9439: ASSUME-LIVE
 9440: BEGIN
 9441:   x
 9442: [ 1 CS-ROLL ] THEN
 9443:   ...
 9444: UNTIL
 9445: @end example
 9446: 
 9447: Other cases where the locals are defined before the @code{BEGIN} can be
 9448: handled by inserting an appropriate @code{CS-ROLL} before the
 9449: @code{ASSUME-LIVE} (and changing the control-flow stack manipulation
 9450: behind the @code{ASSUME-LIVE}).
 9451: 
 9452: Cases where locals are defined after the @code{BEGIN} (but should be
 9453: visible immediately after the @code{BEGIN}) can only be handled by
 9454: rearranging the loop. E.g., the ``most insidious'' example above can be
 9455: arranged into:
 9456: @example
 9457: BEGIN
 9458:   @{ x @}
 9459:   ... 0=
 9460: WHILE
 9461:   x
 9462: REPEAT
 9463: @end example
 9464: 
 9465: @node How long do locals live?, Programming Style, Where are locals visible by name?, Gforth locals
 9466: @subsubsection How long do locals live?
 9467: @cindex locals lifetime
 9468: @cindex lifetime of locals
 9469: 
 9470: The right answer for the lifetime question would be: A local lives at
 9471: least as long as it can be accessed. For a value-flavoured local this
 9472: means: until the end of its visibility. However, a variable-flavoured
 9473: local could be accessed through its address far beyond its visibility
 9474: scope. Ultimately, this would mean that such locals would have to be
 9475: garbage collected. Since this entails un-Forth-like implementation
 9476: complexities, I adopted the same cowardly solution as some other
 9477: languages (e.g., C): The local lives only as long as it is visible;
 9478: afterwards its address is invalid (and programs that access it
 9479: afterwards are erroneous).
 9480: 
 9481: @node Programming Style, Implementation, How long do locals live?, Gforth locals
 9482: @subsubsection Programming Style
 9483: @cindex locals programming style
 9484: @cindex programming style, locals
 9485: 
 9486: The freedom to define locals anywhere has the potential to change
 9487: programming styles dramatically. In particular, the need to use the
 9488: return stack for intermediate storage vanishes. Moreover, all stack
 9489: manipulations (except @code{PICK}s and @code{ROLL}s with run-time
 9490: determined arguments) can be eliminated: If the stack items are in the
 9491: wrong order, just write a locals definition for all of them; then
 9492: write the items in the order you want.
 9493: 
 9494: This seems a little far-fetched and eliminating stack manipulations is
 9495: unlikely to become a conscious programming objective. Still, the number
 9496: of stack manipulations will be reduced dramatically if local variables
 9497: are used liberally (e.g., compare @code{max} (@pxref{Gforth locals}) with
 9498: a traditional implementation of @code{max}).
 9499: 
 9500: This shows one potential benefit of locals: making Forth programs more
 9501: readable. Of course, this benefit will only be realized if the
 9502: programmers continue to honour the principle of factoring instead of
 9503: using the added latitude to make the words longer.
 9504: 
 9505: @cindex single-assignment style for locals
 9506: Using @code{TO} can and should be avoided.  Without @code{TO},
 9507: every value-flavoured local has only a single assignment and many
 9508: advantages of functional languages apply to Forth. I.e., programs are
 9509: easier to analyse, to optimize and to read: It is clear from the
 9510: definition what the local stands for, it does not turn into something
 9511: different later.
 9512: 
 9513: E.g., a definition using @code{TO} might look like this:
 9514: @example
 9515: : strcmp @{ addr1 u1 addr2 u2 -- n @}
 9516:  u1 u2 min 0
 9517:  ?do
 9518:    addr1 c@@ addr2 c@@ -
 9519:    ?dup-if
 9520:      unloop exit
 9521:    then
 9522:    addr1 char+ TO addr1
 9523:    addr2 char+ TO addr2
 9524:  loop
 9525:  u1 u2 - ;
 9526: @end example
 9527: Here, @code{TO} is used to update @code{addr1} and @code{addr2} at
 9528: every loop iteration. @code{strcmp} is a typical example of the
 9529: readability problems of using @code{TO}. When you start reading
 9530: @code{strcmp}, you think that @code{addr1} refers to the start of the
 9531: string. Only near the end of the loop you realize that it is something
 9532: else.
 9533: 
 9534: This can be avoided by defining two locals at the start of the loop that
 9535: are initialized with the right value for the current iteration.
 9536: @example
 9537: : strcmp @{ addr1 u1 addr2 u2 -- n @}
 9538:  addr1 addr2
 9539:  u1 u2 min 0 
 9540:  ?do @{ s1 s2 @}
 9541:    s1 c@@ s2 c@@ -
 9542:    ?dup-if
 9543:      unloop exit
 9544:    then
 9545:    s1 char+ s2 char+
 9546:  loop
 9547:  2drop
 9548:  u1 u2 - ;
 9549: @end example
 9550: Here it is clear from the start that @code{s1} has a different value
 9551: in every loop iteration.
 9552: 
 9553: @node Implementation,  , Programming Style, Gforth locals
 9554: @subsubsection Implementation
 9555: @cindex locals implementation
 9556: @cindex implementation of locals
 9557: 
 9558: @cindex locals stack
 9559: Gforth uses an extra locals stack. The most compelling reason for
 9560: this is that the return stack is not float-aligned; using an extra stack
 9561: also eliminates the problems and restrictions of using the return stack
 9562: as locals stack. Like the other stacks, the locals stack grows toward
 9563: lower addresses. A few primitives allow an efficient implementation:
 9564: 
 9565: 
 9566: doc-@local#
 9567: doc-f@local#
 9568: doc-laddr#
 9569: doc-lp+!#
 9570: doc-lp!
 9571: doc->l
 9572: doc-f>l
 9573: 
 9574: 
 9575: In addition to these primitives, some specializations of these
 9576: primitives for commonly occurring inline arguments are provided for
 9577: efficiency reasons, e.g., @code{@@local0} as specialization of
 9578: @code{@@local#} for the inline argument 0. The following compiling words
 9579: compile the right specialized version, or the general version, as
 9580: appropriate:
 9581: 
 9582: 
 9583: doc-compile-@local
 9584: doc-compile-f@local
 9585: doc-compile-lp+!
 9586: 
 9587: 
 9588: Combinations of conditional branches and @code{lp+!#} like
 9589: @code{?branch-lp+!#} (the locals pointer is only changed if the branch
 9590: is taken) are provided for efficiency and correctness in loops.
 9591: 
 9592: A special area in the dictionary space is reserved for keeping the
 9593: local variable names. @code{@{} switches the dictionary pointer to this
 9594: area and @code{@}} switches it back and generates the locals
 9595: initializing code. @code{W:} etc.@ are normal defining words. This
 9596: special area is cleared at the start of every colon definition.
 9597: 
 9598: @cindex word list for defining locals
 9599: A special feature of Gforth's dictionary is used to implement the
 9600: definition of locals without type specifiers: every word list (aka
 9601: vocabulary) has its own methods for searching
 9602: etc. (@pxref{Word Lists}). For the present purpose we defined a word list
 9603: with a special search method: When it is searched for a word, it
 9604: actually creates that word using @code{W:}. @code{@{} changes the search
 9605: order to first search the word list containing @code{@}}, @code{W:} etc.,
 9606: and then the word list for defining locals without type specifiers.
 9607: 
 9608: The lifetime rules support a stack discipline within a colon
 9609: definition: The lifetime of a local is either nested with other locals
 9610: lifetimes or it does not overlap them.
 9611: 
 9612: At @code{BEGIN}, @code{IF}, and @code{AHEAD} no code for locals stack
 9613: pointer manipulation is generated. Between control structure words
 9614: locals definitions can push locals onto the locals stack. @code{AGAIN}
 9615: is the simplest of the other three control flow words. It has to
 9616: restore the locals stack depth of the corresponding @code{BEGIN}
 9617: before branching. The code looks like this:
 9618: @format
 9619: @code{lp+!#} current-locals-size @minus{} dest-locals-size
 9620: @code{branch} <begin>
 9621: @end format
 9622: 
 9623: @code{UNTIL} is a little more complicated: If it branches back, it
 9624: must adjust the stack just like @code{AGAIN}. But if it falls through,
 9625: the locals stack must not be changed. The compiler generates the
 9626: following code:
 9627: @format
 9628: @code{?branch-lp+!#} <begin> current-locals-size @minus{} dest-locals-size
 9629: @end format
 9630: The locals stack pointer is only adjusted if the branch is taken.
 9631: 
 9632: @code{THEN} can produce somewhat inefficient code:
 9633: @format
 9634: @code{lp+!#} current-locals-size @minus{} orig-locals-size
 9635: <orig target>:
 9636: @code{lp+!#} orig-locals-size @minus{} new-locals-size
 9637: @end format
 9638: The second @code{lp+!#} adjusts the locals stack pointer from the
 9639: level at the @i{orig} point to the level after the @code{THEN}. The
 9640: first @code{lp+!#} adjusts the locals stack pointer from the current
 9641: level to the level at the orig point, so the complete effect is an
 9642: adjustment from the current level to the right level after the
 9643: @code{THEN}.
 9644: 
 9645: @cindex locals information on the control-flow stack
 9646: @cindex control-flow stack items, locals information
 9647: In a conventional Forth implementation a dest control-flow stack entry
 9648: is just the target address and an orig entry is just the address to be
 9649: patched. Our locals implementation adds a word list to every orig or dest
 9650: item. It is the list of locals visible (or assumed visible) at the point
 9651: described by the entry. Our implementation also adds a tag to identify
 9652: the kind of entry, in particular to differentiate between live and dead
 9653: (reachable and unreachable) orig entries.
 9654: 
 9655: A few unusual operations have to be performed on locals word lists:
 9656: 
 9657: 
 9658: doc-common-list
 9659: doc-sub-list?
 9660: doc-list-size
 9661: 
 9662: 
 9663: Several features of our locals word list implementation make these
 9664: operations easy to implement: The locals word lists are organised as
 9665: linked lists; the tails of these lists are shared, if the lists
 9666: contain some of the same locals; and the address of a name is greater
 9667: than the address of the names behind it in the list.
 9668: 
 9669: Another important implementation detail is the variable
 9670: @code{dead-code}. It is used by @code{BEGIN} and @code{THEN} to
 9671: determine if they can be reached directly or only through the branch
 9672: that they resolve. @code{dead-code} is set by @code{UNREACHABLE},
 9673: @code{AHEAD}, @code{EXIT} etc., and cleared at the start of a colon
 9674: definition, by @code{BEGIN} and usually by @code{THEN}.
 9675: 
 9676: Counted loops are similar to other loops in most respects, but
 9677: @code{LEAVE} requires special attention: It performs basically the same
 9678: service as @code{AHEAD}, but it does not create a control-flow stack
 9679: entry. Therefore the information has to be stored elsewhere;
 9680: traditionally, the information was stored in the target fields of the
 9681: branches created by the @code{LEAVE}s, by organizing these fields into a
 9682: linked list. Unfortunately, this clever trick does not provide enough
 9683: space for storing our extended control flow information. Therefore, we
 9684: introduce another stack, the leave stack. It contains the control-flow
 9685: stack entries for all unresolved @code{LEAVE}s.
 9686: 
 9687: Local names are kept until the end of the colon definition, even if
 9688: they are no longer visible in any control-flow path. In a few cases
 9689: this may lead to increased space needs for the locals name area, but
 9690: usually less than reclaiming this space would cost in code size.
 9691: 
 9692: 
 9693: @node ANS Forth locals,  , Gforth locals, Locals
 9694: @subsection ANS Forth locals
 9695: @cindex locals, ANS Forth style
 9696: 
 9697: The ANS Forth locals wordset does not define a syntax for locals, but
 9698: words that make it possible to define various syntaxes. One of the
 9699: possible syntaxes is a subset of the syntax we used in the Gforth locals
 9700: wordset, i.e.:
 9701: 
 9702: @example
 9703: @{ local1 local2 ... -- comment @}
 9704: @end example
 9705: @noindent
 9706: or
 9707: @example
 9708: @{ local1 local2 ... @}
 9709: @end example
 9710: 
 9711: The order of the locals corresponds to the order in a stack comment. The
 9712: restrictions are:
 9713: 
 9714: @itemize @bullet
 9715: @item
 9716: Locals can only be cell-sized values (no type specifiers are allowed).
 9717: @item
 9718: Locals can be defined only outside control structures.
 9719: @item
 9720: Locals can interfere with explicit usage of the return stack. For the
 9721: exact (and long) rules, see the standard. If you don't use return stack
 9722: accessing words in a definition using locals, you will be all right. The
 9723: purpose of this rule is to make locals implementation on the return
 9724: stack easier.
 9725: @item
 9726: The whole definition must be in one line.
 9727: @end itemize
 9728: 
 9729: Locals defined in this way behave like @code{VALUE}s
 9730: (@pxref{Values}). I.e., they are initialized from the stack. Using their
 9731: name produces their value. Their value can be changed using @code{TO}.
 9732: 
 9733: Since this syntax is supported by Gforth directly, you need not do
 9734: anything to use it. If you want to port a program using this syntax to
 9735: another ANS Forth system, use @file{compat/anslocal.fs} to implement the
 9736: syntax on the other system.
 9737: 
 9738: Note that a syntax shown in the standard, section A.13 looks
 9739: similar, but is quite different in having the order of locals
 9740: reversed. Beware!
 9741: 
 9742: The ANS Forth locals wordset itself consists of a word:
 9743: 
 9744: 
 9745: doc-(local)
 9746: 
 9747: 
 9748: The ANS Forth locals extension wordset defines a syntax using @code{locals|}, but it is so
 9749: awful that we strongly recommend not to use it. We have implemented this
 9750: syntax to make porting to Gforth easy, but do not document it here. The
 9751: problem with this syntax is that the locals are defined in an order
 9752: reversed with respect to the standard stack comment notation, making
 9753: programs harder to read, and easier to misread and miswrite. The only
 9754: merit of this syntax is that it is easy to implement using the ANS Forth
 9755: locals wordset.
 9756: 
 9757: 
 9758: @c ----------------------------------------------------------
 9759: @node Structures, Object-oriented Forth, Locals, Words
 9760: @section  Structures
 9761: @cindex structures
 9762: @cindex records
 9763: 
 9764: This section presents the structure package that comes with Gforth. A
 9765: version of the package implemented in ANS Forth is available in
 9766: @file{compat/struct.fs}. This package was inspired by a posting on
 9767: comp.lang.forth in 1989 (unfortunately I don't remember, by whom;
 9768: possibly John Hayes). A version of this section has been published in
 9769: ???. Marcel Hendrix provided helpful comments.
 9770: 
 9771: @menu
 9772: * Why explicit structure support?::  
 9773: * Structure Usage::             
 9774: * Structure Naming Convention::  
 9775: * Structure Implementation::    
 9776: * Structure Glossary::          
 9777: @end menu
 9778: 
 9779: @node Why explicit structure support?, Structure Usage, Structures, Structures
 9780: @subsection Why explicit structure support?
 9781: 
 9782: @cindex address arithmetic for structures
 9783: @cindex structures using address arithmetic
 9784: If we want to use a structure containing several fields, we could simply
 9785: reserve memory for it, and access the fields using address arithmetic
 9786: (@pxref{Address arithmetic}). As an example, consider a structure with
 9787: the following fields
 9788: 
 9789: @table @code
 9790: @item a
 9791: is a float
 9792: @item b
 9793: is a cell
 9794: @item c
 9795: is a float
 9796: @end table
 9797: 
 9798: Given the (float-aligned) base address of the structure we get the
 9799: address of the field
 9800: 
 9801: @table @code
 9802: @item a
 9803: without doing anything further.
 9804: @item b
 9805: with @code{float+}
 9806: @item c
 9807: with @code{float+ cell+ faligned}
 9808: @end table
 9809: 
 9810: It is easy to see that this can become quite tiring. 
 9811: 
 9812: Moreover, it is not very readable, because seeing a
 9813: @code{cell+} tells us neither which kind of structure is
 9814: accessed nor what field is accessed; we have to somehow infer the kind
 9815: of structure, and then look up in the documentation, which field of
 9816: that structure corresponds to that offset.
 9817: 
 9818: Finally, this kind of address arithmetic also causes maintenance
 9819: troubles: If you add or delete a field somewhere in the middle of the
 9820: structure, you have to find and change all computations for the fields
 9821: afterwards.
 9822: 
 9823: So, instead of using @code{cell+} and friends directly, how
 9824: about storing the offsets in constants:
 9825: 
 9826: @example
 9827: 0 constant a-offset
 9828: 0 float+ constant b-offset
 9829: 0 float+ cell+ faligned c-offset
 9830: @end example
 9831: 
 9832: Now we can get the address of field @code{x} with @code{x-offset
 9833: +}. This is much better in all respects. Of course, you still
 9834: have to change all later offset definitions if you add a field. You can
 9835: fix this by declaring the offsets in the following way:
 9836: 
 9837: @example
 9838: 0 constant a-offset
 9839: a-offset float+ constant b-offset
 9840: b-offset cell+ faligned constant c-offset
 9841: @end example
 9842: 
 9843: Since we always use the offsets with @code{+}, we could use a defining
 9844: word @code{cfield} that includes the @code{+} in the action of the
 9845: defined word:
 9846: 
 9847: @example
 9848: : cfield ( n "name" -- )
 9849:     create ,
 9850: does> ( name execution: addr1 -- addr2 )
 9851:     @@ + ;
 9852: 
 9853: 0 cfield a
 9854: 0 a float+ cfield b
 9855: 0 b cell+ faligned cfield c
 9856: @end example
 9857: 
 9858: Instead of @code{x-offset +}, we now simply write @code{x}.
 9859: 
 9860: The structure field words now can be used quite nicely. However,
 9861: their definition is still a bit cumbersome: We have to repeat the
 9862: name, the information about size and alignment is distributed before
 9863: and after the field definitions etc.  The structure package presented
 9864: here addresses these problems.
 9865: 
 9866: @node Structure Usage, Structure Naming Convention, Why explicit structure support?, Structures
 9867: @subsection Structure Usage
 9868: @cindex structure usage
 9869: 
 9870: @cindex @code{field} usage
 9871: @cindex @code{struct} usage
 9872: @cindex @code{end-struct} usage
 9873: You can define a structure for a (data-less) linked list with:
 9874: @example
 9875: struct
 9876:     cell% field list-next
 9877: end-struct list%
 9878: @end example
 9879: 
 9880: With the address of the list node on the stack, you can compute the
 9881: address of the field that contains the address of the next node with
 9882: @code{list-next}. E.g., you can determine the length of a list
 9883: with:
 9884: 
 9885: @example
 9886: : list-length ( list -- n )
 9887: \ "list" is a pointer to the first element of a linked list
 9888: \ "n" is the length of the list
 9889:     0 BEGIN ( list1 n1 )
 9890:         over
 9891:     WHILE ( list1 n1 )
 9892:         1+ swap list-next @@ swap
 9893:     REPEAT
 9894:     nip ;
 9895: @end example
 9896: 
 9897: You can reserve memory for a list node in the dictionary with
 9898: @code{list% %allot}, which leaves the address of the list node on the
 9899: stack. For the equivalent allocation on the heap you can use @code{list%
 9900: %alloc} (or, for an @code{allocate}-like stack effect (i.e., with ior),
 9901: use @code{list% %allocate}). You can get the the size of a list
 9902: node with @code{list% %size} and its alignment with @code{list%
 9903: %alignment}.
 9904: 
 9905: Note that in ANS Forth the body of a @code{create}d word is
 9906: @code{aligned} but not necessarily @code{faligned};
 9907: therefore, if you do a:
 9908: @example
 9909: create @emph{name} foo% %allot
 9910: @end example
 9911: 
 9912: @noindent
 9913: then the memory alloted for @code{foo%} is
 9914: guaranteed to start at the body of @code{@emph{name}} only if
 9915: @code{foo%} contains only character, cell and double fields.
 9916: 
 9917: @cindex structures containing structures
 9918: You can include a structure @code{foo%} as a field of
 9919: another structure, like this:
 9920: @example
 9921: struct
 9922: ...
 9923:     foo% field ...
 9924: ...
 9925: end-struct ...
 9926: @end example
 9927: 
 9928: @cindex structure extension
 9929: @cindex extended records
 9930: Instead of starting with an empty structure, you can extend an
 9931: existing structure. E.g., a plain linked list without data, as defined
 9932: above, is hardly useful; You can extend it to a linked list of integers,
 9933: like this:@footnote{This feature is also known as @emph{extended
 9934: records}. It is the main innovation in the Oberon language; in other
 9935: words, adding this feature to Modula-2 led Wirth to create a new
 9936: language, write a new compiler etc.  Adding this feature to Forth just
 9937: required a few lines of code.}
 9938: 
 9939: @example
 9940: list%
 9941:     cell% field intlist-int
 9942: end-struct intlist%
 9943: @end example
 9944: 
 9945: @code{intlist%} is a structure with two fields:
 9946: @code{list-next} and @code{intlist-int}.
 9947: 
 9948: @cindex structures containing arrays
 9949: You can specify an array type containing @emph{n} elements of
 9950: type @code{foo%} like this:
 9951: 
 9952: @example
 9953: foo% @emph{n} *
 9954: @end example
 9955: 
 9956: You can use this array type in any place where you can use a normal
 9957: type, e.g., when defining a @code{field}, or with
 9958: @code{%allot}.
 9959: 
 9960: @cindex first field optimization
 9961: The first field is at the base address of a structure and the word
 9962: for this field (e.g., @code{list-next}) actually does not change
 9963: the address on the stack. You may be tempted to leave it away in the
 9964: interest of run-time and space efficiency. This is not necessary,
 9965: because the structure package optimizes this case and compiling such
 9966: words does not generate any code. So, in the interest of readability
 9967: and maintainability you should include the word for the field when
 9968: accessing the field.
 9969: 
 9970: @node Structure Naming Convention, Structure Implementation, Structure Usage, Structures
 9971: @subsection Structure Naming Convention
 9972: @cindex structure naming convention
 9973: 
 9974: The field names that come to (my) mind are often quite generic, and,
 9975: if used, would cause frequent name clashes. E.g., many structures
 9976: probably contain a @code{counter} field. The structure names
 9977: that come to (my) mind are often also the logical choice for the names
 9978: of words that create such a structure.
 9979: 
 9980: Therefore, I have adopted the following naming conventions: 
 9981: 
 9982: @itemize @bullet
 9983: @cindex field naming convention
 9984: @item
 9985: The names of fields are of the form
 9986: @code{@emph{struct}-@emph{field}}, where
 9987: @code{@emph{struct}} is the basic name of the structure, and
 9988: @code{@emph{field}} is the basic name of the field. You can
 9989: think of field words as converting the (address of the)
 9990: structure into the (address of the) field.
 9991: 
 9992: @cindex structure naming convention
 9993: @item
 9994: The names of structures are of the form
 9995: @code{@emph{struct}%}, where
 9996: @code{@emph{struct}} is the basic name of the structure.
 9997: @end itemize
 9998: 
 9999: This naming convention does not work that well for fields of extended
10000: structures; e.g., the integer list structure has a field
10001: @code{intlist-int}, but has @code{list-next}, not
10002: @code{intlist-next}.
10003: 
10004: @node Structure Implementation, Structure Glossary, Structure Naming Convention, Structures
10005: @subsection Structure Implementation
10006: @cindex structure implementation
10007: @cindex implementation of structures
10008: 
10009: The central idea in the implementation is to pass the data about the
10010: structure being built on the stack, not in some global
10011: variable. Everything else falls into place naturally once this design
10012: decision is made.
10013: 
10014: The type description on the stack is of the form @emph{align
10015: size}. Keeping the size on the top-of-stack makes dealing with arrays
10016: very simple.
10017: 
10018: @code{field} is a defining word that uses @code{Create}
10019: and @code{DOES>}. The body of the field contains the offset
10020: of the field, and the normal @code{DOES>} action is simply:
10021: 
10022: @example
10023: @@ +
10024: @end example
10025: 
10026: @noindent
10027: i.e., add the offset to the address, giving the stack effect
10028: @i{addr1 -- addr2} for a field.
10029: 
10030: @cindex first field optimization, implementation
10031: This simple structure is slightly complicated by the optimization
10032: for fields with offset 0, which requires a different
10033: @code{DOES>}-part (because we cannot rely on there being
10034: something on the stack if such a field is invoked during
10035: compilation). Therefore, we put the different @code{DOES>}-parts
10036: in separate words, and decide which one to invoke based on the
10037: offset. For a zero offset, the field is basically a noop; it is
10038: immediate, and therefore no code is generated when it is compiled.
10039: 
10040: @node Structure Glossary,  , Structure Implementation, Structures
10041: @subsection Structure Glossary
10042: @cindex structure glossary
10043: 
10044: 
10045: doc-%align
10046: doc-%alignment
10047: doc-%alloc
10048: doc-%allocate
10049: doc-%allot
10050: doc-cell%
10051: doc-char%
10052: doc-dfloat%
10053: doc-double%
10054: doc-end-struct
10055: doc-field
10056: doc-float%
10057: doc-naligned
10058: doc-sfloat%
10059: doc-%size
10060: doc-struct
10061: 
10062: 
10063: @c -------------------------------------------------------------
10064: @node Object-oriented Forth, Passing Commands to the OS, Structures, Words
10065: @section Object-oriented Forth
10066: 
10067: Gforth comes with three packages for object-oriented programming:
10068: @file{objects.fs}, @file{oof.fs}, and @file{mini-oof.fs}; none of them
10069: is preloaded, so you have to @code{include} them before use. The most
10070: important differences between these packages (and others) are discussed
10071: in @ref{Comparison with other object models}. All packages are written
10072: in ANS Forth and can be used with any other ANS Forth.
10073: 
10074: @menu
10075: * Why object-oriented programming?::  
10076: * Object-Oriented Terminology::  
10077: * Objects::                     
10078: * OOF::                         
10079: * Mini-OOF::                    
10080: * Comparison with other object models::  
10081: @end menu
10082: 
10083: @c ----------------------------------------------------------------
10084: @node Why object-oriented programming?, Object-Oriented Terminology, Object-oriented Forth, Object-oriented Forth
10085: @subsection Why object-oriented programming?
10086: @cindex object-oriented programming motivation
10087: @cindex motivation for object-oriented programming
10088: 
10089: Often we have to deal with several data structures (@emph{objects}),
10090: that have to be treated similarly in some respects, but differently in
10091: others. Graphical objects are the textbook example: circles, triangles,
10092: dinosaurs, icons, and others, and we may want to add more during program
10093: development. We want to apply some operations to any graphical object,
10094: e.g., @code{draw} for displaying it on the screen. However, @code{draw}
10095: has to do something different for every kind of object.
10096: @comment TODO add some other operations eg perimeter, area
10097: @comment and tie in to concrete examples later..
10098: 
10099: We could implement @code{draw} as a big @code{CASE}
10100: control structure that executes the appropriate code depending on the
10101: kind of object to be drawn. This would be not be very elegant, and,
10102: moreover, we would have to change @code{draw} every time we add
10103: a new kind of graphical object (say, a spaceship).
10104: 
10105: What we would rather do is: When defining spaceships, we would tell
10106: the system: ``Here's how you @code{draw} a spaceship; you figure
10107: out the rest''.
10108: 
10109: This is the problem that all systems solve that (rightfully) call
10110: themselves object-oriented; the object-oriented packages presented here
10111: solve this problem (and not much else).
10112: @comment TODO ?list properties of oo systems.. oo vs o-based?
10113: 
10114: @c ------------------------------------------------------------------------
10115: @node Object-Oriented Terminology, Objects, Why object-oriented programming?, Object-oriented Forth
10116: @subsection Object-Oriented Terminology
10117: @cindex object-oriented terminology
10118: @cindex terminology for object-oriented programming
10119: 
10120: This section is mainly for reference, so you don't have to understand
10121: all of it right away.  The terminology is mainly Smalltalk-inspired.  In
10122: short:
10123: 
10124: @table @emph
10125: @cindex class
10126: @item class
10127: a data structure definition with some extras.
10128: 
10129: @cindex object
10130: @item object
10131: an instance of the data structure described by the class definition.
10132: 
10133: @cindex instance variables
10134: @item instance variables
10135: fields of the data structure.
10136: 
10137: @cindex selector
10138: @cindex method selector
10139: @cindex virtual function
10140: @item selector
10141: (or @emph{method selector}) a word (e.g.,
10142: @code{draw}) that performs an operation on a variety of data
10143: structures (classes). A selector describes @emph{what} operation to
10144: perform. In C++ terminology: a (pure) virtual function.
10145: 
10146: @cindex method
10147: @item method
10148: the concrete definition that performs the operation
10149: described by the selector for a specific class. A method specifies
10150: @emph{how} the operation is performed for a specific class.
10151: 
10152: @cindex selector invocation
10153: @cindex message send
10154: @cindex invoking a selector
10155: @item selector invocation
10156: a call of a selector. One argument of the call (the TOS (top-of-stack))
10157: is used for determining which method is used. In Smalltalk terminology:
10158: a message (consisting of the selector and the other arguments) is sent
10159: to the object.
10160: 
10161: @cindex receiving object
10162: @item receiving object
10163: the object used for determining the method executed by a selector
10164: invocation. In the @file{objects.fs} model, it is the object that is on
10165: the TOS when the selector is invoked. (@emph{Receiving} comes from
10166: the Smalltalk @emph{message} terminology.)
10167: 
10168: @cindex child class
10169: @cindex parent class
10170: @cindex inheritance
10171: @item child class
10172: a class that has (@emph{inherits}) all properties (instance variables,
10173: selectors, methods) from a @emph{parent class}. In Smalltalk
10174: terminology: The subclass inherits from the superclass. In C++
10175: terminology: The derived class inherits from the base class.
10176: 
10177: @end table
10178: 
10179: @c If you wonder about the message sending terminology, it comes from
10180: @c a time when each object had it's own task and objects communicated via
10181: @c message passing; eventually the Smalltalk developers realized that
10182: @c they can do most things through simple (indirect) calls. They kept the
10183: @c terminology.
10184: 
10185: @c --------------------------------------------------------------
10186: @node Objects, OOF, Object-Oriented Terminology, Object-oriented Forth
10187: @subsection The @file{objects.fs} model
10188: @cindex objects
10189: @cindex object-oriented programming
10190: 
10191: @cindex @file{objects.fs}
10192: @cindex @file{oof.fs}
10193: 
10194: This section describes the @file{objects.fs} package. This material also
10195: has been published in M. Anton Ertl,
10196: @cite{@uref{http://www.complang.tuwien.ac.at/forth/objects/objects.html,
10197: Yet Another Forth Objects Package}}, Forth Dimensions 19(2), pages
10198: 37--43.
10199: @c McKewan's and Zsoter's packages
10200: 
10201: This section assumes that you have read @ref{Structures}.
10202: 
10203: The techniques on which this model is based have been used to implement
10204: the parser generator, Gray, and have also been used in Gforth for
10205: implementing the various flavours of word lists (hashed or not,
10206: case-sensitive or not, special-purpose word lists for locals etc.).
10207: 
10208: 
10209: @menu
10210: * Properties of the Objects model::  
10211: * Basic Objects Usage::         
10212: * The Objects base class::      
10213: * Creating objects::            
10214: * Object-Oriented Programming Style::  
10215: * Class Binding::               
10216: * Method conveniences::         
10217: * Classes and Scoping::         
10218: * Dividing classes::            
10219: * Object Interfaces::           
10220: * Objects Implementation::      
10221: * Objects Glossary::            
10222: @end menu
10223: 
10224: Marcel Hendrix provided helpful comments on this section. Andras Zsoter
10225: and Bernd Paysan helped me with the related works section.
10226: 
10227: @node Properties of the Objects model, Basic Objects Usage, Objects, Objects
10228: @subsubsection Properties of the @file{objects.fs} model
10229: @cindex @file{objects.fs} properties
10230: 
10231: @itemize @bullet
10232: @item
10233: It is straightforward to pass objects on the stack. Passing
10234: selectors on the stack is a little less convenient, but possible.
10235: 
10236: @item
10237: Objects are just data structures in memory, and are referenced by their
10238: address. You can create words for objects with normal defining words
10239: like @code{constant}. Likewise, there is no difference between instance
10240: variables that contain objects and those that contain other data.
10241: 
10242: @item
10243: Late binding is efficient and easy to use.
10244: 
10245: @item
10246: It avoids parsing, and thus avoids problems with state-smartness
10247: and reduced extensibility; for convenience there are a few parsing
10248: words, but they have non-parsing counterparts. There are also a few
10249: defining words that parse. This is hard to avoid, because all standard
10250: defining words parse (except @code{:noname}); however, such
10251: words are not as bad as many other parsing words, because they are not
10252: state-smart.
10253: 
10254: @item
10255: It does not try to incorporate everything. It does a few things and does
10256: them well (IMO). In particular, this model was not designed to support
10257: information hiding (although it has features that may help); you can use
10258: a separate package for achieving this.
10259: 
10260: @item
10261: It is layered; you don't have to learn and use all features to use this
10262: model. Only a few features are necessary (@pxref{Basic Objects Usage},
10263: @pxref{The Objects base class}, @pxref{Creating objects}.), the others
10264: are optional and independent of each other.
10265: 
10266: @item
10267: An implementation in ANS Forth is available.
10268: 
10269: @end itemize
10270: 
10271: 
10272: @node Basic Objects Usage, The Objects base class, Properties of the Objects model, Objects
10273: @subsubsection Basic @file{objects.fs} Usage
10274: @cindex basic objects usage
10275: @cindex objects, basic usage
10276: 
10277: You can define a class for graphical objects like this:
10278: 
10279: @cindex @code{class} usage
10280: @cindex @code{end-class} usage
10281: @cindex @code{selector} usage
10282: @example
10283: object class \ "object" is the parent class
10284:   selector draw ( x y graphical -- )
10285: end-class graphical
10286: @end example
10287: 
10288: This code defines a class @code{graphical} with an
10289: operation @code{draw}.  We can perform the operation
10290: @code{draw} on any @code{graphical} object, e.g.:
10291: 
10292: @example
10293: 100 100 t-rex draw
10294: @end example
10295: 
10296: @noindent
10297: where @code{t-rex} is a word (say, a constant) that produces a
10298: graphical object.
10299: 
10300: @comment TODO add a 2nd operation eg perimeter.. and use for
10301: @comment a concrete example
10302: 
10303: @cindex abstract class
10304: How do we create a graphical object? With the present definitions,
10305: we cannot create a useful graphical object. The class
10306: @code{graphical} describes graphical objects in general, but not
10307: any concrete graphical object type (C++ users would call it an
10308: @emph{abstract class}); e.g., there is no method for the selector
10309: @code{draw} in the class @code{graphical}.
10310: 
10311: For concrete graphical objects, we define child classes of the
10312: class @code{graphical}, e.g.:
10313: 
10314: @cindex @code{overrides} usage
10315: @cindex @code{field} usage in class definition
10316: @example
10317: graphical class \ "graphical" is the parent class
10318:   cell% field circle-radius
10319: 
10320: :noname ( x y circle -- )
10321:   circle-radius @@ draw-circle ;
10322: overrides draw
10323: 
10324: :noname ( n-radius circle -- )
10325:   circle-radius ! ;
10326: overrides construct
10327: 
10328: end-class circle
10329: @end example
10330: 
10331: Here we define a class @code{circle} as a child of @code{graphical},
10332: with field @code{circle-radius} (which behaves just like a field
10333: (@pxref{Structures}); it defines (using @code{overrides}) new methods
10334: for the selectors @code{draw} and @code{construct} (@code{construct} is
10335: defined in @code{object}, the parent class of @code{graphical}).
10336: 
10337: Now we can create a circle on the heap (i.e.,
10338: @code{allocate}d memory) with:
10339: 
10340: @cindex @code{heap-new} usage
10341: @example
10342: 50 circle heap-new constant my-circle
10343: @end example
10344: 
10345: @noindent
10346: @code{heap-new} invokes @code{construct}, thus
10347: initializing the field @code{circle-radius} with 50. We can draw
10348: this new circle at (100,100) with:
10349: 
10350: @example
10351: 100 100 my-circle draw
10352: @end example
10353: 
10354: @cindex selector invocation, restrictions
10355: @cindex class definition, restrictions
10356: Note: You can only invoke a selector if the object on the TOS
10357: (the receiving object) belongs to the class where the selector was
10358: defined or one of its descendents; e.g., you can invoke
10359: @code{draw} only for objects belonging to @code{graphical}
10360: or its descendents (e.g., @code{circle}).  Immediately before
10361: @code{end-class}, the search order has to be the same as
10362: immediately after @code{class}.
10363: 
10364: @node The Objects base class, Creating objects, Basic Objects Usage, Objects
10365: @subsubsection The @file{object.fs} base class
10366: @cindex @code{object} class
10367: 
10368: When you define a class, you have to specify a parent class.  So how do
10369: you start defining classes? There is one class available from the start:
10370: @code{object}. It is ancestor for all classes and so is the
10371: only class that has no parent. It has two selectors: @code{construct}
10372: and @code{print}.
10373: 
10374: @node Creating objects, Object-Oriented Programming Style, The Objects base class, Objects
10375: @subsubsection Creating objects
10376: @cindex creating objects
10377: @cindex object creation
10378: @cindex object allocation options
10379: 
10380: @cindex @code{heap-new} discussion
10381: @cindex @code{dict-new} discussion
10382: @cindex @code{construct} discussion
10383: You can create and initialize an object of a class on the heap with
10384: @code{heap-new} ( ... class -- object ) and in the dictionary
10385: (allocation with @code{allot}) with @code{dict-new} (
10386: ... class -- object ). Both words invoke @code{construct}, which
10387: consumes the stack items indicated by "..." above.
10388: 
10389: @cindex @code{init-object} discussion
10390: @cindex @code{class-inst-size} discussion
10391: If you want to allocate memory for an object yourself, you can get its
10392: alignment and size with @code{class-inst-size 2@@} ( class --
10393: align size ). Once you have memory for an object, you can initialize
10394: it with @code{init-object} ( ... class object -- );
10395: @code{construct} does only a part of the necessary work.
10396: 
10397: @node Object-Oriented Programming Style, Class Binding, Creating objects, Objects
10398: @subsubsection Object-Oriented Programming Style
10399: @cindex object-oriented programming style
10400: @cindex programming style, object-oriented
10401: 
10402: This section is not exhaustive.
10403: 
10404: @cindex stack effects of selectors
10405: @cindex selectors and stack effects
10406: In general, it is a good idea to ensure that all methods for the
10407: same selector have the same stack effect: when you invoke a selector,
10408: you often have no idea which method will be invoked, so, unless all
10409: methods have the same stack effect, you will not know the stack effect
10410: of the selector invocation.
10411: 
10412: One exception to this rule is methods for the selector
10413: @code{construct}. We know which method is invoked, because we
10414: specify the class to be constructed at the same place. Actually, I
10415: defined @code{construct} as a selector only to give the users a
10416: convenient way to specify initialization. The way it is used, a
10417: mechanism different from selector invocation would be more natural
10418: (but probably would take more code and more space to explain).
10419: 
10420: @node Class Binding, Method conveniences, Object-Oriented Programming Style, Objects
10421: @subsubsection Class Binding
10422: @cindex class binding
10423: @cindex early binding
10424: 
10425: @cindex late binding
10426: Normal selector invocations determine the method at run-time depending
10427: on the class of the receiving object. This run-time selection is called
10428: @i{late binding}.
10429: 
10430: Sometimes it's preferable to invoke a different method. For example,
10431: you might want to use the simple method for @code{print}ing
10432: @code{object}s instead of the possibly long-winded @code{print} method
10433: of the receiver class. You can achieve this by replacing the invocation
10434: of @code{print} with:
10435: 
10436: @cindex @code{[bind]} usage
10437: @example
10438: [bind] object print
10439: @end example
10440: 
10441: @noindent
10442: in compiled code or:
10443: 
10444: @cindex @code{bind} usage
10445: @example
10446: bind object print
10447: @end example
10448: 
10449: @cindex class binding, alternative to
10450: @noindent
10451: in interpreted code. Alternatively, you can define the method with a
10452: name (e.g., @code{print-object}), and then invoke it through the
10453: name. Class binding is just a (often more convenient) way to achieve
10454: the same effect; it avoids name clutter and allows you to invoke
10455: methods directly without naming them first.
10456: 
10457: @cindex superclass binding
10458: @cindex parent class binding
10459: A frequent use of class binding is this: When we define a method
10460: for a selector, we often want the method to do what the selector does
10461: in the parent class, and a little more. There is a special word for
10462: this purpose: @code{[parent]}; @code{[parent]
10463: @emph{selector}} is equivalent to @code{[bind] @emph{parent
10464: selector}}, where @code{@emph{parent}} is the parent
10465: class of the current class. E.g., a method definition might look like:
10466: 
10467: @cindex @code{[parent]} usage
10468: @example
10469: :noname
10470:   dup [parent] foo \ do parent's foo on the receiving object
10471:   ... \ do some more
10472: ; overrides foo
10473: @end example
10474: 
10475: @cindex class binding as optimization
10476: In @cite{Object-oriented programming in ANS Forth} (Forth Dimensions,
10477: March 1997), Andrew McKewan presents class binding as an optimization
10478: technique. I recommend not using it for this purpose unless you are in
10479: an emergency. Late binding is pretty fast with this model anyway, so the
10480: benefit of using class binding is small; the cost of using class binding
10481: where it is not appropriate is reduced maintainability.
10482: 
10483: While we are at programming style questions: You should bind
10484: selectors only to ancestor classes of the receiving object. E.g., say,
10485: you know that the receiving object is of class @code{foo} or its
10486: descendents; then you should bind only to @code{foo} and its
10487: ancestors.
10488: 
10489: @node Method conveniences, Classes and Scoping, Class Binding, Objects
10490: @subsubsection Method conveniences
10491: @cindex method conveniences
10492: 
10493: In a method you usually access the receiving object pretty often.  If
10494: you define the method as a plain colon definition (e.g., with
10495: @code{:noname}), you may have to do a lot of stack
10496: gymnastics. To avoid this, you can define the method with @code{m:
10497: ... ;m}. E.g., you could define the method for
10498: @code{draw}ing a @code{circle} with
10499: 
10500: @cindex @code{this} usage
10501: @cindex @code{m:} usage
10502: @cindex @code{;m} usage
10503: @example
10504: m: ( x y circle -- )
10505:   ( x y ) this circle-radius @@ draw-circle ;m
10506: @end example
10507: 
10508: @cindex @code{exit} in @code{m: ... ;m}
10509: @cindex @code{exitm} discussion
10510: @cindex @code{catch} in @code{m: ... ;m}
10511: When this method is executed, the receiver object is removed from the
10512: stack; you can access it with @code{this} (admittedly, in this
10513: example the use of @code{m: ... ;m} offers no advantage). Note
10514: that I specify the stack effect for the whole method (i.e. including
10515: the receiver object), not just for the code between @code{m:}
10516: and @code{;m}. You cannot use @code{exit} in
10517: @code{m:...;m}; instead, use
10518: @code{exitm}.@footnote{Moreover, for any word that calls
10519: @code{catch} and was defined before loading
10520: @code{objects.fs}, you have to redefine it like I redefined
10521: @code{catch}: @code{: catch this >r catch r> to-this ;}}
10522: 
10523: @cindex @code{inst-var} usage
10524: You will frequently use sequences of the form @code{this
10525: @emph{field}} (in the example above: @code{this
10526: circle-radius}). If you use the field only in this way, you can
10527: define it with @code{inst-var} and eliminate the
10528: @code{this} before the field name. E.g., the @code{circle}
10529: class above could also be defined with:
10530: 
10531: @example
10532: graphical class
10533:   cell% inst-var radius
10534: 
10535: m: ( x y circle -- )
10536:   radius @@ draw-circle ;m
10537: overrides draw
10538: 
10539: m: ( n-radius circle -- )
10540:   radius ! ;m
10541: overrides construct
10542: 
10543: end-class circle
10544: @end example
10545: 
10546: @code{radius} can only be used in @code{circle} and its
10547: descendent classes and inside @code{m:...;m}.
10548: 
10549: @cindex @code{inst-value} usage
10550: You can also define fields with @code{inst-value}, which is
10551: to @code{inst-var} what @code{value} is to
10552: @code{variable}.  You can change the value of such a field with
10553: @code{[to-inst]}.  E.g., we could also define the class
10554: @code{circle} like this:
10555: 
10556: @example
10557: graphical class
10558:   inst-value radius
10559: 
10560: m: ( x y circle -- )
10561:   radius draw-circle ;m
10562: overrides draw
10563: 
10564: m: ( n-radius circle -- )
10565:   [to-inst] radius ;m
10566: overrides construct
10567: 
10568: end-class circle
10569: @end example
10570: 
10571: Finally, you can define named methods with @code{:m}.  One use of this
10572: feature is the definition of words that occur only in one class and are
10573: not intended to be overridden, but which still need method context
10574: (e.g., for accessing @code{inst-var}s).  Another use is for methods that
10575: would be bound frequently, if defined anonymously.
10576: 
10577: 
10578: @node Classes and Scoping, Dividing classes, Method conveniences, Objects
10579: @subsubsection Classes and Scoping
10580: @cindex classes and scoping
10581: @cindex scoping and classes
10582: 
10583: Inheritance is frequent, unlike structure extension. This exacerbates
10584: the problem with the field name convention (@pxref{Structure Naming
10585: Convention}): One always has to remember in which class the field was
10586: originally defined; changing a part of the class structure would require
10587: changes for renaming in otherwise unaffected code.
10588: 
10589: @cindex @code{inst-var} visibility
10590: @cindex @code{inst-value} visibility
10591: To solve this problem, I added a scoping mechanism (which was not in my
10592: original charter): A field defined with @code{inst-var} (or
10593: @code{inst-value}) is visible only in the class where it is defined and in
10594: the descendent classes of this class.  Using such fields only makes
10595: sense in @code{m:}-defined methods in these classes anyway.
10596: 
10597: This scoping mechanism allows us to use the unadorned field name,
10598: because name clashes with unrelated words become much less likely.
10599: 
10600: @cindex @code{protected} discussion
10601: @cindex @code{private} discussion
10602: Once we have this mechanism, we can also use it for controlling the
10603: visibility of other words: All words defined after
10604: @code{protected} are visible only in the current class and its
10605: descendents. @code{public} restores the compilation
10606: (i.e. @code{current}) word list that was in effect before. If you
10607: have several @code{protected}s without an intervening
10608: @code{public} or @code{set-current}, @code{public}
10609: will restore the compilation word list in effect before the first of
10610: these @code{protected}s.
10611: 
10612: @node Dividing classes, Object Interfaces, Classes and Scoping, Objects
10613: @subsubsection Dividing classes
10614: @cindex Dividing classes
10615: @cindex @code{methods}...@code{end-methods}
10616: 
10617: You may want to do the definition of methods separate from the
10618: definition of the class, its selectors, fields, and instance variables,
10619: i.e., separate the implementation from the definition.  You can do this
10620: in the following way:
10621: 
10622: @example
10623: graphical class
10624:   inst-value radius
10625: end-class circle
10626: 
10627: ... \ do some other stuff
10628: 
10629: circle methods \ now we are ready
10630: 
10631: m: ( x y circle -- )
10632:   radius draw-circle ;m
10633: overrides draw
10634: 
10635: m: ( n-radius circle -- )
10636:   [to-inst] radius ;m
10637: overrides construct
10638: 
10639: end-methods
10640: @end example
10641: 
10642: You can use several @code{methods}...@code{end-methods} sections.  The
10643: only things you can do to the class in these sections are: defining
10644: methods, and overriding the class's selectors.  You must not define new
10645: selectors or fields.
10646: 
10647: Note that you often have to override a selector before using it.  In
10648: particular, you usually have to override @code{construct} with a new
10649: method before you can invoke @code{heap-new} and friends.  E.g., you
10650: must not create a circle before the @code{overrides construct} sequence
10651: in the example above.
10652: 
10653: @node Object Interfaces, Objects Implementation, Dividing classes, Objects
10654: @subsubsection Object Interfaces
10655: @cindex object interfaces
10656: @cindex interfaces for objects
10657: 
10658: In this model you can only call selectors defined in the class of the
10659: receiving objects or in one of its ancestors. If you call a selector
10660: with a receiving object that is not in one of these classes, the
10661: result is undefined; if you are lucky, the program crashes
10662: immediately.
10663: 
10664: @cindex selectors common to hardly-related classes
10665: Now consider the case when you want to have a selector (or several)
10666: available in two classes: You would have to add the selector to a
10667: common ancestor class, in the worst case to @code{object}. You
10668: may not want to do this, e.g., because someone else is responsible for
10669: this ancestor class.
10670: 
10671: The solution for this problem is interfaces. An interface is a
10672: collection of selectors. If a class implements an interface, the
10673: selectors become available to the class and its descendents. A class
10674: can implement an unlimited number of interfaces. For the problem
10675: discussed above, we would define an interface for the selector(s), and
10676: both classes would implement the interface.
10677: 
10678: As an example, consider an interface @code{storage} for
10679: writing objects to disk and getting them back, and a class
10680: @code{foo} that implements it. The code would look like this:
10681: 
10682: @cindex @code{interface} usage
10683: @cindex @code{end-interface} usage
10684: @cindex @code{implementation} usage
10685: @example
10686: interface
10687:   selector write ( file object -- )
10688:   selector read1 ( file object -- )
10689: end-interface storage
10690: 
10691: bar class
10692:   storage implementation
10693: 
10694: ... overrides write
10695: ... overrides read1
10696: ...
10697: end-class foo
10698: @end example
10699: 
10700: @noindent
10701: (I would add a word @code{read} @i{( file -- object )} that uses
10702: @code{read1} internally, but that's beyond the point illustrated
10703: here.)
10704: 
10705: Note that you cannot use @code{protected} in an interface; and
10706: of course you cannot define fields.
10707: 
10708: In the Neon model, all selectors are available for all classes;
10709: therefore it does not need interfaces. The price you pay in this model
10710: is slower late binding, and therefore, added complexity to avoid late
10711: binding.
10712: 
10713: @node Objects Implementation, Objects Glossary, Object Interfaces, Objects
10714: @subsubsection @file{objects.fs} Implementation
10715: @cindex @file{objects.fs} implementation
10716: 
10717: @cindex @code{object-map} discussion
10718: An object is a piece of memory, like one of the data structures
10719: described with @code{struct...end-struct}. It has a field
10720: @code{object-map} that points to the method map for the object's
10721: class.
10722: 
10723: @cindex method map
10724: @cindex virtual function table
10725: The @emph{method map}@footnote{This is Self terminology; in C++
10726: terminology: virtual function table.} is an array that contains the
10727: execution tokens (@i{xt}s) of the methods for the object's class. Each
10728: selector contains an offset into a method map.
10729: 
10730: @cindex @code{selector} implementation, class
10731: @code{selector} is a defining word that uses
10732: @code{CREATE} and @code{DOES>}. The body of the
10733: selector contains the offset; the @code{DOES>} action for a
10734: class selector is, basically:
10735: 
10736: @example
10737: ( object addr ) @@ over object-map @@ + @@ execute
10738: @end example
10739: 
10740: Since @code{object-map} is the first field of the object, it
10741: does not generate any code. As you can see, calling a selector has a
10742: small, constant cost.
10743: 
10744: @cindex @code{current-interface} discussion
10745: @cindex class implementation and representation
10746: A class is basically a @code{struct} combined with a method
10747: map. During the class definition the alignment and size of the class
10748: are passed on the stack, just as with @code{struct}s, so
10749: @code{field} can also be used for defining class
10750: fields. However, passing more items on the stack would be
10751: inconvenient, so @code{class} builds a data structure in memory,
10752: which is accessed through the variable
10753: @code{current-interface}. After its definition is complete, the
10754: class is represented on the stack by a pointer (e.g., as parameter for
10755: a child class definition).
10756: 
10757: A new class starts off with the alignment and size of its parent,
10758: and a copy of the parent's method map. Defining new fields extends the
10759: size and alignment; likewise, defining new selectors extends the
10760: method map. @code{overrides} just stores a new @i{xt} in the method
10761: map at the offset given by the selector.
10762: 
10763: @cindex class binding, implementation
10764: Class binding just gets the @i{xt} at the offset given by the selector
10765: from the class's method map and @code{compile,}s (in the case of
10766: @code{[bind]}) it.
10767: 
10768: @cindex @code{this} implementation
10769: @cindex @code{catch} and @code{this}
10770: @cindex @code{this} and @code{catch}
10771: I implemented @code{this} as a @code{value}. At the
10772: start of an @code{m:...;m} method the old @code{this} is
10773: stored to the return stack and restored at the end; and the object on
10774: the TOS is stored @code{TO this}. This technique has one
10775: disadvantage: If the user does not leave the method via
10776: @code{;m}, but via @code{throw} or @code{exit},
10777: @code{this} is not restored (and @code{exit} may
10778: crash). To deal with the @code{throw} problem, I have redefined
10779: @code{catch} to save and restore @code{this}; the same
10780: should be done with any word that can catch an exception. As for
10781: @code{exit}, I simply forbid it (as a replacement, there is
10782: @code{exitm}).
10783: 
10784: @cindex @code{inst-var} implementation
10785: @code{inst-var} is just the same as @code{field}, with
10786: a different @code{DOES>} action:
10787: @example
10788: @@ this +
10789: @end example
10790: Similar for @code{inst-value}.
10791: 
10792: @cindex class scoping implementation
10793: Each class also has a word list that contains the words defined with
10794: @code{inst-var} and @code{inst-value}, and its protected
10795: words. It also has a pointer to its parent. @code{class} pushes
10796: the word lists of the class and all its ancestors onto the search order stack,
10797: and @code{end-class} drops them.
10798: 
10799: @cindex interface implementation
10800: An interface is like a class without fields, parent and protected
10801: words; i.e., it just has a method map. If a class implements an
10802: interface, its method map contains a pointer to the method map of the
10803: interface. The positive offsets in the map are reserved for class
10804: methods, therefore interface map pointers have negative
10805: offsets. Interfaces have offsets that are unique throughout the
10806: system, unlike class selectors, whose offsets are only unique for the
10807: classes where the selector is available (invokable).
10808: 
10809: This structure means that interface selectors have to perform one
10810: indirection more than class selectors to find their method. Their body
10811: contains the interface map pointer offset in the class method map, and
10812: the method offset in the interface method map. The
10813: @code{does>} action for an interface selector is, basically:
10814: 
10815: @example
10816: ( object selector-body )
10817: 2dup selector-interface @@ ( object selector-body object interface-offset )
10818: swap object-map @@ + @@ ( object selector-body map )
10819: swap selector-offset @@ + @@ execute
10820: @end example
10821: 
10822: where @code{object-map} and @code{selector-offset} are
10823: first fields and generate no code.
10824: 
10825: As a concrete example, consider the following code:
10826: 
10827: @example
10828: interface
10829:   selector if1sel1
10830:   selector if1sel2
10831: end-interface if1
10832: 
10833: object class
10834:   if1 implementation
10835:   selector cl1sel1
10836:   cell% inst-var cl1iv1
10837: 
10838: ' m1 overrides construct
10839: ' m2 overrides if1sel1
10840: ' m3 overrides if1sel2
10841: ' m4 overrides cl1sel2
10842: end-class cl1
10843: 
10844: create obj1 object dict-new drop
10845: create obj2 cl1    dict-new drop
10846: @end example
10847: 
10848: The data structure created by this code (including the data structure
10849: for @code{object}) is shown in the <a
10850: href="objects-implementation.eps">figure</a>, assuming a cell size of 4.
10851: @comment TODO add this diagram..
10852: 
10853: @node Objects Glossary,  , Objects Implementation, Objects
10854: @subsubsection @file{objects.fs} Glossary
10855: @cindex @file{objects.fs} Glossary
10856: 
10857: 
10858: doc---objects-bind
10859: doc---objects-<bind>
10860: doc---objects-bind'
10861: doc---objects-[bind]
10862: doc---objects-class
10863: doc---objects-class->map
10864: doc---objects-class-inst-size
10865: doc---objects-class-override!
10866: doc---objects-construct
10867: doc---objects-current'
10868: doc---objects-[current]
10869: doc---objects-current-interface
10870: doc---objects-dict-new
10871: doc---objects-drop-order
10872: doc---objects-end-class
10873: doc---objects-end-class-noname
10874: doc---objects-end-interface
10875: doc---objects-end-interface-noname
10876: doc---objects-end-methods
10877: doc---objects-exitm
10878: doc---objects-heap-new
10879: doc---objects-implementation
10880: doc---objects-init-object
10881: doc---objects-inst-value
10882: doc---objects-inst-var
10883: doc---objects-interface
10884: doc---objects-m:
10885: doc---objects-:m
10886: doc---objects-;m
10887: doc---objects-method
10888: doc---objects-methods
10889: doc---objects-object
10890: doc---objects-overrides
10891: doc---objects-[parent]
10892: doc---objects-print
10893: doc---objects-protected
10894: doc---objects-public
10895: doc---objects-push-order
10896: doc---objects-selector
10897: doc---objects-this
10898: doc---objects-<to-inst>
10899: doc---objects-[to-inst]
10900: doc---objects-to-this
10901: doc---objects-xt-new
10902: 
10903: 
10904: @c -------------------------------------------------------------
10905: @node OOF, Mini-OOF, Objects, Object-oriented Forth
10906: @subsection The @file{oof.fs} model
10907: @cindex oof
10908: @cindex object-oriented programming
10909: 
10910: @cindex @file{objects.fs}
10911: @cindex @file{oof.fs}
10912: 
10913: This section describes the @file{oof.fs} package.
10914: 
10915: The package described in this section has been used in bigFORTH since 1991, and
10916: used for two large applications: a chromatographic system used to
10917: create new medicaments, and a graphic user interface library (MINOS).
10918: 
10919: You can find a description (in German) of @file{oof.fs} in @cite{Object
10920: oriented bigFORTH} by Bernd Paysan, published in @cite{Vierte Dimension}
10921: 10(2), 1994.
10922: 
10923: @menu
10924: * Properties of the OOF model::  
10925: * Basic OOF Usage::             
10926: * The OOF base class::          
10927: * Class Declaration::           
10928: * Class Implementation::        
10929: @end menu
10930: 
10931: @node Properties of the OOF model, Basic OOF Usage, OOF, OOF
10932: @subsubsection Properties of the @file{oof.fs} model
10933: @cindex @file{oof.fs} properties
10934: 
10935: @itemize @bullet
10936: @item
10937: This model combines object oriented programming with information
10938: hiding. It helps you writing large application, where scoping is
10939: necessary, because it provides class-oriented scoping.
10940: 
10941: @item
10942: Named objects, object pointers, and object arrays can be created,
10943: selector invocation uses the ``object selector'' syntax. Selector invocation
10944: to objects and/or selectors on the stack is a bit less convenient, but
10945: possible.
10946: 
10947: @item
10948: Selector invocation and instance variable usage of the active object is
10949: straightforward, since both make use of the active object.
10950: 
10951: @item
10952: Late binding is efficient and easy to use.
10953: 
10954: @item
10955: State-smart objects parse selectors. However, extensibility is provided
10956: using a (parsing) selector @code{postpone} and a selector @code{'}.
10957: 
10958: @item
10959: An implementation in ANS Forth is available.
10960: 
10961: @end itemize
10962: 
10963: 
10964: @node Basic OOF Usage, The OOF base class, Properties of the OOF model, OOF
10965: @subsubsection Basic @file{oof.fs} Usage
10966: @cindex @file{oof.fs} usage
10967: 
10968: This section uses the same example as for @code{objects} (@pxref{Basic Objects Usage}).
10969: 
10970: You can define a class for graphical objects like this:
10971: 
10972: @cindex @code{class} usage
10973: @cindex @code{class;} usage
10974: @cindex @code{method} usage
10975: @example
10976: object class graphical \ "object" is the parent class
10977:   method draw ( x y graphical -- )
10978: class;
10979: @end example
10980: 
10981: This code defines a class @code{graphical} with an
10982: operation @code{draw}.  We can perform the operation
10983: @code{draw} on any @code{graphical} object, e.g.:
10984: 
10985: @example
10986: 100 100 t-rex draw
10987: @end example
10988: 
10989: @noindent
10990: where @code{t-rex} is an object or object pointer, created with e.g.
10991: @code{graphical : t-rex}.
10992: 
10993: @cindex abstract class
10994: How do we create a graphical object? With the present definitions,
10995: we cannot create a useful graphical object. The class
10996: @code{graphical} describes graphical objects in general, but not
10997: any concrete graphical object type (C++ users would call it an
10998: @emph{abstract class}); e.g., there is no method for the selector
10999: @code{draw} in the class @code{graphical}.
11000: 
11001: For concrete graphical objects, we define child classes of the
11002: class @code{graphical}, e.g.:
11003: 
11004: @example
11005: graphical class circle \ "graphical" is the parent class
11006:   cell var circle-radius
11007: how:
11008:   : draw ( x y -- )
11009:     circle-radius @@ draw-circle ;
11010: 
11011:   : init ( n-radius -- (
11012:     circle-radius ! ;
11013: class;
11014: @end example
11015: 
11016: Here we define a class @code{circle} as a child of @code{graphical},
11017: with a field @code{circle-radius}; it defines new methods for the
11018: selectors @code{draw} and @code{init} (@code{init} is defined in
11019: @code{object}, the parent class of @code{graphical}).
11020: 
11021: Now we can create a circle in the dictionary with:
11022: 
11023: @example
11024: 50 circle : my-circle
11025: @end example
11026: 
11027: @noindent
11028: @code{:} invokes @code{init}, thus initializing the field
11029: @code{circle-radius} with 50. We can draw this new circle at (100,100)
11030: with:
11031: 
11032: @example
11033: 100 100 my-circle draw
11034: @end example
11035: 
11036: @cindex selector invocation, restrictions
11037: @cindex class definition, restrictions
11038: Note: You can only invoke a selector if the receiving object belongs to
11039: the class where the selector was defined or one of its descendents;
11040: e.g., you can invoke @code{draw} only for objects belonging to
11041: @code{graphical} or its descendents (e.g., @code{circle}). The scoping
11042: mechanism will check if you try to invoke a selector that is not
11043: defined in this class hierarchy, so you'll get an error at compilation
11044: time.
11045: 
11046: 
11047: @node The OOF base class, Class Declaration, Basic OOF Usage, OOF
11048: @subsubsection The @file{oof.fs} base class
11049: @cindex @file{oof.fs} base class
11050: 
11051: When you define a class, you have to specify a parent class.  So how do
11052: you start defining classes? There is one class available from the start:
11053: @code{object}. You have to use it as ancestor for all classes. It is the
11054: only class that has no parent. Classes are also objects, except that
11055: they don't have instance variables; class manipulation such as
11056: inheritance or changing definitions of a class is handled through
11057: selectors of the class @code{object}.
11058: 
11059: @code{object} provides a number of selectors:
11060: 
11061: @itemize @bullet
11062: @item
11063: @code{class} for subclassing, @code{definitions} to add definitions
11064: later on, and @code{class?} to get type informations (is the class a
11065: subclass of the class passed on the stack?).
11066: 
11067: doc---object-class
11068: doc---object-definitions
11069: doc---object-class?
11070: 
11071: 
11072: @item
11073: @code{init} and @code{dispose} as constructor and destructor of the
11074: object. @code{init} is invocated after the object's memory is allocated,
11075: while @code{dispose} also handles deallocation. Thus if you redefine
11076: @code{dispose}, you have to call the parent's dispose with @code{super
11077: dispose}, too.
11078: 
11079: doc---object-init
11080: doc---object-dispose
11081: 
11082: 
11083: @item
11084: @code{new}, @code{new[]}, @code{:}, @code{ptr}, @code{asptr}, and
11085: @code{[]} to create named and unnamed objects and object arrays or
11086: object pointers.
11087: 
11088: doc---object-new
11089: doc---object-new[]
11090: doc---object-:
11091: doc---object-ptr
11092: doc---object-asptr
11093: doc---object-[]
11094: 
11095: 
11096: @item
11097: @code{::} and @code{super} for explicit scoping. You should use explicit
11098: scoping only for super classes or classes with the same set of instance
11099: variables. Explicitly-scoped selectors use early binding.
11100: 
11101: doc---object-::
11102: doc---object-super
11103: 
11104: 
11105: @item
11106: @code{self} to get the address of the object
11107: 
11108: doc---object-self
11109: 
11110: 
11111: @item
11112: @code{bind}, @code{bound}, @code{link}, and @code{is} to assign object
11113: pointers and instance defers.
11114: 
11115: doc---object-bind
11116: doc---object-bound
11117: doc---object-link
11118: doc---object-is
11119: 
11120: 
11121: @item
11122: @code{'} to obtain selector tokens, @code{send} to invocate selectors
11123: form the stack, and @code{postpone} to generate selector invocation code.
11124: 
11125: doc---object-'
11126: doc---object-postpone
11127: 
11128: 
11129: @item
11130: @code{with} and @code{endwith} to select the active object from the
11131: stack, and enable its scope. Using @code{with} and @code{endwith}
11132: also allows you to create code using selector @code{postpone} without being
11133: trapped by the state-smart objects.
11134: 
11135: doc---object-with
11136: doc---object-endwith
11137: 
11138: 
11139: @end itemize
11140: 
11141: @node Class Declaration, Class Implementation, The OOF base class, OOF
11142: @subsubsection Class Declaration
11143: @cindex class declaration
11144: 
11145: @itemize @bullet
11146: @item
11147: Instance variables
11148: 
11149: doc---oof-var
11150: 
11151: 
11152: @item
11153: Object pointers
11154: 
11155: doc---oof-ptr
11156: doc---oof-asptr
11157: 
11158: 
11159: @item
11160: Instance defers
11161: 
11162: doc---oof-defer
11163: 
11164: 
11165: @item
11166: Method selectors
11167: 
11168: doc---oof-early
11169: doc---oof-method
11170: 
11171: 
11172: @item
11173: Class-wide variables
11174: 
11175: doc---oof-static
11176: 
11177: 
11178: @item
11179: End declaration
11180: 
11181: doc---oof-how:
11182: doc---oof-class;
11183: 
11184: 
11185: @end itemize
11186: 
11187: @c -------------------------------------------------------------
11188: @node Class Implementation,  , Class Declaration, OOF
11189: @subsubsection Class Implementation
11190: @cindex class implementation
11191: 
11192: @c -------------------------------------------------------------
11193: @node Mini-OOF, Comparison with other object models, OOF, Object-oriented Forth
11194: @subsection The @file{mini-oof.fs} model
11195: @cindex mini-oof
11196: 
11197: Gforth's third object oriented Forth package is a 12-liner. It uses a
11198: mixture of the @file{object.fs} and the @file{oof.fs} syntax,
11199: and reduces to the bare minimum of features. This is based on a posting
11200: of Bernd Paysan in comp.lang.forth.
11201: 
11202: @menu
11203: * Basic Mini-OOF Usage::        
11204: * Mini-OOF Example::            
11205: * Mini-OOF Implementation::     
11206: @end menu
11207: 
11208: @c -------------------------------------------------------------
11209: @node Basic Mini-OOF Usage, Mini-OOF Example, Mini-OOF, Mini-OOF
11210: @subsubsection Basic @file{mini-oof.fs} Usage
11211: @cindex mini-oof usage
11212: 
11213: There is a base class (@code{class}, which allocates one cell for the
11214: object pointer) plus seven other words: to define a method, a variable,
11215: a class; to end a class, to resolve binding, to allocate an object and
11216: to compile a class method.
11217: @comment TODO better description of the last one
11218: 
11219: 
11220: doc-object
11221: doc-method
11222: doc-var
11223: doc-class
11224: doc-end-class
11225: doc-defines
11226: doc-new
11227: doc-::
11228: 
11229: 
11230: 
11231: @c -------------------------------------------------------------
11232: @node Mini-OOF Example, Mini-OOF Implementation, Basic Mini-OOF Usage, Mini-OOF
11233: @subsubsection Mini-OOF Example
11234: @cindex mini-oof example
11235: 
11236: A short example shows how to use this package. This example, in slightly
11237: extended form, is supplied as @file{moof-exm.fs}
11238: @comment TODO could flesh this out with some comments from the Forthwrite article
11239: 
11240: @example
11241: object class
11242:   method init
11243:   method draw
11244: end-class graphical
11245: @end example
11246: 
11247: This code defines a class @code{graphical} with an
11248: operation @code{draw}.  We can perform the operation
11249: @code{draw} on any @code{graphical} object, e.g.:
11250: 
11251: @example
11252: 100 100 t-rex draw
11253: @end example
11254: 
11255: where @code{t-rex} is an object or object pointer, created with e.g.
11256: @code{graphical new Constant t-rex}.
11257: 
11258: For concrete graphical objects, we define child classes of the
11259: class @code{graphical}, e.g.:
11260: 
11261: @example
11262: graphical class
11263:   cell var circle-radius
11264: end-class circle \ "graphical" is the parent class
11265: 
11266: :noname ( x y -- )
11267:   circle-radius @@ draw-circle ; circle defines draw
11268: :noname ( r -- )
11269:   circle-radius ! ; circle defines init
11270: @end example
11271: 
11272: There is no implicit init method, so we have to define one. The creation
11273: code of the object now has to call init explicitely.
11274: 
11275: @example
11276: circle new Constant my-circle
11277: 50 my-circle init
11278: @end example
11279: 
11280: It is also possible to add a function to create named objects with
11281: automatic call of @code{init}, given that all objects have @code{init}
11282: on the same place:
11283: 
11284: @example
11285: : new: ( .. o "name" -- )
11286:     new dup Constant init ;
11287: 80 circle new: large-circle
11288: @end example
11289: 
11290: We can draw this new circle at (100,100) with:
11291: 
11292: @example
11293: 100 100 my-circle draw
11294: @end example
11295: 
11296: @node Mini-OOF Implementation,  , Mini-OOF Example, Mini-OOF
11297: @subsubsection @file{mini-oof.fs} Implementation
11298: 
11299: Object-oriented systems with late binding typically use a
11300: ``vtable''-approach: the first variable in each object is a pointer to a
11301: table, which contains the methods as function pointers. The vtable
11302: may also contain other information.
11303: 
11304: So first, let's declare methods:
11305: 
11306: @example
11307: : method ( m v -- m' v ) Create  over , swap cell+ swap
11308:   DOES> ( ... o -- ... ) @ over @ + @ execute ;
11309: @end example
11310: 
11311: During method declaration, the number of methods and instance
11312: variables is on the stack (in address units). @code{method} creates
11313: one method and increments the method number. To execute a method, it
11314: takes the object, fetches the vtable pointer, adds the offset, and
11315: executes the @i{xt} stored there. Each method takes the object it is
11316: invoked from as top of stack parameter. The method itself should
11317: consume that object.
11318: 
11319: Now, we also have to declare instance variables
11320: 
11321: @example
11322: : var ( m v size -- m v' ) Create  over , +
11323:   DOES> ( o -- addr ) @ + ;
11324: @end example
11325: 
11326: As before, a word is created with the current offset. Instance
11327: variables can have different sizes (cells, floats, doubles, chars), so
11328: all we do is take the size and add it to the offset. If your machine
11329: has alignment restrictions, put the proper @code{aligned} or
11330: @code{faligned} before the variable, to adjust the variable
11331: offset. That's why it is on the top of stack.
11332: 
11333: We need a starting point (the base object) and some syntactic sugar:
11334: 
11335: @example
11336: Create object  1 cells , 2 cells ,
11337: : class ( class -- class methods vars ) dup 2@ ;
11338: @end example
11339: 
11340: For inheritance, the vtable of the parent object has to be
11341: copied when a new, derived class is declared. This gives all the
11342: methods of the parent class, which can be overridden, though.
11343: 
11344: @example
11345: : end-class  ( class methods vars -- )
11346:   Create  here >r , dup , 2 cells ?DO ['] noop , 1 cells +LOOP
11347:   cell+ dup cell+ r> rot @ 2 cells /string move ;
11348: @end example
11349: 
11350: The first line creates the vtable, initialized with
11351: @code{noop}s. The second line is the inheritance mechanism, it
11352: copies the xts from the parent vtable.
11353: 
11354: We still have no way to define new methods, let's do that now:
11355: 
11356: @example
11357: : defines ( xt class -- ) ' >body @ + ! ;
11358: @end example
11359: 
11360: To allocate a new object, we need a word, too:
11361: 
11362: @example
11363: : new ( class -- o )  here over @ allot swap over ! ;
11364: @end example
11365: 
11366: Sometimes derived classes want to access the method of the
11367: parent object. There are two ways to achieve this with Mini-OOF:
11368: first, you could use named words, and second, you could look up the
11369: vtable of the parent object.
11370: 
11371: @example
11372: : :: ( class "name" -- ) ' >body @ + @ compile, ;
11373: @end example
11374: 
11375: 
11376: Nothing can be more confusing than a good example, so here is
11377: one. First let's declare a text object (called
11378: @code{button}), that stores text and position:
11379: 
11380: @example
11381: object class
11382:   cell var text
11383:   cell var len
11384:   cell var x
11385:   cell var y
11386:   method init
11387:   method draw
11388: end-class button
11389: @end example
11390: 
11391: @noindent
11392: Now, implement the two methods, @code{draw} and @code{init}:
11393: 
11394: @example
11395: :noname ( o -- )
11396:  >r r@ x @ r@ y @ at-xy  r@ text @ r> len @ type ;
11397:  button defines draw
11398: :noname ( addr u o -- )
11399:  >r 0 r@ x ! 0 r@ y ! r@ len ! r> text ! ;
11400:  button defines init
11401: @end example
11402: 
11403: @noindent
11404: To demonstrate inheritance, we define a class @code{bold-button}, with no
11405: new data and no new methods:
11406: 
11407: @example
11408: button class
11409: end-class bold-button
11410: 
11411: : bold   27 emit ." [1m" ;
11412: : normal 27 emit ." [0m" ;
11413: @end example
11414: 
11415: @noindent
11416: The class @code{bold-button} has a different draw method to
11417: @code{button}, but the new method is defined in terms of the draw method
11418: for @code{button}:
11419: 
11420: @example
11421: :noname bold [ button :: draw ] normal ; bold-button defines draw
11422: @end example
11423: 
11424: @noindent
11425: Finally, create two objects and apply methods:
11426: 
11427: @example
11428: button new Constant foo
11429: s" thin foo" foo init
11430: page
11431: foo draw
11432: bold-button new Constant bar
11433: s" fat bar" bar init
11434: 1 bar y !
11435: bar draw
11436: @end example
11437: 
11438: 
11439: @node Comparison with other object models,  , Mini-OOF, Object-oriented Forth
11440: @subsection Comparison with other object models
11441: @cindex comparison of object models
11442: @cindex object models, comparison
11443: 
11444: Many object-oriented Forth extensions have been proposed (@cite{A survey
11445: of object-oriented Forths} (SIGPLAN Notices, April 1996) by Bradford
11446: J. Rodriguez and W. F. S. Poehlman lists 17). This section discusses the
11447: relation of the object models described here to two well-known and two
11448: closely-related (by the use of method maps) models.
11449: 
11450: @cindex Neon model
11451: The most popular model currently seems to be the Neon model (see
11452: @cite{Object-oriented programming in ANS Forth} (Forth Dimensions, March
11453: 1997) by Andrew McKewan) but this model has a number of limitations
11454: @footnote{A longer version of this critique can be
11455: found in @cite{On Standardizing Object-Oriented Forth Extensions} (Forth
11456: Dimensions, May 1997) by Anton Ertl.}:
11457: 
11458: @itemize @bullet
11459: @item
11460: It uses a @code{@emph{selector object}} syntax, which makes it unnatural
11461: to pass objects on the stack.
11462: 
11463: @item
11464: It requires that the selector parses the input stream (at
11465: compile time); this leads to reduced extensibility and to bugs that are+
11466: hard to find.
11467: 
11468: @item
11469: It allows using every selector to every object;
11470: this eliminates the need for classes, but makes it harder to create
11471: efficient implementations. 
11472: @end itemize
11473: 
11474: @cindex Pountain's object-oriented model
11475: Another well-known publication is @cite{Object-Oriented Forth} (Academic
11476: Press, London, 1987) by Dick Pountain. However, it is not really about
11477: object-oriented programming, because it hardly deals with late
11478: binding. Instead, it focuses on features like information hiding and
11479: overloading that are characteristic of modular languages like Ada (83).
11480: 
11481: @cindex Zsoter's object-oriented model
11482: In @cite{Does late binding have to be slow?} (Forth Dimensions 18(1)
11483: 1996, pages 31-35) Andras Zsoter describes a model that makes heavy use
11484: of an active object (like @code{this} in @file{objects.fs}): The active
11485: object is not only used for accessing all fields, but also specifies the
11486: receiving object of every selector invocation; you have to change the
11487: active object explicitly with @code{@{ ... @}}, whereas in
11488: @file{objects.fs} it changes more or less implicitly at @code{m:
11489: ... ;m}. Such a change at the method entry point is unnecessary with the
11490: Zsoter's model, because the receiving object is the active object
11491: already. On the other hand, the explicit change is absolutely necessary
11492: in that model, because otherwise no one could ever change the active
11493: object. An ANS Forth implementation of this model is available at
11494: @uref{http://www.forth.org/fig/oopf.html}.
11495: 
11496: @cindex @file{oof.fs}, differences to other models
11497: The @file{oof.fs} model combines information hiding and overloading
11498: resolution (by keeping names in various word lists) with object-oriented
11499: programming. It sets the active object implicitly on method entry, but
11500: also allows explicit changing (with @code{>o...o>} or with
11501: @code{with...endwith}). It uses parsing and state-smart objects and
11502: classes for resolving overloading and for early binding: the object or
11503: class parses the selector and determines the method from this. If the
11504: selector is not parsed by an object or class, it performs a call to the
11505: selector for the active object (late binding), like Zsoter's model.
11506: Fields are always accessed through the active object. The big
11507: disadvantage of this model is the parsing and the state-smartness, which
11508: reduces extensibility and increases the opportunities for subtle bugs;
11509: essentially, you are only safe if you never tick or @code{postpone} an
11510: object or class (Bernd disagrees, but I (Anton) am not convinced).
11511: 
11512: @cindex @file{mini-oof.fs}, differences to other models
11513: The @file{mini-oof.fs} model is quite similar to a very stripped-down
11514: version of the @file{objects.fs} model, but syntactically it is a
11515: mixture of the @file{objects.fs} and @file{oof.fs} models.
11516: 
11517: @c -------------------------------------------------------------
11518: @node Passing Commands to the OS, Keeping track of Time, Object-oriented Forth, Words
11519: @section Passing Commands to the Operating System
11520: @cindex operating system - passing commands
11521: @cindex shell commands
11522: 
11523: Gforth allows you to pass an arbitrary string to the host operating
11524: system shell (if such a thing exists) for execution.
11525: 
11526: 
11527: doc-sh
11528: doc-system
11529: doc-$?
11530: doc-getenv
11531: 
11532: 
11533: @c -------------------------------------------------------------
11534: @node Keeping track of Time, Miscellaneous Words, Passing Commands to the OS, Words
11535: @section Keeping track of Time
11536: @cindex time-related words
11537: 
11538: Gforth implements time-related operations by making calls to the C
11539: library function, @code{gettimeofday}.
11540: 
11541: doc-ms
11542: doc-time&date
11543: 
11544: 
11545: 
11546: @c -------------------------------------------------------------
11547: @node Miscellaneous Words,  , Keeping track of Time, Words
11548: @section Miscellaneous Words
11549: @cindex miscellaneous words
11550: 
11551: @comment TODO find homes for these
11552: 
11553: These section lists the ANS Forth words that are not documented
11554: elsewhere in this manual. Ultimately, they all need proper homes.
11555: 
11556: doc-[compile]
11557: doc-quit
11558: 
11559: The following ANS Forth words are not currently supported by Gforth 
11560: (@pxref{ANS conformance}):
11561: 
11562: @code{EDITOR} 
11563: @code{EMIT?} 
11564: @code{FORGET} 
11565: 
11566: @c ******************************************************************
11567: @node Error messages, Tools, Words, Top
11568: @chapter Error messages
11569: @cindex error messages
11570: @cindex backtrace
11571: 
11572: A typical Gforth error message looks like this:
11573: 
11574: @example
11575: in file included from :-1
11576: in file included from ./yyy.fs:1
11577: ./xxx.fs:4: Invalid memory address
11578: bar
11579: ^^^
11580: $400E664C @@
11581: $400E6664 foo
11582: @end example
11583: 
11584: The message identifying the error is @code{Invalid memory address}.  The
11585: error happened when text-interpreting line 4 of the file
11586: @file{./xxx.fs}. This line is given (it contains @code{bar}), and the
11587: word on the line where the error happened, is pointed out (with
11588: @code{^^^}).
11589: 
11590: The file containing the error was included in line 1 of @file{./yyy.fs},
11591: and @file{yyy.fs} was included from a non-file (in this case, by giving
11592: @file{yyy.fs} as command-line parameter to Gforth).
11593: 
11594: At the end of the error message you find a return stack dump that can be
11595: interpreted as a backtrace (possibly empty). On top you find the top of
11596: the return stack when the @code{throw} happened, and at the bottom you
11597: find the return stack entry just above the return stack of the topmost
11598: text interpreter.
11599: 
11600: To the right of most return stack entries you see a guess for the word
11601: that pushed that return stack entry as its return address. This gives a
11602: backtrace. In our case we see that @code{bar} called @code{foo}, and
11603: @code{foo} called @code{@@} (and @code{@@} had an @emph{Invalid memory
11604: address} exception).
11605: 
11606: Note that the backtrace is not perfect: We don't know which return stack
11607: entries are return addresses (so we may get false positives); and in
11608: some cases (e.g., for @code{abort"}) we cannot determine from the return
11609: address the word that pushed the return address, so for some return
11610: addresses you see no names in the return stack dump.
11611: 
11612: @cindex @code{catch} and backtraces
11613: The return stack dump represents the return stack at the time when a
11614: specific @code{throw} was executed.  In programs that make use of
11615: @code{catch}, it is not necessarily clear which @code{throw} should be
11616: used for the return stack dump (e.g., consider one @code{throw} that
11617: indicates an error, which is caught, and during recovery another error
11618: happens; which @code{throw} should be used for the stack dump?).  Gforth
11619: presents the return stack dump for the first @code{throw} after the last
11620: executed (not returned-to) @code{catch}; this works well in the usual
11621: case.
11622: 
11623: @cindex @code{gforth-fast} and backtraces
11624: @cindex @code{gforth-fast}, difference from @code{gforth}
11625: @cindex backtraces with @code{gforth-fast}
11626: @cindex return stack dump with @code{gforth-fast}
11627: @code{gforth} is able to do a return stack dump for throws generated
11628: from primitives (e.g., invalid memory address, stack empty etc.);
11629: @code{gforth-fast} is only able to do a return stack dump from a
11630: directly called @code{throw} (including @code{abort} etc.).  This is the
11631: only difference (apart from a speed factor of between 1.15 (K6-2) and
11632: 1.6 (21164A)) between @code{gforth} and @code{gforth-fast}.  Given an
11633: exception caused by a primitive in @code{gforth-fast}, you will
11634: typically see no return stack dump at all; however, if the exception is
11635: caught by @code{catch} (e.g., for restoring some state), and then
11636: @code{throw}n again, the return stack dump will be for the first such
11637: @code{throw}.
11638: 
11639: @c ******************************************************************
11640: @node Tools, ANS conformance, Error messages, Top
11641: @chapter Tools
11642: 
11643: @menu
11644: * ANS Report::                  Report the words used, sorted by wordset.
11645: @end menu
11646: 
11647: See also @ref{Emacs and Gforth}.
11648: 
11649: @node ANS Report,  , Tools, Tools
11650: @section @file{ans-report.fs}: Report the words used, sorted by wordset
11651: @cindex @file{ans-report.fs}
11652: @cindex report the words used in your program
11653: @cindex words used in your program
11654: 
11655: If you want to label a Forth program as ANS Forth Program, you must
11656: document which wordsets the program uses; for extension wordsets, it is
11657: helpful to list the words the program requires from these wordsets
11658: (because Forth systems are allowed to provide only some words of them).
11659: 
11660: The @file{ans-report.fs} tool makes it easy for you to determine which
11661: words from which wordset and which non-ANS words your application
11662: uses. You simply have to include @file{ans-report.fs} before loading the
11663: program you want to check. After loading your program, you can get the
11664: report with @code{print-ans-report}. A typical use is to run this as
11665: batch job like this:
11666: @example
11667: gforth ans-report.fs myprog.fs -e "print-ans-report bye"
11668: @end example
11669: 
11670: The output looks like this (for @file{compat/control.fs}):
11671: @example
11672: The program uses the following words
11673: from CORE :
11674: : POSTPONE THEN ; immediate ?dup IF 0= 
11675: from BLOCK-EXT :
11676: \ 
11677: from FILE :
11678: ( 
11679: @end example
11680: 
11681: @subsection Caveats
11682: 
11683: Note that @file{ans-report.fs} just checks which words are used, not whether
11684: they are used in an ANS Forth conforming way!
11685: 
11686: Some words are defined in several wordsets in the
11687: standard. @file{ans-report.fs} reports them for only one of the
11688: wordsets, and not necessarily the one you expect. It depends on usage
11689: which wordset is the right one to specify. E.g., if you only use the
11690: compilation semantics of @code{S"}, it is a Core word; if you also use
11691: its interpretation semantics, it is a File word.
11692: 
11693: @c ******************************************************************
11694: @node ANS conformance, Standard vs Extensions, Tools, Top
11695: @chapter ANS conformance
11696: @cindex ANS conformance of Gforth
11697: 
11698: To the best of our knowledge, Gforth is an
11699: 
11700: ANS Forth System
11701: @itemize @bullet
11702: @item providing the Core Extensions word set
11703: @item providing the Block word set
11704: @item providing the Block Extensions word set
11705: @item providing the Double-Number word set
11706: @item providing the Double-Number Extensions word set
11707: @item providing the Exception word set
11708: @item providing the Exception Extensions word set
11709: @item providing the Facility word set
11710: @item providing @code{EKEY}, @code{EKEY>CHAR}, @code{EKEY?}, @code{MS} and @code{TIME&DATE} from the Facility Extensions word set
11711: @item providing the File Access word set
11712: @item providing the File Access Extensions word set
11713: @item providing the Floating-Point word set
11714: @item providing the Floating-Point Extensions word set
11715: @item providing the Locals word set
11716: @item providing the Locals Extensions word set
11717: @item providing the Memory-Allocation word set
11718: @item providing the Memory-Allocation Extensions word set (that one's easy)
11719: @item providing the Programming-Tools word set
11720: @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
11721: @item providing the Search-Order word set
11722: @item providing the Search-Order Extensions word set
11723: @item providing the String word set
11724: @item providing the String Extensions word set (another easy one)
11725: @end itemize
11726: 
11727: @cindex system documentation
11728: In addition, ANS Forth systems are required to document certain
11729: implementation choices. This chapter tries to meet these
11730: requirements. In many cases it gives a way to ask the system for the
11731: information instead of providing the information directly, in
11732: particular, if the information depends on the processor, the operating
11733: system or the installation options chosen, or if they are likely to
11734: change during the maintenance of Gforth.
11735: 
11736: @comment The framework for the rest has been taken from pfe.
11737: 
11738: @menu
11739: * The Core Words::              
11740: * The optional Block word set::  
11741: * The optional Double Number word set::  
11742: * The optional Exception word set::  
11743: * The optional Facility word set::  
11744: * The optional File-Access word set::  
11745: * The optional Floating-Point word set::  
11746: * The optional Locals word set::  
11747: * The optional Memory-Allocation word set::  
11748: * The optional Programming-Tools word set::  
11749: * The optional Search-Order word set::  
11750: @end menu
11751: 
11752: 
11753: @c =====================================================================
11754: @node The Core Words, The optional Block word set, ANS conformance, ANS conformance
11755: @comment  node-name,  next,  previous,  up
11756: @section The Core Words
11757: @c =====================================================================
11758: @cindex core words, system documentation
11759: @cindex system documentation, core words
11760: 
11761: @menu
11762: * core-idef::                   Implementation Defined Options                   
11763: * core-ambcond::                Ambiguous Conditions                
11764: * core-other::                  Other System Documentation                  
11765: @end menu
11766: 
11767: @c ---------------------------------------------------------------------
11768: @node core-idef, core-ambcond, The Core Words, The Core Words
11769: @subsection Implementation Defined Options
11770: @c ---------------------------------------------------------------------
11771: @cindex core words, implementation-defined options
11772: @cindex implementation-defined options, core words
11773: 
11774: 
11775: @table @i
11776: @item (Cell) aligned addresses:
11777: @cindex cell-aligned addresses
11778: @cindex aligned addresses
11779: processor-dependent. Gforth's alignment words perform natural alignment
11780: (e.g., an address aligned for a datum of size 8 is divisible by
11781: 8). Unaligned accesses usually result in a @code{-23 THROW}.
11782: 
11783: @item @code{EMIT} and non-graphic characters:
11784: @cindex @code{EMIT} and non-graphic characters
11785: @cindex non-graphic characters and @code{EMIT}
11786: The character is output using the C library function (actually, macro)
11787: @code{putc}.
11788: 
11789: @item character editing of @code{ACCEPT} and @code{EXPECT}:
11790: @cindex character editing of @code{ACCEPT} and @code{EXPECT}
11791: @cindex editing in @code{ACCEPT} and @code{EXPECT}
11792: @cindex @code{ACCEPT}, editing
11793: @cindex @code{EXPECT}, editing
11794: This is modeled on the GNU readline library (@pxref{Readline
11795: Interaction, , Command Line Editing, readline, The GNU Readline
11796: Library}) with Emacs-like key bindings. @kbd{Tab} deviates a little by
11797: producing a full word completion every time you type it (instead of
11798: producing the common prefix of all completions). @xref{Command-line editing}.
11799: 
11800: @item character set:
11801: @cindex character set
11802: The character set of your computer and display device. Gforth is
11803: 8-bit-clean (but some other component in your system may make trouble).
11804: 
11805: @item Character-aligned address requirements:
11806: @cindex character-aligned address requirements
11807: installation-dependent. Currently a character is represented by a C
11808: @code{unsigned char}; in the future we might switch to @code{wchar_t}
11809: (Comments on that requested).
11810: 
11811: @item character-set extensions and matching of names:
11812: @cindex character-set extensions and matching of names
11813: @cindex case-sensitivity for name lookup
11814: @cindex name lookup, case-sensitivity
11815: @cindex locale and case-sensitivity
11816: Any character except the ASCII NUL character can be used in a
11817: name. Matching is case-insensitive (except in @code{TABLE}s). The
11818: matching is performed using the C library function @code{strncasecmp}, whose
11819: function is probably influenced by the locale. E.g., the @code{C} locale
11820: does not know about accents and umlauts, so they are matched
11821: case-sensitively in that locale. For portability reasons it is best to
11822: write programs such that they work in the @code{C} locale. Then one can
11823: use libraries written by a Polish programmer (who might use words
11824: containing ISO Latin-2 encoded characters) and by a French programmer
11825: (ISO Latin-1) in the same program (of course, @code{WORDS} will produce
11826: funny results for some of the words (which ones, depends on the font you
11827: are using)). Also, the locale you prefer may not be available in other
11828: operating systems. Hopefully, Unicode will solve these problems one day.
11829: 
11830: @item conditions under which control characters match a space delimiter:
11831: @cindex space delimiters
11832: @cindex control characters as delimiters
11833: If @code{WORD} is called with the space character as a delimiter, all
11834: white-space characters (as identified by the C macro @code{isspace()})
11835: are delimiters. @code{PARSE}, on the other hand, treats space like other
11836: delimiters. @code{SWORD} treats space like @code{WORD}, but behaves
11837: like @code{PARSE} otherwise. @code{(NAME)}, which is used by the outer
11838: interpreter (aka text interpreter) by default, treats all white-space
11839: characters as delimiters.
11840: 
11841: @item format of the control-flow stack:
11842: @cindex control-flow stack, format
11843: The data stack is used as control-flow stack. The size of a control-flow
11844: stack item in cells is given by the constant @code{cs-item-size}. At the
11845: time of this writing, an item consists of a (pointer to a) locals list
11846: (third), an address in the code (second), and a tag for identifying the
11847: item (TOS). The following tags are used: @code{defstart},
11848: @code{live-orig}, @code{dead-orig}, @code{dest}, @code{do-dest},
11849: @code{scopestart}.
11850: 
11851: @item conversion of digits > 35
11852: @cindex digits > 35
11853: The characters @code{[\]^_'} are the digits with the decimal value
11854: 36@minus{}41. There is no way to input many of the larger digits.
11855: 
11856: @item display after input terminates in @code{ACCEPT} and @code{EXPECT}:
11857: @cindex @code{EXPECT}, display after end of input
11858: @cindex @code{ACCEPT}, display after end of input
11859: The cursor is moved to the end of the entered string. If the input is
11860: terminated using the @kbd{Return} key, a space is typed.
11861: 
11862: @item exception abort sequence of @code{ABORT"}:
11863: @cindex exception abort sequence of @code{ABORT"}
11864: @cindex @code{ABORT"}, exception abort sequence
11865: The error string is stored into the variable @code{"error} and a
11866: @code{-2 throw} is performed.
11867: 
11868: @item input line terminator:
11869: @cindex input line terminator
11870: @cindex line terminator on input
11871: @cindex newline character on input
11872: For interactive input, @kbd{C-m} (CR) and @kbd{C-j} (LF) terminate
11873: lines. One of these characters is typically produced when you type the
11874: @kbd{Enter} or @kbd{Return} key.
11875: 
11876: @item maximum size of a counted string:
11877: @cindex maximum size of a counted string
11878: @cindex counted string, maximum size
11879: @code{s" /counted-string" environment? drop .}. Currently 255 characters
11880: on all ports, but this may change.
11881: 
11882: @item maximum size of a parsed string:
11883: @cindex maximum size of a parsed string
11884: @cindex parsed string, maximum size
11885: Given by the constant @code{/line}. Currently 255 characters.
11886: 
11887: @item maximum size of a definition name, in characters:
11888: @cindex maximum size of a definition name, in characters
11889: @cindex name, maximum length
11890: 31
11891: 
11892: @item maximum string length for @code{ENVIRONMENT?}, in characters:
11893: @cindex maximum string length for @code{ENVIRONMENT?}, in characters
11894: @cindex @code{ENVIRONMENT?} string length, maximum
11895: 31
11896: 
11897: @item method of selecting the user input device:
11898: @cindex user input device, method of selecting
11899: The user input device is the standard input. There is currently no way to
11900: change it from within Gforth. However, the input can typically be
11901: redirected in the command line that starts Gforth.
11902: 
11903: @item method of selecting the user output device:
11904: @cindex user output device, method of selecting
11905: @code{EMIT} and @code{TYPE} output to the file-id stored in the value
11906: @code{outfile-id} (@code{stdout} by default). Gforth uses unbuffered
11907: output when the user output device is a terminal, otherwise the output
11908: is buffered.
11909: 
11910: @item methods of dictionary compilation:
11911: What are we expected to document here?
11912: 
11913: @item number of bits in one address unit:
11914: @cindex number of bits in one address unit
11915: @cindex address unit, size in bits
11916: @code{s" address-units-bits" environment? drop .}. 8 in all current
11917: ports.
11918: 
11919: @item number representation and arithmetic:
11920: @cindex number representation and arithmetic
11921: Processor-dependent. Binary two's complement on all current ports.
11922: 
11923: @item ranges for integer types:
11924: @cindex ranges for integer types
11925: @cindex integer types, ranges
11926: Installation-dependent. Make environmental queries for @code{MAX-N},
11927: @code{MAX-U}, @code{MAX-D} and @code{MAX-UD}. The lower bounds for
11928: unsigned (and positive) types is 0. The lower bound for signed types on
11929: two's complement and one's complement machines machines can be computed
11930: by adding 1 to the upper bound.
11931: 
11932: @item read-only data space regions:
11933: @cindex read-only data space regions
11934: @cindex data-space, read-only regions
11935: The whole Forth data space is writable.
11936: 
11937: @item size of buffer at @code{WORD}:
11938: @cindex size of buffer at @code{WORD}
11939: @cindex @code{WORD} buffer size
11940: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
11941: shared with the pictured numeric output string. If overwriting
11942: @code{PAD} is acceptable, it is as large as the remaining dictionary
11943: space, although only as much can be sensibly used as fits in a counted
11944: string.
11945: 
11946: @item size of one cell in address units:
11947: @cindex cell size
11948: @code{1 cells .}.
11949: 
11950: @item size of one character in address units:
11951: @cindex char size
11952: @code{1 chars .}. 1 on all current ports.
11953: 
11954: @item size of the keyboard terminal buffer:
11955: @cindex size of the keyboard terminal buffer
11956: @cindex terminal buffer, size
11957: Varies. You can determine the size at a specific time using @code{lp@@
11958: tib - .}. It is shared with the locals stack and TIBs of files that
11959: include the current file. You can change the amount of space for TIBs
11960: and locals stack at Gforth startup with the command line option
11961: @code{-l}.
11962: 
11963: @item size of the pictured numeric output buffer:
11964: @cindex size of the pictured numeric output buffer
11965: @cindex pictured numeric output buffer, size
11966: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
11967: shared with @code{WORD}.
11968: 
11969: @item size of the scratch area returned by @code{PAD}:
11970: @cindex size of the scratch area returned by @code{PAD}
11971: @cindex @code{PAD} size
11972: The remainder of dictionary space. @code{unused pad here - - .}.
11973: 
11974: @item system case-sensitivity characteristics:
11975: @cindex case-sensitivity characteristics
11976: Dictionary searches are case-insensitive (except in
11977: @code{TABLE}s). However, as explained above under @i{character-set
11978: extensions}, the matching for non-ASCII characters is determined by the
11979: locale you are using. In the default @code{C} locale all non-ASCII
11980: characters are matched case-sensitively.
11981: 
11982: @item system prompt:
11983: @cindex system prompt
11984: @cindex prompt
11985: @code{ ok} in interpret state, @code{ compiled} in compile state.
11986: 
11987: @item division rounding:
11988: @cindex division rounding
11989: installation dependent. @code{s" floored" environment? drop .}. We leave
11990: the choice to @code{gcc} (what to use for @code{/}) and to you (whether
11991: to use @code{fm/mod}, @code{sm/rem} or simply @code{/}).
11992: 
11993: @item values of @code{STATE} when true:
11994: @cindex @code{STATE} values
11995: -1.
11996: 
11997: @item values returned after arithmetic overflow:
11998: On two's complement machines, arithmetic is performed modulo
11999: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
12000: arithmetic (with appropriate mapping for signed types). Division by zero
12001: typically results in a @code{-55 throw} (Floating-point unidentified
12002: fault), although a @code{-10 throw} (divide by zero) would be more
12003: appropriate.
12004: 
12005: @item whether the current definition can be found after @t{DOES>}:
12006: @cindex @t{DOES>}, visibility of current definition
12007: No.
12008: 
12009: @end table
12010: 
12011: @c ---------------------------------------------------------------------
12012: @node core-ambcond, core-other, core-idef, The Core Words
12013: @subsection Ambiguous conditions
12014: @c ---------------------------------------------------------------------
12015: @cindex core words, ambiguous conditions
12016: @cindex ambiguous conditions, core words
12017: 
12018: @table @i
12019: 
12020: @item a name is neither a word nor a number:
12021: @cindex name not found
12022: @cindex undefined word
12023: @code{-13 throw} (Undefined word). Actually, @code{-13 bounce}, which
12024: preserves the data and FP stack, so you don't lose more work than
12025: necessary.
12026: 
12027: @item a definition name exceeds the maximum length allowed:
12028: @cindex word name too long
12029: @code{-19 throw} (Word name too long)
12030: 
12031: @item addressing a region not inside the various data spaces of the forth system:
12032: @cindex Invalid memory address
12033: The stacks, code space and header space are accessible. Machine code space is
12034: typically readable. Accessing other addresses gives results dependent on
12035: the operating system. On decent systems: @code{-9 throw} (Invalid memory
12036: address).
12037: 
12038: @item argument type incompatible with parameter:
12039: @cindex argument type mismatch
12040: This is usually not caught. Some words perform checks, e.g., the control
12041: flow words, and issue a @code{ABORT"} or @code{-12 THROW} (Argument type
12042: mismatch).
12043: 
12044: @item attempting to obtain the execution token of a word with undefined execution semantics:
12045: @cindex Interpreting a compile-only word, for @code{'} etc.
12046: @cindex execution token of words with undefined execution semantics
12047: @code{-14 throw} (Interpreting a compile-only word). In some cases, you
12048: get an execution token for @code{compile-only-error} (which performs a
12049: @code{-14 throw} when executed).
12050: 
12051: @item dividing by zero:
12052: @cindex dividing by zero
12053: @cindex floating point unidentified fault, integer division
12054: On better platforms, this produces a @code{-10 throw} (Division by
12055: zero); on other systems, this typically results in a @code{-55 throw}
12056: (Floating-point unidentified fault).
12057: 
12058: @item insufficient data stack or return stack space:
12059: @cindex insufficient data stack or return stack space
12060: @cindex stack overflow
12061: @cindex address alignment exception, stack overflow
12062: @cindex Invalid memory address, stack overflow
12063: Depending on the operating system, the installation, and the invocation
12064: of Gforth, this is either checked by the memory management hardware, or
12065: it is not checked. If it is checked, you typically get a @code{-3 throw}
12066: (Stack overflow), @code{-5 throw} (Return stack overflow), or @code{-9
12067: throw} (Invalid memory address) (depending on the platform and how you
12068: achieved the overflow) as soon as the overflow happens. If it is not
12069: checked, overflows typically result in mysterious illegal memory
12070: accesses, producing @code{-9 throw} (Invalid memory address) or
12071: @code{-23 throw} (Address alignment exception); they might also destroy
12072: the internal data structure of @code{ALLOCATE} and friends, resulting in
12073: various errors in these words.
12074: 
12075: @item insufficient space for loop control parameters:
12076: @cindex insufficient space for loop control parameters
12077: like other return stack overflows.
12078: 
12079: @item insufficient space in the dictionary:
12080: @cindex insufficient space in the dictionary
12081: @cindex dictionary overflow
12082: If you try to allot (either directly with @code{allot}, or indirectly
12083: with @code{,}, @code{create} etc.) more memory than available in the
12084: dictionary, you get a @code{-8 throw} (Dictionary overflow). If you try
12085: to access memory beyond the end of the dictionary, the results are
12086: similar to stack overflows.
12087: 
12088: @item interpreting a word with undefined interpretation semantics:
12089: @cindex interpreting a word with undefined interpretation semantics
12090: @cindex Interpreting a compile-only word
12091: For some words, we have defined interpretation semantics. For the
12092: others: @code{-14 throw} (Interpreting a compile-only word).
12093: 
12094: @item modifying the contents of the input buffer or a string literal:
12095: @cindex modifying the contents of the input buffer or a string literal
12096: These are located in writable memory and can be modified.
12097: 
12098: @item overflow of the pictured numeric output string:
12099: @cindex overflow of the pictured numeric output string
12100: @cindex pictured numeric output string, overflow
12101: @code{-17 throw} (Pictured numeric ouput string overflow).
12102: 
12103: @item parsed string overflow:
12104: @cindex parsed string overflow
12105: @code{PARSE} cannot overflow. @code{WORD} does not check for overflow.
12106: 
12107: @item producing a result out of range:
12108: @cindex result out of range
12109: On two's complement machines, arithmetic is performed modulo
12110: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
12111: arithmetic (with appropriate mapping for signed types). Division by zero
12112: typically results in a @code{-10 throw} (divide by zero) or @code{-55
12113: throw} (floating point unidentified fault). @code{convert} and
12114: @code{>number} currently overflow silently.
12115: 
12116: @item reading from an empty data or return stack:
12117: @cindex stack empty
12118: @cindex stack underflow
12119: @cindex return stack underflow
12120: The data stack is checked by the outer (aka text) interpreter after
12121: every word executed. If it has underflowed, a @code{-4 throw} (Stack
12122: underflow) is performed. Apart from that, stacks may be checked or not,
12123: depending on operating system, installation, and invocation. If they are
12124: caught by a check, they typically result in @code{-4 throw} (Stack
12125: underflow), @code{-6 throw} (Return stack underflow) or @code{-9 throw}
12126: (Invalid memory address), depending on the platform and which stack
12127: underflows and by how much. Note that even if the system uses checking
12128: (through the MMU), your program may have to underflow by a significant
12129: number of stack items to trigger the reaction (the reason for this is
12130: that the MMU, and therefore the checking, works with a page-size
12131: granularity).  If there is no checking, the symptoms resulting from an
12132: underflow are similar to those from an overflow.  Unbalanced return
12133: stack errors result in a variaty of symptoms, including @code{-9 throw}
12134: (Invalid memory address) and Illegal Instruction (typically @code{-260
12135: throw}).
12136: 
12137: @item unexpected end of the input buffer, resulting in an attempt to use a zero-length string as a name:
12138: @cindex unexpected end of the input buffer
12139: @cindex zero-length string as a name
12140: @cindex Attempt to use zero-length string as a name
12141: @code{Create} and its descendants perform a @code{-16 throw} (Attempt to
12142: use zero-length string as a name). Words like @code{'} probably will not
12143: find what they search. Note that it is possible to create zero-length
12144: names with @code{nextname} (should it not?).
12145: 
12146: @item @code{>IN} greater than input buffer:
12147: @cindex @code{>IN} greater than input buffer
12148: The next invocation of a parsing word returns a string with length 0.
12149: 
12150: @item @code{RECURSE} appears after @code{DOES>}:
12151: @cindex @code{RECURSE} appears after @code{DOES>}
12152: Compiles a recursive call to the defining word, not to the defined word.
12153: 
12154: @item argument input source different than current input source for @code{RESTORE-INPUT}:
12155: @cindex argument input source different than current input source for @code{RESTORE-INPUT}
12156: @cindex argument type mismatch, @code{RESTORE-INPUT}
12157: @cindex @code{RESTORE-INPUT}, Argument type mismatch
12158: @code{-12 THROW}. Note that, once an input file is closed (e.g., because
12159: the end of the file was reached), its source-id may be
12160: reused. Therefore, restoring an input source specification referencing a
12161: closed file may lead to unpredictable results instead of a @code{-12
12162: THROW}.
12163: 
12164: In the future, Gforth may be able to restore input source specifications
12165: from other than the current input source.
12166: 
12167: @item data space containing definitions gets de-allocated:
12168: @cindex data space containing definitions gets de-allocated
12169: Deallocation with @code{allot} is not checked. This typically results in
12170: memory access faults or execution of illegal instructions.
12171: 
12172: @item data space read/write with incorrect alignment:
12173: @cindex data space read/write with incorrect alignment
12174: @cindex alignment faults
12175: @cindex address alignment exception
12176: Processor-dependent. Typically results in a @code{-23 throw} (Address
12177: alignment exception). Under Linux-Intel on a 486 or later processor with
12178: alignment turned on, incorrect alignment results in a @code{-9 throw}
12179: (Invalid memory address). There are reportedly some processors with
12180: alignment restrictions that do not report violations.
12181: 
12182: @item data space pointer not properly aligned, @code{,}, @code{C,}:
12183: @cindex data space pointer not properly aligned, @code{,}, @code{C,}
12184: Like other alignment errors.
12185: 
12186: @item less than u+2 stack items (@code{PICK} and @code{ROLL}):
12187: Like other stack underflows.
12188: 
12189: @item loop control parameters not available:
12190: @cindex loop control parameters not available
12191: Not checked. The counted loop words simply assume that the top of return
12192: stack items are loop control parameters and behave accordingly.
12193: 
12194: @item most recent definition does not have a name (@code{IMMEDIATE}):
12195: @cindex most recent definition does not have a name (@code{IMMEDIATE})
12196: @cindex last word was headerless
12197: @code{abort" last word was headerless"}.
12198: 
12199: @item name not defined by @code{VALUE} used by @code{TO}:
12200: @cindex name not defined by @code{VALUE} used by @code{TO}
12201: @cindex @code{TO} on non-@code{VALUE}s
12202: @cindex Invalid name argument, @code{TO}
12203: @code{-32 throw} (Invalid name argument) (unless name is a local or was
12204: defined by @code{CONSTANT}; in the latter case it just changes the constant).
12205: 
12206: @item name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}):
12207: @cindex name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]})
12208: @cindex undefined word, @code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}
12209: @code{-13 throw} (Undefined word)
12210: 
12211: @item parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN}):
12212: @cindex parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN})
12213: Gforth behaves as if they were of the same type. I.e., you can predict
12214: the behaviour by interpreting all parameters as, e.g., signed.
12215: 
12216: @item @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}:
12217: @cindex @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}
12218: Assume @code{: X POSTPONE TO ; IMMEDIATE}. @code{X} performs the
12219: compilation semantics of @code{TO}.
12220: 
12221: @item String longer than a counted string returned by @code{WORD}:
12222: @cindex string longer than a counted string returned by @code{WORD}
12223: @cindex @code{WORD}, string overflow
12224: Not checked. The string will be ok, but the count will, of course,
12225: contain only the least significant bits of the length.
12226: 
12227: @item u greater than or equal to the number of bits in a cell (@code{LSHIFT}, @code{RSHIFT}):
12228: @cindex @code{LSHIFT}, large shift counts
12229: @cindex @code{RSHIFT}, large shift counts
12230: Processor-dependent. Typical behaviours are returning 0 and using only
12231: the low bits of the shift count.
12232: 
12233: @item word not defined via @code{CREATE}:
12234: @cindex @code{>BODY} of non-@code{CREATE}d words
12235: @code{>BODY} produces the PFA of the word no matter how it was defined.
12236: 
12237: @cindex @code{DOES>} of non-@code{CREATE}d words
12238: @code{DOES>} changes the execution semantics of the last defined word no
12239: matter how it was defined. E.g., @code{CONSTANT DOES>} is equivalent to
12240: @code{CREATE , DOES>}.
12241: 
12242: @item words improperly used outside @code{<#} and @code{#>}:
12243: Not checked. As usual, you can expect memory faults.
12244: 
12245: @end table
12246: 
12247: 
12248: @c ---------------------------------------------------------------------
12249: @node core-other,  , core-ambcond, The Core Words
12250: @subsection Other system documentation
12251: @c ---------------------------------------------------------------------
12252: @cindex other system documentation, core words
12253: @cindex core words, other system documentation
12254: 
12255: @table @i
12256: @item nonstandard words using @code{PAD}:
12257: @cindex @code{PAD} use by nonstandard words
12258: None.
12259: 
12260: @item operator's terminal facilities available:
12261: @cindex operator's terminal facilities available
12262: After processing the command line, Gforth goes into interactive mode,
12263: and you can give commands to Gforth interactively. The actual facilities
12264: available depend on how you invoke Gforth.
12265: 
12266: @item program data space available:
12267: @cindex program data space available
12268: @cindex data space available
12269: @code{UNUSED .} gives the remaining dictionary space. The total
12270: dictionary space can be specified with the @code{-m} switch
12271: (@pxref{Invoking Gforth}) when Gforth starts up.
12272: 
12273: @item return stack space available:
12274: @cindex return stack space available
12275: You can compute the total return stack space in cells with
12276: @code{s" RETURN-STACK-CELLS" environment? drop .}. You can specify it at
12277: startup time with the @code{-r} switch (@pxref{Invoking Gforth}).
12278: 
12279: @item stack space available:
12280: @cindex stack space available
12281: You can compute the total data stack space in cells with
12282: @code{s" STACK-CELLS" environment? drop .}. You can specify it at
12283: startup time with the @code{-d} switch (@pxref{Invoking Gforth}).
12284: 
12285: @item system dictionary space required, in address units:
12286: @cindex system dictionary space required, in address units
12287: Type @code{here forthstart - .} after startup. At the time of this
12288: writing, this gives 80080 (bytes) on a 32-bit system.
12289: @end table
12290: 
12291: 
12292: @c =====================================================================
12293: @node The optional Block word set, The optional Double Number word set, The Core Words, ANS conformance
12294: @section The optional Block word set
12295: @c =====================================================================
12296: @cindex system documentation, block words
12297: @cindex block words, system documentation
12298: 
12299: @menu
12300: * block-idef::                  Implementation Defined Options
12301: * block-ambcond::               Ambiguous Conditions               
12302: * block-other::                 Other System Documentation                 
12303: @end menu
12304: 
12305: 
12306: @c ---------------------------------------------------------------------
12307: @node block-idef, block-ambcond, The optional Block word set, The optional Block word set
12308: @subsection Implementation Defined Options
12309: @c ---------------------------------------------------------------------
12310: @cindex implementation-defined options, block words
12311: @cindex block words, implementation-defined options
12312: 
12313: @table @i
12314: @item the format for display by @code{LIST}:
12315: @cindex @code{LIST} display format
12316: First the screen number is displayed, then 16 lines of 64 characters,
12317: each line preceded by the line number.
12318: 
12319: @item the length of a line affected by @code{\}:
12320: @cindex length of a line affected by @code{\}
12321: @cindex @code{\}, line length in blocks
12322: 64 characters.
12323: @end table
12324: 
12325: 
12326: @c ---------------------------------------------------------------------
12327: @node block-ambcond, block-other, block-idef, The optional Block word set
12328: @subsection Ambiguous conditions
12329: @c ---------------------------------------------------------------------
12330: @cindex block words, ambiguous conditions
12331: @cindex ambiguous conditions, block words
12332: 
12333: @table @i
12334: @item correct block read was not possible:
12335: @cindex block read not possible
12336: Typically results in a @code{throw} of some OS-derived value (between
12337: -512 and -2048). If the blocks file was just not long enough, blanks are
12338: supplied for the missing portion.
12339: 
12340: @item I/O exception in block transfer:
12341: @cindex I/O exception in block transfer
12342: @cindex block transfer, I/O exception
12343: Typically results in a @code{throw} of some OS-derived value (between
12344: -512 and -2048).
12345: 
12346: @item invalid block number:
12347: @cindex invalid block number
12348: @cindex block number invalid
12349: @code{-35 throw} (Invalid block number)
12350: 
12351: @item a program directly alters the contents of @code{BLK}:
12352: @cindex @code{BLK}, altering @code{BLK}
12353: The input stream is switched to that other block, at the same
12354: position. If the storing to @code{BLK} happens when interpreting
12355: non-block input, the system will get quite confused when the block ends.
12356: 
12357: @item no current block buffer for @code{UPDATE}:
12358: @cindex @code{UPDATE}, no current block buffer
12359: @code{UPDATE} has no effect.
12360: 
12361: @end table
12362: 
12363: @c ---------------------------------------------------------------------
12364: @node block-other,  , block-ambcond, The optional Block word set
12365: @subsection Other system documentation
12366: @c ---------------------------------------------------------------------
12367: @cindex other system documentation, block words
12368: @cindex block words, other system documentation
12369: 
12370: @table @i
12371: @item any restrictions a multiprogramming system places on the use of buffer addresses:
12372: No restrictions (yet).
12373: 
12374: @item the number of blocks available for source and data:
12375: depends on your disk space.
12376: 
12377: @end table
12378: 
12379: 
12380: @c =====================================================================
12381: @node The optional Double Number word set, The optional Exception word set, The optional Block word set, ANS conformance
12382: @section The optional Double Number word set
12383: @c =====================================================================
12384: @cindex system documentation, double words
12385: @cindex double words, system documentation
12386: 
12387: @menu
12388: * double-ambcond::              Ambiguous Conditions              
12389: @end menu
12390: 
12391: 
12392: @c ---------------------------------------------------------------------
12393: @node double-ambcond,  , The optional Double Number word set, The optional Double Number word set
12394: @subsection Ambiguous conditions
12395: @c ---------------------------------------------------------------------
12396: @cindex double words, ambiguous conditions
12397: @cindex ambiguous conditions, double words
12398: 
12399: @table @i
12400: @item @i{d} outside of range of @i{n} in @code{D>S}:
12401: @cindex @code{D>S}, @i{d} out of range of @i{n} 
12402: The least significant cell of @i{d} is produced.
12403: 
12404: @end table
12405: 
12406: 
12407: @c =====================================================================
12408: @node The optional Exception word set, The optional Facility word set, The optional Double Number word set, ANS conformance
12409: @section The optional Exception word set
12410: @c =====================================================================
12411: @cindex system documentation, exception words
12412: @cindex exception words, system documentation
12413: 
12414: @menu
12415: * exception-idef::              Implementation Defined Options              
12416: @end menu
12417: 
12418: 
12419: @c ---------------------------------------------------------------------
12420: @node exception-idef,  , The optional Exception word set, The optional Exception word set
12421: @subsection Implementation Defined Options
12422: @c ---------------------------------------------------------------------
12423: @cindex implementation-defined options, exception words
12424: @cindex exception words, implementation-defined options
12425: 
12426: @table @i
12427: @item @code{THROW}-codes used in the system:
12428: @cindex @code{THROW}-codes used in the system
12429: The codes -256@minus{}-511 are used for reporting signals. The mapping
12430: from OS signal numbers to throw codes is -256@minus{}@i{signal}. The
12431: codes -512@minus{}-2047 are used for OS errors (for file and memory
12432: allocation operations). The mapping from OS error numbers to throw codes
12433: is -512@minus{}@code{errno}. One side effect of this mapping is that
12434: undefined OS errors produce a message with a strange number; e.g.,
12435: @code{-1000 THROW} results in @code{Unknown error 488} on my system.
12436: @end table
12437: 
12438: @c =====================================================================
12439: @node The optional Facility word set, The optional File-Access word set, The optional Exception word set, ANS conformance
12440: @section The optional Facility word set
12441: @c =====================================================================
12442: @cindex system documentation, facility words
12443: @cindex facility words, system documentation
12444: 
12445: @menu
12446: * facility-idef::               Implementation Defined Options               
12447: * facility-ambcond::            Ambiguous Conditions            
12448: @end menu
12449: 
12450: 
12451: @c ---------------------------------------------------------------------
12452: @node facility-idef, facility-ambcond, The optional Facility word set, The optional Facility word set
12453: @subsection Implementation Defined Options
12454: @c ---------------------------------------------------------------------
12455: @cindex implementation-defined options, facility words
12456: @cindex facility words, implementation-defined options
12457: 
12458: @table @i
12459: @item encoding of keyboard events (@code{EKEY}):
12460: @cindex keyboard events, encoding in @code{EKEY}
12461: @cindex @code{EKEY}, encoding of keyboard events
12462: Keys corresponding to ASCII characters are encoded as ASCII characters.
12463: Other keys are encoded with the constants @code{k-left}, @code{k-right},
12464: @code{k-up}, @code{k-down}, @code{k-home}, @code{k-end}, @code{k1},
12465: @code{k2}, @code{k3}, @code{k4}, @code{k5}, @code{k6}, @code{k7},
12466: @code{k8}, @code{k9}, @code{k10}, @code{k11}, @code{k12}.
12467: 
12468: 
12469: @item duration of a system clock tick:
12470: @cindex duration of a system clock tick
12471: @cindex clock tick duration
12472: System dependent. With respect to @code{MS}, the time is specified in
12473: microseconds. How well the OS and the hardware implement this, is
12474: another question.
12475: 
12476: @item repeatability to be expected from the execution of @code{MS}:
12477: @cindex repeatability to be expected from the execution of @code{MS}
12478: @cindex @code{MS}, repeatability to be expected
12479: System dependent. On Unix, a lot depends on load. If the system is
12480: lightly loaded, and the delay is short enough that Gforth does not get
12481: swapped out, the performance should be acceptable. Under MS-DOS and
12482: other single-tasking systems, it should be good.
12483: 
12484: @end table
12485: 
12486: 
12487: @c ---------------------------------------------------------------------
12488: @node facility-ambcond,  , facility-idef, The optional Facility word set
12489: @subsection Ambiguous conditions
12490: @c ---------------------------------------------------------------------
12491: @cindex facility words, ambiguous conditions
12492: @cindex ambiguous conditions, facility words
12493: 
12494: @table @i
12495: @item @code{AT-XY} can't be performed on user output device:
12496: @cindex @code{AT-XY} can't be performed on user output device
12497: Largely terminal dependent. No range checks are done on the arguments.
12498: No errors are reported. You may see some garbage appearing, you may see
12499: simply nothing happen.
12500: 
12501: @end table
12502: 
12503: 
12504: @c =====================================================================
12505: @node The optional File-Access word set, The optional Floating-Point word set, The optional Facility word set, ANS conformance
12506: @section The optional File-Access word set
12507: @c =====================================================================
12508: @cindex system documentation, file words
12509: @cindex file words, system documentation
12510: 
12511: @menu
12512: * file-idef::                   Implementation Defined Options
12513: * file-ambcond::                Ambiguous Conditions                
12514: @end menu
12515: 
12516: @c ---------------------------------------------------------------------
12517: @node file-idef, file-ambcond, The optional File-Access word set, The optional File-Access word set
12518: @subsection Implementation Defined Options
12519: @c ---------------------------------------------------------------------
12520: @cindex implementation-defined options, file words
12521: @cindex file words, implementation-defined options
12522: 
12523: @table @i
12524: @item file access methods used:
12525: @cindex file access methods used
12526: @code{R/O}, @code{R/W} and @code{BIN} work as you would
12527: expect. @code{W/O} translates into the C file opening mode @code{w} (or
12528: @code{wb}): The file is cleared, if it exists, and created, if it does
12529: not (with both @code{open-file} and @code{create-file}).  Under Unix
12530: @code{create-file} creates a file with 666 permissions modified by your
12531: umask.
12532: 
12533: @item file exceptions:
12534: @cindex file exceptions
12535: The file words do not raise exceptions (except, perhaps, memory access
12536: faults when you pass illegal addresses or file-ids).
12537: 
12538: @item file line terminator:
12539: @cindex file line terminator
12540: System-dependent. Gforth uses C's newline character as line
12541: terminator. What the actual character code(s) of this are is
12542: system-dependent.
12543: 
12544: @item file name format:
12545: @cindex file name format
12546: System dependent. Gforth just uses the file name format of your OS.
12547: 
12548: @item information returned by @code{FILE-STATUS}:
12549: @cindex @code{FILE-STATUS}, returned information
12550: @code{FILE-STATUS} returns the most powerful file access mode allowed
12551: for the file: Either @code{R/O}, @code{W/O} or @code{R/W}. If the file
12552: cannot be accessed, @code{R/O BIN} is returned. @code{BIN} is applicable
12553: along with the returned mode.
12554: 
12555: @item input file state after an exception when including source:
12556: @cindex exception when including source
12557: All files that are left via the exception are closed.
12558: 
12559: @item @i{ior} values and meaning:
12560: @cindex @i{ior} values and meaning
12561: @cindex @i{wior} values and meaning
12562: The @i{ior}s returned by the file and memory allocation words are
12563: intended as throw codes. They typically are in the range
12564: -512@minus{}-2047 of OS errors.  The mapping from OS error numbers to
12565: @i{ior}s is -512@minus{}@i{errno}.
12566: 
12567: @item maximum depth of file input nesting:
12568: @cindex maximum depth of file input nesting
12569: @cindex file input nesting, maximum depth
12570: limited by the amount of return stack, locals/TIB stack, and the number
12571: of open files available. This should not give you troubles.
12572: 
12573: @item maximum size of input line:
12574: @cindex maximum size of input line
12575: @cindex input line size, maximum
12576: @code{/line}. Currently 255.
12577: 
12578: @item methods of mapping block ranges to files:
12579: @cindex mapping block ranges to files
12580: @cindex files containing blocks
12581: @cindex blocks in files
12582: By default, blocks are accessed in the file @file{blocks.fb} in the
12583: current working directory. The file can be switched with @code{USE}.
12584: 
12585: @item number of string buffers provided by @code{S"}:
12586: @cindex @code{S"}, number of string buffers
12587: 1
12588: 
12589: @item size of string buffer used by @code{S"}:
12590: @cindex @code{S"}, size of string buffer
12591: @code{/line}. currently 255.
12592: 
12593: @end table
12594: 
12595: @c ---------------------------------------------------------------------
12596: @node file-ambcond,  , file-idef, The optional File-Access word set
12597: @subsection Ambiguous conditions
12598: @c ---------------------------------------------------------------------
12599: @cindex file words, ambiguous conditions
12600: @cindex ambiguous conditions, file words
12601: 
12602: @table @i
12603: @item attempting to position a file outside its boundaries:
12604: @cindex @code{REPOSITION-FILE}, outside the file's boundaries
12605: @code{REPOSITION-FILE} is performed as usual: Afterwards,
12606: @code{FILE-POSITION} returns the value given to @code{REPOSITION-FILE}.
12607: 
12608: @item attempting to read from file positions not yet written:
12609: @cindex reading from file positions not yet written
12610: End-of-file, i.e., zero characters are read and no error is reported.
12611: 
12612: @item @i{file-id} is invalid (@code{INCLUDE-FILE}):
12613: @cindex @code{INCLUDE-FILE}, @i{file-id} is invalid 
12614: An appropriate exception may be thrown, but a memory fault or other
12615: problem is more probable.
12616: 
12617: @item I/O exception reading or closing @i{file-id} (@code{INCLUDE-FILE}, @code{INCLUDED}):
12618: @cindex @code{INCLUDE-FILE}, I/O exception reading or closing @i{file-id}
12619: @cindex @code{INCLUDED}, I/O exception reading or closing @i{file-id}
12620: The @i{ior} produced by the operation, that discovered the problem, is
12621: thrown.
12622: 
12623: @item named file cannot be opened (@code{INCLUDED}):
12624: @cindex @code{INCLUDED}, named file cannot be opened
12625: The @i{ior} produced by @code{open-file} is thrown.
12626: 
12627: @item requesting an unmapped block number:
12628: @cindex unmapped block numbers
12629: There are no unmapped legal block numbers. On some operating systems,
12630: writing a block with a large number may overflow the file system and
12631: have an error message as consequence.
12632: 
12633: @item using @code{source-id} when @code{blk} is non-zero:
12634: @cindex @code{SOURCE-ID}, behaviour when @code{BLK} is non-zero
12635: @code{source-id} performs its function. Typically it will give the id of
12636: the source which loaded the block. (Better ideas?)
12637: 
12638: @end table
12639: 
12640: 
12641: @c =====================================================================
12642: @node  The optional Floating-Point word set, The optional Locals word set, The optional File-Access word set, ANS conformance
12643: @section The optional Floating-Point word set
12644: @c =====================================================================
12645: @cindex system documentation, floating-point words
12646: @cindex floating-point words, system documentation
12647: 
12648: @menu
12649: * floating-idef::               Implementation Defined Options
12650: * floating-ambcond::            Ambiguous Conditions            
12651: @end menu
12652: 
12653: 
12654: @c ---------------------------------------------------------------------
12655: @node floating-idef, floating-ambcond, The optional Floating-Point word set, The optional Floating-Point word set
12656: @subsection Implementation Defined Options
12657: @c ---------------------------------------------------------------------
12658: @cindex implementation-defined options, floating-point words
12659: @cindex floating-point words, implementation-defined options
12660: 
12661: @table @i
12662: @item format and range of floating point numbers:
12663: @cindex format and range of floating point numbers
12664: @cindex floating point numbers, format and range
12665: System-dependent; the @code{double} type of C.
12666: 
12667: @item results of @code{REPRESENT} when @i{float} is out of range:
12668: @cindex  @code{REPRESENT}, results when @i{float} is out of range
12669: System dependent; @code{REPRESENT} is implemented using the C library
12670: function @code{ecvt()} and inherits its behaviour in this respect.
12671: 
12672: @item rounding or truncation of floating-point numbers:
12673: @cindex rounding of floating-point numbers
12674: @cindex truncation of floating-point numbers
12675: @cindex floating-point numbers, rounding or truncation
12676: System dependent; the rounding behaviour is inherited from the hosting C
12677: compiler. IEEE-FP-based (i.e., most) systems by default round to
12678: nearest, and break ties by rounding to even (i.e., such that the last
12679: bit of the mantissa is 0).
12680: 
12681: @item size of floating-point stack:
12682: @cindex floating-point stack size
12683: @code{s" FLOATING-STACK" environment? drop .} gives the total size of
12684: the floating-point stack (in floats). You can specify this on startup
12685: with the command-line option @code{-f} (@pxref{Invoking Gforth}).
12686: 
12687: @item width of floating-point stack:
12688: @cindex floating-point stack width 
12689: @code{1 floats}.
12690: 
12691: @end table
12692: 
12693: 
12694: @c ---------------------------------------------------------------------
12695: @node floating-ambcond,  , floating-idef, The optional Floating-Point word set
12696: @subsection Ambiguous conditions
12697: @c ---------------------------------------------------------------------
12698: @cindex floating-point words, ambiguous conditions
12699: @cindex ambiguous conditions, floating-point words
12700: 
12701: @table @i
12702: @item @code{df@@} or @code{df!} used with an address that is not double-float  aligned:
12703: @cindex @code{df@@} or @code{df!} used with an address that is not double-float  aligned
12704: System-dependent. Typically results in a @code{-23 THROW} like other
12705: alignment violations.
12706: 
12707: @item @code{f@@} or @code{f!} used with an address that is not float  aligned:
12708: @cindex @code{f@@} used with an address that is not float aligned
12709: @cindex @code{f!} used with an address that is not float aligned
12710: System-dependent. Typically results in a @code{-23 THROW} like other
12711: alignment violations.
12712: 
12713: @item floating-point result out of range:
12714: @cindex floating-point result out of range
12715: System-dependent. Can result in a @code{-55 THROW} (Floating-point
12716: unidentified fault), or can produce a special value representing, e.g.,
12717: Infinity.
12718: 
12719: @item @code{sf@@} or @code{sf!} used with an address that is not single-float  aligned:
12720: @cindex @code{sf@@} or @code{sf!} used with an address that is not single-float  aligned
12721: System-dependent. Typically results in an alignment fault like other
12722: alignment violations.
12723: 
12724: @item @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.}):
12725: @cindex @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.})
12726: The floating-point number is converted into decimal nonetheless.
12727: 
12728: @item Both arguments are equal to zero (@code{FATAN2}):
12729: @cindex @code{FATAN2}, both arguments are equal to zero
12730: System-dependent. @code{FATAN2} is implemented using the C library
12731: function @code{atan2()}.
12732: 
12733: @item Using @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero:
12734: @cindex @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero
12735: System-dependent. Anyway, typically the cos of @i{r1} will not be zero
12736: because of small errors and the tan will be a very large (or very small)
12737: but finite number.
12738: 
12739: @item @i{d} cannot be presented precisely as a float in @code{D>F}:
12740: @cindex @code{D>F}, @i{d} cannot be presented precisely as a float
12741: The result is rounded to the nearest float.
12742: 
12743: @item dividing by zero:
12744: @cindex dividing by zero, floating-point
12745: @cindex floating-point dividing by zero
12746: @cindex floating-point unidentified fault, FP divide-by-zero
12747: @code{-55 throw} (Floating-point unidentified fault)
12748: 
12749: @item exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@}):
12750: @cindex exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@})
12751: System dependent. On IEEE-FP based systems the number is converted into
12752: an infinity.
12753: 
12754: @item @i{float}<1 (@code{FACOSH}):
12755: @cindex @code{FACOSH}, @i{float}<1
12756: @cindex floating-point unidentified fault, @code{FACOSH}
12757: @code{-55 throw} (Floating-point unidentified fault)
12758: 
12759: @item @i{float}=<-1 (@code{FLNP1}):
12760: @cindex @code{FLNP1}, @i{float}=<-1
12761: @cindex floating-point unidentified fault, @code{FLNP1}
12762: @code{-55 throw} (Floating-point unidentified fault). On IEEE-FP systems
12763: negative infinity is typically produced for @i{float}=-1.
12764: 
12765: @item @i{float}=<0 (@code{FLN}, @code{FLOG}):
12766: @cindex @code{FLN}, @i{float}=<0
12767: @cindex @code{FLOG}, @i{float}=<0
12768: @cindex floating-point unidentified fault, @code{FLN} or @code{FLOG}
12769: @code{-55 throw} (Floating-point unidentified fault). On IEEE-FP systems
12770: negative infinity is typically produced for @i{float}=0.
12771: 
12772: @item @i{float}<0 (@code{FASINH}, @code{FSQRT}):
12773: @cindex @code{FASINH}, @i{float}<0
12774: @cindex @code{FSQRT}, @i{float}<0
12775: @cindex floating-point unidentified fault, @code{FASINH} or @code{FSQRT}
12776: @code{-55 throw} (Floating-point unidentified fault). @code{fasinh}
12777: produces values for these inputs on my Linux box (Bug in the C library?)
12778: 
12779: @item |@i{float}|>1 (@code{FACOS}, @code{FASIN}, @code{FATANH}):
12780: @cindex @code{FACOS}, |@i{float}|>1
12781: @cindex @code{FASIN}, |@i{float}|>1
12782: @cindex @code{FATANH}, |@i{float}|>1
12783: @cindex floating-point unidentified fault, @code{FACOS}, @code{FASIN} or @code{FATANH}
12784: @code{-55 throw} (Floating-point unidentified fault).
12785: 
12786: @item integer part of float cannot be represented by @i{d} in @code{F>D}:
12787: @cindex @code{F>D}, integer part of float cannot be represented by @i{d}
12788: @cindex floating-point unidentified fault, @code{F>D}
12789: @code{-55 throw} (Floating-point unidentified fault).
12790: 
12791: @item string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.}):
12792: @cindex string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.})
12793: This does not happen.
12794: @end table
12795: 
12796: @c =====================================================================
12797: @node  The optional Locals word set, The optional Memory-Allocation word set, The optional Floating-Point word set, ANS conformance
12798: @section The optional Locals word set
12799: @c =====================================================================
12800: @cindex system documentation, locals words
12801: @cindex locals words, system documentation
12802: 
12803: @menu
12804: * locals-idef::                 Implementation Defined Options                 
12805: * locals-ambcond::              Ambiguous Conditions              
12806: @end menu
12807: 
12808: 
12809: @c ---------------------------------------------------------------------
12810: @node locals-idef, locals-ambcond, The optional Locals word set, The optional Locals word set
12811: @subsection Implementation Defined Options
12812: @c ---------------------------------------------------------------------
12813: @cindex implementation-defined options, locals words
12814: @cindex locals words, implementation-defined options
12815: 
12816: @table @i
12817: @item maximum number of locals in a definition:
12818: @cindex maximum number of locals in a definition
12819: @cindex locals, maximum number in a definition
12820: @code{s" #locals" environment? drop .}. Currently 15. This is a lower
12821: bound, e.g., on a 32-bit machine there can be 41 locals of up to 8
12822: characters. The number of locals in a definition is bounded by the size
12823: of locals-buffer, which contains the names of the locals.
12824: 
12825: @end table
12826: 
12827: 
12828: @c ---------------------------------------------------------------------
12829: @node locals-ambcond,  , locals-idef, The optional Locals word set
12830: @subsection Ambiguous conditions
12831: @c ---------------------------------------------------------------------
12832: @cindex locals words, ambiguous conditions
12833: @cindex ambiguous conditions, locals words
12834: 
12835: @table @i
12836: @item executing a named local in interpretation state:
12837: @cindex local in interpretation state
12838: @cindex Interpreting a compile-only word, for a local
12839: Locals have no interpretation semantics. If you try to perform the
12840: interpretation semantics, you will get a @code{-14 throw} somewhere
12841: (Interpreting a compile-only word). If you perform the compilation
12842: semantics, the locals access will be compiled (irrespective of state).
12843: 
12844: @item @i{name} not defined by @code{VALUE} or @code{(LOCAL)} (@code{TO}):
12845: @cindex name not defined by @code{VALUE} or @code{(LOCAL)} used by @code{TO}
12846: @cindex @code{TO} on non-@code{VALUE}s and non-locals
12847: @cindex Invalid name argument, @code{TO}
12848: @code{-32 throw} (Invalid name argument)
12849: 
12850: @end table
12851: 
12852: 
12853: @c =====================================================================
12854: @node  The optional Memory-Allocation word set, The optional Programming-Tools word set, The optional Locals word set, ANS conformance
12855: @section The optional Memory-Allocation word set
12856: @c =====================================================================
12857: @cindex system documentation, memory-allocation words
12858: @cindex memory-allocation words, system documentation
12859: 
12860: @menu
12861: * memory-idef::                 Implementation Defined Options                 
12862: @end menu
12863: 
12864: 
12865: @c ---------------------------------------------------------------------
12866: @node memory-idef,  , The optional Memory-Allocation word set, The optional Memory-Allocation word set
12867: @subsection Implementation Defined Options
12868: @c ---------------------------------------------------------------------
12869: @cindex implementation-defined options, memory-allocation words
12870: @cindex memory-allocation words, implementation-defined options
12871: 
12872: @table @i
12873: @item values and meaning of @i{ior}:
12874: @cindex  @i{ior} values and meaning
12875: The @i{ior}s returned by the file and memory allocation words are
12876: intended as throw codes. They typically are in the range
12877: -512@minus{}-2047 of OS errors.  The mapping from OS error numbers to
12878: @i{ior}s is -512@minus{}@i{errno}.
12879: 
12880: @end table
12881: 
12882: @c =====================================================================
12883: @node  The optional Programming-Tools word set, The optional Search-Order word set, The optional Memory-Allocation word set, ANS conformance
12884: @section The optional Programming-Tools word set
12885: @c =====================================================================
12886: @cindex system documentation, programming-tools words
12887: @cindex programming-tools words, system documentation
12888: 
12889: @menu
12890: * programming-idef::            Implementation Defined Options            
12891: * programming-ambcond::         Ambiguous Conditions         
12892: @end menu
12893: 
12894: 
12895: @c ---------------------------------------------------------------------
12896: @node programming-idef, programming-ambcond, The optional Programming-Tools word set, The optional Programming-Tools word set
12897: @subsection Implementation Defined Options
12898: @c ---------------------------------------------------------------------
12899: @cindex implementation-defined options, programming-tools words
12900: @cindex programming-tools words, implementation-defined options
12901: 
12902: @table @i
12903: @item ending sequence for input following @code{;CODE} and @code{CODE}:
12904: @cindex @code{;CODE} ending sequence
12905: @cindex @code{CODE} ending sequence
12906: @code{END-CODE}
12907: 
12908: @item manner of processing input following @code{;CODE} and @code{CODE}:
12909: @cindex @code{;CODE}, processing input
12910: @cindex @code{CODE}, processing input
12911: The @code{ASSEMBLER} vocabulary is pushed on the search order stack, and
12912: the input is processed by the text interpreter, (starting) in interpret
12913: state.
12914: 
12915: @item search order capability for @code{EDITOR} and @code{ASSEMBLER}:
12916: @cindex @code{ASSEMBLER}, search order capability
12917: The ANS Forth search order word set.
12918: 
12919: @item source and format of display by @code{SEE}:
12920: @cindex @code{SEE}, source and format of output
12921: The source for @code{see} is the intermediate code used by the inner
12922: interpreter.  The current @code{see} tries to output Forth source code
12923: as well as possible.
12924: 
12925: @end table
12926: 
12927: @c ---------------------------------------------------------------------
12928: @node programming-ambcond,  , programming-idef, The optional Programming-Tools word set
12929: @subsection Ambiguous conditions
12930: @c ---------------------------------------------------------------------
12931: @cindex programming-tools words, ambiguous conditions
12932: @cindex ambiguous conditions, programming-tools words
12933: 
12934: @table @i
12935: 
12936: @item deleting the compilation word list (@code{FORGET}):
12937: @cindex @code{FORGET}, deleting the compilation word list
12938: Not implemented (yet).
12939: 
12940: @item fewer than @i{u}+1 items on the control-flow stack (@code{CS-PICK}, @code{CS-ROLL}):
12941: @cindex @code{CS-PICK}, fewer than @i{u}+1 items on the control flow-stack
12942: @cindex @code{CS-ROLL}, fewer than @i{u}+1 items on the control flow-stack
12943: @cindex control-flow stack underflow
12944: This typically results in an @code{abort"} with a descriptive error
12945: message (may change into a @code{-22 throw} (Control structure mismatch)
12946: in the future). You may also get a memory access error. If you are
12947: unlucky, this ambiguous condition is not caught.
12948: 
12949: @item @i{name} can't be found (@code{FORGET}):
12950: @cindex @code{FORGET}, @i{name} can't be found
12951: Not implemented (yet).
12952: 
12953: @item @i{name} not defined via @code{CREATE}:
12954: @cindex @code{;CODE}, @i{name} not defined via @code{CREATE}
12955: @code{;CODE} behaves like @code{DOES>} in this respect, i.e., it changes
12956: the execution semantics of the last defined word no matter how it was
12957: defined.
12958: 
12959: @item @code{POSTPONE} applied to @code{[IF]}:
12960: @cindex @code{POSTPONE} applied to @code{[IF]}
12961: @cindex @code{[IF]} and @code{POSTPONE}
12962: After defining @code{: X POSTPONE [IF] ; IMMEDIATE}. @code{X} is
12963: equivalent to @code{[IF]}.
12964: 
12965: @item reaching the end of the input source before matching @code{[ELSE]} or @code{[THEN]}:
12966: @cindex @code{[IF]}, end of the input source before matching @code{[ELSE]} or @code{[THEN]}
12967: Continue in the same state of conditional compilation in the next outer
12968: input source. Currently there is no warning to the user about this.
12969: 
12970: @item removing a needed definition (@code{FORGET}):
12971: @cindex @code{FORGET}, removing a needed definition
12972: Not implemented (yet).
12973: 
12974: @end table
12975: 
12976: 
12977: @c =====================================================================
12978: @node  The optional Search-Order word set,  , The optional Programming-Tools word set, ANS conformance
12979: @section The optional Search-Order word set
12980: @c =====================================================================
12981: @cindex system documentation, search-order words
12982: @cindex search-order words, system documentation
12983: 
12984: @menu
12985: * search-idef::                 Implementation Defined Options                 
12986: * search-ambcond::              Ambiguous Conditions              
12987: @end menu
12988: 
12989: 
12990: @c ---------------------------------------------------------------------
12991: @node search-idef, search-ambcond, The optional Search-Order word set, The optional Search-Order word set
12992: @subsection Implementation Defined Options
12993: @c ---------------------------------------------------------------------
12994: @cindex implementation-defined options, search-order words
12995: @cindex search-order words, implementation-defined options
12996: 
12997: @table @i
12998: @item maximum number of word lists in search order:
12999: @cindex maximum number of word lists in search order
13000: @cindex search order, maximum depth
13001: @code{s" wordlists" environment? drop .}. Currently 16.
13002: 
13003: @item minimum search order:
13004: @cindex minimum search order
13005: @cindex search order, minimum
13006: @code{root root}.
13007: 
13008: @end table
13009: 
13010: @c ---------------------------------------------------------------------
13011: @node search-ambcond,  , search-idef, The optional Search-Order word set
13012: @subsection Ambiguous conditions
13013: @c ---------------------------------------------------------------------
13014: @cindex search-order words, ambiguous conditions
13015: @cindex ambiguous conditions, search-order words
13016: 
13017: @table @i
13018: @item changing the compilation word list (during compilation):
13019: @cindex changing the compilation word list (during compilation)
13020: @cindex compilation word list, change before definition ends
13021: The word is entered into the word list that was the compilation word list
13022: at the start of the definition. Any changes to the name field (e.g.,
13023: @code{immediate}) or the code field (e.g., when executing @code{DOES>})
13024: are applied to the latest defined word (as reported by @code{last} or
13025: @code{lastxt}), if possible, irrespective of the compilation word list.
13026: 
13027: @item search order empty (@code{previous}):
13028: @cindex @code{previous}, search order empty
13029: @cindex vocstack empty, @code{previous}
13030: @code{abort" Vocstack empty"}.
13031: 
13032: @item too many word lists in search order (@code{also}):
13033: @cindex @code{also}, too many word lists in search order
13034: @cindex vocstack full, @code{also}
13035: @code{abort" Vocstack full"}.
13036: 
13037: @end table
13038: 
13039: @c ***************************************************************
13040: @node Standard vs Extensions, Model, ANS conformance, Top
13041: @chapter Should I use Gforth extensions?
13042: @cindex Gforth extensions
13043: 
13044: As you read through the rest of this manual, you will see documentation
13045: for @i{Standard} words, and documentation for some appealing Gforth
13046: @i{extensions}. You might ask yourself the question: @i{``Should I
13047: restrict myself to the standard, or should I use the extensions?''}
13048: 
13049: The answer depends on the goals you have for the program you are working
13050: on:
13051: 
13052: @itemize @bullet
13053: 
13054: @item Is it just for yourself or do you want to share it with others?
13055: 
13056: @item
13057: If you want to share it, do the others all use Gforth?
13058: 
13059: @item
13060: If it is just for yourself, do you want to restrict yourself to Gforth?
13061: 
13062: @end itemize
13063: 
13064: If restricting the program to Gforth is ok, then there is no reason not
13065: to use extensions.  It is still a good idea to keep to the standard
13066: where it is easy, in case you want to reuse these parts in another
13067: program that you want to be portable.
13068: 
13069: If you want to be able to port the program to other Forth systems, there
13070: are the following points to consider:
13071: 
13072: @itemize @bullet
13073: 
13074: @item
13075: Most Forth systems that are being maintained support the ANS Forth
13076: standard.  So if your program complies with the standard, it will be
13077: portable among many systems.
13078: 
13079: @item
13080: A number of the Gforth extensions can be implemented in ANS Forth using
13081: public-domain files provided in the @file{compat/} directory. These are
13082: mentioned in the text in passing.  There is no reason not to use these
13083: extensions, your program will still be ANS Forth compliant; just include
13084: the appropriate compat files with your program.
13085: 
13086: @item
13087: The tool @file{ans-report.fs} (@pxref{ANS Report}) makes it easy to
13088: analyse your program and determine what non-Standard words it relies
13089: upon.  However, it does not check whether you use standard words in a
13090: non-standard way.
13091: 
13092: @item
13093: Some techniques are not standardized by ANS Forth, and are hard or
13094: impossible to implement in a standard way, but can be implemented in
13095: most Forth systems easily, and usually in similar ways (e.g., accessing
13096: word headers).  Forth has a rich historical precedent for programmers
13097: taking advantage of implementation-dependent features of their tools
13098: (for example, relying on a knowledge of the dictionary
13099: structure). Sometimes these techniques are necessary to extract every
13100: last bit of performance from the hardware, sometimes they are just a
13101: programming shorthand.
13102: 
13103: @item
13104: Does using a Gforth extension save more work than the porting this part
13105: to other Forth systems (if any) will cost?
13106: 
13107: @item
13108: Is the additional functionality worth the reduction in portability and
13109: the additional porting problems?
13110: 
13111: @end itemize
13112: 
13113: In order to perform these consideratios, you need to know what's
13114: standard and what's not.  This manual generally states if something is
13115: non-standard, but the authoritative source is the standard document.
13116: Appendix A of the Standard (@var{Rationale}) provides a valuable insight
13117: into the thought processes of the technical committee.
13118: 
13119: Note also that portability between Forth systems is not the only
13120: portability issue; there is also the issue of portability between
13121: different platforms (processor/OS combinations).
13122: 
13123: @c ***************************************************************
13124: @node Model, Integrating Gforth, Standard vs Extensions, Top
13125: @chapter Model
13126: 
13127: This chapter has yet to be written. It will contain information, on
13128: which internal structures you can rely.
13129: 
13130: @c ***************************************************************
13131: @node Integrating Gforth, Emacs and Gforth, Model, Top
13132: @chapter Integrating Gforth into C programs
13133: 
13134: This is not yet implemented.
13135: 
13136: Several people like to use Forth as scripting language for applications
13137: that are otherwise written in C, C++, or some other language.
13138: 
13139: The Forth system ATLAST provides facilities for embedding it into
13140: applications; unfortunately it has several disadvantages: most
13141: importantly, it is not based on ANS Forth, and it is apparently dead
13142: (i.e., not developed further and not supported). The facilities
13143: provided by Gforth in this area are inspired by ATLAST's facilities, so
13144: making the switch should not be hard.
13145: 
13146: We also tried to design the interface such that it can easily be
13147: implemented by other Forth systems, so that we may one day arrive at a
13148: standardized interface. Such a standard interface would allow you to
13149: replace the Forth system without having to rewrite C code.
13150: 
13151: You embed the Gforth interpreter by linking with the library
13152: @code{libgforth.a} (give the compiler the option @code{-lgforth}).  All
13153: global symbols in this library that belong to the interface, have the
13154: prefix @code{forth_}. (Global symbols that are used internally have the
13155: prefix @code{gforth_}).
13156: 
13157: You can include the declarations of Forth types and the functions and
13158: variables of the interface with @code{#include <forth.h>}.
13159: 
13160: Types.
13161: 
13162: Variables.
13163: 
13164: Data and FP Stack pointer. Area sizes.
13165: 
13166: functions.
13167: 
13168: forth_init(imagefile)
13169: forth_evaluate(string) exceptions?
13170: forth_goto(address) (or forth_execute(xt)?)
13171: forth_continue() (a corountining mechanism)
13172: 
13173: Adding primitives.
13174: 
13175: No checking.
13176: 
13177: Signals?
13178: 
13179: Accessing the Stacks
13180: 
13181: @c ******************************************************************
13182: @node Emacs and Gforth, Image Files, Integrating Gforth, Top
13183: @chapter Emacs and Gforth
13184: @cindex Emacs and Gforth
13185: 
13186: @cindex @file{gforth.el}
13187: @cindex @file{forth.el}
13188: @cindex Rydqvist, Goran
13189: @cindex comment editing commands
13190: @cindex @code{\}, editing with Emacs
13191: @cindex debug tracer editing commands
13192: @cindex @code{~~}, removal with Emacs
13193: @cindex Forth mode in Emacs
13194: Gforth comes with @file{gforth.el}, an improved version of
13195: @file{forth.el} by Goran Rydqvist (included in the TILE package). The
13196: improvements are:
13197: 
13198: @itemize @bullet
13199: @item
13200: A better (but still not perfect) handling of indentation.
13201: @item
13202: Comment paragraph filling (@kbd{M-q})
13203: @item
13204: Commenting (@kbd{C-x \}) and uncommenting (@kbd{C-u C-x \}) of regions
13205: @item
13206: Removal of debugging tracers (@kbd{C-x ~}, @pxref{Debugging}).
13207: @item
13208: Support of the @code{info-lookup} feature for looking up the
13209: documentation of a word.
13210: @end itemize
13211: 
13212: I left the stuff I do not use alone, even though some of it only makes
13213: sense for TILE. To get a description of these features, enter Forth mode
13214: and type @kbd{C-h m}.
13215: 
13216: @cindex source location of error or debugging output in Emacs
13217: @cindex error output, finding the source location in Emacs
13218: @cindex debugging output, finding the source location in Emacs
13219: In addition, Gforth supports Emacs quite well: The source code locations
13220: given in error messages, debugging output (from @code{~~}) and failed
13221: assertion messages are in the right format for Emacs' compilation mode
13222: (@pxref{Compilation, , Running Compilations under Emacs, emacs, Emacs
13223: Manual}) so the source location corresponding to an error or other
13224: message is only a few keystrokes away (@kbd{C-x `} for the next error,
13225: @kbd{C-c C-c} for the error under the cursor).
13226: 
13227: @cindex @file{TAGS} file
13228: @cindex @file{etags.fs}
13229: @cindex viewing the source of a word in Emacs
13230: @cindex @code{require}, placement in files
13231: @cindex @code{include}, placement in files
13232: Also, if you @code{require} @file{etags.fs}, a new @file{TAGS} file will
13233: be produced (@pxref{Tags, , Tags Tables, emacs, Emacs Manual}) that
13234: contains the definitions of all words defined afterwards. You can then
13235: find the source for a word using @kbd{M-.}. Note that emacs can use
13236: several tags files at the same time (e.g., one for the Gforth sources
13237: and one for your program, @pxref{Select Tags Table,,Selecting a Tags
13238: Table,emacs, Emacs Manual}). The TAGS file for the preloaded words is
13239: @file{$(datadir)/gforth/$(VERSION)/TAGS} (e.g.,
13240: @file{/usr/local/share/gforth/0.2.0/TAGS}).  To get the best behaviour
13241: with @file{etags.fs}, you should avoid putting definitions both before
13242: and after @code{require} etc., otherwise you will see the same file
13243: visited several times by commands like @code{tags-search}.
13244: 
13245: @cindex viewing the documentation of a word in Emacs
13246: @cindex context-sensitive help
13247: Moreover, for words documented in this manual, you can look up the
13248: glossary entry quickly by using @kbd{C-h TAB}
13249: (@code{info-lookup-symbol}, see @pxref{Documentation, ,Documentation
13250: Commands, emacs, Emacs Manual}).  This feature requires Emacs 20.3 or
13251: later and does not work for words containing @code{:}.
13252: 
13253: 
13254: @cindex @file{.emacs}
13255: To get all these benefits, add the following lines to your @file{.emacs}
13256: file:
13257: 
13258: @example
13259: (autoload 'forth-mode "gforth.el")
13260: (setq auto-mode-alist (cons '("\\.fs\\'" . forth-mode) auto-mode-alist))
13261: @end example
13262: 
13263: @c ******************************************************************
13264: @node Image Files, Engine, Emacs and Gforth, Top
13265: @chapter Image Files
13266: @cindex image file
13267: @cindex @file{.fi} files
13268: @cindex precompiled Forth code
13269: @cindex dictionary in persistent form
13270: @cindex persistent form of dictionary
13271: 
13272: An image file is a file containing an image of the Forth dictionary,
13273: i.e., compiled Forth code and data residing in the dictionary.  By
13274: convention, we use the extension @code{.fi} for image files.
13275: 
13276: @menu
13277: * Image Licensing Issues::      Distribution terms for images.
13278: * Image File Background::       Why have image files?
13279: * Non-Relocatable Image Files::  don't always work.
13280: * Data-Relocatable Image Files::  are better.
13281: * Fully Relocatable Image Files::  better yet.
13282: * Stack and Dictionary Sizes::  Setting the default sizes for an image.
13283: * Running Image Files::         @code{gforth -i @i{file}} or @i{file}.
13284: * Modifying the Startup Sequence::  and turnkey applications.
13285: @end menu
13286: 
13287: @node Image Licensing Issues, Image File Background, Image Files, Image Files
13288: @section Image Licensing Issues
13289: @cindex license for images
13290: @cindex image license
13291: 
13292: An image created with @code{gforthmi} (@pxref{gforthmi}) or
13293: @code{savesystem} (@pxref{Non-Relocatable Image Files}) includes the
13294: original image; i.e., according to copyright law it is a derived work of
13295: the original image.
13296: 
13297: Since Gforth is distributed under the GNU GPL, the newly created image
13298: falls under the GNU GPL, too. In particular, this means that if you
13299: distribute the image, you have to make all of the sources for the image
13300: available, including those you wrote.  For details see @ref{License, ,
13301: GNU General Public License (Section 3)}.
13302: 
13303: If you create an image with @code{cross} (@pxref{cross.fs}), the image
13304: contains only code compiled from the sources you gave it; if none of
13305: these sources is under the GPL, the terms discussed above do not apply
13306: to the image. However, if your image needs an engine (a gforth binary)
13307: that is under the GPL, you should make sure that you distribute both in
13308: a way that is at most a @emph{mere aggregation}, if you don't want the
13309: terms of the GPL to apply to the image.
13310: 
13311: @node Image File Background, Non-Relocatable Image Files, Image Licensing Issues, Image Files
13312: @section Image File Background
13313: @cindex image file background
13314: 
13315: Our Forth system consists not only of primitives, but also of
13316: definitions written in Forth. Since the Forth compiler itself belongs to
13317: those definitions, it is not possible to start the system with the
13318: primitives and the Forth source alone. Therefore we provide the Forth
13319: code as an image file in nearly executable form. When Gforth starts up,
13320: a C routine loads the image file into memory, optionally relocates the
13321: addresses, then sets up the memory (stacks etc.) according to
13322: information in the image file, and (finally) starts executing Forth
13323: code.
13324: 
13325: The image file variants represent different compromises between the
13326: goals of making it easy to generate image files and making them
13327: portable.
13328: 
13329: @cindex relocation at run-time
13330: Win32Forth 3.4 and Mitch Bradley's @code{cforth} use relocation at
13331: run-time. This avoids many of the complications discussed below (image
13332: files are data relocatable without further ado), but costs performance
13333: (one addition per memory access).
13334: 
13335: @cindex relocation at load-time
13336: By contrast, the Gforth loader performs relocation at image load time. The
13337: loader also has to replace tokens that represent primitive calls with the
13338: appropriate code-field addresses (or code addresses in the case of
13339: direct threading).
13340: 
13341: There are three kinds of image files, with different degrees of
13342: relocatability: non-relocatable, data-relocatable, and fully relocatable
13343: image files.
13344: 
13345: @cindex image file loader
13346: @cindex relocating loader
13347: @cindex loader for image files
13348: These image file variants have several restrictions in common; they are
13349: caused by the design of the image file loader:
13350: 
13351: @itemize @bullet
13352: @item
13353: There is only one segment; in particular, this means, that an image file
13354: cannot represent @code{ALLOCATE}d memory chunks (and pointers to
13355: them). The contents of the stacks are not represented, either.
13356: 
13357: @item
13358: The only kinds of relocation supported are: adding the same offset to
13359: all cells that represent data addresses; and replacing special tokens
13360: with code addresses or with pieces of machine code.
13361: 
13362: If any complex computations involving addresses are performed, the
13363: results cannot be represented in the image file. Several applications that
13364: use such computations come to mind:
13365: @itemize @minus
13366: @item
13367: Hashing addresses (or data structures which contain addresses) for table
13368: lookup. If you use Gforth's @code{table}s or @code{wordlist}s for this
13369: purpose, you will have no problem, because the hash tables are
13370: recomputed automatically when the system is started. If you use your own
13371: hash tables, you will have to do something similar.
13372: 
13373: @item
13374: There's a cute implementation of doubly-linked lists that uses
13375: @code{XOR}ed addresses. You could represent such lists as singly-linked
13376: in the image file, and restore the doubly-linked representation on
13377: startup.@footnote{In my opinion, though, you should think thrice before
13378: using a doubly-linked list (whatever implementation).}
13379: 
13380: @item
13381: The code addresses of run-time routines like @code{docol:} cannot be
13382: represented in the image file (because their tokens would be replaced by
13383: machine code in direct threaded implementations). As a workaround,
13384: compute these addresses at run-time with @code{>code-address} from the
13385: executions tokens of appropriate words (see the definitions of
13386: @code{docol:} and friends in @file{kernel.fs}).
13387: 
13388: @item
13389: On many architectures addresses are represented in machine code in some
13390: shifted or mangled form. You cannot put @code{CODE} words that contain
13391: absolute addresses in this form in a relocatable image file. Workarounds
13392: are representing the address in some relative form (e.g., relative to
13393: the CFA, which is present in some register), or loading the address from
13394: a place where it is stored in a non-mangled form.
13395: @end itemize
13396: @end itemize
13397: 
13398: @node  Non-Relocatable Image Files, Data-Relocatable Image Files, Image File Background, Image Files
13399: @section Non-Relocatable Image Files
13400: @cindex non-relocatable image files
13401: @cindex image file, non-relocatable
13402: 
13403: These files are simple memory dumps of the dictionary. They are specific
13404: to the executable (i.e., @file{gforth} file) they were created
13405: with. What's worse, they are specific to the place on which the
13406: dictionary resided when the image was created. Now, there is no
13407: guarantee that the dictionary will reside at the same place the next
13408: time you start Gforth, so there's no guarantee that a non-relocatable
13409: image will work the next time (Gforth will complain instead of crashing,
13410: though).
13411: 
13412: You can create a non-relocatable image file with
13413: 
13414: 
13415: doc-savesystem
13416: 
13417: 
13418: @node Data-Relocatable Image Files, Fully Relocatable Image Files, Non-Relocatable Image Files, Image Files
13419: @section Data-Relocatable Image Files
13420: @cindex data-relocatable image files
13421: @cindex image file, data-relocatable
13422: 
13423: These files contain relocatable data addresses, but fixed code addresses
13424: (instead of tokens). They are specific to the executable (i.e.,
13425: @file{gforth} file) they were created with. For direct threading on some
13426: architectures (e.g., the i386), data-relocatable images do not work. You
13427: get a data-relocatable image, if you use @file{gforthmi} with a
13428: Gforth binary that is not doubly indirect threaded (@pxref{Fully
13429: Relocatable Image Files}).
13430: 
13431: @node Fully Relocatable Image Files, Stack and Dictionary Sizes, Data-Relocatable Image Files, Image Files
13432: @section Fully Relocatable Image Files
13433: @cindex fully relocatable image files
13434: @cindex image file, fully relocatable
13435: 
13436: @cindex @file{kern*.fi}, relocatability
13437: @cindex @file{gforth.fi}, relocatability
13438: These image files have relocatable data addresses, and tokens for code
13439: addresses. They can be used with different binaries (e.g., with and
13440: without debugging) on the same machine, and even across machines with
13441: the same data formats (byte order, cell size, floating point
13442: format). However, they are usually specific to the version of Gforth
13443: they were created with. The files @file{gforth.fi} and @file{kernl*.fi}
13444: are fully relocatable.
13445: 
13446: There are two ways to create a fully relocatable image file:
13447: 
13448: @menu
13449: * gforthmi::                    The normal way
13450: * cross.fs::                    The hard way
13451: @end menu
13452: 
13453: @node gforthmi, cross.fs, Fully Relocatable Image Files, Fully Relocatable Image Files
13454: @subsection @file{gforthmi}
13455: @cindex @file{comp-i.fs}
13456: @cindex @file{gforthmi}
13457: 
13458: You will usually use @file{gforthmi}. If you want to create an
13459: image @i{file} that contains everything you would load by invoking
13460: Gforth with @code{gforth @i{options}}, you simply say:
13461: @example
13462: gforthmi @i{file} @i{options}
13463: @end example
13464: 
13465: E.g., if you want to create an image @file{asm.fi} that has the file
13466: @file{asm.fs} loaded in addition to the usual stuff, you could do it
13467: like this:
13468: 
13469: @example
13470: gforthmi asm.fi asm.fs
13471: @end example
13472: 
13473: @file{gforthmi} is implemented as a sh script and works like this: It
13474: produces two non-relocatable images for different addresses and then
13475: compares them. Its output reflects this: first you see the output (if
13476: any) of the two Gforth invocations that produce the non-relocatable image
13477: files, then you see the output of the comparing program: It displays the
13478: offset used for data addresses and the offset used for code addresses;
13479: moreover, for each cell that cannot be represented correctly in the
13480: image files, it displays a line like this:
13481: 
13482: @example
13483:      78DC         BFFFFA50         BFFFFA40
13484: @end example
13485: 
13486: This means that at offset $78dc from @code{forthstart}, one input image
13487: contains $bffffa50, and the other contains $bffffa40. Since these cells
13488: cannot be represented correctly in the output image, you should examine
13489: these places in the dictionary and verify that these cells are dead
13490: (i.e., not read before they are written).
13491: 
13492: @cindex --application, @code{gforthmi} option
13493: If you insert the option @code{--application} in front of the image file
13494: name, you will get an image that uses the @code{--appl-image} option
13495: instead of the @code{--image-file} option (@pxref{Invoking
13496: Gforth}). When you execute such an image on Unix (by typing the image
13497: name as command), the Gforth engine will pass all options to the image
13498: instead of trying to interpret them as engine options.
13499: 
13500: If you type @file{gforthmi} with no arguments, it prints some usage
13501: instructions.
13502: 
13503: @cindex @code{savesystem} during @file{gforthmi}
13504: @cindex @code{bye} during @file{gforthmi}
13505: @cindex doubly indirect threaded code
13506: @cindex environment variables
13507: @cindex @code{GFORTHD} -- environment variable
13508: @cindex @code{GFORTH} -- environment variable
13509: @cindex @code{gforth-ditc}
13510: There are a few wrinkles: After processing the passed @i{options}, the
13511: words @code{savesystem} and @code{bye} must be visible. A special doubly
13512: indirect threaded version of the @file{gforth} executable is used for
13513: creating the non-relocatable images; you can pass the exact filename of
13514: this executable through the environment variable @code{GFORTHD}
13515: (default: @file{gforth-ditc}); if you pass a version that is not doubly
13516: indirect threaded, you will not get a fully relocatable image, but a
13517: data-relocatable image (because there is no code address offset). The
13518: normal @file{gforth} executable is used for creating the relocatable
13519: image; you can pass the exact filename of this executable through the
13520: environment variable @code{GFORTH}.
13521: 
13522: @node cross.fs,  , gforthmi, Fully Relocatable Image Files
13523: @subsection @file{cross.fs}
13524: @cindex @file{cross.fs}
13525: @cindex cross-compiler
13526: @cindex metacompiler
13527: @cindex target compiler
13528: 
13529: You can also use @code{cross}, a batch compiler that accepts a Forth-like
13530: programming language (@pxref{Cross Compiler}).
13531: 
13532: @code{cross} allows you to create image files for machines with
13533: different data sizes and data formats than the one used for generating
13534: the image file. You can also use it to create an application image that
13535: does not contain a Forth compiler. These features are bought with
13536: restrictions and inconveniences in programming. E.g., addresses have to
13537: be stored in memory with special words (@code{A!}, @code{A,}, etc.) in
13538: order to make the code relocatable.
13539: 
13540: 
13541: @node Stack and Dictionary Sizes, Running Image Files, Fully Relocatable Image Files, Image Files
13542: @section Stack and Dictionary Sizes
13543: @cindex image file, stack and dictionary sizes
13544: @cindex dictionary size default
13545: @cindex stack size default
13546: 
13547: If you invoke Gforth with a command line flag for the size
13548: (@pxref{Invoking Gforth}), the size you specify is stored in the
13549: dictionary. If you save the dictionary with @code{savesystem} or create
13550: an image with @file{gforthmi}, this size will become the default
13551: for the resulting image file. E.g., the following will create a
13552: fully relocatable version of @file{gforth.fi} with a 1MB dictionary:
13553: 
13554: @example
13555: gforthmi gforth.fi -m 1M
13556: @end example
13557: 
13558: In other words, if you want to set the default size for the dictionary
13559: and the stacks of an image, just invoke @file{gforthmi} with the
13560: appropriate options when creating the image.
13561: 
13562: @cindex stack size, cache-friendly
13563: Note: For cache-friendly behaviour (i.e., good performance), you should
13564: make the sizes of the stacks modulo, say, 2K, somewhat different. E.g.,
13565: the default stack sizes are: data: 16k (mod 2k=0); fp: 15.5k (mod
13566: 2k=1.5k); return: 15k(mod 2k=1k); locals: 14.5k (mod 2k=0.5k).
13567: 
13568: @node Running Image Files, Modifying the Startup Sequence, Stack and Dictionary Sizes, Image Files
13569: @section Running Image Files
13570: @cindex running image files
13571: @cindex invoking image files
13572: @cindex image file invocation
13573: 
13574: @cindex -i, invoke image file
13575: @cindex --image file, invoke image file
13576: You can invoke Gforth with an image file @i{image} instead of the
13577: default @file{gforth.fi} with the @code{-i} flag (@pxref{Invoking Gforth}):
13578: @example
13579: gforth -i @i{image}
13580: @end example
13581: 
13582: @cindex executable image file
13583: @cindex image file, executable
13584: If your operating system supports starting scripts with a line of the
13585: form @code{#! ...}, you just have to type the image file name to start
13586: Gforth with this image file (note that the file extension @code{.fi} is
13587: just a convention). I.e., to run Gforth with the image file @i{image},
13588: you can just type @i{image} instead of @code{gforth -i @i{image}}.
13589: This works because every @code{.fi} file starts with a line of this
13590: format:
13591: 
13592: @example
13593: #! /usr/local/bin/gforth-0.4.0 -i
13594: @end example
13595: 
13596: The file and pathname for the Gforth engine specified on this line is
13597: the specific Gforth executable that it was built against; i.e. the value
13598: of the environment variable @code{GFORTH} at the time that
13599: @file{gforthmi} was executed.
13600: 
13601: You can make use of the same shell capability to make a Forth source
13602: file into an executable. For example, if you place this text in a file:
13603: 
13604: @example
13605: #! /usr/local/bin/gforth
13606: 
13607: ." Hello, world" CR
13608: bye
13609: @end example
13610: 
13611: @noindent
13612: and then make the file executable (chmod +x in Unix), you can run it
13613: directly from the command line. The sequence @code{#!} is used in two
13614: ways; firstly, it is recognised as a ``magic sequence'' by the operating
13615: system@footnote{The Unix kernel actually recognises two types of files:
13616: executable files and files of data, where the data is processed by an
13617: interpreter that is specified on the ``interpreter line'' -- the first
13618: line of the file, starting with the sequence #!. There may be a small
13619: limit (e.g., 32) on the number of characters that may be specified on
13620: the interpreter line.} secondly it is treated as a comment character by
13621: Gforth. Because of the second usage, a space is required between
13622: @code{#!} and the path to the executable.
13623: 
13624: The disadvantage of this latter technique, compared with using
13625: @file{gforthmi}, is that it is slower; the Forth source code is compiled
13626: on-the-fly, each time the program is invoked.
13627: 
13628: 
13629: doc-#!
13630: 
13631: 
13632: @node Modifying the Startup Sequence,  , Running Image Files, Image Files
13633: @section Modifying the Startup Sequence
13634: @cindex startup sequence for image file
13635: @cindex image file initialization sequence
13636: @cindex initialization sequence of image file
13637: 
13638: You can add your own initialization to the startup sequence through the
13639: deferred word @code{'cold}. @code{'cold} is invoked just before the
13640: image-specific command line processing (by default, loading files and
13641: evaluating (@code{-e}) strings) starts.
13642: 
13643: A sequence for adding your initialization usually looks like this:
13644: 
13645: @example
13646: :noname
13647:     Defers 'cold \ do other initialization stuff (e.g., rehashing wordlists)
13648:     ... \ your stuff
13649: ; IS 'cold
13650: @end example
13651: 
13652: @cindex turnkey image files
13653: @cindex image file, turnkey applications
13654: You can make a turnkey image by letting @code{'cold} execute a word
13655: (your turnkey application) that never returns; instead, it exits Gforth
13656: via @code{bye} or @code{throw}.
13657: 
13658: @cindex command-line arguments, access
13659: @cindex arguments on the command line, access
13660: You can access the (image-specific) command-line arguments through the
13661: variables @code{argc} and @code{argv}. @code{arg} provides convenient
13662: access to @code{argv}.
13663: 
13664: If @code{'cold} exits normally, Gforth processes the command-line
13665: arguments as files to be loaded and strings to be evaluated.  Therefore,
13666: @code{'cold} should remove the arguments it has used in this case.
13667: 
13668: 
13669: 
13670: doc-'cold
13671: doc-argc
13672: doc-argv
13673: doc-arg
13674: 
13675: 
13676: 
13677: @c ******************************************************************
13678: @node Engine, Binding to System Library, Image Files, Top
13679: @chapter Engine
13680: @cindex engine
13681: @cindex virtual machine
13682: 
13683: Reading this chapter is not necessary for programming with Gforth. It
13684: may be helpful for finding your way in the Gforth sources.
13685: 
13686: The ideas in this section have also been published in Bernd Paysan,
13687: @cite{ANS fig/GNU/??? Forth} (in German), Forth-Tagung '93 and M. Anton
13688: Ertl, @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl93.ps.Z, A
13689: Portable Forth Engine}}, EuroForth '93.
13690: 
13691: @menu
13692: * Portability::                 
13693: * Threading::                   
13694: * Primitives::                  
13695: * Performance::                 
13696: @end menu
13697: 
13698: @node Portability, Threading, Engine, Engine
13699: @section Portability
13700: @cindex engine portability
13701: 
13702: An important goal of the Gforth Project is availability across a wide
13703: range of personal machines. fig-Forth, and, to a lesser extent, F83,
13704: achieved this goal by manually coding the engine in assembly language
13705: for several then-popular processors. This approach is very
13706: labor-intensive and the results are short-lived due to progress in
13707: computer architecture.
13708: 
13709: @cindex C, using C for the engine
13710: Others have avoided this problem by coding in C, e.g., Mitch Bradley
13711: (cforth), Mikael Patel (TILE) and Dirk Zoller (pfe). This approach is
13712: particularly popular for UNIX-based Forths due to the large variety of
13713: architectures of UNIX machines. Unfortunately an implementation in C
13714: does not mix well with the goals of efficiency and with using
13715: traditional techniques: Indirect or direct threading cannot be expressed
13716: in C, and switch threading, the fastest technique available in C, is
13717: significantly slower. Another problem with C is that it is very
13718: cumbersome to express double integer arithmetic.
13719: 
13720: @cindex GNU C for the engine
13721: @cindex long long
13722: Fortunately, there is a portable language that does not have these
13723: limitations: GNU C, the version of C processed by the GNU C compiler
13724: (@pxref{C Extensions, , Extensions to the C Language Family, gcc.info,
13725: GNU C Manual}). Its labels as values feature (@pxref{Labels as Values, ,
13726: Labels as Values, gcc.info, GNU C Manual}) makes direct and indirect
13727: threading possible, its @code{long long} type (@pxref{Long Long, ,
13728: Double-Word Integers, gcc.info, GNU C Manual}) corresponds to Forth's
13729: double numbers@footnote{Unfortunately, long longs are not implemented
13730: properly on all machines (e.g., on alpha-osf1, long longs are only 64
13731: bits, the same size as longs (and pointers), but they should be twice as
13732: long according to @pxref{Long Long, , Double-Word Integers, gcc.info, GNU
13733: C Manual}). So, we had to implement doubles in C after all. Still, on
13734: most machines we can use long longs and achieve better performance than
13735: with the emulation package.}. GNU C is available for free on all
13736: important (and many unimportant) UNIX machines, VMS, 80386s running
13737: MS-DOS, the Amiga, and the Atari ST, so a Forth written in GNU C can run
13738: on all these machines.
13739: 
13740: Writing in a portable language has the reputation of producing code that
13741: is slower than assembly. For our Forth engine we repeatedly looked at
13742: the code produced by the compiler and eliminated most compiler-induced
13743: inefficiencies by appropriate changes in the source code.
13744: 
13745: @cindex explicit register declarations
13746: @cindex --enable-force-reg, configuration flag
13747: @cindex -DFORCE_REG
13748: However, register allocation cannot be portably influenced by the
13749: programmer, leading to some inefficiencies on register-starved
13750: machines. We use explicit register declarations (@pxref{Explicit Reg
13751: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) to
13752: improve the speed on some machines. They are turned on by using the
13753: configuration flag @code{--enable-force-reg} (@code{gcc} switch
13754: @code{-DFORCE_REG}). Unfortunately, this feature not only depends on the
13755: machine, but also on the compiler version: On some machines some
13756: compiler versions produce incorrect code when certain explicit register
13757: declarations are used. So by default @code{-DFORCE_REG} is not used.
13758: 
13759: @node Threading, Primitives, Portability, Engine
13760: @section Threading
13761: @cindex inner interpreter implementation
13762: @cindex threaded code implementation
13763: 
13764: @cindex labels as values
13765: GNU C's labels as values extension (available since @code{gcc-2.0},
13766: @pxref{Labels as Values, , Labels as Values, gcc.info, GNU C Manual})
13767: makes it possible to take the address of @i{label} by writing
13768: @code{&&@i{label}}.  This address can then be used in a statement like
13769: @code{goto *@i{address}}. I.e., @code{goto *&&x} is the same as
13770: @code{goto x}.
13771: 
13772: @cindex @code{NEXT}, indirect threaded
13773: @cindex indirect threaded inner interpreter
13774: @cindex inner interpreter, indirect threaded
13775: With this feature an indirect threaded @code{NEXT} looks like:
13776: @example
13777: cfa = *ip++;
13778: ca = *cfa;
13779: goto *ca;
13780: @end example
13781: @cindex instruction pointer
13782: For those unfamiliar with the names: @code{ip} is the Forth instruction
13783: pointer; the @code{cfa} (code-field address) corresponds to ANS Forths
13784: execution token and points to the code field of the next word to be
13785: executed; The @code{ca} (code address) fetched from there points to some
13786: executable code, e.g., a primitive or the colon definition handler
13787: @code{docol}.
13788: 
13789: @cindex @code{NEXT}, direct threaded
13790: @cindex direct threaded inner interpreter
13791: @cindex inner interpreter, direct threaded
13792: Direct threading is even simpler:
13793: @example
13794: ca = *ip++;
13795: goto *ca;
13796: @end example
13797: 
13798: Of course we have packaged the whole thing neatly in macros called
13799: @code{NEXT} and @code{NEXT1} (the part of @code{NEXT} after fetching the cfa).
13800: 
13801: @menu
13802: * Scheduling::                  
13803: * Direct or Indirect Threaded?::  
13804: * DOES>::                       
13805: @end menu
13806: 
13807: @node Scheduling, Direct or Indirect Threaded?, Threading, Threading
13808: @subsection Scheduling
13809: @cindex inner interpreter optimization
13810: 
13811: There is a little complication: Pipelined and superscalar processors,
13812: i.e., RISC and some modern CISC machines can process independent
13813: instructions while waiting for the results of an instruction. The
13814: compiler usually reorders (schedules) the instructions in a way that
13815: achieves good usage of these delay slots. However, on our first tries
13816: the compiler did not do well on scheduling primitives. E.g., for
13817: @code{+} implemented as
13818: @example
13819: n=sp[0]+sp[1];
13820: sp++;
13821: sp[0]=n;
13822: NEXT;
13823: @end example
13824: the @code{NEXT} comes strictly after the other code, i.e., there is nearly no
13825: scheduling. After a little thought the problem becomes clear: The
13826: compiler cannot know that @code{sp} and @code{ip} point to different
13827: addresses (and the version of @code{gcc} we used would not know it even
13828: if it was possible), so it could not move the load of the cfa above the
13829: store to the TOS. Indeed the pointers could be the same, if code on or
13830: very near the top of stack were executed. In the interest of speed we
13831: chose to forbid this probably unused ``feature'' and helped the compiler
13832: in scheduling: @code{NEXT} is divided into the loading part (@code{NEXT_P1})
13833: and the goto part (@code{NEXT_P2}). @code{+} now looks like:
13834: @example
13835: n=sp[0]+sp[1];
13836: sp++;
13837: NEXT_P1;
13838: sp[0]=n;
13839: NEXT_P2;
13840: @end example
13841: This can be scheduled optimally by the compiler.
13842: 
13843: This division can be turned off with the switch @code{-DCISC_NEXT}. This
13844: switch is on by default on machines that do not profit from scheduling
13845: (e.g., the 80386), in order to preserve registers.
13846: 
13847: @node Direct or Indirect Threaded?, DOES>, Scheduling, Threading
13848: @subsection Direct or Indirect Threaded?
13849: @cindex threading, direct or indirect?
13850: 
13851: @cindex -DDIRECT_THREADED
13852: Both! After packaging the nasty details in macro definitions we
13853: realized that we could switch between direct and indirect threading by
13854: simply setting a compilation flag (@code{-DDIRECT_THREADED}) and
13855: defining a few machine-specific macros for the direct-threading case.
13856: On the Forth level we also offer access words that hide the
13857: differences between the threading methods (@pxref{Threading Words}).
13858: 
13859: Indirect threading is implemented completely machine-independently.
13860: Direct threading needs routines for creating jumps to the executable
13861: code (e.g. to @code{docol} or @code{dodoes}). These routines are inherently
13862: machine-dependent, but they do not amount to many source lines. Therefore,
13863: even porting direct threading to a new machine requires little effort.
13864: 
13865: @cindex --enable-indirect-threaded, configuration flag
13866: @cindex --enable-direct-threaded, configuration flag
13867: The default threading method is machine-dependent. You can enforce a
13868: specific threading method when building Gforth with the configuration
13869: flag @code{--enable-direct-threaded} or
13870: @code{--enable-indirect-threaded}. Note that direct threading is not
13871: supported on all machines.
13872: 
13873: @node DOES>,  , Direct or Indirect Threaded?, Threading
13874: @subsection DOES>
13875: @cindex @code{DOES>} implementation
13876: 
13877: @cindex @code{dodoes} routine
13878: @cindex @code{DOES>}-code
13879: One of the most complex parts of a Forth engine is @code{dodoes}, i.e.,
13880: the chunk of code executed by every word defined by a
13881: @code{CREATE}...@code{DOES>} pair. The main problem here is: How to find
13882: the Forth code to be executed, i.e. the code after the
13883: @code{DOES>} (the @code{DOES>}-code)? There are two solutions:
13884: 
13885: In fig-Forth the code field points directly to the @code{dodoes} and the
13886: @code{DOES>}-code address is stored in the cell after the code address (i.e. at
13887: @code{@i{CFA} cell+}). It may seem that this solution is illegal in
13888: the Forth-79 and all later standards, because in fig-Forth this address
13889: lies in the body (which is illegal in these standards). However, by
13890: making the code field larger for all words this solution becomes legal
13891: again. We use this approach for the indirect threaded version and for
13892: direct threading on some machines. Leaving a cell unused in most words
13893: is a bit wasteful, but on the machines we are targeting this is hardly a
13894: problem. The other reason for having a code field size of two cells is
13895: to avoid having different image files for direct and indirect threaded
13896: systems (direct threaded systems require two-cell code fields on many
13897: machines).
13898: 
13899: @cindex @code{DOES>}-handler
13900: The other approach is that the code field points or jumps to the cell
13901: after @code{DOES>}. In this variant there is a jump to @code{dodoes} at
13902: this address (the @code{DOES>}-handler). @code{dodoes} can then get the
13903: @code{DOES>}-code address by computing the code address, i.e., the address of
13904: the jump to @code{dodoes}, and add the length of that jump field. A variant of
13905: this is to have a call to @code{dodoes} after the @code{DOES>}; then the
13906: return address (which can be found in the return register on RISCs) is
13907: the @code{DOES>}-code address. Since the two cells available in the code field
13908: are used up by the jump to the code address in direct threading on many
13909: architectures, we use this approach for direct threading on these
13910: architectures. We did not want to add another cell to the code field.
13911: 
13912: @node Primitives, Performance, Threading, Engine
13913: @section Primitives
13914: @cindex primitives, implementation
13915: @cindex virtual machine instructions, implementation
13916: 
13917: @menu
13918: * Automatic Generation::        
13919: * TOS Optimization::            
13920: * Produced code::               
13921: @end menu
13922: 
13923: @node Automatic Generation, TOS Optimization, Primitives, Primitives
13924: @subsection Automatic Generation
13925: @cindex primitives, automatic generation
13926: 
13927: @cindex @file{prims2x.fs}
13928: Since the primitives are implemented in a portable language, there is no
13929: longer any need to minimize the number of primitives. On the contrary,
13930: having many primitives has an advantage: speed. In order to reduce the
13931: number of errors in primitives and to make programming them easier, we
13932: provide a tool, the primitive generator (@file{prims2x.fs}), that
13933: automatically generates most (and sometimes all) of the C code for a
13934: primitive from the stack effect notation.  The source for a primitive
13935: has the following form:
13936: 
13937: @cindex primitive source format
13938: @format
13939: @i{Forth-name}  ( @i{stack-effect} )        @i{category}    [@i{pronounc.}]
13940: [@code{""}@i{glossary entry}@code{""}]
13941: @i{C code}
13942: [@code{:}
13943: @i{Forth code}]
13944: @end format
13945: 
13946: The items in brackets are optional. The category and glossary fields
13947: are there for generating the documentation, the Forth code is there
13948: for manual implementations on machines without GNU C. E.g., the source
13949: for the primitive @code{+} is:
13950: @example
13951: +    ( n1 n2 -- n )   core    plus
13952: n = n1+n2;
13953: @end example
13954: 
13955: This looks like a specification, but in fact @code{n = n1+n2} is C
13956: code. Our primitive generation tool extracts a lot of information from
13957: the stack effect notations@footnote{We use a one-stack notation, even
13958: though we have separate data and floating-point stacks; The separate
13959: notation can be generated easily from the unified notation.}: The number
13960: of items popped from and pushed on the stack, their type, and by what
13961: name they are referred to in the C code. It then generates a C code
13962: prelude and postlude for each primitive. The final C code for @code{+}
13963: looks like this:
13964: 
13965: @example
13966: I_plus: /* + ( n1 n2 -- n ) */  /* label, stack effect */
13967: /*  */                          /* documentation */
13968: @{
13969: DEF_CA                          /* definition of variable ca (indirect threading) */
13970: Cell n1;                        /* definitions of variables */
13971: Cell n2;
13972: Cell n;
13973: n1 = (Cell) sp[1];              /* input */
13974: n2 = (Cell) TOS;
13975: sp += 1;                        /* stack adjustment */
13976: NAME("+")                       /* debugging output (with -DDEBUG) */
13977: @{
13978: n = n1+n2;                      /* C code taken from the source */
13979: @}
13980: NEXT_P1;                        /* NEXT part 1 */
13981: TOS = (Cell)n;                  /* output */
13982: NEXT_P2;                        /* NEXT part 2 */
13983: @}
13984: @end example
13985: 
13986: This looks long and inefficient, but the GNU C compiler optimizes quite
13987: well and produces optimal code for @code{+} on, e.g., the R3000 and the
13988: HP RISC machines: Defining the @code{n}s does not produce any code, and
13989: using them as intermediate storage also adds no cost.
13990: 
13991: There are also other optimizations that are not illustrated by this
13992: example: assignments between simple variables are usually for free (copy
13993: propagation). If one of the stack items is not used by the primitive
13994: (e.g.  in @code{drop}), the compiler eliminates the load from the stack
13995: (dead code elimination). On the other hand, there are some things that
13996: the compiler does not do, therefore they are performed by
13997: @file{prims2x.fs}: The compiler does not optimize code away that stores
13998: a stack item to the place where it just came from (e.g., @code{over}).
13999: 
14000: While programming a primitive is usually easy, there are a few cases
14001: where the programmer has to take the actions of the generator into
14002: account, most notably @code{?dup}, but also words that do not (always)
14003: fall through to @code{NEXT}.
14004: 
14005: @node TOS Optimization, Produced code, Automatic Generation, Primitives
14006: @subsection TOS Optimization
14007: @cindex TOS optimization for primitives
14008: @cindex primitives, keeping the TOS in a register
14009: 
14010: An important optimization for stack machine emulators, e.g., Forth
14011: engines, is keeping  one or more of the top stack items in
14012: registers.  If a word has the stack effect @i{in1}...@i{inx} @code{--}
14013: @i{out1}...@i{outy}, keeping the top @i{n} items in registers
14014: @itemize @bullet
14015: @item
14016: is better than keeping @i{n-1} items, if @i{x>=n} and @i{y>=n},
14017: due to fewer loads from and stores to the stack.
14018: @item is slower than keeping @i{n-1} items, if @i{x<>y} and @i{x<n} and
14019: @i{y<n}, due to additional moves between registers.
14020: @end itemize
14021: 
14022: @cindex -DUSE_TOS
14023: @cindex -DUSE_NO_TOS
14024: In particular, keeping one item in a register is never a disadvantage,
14025: if there are enough registers. Keeping two items in registers is a
14026: disadvantage for frequent words like @code{?branch}, constants,
14027: variables, literals and @code{i}. Therefore our generator only produces
14028: code that keeps zero or one items in registers. The generated C code
14029: covers both cases; the selection between these alternatives is made at
14030: C-compile time using the switch @code{-DUSE_TOS}. @code{TOS} in the C
14031: code for @code{+} is just a simple variable name in the one-item case,
14032: otherwise it is a macro that expands into @code{sp[0]}. Note that the
14033: GNU C compiler tries to keep simple variables like @code{TOS} in
14034: registers, and it usually succeeds, if there are enough registers.
14035: 
14036: @cindex -DUSE_FTOS
14037: @cindex -DUSE_NO_FTOS
14038: The primitive generator performs the TOS optimization for the
14039: floating-point stack, too (@code{-DUSE_FTOS}). For floating-point
14040: operations the benefit of this optimization is even larger:
14041: floating-point operations take quite long on most processors, but can be
14042: performed in parallel with other operations as long as their results are
14043: not used. If the FP-TOS is kept in a register, this works. If
14044: it is kept on the stack, i.e., in memory, the store into memory has to
14045: wait for the result of the floating-point operation, lengthening the
14046: execution time of the primitive considerably.
14047: 
14048: The TOS optimization makes the automatic generation of primitives a
14049: bit more complicated. Just replacing all occurrences of @code{sp[0]} by
14050: @code{TOS} is not sufficient. There are some special cases to
14051: consider:
14052: @itemize @bullet
14053: @item In the case of @code{dup ( w -- w w )} the generator must not
14054: eliminate the store to the original location of the item on the stack,
14055: if the TOS optimization is turned on.
14056: @item Primitives with stack effects of the form @code{--}
14057: @i{out1}...@i{outy} must store the TOS to the stack at the start.
14058: Likewise, primitives with the stack effect @i{in1}...@i{inx} @code{--}
14059: must load the TOS from the stack at the end. But for the null stack
14060: effect @code{--} no stores or loads should be generated.
14061: @end itemize
14062: 
14063: @node Produced code,  , TOS Optimization, Primitives
14064: @subsection Produced code
14065: @cindex primitives, assembly code listing
14066: 
14067: @cindex @file{engine.s}
14068: To see what assembly code is produced for the primitives on your machine
14069: with your compiler and your flag settings, type @code{make engine.s} and
14070: look at the resulting file @file{engine.s}.
14071: 
14072: @node  Performance,  , Primitives, Engine
14073: @section Performance
14074: @cindex performance of some Forth interpreters
14075: @cindex engine performance
14076: @cindex benchmarking Forth systems
14077: @cindex Gforth performance
14078: 
14079: On RISCs the Gforth engine is very close to optimal; i.e., it is usually
14080: impossible to write a significantly faster engine.
14081: 
14082: On register-starved machines like the 386 architecture processors
14083: improvements are possible, because @code{gcc} does not utilize the
14084: registers as well as a human, even with explicit register declarations;
14085: e.g., Bernd Beuster wrote a Forth system fragment in assembly language
14086: and hand-tuned it for the 486; this system is 1.19 times faster on the
14087: Sieve benchmark on a 486DX2/66 than Gforth compiled with
14088: @code{gcc-2.6.3} with @code{-DFORCE_REG}.  The situation has improved
14089: with gcc-2.95 and gforth-0.4.9; now the most important virtual machine
14090: registers fit in real registers (and we can even afford to use the TOS
14091: optimization), resulting in a speedup of 1.14 on the sieve over the
14092: earlier results.
14093: 
14094: @cindex Win32Forth performance
14095: @cindex NT Forth performance
14096: @cindex eforth performance
14097: @cindex ThisForth performance
14098: @cindex PFE performance
14099: @cindex TILE performance
14100: The potential advantage of assembly language implementations
14101: is not necessarily realized in complete Forth systems: We compared
14102: Gforth-0.4.9 (direct threaded, compiled with @code{gcc-2.95.1} and
14103: @code{-DFORCE_REG}) with Win32Forth 1.2093, LMI's NT Forth (Beta, May
14104: 1994) and Eforth (with and without peephole (aka pinhole) optimization
14105: of the threaded code); all these systems were written in assembly
14106: language. We also compared Gforth with three systems written in C:
14107: PFE-0.9.14 (compiled with @code{gcc-2.6.3} with the default
14108: configuration for Linux: @code{-O2 -fomit-frame-pointer -DUSE_REGS
14109: -DUNROLL_NEXT}), ThisForth Beta (compiled with @code{gcc-2.6.3 -O3
14110: -fomit-frame-pointer}; ThisForth employs peephole optimization of the
14111: threaded code) and TILE (compiled with @code{make opt}). We benchmarked
14112: Gforth, PFE, ThisForth and TILE on a 486DX2/66 under Linux. Kenneth
14113: O'Heskin kindly provided the results for Win32Forth and NT Forth on a
14114: 486DX2/66 with similar memory performance under Windows NT. Marcel
14115: Hendrix ported Eforth to Linux, then extended it to run the benchmarks,
14116: added the peephole optimizer, ran the benchmarks and reported the
14117: results.
14118: 
14119: We used four small benchmarks: the ubiquitous Sieve; bubble-sorting and
14120: matrix multiplication come from the Stanford integer benchmarks and have
14121: been translated into Forth by Martin Fraeman; we used the versions
14122: included in the TILE Forth package, but with bigger data set sizes; and
14123: a recursive Fibonacci number computation for benchmarking calling
14124: performance. The following table shows the time taken for the benchmarks
14125: scaled by the time taken by Gforth (in other words, it shows the speedup
14126: factor that Gforth achieved over the other systems).
14127: 
14128: @example
14129: relative      Win32-    NT       eforth       This-      
14130:   time  Gforth Forth Forth eforth  +opt   PFE Forth  TILE
14131: sieve     1.00  1.58  1.30   1.58  0.97  1.80  3.63  9.79
14132: bubble    1.00  1.55  1.67   1.75  1.04  1.78        4.59
14133: matmul    1.00  1.67  1.53   1.66  0.84  1.79        4.63
14134: fib       1.00  1.75  1.53   1.40  0.99  1.99  3.43  4.93
14135: @end example
14136: 
14137: You may be quite surprised by the good performance of Gforth when
14138: compared with systems written in assembly language. One important reason
14139: for the disappointing performance of these other systems is probably
14140: that they are not written optimally for the 486 (e.g., they use the
14141: @code{lods} instruction). In addition, Win32Forth uses a comfortable,
14142: but costly method for relocating the Forth image: like @code{cforth}, it
14143: computes the actual addresses at run time, resulting in two address
14144: computations per @code{NEXT} (@pxref{Image File Background}).
14145: 
14146: Only Eforth with the peephole optimizer performs comparable to
14147: Gforth. The speedups achieved with peephole optimization of threaded
14148: code are quite remarkable. Adding a peephole optimizer to Gforth should
14149: cause similar speedups.
14150: 
14151: The speedup of Gforth over PFE, ThisForth and TILE can be easily
14152: explained with the self-imposed restriction of the latter systems to
14153: standard C, which makes efficient threading impossible (however, the
14154: measured implementation of PFE uses a GNU C extension: @pxref{Global Reg
14155: Vars, , Defining Global Register Variables, gcc.info, GNU C Manual}).
14156: Moreover, current C compilers have a hard time optimizing other aspects
14157: of the ThisForth and the TILE source.
14158: 
14159: The performance of Gforth on 386 architecture processors varies widely
14160: with the version of @code{gcc} used. E.g., @code{gcc-2.5.8} failed to
14161: allocate any of the virtual machine registers into real machine
14162: registers by itself and would not work correctly with explicit register
14163: declarations, giving a 1.5 times slower engine (on a 486DX2/66 running
14164: the Sieve) than the one measured above.
14165: 
14166: Note that there have been several releases of Win32Forth since the
14167: release presented here, so the results presented above may have little
14168: predictive value for the performance of Win32Forth today (results for
14169: the current release on an i486DX2/66 are welcome).
14170: 
14171: @cindex @file{Benchres}
14172: In
14173: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl&maierhofer95.ps.gz,
14174: Translating Forth to Efficient C}} by M. Anton Ertl and Martin
14175: Maierhofer (presented at EuroForth '95), an indirect threaded version of
14176: Gforth is compared with Win32Forth, NT Forth, PFE, ThisForth, and
14177: several native code systems; that version of Gforth is slower on a 486
14178: than the direct threaded version used here. You can find a newer version
14179: of these measurements at
14180: @uref{http://www.complang.tuwien.ac.at/forth/performance.html}. You can
14181: find numbers for Gforth on various machines in @file{Benchres}.
14182: 
14183: @c ******************************************************************
14184: @node Binding to System Library, Cross Compiler, Engine, Top
14185: @chapter Binding to System Library
14186: 
14187: @node Cross Compiler, Bugs, Binding to System Library, Top
14188: @chapter Cross Compiler
14189: @cindex @file{cross.fs}
14190: @cindex cross-compiler
14191: @cindex metacompiler
14192: @cindex target compiler
14193: 
14194: The cross compiler is used to bootstrap a Forth kernel. Since Gforth is
14195: mostly written in Forth, including crucial parts like the outer
14196: interpreter and compiler, it needs compiled Forth code to get
14197: started. The cross compiler allows to create new images for other
14198: architectures, even running under another Forth system.
14199: 
14200: @menu
14201: * Using the Cross Compiler::    
14202: * How the Cross Compiler Works::  
14203: @end menu
14204: 
14205: @node Using the Cross Compiler, How the Cross Compiler Works, Cross Compiler, Cross Compiler
14206: @section Using the Cross Compiler
14207: 
14208: The cross compiler uses a language that resembles Forth, but isn't. The
14209: main difference is that you can execute Forth code after definition,
14210: while you usually can't execute the code compiled by cross, because the
14211: code you are compiling is typically for a different computer than the
14212: one you are compiling on.
14213: 
14214: The Makefile is already set up to allow you to create kernels for new
14215: architectures with a simple make command. The generic kernels using the
14216: GCC compiled virtual machine are created in the normal build process
14217: with @code{make}. To create a embedded Gforth executable for e.g. the
14218: 8086 processor (running on a DOS machine), type
14219: 
14220: @example
14221: make kernl-8086.fi
14222: @end example
14223: 
14224: This will use the machine description from the @file{arch/8086}
14225: directory to create a new kernel. A machine file may look like that:
14226: 
14227: @example
14228: \ Parameter for target systems                         06oct92py
14229: 
14230:     4 Constant cell             \ cell size in bytes
14231:     2 Constant cell<<           \ cell shift to bytes
14232:     5 Constant cell>bit         \ cell shift to bits
14233:     8 Constant bits/char        \ bits per character
14234:     8 Constant bits/byte        \ bits per byte [default: 8]
14235:     8 Constant float            \ bytes per float
14236:     8 Constant /maxalign        \ maximum alignment in bytes
14237: false Constant bigendian        \ byte order
14238: ( true=big, false=little )
14239: 
14240: include machpc.fs               \ feature list
14241: @end example
14242: 
14243: This part is obligatory for the cross compiler itself, the feature list
14244: is used by the kernel to conditionally compile some features in and out,
14245: depending on whether the target supports these features.
14246: 
14247: There are some optional features, if you define your own primitives,
14248: have an assembler, or need special, nonstandard preparation to make the
14249: boot process work. @code{asm-include} include an assembler,
14250: @code{prims-include} includes primitives, and @code{>boot} prepares for
14251: booting.
14252: 
14253: @example
14254: : asm-include    ." Include assembler" cr
14255:   s" arch/8086/asm.fs" included ;
14256: 
14257: : prims-include  ." Include primitives" cr
14258:   s" arch/8086/prim.fs" included ;
14259: 
14260: : >boot          ." Prepare booting" cr
14261:   s" ' boot >body into-forth 1+ !" evaluate ;
14262: @end example
14263: 
14264: These words are used as sort of macro during the cross compilation in
14265: the file @file{kernel/main.fs}. Instead of using this macros, it would
14266: be possible --- but more complicated --- to write a new kernel project
14267: file, too.
14268: 
14269: @file{kernel/main.fs} expects the machine description file name on the
14270: stack; the cross compiler itself (@file{cross.fs}) assumes that either
14271: @code{mach-file} leaves a counted string on the stack, or
14272: @code{machine-file} leaves an address, count pair of the filename on the
14273: stack.
14274: 
14275: The feature list is typically controlled using @code{SetValue}, generic
14276: files that are used by several projects can use @code{DefaultValue}
14277: instead. Both functions work like @code{Value}, when the value isn't
14278: defined, but @code{SetValue} works like @code{to} if the value is
14279: defined, and @code{DefaultValue} doesn't set anything, if the value is
14280: defined.
14281: 
14282: @example
14283: \ generic mach file for pc gforth                       03sep97jaw
14284: 
14285: true DefaultValue NIL  \ relocating
14286: 
14287: >ENVIRON
14288: 
14289: true DefaultValue file          \ controls the presence of the
14290:                                 \ file access wordset
14291: true DefaultValue OS            \ flag to indicate a operating system
14292: 
14293: true DefaultValue prims         \ true: primitives are c-code
14294: 
14295: true DefaultValue floating      \ floating point wordset is present
14296: 
14297: true DefaultValue glocals       \ gforth locals are present
14298:                                 \ will be loaded
14299: true DefaultValue dcomps        \ double number comparisons
14300: 
14301: true DefaultValue hash          \ hashing primitives are loaded/present
14302: 
14303: true DefaultValue xconds        \ used together with glocals,
14304:                                 \ special conditionals supporting gforths'
14305:                                 \ local variables
14306: true DefaultValue header        \ save a header information
14307: 
14308: true DefaultValue backtrace     \ enables backtrace code
14309: 
14310: false DefaultValue ec
14311: false DefaultValue crlf
14312: 
14313: cell 2 = [IF] &32 [ELSE] &256 [THEN] KB DefaultValue kernel-size
14314: 
14315: &16 KB          DefaultValue stack-size
14316: &15 KB &512 +   DefaultValue fstack-size
14317: &15 KB          DefaultValue rstack-size
14318: &14 KB &512 +   DefaultValue lstack-size
14319: @end example
14320: 
14321: @node How the Cross Compiler Works,  , Using the Cross Compiler, Cross Compiler
14322: @section How the Cross Compiler Works
14323: 
14324: @node Bugs, Origin, Cross Compiler, Top
14325: @appendix Bugs
14326: @cindex bug reporting
14327: 
14328: Known bugs are described in the file @file{BUGS} in the Gforth distribution.
14329: 
14330: If you find a bug, please send a bug report to
14331: @email{bug-gforth@@gnu.org}. A bug report should include this
14332: information:
14333: 
14334: @itemize @bullet
14335: @item
14336: The Gforth version used (it is announced at the start of an
14337: interactive Gforth session).
14338: @item
14339: The machine and operating system (on Unix
14340: systems @code{uname -a} will report this information).
14341: @item
14342: The installation options (send the file @file{config.status}).
14343: @item
14344: A complete list of changes (if any) you (or your installer) have made to the
14345: Gforth sources.
14346: @item
14347: A program (or a sequence of keyboard commands) that reproduces the bug.
14348: @item
14349: A description of what you think constitutes the buggy behaviour.
14350: @end itemize
14351: 
14352: For a thorough guide on reporting bugs read @ref{Bug Reporting, , How
14353: to Report Bugs, gcc.info, GNU C Manual}.
14354: 
14355: 
14356: @node Origin, Forth-related information, Bugs, Top
14357: @appendix Authors and Ancestors of Gforth
14358: 
14359: @section Authors and Contributors
14360: @cindex authors of Gforth
14361: @cindex contributors to Gforth
14362: 
14363: The Gforth project was started in mid-1992 by Bernd Paysan and Anton
14364: Ertl. The third major author was Jens Wilke.  Lennart Benschop (who was
14365: one of Gforth's first users, in mid-1993) and Stuart Ramsden inspired us
14366: with their continuous feedback. Lennart Benshop contributed
14367: @file{glosgen.fs}, while Stuart Ramsden has been working on automatic
14368: support for calling C libraries. Helpful comments also came from Paul
14369: Kleinrubatscher, Christian Pirker, Dirk Zoller, Marcel Hendrix, John
14370: Wavrik, Barrie Stott, Marc de Groot, Jorge Acerada, Bruce Hoyt, and
14371: Robert Epprecht. Since the release of Gforth-0.2.1 there were also
14372: helpful comments from many others; thank you all, sorry for not listing
14373: you here (but digging through my mailbox to extract your names is on my
14374: to-do list). Since the release of Gforth-0.4.0 Neal Crook worked on the
14375: manual.
14376: 
14377: Gforth also owes a lot to the authors of the tools we used (GCC, CVS,
14378: and autoconf, among others), and to the creators of the Internet: Gforth
14379: was developed across the Internet, and its authors did not meet
14380: physically for the first 4 years of development.
14381: 
14382: @section Pedigree
14383: @cindex pedigree of Gforth
14384: 
14385: Gforth descends from bigFORTH (1993) and fig-Forth. Gforth and PFE (by
14386: Dirk Zoller) will cross-fertilize each other. Of course, a significant
14387: part of the design of Gforth was prescribed by ANS Forth.
14388: 
14389: Bernd Paysan wrote bigFORTH, a descendent from TurboForth, an unreleased
14390: 32 bit native code version of VolksForth for the Atari ST, written
14391: mostly by Dietrich Weineck.
14392: 
14393: VolksForth descends from F83. It was written by Klaus Schleisiek, Bernd
14394: Pennemann, Georg Rehfeld and Dietrich Weineck for the C64 (called
14395: UltraForth there) in the mid-80s and ported to the Atari ST in 1986.
14396: 
14397: Henry Laxen and Mike Perry wrote F83 as a model implementation of the
14398: Forth-83 standard. !! Pedigree? When?
14399: 
14400: A team led by Bill Ragsdale implemented fig-Forth on many processors in
14401: 1979. Robert Selzer and Bill Ragsdale developed the original
14402: implementation of fig-Forth for the 6502 based on microForth.
14403: 
14404: The principal architect of microForth was Dean Sanderson. microForth was
14405: FORTH, Inc.'s first off-the-shelf product. It was developed in 1976 for
14406: the 1802, and subsequently implemented on the 8080, the 6800 and the
14407: Z80.
14408: 
14409: All earlier Forth systems were custom-made, usually by Charles Moore,
14410: who discovered (as he puts it) Forth during the late 60s. The first full
14411: Forth existed in 1971.
14412: 
14413: A part of the information in this section comes from @cite{The Evolution
14414: of Forth} by Elizabeth D. Rather, Donald R. Colburn and Charles
14415: H. Moore, presented at the HOPL-II conference and preprinted in SIGPLAN
14416: Notices 28(3), 1993.  You can find more historical and genealogical
14417: information about Forth there.
14418: 
14419: @node Forth-related information, Word Index, Origin, Top
14420: @appendix Other Forth-related information
14421: @cindex Forth-related information
14422: 
14423: @menu
14424: * Internet resources::          
14425: * Books::                       
14426: * The Forth Interest Group::    
14427: * Conferences::                 
14428: @end menu
14429: 
14430: 
14431: @node Internet resources, Books, Forth-related information, Forth-related information
14432: @section Internet resources
14433: @cindex internet resources
14434: 
14435: @cindex comp.lang.forth
14436: @cindex frequently asked questions
14437: There is an active news group (comp.lang.forth) discussing Forth and
14438: Forth-related issues. A frequently-asked-questions (FAQ) list
14439: is posted to the news group regularly, and archived at these sites:
14440: 
14441: @itemize @bullet
14442: @item
14443: @uref{ftp://rtfm.mit.edu/pub/usenet-by-group/comp.lang.forth/}
14444: @item
14445: @uref{ftp://ftp.forth.org/pub/Forth/FAQ/}
14446: @end itemize
14447: 
14448: The FAQ list should be considered mandatory reading before posting to
14449: the news group.
14450: 
14451: Here are some other web sites holding Forth-related material:
14452: 
14453: @itemize @bullet
14454: @item
14455: @uref{http://www.taygeta.com/forth.html} -- Skip Carter's Forth pages.
14456: @item
14457: @uref{http://www.jwdt.com/~paysan/gforth.html} -- the Gforth home page.
14458: @item
14459: @uref{http://www.minerva.com/uathena.htm} -- home of ANS Forth Standard.
14460: @item
14461: @uref{http://dec.bournemouth.ac.uk/forth/index.html} -- the Forth
14462: Research page, including links to the Journal of Forth Application and
14463: Research (JFAR) and a searchable Forth bibliography.
14464: @end itemize
14465: 
14466: 
14467: @node Books, The Forth Interest Group, Internet resources, Forth-related information
14468: @section Books
14469: @cindex books on Forth
14470: 
14471: As the Standard is relatively new, there are not many books out yet. It
14472: is not recommended to learn Forth by using Gforth and a book that is not
14473: written for ANS Forth, as you will not know your mistakes from the
14474: deviations of the book. However, books based on the Forth-83 standard
14475: should be ok, because ANS Forth is primarily an extension of Forth-83.
14476: Refer to the Forth FAQ for details of Forth-related books.
14477: 
14478: @cindex standard document for ANS Forth
14479: @cindex ANS Forth document
14480: The definite reference if you want to write ANS Forth programs is, of
14481: course, the ANS Forth document. It is available in printed form from the
14482: National Standards Institute Sales Department (Tel.: USA (212) 642-4900;
14483: Fax.: USA (212) 302-1286) as document @cite{X3.215-1994} for about
14484: $200. You can also get it from Global Engineering Documents (Tel.: USA
14485: (800) 854-7179; Fax.: (303) 843-9880) for about $300.
14486: 
14487: @cite{dpANS6}, the last draft of the standard, which was then submitted
14488: to ANSI for publication is available electronically and for free in some
14489: MS Word format, and it has been converted to HTML
14490: (@uref{http://www.taygeta.com/forth/dpans.html}; this HTML version also
14491: includes the answers to Requests for Interpretation (RFIs). Some
14492: pointers to these versions can be found through
14493: @*@uref{http://www.complang.tuwien.ac.at/projects/forth.html}.
14494: 
14495: 
14496: @node The Forth Interest Group, Conferences, Books, Forth-related information
14497: @section The Forth Interest Group
14498: @cindex Forth interest group (FIG)
14499: 
14500: The Forth Interest Group (FIG) is a world-wide, non-profit,
14501: member-supported organisation. It publishes a regular magazine,
14502: @var{FORTH Dimensions}, and offers other benefits of membership. You can
14503: contact the FIG through their office email address:
14504: @email{office@@forth.org} or by visiting their web site at
14505: @uref{http://www.forth.org/}. This web site also includes links to FIG
14506: chapters in other countries and American cities
14507: (@uref{http://www.forth.org/chapters.html}).
14508: 
14509: @node Conferences,  , The Forth Interest Group, Forth-related information
14510: @section Conferences
14511: @cindex Conferences
14512: 
14513: There are several regular conferences related to Forth. They are all
14514: well-publicised in @var{FORTH Dimensions} and on the comp.lang.forth
14515: news group:
14516: 
14517: @itemize @bullet
14518: @item
14519: FORML -- the Forth modification laboratory convenes every year near
14520: Monterey, California.
14521: @item
14522: The Rochester Forth Conference -- an annual conference traditionally
14523: held in Rochester, New York.
14524: @item
14525: EuroForth -- this European conference takes place annually.
14526: @end itemize
14527: 
14528: 
14529: @node Word Index, Name Index, Forth-related information, Top
14530: @unnumbered Word Index
14531: 
14532: This index is a list of Forth words that have ``glossary'' entries
14533: within this manual. Each word is listed with its stack effect and
14534: wordset.
14535: 
14536: @printindex fn
14537: 
14538: @node Name Index, Concept Index, Word Index, Top
14539: @unnumbered Name Index
14540: 
14541: This index is a list of Forth words that have ``glossary'' entries
14542: within this manual.
14543: 
14544: @printindex ky
14545: 
14546: @node Concept Index,  , Name Index, Top
14547: @unnumbered Concept and Word Index
14548: 
14549: Not all entries listed in this index are present verbatim in the
14550: text. This index also duplicates, in abbreviated form, all of the words
14551: listed in the Word Index (only the names are listed for the words here).
14552: 
14553: @printindex cp
14554: 
14555: @contents
14556: @bye
14557: 

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