File:  [gforth] / gforth / doc / gforth.ds
Revision 1.84: download - view: text, annotated - select for diffs
Sun Sep 3 22:29:16 2000 UTC (23 years, 7 months ago) by pazsan
Branches: MAIN
CVS tags: HEAD
Added Files section to the tutorial
changed sfind .. [if] into [ifdef] in tt.fs

    1: \input texinfo   @c -*-texinfo-*-
    2: @comment The source is gforth.ds, from which gforth.texi is generated
    3: 
    4: @comment TODO: nac29jan99 - a list of things to add in the next edit:
    5: @comment 1. x-ref all ambiguous or implementation-defined features?
    6: @comment 2. Describe the use of Auser Avariable AConstant A, etc.
    7: @comment 3. words in miscellaneous section need a home.
    8: @comment 4. search for TODO for other minor and major works required.
    9: @comment 5. [rats] change all @var to @i in Forth source so that info
   10: @comment    file looks decent.
   11: @c          Not an improvement IMO - anton
   12: @c          and anyway, this should be taken up
   13: @c          with Karl Berry (the texinfo guy) - anton
   14: @comment .. would be useful to have a word that identified all deferred words
   15: @comment should semantics stuff in intro be moved to another section
   16: 
   17: @c POSTPONE, COMPILE, [COMPILE], LITERAL should have their own section
   18: 
   19: @comment %**start of header (This is for running Texinfo on a region.)
   20: @setfilename gforth.info
   21: @settitle Gforth Manual
   22: @dircategory GNU programming tools
   23: @direntry
   24: * Gforth: (gforth).             A fast interpreter for the Forth language.
   25: @end direntry
   26: @c The Texinfo manual also recommends doing this, but for Gforth it may
   27: @c  not make much sense
   28: @c @dircategory Individual utilities
   29: @c @direntry
   30: @c * Gforth: (gforth)Invoking Gforth.      gforth, gforth-fast, gforthmi
   31: @c @end direntry
   32: 
   33: @comment @setchapternewpage odd
   34: @comment TODO this gets left in by HTML converter
   35: @macro progstyle {}
   36: Programming style note:
   37: @end macro
   38: 
   39: @macro assignment {}
   40: @table @i
   41: @item Assignment:
   42: @end macro
   43: @macro endassignment {}
   44: @end table
   45: @end macro
   46: 
   47: @comment %**end of header (This is for running Texinfo on a region.)
   48: 
   49: 
   50: @comment ----------------------------------------------------------
   51: @comment macros for beautifying glossary entries
   52: @comment if these are used, need to strip them out for HTML converter
   53: @comment else they get repeated verbatim in HTML output.
   54: @comment .. not working yet.
   55: 
   56: @macro GLOSS-START {}
   57: @iftex
   58: @ninerm
   59: @end iftex
   60: @end macro
   61: 
   62: @macro GLOSS-END {}
   63: @iftex
   64: @rm
   65: @end iftex
   66: @end macro
   67: 
   68: @comment ----------------------------------------------------------
   69: 
   70: 
   71: @include version.texi
   72: 
   73: @ifnottex
   74: This file documents Gforth @value{VERSION}
   75: 
   76: Copyright @copyright{} 1995--2000 Free Software Foundation, Inc.
   77: 
   78:      Permission is granted to make and distribute verbatim copies of
   79:      this manual provided the copyright notice and this permission notice
   80:      are preserved on all copies.
   81:      
   82: @ignore
   83:      Permission is granted to process this file through TeX and print the
   84:      results, provided the printed document carries a copying permission
   85:      notice identical to this one except for the removal of this paragraph
   86:      (this paragraph not being relevant to the printed manual).
   87:      
   88: @end ignore
   89:      Permission is granted to copy and distribute modified versions of this
   90:      manual under the conditions for verbatim copying, provided also that the
   91:      sections entitled "Distribution" and "General Public License" are
   92:      included exactly as in the original, and provided that the entire
   93:      resulting derived work is distributed under the terms of a permission
   94:      notice identical to this one.
   95:      
   96:      Permission is granted to copy and distribute translations of this manual
   97:      into another language, under the above conditions for modified versions,
   98:      except that the sections entitled "Distribution" and "General Public
   99:      License" may be included in a translation approved by the author instead
  100:      of in the original English.
  101: @end ifnottex
  102: 
  103: @finalout
  104: @titlepage
  105: @sp 10
  106: @center @titlefont{Gforth Manual}
  107: @sp 2
  108: @center for version @value{VERSION}
  109: @sp 2
  110: @center Neal Crook
  111: @center Anton Ertl
  112: @center Bernd Paysan
  113: @center Jens Wilke
  114: @sp 3
  115: @center This manual is permanently under construction and was last updated on 15-Mar-2000
  116: 
  117: @comment  The following two commands start the copyright page.
  118: @page
  119: @vskip 0pt plus 1filll
  120: Copyright @copyright{} 1995--2000 Free Software Foundation, Inc.
  121: 
  122: @comment !! Published by ... or You can get a copy of this manual ...
  123: 
  124:      Permission is granted to make and distribute verbatim copies of
  125:      this manual provided the copyright notice and this permission notice
  126:      are preserved on all copies.
  127:      
  128:      Permission is granted to copy and distribute modified versions of this
  129:      manual under the conditions for verbatim copying, provided also that the
  130:      sections entitled "Distribution" and "General Public License" are
  131:      included exactly as in the original, and provided that the entire
  132:      resulting derived work is distributed under the terms of a permission
  133:      notice identical to this one.
  134:      
  135:      Permission is granted to copy and distribute translations of this manual
  136:      into another language, under the above conditions for modified versions,
  137:      except that the sections entitled "Distribution" and "General Public
  138:      License" may be included in a translation approved by the author instead
  139:      of in the original English.
  140: @end titlepage
  141: 
  142: @node Top, License, (dir), (dir)
  143: @ifnottex
  144: Gforth is a free implementation of ANS Forth available on many
  145: personal machines. This manual corresponds to version @value{VERSION}.
  146: @end ifnottex
  147: 
  148: @menu
  149: * License::                     The GPL
  150: * Goals::                       About the Gforth Project
  151: * Gforth Environment::          Starting (and exiting) Gforth
  152: * Tutorial::                    Hands-on Forth Tutorial
  153: * Introduction::                An introduction to ANS Forth
  154: * Words::                       Forth words available in Gforth
  155: * Error messages::              How to interpret them
  156: * Tools::                       Programming tools
  157: * ANS conformance::             Implementation-defined options etc.
  158: * Standard vs Extensions::      Should I use extensions?
  159: * Model::                       The abstract machine of Gforth
  160: * Integrating Gforth::          Forth as scripting language for applications
  161: * Emacs and Gforth::            The Gforth Mode
  162: * Image Files::                 @code{.fi} files contain compiled code
  163: * Engine::                      The inner interpreter and the primitives
  164: * Binding to System Library::   
  165: * Cross Compiler::              The Cross Compiler
  166: * Bugs::                        How to report them
  167: * Origin::                      Authors and ancestors of Gforth
  168: * Forth-related information::   Books and places to look on the WWW
  169: * Word Index::                  An item for each Forth word
  170: * Concept Index::               A menu covering many topics
  171: 
  172: @detailmenu --- The Detailed Node Listing ---
  173: 
  174: Gforth Environment
  175: 
  176: * Invoking Gforth::             Getting in
  177: * Leaving Gforth::              Getting out
  178: * Command-line editing::        
  179: * Environment variables::       that affect how Gforth starts up
  180: * Gforth Files::                What gets installed and where
  181: * Startup speed::               When 35ms is not fast enough ...
  182: 
  183: Forth Tutorial
  184: 
  185: * Starting Gforth Tutorial::    
  186: * Syntax Tutorial::             
  187: * Crash Course Tutorial::       
  188: * Stack Tutorial::              
  189: * Arithmetics Tutorial::        
  190: * Stack Manipulation Tutorial::  
  191: * Using files for Forth code Tutorial::  
  192: * Comments Tutorial::           
  193: * Colon Definitions Tutorial::  
  194: * Decompilation Tutorial::      
  195: * Stack-Effect Comments Tutorial::  
  196: * Types Tutorial::              
  197: * Factoring Tutorial::          
  198: * Designing the stack effect Tutorial::  
  199: * Local Variables Tutorial::    
  200: * Conditional execution Tutorial::  
  201: * Flags and Comparisons Tutorial::  
  202: * General Loops Tutorial::      
  203: * Counted loops Tutorial::      
  204: * Recursion Tutorial::          
  205: * Leaving definitions or loops Tutorial::  
  206: * Return Stack Tutorial::       
  207: * Memory Tutorial::             
  208: * Characters and Strings Tutorial::  
  209: * Alignment Tutorial::          
  210: * Interpretation and Compilation Semantics and Immediacy Tutorial::  
  211: * Execution Tokens Tutorial::   
  212: * Exceptions Tutorial::         
  213: * Defining Words Tutorial::     
  214: * Arrays and Records Tutorial::  
  215: * POSTPONE Tutorial::           
  216: * Literal Tutorial::            
  217: * Advanced macros Tutorial::    
  218: * Compilation Tokens Tutorial::  
  219: * Wordlists and Search Order Tutorial::  
  220: 
  221: An Introduction to ANS Forth
  222: 
  223: * Introducing the Text Interpreter::  
  224: * Stacks and Postfix notation::  
  225: * Your first definition::       
  226: * How does that work?::         
  227: * Forth is written in Forth::   
  228: * Review - elements of a Forth system::  
  229: * Where to go next::            
  230: * Exercises::                   
  231: 
  232: Forth Words
  233: 
  234: * Notation::                    
  235: * Case insensitivity::          
  236: * Comments::                    
  237: * Boolean Flags::               
  238: * Arithmetic::                  
  239: * Stack Manipulation::          
  240: * Memory::                      
  241: * Control Structures::          
  242: * Defining Words::              
  243: * Interpretation and Compilation Semantics::  
  244: * Tokens for Words::            
  245: * Compiling words::             
  246: * The Text Interpreter::        
  247: * Word Lists::                  
  248: * Environmental Queries::       
  249: * Files::                       
  250: * Blocks::                      
  251: * Other I/O::                   
  252: * Locals::                      
  253: * Structures::                  
  254: * Object-oriented Forth::       
  255: * Programming Tools::           
  256: * Assembler and Code Words::    
  257: * Threading Words::             
  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::             Passing definition names as strings
  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: Tokens for Words
  321: 
  322: * Execution token::             represents execution/interpretation semantics
  323: * Compilation token::           represents compilation semantics
  324: * Name token::                  represents named words
  325: 
  326: Compiling words
  327: 
  328: * Literals::                    Compiling data values
  329: * Macros::                      Compiling words
  330: 
  331: The Text Interpreter
  332: 
  333: * Input Sources::               
  334: * Number Conversion::           
  335: * Interpret/Compile states::    
  336: * Interpreter Directives::      
  337: 
  338: Word Lists
  339: 
  340: * Vocabularies::                
  341: * Why use word lists?::         
  342: * Word list example::           
  343: 
  344: Files
  345: 
  346: * Forth source files::          
  347: * General files::               
  348: * Search Paths::                
  349: 
  350: Search Paths
  351: 
  352: * Source Search Paths::         
  353: * General Search Paths::        
  354: 
  355: Other I/O
  356: 
  357: * Simple numeric output::       Predefined formats
  358: * Formatted numeric output::    Formatted (pictured) output
  359: * String Formats::              How Forth stores strings in memory
  360: * Displaying characters and strings::  Other stuff
  361: * Input::                       Input
  362: 
  363: Locals
  364: 
  365: * Gforth locals::               
  366: * ANS Forth locals::            
  367: 
  368: Gforth locals
  369: 
  370: * Where are locals visible by name?::  
  371: * How long do locals live?::    
  372: * Locals programming style::    
  373: * Locals implementation::       
  374: 
  375: Structures
  376: 
  377: * Why explicit structure support?::  
  378: * Structure Usage::             
  379: * Structure Naming Convention::  
  380: * Structure Implementation::    
  381: * Structure Glossary::          
  382: 
  383: Object-oriented Forth
  384: 
  385: * Why object-oriented programming?::  
  386: * Object-Oriented Terminology::  
  387: * Objects::                     
  388: * OOF::                         
  389: * Mini-OOF::                    
  390: * Comparison with other object models::  
  391: 
  392: The @file{objects.fs} model
  393: 
  394: * Properties of the Objects model::  
  395: * Basic Objects Usage::         
  396: * The Objects base class::      
  397: * Creating objects::            
  398: * Object-Oriented Programming Style::  
  399: * Class Binding::               
  400: * Method conveniences::         
  401: * Classes and Scoping::         
  402: * Dividing classes::            
  403: * Object Interfaces::           
  404: * Objects Implementation::      
  405: * Objects Glossary::            
  406: 
  407: The @file{oof.fs} model
  408: 
  409: * Properties of the OOF model::  
  410: * Basic OOF Usage::             
  411: * The OOF base class::          
  412: * Class Declaration::           
  413: * Class Implementation::        
  414: 
  415: The @file{mini-oof.fs} model
  416: 
  417: * Basic Mini-OOF Usage::        
  418: * Mini-OOF Example::            
  419: * Mini-OOF Implementation::     
  420: 
  421: Programming Tools
  422: 
  423: * Examining::                   
  424: * Forgetting words::            
  425: * Debugging::                   Simple and quick.
  426: * Assertions::                  Making your programs self-checking.
  427: * Singlestep Debugger::         Executing your program word by word.
  428: 
  429: Assembler and Code Words
  430: 
  431: * Code and ;code::              
  432: * Common Assembler::            Assembler Syntax
  433: * Common Disassembler::         
  434: * 386 Assembler::               Deviations and special cases
  435: * Alpha Assembler::             Deviations and special cases
  436: * MIPS assembler::              Deviations and special cases
  437: * Other assemblers::            How to write them
  438: 
  439: Tools
  440: 
  441: * ANS Report::                  Report the words used, sorted by wordset.
  442: 
  443: ANS conformance
  444: 
  445: * The Core Words::              
  446: * The optional Block word set::  
  447: * The optional Double Number word set::  
  448: * The optional Exception word set::  
  449: * The optional Facility word set::  
  450: * The optional File-Access word set::  
  451: * The optional Floating-Point word set::  
  452: * The optional Locals word set::  
  453: * The optional Memory-Allocation word set::  
  454: * The optional Programming-Tools word set::  
  455: * The optional Search-Order word set::  
  456: 
  457: The Core Words
  458: 
  459: * core-idef::                   Implementation Defined Options                   
  460: * core-ambcond::                Ambiguous Conditions                
  461: * core-other::                  Other System Documentation                  
  462: 
  463: The optional Block word set
  464: 
  465: * block-idef::                  Implementation Defined Options
  466: * block-ambcond::               Ambiguous Conditions               
  467: * block-other::                 Other System Documentation                 
  468: 
  469: The optional Double Number word set
  470: 
  471: * double-ambcond::              Ambiguous Conditions              
  472: 
  473: The optional Exception word set
  474: 
  475: * exception-idef::              Implementation Defined Options              
  476: 
  477: The optional Facility word set
  478: 
  479: * facility-idef::               Implementation Defined Options               
  480: * facility-ambcond::            Ambiguous Conditions            
  481: 
  482: The optional File-Access word set
  483: 
  484: * file-idef::                   Implementation Defined Options
  485: * file-ambcond::                Ambiguous Conditions                
  486: 
  487: The optional Floating-Point word set
  488: 
  489: * floating-idef::               Implementation Defined Options
  490: * floating-ambcond::            Ambiguous Conditions            
  491: 
  492: The optional Locals word set
  493: 
  494: * locals-idef::                 Implementation Defined Options                 
  495: * locals-ambcond::              Ambiguous Conditions              
  496: 
  497: The optional Memory-Allocation word set
  498: 
  499: * memory-idef::                 Implementation Defined Options                 
  500: 
  501: The optional Programming-Tools word set
  502: 
  503: * programming-idef::            Implementation Defined Options            
  504: * programming-ambcond::         Ambiguous Conditions         
  505: 
  506: The optional Search-Order word set
  507: 
  508: * search-idef::                 Implementation Defined Options                 
  509: * search-ambcond::              Ambiguous Conditions              
  510: 
  511: Image Files
  512: 
  513: * Image Licensing Issues::      Distribution terms for images.
  514: * Image File Background::       Why have image files?
  515: * Non-Relocatable Image Files::  don't always work.
  516: * Data-Relocatable Image Files::  are better.
  517: * Fully Relocatable Image Files::  better yet.
  518: * Stack and Dictionary Sizes::  Setting the default sizes for an image.
  519: * Running Image Files::         @code{gforth -i @i{file}} or @i{file}.
  520: * Modifying the Startup Sequence::  and turnkey applications.
  521: 
  522: Fully Relocatable Image Files
  523: 
  524: * gforthmi::                    The normal way
  525: * cross.fs::                    The hard way
  526: 
  527: Engine
  528: 
  529: * Portability::                 
  530: * Threading::                   
  531: * Primitives::                  
  532: * Performance::                 
  533: 
  534: Threading
  535: 
  536: * Scheduling::                  
  537: * Direct or Indirect Threaded?::  
  538: * DOES>::                       
  539: 
  540: Primitives
  541: 
  542: * Automatic Generation::        
  543: * TOS Optimization::            
  544: * Produced code::               
  545: 
  546: Cross Compiler
  547: 
  548: * Using the Cross Compiler::    
  549: * How the Cross Compiler Works::  
  550: 
  551: @end detailmenu
  552: @end menu
  553: 
  554: @node License, Goals, Top, Top
  555: @unnumbered GNU GENERAL PUBLIC LICENSE
  556: @center Version 2, June 1991
  557: 
  558: @display
  559: Copyright @copyright{} 1989, 1991 Free Software Foundation, Inc.
  560: 675 Mass Ave, Cambridge, MA 02139, USA
  561: 
  562: Everyone is permitted to copy and distribute verbatim copies
  563: of this license document, but changing it is not allowed.
  564: @end display
  565: 
  566: @unnumberedsec Preamble
  567: 
  568:   The licenses for most software are designed to take away your
  569: freedom to share and change it.  By contrast, the GNU General Public
  570: License is intended to guarantee your freedom to share and change free
  571: software---to make sure the software is free for all its users.  This
  572: General Public License applies to most of the Free Software
  573: Foundation's software and to any other program whose authors commit to
  574: using it.  (Some other Free Software Foundation software is covered by
  575: the GNU Library General Public License instead.)  You can apply it to
  576: your programs, too.
  577: 
  578:   When we speak of free software, we are referring to freedom, not
  579: price.  Our General Public Licenses are designed to make sure that you
  580: have the freedom to distribute copies of free software (and charge for
  581: this service if you wish), that you receive source code or can get it
  582: if you want it, that you can change the software or use pieces of it
  583: in new free programs; and that you know you can do these things.
  584: 
  585:   To protect your rights, we need to make restrictions that forbid
  586: anyone to deny you these rights or to ask you to surrender the rights.
  587: These restrictions translate to certain responsibilities for you if you
  588: distribute copies of the software, or if you modify it.
  589: 
  590:   For example, if you distribute copies of such a program, whether
  591: gratis or for a fee, you must give the recipients all the rights that
  592: you have.  You must make sure that they, too, receive or can get the
  593: source code.  And you must show them these terms so they know their
  594: rights.
  595: 
  596:   We protect your rights with two steps: (1) copyright the software, and
  597: (2) offer you this license which gives you legal permission to copy,
  598: distribute and/or modify the software.
  599: 
  600:   Also, for each author's protection and ours, we want to make certain
  601: that everyone understands that there is no warranty for this free
  602: software.  If the software is modified by someone else and passed on, we
  603: want its recipients to know that what they have is not the original, so
  604: that any problems introduced by others will not reflect on the original
  605: authors' reputations.
  606: 
  607:   Finally, any free program is threatened constantly by software
  608: patents.  We wish to avoid the danger that redistributors of a free
  609: program will individually obtain patent licenses, in effect making the
  610: program proprietary.  To prevent this, we have made it clear that any
  611: patent must be licensed for everyone's free use or not licensed at all.
  612: 
  613:   The precise terms and conditions for copying, distribution and
  614: modification follow.
  615: 
  616: @iftex
  617: @unnumberedsec TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
  618: @end iftex
  619: @ifnottex
  620: @center TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
  621: @end ifnottex
  622: 
  623: @enumerate 0
  624: @item
  625: This License applies to any program or other work which contains
  626: a notice placed by the copyright holder saying it may be distributed
  627: under the terms of this General Public License.  The ``Program'', below,
  628: refers to any such program or work, and a ``work based on the Program''
  629: means either the Program or any derivative work under copyright law:
  630: that is to say, a work containing the Program or a portion of it,
  631: either verbatim or with modifications and/or translated into another
  632: language.  (Hereinafter, translation is included without limitation in
  633: the term ``modification''.)  Each licensee is addressed as ``you''.
  634: 
  635: Activities other than copying, distribution and modification are not
  636: covered by this License; they are outside its scope.  The act of
  637: running the Program is not restricted, and the output from the Program
  638: is covered only if its contents constitute a work based on the
  639: Program (independent of having been made by running the Program).
  640: Whether that is true depends on what the Program does.
  641: 
  642: @item
  643: You may copy and distribute verbatim copies of the Program's
  644: source code as you receive it, in any medium, provided that you
  645: conspicuously and appropriately publish on each copy an appropriate
  646: copyright notice and disclaimer of warranty; keep intact all the
  647: notices that refer to this License and to the absence of any warranty;
  648: and give any other recipients of the Program a copy of this License
  649: along with the Program.
  650: 
  651: You may charge a fee for the physical act of transferring a copy, and
  652: you may at your option offer warranty protection in exchange for a fee.
  653: 
  654: @item
  655: You may modify your copy or copies of the Program or any portion
  656: of it, thus forming a work based on the Program, and copy and
  657: distribute such modifications or work under the terms of Section 1
  658: above, provided that you also meet all of these conditions:
  659: 
  660: @enumerate a
  661: @item
  662: You must cause the modified files to carry prominent notices
  663: stating that you changed the files and the date of any change.
  664: 
  665: @item
  666: You must cause any work that you distribute or publish, that in
  667: whole or in part contains or is derived from the Program or any
  668: part thereof, to be licensed as a whole at no charge to all third
  669: parties under the terms of this License.
  670: 
  671: @item
  672: If the modified program normally reads commands interactively
  673: when run, you must cause it, when started running for such
  674: interactive use in the most ordinary way, to print or display an
  675: announcement including an appropriate copyright notice and a
  676: notice that there is no warranty (or else, saying that you provide
  677: a warranty) and that users may redistribute the program under
  678: these conditions, and telling the user how to view a copy of this
  679: License.  (Exception: if the Program itself is interactive but
  680: does not normally print such an announcement, your work based on
  681: the Program is not required to print an announcement.)
  682: @end enumerate
  683: 
  684: These requirements apply to the modified work as a whole.  If
  685: identifiable sections of that work are not derived from the Program,
  686: and can be reasonably considered independent and separate works in
  687: themselves, then this License, and its terms, do not apply to those
  688: sections when you distribute them as separate works.  But when you
  689: distribute the same sections as part of a whole which is a work based
  690: on the Program, the distribution of the whole must be on the terms of
  691: this License, whose permissions for other licensees extend to the
  692: entire whole, and thus to each and every part regardless of who wrote it.
  693: 
  694: Thus, it is not the intent of this section to claim rights or contest
  695: your rights to work written entirely by you; rather, the intent is to
  696: exercise the right to control the distribution of derivative or
  697: collective works based on the Program.
  698: 
  699: In addition, mere aggregation of another work not based on the Program
  700: with the Program (or with a work based on the Program) on a volume of
  701: a storage or distribution medium does not bring the other work under
  702: the scope of this License.
  703: 
  704: @item
  705: You may copy and distribute the Program (or a work based on it,
  706: under Section 2) in object code or executable form under the terms of
  707: Sections 1 and 2 above provided that you also do one of the following:
  708: 
  709: @enumerate a
  710: @item
  711: Accompany it with the complete corresponding machine-readable
  712: source code, which must be distributed under the terms of Sections
  713: 1 and 2 above on a medium customarily used for software interchange; or,
  714: 
  715: @item
  716: Accompany it with a written offer, valid for at least three
  717: years, to give any third party, for a charge no more than your
  718: cost of physically performing source distribution, a complete
  719: machine-readable copy of the corresponding source code, to be
  720: distributed under the terms of Sections 1 and 2 above on a medium
  721: customarily used for software interchange; or,
  722: 
  723: @item
  724: Accompany it with the information you received as to the offer
  725: to distribute corresponding source code.  (This alternative is
  726: allowed only for noncommercial distribution and only if you
  727: received the program in object code or executable form with such
  728: an offer, in accord with Subsection b above.)
  729: @end enumerate
  730: 
  731: The source code for a work means the preferred form of the work for
  732: making modifications to it.  For an executable work, complete source
  733: code means all the source code for all modules it contains, plus any
  734: associated interface definition files, plus the scripts used to
  735: control compilation and installation of the executable.  However, as a
  736: special exception, the source code distributed need not include
  737: anything that is normally distributed (in either source or binary
  738: form) with the major components (compiler, kernel, and so on) of the
  739: operating system on which the executable runs, unless that component
  740: itself accompanies the executable.
  741: 
  742: If distribution of executable or object code is made by offering
  743: access to copy from a designated place, then offering equivalent
  744: access to copy the source code from the same place counts as
  745: distribution of the source code, even though third parties are not
  746: compelled to copy the source along with the object code.
  747: 
  748: @item
  749: You may not copy, modify, sublicense, or distribute the Program
  750: except as expressly provided under this License.  Any attempt
  751: otherwise to copy, modify, sublicense or distribute the Program is
  752: void, and will automatically terminate your rights under this License.
  753: However, parties who have received copies, or rights, from you under
  754: this License will not have their licenses terminated so long as such
  755: parties remain in full compliance.
  756: 
  757: @item
  758: You are not required to accept this License, since you have not
  759: signed it.  However, nothing else grants you permission to modify or
  760: distribute the Program or its derivative works.  These actions are
  761: prohibited by law if you do not accept this License.  Therefore, by
  762: modifying or distributing the Program (or any work based on the
  763: Program), you indicate your acceptance of this License to do so, and
  764: all its terms and conditions for copying, distributing or modifying
  765: the Program or works based on it.
  766: 
  767: @item
  768: Each time you redistribute the Program (or any work based on the
  769: Program), the recipient automatically receives a license from the
  770: original licensor to copy, distribute or modify the Program subject to
  771: these terms and conditions.  You may not impose any further
  772: restrictions on the recipients' exercise of the rights granted herein.
  773: You are not responsible for enforcing compliance by third parties to
  774: this License.
  775: 
  776: @item
  777: If, as a consequence of a court judgment or allegation of patent
  778: infringement or for any other reason (not limited to patent issues),
  779: conditions are imposed on you (whether by court order, agreement or
  780: otherwise) that contradict the conditions of this License, they do not
  781: excuse you from the conditions of this License.  If you cannot
  782: distribute so as to satisfy simultaneously your obligations under this
  783: License and any other pertinent obligations, then as a consequence you
  784: may not distribute the Program at all.  For example, if a patent
  785: license would not permit royalty-free redistribution of the Program by
  786: all those who receive copies directly or indirectly through you, then
  787: the only way you could satisfy both it and this License would be to
  788: refrain entirely from distribution of the Program.
  789: 
  790: If any portion of this section is held invalid or unenforceable under
  791: any particular circumstance, the balance of the section is intended to
  792: apply and the section as a whole is intended to apply in other
  793: circumstances.
  794: 
  795: It is not the purpose of this section to induce you to infringe any
  796: patents or other property right claims or to contest validity of any
  797: such claims; this section has the sole purpose of protecting the
  798: integrity of the free software distribution system, which is
  799: implemented by public license practices.  Many people have made
  800: generous contributions to the wide range of software distributed
  801: through that system in reliance on consistent application of that
  802: system; it is up to the author/donor to decide if he or she is willing
  803: to distribute software through any other system and a licensee cannot
  804: impose that choice.
  805: 
  806: This section is intended to make thoroughly clear what is believed to
  807: be a consequence of the rest of this License.
  808: 
  809: @item
  810: If the distribution and/or use of the Program is restricted in
  811: certain countries either by patents or by copyrighted interfaces, the
  812: original copyright holder who places the Program under this License
  813: may add an explicit geographical distribution limitation excluding
  814: those countries, so that distribution is permitted only in or among
  815: countries not thus excluded.  In such case, this License incorporates
  816: the limitation as if written in the body of this License.
  817: 
  818: @item
  819: The Free Software Foundation may publish revised and/or new versions
  820: of the General Public License from time to time.  Such new versions will
  821: be similar in spirit to the present version, but may differ in detail to
  822: address new problems or concerns.
  823: 
  824: Each version is given a distinguishing version number.  If the Program
  825: specifies a version number of this License which applies to it and ``any
  826: later version'', you have the option of following the terms and conditions
  827: either of that version or of any later version published by the Free
  828: Software Foundation.  If the Program does not specify a version number of
  829: this License, you may choose any version ever published by the Free Software
  830: Foundation.
  831: 
  832: @item
  833: If you wish to incorporate parts of the Program into other free
  834: programs whose distribution conditions are different, write to the author
  835: to ask for permission.  For software which is copyrighted by the Free
  836: Software Foundation, write to the Free Software Foundation; we sometimes
  837: make exceptions for this.  Our decision will be guided by the two goals
  838: of preserving the free status of all derivatives of our free software and
  839: of promoting the sharing and reuse of software generally.
  840: 
  841: @iftex
  842: @heading NO WARRANTY
  843: @end iftex
  844: @ifnottex
  845: @center NO WARRANTY
  846: @end ifnottex
  847: 
  848: @item
  849: BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
  850: FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN
  851: OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
  852: PROVIDE THE PROGRAM ``AS IS'' WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
  853: OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
  854: MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS
  855: TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE
  856: PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
  857: REPAIR OR CORRECTION.
  858: 
  859: @item
  860: IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
  861: WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
  862: REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
  863: INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
  864: OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
  865: TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
  866: YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
  867: PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
  868: POSSIBILITY OF SUCH DAMAGES.
  869: @end enumerate
  870: 
  871: @iftex
  872: @heading END OF TERMS AND CONDITIONS
  873: @end iftex
  874: @ifnottex
  875: @center END OF TERMS AND CONDITIONS
  876: @end ifnottex
  877: 
  878: @page
  879: @unnumberedsec How to Apply These Terms to Your New Programs
  880: 
  881:   If you develop a new program, and you want it to be of the greatest
  882: possible use to the public, the best way to achieve this is to make it
  883: free software which everyone can redistribute and change under these terms.
  884: 
  885:   To do so, attach the following notices to the program.  It is safest
  886: to attach them to the start of each source file to most effectively
  887: convey the exclusion of warranty; and each file should have at least
  888: the ``copyright'' line and a pointer to where the full notice is found.
  889: 
  890: @smallexample
  891: @var{one line to give the program's name and a brief idea of what it does.}
  892: Copyright (C) 19@var{yy}  @var{name of author}
  893: 
  894: This program is free software; you can redistribute it and/or modify 
  895: it under the terms of the GNU General Public License as published by 
  896: the Free Software Foundation; either version 2 of the License, or 
  897: (at your option) any later version.
  898: 
  899: This program is distributed in the hope that it will be useful,
  900: but WITHOUT ANY WARRANTY; without even the implied warranty of
  901: MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  902: GNU General Public License for more details.
  903: 
  904: You should have received a copy of the GNU General Public License
  905: along with this program; if not, write to the Free Software
  906: Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  907: @end smallexample
  908: 
  909: Also add information on how to contact you by electronic and paper mail.
  910: 
  911: If the program is interactive, make it output a short notice like this
  912: when it starts in an interactive mode:
  913: 
  914: @smallexample
  915: Gnomovision version 69, Copyright (C) 19@var{yy} @var{name of author}
  916: Gnomovision comes with ABSOLUTELY NO WARRANTY; for details
  917: type `show w'.  
  918: This is free software, and you are welcome to redistribute it 
  919: under certain conditions; type `show c' for details.
  920: @end smallexample
  921: 
  922: The hypothetical commands @samp{show w} and @samp{show c} should show
  923: the appropriate parts of the General Public License.  Of course, the
  924: commands you use may be called something other than @samp{show w} and
  925: @samp{show c}; they could even be mouse-clicks or menu items---whatever
  926: suits your program.
  927: 
  928: You should also get your employer (if you work as a programmer) or your
  929: school, if any, to sign a ``copyright disclaimer'' for the program, if
  930: necessary.  Here is a sample; alter the names:
  931: 
  932: @smallexample
  933: Yoyodyne, Inc., hereby disclaims all copyright interest in the program
  934: `Gnomovision' (which makes passes at compilers) written by James Hacker.
  935: 
  936: @var{signature of Ty Coon}, 1 April 1989
  937: Ty Coon, President of Vice
  938: @end smallexample
  939: 
  940: This General Public License does not permit incorporating your program into
  941: proprietary programs.  If your program is a subroutine library, you may
  942: consider it more useful to permit linking proprietary applications with the
  943: library.  If this is what you want to do, use the GNU Library General
  944: Public License instead of this License.
  945: 
  946: @iftex
  947: @unnumbered Preface
  948: @cindex Preface
  949: This manual documents Gforth. Some introductory material is provided for
  950: readers who are unfamiliar with Forth or who are migrating to Gforth
  951: from other Forth compilers. However, this manual is primarily a
  952: reference manual.
  953: @end iftex
  954: 
  955: @comment TODO much more blurb here.
  956: 
  957: @c ******************************************************************
  958: @node Goals, Gforth Environment, License, Top
  959: @comment node-name,     next,           previous, up
  960: @chapter Goals of Gforth
  961: @cindex goals of the Gforth project
  962: The goal of the Gforth Project is to develop a standard model for
  963: ANS Forth. This can be split into several subgoals:
  964: 
  965: @itemize @bullet
  966: @item
  967: Gforth should conform to the ANS Forth Standard.
  968: @item
  969: It should be a model, i.e. it should define all the
  970: implementation-dependent things.
  971: @item
  972: It should become standard, i.e. widely accepted and used. This goal
  973: is the most difficult one.
  974: @end itemize
  975: 
  976: To achieve these goals Gforth should be
  977: @itemize @bullet
  978: @item
  979: Similar to previous models (fig-Forth, F83)
  980: @item
  981: Powerful. It should provide for all the things that are considered
  982: necessary today and even some that are not yet considered necessary.
  983: @item
  984: Efficient. It should not get the reputation of being exceptionally
  985: slow.
  986: @item
  987: Free.
  988: @item
  989: Available on many machines/easy to port.
  990: @end itemize
  991: 
  992: Have we achieved these goals? Gforth conforms to the ANS Forth
  993: standard. It may be considered a model, but we have not yet documented
  994: which parts of the model are stable and which parts we are likely to
  995: change. It certainly has not yet become a de facto standard, but it
  996: appears to be quite popular. It has some similarities to and some
  997: differences from previous models. It has some powerful features, but not
  998: yet everything that we envisioned. We certainly have achieved our
  999: execution speed goals (@pxref{Performance})@footnote{However, in 1998
 1000: the bar was raised when the major commercial Forth vendors switched to
 1001: native code compilers.}.  It is free and available on many machines.
 1002: 
 1003: @c ******************************************************************
 1004: @node Gforth Environment, Tutorial, Goals, Top
 1005: @chapter Gforth Environment
 1006: @cindex Gforth environment
 1007: 
 1008: Note: ultimately, the Gforth man page will be auto-generated from the
 1009: material in this chapter.
 1010: 
 1011: @menu
 1012: * Invoking Gforth::             Getting in
 1013: * Leaving Gforth::              Getting out
 1014: * Command-line editing::        
 1015: * Environment variables::       that affect how Gforth starts up
 1016: * Gforth Files::                What gets installed and where
 1017: * Startup speed::               When 35ms is not fast enough ...
 1018: @end menu
 1019: 
 1020: For related information about the creation of images see @ref{Image Files}.
 1021: 
 1022: @comment ----------------------------------------------
 1023: @node Invoking Gforth, Leaving Gforth, Gforth Environment, Gforth Environment
 1024: @section Invoking Gforth
 1025: @cindex invoking Gforth
 1026: @cindex running Gforth
 1027: @cindex command-line options
 1028: @cindex options on the command line
 1029: @cindex flags on the command line
 1030: 
 1031: Gforth is made up of two parts; an executable ``engine'' (named
 1032: @file{gforth} or @file{gforth-fast}) and an image file. To start it, you
 1033: will usually just say @code{gforth} -- this automatically loads the
 1034: default image file @file{gforth.fi}. In many other cases the default
 1035: Gforth image will be invoked like this:
 1036: @example
 1037: gforth [file | -e forth-code] ...
 1038: @end example
 1039: @noindent
 1040: This interprets the contents of the files and the Forth code in the order they
 1041: are given.
 1042: 
 1043: In addition to the @file{gforth} engine, there is also an engine called
 1044: @file{gforth-fast}, which is faster, but gives less informative error
 1045: messages (@pxref{Error messages}).
 1046: 
 1047: In general, the command line looks like this:
 1048: 
 1049: @example
 1050: gforth[-fast] [engine options] [image options]
 1051: @end example
 1052: 
 1053: The engine options must come before the rest of the command
 1054: line. They are:
 1055: 
 1056: @table @code
 1057: @cindex -i, command-line option
 1058: @cindex --image-file, command-line option
 1059: @item --image-file @i{file}
 1060: @itemx -i @i{file}
 1061: Loads the Forth image @i{file} instead of the default
 1062: @file{gforth.fi} (@pxref{Image Files}).
 1063: 
 1064: @cindex --appl-image, command-line option
 1065: @item --appl-image @i{file}
 1066: Loads the image @i{file} and leaves all further command-line arguments
 1067: to the image (instead of processing them as engine options).  This is
 1068: useful for building executable application images on Unix, built with
 1069: @code{gforthmi --application ...}.
 1070: 
 1071: @cindex --path, command-line option
 1072: @cindex -p, command-line option
 1073: @item --path @i{path}
 1074: @itemx -p @i{path}
 1075: Uses @i{path} for searching the image file and Forth source code files
 1076: instead of the default in the environment variable @code{GFORTHPATH} or
 1077: the path specified at installation time (e.g.,
 1078: @file{/usr/local/share/gforth/0.2.0:.}). A path is given as a list of
 1079: directories, separated by @samp{:} (on Unix) or @samp{;} (on other OSs).
 1080: 
 1081: @cindex --dictionary-size, command-line option
 1082: @cindex -m, command-line option
 1083: @cindex @i{size} parameters for command-line options
 1084: @cindex size of the dictionary and the stacks
 1085: @item --dictionary-size @i{size}
 1086: @itemx -m @i{size}
 1087: Allocate @i{size} space for the Forth dictionary space instead of
 1088: using the default specified in the image (typically 256K). The
 1089: @i{size} specification for this and subsequent options consists of
 1090: an integer and a unit (e.g.,
 1091: @code{4M}). The unit can be one of @code{b} (bytes), @code{e} (element
 1092: size, in this case Cells), @code{k} (kilobytes), @code{M} (Megabytes),
 1093: @code{G} (Gigabytes), and @code{T} (Terabytes). If no unit is specified,
 1094: @code{e} is used.
 1095: 
 1096: @cindex --data-stack-size, command-line option
 1097: @cindex -d, command-line option
 1098: @item --data-stack-size @i{size}
 1099: @itemx -d @i{size}
 1100: Allocate @i{size} space for the data stack instead of using the
 1101: default specified in the image (typically 16K).
 1102: 
 1103: @cindex --return-stack-size, command-line option
 1104: @cindex -r, command-line option
 1105: @item --return-stack-size @i{size}
 1106: @itemx -r @i{size}
 1107: Allocate @i{size} space for the return stack instead of using the
 1108: default specified in the image (typically 15K).
 1109: 
 1110: @cindex --fp-stack-size, command-line option
 1111: @cindex -f, command-line option
 1112: @item --fp-stack-size @i{size}
 1113: @itemx -f @i{size}
 1114: Allocate @i{size} space for the floating point stack instead of
 1115: using the default specified in the image (typically 15.5K). In this case
 1116: the unit specifier @code{e} refers to floating point numbers.
 1117: 
 1118: @cindex --locals-stack-size, command-line option
 1119: @cindex -l, command-line option
 1120: @item --locals-stack-size @i{size}
 1121: @itemx -l @i{size}
 1122: Allocate @i{size} space for the locals stack instead of using the
 1123: default specified in the image (typically 14.5K).
 1124: 
 1125: @cindex -h, command-line option
 1126: @cindex --help, command-line option
 1127: @item --help
 1128: @itemx -h
 1129: Print a message about the command-line options
 1130: 
 1131: @cindex -v, command-line option
 1132: @cindex --version, command-line option
 1133: @item --version
 1134: @itemx -v
 1135: Print version and exit
 1136: 
 1137: @cindex --debug, command-line option
 1138: @item --debug
 1139: Print some information useful for debugging on startup.
 1140: 
 1141: @cindex --offset-image, command-line option
 1142: @item --offset-image
 1143: Start the dictionary at a slightly different position than would be used
 1144: otherwise (useful for creating data-relocatable images,
 1145: @pxref{Data-Relocatable Image Files}).
 1146: 
 1147: @cindex --no-offset-im, command-line option
 1148: @item --no-offset-im
 1149: Start the dictionary at the normal position.
 1150: 
 1151: @cindex --clear-dictionary, command-line option
 1152: @item --clear-dictionary
 1153: Initialize all bytes in the dictionary to 0 before loading the image
 1154: (@pxref{Data-Relocatable Image Files}).
 1155: 
 1156: @cindex --die-on-signal, command-line-option
 1157: @item --die-on-signal
 1158: Normally Gforth handles most signals (e.g., the user interrupt SIGINT,
 1159: or the segmentation violation SIGSEGV) by translating it into a Forth
 1160: @code{THROW}. With this option, Gforth exits if it receives such a
 1161: signal. This option is useful when the engine and/or the image might be
 1162: severely broken (such that it causes another signal before recovering
 1163: from the first); this option avoids endless loops in such cases.
 1164: @end table
 1165: 
 1166: @cindex loading files at startup
 1167: @cindex executing code on startup
 1168: @cindex batch processing with Gforth
 1169: As explained above, the image-specific command-line arguments for the
 1170: default image @file{gforth.fi} consist of a sequence of filenames and
 1171: @code{-e @var{forth-code}} options that are interpreted in the sequence
 1172: in which they are given. The @code{-e @var{forth-code}} or
 1173: @code{--evaluate @var{forth-code}} option evaluates the Forth
 1174: code. This option takes only one argument; if you want to evaluate more
 1175: Forth words, you have to quote them or use @code{-e} several times. To exit
 1176: after processing the command line (instead of entering interactive mode)
 1177: append @code{-e bye} to the command line.
 1178: 
 1179: @cindex versions, invoking other versions of Gforth
 1180: If you have several versions of Gforth installed, @code{gforth} will
 1181: invoke the version that was installed last. @code{gforth-@i{version}}
 1182: invokes a specific version. If your environment contains the variable
 1183: @code{GFORTHPATH}, you may want to override it by using the
 1184: @code{--path} option.
 1185: 
 1186: Not yet implemented:
 1187: On startup the system first executes the system initialization file
 1188: (unless the option @code{--no-init-file} is given; note that the system
 1189: resulting from using this option may not be ANS Forth conformant). Then
 1190: the user initialization file @file{.gforth.fs} is executed, unless the
 1191: option @code{--no-rc} is given; this file is searched for in @file{.},
 1192: then in @file{~}, then in the normal path (see above).
 1193: 
 1194: 
 1195: 
 1196: @comment ----------------------------------------------
 1197: @node Leaving Gforth, Command-line editing, Invoking Gforth, Gforth Environment
 1198: @section Leaving Gforth
 1199: @cindex Gforth - leaving
 1200: @cindex leaving Gforth
 1201: 
 1202: You can leave Gforth by typing @code{bye} or @kbd{Ctrl-d} (at the start
 1203: of a line) or (if you invoked Gforth with the @code{--die-on-signal}
 1204: option) @kbd{Ctrl-c}. When you leave Gforth, all of your definitions and
 1205: data are discarded.  For ways of saving the state of the system before
 1206: leaving Gforth see @ref{Image Files}.
 1207: 
 1208: doc-bye
 1209: 
 1210: 
 1211: @comment ----------------------------------------------
 1212: @node Command-line editing, Environment variables, Leaving Gforth, Gforth Environment
 1213: @section Command-line editing
 1214: @cindex command-line editing
 1215: 
 1216: Gforth maintains a history file that records every line that you type to
 1217: the text interpreter. This file is preserved between sessions, and is
 1218: used to provide a command-line recall facility; if you type @kbd{Ctrl-P}
 1219: repeatedly you can recall successively older commands from this (or
 1220: previous) session(s). The full list of command-line editing facilities is:
 1221: 
 1222: @itemize @bullet
 1223: @item
 1224: @kbd{Ctrl-p} (``previous'') (or up-arrow) to recall successively older
 1225: commands from the history buffer.
 1226: @item
 1227: @kbd{Ctrl-n} (``next'') (or down-arrow) to recall successively newer commands
 1228: from the history buffer.
 1229: @item
 1230: @kbd{Ctrl-f} (or right-arrow) to move the cursor right, non-destructively.
 1231: @item
 1232: @kbd{Ctrl-b} (or left-arrow) to move the cursor left, non-destructively.
 1233: @item
 1234: @kbd{Ctrl-h} (backspace) to delete the character to the left of the cursor,
 1235: closing up the line.
 1236: @item
 1237: @kbd{Ctrl-k} to delete (``kill'') from the cursor to the end of the line.
 1238: @item
 1239: @kbd{Ctrl-a} to move the cursor to the start of the line.
 1240: @item
 1241: @kbd{Ctrl-e} to move the cursor to the end of the line.
 1242: @item
 1243: @key{RET} (@kbd{Ctrl-m}) or @key{LFD} (@kbd{Ctrl-j}) to submit the current
 1244: line.
 1245: @item
 1246: @key{TAB} to step through all possible full-word completions of the word
 1247: currently being typed.
 1248: @item
 1249: @kbd{Ctrl-d} on an empty line line to terminate Gforth (gracefully,
 1250: using @code{bye}). 
 1251: @item
 1252: @kbd{Ctrl-x} (or @code{Ctrl-d} on a non-empty line) to delete the
 1253: character under the cursor.
 1254: @end itemize
 1255: 
 1256: When editing, displayable characters are inserted to the left of the
 1257: cursor position; the line is always in ``insert'' (as opposed to
 1258: ``overstrike'') mode.
 1259: 
 1260: @cindex history file
 1261: @cindex @file{.gforth-history}
 1262: On Unix systems, the history file is @file{~/.gforth-history} by
 1263: default@footnote{i.e. it is stored in the user's home directory.}. You
 1264: can find out the name and location of your history file using:
 1265: 
 1266: @example 
 1267: history-file type \ Unix-class systems
 1268: 
 1269: history-file type \ Other systems
 1270: history-dir  type
 1271: @end example
 1272: 
 1273: If you enter long definitions by hand, you can use a text editor to
 1274: paste them out of the history file into a Forth source file for reuse at
 1275: a later time.
 1276: 
 1277: Gforth never trims the size of the history file, so you should do this
 1278: periodically, if necessary.
 1279: 
 1280: @comment this is all defined in history.fs
 1281: @comment NAC TODO the ctrl-D behaviour can either do a bye or a beep.. how is that option
 1282: @comment chosen?
 1283: 
 1284: 
 1285: @comment ----------------------------------------------
 1286: @node Environment variables, Gforth Files, Command-line editing, Gforth Environment
 1287: @section Environment variables
 1288: @cindex environment variables
 1289: 
 1290: Gforth uses these environment variables:
 1291: 
 1292: @itemize @bullet
 1293: @item
 1294: @cindex @code{GFORTHHIST} -- environment variable
 1295: @code{GFORTHHIST} -- (Unix systems only) specifies the directory in which to
 1296: open/create the history file, @file{.gforth-history}. Default:
 1297: @code{$HOME}.
 1298: 
 1299: @item
 1300: @cindex @code{GFORTHPATH} -- environment variable
 1301: @code{GFORTHPATH} -- specifies the path used when searching for the gforth image file and
 1302: for Forth source-code files.
 1303: 
 1304: @item
 1305: @cindex @code{GFORTH} -- environment variable
 1306: @code{GFORTH} -- used by @file{gforthmi}, @xref{gforthmi}.
 1307: 
 1308: @item
 1309: @cindex @code{GFORTHD} -- environment variable
 1310: @code{GFORTHD} -- used by @file{gforthmi}, @xref{gforthmi}.
 1311: 
 1312: @item
 1313: @cindex @code{TMP}, @code{TEMP} - environment variable
 1314: @code{TMP}, @code{TEMP} - (non-Unix systems only) used as a potential
 1315: location for the history file.
 1316: @end itemize
 1317: 
 1318: @comment also POSIXELY_CORRECT LINES COLUMNS HOME but no interest in
 1319: @comment mentioning these.
 1320: 
 1321: All the Gforth environment variables default to sensible values if they
 1322: are not set.
 1323: 
 1324: 
 1325: @comment ----------------------------------------------
 1326: @node Gforth Files, Startup speed, Environment variables, Gforth Environment
 1327: @section Gforth files
 1328: @cindex Gforth files
 1329: 
 1330: When you install Gforth on a Unix system, it installs files in these
 1331: locations by default:
 1332: 
 1333: @itemize @bullet
 1334: @item
 1335: @file{/usr/local/bin/gforth}
 1336: @item
 1337: @file{/usr/local/bin/gforthmi}
 1338: @item
 1339: @file{/usr/local/man/man1/gforth.1} - man page.
 1340: @item
 1341: @file{/usr/local/info} - the Info version of this manual.
 1342: @item
 1343: @file{/usr/local/lib/gforth/<version>/...} - Gforth @file{.fi} files.
 1344: @item
 1345: @file{/usr/local/share/gforth/<version>/TAGS} - Emacs TAGS file.
 1346: @item
 1347: @file{/usr/local/share/gforth/<version>/...} - Gforth source files.
 1348: @item
 1349: @file{.../emacs/site-lisp/gforth.el} - Emacs gforth mode.
 1350: @end itemize
 1351: 
 1352: You can select different places for installation by using
 1353: @code{configure} options (listed with @code{configure --help}).
 1354: 
 1355: @comment ----------------------------------------------
 1356: @node Startup speed,  , Gforth Files, Gforth Environment
 1357: @section Startup speed
 1358: @cindex Startup speed
 1359: @cindex speed, startup
 1360: 
 1361: If Gforth is used for CGI scripts or in shell scripts, its startup
 1362: speed may become a problem.  On a 300MHz 21064a under Linux-2.2.13 with
 1363: glibc-2.0.7, @code{gforth -e bye} takes about 24.6ms user and 11.3ms
 1364: system time.
 1365: 
 1366: If startup speed is a problem, you may consider the following ways to
 1367: improve it; or you may consider ways to reduce the number of startups
 1368: (for example, by using Fast-CGI).
 1369: 
 1370: The first step to improve startup speed is to statically link Gforth, by
 1371: building it with @code{XLDFLAGS=-static}.  This requires more memory for
 1372: the code and will therefore slow down the first invocation, but
 1373: subsequent invocations avoid the dynamic linking overhead.  Another
 1374: disadvantage is that Gforth won't profit from library upgrades.  As a
 1375: result, @code{gforth-static -e bye} takes about 17.1ms user and
 1376: 8.2ms system time.
 1377: 
 1378: The next step to improve startup speed is to use a non-relocatable image
 1379: (@pxref{Non-Relocatable Image Files}).  You can create this image with
 1380: @code{gforth -e "savesystem gforthnr.fi bye"} and later use it with
 1381: @code{gforth -i gforthnr.fi ...}.  This avoids the relocation overhead
 1382: and a part of the copy-on-write overhead.  The disadvantage is that the
 1383: non-relocatable image does not work if the OS gives Gforth a different
 1384: address for the dictionary, for whatever reason; so you better provide a
 1385: fallback on a relocatable image.  @code{gforth-static -i gforthnr.fi -e
 1386: bye} takes about 15.3ms user and 7.5ms system time.
 1387: 
 1388: The final step is to disable dictionary hashing in Gforth.  Gforth
 1389: builds the hash table on startup, which takes much of the startup
 1390: overhead. You can do this by commenting out the @code{include hash.fs}
 1391: in @file{startup.fs} and everything that requires @file{hash.fs} (at the
 1392: moment @file{table.fs} and @file{ekey.fs}) and then doing @code{make}.
 1393: The disadvantages are that functionality like @code{table} and
 1394: @code{ekey} is missing and that text interpretation (e.g., compiling)
 1395: now takes much longer. So, you should only use this method if there is
 1396: no significant text interpretation to perform (the script should be
 1397: compiled into the image, amongst other things).  @code{gforth-static -i
 1398: gforthnrnh.fi -e bye} takes about 2.1ms user and 6.1ms system time.
 1399: 
 1400: @c ******************************************************************
 1401: @node Tutorial, Introduction, Gforth Environment, Top
 1402: @chapter Forth Tutorial
 1403: @cindex Tutorial
 1404: @cindex Forth Tutorial
 1405: 
 1406: @c Topics from nac's Introduction that could be mentioned:
 1407: @c press <ret> after each line
 1408: @c Prompt
 1409: @c numbers vs. words in dictionary on text interpretation
 1410: @c what happens on redefinition
 1411: @c parsing words (in particular, defining words)
 1412: 
 1413: The difference of this chapter from the Introduction
 1414: (@pxref{Introduction}) is that this tutorial is more fast-paced, should
 1415: be used while sitting in front of a computer, and covers much more
 1416: material, but does not explain how the Forth system works.
 1417: 
 1418: This tutorial can be used with any ANS-compliant Forth; any
 1419: Gforth-specific features are marked as such and you can skip them if you
 1420: work with another Forth.  This tutorial does not explain all features of
 1421: Forth, just enough to get you started and give you some ideas about the
 1422: facilities available in Forth.  Read the rest of the manual and the
 1423: standard when you are through this.
 1424: 
 1425: The intended way to use this tutorial is that you work through it while
 1426: sitting in front of the console, take a look at the examples and predict
 1427: what they will do, then try them out; if the outcome is not as expected,
 1428: find out why (e.g., by trying out variations of the example), so you
 1429: understand what's going on.  There are also some assignments that you
 1430: should solve.
 1431: 
 1432: This tutorial assumes that you have programmed before and know what,
 1433: e.g., a loop is.
 1434: 
 1435: @c !! explain compat library
 1436: 
 1437: @menu
 1438: * Starting Gforth Tutorial::    
 1439: * Syntax Tutorial::             
 1440: * Crash Course Tutorial::       
 1441: * Stack Tutorial::              
 1442: * Arithmetics Tutorial::        
 1443: * Stack Manipulation Tutorial::  
 1444: * Using files for Forth code Tutorial::  
 1445: * Comments Tutorial::           
 1446: * Colon Definitions Tutorial::  
 1447: * Decompilation Tutorial::      
 1448: * Stack-Effect Comments Tutorial::  
 1449: * Types Tutorial::              
 1450: * Factoring Tutorial::          
 1451: * Designing the stack effect Tutorial::  
 1452: * Local Variables Tutorial::    
 1453: * Conditional execution Tutorial::  
 1454: * Flags and Comparisons Tutorial::  
 1455: * General Loops Tutorial::      
 1456: * Counted loops Tutorial::      
 1457: * Recursion Tutorial::          
 1458: * Leaving definitions or loops Tutorial::  
 1459: * Return Stack Tutorial::       
 1460: * Memory Tutorial::             
 1461: * Characters and Strings Tutorial::  
 1462: * Alignment Tutorial::          
 1463: * Interpretation and Compilation Semantics and Immediacy Tutorial::  
 1464: * Execution Tokens Tutorial::   
 1465: * Exceptions Tutorial::         
 1466: * Defining Words Tutorial::     
 1467: * Arrays and Records Tutorial::  
 1468: * POSTPONE Tutorial::           
 1469: * Literal Tutorial::            
 1470: * Advanced macros Tutorial::    
 1471: * Compilation Tokens Tutorial::  
 1472: * Wordlists and Search Order Tutorial::  
 1473: @end menu
 1474: 
 1475: @node Starting Gforth Tutorial, Syntax Tutorial, Tutorial, Tutorial
 1476: @section Starting Gforth
 1477: @cindex starting Gforth tutorial
 1478: You can start Gforth by typing its name:
 1479: 
 1480: @example
 1481: gforth
 1482: @end example
 1483: 
 1484: That puts you into interactive mode; you can leave Gforth by typing
 1485: @code{bye}.  While in Gforth, you can edit the command line and access
 1486: the command line history with cursor keys, similar to bash.
 1487: 
 1488: 
 1489: @node Syntax Tutorial, Crash Course Tutorial, Starting Gforth Tutorial, Tutorial
 1490: @section Syntax
 1491: @cindex syntax tutorial
 1492: 
 1493: A @dfn{word} is a sequence of arbitrary characters (expcept white
 1494: space).  Words are separated by white space.  E.g., each of the
 1495: following lines contains exactly one word:
 1496: 
 1497: @example
 1498: word
 1499: !@@#$%^&*()
 1500: 1234567890
 1501: 5!a
 1502: @end example
 1503: 
 1504: A frequent beginner's error is to leave away necessary white space,
 1505: resulting in an error like @samp{Undefined word}; so if you see such an
 1506: error, check if you have put spaces wherever necessary.
 1507: 
 1508: @example
 1509: ." hello, world" \ correct
 1510: ."hello, world"  \ gives an "Undefined word" error
 1511: @end example
 1512: 
 1513: Gforth and most other Forth systems ignore differences in case (they are
 1514: case-insensitive), i.e., @samp{word} is the same as @samp{Word}.  If
 1515: your system is case-sensitive, you may have to type all the examples
 1516: given here in upper case.
 1517: 
 1518: 
 1519: @node Crash Course Tutorial, Stack Tutorial, Syntax Tutorial, Tutorial
 1520: @section Crash Course
 1521: 
 1522: Type
 1523: 
 1524: @example
 1525: 0 0 !
 1526: here execute
 1527: ' catch >body 20 erase abort
 1528: ' (quit) >body 20 erase
 1529: @end example
 1530: 
 1531: The last two examples are guaranteed to destroy parts of Gforth (and
 1532: most other systems), so you better leave Gforth afterwards (if it has
 1533: not finished by itself).  On some systems you may have to kill gforth
 1534: from outside (e.g., in Unix with @code{kill}).
 1535: 
 1536: Now that you know how to produce crashes (and that there's not much to
 1537: them), let's learn how to produce meaningful programs.
 1538: 
 1539: 
 1540: @node Stack Tutorial, Arithmetics Tutorial, Crash Course Tutorial, Tutorial
 1541: @section Stack
 1542: @cindex stack tutorial
 1543: 
 1544: The most obvious feature of Forth is the stack.  When you type in a
 1545: number, it is pushed on the stack.  You can display the content of the
 1546: stack with @code{.s}.
 1547: 
 1548: @example
 1549: 1 2 .s
 1550: 3 .s
 1551: @end example
 1552: 
 1553: @code{.s} displays the top-of-stack to the right, i.e., the numbers
 1554: appear in @code{.s} output as they appeared in the input.
 1555: 
 1556: You can print the top of stack element with @code{.}.
 1557: 
 1558: @example
 1559: 1 2 3 . . .
 1560: @end example
 1561: 
 1562: In general, words consume their stack arguments (@code{.s} is an
 1563: exception).
 1564: 
 1565: @assignment
 1566: What does the stack contain after @code{5 6 7 .}?
 1567: @endassignment
 1568: 
 1569: 
 1570: @node Arithmetics Tutorial, Stack Manipulation Tutorial, Stack Tutorial, Tutorial
 1571: @section Arithmetics
 1572: @cindex arithmetics tutorial
 1573: 
 1574: The words @code{+}, @code{-}, @code{*}, @code{/}, and @code{mod} always
 1575: operate on the top two stack items:
 1576: 
 1577: @example
 1578: 2 2 .s
 1579: + .s
 1580: .
 1581: 2 1 - .
 1582: 7 3 mod .
 1583: @end example
 1584: 
 1585: The operands of @code{-}, @code{/}, and @code{mod} are in the same order
 1586: as in the corresponding infix expression (this is generally the case in
 1587: Forth).
 1588: 
 1589: Parentheses are superfluous (and not available), because the order of
 1590: the words unambiguously determines the order of evaluation and the
 1591: operands:
 1592: 
 1593: @example
 1594: 3 4 + 5 * .
 1595: 3 4 5 * + .
 1596: @end example
 1597: 
 1598: @assignment
 1599: What are the infix expressions corresponding to the Forth code above?
 1600: Write @code{6-7*8+9} in Forth notation@footnote{This notation is also
 1601: known as Postfix or RPN (Reverse Polish Notation).}.
 1602: @endassignment
 1603: 
 1604: To change the sign, use @code{negate}:
 1605: 
 1606: @example
 1607: 2 negate .
 1608: @end example
 1609: 
 1610: @assignment
 1611: Convert -(-3)*4-5 to Forth.
 1612: @endassignment
 1613: 
 1614: @code{/mod} performs both @code{/} and @code{mod}.
 1615: 
 1616: @example
 1617: 7 3 /mod . .
 1618: @end example
 1619: 
 1620: Reference: @ref{Arithmetic}.
 1621: 
 1622: 
 1623: @node Stack Manipulation Tutorial, Using files for Forth code Tutorial, Arithmetics Tutorial, Tutorial
 1624: @section Stack Manipulation
 1625: @cindex stack manipulation tutorial
 1626: 
 1627: Stack manipulation words rearrange the data on the stack.
 1628: 
 1629: @example
 1630: 1 .s drop .s
 1631: 1 .s dup .s drop drop .s
 1632: 1 2 .s over .s drop drop drop
 1633: 1 2 .s swap .s drop drop
 1634: 1 2 3 .s rot .s drop drop drop
 1635: @end example
 1636: 
 1637: These are the most important stack manipulation words.  There are also
 1638: variants that manipulate twice as many stack items:
 1639: 
 1640: @example
 1641: 1 2 3 4 .s 2swap .s 2drop 2drop
 1642: @end example
 1643: 
 1644: Two more stack manipulation words are:
 1645: 
 1646: @example
 1647: 1 2 .s nip .s drop
 1648: 1 2 .s tuck .s 2drop drop
 1649: @end example
 1650: 
 1651: @assignment
 1652: Replace @code{nip} and @code{tuck} with combinations of other stack
 1653: manipulation words.
 1654: 
 1655: @example
 1656: Given:          How do you get:
 1657: 1 2 3           3 2 1           
 1658: 1 2 3           1 2 3 2                 
 1659: 1 2 3           1 2 3 3                 
 1660: 1 2 3           1 3 3           
 1661: 1 2 3           2 1 3           
 1662: 1 2 3 4         4 3 2 1         
 1663: 1 2 3           1 2 3 1 2 3             
 1664: 1 2 3 4         1 2 3 4 1 2             
 1665: 1 2 3
 1666: 1 2 3           1 2 3 4                 
 1667: 1 2 3           1 3             
 1668: @end example
 1669: @endassignment
 1670: 
 1671: @example
 1672: 5 dup * .
 1673: @end example
 1674: 
 1675: @assignment
 1676: Write 17^3 and 17^4 in Forth, without writing @code{17} more than once.
 1677: Write a piece of Forth code that expects two numbers on the stack
 1678: (@var{a} and @var{b}, with @var{b} on top) and computes
 1679: @code{(a-b)(a+1)}.
 1680: @endassignment
 1681: 
 1682: Reference: @ref{Stack Manipulation}.
 1683: 
 1684: 
 1685: @node Using files for Forth code Tutorial, Comments Tutorial, Stack Manipulation Tutorial, Tutorial
 1686: @section Using files for Forth code
 1687: @cindex loading Forth code, tutorial
 1688: @cindex files containing Forth code, tutorial
 1689: 
 1690: While working at the Forth command line is convenient for one-line
 1691: examples and short one-off code, you probably want to store your source
 1692: code in files for convenient editing and persistence.  You can use your
 1693: favourite editor (Gforth includes Emacs support, @pxref{Emacs and
 1694: Gforth}) to create @var{file} and use
 1695: 
 1696: @example
 1697: s" @var{file}" included
 1698: @end example
 1699: 
 1700: to load it into your Forth system.  The file name extension I use for
 1701: Forth files is @samp{.fs}.
 1702: 
 1703: You can easily start Gforth with some files loaded like this:
 1704: 
 1705: @example
 1706: gforth @var{file1} @var{file2}
 1707: @end example
 1708: 
 1709: If an error occurs during loading these files, Gforth terminates,
 1710: whereas an error during @code{INCLUDED} within Gforth usually gives you
 1711: a Gforth command line.  Starting the Forth system every time gives you a
 1712: clean start every time, without interference from the results of earlier
 1713: tries.
 1714: 
 1715: I often put all the tests in a file, then load the code and run the
 1716: tests with
 1717: 
 1718: @example
 1719: gforth @var{code} @var{tests} -e bye
 1720: @end example
 1721: 
 1722: (often by performing this command with @kbd{C-x C-e} in Emacs).  The
 1723: @code{-e bye} ensures that Gforth terminates afterwards so that I can
 1724: restart this command without ado.
 1725: 
 1726: The advantage of this approach is that the tests can be repeated easily
 1727: every time the program ist changed, making it easy to catch bugs
 1728: introduced by the change.
 1729: 
 1730: Reference: @ref{Forth source files}.
 1731: 
 1732: 
 1733: @node Comments Tutorial, Colon Definitions Tutorial, Using files for Forth code Tutorial, Tutorial
 1734: @section Comments
 1735: @cindex comments tutorial
 1736: 
 1737: @example
 1738: \ That's a comment; it ends at the end of the line
 1739: ( Another comment; it ends here: )  .s
 1740: @end example
 1741: 
 1742: @code{\} and @code{(} are ordinary Forth words and therefore have to be
 1743: separated with white space from the following text.
 1744: 
 1745: @example
 1746: \This gives an "Undefined word" error
 1747: @end example
 1748: 
 1749: The first @code{)} ends a comment started with @code{(}, so you cannot
 1750: nest @code{(}-comments; and you cannot comment out text containing a
 1751: @code{)} with @code{( ... )}@footnote{therefore it's a good idea to
 1752: avoid @code{)} in word names.}.
 1753: 
 1754: I use @code{\}-comments for descriptive text and for commenting out code
 1755: of one or more line; I use @code{(}-comments for describing the stack
 1756: effect, the stack contents, or for commenting out sub-line pieces of
 1757: code.
 1758: 
 1759: The Emacs mode @file{gforth.el} (@pxref{Emacs and Gforth}) supports
 1760: these uses by commenting out a region with @kbd{C-x \}, uncommenting a
 1761: region with @kbd{C-u C-x \}, and filling a @code{\}-commented region
 1762: with @kbd{M-q}.
 1763: 
 1764: Reference: @ref{Comments}.
 1765: 
 1766: 
 1767: @node Colon Definitions Tutorial, Decompilation Tutorial, Comments Tutorial, Tutorial
 1768: @section Colon Definitions
 1769: @cindex colon definitions, tutorial
 1770: @cindex definitions, tutorial
 1771: @cindex procedures, tutorial
 1772: @cindex functions, tutorial
 1773: 
 1774: are similar to procedures and functions in other programming languages.
 1775: 
 1776: @example
 1777: : squared ( n -- n^2 )
 1778:    dup * ;
 1779: 5 squared .
 1780: 7 squared .
 1781: @end example
 1782: 
 1783: @code{:} starts the colon definition; its name is @code{squared}.  The
 1784: following comment describes its stack effect.  The words @code{dup *}
 1785: are not executed, but compiled into the definition.  @code{;} ends the
 1786: colon definition.
 1787: 
 1788: The newly-defined word can be used like any other word, including using
 1789: it in other definitions:
 1790: 
 1791: @example
 1792: : cubed ( n -- n^3 )
 1793:    dup squared * ;
 1794: -5 cubed .
 1795: : fourth-power ( n -- n^4 )
 1796:    squared squared ;
 1797: 3 fourth-power .
 1798: @end example
 1799: 
 1800: @assignment
 1801: Write colon definitions for @code{nip}, @code{tuck}, @code{negate}, and
 1802: @code{/mod} in terms of other Forth words, and check if they work (hint:
 1803: test your tests on the originals first).  Don't let the
 1804: @samp{redefined}-Messages spook you, they are just warnings.
 1805: @endassignment
 1806: 
 1807: Reference: @ref{Colon Definitions}.
 1808: 
 1809: 
 1810: @node Decompilation Tutorial, Stack-Effect Comments Tutorial, Colon Definitions Tutorial, Tutorial
 1811: @section Decompilation
 1812: @cindex decompilation tutorial
 1813: @cindex see tutorial
 1814: 
 1815: You can decompile colon definitions with @code{see}:
 1816: 
 1817: @example
 1818: see squared
 1819: see cubed
 1820: @end example
 1821: 
 1822: In Gforth @code{see} shows you a reconstruction of the source code from
 1823: the executable code.  Informations that were present in the source, but
 1824: not in the executable code, are lost (e.g., comments).
 1825: 
 1826: You can also decompile the predefined words:
 1827: 
 1828: @example
 1829: see .
 1830: see +
 1831: @end example
 1832: 
 1833: 
 1834: @node Stack-Effect Comments Tutorial, Types Tutorial, Decompilation Tutorial, Tutorial
 1835: @section Stack-Effect Comments
 1836: @cindex stack-effect comments, tutorial
 1837: @cindex --, tutorial
 1838: By convention the comment after the name of a definition describes the
 1839: stack effect: The part in from of the @samp{--} describes the state of
 1840: the stack before the execution of the definition, i.e., the parameters
 1841: that are passed into the colon definition; the part behind the @samp{--}
 1842: is the state of the stack after the execution of the definition, i.e.,
 1843: the results of the definition.  The stack comment only shows the top
 1844: stack items that the definition accesses and/or changes.
 1845: 
 1846: You should put a correct stack effect on every definition, even if it is
 1847: just @code{( -- )}.  You should also add some descriptive comment to
 1848: more complicated words (I usually do this in the lines following
 1849: @code{:}).  If you don't do this, your code becomes unreadable (because
 1850: you have to work through every definition before you can undertsand
 1851: any).
 1852: 
 1853: @assignment
 1854: The stack effect of @code{swap} can be written like this: @code{x1 x2 --
 1855: x2 x1}.  Describe the stack effect of @code{-}, @code{drop}, @code{dup},
 1856: @code{over}, @code{rot}, @code{nip}, and @code{tuck}.  Hint: When you
 1857: are done, you can compare your stack effects to those in this manual
 1858: (@pxref{Word Index}).
 1859: @endassignment
 1860: 
 1861: Sometimes programmers put comments at various places in colon
 1862: definitions that describe the contents of the stack at that place (stack
 1863: comments); i.e., they are like the first part of a stack-effect
 1864: comment. E.g.,
 1865: 
 1866: @example
 1867: : cubed ( n -- n^3 )
 1868:    dup squared  ( n n^2 ) * ;
 1869: @end example
 1870: 
 1871: In this case the stack comment is pretty superfluous, because the word
 1872: is simple enough.  If you think it would be a good idea to add such a
 1873: comment to increase readability, you should also consider factoring the
 1874: word into several simpler words (@pxref{Factoring Tutorial,,
 1875: Factoring}), which typically eliminates the need for the stack comment;
 1876: however, if you decide not to refactor it, then having such a comment is
 1877: better than not having it.
 1878: 
 1879: The names of the stack items in stack-effect and stack comments in the
 1880: standard, in this manual, and in many programs specify the type through
 1881: a type prefix, similar to Fortran and Hungarian notation.  The most
 1882: frequent prefixes are:
 1883: 
 1884: @table @code
 1885: @item n
 1886: signed integer
 1887: @item u
 1888: unsigned integer
 1889: @item c
 1890: character
 1891: @item f
 1892: Boolean flags, i.e. @code{false} or @code{true}.
 1893: @item a-addr,a-
 1894: Cell-aligned address
 1895: @item c-addr,c-
 1896: Char-aligned address (note that a Char may have two bytes in Windows NT)
 1897: @item xt
 1898: Execution token, same size as Cell
 1899: @item w,x
 1900: Cell, can contain an integer or an address.  It usually takes 32, 64 or
 1901: 16 bits (depending on your platform and Forth system). A cell is more
 1902: commonly known as machine word, but the term @emph{word} already means
 1903: something different in Forth.
 1904: @item d
 1905: signed double-cell integer
 1906: @item ud
 1907: unsigned double-cell integer
 1908: @item r
 1909: Float (on the FP stack)
 1910: @end table
 1911: 
 1912: You can find a more complete list in @ref{Notation}.
 1913: 
 1914: @assignment
 1915: Write stack-effect comments for all definitions you have written up to
 1916: now.
 1917: @endassignment
 1918: 
 1919: 
 1920: @node Types Tutorial, Factoring Tutorial, Stack-Effect Comments Tutorial, Tutorial
 1921: @section Types
 1922: @cindex types tutorial
 1923: 
 1924: In Forth the names of the operations are not overloaded; so similar
 1925: operations on different types need different names; e.g., @code{+} adds
 1926: integers, and you have to use @code{f+} to add floating-point numbers.
 1927: The following prefixes are often used for related operations on
 1928: different types:
 1929: 
 1930: @table @code
 1931: @item (none)
 1932: signed integer
 1933: @item u
 1934: unsigned integer
 1935: @item c
 1936: character
 1937: @item d
 1938: signed double-cell integer
 1939: @item ud, du
 1940: unsigned double-cell integer
 1941: @item 2
 1942: two cells (not-necessarily double-cell numbers)
 1943: @item m, um
 1944: mixed single-cell and double-cell operations
 1945: @item f
 1946: floating-point (note that in stack comments @samp{f} represents flags,
 1947: and @samp{r} represents FP numbers).
 1948: @end table
 1949: 
 1950: If there are no differences between the signed and the unsigned variant
 1951: (e.g., for @code{+}), there is only the prefix-less variant.
 1952: 
 1953: Forth does not perform type checking, neither at compile time, nor at
 1954: run time.  If you use the wrong oeration, the data are interpreted
 1955: incorrectly:
 1956: 
 1957: @example
 1958: -1 u.
 1959: @end example
 1960: 
 1961: If you have only experience with type-checked languages until now, and
 1962: have heard how important type-checking is, don't panic!  In my
 1963: experience (and that of other Forthers), type errors in Forth code are
 1964: usually easy to find (once you get used to it), the increased vigilance
 1965: of the programmer tends to catch some harder errors in addition to most
 1966: type errors, and you never have to work around the type system, so in
 1967: most situations the lack of type-checking seems to be a win (projects to
 1968: add type checking to Forth have not caught on).
 1969: 
 1970: 
 1971: @node Factoring Tutorial, Designing the stack effect Tutorial, Types Tutorial, Tutorial
 1972: @section Factoring
 1973: @cindex factoring tutorial
 1974: 
 1975: If you try to write longer definitions, you will soon find it hard to
 1976: keep track of the stack contents.  Therefore, good Forth programmers
 1977: tend to write only short definitions (e.g., three lines).  The art of
 1978: finding meaningful short definitions is known as factoring (as in
 1979: factoring polynomials).
 1980: 
 1981: Well-factored programs offer additional advantages: smaller, more
 1982: general words, are easier to test and debug and can be reused more and
 1983: better than larger, specialized words.
 1984: 
 1985: So, if you run into difficulties with stack management, when writing
 1986: code, try to define meaningful factors for the word, and define the word
 1987: in terms of those.  Even if a factor contains only two words, it is
 1988: often helpful.
 1989: 
 1990: Good factoring is not easy, and it takes some practice to get the knack
 1991: for it; but even experienced Forth programmers often don't find the
 1992: right solution right away, but only when rewriting the program.  So, if
 1993: you don't come up with a good solution immediately, keep trying, don't
 1994: despair.
 1995: 
 1996: @c example !!
 1997: 
 1998: 
 1999: @node Designing the stack effect Tutorial, Local Variables Tutorial, Factoring Tutorial, Tutorial
 2000: @section Designing the stack effect
 2001: @cindex Stack effect design, tutorial
 2002: @cindex design of stack effects, tutorial
 2003: 
 2004: In other languages you can use an arbitrary order of parameters for a
 2005: function; and since there is only one result, you don't have to deal with
 2006: the order of results, either.
 2007: 
 2008: In Forth (and other stack-based languages, e.g., Postscript) the
 2009: parameter and result order of a definition is important and should be
 2010: designed well.  The general guideline is to design the stack effect such
 2011: that the word is simple to use in most cases, even if that complicates
 2012: the implementation of the word.  Some concrete rules are:
 2013: 
 2014: @itemize @bullet
 2015: 
 2016: @item
 2017: Words consume all of their parameters (e.g., @code{.}).
 2018: 
 2019: @item
 2020: If there is a convention on the order of parameters (e.g., from
 2021: mathematics or another programming language), stick with it (e.g.,
 2022: @code{-}).
 2023: 
 2024: @item
 2025: If one parameter usually requires only a short computation (e.g., it is
 2026: a constant), pass it on the top of the stack.  Conversely, parameters
 2027: that usually require a long sequence of code to compute should be passed
 2028: as the bottom (i.e., first) parameter.  This makes the code easier to
 2029: read, because reader does not need to keep track of the bottom item
 2030: through a long sequence of code (or, alternatively, through stack
 2031: manipulations). E.g., @code{!} (store, @pxref{Memory}) expects the
 2032: address on top of the stack because it is usually simpler to compute
 2033: than the stored value (often the address is just a variable).
 2034: 
 2035: @item
 2036: Similarly, results that are usually consumed quickly should be returned
 2037: on the top of stack, whereas a result that is often used in long
 2038: computations should be passed as bottom result.  E.g., the file words
 2039: like @code{open-file} return the error code on the top of stack, because
 2040: it is usually consumed quickly by @code{throw}; moreover, the error code
 2041: has to be checked before doing anything with the other results.
 2042: 
 2043: @end itemize
 2044: 
 2045: These rules are just general guidelines, don't lose sight of the overall
 2046: goal to make the words easy to use.  E.g., if the convention rule
 2047: conflicts with the computation-length rule, you might decide in favour
 2048: of the convention if the word will be used rarely, and in favour of the
 2049: computation-length rule if the word will be used frequently (because
 2050: with frequent use the cost of breaking the computation-length rule would
 2051: be quite high, and frequent use makes it easier to remember an
 2052: unconventional order).
 2053: 
 2054: @c example !! structure package
 2055: 
 2056: 
 2057: @node Local Variables Tutorial, Conditional execution Tutorial, Designing the stack effect Tutorial, Tutorial
 2058: @section Local Variables
 2059: @cindex local variables, tutorial
 2060: 
 2061: You can define local variables (@emph{locals}) in a colon definition:
 2062: 
 2063: @example
 2064: : swap @{ a b -- b a @}
 2065:   b a ;
 2066: 1 2 swap .s 2drop
 2067: @end example
 2068: 
 2069: (If your Forth system does not support this syntax, include
 2070: @file{compat/anslocals.fs} first).
 2071: 
 2072: In this example @code{@{ a b -- b a @}} is the locals definition; it
 2073: takes two cells from the stack, puts the top of stack in @code{b} and
 2074: the next stack element in @code{a}.  @code{--} starts a comment ending
 2075: with @code{@}}.  After the locals definition, using the name of the
 2076: local will push its value on the stack.  You can leave the comment
 2077: part (@code{-- b a}) away:
 2078: 
 2079: @example
 2080: : swap ( x1 x2 -- x2 x1 )
 2081:   @{ a b @} b a ;
 2082: @end example
 2083: 
 2084: In Gforth you can have several locals definitions, anywhere in a colon
 2085: definition; in contrast, in a standard program you can have only one
 2086: locals definition per colon definition, and that locals definition must
 2087: be outside any controll structure.
 2088: 
 2089: With locals you can write slightly longer definitions without running
 2090: into stack trouble.  However, I recommend trying to write colon
 2091: definitions without locals for exercise purposes to help you gain the
 2092: essential factoring skills.
 2093: 
 2094: @assignment
 2095: Rewrite your definitions until now with locals
 2096: @endassignment
 2097: 
 2098: Reference: @ref{Locals}.
 2099: 
 2100: 
 2101: @node Conditional execution Tutorial, Flags and Comparisons Tutorial, Local Variables Tutorial, Tutorial
 2102: @section Conditional execution
 2103: @cindex conditionals, tutorial
 2104: @cindex if, tutorial
 2105: 
 2106: In Forth you can use control structures only inside colon definitions.
 2107: An @code{if}-structure looks like this:
 2108: 
 2109: @example
 2110: : abs ( n1 -- +n2 )
 2111:     dup 0 < if
 2112:         negate
 2113:     endif ;
 2114: 5 abs .
 2115: -5 abs .
 2116: @end example
 2117: 
 2118: @code{if} takes a flag from the stack.  If the flag is non-zero (true),
 2119: the following code is performed, otherwise execution continues after the
 2120: @code{endif} (or @code{else}).  @code{<} compares the top two stack
 2121: elements and prioduces a flag:
 2122: 
 2123: @example
 2124: 1 2 < .
 2125: 2 1 < .
 2126: 1 1 < .
 2127: @end example
 2128: 
 2129: Actually the standard name for @code{endif} is @code{then}.  This
 2130: tutorial presents the examples using @code{endif}, because this is often
 2131: less confusing for people familiar with other programming languages
 2132: where @code{then} has a different meaning.  If your system does not have
 2133: @code{endif}, define it with
 2134: 
 2135: @example
 2136: : endif postpone then ; immediate
 2137: @end example
 2138: 
 2139: You can optionally use an @code{else}-part:
 2140: 
 2141: @example
 2142: : min ( n1 n2 -- n )
 2143:   2dup < if
 2144:     drop
 2145:   else
 2146:     nip
 2147:   endif ;
 2148: 2 3 min .
 2149: 3 2 min .
 2150: @end example
 2151: 
 2152: @assignment
 2153: Write @code{min} without @code{else}-part (hint: what's the definition
 2154: of @code{nip}?).
 2155: @endassignment
 2156: 
 2157: Reference: @ref{Selection}.
 2158: 
 2159: 
 2160: @node Flags and Comparisons Tutorial, General Loops Tutorial, Conditional execution Tutorial, Tutorial
 2161: @section Flags and Comparisons
 2162: @cindex flags tutorial
 2163: @cindex comparison tutorial
 2164: 
 2165: In a false-flag all bits are clear (0 when interpreted as integer).  In
 2166: a canonical true-flag all bits are set (-1 as a twos-complement signed
 2167: integer); in many contexts (e.g., @code{if}) any non-zero value is
 2168: treated as true flag.
 2169: 
 2170: @example
 2171: false .
 2172: true .
 2173: true hex u. decimal
 2174: @end example
 2175: 
 2176: Comparison words produce canonical flags:
 2177: 
 2178: @example
 2179: 1 1 = .
 2180: 1 0= .
 2181: 0 1 < .
 2182: 0 0 < .
 2183: -1 1 u< . \ type error, u< interprets -1 as large unsigned number
 2184: -1 1 < .
 2185: @end example
 2186: 
 2187: Gforth supports all combinations of the prefixes @code{0 u d d0 du f f0}
 2188: (or none) and the comparisons @code{= <> < > <= >=}.  Only a part of
 2189: these combinations are standard (for details see the standard,
 2190: @ref{Numeric comparison}, @ref{Floating Point} or @ref{Word Index}).
 2191: 
 2192: You can use @code{and or xor invert} can be used as operations on
 2193: canonical flags.  Actually they are bitwise operations:
 2194: 
 2195: @example
 2196: 1 2 and .
 2197: 1 2 or .
 2198: 1 3 xor .
 2199: 1 invert .
 2200: @end example
 2201: 
 2202: You can convert a zero/non-zero flag into a canonical flag with
 2203: @code{0<>} (and complement it on the way with @code{0=}).
 2204: 
 2205: @example
 2206: 1 0= .
 2207: 1 0<> .
 2208: @end example
 2209: 
 2210: You can use the all-bits-set feature of canonical flags and the bitwise
 2211: operation of the Boolean operations to avoid @code{if}s:
 2212: 
 2213: @example
 2214: : foo ( n1 -- n2 )
 2215:   0= if
 2216:     14
 2217:   else
 2218:     0
 2219:   endif ;
 2220: 0 foo .
 2221: 1 foo .
 2222: 
 2223: : foo ( n1 -- n2 )
 2224:   0= 14 and ;
 2225: 0 foo .
 2226: 1 foo .
 2227: @end example
 2228: 
 2229: @assignment
 2230: Write @code{min} without @code{if}.
 2231: @endassignment
 2232: 
 2233: For reference, see @ref{Boolean Flags}, @ref{Numeric comparison}, and
 2234: @ref{Bitwise operations}.
 2235: 
 2236: 
 2237: @node General Loops Tutorial, Counted loops Tutorial, Flags and Comparisons Tutorial, Tutorial
 2238: @section General Loops
 2239: @cindex loops, indefinite, tutorial
 2240: 
 2241: The endless loop is the most simple one:
 2242: 
 2243: @example
 2244: : endless ( -- )
 2245:   0 begin
 2246:     dup . 1+
 2247:   again ;
 2248: endless
 2249: @end example
 2250: 
 2251: Terminate this loop by pressing @kbd{Ctrl-C} (in Gforth).  @code{begin}
 2252: does nothing at run-time, @code{again} jumps back to @code{begin}.
 2253: 
 2254: A loop with one exit at any place looks like this:
 2255: 
 2256: @example
 2257: : log2 ( +n1 -- n2 )
 2258: \ logarithmus dualis of n1>0, rounded down to the next integer
 2259:   assert( dup 0> )
 2260:   2/ 0 begin
 2261:     over 0> while
 2262:       1+ swap 2/ swap
 2263:   repeat
 2264:   nip ;
 2265: 7 log2 .
 2266: 8 log2 .
 2267: @end example
 2268: 
 2269: At run-time @code{while} consumes a flag; if it is 0, execution
 2270: continues behind the @code{repeat}; if the flag is non-zero, execution
 2271: continues behind the @code{while}.  @code{Repeat} jumps back to
 2272: @code{begin}, just like @code{again}.
 2273: 
 2274: In Forth there are many combinations/abbreviations, like @code{1+}.
 2275: However, @code{2/} is not one of them; it shifts it's argument right by
 2276: one bit (arithmetic shift right):
 2277: 
 2278: @example
 2279: -5 2 / .
 2280: -5 2/ .
 2281: @end example
 2282: 
 2283: @code{assert(} is no standard word, but you can get it on systems other
 2284: then Gforth by including @file{compat/assert.fs}.  You can see what it
 2285: does by trying
 2286: 
 2287: @example
 2288: 0 log2 .
 2289: @end example
 2290: 
 2291: Here's a loop with an exit at the end:
 2292: 
 2293: @example
 2294: : log2 ( +n1 -- n2 )
 2295: \ logarithmus dualis of n1>0, rounded down to the next integer
 2296:   assert( dup 0 > )
 2297:   -1 begin
 2298:     1+ swap 2/ swap
 2299:     over 0 <=
 2300:   until
 2301:   nip ;
 2302: @end example
 2303: 
 2304: @code{Until} consumes a flag; if it is non-zero, execution continues at
 2305: the @code{begin}, otherwise after the @code{until}.
 2306: 
 2307: @assignment
 2308: Write a definition for computing the greatest common divisor.
 2309: @endassignment
 2310: 
 2311: Reference: @ref{Simple Loops}.
 2312: 
 2313: 
 2314: @node Counted loops Tutorial, Recursion Tutorial, General Loops Tutorial, Tutorial
 2315: @section Counted loops
 2316: @cindex loops, counted, tutorial
 2317: 
 2318: @example
 2319: : ^ ( n1 u -- n )
 2320: \ n = the uth power of u1
 2321:   1 swap 0 u+do
 2322:     over *
 2323:   loop
 2324:   nip ;
 2325: 3 2 ^ .
 2326: 4 3 ^ .
 2327: @end example
 2328: 
 2329: @code{U+do} (from @file{compat/loops.fs}, if your Forth system doesn't
 2330: have it) takes two numbers of the stack @code{( u3 u4 -- )}, and then
 2331: performs the code between @code{u+do} and @code{loop} for @code{u3-u4}
 2332: times (or not at all, if @code{u3-u4<0}).
 2333: 
 2334: You can see the stack effect design rules at work in the stack effect of
 2335: the loop start words: Since the start value of the loop is more
 2336: frequently constant than the end value, the start value is passed on
 2337: the top-of-stack.
 2338: 
 2339: You can access the counter of a counted loop with @code{i}:
 2340: 
 2341: @example
 2342: : fac ( u -- u! )
 2343:   1 swap 1+ 1 u+do
 2344:     i *
 2345:   loop ;
 2346: 5 fac .
 2347: 7 fac .
 2348: @end example
 2349: 
 2350: There is also @code{+do}, which expects signed numbers (important for
 2351: deciding whether to enter the loop).
 2352: 
 2353: @assignment
 2354: Write a definition for computing the nth Fibonacci number.
 2355: @endassignment
 2356: 
 2357: You can also use increments other than 1:
 2358: 
 2359: @example
 2360: : up2 ( n1 n2 -- )
 2361:   +do
 2362:     i .
 2363:   2 +loop ;
 2364: 10 0 up2
 2365: 
 2366: : down2 ( n1 n2 -- )
 2367:   -do
 2368:     i .
 2369:   2 -loop ;
 2370: 0 10 down2
 2371: @end example
 2372: 
 2373: Reference: @ref{Counted Loops}.
 2374: 
 2375: 
 2376: @node Recursion Tutorial, Leaving definitions or loops Tutorial, Counted loops Tutorial, Tutorial
 2377: @section Recursion
 2378: @cindex recursion tutorial
 2379: 
 2380: Usually the name of a definition is not visible in the definition; but
 2381: earlier definitions are usually visible:
 2382: 
 2383: @example
 2384: 1 0 / . \ "Floating-point unidentified fault" in Gforth on most platforms
 2385: : / ( n1 n2 -- n )
 2386:   dup 0= if
 2387:     -10 throw \ report division by zero
 2388:   endif
 2389:   /           \ old version
 2390: ;
 2391: 1 0 /
 2392: @end example
 2393: 
 2394: For recursive definitions you can use @code{recursive} (non-standard) or
 2395: @code{recurse}:
 2396: 
 2397: @example
 2398: : fac1 ( n -- n! ) recursive
 2399:  dup 0> if
 2400:    dup 1- fac1 *
 2401:  else
 2402:    drop 1
 2403:  endif ;
 2404: 7 fac1 .
 2405: 
 2406: : fac2 ( n -- n! )
 2407:  dup 0> if
 2408:    dup 1- recurse *
 2409:  else
 2410:    drop 1
 2411:  endif ;
 2412: 8 fac2 .
 2413: @end example
 2414: 
 2415: @assignment
 2416: Write a recursive definition for computing the nth Fibonacci number.
 2417: @endassignment
 2418: 
 2419: Reference (including indirect recursion): @xref{Calls and returns}.
 2420: 
 2421: 
 2422: @node Leaving definitions or loops Tutorial, Return Stack Tutorial, Recursion Tutorial, Tutorial
 2423: @section Leaving definitions or loops
 2424: @cindex leaving definitions, tutorial
 2425: @cindex leaving loops, tutorial
 2426: 
 2427: @code{EXIT} exits the current definition right away.  For every counted
 2428: loop that is left in this way, an @code{UNLOOP} has to be performed
 2429: before the @code{EXIT}:
 2430: 
 2431: @c !! real examples
 2432: @example
 2433: : ...
 2434:  ... u+do
 2435:    ... if
 2436:      ... unloop exit
 2437:    endif
 2438:    ...
 2439:  loop
 2440:  ... ;
 2441: @end example
 2442: 
 2443: @code{LEAVE} leaves the innermost counted loop right away:
 2444: 
 2445: @example
 2446: : ...
 2447:  ... u+do
 2448:    ... if
 2449:      ... leave
 2450:    endif
 2451:    ...
 2452:  loop
 2453:  ... ;
 2454: @end example
 2455: 
 2456: @c !! example
 2457: 
 2458: Reference: @ref{Calls and returns}, @ref{Counted Loops}.
 2459: 
 2460: 
 2461: @node Return Stack Tutorial, Memory Tutorial, Leaving definitions or loops Tutorial, Tutorial
 2462: @section Return Stack
 2463: @cindex return stack tutorial
 2464: 
 2465: In addition to the data stack Forth also has a second stack, the return
 2466: stack; most Forth systems store the return addresses of procedure calls
 2467: there (thus its name).  Programmers can also use this stack:
 2468: 
 2469: @example
 2470: : foo ( n1 n2 -- )
 2471:  .s
 2472:  >r .s
 2473:  r@@ .
 2474:  >r .s
 2475:  r@@ .
 2476:  r> .
 2477:  r@@ .
 2478:  r> . ;
 2479: 1 2 foo
 2480: @end example
 2481: 
 2482: @code{>r} takes an element from the data stack and pushes it onto the
 2483: return stack; conversely, @code{r>} moves an elementm from the return to
 2484: the data stack; @code{r@@} pushes a copy of the top of the return stack
 2485: on the return stack.
 2486: 
 2487: Forth programmers usually use the return stack for storing data
 2488: temporarily, if using the data stack alone would be too complex, and
 2489: factoring and locals are not an option:
 2490: 
 2491: @example
 2492: : 2swap ( x1 x2 x3 x4 -- x3 x4 x1 x2 )
 2493:  rot >r rot r> ;
 2494: @end example
 2495: 
 2496: The return address of the definition and the loop control parameters of
 2497: counted loops usually reside on the return stack, so you have to take
 2498: all items, that you have pushed on the return stack in a colon
 2499: definition or counted loop, from the return stack before the definition
 2500: or loop ends.  You cannot access items that you pushed on the return
 2501: stack outside some definition or loop within the definition of loop.
 2502: 
 2503: If you miscount the return stack items, this usually ends in a crash:
 2504: 
 2505: @example
 2506: : crash ( n -- )
 2507:   >r ;
 2508: 5 crash
 2509: @end example
 2510: 
 2511: You cannot mix using locals and using the return stack (according to the
 2512: standard; Gforth has no problem).  However, they solve the same
 2513: problems, so this shouldn't be an issue.
 2514: 
 2515: @assignment
 2516: Can you rewrite any of the definitions you wrote until now in a better
 2517: way using the return stack?
 2518: @endassignment
 2519: 
 2520: Reference: @ref{Return stack}.
 2521: 
 2522: 
 2523: @node Memory Tutorial, Characters and Strings Tutorial, Return Stack Tutorial, Tutorial
 2524: @section Memory
 2525: @cindex memory access/allocation tutorial
 2526: 
 2527: You can create a global variable @code{v} with
 2528: 
 2529: @example
 2530: variable v ( -- addr )
 2531: @end example
 2532: 
 2533: @code{v} pushes the address of a cell in memory on the stack.  This cell
 2534: was reserved by @code{variable}.  You can use @code{!} (store) to store
 2535: values into this cell and @code{@@} (fetch) to load the value from the
 2536: stack into memory:
 2537: 
 2538: @example
 2539: v .
 2540: 5 v ! .s
 2541: v @@ .
 2542: @end example
 2543: 
 2544: You can see a raw dump of memory with @code{dump}:
 2545: 
 2546: @example
 2547: v 1 cells .s dump
 2548: @end example
 2549: 
 2550: @code{Cells ( n1 -- n2 )} gives you the number of bytes (or, more
 2551: generally, address units (aus)) that @code{n1 cells} occupy.  You can
 2552: also reserve more memory:
 2553: 
 2554: @example
 2555: create v2 20 cells allot
 2556: v2 20 cells dump
 2557: @end example
 2558: 
 2559: creates a word @code{v2} and reserves 20 uninitialized cells; the
 2560: address pushed by @code{v2} points to the start of these 20 cells.  You
 2561: can use address arithmetic to access these cells:
 2562: 
 2563: @example
 2564: 3 v2 5 cells + !
 2565: v2 20 cells dump
 2566: @end example
 2567: 
 2568: You can reserve and initialize memory with @code{,}:
 2569: 
 2570: @example
 2571: create v3
 2572:   5 , 4 , 3 , 2 , 1 ,
 2573: v3 @@ .
 2574: v3 cell+ @@ .
 2575: v3 2 cells + @@ .
 2576: v3 5 cells dump
 2577: @end example
 2578: 
 2579: @assignment
 2580: Write a definition @code{vsum ( addr u -- n )} that computes the sum of
 2581: @code{u} cells, with the first of these cells at @code{addr}, the next
 2582: one at @code{addr cell+} etc.
 2583: @endassignment
 2584: 
 2585: You can also reserve memory without creating a new word:
 2586: 
 2587: @example
 2588: here 10 cells allot .
 2589: here .
 2590: @end example
 2591: 
 2592: @code{Here} pushes the start address of the memory area.  You should
 2593: store it somewhere, or you will have a hard time finding the memory area
 2594: again.
 2595: 
 2596: @code{Allot} manages dictionary memory.  The dictionary memory contains
 2597: the system's data structures for words etc. on Gforth and most other
 2598: Forth systems.  It is managed like a stack: You can free the memory that
 2599: you have just @code{allot}ed with
 2600: 
 2601: @example
 2602: -10 cells allot
 2603: here .
 2604: @end example
 2605: 
 2606: Note that you cannot do this if you have created a new word in the
 2607: meantime (because then your @code{allot}ed memory is no longer on the
 2608: top of the dictionary ``stack'').
 2609: 
 2610: Alternatively, you can use @code{allocate} and @code{free} which allow
 2611: freeing memory in any order:
 2612: 
 2613: @example
 2614: 10 cells allocate throw .s
 2615: 20 cells allocate throw .s
 2616: swap
 2617: free throw
 2618: free throw
 2619: @end example
 2620: 
 2621: The @code{throw}s deal with errors (e.g., out of memory).
 2622: 
 2623: And there is also a
 2624: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
 2625: garbage collector}, which eliminates the need to @code{free} memory
 2626: explicitly.
 2627: 
 2628: Reference: @ref{Memory}.
 2629: 
 2630: 
 2631: @node Characters and Strings Tutorial, Alignment Tutorial, Memory Tutorial, Tutorial
 2632: @section Characters and Strings
 2633: @cindex strings tutorial
 2634: @cindex characters tutorial
 2635: 
 2636: On the stack characters take up a cell, like numbers.  In memory they
 2637: have their own size (one 8-bit byte on most systems), and therefore
 2638: require their own words for memory access:
 2639: 
 2640: @example
 2641: create v4 
 2642:   104 c, 97 c, 108 c, 108 c, 111 c,
 2643: v4 4 chars + c@@ .
 2644: v4 5 chars dump
 2645: @end example
 2646: 
 2647: The preferred representation of strings on the stack is @code{addr
 2648: u-count}, where @code{addr} is the address of the first character and
 2649: @code{u-count} is the number of characters in the string.
 2650: 
 2651: @example
 2652: v4 5 type
 2653: @end example
 2654: 
 2655: You get a string constant with
 2656: 
 2657: @example
 2658: s" hello, world" .s
 2659: type
 2660: @end example
 2661: 
 2662: Make sure you have a space between @code{s"} and the string; @code{s"}
 2663: is a normal Forth word and must be delimited with white space (try what
 2664: happens when you remove the space).
 2665: 
 2666: However, this interpretive use of @code{s"} is quite restricted: the
 2667: string exists only until the next call of @code{s"} (some Forth systems
 2668: keep more than one of these strings, but usually they still have a
 2669: limited lifetime).
 2670: 
 2671: @example
 2672: s" hello," s" world" .s
 2673: type
 2674: type
 2675: @end example
 2676: 
 2677: You can also use @code{s"} in a definition, and the resulting
 2678: strings then live forever (well, for as long as the definition):
 2679: 
 2680: @example
 2681: : foo s" hello," s" world" ;
 2682: foo .s
 2683: type
 2684: type
 2685: @end example
 2686: 
 2687: @assignment
 2688: @code{Emit ( c -- )} types @code{c} as character (not a number).
 2689: Implement @code{type ( addr u -- )}.
 2690: @endassignment
 2691: 
 2692: Reference: @ref{Memory Blocks}.
 2693: 
 2694: 
 2695: @node Alignment Tutorial, Files Tutorial, Characters and Strings Tutorial, Tutorial
 2696: @section Alignment
 2697: @cindex alignment tutorial
 2698: @cindex memory alignment tutorial
 2699: 
 2700: On many processors cells have to be aligned in memory, if you want to
 2701: access them with @code{@@} and @code{!} (and even if the processor does
 2702: not require alignment, access to aligned cells is faster).
 2703: 
 2704: @code{Create} aligns @code{here} (i.e., the place where the next
 2705: allocation will occur, and that the @code{create}d word points to).
 2706: Likewise, the memory produced by @code{allocate} starts at an aligned
 2707: address.  Adding a number of @code{cells} to an aligned address produces
 2708: another aligned address.
 2709: 
 2710: However, address arithmetic involving @code{char+} and @code{chars} can
 2711: create an address that is not cell-aligned.  @code{Aligned ( addr --
 2712: a-addr )} produces the next aligned address:
 2713: 
 2714: @example
 2715: v3 char+ aligned .s @@ .
 2716: v3 char+ .s @@ .
 2717: @end example
 2718: 
 2719: Similarly, @code{align} advances @code{here} to the next aligned
 2720: address:
 2721: 
 2722: @example
 2723: create v5 97 c,
 2724: here .
 2725: align here .
 2726: 1000 ,
 2727: @end example
 2728: 
 2729: Note that you should use aligned addresses even if your processor does
 2730: not require them, if you want your program to be portable.
 2731: 
 2732: Reference: @ref{Address arithmetic}.
 2733: 
 2734: 
 2735: @node Files Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Alignment Tutorial, Tutorial
 2736: @section Files
 2737: @cindex files tutorial
 2738: 
 2739: This section gives a short introduction into how to use files inside
 2740: Forth. It's broken up into five easy steps:
 2741: 
 2742: @enumerate 1
 2743: @item Opened an ASCII text file for input
 2744: @item Opened a file for output
 2745: @item Read input file until string matched (or some other condition matched)
 2746: @item Wrote some lines from input ( modified or not) to output
 2747: @item Closed the files.
 2748: @end enumerate
 2749: 
 2750: @subsection Open file for input
 2751: 
 2752: @example
 2753: s" foo.in"  r/o open-file throw Value fd-in
 2754: @end example
 2755: 
 2756: @subsection Create file for output
 2757: 
 2758: @example
 2759: s" foo.out" w/o create-file throw Value fd-out
 2760: @end example
 2761: 
 2762: The available file modes are r/o for read-only access, r/w for
 2763: read-write access, and w/o for write-only access. You could open both
 2764: files with r/w, too, if you like. All file words return error codes; for
 2765: most applications, it's best to pass there error codes with @code{throw}
 2766: to the outer error handler.
 2767: 
 2768: If you want words for opening and assigning, define them as follows:
 2769: 
 2770: @example
 2771: 0 Value fd-in
 2772: 0 Value fd-out
 2773: : open-input ( addr u -- )  r/o open-file throw to fd-in ;
 2774: : open-output ( addr u -- )  w/o create-file throw to fd-out ;
 2775: @end example
 2776: 
 2777: Usage example:
 2778: 
 2779: @example
 2780: s" foo.in" open-input
 2781: s" foo.out" open-output
 2782: @end example
 2783: 
 2784: @subsection Scan file for a particular line
 2785: 
 2786: @example
 2787: 256 Constant max-line
 2788: Create line-buffer  max-line 2 + allot
 2789: 
 2790: : scan-file ( addr u -- )
 2791:   begin
 2792:       line-buffer max-line fd-in read-line throw
 2793:   while
 2794:          >r 2dup line-buffer r> compare 0=
 2795:      until
 2796:   else
 2797:      drop
 2798:   then
 2799:   2drop ;
 2800: @end example
 2801: 
 2802: @code{read-line ( addr u1 fd -- u2 flag ior )} reads up to u1 bytes into
 2803: the buffer at addr, and returns the number of bytes read, a flag that's
 2804: true when the end of file is reached, and an error code.
 2805: 
 2806: @code{compare ( addr1 u1 addr2 u2 -- n )} compares two strings and
 2807: returns zero if both strings are equal. It returns a positive number if
 2808: the first string is lexically greater, a negative if the second string
 2809: is lexically greater.
 2810: 
 2811: We haven't seen this loop here; it has two exits. Since the @code{while}
 2812: exits with the number of bytes read on the stack, we have to clean up
 2813: that separately; that's after the @code{else}.
 2814: 
 2815: Usage example:
 2816: 
 2817: @example
 2818: s" The text I search is here" scan-file
 2819: @end example
 2820: 
 2821: @subsection Copy input to output
 2822: 
 2823: @example
 2824: : copy-file ( -- )
 2825:   begin
 2826:       line-buffer max-line fd-in read-line throw
 2827:   while
 2828:       line-buffer swap fd-out write-file throw
 2829:   repeat ;
 2830: @end example
 2831: 
 2832: @subsection Close files
 2833: 
 2834: @example
 2835: fd-in close-file throw
 2836: fd-out close-file throw
 2837: @end example
 2838: 
 2839: Likewise, you can put that into definitions, too:
 2840: 
 2841: @example
 2842: : close-input ( -- )  fd-in close-file throw ;
 2843: : close-output ( -- )  fd-out close-file throw ;
 2844: @end example
 2845: 
 2846: @assignment
 2847: How could you modify @code{copy-file} so that it copies until a second line is
 2848: matched? Can you write a program that extracts a section of a text file,
 2849: given the line that starts and the line that terminates that section?
 2850: @endassignment
 2851: 
 2852: @node Interpretation and Compilation Semantics and Immediacy Tutorial, Execution Tokens Tutorial, Files Tutorial, Tutorial
 2853: @section Interpretation and Compilation Semantics and Immediacy
 2854: @cindex semantics tutorial
 2855: @cindex interpretation semantics tutorial
 2856: @cindex compilation semantics tutorial
 2857: @cindex immediate, tutorial
 2858: 
 2859: When a word is compiled, it behaves differently from being interpreted.
 2860: E.g., consider @code{+}:
 2861: 
 2862: @example
 2863: 1 2 + .
 2864: : foo + ;
 2865: @end example
 2866: 
 2867: These two behaviours are known as compilation and interpretation
 2868: semantics.  For normal words (e.g., @code{+}), the compilation semantics
 2869: is to append the interpretation semantics to the currently defined word
 2870: (@code{foo} in the example above).  I.e., when @code{foo} is executed
 2871: later, the interpretation semantics of @code{+} (i.e., adding two
 2872: numbers) will be performed.
 2873: 
 2874: However, there are words with non-default compilation semantics, e.g.,
 2875: the control-flow words like @code{if}.  You can use @code{immediate} to
 2876: change the compilation semantics of the last defined word to be equal to
 2877: the interpretation semantics:
 2878: 
 2879: @example
 2880: : [FOO] ( -- )
 2881:  5 . ; immediate
 2882: 
 2883: [FOO]
 2884: : bar ( -- )
 2885:   [FOO] ;
 2886: bar
 2887: see bar
 2888: @end example
 2889: 
 2890: Two conventions to mark words with non-default compilation semnatics are
 2891: names with brackets (more frequently used) and to write them all in
 2892: upper case (less frequently used).
 2893: 
 2894: In Gforth (and many other systems) you can also remove the
 2895: interpretation semantics with @code{compile-only} (the compilation
 2896: semantics is derived from the original interpretation semantics):
 2897: 
 2898: @example
 2899: : flip ( -- )
 2900:  6 . ; compile-only \ but not immediate
 2901: flip
 2902: 
 2903: : flop ( -- )
 2904:  flip ;
 2905: flop
 2906: @end example
 2907: 
 2908: In this example the interpretation semantics of @code{flop} is equal to
 2909: the original interpretation semantics of @code{flip}.
 2910: 
 2911: The text interpreter has two states: in interpret state, it performs the
 2912: interpretation semantics of words it encounters; in compile state, it
 2913: performs the compilation semantics of these words.
 2914: 
 2915: Among other things, @code{:} switches into compile state, and @code{;}
 2916: switches back to interpret state.  They contain the factors @code{]}
 2917: (switch to compile state) and @code{[} (switch to interpret state), that
 2918: do nothing but switch the state.
 2919: 
 2920: @example
 2921: : xxx ( -- )
 2922:   [ 5 . ]
 2923: ;
 2924: 
 2925: xxx
 2926: see xxx
 2927: @end example
 2928: 
 2929: These brackets are also the source of the naming convention mentioned
 2930: above.
 2931: 
 2932: Reference: @ref{Interpretation and Compilation Semantics}.
 2933: 
 2934: 
 2935: @node Execution Tokens Tutorial, Exceptions Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Tutorial
 2936: @section Execution Tokens
 2937: @cindex execution tokens tutorial
 2938: @cindex XT tutorial
 2939: 
 2940: @code{' word} gives you the execution token (XT) of a word.  The XT is a
 2941: cell representing the interpretation semantics of a word.  You can
 2942: execute this semantics with @code{execute}:
 2943: 
 2944: @example
 2945: ' + .s
 2946: 1 2 rot execute .
 2947: @end example
 2948: 
 2949: The XT is similar to a function pointer in C.  However, parameter
 2950: passing through the stack makes it a little more flexible:
 2951: 
 2952: @example
 2953: : map-array ( ... addr u xt -- ... )
 2954: \ executes xt ( ... x -- ... ) for every element of the array starting
 2955: \ at addr and containing u elements
 2956:   @{ xt @}
 2957:   cells over + swap ?do
 2958:     i @@ xt execute
 2959:   1 cells +loop ;
 2960: 
 2961: create a 3 , 4 , 2 , -1 , 4 ,
 2962: a 5 ' . map-array .s
 2963: 0 a 5 ' + map-array .
 2964: s" max-n" environment? drop .s
 2965: a 5 ' min map-array .
 2966: @end example
 2967: 
 2968: You can use map-array with the XTs of words that consume one element
 2969: more than they produce.  In theory you can also use it with other XTs,
 2970: but the stack effect then depends on the size of the array, which is
 2971: hard to understand.
 2972: 
 2973: Since XTs are cell-sized, you can store them in memory and manipulate
 2974: them on the stack like other cells.  You can also compile the XT into a
 2975: word with @code{compile,}:
 2976: 
 2977: @example
 2978: : foo1 ( n1 n2 -- n )
 2979:    [ ' + compile, ] ;
 2980: see foo
 2981: @end example
 2982: 
 2983: This is non-standard, because @code{compile,} has no compilation
 2984: semantics in the standard, but it works in good Forth systems.  For the
 2985: broken ones, use
 2986: 
 2987: @example
 2988: : [compile,] compile, ; immediate
 2989: 
 2990: : foo1 ( n1 n2 -- n )
 2991:    [ ' + ] [compile,] ;
 2992: see foo
 2993: @end example
 2994: 
 2995: @code{'} is a word with default compilation semantics; it parses the
 2996: next word when its interpretation semantics are executed, not during
 2997: compilation:
 2998: 
 2999: @example
 3000: : foo ( -- xt )
 3001:   ' ;
 3002: see foo
 3003: : bar ( ... "word" -- ... )
 3004:   ' execute ;
 3005: see bar
 3006: 1 2 bar + .
 3007: @end example
 3008: 
 3009: You often want to parse a word during compilation and compile its XT so
 3010: it will be pushed on the stack at run-time.  @code{[']} does this:
 3011: 
 3012: @example
 3013: : xt-+ ( -- xt )
 3014:   ['] + ;
 3015: see xt-+
 3016: 1 2 xt-+ execute .
 3017: @end example
 3018: 
 3019: Many programmers tend to see @code{'} and the word it parses as one
 3020: unit, and expect it to behave like @code{[']} when compiled, and are
 3021: confused by the actual behaviour.  If you are, just remember that the
 3022: Forth system just takes @code{'} as one unit and has no idea that it is
 3023: a parsing word (attempts to convenience programmers in this issue have
 3024: usually resulted in even worse pitfalls, see
 3025: @uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,
 3026: @code{State}-smartness---Why it is evil and How to Exorcise it}).
 3027: 
 3028: Note that the state of the interpreter does not come into play when
 3029: creating and executing XTs.  I.e., even when you execute @code{'} in
 3030: compile state, it still gives you the interpretation semantics.  And
 3031: whatever that state is, @code{execute} performs the semantics
 3032: represented by the XT (i.e., for XTs produced with @code{'} the
 3033: interpretation semantics).
 3034: 
 3035: Reference: @ref{Tokens for Words}.
 3036: 
 3037: 
 3038: @node Exceptions Tutorial, Defining Words Tutorial, Execution Tokens Tutorial, Tutorial
 3039: @section Exceptions
 3040: @cindex exceptions tutorial
 3041: 
 3042: @code{throw ( n -- )} causes an exception unless n is zero.
 3043: 
 3044: @example
 3045: 100 throw .s
 3046: 0 throw .s
 3047: @end example
 3048: 
 3049: @code{catch ( ... xt -- ... n )} behaves similar to @code{execute}, but
 3050: it catches exceptions and pushes the number of the exception on the
 3051: stack (or 0, if the xt executed without exception).  If there was an
 3052: exception, the stacks have the same depth as when entering @code{catch}:
 3053: 
 3054: @example
 3055: .s
 3056: 3 0 ' / catch .s
 3057: 3 2 ' / catch .s
 3058: @end example
 3059: 
 3060: @assignment
 3061: Try the same with @code{execute} instead of @code{catch}.
 3062: @endassignment
 3063: 
 3064: @code{Throw} always jumps to the dynamically next enclosing
 3065: @code{catch}, even if it has to leave several call levels to achieve
 3066: this:
 3067: 
 3068: @example
 3069: : foo 100 throw ;
 3070: : foo1 foo ." after foo" ;
 3071: : bar ['] foo1 catch ;
 3072: bar .
 3073: @end example
 3074: 
 3075: It is often important to restore a value upon leaving a definition, even
 3076: if the definition is left through an exception.  You can ensure this
 3077: like this:
 3078: 
 3079: @example
 3080: : ...
 3081:    save-x
 3082:    ['] word-changing-x catch ( ... n )
 3083:    restore-x
 3084:    ( ... n ) throw ;
 3085: @end example
 3086: 
 3087: Gforth provides an alternative syntax in addition to @code{catch}:
 3088: @code{try ... recover ... endtry}.  If the code between @code{try} and
 3089: @code{recover} has an exception, the stack depths are restored, the
 3090: exception number is pushed on the stack, and the code between
 3091: @code{recover} and @code{endtry} is performed.  E.g., the definition for
 3092: @code{catch} is
 3093: 
 3094: @example
 3095: : catch ( x1 .. xn xt -- y1 .. ym 0 / z1 .. zn error ) \ exception
 3096:   try
 3097:     execute 0
 3098:   recover
 3099:     nip
 3100:   endtry ;
 3101: @end example
 3102: 
 3103: The equivalent to the restoration code above is
 3104: 
 3105: @example
 3106: : ...
 3107:   save-x
 3108:   try
 3109:     word-changing-x
 3110:   end-try
 3111:   restore-x
 3112:   throw ;
 3113: @end example
 3114: 
 3115: As you can see, the @code{recover} part is optional.
 3116: 
 3117: Reference: @ref{Exception Handling}.
 3118: 
 3119: 
 3120: @node Defining Words Tutorial, Arrays and Records Tutorial, Exceptions Tutorial, Tutorial
 3121: @section Defining Words
 3122: @cindex defining words tutorial
 3123: @cindex does> tutorial
 3124: @cindex create...does> tutorial
 3125: 
 3126: @c before semantics?
 3127: 
 3128: @code{:}, @code{create}, and @code{variable} are definition words: They
 3129: define other words.  @code{Constant} is another definition word:
 3130: 
 3131: @example
 3132: 5 constant foo
 3133: foo .
 3134: @end example
 3135: 
 3136: You can also use the prefixes @code{2} (double-cell) and @code{f}
 3137: (floating point) with @code{variable} and @code{constant}.
 3138: 
 3139: You can also define your own defining words.  E.g.:
 3140: 
 3141: @example
 3142: : variable ( "name" -- )
 3143:   create 0 , ;
 3144: @end example
 3145: 
 3146: You can also define defining words that create words that do something
 3147: other than just producing their address:
 3148: 
 3149: @example
 3150: : constant ( n "name" -- )
 3151:   create ,
 3152: does> ( -- n )
 3153:   ( addr ) @@ ;
 3154: 
 3155: 5 constant foo
 3156: foo .
 3157: @end example
 3158: 
 3159: The definition of @code{constant} above ends at the @code{does>}; i.e.,
 3160: @code{does>} replaces @code{;}, but it also does something else: It
 3161: changes the last defined word such that it pushes the address of the
 3162: body of the word and then performs the code after the @code{does>}
 3163: whenever it is called.
 3164: 
 3165: In the example above, @code{constant} uses @code{,} to store 5 into the
 3166: body of @code{foo}.  When @code{foo} executes, it pushes the address of
 3167: the body onto the stack, then (in the code after the @code{does>})
 3168: fetches the 5 from there.
 3169: 
 3170: The stack comment near the @code{does>} reflects the stack effect of the
 3171: defined word, not the stack effect of the code after the @code{does>}
 3172: (the difference is that the code expects the address of the body that
 3173: the stack comment does not show).
 3174: 
 3175: You can use these definition words to do factoring in cases that involve
 3176: (other) definition words.  E.g., a field offset is always added to an
 3177: address.  Instead of defining
 3178: 
 3179: @example
 3180: 2 cells constant offset-field1
 3181: @end example
 3182: 
 3183: and using this like
 3184: 
 3185: @example
 3186: ( addr ) offset-field1 +
 3187: @end example
 3188: 
 3189: you can define a definition word
 3190: 
 3191: @example
 3192: : simple-field ( n "name" -- )
 3193:   create ,
 3194: does> ( n1 -- n1+n )
 3195:   ( addr ) @@ + ;
 3196: @end example
 3197: 
 3198: Definition and use of field offsets now look like this:
 3199: 
 3200: @example
 3201: 2 cells simple-field field1
 3202: create mystruct 4 cells allot
 3203: mystruct .s field1 .s drop
 3204: @end example
 3205: 
 3206: If you want to do something with the word without performing the code
 3207: after the @code{does>}, you can access the body of a @code{create}d word
 3208: with @code{>body ( xt -- addr )}:
 3209: 
 3210: @example
 3211: : value ( n "name" -- )
 3212:   create ,
 3213: does> ( -- n1 )
 3214:   @@ ;
 3215: : to ( n "name" -- )
 3216:   ' >body ! ;
 3217: 
 3218: 5 value foo
 3219: foo .
 3220: 7 to foo
 3221: foo .
 3222: @end example
 3223: 
 3224: @assignment
 3225: Define @code{defer ( "name" -- )}, which creates a word that stores an
 3226: XT (at the start the XT of @code{abort}), and upon execution
 3227: @code{execute}s the XT.  Define @code{is ( xt "name" -- )} that stores
 3228: @code{xt} into @code{name}, a word defined with @code{defer}.  Indirect
 3229: recursion is one application of @code{defer}.
 3230: @endassignment
 3231: 
 3232: Reference: @ref{User-defined Defining Words}.
 3233: 
 3234: 
 3235: @node Arrays and Records Tutorial, POSTPONE Tutorial, Defining Words Tutorial, Tutorial
 3236: @section Arrays and Records
 3237: @cindex arrays tutorial
 3238: @cindex records tutorial
 3239: @cindex structs tutorial
 3240: 
 3241: Forth has no standard words for defining data structures such as arrays
 3242: and records (structs in C terminology), but you can build them yourself
 3243: based on address arithmetic.  You can also define words for defining
 3244: arrays and records (@pxref{Defining Words Tutorial,, Defining Words}).
 3245: 
 3246: One of the first projects a Forth newcomer sets out upon when learning
 3247: about defining words is an array defining word (possibly for
 3248: n-dimensional arrays).  Go ahead and do it, I did it, too; you will
 3249: learn something from it.  However, don't be disappointed when you later
 3250: learn that you have little use for these words (inappropriate use would
 3251: be even worse).  I have not yet found a set of useful array words yet;
 3252: the needs are just too diverse, and named, global arrays (the result of
 3253: naive use of defining words) are often not flexible enough (e.g.,
 3254: consider how to pass them as parameters).  Another such project is a set
 3255: of words to help dealing with strings.
 3256: 
 3257: On the other hand, there is a useful set of record words, and it has
 3258: been defined in @file{compat/struct.fs}; these words are predefined in
 3259: Gforth.  They are explained in depth elsewhere in this manual (see
 3260: @pxref{Structures}).  The @code{simple-field} example above is
 3261: simplified variant of fields in this package.
 3262: 
 3263: 
 3264: @node POSTPONE Tutorial, Literal Tutorial, Arrays and Records Tutorial, Tutorial
 3265: @section @code{POSTPONE}
 3266: @cindex postpone tutorial
 3267: 
 3268: You can compile the compilation semantics (instead of compiling the
 3269: interpretation semantics) of a word with @code{POSTPONE}:
 3270: 
 3271: @example
 3272: : MY-+ ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
 3273:  POSTPONE + ; immediate
 3274: : foo ( n1 n2 -- n )
 3275:  MY-+ ;
 3276: 1 2 foo .
 3277: see foo
 3278: @end example
 3279: 
 3280: During the definition of @code{foo} the text interpreter performs the
 3281: compilation semantics of @code{MY-+}, which performs the compilation
 3282: semantics of @code{+}, i.e., it compiles @code{+} into @code{foo}.
 3283: 
 3284: This example also displays separate stack comments for the compilation
 3285: semantics and for the stack effect of the compiled code.  For words with
 3286: default compilation semantics these stack effects are usually not
 3287: displayed; the stack effect of the compilation semantics is always
 3288: @code{( -- )} for these words, the stack effect for the compiled code is
 3289: the stack effect of the interpretation semantics.
 3290: 
 3291: Note that the state of the interpreter does not come into play when
 3292: performing the compilation semantics in this way.  You can also perform
 3293: it interpretively, e.g.:
 3294: 
 3295: @example
 3296: : foo2 ( n1 n2 -- n )
 3297:  [ MY-+ ] ;
 3298: 1 2 foo .
 3299: see foo
 3300: @end example
 3301: 
 3302: However, there are some broken Forth systems where this does not always
 3303: work, and therefore this practice was been declared non-standard in
 3304: 1999.
 3305: @c !! repair.fs
 3306: 
 3307: Here is another example for using @code{POSTPONE}:
 3308: 
 3309: @example
 3310: : MY-- ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
 3311:  POSTPONE negate POSTPONE + ; immediate compile-only
 3312: : bar ( n1 n2 -- n )
 3313:   MY-- ;
 3314: 2 1 bar .
 3315: see bar
 3316: @end example
 3317: 
 3318: You can define @code{ENDIF} in this way:
 3319: 
 3320: @example
 3321: : ENDIF ( Compilation: orig -- )
 3322:   POSTPONE then ; immediate
 3323: @end example
 3324: 
 3325: @assignment
 3326: Write @code{MY-2DUP} that has compilation semantics equivalent to
 3327: @code{2dup}, but compiles @code{over over}.
 3328: @endassignment
 3329: 
 3330: @c !! @xref{Macros} for reference
 3331: 
 3332: 
 3333: @node Literal Tutorial, Advanced macros Tutorial, POSTPONE Tutorial, Tutorial
 3334: @section @code{Literal}
 3335: @cindex literal tutorial
 3336: 
 3337: You cannot @code{POSTPONE} numbers:
 3338: 
 3339: @example
 3340: : [FOO] POSTPONE 500 ; immediate
 3341: @end example
 3342: 
 3343: Instead, you can use @code{LITERAL (compilation: n --; run-time: -- n )}:
 3344: 
 3345: @example
 3346: : [FOO] ( compilation: --; run-time: -- n )
 3347:   500 POSTPONE literal ; immediate
 3348: 
 3349: : flip [FOO] ;
 3350: flip .
 3351: see flip
 3352: @end example
 3353: 
 3354: @code{LITERAL} consumes a number at compile-time (when it's compilation
 3355: semantics are executed) and pushes it at run-time (when the code it
 3356: compiled is executed).  A frequent use of @code{LITERAL} is to compile a
 3357: number computed at compile time into the current word:
 3358: 
 3359: @example
 3360: : bar ( -- n )
 3361:   [ 2 2 + ] literal ;
 3362: see bar
 3363: @end example
 3364: 
 3365: @assignment
 3366: Write @code{]L} which allows writing the example above as @code{: bar (
 3367: -- n ) [ 2 2 + ]L ;}
 3368: @endassignment
 3369: 
 3370: @c !! @xref{Macros} for reference
 3371: 
 3372: 
 3373: @node Advanced macros Tutorial, Compilation Tokens Tutorial, Literal Tutorial, Tutorial
 3374: @section Advanced macros
 3375: @cindex macros, advanced tutorial
 3376: @cindex run-time code generation, tutorial
 3377: 
 3378: Reconsider @code{map-array} from @ref{Execution Tokens Tutorial,,
 3379: Execution Tokens}.  It frequently performs @code{execute}, a relatively
 3380: expensive operation in some Forth implementations.  You can use
 3381: @code{compile,} and @code{POSTPONE} to eliminate these @code{execute}s
 3382: and produce a word that contains the word to be performed directly:
 3383: 
 3384: @c use ]] ... [[
 3385: @example
 3386: : compile-map-array ( compilation: xt -- ; run-time: ... addr u -- ... )
 3387: \ at run-time, execute xt ( ... x -- ... ) for each element of the
 3388: \ array beginning at addr and containing u elements
 3389:   @{ xt @}
 3390:   POSTPONE cells POSTPONE over POSTPONE + POSTPONE swap POSTPONE ?do
 3391:     POSTPONE i POSTPONE @@ xt compile,
 3392:   1 cells POSTPONE literal POSTPONE +loop ;
 3393: 
 3394: : sum-array ( addr u -- n )
 3395:  0 rot rot [ ' + compile-map-array ] ;
 3396: see sum-array
 3397: a 5 sum-array .
 3398: @end example
 3399: 
 3400: You can use the full power of Forth for generating the code; here's an
 3401: example where the code is generated in a loop:
 3402: 
 3403: @example
 3404: : compile-vmul-step ( compilation: n --; run-time: n1 addr1 -- n2 addr2 )
 3405: \ n2=n1+(addr1)*n, addr2=addr1+cell
 3406:   POSTPONE tuck POSTPONE @@
 3407:   POSTPONE literal POSTPONE * POSTPONE +
 3408:   POSTPONE swap POSTPONE cell+ ;
 3409: 
 3410: : compile-vmul ( compilation: addr1 u -- ; run-time: addr2 -- n )
 3411: \ n=v1*v2 (inner product), where the v_i are represented as addr_i u
 3412:   0 postpone literal postpone swap
 3413:   [ ' compile-vmul-step compile-map-array ]
 3414:   postpone drop ;
 3415: see compile-vmul
 3416: 
 3417: : a-vmul ( addr -- n )
 3418: \ n=a*v, where v is a vector that's as long as a and starts at addr
 3419:  [ a 5 compile-vmul ] ;
 3420: see a-vmul
 3421: a a-vmul .
 3422: @end example
 3423: 
 3424: This example uses @code{compile-map-array} to show off, but you could
 3425: also use @code{map-array} instead (try it now!).
 3426: 
 3427: You can use this technique for efficient multiplication of large
 3428: matrices.  In matrix multiplication, you multiply every line of one
 3429: matrix with every column of the other matrix.  You can generate the code
 3430: for one line once, and use it for every column.  The only downside of
 3431: this technique is that it is cumbersome to recover the memory consumed
 3432: by the generated code when you are done (and in more complicated cases
 3433: it is not possible portably).
 3434: 
 3435: @c !! @xref{Macros} for reference
 3436: 
 3437: 
 3438: @node Compilation Tokens Tutorial, Wordlists and Search Order Tutorial, Advanced macros Tutorial, Tutorial
 3439: @section Compilation Tokens
 3440: @cindex compilation tokens, tutorial
 3441: @cindex CT, tutorial
 3442: 
 3443: This section is Gforth-specific.  You can skip it.
 3444: 
 3445: @code{' word compile,} compiles the interpretation semantics.  For words
 3446: with default compilation semantics this is the same as performing the
 3447: compilation semantics.  To represent the compilation semantics of other
 3448: words (e.g., words like @code{if} that have no interpretation
 3449: semantics), Gforth has the concept of a compilation token (CT,
 3450: consisting of two cells), and words @code{comp'} and @code{[comp']}.
 3451: You can perform the compilation semantics represented by a CT with
 3452: @code{execute}:
 3453: 
 3454: @example
 3455: : foo2 ( n1 n2 -- n )
 3456:    [ comp' + execute ] ;
 3457: see foo
 3458: @end example
 3459: 
 3460: You can compile the compilation semantics represented by a CT with
 3461: @code{postpone,}:
 3462: 
 3463: @example
 3464: : foo3 ( -- )
 3465:   [ comp' + postpone, ] ;
 3466: see foo3
 3467: @end example
 3468: 
 3469: @code{[ comp' word postpone, ]} is equivalent to @code{POSTPONE word}.
 3470: @code{comp'} is particularly useful for words that have no
 3471: interpretation semantics:
 3472: 
 3473: @example
 3474: ' if
 3475: comp' if .s 2drop
 3476: @end example
 3477: 
 3478: Reference: @ref{Tokens for Words}.
 3479: 
 3480: 
 3481: @node Wordlists and Search Order Tutorial,  , Compilation Tokens Tutorial, Tutorial
 3482: @section Wordlists and Search Order
 3483: @cindex wordlists tutorial
 3484: @cindex search order, tutorial
 3485: 
 3486: The dictionary is not just a memory area that allows you to allocate
 3487: memory with @code{allot}, it also contains the Forth words, arranged in
 3488: several wordlists.  When searching for a word in a wordlist,
 3489: conceptually you start searching at the youngest and proceed towards
 3490: older words (in reality most systems nowadays use hash-tables); i.e., if
 3491: you define a word with the same name as an older word, the new word
 3492: shadows the older word.
 3493: 
 3494: Which wordlists are searched in which order is determined by the search
 3495: order.  You can display the search order with @code{order}.  It displays
 3496: first the search order, starting with the wordlist searched first, then
 3497: it displays the wordlist that will contain newly defined words.
 3498: 
 3499: You can create a new, empty wordlist with @code{wordlist ( -- wid )}:
 3500: 
 3501: @example
 3502: wordlist constant mywords
 3503: @end example
 3504: 
 3505: @code{Set-current ( wid -- )} sets the wordlist that will contain newly
 3506: defined words (the @emph{current} wordlist):
 3507: 
 3508: @example
 3509: mywords set-current
 3510: order
 3511: @end example
 3512: 
 3513: Gforth does not display a name for the wordlist in @code{mywords}
 3514: because this wordlist was created anonymously with @code{wordlist}.
 3515: 
 3516: You can get the current wordlist with @code{get-current ( -- wid)}.  If
 3517: you want to put something into a specific wordlist without overall
 3518: effect on the current wordlist, this typically looks like this:
 3519: 
 3520: @example
 3521: get-current mywords set-current ( wid )
 3522: create someword
 3523: ( wid ) set-current
 3524: @end example
 3525: 
 3526: You can write the search order with @code{set-order ( wid1 .. widn n --
 3527: )} and read it with @code{get-order ( -- wid1 .. widn n )}.  The first
 3528: searched wordlist is topmost.
 3529: 
 3530: @example
 3531: get-order mywords swap 1+ set-order
 3532: order
 3533: @end example
 3534: 
 3535: Yes, the order of wordlists in the output of @code{order} is reversed
 3536: from stack comments and the output of @code{.s} and thus unintuitive.
 3537: 
 3538: @assignment
 3539: Define @code{>order ( wid -- )} with adds @code{wid} as first searched
 3540: wordlist to the search order.  Define @code{previous ( -- )}, which
 3541: removes the first searched wordlist from the search order.  Experiment
 3542: with boundary conditions (you will see some crashes or situations that
 3543: are hard or impossible to leave).
 3544: @endassignment
 3545: 
 3546: The search order is a powerful foundation for providing features similar
 3547: to Modula-2 modules and C++ namespaces.  However, trying to modularize
 3548: programs in this way has disadvantages for debugging and reuse/factoring
 3549: that overcome the advantages in my experience (I don't do huge projects,
 3550: though).  These disadvantages are not so clear in other
 3551: languages/programming environments, because these languages are not so
 3552: strong in debugging and reuse.
 3553: 
 3554: @c !! example
 3555: 
 3556: Reference: @ref{Word Lists}.
 3557: 
 3558: @c ******************************************************************
 3559: @node Introduction, Words, Tutorial, Top
 3560: @comment node-name,     next,           previous, up
 3561: @chapter An Introduction to ANS Forth
 3562: @cindex Forth - an introduction
 3563: 
 3564: The difference of this chapter from the Tutorial (@pxref{Tutorial}) is
 3565: that it is slower-paced in its examples, but uses them to dive deep into
 3566: explaining Forth internals (not covered by the Tutorial).  Apart from
 3567: that, this chapter covers far less material.  It is suitable for reading
 3568: without using a computer.
 3569: 
 3570: The primary purpose of this manual is to document Gforth. However, since
 3571: Forth is not a widely-known language and there is a lack of up-to-date
 3572: teaching material, it seems worthwhile to provide some introductory
 3573: material.  For other sources of Forth-related
 3574: information, see @ref{Forth-related information}.
 3575: 
 3576: The examples in this section should work on any ANS Forth; the
 3577: output shown was produced using Gforth. Each example attempts to
 3578: reproduce the exact output that Gforth produces. If you try out the
 3579: examples (and you should), what you should type is shown @kbd{like this}
 3580: and Gforth's response is shown @code{like this}. The single exception is
 3581: that, where the example shows @key{RET} it means that you should
 3582: press the ``carriage return'' key. Unfortunately, some output formats for
 3583: this manual cannot show the difference between @kbd{this} and
 3584: @code{this} which will make trying out the examples harder (but not
 3585: impossible).
 3586: 
 3587: Forth is an unusual language. It provides an interactive development
 3588: environment which includes both an interpreter and compiler. Forth
 3589: programming style encourages you to break a problem down into many
 3590: @cindex factoring
 3591: small fragments (@dfn{factoring}), and then to develop and test each
 3592: fragment interactively. Forth advocates assert that breaking the
 3593: edit-compile-test cycle used by conventional programming languages can
 3594: lead to great productivity improvements.
 3595: 
 3596: @menu
 3597: * Introducing the Text Interpreter::  
 3598: * Stacks and Postfix notation::  
 3599: * Your first definition::       
 3600: * How does that work?::         
 3601: * Forth is written in Forth::   
 3602: * Review - elements of a Forth system::  
 3603: * Where to go next::            
 3604: * Exercises::                   
 3605: @end menu
 3606: 
 3607: @comment ----------------------------------------------
 3608: @node Introducing the Text Interpreter, Stacks and Postfix notation, Introduction, Introduction
 3609: @section Introducing the Text Interpreter
 3610: @cindex text interpreter
 3611: @cindex outer interpreter
 3612: 
 3613: @c IMO this is too detailed and the pace is too slow for
 3614: @c an introduction.  If you know German, take a look at
 3615: @c http://www.complang.tuwien.ac.at/anton/lvas/skriptum-stack.html 
 3616: @c to see how I do it - anton 
 3617: 
 3618: @c nac-> Where I have accepted your comments 100% and modified the text
 3619: @c accordingly, I have deleted your comments. Elsewhere I have added a
 3620: @c response like this to attempt to rationalise what I have done. Of
 3621: @c course, this is a very clumsy mechanism for something that would be
 3622: @c done far more efficiently over a beer. Please delete any dialogue
 3623: @c you consider closed.
 3624: 
 3625: When you invoke the Forth image, you will see a startup banner printed
 3626: and nothing else (if you have Gforth installed on your system, try
 3627: invoking it now, by typing @kbd{gforth@key{RET}}). Forth is now running
 3628: its command line interpreter, which is called the @dfn{Text Interpreter}
 3629: (also known as the @dfn{Outer Interpreter}).  (You will learn a lot
 3630: about the text interpreter as you read through this chapter, for more
 3631: detail @pxref{The Text Interpreter}).
 3632: 
 3633: Although it's not obvious, Forth is actually waiting for your
 3634: input. Type a number and press the @key{RET} key:
 3635: 
 3636: @example
 3637: @kbd{45@key{RET}}  ok
 3638: @end example
 3639: 
 3640: Rather than give you a prompt to invite you to input something, the text
 3641: interpreter prints a status message @i{after} it has processed a line
 3642: of input. The status message in this case (``@code{ ok}'' followed by
 3643: carriage-return) indicates that the text interpreter was able to process
 3644: all of your input successfully. Now type something illegal:
 3645: 
 3646: @example
 3647: @kbd{qwer341@key{RET}}
 3648: :1: Undefined word
 3649: qwer341
 3650: ^^^^^^^
 3651: $400D2BA8 Bounce
 3652: $400DBDA8 no.extensions
 3653: @end example
 3654: 
 3655: The exact text, other than the ``Undefined word'' may differ slightly on
 3656: your system, but the effect is the same; when the text interpreter
 3657: detects an error, it discards any remaining text on a line, resets
 3658: certain internal state and prints an error message. For a detailed description of error messages see @ref{Error
 3659: messages}.
 3660: 
 3661: The text interpreter waits for you to press carriage-return, and then
 3662: processes your input line. Starting at the beginning of the line, it
 3663: breaks the line into groups of characters separated by spaces. For each
 3664: group of characters in turn, it makes two attempts to do something:
 3665: 
 3666: @itemize @bullet
 3667: @item
 3668: @cindex name dictionary
 3669: It tries to treat it as a command. It does this by searching a @dfn{name
 3670: dictionary}. If the group of characters matches an entry in the name
 3671: dictionary, the name dictionary provides the text interpreter with
 3672: information that allows the text interpreter perform some actions. In
 3673: Forth jargon, we say that the group
 3674: @cindex word
 3675: @cindex definition
 3676: @cindex execution token
 3677: @cindex xt
 3678: of characters names a @dfn{word}, that the dictionary search returns an
 3679: @dfn{execution token (xt)} corresponding to the @dfn{definition} of the
 3680: word, and that the text interpreter executes the xt. Often, the terms
 3681: @dfn{word} and @dfn{definition} are used interchangeably.
 3682: @item
 3683: If the text interpreter fails to find a match in the name dictionary, it
 3684: tries to treat the group of characters as a number in the current number
 3685: base (when you start up Forth, the current number base is base 10). If
 3686: the group of characters legitimately represents a number, the text
 3687: interpreter pushes the number onto a stack (we'll learn more about that
 3688: in the next section).
 3689: @end itemize
 3690: 
 3691: If the text interpreter is unable to do either of these things with any
 3692: group of characters, it discards the group of characters and the rest of
 3693: the line, then prints an error message. If the text interpreter reaches
 3694: the end of the line without error, it prints the status message ``@code{ ok}''
 3695: followed by carriage-return.
 3696: 
 3697: This is the simplest command we can give to the text interpreter:
 3698: 
 3699: @example
 3700: @key{RET}  ok
 3701: @end example
 3702: 
 3703: The text interpreter did everything we asked it to do (nothing) without
 3704: an error, so it said that everything is ``@code{ ok}''. Try a slightly longer
 3705: command:
 3706: 
 3707: @example
 3708: @kbd{12 dup fred dup@key{RET}}
 3709: :1: Undefined word
 3710: 12 dup fred dup
 3711:        ^^^^
 3712: $400D2BA8 Bounce
 3713: $400DBDA8 no.extensions
 3714: @end example
 3715: 
 3716: When you press the carriage-return key, the text interpreter starts to
 3717: work its way along the line:
 3718: 
 3719: @itemize @bullet
 3720: @item
 3721: When it gets to the space after the @code{2}, it takes the group of
 3722: characters @code{12} and looks them up in the name
 3723: dictionary@footnote{We can't tell if it found them or not, but assume
 3724: for now that it did not}. There is no match for this group of characters
 3725: in the name dictionary, so it tries to treat them as a number. It is
 3726: able to do this successfully, so it puts the number, 12, ``on the stack''
 3727: (whatever that means).
 3728: @item
 3729: The text interpreter resumes scanning the line and gets the next group
 3730: of characters, @code{dup}. It looks it up in the name dictionary and
 3731: (you'll have to take my word for this) finds it, and executes the word
 3732: @code{dup} (whatever that means).
 3733: @item
 3734: Once again, the text interpreter resumes scanning the line and gets the
 3735: group of characters @code{fred}. It looks them up in the name
 3736: dictionary, but can't find them. It tries to treat them as a number, but
 3737: they don't represent any legal number.
 3738: @end itemize
 3739: 
 3740: At this point, the text interpreter gives up and prints an error
 3741: message. The error message shows exactly how far the text interpreter
 3742: got in processing the line. In particular, it shows that the text
 3743: interpreter made no attempt to do anything with the final character
 3744: group, @code{dup}, even though we have good reason to believe that the
 3745: text interpreter would have no problem looking that word up and
 3746: executing it a second time.
 3747: 
 3748: 
 3749: @comment ----------------------------------------------
 3750: @node Stacks and Postfix notation, Your first definition, Introducing the Text Interpreter, Introduction
 3751: @section Stacks, postfix notation and parameter passing
 3752: @cindex text interpreter
 3753: @cindex outer interpreter
 3754: 
 3755: In procedural programming languages (like C and Pascal), the
 3756: building-block of programs is the @dfn{function} or @dfn{procedure}. These
 3757: functions or procedures are called with @dfn{explicit parameters}. For
 3758: example, in C we might write:
 3759: 
 3760: @example
 3761: total = total + new_volume(length,height,depth);
 3762: @end example
 3763: 
 3764: @noindent
 3765: where new_volume is a function-call to another piece of code, and total,
 3766: length, height and depth are all variables. length, height and depth are
 3767: parameters to the function-call.
 3768: 
 3769: In Forth, the equivalent of the function or procedure is the
 3770: @dfn{definition} and parameters are implicitly passed between
 3771: definitions using a shared stack that is visible to the
 3772: programmer. Although Forth does support variables, the existence of the
 3773: stack means that they are used far less often than in most other
 3774: programming languages. When the text interpreter encounters a number, it
 3775: will place (@dfn{push}) it on the stack. There are several stacks (the
 3776: actual number is implementation-dependent ...) and the particular stack
 3777: used for any operation is implied unambiguously by the operation being
 3778: performed. The stack used for all integer operations is called the @dfn{data
 3779: stack} and, since this is the stack used most commonly, references to
 3780: ``the data stack'' are often abbreviated to ``the stack''.
 3781: 
 3782: The stacks have a last-in, first-out (LIFO) organisation. If you type:
 3783: 
 3784: @example
 3785: @kbd{1 2 3@key{RET}}  ok
 3786: @end example
 3787: 
 3788: Then this instructs the text interpreter to placed three numbers on the
 3789: (data) stack. An analogy for the behaviour of the stack is to take a
 3790: pack of playing cards and deal out the ace (1), 2 and 3 into a pile on
 3791: the table. The 3 was the last card onto the pile (``last-in'') and if
 3792: you take a card off the pile then, unless you're prepared to fiddle a
 3793: bit, the card that you take off will be the 3 (``first-out''). The
 3794: number that will be first-out of the stack is called the @dfn{top of
 3795: stack}, which
 3796: @cindex TOS definition
 3797: is often abbreviated to @dfn{TOS}.
 3798: 
 3799: To understand how parameters are passed in Forth, consider the
 3800: behaviour of the definition @code{+} (pronounced ``plus''). You will not
 3801: be surprised to learn that this definition performs addition. More
 3802: precisely, it adds two number together and produces a result. Where does
 3803: it get the two numbers from? It takes the top two numbers off the
 3804: stack. Where does it place the result? On the stack. You can act-out the
 3805: behaviour of @code{+} with your playing cards like this:
 3806: 
 3807: @itemize @bullet
 3808: @item
 3809: Pick up two cards from the stack on the table
 3810: @item
 3811: Stare at them intently and ask yourself ``what @i{is} the sum of these two
 3812: numbers''
 3813: @item
 3814: Decide that the answer is 5
 3815: @item
 3816: Shuffle the two cards back into the pack and find a 5
 3817: @item
 3818: Put a 5 on the remaining ace that's on the table.
 3819: @end itemize
 3820: 
 3821: If you don't have a pack of cards handy but you do have Forth running,
 3822: you can use the definition @code{.s} to show the current state of the stack,
 3823: without affecting the stack. Type:
 3824: 
 3825: @example
 3826: @kbd{clearstack 1 2 3@key{RET}} ok
 3827: @kbd{.s@key{RET}} <3> 1 2 3  ok
 3828: @end example
 3829: 
 3830: The text interpreter looks up the word @code{clearstack} and executes
 3831: it; it tidies up the stack and removes any entries that may have been
 3832: left on it by earlier examples. The text interpreter pushes each of the
 3833: three numbers in turn onto the stack. Finally, the text interpreter
 3834: looks up the word @code{.s} and executes it. The effect of executing
 3835: @code{.s} is to print the ``<3>'' (the total number of items on the stack)
 3836: followed by a list of all the items on the stack; the item on the far
 3837: right-hand side is the TOS.
 3838: 
 3839: You can now type:
 3840: 
 3841: @example
 3842: @kbd{+ .s@key{RET}} <2> 1 5  ok
 3843: @end example
 3844: 
 3845: @noindent
 3846: which is correct; there are now 2 items on the stack and the result of
 3847: the addition is 5.
 3848: 
 3849: If you're playing with cards, try doing a second addition: pick up the
 3850: two cards, work out that their sum is 6, shuffle them into the pack,
 3851: look for a 6 and place that on the table. You now have just one item on
 3852: the stack. What happens if you try to do a third addition? Pick up the
 3853: first card, pick up the second card -- ah! There is no second card. This
 3854: is called a @dfn{stack underflow} and consitutes an error. If you try to
 3855: do the same thing with Forth it will report an error (probably a Stack
 3856: Underflow or an Invalid Memory Address error).
 3857: 
 3858: The opposite situation to a stack underflow is a @dfn{stack overflow},
 3859: which simply accepts that there is a finite amount of storage space
 3860: reserved for the stack. To stretch the playing card analogy, if you had
 3861: enough packs of cards and you piled the cards up on the table, you would
 3862: eventually be unable to add another card; you'd hit the ceiling. Gforth
 3863: allows you to set the maximum size of the stacks. In general, the only
 3864: time that you will get a stack overflow is because a definition has a
 3865: bug in it and is generating data on the stack uncontrollably.
 3866: 
 3867: There's one final use for the playing card analogy. If you model your
 3868: stack using a pack of playing cards, the maximum number of items on
 3869: your stack will be 52 (I assume you didn't use the Joker). The maximum
 3870: @i{value} of any item on the stack is 13 (the King). In fact, the only
 3871: possible numbers are positive integer numbers 1 through 13; you can't
 3872: have (for example) 0 or 27 or 3.52 or -2. If you change the way you
 3873: think about some of the cards, you can accommodate different
 3874: numbers. For example, you could think of the Jack as representing 0,
 3875: the Queen as representing -1 and the King as representing -2. Your
 3876: @i{range} remains unchanged (you can still only represent a total of 13
 3877: numbers) but the numbers that you can represent are -2 through 10.
 3878: 
 3879: In that analogy, the limit was the amount of information that a single
 3880: stack entry could hold, and Forth has a similar limit. In Forth, the
 3881: size of a stack entry is called a @dfn{cell}. The actual size of a cell is
 3882: implementation dependent and affects the maximum value that a stack
 3883: entry can hold. A Standard Forth provides a cell size of at least
 3884: 16-bits, and most desktop systems use a cell size of 32-bits.
 3885: 
 3886: Forth does not do any type checking for you, so you are free to
 3887: manipulate and combine stack items in any way you wish. A convenient way
 3888: of treating stack items is as 2's complement signed integers, and that
 3889: is what Standard words like @code{+} do. Therefore you can type:
 3890: 
 3891: @example
 3892: @kbd{-5 12 + .s@key{RET}} <1> 7  ok
 3893: @end example
 3894: 
 3895: If you use numbers and definitions like @code{+} in order to turn Forth
 3896: into a great big pocket calculator, you will realise that it's rather
 3897: different from a normal calculator. Rather than typing 2 + 3 = you had
 3898: to type 2 3 + (ignore the fact that you had to use @code{.s} to see the
 3899: result). The terminology used to describe this difference is to say that
 3900: your calculator uses @dfn{Infix Notation} (parameters and operators are
 3901: mixed) whilst Forth uses @dfn{Postfix Notation} (parameters and
 3902: operators are separate), also called @dfn{Reverse Polish Notation}.
 3903: 
 3904: Whilst postfix notation might look confusing to begin with, it has
 3905: several important advantages:
 3906: 
 3907: @itemize @bullet
 3908: @item
 3909: it is unambiguous
 3910: @item
 3911: it is more concise
 3912: @item
 3913: it fits naturally with a stack-based system
 3914: @end itemize
 3915: 
 3916: To examine these claims in more detail, consider these sums:
 3917: 
 3918: @example
 3919: 6 + 5 * 4 =
 3920: 4 * 5 + 6 =
 3921: @end example
 3922: 
 3923: If you're just learning maths or your maths is very rusty, you will
 3924: probably come up with the answer 44 for the first and 26 for the
 3925: second. If you are a bit of a whizz at maths you will remember the
 3926: @i{convention} that multiplication takes precendence over addition, and
 3927: you'd come up with the answer 26 both times. To explain the answer 26
 3928: to someone who got the answer 44, you'd probably rewrite the first sum
 3929: like this:
 3930: 
 3931: @example
 3932: 6 + (5 * 4) =
 3933: @end example
 3934: 
 3935: If what you really wanted was to perform the addition before the
 3936: multiplication, you would have to use parentheses to force it.
 3937: 
 3938: If you did the first two sums on a pocket calculator you would probably
 3939: get the right answers, unless you were very cautious and entered them using
 3940: these keystroke sequences:
 3941: 
 3942: 6 + 5 = * 4 =
 3943: 4 * 5 = + 6 =
 3944: 
 3945: Postfix notation is unambiguous because the order that the operators
 3946: are applied is always explicit; that also means that parentheses are
 3947: never required. The operators are @i{active} (the act of quoting the
 3948: operator makes the operation occur) which removes the need for ``=''.
 3949: 
 3950: The sum 6 + 5 * 4 can be written (in postfix notation) in two
 3951: equivalent ways:
 3952: 
 3953: @example
 3954: 6 5 4 * +      or:
 3955: 5 4 * 6 +
 3956: @end example
 3957: 
 3958: An important thing that you should notice about this notation is that
 3959: the @i{order} of the numbers does not change; if you want to subtract
 3960: 2 from 10 you type @code{10 2 -}.
 3961: 
 3962: The reason that Forth uses postfix notation is very simple to explain: it
 3963: makes the implementation extremely simple, and it follows naturally from
 3964: using the stack as a mechanism for passing parameters. Another way of
 3965: thinking about this is to realise that all Forth definitions are
 3966: @i{active}; they execute as they are encountered by the text
 3967: interpreter. The result of this is that the syntax of Forth is trivially
 3968: simple.
 3969: 
 3970: 
 3971: 
 3972: @comment ----------------------------------------------
 3973: @node Your first definition, How does that work?, Stacks and Postfix notation, Introduction
 3974: @section Your first Forth definition
 3975: @cindex first definition
 3976: 
 3977: Until now, the examples we've seen have been trivial; we've just been
 3978: using Forth as a bigger-than-pocket calculator. Also, each calculation
 3979: we've shown has been a ``one-off'' -- to repeat it we'd need to type it in
 3980: again@footnote{That's not quite true. If you press the up-arrow key on
 3981: your keyboard you should be able to scroll back to any earlier command,
 3982: edit it and re-enter it.} In this section we'll see how to add new
 3983: words to Forth's vocabulary.
 3984: 
 3985: The easiest way to create a new word is to use a @dfn{colon
 3986: definition}. We'll define a few and try them out before worrying too
 3987: much about how they work. Try typing in these examples; be careful to
 3988: copy the spaces accurately:
 3989: 
 3990: @example
 3991: : add-two 2 + . ;
 3992: : greet ." Hello and welcome" ;
 3993: : demo 5 add-two ;
 3994: @end example
 3995: 
 3996: @noindent
 3997: Now try them out:
 3998: 
 3999: @example
 4000: @kbd{greet@key{RET}} Hello and welcome  ok
 4001: @kbd{greet greet@key{RET}} Hello and welcomeHello and welcome  ok
 4002: @kbd{4 add-two@key{RET}} 6  ok
 4003: @kbd{demo@key{RET}} 7  ok
 4004: @kbd{9 greet demo add-two@key{RET}} Hello and welcome7 11  ok
 4005: @end example
 4006: 
 4007: The first new thing that we've introduced here is the pair of words
 4008: @code{:} and @code{;}. These are used to start and terminate a new
 4009: definition, respectively. The first word after the @code{:} is the name
 4010: for the new definition.
 4011: 
 4012: As you can see from the examples, a definition is built up of words that
 4013: have already been defined; Forth makes no distinction between
 4014: definitions that existed when you started the system up, and those that
 4015: you define yourself.
 4016: 
 4017: The examples also introduce the words @code{.} (dot), @code{."}
 4018: (dot-quote) and @code{dup} (dewp). Dot takes the value from the top of
 4019: the stack and displays it. It's like @code{.s} except that it only
 4020: displays the top item of the stack and it is destructive; after it has
 4021: executed, the number is no longer on the stack. There is always one
 4022: space printed after the number, and no spaces before it. Dot-quote
 4023: defines a string (a sequence of characters) that will be printed when
 4024: the word is executed. The string can contain any printable characters
 4025: except @code{"}. A @code{"} has a special function; it is not a Forth
 4026: word but it acts as a delimiter (the way that delimiters work is
 4027: described in the next section). Finally, @code{dup} duplicates the value
 4028: at the top of the stack. Try typing @code{5 dup .s} to see what it does.
 4029: 
 4030: We already know that the text interpreter searches through the
 4031: dictionary to locate names. If you've followed the examples earlier, you
 4032: will already have a definition called @code{add-two}. Lets try modifying
 4033: it by typing in a new definition:
 4034: 
 4035: @example
 4036: @kbd{: add-two dup . ." + 2 =" 2 + . ;@key{RET}} redefined add-two  ok
 4037: @end example
 4038: 
 4039: Forth recognised that we were defining a word that already exists, and
 4040: printed a message to warn us of that fact. Let's try out the new
 4041: definition:
 4042: 
 4043: @example
 4044: @kbd{9 add-two@key{RET}} 9 + 2 =11  ok
 4045: @end example
 4046: 
 4047: @noindent
 4048: All that we've actually done here, though, is to create a new
 4049: definition, with a particular name. The fact that there was already a
 4050: definition with the same name did not make any difference to the way
 4051: that the new definition was created (except that Forth printed a warning
 4052: message). The old definition of add-two still exists (try @code{demo}
 4053: again to see that this is true). Any new definition will use the new
 4054: definition of @code{add-two}, but old definitions continue to use the
 4055: version that already existed at the time that they were @code{compiled}.
 4056: 
 4057: Before you go on to the next section, try defining and redefining some
 4058: words of your own.
 4059: 
 4060: @comment ----------------------------------------------
 4061: @node How does that work?, Forth is written in Forth, Your first definition, Introduction
 4062: @section How does that work?
 4063: @cindex parsing words
 4064: 
 4065: @c That's pretty deep (IMO way too deep) for an introduction. - anton
 4066: 
 4067: @c Is it a good idea to talk about the interpretation semantics of a
 4068: @c number? We don't have an xt to go along with it. - anton
 4069: 
 4070: @c Now that I have eliminated execution semantics, I wonder if it would not
 4071: @c be better to keep them (or add run-time semantics), to make it easier to
 4072: @c explain what compilation semantics usually does. - anton
 4073: 
 4074: @c nac-> I removed the term ``default compilation sematics'' from the
 4075: @c introductory chapter. Removing ``execution semantics'' was making
 4076: @c everything simpler to explain, then I think the use of this term made
 4077: @c everything more complex again. I replaced it with ``default
 4078: @c semantics'' (which is used elsewhere in the manual) by which I mean
 4079: @c ``a definition that has neither the immediate nor the compile-only
 4080: @c flag set''.
 4081: 
 4082: @c anton: I have eliminated default semantics (except in one place where it
 4083: @c means "default interpretation and compilation semantics"), because it
 4084: @c makes no sense in the presence of combined words.  I reverted to
 4085: @c "execution semantics" where necessary.
 4086: 
 4087: @c nac-> I reworded big chunks of the ``how does that work''
 4088: @c section (and, unusually for me, I think I even made it shorter!).  See
 4089: @c what you think -- I know I have not addressed your primary concern
 4090: @c that it is too heavy-going for an introduction. From what I understood
 4091: @c of your course notes it looks as though they might be a good framework. 
 4092: @c Things that I've tried to capture here are some things that came as a
 4093: @c great revelation here when I first understood them. Also, I like the
 4094: @c fact that a very simple code example shows up almost all of the issues
 4095: @c that you need to understand to see how Forth works. That's unique and
 4096: @c worthwhile to emphasise.
 4097: 
 4098: @c anton: I think it's a good idea to present the details, especially those
 4099: @c that you found to be a revelation, and probably the tutorial tries to be
 4100: @c too superficial and does not get some of the things across that make
 4101: @c Forth special.  I do believe that most of the time these things should
 4102: @c be discussed at the end of a section or in separate sections instead of
 4103: @c in the middle of a section (e.g., the stuff you added in "User-defined
 4104: @c defining words" leads in a completely different direction from the rest
 4105: @c of the section).
 4106: 
 4107: Now we're going to take another look at the definition of @code{add-two}
 4108: from the previous section. From our knowledge of the way that the text
 4109: interpreter works, we would have expected this result when we tried to
 4110: define @code{add-two}:
 4111: 
 4112: @example
 4113: @kbd{: add-two 2 + . ;@key{RET}}
 4114:   ^^^^^^^
 4115: Error: Undefined word
 4116: @end example
 4117: 
 4118: The reason that this didn't happen is bound up in the way that @code{:}
 4119: works. The word @code{:} does two special things. The first special
 4120: thing that it does prevents the text interpreter from ever seeing the
 4121: characters @code{add-two}. The text interpreter uses a variable called
 4122: @cindex modifying >IN
 4123: @code{>IN} (pronounced ``to-in'') to keep track of where it is in the
 4124: input line. When it encounters the word @code{:} it behaves in exactly
 4125: the same way as it does for any other word; it looks it up in the name
 4126: dictionary, finds its xt and executes it. When @code{:} executes, it
 4127: looks at the input buffer, finds the word @code{add-two} and advances the
 4128: value of @code{>IN} to point past it. It then does some other stuff
 4129: associated with creating the new definition (including creating an entry
 4130: for @code{add-two} in the name dictionary). When the execution of @code{:}
 4131: completes, control returns to the text interpreter, which is oblivious
 4132: to the fact that it has been tricked into ignoring part of the input
 4133: line.
 4134: 
 4135: @cindex parsing words
 4136: Words like @code{:} -- words that advance the value of @code{>IN} and so
 4137: prevent the text interpreter from acting on the whole of the input line
 4138: -- are called @dfn{parsing words}.
 4139: 
 4140: @cindex @code{state} - effect on the text interpreter
 4141: @cindex text interpreter - effect of state
 4142: The second special thing that @code{:} does is change the value of a
 4143: variable called @code{state}, which affects the way that the text
 4144: interpreter behaves. When Gforth starts up, @code{state} has the value
 4145: 0, and the text interpreter is said to be @dfn{interpreting}. During a
 4146: colon definition (started with @code{:}), @code{state} is set to -1 and
 4147: the text interpreter is said to be @dfn{compiling}.
 4148: 
 4149: In this example, the text interpreter is compiling when it processes the
 4150: string ``@code{2 + . ;}''. It still breaks the string down into
 4151: character sequences in the same way. However, instead of pushing the
 4152: number @code{2} onto the stack, it lays down (@dfn{compiles}) some magic
 4153: into the definition of @code{add-two} that will make the number @code{2} get
 4154: pushed onto the stack when @code{add-two} is @dfn{executed}. Similarly,
 4155: the behaviours of @code{+} and @code{.} are also compiled into the
 4156: definition.
 4157: 
 4158: One category of words don't get compiled. These so-called @dfn{immediate
 4159: words} get executed (performed @i{now}) regardless of whether the text
 4160: interpreter is interpreting or compiling. The word @code{;} is an
 4161: immediate word. Rather than being compiled into the definition, it
 4162: executes. Its effect is to terminate the current definition, which
 4163: includes changing the value of @code{state} back to 0.
 4164: 
 4165: When you execute @code{add-two}, it has a @dfn{run-time effect} that is
 4166: exactly the same as if you had typed @code{2 + . @key{RET}} outside of a
 4167: definition.
 4168: 
 4169: In Forth, every word or number can be described in terms of two
 4170: properties:
 4171: 
 4172: @itemize @bullet
 4173: @item
 4174: @cindex interpretation semantics
 4175: Its @dfn{interpretation semantics} describe how it will behave when the
 4176: text interpreter encounters it in @dfn{interpret} state. The
 4177: interpretation semantics of a word are represented by an @dfn{execution
 4178: token}.
 4179: @item
 4180: @cindex compilation semantics
 4181: Its @dfn{compilation semantics} describe how it will behave when the
 4182: text interpreter encounters it in @dfn{compile} state. The compilation
 4183: semantics of a word are represented in an implementation-dependent way;
 4184: Gforth uses a @dfn{compilation token}.
 4185: @end itemize
 4186: 
 4187: @noindent
 4188: Numbers are always treated in a fixed way:
 4189: 
 4190: @itemize @bullet
 4191: @item
 4192: When the number is @dfn{interpreted}, its behaviour is to push the
 4193: number onto the stack.
 4194: @item
 4195: When the number is @dfn{compiled}, a piece of code is appended to the
 4196: current definition that pushes the number when it runs. (In other words,
 4197: the compilation semantics of a number are to postpone its interpretation
 4198: semantics until the run-time of the definition that it is being compiled
 4199: into.)
 4200: @end itemize
 4201: 
 4202: Words don't behave in such a regular way, but most have @i{default
 4203: semantics} which means that they behave like this:
 4204: 
 4205: @itemize @bullet
 4206: @item
 4207: The @dfn{interpretation semantics} of the word are to do something useful.
 4208: @item
 4209: The @dfn{compilation semantics} of the word are to append its
 4210: @dfn{interpretation semantics} to the current definition (so that its
 4211: run-time behaviour is to do something useful).
 4212: @end itemize
 4213: 
 4214: @cindex immediate words
 4215: The actual behaviour of any particular word can be controlled by using
 4216: the words @code{immediate} and @code{compile-only} when the word is
 4217: defined. These words set flags in the name dictionary entry of the most
 4218: recently defined word, and these flags are retrieved by the text
 4219: interpreter when it finds the word in the name dictionary.
 4220: 
 4221: A word that is marked as @dfn{immediate} has compilation semantics that
 4222: are identical to its interpretation semantics. In other words, it
 4223: behaves like this:
 4224: 
 4225: @itemize @bullet
 4226: @item
 4227: The @dfn{interpretation semantics} of the word are to do something useful.
 4228: @item
 4229: The @dfn{compilation semantics} of the word are to do something useful
 4230: (and actually the same thing); i.e., it is executed during compilation.
 4231: @end itemize
 4232: 
 4233: Marking a word as @dfn{compile-only} prohibits the text interpreter from
 4234: performing the interpretation semantics of the word directly; an attempt
 4235: to do so will generate an error. It is never necessary to use
 4236: @code{compile-only} (and it is not even part of ANS Forth, though it is
 4237: provided by many implementations) but it is good etiquette to apply it
 4238: to a word that will not behave correctly (and might have unexpected
 4239: side-effects) in interpret state. For example, it is only legal to use
 4240: the conditional word @code{IF} within a definition. If you forget this
 4241: and try to use it elsewhere, the fact that (in Gforth) it is marked as
 4242: @code{compile-only} allows the text interpreter to generate a helpful
 4243: error message rather than subjecting you to the consequences of your
 4244: folly.
 4245: 
 4246: This example shows the difference between an immediate and a
 4247: non-immediate word:
 4248: 
 4249: @example
 4250: : show-state state @@ . ;
 4251: : show-state-now show-state ; immediate
 4252: : word1 show-state ;
 4253: : word2 show-state-now ;
 4254: @end example
 4255: 
 4256: The word @code{immediate} after the definition of @code{show-state-now}
 4257: makes that word an immediate word. These definitions introduce a new
 4258: word: @code{@@} (pronounced ``fetch''). This word fetches the value of a
 4259: variable, and leaves it on the stack. Therefore, the behaviour of
 4260: @code{show-state} is to print a number that represents the current value
 4261: of @code{state}.
 4262: 
 4263: When you execute @code{word1}, it prints the number 0, indicating that
 4264: the system is interpreting. When the text interpreter compiled the
 4265: definition of @code{word1}, it encountered @code{show-state} whose
 4266: compilation semantics are to append its interpretation semantics to the
 4267: current definition. When you execute @code{word1}, it performs the
 4268: interpretation semantics of @code{show-state}.  At the time that @code{word1}
 4269: (and therefore @code{show-state}) are executed, the system is
 4270: interpreting.
 4271: 
 4272: When you pressed @key{RET} after entering the definition of @code{word2},
 4273: you should have seen the number -1 printed, followed by ``@code{
 4274: ok}''. When the text interpreter compiled the definition of
 4275: @code{word2}, it encountered @code{show-state-now}, an immediate word,
 4276: whose compilation semantics are therefore to perform its interpretation
 4277: semantics. It is executed straight away (even before the text
 4278: interpreter has moved on to process another group of characters; the
 4279: @code{;} in this example). The effect of executing it are to display the
 4280: value of @code{state} @i{at the time that the definition of}
 4281: @code{word2} @i{is being defined}. Printing -1 demonstrates that the
 4282: system is compiling at this time. If you execute @code{word2} it does
 4283: nothing at all.
 4284: 
 4285: @cindex @code{."}, how it works
 4286: Before leaving the subject of immediate words, consider the behaviour of
 4287: @code{."} in the definition of @code{greet}, in the previous
 4288: section. This word is both a parsing word and an immediate word. Notice
 4289: that there is a space between @code{."} and the start of the text
 4290: @code{Hello and welcome}, but that there is no space between the last
 4291: letter of @code{welcome} and the @code{"} character. The reason for this
 4292: is that @code{."} is a Forth word; it must have a space after it so that
 4293: the text interpreter can identify it. The @code{"} is not a Forth word;
 4294: it is a @dfn{delimiter}. The examples earlier show that, when the string
 4295: is displayed, there is neither a space before the @code{H} nor after the
 4296: @code{e}. Since @code{."} is an immediate word, it executes at the time
 4297: that @code{greet} is defined. When it executes, its behaviour is to
 4298: search forward in the input line looking for the delimiter. When it
 4299: finds the delimiter, it updates @code{>IN} to point past the
 4300: delimiter. It also compiles some magic code into the definition of
 4301: @code{greet}; the xt of a run-time routine that prints a text string. It
 4302: compiles the string @code{Hello and welcome} into memory so that it is
 4303: available to be printed later. When the text interpreter gains control,
 4304: the next word it finds in the input stream is @code{;} and so it
 4305: terminates the definition of @code{greet}.
 4306: 
 4307: 
 4308: @comment ----------------------------------------------
 4309: @node Forth is written in Forth, Review - elements of a Forth system, How does that work?, Introduction
 4310: @section Forth is written in Forth
 4311: @cindex structure of Forth programs
 4312: 
 4313: When you start up a Forth compiler, a large number of definitions
 4314: already exist. In Forth, you develop a new application using bottom-up
 4315: programming techniques to create new definitions that are defined in
 4316: terms of existing definitions. As you create each definition you can
 4317: test and debug it interactively.
 4318: 
 4319: If you have tried out the examples in this section, you will probably
 4320: have typed them in by hand; when you leave Gforth, your definitions will
 4321: be lost. You can avoid this by using a text editor to enter Forth source
 4322: code into a file, and then loading code from the file using
 4323: @code{include} (@pxref{Forth source files}). A Forth source file is
 4324: processed by the text interpreter, just as though you had typed it in by
 4325: hand@footnote{Actually, there are some subtle differences -- see
 4326: @ref{The Text Interpreter}.}.
 4327: 
 4328: Gforth also supports the traditional Forth alternative to using text
 4329: files for program entry (@pxref{Blocks}).
 4330: 
 4331: In common with many, if not most, Forth compilers, most of Gforth is
 4332: actually written in Forth. All of the @file{.fs} files in the
 4333: installation directory@footnote{For example,
 4334: @file{/usr/local/share/gforth...}} are Forth source files, which you can
 4335: study to see examples of Forth programming.
 4336: 
 4337: Gforth maintains a history file that records every line that you type to
 4338: the text interpreter. This file is preserved between sessions, and is
 4339: used to provide a command-line recall facility. If you enter long
 4340: definitions by hand, you can use a text editor to paste them out of the
 4341: history file into a Forth source file for reuse at a later time
 4342: (for more information @pxref{Command-line editing}).
 4343: 
 4344: 
 4345: @comment ----------------------------------------------
 4346: @node Review - elements of a Forth system, Where to go next, Forth is written in Forth, Introduction
 4347: @section Review - elements of a Forth system
 4348: @cindex elements of a Forth system
 4349: 
 4350: To summarise this chapter:
 4351: 
 4352: @itemize @bullet
 4353: @item
 4354: Forth programs use @dfn{factoring} to break a problem down into small
 4355: fragments called @dfn{words} or @dfn{definitions}.
 4356: @item
 4357: Forth program development is an interactive process.
 4358: @item
 4359: The main command loop that accepts input, and controls both
 4360: interpretation and compilation, is called the @dfn{text interpreter}
 4361: (also known as the @dfn{outer interpreter}).
 4362: @item
 4363: Forth has a very simple syntax, consisting of words and numbers
 4364: separated by spaces or carriage-return characters. Any additional syntax
 4365: is imposed by @dfn{parsing words}.
 4366: @item
 4367: Forth uses a stack to pass parameters between words. As a result, it
 4368: uses postfix notation.
 4369: @item
 4370: To use a word that has previously been defined, the text interpreter
 4371: searches for the word in the @dfn{name dictionary}.
 4372: @item
 4373: Words have @dfn{interpretation semantics} and @dfn{compilation semantics}.
 4374: @item
 4375: The text interpreter uses the value of @code{state} to select between
 4376: the use of the @dfn{interpretation semantics} and the  @dfn{compilation
 4377: semantics} of a word that it encounters.
 4378: @item
 4379: The relationship between the @dfn{interpretation semantics} and
 4380: @dfn{compilation semantics} for a word
 4381: depend upon the way in which the word was defined (for example, whether
 4382: it is an @dfn{immediate} word).
 4383: @item
 4384: Forth definitions can be implemented in Forth (called @dfn{high-level
 4385: definitions}) or in some other way (usually a lower-level language and
 4386: as a result often called @dfn{low-level definitions}, @dfn{code
 4387: definitions} or @dfn{primitives}).
 4388: @item
 4389: Many Forth systems are implemented mainly in Forth.
 4390: @end itemize
 4391: 
 4392: 
 4393: @comment ----------------------------------------------
 4394: @node Where to go next, Exercises, Review - elements of a Forth system, Introduction
 4395: @section Where To Go Next
 4396: @cindex where to go next
 4397: 
 4398: Amazing as it may seem, if you have read (and understood) this far, you
 4399: know almost all the fundamentals about the inner workings of a Forth
 4400: system. You certainly know enough to be able to read and understand the
 4401: rest of this manual and the ANS Forth document, to learn more about the
 4402: facilities that Forth in general and Gforth in particular provide. Even
 4403: scarier, you know almost enough to implement your own Forth system.
 4404: However, that's not a good idea just yet... better to try writing some
 4405: programs in Gforth.
 4406: 
 4407: Forth has such a rich vocabulary that it can be hard to know where to
 4408: start in learning it. This section suggests a few sets of words that are
 4409: enough to write small but useful programs. Use the word index in this
 4410: document to learn more about each word, then try it out and try to write
 4411: small definitions using it. Start by experimenting with these words:
 4412: 
 4413: @itemize @bullet
 4414: @item
 4415: Arithmetic: @code{+ - * / /MOD */ ABS INVERT}
 4416: @item
 4417: Comparison: @code{MIN MAX =}
 4418: @item
 4419: Logic: @code{AND OR XOR NOT}
 4420: @item
 4421: Stack manipulation: @code{DUP DROP SWAP OVER}
 4422: @item
 4423: Loops and decisions: @code{IF ELSE ENDIF ?DO I LOOP}
 4424: @item
 4425: Input/Output: @code{. ." EMIT CR KEY}
 4426: @item
 4427: Defining words: @code{: ; CREATE}
 4428: @item
 4429: Memory allocation words: @code{ALLOT ,}
 4430: @item
 4431: Tools: @code{SEE WORDS .S MARKER}
 4432: @end itemize
 4433: 
 4434: When you have mastered those, go on to:
 4435: 
 4436: @itemize @bullet
 4437: @item
 4438: More defining words: @code{VARIABLE CONSTANT VALUE TO CREATE DOES>}
 4439: @item
 4440: Memory access: @code{@@ !}
 4441: @end itemize
 4442: 
 4443: When you have mastered these, there's nothing for it but to read through
 4444: the whole of this manual and find out what you've missed.
 4445: 
 4446: @comment ----------------------------------------------
 4447: @node Exercises,  , Where to go next, Introduction
 4448: @section Exercises
 4449: @cindex exercises
 4450: 
 4451: TODO: provide a set of programming excercises linked into the stuff done
 4452: already and into other sections of the manual. Provide solutions to all
 4453: the exercises in a .fs file in the distribution.
 4454: 
 4455: @c Get some inspiration from Starting Forth and Kelly&Spies.
 4456: 
 4457: @c excercises:
 4458: @c 1. take inches and convert to feet and inches.
 4459: @c 2. take temperature and convert from fahrenheight to celcius;
 4460: @c    may need to care about symmetric vs floored??
 4461: @c 3. take input line and do character substitution
 4462: @c    to encipher or decipher
 4463: @c 4. as above but work on a file for in and out
 4464: @c 5. take input line and convert to pig-latin 
 4465: @c
 4466: @c thing of sets of things to exercise then come up with
 4467: @c problems that need those things.
 4468: 
 4469: 
 4470: @c ******************************************************************
 4471: @node Words, Error messages, Introduction, Top
 4472: @chapter Forth Words
 4473: @cindex words
 4474: 
 4475: @menu
 4476: * Notation::                    
 4477: * Case insensitivity::          
 4478: * Comments::                    
 4479: * Boolean Flags::               
 4480: * Arithmetic::                  
 4481: * Stack Manipulation::          
 4482: * Memory::                      
 4483: * Control Structures::          
 4484: * Defining Words::              
 4485: * Interpretation and Compilation Semantics::  
 4486: * Tokens for Words::            
 4487: * Compiling words::             
 4488: * The Text Interpreter::        
 4489: * Word Lists::                  
 4490: * Environmental Queries::       
 4491: * Files::                       
 4492: * Blocks::                      
 4493: * Other I/O::                   
 4494: * Locals::                      
 4495: * Structures::                  
 4496: * Object-oriented Forth::       
 4497: * Programming Tools::           
 4498: * Assembler and Code Words::    
 4499: * Threading Words::             
 4500: * Passing Commands to the OS::  
 4501: * Keeping track of Time::       
 4502: * Miscellaneous Words::         
 4503: @end menu
 4504: 
 4505: @node Notation, Case insensitivity, Words, Words
 4506: @section Notation
 4507: @cindex notation of glossary entries
 4508: @cindex format of glossary entries
 4509: @cindex glossary notation format
 4510: @cindex word glossary entry format
 4511: 
 4512: The Forth words are described in this section in the glossary notation
 4513: that has become a de-facto standard for Forth texts:
 4514: 
 4515: @format
 4516: @i{word}     @i{Stack effect}   @i{wordset}   @i{pronunciation}
 4517: @end format
 4518: @i{Description}
 4519: 
 4520: @table @var
 4521: @item word
 4522: The name of the word.
 4523: 
 4524: @item Stack effect
 4525: @cindex stack effect
 4526: The stack effect is written in the notation @code{@i{before} --
 4527: @i{after}}, where @i{before} and @i{after} describe the top of
 4528: stack entries before and after the execution of the word. The rest of
 4529: the stack is not touched by the word. The top of stack is rightmost,
 4530: i.e., a stack sequence is written as it is typed in. Note that Gforth
 4531: uses a separate floating point stack, but a unified stack
 4532: notation. Also, return stack effects are not shown in @i{stack
 4533: effect}, but in @i{Description}. The name of a stack item describes
 4534: the type and/or the function of the item. See below for a discussion of
 4535: the types.
 4536: 
 4537: All words have two stack effects: A compile-time stack effect and a
 4538: run-time stack effect. The compile-time stack-effect of most words is
 4539: @i{ -- }. If the compile-time stack-effect of a word deviates from
 4540: this standard behaviour, or the word does other unusual things at
 4541: compile time, both stack effects are shown; otherwise only the run-time
 4542: stack effect is shown.
 4543: 
 4544: @cindex pronounciation of words
 4545: @item pronunciation
 4546: How the word is pronounced.
 4547: 
 4548: @cindex wordset
 4549: @cindex environment wordset
 4550: @item wordset
 4551: The ANS Forth standard is divided into several word sets. A standard
 4552: system need not support all of them. Therefore, in theory, the fewer
 4553: word sets your program uses the more portable it will be. However, we
 4554: suspect that most ANS Forth systems on personal machines will feature
 4555: all word sets. Words that are not defined in ANS Forth have
 4556: @code{gforth} or @code{gforth-internal} as word set. @code{gforth}
 4557: describes words that will work in future releases of Gforth;
 4558: @code{gforth-internal} words are more volatile. Environmental query
 4559: strings are also displayed like words; you can recognize them by the
 4560: @code{environment} in the word set field.
 4561: 
 4562: @item Description
 4563: A description of the behaviour of the word.
 4564: @end table
 4565: 
 4566: @cindex types of stack items
 4567: @cindex stack item types
 4568: The type of a stack item is specified by the character(s) the name
 4569: starts with:
 4570: 
 4571: @table @code
 4572: @item f
 4573: @cindex @code{f}, stack item type
 4574: Boolean flags, i.e. @code{false} or @code{true}.
 4575: @item c
 4576: @cindex @code{c}, stack item type
 4577: Char
 4578: @item w
 4579: @cindex @code{w}, stack item type
 4580: Cell, can contain an integer or an address
 4581: @item n
 4582: @cindex @code{n}, stack item type
 4583: signed integer
 4584: @item u
 4585: @cindex @code{u}, stack item type
 4586: unsigned integer
 4587: @item d
 4588: @cindex @code{d}, stack item type
 4589: double sized signed integer
 4590: @item ud
 4591: @cindex @code{ud}, stack item type
 4592: double sized unsigned integer
 4593: @item r
 4594: @cindex @code{r}, stack item type
 4595: Float (on the FP stack)
 4596: @item a-
 4597: @cindex @code{a_}, stack item type
 4598: Cell-aligned address
 4599: @item c-
 4600: @cindex @code{c_}, stack item type
 4601: Char-aligned address (note that a Char may have two bytes in Windows NT)
 4602: @item f-
 4603: @cindex @code{f_}, stack item type
 4604: Float-aligned address
 4605: @item df-
 4606: @cindex @code{df_}, stack item type
 4607: Address aligned for IEEE double precision float
 4608: @item sf-
 4609: @cindex @code{sf_}, stack item type
 4610: Address aligned for IEEE single precision float
 4611: @item xt
 4612: @cindex @code{xt}, stack item type
 4613: Execution token, same size as Cell
 4614: @item wid
 4615: @cindex @code{wid}, stack item type
 4616: Word list ID, same size as Cell
 4617: @item ior, wior
 4618: @cindex ior type description
 4619: @cindex wior type description
 4620: I/O result code, cell-sized.  In Gforth, you can @code{throw} iors.
 4621: @item f83name
 4622: @cindex @code{f83name}, stack item type
 4623: Pointer to a name structure
 4624: @item "
 4625: @cindex @code{"}, stack item type
 4626: string in the input stream (not on the stack). The terminating character
 4627: is a blank by default. If it is not a blank, it is shown in @code{<>}
 4628: quotes.
 4629: @end table
 4630: 
 4631: @comment ----------------------------------------------
 4632: @node Case insensitivity, Comments, Notation, Words
 4633: @section Case insensitivity
 4634: @cindex case sensitivity
 4635: @cindex upper and lower case
 4636: 
 4637: Gforth is case-insensitive; you can enter definitions and invoke
 4638: Standard words using upper, lower or mixed case (however,
 4639: @pxref{core-idef, Implementation-defined options, Implementation-defined
 4640: options}).
 4641: 
 4642: ANS Forth only @i{requires} implementations to recognise Standard words
 4643: when they are typed entirely in upper case. Therefore, a Standard
 4644: program must use upper case for all Standard words. You can use whatever
 4645: case you like for words that you define, but in a Standard program you
 4646: have to use the words in the same case that you defined them.
 4647: 
 4648: Gforth supports case sensitivity through @code{table}s (case-sensitive
 4649: wordlists, @pxref{Word Lists}).
 4650: 
 4651: Two people have asked how to convert Gforth to be case-sensitive; while
 4652: we think this is a bad idea, you can change all wordlists into tables
 4653: like this:
 4654: 
 4655: @example
 4656: ' table-find forth-wordlist wordlist-map @ !
 4657: @end example
 4658: 
 4659: Note that you now have to type the predefined words in the same case
 4660: that we defined them, which are varying.  You may want to convert them
 4661: to your favourite case before doing this operation (I won't explain how,
 4662: because if you are even contemplating doing this, you'd better have
 4663: enough knowledge of Forth systems to know this already).
 4664: 
 4665: @node Comments, Boolean Flags, Case insensitivity, Words
 4666: @section Comments
 4667: @cindex comments
 4668: 
 4669: Forth supports two styles of comment; the traditional @i{in-line} comment,
 4670: @code{(} and its modern cousin, the @i{comment to end of line}; @code{\}.
 4671: 
 4672: 
 4673: doc-(
 4674: doc-\
 4675: doc-\G
 4676: 
 4677: 
 4678: @node Boolean Flags, Arithmetic, Comments, Words
 4679: @section Boolean Flags
 4680: @cindex Boolean flags
 4681: 
 4682: A Boolean flag is cell-sized. A cell with all bits clear represents the
 4683: flag @code{false} and a flag with all bits set represents the flag
 4684: @code{true}. Words that check a flag (for example, @code{IF}) will treat
 4685: a cell that has @i{any} bit set as @code{true}.
 4686: @c on and off to Memory? 
 4687: @c true and false to "Bitwise operations" or "Numeric comparison"?
 4688: 
 4689: doc-true
 4690: doc-false
 4691: doc-on
 4692: doc-off
 4693: 
 4694: 
 4695: @node Arithmetic, Stack Manipulation, Boolean Flags, Words
 4696: @section Arithmetic
 4697: @cindex arithmetic words
 4698: 
 4699: @cindex division with potentially negative operands
 4700: Forth arithmetic is not checked, i.e., you will not hear about integer
 4701: overflow on addition or multiplication, you may hear about division by
 4702: zero if you are lucky. The operator is written after the operands, but
 4703: the operands are still in the original order. I.e., the infix @code{2-1}
 4704: corresponds to @code{2 1 -}. Forth offers a variety of division
 4705: operators. If you perform division with potentially negative operands,
 4706: you do not want to use @code{/} or @code{/mod} with its undefined
 4707: behaviour, but rather @code{fm/mod} or @code{sm/mod} (probably the
 4708: former, @pxref{Mixed precision}).
 4709: @comment TODO discuss the different division forms and the std approach
 4710: 
 4711: @menu
 4712: * Single precision::            
 4713: * Double precision::            Double-cell integer arithmetic
 4714: * Bitwise operations::          
 4715: * Numeric comparison::          
 4716: * Mixed precision::             Operations with single and double-cell integers
 4717: * Floating Point::              
 4718: @end menu
 4719: 
 4720: @node Single precision, Double precision, Arithmetic, Arithmetic
 4721: @subsection Single precision
 4722: @cindex single precision arithmetic words
 4723: 
 4724: @c !! cell undefined
 4725: 
 4726: By default, numbers in Forth are single-precision integers that are one
 4727: cell in size. They can be signed or unsigned, depending upon how you
 4728: treat them. For the rules used by the text interpreter for recognising
 4729: single-precision integers see @ref{Number Conversion}.
 4730: 
 4731: These words are all defined for signed operands, but some of them also
 4732: work for unsigned numbers: @code{+}, @code{1+}, @code{-}, @code{1-},
 4733: @code{*}.
 4734: 
 4735: doc-+
 4736: doc-1+
 4737: doc--
 4738: doc-1-
 4739: doc-*
 4740: doc-/
 4741: doc-mod
 4742: doc-/mod
 4743: doc-negate
 4744: doc-abs
 4745: doc-min
 4746: doc-max
 4747: doc-floored
 4748: 
 4749: 
 4750: @node Double precision, Bitwise operations, Single precision, Arithmetic
 4751: @subsection Double precision
 4752: @cindex double precision arithmetic words
 4753: 
 4754: For the rules used by the text interpreter for
 4755: recognising double-precision integers, see @ref{Number Conversion}.
 4756: 
 4757: A double precision number is represented by a cell pair, with the most
 4758: significant cell at the TOS. It is trivial to convert an unsigned single
 4759: to a double: simply push a @code{0} onto the TOS. Since numbers are
 4760: represented by Gforth using 2's complement arithmetic, converting a
 4761: signed single to a (signed) double requires sign-extension across the
 4762: most significant cell. This can be achieved using @code{s>d}. The moral
 4763: of the story is that you cannot convert a number without knowing whether
 4764: it represents an unsigned or a signed number.
 4765: 
 4766: These words are all defined for signed operands, but some of them also
 4767: work for unsigned numbers: @code{d+}, @code{d-}.
 4768: 
 4769: doc-s>d
 4770: doc-d>s
 4771: doc-d+
 4772: doc-d-
 4773: doc-dnegate
 4774: doc-dabs
 4775: doc-dmin
 4776: doc-dmax
 4777: 
 4778: 
 4779: @node Bitwise operations, Numeric comparison, Double precision, Arithmetic
 4780: @subsection Bitwise operations
 4781: @cindex bitwise operation words
 4782: 
 4783: 
 4784: doc-and
 4785: doc-or
 4786: doc-xor
 4787: doc-invert
 4788: doc-lshift
 4789: doc-rshift
 4790: doc-2*
 4791: doc-d2*
 4792: doc-2/
 4793: doc-d2/
 4794: 
 4795: 
 4796: @node Numeric comparison, Mixed precision, Bitwise operations, Arithmetic
 4797: @subsection Numeric comparison
 4798: @cindex numeric comparison words
 4799: 
 4800: Note that the words that compare for equality (@code{= <> 0= 0<> d= d<>
 4801: d0= d0<>}) work for for both signed and unsigned numbers.
 4802: 
 4803: doc-<
 4804: doc-<=
 4805: doc-<>
 4806: doc-=
 4807: doc->
 4808: doc->=
 4809: 
 4810: doc-0<
 4811: doc-0<=
 4812: doc-0<>
 4813: doc-0=
 4814: doc-0>
 4815: doc-0>=
 4816: 
 4817: doc-u<
 4818: doc-u<=
 4819: @c u<> and u= exist but are the same as <> and =
 4820: @c doc-u<>
 4821: @c doc-u=
 4822: doc-u>
 4823: doc-u>=
 4824: 
 4825: doc-within
 4826: 
 4827: doc-d<
 4828: doc-d<=
 4829: doc-d<>
 4830: doc-d=
 4831: doc-d>
 4832: doc-d>=
 4833: 
 4834: doc-d0<
 4835: doc-d0<=
 4836: doc-d0<>
 4837: doc-d0=
 4838: doc-d0>
 4839: doc-d0>=
 4840: 
 4841: doc-du<
 4842: doc-du<=
 4843: @c du<> and du= exist but are the same as d<> and d=
 4844: @c doc-du<>
 4845: @c doc-du=
 4846: doc-du>
 4847: doc-du>=
 4848: 
 4849: 
 4850: @node Mixed precision, Floating Point, Numeric comparison, Arithmetic
 4851: @subsection Mixed precision
 4852: @cindex mixed precision arithmetic words
 4853: 
 4854: 
 4855: doc-m+
 4856: doc-*/
 4857: doc-*/mod
 4858: doc-m*
 4859: doc-um*
 4860: doc-m*/
 4861: doc-um/mod
 4862: doc-fm/mod
 4863: doc-sm/rem
 4864: 
 4865: 
 4866: @node Floating Point,  , Mixed precision, Arithmetic
 4867: @subsection Floating Point
 4868: @cindex floating point arithmetic words
 4869: 
 4870: For the rules used by the text interpreter for
 4871: recognising floating-point numbers see @ref{Number Conversion}.
 4872: 
 4873: Gforth has a separate floating point stack, but the documentation uses
 4874: the unified notation.@footnote{It's easy to generate the separate
 4875: notation from that by just separating the floating-point numbers out:
 4876: e.g. @code{( n r1 u r2 -- r3 )} becomes @code{( n u -- ) ( F: r1 r2 --
 4877: r3 )}.}
 4878: 
 4879: @cindex floating-point arithmetic, pitfalls
 4880: Floating point numbers have a number of unpleasant surprises for the
 4881: unwary (e.g., floating point addition is not associative) and even a few
 4882: for the wary. You should not use them unless you know what you are doing
 4883: or you don't care that the results you get are totally bogus. If you
 4884: want to learn about the problems of floating point numbers (and how to
 4885: avoid them), you might start with @cite{David Goldberg,
 4886: @uref{http://www.validgh.com/goldberg/paper.ps,What Every Computer
 4887: Scientist Should Know About Floating-Point Arithmetic}, ACM Computing
 4888: Surveys 23(1):5@minus{}48, March 1991}.
 4889: 
 4890: 
 4891: doc-d>f
 4892: doc-f>d
 4893: doc-f+
 4894: doc-f-
 4895: doc-f*
 4896: doc-f/
 4897: doc-fnegate
 4898: doc-fabs
 4899: doc-fmax
 4900: doc-fmin
 4901: doc-floor
 4902: doc-fround
 4903: doc-f**
 4904: doc-fsqrt
 4905: doc-fexp
 4906: doc-fexpm1
 4907: doc-fln
 4908: doc-flnp1
 4909: doc-flog
 4910: doc-falog
 4911: doc-f2*
 4912: doc-f2/
 4913: doc-1/f
 4914: doc-precision
 4915: doc-set-precision
 4916: 
 4917: @cindex angles in trigonometric operations
 4918: @cindex trigonometric operations
 4919: Angles in floating point operations are given in radians (a full circle
 4920: has 2 pi radians).
 4921: 
 4922: doc-fsin
 4923: doc-fcos
 4924: doc-fsincos
 4925: doc-ftan
 4926: doc-fasin
 4927: doc-facos
 4928: doc-fatan
 4929: doc-fatan2
 4930: doc-fsinh
 4931: doc-fcosh
 4932: doc-ftanh
 4933: doc-fasinh
 4934: doc-facosh
 4935: doc-fatanh
 4936: doc-pi
 4937: 
 4938: @cindex equality of floats
 4939: @cindex floating-point comparisons
 4940: One particular problem with floating-point arithmetic is that comparison
 4941: for equality often fails when you would expect it to succeed.  For this
 4942: reason approximate equality is often preferred (but you still have to
 4943: know what you are doing).  Also note that IEEE NaNs may compare
 4944: differently from what you might expect.  The comparison words are:
 4945: 
 4946: doc-f~rel
 4947: doc-f~abs
 4948: doc-f~
 4949: doc-f=
 4950: doc-f<>
 4951: 
 4952: doc-f<
 4953: doc-f<=
 4954: doc-f>
 4955: doc-f>=
 4956: 
 4957: doc-f0<
 4958: doc-f0<=
 4959: doc-f0<>
 4960: doc-f0=
 4961: doc-f0>
 4962: doc-f0>=
 4963: 
 4964: 
 4965: @node Stack Manipulation, Memory, Arithmetic, Words
 4966: @section Stack Manipulation
 4967: @cindex stack manipulation words
 4968: 
 4969: @cindex floating-point stack in the standard
 4970: Gforth maintains a number of separate stacks:
 4971: 
 4972: @cindex data stack
 4973: @cindex parameter stack
 4974: @itemize @bullet
 4975: @item
 4976: A data stack (also known as the @dfn{parameter stack}) -- for
 4977: characters, cells, addresses, and double cells.
 4978: 
 4979: @cindex floating-point stack
 4980: @item
 4981: A floating point stack -- for holding floating point (FP) numbers.
 4982: 
 4983: @cindex return stack
 4984: @item
 4985: A return stack -- for holding the return addresses of colon
 4986: definitions and other (non-FP) data.
 4987: 
 4988: @cindex locals stack
 4989: @item
 4990: A locals stack -- for holding local variables.
 4991: @end itemize
 4992: 
 4993: @menu
 4994: * Data stack::                  
 4995: * Floating point stack::        
 4996: * Return stack::                
 4997: * Locals stack::                
 4998: * Stack pointer manipulation::  
 4999: @end menu
 5000: 
 5001: @node Data stack, Floating point stack, Stack Manipulation, Stack Manipulation
 5002: @subsection Data stack
 5003: @cindex data stack manipulation words
 5004: @cindex stack manipulations words, data stack
 5005: 
 5006: 
 5007: doc-drop
 5008: doc-nip
 5009: doc-dup
 5010: doc-over
 5011: doc-tuck
 5012: doc-swap
 5013: doc-pick
 5014: doc-rot
 5015: doc--rot
 5016: doc-?dup
 5017: doc-roll
 5018: doc-2drop
 5019: doc-2nip
 5020: doc-2dup
 5021: doc-2over
 5022: doc-2tuck
 5023: doc-2swap
 5024: doc-2rot
 5025: 
 5026: 
 5027: @node Floating point stack, Return stack, Data stack, Stack Manipulation
 5028: @subsection Floating point stack
 5029: @cindex floating-point stack manipulation words
 5030: @cindex stack manipulation words, floating-point stack
 5031: 
 5032: Whilst every sane Forth has a separate floating-point stack, it is not
 5033: strictly required; an ANS Forth system could theoretically keep
 5034: floating-point numbers on the data stack. As an additional difficulty,
 5035: you don't know how many cells a floating-point number takes. It is
 5036: reportedly possible to write words in a way that they work also for a
 5037: unified stack model, but we do not recommend trying it. Instead, just
 5038: say that your program has an environmental dependency on a separate
 5039: floating-point stack.
 5040: 
 5041: doc-floating-stack
 5042: 
 5043: doc-fdrop
 5044: doc-fnip
 5045: doc-fdup
 5046: doc-fover
 5047: doc-ftuck
 5048: doc-fswap
 5049: doc-fpick
 5050: doc-frot
 5051: 
 5052: 
 5053: @node Return stack, Locals stack, Floating point stack, Stack Manipulation
 5054: @subsection Return stack
 5055: @cindex return stack manipulation words
 5056: @cindex stack manipulation words, return stack
 5057: 
 5058: @cindex return stack and locals
 5059: @cindex locals and return stack
 5060: A Forth system is allowed to keep local variables on the
 5061: return stack. This is reasonable, as local variables usually eliminate
 5062: the need to use the return stack explicitly. So, if you want to produce
 5063: a standard compliant program and you are using local variables in a
 5064: word, forget about return stack manipulations in that word (refer to the
 5065: standard document for the exact rules).
 5066: 
 5067: doc->r
 5068: doc-r>
 5069: doc-r@
 5070: doc-rdrop
 5071: doc-2>r
 5072: doc-2r>
 5073: doc-2r@
 5074: doc-2rdrop
 5075: 
 5076: 
 5077: @node Locals stack, Stack pointer manipulation, Return stack, Stack Manipulation
 5078: @subsection Locals stack
 5079: 
 5080: Gforth uses an extra locals stack.  It is described, along with the
 5081: reasons for its existence, in @ref{Locals implementation}.
 5082: 
 5083: @node Stack pointer manipulation,  , Locals stack, Stack Manipulation
 5084: @subsection Stack pointer manipulation
 5085: @cindex stack pointer manipulation words
 5086: 
 5087: @c removed s0 r0 l0 -- they are obsolete aliases for sp0 rp0 lp0
 5088: doc-sp0
 5089: doc-sp@
 5090: doc-sp!
 5091: doc-fp0
 5092: doc-fp@
 5093: doc-fp!
 5094: doc-rp0
 5095: doc-rp@
 5096: doc-rp!
 5097: doc-lp0
 5098: doc-lp@
 5099: doc-lp!
 5100: 
 5101: 
 5102: @node Memory, Control Structures, Stack Manipulation, Words
 5103: @section Memory
 5104: @cindex memory words
 5105: 
 5106: @menu
 5107: * Memory model::                
 5108: * Dictionary allocation::       
 5109: * Heap Allocation::             
 5110: * Memory Access::               
 5111: * Address arithmetic::          
 5112: * Memory Blocks::               
 5113: @end menu
 5114: 
 5115: In addition to the standard Forth memory allocation words, there is also
 5116: a @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
 5117: garbage collector}.
 5118: 
 5119: @node Memory model, Dictionary allocation, Memory, Memory
 5120: @subsection ANS Forth and Gforth memory models
 5121: 
 5122: @c The ANS Forth description is a mess (e.g., is the heap part of
 5123: @c the dictionary?), so let's not stick to closely with it.
 5124: 
 5125: ANS Forth considers a Forth system as consisting of several address
 5126: spaces, of which only @dfn{data space} is managed and accessible with
 5127: the memory words.  Memory not necessarily in data space includes the
 5128: stacks, the code (called code space) and the headers (called name
 5129: space). In Gforth everything is in data space, but the code for the
 5130: primitives is usually read-only.
 5131: 
 5132: Data space is divided into a number of areas: The (data space portion of
 5133: the) dictionary@footnote{Sometimes, the term @dfn{dictionary} is used to
 5134: refer to the search data structure embodied in word lists and headers,
 5135: because it is used for looking up names, just as you would in a
 5136: conventional dictionary.}, the heap, and a number of system-allocated
 5137: buffers.
 5138: 
 5139: @cindex address arithmetic restrictions, ANS vs. Gforth
 5140: @cindex contiguous regions, ANS vs. Gforth
 5141: In ANS Forth data space is also divided into contiguous regions.  You
 5142: can only use address arithmetic within a contiguous region, not between
 5143: them.  Usually each allocation gives you one contiguous region, but the
 5144: dictionary allocation words have additional rules (@pxref{Dictionary
 5145: allocation}).
 5146: 
 5147: Gforth provides one big address space, and address arithmetic can be
 5148: performed between any addresses. However, in the dictionary headers or
 5149: code are interleaved with data, so almost the only contiguous data space
 5150: regions there are those described by ANS Forth as contiguous; but you
 5151: can be sure that the dictionary is allocated towards increasing
 5152: addresses even between contiguous regions.  The memory order of
 5153: allocations in the heap is platform-dependent (and possibly different
 5154: from one run to the next).
 5155: 
 5156: 
 5157: @node Dictionary allocation, Heap Allocation, Memory model, Memory
 5158: @subsection Dictionary allocation
 5159: @cindex reserving data space
 5160: @cindex data space - reserving some
 5161: 
 5162: Dictionary allocation is a stack-oriented allocation scheme, i.e., if
 5163: you want to deallocate X, you also deallocate everything
 5164: allocated after X.
 5165: 
 5166: @cindex contiguous regions in dictionary allocation
 5167: The allocations using the words below are contiguous and grow the region
 5168: towards increasing addresses.  Other words that allocate dictionary
 5169: memory of any kind (i.e., defining words including @code{:noname}) end
 5170: the contiguous region and start a new one.
 5171: 
 5172: In ANS Forth only @code{create}d words are guaranteed to produce an
 5173: address that is the start of the following contiguous region.  In
 5174: particular, the cell allocated by @code{variable} is not guaranteed to
 5175: be contiguous with following @code{allot}ed memory.
 5176: 
 5177: You can deallocate memory by using @code{allot} with a negative argument
 5178: (with some restrictions, see @code{allot}). For larger deallocations use
 5179: @code{marker}.
 5180: 
 5181: 
 5182: doc-here
 5183: doc-unused
 5184: doc-allot
 5185: doc-c,
 5186: doc-f,
 5187: doc-,
 5188: doc-2,
 5189: 
 5190: Memory accesses have to be aligned (@pxref{Address arithmetic}). So of
 5191: course you should allocate memory in an aligned way, too. I.e., before
 5192: allocating allocating a cell, @code{here} must be cell-aligned, etc.
 5193: The words below align @code{here} if it is not already.  Basically it is
 5194: only already aligned for a type, if the last allocation was a multiple
 5195: of the size of this type and if @code{here} was aligned for this type
 5196: before.
 5197: 
 5198: After freshly @code{create}ing a word, @code{here} is @code{align}ed in
 5199: ANS Forth (@code{maxalign}ed in Gforth).
 5200: 
 5201: doc-align
 5202: doc-falign
 5203: doc-sfalign
 5204: doc-dfalign
 5205: doc-maxalign
 5206: doc-cfalign
 5207: 
 5208: 
 5209: @node Heap Allocation, Memory Access, Dictionary allocation, Memory
 5210: @subsection Heap allocation
 5211: @cindex heap allocation
 5212: @cindex dynamic allocation of memory
 5213: @cindex memory-allocation word set
 5214: 
 5215: @cindex contiguous regions and heap allocation
 5216: Heap allocation supports deallocation of allocated memory in any
 5217: order. Dictionary allocation is not affected by it (i.e., it does not
 5218: end a contiguous region). In Gforth, these words are implemented using
 5219: the standard C library calls malloc(), free() and resize().
 5220: 
 5221: The memory region produced by one invocation of @code{allocate} or
 5222: @code{resize} is internally contiguous.  There is no contiguity between
 5223: such a region and any other region (including others allocated from the
 5224: heap).
 5225: 
 5226: doc-allocate
 5227: doc-free
 5228: doc-resize
 5229: 
 5230: 
 5231: @node Memory Access, Address arithmetic, Heap Allocation, Memory
 5232: @subsection Memory Access
 5233: @cindex memory access words
 5234: 
 5235: doc-@
 5236: doc-!
 5237: doc-+!
 5238: doc-c@
 5239: doc-c!
 5240: doc-2@
 5241: doc-2!
 5242: doc-f@
 5243: doc-f!
 5244: doc-sf@
 5245: doc-sf!
 5246: doc-df@
 5247: doc-df!
 5248: 
 5249: 
 5250: @node Address arithmetic, Memory Blocks, Memory Access, Memory
 5251: @subsection Address arithmetic
 5252: @cindex address arithmetic words
 5253: 
 5254: Address arithmetic is the foundation on which you can build data
 5255: structures like arrays, records (@pxref{Structures}) and objects
 5256: (@pxref{Object-oriented Forth}).
 5257: 
 5258: @cindex address unit
 5259: @cindex au (address unit)
 5260: ANS Forth does not specify the sizes of the data types. Instead, it
 5261: offers a number of words for computing sizes and doing address
 5262: arithmetic. Address arithmetic is performed in terms of address units
 5263: (aus); on most systems the address unit is one byte. Note that a
 5264: character may have more than one au, so @code{chars} is no noop (on
 5265: platforms where it is a noop, it compiles to nothing).
 5266: 
 5267: The basic address arithmetic words are @code{+} and @code{-}.  E.g., if
 5268: you have the address of a cell, perform @code{1 cells +}, and you will
 5269: have the address of the next cell.
 5270: 
 5271: @cindex contiguous regions and address arithmetic
 5272: In ANS Forth you can perform address arithmetic only within a contiguous
 5273: region, i.e., if you have an address into one region, you can only add
 5274: and subtract such that the result is still within the region; you can
 5275: only subtract or compare addresses from within the same contiguous
 5276: region.  Reasons: several contiguous regions can be arranged in memory
 5277: in any way; on segmented systems addresses may have unusual
 5278: representations, such that address arithmetic only works within a
 5279: region.  Gforth provides a few more guarantees (linear address space,
 5280: dictionary grows upwards), but in general I have found it easy to stay
 5281: within contiguous regions (exception: computing and comparing to the
 5282: address just beyond the end of an array).
 5283: 
 5284: @cindex alignment of addresses for types
 5285: ANS Forth also defines words for aligning addresses for specific
 5286: types. Many computers require that accesses to specific data types
 5287: must only occur at specific addresses; e.g., that cells may only be
 5288: accessed at addresses divisible by 4. Even if a machine allows unaligned
 5289: accesses, it can usually perform aligned accesses faster. 
 5290: 
 5291: For the performance-conscious: alignment operations are usually only
 5292: necessary during the definition of a data structure, not during the
 5293: (more frequent) accesses to it.
 5294: 
 5295: ANS Forth defines no words for character-aligning addresses. This is not
 5296: an oversight, but reflects the fact that addresses that are not
 5297: char-aligned have no use in the standard and therefore will not be
 5298: created.
 5299: 
 5300: @cindex @code{CREATE} and alignment
 5301: ANS Forth guarantees that addresses returned by @code{CREATE}d words
 5302: are cell-aligned; in addition, Gforth guarantees that these addresses
 5303: are aligned for all purposes.
 5304: 
 5305: Note that the ANS Forth word @code{char} has nothing to do with address
 5306: arithmetic.
 5307: 
 5308: 
 5309: doc-chars
 5310: doc-char+
 5311: doc-cells
 5312: doc-cell+
 5313: doc-cell
 5314: doc-aligned
 5315: doc-floats
 5316: doc-float+
 5317: doc-float
 5318: doc-faligned
 5319: doc-sfloats
 5320: doc-sfloat+
 5321: doc-sfaligned
 5322: doc-dfloats
 5323: doc-dfloat+
 5324: doc-dfaligned
 5325: doc-maxaligned
 5326: doc-cfaligned
 5327: doc-address-unit-bits
 5328: 
 5329: 
 5330: @node Memory Blocks,  , Address arithmetic, Memory
 5331: @subsection Memory Blocks
 5332: @cindex memory block words
 5333: @cindex character strings - moving and copying
 5334: 
 5335: Memory blocks often represent character strings; For ways of storing
 5336: character strings in memory see @ref{String Formats}.  For other
 5337: string-processing words see @ref{Displaying characters and strings}.
 5338: 
 5339: A few of these words work on address unit blocks.  In that case, you
 5340: usually have to insert @code{CHARS} before the word when working on
 5341: character strings.  Most words work on character blocks, and expect a
 5342: char-aligned address.
 5343: 
 5344: When copying characters between overlapping memory regions, use
 5345: @code{chars move} or choose carefully between @code{cmove} and
 5346: @code{cmove>}.
 5347: 
 5348: doc-move
 5349: doc-erase
 5350: doc-cmove
 5351: doc-cmove>
 5352: doc-fill
 5353: doc-blank
 5354: doc-compare
 5355: doc-search
 5356: doc--trailing
 5357: doc-/string
 5358: doc-bounds
 5359: 
 5360: @comment TODO examples
 5361: 
 5362: 
 5363: @node Control Structures, Defining Words, Memory, Words
 5364: @section Control Structures
 5365: @cindex control structures
 5366: 
 5367: Control structures in Forth cannot be used interpretively, only in a
 5368: colon definition@footnote{To be precise, they have no interpretation
 5369: semantics (@pxref{Interpretation and Compilation Semantics}).}. We do
 5370: not like this limitation, but have not seen a satisfying way around it
 5371: yet, although many schemes have been proposed.
 5372: 
 5373: @menu
 5374: * Selection::                   IF ... ELSE ... ENDIF
 5375: * Simple Loops::                BEGIN ...
 5376: * Counted Loops::               DO
 5377: * Arbitrary control structures::  
 5378: * Calls and returns::           
 5379: * Exception Handling::          
 5380: @end menu
 5381: 
 5382: @node Selection, Simple Loops, Control Structures, Control Structures
 5383: @subsection Selection
 5384: @cindex selection control structures
 5385: @cindex control structures for selection
 5386: 
 5387: @cindex @code{IF} control structure
 5388: @example
 5389: @i{flag}
 5390: IF
 5391:   @i{code}
 5392: ENDIF
 5393: @end example
 5394: @noindent
 5395: 
 5396: If @i{flag} is non-zero (as far as @code{IF} etc. are concerned, a cell
 5397: with any bit set represents truth) @i{code} is executed.
 5398: 
 5399: @example
 5400: @i{flag}
 5401: IF
 5402:   @i{code1}
 5403: ELSE
 5404:   @i{code2}
 5405: ENDIF
 5406: @end example
 5407: 
 5408: If @var{flag} is true, @i{code1} is executed, otherwise @i{code2} is
 5409: executed.
 5410: 
 5411: You can use @code{THEN} instead of @code{ENDIF}. Indeed, @code{THEN} is
 5412: standard, and @code{ENDIF} is not, although it is quite popular. We
 5413: recommend using @code{ENDIF}, because it is less confusing for people
 5414: who also know other languages (and is not prone to reinforcing negative
 5415: prejudices against Forth in these people). Adding @code{ENDIF} to a
 5416: system that only supplies @code{THEN} is simple:
 5417: @example
 5418: : ENDIF   POSTPONE then ; immediate
 5419: @end example
 5420: 
 5421: [According to @cite{Webster's New Encyclopedic Dictionary}, @dfn{then
 5422: (adv.)}  has the following meanings:
 5423: @quotation
 5424: ... 2b: following next after in order ... 3d: as a necessary consequence
 5425: (if you were there, then you saw them).
 5426: @end quotation
 5427: Forth's @code{THEN} has the meaning 2b, whereas @code{THEN} in Pascal
 5428: and many other programming languages has the meaning 3d.]
 5429: 
 5430: Gforth also provides the words @code{?DUP-IF} and @code{?DUP-0=-IF}, so
 5431: you can avoid using @code{?dup}. Using these alternatives is also more
 5432: efficient than using @code{?dup}. Definitions in ANS Forth
 5433: for @code{ENDIF}, @code{?DUP-IF} and @code{?DUP-0=-IF} are provided in
 5434: @file{compat/control.fs}.
 5435: 
 5436: @cindex @code{CASE} control structure
 5437: @example
 5438: @i{n}
 5439: CASE
 5440:   @i{n1} OF @i{code1} ENDOF
 5441:   @i{n2} OF @i{code2} ENDOF
 5442:   @dots{}
 5443:   ( n ) @i{default-code} ( n )
 5444: ENDCASE
 5445: @end example
 5446: 
 5447: Executes the first @i{codei}, where the @i{ni} is equal to @i{n}.  If no
 5448: @i{ni} matches, the optional @i{default-code} is executed. The optional
 5449: default case can be added by simply writing the code after the last
 5450: @code{ENDOF}. It may use @i{n}, which is on top of the stack, but must
 5451: not consume it.
 5452: 
 5453: @progstyle
 5454: To keep the code understandable, you should ensure that on all paths
 5455: through a selection construct the stack is changed in the same way
 5456: (wrt. number and types of stack items consumed and pushed).
 5457: 
 5458: @node Simple Loops, Counted Loops, Selection, Control Structures
 5459: @subsection Simple Loops
 5460: @cindex simple loops
 5461: @cindex loops without count 
 5462: 
 5463: @cindex @code{WHILE} loop
 5464: @example
 5465: BEGIN
 5466:   @i{code1}
 5467:   @i{flag}
 5468: WHILE
 5469:   @i{code2}
 5470: REPEAT
 5471: @end example
 5472: 
 5473: @i{code1} is executed and @i{flag} is computed. If it is true,
 5474: @i{code2} is executed and the loop is restarted; If @i{flag} is
 5475: false, execution continues after the @code{REPEAT}.
 5476: 
 5477: @cindex @code{UNTIL} loop
 5478: @example
 5479: BEGIN
 5480:   @i{code}
 5481:   @i{flag}
 5482: UNTIL
 5483: @end example
 5484: 
 5485: @i{code} is executed. The loop is restarted if @code{flag} is false.
 5486: 
 5487: @progstyle
 5488: To keep the code understandable, a complete iteration of the loop should
 5489: not change the number and types of the items on the stacks.
 5490: 
 5491: @cindex endless loop
 5492: @cindex loops, endless
 5493: @example
 5494: BEGIN
 5495:   @i{code}
 5496: AGAIN
 5497: @end example
 5498: 
 5499: This is an endless loop.
 5500: 
 5501: @node Counted Loops, Arbitrary control structures, Simple Loops, Control Structures
 5502: @subsection Counted Loops
 5503: @cindex counted loops
 5504: @cindex loops, counted
 5505: @cindex @code{DO} loops
 5506: 
 5507: The basic counted loop is:
 5508: @example
 5509: @i{limit} @i{start}
 5510: ?DO
 5511:   @i{body}
 5512: LOOP
 5513: @end example
 5514: 
 5515: This performs one iteration for every integer, starting from @i{start}
 5516: and up to, but excluding @i{limit}. The counter, or @i{index}, can be
 5517: accessed with @code{i}. For example, the loop:
 5518: @example
 5519: 10 0 ?DO
 5520:   i .
 5521: LOOP
 5522: @end example
 5523: @noindent
 5524: prints @code{0 1 2 3 4 5 6 7 8 9}
 5525: 
 5526: The index of the innermost loop can be accessed with @code{i}, the index
 5527: of the next loop with @code{j}, and the index of the third loop with
 5528: @code{k}.
 5529: 
 5530: 
 5531: doc-i
 5532: doc-j
 5533: doc-k
 5534: 
 5535: 
 5536: The loop control data are kept on the return stack, so there are some
 5537: restrictions on mixing return stack accesses and counted loop words. In
 5538: particuler, if you put values on the return stack outside the loop, you
 5539: cannot read them inside the loop@footnote{well, not in a way that is
 5540: portable.}. If you put values on the return stack within a loop, you
 5541: have to remove them before the end of the loop and before accessing the
 5542: index of the loop.
 5543: 
 5544: There are several variations on the counted loop:
 5545: 
 5546: @itemize @bullet
 5547: @item
 5548: @code{LEAVE} leaves the innermost counted loop immediately; execution
 5549: continues after the associated @code{LOOP} or @code{NEXT}. For example:
 5550: 
 5551: @example
 5552: 10 0 ?DO  i DUP . 3 = IF LEAVE THEN LOOP
 5553: @end example
 5554: prints @code{0 1 2 3}
 5555: 
 5556: 
 5557: @item
 5558: @code{UNLOOP} prepares for an abnormal loop exit, e.g., via
 5559: @code{EXIT}. @code{UNLOOP} removes the loop control parameters from the
 5560: return stack so @code{EXIT} can get to its return address. For example:
 5561: 
 5562: @example
 5563: : demo 10 0 ?DO i DUP . 3 = IF UNLOOP EXIT THEN LOOP ." Done" ;
 5564: @end example
 5565: prints @code{0 1 2 3}
 5566: 
 5567: 
 5568: @item
 5569: If @i{start} is greater than @i{limit}, a @code{?DO} loop is entered
 5570: (and @code{LOOP} iterates until they become equal by wrap-around
 5571: arithmetic). This behaviour is usually not what you want. Therefore,
 5572: Gforth offers @code{+DO} and @code{U+DO} (as replacements for
 5573: @code{?DO}), which do not enter the loop if @i{start} is greater than
 5574: @i{limit}; @code{+DO} is for signed loop parameters, @code{U+DO} for
 5575: unsigned loop parameters.
 5576: 
 5577: @item
 5578: @code{?DO} can be replaced by @code{DO}. @code{DO} always enters
 5579: the loop, independent of the loop parameters. Do not use @code{DO}, even
 5580: if you know that the loop is entered in any case. Such knowledge tends
 5581: to become invalid during maintenance of a program, and then the
 5582: @code{DO} will make trouble.
 5583: 
 5584: @item
 5585: @code{LOOP} can be replaced with @code{@i{n} +LOOP}; this updates the
 5586: index by @i{n} instead of by 1. The loop is terminated when the border
 5587: between @i{limit-1} and @i{limit} is crossed. E.g.:
 5588: 
 5589: @example
 5590: 4 0 +DO  i .  2 +LOOP
 5591: @end example
 5592: @noindent
 5593: prints @code{0 2}
 5594: 
 5595: @example
 5596: 4 1 +DO  i .  2 +LOOP
 5597: @end example
 5598: @noindent
 5599: prints @code{1 3}
 5600: 
 5601: @item
 5602: @cindex negative increment for counted loops
 5603: @cindex counted loops with negative increment
 5604: The behaviour of @code{@i{n} +LOOP} is peculiar when @i{n} is negative:
 5605: 
 5606: @example
 5607: -1 0 ?DO  i .  -1 +LOOP
 5608: @end example
 5609: @noindent
 5610: prints @code{0 -1}
 5611: 
 5612: @example
 5613: 0 0 ?DO  i .  -1 +LOOP
 5614: @end example
 5615: prints nothing.
 5616: 
 5617: Therefore we recommend avoiding @code{@i{n} +LOOP} with negative
 5618: @i{n}. One alternative is @code{@i{u} -LOOP}, which reduces the
 5619: index by @i{u} each iteration. The loop is terminated when the border
 5620: between @i{limit+1} and @i{limit} is crossed. Gforth also provides
 5621: @code{-DO} and @code{U-DO} for down-counting loops. E.g.:
 5622: 
 5623: @example
 5624: -2 0 -DO  i .  1 -LOOP
 5625: @end example
 5626: @noindent
 5627: prints @code{0 -1}
 5628: 
 5629: @example
 5630: -1 0 -DO  i .  1 -LOOP
 5631: @end example
 5632: @noindent
 5633: prints @code{0}
 5634: 
 5635: @example
 5636: 0 0 -DO  i .  1 -LOOP
 5637: @end example
 5638: @noindent
 5639: prints nothing.
 5640: 
 5641: @end itemize
 5642: 
 5643: Unfortunately, @code{+DO}, @code{U+DO}, @code{-DO}, @code{U-DO} and
 5644: @code{-LOOP} are not defined in ANS Forth. However, an implementation
 5645: for these words that uses only standard words is provided in
 5646: @file{compat/loops.fs}.
 5647: 
 5648: 
 5649: @cindex @code{FOR} loops
 5650: Another counted loop is:
 5651: @example
 5652: @i{n}
 5653: FOR
 5654:   @i{body}
 5655: NEXT
 5656: @end example
 5657: This is the preferred loop of native code compiler writers who are too
 5658: lazy to optimize @code{?DO} loops properly. This loop structure is not
 5659: defined in ANS Forth. In Gforth, this loop iterates @i{n+1} times;
 5660: @code{i} produces values starting with @i{n} and ending with 0. Other
 5661: Forth systems may behave differently, even if they support @code{FOR}
 5662: loops. To avoid problems, don't use @code{FOR} loops.
 5663: 
 5664: @node Arbitrary control structures, Calls and returns, Counted Loops, Control Structures
 5665: @subsection Arbitrary control structures
 5666: @cindex control structures, user-defined
 5667: 
 5668: @cindex control-flow stack
 5669: ANS Forth permits and supports using control structures in a non-nested
 5670: way. Information about incomplete control structures is stored on the
 5671: control-flow stack. This stack may be implemented on the Forth data
 5672: stack, and this is what we have done in Gforth.
 5673: 
 5674: @cindex @code{orig}, control-flow stack item
 5675: @cindex @code{dest}, control-flow stack item
 5676: An @i{orig} entry represents an unresolved forward branch, a @i{dest}
 5677: entry represents a backward branch target. A few words are the basis for
 5678: building any control structure possible (except control structures that
 5679: need storage, like calls, coroutines, and backtracking).
 5680: 
 5681: 
 5682: doc-if
 5683: doc-ahead
 5684: doc-then
 5685: doc-begin
 5686: doc-until
 5687: doc-again
 5688: doc-cs-pick
 5689: doc-cs-roll
 5690: 
 5691: 
 5692: The Standard words @code{CS-PICK} and @code{CS-ROLL} allow you to
 5693: manipulate the control-flow stack in a portable way. Without them, you
 5694: would need to know how many stack items are occupied by a control-flow
 5695: entry (many systems use one cell. In Gforth they currently take three,
 5696: but this may change in the future).
 5697: 
 5698: Some standard control structure words are built from these words:
 5699: 
 5700: 
 5701: doc-else
 5702: doc-while
 5703: doc-repeat
 5704: 
 5705: 
 5706: @noindent
 5707: Gforth adds some more control-structure words:
 5708: 
 5709: 
 5710: doc-endif
 5711: doc-?dup-if
 5712: doc-?dup-0=-if
 5713: 
 5714: 
 5715: @noindent
 5716: Counted loop words constitute a separate group of words:
 5717: 
 5718: 
 5719: doc-?do
 5720: doc-+do
 5721: doc-u+do
 5722: doc--do
 5723: doc-u-do
 5724: doc-do
 5725: doc-for
 5726: doc-loop
 5727: doc-+loop
 5728: doc--loop
 5729: doc-next
 5730: doc-leave
 5731: doc-?leave
 5732: doc-unloop
 5733: doc-done
 5734: 
 5735: 
 5736: The standard does not allow using @code{CS-PICK} and @code{CS-ROLL} on
 5737: @i{do-sys}. Gforth allows it, but it's your job to ensure that for
 5738: every @code{?DO} etc. there is exactly one @code{UNLOOP} on any path
 5739: through the definition (@code{LOOP} etc. compile an @code{UNLOOP} on the
 5740: fall-through path). Also, you have to ensure that all @code{LEAVE}s are
 5741: resolved (by using one of the loop-ending words or @code{DONE}).
 5742: 
 5743: @noindent
 5744: Another group of control structure words are:
 5745: 
 5746: 
 5747: doc-case
 5748: doc-endcase
 5749: doc-of
 5750: doc-endof
 5751: 
 5752: 
 5753: @i{case-sys} and @i{of-sys} cannot be processed using @code{CS-PICK} and
 5754: @code{CS-ROLL}.
 5755: 
 5756: @subsubsection Programming Style
 5757: @cindex control structures programming style
 5758: @cindex programming style, arbitrary control structures
 5759: 
 5760: In order to ensure readability we recommend that you do not create
 5761: arbitrary control structures directly, but define new control structure
 5762: words for the control structure you want and use these words in your
 5763: program. For example, instead of writing:
 5764: 
 5765: @example
 5766: BEGIN
 5767:   ...
 5768: IF [ 1 CS-ROLL ]
 5769:   ...
 5770: AGAIN THEN
 5771: @end example
 5772: 
 5773: @noindent
 5774: we recommend defining control structure words, e.g.,
 5775: 
 5776: @example
 5777: : WHILE ( DEST -- ORIG DEST )
 5778:  POSTPONE IF
 5779:  1 CS-ROLL ; immediate
 5780: 
 5781: : REPEAT ( orig dest -- )
 5782:  POSTPONE AGAIN
 5783:  POSTPONE THEN ; immediate
 5784: @end example
 5785: 
 5786: @noindent
 5787: and then using these to create the control structure:
 5788: 
 5789: @example
 5790: BEGIN
 5791:   ...
 5792: WHILE
 5793:   ...
 5794: REPEAT
 5795: @end example
 5796: 
 5797: That's much easier to read, isn't it? Of course, @code{REPEAT} and
 5798: @code{WHILE} are predefined, so in this example it would not be
 5799: necessary to define them.
 5800: 
 5801: @node Calls and returns, Exception Handling, Arbitrary control structures, Control Structures
 5802: @subsection Calls and returns
 5803: @cindex calling a definition
 5804: @cindex returning from a definition
 5805: 
 5806: @cindex recursive definitions
 5807: A definition can be called simply be writing the name of the definition
 5808: to be called. Normally a definition is invisible during its own
 5809: definition. If you want to write a directly recursive definition, you
 5810: can use @code{recursive} to make the current definition visible, or
 5811: @code{recurse} to call the current definition directly.
 5812: 
 5813: 
 5814: doc-recursive
 5815: doc-recurse
 5816: 
 5817: 
 5818: @comment TODO add example of the two recursion methods
 5819: @quotation
 5820: @progstyle
 5821: I prefer using @code{recursive} to @code{recurse}, because calling the
 5822: definition by name is more descriptive (if the name is well-chosen) than
 5823: the somewhat cryptic @code{recurse}.  E.g., in a quicksort
 5824: implementation, it is much better to read (and think) ``now sort the
 5825: partitions'' than to read ``now do a recursive call''.
 5826: @end quotation
 5827: 
 5828: For mutual recursion, use @code{Defer}red words, like this:
 5829: 
 5830: @example
 5831: Defer foo
 5832: 
 5833: : bar ( ... -- ... )
 5834:  ... foo ... ;
 5835: 
 5836: :noname ( ... -- ... )
 5837:  ... bar ... ;
 5838: IS foo
 5839: @end example
 5840: 
 5841: Deferred words are discussed in more detail in @ref{Deferred words}.
 5842: 
 5843: The current definition returns control to the calling definition when
 5844: the end of the definition is reached or @code{EXIT} is encountered.
 5845: 
 5846: doc-exit
 5847: doc-;s
 5848: 
 5849: 
 5850: @node Exception Handling,  , Calls and returns, Control Structures
 5851: @subsection Exception Handling
 5852: @cindex exceptions
 5853: 
 5854: @c quit is a very bad idea for error handling, 
 5855: @c because it does not translate into a THROW
 5856: @c it also does not belong into this chapter
 5857: 
 5858: If a word detects an error condition that it cannot handle, it can
 5859: @code{throw} an exception.  In the simplest case, this will terminate
 5860: your program, and report an appropriate error.
 5861: 
 5862: doc-throw
 5863: 
 5864: @code{Throw} consumes a cell-sized error number on the stack. There are
 5865: some predefined error numbers in ANS Forth (see @file{errors.fs}).  In
 5866: Gforth (and most other systems) you can use the iors produced by various
 5867: words as error numbers (e.g., a typical use of @code{allocate} is
 5868: @code{allocate throw}).  Gforth also provides the word @code{exception}
 5869: to define your own error numbers (with decent error reporting); an ANS
 5870: Forth version of this word (but without the error messages) is available
 5871: in @code{compat/except.fs}.  And finally, you can use your own error
 5872: numbers (anything outside the range -4095..0), but won't get nice error
 5873: messages, only numbers.  For example, try:
 5874: 
 5875: @example
 5876: -10 throw                    \ ANS defined
 5877: -267 throw                   \ system defined
 5878: s" my error" exception throw \ user defined
 5879: 7 throw                      \ arbitrary number
 5880: @end example
 5881: 
 5882: doc---exception-exception
 5883: 
 5884: A common idiom to @code{THROW} a specific error if a flag is true is
 5885: this:
 5886: 
 5887: @example
 5888: @code{( flag ) 0<> @i{errno} and throw}
 5889: @end example
 5890: 
 5891: Your program can provide exception handlers to catch exceptions.  An
 5892: exception handler can be used to correct the problem, or to clean up
 5893: some data structures and just throw the exception to the next exception
 5894: handler.  Note that @code{throw} jumps to the dynamically innermost
 5895: exception handler.  The system's exception handler is outermost, and just
 5896: prints an error and restarts command-line interpretation (or, in batch
 5897: mode (i.e., while processing the shell command line), leaves Gforth).
 5898: 
 5899: The ANS Forth way to catch exceptions is @code{catch}:
 5900: 
 5901: doc-catch
 5902: 
 5903: The most common use of exception handlers is to clean up the state when
 5904: an error happens.  E.g.,
 5905: 
 5906: @example
 5907: base @ >r hex \ actually the hex should be inside foo, or we h
 5908: ['] foo catch ( nerror|0 )
 5909: r> base !
 5910: ( nerror|0 ) throw \ pass it on
 5911: @end example
 5912: 
 5913: A use of @code{catch} for handling the error @code{myerror} might look
 5914: like this:
 5915: 
 5916: @example
 5917: ['] foo catch
 5918: CASE
 5919:   myerror OF ... ( do something about it ) ENDOF
 5920:   dup throw \ default: pass other errors on, do nothing on non-errors
 5921: ENDCASE
 5922: @end example
 5923: 
 5924: Having to wrap the code into a separate word is often cumbersome,
 5925: therefore Gforth provides an alternative syntax:
 5926: 
 5927: @example
 5928: TRY
 5929:   @i{code1}
 5930: RECOVER     \ optional
 5931:   @i{code2} \ optional
 5932: ENDTRY
 5933: @end example
 5934: 
 5935: This performs @i{Code1}.  If @i{code1} completes normally, execution
 5936: continues after the @code{endtry}.  If @i{Code1} throws, the stacks are
 5937: reset to the state during @code{try}, the throw value is pushed on the
 5938: data stack, and execution constinues at @i{code2}, and finally falls
 5939: through the @code{endtry} into the following code. If there is no
 5940: @code{recover} clause, this works like an empty recover clause.
 5941: 
 5942: doc-try
 5943: doc-recover
 5944: doc-endtry
 5945: 
 5946: The cleanup example from above in this syntax:
 5947: 
 5948: @example
 5949: base @ >r TRY
 5950:   hex foo \ now the hex is placed correctly
 5951:   0       \ value for throw
 5952: ENDTRY
 5953: r> base ! throw
 5954: @end example
 5955: 
 5956: And here's the error handling example:
 5957: 
 5958: @example
 5959: TRY
 5960:   foo
 5961: RECOVER
 5962:   CASE
 5963:     myerror OF ... ( do something about it ) ENDOF
 5964:     throw \ pass other errors on
 5965:   ENDCASE
 5966: ENDTRY
 5967: @end example
 5968: 
 5969: @progstyle
 5970: As usual, you should ensure that the stack depth is statically known at
 5971: the end: either after the @code{throw} for passing on errors, or after
 5972: the @code{ENDTRY} (or, if you use @code{catch}, after the end of the
 5973: selection construct for handling the error).
 5974: 
 5975: There are two alternatives to @code{throw}: @code{Abort"} is conditional
 5976: and you can provide an error message.  @code{Abort} just produces an
 5977: ``Aborted'' error.
 5978: 
 5979: The problem with these words is that exception handlers cannot
 5980: differentiate between different @code{abort"}s; they just look like
 5981: @code{-2 throw} to them (the error message cannot be accessed by
 5982: standard programs).  Similar @code{abort} looks like @code{-1 throw} to
 5983: exception handlers.
 5984: 
 5985: doc-abort"
 5986: doc-abort
 5987: 
 5988: 
 5989: 
 5990: @c -------------------------------------------------------------
 5991: @node Defining Words, Interpretation and Compilation Semantics, Control Structures, Words
 5992: @section Defining Words
 5993: @cindex defining words
 5994: 
 5995: Defining words are used to extend Forth by creating new entries in the dictionary.
 5996: 
 5997: @menu
 5998: * CREATE::                      
 5999: * Variables::                   Variables and user variables
 6000: * Constants::                   
 6001: * Values::                      Initialised variables
 6002: * Colon Definitions::           
 6003: * Anonymous Definitions::       Definitions without names
 6004: * Supplying names::             Passing definition names as strings
 6005: * User-defined Defining Words::  
 6006: * Deferred words::              Allow forward references
 6007: * Aliases::                     
 6008: @end menu
 6009: 
 6010: @node CREATE, Variables, Defining Words, Defining Words
 6011: @subsection @code{CREATE}
 6012: @cindex simple defining words
 6013: @cindex defining words, simple
 6014: 
 6015: Defining words are used to create new entries in the dictionary. The
 6016: simplest defining word is @code{CREATE}. @code{CREATE} is used like
 6017: this:
 6018: 
 6019: @example
 6020: CREATE new-word1
 6021: @end example
 6022: 
 6023: @code{CREATE} is a parsing word, i.e., it takes an argument from the
 6024: input stream (@code{new-word1} in our example).  It generates a
 6025: dictionary entry for @code{new-word1}. When @code{new-word1} is
 6026: executed, all that it does is leave an address on the stack. The address
 6027: represents the value of the data space pointer (@code{HERE}) at the time
 6028: that @code{new-word1} was defined. Therefore, @code{CREATE} is a way of
 6029: associating a name with the address of a region of memory.
 6030: 
 6031: doc-create
 6032: 
 6033: Note that in ANS Forth guarantees only for @code{create} that its body
 6034: is in dictionary data space (i.e., where @code{here}, @code{allot}
 6035: etc. work, @pxref{Dictionary allocation}).  Also, in ANS Forth only
 6036: @code{create}d words can be modified with @code{does>}
 6037: (@pxref{User-defined Defining Words}).  And in ANS Forth @code{>body}
 6038: can only be applied to @code{create}d words.
 6039: 
 6040: By extending this example to reserve some memory in data space, we end
 6041: up with something like a @i{variable}. Here are two different ways to do
 6042: it:
 6043: 
 6044: @example
 6045: CREATE new-word2 1 cells allot  \ reserve 1 cell - initial value undefined
 6046: CREATE new-word3 4 ,            \ reserve 1 cell and initialise it (to 4)
 6047: @end example
 6048: 
 6049: The variable can be examined and modified using @code{@@} (``fetch'') and
 6050: @code{!} (``store'') like this:
 6051: 
 6052: @example
 6053: new-word2 @@ .      \ get address, fetch from it and display
 6054: 1234 new-word2 !   \ new value, get address, store to it
 6055: @end example
 6056: 
 6057: @cindex arrays
 6058: A similar mechanism can be used to create arrays. For example, an
 6059: 80-character text input buffer:
 6060: 
 6061: @example
 6062: CREATE text-buf 80 chars allot
 6063: 
 6064: text-buf 0 chars c@@ \ the 1st character (offset 0)
 6065: text-buf 3 chars c@@ \ the 4th character (offset 3)
 6066: @end example
 6067: 
 6068: You can build arbitrarily complex data structures by allocating
 6069: appropriate areas of memory. For further discussions of this, and to
 6070: learn about some Gforth tools that make it easier,
 6071: @xref{Structures}.
 6072: 
 6073: 
 6074: @node Variables, Constants, CREATE, Defining Words
 6075: @subsection Variables
 6076: @cindex variables
 6077: 
 6078: The previous section showed how a sequence of commands could be used to
 6079: generate a variable.  As a final refinement, the whole code sequence can
 6080: be wrapped up in a defining word (pre-empting the subject of the next
 6081: section), making it easier to create new variables:
 6082: 
 6083: @example
 6084: : myvariableX ( "name" -- a-addr ) CREATE 1 cells allot ;
 6085: : myvariable0 ( "name" -- a-addr ) CREATE 0 , ;
 6086: 
 6087: myvariableX foo \ variable foo starts off with an unknown value
 6088: myvariable0 joe \ whilst joe is initialised to 0
 6089: 
 6090: 45 3 * foo !   \ set foo to 135
 6091: 1234 joe !     \ set joe to 1234
 6092: 3 joe +!       \ increment joe by 3.. to 1237
 6093: @end example
 6094: 
 6095: Not surprisingly, there is no need to define @code{myvariable}, since
 6096: Forth already has a definition @code{Variable}. ANS Forth does not
 6097: guarantee that a @code{Variable} is initialised when it is created
 6098: (i.e., it may behave like @code{myvariableX}). In contrast, Gforth's
 6099: @code{Variable} initialises the variable to 0 (i.e., it behaves exactly
 6100: like @code{myvariable0}). Forth also provides @code{2Variable} and
 6101: @code{fvariable} for double and floating-point variables, respectively
 6102: -- they are initialised to 0. and 0e in Gforth. If you use a @code{Variable} to
 6103: store a boolean, you can use @code{on} and @code{off} to toggle its
 6104: state.
 6105: 
 6106: doc-variable
 6107: doc-2variable
 6108: doc-fvariable
 6109: 
 6110: @cindex user variables
 6111: @cindex user space
 6112: The defining word @code{User} behaves in the same way as @code{Variable}.
 6113: The difference is that it reserves space in @i{user (data) space} rather
 6114: than normal data space. In a Forth system that has a multi-tasker, each
 6115: task has its own set of user variables.
 6116: 
 6117: doc-user
 6118: @c doc-udp
 6119: @c doc-uallot
 6120: 
 6121: @comment TODO is that stuff about user variables strictly correct? Is it
 6122: @comment just terminal tasks that have user variables?
 6123: @comment should document tasker.fs (with some examples) elsewhere
 6124: @comment in this manual, then expand on user space and user variables.
 6125: 
 6126: @node Constants, Values, Variables, Defining Words
 6127: @subsection Constants
 6128: @cindex constants
 6129: 
 6130: @code{Constant} allows you to declare a fixed value and refer to it by
 6131: name. For example:
 6132: 
 6133: @example
 6134: 12 Constant INCHES-PER-FOOT
 6135: 3E+08 fconstant SPEED-O-LIGHT
 6136: @end example
 6137: 
 6138: A @code{Variable} can be both read and written, so its run-time
 6139: behaviour is to supply an address through which its current value can be
 6140: manipulated. In contrast, the value of a @code{Constant} cannot be
 6141: changed once it has been declared@footnote{Well, often it can be -- but
 6142: not in a Standard, portable way. It's safer to use a @code{Value} (read
 6143: on).} so it's not necessary to supply the address -- it is more
 6144: efficient to return the value of the constant directly. That's exactly
 6145: what happens; the run-time effect of a constant is to put its value on
 6146: the top of the stack (You can find one
 6147: way of implementing @code{Constant} in @ref{User-defined Defining Words}).
 6148: 
 6149: Forth also provides @code{2Constant} and @code{fconstant} for defining
 6150: double and floating-point constants, respectively.
 6151: 
 6152: doc-constant
 6153: doc-2constant
 6154: doc-fconstant
 6155: 
 6156: @c that's too deep, and it's not necessarily true for all ANS Forths. - anton
 6157: @c nac-> How could that not be true in an ANS Forth? You can't define a
 6158: @c constant, use it and then delete the definition of the constant..
 6159: 
 6160: @c anton->An ANS Forth system can compile a constant to a literal; On
 6161: @c decompilation you would see only the number, just as if it had been used
 6162: @c in the first place.  The word will stay, of course, but it will only be
 6163: @c used by the text interpreter (no run-time duties, except when it is 
 6164: @c POSTPONEd or somesuch).
 6165: 
 6166: @c nac:
 6167: @c I agree that it's rather deep, but IMO it is an important difference
 6168: @c relative to other programming languages.. often it's annoying: it
 6169: @c certainly changes my programming style relative to C.
 6170: 
 6171: @c anton: In what way?
 6172: 
 6173: Constants in Forth behave differently from their equivalents in other
 6174: programming languages. In other languages, a constant (such as an EQU in
 6175: assembler or a #define in C) only exists at compile-time; in the
 6176: executable program the constant has been translated into an absolute
 6177: number and, unless you are using a symbolic debugger, it's impossible to
 6178: know what abstract thing that number represents. In Forth a constant has
 6179: an entry in the header space and remains there after the code that uses
 6180: it has been defined. In fact, it must remain in the dictionary since it
 6181: has run-time duties to perform. For example:
 6182: 
 6183: @example
 6184: 12 Constant INCHES-PER-FOOT
 6185: : FEET-TO-INCHES ( n1 -- n2 ) INCHES-PER-FOOT * ;
 6186: @end example
 6187: 
 6188: @cindex in-lining of constants
 6189: When @code{FEET-TO-INCHES} is executed, it will in turn execute the xt
 6190: associated with the constant @code{INCHES-PER-FOOT}. If you use
 6191: @code{see} to decompile the definition of @code{FEET-TO-INCHES}, you can
 6192: see that it makes a call to @code{INCHES-PER-FOOT}. Some Forth compilers
 6193: attempt to optimise constants by in-lining them where they are used. You
 6194: can force Gforth to in-line a constant like this:
 6195: 
 6196: @example
 6197: : FEET-TO-INCHES ( n1 -- n2 ) [ INCHES-PER-FOOT ] LITERAL * ;
 6198: @end example
 6199: 
 6200: If you use @code{see} to decompile @i{this} version of
 6201: @code{FEET-TO-INCHES}, you can see that @code{INCHES-PER-FOOT} is no
 6202: longer present. To understand how this works, read
 6203: @ref{Interpret/Compile states}, and @ref{Literals}.
 6204: 
 6205: In-lining constants in this way might improve execution time
 6206: fractionally, and can ensure that a constant is now only referenced at
 6207: compile-time. However, the definition of the constant still remains in
 6208: the dictionary. Some Forth compilers provide a mechanism for controlling
 6209: a second dictionary for holding transient words such that this second
 6210: dictionary can be deleted later in order to recover memory
 6211: space. However, there is no standard way of doing this.
 6212: 
 6213: 
 6214: @node Values, Colon Definitions, Constants, Defining Words
 6215: @subsection Values
 6216: @cindex values
 6217: 
 6218: A @code{Value} behaves like a @code{Constant}, but it can be changed.
 6219: @code{TO} is a parsing word that changes a @code{Values}.  In Gforth
 6220: (not in ANS Forth) you can access (and change) a @code{value} also with
 6221: @code{>body}.
 6222: 
 6223: Here are some
 6224: examples:
 6225: 
 6226: @example
 6227: 12 Value APPLES     \ Define APPLES with an initial value of 12
 6228: 34 TO APPLES        \ Change the value of APPLES. TO is a parsing word
 6229: 1 ' APPLES >body +! \ Increment APPLES.  Non-standard usage.
 6230: APPLES              \ puts 35 on the top of the stack.
 6231: @end example
 6232: 
 6233: doc-value
 6234: doc-to
 6235: 
 6236: 
 6237: 
 6238: @node Colon Definitions, Anonymous Definitions, Values, Defining Words
 6239: @subsection Colon Definitions
 6240: @cindex colon definitions
 6241: 
 6242: @example
 6243: : name ( ... -- ... )
 6244:     word1 word2 word3 ;
 6245: @end example
 6246: 
 6247: @noindent
 6248: Creates a word called @code{name} that, upon execution, executes
 6249: @code{word1 word2 word3}. @code{name} is a @dfn{(colon) definition}.
 6250: 
 6251: The explanation above is somewhat superficial. For simple examples of
 6252: colon definitions see @ref{Your first definition}.  For an in-depth
 6253: discussion of some of the issues involved, @xref{Interpretation and
 6254: Compilation Semantics}.
 6255: 
 6256: doc-:
 6257: doc-;
 6258: 
 6259: 
 6260: @node Anonymous Definitions, Supplying names, Colon Definitions, Defining Words
 6261: @subsection Anonymous Definitions
 6262: @cindex colon definitions
 6263: @cindex defining words without name
 6264: 
 6265: Sometimes you want to define an @dfn{anonymous word}; a word without a
 6266: name. You can do this with:
 6267: 
 6268: doc-:noname
 6269: 
 6270: This leaves the execution token for the word on the stack after the
 6271: closing @code{;}. Here's an example in which a deferred word is
 6272: initialised with an @code{xt} from an anonymous colon definition:
 6273: 
 6274: @example
 6275: Defer deferred
 6276: :noname ( ... -- ... )
 6277:   ... ;
 6278: IS deferred
 6279: @end example
 6280: 
 6281: @noindent
 6282: Gforth provides an alternative way of doing this, using two separate
 6283: words:
 6284: 
 6285: doc-noname
 6286: @cindex execution token of last defined word
 6287: doc-lastxt
 6288: 
 6289: @noindent
 6290: The previous example can be rewritten using @code{noname} and
 6291: @code{lastxt}:
 6292: 
 6293: @example
 6294: Defer deferred
 6295: noname : ( ... -- ... )
 6296:   ... ;
 6297: lastxt IS deferred
 6298: @end example
 6299: 
 6300: @noindent
 6301: @code{noname} works with any defining word, not just @code{:}.
 6302: 
 6303: @code{lastxt} also works when the last word was not defined as
 6304: @code{noname}.  It does not work for combined words, though.  It also has
 6305: the useful property that is is valid as soon as the header for a
 6306: definition has been built. Thus:
 6307: 
 6308: @example
 6309: lastxt . : foo [ lastxt . ] ; ' foo .
 6310: @end example
 6311: 
 6312: @noindent
 6313: prints 3 numbers; the last two are the same.
 6314: 
 6315: @node Supplying names, User-defined Defining Words, Anonymous Definitions, Defining Words
 6316: @subsection Supplying the name of a defined word
 6317: @cindex names for defined words
 6318: @cindex defining words, name given in a string
 6319: 
 6320: By default, a defining word takes the name for the defined word from the
 6321: input stream. Sometimes you want to supply the name from a string. You
 6322: can do this with:
 6323: 
 6324: doc-nextname
 6325: 
 6326: For example:
 6327: 
 6328: @example
 6329: s" foo" nextname create
 6330: @end example
 6331: 
 6332: @noindent
 6333: is equivalent to:
 6334: 
 6335: @example
 6336: create foo
 6337: @end example
 6338: 
 6339: @noindent
 6340: @code{nextname} works with any defining word.
 6341: 
 6342: 
 6343: @node User-defined Defining Words, Deferred words, Supplying names, Defining Words
 6344: @subsection User-defined Defining Words
 6345: @cindex user-defined defining words
 6346: @cindex defining words, user-defined
 6347: 
 6348: You can create a new defining word by wrapping defining-time code around
 6349: an existing defining word and putting the sequence in a colon
 6350: definition. 
 6351: 
 6352: @c anton: This example is very complex and leads in a quite different
 6353: @c direction from the CREATE-DOES> stuff that follows.  It should probably
 6354: @c be done elsewhere, or as a subsubsection of this subsection (or as a
 6355: @c subsection of Defining Words)
 6356: 
 6357: For example, suppose that you have a word @code{stats} that
 6358: gathers statistics about colon definitions given the @i{xt} of the
 6359: definition, and you want every colon definition in your application to
 6360: make a call to @code{stats}. You can define and use a new version of
 6361: @code{:} like this:
 6362: 
 6363: @example
 6364: : stats ( xt -- ) DUP ." (Gathering statistics for " . ." )"
 6365:   ... ;  \ other code
 6366: 
 6367: : my: : lastxt postpone literal ['] stats compile, ;
 6368: 
 6369: my: foo + - ;
 6370: @end example
 6371: 
 6372: When @code{foo} is defined using @code{my:} these steps occur:
 6373: 
 6374: @itemize @bullet
 6375: @item
 6376: @code{my:} is executed.
 6377: @item
 6378: The @code{:} within the definition (the one between @code{my:} and
 6379: @code{lastxt}) is executed, and does just what it always does; it parses
 6380: the input stream for a name, builds a dictionary header for the name
 6381: @code{foo} and switches @code{state} from interpret to compile.
 6382: @item
 6383: The word @code{lastxt} is executed. It puts the @i{xt} for the word that is
 6384: being defined -- @code{foo} -- onto the stack.
 6385: @item
 6386: The code that was produced by @code{postpone literal} is executed; this
 6387: causes the value on the stack to be compiled as a literal in the code
 6388: area of @code{foo}.
 6389: @item
 6390: The code @code{['] stats} compiles a literal into the definition of
 6391: @code{my:}. When @code{compile,} is executed, that literal -- the
 6392: execution token for @code{stats} -- is layed down in the code area of
 6393: @code{foo} , following the literal@footnote{Strictly speaking, the
 6394: mechanism that @code{compile,} uses to convert an @i{xt} into something
 6395: in the code area is implementation-dependent. A threaded implementation
 6396: might spit out the execution token directly whilst another
 6397: implementation might spit out a native code sequence.}.
 6398: @item
 6399: At this point, the execution of @code{my:} is complete, and control
 6400: returns to the text interpreter. The text interpreter is in compile
 6401: state, so subsequent text @code{+ -} is compiled into the definition of
 6402: @code{foo} and the @code{;} terminates the definition as always.
 6403: @end itemize
 6404: 
 6405: You can use @code{see} to decompile a word that was defined using
 6406: @code{my:} and see how it is different from a normal @code{:}
 6407: definition. For example:
 6408: 
 6409: @example
 6410: : bar + - ;  \ like foo but using : rather than my:
 6411: see bar
 6412: : bar
 6413:   + - ;
 6414: see foo
 6415: : foo
 6416:   107645672 stats + - ;
 6417: 
 6418: \ use ' stats . to show that 107645672 is the xt for stats
 6419: @end example
 6420: 
 6421: You can use techniques like this to make new defining words in terms of
 6422: @i{any} existing defining word.
 6423: 
 6424: 
 6425: @cindex defining defining words
 6426: @cindex @code{CREATE} ... @code{DOES>}
 6427: If you want the words defined with your defining words to behave
 6428: differently from words defined with standard defining words, you can
 6429: write your defining word like this:
 6430: 
 6431: @example
 6432: : def-word ( "name" -- )
 6433:     CREATE @i{code1}
 6434: DOES> ( ... -- ... )
 6435:     @i{code2} ;
 6436: 
 6437: def-word name
 6438: @end example
 6439: 
 6440: @cindex child words
 6441: This fragment defines a @dfn{defining word} @code{def-word} and then
 6442: executes it.  When @code{def-word} executes, it @code{CREATE}s a new
 6443: word, @code{name}, and executes the code @i{code1}. The code @i{code2}
 6444: is not executed at this time. The word @code{name} is sometimes called a
 6445: @dfn{child} of @code{def-word}.
 6446: 
 6447: When you execute @code{name}, the address of the body of @code{name} is
 6448: put on the data stack and @i{code2} is executed (the address of the body
 6449: of @code{name} is the address @code{HERE} returns immediately after the
 6450: @code{CREATE}, i.e., the address a @code{create}d word returns by
 6451: default).
 6452: 
 6453: @c anton:
 6454: @c www.dictionary.com says:
 6455: @c at·a·vism: 1.The reappearance of a characteristic in an organism after
 6456: @c several generations of absence, usually caused by the chance
 6457: @c recombination of genes.  2.An individual or a part that exhibits
 6458: @c atavism. Also called throwback.  3.The return of a trait or recurrence
 6459: @c of previous behavior after a period of absence.
 6460: @c
 6461: @c Doesn't seem to fit.
 6462: 
 6463: @c @cindex atavism in child words
 6464: You can use @code{def-word} to define a set of child words that behave
 6465: similarly; they all have a common run-time behaviour determined by
 6466: @i{code2}. Typically, the @i{code1} sequence builds a data area in the
 6467: body of the child word. The structure of the data is common to all
 6468: children of @code{def-word}, but the data values are specific -- and
 6469: private -- to each child word. When a child word is executed, the
 6470: address of its private data area is passed as a parameter on TOS to be
 6471: used and manipulated@footnote{It is legitimate both to read and write to
 6472: this data area.} by @i{code2}.
 6473: 
 6474: The two fragments of code that make up the defining words act (are
 6475: executed) at two completely separate times:
 6476: 
 6477: @itemize @bullet
 6478: @item
 6479: At @i{define time}, the defining word executes @i{code1} to generate a
 6480: child word
 6481: @item
 6482: At @i{child execution time}, when a child word is invoked, @i{code2}
 6483: is executed, using parameters (data) that are private and specific to
 6484: the child word.
 6485: @end itemize
 6486: 
 6487: Another way of understanding the behaviour of @code{def-word} and
 6488: @code{name} is to say that, if you make the following definitions:
 6489: @example
 6490: : def-word1 ( "name" -- )
 6491:     CREATE @i{code1} ;
 6492: 
 6493: : action1 ( ... -- ... )
 6494:     @i{code2} ;
 6495: 
 6496: def-word1 name1
 6497: @end example
 6498: 
 6499: @noindent
 6500: Then using @code{name1 action1} is equivalent to using @code{name}.
 6501: 
 6502: The classic example is that you can define @code{CONSTANT} in this way:
 6503: 
 6504: @example
 6505: : CONSTANT ( w "name" -- )
 6506:     CREATE ,
 6507: DOES> ( -- w )
 6508:     @@ ;
 6509: @end example
 6510: 
 6511: @comment There is a beautiful description of how this works and what
 6512: @comment it does in the Forthwrite 100th edition.. as well as an elegant
 6513: @comment commentary on the Counting Fruits problem.
 6514: 
 6515: When you create a constant with @code{5 CONSTANT five}, a set of
 6516: define-time actions take place; first a new word @code{five} is created,
 6517: then the value 5 is laid down in the body of @code{five} with
 6518: @code{,}. When @code{five} is executed, the address of the body is put on
 6519: the stack, and @code{@@} retrieves the value 5. The word @code{five} has
 6520: no code of its own; it simply contains a data field and a pointer to the
 6521: code that follows @code{DOES>} in its defining word. That makes words
 6522: created in this way very compact.
 6523: 
 6524: The final example in this section is intended to remind you that space
 6525: reserved in @code{CREATE}d words is @i{data} space and therefore can be
 6526: both read and written by a Standard program@footnote{Exercise: use this
 6527: example as a starting point for your own implementation of @code{Value}
 6528: and @code{TO} -- if you get stuck, investigate the behaviour of @code{'} and
 6529: @code{[']}.}:
 6530: 
 6531: @example
 6532: : foo ( "name" -- )
 6533:     CREATE -1 ,
 6534: DOES> ( -- )
 6535:     @@ . ;
 6536: 
 6537: foo first-word
 6538: foo second-word
 6539: 
 6540: 123 ' first-word >BODY !
 6541: @end example
 6542: 
 6543: If @code{first-word} had been a @code{CREATE}d word, we could simply
 6544: have executed it to get the address of its data field. However, since it
 6545: was defined to have @code{DOES>} actions, its execution semantics are to
 6546: perform those @code{DOES>} actions. To get the address of its data field
 6547: it's necessary to use @code{'} to get its xt, then @code{>BODY} to
 6548: translate the xt into the address of the data field.  When you execute
 6549: @code{first-word}, it will display @code{123}. When you execute
 6550: @code{second-word} it will display @code{-1}.
 6551: 
 6552: @cindex stack effect of @code{DOES>}-parts
 6553: @cindex @code{DOES>}-parts, stack effect
 6554: In the examples above the stack comment after the @code{DOES>} specifies
 6555: the stack effect of the defined words, not the stack effect of the
 6556: following code (the following code expects the address of the body on
 6557: the top of stack, which is not reflected in the stack comment). This is
 6558: the convention that I use and recommend (it clashes a bit with using
 6559: locals declarations for stack effect specification, though).
 6560: 
 6561: @menu
 6562: * CREATE..DOES> applications::  
 6563: * CREATE..DOES> details::       
 6564: * Advanced does> usage example::  
 6565: @end menu
 6566: 
 6567: @node CREATE..DOES> applications, CREATE..DOES> details, User-defined Defining Words, User-defined Defining Words
 6568: @subsubsection Applications of @code{CREATE..DOES>}
 6569: @cindex @code{CREATE} ... @code{DOES>}, applications
 6570: 
 6571: You may wonder how to use this feature. Here are some usage patterns:
 6572: 
 6573: @cindex factoring similar colon definitions
 6574: When you see a sequence of code occurring several times, and you can
 6575: identify a meaning, you will factor it out as a colon definition. When
 6576: you see similar colon definitions, you can factor them using
 6577: @code{CREATE..DOES>}. E.g., an assembler usually defines several words
 6578: that look very similar:
 6579: @example
 6580: : ori, ( reg-target reg-source n -- )
 6581:     0 asm-reg-reg-imm ;
 6582: : andi, ( reg-target reg-source n -- )
 6583:     1 asm-reg-reg-imm ;
 6584: @end example
 6585: 
 6586: @noindent
 6587: This could be factored with:
 6588: @example
 6589: : reg-reg-imm ( op-code -- )
 6590:     CREATE ,
 6591: DOES> ( reg-target reg-source n -- )
 6592:     @@ asm-reg-reg-imm ;
 6593: 
 6594: 0 reg-reg-imm ori,
 6595: 1 reg-reg-imm andi,
 6596: @end example
 6597: 
 6598: @cindex currying
 6599: Another view of @code{CREATE..DOES>} is to consider it as a crude way to
 6600: supply a part of the parameters for a word (known as @dfn{currying} in
 6601: the functional language community). E.g., @code{+} needs two
 6602: parameters. Creating versions of @code{+} with one parameter fixed can
 6603: be done like this:
 6604: 
 6605: @example
 6606: : curry+ ( n1 "name" -- )
 6607:     CREATE ,
 6608: DOES> ( n2 -- n1+n2 )
 6609:     @@ + ;
 6610: 
 6611:  3 curry+ 3+
 6612: -2 curry+ 2-
 6613: @end example
 6614: 
 6615: @node CREATE..DOES> details, Advanced does> usage example, CREATE..DOES> applications, User-defined Defining Words
 6616: @subsubsection The gory details of @code{CREATE..DOES>}
 6617: @cindex @code{CREATE} ... @code{DOES>}, details
 6618: 
 6619: doc-does>
 6620: 
 6621: @cindex @code{DOES>} in a separate definition
 6622: This means that you need not use @code{CREATE} and @code{DOES>} in the
 6623: same definition; you can put the @code{DOES>}-part in a separate
 6624: definition. This allows us to, e.g., select among different @code{DOES>}-parts:
 6625: @example
 6626: : does1 
 6627: DOES> ( ... -- ... )
 6628:     ... ;
 6629: 
 6630: : does2
 6631: DOES> ( ... -- ... )
 6632:     ... ;
 6633: 
 6634: : def-word ( ... -- ... )
 6635:     create ...
 6636:     IF
 6637:        does1
 6638:     ELSE
 6639:        does2
 6640:     ENDIF ;
 6641: @end example
 6642: 
 6643: In this example, the selection of whether to use @code{does1} or
 6644: @code{does2} is made at definition-time; at the time that the child word is
 6645: @code{CREATE}d.
 6646: 
 6647: @cindex @code{DOES>} in interpretation state
 6648: In a standard program you can apply a @code{DOES>}-part only if the last
 6649: word was defined with @code{CREATE}. In Gforth, the @code{DOES>}-part
 6650: will override the behaviour of the last word defined in any case. In a
 6651: standard program, you can use @code{DOES>} only in a colon
 6652: definition. In Gforth, you can also use it in interpretation state, in a
 6653: kind of one-shot mode; for example:
 6654: @example
 6655: CREATE name ( ... -- ... )
 6656:   @i{initialization}
 6657: DOES>
 6658:   @i{code} ;
 6659: @end example
 6660: 
 6661: @noindent
 6662: is equivalent to the standard:
 6663: @example
 6664: :noname
 6665: DOES>
 6666:     @i{code} ;
 6667: CREATE name EXECUTE ( ... -- ... )
 6668:     @i{initialization}
 6669: @end example
 6670: 
 6671: doc->body
 6672: 
 6673: @node Advanced does> usage example,  , CREATE..DOES> details, User-defined Defining Words
 6674: @subsubsection Advanced does> usage example
 6675: 
 6676: The MIPS disassembler (@file{arch/mips/disasm.fs}) contains many words
 6677: for disassembling instructions, that follow a very repetetive scheme:
 6678: 
 6679: @example
 6680: :noname @var{disasm-operands} s" @var{inst-name}" type ;
 6681: @var{entry-num} cells @var{table} + !
 6682: @end example
 6683: 
 6684: Of course, this inspires the idea to factor out the commonalities to
 6685: allow a definition like
 6686: 
 6687: @example
 6688: @var{disasm-operands} @var{entry-num} @var{table} define-inst @var{inst-name}
 6689: @end example
 6690: 
 6691: The parameters @var{disasm-operands} and @var{table} are usually
 6692: correlated.  Moreover, before I wrote the disassembler, there already
 6693: existed code that defines instructions like this:
 6694: 
 6695: @example
 6696: @var{entry-num} @var{inst-format} @var{inst-name}
 6697: @end example
 6698: 
 6699: This code comes from the assembler and resides in
 6700: @file{arch/mips/insts.fs}.
 6701: 
 6702: So I had to define the @var{inst-format} words that performed the scheme
 6703: above when executed.  At first I chose to use run-time code-generation:
 6704: 
 6705: @example
 6706: : @var{inst-format} ( entry-num "name" -- ; compiled code: addr w -- )
 6707:   :noname Postpone @var{disasm-operands}
 6708:   name Postpone sliteral Postpone type Postpone ;
 6709:   swap cells @var{table} + ! ;
 6710: @end example
 6711: 
 6712: Note that this supplies the other two parameters of the scheme above.
 6713: 
 6714: An alternative would have been to write this using
 6715: @code{create}/@code{does>}:
 6716: 
 6717: @example
 6718: : @var{inst-format} ( entry-num "name" -- )
 6719:   here name string, ( entry-num c-addr ) \ parse and save "name"
 6720:   noname create , ( entry-num )
 6721:   lastxt swap cells @var{table} + !
 6722: does> ( addr w -- )
 6723:   \ disassemble instruction w at addr
 6724:   @@ >r 
 6725:   @var{disasm-operands}
 6726:   r> count type ;
 6727: @end example
 6728: 
 6729: Somehow the first solution is simpler, mainly because it's simpler to
 6730: shift a string from definition-time to use-time with @code{sliteral}
 6731: than with @code{string,} and friends.
 6732: 
 6733: I wrote a lot of words following this scheme and soon thought about
 6734: factoring out the commonalities among them.  Note that this uses a
 6735: two-level defining word, i.e., a word that defines ordinary defining
 6736: words.
 6737: 
 6738: This time a solution involving @code{postpone} and friends seemed more
 6739: difficult (try it as an exercise), so I decided to use a
 6740: @code{create}/@code{does>} word; since I was already at it, I also used
 6741: @code{create}/@code{does>} for the lower level (try using
 6742: @code{postpone} etc. as an exercise), resulting in the following
 6743: definition:
 6744: 
 6745: @example
 6746: : define-format ( disasm-xt table-xt -- )
 6747:     \ define an instruction format that uses disasm-xt for
 6748:     \ disassembling and enters the defined instructions into table
 6749:     \ table-xt
 6750:     create 2,
 6751: does> ( u "inst" -- )
 6752:     \ defines an anonymous word for disassembling instruction inst,
 6753:     \ and enters it as u-th entry into table-xt
 6754:     2@@ swap here name string, ( u table-xt disasm-xt c-addr ) \ remember string
 6755:     noname create 2,      \ define anonymous word
 6756:     execute lastxt swap ! \ enter xt of defined word into table-xt
 6757: does> ( addr w -- )
 6758:     \ disassemble instruction w at addr
 6759:     2@@ >r ( addr w disasm-xt R: c-addr )
 6760:     execute ( R: c-addr ) \ disassemble operands
 6761:     r> count type ; \ print name 
 6762: @end example
 6763: 
 6764: Note that the tables here (in contrast to above) do the @code{cells +}
 6765: by themselves (that's why you have to pass an xt).  This word is used in
 6766: the following way:
 6767: 
 6768: @example
 6769: ' @var{disasm-operands} ' @var{table} define-format @var{inst-format}
 6770: @end example
 6771: 
 6772: As shown above, the defined instruction format is then used like this:
 6773: 
 6774: @example
 6775: @var{entry-num} @var{inst-format} @var{inst-name}
 6776: @end example
 6777: 
 6778: In terms of currying, this kind of two-level defining word provides the
 6779: parameters in three stages: first @var{disasm-operands} and @var{table},
 6780: then @var{entry-num} and @var{inst-name}, finally @code{addr w}, i.e.,
 6781: the instruction to be disassembled.  
 6782: 
 6783: Of course this did not quite fit all the instruction format names used
 6784: in @file{insts.fs}, so I had to define a few wrappers that conditioned
 6785: the parameters into the right form.
 6786: 
 6787: If you have trouble following this section, don't worry.  First, this is
 6788: involved and takes time (and probably some playing around) to
 6789: understand; second, this is the first two-level
 6790: @code{create}/@code{does>} word I have written in seventeen years of
 6791: Forth; and if I did not have @file{insts.fs} to start with, I may well
 6792: have elected to use just a one-level defining word (with some repeating
 6793: of parameters when using the defining word). So it is not necessary to
 6794: understand this, but it may improve your understanding of Forth.
 6795: 
 6796: 
 6797: @node Deferred words, Aliases, User-defined Defining Words, Defining Words
 6798: @subsection Deferred words
 6799: @cindex deferred words
 6800: 
 6801: The defining word @code{Defer} allows you to define a word by name
 6802: without defining its behaviour; the definition of its behaviour is
 6803: deferred. Here are two situation where this can be useful:
 6804: 
 6805: @itemize @bullet
 6806: @item
 6807: Where you want to allow the behaviour of a word to be altered later, and
 6808: for all precompiled references to the word to change when its behaviour
 6809: is changed.
 6810: @item
 6811: For mutual recursion; @xref{Calls and returns}.
 6812: @end itemize
 6813: 
 6814: In the following example, @code{foo} always invokes the version of
 6815: @code{greet} that prints ``@code{Good morning}'' whilst @code{bar}
 6816: always invokes the version that prints ``@code{Hello}''. There is no way
 6817: of getting @code{foo} to use the later version without re-ordering the
 6818: source code and recompiling it.
 6819: 
 6820: @example
 6821: : greet ." Good morning" ;
 6822: : foo ... greet ... ;
 6823: : greet ." Hello" ;
 6824: : bar ... greet ... ;
 6825: @end example
 6826: 
 6827: This problem can be solved by defining @code{greet} as a @code{Defer}red
 6828: word. The behaviour of a @code{Defer}red word can be defined and
 6829: redefined at any time by using @code{IS} to associate the xt of a
 6830: previously-defined word with it. The previous example becomes:
 6831: 
 6832: @example
 6833: Defer greet ( -- )
 6834: : foo ... greet ... ;
 6835: : bar ... greet ... ;
 6836: : greet1 ( -- ) ." Good morning" ;
 6837: : greet2 ( -- ) ." Hello" ;
 6838: ' greet2 <IS> greet  \ make greet behave like greet2
 6839: @end example
 6840: 
 6841: @progstyle
 6842: You should write a stack comment for every deferred word, and put only
 6843: XTs into deferred words that conform to this stack effect.  Otherwise
 6844: it's too difficult to use the deferred word.
 6845: 
 6846: A deferred word can be used to improve the statistics-gathering example
 6847: from @ref{User-defined Defining Words}; rather than edit the
 6848: application's source code to change every @code{:} to a @code{my:}, do
 6849: this:
 6850: 
 6851: @example
 6852: : real: : ;     \ retain access to the original
 6853: defer :         \ redefine as a deferred word
 6854: ' my: <IS> :      \ use special version of :
 6855: \
 6856: \ load application here
 6857: \
 6858: ' real: <IS> :    \ go back to the original
 6859: @end example
 6860: 
 6861: 
 6862: One thing to note is that @code{<IS>} consumes its name when it is
 6863: executed.  If you want to specify the name at compile time, use
 6864: @code{[IS]}:
 6865: 
 6866: @example
 6867: : set-greet ( xt -- )
 6868:   [IS] greet ;
 6869: 
 6870: ' greet1 set-greet
 6871: @end example
 6872: 
 6873: A deferred word can only inherit execution semantics from the xt
 6874: (because that is all that an xt can represent -- for more discussion of
 6875: this @pxref{Tokens for Words}); by default it will have default
 6876: interpretation and compilation semantics deriving from this execution
 6877: semantics.  However, you can change the interpretation and compilation
 6878: semantics of the deferred word in the usual ways:
 6879: 
 6880: @example
 6881: : bar .... ; compile-only
 6882: Defer fred immediate
 6883: Defer jim
 6884: 
 6885: ' bar <IS> jim  \ jim has default semantics
 6886: ' bar <IS> fred \ fred is immediate
 6887: @end example
 6888: 
 6889: doc-defer
 6890: doc-<is>
 6891: doc-[is]
 6892: doc-is
 6893: @comment TODO document these: what's defers [is]
 6894: doc-what's
 6895: doc-defers
 6896: 
 6897: @c Use @code{words-deferred} to see a list of deferred words.
 6898: 
 6899: Definitions in ANS Forth for @code{defer}, @code{<is>} and @code{[is]}
 6900: are provided in @file{compat/defer.fs}.
 6901: 
 6902: 
 6903: @node Aliases,  , Deferred words, Defining Words
 6904: @subsection Aliases
 6905: @cindex aliases
 6906: 
 6907: The defining word @code{Alias} allows you to define a word by name that
 6908: has the same behaviour as some other word. Here are two situation where
 6909: this can be useful:
 6910: 
 6911: @itemize @bullet
 6912: @item
 6913: When you want access to a word's definition from a different word list
 6914: (for an example of this, see the definition of the @code{Root} word list
 6915: in the Gforth source).
 6916: @item
 6917: When you want to create a synonym; a definition that can be known by
 6918: either of two names (for example, @code{THEN} and @code{ENDIF} are
 6919: aliases).
 6920: @end itemize
 6921: 
 6922: Like deferred words, an alias has default compilation and interpretation
 6923: semantics at the beginning (not the modifications of the other word),
 6924: but you can change them in the usual ways (@code{immediate},
 6925: @code{compile-only}). For example:
 6926: 
 6927: @example
 6928: : foo ... ; immediate
 6929: 
 6930: ' foo Alias bar \ bar is not an immediate word
 6931: ' foo Alias fooby immediate \ fooby is an immediate word
 6932: @end example
 6933: 
 6934: Words that are aliases have the same xt, different headers in the
 6935: dictionary, and consequently different name tokens (@pxref{Tokens for
 6936: Words}) and possibly different immediate flags.  An alias can only have
 6937: default or immediate compilation semantics; you can define aliases for
 6938: combined words with @code{interpret/compile:} -- see @ref{Combined words}.
 6939: 
 6940: doc-alias
 6941: 
 6942: 
 6943: @node Interpretation and Compilation Semantics, Tokens for Words, Defining Words, Words
 6944: @section Interpretation and Compilation Semantics
 6945: @cindex semantics, interpretation and compilation
 6946: 
 6947: @c !! state and ' are used without explanation
 6948: @c example for immediate/compile-only? or is the tutorial enough
 6949: 
 6950: @cindex interpretation semantics
 6951: The @dfn{interpretation semantics} of a (named) word are what the text
 6952: interpreter does when it encounters the word in interpret state. It also
 6953: appears in some other contexts, e.g., the execution token returned by
 6954: @code{' @i{word}} identifies the interpretation semantics of @i{word}
 6955: (in other words, @code{' @i{word} execute} is equivalent to
 6956: interpret-state text interpretation of @code{@i{word}}).
 6957: 
 6958: @cindex compilation semantics
 6959: The @dfn{compilation semantics} of a (named) word are what the text
 6960: interpreter does when it encounters the word in compile state. It also
 6961: appears in other contexts, e.g, @code{POSTPONE @i{word}}
 6962: compiles@footnote{In standard terminology, ``appends to the current
 6963: definition''.} the compilation semantics of @i{word}.
 6964: 
 6965: @cindex execution semantics
 6966: The standard also talks about @dfn{execution semantics}. They are used
 6967: only for defining the interpretation and compilation semantics of many
 6968: words. By default, the interpretation semantics of a word are to
 6969: @code{execute} its execution semantics, and the compilation semantics of
 6970: a word are to @code{compile,} its execution semantics.@footnote{In
 6971: standard terminology: The default interpretation semantics are its
 6972: execution semantics; the default compilation semantics are to append its
 6973: execution semantics to the execution semantics of the current
 6974: definition.}
 6975: 
 6976: Unnamed words (@pxref{Anonymous Definitions}) cannot be encountered by
 6977: the text interpreter, ticked, or @code{postpone}d, so they have no
 6978: interpretation or compilation semantics.  Their behaviour is represented
 6979: by their XT (@pxref{Tokens for Words}), and we call it execution
 6980: semantics, too.
 6981: 
 6982: @comment TODO expand, make it co-operate with new sections on text interpreter.
 6983: 
 6984: @cindex immediate words
 6985: @cindex compile-only words
 6986: You can change the semantics of the most-recently defined word:
 6987: 
 6988: 
 6989: doc-immediate
 6990: doc-compile-only
 6991: doc-restrict
 6992: 
 6993: By convention, words with non-default compilation semantics (e.g.,
 6994: immediate words) often have names surrounded with brackets (e.g.,
 6995: @code{[']}, @pxref{Execution token}).
 6996: 
 6997: Note that ticking (@code{'}) a compile-only word gives an error
 6998: (``Interpreting a compile-only word'').
 6999: 
 7000: @menu
 7001: * Combined words::              
 7002: @end menu
 7003: 
 7004: 
 7005: @node Combined words,  , Interpretation and Compilation Semantics, Interpretation and Compilation Semantics
 7006: @subsection Combined Words
 7007: @cindex combined words
 7008: 
 7009: Gforth allows you to define @dfn{combined words} -- words that have an
 7010: arbitrary combination of interpretation and compilation semantics.
 7011: 
 7012: doc-interpret/compile:
 7013: 
 7014: This feature was introduced for implementing @code{TO} and @code{S"}. I
 7015: recommend that you do not define such words, as cute as they may be:
 7016: they make it hard to get at both parts of the word in some contexts.
 7017: E.g., assume you want to get an execution token for the compilation
 7018: part. Instead, define two words, one that embodies the interpretation
 7019: part, and one that embodies the compilation part.  Once you have done
 7020: that, you can define a combined word with @code{interpret/compile:} for
 7021: the convenience of your users.
 7022: 
 7023: You might try to use this feature to provide an optimizing
 7024: implementation of the default compilation semantics of a word. For
 7025: example, by defining:
 7026: @example
 7027: :noname
 7028:    foo bar ;
 7029: :noname
 7030:    POSTPONE foo POSTPONE bar ;
 7031: interpret/compile: opti-foobar
 7032: @end example
 7033: 
 7034: @noindent
 7035: as an optimizing version of:
 7036: 
 7037: @example
 7038: : foobar
 7039:     foo bar ;
 7040: @end example
 7041: 
 7042: Unfortunately, this does not work correctly with @code{[compile]},
 7043: because @code{[compile]} assumes that the compilation semantics of all
 7044: @code{interpret/compile:} words are non-default. I.e., @code{[compile]
 7045: opti-foobar} would compile compilation semantics, whereas
 7046: @code{[compile] foobar} would compile interpretation semantics.
 7047: 
 7048: @cindex state-smart words (are a bad idea)
 7049: @anchor{state-smartness}
 7050: Some people try to use @dfn{state-smart} words to emulate the feature provided
 7051: by @code{interpret/compile:} (words are state-smart if they check
 7052: @code{STATE} during execution). E.g., they would try to code
 7053: @code{foobar} like this:
 7054: 
 7055: @example
 7056: : foobar
 7057:   STATE @@
 7058:   IF ( compilation state )
 7059:     POSTPONE foo POSTPONE bar
 7060:   ELSE
 7061:     foo bar
 7062:   ENDIF ; immediate
 7063: @end example
 7064: 
 7065: Although this works if @code{foobar} is only processed by the text
 7066: interpreter, it does not work in other contexts (like @code{'} or
 7067: @code{POSTPONE}). E.g., @code{' foobar} will produce an execution token
 7068: for a state-smart word, not for the interpretation semantics of the
 7069: original @code{foobar}; when you execute this execution token (directly
 7070: with @code{EXECUTE} or indirectly through @code{COMPILE,}) in compile
 7071: state, the result will not be what you expected (i.e., it will not
 7072: perform @code{foo bar}). State-smart words are a bad idea. Simply don't
 7073: write them@footnote{For a more detailed discussion of this topic, see
 7074: M. Anton Ertl,
 7075: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,@code{State}-smartness---Why
 7076: it is Evil and How to Exorcise it}}, EuroForth '98.}!
 7077: 
 7078: @cindex defining words with arbitrary semantics combinations
 7079: It is also possible to write defining words that define words with
 7080: arbitrary combinations of interpretation and compilation semantics. In
 7081: general, they look like this:
 7082: 
 7083: @example
 7084: : def-word
 7085:     create-interpret/compile
 7086:     @i{code1}
 7087: interpretation>
 7088:     @i{code2}
 7089: <interpretation
 7090: compilation>
 7091:     @i{code3}
 7092: <compilation ;
 7093: @end example
 7094: 
 7095: For a @i{word} defined with @code{def-word}, the interpretation
 7096: semantics are to push the address of the body of @i{word} and perform
 7097: @i{code2}, and the compilation semantics are to push the address of
 7098: the body of @i{word} and perform @i{code3}. E.g., @code{constant}
 7099: can also be defined like this (except that the defined constants don't
 7100: behave correctly when @code{[compile]}d):
 7101: 
 7102: @example
 7103: : constant ( n "name" -- )
 7104:     create-interpret/compile
 7105:     ,
 7106: interpretation> ( -- n )
 7107:     @@
 7108: <interpretation
 7109: compilation> ( compilation. -- ; run-time. -- n )
 7110:     @@ postpone literal
 7111: <compilation ;
 7112: @end example
 7113: 
 7114: 
 7115: doc-create-interpret/compile
 7116: doc-interpretation>
 7117: doc-<interpretation
 7118: doc-compilation>
 7119: doc-<compilation
 7120: 
 7121: 
 7122: Words defined with @code{interpret/compile:} and
 7123: @code{create-interpret/compile} have an extended header structure that
 7124: differs from other words; however, unless you try to access them with
 7125: plain address arithmetic, you should not notice this. Words for
 7126: accessing the header structure usually know how to deal with this; e.g.,
 7127: @code{'} @i{word} @code{>body} also gives you the body of a word created
 7128: with @code{create-interpret/compile}.
 7129: 
 7130: 
 7131: @c -------------------------------------------------------------
 7132: @node Tokens for Words, Compiling words, Interpretation and Compilation Semantics, Words
 7133: @section Tokens for Words
 7134: @cindex tokens for words
 7135: 
 7136: This section describes the creation and use of tokens that represent
 7137: words.
 7138: 
 7139: @menu
 7140: * Execution token::             represents execution/interpretation semantics
 7141: * Compilation token::           represents compilation semantics
 7142: * Name token::                  represents named words
 7143: @end menu
 7144: 
 7145: @node Execution token, Compilation token, Tokens for Words, Tokens for Words
 7146: @subsection Execution token
 7147: 
 7148: @cindex xt
 7149: @cindex execution token
 7150: An @dfn{execution token} (@i{XT}) represents some behaviour of a word.
 7151: You can use @code{execute} to invoke this behaviour.
 7152: 
 7153: @cindex tick (')
 7154: You can use @code{'} to get an execution token that represents the
 7155: interpretation semantics of a named word:
 7156: 
 7157: @example
 7158: 5 ' .
 7159: execute
 7160: @end example
 7161: 
 7162: doc-'
 7163: 
 7164: @code{'} parses at run-time; there is also a word @code{[']} that parses
 7165: when it is compiled, and compiles the resulting XT:
 7166: 
 7167: @example
 7168: : foo ['] . execute ;
 7169: 5 foo
 7170: : bar ' execute ; \ by contrast,
 7171: 5 bar .           \ ' parses "." when bar executes
 7172: @end example
 7173: 
 7174: doc-[']
 7175: 
 7176: If you want the execution token of @i{word}, write @code{['] @i{word}}
 7177: in compiled code and @code{' @i{word}} in interpreted code.  Gforth's
 7178: @code{'} and @code{[']} behave somewhat unusually by complaining about
 7179: compile-only words (because these words have no interpretation
 7180: semantics).  You might get what you want by using @code{COMP' @i{word}
 7181: DROP} or @code{[COMP'] @i{word} DROP} (for details @pxref{Compilation
 7182: token}).
 7183: 
 7184: Another way to get an XT is @code{:noname} or @code{lastxt}
 7185: (@pxref{Anonymous Definitions}).  For anonymous words this gives an xt
 7186: for the only behaviour the word has (the execution semantics).  For
 7187: named words, @code{lastxt} produces an XT for the same behaviour it
 7188: would produce if the word was defined anonymously.
 7189: 
 7190: @example
 7191: :noname ." hello" ;
 7192: execute
 7193: @end example
 7194: 
 7195: An XT occupies one cell and can be manipulated like any other cell.
 7196: 
 7197: @cindex code field address
 7198: @cindex CFA
 7199: In ANS Forth the XT is just an abstract data type (i.e., defined by the
 7200: operations that produce or consume it).  For old hands: In Gforth, the
 7201: XT is implemented as a code field address (CFA).
 7202: 
 7203: doc-execute
 7204: doc-perform
 7205: 
 7206: @node Compilation token, Name token, Execution token, Tokens for Words
 7207: @subsection Compilation token
 7208: 
 7209: @cindex compilation token
 7210: @cindex CT (compilation token)
 7211: Gforth represents the compilation semantics of a named word by a
 7212: @dfn{compilation token} consisting of two cells: @i{w xt}. The top cell
 7213: @i{xt} is an execution token. The compilation semantics represented by
 7214: the compilation token can be performed with @code{execute}, which
 7215: consumes the whole compilation token, with an additional stack effect
 7216: determined by the represented compilation semantics.
 7217: 
 7218: At present, the @i{w} part of a compilation token is an execution token,
 7219: and the @i{xt} part represents either @code{execute} or
 7220: @code{compile,}@footnote{Depending upon the compilation semantics of the
 7221: word. If the word has default compilation semantics, the @i{xt} will
 7222: represent @code{compile,}. Otherwise (e.g., for immediate words), the
 7223: @i{xt} will represent @code{execute}.}. However, don't rely on that
 7224: knowledge, unless necessary; future versions of Gforth may introduce
 7225: unusual compilation tokens (e.g., a compilation token that represents
 7226: the compilation semantics of a literal).
 7227: 
 7228: You can perform the compilation semantics represented by the compilation
 7229: token with @code{execute}.  You can compile the compilation semantics
 7230: with @code{postpone,}. I.e., @code{COMP' @i{word} postpone,} is
 7231: equivalent to @code{postpone @i{word}}.
 7232: 
 7233: doc-[comp']
 7234: doc-comp'
 7235: doc-postpone,
 7236: 
 7237: @node Name token,  , Compilation token, Tokens for Words
 7238: @subsection Name token
 7239: 
 7240: @cindex name token
 7241: @cindex name field address
 7242: @cindex NFA
 7243: Gforth represents named words by the @dfn{name token}, (@i{nt}). In
 7244: Gforth, the abstract data type @emph{name token} is implemented as a
 7245: name field address (NFA).
 7246: 
 7247: doc-find-name
 7248: doc-name>int
 7249: doc-name?int
 7250: doc-name>comp
 7251: doc-name>string
 7252: 
 7253: @c ----------------------------------------------------------
 7254: @node Compiling words, The Text Interpreter, Tokens for Words, Words
 7255: @section Compiling words
 7256: @cindex compiling words
 7257: @cindex macros
 7258: 
 7259: In contrast to most other languages, Forth has no strict boundary
 7260: between compilation and run-time.  E.g., you can run arbitrary code
 7261: between defining words (or for computing data used by defining words
 7262: like @code{constant}). Moreover, @code{Immediate} (@pxref{Interpretation
 7263: and Compilation Semantics} and @code{[}...@code{]} (see below) allow
 7264: running arbitrary code while compiling a colon definition (exception:
 7265: you must not allot dictionary space).
 7266: 
 7267: @menu
 7268: * Literals::                    Compiling data values
 7269: * Macros::                      Compiling words
 7270: @end menu
 7271: 
 7272: @node Literals, Macros, Compiling words, Compiling words
 7273: @subsection Literals
 7274: @cindex Literals
 7275: 
 7276: The simplest and most frequent example is to compute a literal during
 7277: compilation.  E.g., the following definition prints an array of strings,
 7278: one string per line:
 7279: 
 7280: @example
 7281: : .strings ( addr u -- ) \ gforth
 7282:     2* cells bounds U+DO
 7283: 	cr i 2@@ type
 7284:     2 cells +LOOP ;  
 7285: @end example
 7286: 
 7287: With a simple-minded compiler like Gforth's, this computes @code{2
 7288: cells} on every loop iteration.  You can compute this value once and for
 7289: all at compile time and compile it into the definition like this:
 7290: 
 7291: @example
 7292: : .strings ( addr u -- ) \ gforth
 7293:     2* cells bounds U+DO
 7294: 	cr i 2@@ type
 7295:     [ 2 cells ] literal +LOOP ;  
 7296: @end example
 7297: 
 7298: @code{[} switches the text interpreter to interpret state (you will get
 7299: an @code{ok} prompt if you type this example interactively and insert a
 7300: newline between @code{[} and @code{]}), so it performs the
 7301: interpretation semantics of @code{2 cells}; this computes a number.
 7302: @code{]} switches the text interpreter back into compile state.  It then
 7303: performs @code{Literal}'s compilation semantics, which are to compile
 7304: this number into the current word.  You can decompile the word with
 7305: @code{see .strings} to see the effect on the compiled code.
 7306: 
 7307: You can also optimize the @code{2* cells} into @code{[ 2 cells ] literal
 7308: *} in this way.
 7309: 
 7310: doc-[
 7311: doc-]
 7312: doc-literal
 7313: doc-]L
 7314: 
 7315: There are also words for compiling other data types than single cells as
 7316: literals:
 7317: 
 7318: doc-2literal
 7319: doc-fliteral
 7320: doc-sliteral
 7321: 
 7322: @cindex colon-sys, passing data across @code{:}
 7323: @cindex @code{:}, passing data across
 7324: You might be tempted to pass data from outside a colon definition to the
 7325: inside on the data stack.  This does not work, because @code{:} puhes a
 7326: colon-sys, making stuff below unaccessible.  E.g., this does not work:
 7327: 
 7328: @example
 7329: 5 : foo literal ; \ error: "unstructured"
 7330: @end example
 7331: 
 7332: Instead, you have to pass the value in some other way, e.g., through a
 7333: variable:
 7334: 
 7335: @example
 7336: variable temp
 7337: 5 temp !
 7338: : foo [ temp @@ ] literal ;
 7339: @end example
 7340: 
 7341: 
 7342: @node Macros,  , Literals, Compiling words
 7343: @subsection Macros
 7344: @cindex Macros
 7345: @cindex compiling compilation semantics
 7346: 
 7347: @code{Literal} and friends compile data values into the current
 7348: definition.  You can also write words that compile other words into the
 7349: current definition.  E.g.,
 7350: 
 7351: @example
 7352: : compile-+ ( -- ) \ compiled code: ( n1 n2 -- n )
 7353:   POSTPONE + ;
 7354: 
 7355: : foo ( n1 n2 -- n )
 7356:   [ compile-+ ] ;
 7357: 1 2 foo .
 7358: @end example
 7359: 
 7360: This is equivalent to @code{: foo + ;} (@code{see foo} to check this).
 7361: What happens in this example?  @code{Postpone} compiles the compilation
 7362: semantics of @code{+} into @code{compile-+}; later the text interpreter
 7363: executes @code{compile-+} and thus the compilation semantics of +, which
 7364: compile (the execution semantics of) @code{+} into
 7365: @code{foo}.@footnote{A recent RFI answer requires that compiling words
 7366: should only be executed in compile state, so this example is not
 7367: guaranteed to work on all standard systems, but on any decent system it
 7368: will work.}
 7369: 
 7370: doc-postpone
 7371: doc-[compile]
 7372: 
 7373: Compiling words like @code{compile-+} are usually immediate (or similar)
 7374: so you do not have to switch to interpret state to execute them;
 7375: mopifying the last example accordingly produces:
 7376: 
 7377: @example
 7378: : [compile-+] ( compilation: --; interpretation: -- )
 7379:   \ compiled code: ( n1 n2 -- n )
 7380:   POSTPONE + ; immediate
 7381: 
 7382: : foo ( n1 n2 -- n )
 7383:   [compile-+] ;
 7384: 1 2 foo .
 7385: @end example
 7386: 
 7387: Immediate compiling words are similar to macros in other languages (in
 7388: particular, Lisp).  The important differences to macros in, e.g., C are:
 7389: 
 7390: @itemize @bullet
 7391: 
 7392: @item
 7393: You use the same language for defining and processing macros, not a
 7394: separate preprocessing language and processor.
 7395: 
 7396: @item
 7397: Consequently, the full power of Forth is available in macro definitions.
 7398: E.g., you can perform arbitrarily complex computations, or generate
 7399: different code conditionally or in a loop (e.g., @pxref{Advanced macros
 7400: Tutorial}).  This power is very useful when writing a parser generators
 7401: or other code-generating software.
 7402: 
 7403: @item
 7404: Macros defined using @code{postpone} etc. deal with the language at a
 7405: higher level than strings; name binding happens at macro definition
 7406: time, so you can avoid the pitfalls of name collisions that can happen
 7407: in C macros.  Of course, Forth is a liberal language and also allows to
 7408: shoot yourself in the foot with text-interpreted macros like
 7409: 
 7410: @example
 7411: : [compile-+] s" +" evaluate ; immediate
 7412: @end example
 7413: 
 7414: Apart from binding the name at macro use time, using @code{evaluate}
 7415: also makes your definition @code{state}-smart (@pxref{state-smartness}).
 7416: @end itemize
 7417: 
 7418: You may want the macro to compile a number into a word.  The word to do
 7419: it is @code{literal}, but you have to @code{postpone} it, so its
 7420: compilation semantics take effect when the macro is executed, not when
 7421: it is compiled:
 7422: 
 7423: @example
 7424: : [compile-5] ( -- ) \ compiled code: ( -- n )
 7425:   5 POSTPONE literal ; immediate
 7426: 
 7427: : foo [compile-5] ;
 7428: foo .
 7429: @end example
 7430: 
 7431: You may want to pass parameters to a macro, that the macro should
 7432: compile into the current definition.  If the parameter is a number, then
 7433: you can use @code{postpone literal} (similar for other values).
 7434: 
 7435: If you want to pass a word that is to be compiled, the usual way is to
 7436: pass an execution token and @code{compile,} it:
 7437: 
 7438: @example
 7439: : twice1 ( xt -- ) \ compiled code: ... -- ...
 7440:   dup compile, compile, ;
 7441: 
 7442: : 2+ ( n1 -- n2 )
 7443:   [ ' 1+ twice1 ] ;
 7444: @end example
 7445: 
 7446: doc-compile,
 7447: 
 7448: An alternative available in Gforth, that allows you to pass compile-only
 7449: words as parameters is to use the compilation token (@pxref{Compilation
 7450: token}).  The same example in this technique:
 7451: 
 7452: @example
 7453: : twice ( ... ct -- ... ) \ compiled code: ... -- ...
 7454:   2dup 2>r execute 2r> execute ;
 7455: 
 7456: : 2+ ( n1 -- n2 )
 7457:   [ comp' 1+ twice ] ;
 7458: @end example
 7459: 
 7460: In the example above @code{2>r} and @code{2r>} ensure that @code{twice}
 7461: works even if the executed compilation semantics has an effect on the
 7462: data stack.
 7463: 
 7464: You can also define complete definitions with these words; this provides
 7465: an alternative to using @code{does>} (@pxref{User-defined Defining
 7466: Words}).  E.g., instead of
 7467: 
 7468: @example
 7469: : curry+ ( n1 "name" -- )
 7470:     CREATE ,
 7471: DOES> ( n2 -- n1+n2 )
 7472:     @@ + ;
 7473: @end example
 7474: 
 7475: you could define
 7476: 
 7477: @example
 7478: : curry+ ( n1 "name" -- )
 7479:   \ name execution: ( n2 -- n1+n2 )
 7480:   >r : r> POSTPONE literal POSTPONE + POSTPONE ; ;
 7481: 
 7482: -3 curry+ 3-
 7483: see 3-
 7484: @end example
 7485: 
 7486: The sequence @code{>r : r>} is necessary, because @code{:} puts a
 7487: colon-sys on the data stack that makes everything below it unaccessible.
 7488: 
 7489: This way of writing defining words is sometimes more, sometimes less
 7490: convenient than using @code{does>} (@pxref{Advanced does> usage
 7491: example}).  One advantage of this method is that it can be optimized
 7492: better, because the compiler knows that the value compiled with
 7493: @code{literal} is fixed, whereas the data associated with a
 7494: @code{create}d word can be changed.
 7495: 
 7496: @c ----------------------------------------------------------
 7497: @node The Text Interpreter, Word Lists, Compiling words, Words
 7498: @section  The Text Interpreter
 7499: @cindex interpreter - outer
 7500: @cindex text interpreter
 7501: @cindex outer interpreter
 7502: 
 7503: @c Should we really describe all these ugly details?  IMO the text
 7504: @c interpreter should be much cleaner, but that may not be possible within
 7505: @c ANS Forth. - anton
 7506: @c nac-> I wanted to explain how it works to show how you can exploit
 7507: @c it in your own programs. When I was writing a cross-compiler, figuring out
 7508: @c some of these gory details was very helpful to me. None of the textbooks
 7509: @c I've seen cover it, and the most modern Forth textbook -- Forth Inc's,
 7510: @c seems to positively avoid going into too much detail for some of
 7511: @c the internals.
 7512: 
 7513: @c anton: ok.  I wonder, though, if this is the right place; for some stuff
 7514: @c it is; for the ugly details, I would prefer another place.  I wonder
 7515: @c whether we should have a chapter before "Words" that describes some
 7516: @c basic concepts referred to in words, and a chapter after "Words" that
 7517: @c describes implementation details.
 7518: 
 7519: The text interpreter@footnote{This is an expanded version of the
 7520: material in @ref{Introducing the Text Interpreter}.} is an endless loop
 7521: that processes input from the current input device. It is also called
 7522: the outer interpreter, in contrast to the inner interpreter
 7523: (@pxref{Engine}) which executes the compiled Forth code on interpretive
 7524: implementations.
 7525: 
 7526: @cindex interpret state
 7527: @cindex compile state
 7528: The text interpreter operates in one of two states: @dfn{interpret
 7529: state} and @dfn{compile state}. The current state is defined by the
 7530: aptly-named variable @code{state}.
 7531: 
 7532: This section starts by describing how the text interpreter behaves when
 7533: it is in interpret state, processing input from the user input device --
 7534: the keyboard. This is the mode that a Forth system is in after it starts
 7535: up.
 7536: 
 7537: @cindex input buffer
 7538: @cindex terminal input buffer
 7539: The text interpreter works from an area of memory called the @dfn{input
 7540: buffer}@footnote{When the text interpreter is processing input from the
 7541: keyboard, this area of memory is called the @dfn{terminal input buffer}
 7542: (TIB) and is addressed by the (obsolescent) words @code{TIB} and
 7543: @code{#TIB}.}, which stores your keyboard input when you press the
 7544: @key{RET} key. Starting at the beginning of the input buffer, it skips
 7545: leading spaces (called @dfn{delimiters}) then parses a string (a
 7546: sequence of non-space characters) until it reaches either a space
 7547: character or the end of the buffer. Having parsed a string, it makes two
 7548: attempts to process it:
 7549: 
 7550: @cindex dictionary
 7551: @itemize @bullet
 7552: @item
 7553: It looks for the string in a @dfn{dictionary} of definitions. If the
 7554: string is found, the string names a @dfn{definition} (also known as a
 7555: @dfn{word}) and the dictionary search returns information that allows
 7556: the text interpreter to perform the word's @dfn{interpretation
 7557: semantics}. In most cases, this simply means that the word will be
 7558: executed.
 7559: @item
 7560: If the string is not found in the dictionary, the text interpreter
 7561: attempts to treat it as a number, using the rules described in
 7562: @ref{Number Conversion}. If the string represents a legal number in the
 7563: current radix, the number is pushed onto a parameter stack (the data
 7564: stack for integers, the floating-point stack for floating-point
 7565: numbers).
 7566: @end itemize
 7567: 
 7568: If both attempts fail, or if the word is found in the dictionary but has
 7569: no interpretation semantics@footnote{This happens if the word was
 7570: defined as @code{COMPILE-ONLY}.} the text interpreter discards the
 7571: remainder of the input buffer, issues an error message and waits for
 7572: more input. If one of the attempts succeeds, the text interpreter
 7573: repeats the parsing process until the whole of the input buffer has been
 7574: processed, at which point it prints the status message ``@code{ ok}''
 7575: and waits for more input.
 7576: 
 7577: @c anton: this should be in the input stream subsection (or below it)
 7578: 
 7579: @cindex parse area
 7580: The text interpreter keeps track of its position in the input buffer by
 7581: updating a variable called @code{>IN} (pronounced ``to-in''). The value
 7582: of @code{>IN} starts out as 0, indicating an offset of 0 from the start
 7583: of the input buffer. The region from offset @code{>IN @@} to the end of
 7584: the input buffer is called the @dfn{parse area}@footnote{In other words,
 7585: the text interpreter processes the contents of the input buffer by
 7586: parsing strings from the parse area until the parse area is empty.}.
 7587: This example shows how @code{>IN} changes as the text interpreter parses
 7588: the input buffer:
 7589: 
 7590: @example
 7591: : remaining >IN @@ SOURCE 2 PICK - -ROT + SWAP
 7592:   CR ." ->" TYPE ." <-" ; IMMEDIATE 
 7593: 
 7594: 1 2 3 remaining + remaining . 
 7595: 
 7596: : foo 1 2 3 remaining SWAP remaining ;
 7597: @end example
 7598: 
 7599: @noindent
 7600: The result is:
 7601: 
 7602: @example
 7603: ->+ remaining .<-
 7604: ->.<-5  ok
 7605: 
 7606: ->SWAP remaining ;-<
 7607: ->;<-  ok
 7608: @end example
 7609: 
 7610: @cindex parsing words
 7611: The value of @code{>IN} can also be modified by a word in the input
 7612: buffer that is executed by the text interpreter.  This means that a word
 7613: can ``trick'' the text interpreter into either skipping a section of the
 7614: input buffer@footnote{This is how parsing words work.} or into parsing a
 7615: section twice. For example:
 7616: 
 7617: @example
 7618: : lat ." <<foo>>" ;
 7619: : flat ." <<bar>>" >IN DUP @@ 3 - SWAP ! ;
 7620: @end example
 7621: 
 7622: @noindent
 7623: When @code{flat} is executed, this output is produced@footnote{Exercise
 7624: for the reader: what would happen if the @code{3} were replaced with
 7625: @code{4}?}:
 7626: 
 7627: @example
 7628: <<bar>><<foo>>
 7629: @end example
 7630: 
 7631: This technique can be used to work around some of the interoperability
 7632: problems of parsing words.  Of course, it's better to avoid parsing
 7633: words where possible.
 7634: 
 7635: @noindent
 7636: Two important notes about the behaviour of the text interpreter:
 7637: 
 7638: @itemize @bullet
 7639: @item
 7640: It processes each input string to completion before parsing additional
 7641: characters from the input buffer.
 7642: @item
 7643: It treats the input buffer as a read-only region (and so must your code).
 7644: @end itemize
 7645: 
 7646: @noindent
 7647: When the text interpreter is in compile state, its behaviour changes in
 7648: these ways:
 7649: 
 7650: @itemize @bullet
 7651: @item
 7652: If a parsed string is found in the dictionary, the text interpreter will
 7653: perform the word's @dfn{compilation semantics}. In most cases, this
 7654: simply means that the execution semantics of the word will be appended
 7655: to the current definition.
 7656: @item
 7657: When a number is encountered, it is compiled into the current definition
 7658: (as a literal) rather than being pushed onto a parameter stack.
 7659: @item
 7660: If an error occurs, @code{state} is modified to put the text interpreter
 7661: back into interpret state.
 7662: @item
 7663: Each time a line is entered from the keyboard, Gforth prints
 7664: ``@code{ compiled}'' rather than `` @code{ok}''.
 7665: @end itemize
 7666: 
 7667: @cindex text interpreter - input sources
 7668: When the text interpreter is using an input device other than the
 7669: keyboard, its behaviour changes in these ways:
 7670: 
 7671: @itemize @bullet
 7672: @item
 7673: When the parse area is empty, the text interpreter attempts to refill
 7674: the input buffer from the input source. When the input source is
 7675: exhausted, the input source is set back to the previous input source.
 7676: @item
 7677: It doesn't print out ``@code{ ok}'' or ``@code{ compiled}'' messages each
 7678: time the parse area is emptied.
 7679: @item
 7680: If an error occurs, the input source is set back to the user input
 7681: device.
 7682: @end itemize
 7683: 
 7684: You can read about this in more detail in @ref{Input Sources}.
 7685: 
 7686: doc->in
 7687: doc-source
 7688: 
 7689: doc-tib
 7690: doc-#tib
 7691: 
 7692: 
 7693: @menu
 7694: * Input Sources::               
 7695: * Number Conversion::           
 7696: * Interpret/Compile states::    
 7697: * Interpreter Directives::      
 7698: @end menu
 7699: 
 7700: @node Input Sources, Number Conversion, The Text Interpreter, The Text Interpreter
 7701: @subsection Input Sources
 7702: @cindex input sources
 7703: @cindex text interpreter - input sources
 7704: 
 7705: By default, the text interpreter processes input from the user input
 7706: device (the keyboard) when Forth starts up. The text interpreter can
 7707: process input from any of these sources:
 7708: 
 7709: @itemize @bullet
 7710: @item
 7711: The user input device -- the keyboard.
 7712: @item
 7713: A file, using the words described in @ref{Forth source files}.
 7714: @item
 7715: A block, using the words described in @ref{Blocks}.
 7716: @item
 7717: A text string, using @code{evaluate}.
 7718: @end itemize
 7719: 
 7720: A program can identify the current input device from the values of
 7721: @code{source-id} and @code{blk}.
 7722: 
 7723: 
 7724: doc-source-id
 7725: doc-blk
 7726: 
 7727: doc-save-input
 7728: doc-restore-input
 7729: 
 7730: doc-evaluate
 7731: 
 7732: 
 7733: 
 7734: @node Number Conversion, Interpret/Compile states, Input Sources, The Text Interpreter
 7735: @subsection Number Conversion
 7736: @cindex number conversion
 7737: @cindex double-cell numbers, input format
 7738: @cindex input format for double-cell numbers
 7739: @cindex single-cell numbers, input format
 7740: @cindex input format for single-cell numbers
 7741: @cindex floating-point numbers, input format
 7742: @cindex input format for floating-point numbers
 7743: 
 7744: This section describes the rules that the text interpreter uses when it
 7745: tries to convert a string into a number.
 7746: 
 7747: Let <digit> represent any character that is a legal digit in the current
 7748: number base@footnote{For example, 0-9 when the number base is decimal or
 7749: 0-9, A-F when the number base is hexadecimal.}.
 7750: 
 7751: Let <decimal digit> represent any character in the range 0-9.
 7752: 
 7753: Let @{@i{a b}@} represent the @i{optional} presence of any of the characters
 7754: in the braces (@i{a} or @i{b} or neither).
 7755: 
 7756: Let * represent any number of instances of the previous character
 7757: (including none).
 7758: 
 7759: Let any other character represent itself.
 7760: 
 7761: @noindent
 7762: Now, the conversion rules are:
 7763: 
 7764: @itemize @bullet
 7765: @item
 7766: A string of the form <digit><digit>* is treated as a single-precision
 7767: (cell-sized) positive integer. Examples are 0 123 6784532 32343212343456 42
 7768: @item
 7769: A string of the form -<digit><digit>* is treated as a single-precision
 7770: (cell-sized) negative integer, and is represented using 2's-complement
 7771: arithmetic. Examples are -45 -5681 -0
 7772: @item
 7773: A string of the form <digit><digit>*.<digit>* is treated as a double-precision
 7774: (double-cell-sized) positive integer. Examples are 3465. 3.465 34.65
 7775: (all three of these represent the same number).
 7776: @item
 7777: A string of the form -<digit><digit>*.<digit>* is treated as a
 7778: double-precision (double-cell-sized) negative integer, and is
 7779: represented using 2's-complement arithmetic. Examples are -3465. -3.465
 7780: -34.65 (all three of these represent the same number).
 7781: @item
 7782: A string of the form @{+ -@}<decimal digit>@{.@}<decimal digit>*@{e
 7783: E@}@{+ -@}<decimal digit><decimal digit>* is treated as a floating-point
 7784: number. Examples are 1e 1e0 1.e 1.e0 +1e+0 (which all represent the same
 7785: number) +12.E-4
 7786: @end itemize
 7787: 
 7788: By default, the number base used for integer number conversion is given
 7789: by the contents of the variable @code{base}.  Note that a lot of
 7790: confusion can result from unexpected values of @code{base}.  If you
 7791: change @code{base} anywhere, make sure to save the old value and restore
 7792: it afterwards.  In general I recommend keeping @code{base} decimal, and
 7793: using the prefixes described below for the popular non-decimal bases.
 7794: 
 7795: doc-dpl
 7796: doc-base
 7797: doc-hex
 7798: doc-decimal
 7799: 
 7800: 
 7801: @cindex '-prefix for character strings
 7802: @cindex &-prefix for decimal numbers
 7803: @cindex %-prefix for binary numbers
 7804: @cindex $-prefix for hexadecimal numbers
 7805: Gforth allows you to override the value of @code{base} by using a
 7806: prefix@footnote{Some Forth implementations provide a similar scheme by
 7807: implementing @code{$} etc. as parsing words that process the subsequent
 7808: number in the input stream and push it onto the stack. For example, see
 7809: @cite{Number Conversion and Literals}, by Wil Baden; Forth Dimensions
 7810: 20(3) pages 26--27. In such implementations, unlike in Gforth, a space
 7811: is required between the prefix and the number.} before the first digit
 7812: of an (integer) number. Four prefixes are supported:
 7813: 
 7814: @itemize @bullet
 7815: @item
 7816: @code{&} -- decimal
 7817: @item
 7818: @code{%} -- binary
 7819: @item
 7820: @code{$} -- hexadecimal
 7821: @item
 7822: @code{'} -- base @code{max-char+1}
 7823: @end itemize
 7824: 
 7825: Here are some examples, with the equivalent decimal number shown after
 7826: in braces:
 7827: 
 7828: -$41 (-65), %1001101 (205), %1001.0001 (145 - a double-precision number),
 7829: 'AB (16706; ascii A is 65, ascii B is 66, number is 65*256 + 66),
 7830: 'ab (24930; ascii a is 97, ascii B is 98, number is 97*256 + 98),
 7831: &905 (905), $abc (2478), $ABC (2478).
 7832: 
 7833: @cindex number conversion - traps for the unwary
 7834: @noindent
 7835: Number conversion has a number of traps for the unwary:
 7836: 
 7837: @itemize @bullet
 7838: @item
 7839: You cannot determine the current number base using the code sequence
 7840: @code{base @@ .} -- the number base is always 10 in the current number
 7841: base. Instead, use something like @code{base @@ dec.}
 7842: @item
 7843: If the number base is set to a value greater than 14 (for example,
 7844: hexadecimal), the number 123E4 is ambiguous; the conversion rules allow
 7845: it to be intepreted as either a single-precision integer or a
 7846: floating-point number (Gforth treats it as an integer). The ambiguity
 7847: can be resolved by explicitly stating the sign of the mantissa and/or
 7848: exponent: 123E+4 or +123E4 -- if the number base is decimal, no
 7849: ambiguity arises; either representation will be treated as a
 7850: floating-point number.
 7851: @item
 7852: There is a word @code{bin} but it does @i{not} set the number base!
 7853: It is used to specify file types.
 7854: @item
 7855: ANS Forth requires the @code{.} of a double-precision number to be the
 7856: final character in the string.  Gforth allows the @code{.} to be
 7857: anywhere after the first digit.
 7858: @item
 7859: The number conversion process does not check for overflow.
 7860: @item
 7861: In an ANS Forth program @code{base} is required to be decimal when
 7862: converting floating-point numbers.  In Gforth, number conversion to
 7863: floating-point numbers always uses base &10, irrespective of the value
 7864: of @code{base}.
 7865: @end itemize
 7866: 
 7867: You can read numbers into your programs with the words described in
 7868: @ref{Input}.
 7869: 
 7870: @node Interpret/Compile states, Interpreter Directives, Number Conversion, The Text Interpreter
 7871: @subsection Interpret/Compile states
 7872: @cindex Interpret/Compile states
 7873: 
 7874: A standard program is not permitted to change @code{state}
 7875: explicitly. However, it can change @code{state} implicitly, using the
 7876: words @code{[} and @code{]}. When @code{[} is executed it switches
 7877: @code{state} to interpret state, and therefore the text interpreter
 7878: starts interpreting. When @code{]} is executed it switches @code{state}
 7879: to compile state and therefore the text interpreter starts
 7880: compiling. The most common usage for these words is for switching into
 7881: interpret state and back from within a colon definition; this technique
 7882: can be used to compile a literal (for an example, @pxref{Literals}) or
 7883: for conditional compilation (for an example, @pxref{Interpreter
 7884: Directives}).
 7885: 
 7886: 
 7887: @c This is a bad example: It's non-standard, and it's not necessary.
 7888: @c However, I can't think of a good example for switching into compile
 7889: @c state when there is no current word (@code{state}-smart words are not a
 7890: @c good reason).  So maybe we should use an example for switching into
 7891: @c interpret @code{state} in a colon def. - anton
 7892: @c nac-> I agree. I started out by putting in the example, then realised
 7893: @c that it was non-ANS, so wrote more words around it. I hope this
 7894: @c re-written version is acceptable to you. I do want to keep the example
 7895: @c as it is helpful for showing what is and what is not portable, particularly
 7896: @c where it outlaws a style in common use.
 7897: 
 7898: @c anton: it's more important to show what's portable.  After we have done
 7899: @c that, we can also show what's not.  In any case, I have written a
 7900: @c section Compiling Words which also deals with [ ].
 7901: 
 7902: @code{[} and @code{]} also give you the ability to switch into compile
 7903: state and back, but we cannot think of any useful Standard application
 7904: for this ability. Pre-ANS Forth textbooks have examples like this:
 7905: 
 7906: @example
 7907: : AA ." this is A" ;
 7908: : BB ." this is B" ;
 7909: : CC ." this is C" ;
 7910: 
 7911: create table ] aa bb cc [
 7912: 
 7913: : go ( n -- ) \ n is offset into table.. 0 for 1st entry
 7914:   cells table + @ execute ;
 7915: @end example
 7916: 
 7917: This example builds a jump table; @code{0 go} will display ``@code{this
 7918: is A}''. Using @code{[} and @code{]} in this example is equivalent to
 7919: defining @code{table} like this:
 7920: 
 7921: @example
 7922: create table ' aa COMPILE, ' bb COMPILE, ' cc COMPILE,
 7923: @end example
 7924: 
 7925: The problem with this code is that the definition of @code{table} is not
 7926: portable -- it @i{compile}s execution tokens into code space. Whilst it
 7927: @i{may} work on systems where code space and data space co-incide, the
 7928: Standard only allows data space to be assigned for a @code{CREATE}d
 7929: word. In addition, the Standard only allows @code{@@} to access data
 7930: space, whilst this example is using it to access code space. The only
 7931: portable, Standard way to build this table is to build it in data space,
 7932: like this:
 7933: 
 7934: @example
 7935: create table ' aa , ' bb , ' cc ,
 7936: @end example
 7937: 
 7938: doc-state
 7939: 
 7940: 
 7941: @node Interpreter Directives,  , Interpret/Compile states, The Text Interpreter
 7942: @subsection Interpreter Directives
 7943: @cindex interpreter directives
 7944: @cindex conditional compilation
 7945: 
 7946: These words are usually used in interpret state; typically to control
 7947: which parts of a source file are processed by the text
 7948: interpreter. There are only a few ANS Forth Standard words, but Gforth
 7949: supplements these with a rich set of immediate control structure words
 7950: to compensate for the fact that the non-immediate versions can only be
 7951: used in compile state (@pxref{Control Structures}). Typical usages:
 7952: 
 7953: @example
 7954: FALSE Constant HAVE-ASSEMBLER
 7955: .
 7956: .
 7957: HAVE-ASSEMBLER [IF]
 7958: : ASSEMBLER-FEATURE
 7959:   ...
 7960: ;
 7961: [ENDIF]
 7962: .
 7963: .
 7964: : SEE
 7965:   ... \ general-purpose SEE code
 7966:   [ HAVE-ASSEMBLER [IF] ]
 7967:   ... \ assembler-specific SEE code
 7968:   [ [ENDIF] ]
 7969: ;
 7970: @end example
 7971: 
 7972: 
 7973: doc-[IF]
 7974: doc-[ELSE]
 7975: doc-[THEN]
 7976: doc-[ENDIF]
 7977: 
 7978: doc-[IFDEF]
 7979: doc-[IFUNDEF]
 7980: 
 7981: doc-[?DO]
 7982: doc-[DO]
 7983: doc-[FOR]
 7984: doc-[LOOP]
 7985: doc-[+LOOP]
 7986: doc-[NEXT]
 7987: 
 7988: doc-[BEGIN]
 7989: doc-[UNTIL]
 7990: doc-[AGAIN]
 7991: doc-[WHILE]
 7992: doc-[REPEAT]
 7993: 
 7994: 
 7995: @c -------------------------------------------------------------
 7996: @node Word Lists, Environmental Queries, The Text Interpreter, Words
 7997: @section Word Lists
 7998: @cindex word lists
 7999: @cindex header space
 8000: 
 8001: A wordlist is a list of named words; you can add new words and look up
 8002: words by name (and you can remove words in a restricted way with
 8003: markers).  Every named (and @code{reveal}ed) word is in one wordlist.
 8004: 
 8005: @cindex search order stack
 8006: The text interpreter searches the wordlists present in the search order
 8007: (a stack of wordlists), from the top to the bottom.  Within each
 8008: wordlist, the search starts conceptually at the newest word; i.e., if
 8009: two words in a wordlist have the same name, the newer word is found.
 8010: 
 8011: @cindex compilation word list
 8012: New words are added to the @dfn{compilation wordlist} (aka current
 8013: wordlist).
 8014: 
 8015: @cindex wid
 8016: A word list is identified by a cell-sized word list identifier (@i{wid})
 8017: in much the same way as a file is identified by a file handle. The
 8018: numerical value of the wid has no (portable) meaning, and might change
 8019: from session to session.
 8020: 
 8021: The ANS Forth ``Search order'' word set is intended to provide a set of
 8022: low-level tools that allow various different schemes to be
 8023: implemented. Gforth also provides @code{vocabulary}, a traditional Forth
 8024: word.  @file{compat/vocabulary.fs} provides an implementation in ANS
 8025: Forth.
 8026: 
 8027: @comment TODO: locals section refers to here, saying that every word list (aka
 8028: @comment vocabulary) has its own methods for searching etc. Need to document that.
 8029: @c anton: but better in a separate subsection on wordlist internals
 8030: 
 8031: @comment TODO: document markers, reveal, tables, mappedwordlist
 8032: 
 8033: @comment the gforthman- prefix is used to pick out the true definition of a
 8034: @comment word from the source files, rather than some alias.
 8035: 
 8036: doc-forth-wordlist
 8037: doc-definitions
 8038: doc-get-current
 8039: doc-set-current
 8040: doc-get-order
 8041: doc---gforthman-set-order
 8042: doc-wordlist
 8043: doc-table
 8044: doc->order
 8045: doc-previous
 8046: doc-also
 8047: doc---gforthman-forth
 8048: doc-only
 8049: doc---gforthman-order
 8050: 
 8051: doc-find
 8052: doc-search-wordlist
 8053: 
 8054: doc-words
 8055: doc-vlist
 8056: @c doc-words-deferred
 8057: 
 8058: @c doc-mappedwordlist @c map-structure undefined, implemantation-specific
 8059: doc-root
 8060: doc-vocabulary
 8061: doc-seal
 8062: doc-vocs
 8063: doc-current
 8064: doc-context
 8065: 
 8066: 
 8067: @menu
 8068: * Vocabularies::                
 8069: * Why use word lists?::         
 8070: * Word list example::           
 8071: @end menu
 8072: 
 8073: @node Vocabularies, Why use word lists?, Word Lists, Word Lists
 8074: @subsection Vocabularies
 8075: @cindex Vocabularies, detailed explanation
 8076: 
 8077: Here is an example of creating and using a new wordlist using ANS
 8078: Forth words:
 8079: 
 8080: @example
 8081: wordlist constant my-new-words-wordlist
 8082: : my-new-words get-order nip my-new-words-wordlist swap set-order ;
 8083: 
 8084: \ add it to the search order
 8085: also my-new-words
 8086: 
 8087: \ alternatively, add it to the search order and make it
 8088: \ the compilation word list
 8089: also my-new-words definitions
 8090: \ type "order" to see the problem
 8091: @end example
 8092: 
 8093: The problem with this example is that @code{order} has no way to
 8094: associate the name @code{my-new-words} with the wid of the word list (in
 8095: Gforth, @code{order} and @code{vocs} will display @code{???}  for a wid
 8096: that has no associated name). There is no Standard way of associating a
 8097: name with a wid.
 8098: 
 8099: In Gforth, this example can be re-coded using @code{vocabulary}, which
 8100: associates a name with a wid:
 8101: 
 8102: @example
 8103: vocabulary my-new-words
 8104: 
 8105: \ add it to the search order
 8106: also my-new-words
 8107: 
 8108: \ alternatively, add it to the search order and make it
 8109: \ the compilation word list
 8110: my-new-words definitions
 8111: \ type "order" to see that the problem is solved
 8112: @end example
 8113: 
 8114: 
 8115: @node Why use word lists?, Word list example, Vocabularies, Word Lists
 8116: @subsection Why use word lists?
 8117: @cindex word lists - why use them?
 8118: 
 8119: Here are some reasons why people use wordlists:
 8120: 
 8121: @itemize @bullet
 8122: 
 8123: @c anton: Gforth's hashing implementation makes the search speed
 8124: @c independent from the number of words.  But it is linear with the number
 8125: @c of wordlists that have to be searched, so in effect using more wordlists
 8126: @c actually slows down compilation.
 8127: 
 8128: @c @item
 8129: @c To improve compilation speed by reducing the number of header space
 8130: @c entries that must be searched. This is achieved by creating a new
 8131: @c word list that contains all of the definitions that are used in the
 8132: @c definition of a Forth system but which would not usually be used by
 8133: @c programs running on that system. That word list would be on the search
 8134: @c list when the Forth system was compiled but would be removed from the
 8135: @c search list for normal operation. This can be a useful technique for
 8136: @c low-performance systems (for example, 8-bit processors in embedded
 8137: @c systems) but is unlikely to be necessary in high-performance desktop
 8138: @c systems.
 8139: 
 8140: @item
 8141: To prevent a set of words from being used outside the context in which
 8142: they are valid. Two classic examples of this are an integrated editor
 8143: (all of the edit commands are defined in a separate word list; the
 8144: search order is set to the editor word list when the editor is invoked;
 8145: the old search order is restored when the editor is terminated) and an
 8146: integrated assembler (the op-codes for the machine are defined in a
 8147: separate word list which is used when a @code{CODE} word is defined).
 8148: 
 8149: @item
 8150: To organize the words of an application or library into a user-visible
 8151: set (in @code{forth-wordlist} or some other common wordlist) and a set
 8152: of helper words used just for the implementation (hidden in a separate
 8153: wordlist).  This keeps @code{words}' output smaller, separates
 8154: implementation and interface, and reduces the chance of name conflicts
 8155: within the common wordlist.
 8156: 
 8157: @item
 8158: To prevent a name-space clash between multiple definitions with the same
 8159: name. For example, when building a cross-compiler you might have a word
 8160: @code{IF} that generates conditional code for your target system. By
 8161: placing this definition in a different word list you can control whether
 8162: the host system's @code{IF} or the target system's @code{IF} get used in
 8163: any particular context by controlling the order of the word lists on the
 8164: search order stack.
 8165: 
 8166: @end itemize
 8167: 
 8168: The downsides of using wordlists are:
 8169: 
 8170: @itemize
 8171: 
 8172: @item
 8173: Debugging becomes more cumbersome.
 8174: 
 8175: @item
 8176: Name conflicts worked around with wordlists are still there, and you
 8177: have to arrange the search order carefully to get the desired results;
 8178: if you forget to do that, you get hard-to-find errors (as in any case
 8179: where you read the code differently from the compiler; @code{see} can
 8180: help seeing which of several possible words the name resolves to in such
 8181: cases).  @code{See} displays just the name of the words, not what
 8182: wordlist they belong to, so it might be misleading.  Using unique names
 8183: is a better approach to avoid name conflicts.
 8184: 
 8185: @item
 8186: You have to explicitly undo any changes to the search order.  In many
 8187: cases it would be more convenient if this happened implicitly.  Gforth
 8188: currently does not provide such a feature, but it may do so in the
 8189: future.
 8190: @end itemize
 8191: 
 8192: 
 8193: @node Word list example,  , Why use word lists?, Word Lists
 8194: @subsection Word list example
 8195: @cindex word lists - example
 8196: 
 8197: The following example is from the
 8198: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
 8199: garbage collector} and uses wordlists to separate public words from
 8200: helper words:
 8201: 
 8202: @example
 8203: get-current ( wid )
 8204: vocabulary garbage-collector also garbage-collector definitions
 8205: ... \ define helper words
 8206: ( wid ) set-current \ restore original (i.e., public) compilation wordlist
 8207: ... \ define the public (i.e., API) words
 8208:     \ they can refer to the helper words
 8209: previous \ restore original search order (helper words become invisible)
 8210: @end example
 8211: 
 8212: @c -------------------------------------------------------------
 8213: @node Environmental Queries, Files, Word Lists, Words
 8214: @section Environmental Queries
 8215: @cindex environmental queries
 8216: 
 8217: ANS Forth introduced the idea of ``environmental queries'' as a way
 8218: for a program running on a system to determine certain characteristics of the system.
 8219: The Standard specifies a number of strings that might be recognised by a system.
 8220: 
 8221: The Standard requires that the header space used for environmental queries
 8222: be distinct from the header space used for definitions.
 8223: 
 8224: Typically, environmental queries are supported by creating a set of
 8225: definitions in a word list that is @i{only} used during environmental
 8226: queries; that is what Gforth does. There is no Standard way of adding
 8227: definitions to the set of recognised environmental queries, but any
 8228: implementation that supports the loading of optional word sets must have
 8229: some mechanism for doing this (after loading the word set, the
 8230: associated environmental query string must return @code{true}). In
 8231: Gforth, the word list used to honour environmental queries can be
 8232: manipulated just like any other word list.
 8233: 
 8234: 
 8235: doc-environment?
 8236: doc-environment-wordlist
 8237: 
 8238: doc-gforth
 8239: doc-os-class
 8240: 
 8241: 
 8242: Note that, whilst the documentation for (e.g.) @code{gforth} shows it
 8243: returning two items on the stack, querying it using @code{environment?}
 8244: will return an additional item; the @code{true} flag that shows that the
 8245: string was recognised.
 8246: 
 8247: @comment TODO Document the standard strings or note where they are documented herein
 8248: 
 8249: Here are some examples of using environmental queries:
 8250: 
 8251: @example
 8252: s" address-unit-bits" environment? 0=
 8253: [IF]
 8254:      cr .( environmental attribute address-units-bits unknown... ) cr
 8255: [ELSE]
 8256:      drop \ ensure balanced stack effect
 8257: [THEN]
 8258: 
 8259: \ this might occur in the prelude of a standard program that uses THROW
 8260: s" exception" environment? [IF]
 8261:    0= [IF]
 8262:       : throw abort" exception thrown" ;
 8263:    [THEN]
 8264: [ELSE] \ we don't know, so make sure
 8265:    : throw abort" exception thrown" ;
 8266: [THEN]
 8267: 
 8268: s" gforth" environment? [IF] .( Gforth version ) TYPE
 8269:                         [ELSE] .( Not Gforth..) [THEN]
 8270: 
 8271: \ a program using v*
 8272: s" gforth" environment? [IF]
 8273:   s" 0.5.0" compare 0< [IF] \ v* is a primitive since 0.5.0
 8274:    : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
 8275:      >r swap 2swap swap 0e r> 0 ?DO
 8276:        dup f@ over + 2swap dup f@ f* f+ over + 2swap
 8277:      LOOP
 8278:      2drop 2drop ; 
 8279:   [THEN]
 8280: [ELSE] \ 
 8281:   : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
 8282:   ...
 8283: [THEN]
 8284: @end example
 8285: 
 8286: Here is an example of adding a definition to the environment word list:
 8287: 
 8288: @example
 8289: get-current environment-wordlist set-current
 8290: true constant block
 8291: true constant block-ext
 8292: set-current
 8293: @end example
 8294: 
 8295: You can see what definitions are in the environment word list like this:
 8296: 
 8297: @example
 8298: environment-wordlist >order words previous
 8299: @end example
 8300: 
 8301: 
 8302: @c -------------------------------------------------------------
 8303: @node Files, Blocks, Environmental Queries, Words
 8304: @section Files
 8305: @cindex files
 8306: @cindex I/O - file-handling
 8307: 
 8308: Gforth provides facilities for accessing files that are stored in the
 8309: host operating system's file-system. Files that are processed by Gforth
 8310: can be divided into two categories:
 8311: 
 8312: @itemize @bullet
 8313: @item
 8314: Files that are processed by the Text Interpreter (@dfn{Forth source files}).
 8315: @item
 8316: Files that are processed by some other program (@dfn{general files}).
 8317: @end itemize
 8318: 
 8319: @menu
 8320: * Forth source files::          
 8321: * General files::               
 8322: * Search Paths::                
 8323: @end menu
 8324: 
 8325: @c -------------------------------------------------------------
 8326: @node Forth source files, General files, Files, Files
 8327: @subsection Forth source files
 8328: @cindex including files
 8329: @cindex Forth source files
 8330: 
 8331: The simplest way to interpret the contents of a file is to use one of
 8332: these two formats:
 8333: 
 8334: @example
 8335: include mysource.fs
 8336: s" mysource.fs" included
 8337: @end example
 8338: 
 8339: You usually want to include a file only if it is not included already
 8340: (by, say, another source file). In that case, you can use one of these
 8341: three formats:
 8342: 
 8343: @example
 8344: require mysource.fs
 8345: needs mysource.fs
 8346: s" mysource.fs" required
 8347: @end example
 8348: 
 8349: @cindex stack effect of included files
 8350: @cindex including files, stack effect
 8351: It is good practice to write your source files such that interpreting them
 8352: does not change the stack. Source files designed in this way can be used with
 8353: @code{required} and friends without complications. For example:
 8354: 
 8355: @example
 8356: 1024 require foo.fs drop
 8357: @end example
 8358: 
 8359: Here you want to pass the argument 1024 (e.g., a buffer size) to
 8360: @file{foo.fs}.  Interpreting @file{foo.fs} has the stack effect ( n -- n
 8361: ), which allows its use with @code{require}.  Of course with such
 8362: parameters to required files, you have to ensure that the first
 8363: @code{require} fits for all uses (i.e., @code{require} it early in the
 8364: master load file).
 8365: 
 8366: doc-include-file
 8367: doc-included
 8368: doc-included?
 8369: doc-include
 8370: doc-required
 8371: doc-require
 8372: doc-needs
 8373: @c doc-init-included-files @c internal
 8374: @c doc-loadfilename @c internal word
 8375: doc-sourcefilename
 8376: doc-sourceline#
 8377: 
 8378: A definition in ANS Forth for @code{required} is provided in
 8379: @file{compat/required.fs}.
 8380: 
 8381: @c -------------------------------------------------------------
 8382: @node General files, Search Paths, Forth source files, Files
 8383: @subsection General files
 8384: @cindex general files
 8385: @cindex file-handling
 8386: 
 8387: Files are opened/created by name and type. The following file access
 8388: methods (FAMs) are recognised:
 8389: 
 8390: @cindex fam (file access method)
 8391: doc-r/o
 8392: doc-r/w
 8393: doc-w/o
 8394: doc-bin
 8395: 
 8396: 
 8397: When a file is opened/created, it returns a file identifier,
 8398: @i{wfileid} that is used for all other file commands. All file
 8399: commands also return a status value, @i{wior}, that is 0 for a
 8400: successful operation and an implementation-defined non-zero value in the
 8401: case of an error.
 8402: 
 8403: 
 8404: doc-open-file
 8405: doc-create-file
 8406: 
 8407: doc-close-file
 8408: doc-delete-file
 8409: doc-rename-file
 8410: doc-read-file
 8411: doc-read-line
 8412: doc-write-file
 8413: doc-write-line
 8414: doc-emit-file
 8415: doc-flush-file
 8416: 
 8417: doc-file-status
 8418: doc-file-position
 8419: doc-reposition-file
 8420: doc-file-size
 8421: doc-resize-file
 8422: 
 8423: 
 8424: @c ---------------------------------------------------------
 8425: @node Search Paths,  , General files, Files
 8426: @subsection Search Paths
 8427: @cindex path for @code{included}
 8428: @cindex file search path
 8429: @cindex @code{include} search path
 8430: @cindex search path for files
 8431: 
 8432: If you specify an absolute filename (i.e., a filename starting with
 8433: @file{/} or @file{~}, or with @file{:} in the second position (as in
 8434: @samp{C:...})) for @code{included} and friends, that file is included
 8435: just as you would expect.
 8436: 
 8437: If the filename starts with @file{./}, this refers to the directory that
 8438: the present file was @code{included} from.  This allows files to include
 8439: other files relative to their own position (irrespective of the current
 8440: working directory or the absolute position).  This feature is essential
 8441: for libraries consisting of several files, where a file may include
 8442: other files from the library.  It corresponds to @code{#include "..."}
 8443: in C. If the current input source is not a file, @file{.} refers to the
 8444: directory of the innermost file being included, or, if there is no file
 8445: being included, to the current working directory.
 8446: 
 8447: For relative filenames (not starting with @file{./}), Gforth uses a
 8448: search path similar to Forth's search order (@pxref{Word Lists}). It
 8449: tries to find the given filename in the directories present in the path,
 8450: and includes the first one it finds. There are separate search paths for
 8451: Forth source files and general files.  If the search path contains the
 8452: directory @file{.}, this refers to the directory of the current file, or
 8453: the working directory, as if the file had been specified with @file{./}.
 8454: 
 8455: Use @file{~+} to refer to the current working directory (as in the
 8456: @code{bash}).
 8457: 
 8458: @c anton: fold the following subsubsections into this subsection?
 8459: 
 8460: @menu
 8461: * Source Search Paths::         
 8462: * General Search Paths::        
 8463: @end menu
 8464: 
 8465: @c ---------------------------------------------------------
 8466: @node Source Search Paths, General Search Paths, Search Paths, Search Paths
 8467: @subsubsection Source Search Paths
 8468: @cindex search path control, source files
 8469: 
 8470: The search path is initialized when you start Gforth (@pxref{Invoking
 8471: Gforth}). You can display it and change it using @code{fpath} in
 8472: combination with the general path handling words.
 8473: 
 8474: doc-fpath
 8475: @c the functionality of the following words is easily available through
 8476: @c   fpath and the general path words.  The may go away.
 8477: @c doc-.fpath
 8478: @c doc-fpath+
 8479: @c doc-fpath=
 8480: @c doc-open-fpath-file
 8481: 
 8482: @noindent
 8483: Here is an example of using @code{fpath} and @code{require}:
 8484: 
 8485: @example
 8486: fpath path= /usr/lib/forth/|./
 8487: require timer.fs
 8488: @end example
 8489: 
 8490: 
 8491: @c ---------------------------------------------------------
 8492: @node General Search Paths,  , Source Search Paths, Search Paths
 8493: @subsubsection General Search Paths
 8494: @cindex search path control, source files
 8495: 
 8496: Your application may need to search files in several directories, like
 8497: @code{included} does. To facilitate this, Gforth allows you to define
 8498: and use your own search paths, by providing generic equivalents of the
 8499: Forth search path words:
 8500: 
 8501: doc-open-path-file
 8502: doc-path-allot
 8503: doc-clear-path
 8504: doc-also-path
 8505: doc-.path
 8506: doc-path+
 8507: doc-path=
 8508: 
 8509: @c anton: better define a word for it, say "path-allot ( ucount -- path-addr )
 8510: 
 8511: Here's an example of creating an empty search path:
 8512: @c
 8513: @example
 8514: create mypath 500 path-allot \ maximum length 500 chars (is checked)
 8515: @end example
 8516: 
 8517: @c -------------------------------------------------------------
 8518: @node Blocks, Other I/O, Files, Words
 8519: @section Blocks
 8520: @cindex I/O - blocks
 8521: @cindex blocks
 8522: 
 8523: When you run Gforth on a modern desk-top computer, it runs under the
 8524: control of an operating system which provides certain services.  One of
 8525: these services is @var{file services}, which allows Forth source code
 8526: and data to be stored in files and read into Gforth (@pxref{Files}).
 8527: 
 8528: Traditionally, Forth has been an important programming language on
 8529: systems where it has interfaced directly to the underlying hardware with
 8530: no intervening operating system. Forth provides a mechanism, called
 8531: @dfn{blocks}, for accessing mass storage on such systems.
 8532: 
 8533: A block is a 1024-byte data area, which can be used to hold data or
 8534: Forth source code. No structure is imposed on the contents of the
 8535: block. A block is identified by its number; blocks are numbered
 8536: contiguously from 1 to an implementation-defined maximum.
 8537: 
 8538: A typical system that used blocks but no operating system might use a
 8539: single floppy-disk drive for mass storage, with the disks formatted to
 8540: provide 256-byte sectors. Blocks would be implemented by assigning the
 8541: first four sectors of the disk to block 1, the second four sectors to
 8542: block 2 and so on, up to the limit of the capacity of the disk. The disk
 8543: would not contain any file system information, just the set of blocks.
 8544: 
 8545: @cindex blocks file
 8546: On systems that do provide file services, blocks are typically
 8547: implemented by storing a sequence of blocks within a single @dfn{blocks
 8548: file}.  The size of the blocks file will be an exact multiple of 1024
 8549: bytes, corresponding to the number of blocks it contains. This is the
 8550: mechanism that Gforth uses.
 8551: 
 8552: @cindex @file{blocks.fb}
 8553: Only one blocks file can be open at a time. If you use block words without
 8554: having specified a blocks file, Gforth defaults to the blocks file
 8555: @file{blocks.fb}. Gforth uses the Forth search path when attempting to
 8556: locate a blocks file (@pxref{Source Search Paths}).
 8557: 
 8558: @cindex block buffers
 8559: When you read and write blocks under program control, Gforth uses a
 8560: number of @dfn{block buffers} as intermediate storage. These buffers are
 8561: not used when you use @code{load} to interpret the contents of a block.
 8562: 
 8563: The behaviour of the block buffers is analagous to that of a cache.
 8564: Each block buffer has three states:
 8565: 
 8566: @itemize @bullet
 8567: @item
 8568: Unassigned
 8569: @item
 8570: Assigned-clean
 8571: @item
 8572: Assigned-dirty
 8573: @end itemize
 8574: 
 8575: Initially, all block buffers are @i{unassigned}. In order to access a
 8576: block, the block (specified by its block number) must be assigned to a
 8577: block buffer.
 8578: 
 8579: The assignment of a block to a block buffer is performed by @code{block}
 8580: or @code{buffer}. Use @code{block} when you wish to modify the existing
 8581: contents of a block. Use @code{buffer} when you don't care about the
 8582: existing contents of the block@footnote{The ANS Forth definition of
 8583: @code{buffer} is intended not to cause disk I/O; if the data associated
 8584: with the particular block is already stored in a block buffer due to an
 8585: earlier @code{block} command, @code{buffer} will return that block
 8586: buffer and the existing contents of the block will be
 8587: available. Otherwise, @code{buffer} will simply assign a new, empty
 8588: block buffer for the block.}.
 8589: 
 8590: Once a block has been assigned to a block buffer using @code{block} or
 8591: @code{buffer}, that block buffer becomes the @i{current block
 8592: buffer}. Data may only be manipulated (read or written) within the
 8593: current block buffer.
 8594: 
 8595: When the contents of the current block buffer has been modified it is
 8596: necessary, @emph{before calling @code{block} or @code{buffer} again}, to
 8597: either abandon the changes (by doing nothing) or mark the block as
 8598: changed (assigned-dirty), using @code{update}. Using @code{update} does
 8599: not change the blocks file; it simply changes a block buffer's state to
 8600: @i{assigned-dirty}.  The block will be written implicitly when it's
 8601: buffer is needed for another block, or explicitly by @code{flush} or
 8602: @code{save-buffers}.
 8603: 
 8604: word @code{Flush} writes all @i{assigned-dirty} blocks back to the
 8605: blocks file on disk. Leaving Gforth with @code{bye} also performs a
 8606: @code{flush}.
 8607: 
 8608: In Gforth, @code{block} and @code{buffer} use a @i{direct-mapped}
 8609: algorithm to assign a block buffer to a block. That means that any
 8610: particular block can only be assigned to one specific block buffer,
 8611: called (for the particular operation) the @i{victim buffer}. If the
 8612: victim buffer is @i{unassigned} or @i{assigned-clean} it is allocated to
 8613: the new block immediately. If it is @i{assigned-dirty} its current
 8614: contents are written back to the blocks file on disk before it is
 8615: allocated to the new block.
 8616: 
 8617: Although no structure is imposed on the contents of a block, it is
 8618: traditional to display the contents as 16 lines each of 64 characters.  A
 8619: block provides a single, continuous stream of input (for example, it
 8620: acts as a single parse area) -- there are no end-of-line characters
 8621: within a block, and no end-of-file character at the end of a
 8622: block. There are two consequences of this:
 8623: 
 8624: @itemize @bullet
 8625: @item
 8626: The last character of one line wraps straight into the first character
 8627: of the following line
 8628: @item
 8629: The word @code{\} -- comment to end of line -- requires special
 8630: treatment; in the context of a block it causes all characters until the
 8631: end of the current 64-character ``line'' to be ignored.
 8632: @end itemize
 8633: 
 8634: In Gforth, when you use @code{block} with a non-existent block number,
 8635: the current blocks file will be extended to the appropriate size and the
 8636: block buffer will be initialised with spaces.
 8637: 
 8638: Gforth includes a simple block editor (type @code{use blocked.fb 0 list}
 8639: for details) but doesn't encourage the use of blocks; the mechanism is
 8640: only provided for backward compatibility -- ANS Forth requires blocks to
 8641: be available when files are.
 8642: 
 8643: Common techniques that are used when working with blocks include:
 8644: 
 8645: @itemize @bullet
 8646: @item
 8647: A screen editor that allows you to edit blocks without leaving the Forth
 8648: environment.
 8649: @item
 8650: Shadow screens; where every code block has an associated block
 8651: containing comments (for example: code in odd block numbers, comments in
 8652: even block numbers). Typically, the block editor provides a convenient
 8653: mechanism to toggle between code and comments.
 8654: @item
 8655: Load blocks; a single block (typically block 1) contains a number of
 8656: @code{thru} commands which @code{load} the whole of the application.
 8657: @end itemize
 8658: 
 8659: See Frank Sergeant's Pygmy Forth to see just how well blocks can be
 8660: integrated into a Forth programming environment.
 8661: 
 8662: @comment TODO what about errors on open-blocks?
 8663: 
 8664: doc-open-blocks
 8665: doc-use
 8666: doc-block-offset
 8667: doc-get-block-fid
 8668: doc-block-position
 8669: 
 8670: doc-list
 8671: doc-scr
 8672: 
 8673: doc---gforthman-block
 8674: doc-buffer
 8675: 
 8676: doc-empty-buffers
 8677: doc-empty-buffer
 8678: doc-update
 8679: doc-updated?
 8680: doc-save-buffers
 8681: doc-save-buffer
 8682: doc-flush
 8683: 
 8684: doc-load
 8685: doc-thru
 8686: doc-+load
 8687: doc-+thru
 8688: doc---gforthman--->
 8689: doc-block-included
 8690: 
 8691: 
 8692: @c -------------------------------------------------------------
 8693: @node Other I/O, Locals, Blocks, Words
 8694: @section Other I/O
 8695: @cindex I/O - keyboard and display
 8696: 
 8697: @menu
 8698: * Simple numeric output::       Predefined formats
 8699: * Formatted numeric output::    Formatted (pictured) output
 8700: * String Formats::              How Forth stores strings in memory
 8701: * Displaying characters and strings::  Other stuff
 8702: * Input::                       Input
 8703: @end menu
 8704: 
 8705: @node Simple numeric output, Formatted numeric output, Other I/O, Other I/O
 8706: @subsection Simple numeric output
 8707: @cindex numeric output - simple/free-format
 8708: 
 8709: The simplest output functions are those that display numbers from the
 8710: data or floating-point stacks. Floating-point output is always displayed
 8711: using base 10. Numbers displayed from the data stack use the value stored
 8712: in @code{base}.
 8713: 
 8714: 
 8715: doc-.
 8716: doc-dec.
 8717: doc-hex.
 8718: doc-u.
 8719: doc-.r
 8720: doc-u.r
 8721: doc-d.
 8722: doc-ud.
 8723: doc-d.r
 8724: doc-ud.r
 8725: doc-f.
 8726: doc-fe.
 8727: doc-fs.
 8728: 
 8729: 
 8730: Examples of printing the number 1234.5678E23 in the different floating-point output
 8731: formats are shown below:
 8732: 
 8733: @example
 8734: f. 123456779999999000000000000.
 8735: fe. 123.456779999999E24
 8736: fs. 1.23456779999999E26
 8737: @end example
 8738: 
 8739: 
 8740: @node Formatted numeric output, String Formats, Simple numeric output, Other I/O
 8741: @subsection Formatted numeric output
 8742: @cindex formatted numeric output
 8743: @cindex pictured numeric output
 8744: @cindex numeric output - formatted
 8745: 
 8746: Forth traditionally uses a technique called @dfn{pictured numeric
 8747: output} for formatted printing of integers.  In this technique, digits
 8748: are extracted from the number (using the current output radix defined by
 8749: @code{base}), converted to ASCII codes and appended to a string that is
 8750: built in a scratch-pad area of memory (@pxref{core-idef,
 8751: Implementation-defined options, Implementation-defined
 8752: options}). Arbitrary characters can be appended to the string during the
 8753: extraction process. The completed string is specified by an address
 8754: and length and can be manipulated (@code{TYPE}ed, copied, modified)
 8755: under program control.
 8756: 
 8757: All of the integer output words described in the previous section
 8758: (@pxref{Simple numeric output}) are implemented in Gforth using pictured
 8759: numeric output.
 8760: 
 8761: Three important things to remember about pictured numeric output:
 8762: 
 8763: @itemize @bullet
 8764: @item
 8765: It always operates on double-precision numbers; to display a
 8766: single-precision number, convert it first (for ways of doing this
 8767: @pxref{Double precision}).
 8768: @item
 8769: It always treats the double-precision number as though it were
 8770: unsigned. The examples below show ways of printing signed numbers.
 8771: @item
 8772: The string is built up from right to left; least significant digit first.
 8773: @end itemize
 8774: 
 8775: 
 8776: doc-<#
 8777: doc-<<#
 8778: doc-#
 8779: doc-#s
 8780: doc-hold
 8781: doc-sign
 8782: doc-#>
 8783: doc-#>>
 8784: 
 8785: doc-represent
 8786: 
 8787: 
 8788: @noindent
 8789: Here are some examples of using pictured numeric output:
 8790: 
 8791: @example
 8792: : my-u. ( u -- )
 8793:   \ Simplest use of pns.. behaves like Standard u. 
 8794:   0              \ convert to unsigned double
 8795:   <<#            \ start conversion
 8796:   #s             \ convert all digits
 8797:   #>             \ complete conversion
 8798:   TYPE SPACE     \ display, with trailing space
 8799:   #>> ;          \ release hold area
 8800: 
 8801: : cents-only ( u -- )
 8802:   0              \ convert to unsigned double
 8803:   <<#            \ start conversion
 8804:   # #            \ convert two least-significant digits
 8805:   #>             \ complete conversion, discard other digits
 8806:   TYPE SPACE     \ display, with trailing space
 8807:   #>> ;          \ release hold area
 8808: 
 8809: : dollars-and-cents ( u -- )
 8810:   0              \ convert to unsigned double
 8811:   <<#            \ start conversion
 8812:   # #            \ convert two least-significant digits
 8813:   [char] . hold  \ insert decimal point
 8814:   #s             \ convert remaining digits
 8815:   [char] $ hold  \ append currency symbol
 8816:   #>             \ complete conversion
 8817:   TYPE SPACE     \ display, with trailing space
 8818:   #>> ;          \ release hold area
 8819: 
 8820: : my-. ( n -- )
 8821:   \ handling negatives.. behaves like Standard .
 8822:   s>d            \ convert to signed double
 8823:   swap over dabs \ leave sign byte followed by unsigned double
 8824:   <<#            \ start conversion
 8825:   #s             \ convert all digits
 8826:   rot sign       \ get at sign byte, append "-" if needed
 8827:   #>             \ complete conversion
 8828:   TYPE SPACE     \ display, with trailing space
 8829:   #>> ;          \ release hold area
 8830: 
 8831: : account. ( n -- )
 8832:   \ accountants don't like minus signs, they use parentheses
 8833:   \ for negative numbers
 8834:   s>d            \ convert to signed double
 8835:   swap over dabs \ leave sign byte followed by unsigned double
 8836:   <<#            \ start conversion
 8837:   2 pick         \ get copy of sign byte
 8838:   0< IF [char] ) hold THEN \ right-most character of output
 8839:   #s             \ convert all digits
 8840:   rot            \ get at sign byte
 8841:   0< IF [char] ( hold THEN
 8842:   #>             \ complete conversion
 8843:   TYPE SPACE     \ display, with trailing space
 8844:   #>> ;          \ release hold area
 8845: 
 8846: @end example
 8847: 
 8848: Here are some examples of using these words:
 8849: 
 8850: @example
 8851: 1 my-u. 1
 8852: hex -1 my-u. decimal FFFFFFFF
 8853: 1 cents-only 01
 8854: 1234 cents-only 34
 8855: 2 dollars-and-cents $0.02
 8856: 1234 dollars-and-cents $12.34
 8857: 123 my-. 123
 8858: -123 my. -123
 8859: 123 account. 123
 8860: -456 account. (456)
 8861: @end example
 8862: 
 8863: 
 8864: @node String Formats, Displaying characters and strings, Formatted numeric output, Other I/O
 8865: @subsection String Formats
 8866: @cindex strings - see character strings
 8867: @cindex character strings - formats
 8868: @cindex I/O - see character strings
 8869: @cindex counted strings
 8870: 
 8871: @c anton: this does not really belong here; maybe the memory section,
 8872: @c  or the principles chapter
 8873: 
 8874: Forth commonly uses two different methods for representing character
 8875: strings:
 8876: 
 8877: @itemize @bullet
 8878: @item
 8879: @cindex address of counted string
 8880: @cindex counted string
 8881: As a @dfn{counted string}, represented by a @i{c-addr}. The char
 8882: addressed by @i{c-addr} contains a character-count, @i{n}, of the
 8883: string and the string occupies the subsequent @i{n} char addresses in
 8884: memory.
 8885: @item
 8886: As cell pair on the stack; @i{c-addr u}, where @i{u} is the length
 8887: of the string in characters, and @i{c-addr} is the address of the
 8888: first byte of the string.
 8889: @end itemize
 8890: 
 8891: ANS Forth encourages the use of the second format when representing
 8892: strings.
 8893: 
 8894: 
 8895: doc-count
 8896: 
 8897: 
 8898: For words that move, copy and search for strings see @ref{Memory
 8899: Blocks}. For words that display characters and strings see
 8900: @ref{Displaying characters and strings}.
 8901: 
 8902: @node Displaying characters and strings, Input, String Formats, Other I/O
 8903: @subsection Displaying characters and strings
 8904: @cindex characters - compiling and displaying
 8905: @cindex character strings - compiling and displaying
 8906: 
 8907: This section starts with a glossary of Forth words and ends with a set
 8908: of examples.
 8909: 
 8910: 
 8911: doc-bl
 8912: doc-space
 8913: doc-spaces
 8914: doc-emit
 8915: doc-toupper
 8916: doc-."
 8917: doc-.(
 8918: doc-type
 8919: doc-typewhite
 8920: doc-cr
 8921: @cindex cursor control
 8922: doc-at-xy
 8923: doc-page
 8924: doc-s"
 8925: doc-c"
 8926: doc-char
 8927: doc-[char]
 8928: 
 8929: 
 8930: @noindent
 8931: As an example, consider the following text, stored in a file @file{test.fs}:
 8932: 
 8933: @example
 8934: .( text-1)
 8935: : my-word
 8936:   ." text-2" cr
 8937:   .( text-3)
 8938: ;
 8939: 
 8940: ." text-4"
 8941: 
 8942: : my-char
 8943:   [char] ALPHABET emit
 8944:   char emit
 8945: ;
 8946: @end example
 8947: 
 8948: When you load this code into Gforth, the following output is generated:
 8949: 
 8950: @example
 8951: @kbd{include test.fs @key{RET}} text-1text-3text-4 ok
 8952: @end example
 8953: 
 8954: @itemize @bullet
 8955: @item
 8956: Messages @code{text-1} and @code{text-3} are displayed because @code{.(} 
 8957: is an immediate word; it behaves in the same way whether it is used inside
 8958: or outside a colon definition.
 8959: @item
 8960: Message @code{text-4} is displayed because of Gforth's added interpretation
 8961: semantics for @code{."}.
 8962: @item
 8963: Message @code{text-2} is @i{not} displayed, because the text interpreter
 8964: performs the compilation semantics for @code{."} within the definition of
 8965: @code{my-word}.
 8966: @end itemize
 8967: 
 8968: Here are some examples of executing @code{my-word} and @code{my-char}:
 8969: 
 8970: @example
 8971: @kbd{my-word @key{RET}} text-2
 8972:  ok
 8973: @kbd{my-char fred @key{RET}} Af ok
 8974: @kbd{my-char jim @key{RET}} Aj ok
 8975: @end example
 8976: 
 8977: @itemize @bullet
 8978: @item
 8979: Message @code{text-2} is displayed because of the run-time behaviour of
 8980: @code{."}.
 8981: @item
 8982: @code{[char]} compiles the ``A'' from ``ALPHABET'' and puts its display code
 8983: on the stack at run-time. @code{emit} always displays the character
 8984: when @code{my-char} is executed.
 8985: @item
 8986: @code{char} parses a string at run-time and the second @code{emit} displays
 8987: the first character of the string.
 8988: @item
 8989: If you type @code{see my-char} you can see that @code{[char]} discarded
 8990: the text ``LPHABET'' and only compiled the display code for ``A'' into the
 8991: definition of @code{my-char}.
 8992: @end itemize
 8993: 
 8994: 
 8995: 
 8996: @node Input,  , Displaying characters and strings, Other I/O
 8997: @subsection Input
 8998: @cindex input
 8999: @cindex I/O - see input
 9000: @cindex parsing a string
 9001: 
 9002: For ways of storing character strings in memory see @ref{String Formats}.
 9003: 
 9004: @comment TODO examples for >number >float accept key key? pad parse word refill
 9005: @comment then index them
 9006: 
 9007: 
 9008: doc-key
 9009: doc-key?
 9010: doc-ekey
 9011: doc-ekey?
 9012: doc-ekey>char
 9013: doc->number
 9014: doc->float
 9015: doc-accept
 9016: doc-pad
 9017: @c anton: these belong in the input stream section
 9018: doc-parse
 9019: doc-word
 9020: doc-sword
 9021: doc-name
 9022: doc-refill
 9023: @comment obsolescent words..
 9024: doc-convert
 9025: doc-query
 9026: doc-expect
 9027: doc-span
 9028: 
 9029: 
 9030: @c -------------------------------------------------------------
 9031: @node Locals, Structures, Other I/O, Words
 9032: @section Locals
 9033: @cindex locals
 9034: 
 9035: Local variables can make Forth programming more enjoyable and Forth
 9036: programs easier to read. Unfortunately, the locals of ANS Forth are
 9037: laden with restrictions. Therefore, we provide not only the ANS Forth
 9038: locals wordset, but also our own, more powerful locals wordset (we
 9039: implemented the ANS Forth locals wordset through our locals wordset).
 9040: 
 9041: The ideas in this section have also been published in M. Anton Ertl,
 9042: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl94l.ps.gz,
 9043: Automatic Scoping of Local Variables}}, EuroForth '94.
 9044: 
 9045: @menu
 9046: * Gforth locals::               
 9047: * ANS Forth locals::            
 9048: @end menu
 9049: 
 9050: @node Gforth locals, ANS Forth locals, Locals, Locals
 9051: @subsection Gforth locals
 9052: @cindex Gforth locals
 9053: @cindex locals, Gforth style
 9054: 
 9055: Locals can be defined with
 9056: 
 9057: @example
 9058: @{ local1 local2 ... -- comment @}
 9059: @end example
 9060: or
 9061: @example
 9062: @{ local1 local2 ... @}
 9063: @end example
 9064: 
 9065: E.g.,
 9066: @example
 9067: : max @{ n1 n2 -- n3 @}
 9068:  n1 n2 > if
 9069:    n1
 9070:  else
 9071:    n2
 9072:  endif ;
 9073: @end example
 9074: 
 9075: The similarity of locals definitions with stack comments is intended. A
 9076: locals definition often replaces the stack comment of a word. The order
 9077: of the locals corresponds to the order in a stack comment and everything
 9078: after the @code{--} is really a comment.
 9079: 
 9080: This similarity has one disadvantage: It is too easy to confuse locals
 9081: declarations with stack comments, causing bugs and making them hard to
 9082: find. However, this problem can be avoided by appropriate coding
 9083: conventions: Do not use both notations in the same program. If you do,
 9084: they should be distinguished using additional means, e.g. by position.
 9085: 
 9086: @cindex types of locals
 9087: @cindex locals types
 9088: The name of the local may be preceded by a type specifier, e.g.,
 9089: @code{F:} for a floating point value:
 9090: 
 9091: @example
 9092: : CX* @{ F: Ar F: Ai F: Br F: Bi -- Cr Ci @}
 9093: \ complex multiplication
 9094:  Ar Br f* Ai Bi f* f-
 9095:  Ar Bi f* Ai Br f* f+ ;
 9096: @end example
 9097: 
 9098: @cindex flavours of locals
 9099: @cindex locals flavours
 9100: @cindex value-flavoured locals
 9101: @cindex variable-flavoured locals
 9102: Gforth currently supports cells (@code{W:}, @code{W^}), doubles
 9103: (@code{D:}, @code{D^}), floats (@code{F:}, @code{F^}) and characters
 9104: (@code{C:}, @code{C^}) in two flavours: a value-flavoured local (defined
 9105: with @code{W:}, @code{D:} etc.) produces its value and can be changed
 9106: with @code{TO}. A variable-flavoured local (defined with @code{W^} etc.)
 9107: produces its address (which becomes invalid when the variable's scope is
 9108: left). E.g., the standard word @code{emit} can be defined in terms of
 9109: @code{type} like this:
 9110: 
 9111: @example
 9112: : emit @{ C^ char* -- @}
 9113:     char* 1 type ;
 9114: @end example
 9115: 
 9116: @cindex default type of locals
 9117: @cindex locals, default type
 9118: A local without type specifier is a @code{W:} local. Both flavours of
 9119: locals are initialized with values from the data or FP stack.
 9120: 
 9121: Currently there is no way to define locals with user-defined data
 9122: structures, but we are working on it.
 9123: 
 9124: Gforth allows defining locals everywhere in a colon definition. This
 9125: poses the following questions:
 9126: 
 9127: @menu
 9128: * Where are locals visible by name?::  
 9129: * How long do locals live?::    
 9130: * Locals programming style::    
 9131: * Locals implementation::       
 9132: @end menu
 9133: 
 9134: @node Where are locals visible by name?, How long do locals live?, Gforth locals, Gforth locals
 9135: @subsubsection Where are locals visible by name?
 9136: @cindex locals visibility
 9137: @cindex visibility of locals
 9138: @cindex scope of locals
 9139: 
 9140: Basically, the answer is that locals are visible where you would expect
 9141: it in block-structured languages, and sometimes a little longer. If you
 9142: want to restrict the scope of a local, enclose its definition in
 9143: @code{SCOPE}...@code{ENDSCOPE}.
 9144: 
 9145: 
 9146: doc-scope
 9147: doc-endscope
 9148: 
 9149: 
 9150: These words behave like control structure words, so you can use them
 9151: with @code{CS-PICK} and @code{CS-ROLL} to restrict the scope in
 9152: arbitrary ways.
 9153: 
 9154: If you want a more exact answer to the visibility question, here's the
 9155: basic principle: A local is visible in all places that can only be
 9156: reached through the definition of the local@footnote{In compiler
 9157: construction terminology, all places dominated by the definition of the
 9158: local.}. In other words, it is not visible in places that can be reached
 9159: without going through the definition of the local. E.g., locals defined
 9160: in @code{IF}...@code{ENDIF} are visible until the @code{ENDIF}, locals
 9161: defined in @code{BEGIN}...@code{UNTIL} are visible after the
 9162: @code{UNTIL} (until, e.g., a subsequent @code{ENDSCOPE}).
 9163: 
 9164: The reasoning behind this solution is: We want to have the locals
 9165: visible as long as it is meaningful. The user can always make the
 9166: visibility shorter by using explicit scoping. In a place that can
 9167: only be reached through the definition of a local, the meaning of a
 9168: local name is clear. In other places it is not: How is the local
 9169: initialized at the control flow path that does not contain the
 9170: definition? Which local is meant, if the same name is defined twice in
 9171: two independent control flow paths?
 9172: 
 9173: This should be enough detail for nearly all users, so you can skip the
 9174: rest of this section. If you really must know all the gory details and
 9175: options, read on.
 9176: 
 9177: In order to implement this rule, the compiler has to know which places
 9178: are unreachable. It knows this automatically after @code{AHEAD},
 9179: @code{AGAIN}, @code{EXIT} and @code{LEAVE}; in other cases (e.g., after
 9180: most @code{THROW}s), you can use the word @code{UNREACHABLE} to tell the
 9181: compiler that the control flow never reaches that place. If
 9182: @code{UNREACHABLE} is not used where it could, the only consequence is
 9183: that the visibility of some locals is more limited than the rule above
 9184: says. If @code{UNREACHABLE} is used where it should not (i.e., if you
 9185: lie to the compiler), buggy code will be produced.
 9186: 
 9187: 
 9188: doc-unreachable
 9189: 
 9190: 
 9191: Another problem with this rule is that at @code{BEGIN}, the compiler
 9192: does not know which locals will be visible on the incoming
 9193: back-edge. All problems discussed in the following are due to this
 9194: ignorance of the compiler (we discuss the problems using @code{BEGIN}
 9195: loops as examples; the discussion also applies to @code{?DO} and other
 9196: loops). Perhaps the most insidious example is:
 9197: @example
 9198: AHEAD
 9199: BEGIN
 9200:   x
 9201: [ 1 CS-ROLL ] THEN
 9202:   @{ x @}
 9203:   ...
 9204: UNTIL
 9205: @end example
 9206: 
 9207: This should be legal according to the visibility rule. The use of
 9208: @code{x} can only be reached through the definition; but that appears
 9209: textually below the use.
 9210: 
 9211: From this example it is clear that the visibility rules cannot be fully
 9212: implemented without major headaches. Our implementation treats common
 9213: cases as advertised and the exceptions are treated in a safe way: The
 9214: compiler makes a reasonable guess about the locals visible after a
 9215: @code{BEGIN}; if it is too pessimistic, the
 9216: user will get a spurious error about the local not being defined; if the
 9217: compiler is too optimistic, it will notice this later and issue a
 9218: warning. In the case above the compiler would complain about @code{x}
 9219: being undefined at its use. You can see from the obscure examples in
 9220: this section that it takes quite unusual control structures to get the
 9221: compiler into trouble, and even then it will often do fine.
 9222: 
 9223: If the @code{BEGIN} is reachable from above, the most optimistic guess
 9224: is that all locals visible before the @code{BEGIN} will also be
 9225: visible after the @code{BEGIN}. This guess is valid for all loops that
 9226: are entered only through the @code{BEGIN}, in particular, for normal
 9227: @code{BEGIN}...@code{WHILE}...@code{REPEAT} and
 9228: @code{BEGIN}...@code{UNTIL} loops and it is implemented in our
 9229: compiler. When the branch to the @code{BEGIN} is finally generated by
 9230: @code{AGAIN} or @code{UNTIL}, the compiler checks the guess and
 9231: warns the user if it was too optimistic:
 9232: @example
 9233: IF
 9234:   @{ x @}
 9235: BEGIN
 9236:   \ x ? 
 9237: [ 1 cs-roll ] THEN
 9238:   ...
 9239: UNTIL
 9240: @end example
 9241: 
 9242: Here, @code{x} lives only until the @code{BEGIN}, but the compiler
 9243: optimistically assumes that it lives until the @code{THEN}. It notices
 9244: this difference when it compiles the @code{UNTIL} and issues a
 9245: warning. The user can avoid the warning, and make sure that @code{x}
 9246: is not used in the wrong area by using explicit scoping:
 9247: @example
 9248: IF
 9249:   SCOPE
 9250:   @{ x @}
 9251:   ENDSCOPE
 9252: BEGIN
 9253: [ 1 cs-roll ] THEN
 9254:   ...
 9255: UNTIL
 9256: @end example
 9257: 
 9258: Since the guess is optimistic, there will be no spurious error messages
 9259: about undefined locals.
 9260: 
 9261: If the @code{BEGIN} is not reachable from above (e.g., after
 9262: @code{AHEAD} or @code{EXIT}), the compiler cannot even make an
 9263: optimistic guess, as the locals visible after the @code{BEGIN} may be
 9264: defined later. Therefore, the compiler assumes that no locals are
 9265: visible after the @code{BEGIN}. However, the user can use
 9266: @code{ASSUME-LIVE} to make the compiler assume that the same locals are
 9267: visible at the BEGIN as at the point where the top control-flow stack
 9268: item was created.
 9269: 
 9270: 
 9271: doc-assume-live
 9272: 
 9273: 
 9274: @noindent
 9275: E.g.,
 9276: @example
 9277: @{ x @}
 9278: AHEAD
 9279: ASSUME-LIVE
 9280: BEGIN
 9281:   x
 9282: [ 1 CS-ROLL ] THEN
 9283:   ...
 9284: UNTIL
 9285: @end example
 9286: 
 9287: Other cases where the locals are defined before the @code{BEGIN} can be
 9288: handled by inserting an appropriate @code{CS-ROLL} before the
 9289: @code{ASSUME-LIVE} (and changing the control-flow stack manipulation
 9290: behind the @code{ASSUME-LIVE}).
 9291: 
 9292: Cases where locals are defined after the @code{BEGIN} (but should be
 9293: visible immediately after the @code{BEGIN}) can only be handled by
 9294: rearranging the loop. E.g., the ``most insidious'' example above can be
 9295: arranged into:
 9296: @example
 9297: BEGIN
 9298:   @{ x @}
 9299:   ... 0=
 9300: WHILE
 9301:   x
 9302: REPEAT
 9303: @end example
 9304: 
 9305: @node How long do locals live?, Locals programming style, Where are locals visible by name?, Gforth locals
 9306: @subsubsection How long do locals live?
 9307: @cindex locals lifetime
 9308: @cindex lifetime of locals
 9309: 
 9310: The right answer for the lifetime question would be: A local lives at
 9311: least as long as it can be accessed. For a value-flavoured local this
 9312: means: until the end of its visibility. However, a variable-flavoured
 9313: local could be accessed through its address far beyond its visibility
 9314: scope. Ultimately, this would mean that such locals would have to be
 9315: garbage collected. Since this entails un-Forth-like implementation
 9316: complexities, I adopted the same cowardly solution as some other
 9317: languages (e.g., C): The local lives only as long as it is visible;
 9318: afterwards its address is invalid (and programs that access it
 9319: afterwards are erroneous).
 9320: 
 9321: @node Locals programming style, Locals implementation, How long do locals live?, Gforth locals
 9322: @subsubsection Locals programming style
 9323: @cindex locals programming style
 9324: @cindex programming style, locals
 9325: 
 9326: The freedom to define locals anywhere has the potential to change
 9327: programming styles dramatically. In particular, the need to use the
 9328: return stack for intermediate storage vanishes. Moreover, all stack
 9329: manipulations (except @code{PICK}s and @code{ROLL}s with run-time
 9330: determined arguments) can be eliminated: If the stack items are in the
 9331: wrong order, just write a locals definition for all of them; then
 9332: write the items in the order you want.
 9333: 
 9334: This seems a little far-fetched and eliminating stack manipulations is
 9335: unlikely to become a conscious programming objective. Still, the number
 9336: of stack manipulations will be reduced dramatically if local variables
 9337: are used liberally (e.g., compare @code{max} (@pxref{Gforth locals}) with
 9338: a traditional implementation of @code{max}).
 9339: 
 9340: This shows one potential benefit of locals: making Forth programs more
 9341: readable. Of course, this benefit will only be realized if the
 9342: programmers continue to honour the principle of factoring instead of
 9343: using the added latitude to make the words longer.
 9344: 
 9345: @cindex single-assignment style for locals
 9346: Using @code{TO} can and should be avoided.  Without @code{TO},
 9347: every value-flavoured local has only a single assignment and many
 9348: advantages of functional languages apply to Forth. I.e., programs are
 9349: easier to analyse, to optimize and to read: It is clear from the
 9350: definition what the local stands for, it does not turn into something
 9351: different later.
 9352: 
 9353: E.g., a definition using @code{TO} might look like this:
 9354: @example
 9355: : strcmp @{ addr1 u1 addr2 u2 -- n @}
 9356:  u1 u2 min 0
 9357:  ?do
 9358:    addr1 c@@ addr2 c@@ -
 9359:    ?dup-if
 9360:      unloop exit
 9361:    then
 9362:    addr1 char+ TO addr1
 9363:    addr2 char+ TO addr2
 9364:  loop
 9365:  u1 u2 - ;
 9366: @end example
 9367: Here, @code{TO} is used to update @code{addr1} and @code{addr2} at
 9368: every loop iteration. @code{strcmp} is a typical example of the
 9369: readability problems of using @code{TO}. When you start reading
 9370: @code{strcmp}, you think that @code{addr1} refers to the start of the
 9371: string. Only near the end of the loop you realize that it is something
 9372: else.
 9373: 
 9374: This can be avoided by defining two locals at the start of the loop that
 9375: are initialized with the right value for the current iteration.
 9376: @example
 9377: : strcmp @{ addr1 u1 addr2 u2 -- n @}
 9378:  addr1 addr2
 9379:  u1 u2 min 0 
 9380:  ?do @{ s1 s2 @}
 9381:    s1 c@@ s2 c@@ -
 9382:    ?dup-if
 9383:      unloop exit
 9384:    then
 9385:    s1 char+ s2 char+
 9386:  loop
 9387:  2drop
 9388:  u1 u2 - ;
 9389: @end example
 9390: Here it is clear from the start that @code{s1} has a different value
 9391: in every loop iteration.
 9392: 
 9393: @node Locals implementation,  , Locals programming style, Gforth locals
 9394: @subsubsection Locals implementation
 9395: @cindex locals implementation
 9396: @cindex implementation of locals
 9397: 
 9398: @cindex locals stack
 9399: Gforth uses an extra locals stack. The most compelling reason for
 9400: this is that the return stack is not float-aligned; using an extra stack
 9401: also eliminates the problems and restrictions of using the return stack
 9402: as locals stack. Like the other stacks, the locals stack grows toward
 9403: lower addresses. A few primitives allow an efficient implementation:
 9404: 
 9405: 
 9406: doc-@local#
 9407: doc-f@local#
 9408: doc-laddr#
 9409: doc-lp+!#
 9410: doc-lp!
 9411: doc->l
 9412: doc-f>l
 9413: 
 9414: 
 9415: In addition to these primitives, some specializations of these
 9416: primitives for commonly occurring inline arguments are provided for
 9417: efficiency reasons, e.g., @code{@@local0} as specialization of
 9418: @code{@@local#} for the inline argument 0. The following compiling words
 9419: compile the right specialized version, or the general version, as
 9420: appropriate:
 9421: 
 9422: 
 9423: doc-compile-@local
 9424: doc-compile-f@local
 9425: doc-compile-lp+!
 9426: 
 9427: 
 9428: Combinations of conditional branches and @code{lp+!#} like
 9429: @code{?branch-lp+!#} (the locals pointer is only changed if the branch
 9430: is taken) are provided for efficiency and correctness in loops.
 9431: 
 9432: A special area in the dictionary space is reserved for keeping the
 9433: local variable names. @code{@{} switches the dictionary pointer to this
 9434: area and @code{@}} switches it back and generates the locals
 9435: initializing code. @code{W:} etc.@ are normal defining words. This
 9436: special area is cleared at the start of every colon definition.
 9437: 
 9438: @cindex word list for defining locals
 9439: A special feature of Gforth's dictionary is used to implement the
 9440: definition of locals without type specifiers: every word list (aka
 9441: vocabulary) has its own methods for searching
 9442: etc. (@pxref{Word Lists}). For the present purpose we defined a word list
 9443: with a special search method: When it is searched for a word, it
 9444: actually creates that word using @code{W:}. @code{@{} changes the search
 9445: order to first search the word list containing @code{@}}, @code{W:} etc.,
 9446: and then the word list for defining locals without type specifiers.
 9447: 
 9448: The lifetime rules support a stack discipline within a colon
 9449: definition: The lifetime of a local is either nested with other locals
 9450: lifetimes or it does not overlap them.
 9451: 
 9452: At @code{BEGIN}, @code{IF}, and @code{AHEAD} no code for locals stack
 9453: pointer manipulation is generated. Between control structure words
 9454: locals definitions can push locals onto the locals stack. @code{AGAIN}
 9455: is the simplest of the other three control flow words. It has to
 9456: restore the locals stack depth of the corresponding @code{BEGIN}
 9457: before branching. The code looks like this:
 9458: @format
 9459: @code{lp+!#} current-locals-size @minus{} dest-locals-size
 9460: @code{branch} <begin>
 9461: @end format
 9462: 
 9463: @code{UNTIL} is a little more complicated: If it branches back, it
 9464: must adjust the stack just like @code{AGAIN}. But if it falls through,
 9465: the locals stack must not be changed. The compiler generates the
 9466: following code:
 9467: @format
 9468: @code{?branch-lp+!#} <begin> current-locals-size @minus{} dest-locals-size
 9469: @end format
 9470: The locals stack pointer is only adjusted if the branch is taken.
 9471: 
 9472: @code{THEN} can produce somewhat inefficient code:
 9473: @format
 9474: @code{lp+!#} current-locals-size @minus{} orig-locals-size
 9475: <orig target>:
 9476: @code{lp+!#} orig-locals-size @minus{} new-locals-size
 9477: @end format
 9478: The second @code{lp+!#} adjusts the locals stack pointer from the
 9479: level at the @i{orig} point to the level after the @code{THEN}. The
 9480: first @code{lp+!#} adjusts the locals stack pointer from the current
 9481: level to the level at the orig point, so the complete effect is an
 9482: adjustment from the current level to the right level after the
 9483: @code{THEN}.
 9484: 
 9485: @cindex locals information on the control-flow stack
 9486: @cindex control-flow stack items, locals information
 9487: In a conventional Forth implementation a dest control-flow stack entry
 9488: is just the target address and an orig entry is just the address to be
 9489: patched. Our locals implementation adds a word list to every orig or dest
 9490: item. It is the list of locals visible (or assumed visible) at the point
 9491: described by the entry. Our implementation also adds a tag to identify
 9492: the kind of entry, in particular to differentiate between live and dead
 9493: (reachable and unreachable) orig entries.
 9494: 
 9495: A few unusual operations have to be performed on locals word lists:
 9496: 
 9497: 
 9498: doc-common-list
 9499: doc-sub-list?
 9500: doc-list-size
 9501: 
 9502: 
 9503: Several features of our locals word list implementation make these
 9504: operations easy to implement: The locals word lists are organised as
 9505: linked lists; the tails of these lists are shared, if the lists
 9506: contain some of the same locals; and the address of a name is greater
 9507: than the address of the names behind it in the list.
 9508: 
 9509: Another important implementation detail is the variable
 9510: @code{dead-code}. It is used by @code{BEGIN} and @code{THEN} to
 9511: determine if they can be reached directly or only through the branch
 9512: that they resolve. @code{dead-code} is set by @code{UNREACHABLE},
 9513: @code{AHEAD}, @code{EXIT} etc., and cleared at the start of a colon
 9514: definition, by @code{BEGIN} and usually by @code{THEN}.
 9515: 
 9516: Counted loops are similar to other loops in most respects, but
 9517: @code{LEAVE} requires special attention: It performs basically the same
 9518: service as @code{AHEAD}, but it does not create a control-flow stack
 9519: entry. Therefore the information has to be stored elsewhere;
 9520: traditionally, the information was stored in the target fields of the
 9521: branches created by the @code{LEAVE}s, by organizing these fields into a
 9522: linked list. Unfortunately, this clever trick does not provide enough
 9523: space for storing our extended control flow information. Therefore, we
 9524: introduce another stack, the leave stack. It contains the control-flow
 9525: stack entries for all unresolved @code{LEAVE}s.
 9526: 
 9527: Local names are kept until the end of the colon definition, even if
 9528: they are no longer visible in any control-flow path. In a few cases
 9529: this may lead to increased space needs for the locals name area, but
 9530: usually less than reclaiming this space would cost in code size.
 9531: 
 9532: 
 9533: @node ANS Forth locals,  , Gforth locals, Locals
 9534: @subsection ANS Forth locals
 9535: @cindex locals, ANS Forth style
 9536: 
 9537: The ANS Forth locals wordset does not define a syntax for locals, but
 9538: words that make it possible to define various syntaxes. One of the
 9539: possible syntaxes is a subset of the syntax we used in the Gforth locals
 9540: wordset, i.e.:
 9541: 
 9542: @example
 9543: @{ local1 local2 ... -- comment @}
 9544: @end example
 9545: @noindent
 9546: or
 9547: @example
 9548: @{ local1 local2 ... @}
 9549: @end example
 9550: 
 9551: The order of the locals corresponds to the order in a stack comment. The
 9552: restrictions are:
 9553: 
 9554: @itemize @bullet
 9555: @item
 9556: Locals can only be cell-sized values (no type specifiers are allowed).
 9557: @item
 9558: Locals can be defined only outside control structures.
 9559: @item
 9560: Locals can interfere with explicit usage of the return stack. For the
 9561: exact (and long) rules, see the standard. If you don't use return stack
 9562: accessing words in a definition using locals, you will be all right. The
 9563: purpose of this rule is to make locals implementation on the return
 9564: stack easier.
 9565: @item
 9566: The whole definition must be in one line.
 9567: @end itemize
 9568: 
 9569: Locals defined in ANS Forth behave like @code{VALUE}s
 9570: (@pxref{Values}). I.e., they are initialized from the stack. Using their
 9571: name produces their value. Their value can be changed using @code{TO}.
 9572: 
 9573: Since the syntax above is supported by Gforth directly, you need not do
 9574: anything to use it. If you want to port a program using this syntax to
 9575: another ANS Forth system, use @file{compat/anslocal.fs} to implement the
 9576: syntax on the other system.
 9577: 
 9578: Note that a syntax shown in the standard, section A.13 looks
 9579: similar, but is quite different in having the order of locals
 9580: reversed. Beware!
 9581: 
 9582: The ANS Forth locals wordset itself consists of one word:
 9583: 
 9584: doc-(local)
 9585: 
 9586: The ANS Forth locals extension wordset defines a syntax using
 9587: @code{locals|}, but it is so awful that we strongly recommend not to use
 9588: it. We have implemented this syntax to make porting to Gforth easy, but
 9589: do not document it here. The problem with this syntax is that the locals
 9590: are defined in an order reversed with respect to the standard stack
 9591: comment notation, making programs harder to read, and easier to misread
 9592: and miswrite. The only merit of this syntax is that it is easy to
 9593: implement using the ANS Forth locals wordset.
 9594: 
 9595: 
 9596: @c ----------------------------------------------------------
 9597: @node Structures, Object-oriented Forth, Locals, Words
 9598: @section  Structures
 9599: @cindex structures
 9600: @cindex records
 9601: 
 9602: This section presents the structure package that comes with Gforth. A
 9603: version of the package implemented in ANS Forth is available in
 9604: @file{compat/struct.fs}. This package was inspired by a posting on
 9605: comp.lang.forth in 1989 (unfortunately I don't remember, by whom;
 9606: possibly John Hayes). A version of this section has been published in
 9607: M. Anton Ertl,
 9608: @uref{http://www.complang.tuwien.ac.at/forth/objects/structs.html, Yet
 9609: Another Forth Structures Package}, Forth Dimensions 19(3), pages
 9610: 13--16. Marcel Hendrix provided helpful comments.
 9611: 
 9612: @menu
 9613: * Why explicit structure support?::  
 9614: * Structure Usage::             
 9615: * Structure Naming Convention::  
 9616: * Structure Implementation::    
 9617: * Structure Glossary::          
 9618: @end menu
 9619: 
 9620: @node Why explicit structure support?, Structure Usage, Structures, Structures
 9621: @subsection Why explicit structure support?
 9622: 
 9623: @cindex address arithmetic for structures
 9624: @cindex structures using address arithmetic
 9625: If we want to use a structure containing several fields, we could simply
 9626: reserve memory for it, and access the fields using address arithmetic
 9627: (@pxref{Address arithmetic}). As an example, consider a structure with
 9628: the following fields
 9629: 
 9630: @table @code
 9631: @item a
 9632: is a float
 9633: @item b
 9634: is a cell
 9635: @item c
 9636: is a float
 9637: @end table
 9638: 
 9639: Given the (float-aligned) base address of the structure we get the
 9640: address of the field
 9641: 
 9642: @table @code
 9643: @item a
 9644: without doing anything further.
 9645: @item b
 9646: with @code{float+}
 9647: @item c
 9648: with @code{float+ cell+ faligned}
 9649: @end table
 9650: 
 9651: It is easy to see that this can become quite tiring. 
 9652: 
 9653: Moreover, it is not very readable, because seeing a
 9654: @code{cell+} tells us neither which kind of structure is
 9655: accessed nor what field is accessed; we have to somehow infer the kind
 9656: of structure, and then look up in the documentation, which field of
 9657: that structure corresponds to that offset.
 9658: 
 9659: Finally, this kind of address arithmetic also causes maintenance
 9660: troubles: If you add or delete a field somewhere in the middle of the
 9661: structure, you have to find and change all computations for the fields
 9662: afterwards.
 9663: 
 9664: So, instead of using @code{cell+} and friends directly, how
 9665: about storing the offsets in constants:
 9666: 
 9667: @example
 9668: 0 constant a-offset
 9669: 0 float+ constant b-offset
 9670: 0 float+ cell+ faligned c-offset
 9671: @end example
 9672: 
 9673: Now we can get the address of field @code{x} with @code{x-offset
 9674: +}. This is much better in all respects. Of course, you still
 9675: have to change all later offset definitions if you add a field. You can
 9676: fix this by declaring the offsets in the following way:
 9677: 
 9678: @example
 9679: 0 constant a-offset
 9680: a-offset float+ constant b-offset
 9681: b-offset cell+ faligned constant c-offset
 9682: @end example
 9683: 
 9684: Since we always use the offsets with @code{+}, we could use a defining
 9685: word @code{cfield} that includes the @code{+} in the action of the
 9686: defined word:
 9687: 
 9688: @example
 9689: : cfield ( n "name" -- )
 9690:     create ,
 9691: does> ( name execution: addr1 -- addr2 )
 9692:     @@ + ;
 9693: 
 9694: 0 cfield a
 9695: 0 a float+ cfield b
 9696: 0 b cell+ faligned cfield c
 9697: @end example
 9698: 
 9699: Instead of @code{x-offset +}, we now simply write @code{x}.
 9700: 
 9701: The structure field words now can be used quite nicely. However,
 9702: their definition is still a bit cumbersome: We have to repeat the
 9703: name, the information about size and alignment is distributed before
 9704: and after the field definitions etc.  The structure package presented
 9705: here addresses these problems.
 9706: 
 9707: @node Structure Usage, Structure Naming Convention, Why explicit structure support?, Structures
 9708: @subsection Structure Usage
 9709: @cindex structure usage
 9710: 
 9711: @cindex @code{field} usage
 9712: @cindex @code{struct} usage
 9713: @cindex @code{end-struct} usage
 9714: You can define a structure for a (data-less) linked list with:
 9715: @example
 9716: struct
 9717:     cell% field list-next
 9718: end-struct list%
 9719: @end example
 9720: 
 9721: With the address of the list node on the stack, you can compute the
 9722: address of the field that contains the address of the next node with
 9723: @code{list-next}. E.g., you can determine the length of a list
 9724: with:
 9725: 
 9726: @example
 9727: : list-length ( list -- n )
 9728: \ "list" is a pointer to the first element of a linked list
 9729: \ "n" is the length of the list
 9730:     0 BEGIN ( list1 n1 )
 9731:         over
 9732:     WHILE ( list1 n1 )
 9733:         1+ swap list-next @@ swap
 9734:     REPEAT
 9735:     nip ;
 9736: @end example
 9737: 
 9738: You can reserve memory for a list node in the dictionary with
 9739: @code{list% %allot}, which leaves the address of the list node on the
 9740: stack. For the equivalent allocation on the heap you can use @code{list%
 9741: %alloc} (or, for an @code{allocate}-like stack effect (i.e., with ior),
 9742: use @code{list% %allocate}). You can get the the size of a list
 9743: node with @code{list% %size} and its alignment with @code{list%
 9744: %alignment}.
 9745: 
 9746: Note that in ANS Forth the body of a @code{create}d word is
 9747: @code{aligned} but not necessarily @code{faligned};
 9748: therefore, if you do a:
 9749: 
 9750: @example
 9751: create @emph{name} foo% %allot drop
 9752: @end example
 9753: 
 9754: @noindent
 9755: then the memory alloted for @code{foo%} is guaranteed to start at the
 9756: body of @code{@emph{name}} only if @code{foo%} contains only character,
 9757: cell and double fields.  Therefore, if your structure contains floats,
 9758: better use
 9759: 
 9760: @example
 9761: foo% %allot constant @emph{name}
 9762: @end example
 9763: 
 9764: @cindex structures containing structures
 9765: You can include a structure @code{foo%} as a field of
 9766: another structure, like this:
 9767: @example
 9768: struct
 9769: ...
 9770:     foo% field ...
 9771: ...
 9772: end-struct ...
 9773: @end example
 9774: 
 9775: @cindex structure extension
 9776: @cindex extended records
 9777: Instead of starting with an empty structure, you can extend an
 9778: existing structure. E.g., a plain linked list without data, as defined
 9779: above, is hardly useful; You can extend it to a linked list of integers,
 9780: like this:@footnote{This feature is also known as @emph{extended
 9781: records}. It is the main innovation in the Oberon language; in other
 9782: words, adding this feature to Modula-2 led Wirth to create a new
 9783: language, write a new compiler etc.  Adding this feature to Forth just
 9784: required a few lines of code.}
 9785: 
 9786: @example
 9787: list%
 9788:     cell% field intlist-int
 9789: end-struct intlist%
 9790: @end example
 9791: 
 9792: @code{intlist%} is a structure with two fields:
 9793: @code{list-next} and @code{intlist-int}.
 9794: 
 9795: @cindex structures containing arrays
 9796: You can specify an array type containing @emph{n} elements of
 9797: type @code{foo%} like this:
 9798: 
 9799: @example
 9800: foo% @emph{n} *
 9801: @end example
 9802: 
 9803: You can use this array type in any place where you can use a normal
 9804: type, e.g., when defining a @code{field}, or with
 9805: @code{%allot}.
 9806: 
 9807: @cindex first field optimization
 9808: The first field is at the base address of a structure and the word for
 9809: this field (e.g., @code{list-next}) actually does not change the address
 9810: on the stack. You may be tempted to leave it away in the interest of
 9811: run-time and space efficiency. This is not necessary, because the
 9812: structure package optimizes this case: If you compile a first-field
 9813: words, no code is generated. So, in the interest of readability and
 9814: maintainability you should include the word for the field when accessing
 9815: the field.
 9816: 
 9817: 
 9818: @node Structure Naming Convention, Structure Implementation, Structure Usage, Structures
 9819: @subsection Structure Naming Convention
 9820: @cindex structure naming convention
 9821: 
 9822: The field names that come to (my) mind are often quite generic, and,
 9823: if used, would cause frequent name clashes. E.g., many structures
 9824: probably contain a @code{counter} field. The structure names
 9825: that come to (my) mind are often also the logical choice for the names
 9826: of words that create such a structure.
 9827: 
 9828: Therefore, I have adopted the following naming conventions: 
 9829: 
 9830: @itemize @bullet
 9831: @cindex field naming convention
 9832: @item
 9833: The names of fields are of the form
 9834: @code{@emph{struct}-@emph{field}}, where
 9835: @code{@emph{struct}} is the basic name of the structure, and
 9836: @code{@emph{field}} is the basic name of the field. You can
 9837: think of field words as converting the (address of the)
 9838: structure into the (address of the) field.
 9839: 
 9840: @cindex structure naming convention
 9841: @item
 9842: The names of structures are of the form
 9843: @code{@emph{struct}%}, where
 9844: @code{@emph{struct}} is the basic name of the structure.
 9845: @end itemize
 9846: 
 9847: This naming convention does not work that well for fields of extended
 9848: structures; e.g., the integer list structure has a field
 9849: @code{intlist-int}, but has @code{list-next}, not
 9850: @code{intlist-next}.
 9851: 
 9852: @node Structure Implementation, Structure Glossary, Structure Naming Convention, Structures
 9853: @subsection Structure Implementation
 9854: @cindex structure implementation
 9855: @cindex implementation of structures
 9856: 
 9857: The central idea in the implementation is to pass the data about the
 9858: structure being built on the stack, not in some global
 9859: variable. Everything else falls into place naturally once this design
 9860: decision is made.
 9861: 
 9862: The type description on the stack is of the form @emph{align
 9863: size}. Keeping the size on the top-of-stack makes dealing with arrays
 9864: very simple.
 9865: 
 9866: @code{field} is a defining word that uses @code{Create}
 9867: and @code{DOES>}. The body of the field contains the offset
 9868: of the field, and the normal @code{DOES>} action is simply:
 9869: 
 9870: @example
 9871: @@ +
 9872: @end example
 9873: 
 9874: @noindent
 9875: i.e., add the offset to the address, giving the stack effect
 9876: @i{addr1 -- addr2} for a field.
 9877: 
 9878: @cindex first field optimization, implementation
 9879: This simple structure is slightly complicated by the optimization
 9880: for fields with offset 0, which requires a different
 9881: @code{DOES>}-part (because we cannot rely on there being
 9882: something on the stack if such a field is invoked during
 9883: compilation). Therefore, we put the different @code{DOES>}-parts
 9884: in separate words, and decide which one to invoke based on the
 9885: offset. For a zero offset, the field is basically a noop; it is
 9886: immediate, and therefore no code is generated when it is compiled.
 9887: 
 9888: @node Structure Glossary,  , Structure Implementation, Structures
 9889: @subsection Structure Glossary
 9890: @cindex structure glossary
 9891: 
 9892: 
 9893: doc-%align
 9894: doc-%alignment
 9895: doc-%alloc
 9896: doc-%allocate
 9897: doc-%allot
 9898: doc-cell%
 9899: doc-char%
 9900: doc-dfloat%
 9901: doc-double%
 9902: doc-end-struct
 9903: doc-field
 9904: doc-float%
 9905: doc-naligned
 9906: doc-sfloat%
 9907: doc-%size
 9908: doc-struct
 9909: 
 9910: 
 9911: @c -------------------------------------------------------------
 9912: @node Object-oriented Forth, Programming Tools, Structures, Words
 9913: @section Object-oriented Forth
 9914: 
 9915: Gforth comes with three packages for object-oriented programming:
 9916: @file{objects.fs}, @file{oof.fs}, and @file{mini-oof.fs}; none of them
 9917: is preloaded, so you have to @code{include} them before use. The most
 9918: important differences between these packages (and others) are discussed
 9919: in @ref{Comparison with other object models}. All packages are written
 9920: in ANS Forth and can be used with any other ANS Forth.
 9921: 
 9922: @menu
 9923: * Why object-oriented programming?::  
 9924: * Object-Oriented Terminology::  
 9925: * Objects::                     
 9926: * OOF::                         
 9927: * Mini-OOF::                    
 9928: * Comparison with other object models::  
 9929: @end menu
 9930: 
 9931: @c ----------------------------------------------------------------
 9932: @node Why object-oriented programming?, Object-Oriented Terminology, Object-oriented Forth, Object-oriented Forth
 9933: @subsection Why object-oriented programming?
 9934: @cindex object-oriented programming motivation
 9935: @cindex motivation for object-oriented programming
 9936: 
 9937: Often we have to deal with several data structures (@emph{objects}),
 9938: that have to be treated similarly in some respects, but differently in
 9939: others. Graphical objects are the textbook example: circles, triangles,
 9940: dinosaurs, icons, and others, and we may want to add more during program
 9941: development. We want to apply some operations to any graphical object,
 9942: e.g., @code{draw} for displaying it on the screen. However, @code{draw}
 9943: has to do something different for every kind of object.
 9944: @comment TODO add some other operations eg perimeter, area
 9945: @comment and tie in to concrete examples later..
 9946: 
 9947: We could implement @code{draw} as a big @code{CASE}
 9948: control structure that executes the appropriate code depending on the
 9949: kind of object to be drawn. This would be not be very elegant, and,
 9950: moreover, we would have to change @code{draw} every time we add
 9951: a new kind of graphical object (say, a spaceship).
 9952: 
 9953: What we would rather do is: When defining spaceships, we would tell
 9954: the system: ``Here's how you @code{draw} a spaceship; you figure
 9955: out the rest''.
 9956: 
 9957: This is the problem that all systems solve that (rightfully) call
 9958: themselves object-oriented; the object-oriented packages presented here
 9959: solve this problem (and not much else).
 9960: @comment TODO ?list properties of oo systems.. oo vs o-based?
 9961: 
 9962: @c ------------------------------------------------------------------------
 9963: @node Object-Oriented Terminology, Objects, Why object-oriented programming?, Object-oriented Forth
 9964: @subsection Object-Oriented Terminology
 9965: @cindex object-oriented terminology
 9966: @cindex terminology for object-oriented programming
 9967: 
 9968: This section is mainly for reference, so you don't have to understand
 9969: all of it right away.  The terminology is mainly Smalltalk-inspired.  In
 9970: short:
 9971: 
 9972: @table @emph
 9973: @cindex class
 9974: @item class
 9975: a data structure definition with some extras.
 9976: 
 9977: @cindex object
 9978: @item object
 9979: an instance of the data structure described by the class definition.
 9980: 
 9981: @cindex instance variables
 9982: @item instance variables
 9983: fields of the data structure.
 9984: 
 9985: @cindex selector
 9986: @cindex method selector
 9987: @cindex virtual function
 9988: @item selector
 9989: (or @emph{method selector}) a word (e.g.,
 9990: @code{draw}) that performs an operation on a variety of data
 9991: structures (classes). A selector describes @emph{what} operation to
 9992: perform. In C++ terminology: a (pure) virtual function.
 9993: 
 9994: @cindex method
 9995: @item method
 9996: the concrete definition that performs the operation
 9997: described by the selector for a specific class. A method specifies
 9998: @emph{how} the operation is performed for a specific class.
 9999: 
10000: @cindex selector invocation
10001: @cindex message send
10002: @cindex invoking a selector
10003: @item selector invocation
10004: a call of a selector. One argument of the call (the TOS (top-of-stack))
10005: is used for determining which method is used. In Smalltalk terminology:
10006: a message (consisting of the selector and the other arguments) is sent
10007: to the object.
10008: 
10009: @cindex receiving object
10010: @item receiving object
10011: the object used for determining the method executed by a selector
10012: invocation. In the @file{objects.fs} model, it is the object that is on
10013: the TOS when the selector is invoked. (@emph{Receiving} comes from
10014: the Smalltalk @emph{message} terminology.)
10015: 
10016: @cindex child class
10017: @cindex parent class
10018: @cindex inheritance
10019: @item child class
10020: a class that has (@emph{inherits}) all properties (instance variables,
10021: selectors, methods) from a @emph{parent class}. In Smalltalk
10022: terminology: The subclass inherits from the superclass. In C++
10023: terminology: The derived class inherits from the base class.
10024: 
10025: @end table
10026: 
10027: @c If you wonder about the message sending terminology, it comes from
10028: @c a time when each object had it's own task and objects communicated via
10029: @c message passing; eventually the Smalltalk developers realized that
10030: @c they can do most things through simple (indirect) calls. They kept the
10031: @c terminology.
10032: 
10033: @c --------------------------------------------------------------
10034: @node Objects, OOF, Object-Oriented Terminology, Object-oriented Forth
10035: @subsection The @file{objects.fs} model
10036: @cindex objects
10037: @cindex object-oriented programming
10038: 
10039: @cindex @file{objects.fs}
10040: @cindex @file{oof.fs}
10041: 
10042: This section describes the @file{objects.fs} package. This material also
10043: has been published in M. Anton Ertl,
10044: @cite{@uref{http://www.complang.tuwien.ac.at/forth/objects/objects.html,
10045: Yet Another Forth Objects Package}}, Forth Dimensions 19(2), pages
10046: 37--43.
10047: @c McKewan's and Zsoter's packages
10048: 
10049: This section assumes that you have read @ref{Structures}.
10050: 
10051: The techniques on which this model is based have been used to implement
10052: the parser generator, Gray, and have also been used in Gforth for
10053: implementing the various flavours of word lists (hashed or not,
10054: case-sensitive or not, special-purpose word lists for locals etc.).
10055: 
10056: 
10057: @menu
10058: * Properties of the Objects model::  
10059: * Basic Objects Usage::         
10060: * The Objects base class::      
10061: * Creating objects::            
10062: * Object-Oriented Programming Style::  
10063: * Class Binding::               
10064: * Method conveniences::         
10065: * Classes and Scoping::         
10066: * Dividing classes::            
10067: * Object Interfaces::           
10068: * Objects Implementation::      
10069: * Objects Glossary::            
10070: @end menu
10071: 
10072: Marcel Hendrix provided helpful comments on this section.
10073: 
10074: @node Properties of the Objects model, Basic Objects Usage, Objects, Objects
10075: @subsubsection Properties of the @file{objects.fs} model
10076: @cindex @file{objects.fs} properties
10077: 
10078: @itemize @bullet
10079: @item
10080: It is straightforward to pass objects on the stack. Passing
10081: selectors on the stack is a little less convenient, but possible.
10082: 
10083: @item
10084: Objects are just data structures in memory, and are referenced by their
10085: address. You can create words for objects with normal defining words
10086: like @code{constant}. Likewise, there is no difference between instance
10087: variables that contain objects and those that contain other data.
10088: 
10089: @item
10090: Late binding is efficient and easy to use.
10091: 
10092: @item
10093: It avoids parsing, and thus avoids problems with state-smartness
10094: and reduced extensibility; for convenience there are a few parsing
10095: words, but they have non-parsing counterparts. There are also a few
10096: defining words that parse. This is hard to avoid, because all standard
10097: defining words parse (except @code{:noname}); however, such
10098: words are not as bad as many other parsing words, because they are not
10099: state-smart.
10100: 
10101: @item
10102: It does not try to incorporate everything. It does a few things and does
10103: them well (IMO). In particular, this model was not designed to support
10104: information hiding (although it has features that may help); you can use
10105: a separate package for achieving this.
10106: 
10107: @item
10108: It is layered; you don't have to learn and use all features to use this
10109: model. Only a few features are necessary (@pxref{Basic Objects Usage},
10110: @pxref{The Objects base class}, @pxref{Creating objects}.), the others
10111: are optional and independent of each other.
10112: 
10113: @item
10114: An implementation in ANS Forth is available.
10115: 
10116: @end itemize
10117: 
10118: 
10119: @node Basic Objects Usage, The Objects base class, Properties of the Objects model, Objects
10120: @subsubsection Basic @file{objects.fs} Usage
10121: @cindex basic objects usage
10122: @cindex objects, basic usage
10123: 
10124: You can define a class for graphical objects like this:
10125: 
10126: @cindex @code{class} usage
10127: @cindex @code{end-class} usage
10128: @cindex @code{selector} usage
10129: @example
10130: object class \ "object" is the parent class
10131:   selector draw ( x y graphical -- )
10132: end-class graphical
10133: @end example
10134: 
10135: This code defines a class @code{graphical} with an
10136: operation @code{draw}.  We can perform the operation
10137: @code{draw} on any @code{graphical} object, e.g.:
10138: 
10139: @example
10140: 100 100 t-rex draw
10141: @end example
10142: 
10143: @noindent
10144: where @code{t-rex} is a word (say, a constant) that produces a
10145: graphical object.
10146: 
10147: @comment TODO add a 2nd operation eg perimeter.. and use for
10148: @comment a concrete example
10149: 
10150: @cindex abstract class
10151: How do we create a graphical object? With the present definitions,
10152: we cannot create a useful graphical object. The class
10153: @code{graphical} describes graphical objects in general, but not
10154: any concrete graphical object type (C++ users would call it an
10155: @emph{abstract class}); e.g., there is no method for the selector
10156: @code{draw} in the class @code{graphical}.
10157: 
10158: For concrete graphical objects, we define child classes of the
10159: class @code{graphical}, e.g.:
10160: 
10161: @cindex @code{overrides} usage
10162: @cindex @code{field} usage in class definition
10163: @example
10164: graphical class \ "graphical" is the parent class
10165:   cell% field circle-radius
10166: 
10167: :noname ( x y circle -- )
10168:   circle-radius @@ draw-circle ;
10169: overrides draw
10170: 
10171: :noname ( n-radius circle -- )
10172:   circle-radius ! ;
10173: overrides construct
10174: 
10175: end-class circle
10176: @end example
10177: 
10178: Here we define a class @code{circle} as a child of @code{graphical},
10179: with field @code{circle-radius} (which behaves just like a field
10180: (@pxref{Structures}); it defines (using @code{overrides}) new methods
10181: for the selectors @code{draw} and @code{construct} (@code{construct} is
10182: defined in @code{object}, the parent class of @code{graphical}).
10183: 
10184: Now we can create a circle on the heap (i.e.,
10185: @code{allocate}d memory) with:
10186: 
10187: @cindex @code{heap-new} usage
10188: @example
10189: 50 circle heap-new constant my-circle
10190: @end example
10191: 
10192: @noindent
10193: @code{heap-new} invokes @code{construct}, thus
10194: initializing the field @code{circle-radius} with 50. We can draw
10195: this new circle at (100,100) with:
10196: 
10197: @example
10198: 100 100 my-circle draw
10199: @end example
10200: 
10201: @cindex selector invocation, restrictions
10202: @cindex class definition, restrictions
10203: Note: You can only invoke a selector if the object on the TOS
10204: (the receiving object) belongs to the class where the selector was
10205: defined or one of its descendents; e.g., you can invoke
10206: @code{draw} only for objects belonging to @code{graphical}
10207: or its descendents (e.g., @code{circle}).  Immediately before
10208: @code{end-class}, the search order has to be the same as
10209: immediately after @code{class}.
10210: 
10211: @node The Objects base class, Creating objects, Basic Objects Usage, Objects
10212: @subsubsection The @file{object.fs} base class
10213: @cindex @code{object} class
10214: 
10215: When you define a class, you have to specify a parent class.  So how do
10216: you start defining classes? There is one class available from the start:
10217: @code{object}. It is ancestor for all classes and so is the
10218: only class that has no parent. It has two selectors: @code{construct}
10219: and @code{print}.
10220: 
10221: @node Creating objects, Object-Oriented Programming Style, The Objects base class, Objects
10222: @subsubsection Creating objects
10223: @cindex creating objects
10224: @cindex object creation
10225: @cindex object allocation options
10226: 
10227: @cindex @code{heap-new} discussion
10228: @cindex @code{dict-new} discussion
10229: @cindex @code{construct} discussion
10230: You can create and initialize an object of a class on the heap with
10231: @code{heap-new} ( ... class -- object ) and in the dictionary
10232: (allocation with @code{allot}) with @code{dict-new} (
10233: ... class -- object ). Both words invoke @code{construct}, which
10234: consumes the stack items indicated by "..." above.
10235: 
10236: @cindex @code{init-object} discussion
10237: @cindex @code{class-inst-size} discussion
10238: If you want to allocate memory for an object yourself, you can get its
10239: alignment and size with @code{class-inst-size 2@@} ( class --
10240: align size ). Once you have memory for an object, you can initialize
10241: it with @code{init-object} ( ... class object -- );
10242: @code{construct} does only a part of the necessary work.
10243: 
10244: @node Object-Oriented Programming Style, Class Binding, Creating objects, Objects
10245: @subsubsection Object-Oriented Programming Style
10246: @cindex object-oriented programming style
10247: @cindex programming style, object-oriented
10248: 
10249: This section is not exhaustive.
10250: 
10251: @cindex stack effects of selectors
10252: @cindex selectors and stack effects
10253: In general, it is a good idea to ensure that all methods for the
10254: same selector have the same stack effect: when you invoke a selector,
10255: you often have no idea which method will be invoked, so, unless all
10256: methods have the same stack effect, you will not know the stack effect
10257: of the selector invocation.
10258: 
10259: One exception to this rule is methods for the selector
10260: @code{construct}. We know which method is invoked, because we
10261: specify the class to be constructed at the same place. Actually, I
10262: defined @code{construct} as a selector only to give the users a
10263: convenient way to specify initialization. The way it is used, a
10264: mechanism different from selector invocation would be more natural
10265: (but probably would take more code and more space to explain).
10266: 
10267: @node Class Binding, Method conveniences, Object-Oriented Programming Style, Objects
10268: @subsubsection Class Binding
10269: @cindex class binding
10270: @cindex early binding
10271: 
10272: @cindex late binding
10273: Normal selector invocations determine the method at run-time depending
10274: on the class of the receiving object. This run-time selection is called
10275: @i{late binding}.
10276: 
10277: Sometimes it's preferable to invoke a different method. For example,
10278: you might want to use the simple method for @code{print}ing
10279: @code{object}s instead of the possibly long-winded @code{print} method
10280: of the receiver class. You can achieve this by replacing the invocation
10281: of @code{print} with:
10282: 
10283: @cindex @code{[bind]} usage
10284: @example
10285: [bind] object print
10286: @end example
10287: 
10288: @noindent
10289: in compiled code or:
10290: 
10291: @cindex @code{bind} usage
10292: @example
10293: bind object print
10294: @end example
10295: 
10296: @cindex class binding, alternative to
10297: @noindent
10298: in interpreted code. Alternatively, you can define the method with a
10299: name (e.g., @code{print-object}), and then invoke it through the
10300: name. Class binding is just a (often more convenient) way to achieve
10301: the same effect; it avoids name clutter and allows you to invoke
10302: methods directly without naming them first.
10303: 
10304: @cindex superclass binding
10305: @cindex parent class binding
10306: A frequent use of class binding is this: When we define a method
10307: for a selector, we often want the method to do what the selector does
10308: in the parent class, and a little more. There is a special word for
10309: this purpose: @code{[parent]}; @code{[parent]
10310: @emph{selector}} is equivalent to @code{[bind] @emph{parent
10311: selector}}, where @code{@emph{parent}} is the parent
10312: class of the current class. E.g., a method definition might look like:
10313: 
10314: @cindex @code{[parent]} usage
10315: @example
10316: :noname
10317:   dup [parent] foo \ do parent's foo on the receiving object
10318:   ... \ do some more
10319: ; overrides foo
10320: @end example
10321: 
10322: @cindex class binding as optimization
10323: In @cite{Object-oriented programming in ANS Forth} (Forth Dimensions,
10324: March 1997), Andrew McKewan presents class binding as an optimization
10325: technique. I recommend not using it for this purpose unless you are in
10326: an emergency. Late binding is pretty fast with this model anyway, so the
10327: benefit of using class binding is small; the cost of using class binding
10328: where it is not appropriate is reduced maintainability.
10329: 
10330: While we are at programming style questions: You should bind
10331: selectors only to ancestor classes of the receiving object. E.g., say,
10332: you know that the receiving object is of class @code{foo} or its
10333: descendents; then you should bind only to @code{foo} and its
10334: ancestors.
10335: 
10336: @node Method conveniences, Classes and Scoping, Class Binding, Objects
10337: @subsubsection Method conveniences
10338: @cindex method conveniences
10339: 
10340: In a method you usually access the receiving object pretty often.  If
10341: you define the method as a plain colon definition (e.g., with
10342: @code{:noname}), you may have to do a lot of stack
10343: gymnastics. To avoid this, you can define the method with @code{m:
10344: ... ;m}. E.g., you could define the method for
10345: @code{draw}ing a @code{circle} with
10346: 
10347: @cindex @code{this} usage
10348: @cindex @code{m:} usage
10349: @cindex @code{;m} usage
10350: @example
10351: m: ( x y circle -- )
10352:   ( x y ) this circle-radius @@ draw-circle ;m
10353: @end example
10354: 
10355: @cindex @code{exit} in @code{m: ... ;m}
10356: @cindex @code{exitm} discussion
10357: @cindex @code{catch} in @code{m: ... ;m}
10358: When this method is executed, the receiver object is removed from the
10359: stack; you can access it with @code{this} (admittedly, in this
10360: example the use of @code{m: ... ;m} offers no advantage). Note
10361: that I specify the stack effect for the whole method (i.e. including
10362: the receiver object), not just for the code between @code{m:}
10363: and @code{;m}. You cannot use @code{exit} in
10364: @code{m:...;m}; instead, use
10365: @code{exitm}.@footnote{Moreover, for any word that calls
10366: @code{catch} and was defined before loading
10367: @code{objects.fs}, you have to redefine it like I redefined
10368: @code{catch}: @code{: catch this >r catch r> to-this ;}}
10369: 
10370: @cindex @code{inst-var} usage
10371: You will frequently use sequences of the form @code{this
10372: @emph{field}} (in the example above: @code{this
10373: circle-radius}). If you use the field only in this way, you can
10374: define it with @code{inst-var} and eliminate the
10375: @code{this} before the field name. E.g., the @code{circle}
10376: class above could also be defined with:
10377: 
10378: @example
10379: graphical class
10380:   cell% inst-var radius
10381: 
10382: m: ( x y circle -- )
10383:   radius @@ draw-circle ;m
10384: overrides draw
10385: 
10386: m: ( n-radius circle -- )
10387:   radius ! ;m
10388: overrides construct
10389: 
10390: end-class circle
10391: @end example
10392: 
10393: @code{radius} can only be used in @code{circle} and its
10394: descendent classes and inside @code{m:...;m}.
10395: 
10396: @cindex @code{inst-value} usage
10397: You can also define fields with @code{inst-value}, which is
10398: to @code{inst-var} what @code{value} is to
10399: @code{variable}.  You can change the value of such a field with
10400: @code{[to-inst]}.  E.g., we could also define the class
10401: @code{circle} like this:
10402: 
10403: @example
10404: graphical class
10405:   inst-value radius
10406: 
10407: m: ( x y circle -- )
10408:   radius draw-circle ;m
10409: overrides draw
10410: 
10411: m: ( n-radius circle -- )
10412:   [to-inst] radius ;m
10413: overrides construct
10414: 
10415: end-class circle
10416: @end example
10417: 
10418: @c !! :m is easy to confuse with m:.  Another name would be better.
10419: 
10420: @c Finally, you can define named methods with @code{:m}.  One use of this
10421: @c feature is the definition of words that occur only in one class and are
10422: @c not intended to be overridden, but which still need method context
10423: @c (e.g., for accessing @code{inst-var}s).  Another use is for methods that
10424: @c would be bound frequently, if defined anonymously.
10425: 
10426: 
10427: @node Classes and Scoping, Dividing classes, Method conveniences, Objects
10428: @subsubsection Classes and Scoping
10429: @cindex classes and scoping
10430: @cindex scoping and classes
10431: 
10432: Inheritance is frequent, unlike structure extension. This exacerbates
10433: the problem with the field name convention (@pxref{Structure Naming
10434: Convention}): One always has to remember in which class the field was
10435: originally defined; changing a part of the class structure would require
10436: changes for renaming in otherwise unaffected code.
10437: 
10438: @cindex @code{inst-var} visibility
10439: @cindex @code{inst-value} visibility
10440: To solve this problem, I added a scoping mechanism (which was not in my
10441: original charter): A field defined with @code{inst-var} (or
10442: @code{inst-value}) is visible only in the class where it is defined and in
10443: the descendent classes of this class.  Using such fields only makes
10444: sense in @code{m:}-defined methods in these classes anyway.
10445: 
10446: This scoping mechanism allows us to use the unadorned field name,
10447: because name clashes with unrelated words become much less likely.
10448: 
10449: @cindex @code{protected} discussion
10450: @cindex @code{private} discussion
10451: Once we have this mechanism, we can also use it for controlling the
10452: visibility of other words: All words defined after
10453: @code{protected} are visible only in the current class and its
10454: descendents. @code{public} restores the compilation
10455: (i.e. @code{current}) word list that was in effect before. If you
10456: have several @code{protected}s without an intervening
10457: @code{public} or @code{set-current}, @code{public}
10458: will restore the compilation word list in effect before the first of
10459: these @code{protected}s.
10460: 
10461: @node Dividing classes, Object Interfaces, Classes and Scoping, Objects
10462: @subsubsection Dividing classes
10463: @cindex Dividing classes
10464: @cindex @code{methods}...@code{end-methods}
10465: 
10466: You may want to do the definition of methods separate from the
10467: definition of the class, its selectors, fields, and instance variables,
10468: i.e., separate the implementation from the definition.  You can do this
10469: in the following way:
10470: 
10471: @example
10472: graphical class
10473:   inst-value radius
10474: end-class circle
10475: 
10476: ... \ do some other stuff
10477: 
10478: circle methods \ now we are ready
10479: 
10480: m: ( x y circle -- )
10481:   radius draw-circle ;m
10482: overrides draw
10483: 
10484: m: ( n-radius circle -- )
10485:   [to-inst] radius ;m
10486: overrides construct
10487: 
10488: end-methods
10489: @end example
10490: 
10491: You can use several @code{methods}...@code{end-methods} sections.  The
10492: only things you can do to the class in these sections are: defining
10493: methods, and overriding the class's selectors.  You must not define new
10494: selectors or fields.
10495: 
10496: Note that you often have to override a selector before using it.  In
10497: particular, you usually have to override @code{construct} with a new
10498: method before you can invoke @code{heap-new} and friends.  E.g., you
10499: must not create a circle before the @code{overrides construct} sequence
10500: in the example above.
10501: 
10502: @node Object Interfaces, Objects Implementation, Dividing classes, Objects
10503: @subsubsection Object Interfaces
10504: @cindex object interfaces
10505: @cindex interfaces for objects
10506: 
10507: In this model you can only call selectors defined in the class of the
10508: receiving objects or in one of its ancestors. If you call a selector
10509: with a receiving object that is not in one of these classes, the
10510: result is undefined; if you are lucky, the program crashes
10511: immediately.
10512: 
10513: @cindex selectors common to hardly-related classes
10514: Now consider the case when you want to have a selector (or several)
10515: available in two classes: You would have to add the selector to a
10516: common ancestor class, in the worst case to @code{object}. You
10517: may not want to do this, e.g., because someone else is responsible for
10518: this ancestor class.
10519: 
10520: The solution for this problem is interfaces. An interface is a
10521: collection of selectors. If a class implements an interface, the
10522: selectors become available to the class and its descendents. A class
10523: can implement an unlimited number of interfaces. For the problem
10524: discussed above, we would define an interface for the selector(s), and
10525: both classes would implement the interface.
10526: 
10527: As an example, consider an interface @code{storage} for
10528: writing objects to disk and getting them back, and a class
10529: @code{foo} that implements it. The code would look like this:
10530: 
10531: @cindex @code{interface} usage
10532: @cindex @code{end-interface} usage
10533: @cindex @code{implementation} usage
10534: @example
10535: interface
10536:   selector write ( file object -- )
10537:   selector read1 ( file object -- )
10538: end-interface storage
10539: 
10540: bar class
10541:   storage implementation
10542: 
10543: ... overrides write
10544: ... overrides read1
10545: ...
10546: end-class foo
10547: @end example
10548: 
10549: @noindent
10550: (I would add a word @code{read} @i{( file -- object )} that uses
10551: @code{read1} internally, but that's beyond the point illustrated
10552: here.)
10553: 
10554: Note that you cannot use @code{protected} in an interface; and
10555: of course you cannot define fields.
10556: 
10557: In the Neon model, all selectors are available for all classes;
10558: therefore it does not need interfaces. The price you pay in this model
10559: is slower late binding, and therefore, added complexity to avoid late
10560: binding.
10561: 
10562: @node Objects Implementation, Objects Glossary, Object Interfaces, Objects
10563: @subsubsection @file{objects.fs} Implementation
10564: @cindex @file{objects.fs} implementation
10565: 
10566: @cindex @code{object-map} discussion
10567: An object is a piece of memory, like one of the data structures
10568: described with @code{struct...end-struct}. It has a field
10569: @code{object-map} that points to the method map for the object's
10570: class.
10571: 
10572: @cindex method map
10573: @cindex virtual function table
10574: The @emph{method map}@footnote{This is Self terminology; in C++
10575: terminology: virtual function table.} is an array that contains the
10576: execution tokens (@i{xt}s) of the methods for the object's class. Each
10577: selector contains an offset into a method map.
10578: 
10579: @cindex @code{selector} implementation, class
10580: @code{selector} is a defining word that uses
10581: @code{CREATE} and @code{DOES>}. The body of the
10582: selector contains the offset; the @code{DOES>} action for a
10583: class selector is, basically:
10584: 
10585: @example
10586: ( object addr ) @@ over object-map @@ + @@ execute
10587: @end example
10588: 
10589: Since @code{object-map} is the first field of the object, it
10590: does not generate any code. As you can see, calling a selector has a
10591: small, constant cost.
10592: 
10593: @cindex @code{current-interface} discussion
10594: @cindex class implementation and representation
10595: A class is basically a @code{struct} combined with a method
10596: map. During the class definition the alignment and size of the class
10597: are passed on the stack, just as with @code{struct}s, so
10598: @code{field} can also be used for defining class
10599: fields. However, passing more items on the stack would be
10600: inconvenient, so @code{class} builds a data structure in memory,
10601: which is accessed through the variable
10602: @code{current-interface}. After its definition is complete, the
10603: class is represented on the stack by a pointer (e.g., as parameter for
10604: a child class definition).
10605: 
10606: A new class starts off with the alignment and size of its parent,
10607: and a copy of the parent's method map. Defining new fields extends the
10608: size and alignment; likewise, defining new selectors extends the
10609: method map. @code{overrides} just stores a new @i{xt} in the method
10610: map at the offset given by the selector.
10611: 
10612: @cindex class binding, implementation
10613: Class binding just gets the @i{xt} at the offset given by the selector
10614: from the class's method map and @code{compile,}s (in the case of
10615: @code{[bind]}) it.
10616: 
10617: @cindex @code{this} implementation
10618: @cindex @code{catch} and @code{this}
10619: @cindex @code{this} and @code{catch}
10620: I implemented @code{this} as a @code{value}. At the
10621: start of an @code{m:...;m} method the old @code{this} is
10622: stored to the return stack and restored at the end; and the object on
10623: the TOS is stored @code{TO this}. This technique has one
10624: disadvantage: If the user does not leave the method via
10625: @code{;m}, but via @code{throw} or @code{exit},
10626: @code{this} is not restored (and @code{exit} may
10627: crash). To deal with the @code{throw} problem, I have redefined
10628: @code{catch} to save and restore @code{this}; the same
10629: should be done with any word that can catch an exception. As for
10630: @code{exit}, I simply forbid it (as a replacement, there is
10631: @code{exitm}).
10632: 
10633: @cindex @code{inst-var} implementation
10634: @code{inst-var} is just the same as @code{field}, with
10635: a different @code{DOES>} action:
10636: @example
10637: @@ this +
10638: @end example
10639: Similar for @code{inst-value}.
10640: 
10641: @cindex class scoping implementation
10642: Each class also has a word list that contains the words defined with
10643: @code{inst-var} and @code{inst-value}, and its protected
10644: words. It also has a pointer to its parent. @code{class} pushes
10645: the word lists of the class and all its ancestors onto the search order stack,
10646: and @code{end-class} drops them.
10647: 
10648: @cindex interface implementation
10649: An interface is like a class without fields, parent and protected
10650: words; i.e., it just has a method map. If a class implements an
10651: interface, its method map contains a pointer to the method map of the
10652: interface. The positive offsets in the map are reserved for class
10653: methods, therefore interface map pointers have negative
10654: offsets. Interfaces have offsets that are unique throughout the
10655: system, unlike class selectors, whose offsets are only unique for the
10656: classes where the selector is available (invokable).
10657: 
10658: This structure means that interface selectors have to perform one
10659: indirection more than class selectors to find their method. Their body
10660: contains the interface map pointer offset in the class method map, and
10661: the method offset in the interface method map. The
10662: @code{does>} action for an interface selector is, basically:
10663: 
10664: @example
10665: ( object selector-body )
10666: 2dup selector-interface @@ ( object selector-body object interface-offset )
10667: swap object-map @@ + @@ ( object selector-body map )
10668: swap selector-offset @@ + @@ execute
10669: @end example
10670: 
10671: where @code{object-map} and @code{selector-offset} are
10672: first fields and generate no code.
10673: 
10674: As a concrete example, consider the following code:
10675: 
10676: @example
10677: interface
10678:   selector if1sel1
10679:   selector if1sel2
10680: end-interface if1
10681: 
10682: object class
10683:   if1 implementation
10684:   selector cl1sel1
10685:   cell% inst-var cl1iv1
10686: 
10687: ' m1 overrides construct
10688: ' m2 overrides if1sel1
10689: ' m3 overrides if1sel2
10690: ' m4 overrides cl1sel2
10691: end-class cl1
10692: 
10693: create obj1 object dict-new drop
10694: create obj2 cl1    dict-new drop
10695: @end example
10696: 
10697: The data structure created by this code (including the data structure
10698: for @code{object}) is shown in the
10699: @uref{objects-implementation.eps,figure}, assuming a cell size of 4.
10700: @comment TODO add this diagram..
10701: 
10702: @node Objects Glossary,  , Objects Implementation, Objects
10703: @subsubsection @file{objects.fs} Glossary
10704: @cindex @file{objects.fs} Glossary
10705: 
10706: 
10707: doc---objects-bind
10708: doc---objects-<bind>
10709: doc---objects-bind'
10710: doc---objects-[bind]
10711: doc---objects-class
10712: doc---objects-class->map
10713: doc---objects-class-inst-size
10714: doc---objects-class-override!
10715: doc---objects-class-previous
10716: doc---objects-class>order
10717: doc---objects-construct
10718: doc---objects-current'
10719: doc---objects-[current]
10720: doc---objects-current-interface
10721: doc---objects-dict-new
10722: doc---objects-end-class
10723: doc---objects-end-class-noname
10724: doc---objects-end-interface
10725: doc---objects-end-interface-noname
10726: doc---objects-end-methods
10727: doc---objects-exitm
10728: doc---objects-heap-new
10729: doc---objects-implementation
10730: doc---objects-init-object
10731: doc---objects-inst-value
10732: doc---objects-inst-var
10733: doc---objects-interface
10734: doc---objects-m:
10735: doc---objects-:m
10736: doc---objects-;m
10737: doc---objects-method
10738: doc---objects-methods
10739: doc---objects-object
10740: doc---objects-overrides
10741: doc---objects-[parent]
10742: doc---objects-print
10743: doc---objects-protected
10744: doc---objects-public
10745: doc---objects-selector
10746: doc---objects-this
10747: doc---objects-<to-inst>
10748: doc---objects-[to-inst]
10749: doc---objects-to-this
10750: doc---objects-xt-new
10751: 
10752: 
10753: @c -------------------------------------------------------------
10754: @node OOF, Mini-OOF, Objects, Object-oriented Forth
10755: @subsection The @file{oof.fs} model
10756: @cindex oof
10757: @cindex object-oriented programming
10758: 
10759: @cindex @file{objects.fs}
10760: @cindex @file{oof.fs}
10761: 
10762: This section describes the @file{oof.fs} package.
10763: 
10764: The package described in this section has been used in bigFORTH since 1991, and
10765: used for two large applications: a chromatographic system used to
10766: create new medicaments, and a graphic user interface library (MINOS).
10767: 
10768: You can find a description (in German) of @file{oof.fs} in @cite{Object
10769: oriented bigFORTH} by Bernd Paysan, published in @cite{Vierte Dimension}
10770: 10(2), 1994.
10771: 
10772: @menu
10773: * Properties of the OOF model::  
10774: * Basic OOF Usage::             
10775: * The OOF base class::          
10776: * Class Declaration::           
10777: * Class Implementation::        
10778: @end menu
10779: 
10780: @node Properties of the OOF model, Basic OOF Usage, OOF, OOF
10781: @subsubsection Properties of the @file{oof.fs} model
10782: @cindex @file{oof.fs} properties
10783: 
10784: @itemize @bullet
10785: @item
10786: This model combines object oriented programming with information
10787: hiding. It helps you writing large application, where scoping is
10788: necessary, because it provides class-oriented scoping.
10789: 
10790: @item
10791: Named objects, object pointers, and object arrays can be created,
10792: selector invocation uses the ``object selector'' syntax. Selector invocation
10793: to objects and/or selectors on the stack is a bit less convenient, but
10794: possible.
10795: 
10796: @item
10797: Selector invocation and instance variable usage of the active object is
10798: straightforward, since both make use of the active object.
10799: 
10800: @item
10801: Late binding is efficient and easy to use.
10802: 
10803: @item
10804: State-smart objects parse selectors. However, extensibility is provided
10805: using a (parsing) selector @code{postpone} and a selector @code{'}.
10806: 
10807: @item
10808: An implementation in ANS Forth is available.
10809: 
10810: @end itemize
10811: 
10812: 
10813: @node Basic OOF Usage, The OOF base class, Properties of the OOF model, OOF
10814: @subsubsection Basic @file{oof.fs} Usage
10815: @cindex @file{oof.fs} usage
10816: 
10817: This section uses the same example as for @code{objects} (@pxref{Basic Objects Usage}).
10818: 
10819: You can define a class for graphical objects like this:
10820: 
10821: @cindex @code{class} usage
10822: @cindex @code{class;} usage
10823: @cindex @code{method} usage
10824: @example
10825: object class graphical \ "object" is the parent class
10826:   method draw ( x y graphical -- )
10827: class;
10828: @end example
10829: 
10830: This code defines a class @code{graphical} with an
10831: operation @code{draw}.  We can perform the operation
10832: @code{draw} on any @code{graphical} object, e.g.:
10833: 
10834: @example
10835: 100 100 t-rex draw
10836: @end example
10837: 
10838: @noindent
10839: where @code{t-rex} is an object or object pointer, created with e.g.
10840: @code{graphical : t-rex}.
10841: 
10842: @cindex abstract class
10843: How do we create a graphical object? With the present definitions,
10844: we cannot create a useful graphical object. The class
10845: @code{graphical} describes graphical objects in general, but not
10846: any concrete graphical object type (C++ users would call it an
10847: @emph{abstract class}); e.g., there is no method for the selector
10848: @code{draw} in the class @code{graphical}.
10849: 
10850: For concrete graphical objects, we define child classes of the
10851: class @code{graphical}, e.g.:
10852: 
10853: @example
10854: graphical class circle \ "graphical" is the parent class
10855:   cell var circle-radius
10856: how:
10857:   : draw ( x y -- )
10858:     circle-radius @@ draw-circle ;
10859: 
10860:   : init ( n-radius -- (
10861:     circle-radius ! ;
10862: class;
10863: @end example
10864: 
10865: Here we define a class @code{circle} as a child of @code{graphical},
10866: with a field @code{circle-radius}; it defines new methods for the
10867: selectors @code{draw} and @code{init} (@code{init} is defined in
10868: @code{object}, the parent class of @code{graphical}).
10869: 
10870: Now we can create a circle in the dictionary with:
10871: 
10872: @example
10873: 50 circle : my-circle
10874: @end example
10875: 
10876: @noindent
10877: @code{:} invokes @code{init}, thus initializing the field
10878: @code{circle-radius} with 50. We can draw this new circle at (100,100)
10879: with:
10880: 
10881: @example
10882: 100 100 my-circle draw
10883: @end example
10884: 
10885: @cindex selector invocation, restrictions
10886: @cindex class definition, restrictions
10887: Note: You can only invoke a selector if the receiving object belongs to
10888: the class where the selector was defined or one of its descendents;
10889: e.g., you can invoke @code{draw} only for objects belonging to
10890: @code{graphical} or its descendents (e.g., @code{circle}). The scoping
10891: mechanism will check if you try to invoke a selector that is not
10892: defined in this class hierarchy, so you'll get an error at compilation
10893: time.
10894: 
10895: 
10896: @node The OOF base class, Class Declaration, Basic OOF Usage, OOF
10897: @subsubsection The @file{oof.fs} base class
10898: @cindex @file{oof.fs} base class
10899: 
10900: When you define a class, you have to specify a parent class.  So how do
10901: you start defining classes? There is one class available from the start:
10902: @code{object}. You have to use it as ancestor for all classes. It is the
10903: only class that has no parent. Classes are also objects, except that
10904: they don't have instance variables; class manipulation such as
10905: inheritance or changing definitions of a class is handled through
10906: selectors of the class @code{object}.
10907: 
10908: @code{object} provides a number of selectors:
10909: 
10910: @itemize @bullet
10911: @item
10912: @code{class} for subclassing, @code{definitions} to add definitions
10913: later on, and @code{class?} to get type informations (is the class a
10914: subclass of the class passed on the stack?).
10915: 
10916: doc---object-class
10917: doc---object-definitions
10918: doc---object-class?
10919: 
10920: 
10921: @item
10922: @code{init} and @code{dispose} as constructor and destructor of the
10923: object. @code{init} is invocated after the object's memory is allocated,
10924: while @code{dispose} also handles deallocation. Thus if you redefine
10925: @code{dispose}, you have to call the parent's dispose with @code{super
10926: dispose}, too.
10927: 
10928: doc---object-init
10929: doc---object-dispose
10930: 
10931: 
10932: @item
10933: @code{new}, @code{new[]}, @code{:}, @code{ptr}, @code{asptr}, and
10934: @code{[]} to create named and unnamed objects and object arrays or
10935: object pointers.
10936: 
10937: doc---object-new
10938: doc---object-new[]
10939: doc---object-:
10940: doc---object-ptr
10941: doc---object-asptr
10942: doc---object-[]
10943: 
10944: 
10945: @item
10946: @code{::} and @code{super} for explicit scoping. You should use explicit
10947: scoping only for super classes or classes with the same set of instance
10948: variables. Explicitly-scoped selectors use early binding.
10949: 
10950: doc---object-::
10951: doc---object-super
10952: 
10953: 
10954: @item
10955: @code{self} to get the address of the object
10956: 
10957: doc---object-self
10958: 
10959: 
10960: @item
10961: @code{bind}, @code{bound}, @code{link}, and @code{is} to assign object
10962: pointers and instance defers.
10963: 
10964: doc---object-bind
10965: doc---object-bound
10966: doc---object-link
10967: doc---object-is
10968: 
10969: 
10970: @item
10971: @code{'} to obtain selector tokens, @code{send} to invocate selectors
10972: form the stack, and @code{postpone} to generate selector invocation code.
10973: 
10974: doc---object-'
10975: doc---object-postpone
10976: 
10977: 
10978: @item
10979: @code{with} and @code{endwith} to select the active object from the
10980: stack, and enable its scope. Using @code{with} and @code{endwith}
10981: also allows you to create code using selector @code{postpone} without being
10982: trapped by the state-smart objects.
10983: 
10984: doc---object-with
10985: doc---object-endwith
10986: 
10987: 
10988: @end itemize
10989: 
10990: @node Class Declaration, Class Implementation, The OOF base class, OOF
10991: @subsubsection Class Declaration
10992: @cindex class declaration
10993: 
10994: @itemize @bullet
10995: @item
10996: Instance variables
10997: 
10998: doc---oof-var
10999: 
11000: 
11001: @item
11002: Object pointers
11003: 
11004: doc---oof-ptr
11005: doc---oof-asptr
11006: 
11007: 
11008: @item
11009: Instance defers
11010: 
11011: doc---oof-defer
11012: 
11013: 
11014: @item
11015: Method selectors
11016: 
11017: doc---oof-early
11018: doc---oof-method
11019: 
11020: 
11021: @item
11022: Class-wide variables
11023: 
11024: doc---oof-static
11025: 
11026: 
11027: @item
11028: End declaration
11029: 
11030: doc---oof-how:
11031: doc---oof-class;
11032: 
11033: 
11034: @end itemize
11035: 
11036: @c -------------------------------------------------------------
11037: @node Class Implementation,  , Class Declaration, OOF
11038: @subsubsection Class Implementation
11039: @cindex class implementation
11040: 
11041: @c -------------------------------------------------------------
11042: @node Mini-OOF, Comparison with other object models, OOF, Object-oriented Forth
11043: @subsection The @file{mini-oof.fs} model
11044: @cindex mini-oof
11045: 
11046: Gforth's third object oriented Forth package is a 12-liner. It uses a
11047: mixture of the @file{objects.fs} and the @file{oof.fs} syntax,
11048: and reduces to the bare minimum of features. This is based on a posting
11049: of Bernd Paysan in comp.lang.forth.
11050: 
11051: @menu
11052: * Basic Mini-OOF Usage::        
11053: * Mini-OOF Example::            
11054: * Mini-OOF Implementation::     
11055: @end menu
11056: 
11057: @c -------------------------------------------------------------
11058: @node Basic Mini-OOF Usage, Mini-OOF Example, Mini-OOF, Mini-OOF
11059: @subsubsection Basic @file{mini-oof.fs} Usage
11060: @cindex mini-oof usage
11061: 
11062: There is a base class (@code{class}, which allocates one cell for the
11063: object pointer) plus seven other words: to define a method, a variable,
11064: a class; to end a class, to resolve binding, to allocate an object and
11065: to compile a class method.
11066: @comment TODO better description of the last one
11067: 
11068: 
11069: doc-object
11070: doc-method
11071: doc-var
11072: doc-class
11073: doc-end-class
11074: doc-defines
11075: doc-new
11076: doc-::
11077: 
11078: 
11079: 
11080: @c -------------------------------------------------------------
11081: @node Mini-OOF Example, Mini-OOF Implementation, Basic Mini-OOF Usage, Mini-OOF
11082: @subsubsection Mini-OOF Example
11083: @cindex mini-oof example
11084: 
11085: A short example shows how to use this package. This example, in slightly
11086: extended form, is supplied as @file{moof-exm.fs}
11087: @comment TODO could flesh this out with some comments from the Forthwrite article
11088: 
11089: @example
11090: object class
11091:   method init
11092:   method draw
11093: end-class graphical
11094: @end example
11095: 
11096: This code defines a class @code{graphical} with an
11097: operation @code{draw}.  We can perform the operation
11098: @code{draw} on any @code{graphical} object, e.g.:
11099: 
11100: @example
11101: 100 100 t-rex draw
11102: @end example
11103: 
11104: where @code{t-rex} is an object or object pointer, created with e.g.
11105: @code{graphical new Constant t-rex}.
11106: 
11107: For concrete graphical objects, we define child classes of the
11108: class @code{graphical}, e.g.:
11109: 
11110: @example
11111: graphical class
11112:   cell var circle-radius
11113: end-class circle \ "graphical" is the parent class
11114: 
11115: :noname ( x y -- )
11116:   circle-radius @@ draw-circle ; circle defines draw
11117: :noname ( r -- )
11118:   circle-radius ! ; circle defines init
11119: @end example
11120: 
11121: There is no implicit init method, so we have to define one. The creation
11122: code of the object now has to call init explicitely.
11123: 
11124: @example
11125: circle new Constant my-circle
11126: 50 my-circle init
11127: @end example
11128: 
11129: It is also possible to add a function to create named objects with
11130: automatic call of @code{init}, given that all objects have @code{init}
11131: on the same place:
11132: 
11133: @example
11134: : new: ( .. o "name" -- )
11135:     new dup Constant init ;
11136: 80 circle new: large-circle
11137: @end example
11138: 
11139: We can draw this new circle at (100,100) with:
11140: 
11141: @example
11142: 100 100 my-circle draw
11143: @end example
11144: 
11145: @node Mini-OOF Implementation,  , Mini-OOF Example, Mini-OOF
11146: @subsubsection @file{mini-oof.fs} Implementation
11147: 
11148: Object-oriented systems with late binding typically use a
11149: ``vtable''-approach: the first variable in each object is a pointer to a
11150: table, which contains the methods as function pointers. The vtable
11151: may also contain other information.
11152: 
11153: So first, let's declare selectors:
11154: 
11155: @example
11156: : method ( m v "name" -- m' v ) Create  over , swap cell+ swap
11157:   DOES> ( ... o -- ... ) @@ over @@ + @@ execute ;
11158: @end example
11159: 
11160: During selector declaration, the number of selectors and instance
11161: variables is on the stack (in address units). @code{method} creates one
11162: selector and increments the selector number. To execute a selector, it
11163: takes the object, fetches the vtable pointer, adds the offset, and
11164: executes the method @i{xt} stored there. Each selector takes the object
11165: it is invoked with as top of stack parameter; it passes the parameters
11166: (including the object) unchanged to the appropriate method which should
11167: consume that object.
11168: 
11169: Now, we also have to declare instance variables
11170: 
11171: @example
11172: : var ( m v size "name" -- m v' ) Create  over , +
11173:   DOES> ( o -- addr ) @@ + ;
11174: @end example
11175: 
11176: As before, a word is created with the current offset. Instance
11177: variables can have different sizes (cells, floats, doubles, chars), so
11178: all we do is take the size and add it to the offset. If your machine
11179: has alignment restrictions, put the proper @code{aligned} or
11180: @code{faligned} before the variable, to adjust the variable
11181: offset. That's why it is on the top of stack.
11182: 
11183: We need a starting point (the base object) and some syntactic sugar:
11184: 
11185: @example
11186: Create object  1 cells , 2 cells ,
11187: : class ( class -- class selectors vars ) dup 2@@ ;
11188: @end example
11189: 
11190: For inheritance, the vtable of the parent object has to be
11191: copied when a new, derived class is declared. This gives all the
11192: methods of the parent class, which can be overridden, though.
11193: 
11194: @example
11195: : end-class  ( class selectors vars "name" -- )
11196:   Create  here >r , dup , 2 cells ?DO ['] noop , 1 cells +LOOP
11197:   cell+ dup cell+ r> rot @@ 2 cells /string move ;
11198: @end example
11199: 
11200: The first line creates the vtable, initialized with
11201: @code{noop}s. The second line is the inheritance mechanism, it
11202: copies the xts from the parent vtable.
11203: 
11204: We still have no way to define new methods, let's do that now:
11205: 
11206: @example
11207: : defines ( xt class "name" -- ) ' >body @@ + ! ;
11208: @end example
11209: 
11210: To allocate a new object, we need a word, too:
11211: 
11212: @example
11213: : new ( class -- o )  here over @@ allot swap over ! ;
11214: @end example
11215: 
11216: Sometimes derived classes want to access the method of the
11217: parent object. There are two ways to achieve this with Mini-OOF:
11218: first, you could use named words, and second, you could look up the
11219: vtable of the parent object.
11220: 
11221: @example
11222: : :: ( class "name" -- ) ' >body @@ + @@ compile, ;
11223: @end example
11224: 
11225: 
11226: Nothing can be more confusing than a good example, so here is
11227: one. First let's declare a text object (called
11228: @code{button}), that stores text and position:
11229: 
11230: @example
11231: object class
11232:   cell var text
11233:   cell var len
11234:   cell var x
11235:   cell var y
11236:   method init
11237:   method draw
11238: end-class button
11239: @end example
11240: 
11241: @noindent
11242: Now, implement the two methods, @code{draw} and @code{init}:
11243: 
11244: @example
11245: :noname ( o -- )
11246:  >r r@@ x @@ r@@ y @@ at-xy  r@@ text @@ r> len @@ type ;
11247:  button defines draw
11248: :noname ( addr u o -- )
11249:  >r 0 r@@ x ! 0 r@@ y ! r@@ len ! r> text ! ;
11250:  button defines init
11251: @end example
11252: 
11253: @noindent
11254: To demonstrate inheritance, we define a class @code{bold-button}, with no
11255: new data and no new selectors:
11256: 
11257: @example
11258: button class
11259: end-class bold-button
11260: 
11261: : bold   27 emit ." [1m" ;
11262: : normal 27 emit ." [0m" ;
11263: @end example
11264: 
11265: @noindent
11266: The class @code{bold-button} has a different draw method to
11267: @code{button}, but the new method is defined in terms of the draw method
11268: for @code{button}:
11269: 
11270: @example
11271: :noname bold [ button :: draw ] normal ; bold-button defines draw
11272: @end example
11273: 
11274: @noindent
11275: Finally, create two objects and apply selectors:
11276: 
11277: @example
11278: button new Constant foo
11279: s" thin foo" foo init
11280: page
11281: foo draw
11282: bold-button new Constant bar
11283: s" fat bar" bar init
11284: 1 bar y !
11285: bar draw
11286: @end example
11287: 
11288: 
11289: @node Comparison with other object models,  , Mini-OOF, Object-oriented Forth
11290: @subsection Comparison with other object models
11291: @cindex comparison of object models
11292: @cindex object models, comparison
11293: 
11294: Many object-oriented Forth extensions have been proposed (@cite{A survey
11295: of object-oriented Forths} (SIGPLAN Notices, April 1996) by Bradford
11296: J. Rodriguez and W. F. S. Poehlman lists 17). This section discusses the
11297: relation of the object models described here to two well-known and two
11298: closely-related (by the use of method maps) models.  Andras Zsoter
11299: helped us with this section.
11300: 
11301: @cindex Neon model
11302: The most popular model currently seems to be the Neon model (see
11303: @cite{Object-oriented programming in ANS Forth} (Forth Dimensions, March
11304: 1997) by Andrew McKewan) but this model has a number of limitations
11305: @footnote{A longer version of this critique can be
11306: found in @cite{On Standardizing Object-Oriented Forth Extensions} (Forth
11307: Dimensions, May 1997) by Anton Ertl.}:
11308: 
11309: @itemize @bullet
11310: @item
11311: It uses a @code{@emph{selector object}} syntax, which makes it unnatural
11312: to pass objects on the stack.
11313: 
11314: @item
11315: It requires that the selector parses the input stream (at
11316: compile time); this leads to reduced extensibility and to bugs that are
11317: hard to find.
11318: 
11319: @item
11320: It allows using every selector on every object; this eliminates the
11321: need for interfaces, but makes it harder to create efficient
11322: implementations.
11323: @end itemize
11324: 
11325: @cindex Pountain's object-oriented model
11326: Another well-known publication is @cite{Object-Oriented Forth} (Academic
11327: Press, London, 1987) by Dick Pountain. However, it is not really about
11328: object-oriented programming, because it hardly deals with late
11329: binding. Instead, it focuses on features like information hiding and
11330: overloading that are characteristic of modular languages like Ada (83).
11331: 
11332: @cindex Zsoter's object-oriented model
11333: In @uref{http://www.forth.org/oopf.html, Does late binding have to be
11334: slow?} (Forth Dimensions 18(1) 1996, pages 31-35) Andras Zsoter
11335: describes a model that makes heavy use of an active object (like
11336: @code{this} in @file{objects.fs}): The active object is not only used
11337: for accessing all fields, but also specifies the receiving object of
11338: every selector invocation; you have to change the active object
11339: explicitly with @code{@{ ... @}}, whereas in @file{objects.fs} it
11340: changes more or less implicitly at @code{m: ... ;m}. Such a change at
11341: the method entry point is unnecessary with Zsoter's model, because the
11342: receiving object is the active object already. On the other hand, the
11343: explicit change is absolutely necessary in that model, because otherwise
11344: no one could ever change the active object. An ANS Forth implementation
11345: of this model is available through
11346: @uref{http://www.forth.org/oopf.html}.
11347: 
11348: @cindex @file{oof.fs}, differences to other models
11349: The @file{oof.fs} model combines information hiding and overloading
11350: resolution (by keeping names in various word lists) with object-oriented
11351: programming. It sets the active object implicitly on method entry, but
11352: also allows explicit changing (with @code{>o...o>} or with
11353: @code{with...endwith}). It uses parsing and state-smart objects and
11354: classes for resolving overloading and for early binding: the object or
11355: class parses the selector and determines the method from this. If the
11356: selector is not parsed by an object or class, it performs a call to the
11357: selector for the active object (late binding), like Zsoter's model.
11358: Fields are always accessed through the active object. The big
11359: disadvantage of this model is the parsing and the state-smartness, which
11360: reduces extensibility and increases the opportunities for subtle bugs;
11361: essentially, you are only safe if you never tick or @code{postpone} an
11362: object or class (Bernd disagrees, but I (Anton) am not convinced).
11363: 
11364: @cindex @file{mini-oof.fs}, differences to other models
11365: The @file{mini-oof.fs} model is quite similar to a very stripped-down
11366: version of the @file{objects.fs} model, but syntactically it is a
11367: mixture of the @file{objects.fs} and @file{oof.fs} models.
11368: 
11369: 
11370: @c -------------------------------------------------------------
11371: @node Programming Tools, Assembler and Code Words, Object-oriented Forth, Words
11372: @section Programming Tools
11373: @cindex programming tools
11374: 
11375: @c !! move this and assembler down below OO stuff.
11376: 
11377: @menu
11378: * Examining::                   
11379: * Forgetting words::            
11380: * Debugging::                   Simple and quick.
11381: * Assertions::                  Making your programs self-checking.
11382: * Singlestep Debugger::         Executing your program word by word.
11383: @end menu
11384: 
11385: @node Examining, Forgetting words, Programming Tools, Programming Tools
11386: @subsection Examining data and code
11387: @cindex examining data and code
11388: @cindex data examination
11389: @cindex code examination
11390: 
11391: The following words inspect the stack non-destructively:
11392: 
11393: doc-.s
11394: doc-f.s
11395: 
11396: There is a word @code{.r} but it does @i{not} display the return stack!
11397: It is used for formatted numeric output (@pxref{Simple numeric output}).
11398: 
11399: doc-depth
11400: doc-fdepth
11401: doc-clearstack
11402: 
11403: The following words inspect memory.
11404: 
11405: doc-?
11406: doc-dump
11407: 
11408: And finally, @code{see} allows to inspect code:
11409: 
11410: doc-see
11411: doc-xt-see
11412: 
11413: @node Forgetting words, Debugging, Examining, Programming Tools
11414: @subsection Forgetting words
11415: @cindex words, forgetting
11416: @cindex forgeting words
11417: 
11418: @c  anton: other, maybe better places for this subsection: Defining Words;
11419: @c  Dictionary allocation.  At least a reference should be there.
11420: 
11421: Forth allows you to forget words (and everything that was alloted in the
11422: dictonary after them) in a LIFO manner.
11423: 
11424: doc-marker
11425: 
11426: The most common use of this feature is during progam development: when
11427: you change a source file, forget all the words it defined and load it
11428: again (since you also forget everything defined after the source file
11429: was loaded, you have to reload that, too).  Note that effects like
11430: storing to variables and destroyed system words are not undone when you
11431: forget words.  With a system like Gforth, that is fast enough at
11432: starting up and compiling, I find it more convenient to exit and restart
11433: Gforth, as this gives me a clean slate.
11434: 
11435: Here's an example of using @code{marker} at the start of a source file
11436: that you are debugging; it ensures that you only ever have one copy of
11437: the file's definitions compiled at any time:
11438: 
11439: @example
11440: [IFDEF] my-code
11441:     my-code
11442: [ENDIF]
11443: 
11444: marker my-code
11445: init-included-files
11446: 
11447: \ .. definitions start here
11448: \ .
11449: \ .
11450: \ end
11451: @end example
11452: 
11453: 
11454: @node Debugging, Assertions, Forgetting words, Programming Tools
11455: @subsection Debugging
11456: @cindex debugging
11457: 
11458: Languages with a slow edit/compile/link/test development loop tend to
11459: require sophisticated tracing/stepping debuggers to facilate debugging.
11460: 
11461: A much better (faster) way in fast-compiling languages is to add
11462: printing code at well-selected places, let the program run, look at
11463: the output, see where things went wrong, add more printing code, etc.,
11464: until the bug is found.
11465: 
11466: The simple debugging aids provided in @file{debugs.fs}
11467: are meant to support this style of debugging.
11468: 
11469: The word @code{~~} prints debugging information (by default the source
11470: location and the stack contents). It is easy to insert. If you use Emacs
11471: it is also easy to remove (@kbd{C-x ~} in the Emacs Forth mode to
11472: query-replace them with nothing). The deferred words
11473: @code{printdebugdata} and @code{printdebugline} control the output of
11474: @code{~~}. The default source location output format works well with
11475: Emacs' compilation mode, so you can step through the program at the
11476: source level using @kbd{C-x `} (the advantage over a stepping debugger
11477: is that you can step in any direction and you know where the crash has
11478: happened or where the strange data has occurred).
11479: 
11480: doc-~~
11481: doc-printdebugdata
11482: doc-printdebugline
11483: 
11484: @node Assertions, Singlestep Debugger, Debugging, Programming Tools
11485: @subsection Assertions
11486: @cindex assertions
11487: 
11488: It is a good idea to make your programs self-checking, especially if you
11489: make an assumption that may become invalid during maintenance (for
11490: example, that a certain field of a data structure is never zero). Gforth
11491: supports @dfn{assertions} for this purpose. They are used like this:
11492: 
11493: @example
11494: assert( @i{flag} )
11495: @end example
11496: 
11497: The code between @code{assert(} and @code{)} should compute a flag, that
11498: should be true if everything is alright and false otherwise. It should
11499: not change anything else on the stack. The overall stack effect of the
11500: assertion is @code{( -- )}. E.g.
11501: 
11502: @example
11503: assert( 1 1 + 2 = ) \ what we learn in school
11504: assert( dup 0<> ) \ assert that the top of stack is not zero
11505: assert( false ) \ this code should not be reached
11506: @end example
11507: 
11508: The need for assertions is different at different times. During
11509: debugging, we want more checking, in production we sometimes care more
11510: for speed. Therefore, assertions can be turned off, i.e., the assertion
11511: becomes a comment. Depending on the importance of an assertion and the
11512: time it takes to check it, you may want to turn off some assertions and
11513: keep others turned on. Gforth provides several levels of assertions for
11514: this purpose:
11515: 
11516: 
11517: doc-assert0(
11518: doc-assert1(
11519: doc-assert2(
11520: doc-assert3(
11521: doc-assert(
11522: doc-)
11523: 
11524: 
11525: The variable @code{assert-level} specifies the highest assertions that
11526: are turned on. I.e., at the default @code{assert-level} of one,
11527: @code{assert0(} and @code{assert1(} assertions perform checking, while
11528: @code{assert2(} and @code{assert3(} assertions are treated as comments.
11529: 
11530: The value of @code{assert-level} is evaluated at compile-time, not at
11531: run-time. Therefore you cannot turn assertions on or off at run-time;
11532: you have to set the @code{assert-level} appropriately before compiling a
11533: piece of code. You can compile different pieces of code at different
11534: @code{assert-level}s (e.g., a trusted library at level 1 and
11535: newly-written code at level 3).
11536: 
11537: 
11538: doc-assert-level
11539: 
11540: 
11541: If an assertion fails, a message compatible with Emacs' compilation mode
11542: is produced and the execution is aborted (currently with @code{ABORT"}.
11543: If there is interest, we will introduce a special throw code. But if you
11544: intend to @code{catch} a specific condition, using @code{throw} is
11545: probably more appropriate than an assertion).
11546: 
11547: Definitions in ANS Forth for these assertion words are provided
11548: in @file{compat/assert.fs}.
11549: 
11550: 
11551: @node Singlestep Debugger,  , Assertions, Programming Tools
11552: @subsection Singlestep Debugger
11553: @cindex singlestep Debugger
11554: @cindex debugging Singlestep
11555: 
11556: When you create a new word there's often the need to check whether it
11557: behaves correctly or not. You can do this by typing @code{dbg
11558: badword}. A debug session might look like this:
11559: 
11560: @example
11561: : badword 0 DO i . LOOP ;  ok
11562: 2 dbg badword 
11563: : badword  
11564: Scanning code...
11565: 
11566: Nesting debugger ready!
11567: 
11568: 400D4738  8049BC4 0              -> [ 2 ] 00002 00000 
11569: 400D4740  8049F68 DO             -> [ 0 ] 
11570: 400D4744  804A0C8 i              -> [ 1 ] 00000 
11571: 400D4748 400C5E60 .              -> 0 [ 0 ] 
11572: 400D474C  8049D0C LOOP           -> [ 0 ] 
11573: 400D4744  804A0C8 i              -> [ 1 ] 00001 
11574: 400D4748 400C5E60 .              -> 1 [ 0 ] 
11575: 400D474C  8049D0C LOOP           -> [ 0 ] 
11576: 400D4758  804B384 ;              ->  ok
11577: @end example
11578: 
11579: Each line displayed is one step. You always have to hit return to
11580: execute the next word that is displayed. If you don't want to execute
11581: the next word in a whole, you have to type @kbd{n} for @code{nest}. Here is
11582: an overview what keys are available:
11583: 
11584: @table @i
11585: 
11586: @item @key{RET}
11587: Next; Execute the next word.
11588: 
11589: @item n
11590: Nest; Single step through next word.
11591: 
11592: @item u
11593: Unnest; Stop debugging and execute rest of word. If we got to this word
11594: with nest, continue debugging with the calling word.
11595: 
11596: @item d
11597: Done; Stop debugging and execute rest.
11598: 
11599: @item s
11600: Stop; Abort immediately.
11601: 
11602: @end table
11603: 
11604: Debugging large application with this mechanism is very difficult, because
11605: you have to nest very deeply into the program before the interesting part
11606: begins. This takes a lot of time. 
11607: 
11608: To do it more directly put a @code{BREAK:} command into your source code.
11609: When program execution reaches @code{BREAK:} the single step debugger is
11610: invoked and you have all the features described above.
11611: 
11612: If you have more than one part to debug it is useful to know where the
11613: program has stopped at the moment. You can do this by the 
11614: @code{BREAK" string"} command. This behaves like @code{BREAK:} except that
11615: string is typed out when the ``breakpoint'' is reached.
11616: 
11617: 
11618: doc-dbg
11619: doc-break:
11620: doc-break"
11621: 
11622: 
11623: 
11624: @c -------------------------------------------------------------
11625: @node Assembler and Code Words, Threading Words, Programming Tools, Words
11626: @section Assembler and Code Words
11627: @cindex assembler
11628: @cindex code words
11629: 
11630: @menu
11631: * Code and ;code::              
11632: * Common Assembler::            Assembler Syntax
11633: * Common Disassembler::         
11634: * 386 Assembler::               Deviations and special cases
11635: * Alpha Assembler::             Deviations and special cases
11636: * MIPS assembler::              Deviations and special cases
11637: * Other assemblers::            How to write them
11638: @end menu
11639: 
11640: @node Code and ;code, Common Assembler, Assembler and Code Words, Assembler and Code Words
11641: @subsection @code{Code} and @code{;code}
11642: 
11643: Gforth provides some words for defining primitives (words written in
11644: machine code), and for defining the machine-code equivalent of
11645: @code{DOES>}-based defining words. However, the machine-independent
11646: nature of Gforth poses a few problems: First of all, Gforth runs on
11647: several architectures, so it can provide no standard assembler. What's
11648: worse is that the register allocation not only depends on the processor,
11649: but also on the @code{gcc} version and options used.
11650: 
11651: The words that Gforth offers encapsulate some system dependences (e.g.,
11652: the header structure), so a system-independent assembler may be used in
11653: Gforth. If you do not have an assembler, you can compile machine code
11654: directly with @code{,} and @code{c,}@footnote{This isn't portable,
11655: because these words emit stuff in @i{data} space; it works because
11656: Gforth has unified code/data spaces. Assembler isn't likely to be
11657: portable anyway.}.
11658: 
11659: 
11660: doc-assembler
11661: doc-init-asm
11662: doc-code
11663: doc-end-code
11664: doc-;code
11665: doc-flush-icache
11666: 
11667: 
11668: If @code{flush-icache} does not work correctly, @code{code} words
11669: etc. will not work (reliably), either.
11670: 
11671: The typical usage of these @code{code} words can be shown most easily by
11672: analogy to the equivalent high-level defining words:
11673: 
11674: @example
11675: : foo                              code foo
11676:    <high-level Forth words>              <assembler>
11677: ;                                  end-code
11678:                                 
11679: : bar                              : bar
11680:    <high-level Forth words>           <high-level Forth words>
11681:    CREATE                             CREATE
11682:       <high-level Forth words>           <high-level Forth words>
11683:    DOES>                              ;code
11684:       <high-level Forth words>           <assembler>
11685: ;                                  end-code
11686: @end example
11687: 
11688: @c anton: the following stuff is also in "Common Assembler", in less detail.
11689: 
11690: @cindex registers of the inner interpreter
11691: In the assembly code you will want to refer to the inner interpreter's
11692: registers (e.g., the data stack pointer) and you may want to use other
11693: registers for temporary storage. Unfortunately, the register allocation
11694: is installation-dependent.
11695: 
11696: In particular, @code{ip} (Forth instruction pointer) and @code{rp}
11697: (return stack pointer) are in different places in @code{gforth} and
11698: @code{gforth-fast}.  This means that you cannot write a @code{NEXT}
11699: routine that works on both versions; so for doing @code{NEXT}, I
11700: recomment jumping to @code{' noop >code-address}, which contains nothing
11701: but a @code{NEXT}.
11702: 
11703: For general accesses to the inner interpreter's registers, the easiest
11704: solution is to use explicit register declarations (@pxref{Explicit Reg
11705: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) for
11706: all of the inner interpreter's registers: You have to compile Gforth
11707: with @code{-DFORCE_REG} (configure option @code{--enable-force-reg}) and
11708: the appropriate declarations must be present in the @code{machine.h}
11709: file (see @code{mips.h} for an example; you can find a full list of all
11710: declarable register symbols with @code{grep register engine.c}). If you
11711: give explicit registers to all variables that are declared at the
11712: beginning of @code{engine()}, you should be able to use the other
11713: caller-saved registers for temporary storage. Alternatively, you can use
11714: the @code{gcc} option @code{-ffixed-REG} (@pxref{Code Gen Options, ,
11715: Options for Code Generation Conventions, gcc.info, GNU C Manual}) to
11716: reserve a register (however, this restriction on register allocation may
11717: slow Gforth significantly).
11718: 
11719: If this solution is not viable (e.g., because @code{gcc} does not allow
11720: you to explicitly declare all the registers you need), you have to find
11721: out by looking at the code where the inner interpreter's registers
11722: reside and which registers can be used for temporary storage. You can
11723: get an assembly listing of the engine's code with @code{make engine.s}.
11724: 
11725: In any case, it is good practice to abstract your assembly code from the
11726: actual register allocation. E.g., if the data stack pointer resides in
11727: register @code{$17}, create an alias for this register called @code{sp},
11728: and use that in your assembly code.
11729: 
11730: @cindex code words, portable
11731: Another option for implementing normal and defining words efficiently
11732: is to add the desired functionality to the source of Gforth. For normal
11733: words you just have to edit @file{primitives} (@pxref{Automatic
11734: Generation}). Defining words (equivalent to @code{;CODE} words, for fast
11735: defined words) may require changes in @file{engine.c}, @file{kernel.fs},
11736: @file{prims2x.fs}, and possibly @file{cross.fs}.
11737: 
11738: @node Common Assembler, Common Disassembler, Code and ;code, Assembler and Code Words
11739: @subsection Common Assembler
11740: 
11741: The assemblers in Gforth generally use a postfix syntax, i.e., the
11742: instruction name follows the operands.
11743: 
11744: The operands are passed in the usual order (the same that is used in the
11745: manual of the architecture).  Since they all are Forth words, they have
11746: to be separated by spaces; you can also use Forth words to compute the
11747: operands.
11748: 
11749: The instruction names usually end with a @code{,}.  This makes it easier
11750: to visually separate instructions if you put several of them on one
11751: line; it also avoids shadowing other Forth words (e.g., @code{and}).
11752: 
11753: Registers are usually specified by number; e.g., (decimal) @code{11}
11754: specifies registers R11 and F11 on the Alpha architecture (which one,
11755: depends on the instruction).  The usual names are also available, e.g.,
11756: @code{s2} for R11 on Alpha.
11757: 
11758: Control flow is specified similar to normal Forth code (@pxref{Arbitrary
11759: control structures}), with @code{if,}, @code{ahead,}, @code{then,},
11760: @code{begin,}, @code{until,}, @code{again,}, @code{cs-roll},
11761: @code{cs-pick}, @code{else,}, @code{while,}, and @code{repeat,}.  The
11762: conditions are specified in a way specific to each assembler.
11763: 
11764: Note that the register assignments of the Gforth engine can change
11765: between Gforth versions, or even between different compilations of the
11766: same Gforth version (e.g., if you use a different GCC version).  So if
11767: you want to refer to Gforth's registers (e.g., the stack pointer or
11768: TOS), I recommend defining your own words for refering to these
11769: registers, and using them later on; then you can easily adapt to a
11770: changed register assignment.  The stability of the register assignment
11771: is usually better if you build Gforth with @code{--enable-force-reg}.
11772: 
11773: In particular, the return stack pointer and the instruction pointer are
11774: in memory in @code{gforth}, and usually in registers in
11775: @code{gforth-fast}.  The most common use of these registers is to
11776: dispatch to the next word (the @code{next} routine).  A portable way to
11777: do this is to jump to @code{' noop >code-address} (of course, this is
11778: less efficient than integrating the @code{next} code and scheduling it
11779: well).
11780: 
11781: @node  Common Disassembler, 386 Assembler, Common Assembler, Assembler and Code Words
11782: @subsection Common Disassembler
11783: 
11784: You can disassemble a @code{code} word with @code{see}
11785: (@pxref{Debugging}).  You can disassemble a section of memory with
11786: 
11787: doc-disasm
11788: 
11789: The disassembler generally produces output that can be fed into the
11790: assembler (i.e., same syntax, etc.).  It also includes additional
11791: information in comments.  In particular, the address of the instruction
11792: is given in a comment before the instruction.
11793: 
11794: @code{See} may display more or less than the actual code of the word,
11795: because the recognition of the end of the code is unreliable.  You can
11796: use @code{disasm} if it did not display enough.  It may display more, if
11797: the code word is not immediately followed by a named word.  If you have
11798: something else there, you can follow the word with @code{align last @ ,}
11799: to ensure that the end is recognized.
11800: 
11801: @node 386 Assembler, Alpha Assembler, Common Disassembler, Assembler and Code Words
11802: @subsection 386 Assembler
11803: 
11804: The 386 assembler included in Gforth was written by Bernd Paysan, it's
11805: available under GPL, and originally part of bigFORTH.
11806: 
11807: The 386 disassembler included in Gforth was written by Andrew McKewan
11808: and is in the public domain.
11809: 
11810: The disassembler displays code in prefix Intel syntax.
11811: 
11812: The assembler uses a postfix syntax with reversed parameters.
11813: 
11814: The assembler includes all instruction of the Athlon, i.e. 486 core
11815: instructions, Pentium and PPro extensions, floating point, MMX, 3Dnow!,
11816: but not ISSE. It's an integrated 16- and 32-bit assembler. Default is 32
11817: bit, you can switch to 16 bit with .86 and back to 32 bit with .386.
11818: 
11819: There are several prefixes to switch between different operation sizes,
11820: @code{.b} for byte accesses, @code{.w} for word accesses, @code{.d} for
11821: double-word accesses. Addressing modes can be switched with @code{.wa}
11822: for 16 bit addresses, and @code{.da} for 32 bit addresses. You don't
11823: need a prefix for byte register names (@code{AL} et al).
11824: 
11825: For floating point operations, the prefixes are @code{.fs} (IEEE
11826: single), @code{.fl} (IEEE double), @code{.fx} (extended), @code{.fw}
11827: (word), @code{.fd} (double-word), and @code{.fq} (quad-word).
11828: 
11829: The MMX opcodes don't have size prefixes, they are spelled out like in
11830: the Intel assembler. Instead of move from and to memory, there are
11831: PLDQ/PLDD and PSTQ/PSTD.
11832: 
11833: The registers lack the 'e' prefix; even in 32 bit mode, eax is called
11834: ax.  Immediate values are indicated by postfixing them with @code{#},
11835: e.g., @code{3 #}.  Here are some examples of addressing modes:
11836: 
11837: @example
11838: 3 #          \ immediate
11839: ax           \ register
11840: 100 di d)    \ 100[edi]
11841: 4 bx cx di)  \ 4[ebx][ecx]
11842: di ax *4 i)  \ [edi][eax*4]
11843: 20 ax *4 i#) \ 20[eax*4]
11844: @end example
11845: 
11846: Some example of instructions are:
11847: 
11848: @example
11849: ax bx mov             \ move ebx,eax
11850: 3 # ax mov            \ mov eax,3
11851: 100 di ) ax mov       \ mov eax,100[edi]
11852: 4 bx cx di) ax mov    \ mov eax,4[ebx][ecx]
11853: .w ax bx mov          \ mov bx,ax
11854: @end example
11855: 
11856: The following forms are supported for binary instructions:
11857: 
11858: @example
11859: <reg> <reg> <inst>
11860: <n> # <reg> <inst>
11861: <mem> <reg> <inst>
11862: <reg> <mem> <inst>
11863: @end example
11864: 
11865: Immediate to memory is not supported.  The shift/rotate syntax is:
11866: 
11867: @example
11868: <reg/mem> 1 # shl \ shortens to shift without immediate
11869: <reg/mem> 4 # shl
11870: <reg/mem> cl shl
11871: @end example
11872: 
11873: Precede string instructions (@code{movs} etc.) with @code{.b} to get
11874: the byte version.
11875: 
11876: The control structure words @code{IF} @code{UNTIL} etc. must be preceded
11877: by one of these conditions: @code{vs vc u< u>= 0= 0<> u<= u> 0< 0>= ps
11878: pc < >= <= >}. (Note that most of these words shadow some Forth words
11879: when @code{assembler} is in front of @code{forth} in the search path,
11880: e.g., in @code{code} words).  Currently the control structure words use
11881: one stack item, so you have to use @code{roll} instead of @code{cs-roll}
11882: to shuffle them (you can also use @code{swap} etc.).
11883: 
11884: Here is an example of a @code{code} word (assumes that the stack pointer
11885: is in esi and the TOS is in ebx):
11886: 
11887: @example
11888: code my+ ( n1 n2 -- n )
11889:     4 si D) bx add
11890:     4 # si add
11891:     Next
11892: end-code
11893: @end example
11894: 
11895: @node Alpha Assembler, MIPS assembler, 386 Assembler, Assembler and Code Words
11896: @subsection Alpha Assembler
11897: 
11898: The Alpha assembler and disassembler were originally written by Bernd
11899: Thallner.
11900: 
11901: The register names @code{a0}--@code{a5} are not available to avoid
11902: shadowing hex numbers.
11903: 
11904: Immediate forms of arithmetic instructions are distinguished by a
11905: @code{#} just before the @code{,}, e.g., @code{and#,} (note: @code{lda,}
11906: does not count as arithmetic instruction).
11907: 
11908: You have to specify all operands to an instruction, even those that
11909: other assemblers consider optional, e.g., the destination register for
11910: @code{br,}, or the destination register and hint for @code{jmp,}.
11911: 
11912: You can specify conditions for @code{if,} by removing the first @code{b}
11913: and the trailing @code{,} from a branch with a corresponding name; e.g.,
11914: 
11915: @example
11916: 11 fgt if, \ if F11>0e
11917:   ...
11918: endif,
11919: @end example
11920: 
11921: @code{fbgt,} gives @code{fgt}.  
11922: 
11923: @node MIPS assembler, Other assemblers, Alpha Assembler, Assembler and Code Words
11924: @subsection MIPS assembler
11925: 
11926: The MIPS assembler was originally written by Christian Pirker.
11927: 
11928: Currently the assembler and disassembler only cover the MIPS-I
11929: architecture (R3000), and don't support FP instructions.
11930: 
11931: The register names @code{$a0}--@code{$a3} are not available to avoid
11932: shadowing hex numbers.
11933: 
11934: Because there is no way to distinguish registers from immediate values,
11935: you have to explicitly use the immediate forms of instructions, i.e.,
11936: @code{addiu,}, not just @code{addu,} (@command{as} does this
11937: implicitly).
11938: 
11939: If the architecture manual specifies several formats for the instruction
11940: (e.g., for @code{jalr,}), you usually have to use the one with more
11941: arguments (i.e., two for @code{jalr,}).  When in doubt, see
11942: @code{arch/mips/testasm.fs} for an example of correct use.
11943: 
11944: Branches and jumps in the MIPS architecture have a delay slot.  You have
11945: to fill it yourself (the simplest way is to use @code{nop,}), the
11946: assembler does not do it for you (unlike @command{as}).  Even
11947: @code{if,}, @code{ahead,}, @code{until,}, @code{again,}, @code{while,},
11948: @code{else,} and @code{repeat,} need a delay slot.  Since @code{begin,}
11949: and @code{then,} just specify branch targets, they are not affected.
11950: 
11951: Note that you must not put branches, jumps, or @code{li,} into the delay
11952: slot: @code{li,} may expand to several instructions, and control flow
11953: instructions may not be put into the branch delay slot in any case.
11954: 
11955: For branches the argument specifying the target is a relative address;
11956: You have to add the address of the delay slot to get the absolute
11957: address.
11958: 
11959: The MIPS architecture also has load delay slots and restrictions on
11960: using @code{mfhi,} and @code{mflo,}; you have to order the instructions
11961: yourself to satisfy these restrictions, the assembler does not do it for
11962: you.
11963: 
11964: You can specify the conditions for @code{if,} etc. by taking a
11965: conditional branch and leaving away the @code{b} at the start and the
11966: @code{,} at the end.  E.g.,
11967: 
11968: @example
11969: 4 5 eq if,
11970:   ... \ do something if $4 equals $5
11971: then,
11972: @end example
11973: 
11974: @node Other assemblers,  , MIPS assembler, Assembler and Code Words
11975: @subsection Other assemblers
11976: 
11977: If you want to contribute another assembler/disassembler, please contact
11978: us (@email{bug-gforth@@gnu.org}) to check if we have such an assembler
11979: already.  If you are writing them from scratch, please use a similar
11980: syntax style as the one we use (i.e., postfix, commas at the end of the
11981: instruction names, @pxref{Common Assembler}); make the output of the
11982: disassembler be valid input for the assembler, and keep the style
11983: similar to the style we used.
11984: 
11985: Hints on implementation: The most important part is to have a good test
11986: suite that contains all instructions.  Once you have that, the rest is
11987: easy.  For actual coding you can take a look at
11988: @file{arch/mips/disasm.fs} to get some ideas on how to use data for both
11989: the assembler and disassembler, avoiding redundancy and some potential
11990: bugs.  You can also look at that file (and @pxref{Advanced does> usage
11991: example}) to get ideas how to factor a disassembler.
11992: 
11993: Start with the disassembler, because it's easier to reuse data from the
11994: disassembler for the assembler than the other way round.
11995: 
11996: For the assembler, take a look at @file{arch/alpha/asm.fs}, which shows
11997: how simple it can be.
11998: 
11999: @c -------------------------------------------------------------
12000: @node Threading Words, Passing Commands to the OS, Assembler and Code Words, Words
12001: @section Threading Words
12002: @cindex threading words
12003: 
12004: @cindex code address
12005: These words provide access to code addresses and other threading stuff
12006: in Gforth (and, possibly, other interpretive Forths). It more or less
12007: abstracts away the differences between direct and indirect threading
12008: (and, for direct threading, the machine dependences). However, at
12009: present this wordset is still incomplete. It is also pretty low-level;
12010: some day it will hopefully be made unnecessary by an internals wordset
12011: that abstracts implementation details away completely.
12012: 
12013: The terminology used here stems from indirect threaded Forth systems; in
12014: such a system, the XT of a word is represented by the CFA (code field
12015: address) of a word; the CFA points to a cell that contains the code
12016: address.  The code address is the address of some machine code that
12017: performs the run-time action of invoking the word (e.g., the
12018: @code{dovar:} routine pushes the address of the body of the word (a
12019: variable) on the stack
12020: ).
12021: 
12022: @cindex code address
12023: @cindex code field address
12024: In an indirect threaded Forth, you can get the code address of @i{name}
12025: with @code{' @i{name} @@}; in Gforth you can get it with @code{' @i{name}
12026: >code-address}, independent of the threading method.
12027: 
12028: doc-threading-method
12029: doc->code-address
12030: doc-code-address!
12031: 
12032: @cindex @code{does>}-handler
12033: @cindex @code{does>}-code
12034: For a word defined with @code{DOES>}, the code address usually points to
12035: a jump instruction (the @dfn{does-handler}) that jumps to the dodoes
12036: routine (in Gforth on some platforms, it can also point to the dodoes
12037: routine itself).  What you are typically interested in, though, is
12038: whether a word is a @code{DOES>}-defined word, and what Forth code it
12039: executes; @code{>does-code} tells you that.
12040: 
12041: doc->does-code
12042: 
12043: To create a @code{DOES>}-defined word with the following basic words,
12044: you have to set up a @code{DOES>}-handler with @code{does-handler!};
12045: @code{/does-handler} aus behind you have to place your executable Forth
12046: code.  Finally you have to create a word and modify its behaviour with
12047: @code{does-handler!}.
12048: 
12049: doc-does-code!
12050: doc-does-handler!
12051: doc-/does-handler
12052: 
12053: The code addresses produced by various defining words are produced by
12054: the following words:
12055: 
12056: doc-docol:
12057: doc-docon:
12058: doc-dovar:
12059: doc-douser:
12060: doc-dodefer:
12061: doc-dofield:
12062: 
12063: @c -------------------------------------------------------------
12064: @node Passing Commands to the OS, Keeping track of Time, Threading Words, Words
12065: @section Passing Commands to the Operating System
12066: @cindex operating system - passing commands
12067: @cindex shell commands
12068: 
12069: Gforth allows you to pass an arbitrary string to the host operating
12070: system shell (if such a thing exists) for execution.
12071: 
12072: 
12073: doc-sh
12074: doc-system
12075: doc-$?
12076: doc-getenv
12077: 
12078: 
12079: @c -------------------------------------------------------------
12080: @node Keeping track of Time, Miscellaneous Words, Passing Commands to the OS, Words
12081: @section Keeping track of Time
12082: @cindex time-related words
12083: 
12084: doc-ms
12085: doc-time&date
12086: doc-utime
12087: doc-cputime
12088: 
12089: 
12090: @c -------------------------------------------------------------
12091: @node Miscellaneous Words,  , Keeping track of Time, Words
12092: @section Miscellaneous Words
12093: @cindex miscellaneous words
12094: 
12095: @comment TODO find homes for these
12096: 
12097: These section lists the ANS Forth words that are not documented
12098: elsewhere in this manual. Ultimately, they all need proper homes.
12099: 
12100: doc-quit
12101: 
12102: The following ANS Forth words are not currently supported by Gforth 
12103: (@pxref{ANS conformance}):
12104: 
12105: @code{EDITOR} 
12106: @code{EMIT?} 
12107: @code{FORGET} 
12108: 
12109: @c ******************************************************************
12110: @node Error messages, Tools, Words, Top
12111: @chapter Error messages
12112: @cindex error messages
12113: @cindex backtrace
12114: 
12115: A typical Gforth error message looks like this:
12116: 
12117: @example
12118: in file included from :-1
12119: in file included from ./yyy.fs:1
12120: ./xxx.fs:4: Invalid memory address
12121: bar
12122: ^^^
12123: Backtrace:
12124: $400E664C @@
12125: $400E6664 foo
12126: @end example
12127: 
12128: The message identifying the error is @code{Invalid memory address}.  The
12129: error happened when text-interpreting line 4 of the file
12130: @file{./xxx.fs}. This line is given (it contains @code{bar}), and the
12131: word on the line where the error happened, is pointed out (with
12132: @code{^^^}).
12133: 
12134: The file containing the error was included in line 1 of @file{./yyy.fs},
12135: and @file{yyy.fs} was included from a non-file (in this case, by giving
12136: @file{yyy.fs} as command-line parameter to Gforth).
12137: 
12138: At the end of the error message you find a return stack dump that can be
12139: interpreted as a backtrace (possibly empty). On top you find the top of
12140: the return stack when the @code{throw} happened, and at the bottom you
12141: find the return stack entry just above the return stack of the topmost
12142: text interpreter.
12143: 
12144: To the right of most return stack entries you see a guess for the word
12145: that pushed that return stack entry as its return address. This gives a
12146: backtrace. In our case we see that @code{bar} called @code{foo}, and
12147: @code{foo} called @code{@@} (and @code{@@} had an @emph{Invalid memory
12148: address} exception).
12149: 
12150: Note that the backtrace is not perfect: We don't know which return stack
12151: entries are return addresses (so we may get false positives); and in
12152: some cases (e.g., for @code{abort"}) we cannot determine from the return
12153: address the word that pushed the return address, so for some return
12154: addresses you see no names in the return stack dump.
12155: 
12156: @cindex @code{catch} and backtraces
12157: The return stack dump represents the return stack at the time when a
12158: specific @code{throw} was executed.  In programs that make use of
12159: @code{catch}, it is not necessarily clear which @code{throw} should be
12160: used for the return stack dump (e.g., consider one @code{throw} that
12161: indicates an error, which is caught, and during recovery another error
12162: happens; which @code{throw} should be used for the stack dump?).  Gforth
12163: presents the return stack dump for the first @code{throw} after the last
12164: executed (not returned-to) @code{catch}; this works well in the usual
12165: case.
12166: 
12167: @cindex @code{gforth-fast} and backtraces
12168: @cindex @code{gforth-fast}, difference from @code{gforth}
12169: @cindex backtraces with @code{gforth-fast}
12170: @cindex return stack dump with @code{gforth-fast}
12171: @code{Gforth} is able to do a return stack dump for throws generated
12172: from primitives (e.g., invalid memory address, stack empty etc.);
12173: @code{gforth-fast} is only able to do a return stack dump from a
12174: directly called @code{throw} (including @code{abort} etc.).  This is the
12175: only difference (apart from a speed factor of between 1.15 (K6-2) and
12176: 2 (21264)) between @code{gforth} and @code{gforth-fast}.  Given an
12177: exception caused by a primitive in @code{gforth-fast}, you will
12178: typically see no return stack dump at all; however, if the exception is
12179: caught by @code{catch} (e.g., for restoring some state), and then
12180: @code{throw}n again, the return stack dump will be for the first such
12181: @code{throw}.
12182: 
12183: @c ******************************************************************
12184: @node Tools, ANS conformance, Error messages, Top
12185: @chapter Tools
12186: 
12187: @menu
12188: * ANS Report::                  Report the words used, sorted by wordset.
12189: @end menu
12190: 
12191: See also @ref{Emacs and Gforth}.
12192: 
12193: @node ANS Report,  , Tools, Tools
12194: @section @file{ans-report.fs}: Report the words used, sorted by wordset
12195: @cindex @file{ans-report.fs}
12196: @cindex report the words used in your program
12197: @cindex words used in your program
12198: 
12199: If you want to label a Forth program as ANS Forth Program, you must
12200: document which wordsets the program uses; for extension wordsets, it is
12201: helpful to list the words the program requires from these wordsets
12202: (because Forth systems are allowed to provide only some words of them).
12203: 
12204: The @file{ans-report.fs} tool makes it easy for you to determine which
12205: words from which wordset and which non-ANS words your application
12206: uses. You simply have to include @file{ans-report.fs} before loading the
12207: program you want to check. After loading your program, you can get the
12208: report with @code{print-ans-report}. A typical use is to run this as
12209: batch job like this:
12210: @example
12211: gforth ans-report.fs myprog.fs -e "print-ans-report bye"
12212: @end example
12213: 
12214: The output looks like this (for @file{compat/control.fs}):
12215: @example
12216: The program uses the following words
12217: from CORE :
12218: : POSTPONE THEN ; immediate ?dup IF 0= 
12219: from BLOCK-EXT :
12220: \ 
12221: from FILE :
12222: ( 
12223: @end example
12224: 
12225: @subsection Caveats
12226: 
12227: Note that @file{ans-report.fs} just checks which words are used, not whether
12228: they are used in an ANS Forth conforming way!
12229: 
12230: Some words are defined in several wordsets in the
12231: standard. @file{ans-report.fs} reports them for only one of the
12232: wordsets, and not necessarily the one you expect. It depends on usage
12233: which wordset is the right one to specify. E.g., if you only use the
12234: compilation semantics of @code{S"}, it is a Core word; if you also use
12235: its interpretation semantics, it is a File word.
12236: 
12237: @c ******************************************************************
12238: @node ANS conformance, Standard vs Extensions, Tools, Top
12239: @chapter ANS conformance
12240: @cindex ANS conformance of Gforth
12241: 
12242: To the best of our knowledge, Gforth is an
12243: 
12244: ANS Forth System
12245: @itemize @bullet
12246: @item providing the Core Extensions word set
12247: @item providing the Block word set
12248: @item providing the Block Extensions word set
12249: @item providing the Double-Number word set
12250: @item providing the Double-Number Extensions word set
12251: @item providing the Exception word set
12252: @item providing the Exception Extensions word set
12253: @item providing the Facility word set
12254: @item providing @code{EKEY}, @code{EKEY>CHAR}, @code{EKEY?}, @code{MS} and @code{TIME&DATE} from the Facility Extensions word set
12255: @item providing the File Access word set
12256: @item providing the File Access Extensions word set
12257: @item providing the Floating-Point word set
12258: @item providing the Floating-Point Extensions word set
12259: @item providing the Locals word set
12260: @item providing the Locals Extensions word set
12261: @item providing the Memory-Allocation word set
12262: @item providing the Memory-Allocation Extensions word set (that one's easy)
12263: @item providing the Programming-Tools word set
12264: @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
12265: @item providing the Search-Order word set
12266: @item providing the Search-Order Extensions word set
12267: @item providing the String word set
12268: @item providing the String Extensions word set (another easy one)
12269: @end itemize
12270: 
12271: @cindex system documentation
12272: In addition, ANS Forth systems are required to document certain
12273: implementation choices. This chapter tries to meet these
12274: requirements. In many cases it gives a way to ask the system for the
12275: information instead of providing the information directly, in
12276: particular, if the information depends on the processor, the operating
12277: system or the installation options chosen, or if they are likely to
12278: change during the maintenance of Gforth.
12279: 
12280: @comment The framework for the rest has been taken from pfe.
12281: 
12282: @menu
12283: * The Core Words::              
12284: * The optional Block word set::  
12285: * The optional Double Number word set::  
12286: * The optional Exception word set::  
12287: * The optional Facility word set::  
12288: * The optional File-Access word set::  
12289: * The optional Floating-Point word set::  
12290: * The optional Locals word set::  
12291: * The optional Memory-Allocation word set::  
12292: * The optional Programming-Tools word set::  
12293: * The optional Search-Order word set::  
12294: @end menu
12295: 
12296: 
12297: @c =====================================================================
12298: @node The Core Words, The optional Block word set, ANS conformance, ANS conformance
12299: @comment  node-name,  next,  previous,  up
12300: @section The Core Words
12301: @c =====================================================================
12302: @cindex core words, system documentation
12303: @cindex system documentation, core words
12304: 
12305: @menu
12306: * core-idef::                   Implementation Defined Options                   
12307: * core-ambcond::                Ambiguous Conditions                
12308: * core-other::                  Other System Documentation                  
12309: @end menu
12310: 
12311: @c ---------------------------------------------------------------------
12312: @node core-idef, core-ambcond, The Core Words, The Core Words
12313: @subsection Implementation Defined Options
12314: @c ---------------------------------------------------------------------
12315: @cindex core words, implementation-defined options
12316: @cindex implementation-defined options, core words
12317: 
12318: 
12319: @table @i
12320: @item (Cell) aligned addresses:
12321: @cindex cell-aligned addresses
12322: @cindex aligned addresses
12323: processor-dependent. Gforth's alignment words perform natural alignment
12324: (e.g., an address aligned for a datum of size 8 is divisible by
12325: 8). Unaligned accesses usually result in a @code{-23 THROW}.
12326: 
12327: @item @code{EMIT} and non-graphic characters:
12328: @cindex @code{EMIT} and non-graphic characters
12329: @cindex non-graphic characters and @code{EMIT}
12330: The character is output using the C library function (actually, macro)
12331: @code{putc}.
12332: 
12333: @item character editing of @code{ACCEPT} and @code{EXPECT}:
12334: @cindex character editing of @code{ACCEPT} and @code{EXPECT}
12335: @cindex editing in @code{ACCEPT} and @code{EXPECT}
12336: @cindex @code{ACCEPT}, editing
12337: @cindex @code{EXPECT}, editing
12338: This is modeled on the GNU readline library (@pxref{Readline
12339: Interaction, , Command Line Editing, readline, The GNU Readline
12340: Library}) with Emacs-like key bindings. @kbd{Tab} deviates a little by
12341: producing a full word completion every time you type it (instead of
12342: producing the common prefix of all completions). @xref{Command-line editing}.
12343: 
12344: @item character set:
12345: @cindex character set
12346: The character set of your computer and display device. Gforth is
12347: 8-bit-clean (but some other component in your system may make trouble).
12348: 
12349: @item Character-aligned address requirements:
12350: @cindex character-aligned address requirements
12351: installation-dependent. Currently a character is represented by a C
12352: @code{unsigned char}; in the future we might switch to @code{wchar_t}
12353: (Comments on that requested).
12354: 
12355: @item character-set extensions and matching of names:
12356: @cindex character-set extensions and matching of names
12357: @cindex case-sensitivity for name lookup
12358: @cindex name lookup, case-sensitivity
12359: @cindex locale and case-sensitivity
12360: Any character except the ASCII NUL character can be used in a
12361: name. Matching is case-insensitive (except in @code{TABLE}s). The
12362: matching is performed using the C library function @code{strncasecmp}, whose
12363: function is probably influenced by the locale. E.g., the @code{C} locale
12364: does not know about accents and umlauts, so they are matched
12365: case-sensitively in that locale. For portability reasons it is best to
12366: write programs such that they work in the @code{C} locale. Then one can
12367: use libraries written by a Polish programmer (who might use words
12368: containing ISO Latin-2 encoded characters) and by a French programmer
12369: (ISO Latin-1) in the same program (of course, @code{WORDS} will produce
12370: funny results for some of the words (which ones, depends on the font you
12371: are using)). Also, the locale you prefer may not be available in other
12372: operating systems. Hopefully, Unicode will solve these problems one day.
12373: 
12374: @item conditions under which control characters match a space delimiter:
12375: @cindex space delimiters
12376: @cindex control characters as delimiters
12377: If @code{WORD} is called with the space character as a delimiter, all
12378: white-space characters (as identified by the C macro @code{isspace()})
12379: are delimiters. @code{PARSE}, on the other hand, treats space like other
12380: delimiters. @code{SWORD} treats space like @code{WORD}, but behaves
12381: like @code{PARSE} otherwise. @code{Name}, which is used by the outer
12382: interpreter (aka text interpreter) by default, treats all white-space
12383: characters as delimiters.
12384: 
12385: @item format of the control-flow stack:
12386: @cindex control-flow stack, format
12387: The data stack is used as control-flow stack. The size of a control-flow
12388: stack item in cells is given by the constant @code{cs-item-size}. At the
12389: time of this writing, an item consists of a (pointer to a) locals list
12390: (third), an address in the code (second), and a tag for identifying the
12391: item (TOS). The following tags are used: @code{defstart},
12392: @code{live-orig}, @code{dead-orig}, @code{dest}, @code{do-dest},
12393: @code{scopestart}.
12394: 
12395: @item conversion of digits > 35
12396: @cindex digits > 35
12397: The characters @code{[\]^_'} are the digits with the decimal value
12398: 36@minus{}41. There is no way to input many of the larger digits.
12399: 
12400: @item display after input terminates in @code{ACCEPT} and @code{EXPECT}:
12401: @cindex @code{EXPECT}, display after end of input
12402: @cindex @code{ACCEPT}, display after end of input
12403: The cursor is moved to the end of the entered string. If the input is
12404: terminated using the @kbd{Return} key, a space is typed.
12405: 
12406: @item exception abort sequence of @code{ABORT"}:
12407: @cindex exception abort sequence of @code{ABORT"}
12408: @cindex @code{ABORT"}, exception abort sequence
12409: The error string is stored into the variable @code{"error} and a
12410: @code{-2 throw} is performed.
12411: 
12412: @item input line terminator:
12413: @cindex input line terminator
12414: @cindex line terminator on input
12415: @cindex newline character on input
12416: For interactive input, @kbd{C-m} (CR) and @kbd{C-j} (LF) terminate
12417: lines. One of these characters is typically produced when you type the
12418: @kbd{Enter} or @kbd{Return} key.
12419: 
12420: @item maximum size of a counted string:
12421: @cindex maximum size of a counted string
12422: @cindex counted string, maximum size
12423: @code{s" /counted-string" environment? drop .}. Currently 255 characters
12424: on all platforms, but this may change.
12425: 
12426: @item maximum size of a parsed string:
12427: @cindex maximum size of a parsed string
12428: @cindex parsed string, maximum size
12429: Given by the constant @code{/line}. Currently 255 characters.
12430: 
12431: @item maximum size of a definition name, in characters:
12432: @cindex maximum size of a definition name, in characters
12433: @cindex name, maximum length
12434: 31
12435: 
12436: @item maximum string length for @code{ENVIRONMENT?}, in characters:
12437: @cindex maximum string length for @code{ENVIRONMENT?}, in characters
12438: @cindex @code{ENVIRONMENT?} string length, maximum
12439: 31
12440: 
12441: @item method of selecting the user input device:
12442: @cindex user input device, method of selecting
12443: The user input device is the standard input. There is currently no way to
12444: change it from within Gforth. However, the input can typically be
12445: redirected in the command line that starts Gforth.
12446: 
12447: @item method of selecting the user output device:
12448: @cindex user output device, method of selecting
12449: @code{EMIT} and @code{TYPE} output to the file-id stored in the value
12450: @code{outfile-id} (@code{stdout} by default). Gforth uses unbuffered
12451: output when the user output device is a terminal, otherwise the output
12452: is buffered.
12453: 
12454: @item methods of dictionary compilation:
12455: What are we expected to document here?
12456: 
12457: @item number of bits in one address unit:
12458: @cindex number of bits in one address unit
12459: @cindex address unit, size in bits
12460: @code{s" address-units-bits" environment? drop .}. 8 in all current
12461: platforms.
12462: 
12463: @item number representation and arithmetic:
12464: @cindex number representation and arithmetic
12465: Processor-dependent. Binary two's complement on all current platforms.
12466: 
12467: @item ranges for integer types:
12468: @cindex ranges for integer types
12469: @cindex integer types, ranges
12470: Installation-dependent. Make environmental queries for @code{MAX-N},
12471: @code{MAX-U}, @code{MAX-D} and @code{MAX-UD}. The lower bounds for
12472: unsigned (and positive) types is 0. The lower bound for signed types on
12473: two's complement and one's complement machines machines can be computed
12474: by adding 1 to the upper bound.
12475: 
12476: @item read-only data space regions:
12477: @cindex read-only data space regions
12478: @cindex data-space, read-only regions
12479: The whole Forth data space is writable.
12480: 
12481: @item size of buffer at @code{WORD}:
12482: @cindex size of buffer at @code{WORD}
12483: @cindex @code{WORD} buffer size
12484: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
12485: shared with the pictured numeric output string. If overwriting
12486: @code{PAD} is acceptable, it is as large as the remaining dictionary
12487: space, although only as much can be sensibly used as fits in a counted
12488: string.
12489: 
12490: @item size of one cell in address units:
12491: @cindex cell size
12492: @code{1 cells .}.
12493: 
12494: @item size of one character in address units:
12495: @cindex char size
12496: @code{1 chars .}. 1 on all current platforms.
12497: 
12498: @item size of the keyboard terminal buffer:
12499: @cindex size of the keyboard terminal buffer
12500: @cindex terminal buffer, size
12501: Varies. You can determine the size at a specific time using @code{lp@@
12502: tib - .}. It is shared with the locals stack and TIBs of files that
12503: include the current file. You can change the amount of space for TIBs
12504: and locals stack at Gforth startup with the command line option
12505: @code{-l}.
12506: 
12507: @item size of the pictured numeric output buffer:
12508: @cindex size of the pictured numeric output buffer
12509: @cindex pictured numeric output buffer, size
12510: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
12511: shared with @code{WORD}.
12512: 
12513: @item size of the scratch area returned by @code{PAD}:
12514: @cindex size of the scratch area returned by @code{PAD}
12515: @cindex @code{PAD} size
12516: The remainder of dictionary space. @code{unused pad here - - .}.
12517: 
12518: @item system case-sensitivity characteristics:
12519: @cindex case-sensitivity characteristics
12520: Dictionary searches are case-insensitive (except in
12521: @code{TABLE}s). However, as explained above under @i{character-set
12522: extensions}, the matching for non-ASCII characters is determined by the
12523: locale you are using. In the default @code{C} locale all non-ASCII
12524: characters are matched case-sensitively.
12525: 
12526: @item system prompt:
12527: @cindex system prompt
12528: @cindex prompt
12529: @code{ ok} in interpret state, @code{ compiled} in compile state.
12530: 
12531: @item division rounding:
12532: @cindex division rounding
12533: installation dependent. @code{s" floored" environment? drop .}. We leave
12534: the choice to @code{gcc} (what to use for @code{/}) and to you (whether
12535: to use @code{fm/mod}, @code{sm/rem} or simply @code{/}).
12536: 
12537: @item values of @code{STATE} when true:
12538: @cindex @code{STATE} values
12539: -1.
12540: 
12541: @item values returned after arithmetic overflow:
12542: On two's complement machines, arithmetic is performed modulo
12543: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
12544: arithmetic (with appropriate mapping for signed types). Division by zero
12545: typically results in a @code{-55 throw} (Floating-point unidentified
12546: fault) or @code{-10 throw} (divide by zero).
12547: 
12548: @item whether the current definition can be found after @t{DOES>}:
12549: @cindex @t{DOES>}, visibility of current definition
12550: No.
12551: 
12552: @end table
12553: 
12554: @c ---------------------------------------------------------------------
12555: @node core-ambcond, core-other, core-idef, The Core Words
12556: @subsection Ambiguous conditions
12557: @c ---------------------------------------------------------------------
12558: @cindex core words, ambiguous conditions
12559: @cindex ambiguous conditions, core words
12560: 
12561: @table @i
12562: 
12563: @item a name is neither a word nor a number:
12564: @cindex name not found
12565: @cindex undefined word
12566: @code{-13 throw} (Undefined word).
12567: 
12568: @item a definition name exceeds the maximum length allowed:
12569: @cindex word name too long
12570: @code{-19 throw} (Word name too long)
12571: 
12572: @item addressing a region not inside the various data spaces of the forth system:
12573: @cindex Invalid memory address
12574: The stacks, code space and header space are accessible. Machine code space is
12575: typically readable. Accessing other addresses gives results dependent on
12576: the operating system. On decent systems: @code{-9 throw} (Invalid memory
12577: address).
12578: 
12579: @item argument type incompatible with parameter:
12580: @cindex argument type mismatch
12581: This is usually not caught. Some words perform checks, e.g., the control
12582: flow words, and issue a @code{ABORT"} or @code{-12 THROW} (Argument type
12583: mismatch).
12584: 
12585: @item attempting to obtain the execution token of a word with undefined execution semantics:
12586: @cindex Interpreting a compile-only word, for @code{'} etc.
12587: @cindex execution token of words with undefined execution semantics
12588: @code{-14 throw} (Interpreting a compile-only word). In some cases, you
12589: get an execution token for @code{compile-only-error} (which performs a
12590: @code{-14 throw} when executed).
12591: 
12592: @item dividing by zero:
12593: @cindex dividing by zero
12594: @cindex floating point unidentified fault, integer division
12595: On some platforms, this produces a @code{-10 throw} (Division by
12596: zero); on other systems, this typically results in a @code{-55 throw}
12597: (Floating-point unidentified fault).
12598: 
12599: @item insufficient data stack or return stack space:
12600: @cindex insufficient data stack or return stack space
12601: @cindex stack overflow
12602: @cindex address alignment exception, stack overflow
12603: @cindex Invalid memory address, stack overflow
12604: Depending on the operating system, the installation, and the invocation
12605: of Gforth, this is either checked by the memory management hardware, or
12606: it is not checked. If it is checked, you typically get a @code{-3 throw}
12607: (Stack overflow), @code{-5 throw} (Return stack overflow), or @code{-9
12608: throw} (Invalid memory address) (depending on the platform and how you
12609: achieved the overflow) as soon as the overflow happens. If it is not
12610: checked, overflows typically result in mysterious illegal memory
12611: accesses, producing @code{-9 throw} (Invalid memory address) or
12612: @code{-23 throw} (Address alignment exception); they might also destroy
12613: the internal data structure of @code{ALLOCATE} and friends, resulting in
12614: various errors in these words.
12615: 
12616: @item insufficient space for loop control parameters:
12617: @cindex insufficient space for loop control parameters
12618: Like other return stack overflows.
12619: 
12620: @item insufficient space in the dictionary:
12621: @cindex insufficient space in the dictionary
12622: @cindex dictionary overflow
12623: If you try to allot (either directly with @code{allot}, or indirectly
12624: with @code{,}, @code{create} etc.) more memory than available in the
12625: dictionary, you get a @code{-8 throw} (Dictionary overflow). If you try
12626: to access memory beyond the end of the dictionary, the results are
12627: similar to stack overflows.
12628: 
12629: @item interpreting a word with undefined interpretation semantics:
12630: @cindex interpreting a word with undefined interpretation semantics
12631: @cindex Interpreting a compile-only word
12632: For some words, we have defined interpretation semantics. For the
12633: others: @code{-14 throw} (Interpreting a compile-only word).
12634: 
12635: @item modifying the contents of the input buffer or a string literal:
12636: @cindex modifying the contents of the input buffer or a string literal
12637: These are located in writable memory and can be modified.
12638: 
12639: @item overflow of the pictured numeric output string:
12640: @cindex overflow of the pictured numeric output string
12641: @cindex pictured numeric output string, overflow
12642: @code{-17 throw} (Pictured numeric ouput string overflow).
12643: 
12644: @item parsed string overflow:
12645: @cindex parsed string overflow
12646: @code{PARSE} cannot overflow. @code{WORD} does not check for overflow.
12647: 
12648: @item producing a result out of range:
12649: @cindex result out of range
12650: On two's complement machines, arithmetic is performed modulo
12651: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
12652: arithmetic (with appropriate mapping for signed types). Division by zero
12653: typically results in a @code{-10 throw} (divide by zero) or @code{-55
12654: throw} (floating point unidentified fault). @code{convert} and
12655: @code{>number} currently overflow silently.
12656: 
12657: @item reading from an empty data or return stack:
12658: @cindex stack empty
12659: @cindex stack underflow
12660: @cindex return stack underflow
12661: The data stack is checked by the outer (aka text) interpreter after
12662: every word executed. If it has underflowed, a @code{-4 throw} (Stack
12663: underflow) is performed. Apart from that, stacks may be checked or not,
12664: depending on operating system, installation, and invocation. If they are
12665: caught by a check, they typically result in @code{-4 throw} (Stack
12666: underflow), @code{-6 throw} (Return stack underflow) or @code{-9 throw}
12667: (Invalid memory address), depending on the platform and which stack
12668: underflows and by how much. Note that even if the system uses checking
12669: (through the MMU), your program may have to underflow by a significant
12670: number of stack items to trigger the reaction (the reason for this is
12671: that the MMU, and therefore the checking, works with a page-size
12672: granularity).  If there is no checking, the symptoms resulting from an
12673: underflow are similar to those from an overflow.  Unbalanced return
12674: stack errors can result in a variety of symptoms, including @code{-9 throw}
12675: (Invalid memory address) and Illegal Instruction (typically @code{-260
12676: throw}).
12677: 
12678: @item unexpected end of the input buffer, resulting in an attempt to use a zero-length string as a name:
12679: @cindex unexpected end of the input buffer
12680: @cindex zero-length string as a name
12681: @cindex Attempt to use zero-length string as a name
12682: @code{Create} and its descendants perform a @code{-16 throw} (Attempt to
12683: use zero-length string as a name). Words like @code{'} probably will not
12684: find what they search. Note that it is possible to create zero-length
12685: names with @code{nextname} (should it not?).
12686: 
12687: @item @code{>IN} greater than input buffer:
12688: @cindex @code{>IN} greater than input buffer
12689: The next invocation of a parsing word returns a string with length 0.
12690: 
12691: @item @code{RECURSE} appears after @code{DOES>}:
12692: @cindex @code{RECURSE} appears after @code{DOES>}
12693: Compiles a recursive call to the defining word, not to the defined word.
12694: 
12695: @item argument input source different than current input source for @code{RESTORE-INPUT}:
12696: @cindex argument input source different than current input source for @code{RESTORE-INPUT}
12697: @cindex argument type mismatch, @code{RESTORE-INPUT}
12698: @cindex @code{RESTORE-INPUT}, Argument type mismatch
12699: @code{-12 THROW}. Note that, once an input file is closed (e.g., because
12700: the end of the file was reached), its source-id may be
12701: reused. Therefore, restoring an input source specification referencing a
12702: closed file may lead to unpredictable results instead of a @code{-12
12703: THROW}.
12704: 
12705: In the future, Gforth may be able to restore input source specifications
12706: from other than the current input source.
12707: 
12708: @item data space containing definitions gets de-allocated:
12709: @cindex data space containing definitions gets de-allocated
12710: Deallocation with @code{allot} is not checked. This typically results in
12711: memory access faults or execution of illegal instructions.
12712: 
12713: @item data space read/write with incorrect alignment:
12714: @cindex data space read/write with incorrect alignment
12715: @cindex alignment faults
12716: @cindex address alignment exception
12717: Processor-dependent. Typically results in a @code{-23 throw} (Address
12718: alignment exception). Under Linux-Intel on a 486 or later processor with
12719: alignment turned on, incorrect alignment results in a @code{-9 throw}
12720: (Invalid memory address). There are reportedly some processors with
12721: alignment restrictions that do not report violations.
12722: 
12723: @item data space pointer not properly aligned, @code{,}, @code{C,}:
12724: @cindex data space pointer not properly aligned, @code{,}, @code{C,}
12725: Like other alignment errors.
12726: 
12727: @item less than u+2 stack items (@code{PICK} and @code{ROLL}):
12728: Like other stack underflows.
12729: 
12730: @item loop control parameters not available:
12731: @cindex loop control parameters not available
12732: Not checked. The counted loop words simply assume that the top of return
12733: stack items are loop control parameters and behave accordingly.
12734: 
12735: @item most recent definition does not have a name (@code{IMMEDIATE}):
12736: @cindex most recent definition does not have a name (@code{IMMEDIATE})
12737: @cindex last word was headerless
12738: @code{abort" last word was headerless"}.
12739: 
12740: @item name not defined by @code{VALUE} used by @code{TO}:
12741: @cindex name not defined by @code{VALUE} used by @code{TO}
12742: @cindex @code{TO} on non-@code{VALUE}s
12743: @cindex Invalid name argument, @code{TO}
12744: @code{-32 throw} (Invalid name argument) (unless name is a local or was
12745: defined by @code{CONSTANT}; in the latter case it just changes the constant).
12746: 
12747: @item name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}):
12748: @cindex name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]})
12749: @cindex undefined word, @code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}
12750: @code{-13 throw} (Undefined word)
12751: 
12752: @item parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN}):
12753: @cindex parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN})
12754: Gforth behaves as if they were of the same type. I.e., you can predict
12755: the behaviour by interpreting all parameters as, e.g., signed.
12756: 
12757: @item @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}:
12758: @cindex @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}
12759: Assume @code{: X POSTPONE TO ; IMMEDIATE}. @code{X} performs the
12760: compilation semantics of @code{TO}.
12761: 
12762: @item String longer than a counted string returned by @code{WORD}:
12763: @cindex string longer than a counted string returned by @code{WORD}
12764: @cindex @code{WORD}, string overflow
12765: Not checked. The string will be ok, but the count will, of course,
12766: contain only the least significant bits of the length.
12767: 
12768: @item u greater than or equal to the number of bits in a cell (@code{LSHIFT}, @code{RSHIFT}):
12769: @cindex @code{LSHIFT}, large shift counts
12770: @cindex @code{RSHIFT}, large shift counts
12771: Processor-dependent. Typical behaviours are returning 0 and using only
12772: the low bits of the shift count.
12773: 
12774: @item word not defined via @code{CREATE}:
12775: @cindex @code{>BODY} of non-@code{CREATE}d words
12776: @code{>BODY} produces the PFA of the word no matter how it was defined.
12777: 
12778: @cindex @code{DOES>} of non-@code{CREATE}d words
12779: @code{DOES>} changes the execution semantics of the last defined word no
12780: matter how it was defined. E.g., @code{CONSTANT DOES>} is equivalent to
12781: @code{CREATE , DOES>}.
12782: 
12783: @item words improperly used outside @code{<#} and @code{#>}:
12784: Not checked. As usual, you can expect memory faults.
12785: 
12786: @end table
12787: 
12788: 
12789: @c ---------------------------------------------------------------------
12790: @node core-other,  , core-ambcond, The Core Words
12791: @subsection Other system documentation
12792: @c ---------------------------------------------------------------------
12793: @cindex other system documentation, core words
12794: @cindex core words, other system documentation
12795: 
12796: @table @i
12797: @item nonstandard words using @code{PAD}:
12798: @cindex @code{PAD} use by nonstandard words
12799: None.
12800: 
12801: @item operator's terminal facilities available:
12802: @cindex operator's terminal facilities available
12803: After processing the OS's command line, Gforth goes into interactive mode,
12804: and you can give commands to Gforth interactively. The actual facilities
12805: available depend on how you invoke Gforth.
12806: 
12807: @item program data space available:
12808: @cindex program data space available
12809: @cindex data space available
12810: @code{UNUSED .} gives the remaining dictionary space. The total
12811: dictionary space can be specified with the @code{-m} switch
12812: (@pxref{Invoking Gforth}) when Gforth starts up.
12813: 
12814: @item return stack space available:
12815: @cindex return stack space available
12816: You can compute the total return stack space in cells with
12817: @code{s" RETURN-STACK-CELLS" environment? drop .}. You can specify it at
12818: startup time with the @code{-r} switch (@pxref{Invoking Gforth}).
12819: 
12820: @item stack space available:
12821: @cindex stack space available
12822: You can compute the total data stack space in cells with
12823: @code{s" STACK-CELLS" environment? drop .}. You can specify it at
12824: startup time with the @code{-d} switch (@pxref{Invoking Gforth}).
12825: 
12826: @item system dictionary space required, in address units:
12827: @cindex system dictionary space required, in address units
12828: Type @code{here forthstart - .} after startup. At the time of this
12829: writing, this gives 80080 (bytes) on a 32-bit system.
12830: @end table
12831: 
12832: 
12833: @c =====================================================================
12834: @node The optional Block word set, The optional Double Number word set, The Core Words, ANS conformance
12835: @section The optional Block word set
12836: @c =====================================================================
12837: @cindex system documentation, block words
12838: @cindex block words, system documentation
12839: 
12840: @menu
12841: * block-idef::                  Implementation Defined Options
12842: * block-ambcond::               Ambiguous Conditions               
12843: * block-other::                 Other System Documentation                 
12844: @end menu
12845: 
12846: 
12847: @c ---------------------------------------------------------------------
12848: @node block-idef, block-ambcond, The optional Block word set, The optional Block word set
12849: @subsection Implementation Defined Options
12850: @c ---------------------------------------------------------------------
12851: @cindex implementation-defined options, block words
12852: @cindex block words, implementation-defined options
12853: 
12854: @table @i
12855: @item the format for display by @code{LIST}:
12856: @cindex @code{LIST} display format
12857: First the screen number is displayed, then 16 lines of 64 characters,
12858: each line preceded by the line number.
12859: 
12860: @item the length of a line affected by @code{\}:
12861: @cindex length of a line affected by @code{\}
12862: @cindex @code{\}, line length in blocks
12863: 64 characters.
12864: @end table
12865: 
12866: 
12867: @c ---------------------------------------------------------------------
12868: @node block-ambcond, block-other, block-idef, The optional Block word set
12869: @subsection Ambiguous conditions
12870: @c ---------------------------------------------------------------------
12871: @cindex block words, ambiguous conditions
12872: @cindex ambiguous conditions, block words
12873: 
12874: @table @i
12875: @item correct block read was not possible:
12876: @cindex block read not possible
12877: Typically results in a @code{throw} of some OS-derived value (between
12878: -512 and -2048). If the blocks file was just not long enough, blanks are
12879: supplied for the missing portion.
12880: 
12881: @item I/O exception in block transfer:
12882: @cindex I/O exception in block transfer
12883: @cindex block transfer, I/O exception
12884: Typically results in a @code{throw} of some OS-derived value (between
12885: -512 and -2048).
12886: 
12887: @item invalid block number:
12888: @cindex invalid block number
12889: @cindex block number invalid
12890: @code{-35 throw} (Invalid block number)
12891: 
12892: @item a program directly alters the contents of @code{BLK}:
12893: @cindex @code{BLK}, altering @code{BLK}
12894: The input stream is switched to that other block, at the same
12895: position. If the storing to @code{BLK} happens when interpreting
12896: non-block input, the system will get quite confused when the block ends.
12897: 
12898: @item no current block buffer for @code{UPDATE}:
12899: @cindex @code{UPDATE}, no current block buffer
12900: @code{UPDATE} has no effect.
12901: 
12902: @end table
12903: 
12904: @c ---------------------------------------------------------------------
12905: @node block-other,  , block-ambcond, The optional Block word set
12906: @subsection Other system documentation
12907: @c ---------------------------------------------------------------------
12908: @cindex other system documentation, block words
12909: @cindex block words, other system documentation
12910: 
12911: @table @i
12912: @item any restrictions a multiprogramming system places on the use of buffer addresses:
12913: No restrictions (yet).
12914: 
12915: @item the number of blocks available for source and data:
12916: depends on your disk space.
12917: 
12918: @end table
12919: 
12920: 
12921: @c =====================================================================
12922: @node The optional Double Number word set, The optional Exception word set, The optional Block word set, ANS conformance
12923: @section The optional Double Number word set
12924: @c =====================================================================
12925: @cindex system documentation, double words
12926: @cindex double words, system documentation
12927: 
12928: @menu
12929: * double-ambcond::              Ambiguous Conditions              
12930: @end menu
12931: 
12932: 
12933: @c ---------------------------------------------------------------------
12934: @node double-ambcond,  , The optional Double Number word set, The optional Double Number word set
12935: @subsection Ambiguous conditions
12936: @c ---------------------------------------------------------------------
12937: @cindex double words, ambiguous conditions
12938: @cindex ambiguous conditions, double words
12939: 
12940: @table @i
12941: @item @i{d} outside of range of @i{n} in @code{D>S}:
12942: @cindex @code{D>S}, @i{d} out of range of @i{n} 
12943: The least significant cell of @i{d} is produced.
12944: 
12945: @end table
12946: 
12947: 
12948: @c =====================================================================
12949: @node The optional Exception word set, The optional Facility word set, The optional Double Number word set, ANS conformance
12950: @section The optional Exception word set
12951: @c =====================================================================
12952: @cindex system documentation, exception words
12953: @cindex exception words, system documentation
12954: 
12955: @menu
12956: * exception-idef::              Implementation Defined Options              
12957: @end menu
12958: 
12959: 
12960: @c ---------------------------------------------------------------------
12961: @node exception-idef,  , The optional Exception word set, The optional Exception word set
12962: @subsection Implementation Defined Options
12963: @c ---------------------------------------------------------------------
12964: @cindex implementation-defined options, exception words
12965: @cindex exception words, implementation-defined options
12966: 
12967: @table @i
12968: @item @code{THROW}-codes used in the system:
12969: @cindex @code{THROW}-codes used in the system
12970: The codes -256@minus{}-511 are used for reporting signals. The mapping
12971: from OS signal numbers to throw codes is -256@minus{}@i{signal}. The
12972: codes -512@minus{}-2047 are used for OS errors (for file and memory
12973: allocation operations). The mapping from OS error numbers to throw codes
12974: is -512@minus{}@code{errno}. One side effect of this mapping is that
12975: undefined OS errors produce a message with a strange number; e.g.,
12976: @code{-1000 THROW} results in @code{Unknown error 488} on my system.
12977: @end table
12978: 
12979: @c =====================================================================
12980: @node The optional Facility word set, The optional File-Access word set, The optional Exception word set, ANS conformance
12981: @section The optional Facility word set
12982: @c =====================================================================
12983: @cindex system documentation, facility words
12984: @cindex facility words, system documentation
12985: 
12986: @menu
12987: * facility-idef::               Implementation Defined Options               
12988: * facility-ambcond::            Ambiguous Conditions            
12989: @end menu
12990: 
12991: 
12992: @c ---------------------------------------------------------------------
12993: @node facility-idef, facility-ambcond, The optional Facility word set, The optional Facility word set
12994: @subsection Implementation Defined Options
12995: @c ---------------------------------------------------------------------
12996: @cindex implementation-defined options, facility words
12997: @cindex facility words, implementation-defined options
12998: 
12999: @table @i
13000: @item encoding of keyboard events (@code{EKEY}):
13001: @cindex keyboard events, encoding in @code{EKEY}
13002: @cindex @code{EKEY}, encoding of keyboard events
13003: Keys corresponding to ASCII characters are encoded as ASCII characters.
13004: Other keys are encoded with the constants @code{k-left}, @code{k-right},
13005: @code{k-up}, @code{k-down}, @code{k-home}, @code{k-end}, @code{k1},
13006: @code{k2}, @code{k3}, @code{k4}, @code{k5}, @code{k6}, @code{k7},
13007: @code{k8}, @code{k9}, @code{k10}, @code{k11}, @code{k12}.
13008: 
13009: 
13010: @item duration of a system clock tick:
13011: @cindex duration of a system clock tick
13012: @cindex clock tick duration
13013: System dependent. With respect to @code{MS}, the time is specified in
13014: microseconds. How well the OS and the hardware implement this, is
13015: another question.
13016: 
13017: @item repeatability to be expected from the execution of @code{MS}:
13018: @cindex repeatability to be expected from the execution of @code{MS}
13019: @cindex @code{MS}, repeatability to be expected
13020: System dependent. On Unix, a lot depends on load. If the system is
13021: lightly loaded, and the delay is short enough that Gforth does not get
13022: swapped out, the performance should be acceptable. Under MS-DOS and
13023: other single-tasking systems, it should be good.
13024: 
13025: @end table
13026: 
13027: 
13028: @c ---------------------------------------------------------------------
13029: @node facility-ambcond,  , facility-idef, The optional Facility word set
13030: @subsection Ambiguous conditions
13031: @c ---------------------------------------------------------------------
13032: @cindex facility words, ambiguous conditions
13033: @cindex ambiguous conditions, facility words
13034: 
13035: @table @i
13036: @item @code{AT-XY} can't be performed on user output device:
13037: @cindex @code{AT-XY} can't be performed on user output device
13038: Largely terminal dependent. No range checks are done on the arguments.
13039: No errors are reported. You may see some garbage appearing, you may see
13040: simply nothing happen.
13041: 
13042: @end table
13043: 
13044: 
13045: @c =====================================================================
13046: @node The optional File-Access word set, The optional Floating-Point word set, The optional Facility word set, ANS conformance
13047: @section The optional File-Access word set
13048: @c =====================================================================
13049: @cindex system documentation, file words
13050: @cindex file words, system documentation
13051: 
13052: @menu
13053: * file-idef::                   Implementation Defined Options
13054: * file-ambcond::                Ambiguous Conditions                
13055: @end menu
13056: 
13057: @c ---------------------------------------------------------------------
13058: @node file-idef, file-ambcond, The optional File-Access word set, The optional File-Access word set
13059: @subsection Implementation Defined Options
13060: @c ---------------------------------------------------------------------
13061: @cindex implementation-defined options, file words
13062: @cindex file words, implementation-defined options
13063: 
13064: @table @i
13065: @item file access methods used:
13066: @cindex file access methods used
13067: @code{R/O}, @code{R/W} and @code{BIN} work as you would
13068: expect. @code{W/O} translates into the C file opening mode @code{w} (or
13069: @code{wb}): The file is cleared, if it exists, and created, if it does
13070: not (with both @code{open-file} and @code{create-file}).  Under Unix
13071: @code{create-file} creates a file with 666 permissions modified by your
13072: umask.
13073: 
13074: @item file exceptions:
13075: @cindex file exceptions
13076: The file words do not raise exceptions (except, perhaps, memory access
13077: faults when you pass illegal addresses or file-ids).
13078: 
13079: @item file line terminator:
13080: @cindex file line terminator
13081: System-dependent. Gforth uses C's newline character as line
13082: terminator. What the actual character code(s) of this are is
13083: system-dependent.
13084: 
13085: @item file name format:
13086: @cindex file name format
13087: System dependent. Gforth just uses the file name format of your OS.
13088: 
13089: @item information returned by @code{FILE-STATUS}:
13090: @cindex @code{FILE-STATUS}, returned information
13091: @code{FILE-STATUS} returns the most powerful file access mode allowed
13092: for the file: Either @code{R/O}, @code{W/O} or @code{R/W}. If the file
13093: cannot be accessed, @code{R/O BIN} is returned. @code{BIN} is applicable
13094: along with the returned mode.
13095: 
13096: @item input file state after an exception when including source:
13097: @cindex exception when including source
13098: All files that are left via the exception are closed.
13099: 
13100: @item @i{ior} values and meaning:
13101: @cindex @i{ior} values and meaning
13102: @cindex @i{wior} values and meaning
13103: The @i{ior}s returned by the file and memory allocation words are
13104: intended as throw codes. They typically are in the range
13105: -512@minus{}-2047 of OS errors.  The mapping from OS error numbers to
13106: @i{ior}s is -512@minus{}@i{errno}.
13107: 
13108: @item maximum depth of file input nesting:
13109: @cindex maximum depth of file input nesting
13110: @cindex file input nesting, maximum depth
13111: limited by the amount of return stack, locals/TIB stack, and the number
13112: of open files available. This should not give you troubles.
13113: 
13114: @item maximum size of input line:
13115: @cindex maximum size of input line
13116: @cindex input line size, maximum
13117: @code{/line}. Currently 255.
13118: 
13119: @item methods of mapping block ranges to files:
13120: @cindex mapping block ranges to files
13121: @cindex files containing blocks
13122: @cindex blocks in files
13123: By default, blocks are accessed in the file @file{blocks.fb} in the
13124: current working directory. The file can be switched with @code{USE}.
13125: 
13126: @item number of string buffers provided by @code{S"}:
13127: @cindex @code{S"}, number of string buffers
13128: 1
13129: 
13130: @item size of string buffer used by @code{S"}:
13131: @cindex @code{S"}, size of string buffer
13132: @code{/line}. currently 255.
13133: 
13134: @end table
13135: 
13136: @c ---------------------------------------------------------------------
13137: @node file-ambcond,  , file-idef, The optional File-Access word set
13138: @subsection Ambiguous conditions
13139: @c ---------------------------------------------------------------------
13140: @cindex file words, ambiguous conditions
13141: @cindex ambiguous conditions, file words
13142: 
13143: @table @i
13144: @item attempting to position a file outside its boundaries:
13145: @cindex @code{REPOSITION-FILE}, outside the file's boundaries
13146: @code{REPOSITION-FILE} is performed as usual: Afterwards,
13147: @code{FILE-POSITION} returns the value given to @code{REPOSITION-FILE}.
13148: 
13149: @item attempting to read from file positions not yet written:
13150: @cindex reading from file positions not yet written
13151: End-of-file, i.e., zero characters are read and no error is reported.
13152: 
13153: @item @i{file-id} is invalid (@code{INCLUDE-FILE}):
13154: @cindex @code{INCLUDE-FILE}, @i{file-id} is invalid 
13155: An appropriate exception may be thrown, but a memory fault or other
13156: problem is more probable.
13157: 
13158: @item I/O exception reading or closing @i{file-id} (@code{INCLUDE-FILE}, @code{INCLUDED}):
13159: @cindex @code{INCLUDE-FILE}, I/O exception reading or closing @i{file-id}
13160: @cindex @code{INCLUDED}, I/O exception reading or closing @i{file-id}
13161: The @i{ior} produced by the operation, that discovered the problem, is
13162: thrown.
13163: 
13164: @item named file cannot be opened (@code{INCLUDED}):
13165: @cindex @code{INCLUDED}, named file cannot be opened
13166: The @i{ior} produced by @code{open-file} is thrown.
13167: 
13168: @item requesting an unmapped block number:
13169: @cindex unmapped block numbers
13170: There are no unmapped legal block numbers. On some operating systems,
13171: writing a block with a large number may overflow the file system and
13172: have an error message as consequence.
13173: 
13174: @item using @code{source-id} when @code{blk} is non-zero:
13175: @cindex @code{SOURCE-ID}, behaviour when @code{BLK} is non-zero
13176: @code{source-id} performs its function. Typically it will give the id of
13177: the source which loaded the block. (Better ideas?)
13178: 
13179: @end table
13180: 
13181: 
13182: @c =====================================================================
13183: @node  The optional Floating-Point word set, The optional Locals word set, The optional File-Access word set, ANS conformance
13184: @section The optional Floating-Point word set
13185: @c =====================================================================
13186: @cindex system documentation, floating-point words
13187: @cindex floating-point words, system documentation
13188: 
13189: @menu
13190: * floating-idef::               Implementation Defined Options
13191: * floating-ambcond::            Ambiguous Conditions            
13192: @end menu
13193: 
13194: 
13195: @c ---------------------------------------------------------------------
13196: @node floating-idef, floating-ambcond, The optional Floating-Point word set, The optional Floating-Point word set
13197: @subsection Implementation Defined Options
13198: @c ---------------------------------------------------------------------
13199: @cindex implementation-defined options, floating-point words
13200: @cindex floating-point words, implementation-defined options
13201: 
13202: @table @i
13203: @item format and range of floating point numbers:
13204: @cindex format and range of floating point numbers
13205: @cindex floating point numbers, format and range
13206: System-dependent; the @code{double} type of C.
13207: 
13208: @item results of @code{REPRESENT} when @i{float} is out of range:
13209: @cindex  @code{REPRESENT}, results when @i{float} is out of range
13210: System dependent; @code{REPRESENT} is implemented using the C library
13211: function @code{ecvt()} and inherits its behaviour in this respect.
13212: 
13213: @item rounding or truncation of floating-point numbers:
13214: @cindex rounding of floating-point numbers
13215: @cindex truncation of floating-point numbers
13216: @cindex floating-point numbers, rounding or truncation
13217: System dependent; the rounding behaviour is inherited from the hosting C
13218: compiler. IEEE-FP-based (i.e., most) systems by default round to
13219: nearest, and break ties by rounding to even (i.e., such that the last
13220: bit of the mantissa is 0).
13221: 
13222: @item size of floating-point stack:
13223: @cindex floating-point stack size
13224: @code{s" FLOATING-STACK" environment? drop .} gives the total size of
13225: the floating-point stack (in floats). You can specify this on startup
13226: with the command-line option @code{-f} (@pxref{Invoking Gforth}).
13227: 
13228: @item width of floating-point stack:
13229: @cindex floating-point stack width 
13230: @code{1 floats}.
13231: 
13232: @end table
13233: 
13234: 
13235: @c ---------------------------------------------------------------------
13236: @node floating-ambcond,  , floating-idef, The optional Floating-Point word set
13237: @subsection Ambiguous conditions
13238: @c ---------------------------------------------------------------------
13239: @cindex floating-point words, ambiguous conditions
13240: @cindex ambiguous conditions, floating-point words
13241: 
13242: @table @i
13243: @item @code{df@@} or @code{df!} used with an address that is not double-float  aligned:
13244: @cindex @code{df@@} or @code{df!} used with an address that is not double-float  aligned
13245: System-dependent. Typically results in a @code{-23 THROW} like other
13246: alignment violations.
13247: 
13248: @item @code{f@@} or @code{f!} used with an address that is not float  aligned:
13249: @cindex @code{f@@} used with an address that is not float aligned
13250: @cindex @code{f!} used with an address that is not float aligned
13251: System-dependent. Typically results in a @code{-23 THROW} like other
13252: alignment violations.
13253: 
13254: @item floating-point result out of range:
13255: @cindex floating-point result out of range
13256: System-dependent. Can result in a @code{-43 throw} (floating point
13257: overflow), @code{-54 throw} (floating point underflow), @code{-41 throw}
13258: (floating point inexact result), @code{-55 THROW} (Floating-point
13259: unidentified fault), or can produce a special value representing, e.g.,
13260: Infinity.
13261: 
13262: @item @code{sf@@} or @code{sf!} used with an address that is not single-float  aligned:
13263: @cindex @code{sf@@} or @code{sf!} used with an address that is not single-float  aligned
13264: System-dependent. Typically results in an alignment fault like other
13265: alignment violations.
13266: 
13267: @item @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.}):
13268: @cindex @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.})
13269: The floating-point number is converted into decimal nonetheless.
13270: 
13271: @item Both arguments are equal to zero (@code{FATAN2}):
13272: @cindex @code{FATAN2}, both arguments are equal to zero
13273: System-dependent. @code{FATAN2} is implemented using the C library
13274: function @code{atan2()}.
13275: 
13276: @item Using @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero:
13277: @cindex @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero
13278: System-dependent. Anyway, typically the cos of @i{r1} will not be zero
13279: because of small errors and the tan will be a very large (or very small)
13280: but finite number.
13281: 
13282: @item @i{d} cannot be presented precisely as a float in @code{D>F}:
13283: @cindex @code{D>F}, @i{d} cannot be presented precisely as a float
13284: The result is rounded to the nearest float.
13285: 
13286: @item dividing by zero:
13287: @cindex dividing by zero, floating-point
13288: @cindex floating-point dividing by zero
13289: @cindex floating-point unidentified fault, FP divide-by-zero
13290: Platform-dependent; can produce an Infinity, NaN, @code{-42 throw}
13291: (floating point divide by zero) or @code{-55 throw} (Floating-point
13292: unidentified fault).
13293: 
13294: @item exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@}):
13295: @cindex exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@})
13296: System dependent. On IEEE-FP based systems the number is converted into
13297: an infinity.
13298: 
13299: @item @i{float}<1 (@code{FACOSH}):
13300: @cindex @code{FACOSH}, @i{float}<1
13301: @cindex floating-point unidentified fault, @code{FACOSH}
13302: Platform-dependent; on IEEE-FP systems typically produces a NaN.
13303: 
13304: @item @i{float}=<-1 (@code{FLNP1}):
13305: @cindex @code{FLNP1}, @i{float}=<-1
13306: @cindex floating-point unidentified fault, @code{FLNP1}
13307: Platform-dependent; on IEEE-FP systems typically produces a NaN (or a
13308: negative infinity for @i{float}=-1).
13309: 
13310: @item @i{float}=<0 (@code{FLN}, @code{FLOG}):
13311: @cindex @code{FLN}, @i{float}=<0
13312: @cindex @code{FLOG}, @i{float}=<0
13313: @cindex floating-point unidentified fault, @code{FLN} or @code{FLOG}
13314: Platform-dependent; on IEEE-FP systems typically produces a NaN (or a
13315: negative infinity for @i{float}=0).
13316: 
13317: @item @i{float}<0 (@code{FASINH}, @code{FSQRT}):
13318: @cindex @code{FASINH}, @i{float}<0
13319: @cindex @code{FSQRT}, @i{float}<0
13320: @cindex floating-point unidentified fault, @code{FASINH} or @code{FSQRT}
13321: Platform-dependent; for @code{fsqrt} this typically gives a NaN, for
13322: @code{fasinh} some platforms produce a NaN, others a number (bug in the
13323: C library?).
13324: 
13325: @item |@i{float}|>1 (@code{FACOS}, @code{FASIN}, @code{FATANH}):
13326: @cindex @code{FACOS}, |@i{float}|>1
13327: @cindex @code{FASIN}, |@i{float}|>1
13328: @cindex @code{FATANH}, |@i{float}|>1
13329: @cindex floating-point unidentified fault, @code{FACOS}, @code{FASIN} or @code{FATANH}
13330: Platform-dependent; IEEE-FP systems typically produce a NaN.
13331: 
13332: @item integer part of float cannot be represented by @i{d} in @code{F>D}:
13333: @cindex @code{F>D}, integer part of float cannot be represented by @i{d}
13334: @cindex floating-point unidentified fault, @code{F>D}
13335: Platform-dependent; typically, some double number is produced and no
13336: error is reported.
13337: 
13338: @item string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.}):
13339: @cindex string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.})
13340: @code{Precision} characters of the numeric output area are used.  If
13341: @code{precision} is too high, these words will smash the data or code
13342: close to @code{here}.
13343: @end table
13344: 
13345: @c =====================================================================
13346: @node  The optional Locals word set, The optional Memory-Allocation word set, The optional Floating-Point word set, ANS conformance
13347: @section The optional Locals word set
13348: @c =====================================================================
13349: @cindex system documentation, locals words
13350: @cindex locals words, system documentation
13351: 
13352: @menu
13353: * locals-idef::                 Implementation Defined Options                 
13354: * locals-ambcond::              Ambiguous Conditions              
13355: @end menu
13356: 
13357: 
13358: @c ---------------------------------------------------------------------
13359: @node locals-idef, locals-ambcond, The optional Locals word set, The optional Locals word set
13360: @subsection Implementation Defined Options
13361: @c ---------------------------------------------------------------------
13362: @cindex implementation-defined options, locals words
13363: @cindex locals words, implementation-defined options
13364: 
13365: @table @i
13366: @item maximum number of locals in a definition:
13367: @cindex maximum number of locals in a definition
13368: @cindex locals, maximum number in a definition
13369: @code{s" #locals" environment? drop .}. Currently 15. This is a lower
13370: bound, e.g., on a 32-bit machine there can be 41 locals of up to 8
13371: characters. The number of locals in a definition is bounded by the size
13372: of locals-buffer, which contains the names of the locals.
13373: 
13374: @end table
13375: 
13376: 
13377: @c ---------------------------------------------------------------------
13378: @node locals-ambcond,  , locals-idef, The optional Locals word set
13379: @subsection Ambiguous conditions
13380: @c ---------------------------------------------------------------------
13381: @cindex locals words, ambiguous conditions
13382: @cindex ambiguous conditions, locals words
13383: 
13384: @table @i
13385: @item executing a named local in interpretation state:
13386: @cindex local in interpretation state
13387: @cindex Interpreting a compile-only word, for a local
13388: Locals have no interpretation semantics. If you try to perform the
13389: interpretation semantics, you will get a @code{-14 throw} somewhere
13390: (Interpreting a compile-only word). If you perform the compilation
13391: semantics, the locals access will be compiled (irrespective of state).
13392: 
13393: @item @i{name} not defined by @code{VALUE} or @code{(LOCAL)} (@code{TO}):
13394: @cindex name not defined by @code{VALUE} or @code{(LOCAL)} used by @code{TO}
13395: @cindex @code{TO} on non-@code{VALUE}s and non-locals
13396: @cindex Invalid name argument, @code{TO}
13397: @code{-32 throw} (Invalid name argument)
13398: 
13399: @end table
13400: 
13401: 
13402: @c =====================================================================
13403: @node  The optional Memory-Allocation word set, The optional Programming-Tools word set, The optional Locals word set, ANS conformance
13404: @section The optional Memory-Allocation word set
13405: @c =====================================================================
13406: @cindex system documentation, memory-allocation words
13407: @cindex memory-allocation words, system documentation
13408: 
13409: @menu
13410: * memory-idef::                 Implementation Defined Options                 
13411: @end menu
13412: 
13413: 
13414: @c ---------------------------------------------------------------------
13415: @node memory-idef,  , The optional Memory-Allocation word set, The optional Memory-Allocation word set
13416: @subsection Implementation Defined Options
13417: @c ---------------------------------------------------------------------
13418: @cindex implementation-defined options, memory-allocation words
13419: @cindex memory-allocation words, implementation-defined options
13420: 
13421: @table @i
13422: @item values and meaning of @i{ior}:
13423: @cindex  @i{ior} values and meaning
13424: The @i{ior}s returned by the file and memory allocation words are
13425: intended as throw codes. They typically are in the range
13426: -512@minus{}-2047 of OS errors.  The mapping from OS error numbers to
13427: @i{ior}s is -512@minus{}@i{errno}.
13428: 
13429: @end table
13430: 
13431: @c =====================================================================
13432: @node  The optional Programming-Tools word set, The optional Search-Order word set, The optional Memory-Allocation word set, ANS conformance
13433: @section The optional Programming-Tools word set
13434: @c =====================================================================
13435: @cindex system documentation, programming-tools words
13436: @cindex programming-tools words, system documentation
13437: 
13438: @menu
13439: * programming-idef::            Implementation Defined Options            
13440: * programming-ambcond::         Ambiguous Conditions         
13441: @end menu
13442: 
13443: 
13444: @c ---------------------------------------------------------------------
13445: @node programming-idef, programming-ambcond, The optional Programming-Tools word set, The optional Programming-Tools word set
13446: @subsection Implementation Defined Options
13447: @c ---------------------------------------------------------------------
13448: @cindex implementation-defined options, programming-tools words
13449: @cindex programming-tools words, implementation-defined options
13450: 
13451: @table @i
13452: @item ending sequence for input following @code{;CODE} and @code{CODE}:
13453: @cindex @code{;CODE} ending sequence
13454: @cindex @code{CODE} ending sequence
13455: @code{END-CODE}
13456: 
13457: @item manner of processing input following @code{;CODE} and @code{CODE}:
13458: @cindex @code{;CODE}, processing input
13459: @cindex @code{CODE}, processing input
13460: The @code{ASSEMBLER} vocabulary is pushed on the search order stack, and
13461: the input is processed by the text interpreter, (starting) in interpret
13462: state.
13463: 
13464: @item search order capability for @code{EDITOR} and @code{ASSEMBLER}:
13465: @cindex @code{ASSEMBLER}, search order capability
13466: The ANS Forth search order word set.
13467: 
13468: @item source and format of display by @code{SEE}:
13469: @cindex @code{SEE}, source and format of output
13470: The source for @code{see} is the executable code used by the inner
13471: interpreter.  The current @code{see} tries to output Forth source code
13472: (and on some platforms, assembly code for primitives) as well as
13473: possible.
13474: 
13475: @end table
13476: 
13477: @c ---------------------------------------------------------------------
13478: @node programming-ambcond,  , programming-idef, The optional Programming-Tools word set
13479: @subsection Ambiguous conditions
13480: @c ---------------------------------------------------------------------
13481: @cindex programming-tools words, ambiguous conditions
13482: @cindex ambiguous conditions, programming-tools words
13483: 
13484: @table @i
13485: 
13486: @item deleting the compilation word list (@code{FORGET}):
13487: @cindex @code{FORGET}, deleting the compilation word list
13488: Not implemented (yet).
13489: 
13490: @item fewer than @i{u}+1 items on the control-flow stack (@code{CS-PICK}, @code{CS-ROLL}):
13491: @cindex @code{CS-PICK}, fewer than @i{u}+1 items on the control flow-stack
13492: @cindex @code{CS-ROLL}, fewer than @i{u}+1 items on the control flow-stack
13493: @cindex control-flow stack underflow
13494: This typically results in an @code{abort"} with a descriptive error
13495: message (may change into a @code{-22 throw} (Control structure mismatch)
13496: in the future). You may also get a memory access error. If you are
13497: unlucky, this ambiguous condition is not caught.
13498: 
13499: @item @i{name} can't be found (@code{FORGET}):
13500: @cindex @code{FORGET}, @i{name} can't be found
13501: Not implemented (yet).
13502: 
13503: @item @i{name} not defined via @code{CREATE}:
13504: @cindex @code{;CODE}, @i{name} not defined via @code{CREATE}
13505: @code{;CODE} behaves like @code{DOES>} in this respect, i.e., it changes
13506: the execution semantics of the last defined word no matter how it was
13507: defined.
13508: 
13509: @item @code{POSTPONE} applied to @code{[IF]}:
13510: @cindex @code{POSTPONE} applied to @code{[IF]}
13511: @cindex @code{[IF]} and @code{POSTPONE}
13512: After defining @code{: X POSTPONE [IF] ; IMMEDIATE}. @code{X} is
13513: equivalent to @code{[IF]}.
13514: 
13515: @item reaching the end of the input source before matching @code{[ELSE]} or @code{[THEN]}:
13516: @cindex @code{[IF]}, end of the input source before matching @code{[ELSE]} or @code{[THEN]}
13517: Continue in the same state of conditional compilation in the next outer
13518: input source. Currently there is no warning to the user about this.
13519: 
13520: @item removing a needed definition (@code{FORGET}):
13521: @cindex @code{FORGET}, removing a needed definition
13522: Not implemented (yet).
13523: 
13524: @end table
13525: 
13526: 
13527: @c =====================================================================
13528: @node  The optional Search-Order word set,  , The optional Programming-Tools word set, ANS conformance
13529: @section The optional Search-Order word set
13530: @c =====================================================================
13531: @cindex system documentation, search-order words
13532: @cindex search-order words, system documentation
13533: 
13534: @menu
13535: * search-idef::                 Implementation Defined Options                 
13536: * search-ambcond::              Ambiguous Conditions              
13537: @end menu
13538: 
13539: 
13540: @c ---------------------------------------------------------------------
13541: @node search-idef, search-ambcond, The optional Search-Order word set, The optional Search-Order word set
13542: @subsection Implementation Defined Options
13543: @c ---------------------------------------------------------------------
13544: @cindex implementation-defined options, search-order words
13545: @cindex search-order words, implementation-defined options
13546: 
13547: @table @i
13548: @item maximum number of word lists in search order:
13549: @cindex maximum number of word lists in search order
13550: @cindex search order, maximum depth
13551: @code{s" wordlists" environment? drop .}. Currently 16.
13552: 
13553: @item minimum search order:
13554: @cindex minimum search order
13555: @cindex search order, minimum
13556: @code{root root}.
13557: 
13558: @end table
13559: 
13560: @c ---------------------------------------------------------------------
13561: @node search-ambcond,  , search-idef, The optional Search-Order word set
13562: @subsection Ambiguous conditions
13563: @c ---------------------------------------------------------------------
13564: @cindex search-order words, ambiguous conditions
13565: @cindex ambiguous conditions, search-order words
13566: 
13567: @table @i
13568: @item changing the compilation word list (during compilation):
13569: @cindex changing the compilation word list (during compilation)
13570: @cindex compilation word list, change before definition ends
13571: The word is entered into the word list that was the compilation word list
13572: at the start of the definition. Any changes to the name field (e.g.,
13573: @code{immediate}) or the code field (e.g., when executing @code{DOES>})
13574: are applied to the latest defined word (as reported by @code{last} or
13575: @code{lastxt}), if possible, irrespective of the compilation word list.
13576: 
13577: @item search order empty (@code{previous}):
13578: @cindex @code{previous}, search order empty
13579: @cindex vocstack empty, @code{previous}
13580: @code{abort" Vocstack empty"}.
13581: 
13582: @item too many word lists in search order (@code{also}):
13583: @cindex @code{also}, too many word lists in search order
13584: @cindex vocstack full, @code{also}
13585: @code{abort" Vocstack full"}.
13586: 
13587: @end table
13588: 
13589: @c ***************************************************************
13590: @node Standard vs Extensions, Model, ANS conformance, Top
13591: @chapter Should I use Gforth extensions?
13592: @cindex Gforth extensions
13593: 
13594: As you read through the rest of this manual, you will see documentation
13595: for @i{Standard} words, and documentation for some appealing Gforth
13596: @i{extensions}. You might ask yourself the question: @i{``Should I
13597: restrict myself to the standard, or should I use the extensions?''}
13598: 
13599: The answer depends on the goals you have for the program you are working
13600: on:
13601: 
13602: @itemize @bullet
13603: 
13604: @item Is it just for yourself or do you want to share it with others?
13605: 
13606: @item
13607: If you want to share it, do the others all use Gforth?
13608: 
13609: @item
13610: If it is just for yourself, do you want to restrict yourself to Gforth?
13611: 
13612: @end itemize
13613: 
13614: If restricting the program to Gforth is ok, then there is no reason not
13615: to use extensions.  It is still a good idea to keep to the standard
13616: where it is easy, in case you want to reuse these parts in another
13617: program that you want to be portable.
13618: 
13619: If you want to be able to port the program to other Forth systems, there
13620: are the following points to consider:
13621: 
13622: @itemize @bullet
13623: 
13624: @item
13625: Most Forth systems that are being maintained support the ANS Forth
13626: standard.  So if your program complies with the standard, it will be
13627: portable among many systems.
13628: 
13629: @item
13630: A number of the Gforth extensions can be implemented in ANS Forth using
13631: public-domain files provided in the @file{compat/} directory. These are
13632: mentioned in the text in passing.  There is no reason not to use these
13633: extensions, your program will still be ANS Forth compliant; just include
13634: the appropriate compat files with your program.
13635: 
13636: @item
13637: The tool @file{ans-report.fs} (@pxref{ANS Report}) makes it easy to
13638: analyse your program and determine what non-Standard words it relies
13639: upon.  However, it does not check whether you use standard words in a
13640: non-standard way.
13641: 
13642: @item
13643: Some techniques are not standardized by ANS Forth, and are hard or
13644: impossible to implement in a standard way, but can be implemented in
13645: most Forth systems easily, and usually in similar ways (e.g., accessing
13646: word headers).  Forth has a rich historical precedent for programmers
13647: taking advantage of implementation-dependent features of their tools
13648: (for example, relying on a knowledge of the dictionary
13649: structure). Sometimes these techniques are necessary to extract every
13650: last bit of performance from the hardware, sometimes they are just a
13651: programming shorthand.
13652: 
13653: @item
13654: Does using a Gforth extension save more work than the porting this part
13655: to other Forth systems (if any) will cost?
13656: 
13657: @item
13658: Is the additional functionality worth the reduction in portability and
13659: the additional porting problems?
13660: 
13661: @end itemize
13662: 
13663: In order to perform these consideratios, you need to know what's
13664: standard and what's not.  This manual generally states if something is
13665: non-standard, but the authoritative source is the
13666: @uref{http://www.taygeta.com/forth/dpans.html,standard document}.
13667: Appendix A of the Standard (@var{Rationale}) provides a valuable insight
13668: into the thought processes of the technical committee.
13669: 
13670: Note also that portability between Forth systems is not the only
13671: portability issue; there is also the issue of portability between
13672: different platforms (processor/OS combinations).
13673: 
13674: @c ***************************************************************
13675: @node Model, Integrating Gforth, Standard vs Extensions, Top
13676: @chapter Model
13677: 
13678: This chapter has yet to be written. It will contain information, on
13679: which internal structures you can rely.
13680: 
13681: @c ***************************************************************
13682: @node Integrating Gforth, Emacs and Gforth, Model, Top
13683: @chapter Integrating Gforth into C programs
13684: 
13685: This is not yet implemented.
13686: 
13687: Several people like to use Forth as scripting language for applications
13688: that are otherwise written in C, C++, or some other language.
13689: 
13690: The Forth system ATLAST provides facilities for embedding it into
13691: applications; unfortunately it has several disadvantages: most
13692: importantly, it is not based on ANS Forth, and it is apparently dead
13693: (i.e., not developed further and not supported). The facilities
13694: provided by Gforth in this area are inspired by ATLAST's facilities, so
13695: making the switch should not be hard.
13696: 
13697: We also tried to design the interface such that it can easily be
13698: implemented by other Forth systems, so that we may one day arrive at a
13699: standardized interface. Such a standard interface would allow you to
13700: replace the Forth system without having to rewrite C code.
13701: 
13702: You embed the Gforth interpreter by linking with the library
13703: @code{libgforth.a} (give the compiler the option @code{-lgforth}).  All
13704: global symbols in this library that belong to the interface, have the
13705: prefix @code{forth_}. (Global symbols that are used internally have the
13706: prefix @code{gforth_}).
13707: 
13708: You can include the declarations of Forth types and the functions and
13709: variables of the interface with @code{#include <forth.h>}.
13710: 
13711: Types.
13712: 
13713: Variables.
13714: 
13715: Data and FP Stack pointer. Area sizes.
13716: 
13717: functions.
13718: 
13719: forth_init(imagefile)
13720: forth_evaluate(string) exceptions?
13721: forth_goto(address) (or forth_execute(xt)?)
13722: forth_continue() (a corountining mechanism)
13723: 
13724: Adding primitives.
13725: 
13726: No checking.
13727: 
13728: Signals?
13729: 
13730: Accessing the Stacks
13731: 
13732: @c ******************************************************************
13733: @node Emacs and Gforth, Image Files, Integrating Gforth, Top
13734: @chapter Emacs and Gforth
13735: @cindex Emacs and Gforth
13736: 
13737: @cindex @file{gforth.el}
13738: @cindex @file{forth.el}
13739: @cindex Rydqvist, Goran
13740: @cindex comment editing commands
13741: @cindex @code{\}, editing with Emacs
13742: @cindex debug tracer editing commands
13743: @cindex @code{~~}, removal with Emacs
13744: @cindex Forth mode in Emacs
13745: Gforth comes with @file{gforth.el}, an improved version of
13746: @file{forth.el} by Goran Rydqvist (included in the TILE package). The
13747: improvements are:
13748: 
13749: @itemize @bullet
13750: @item
13751: A better (but still not perfect) handling of indentation.
13752: @item
13753: Comment paragraph filling (@kbd{M-q})
13754: @item
13755: Commenting (@kbd{C-x \}) and uncommenting (@kbd{C-u C-x \}) of regions
13756: @item
13757: Removal of debugging tracers (@kbd{C-x ~}, @pxref{Debugging}).
13758: @item
13759: Support of the @code{info-lookup} feature for looking up the
13760: documentation of a word.
13761: @end itemize
13762: 
13763: I left the stuff I do not use alone, even though some of it only makes
13764: sense for TILE. To get a description of these features, enter Forth mode
13765: and type @kbd{C-h m}.
13766: 
13767: @cindex source location of error or debugging output in Emacs
13768: @cindex error output, finding the source location in Emacs
13769: @cindex debugging output, finding the source location in Emacs
13770: In addition, Gforth supports Emacs quite well: The source code locations
13771: given in error messages, debugging output (from @code{~~}) and failed
13772: assertion messages are in the right format for Emacs' compilation mode
13773: (@pxref{Compilation, , Running Compilations under Emacs, emacs, Emacs
13774: Manual}) so the source location corresponding to an error or other
13775: message is only a few keystrokes away (@kbd{C-x `} for the next error,
13776: @kbd{C-c C-c} for the error under the cursor).
13777: 
13778: @cindex @file{TAGS} file
13779: @cindex @file{etags.fs}
13780: @cindex viewing the source of a word in Emacs
13781: @cindex @code{require}, placement in files
13782: @cindex @code{include}, placement in files
13783: Also, if you @code{require} @file{etags.fs}, a new @file{TAGS} file will
13784: be produced (@pxref{Tags, , Tags Tables, emacs, Emacs Manual}) that
13785: contains the definitions of all words defined afterwards. You can then
13786: find the source for a word using @kbd{M-.}. Note that emacs can use
13787: several tags files at the same time (e.g., one for the Gforth sources
13788: and one for your program, @pxref{Select Tags Table,,Selecting a Tags
13789: Table,emacs, Emacs Manual}). The TAGS file for the preloaded words is
13790: @file{$(datadir)/gforth/$(VERSION)/TAGS} (e.g.,
13791: @file{/usr/local/share/gforth/0.2.0/TAGS}).  To get the best behaviour
13792: with @file{etags.fs}, you should avoid putting definitions both before
13793: and after @code{require} etc., otherwise you will see the same file
13794: visited several times by commands like @code{tags-search}.
13795: 
13796: @cindex viewing the documentation of a word in Emacs
13797: @cindex context-sensitive help
13798: Moreover, for words documented in this manual, you can look up the
13799: glossary entry quickly by using @kbd{C-h TAB}
13800: (@code{info-lookup-symbol}, @pxref{Documentation, ,Documentation
13801: Commands, emacs, Emacs Manual}).  This feature requires Emacs 20.3 or
13802: later and does not work for words containing @code{:}.
13803: 
13804: 
13805: @cindex @file{.emacs}
13806: To get all these benefits, add the following lines to your @file{.emacs}
13807: file:
13808: 
13809: @example
13810: (autoload 'forth-mode "gforth.el")
13811: (setq auto-mode-alist (cons '("\\.fs\\'" . forth-mode) auto-mode-alist))
13812: @end example
13813: 
13814: @c ******************************************************************
13815: @node Image Files, Engine, Emacs and Gforth, Top
13816: @chapter Image Files
13817: @cindex image file
13818: @cindex @file{.fi} files
13819: @cindex precompiled Forth code
13820: @cindex dictionary in persistent form
13821: @cindex persistent form of dictionary
13822: 
13823: An image file is a file containing an image of the Forth dictionary,
13824: i.e., compiled Forth code and data residing in the dictionary.  By
13825: convention, we use the extension @code{.fi} for image files.
13826: 
13827: @menu
13828: * Image Licensing Issues::      Distribution terms for images.
13829: * Image File Background::       Why have image files?
13830: * Non-Relocatable Image Files::  don't always work.
13831: * Data-Relocatable Image Files::  are better.
13832: * Fully Relocatable Image Files::  better yet.
13833: * Stack and Dictionary Sizes::  Setting the default sizes for an image.
13834: * Running Image Files::         @code{gforth -i @i{file}} or @i{file}.
13835: * Modifying the Startup Sequence::  and turnkey applications.
13836: @end menu
13837: 
13838: @node Image Licensing Issues, Image File Background, Image Files, Image Files
13839: @section Image Licensing Issues
13840: @cindex license for images
13841: @cindex image license
13842: 
13843: An image created with @code{gforthmi} (@pxref{gforthmi}) or
13844: @code{savesystem} (@pxref{Non-Relocatable Image Files}) includes the
13845: original image; i.e., according to copyright law it is a derived work of
13846: the original image.
13847: 
13848: Since Gforth is distributed under the GNU GPL, the newly created image
13849: falls under the GNU GPL, too. In particular, this means that if you
13850: distribute the image, you have to make all of the sources for the image
13851: available, including those you wrote.  For details see @ref{License, ,
13852: GNU General Public License (Section 3)}.
13853: 
13854: If you create an image with @code{cross} (@pxref{cross.fs}), the image
13855: contains only code compiled from the sources you gave it; if none of
13856: these sources is under the GPL, the terms discussed above do not apply
13857: to the image. However, if your image needs an engine (a gforth binary)
13858: that is under the GPL, you should make sure that you distribute both in
13859: a way that is at most a @emph{mere aggregation}, if you don't want the
13860: terms of the GPL to apply to the image.
13861: 
13862: @node Image File Background, Non-Relocatable Image Files, Image Licensing Issues, Image Files
13863: @section Image File Background
13864: @cindex image file background
13865: 
13866: Gforth consists not only of primitives (in the engine), but also of
13867: definitions written in Forth. Since the Forth compiler itself belongs to
13868: those definitions, it is not possible to start the system with the
13869: engine and the Forth source alone. Therefore we provide the Forth
13870: code as an image file in nearly executable form. When Gforth starts up,
13871: a C routine loads the image file into memory, optionally relocates the
13872: addresses, then sets up the memory (stacks etc.) according to
13873: information in the image file, and (finally) starts executing Forth
13874: code.
13875: 
13876: The image file variants represent different compromises between the
13877: goals of making it easy to generate image files and making them
13878: portable.
13879: 
13880: @cindex relocation at run-time
13881: Win32Forth 3.4 and Mitch Bradley's @code{cforth} use relocation at
13882: run-time. This avoids many of the complications discussed below (image
13883: files are data relocatable without further ado), but costs performance
13884: (one addition per memory access).
13885: 
13886: @cindex relocation at load-time
13887: By contrast, the Gforth loader performs relocation at image load time. The
13888: loader also has to replace tokens that represent primitive calls with the
13889: appropriate code-field addresses (or code addresses in the case of
13890: direct threading).
13891: 
13892: There are three kinds of image files, with different degrees of
13893: relocatability: non-relocatable, data-relocatable, and fully relocatable
13894: image files.
13895: 
13896: @cindex image file loader
13897: @cindex relocating loader
13898: @cindex loader for image files
13899: These image file variants have several restrictions in common; they are
13900: caused by the design of the image file loader:
13901: 
13902: @itemize @bullet
13903: @item
13904: There is only one segment; in particular, this means, that an image file
13905: cannot represent @code{ALLOCATE}d memory chunks (and pointers to
13906: them). The contents of the stacks are not represented, either.
13907: 
13908: @item
13909: The only kinds of relocation supported are: adding the same offset to
13910: all cells that represent data addresses; and replacing special tokens
13911: with code addresses or with pieces of machine code.
13912: 
13913: If any complex computations involving addresses are performed, the
13914: results cannot be represented in the image file. Several applications that
13915: use such computations come to mind:
13916: @itemize @minus
13917: @item
13918: Hashing addresses (or data structures which contain addresses) for table
13919: lookup. If you use Gforth's @code{table}s or @code{wordlist}s for this
13920: purpose, you will have no problem, because the hash tables are
13921: recomputed automatically when the system is started. If you use your own
13922: hash tables, you will have to do something similar.
13923: 
13924: @item
13925: There's a cute implementation of doubly-linked lists that uses
13926: @code{XOR}ed addresses. You could represent such lists as singly-linked
13927: in the image file, and restore the doubly-linked representation on
13928: startup.@footnote{In my opinion, though, you should think thrice before
13929: using a doubly-linked list (whatever implementation).}
13930: 
13931: @item
13932: The code addresses of run-time routines like @code{docol:} cannot be
13933: represented in the image file (because their tokens would be replaced by
13934: machine code in direct threaded implementations). As a workaround,
13935: compute these addresses at run-time with @code{>code-address} from the
13936: executions tokens of appropriate words (see the definitions of
13937: @code{docol:} and friends in @file{kernel/getdoers.fs}).
13938: 
13939: @item
13940: On many architectures addresses are represented in machine code in some
13941: shifted or mangled form. You cannot put @code{CODE} words that contain
13942: absolute addresses in this form in a relocatable image file. Workarounds
13943: are representing the address in some relative form (e.g., relative to
13944: the CFA, which is present in some register), or loading the address from
13945: a place where it is stored in a non-mangled form.
13946: @end itemize
13947: @end itemize
13948: 
13949: @node  Non-Relocatable Image Files, Data-Relocatable Image Files, Image File Background, Image Files
13950: @section Non-Relocatable Image Files
13951: @cindex non-relocatable image files
13952: @cindex image file, non-relocatable
13953: 
13954: These files are simple memory dumps of the dictionary. They are specific
13955: to the executable (i.e., @file{gforth} file) they were created
13956: with. What's worse, they are specific to the place on which the
13957: dictionary resided when the image was created. Now, there is no
13958: guarantee that the dictionary will reside at the same place the next
13959: time you start Gforth, so there's no guarantee that a non-relocatable
13960: image will work the next time (Gforth will complain instead of crashing,
13961: though).
13962: 
13963: You can create a non-relocatable image file with
13964: 
13965: 
13966: doc-savesystem
13967: 
13968: 
13969: @node Data-Relocatable Image Files, Fully Relocatable Image Files, Non-Relocatable Image Files, Image Files
13970: @section Data-Relocatable Image Files
13971: @cindex data-relocatable image files
13972: @cindex image file, data-relocatable
13973: 
13974: These files contain relocatable data addresses, but fixed code addresses
13975: (instead of tokens). They are specific to the executable (i.e.,
13976: @file{gforth} file) they were created with. For direct threading on some
13977: architectures (e.g., the i386), data-relocatable images do not work. You
13978: get a data-relocatable image, if you use @file{gforthmi} with a
13979: Gforth binary that is not doubly indirect threaded (@pxref{Fully
13980: Relocatable Image Files}).
13981: 
13982: @node Fully Relocatable Image Files, Stack and Dictionary Sizes, Data-Relocatable Image Files, Image Files
13983: @section Fully Relocatable Image Files
13984: @cindex fully relocatable image files
13985: @cindex image file, fully relocatable
13986: 
13987: @cindex @file{kern*.fi}, relocatability
13988: @cindex @file{gforth.fi}, relocatability
13989: These image files have relocatable data addresses, and tokens for code
13990: addresses. They can be used with different binaries (e.g., with and
13991: without debugging) on the same machine, and even across machines with
13992: the same data formats (byte order, cell size, floating point
13993: format). However, they are usually specific to the version of Gforth
13994: they were created with. The files @file{gforth.fi} and @file{kernl*.fi}
13995: are fully relocatable.
13996: 
13997: There are two ways to create a fully relocatable image file:
13998: 
13999: @menu
14000: * gforthmi::                    The normal way
14001: * cross.fs::                    The hard way
14002: @end menu
14003: 
14004: @node gforthmi, cross.fs, Fully Relocatable Image Files, Fully Relocatable Image Files
14005: @subsection @file{gforthmi}
14006: @cindex @file{comp-i.fs}
14007: @cindex @file{gforthmi}
14008: 
14009: You will usually use @file{gforthmi}. If you want to create an
14010: image @i{file} that contains everything you would load by invoking
14011: Gforth with @code{gforth @i{options}}, you simply say:
14012: @example
14013: gforthmi @i{file} @i{options}
14014: @end example
14015: 
14016: E.g., if you want to create an image @file{asm.fi} that has the file
14017: @file{asm.fs} loaded in addition to the usual stuff, you could do it
14018: like this:
14019: 
14020: @example
14021: gforthmi asm.fi asm.fs
14022: @end example
14023: 
14024: @file{gforthmi} is implemented as a sh script and works like this: It
14025: produces two non-relocatable images for different addresses and then
14026: compares them. Its output reflects this: first you see the output (if
14027: any) of the two Gforth invocations that produce the non-relocatable image
14028: files, then you see the output of the comparing program: It displays the
14029: offset used for data addresses and the offset used for code addresses;
14030: moreover, for each cell that cannot be represented correctly in the
14031: image files, it displays a line like this:
14032: 
14033: @example
14034:      78DC         BFFFFA50         BFFFFA40
14035: @end example
14036: 
14037: This means that at offset $78dc from @code{forthstart}, one input image
14038: contains $bffffa50, and the other contains $bffffa40. Since these cells
14039: cannot be represented correctly in the output image, you should examine
14040: these places in the dictionary and verify that these cells are dead
14041: (i.e., not read before they are written).
14042: 
14043: @cindex --application, @code{gforthmi} option
14044: If you insert the option @code{--application} in front of the image file
14045: name, you will get an image that uses the @code{--appl-image} option
14046: instead of the @code{--image-file} option (@pxref{Invoking
14047: Gforth}). When you execute such an image on Unix (by typing the image
14048: name as command), the Gforth engine will pass all options to the image
14049: instead of trying to interpret them as engine options.
14050: 
14051: If you type @file{gforthmi} with no arguments, it prints some usage
14052: instructions.
14053: 
14054: @cindex @code{savesystem} during @file{gforthmi}
14055: @cindex @code{bye} during @file{gforthmi}
14056: @cindex doubly indirect threaded code
14057: @cindex environment variables
14058: @cindex @code{GFORTHD} -- environment variable
14059: @cindex @code{GFORTH} -- environment variable
14060: @cindex @code{gforth-ditc}
14061: There are a few wrinkles: After processing the passed @i{options}, the
14062: words @code{savesystem} and @code{bye} must be visible. A special doubly
14063: indirect threaded version of the @file{gforth} executable is used for
14064: creating the non-relocatable images; you can pass the exact filename of
14065: this executable through the environment variable @code{GFORTHD}
14066: (default: @file{gforth-ditc}); if you pass a version that is not doubly
14067: indirect threaded, you will not get a fully relocatable image, but a
14068: data-relocatable image (because there is no code address offset). The
14069: normal @file{gforth} executable is used for creating the relocatable
14070: image; you can pass the exact filename of this executable through the
14071: environment variable @code{GFORTH}.
14072: 
14073: @node cross.fs,  , gforthmi, Fully Relocatable Image Files
14074: @subsection @file{cross.fs}
14075: @cindex @file{cross.fs}
14076: @cindex cross-compiler
14077: @cindex metacompiler
14078: @cindex target compiler
14079: 
14080: You can also use @code{cross}, a batch compiler that accepts a Forth-like
14081: programming language (@pxref{Cross Compiler}).
14082: 
14083: @code{cross} allows you to create image files for machines with
14084: different data sizes and data formats than the one used for generating
14085: the image file. You can also use it to create an application image that
14086: does not contain a Forth compiler. These features are bought with
14087: restrictions and inconveniences in programming. E.g., addresses have to
14088: be stored in memory with special words (@code{A!}, @code{A,}, etc.) in
14089: order to make the code relocatable.
14090: 
14091: 
14092: @node Stack and Dictionary Sizes, Running Image Files, Fully Relocatable Image Files, Image Files
14093: @section Stack and Dictionary Sizes
14094: @cindex image file, stack and dictionary sizes
14095: @cindex dictionary size default
14096: @cindex stack size default
14097: 
14098: If you invoke Gforth with a command line flag for the size
14099: (@pxref{Invoking Gforth}), the size you specify is stored in the
14100: dictionary. If you save the dictionary with @code{savesystem} or create
14101: an image with @file{gforthmi}, this size will become the default
14102: for the resulting image file. E.g., the following will create a
14103: fully relocatable version of @file{gforth.fi} with a 1MB dictionary:
14104: 
14105: @example
14106: gforthmi gforth.fi -m 1M
14107: @end example
14108: 
14109: In other words, if you want to set the default size for the dictionary
14110: and the stacks of an image, just invoke @file{gforthmi} with the
14111: appropriate options when creating the image.
14112: 
14113: @cindex stack size, cache-friendly
14114: Note: For cache-friendly behaviour (i.e., good performance), you should
14115: make the sizes of the stacks modulo, say, 2K, somewhat different. E.g.,
14116: the default stack sizes are: data: 16k (mod 2k=0); fp: 15.5k (mod
14117: 2k=1.5k); return: 15k(mod 2k=1k); locals: 14.5k (mod 2k=0.5k).
14118: 
14119: @node Running Image Files, Modifying the Startup Sequence, Stack and Dictionary Sizes, Image Files
14120: @section Running Image Files
14121: @cindex running image files
14122: @cindex invoking image files
14123: @cindex image file invocation
14124: 
14125: @cindex -i, invoke image file
14126: @cindex --image file, invoke image file
14127: You can invoke Gforth with an image file @i{image} instead of the
14128: default @file{gforth.fi} with the @code{-i} flag (@pxref{Invoking Gforth}):
14129: @example
14130: gforth -i @i{image}
14131: @end example
14132: 
14133: @cindex executable image file
14134: @cindex image file, executable
14135: If your operating system supports starting scripts with a line of the
14136: form @code{#! ...}, you just have to type the image file name to start
14137: Gforth with this image file (note that the file extension @code{.fi} is
14138: just a convention). I.e., to run Gforth with the image file @i{image},
14139: you can just type @i{image} instead of @code{gforth -i @i{image}}.
14140: This works because every @code{.fi} file starts with a line of this
14141: format:
14142: 
14143: @example
14144: #! /usr/local/bin/gforth-0.4.0 -i
14145: @end example
14146: 
14147: The file and pathname for the Gforth engine specified on this line is
14148: the specific Gforth executable that it was built against; i.e. the value
14149: of the environment variable @code{GFORTH} at the time that
14150: @file{gforthmi} was executed.
14151: 
14152: You can make use of the same shell capability to make a Forth source
14153: file into an executable. For example, if you place this text in a file:
14154: 
14155: @example
14156: #! /usr/local/bin/gforth
14157: 
14158: ." Hello, world" CR
14159: bye
14160: @end example
14161: 
14162: @noindent
14163: and then make the file executable (chmod +x in Unix), you can run it
14164: directly from the command line. The sequence @code{#!} is used in two
14165: ways; firstly, it is recognised as a ``magic sequence'' by the operating
14166: system@footnote{The Unix kernel actually recognises two types of files:
14167: executable files and files of data, where the data is processed by an
14168: interpreter that is specified on the ``interpreter line'' -- the first
14169: line of the file, starting with the sequence #!. There may be a small
14170: limit (e.g., 32) on the number of characters that may be specified on
14171: the interpreter line.} secondly it is treated as a comment character by
14172: Gforth. Because of the second usage, a space is required between
14173: @code{#!} and the path to the executable (moreover, some Unixes
14174: require the sequence @code{#! /}).
14175: 
14176: The disadvantage of this latter technique, compared with using
14177: @file{gforthmi}, is that it is slightly slower; the Forth source code is
14178: compiled on-the-fly, each time the program is invoked.
14179: 
14180: doc-#!
14181: 
14182: 
14183: @node Modifying the Startup Sequence,  , Running Image Files, Image Files
14184: @section Modifying the Startup Sequence
14185: @cindex startup sequence for image file
14186: @cindex image file initialization sequence
14187: @cindex initialization sequence of image file
14188: 
14189: You can add your own initialization to the startup sequence through the
14190: deferred word @code{'cold}. @code{'cold} is invoked just before the
14191: image-specific command line processing (i.e., loading files and
14192: evaluating (@code{-e}) strings) starts.
14193: 
14194: A sequence for adding your initialization usually looks like this:
14195: 
14196: @example
14197: :noname
14198:     Defers 'cold \ do other initialization stuff (e.g., rehashing wordlists)
14199:     ... \ your stuff
14200: ; IS 'cold
14201: @end example
14202: 
14203: @cindex turnkey image files
14204: @cindex image file, turnkey applications
14205: You can make a turnkey image by letting @code{'cold} execute a word
14206: (your turnkey application) that never returns; instead, it exits Gforth
14207: via @code{bye} or @code{throw}.
14208: 
14209: @cindex command-line arguments, access
14210: @cindex arguments on the command line, access
14211: You can access the (image-specific) command-line arguments through the
14212: variables @code{argc} and @code{argv}. @code{arg} provides convenient
14213: access to @code{argv}.
14214: 
14215: If @code{'cold} exits normally, Gforth processes the command-line
14216: arguments as files to be loaded and strings to be evaluated.  Therefore,
14217: @code{'cold} should remove the arguments it has used in this case.
14218: 
14219: 
14220: 
14221: doc-'cold
14222: doc-argc
14223: doc-argv
14224: doc-arg
14225: 
14226: 
14227: 
14228: @c ******************************************************************
14229: @node Engine, Binding to System Library, Image Files, Top
14230: @chapter Engine
14231: @cindex engine
14232: @cindex virtual machine
14233: 
14234: Reading this chapter is not necessary for programming with Gforth. It
14235: may be helpful for finding your way in the Gforth sources.
14236: 
14237: The ideas in this section have also been published in Bernd Paysan,
14238: @cite{ANS fig/GNU/??? Forth} (in German), Forth-Tagung '93 and M. Anton
14239: Ertl, @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl93.ps.Z, A
14240: Portable Forth Engine}}, EuroForth '93.
14241: 
14242: @menu
14243: * Portability::                 
14244: * Threading::                   
14245: * Primitives::                  
14246: * Performance::                 
14247: @end menu
14248: 
14249: @node Portability, Threading, Engine, Engine
14250: @section Portability
14251: @cindex engine portability
14252: 
14253: An important goal of the Gforth Project is availability across a wide
14254: range of personal machines. fig-Forth, and, to a lesser extent, F83,
14255: achieved this goal by manually coding the engine in assembly language
14256: for several then-popular processors. This approach is very
14257: labor-intensive and the results are short-lived due to progress in
14258: computer architecture.
14259: 
14260: @cindex C, using C for the engine
14261: Others have avoided this problem by coding in C, e.g., Mitch Bradley
14262: (cforth), Mikael Patel (TILE) and Dirk Zoller (pfe). This approach is
14263: particularly popular for UNIX-based Forths due to the large variety of
14264: architectures of UNIX machines. Unfortunately an implementation in C
14265: does not mix well with the goals of efficiency and with using
14266: traditional techniques: Indirect or direct threading cannot be expressed
14267: in C, and switch threading, the fastest technique available in C, is
14268: significantly slower. Another problem with C is that it is very
14269: cumbersome to express double integer arithmetic.
14270: 
14271: @cindex GNU C for the engine
14272: @cindex long long
14273: Fortunately, there is a portable language that does not have these
14274: limitations: GNU C, the version of C processed by the GNU C compiler
14275: (@pxref{C Extensions, , Extensions to the C Language Family, gcc.info,
14276: GNU C Manual}). Its labels as values feature (@pxref{Labels as Values, ,
14277: Labels as Values, gcc.info, GNU C Manual}) makes direct and indirect
14278: threading possible, its @code{long long} type (@pxref{Long Long, ,
14279: Double-Word Integers, gcc.info, GNU C Manual}) corresponds to Forth's
14280: double numbers@footnote{Unfortunately, long longs are not implemented
14281: properly on all machines (e.g., on alpha-osf1, long longs are only 64
14282: bits, the same size as longs (and pointers), but they should be twice as
14283: long according to @pxref{Long Long, , Double-Word Integers, gcc.info, GNU
14284: C Manual}). So, we had to implement doubles in C after all. Still, on
14285: most machines we can use long longs and achieve better performance than
14286: with the emulation package.}. GNU C is available for free on all
14287: important (and many unimportant) UNIX machines, VMS, 80386s running
14288: MS-DOS, the Amiga, and the Atari ST, so a Forth written in GNU C can run
14289: on all these machines.
14290: 
14291: Writing in a portable language has the reputation of producing code that
14292: is slower than assembly. For our Forth engine we repeatedly looked at
14293: the code produced by the compiler and eliminated most compiler-induced
14294: inefficiencies by appropriate changes in the source code.
14295: 
14296: @cindex explicit register declarations
14297: @cindex --enable-force-reg, configuration flag
14298: @cindex -DFORCE_REG
14299: However, register allocation cannot be portably influenced by the
14300: programmer, leading to some inefficiencies on register-starved
14301: machines. We use explicit register declarations (@pxref{Explicit Reg
14302: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) to
14303: improve the speed on some machines. They are turned on by using the
14304: configuration flag @code{--enable-force-reg} (@code{gcc} switch
14305: @code{-DFORCE_REG}). Unfortunately, this feature not only depends on the
14306: machine, but also on the compiler version: On some machines some
14307: compiler versions produce incorrect code when certain explicit register
14308: declarations are used. So by default @code{-DFORCE_REG} is not used.
14309: 
14310: @node Threading, Primitives, Portability, Engine
14311: @section Threading
14312: @cindex inner interpreter implementation
14313: @cindex threaded code implementation
14314: 
14315: @cindex labels as values
14316: GNU C's labels as values extension (available since @code{gcc-2.0},
14317: @pxref{Labels as Values, , Labels as Values, gcc.info, GNU C Manual})
14318: makes it possible to take the address of @i{label} by writing
14319: @code{&&@i{label}}.  This address can then be used in a statement like
14320: @code{goto *@i{address}}. I.e., @code{goto *&&x} is the same as
14321: @code{goto x}.
14322: 
14323: @cindex @code{NEXT}, indirect threaded
14324: @cindex indirect threaded inner interpreter
14325: @cindex inner interpreter, indirect threaded
14326: With this feature an indirect threaded @code{NEXT} looks like:
14327: @example
14328: cfa = *ip++;
14329: ca = *cfa;
14330: goto *ca;
14331: @end example
14332: @cindex instruction pointer
14333: For those unfamiliar with the names: @code{ip} is the Forth instruction
14334: pointer; the @code{cfa} (code-field address) corresponds to ANS Forths
14335: execution token and points to the code field of the next word to be
14336: executed; The @code{ca} (code address) fetched from there points to some
14337: executable code, e.g., a primitive or the colon definition handler
14338: @code{docol}.
14339: 
14340: @cindex @code{NEXT}, direct threaded
14341: @cindex direct threaded inner interpreter
14342: @cindex inner interpreter, direct threaded
14343: Direct threading is even simpler:
14344: @example
14345: ca = *ip++;
14346: goto *ca;
14347: @end example
14348: 
14349: Of course we have packaged the whole thing neatly in macros called
14350: @code{NEXT} and @code{NEXT1} (the part of @code{NEXT} after fetching the cfa).
14351: 
14352: @menu
14353: * Scheduling::                  
14354: * Direct or Indirect Threaded?::  
14355: * DOES>::                       
14356: @end menu
14357: 
14358: @node Scheduling, Direct or Indirect Threaded?, Threading, Threading
14359: @subsection Scheduling
14360: @cindex inner interpreter optimization
14361: 
14362: There is a little complication: Pipelined and superscalar processors,
14363: i.e., RISC and some modern CISC machines can process independent
14364: instructions while waiting for the results of an instruction. The
14365: compiler usually reorders (schedules) the instructions in a way that
14366: achieves good usage of these delay slots. However, on our first tries
14367: the compiler did not do well on scheduling primitives. E.g., for
14368: @code{+} implemented as
14369: @example
14370: n=sp[0]+sp[1];
14371: sp++;
14372: sp[0]=n;
14373: NEXT;
14374: @end example
14375: the @code{NEXT} comes strictly after the other code, i.e., there is
14376: nearly no scheduling. After a little thought the problem becomes clear:
14377: The compiler cannot know that @code{sp} and @code{ip} point to different
14378: addresses (and the version of @code{gcc} we used would not know it even
14379: if it was possible), so it could not move the load of the cfa above the
14380: store to the TOS. Indeed the pointers could be the same, if code on or
14381: very near the top of stack were executed. In the interest of speed we
14382: chose to forbid this probably unused ``feature'' and helped the compiler
14383: in scheduling: @code{NEXT} is divided into several parts:
14384: @code{NEXT_P0}, @code{NEXT_P1} and @code{NEXT_P2}). @code{+} now looks
14385: like:
14386: @example
14387: NEXT_P0;
14388: n=sp[0]+sp[1];
14389: sp++;
14390: NEXT_P1;
14391: sp[0]=n;
14392: NEXT_P2;
14393: @end example
14394: 
14395: There are various schemes that distribute the different operations of
14396: NEXT between these parts in several ways; in general, different schemes
14397: perform best on different processors.  We use a scheme for most
14398: architectures that performs well for most processors of this
14399: architecture; in the furture we may switch to benchmarking and chosing
14400: the scheme on installation time.
14401: 
14402: 
14403: @node Direct or Indirect Threaded?, DOES>, Scheduling, Threading
14404: @subsection Direct or Indirect Threaded?
14405: @cindex threading, direct or indirect?
14406: 
14407: @cindex -DDIRECT_THREADED
14408: Both! After packaging the nasty details in macro definitions we
14409: realized that we could switch between direct and indirect threading by
14410: simply setting a compilation flag (@code{-DDIRECT_THREADED}) and
14411: defining a few machine-specific macros for the direct-threading case.
14412: On the Forth level we also offer access words that hide the
14413: differences between the threading methods (@pxref{Threading Words}).
14414: 
14415: Indirect threading is implemented completely machine-independently.
14416: Direct threading needs routines for creating jumps to the executable
14417: code (e.g. to @code{docol} or @code{dodoes}). These routines are inherently
14418: machine-dependent, but they do not amount to many source lines. Therefore,
14419: even porting direct threading to a new machine requires little effort.
14420: 
14421: @cindex --enable-indirect-threaded, configuration flag
14422: @cindex --enable-direct-threaded, configuration flag
14423: The default threading method is machine-dependent. You can enforce a
14424: specific threading method when building Gforth with the configuration
14425: flag @code{--enable-direct-threaded} or
14426: @code{--enable-indirect-threaded}. Note that direct threading is not
14427: supported on all machines.
14428: 
14429: @node DOES>,  , Direct or Indirect Threaded?, Threading
14430: @subsection DOES>
14431: @cindex @code{DOES>} implementation
14432: 
14433: @cindex @code{dodoes} routine
14434: @cindex @code{DOES>}-code
14435: One of the most complex parts of a Forth engine is @code{dodoes}, i.e.,
14436: the chunk of code executed by every word defined by a
14437: @code{CREATE}...@code{DOES>} pair. The main problem here is: How to find
14438: the Forth code to be executed, i.e. the code after the
14439: @code{DOES>} (the @code{DOES>}-code)? There are two solutions:
14440: 
14441: In fig-Forth the code field points directly to the @code{dodoes} and the
14442: @code{DOES>}-code address is stored in the cell after the code address (i.e. at
14443: @code{@i{CFA} cell+}). It may seem that this solution is illegal in
14444: the Forth-79 and all later standards, because in fig-Forth this address
14445: lies in the body (which is illegal in these standards). However, by
14446: making the code field larger for all words this solution becomes legal
14447: again. We use this approach for the indirect threaded version and for
14448: direct threading on some machines. Leaving a cell unused in most words
14449: is a bit wasteful, but on the machines we are targeting this is hardly a
14450: problem. The other reason for having a code field size of two cells is
14451: to avoid having different image files for direct and indirect threaded
14452: systems (direct threaded systems require two-cell code fields on many
14453: machines).
14454: 
14455: @cindex @code{DOES>}-handler
14456: The other approach is that the code field points or jumps to the cell
14457: after @code{DOES>}. In this variant there is a jump to @code{dodoes} at
14458: this address (the @code{DOES>}-handler). @code{dodoes} can then get the
14459: @code{DOES>}-code address by computing the code address, i.e., the address of
14460: the jump to @code{dodoes}, and add the length of that jump field. A variant of
14461: this is to have a call to @code{dodoes} after the @code{DOES>}; then the
14462: return address (which can be found in the return register on RISCs) is
14463: the @code{DOES>}-code address. Since the two cells available in the code field
14464: are used up by the jump to the code address in direct threading on many
14465: architectures, we use this approach for direct threading on these
14466: architectures. We did not want to add another cell to the code field.
14467: 
14468: @node Primitives, Performance, Threading, Engine
14469: @section Primitives
14470: @cindex primitives, implementation
14471: @cindex virtual machine instructions, implementation
14472: 
14473: @menu
14474: * Automatic Generation::        
14475: * TOS Optimization::            
14476: * Produced code::               
14477: @end menu
14478: 
14479: @node Automatic Generation, TOS Optimization, Primitives, Primitives
14480: @subsection Automatic Generation
14481: @cindex primitives, automatic generation
14482: 
14483: @cindex @file{prims2x.fs}
14484: Since the primitives are implemented in a portable language, there is no
14485: longer any need to minimize the number of primitives. On the contrary,
14486: having many primitives has an advantage: speed. In order to reduce the
14487: number of errors in primitives and to make programming them easier, we
14488: provide a tool, the primitive generator (@file{prims2x.fs}), that
14489: automatically generates most (and sometimes all) of the C code for a
14490: primitive from the stack effect notation.  The source for a primitive
14491: has the following form:
14492: 
14493: @cindex primitive source format
14494: @format
14495: @i{Forth-name}  ( @i{stack-effect} )        @i{category}    [@i{pronounc.}]
14496: [@code{""}@i{glossary entry}@code{""}]
14497: @i{C code}
14498: [@code{:}
14499: @i{Forth code}]
14500: @end format
14501: 
14502: The items in brackets are optional. The category and glossary fields
14503: are there for generating the documentation, the Forth code is there
14504: for manual implementations on machines without GNU C. E.g., the source
14505: for the primitive @code{+} is:
14506: @example
14507: +    ( n1 n2 -- n )   core    plus
14508: n = n1+n2;
14509: @end example
14510: 
14511: This looks like a specification, but in fact @code{n = n1+n2} is C
14512: code. Our primitive generation tool extracts a lot of information from
14513: the stack effect notations@footnote{We use a one-stack notation, even
14514: though we have separate data and floating-point stacks; The separate
14515: notation can be generated easily from the unified notation.}: The number
14516: of items popped from and pushed on the stack, their type, and by what
14517: name they are referred to in the C code. It then generates a C code
14518: prelude and postlude for each primitive. The final C code for @code{+}
14519: looks like this:
14520: 
14521: @example
14522: I_plus: /* + ( n1 n2 -- n ) */  /* label, stack effect */
14523: /*  */                          /* documentation */
14524: NAME("+")                       /* debugging output (with -DDEBUG) */
14525: @{
14526: DEF_CA                          /* definition of variable ca (indirect threading) */
14527: Cell n1;                        /* definitions of variables */
14528: Cell n2;
14529: Cell n;
14530: NEXT_P0;                        /* NEXT part 0 */
14531: n1 = (Cell) sp[1];              /* input */
14532: n2 = (Cell) TOS;
14533: sp += 1;                        /* stack adjustment */
14534: @{
14535: n = n1+n2;                      /* C code taken from the source */
14536: @}
14537: NEXT_P1;                        /* NEXT part 1 */
14538: TOS = (Cell)n;                  /* output */
14539: NEXT_P2;                        /* NEXT part 2 */
14540: @}
14541: @end example
14542: 
14543: This looks long and inefficient, but the GNU C compiler optimizes quite
14544: well and produces optimal code for @code{+} on, e.g., the R3000 and the
14545: HP RISC machines: Defining the @code{n}s does not produce any code, and
14546: using them as intermediate storage also adds no cost.
14547: 
14548: There are also other optimizations that are not illustrated by this
14549: example: assignments between simple variables are usually for free (copy
14550: propagation). If one of the stack items is not used by the primitive
14551: (e.g.  in @code{drop}), the compiler eliminates the load from the stack
14552: (dead code elimination). On the other hand, there are some things that
14553: the compiler does not do, therefore they are performed by
14554: @file{prims2x.fs}: The compiler does not optimize code away that stores
14555: a stack item to the place where it just came from (e.g., @code{over}).
14556: 
14557: While programming a primitive is usually easy, there are a few cases
14558: where the programmer has to take the actions of the generator into
14559: account, most notably @code{?dup}, but also words that do not (always)
14560: fall through to @code{NEXT}.
14561: 
14562: @node TOS Optimization, Produced code, Automatic Generation, Primitives
14563: @subsection TOS Optimization
14564: @cindex TOS optimization for primitives
14565: @cindex primitives, keeping the TOS in a register
14566: 
14567: An important optimization for stack machine emulators, e.g., Forth
14568: engines, is keeping  one or more of the top stack items in
14569: registers.  If a word has the stack effect @i{in1}...@i{inx} @code{--}
14570: @i{out1}...@i{outy}, keeping the top @i{n} items in registers
14571: @itemize @bullet
14572: @item
14573: is better than keeping @i{n-1} items, if @i{x>=n} and @i{y>=n},
14574: due to fewer loads from and stores to the stack.
14575: @item is slower than keeping @i{n-1} items, if @i{x<>y} and @i{x<n} and
14576: @i{y<n}, due to additional moves between registers.
14577: @end itemize
14578: 
14579: @cindex -DUSE_TOS
14580: @cindex -DUSE_NO_TOS
14581: In particular, keeping one item in a register is never a disadvantage,
14582: if there are enough registers. Keeping two items in registers is a
14583: disadvantage for frequent words like @code{?branch}, constants,
14584: variables, literals and @code{i}. Therefore our generator only produces
14585: code that keeps zero or one items in registers. The generated C code
14586: covers both cases; the selection between these alternatives is made at
14587: C-compile time using the switch @code{-DUSE_TOS}. @code{TOS} in the C
14588: code for @code{+} is just a simple variable name in the one-item case,
14589: otherwise it is a macro that expands into @code{sp[0]}. Note that the
14590: GNU C compiler tries to keep simple variables like @code{TOS} in
14591: registers, and it usually succeeds, if there are enough registers.
14592: 
14593: @cindex -DUSE_FTOS
14594: @cindex -DUSE_NO_FTOS
14595: The primitive generator performs the TOS optimization for the
14596: floating-point stack, too (@code{-DUSE_FTOS}). For floating-point
14597: operations the benefit of this optimization is even larger:
14598: floating-point operations take quite long on most processors, but can be
14599: performed in parallel with other operations as long as their results are
14600: not used. If the FP-TOS is kept in a register, this works. If
14601: it is kept on the stack, i.e., in memory, the store into memory has to
14602: wait for the result of the floating-point operation, lengthening the
14603: execution time of the primitive considerably.
14604: 
14605: The TOS optimization makes the automatic generation of primitives a
14606: bit more complicated. Just replacing all occurrences of @code{sp[0]} by
14607: @code{TOS} is not sufficient. There are some special cases to
14608: consider:
14609: @itemize @bullet
14610: @item In the case of @code{dup ( w -- w w )} the generator must not
14611: eliminate the store to the original location of the item on the stack,
14612: if the TOS optimization is turned on.
14613: @item Primitives with stack effects of the form @code{--}
14614: @i{out1}...@i{outy} must store the TOS to the stack at the start.
14615: Likewise, primitives with the stack effect @i{in1}...@i{inx} @code{--}
14616: must load the TOS from the stack at the end. But for the null stack
14617: effect @code{--} no stores or loads should be generated.
14618: @end itemize
14619: 
14620: @node Produced code,  , TOS Optimization, Primitives
14621: @subsection Produced code
14622: @cindex primitives, assembly code listing
14623: 
14624: @cindex @file{engine.s}
14625: To see what assembly code is produced for the primitives on your machine
14626: with your compiler and your flag settings, type @code{make engine.s} and
14627: look at the resulting file @file{engine.s}.  Alternatively, you can also
14628: disassemble the code of primitives with @code{see} on some architectures.
14629: 
14630: @node  Performance,  , Primitives, Engine
14631: @section Performance
14632: @cindex performance of some Forth interpreters
14633: @cindex engine performance
14634: @cindex benchmarking Forth systems
14635: @cindex Gforth performance
14636: 
14637: On RISCs the Gforth engine is very close to optimal; i.e., it is usually
14638: impossible to write a significantly faster engine.
14639: 
14640: On register-starved machines like the 386 architecture processors
14641: improvements are possible, because @code{gcc} does not utilize the
14642: registers as well as a human, even with explicit register declarations;
14643: e.g., Bernd Beuster wrote a Forth system fragment in assembly language
14644: and hand-tuned it for the 486; this system is 1.19 times faster on the
14645: Sieve benchmark on a 486DX2/66 than Gforth compiled with
14646: @code{gcc-2.6.3} with @code{-DFORCE_REG}.  The situation has improved
14647: with gcc-2.95 and gforth-0.4.9; now the most important virtual machine
14648: registers fit in real registers (and we can even afford to use the TOS
14649: optimization), resulting in a speedup of 1.14 on the sieve over the
14650: earlier results.
14651: 
14652: @cindex Win32Forth performance
14653: @cindex NT Forth performance
14654: @cindex eforth performance
14655: @cindex ThisForth performance
14656: @cindex PFE performance
14657: @cindex TILE performance
14658: The potential advantage of assembly language implementations is not
14659: necessarily realized in complete Forth systems: We compared Gforth-0.4.9
14660: (direct threaded, compiled with @code{gcc-2.95.1} and
14661: @code{-DFORCE_REG}) with Win32Forth 1.2093 (newer versions are
14662: reportedly much faster), LMI's NT Forth (Beta, May 1994) and Eforth
14663: (with and without peephole (aka pinhole) optimization of the threaded
14664: code); all these systems were written in assembly language. We also
14665: compared Gforth with three systems written in C: PFE-0.9.14 (compiled
14666: with @code{gcc-2.6.3} with the default configuration for Linux:
14667: @code{-O2 -fomit-frame-pointer -DUSE_REGS -DUNROLL_NEXT}), ThisForth
14668: Beta (compiled with @code{gcc-2.6.3 -O3 -fomit-frame-pointer}; ThisForth
14669: employs peephole optimization of the threaded code) and TILE (compiled
14670: with @code{make opt}). We benchmarked Gforth, PFE, ThisForth and TILE on
14671: a 486DX2/66 under Linux. Kenneth O'Heskin kindly provided the results
14672: for Win32Forth and NT Forth on a 486DX2/66 with similar memory
14673: performance under Windows NT. Marcel Hendrix ported Eforth to Linux,
14674: then extended it to run the benchmarks, added the peephole optimizer,
14675: ran the benchmarks and reported the results.
14676: 
14677: We used four small benchmarks: the ubiquitous Sieve; bubble-sorting and
14678: matrix multiplication come from the Stanford integer benchmarks and have
14679: been translated into Forth by Martin Fraeman; we used the versions
14680: included in the TILE Forth package, but with bigger data set sizes; and
14681: a recursive Fibonacci number computation for benchmarking calling
14682: performance. The following table shows the time taken for the benchmarks
14683: scaled by the time taken by Gforth (in other words, it shows the speedup
14684: factor that Gforth achieved over the other systems).
14685: 
14686: @example
14687: relative      Win32-    NT       eforth       This-      
14688:   time  Gforth Forth Forth eforth  +opt   PFE Forth  TILE
14689: sieve     1.00  1.60  1.32   1.60  0.98  1.82  3.67  9.91
14690: bubble    1.00  1.55  1.66   1.75  1.04  1.78        4.58
14691: matmul    1.00  1.71  1.57   1.69  0.86  1.83        4.74
14692: fib       1.00  1.76  1.54   1.41  1.00  2.01  3.45  4.96
14693: @end example
14694: 
14695: You may be quite surprised by the good performance of Gforth when
14696: compared with systems written in assembly language. One important reason
14697: for the disappointing performance of these other systems is probably
14698: that they are not written optimally for the 486 (e.g., they use the
14699: @code{lods} instruction). In addition, Win32Forth uses a comfortable,
14700: but costly method for relocating the Forth image: like @code{cforth}, it
14701: computes the actual addresses at run time, resulting in two address
14702: computations per @code{NEXT} (@pxref{Image File Background}).
14703: 
14704: Only Eforth with the peephole optimizer performs comparable to
14705: Gforth. The speedups achieved with peephole optimization of threaded
14706: code are quite remarkable. Adding a peephole optimizer to Gforth should
14707: cause similar speedups.
14708: 
14709: The speedup of Gforth over PFE, ThisForth and TILE can be easily
14710: explained with the self-imposed restriction of the latter systems to
14711: standard C, which makes efficient threading impossible (however, the
14712: measured implementation of PFE uses a GNU C extension: @pxref{Global Reg
14713: Vars, , Defining Global Register Variables, gcc.info, GNU C Manual}).
14714: Moreover, current C compilers have a hard time optimizing other aspects
14715: of the ThisForth and the TILE source.
14716: 
14717: The performance of Gforth on 386 architecture processors varies widely
14718: with the version of @code{gcc} used. E.g., @code{gcc-2.5.8} failed to
14719: allocate any of the virtual machine registers into real machine
14720: registers by itself and would not work correctly with explicit register
14721: declarations, giving a 1.5 times slower engine (on a 486DX2/66 running
14722: the Sieve) than the one measured above.
14723: 
14724: Note that there have been several releases of Win32Forth since the
14725: release presented here, so the results presented above may have little
14726: predictive value for the performance of Win32Forth today (results for
14727: the current release on an i486DX2/66 are welcome).
14728: 
14729: @cindex @file{Benchres}
14730: In
14731: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl&maierhofer95.ps.gz,
14732: Translating Forth to Efficient C}} by M. Anton Ertl and Martin
14733: Maierhofer (presented at EuroForth '95), an indirect threaded version of
14734: Gforth is compared with Win32Forth, NT Forth, PFE, ThisForth, and
14735: several native code systems; that version of Gforth is slower on a 486
14736: than the direct threaded version used here. You can find a newer version
14737: of these measurements at
14738: @uref{http://www.complang.tuwien.ac.at/forth/performance.html}. You can
14739: find numbers for Gforth on various machines in @file{Benchres}.
14740: 
14741: @c ******************************************************************
14742: @node Binding to System Library, Cross Compiler, Engine, Top
14743: @chapter Binding to System Library
14744: 
14745: @node Cross Compiler, Bugs, Binding to System Library, Top
14746: @chapter Cross Compiler
14747: @cindex @file{cross.fs}
14748: @cindex cross-compiler
14749: @cindex metacompiler
14750: @cindex target compiler
14751: 
14752: The cross compiler is used to bootstrap a Forth kernel. Since Gforth is
14753: mostly written in Forth, including crucial parts like the outer
14754: interpreter and compiler, it needs compiled Forth code to get
14755: started. The cross compiler allows to create new images for other
14756: architectures, even running under another Forth system.
14757: 
14758: @menu
14759: * Using the Cross Compiler::    
14760: * How the Cross Compiler Works::  
14761: @end menu
14762: 
14763: @node Using the Cross Compiler, How the Cross Compiler Works, Cross Compiler, Cross Compiler
14764: @section Using the Cross Compiler
14765: 
14766: The cross compiler uses a language that resembles Forth, but isn't. The
14767: main difference is that you can execute Forth code after definition,
14768: while you usually can't execute the code compiled by cross, because the
14769: code you are compiling is typically for a different computer than the
14770: one you are compiling on.
14771: 
14772: @c anton: This chapter is somewhat different from waht I would expect: I
14773: @c would expect an explanation of the cross language and how to create an
14774: @c application image with it.  The section explains some aspects of
14775: @c creating a Gforth kernel.
14776: 
14777: The Makefile is already set up to allow you to create kernels for new
14778: architectures with a simple make command. The generic kernels using the
14779: GCC compiled virtual machine are created in the normal build process
14780: with @code{make}. To create a embedded Gforth executable for e.g. the
14781: 8086 processor (running on a DOS machine), type
14782: 
14783: @example
14784: make kernl-8086.fi
14785: @end example
14786: 
14787: This will use the machine description from the @file{arch/8086}
14788: directory to create a new kernel. A machine file may look like that:
14789: 
14790: @example
14791: \ Parameter for target systems                         06oct92py
14792: 
14793:     4 Constant cell             \ cell size in bytes
14794:     2 Constant cell<<           \ cell shift to bytes
14795:     5 Constant cell>bit         \ cell shift to bits
14796:     8 Constant bits/char        \ bits per character
14797:     8 Constant bits/byte        \ bits per byte [default: 8]
14798:     8 Constant float            \ bytes per float
14799:     8 Constant /maxalign        \ maximum alignment in bytes
14800: false Constant bigendian        \ byte order
14801: ( true=big, false=little )
14802: 
14803: include machpc.fs               \ feature list
14804: @end example
14805: 
14806: This part is obligatory for the cross compiler itself, the feature list
14807: is used by the kernel to conditionally compile some features in and out,
14808: depending on whether the target supports these features.
14809: 
14810: There are some optional features, if you define your own primitives,
14811: have an assembler, or need special, nonstandard preparation to make the
14812: boot process work. @code{asm-include} includes an assembler,
14813: @code{prims-include} includes primitives, and @code{>boot} prepares for
14814: booting.
14815: 
14816: @example
14817: : asm-include    ." Include assembler" cr
14818:   s" arch/8086/asm.fs" included ;
14819: 
14820: : prims-include  ." Include primitives" cr
14821:   s" arch/8086/prim.fs" included ;
14822: 
14823: : >boot          ." Prepare booting" cr
14824:   s" ' boot >body into-forth 1+ !" evaluate ;
14825: @end example
14826: 
14827: These words are used as sort of macro during the cross compilation in
14828: the file @file{kernel/main.fs}. Instead of using these macros, it would
14829: be possible --- but more complicated --- to write a new kernel project
14830: file, too.
14831: 
14832: @file{kernel/main.fs} expects the machine description file name on the
14833: stack; the cross compiler itself (@file{cross.fs}) assumes that either
14834: @code{mach-file} leaves a counted string on the stack, or
14835: @code{machine-file} leaves an address, count pair of the filename on the
14836: stack.
14837: 
14838: The feature list is typically controlled using @code{SetValue}, generic
14839: files that are used by several projects can use @code{DefaultValue}
14840: instead. Both functions work like @code{Value}, when the value isn't
14841: defined, but @code{SetValue} works like @code{to} if the value is
14842: defined, and @code{DefaultValue} doesn't set anything, if the value is
14843: defined.
14844: 
14845: @example
14846: \ generic mach file for pc gforth                       03sep97jaw
14847: 
14848: true DefaultValue NIL  \ relocating
14849: 
14850: >ENVIRON
14851: 
14852: true DefaultValue file          \ controls the presence of the
14853:                                 \ file access wordset
14854: true DefaultValue OS            \ flag to indicate a operating system
14855: 
14856: true DefaultValue prims         \ true: primitives are c-code
14857: 
14858: true DefaultValue floating      \ floating point wordset is present
14859: 
14860: true DefaultValue glocals       \ gforth locals are present
14861:                                 \ will be loaded
14862: true DefaultValue dcomps        \ double number comparisons
14863: 
14864: true DefaultValue hash          \ hashing primitives are loaded/present
14865: 
14866: true DefaultValue xconds        \ used together with glocals,
14867:                                 \ special conditionals supporting gforths'
14868:                                 \ local variables
14869: true DefaultValue header        \ save a header information
14870: 
14871: true DefaultValue backtrace     \ enables backtrace code
14872: 
14873: false DefaultValue ec
14874: false DefaultValue crlf
14875: 
14876: cell 2 = [IF] &32 [ELSE] &256 [THEN] KB DefaultValue kernel-size
14877: 
14878: &16 KB          DefaultValue stack-size
14879: &15 KB &512 +   DefaultValue fstack-size
14880: &15 KB          DefaultValue rstack-size
14881: &14 KB &512 +   DefaultValue lstack-size
14882: @end example
14883: 
14884: @node How the Cross Compiler Works,  , Using the Cross Compiler, Cross Compiler
14885: @section How the Cross Compiler Works
14886: 
14887: @node Bugs, Origin, Cross Compiler, Top
14888: @appendix Bugs
14889: @cindex bug reporting
14890: 
14891: Known bugs are described in the file @file{BUGS} in the Gforth distribution.
14892: 
14893: If you find a bug, please send a bug report to
14894: @email{bug-gforth@@gnu.org}. A bug report should include this
14895: information:
14896: 
14897: @itemize @bullet
14898: @item
14899: A program (or a sequence of keyboard commands) that reproduces the bug.
14900: @item
14901: A description of what you think constitutes the buggy behaviour.
14902: @item
14903: The Gforth version used (it is announced at the start of an
14904: interactive Gforth session).
14905: @item
14906: The machine and operating system (on Unix
14907: systems @code{uname -a} will report this information).
14908: @item
14909: The installation options (you can find the configure options at the
14910: start of @file{config.status}) and configuration (@code{configure}
14911: output or @file{config.cache}).
14912: @item
14913: A complete list of changes (if any) you (or your installer) have made to the
14914: Gforth sources.
14915: @end itemize
14916: 
14917: For a thorough guide on reporting bugs read @ref{Bug Reporting, , How
14918: to Report Bugs, gcc.info, GNU C Manual}.
14919: 
14920: 
14921: @node Origin, Forth-related information, Bugs, Top
14922: @appendix Authors and Ancestors of Gforth
14923: 
14924: @section Authors and Contributors
14925: @cindex authors of Gforth
14926: @cindex contributors to Gforth
14927: 
14928: The Gforth project was started in mid-1992 by Bernd Paysan and Anton
14929: Ertl. The third major author was Jens Wilke.  Neal Crook contributed a
14930: lot to the manual.  Assemblers and disassemblers were contributed by
14931: Andrew McKewan, Christian Pirker, and Bernd Thallner.  Lennart Benschop
14932: (who was one of Gforth's first users, in mid-1993) and Stuart Ramsden
14933: inspired us with their continuous feedback. Lennart Benshop contributed
14934: @file{glosgen.fs}, while Stuart Ramsden has been working on automatic
14935: support for calling C libraries. Helpful comments also came from Paul
14936: Kleinrubatscher, Christian Pirker, Dirk Zoller, Marcel Hendrix, John
14937: Wavrik, Barrie Stott, Marc de Groot, Jorge Acerada, Bruce Hoyt, and
14938: Robert Epprecht. Since the release of Gforth-0.2.1 there were also
14939: helpful comments from many others; thank you all, sorry for not listing
14940: you here (but digging through my mailbox to extract your names is on my
14941: to-do list).
14942: 
14943: Gforth also owes a lot to the authors of the tools we used (GCC, CVS,
14944: and autoconf, among others), and to the creators of the Internet: Gforth
14945: was developed across the Internet, and its authors did not meet
14946: physically for the first 4 years of development.
14947: 
14948: @section Pedigree
14949: @cindex pedigree of Gforth
14950: 
14951: Gforth descends from bigFORTH (1993) and fig-Forth.  Of course, a
14952: significant part of the design of Gforth was prescribed by ANS Forth.
14953: 
14954: Bernd Paysan wrote bigFORTH, a descendent from TurboForth, an unreleased
14955: 32 bit native code version of VolksForth for the Atari ST, written
14956: mostly by Dietrich Weineck.
14957: 
14958: VolksForth was written by Klaus Schleisiek, Bernd Pennemann, Georg
14959: Rehfeld and Dietrich Weineck for the C64 (called UltraForth there) in
14960: the mid-80s and ported to the Atari ST in 1986.  It descends from F83.
14961: 
14962: Henry Laxen and Mike Perry wrote F83 as a model implementation of the
14963: Forth-83 standard. !! Pedigree? When?
14964: 
14965: A team led by Bill Ragsdale implemented fig-Forth on many processors in
14966: 1979. Robert Selzer and Bill Ragsdale developed the original
14967: implementation of fig-Forth for the 6502 based on microForth.
14968: 
14969: The principal architect of microForth was Dean Sanderson. microForth was
14970: FORTH, Inc.'s first off-the-shelf product. It was developed in 1976 for
14971: the 1802, and subsequently implemented on the 8080, the 6800 and the
14972: Z80.
14973: 
14974: All earlier Forth systems were custom-made, usually by Charles Moore,
14975: who discovered (as he puts it) Forth during the late 60s. The first full
14976: Forth existed in 1971.
14977: 
14978: A part of the information in this section comes from
14979: @cite{@uref{http://www.forth.com/Content/History/History1.htm,The
14980: Evolution of Forth}} by Elizabeth D. Rather, Donald R. Colburn and
14981: Charles H. Moore, presented at the HOPL-II conference and preprinted in
14982: SIGPLAN Notices 28(3), 1993.  You can find more historical and
14983: genealogical information about Forth there.
14984: 
14985: @c ------------------------------------------------------------------
14986: @node Forth-related information, Word Index, Origin, Top
14987: @appendix Other Forth-related information
14988: @cindex Forth-related information
14989: 
14990: @c anton: I threw most of this stuff out, because it can be found through
14991: @c the FAQ and the FAQ is more likely to be up-to-date.
14992: 
14993: @cindex comp.lang.forth
14994: @cindex frequently asked questions
14995: There is an active news group (comp.lang.forth) discussing Forth
14996: (including Gforth) and Forth-related issues. Its
14997: @uref{http://www.complang.tuwien.ac.at/forth/faq/faq-general-2.html,FAQs}
14998: (frequently asked questions and their answers) contains a lot of
14999: information on Forth.  You should read it before posting to
15000: comp.lang.forth.
15001: 
15002: The ANS Forth standard is most usable in its
15003: @uref{http://www.taygeta.com/forth/dpans.html, HTML form}.
15004: 
15005: @c ------------------------------------------------------------------
15006: @node Word Index, Concept Index, Forth-related information, Top
15007: @unnumbered Word Index
15008: 
15009: This index is a list of Forth words that have ``glossary'' entries
15010: within this manual. Each word is listed with its stack effect and
15011: wordset.
15012: 
15013: @printindex fn
15014: 
15015: @c anton: the name index seems superfluous given the word and concept indices.
15016: 
15017: @c @node Name Index, Concept Index, Word Index, Top
15018: @c @unnumbered Name Index
15019: 
15020: @c This index is a list of Forth words that have ``glossary'' entries
15021: @c within this manual.
15022: 
15023: @c @printindex ky
15024: 
15025: @node Concept Index,  , Word Index, Top
15026: @unnumbered Concept and Word Index
15027: 
15028: Not all entries listed in this index are present verbatim in the
15029: text. This index also duplicates, in abbreviated form, all of the words
15030: listed in the Word Index (only the names are listed for the words here).
15031: 
15032: @printindex cp
15033: 
15034: @contents
15035: @bye
15036: 
15037: 
15038: 

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