File:  [gforth] / gforth / doc / gforth.ds
Revision 1.71: download - view: text, annotated - select for diffs
Mon Aug 14 21:15:01 2000 UTC (23 years, 7 months ago) by anton
Branches: MAIN
CVS tags: HEAD
documentation changes

    1: \input texinfo   @c -*-texinfo-*-
    2: @comment The source is gforth.ds, from which gforth.texi is generated
    3: 
    4: @comment TODO: nac29jan99 - a list of things to add in the next edit:
    5: @comment 1. x-ref all ambiguous or implementation-defined features?
    6: @comment 2. Describe the use of Auser Avariable AConstant A, etc.
    7: @comment 3. words in miscellaneous section need a home.
    8: @comment 4. search for TODO for other minor and major works required.
    9: @comment 5. [rats] change all @var to @i in Forth source so that info
   10: @comment    file looks decent.
   11: @c          Not an improvement IMO - anton
   12: @c          and anyway, this should be taken up
   13: @c          with Karl Berry (the texinfo guy) - anton
   14: @comment .. would be useful to have a word that identified all deferred words
   15: @comment should semantics stuff in intro be moved to another section
   16: 
   17: @c POSTPONE, COMPILE, [COMPILE], LITERAL should have their own section
   18: 
   19: @comment %**start of header (This is for running Texinfo on a region.)
   20: @setfilename gforth.info
   21: @settitle Gforth Manual
   22: @dircategory GNU programming tools
   23: @direntry
   24: * Gforth: (gforth).             A fast interpreter for the Forth language.
   25: @end direntry
   26: @c The Texinfo manual also recommends doing this, but for Gforth it may
   27: @c  not make much sense
   28: @c @dircategory Individual utilities
   29: @c @direntry
   30: @c * Gforth: (gforth)Invoking Gforth.      gforth, gforth-fast, gforthmi
   31: @c @end direntry
   32: 
   33: @comment @setchapternewpage odd
   34: @comment TODO this gets left in by HTML converter
   35: @macro progstyle {}
   36: Programming style note:
   37: @end macro
   38: 
   39: @macro assignment {}
   40: @table @i
   41: @item Assignment:
   42: @end macro
   43: @macro endassignment {}
   44: @end table
   45: @end macro
   46: 
   47: @comment %**end of header (This is for running Texinfo on a region.)
   48: 
   49: 
   50: @comment ----------------------------------------------------------
   51: @comment macros for beautifying glossary entries
   52: @comment if these are used, need to strip them out for HTML converter
   53: @comment else they get repeated verbatim in HTML output.
   54: @comment .. not working yet.
   55: 
   56: @macro GLOSS-START {}
   57: @iftex
   58: @ninerm
   59: @end iftex
   60: @end macro
   61: 
   62: @macro GLOSS-END {}
   63: @iftex
   64: @rm
   65: @end iftex
   66: @end macro
   67: 
   68: @comment ----------------------------------------------------------
   69: 
   70: 
   71: @include version.texi
   72: 
   73: @ifnottex
   74: This file documents Gforth @value{VERSION}
   75: 
   76: Copyright @copyright{} 1995--2000 Free Software Foundation, Inc.
   77: 
   78:      Permission is granted to make and distribute verbatim copies of
   79:      this manual provided the copyright notice and this permission notice
   80:      are preserved on all copies.
   81:      
   82: @ignore
   83:      Permission is granted to process this file through TeX and print the
   84:      results, provided the printed document carries a copying permission
   85:      notice identical to this one except for the removal of this paragraph
   86:      (this paragraph not being relevant to the printed manual).
   87:      
   88: @end ignore
   89:      Permission is granted to copy and distribute modified versions of this
   90:      manual under the conditions for verbatim copying, provided also that the
   91:      sections entitled "Distribution" and "General Public License" are
   92:      included exactly as in the original, and provided that the entire
   93:      resulting derived work is distributed under the terms of a permission
   94:      notice identical to this one.
   95:      
   96:      Permission is granted to copy and distribute translations of this manual
   97:      into another language, under the above conditions for modified versions,
   98:      except that the sections entitled "Distribution" and "General Public
   99:      License" may be included in a translation approved by the author instead
  100:      of in the original English.
  101: @end ifnottex
  102: 
  103: @finalout
  104: @titlepage
  105: @sp 10
  106: @center @titlefont{Gforth Manual}
  107: @sp 2
  108: @center for version @value{VERSION}
  109: @sp 2
  110: @center Neal Crook
  111: @center Anton Ertl
  112: @center Bernd Paysan
  113: @center Jens Wilke
  114: @sp 3
  115: @center This manual is permanently under construction and was last updated on 15-Mar-2000
  116: 
  117: @comment  The following two commands start the copyright page.
  118: @page
  119: @vskip 0pt plus 1filll
  120: Copyright @copyright{} 1995--2000 Free Software Foundation, Inc.
  121: 
  122: @comment !! Published by ... or You can get a copy of this manual ...
  123: 
  124:      Permission is granted to make and distribute verbatim copies of
  125:      this manual provided the copyright notice and this permission notice
  126:      are preserved on all copies.
  127:      
  128:      Permission is granted to copy and distribute modified versions of this
  129:      manual under the conditions for verbatim copying, provided also that the
  130:      sections entitled "Distribution" and "General Public License" are
  131:      included exactly as in the original, and provided that the entire
  132:      resulting derived work is distributed under the terms of a permission
  133:      notice identical to this one.
  134:      
  135:      Permission is granted to copy and distribute translations of this manual
  136:      into another language, under the above conditions for modified versions,
  137:      except that the sections entitled "Distribution" and "General Public
  138:      License" may be included in a translation approved by the author instead
  139:      of in the original English.
  140: @end titlepage
  141: 
  142: @node Top, License, (dir), (dir)
  143: @ifnottex
  144: Gforth is a free implementation of ANS Forth available on many
  145: personal machines. This manual corresponds to version @value{VERSION}.
  146: @end ifnottex
  147: 
  148: @menu
  149: * License::                     The GPL
  150: * Goals::                       About the Gforth Project
  151: * Gforth Environment::          Starting (and exiting) Gforth
  152: * Tutorial::                    Hands-on Forth Tutorial
  153: * Introduction::                An introduction to ANS Forth
  154: * Words::                       Forth words available in Gforth
  155: * Error messages::              How to interpret them
  156: * Tools::                       Programming tools
  157: * ANS conformance::             Implementation-defined options etc.
  158: * Standard vs Extensions::      Should I use extensions?
  159: * Model::                       The abstract machine of Gforth
  160: * Integrating Gforth::          Forth as scripting language for applications
  161: * Emacs and Gforth::            The Gforth Mode
  162: * Image Files::                 @code{.fi} files contain compiled code
  163: * Engine::                      The inner interpreter and the primitives
  164: * Binding to System Library::   
  165: * Cross Compiler::              The Cross Compiler
  166: * Bugs::                        How to report them
  167: * Origin::                      Authors and ancestors of Gforth
  168: * Forth-related information::   Books and places to look on the WWW
  169: * Word Index::                  An item for each Forth word
  170: * Name Index::                  Forth words, only names listed
  171: * Concept Index::               A menu covering many topics
  172: 
  173: @detailmenu --- The Detailed Node Listing ---
  174: 
  175: Gforth Environment
  176: 
  177: * Invoking Gforth::             Getting in
  178: * Leaving Gforth::              Getting out
  179: * Command-line editing::        
  180: * Environment variables::       that affect how Gforth starts up
  181: * Gforth Files::                What gets installed and where
  182: * Startup speed::               When 35ms is not fast enough ...
  183: 
  184: Forth Tutorial
  185: 
  186: * Starting Gforth Tutorial::    
  187: * Syntax Tutorial::             
  188: * Crash Course Tutorial::       
  189: * Stack Tutorial::              
  190: * Arithmetics Tutorial::        
  191: * Stack Manipulation Tutorial::  
  192: * Using files for Forth code Tutorial::  
  193: * Comments Tutorial::           
  194: * Colon Definitions Tutorial::  
  195: * Decompilation Tutorial::      
  196: * Stack-Effect Comments Tutorial::  
  197: * Types Tutorial::              
  198: * Factoring Tutorial::          
  199: * Designing the stack effect Tutorial::  
  200: * Local Variables Tutorial::    
  201: * Conditional execution Tutorial::  
  202: * Flags and Comparisons Tutorial::  
  203: * General Loops Tutorial::      
  204: * Counted loops Tutorial::      
  205: * Recursion Tutorial::          
  206: * Leaving definitions or loops Tutorial::  
  207: * Return Stack Tutorial::       
  208: * Memory Tutorial::             
  209: * Characters and Strings Tutorial::  
  210: * Alignment Tutorial::          
  211: * Interpretation and Compilation Semantics and Immediacy Tutorial::  
  212: * Execution Tokens Tutorial::   
  213: * Exceptions Tutorial::         
  214: * Defining Words Tutorial::     
  215: * Arrays and Records Tutorial::  
  216: * POSTPONE Tutorial::           
  217: * Literal Tutorial::            
  218: * Advanced macros Tutorial::    
  219: * Compilation Tokens Tutorial::  
  220: * Wordlists and Search Order Tutorial::  
  221: 
  222: An Introduction to ANS Forth
  223: 
  224: * Introducing the Text Interpreter::  
  225: * Stacks and Postfix notation::  
  226: * Your first definition::       
  227: * How does that work?::         
  228: * Forth is written in Forth::   
  229: * Review - elements of a Forth system::  
  230: * Where to go next::            
  231: * Exercises::                   
  232: 
  233: Forth Words
  234: 
  235: * Notation::                    
  236: * Case insensitivity::          
  237: * Comments::                    
  238: * Boolean Flags::               
  239: * Arithmetic::                  
  240: * Stack Manipulation::          
  241: * Memory::                      
  242: * Control Structures::          
  243: * Defining Words::              
  244: * Interpretation and Compilation Semantics::  
  245: * Tokens for Words::            
  246: * The Text Interpreter::        
  247: * Word Lists::                  
  248: * Environmental Queries::       
  249: * Files::                       
  250: * Blocks::                      
  251: * Other I/O::                   
  252: * Programming Tools::           
  253: * Assembler and Code Words::    
  254: * Threading Words::             
  255: * Locals::                      
  256: * Structures::                  
  257: * Object-oriented Forth::       
  258: * Passing Commands to the OS::  
  259: * Keeping track of Time::       
  260: * Miscellaneous Words::         
  261: 
  262: Arithmetic
  263: 
  264: * Single precision::            
  265: * Double precision::            Double-cell integer arithmetic
  266: * Bitwise operations::          
  267: * Numeric comparison::          
  268: * Mixed precision::             Operations with single and double-cell integers
  269: * Floating Point::              
  270: 
  271: Stack Manipulation
  272: 
  273: * Data stack::                  
  274: * Floating point stack::        
  275: * Return stack::                
  276: * Locals stack::                
  277: * Stack pointer manipulation::  
  278: 
  279: Memory
  280: 
  281: * Memory model::                
  282: * Dictionary allocation::       
  283: * Heap Allocation::             
  284: * Memory Access::               
  285: * Address arithmetic::          
  286: * Memory Blocks::               
  287: 
  288: Control Structures
  289: 
  290: * Selection::                   IF ... ELSE ... ENDIF
  291: * Simple Loops::                BEGIN ...
  292: * Counted Loops::               DO
  293: * Arbitrary control structures::  
  294: * Calls and returns::           
  295: * Exception Handling::          
  296: 
  297: Defining Words
  298: 
  299: * CREATE::                      
  300: * Variables::                   Variables and user variables
  301: * Constants::                   
  302: * Values::                      Initialised variables
  303: * Colon Definitions::           
  304: * Anonymous Definitions::       Definitions without names
  305: * Supplying names::             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: The Text Interpreter
  327: 
  328: * Input Sources::               
  329: * Number Conversion::           
  330: * Interpret/Compile states::    
  331: * Literals::                    
  332: * Interpreter Directives::      
  333: 
  334: Word Lists
  335: 
  336: * Why use word lists?::         
  337: * Word list examples::          
  338: 
  339: Files
  340: 
  341: * Forth source files::          
  342: * General files::               
  343: * Search Paths::                
  344: 
  345: Search Paths
  346: 
  347: * Forth Search Paths::          
  348: * General Search Paths::        
  349: 
  350: Other I/O
  351: 
  352: * Simple numeric output::       Predefined formats
  353: * Formatted numeric output::    Formatted (pictured) output
  354: * String Formats::              How Forth stores strings in memory
  355: * Displaying characters and strings::  Other stuff
  356: * Input::                       Input
  357: 
  358: Programming Tools
  359: 
  360: * Debugging::                   Simple and quick.
  361: * Assertions::                  Making your programs self-checking.
  362: * Singlestep Debugger::         Executing your program word by word.
  363: 
  364: Assembler and Code Words
  365: 
  366: * Code and ;code::              
  367: * Common Assembler::            Assembler Syntax
  368: * Common Disassembler::         
  369: * 386 Assembler::               Deviations and special cases
  370: * Alpha Assembler::             Deviations and special cases
  371: * MIPS assembler::              Deviations and special cases
  372: * Other assemblers::            How to write them
  373: 
  374: Locals
  375: 
  376: * Gforth locals::               
  377: * ANS Forth locals::            
  378: 
  379: Gforth locals
  380: 
  381: * Where are locals visible by name?::  
  382: * How long do locals live?::    
  383: * Programming Style::           
  384: * Implementation::              
  385: 
  386: Structures
  387: 
  388: * Why explicit structure support?::  
  389: * Structure Usage::             
  390: * Structure Naming Convention::  
  391: * Structure Implementation::    
  392: * Structure Glossary::          
  393: 
  394: Object-oriented Forth
  395: 
  396: * Why object-oriented programming?::  
  397: * Object-Oriented Terminology::  
  398: * Objects::                     
  399: * OOF::                         
  400: * Mini-OOF::                    
  401: * Comparison with other object models::  
  402: 
  403: The @file{objects.fs} model
  404: 
  405: * Properties of the Objects model::  
  406: * Basic Objects Usage::         
  407: * The Objects base class::      
  408: * Creating objects::            
  409: * Object-Oriented Programming Style::  
  410: * Class Binding::               
  411: * Method conveniences::         
  412: * Classes and Scoping::         
  413: * Dividing classes::            
  414: * Object Interfaces::           
  415: * Objects Implementation::      
  416: * Objects Glossary::            
  417: 
  418: The @file{oof.fs} model
  419: 
  420: * Properties of the OOF model::  
  421: * Basic OOF Usage::             
  422: * The OOF base class::          
  423: * Class Declaration::           
  424: * Class Implementation::        
  425: 
  426: The @file{mini-oof.fs} model
  427: 
  428: * Basic Mini-OOF Usage::        
  429: * Mini-OOF Example::            
  430: * Mini-OOF Implementation::     
  431: 
  432: Tools
  433: 
  434: * ANS Report::                  Report the words used, sorted by wordset.
  435: 
  436: ANS conformance
  437: 
  438: * The Core Words::              
  439: * The optional Block word set::  
  440: * The optional Double Number word set::  
  441: * The optional Exception word set::  
  442: * The optional Facility word set::  
  443: * The optional File-Access word set::  
  444: * The optional Floating-Point word set::  
  445: * The optional Locals word set::  
  446: * The optional Memory-Allocation word set::  
  447: * The optional Programming-Tools word set::  
  448: * The optional Search-Order word set::  
  449: 
  450: The Core Words
  451: 
  452: * core-idef::                   Implementation Defined Options                   
  453: * core-ambcond::                Ambiguous Conditions                
  454: * core-other::                  Other System Documentation                  
  455: 
  456: The optional Block word set
  457: 
  458: * block-idef::                  Implementation Defined Options
  459: * block-ambcond::               Ambiguous Conditions               
  460: * block-other::                 Other System Documentation                 
  461: 
  462: The optional Double Number word set
  463: 
  464: * double-ambcond::              Ambiguous Conditions              
  465: 
  466: The optional Exception word set
  467: 
  468: * exception-idef::              Implementation Defined Options              
  469: 
  470: The optional Facility word set
  471: 
  472: * facility-idef::               Implementation Defined Options               
  473: * facility-ambcond::            Ambiguous Conditions            
  474: 
  475: The optional File-Access word set
  476: 
  477: * file-idef::                   Implementation Defined Options
  478: * file-ambcond::                Ambiguous Conditions                
  479: 
  480: The optional Floating-Point word set
  481: 
  482: * floating-idef::               Implementation Defined Options
  483: * floating-ambcond::            Ambiguous Conditions            
  484: 
  485: The optional Locals word set
  486: 
  487: * locals-idef::                 Implementation Defined Options                 
  488: * locals-ambcond::              Ambiguous Conditions              
  489: 
  490: The optional Memory-Allocation word set
  491: 
  492: * memory-idef::                 Implementation Defined Options                 
  493: 
  494: The optional Programming-Tools word set
  495: 
  496: * programming-idef::            Implementation Defined Options            
  497: * programming-ambcond::         Ambiguous Conditions         
  498: 
  499: The optional Search-Order word set
  500: 
  501: * search-idef::                 Implementation Defined Options                 
  502: * search-ambcond::              Ambiguous Conditions              
  503: 
  504: Image Files
  505: 
  506: * Image Licensing Issues::      Distribution terms for images.
  507: * Image File Background::       Why have image files?
  508: * Non-Relocatable Image Files::  don't always work.
  509: * Data-Relocatable Image Files::  are better.
  510: * Fully Relocatable Image Files::  better yet.
  511: * Stack and Dictionary Sizes::  Setting the default sizes for an image.
  512: * Running Image Files::         @code{gforth -i @i{file}} or @i{file}.
  513: * Modifying the Startup Sequence::  and turnkey applications.
  514: 
  515: Fully Relocatable Image Files
  516: 
  517: * gforthmi::                    The normal way
  518: * cross.fs::                    The hard way
  519: 
  520: Engine
  521: 
  522: * Portability::                 
  523: * Threading::                   
  524: * Primitives::                  
  525: * Performance::                 
  526: 
  527: Threading
  528: 
  529: * Scheduling::                  
  530: * Direct or Indirect Threaded?::  
  531: * DOES>::                       
  532: 
  533: Primitives
  534: 
  535: * Automatic Generation::        
  536: * TOS Optimization::            
  537: * Produced code::               
  538: 
  539: Cross Compiler
  540: 
  541: * Using the Cross Compiler::    
  542: * How the Cross Compiler Works::  
  543: 
  544: Other Forth-related information
  545: 
  546: * Internet resources::          
  547: * Books::                       
  548: * The Forth Interest Group::    
  549: * Conferences::                 
  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: This tutorial can be used with any ANS-compliant Forth; any
 1414: Gforth-specific features are marked as such and you can skip them if you
 1415: work with another Forth.  This tutorial does not explain all features of
 1416: Forth, just enough to get you started and give you some ideas about the
 1417: facilities available in Forth.  Read the rest of the manual and the
 1418: standard when you are through this.
 1419: 
 1420: The intended way to use this tutorial is that you work through it while
 1421: sitting in front of the console, take a look at the examples and predict
 1422: what they will do, then try them out; if the outcome is not as expected,
 1423: find out why (e.g., by trying out variations of the example), so you
 1424: understand what's going on.  There are also some assignments that you
 1425: should solve.
 1426: 
 1427: This tutorial assumes that you have programmed before and know what,
 1428: e.g., a loop is.
 1429: 
 1430: @c !! explain compat library
 1431: 
 1432: @menu
 1433: * Starting Gforth Tutorial::    
 1434: * Syntax Tutorial::             
 1435: * Crash Course Tutorial::       
 1436: * Stack Tutorial::              
 1437: * Arithmetics Tutorial::        
 1438: * Stack Manipulation Tutorial::  
 1439: * Using files for Forth code Tutorial::  
 1440: * Comments Tutorial::           
 1441: * Colon Definitions Tutorial::  
 1442: * Decompilation Tutorial::      
 1443: * Stack-Effect Comments Tutorial::  
 1444: * Types Tutorial::              
 1445: * Factoring Tutorial::          
 1446: * Designing the stack effect Tutorial::  
 1447: * Local Variables Tutorial::    
 1448: * Conditional execution Tutorial::  
 1449: * Flags and Comparisons Tutorial::  
 1450: * General Loops Tutorial::      
 1451: * Counted loops Tutorial::      
 1452: * Recursion Tutorial::          
 1453: * Leaving definitions or loops Tutorial::  
 1454: * Return Stack Tutorial::       
 1455: * Memory Tutorial::             
 1456: * Characters and Strings Tutorial::  
 1457: * Alignment Tutorial::          
 1458: * Interpretation and Compilation Semantics and Immediacy Tutorial::  
 1459: * Execution Tokens Tutorial::   
 1460: * Exceptions Tutorial::         
 1461: * Defining Words Tutorial::     
 1462: * Arrays and Records Tutorial::  
 1463: * POSTPONE Tutorial::           
 1464: * Literal Tutorial::            
 1465: * Advanced macros Tutorial::    
 1466: * Compilation Tokens Tutorial::  
 1467: * Wordlists and Search Order Tutorial::  
 1468: @end menu
 1469: 
 1470: @node Starting Gforth Tutorial, Syntax Tutorial, Tutorial, Tutorial
 1471: @section Starting Gforth
 1472: @cindex starting Gforth tutorial
 1473: You can start Gforth by typing its name:
 1474: 
 1475: @example
 1476: gforth
 1477: @end example
 1478: 
 1479: That puts you into interactive mode; you can leave Gforth by typing
 1480: @code{bye}.  While in Gforth, you can edit the command line and access
 1481: the command line history with cursor keys, similar to bash.
 1482: 
 1483: 
 1484: @node Syntax Tutorial, Crash Course Tutorial, Starting Gforth Tutorial, Tutorial
 1485: @section Syntax
 1486: @cindex syntax tutorial
 1487: 
 1488: A @dfn{word} is a sequence of arbitrary characters (expcept white
 1489: space).  Words are separated by white space.  E.g., each of the
 1490: following lines contains exactly one word:
 1491: 
 1492: @example
 1493: word
 1494: !@@#$%^&*()
 1495: 1234567890
 1496: 5!a
 1497: @end example
 1498: 
 1499: A frequent beginner's error is to leave away necessary white space,
 1500: resulting in an error like @samp{Undefined word}; so if you see such an
 1501: error, check if you have put spaces wherever necessary.
 1502: 
 1503: @example
 1504: ." hello, world" \ correct
 1505: ."hello, world"  \ gives an "Undefined word" error
 1506: @end example
 1507: 
 1508: Gforth and most other Forth systems ignore differences in case (they are
 1509: case-insensitive), i.e., @samp{word} is the same as @samp{Word}.  If
 1510: your system is case-sensitive, you may have to type all the examples
 1511: given here in upper case.
 1512: 
 1513: 
 1514: @node Crash Course Tutorial, Stack Tutorial, Syntax Tutorial, Tutorial
 1515: @section Crash Course
 1516: 
 1517: Type
 1518: 
 1519: @example
 1520: 0 0 !
 1521: here execute
 1522: ' catch >body 20 erase abort
 1523: ' (quit) >body 20 erase
 1524: @end example
 1525: 
 1526: The last two examples are guaranteed to destroy parts of Gforth (and
 1527: most other systems), so you better leave Gforth afterwards (if it has
 1528: not finished by itself).  On some systems you may have to kill gforth
 1529: from outside (e.g., in Unix with @code{kill}).
 1530: 
 1531: Now that you know how to produce crashes (and that there's not much to
 1532: them), let's learn how to produce meaningful programs.
 1533: 
 1534: 
 1535: @node Stack Tutorial, Arithmetics Tutorial, Crash Course Tutorial, Tutorial
 1536: @section Stack
 1537: @cindex stack tutorial
 1538: 
 1539: The most obvious feature of Forth is the stack.  When you type in a
 1540: number, it is pushed on the stack.  You can display the content of the
 1541: stack with @code{.s}.
 1542: 
 1543: @example
 1544: 1 2 .s
 1545: 3 .s
 1546: @end example
 1547: 
 1548: @code{.s} displays the top-of-stack to the right, i.e., the numbers
 1549: appear in @code{.s} output as they appeared in the input.
 1550: 
 1551: You can print the top of stack element with @code{.}.
 1552: 
 1553: @example
 1554: 1 2 3 . . .
 1555: @end example
 1556: 
 1557: In general, words consume their stack arguments (@code{.s} is an
 1558: exception).
 1559: 
 1560: @assignment
 1561: What does the stack contain after @code{5 6 7 .}?
 1562: @endassignment
 1563: 
 1564: 
 1565: @node Arithmetics Tutorial, Stack Manipulation Tutorial, Stack Tutorial, Tutorial
 1566: @section Arithmetics
 1567: @cindex arithmetics tutorial
 1568: 
 1569: The words @code{+}, @code{-}, @code{*}, @code{/}, and @code{mod} always
 1570: operate on the top two stack items:
 1571: 
 1572: @example
 1573: 2 2 .s
 1574: + .s
 1575: .
 1576: 2 1 - .
 1577: 7 3 mod .
 1578: @end example
 1579: 
 1580: The operands of @code{-}, @code{/}, and @code{mod} are in the same order
 1581: as in the corresponding infix expression (this is generally the case in
 1582: Forth).
 1583: 
 1584: Parentheses are superfluous (and not available), because the order of
 1585: the words unambiguously determines the order of evaluation and the
 1586: operands:
 1587: 
 1588: @example
 1589: 3 4 + 5 * .
 1590: 3 4 5 * + .
 1591: @end example
 1592: 
 1593: @assignment
 1594: What are the infix expressions corresponding to the Forth code above?
 1595: Write @code{6-7*8+9} in Forth notation@footnote{This notation is also
 1596: known as Postfix or RPN (Reverse Polish Notation).}.
 1597: @endassignment
 1598: 
 1599: To change the sign, use @code{negate}:
 1600: 
 1601: @example
 1602: 2 negate .
 1603: @end example
 1604: 
 1605: @assignment
 1606: Convert -(-3)*4-5 to Forth.
 1607: @endassignment
 1608: 
 1609: @code{/mod} performs both @code{/} and @code{mod}.
 1610: 
 1611: @example
 1612: 7 3 /mod . .
 1613: @end example
 1614: 
 1615: Reference: @ref{Arithmetic}.
 1616: 
 1617: 
 1618: @node Stack Manipulation Tutorial, Using files for Forth code Tutorial, Arithmetics Tutorial, Tutorial
 1619: @section Stack Manipulation
 1620: @cindex stack manipulation tutorial
 1621: 
 1622: Stack manipulation words rearrange the data on the stack.
 1623: 
 1624: @example
 1625: 1 .s drop .s
 1626: 1 .s dup .s drop drop .s
 1627: 1 2 .s over .s drop drop drop
 1628: 1 2 .s swap .s drop drop
 1629: 1 2 3 .s rot .s drop drop drop
 1630: @end example
 1631: 
 1632: These are the most important stack manipulation words.  There are also
 1633: variants that manipulate twice as many stack items:
 1634: 
 1635: @example
 1636: 1 2 3 4 .s 2swap .s 2drop 2drop
 1637: @end example
 1638: 
 1639: Two more stack manipulation words are:
 1640: 
 1641: @example
 1642: 1 2 .s nip .s drop
 1643: 1 2 .s tuck .s 2drop drop
 1644: @end example
 1645: 
 1646: @assignment
 1647: Replace @code{nip} and @code{tuck} with combinations of other stack
 1648: manipulation words.
 1649: 
 1650: @example
 1651: Given:          How do you get:
 1652: 1 2 3           3 2 1           
 1653: 1 2 3           1 2 3 2                 
 1654: 1 2 3           1 2 3 3                 
 1655: 1 2 3           1 3 3           
 1656: 1 2 3           2 1 3           
 1657: 1 2 3 4         4 3 2 1         
 1658: 1 2 3           1 2 3 1 2 3             
 1659: 1 2 3 4         1 2 3 4 1 2             
 1660: 1 2 3
 1661: 1 2 3           1 2 3 4                 
 1662: 1 2 3           1 3             
 1663: @end example
 1664: @endassignment
 1665: 
 1666: @example
 1667: 5 dup * .
 1668: @end example
 1669: 
 1670: @assignment
 1671: Write 17^3 and 17^4 in Forth, without writing @code{17} more than once.
 1672: Write a piece of Forth code that expects two numbers on the stack
 1673: (@var{a} and @var{b}, with @var{b} on top) and computes
 1674: @code{(a-b)(a+1)}.
 1675: @endassignment
 1676: 
 1677: Reference: @ref{Stack Manipulation}.
 1678: 
 1679: 
 1680: @node Using files for Forth code Tutorial, Comments Tutorial, Stack Manipulation Tutorial, Tutorial
 1681: @section Using files for Forth code
 1682: @cindex loading Forth code, tutorial
 1683: @cindex files containing Forth code, tutorial
 1684: 
 1685: While working at the Forth command line is convenient for one-line
 1686: examples and short one-off code, you probably want to store your source
 1687: code in files for convenient editing and persistence.  You can use your
 1688: favourite editor (Gforth includes Emacs support, @pxref{Emacs and
 1689: Gforth}) to create @var{file} and use
 1690: 
 1691: @example
 1692: s" @var{file}" included
 1693: @end example
 1694: 
 1695: to load it into your Forth system.  The file name extension I use for
 1696: Forth files is @samp{.fs}.
 1697: 
 1698: You can easily start Gforth with some files loaded like this:
 1699: 
 1700: @example
 1701: gforth @var{file1} @var{file2}
 1702: @end example
 1703: 
 1704: If an error occurs during loading these files, Gforth terminates,
 1705: whereas an error during @code{INCLUDED} within Gforth usually gives you
 1706: a Gforth command line.  Starting the Forth system every time gives you a
 1707: clean start every time, without interference from the results of earlier
 1708: tries.
 1709: 
 1710: I often put all the tests in a file, then load the code and run the
 1711: tests with
 1712: 
 1713: @example
 1714: gforth @var{code} @var{tests} -e bye
 1715: @end example
 1716: 
 1717: (often by performing this command with @kbd{C-x C-e} in Emacs).  The
 1718: @code{-e bye} ensures that Gforth terminates afterwards so that I can
 1719: restart this command without ado.
 1720: 
 1721: The advantage of this approach is that the tests can be repeated easily
 1722: every time the program ist changed, making it easy to catch bugs
 1723: introduced by the change.
 1724: 
 1725: Reference: @ref{Forth source files}.
 1726: 
 1727: 
 1728: @node Comments Tutorial, Colon Definitions Tutorial, Using files for Forth code Tutorial, Tutorial
 1729: @section Comments
 1730: @cindex comments tutorial
 1731: 
 1732: @example
 1733: \ That's a comment; it ends at the end of the line
 1734: ( Another comment; it ends here: )  .s
 1735: @end example
 1736: 
 1737: @code{\} and @code{(} are ordinary Forth words and therefore have to be
 1738: separated with white space from the following text.
 1739: 
 1740: @example
 1741: \This gives an "Undefined word" error
 1742: @end example
 1743: 
 1744: The first @code{)} ends a comment started with @code{(}, so you cannot
 1745: nest @code{(}-comments; and you cannot comment out text containing a
 1746: @code{)} with @code{( ... )}@footnote{therefore it's a good idea to
 1747: avoid @code{)} in word names.}.
 1748: 
 1749: I use @code{\}-comments for descriptive text and for commenting out code
 1750: of one or more line; I use @code{(}-comments for describing the stack
 1751: effect, the stack contents, or for commenting out sub-line pieces of
 1752: code.
 1753: 
 1754: The Emacs mode @file{gforth.el} (@pxref{Emacs and Gforth}) supports
 1755: these uses by commenting out a region with @kbd{C-x \}, uncommenting a
 1756: region with @kbd{C-u C-x \}, and filling a @code{\}-commented region
 1757: with @kbd{M-q}.
 1758: 
 1759: Reference: @ref{Comments}.
 1760: 
 1761: 
 1762: @node Colon Definitions Tutorial, Decompilation Tutorial, Comments Tutorial, Tutorial
 1763: @section Colon Definitions
 1764: @cindex colon definitions, tutorial
 1765: @cindex definitions, tutorial
 1766: @cindex procedures, tutorial
 1767: @cindex functions, tutorial
 1768: 
 1769: are similar to procedures and functions in other programming languages.
 1770: 
 1771: @example
 1772: : squared ( n -- n^2 )
 1773:    dup * ;
 1774: 5 squared .
 1775: 7 squared .
 1776: @end example
 1777: 
 1778: @code{:} starts the colon definition; its name is @code{squared}.  The
 1779: following comment describes its stack effect.  The words @code{dup *}
 1780: are not executed, but compiled into the definition.  @code{;} ends the
 1781: colon definition.
 1782: 
 1783: The newly-defined word can be used like any other word, including using
 1784: it in other definitions:
 1785: 
 1786: @example
 1787: : cubed ( n -- n^3 )
 1788:    dup squared * ;
 1789: -5 cubed .
 1790: : fourth-power ( n -- n^4 )
 1791:    squared squared ;
 1792: 3 fourth-power .
 1793: @end example
 1794: 
 1795: @assignment
 1796: Write colon definitions for @code{nip}, @code{tuck}, @code{negate}, and
 1797: @code{/mod} in terms of other Forth words, and check if they work (hint:
 1798: test your tests on the originals first).  Don't let the
 1799: @samp{redefined}-Messages spook you, they are just warnings.
 1800: @endassignment
 1801: 
 1802: Reference: @ref{Colon Definitions}.
 1803: 
 1804: 
 1805: @node Decompilation Tutorial, Stack-Effect Comments Tutorial, Colon Definitions Tutorial, Tutorial
 1806: @section Decompilation
 1807: @cindex decompilation tutorial
 1808: @cindex see tutorial
 1809: 
 1810: You can decompile colon definitions with @code{see}:
 1811: 
 1812: @example
 1813: see squared
 1814: see cubed
 1815: @end example
 1816: 
 1817: In Gforth @code{see} shows you a reconstruction of the source code from
 1818: the executable code.  Informations that were present in the source, but
 1819: not in the executable code, are lost (e.g., comments).
 1820: 
 1821: You can also decompile the predefined words:
 1822: 
 1823: @example
 1824: see .
 1825: see +
 1826: @end example
 1827: 
 1828: 
 1829: @node Stack-Effect Comments Tutorial, Types Tutorial, Decompilation Tutorial, Tutorial
 1830: @section Stack-Effect Comments
 1831: @cindex stack-effect comments, tutorial
 1832: @cindex --, tutorial
 1833: By convention the comment after the name of a definition describes the
 1834: stack effect: The part in from of the @samp{--} describes the state of
 1835: the stack before the execution of the definition, i.e., the parameters
 1836: that are passed into the colon definition; the part behind the @samp{--}
 1837: is the state of the stack after the execution of the definition, i.e.,
 1838: the results of the definition.  The stack comment only shows the top
 1839: stack items that the definition accesses and/or changes.
 1840: 
 1841: You should put a correct stack effect on every definition, even if it is
 1842: just @code{( -- )}.  You should also add some descriptive comment to
 1843: more complicated words (I usually do this in the lines following
 1844: @code{:}).  If you don't do this, your code becomes unreadable (because
 1845: you have to work through every definition before you can undertsand
 1846: any).
 1847: 
 1848: @assignment
 1849: The stack effect of @code{swap} can be written like this: @code{x1 x2 --
 1850: x2 x1}.  Describe the stack effect of @code{-}, @code{drop}, @code{dup},
 1851: @code{over}, @code{rot}, @code{nip}, and @code{tuck}.  Hint: When you
 1852: are done, you can compare your stack effects to those in this manual
 1853: (@pxref{Word Index}).
 1854: @endassignment
 1855: 
 1856: Sometimes programmers put comments at various places in colon
 1857: definitions that describe the contents of the stack at that place (stack
 1858: comments); i.e., they are like the first part of a stack-effect
 1859: comment. E.g.,
 1860: 
 1861: @example
 1862: : cubed ( n -- n^3 )
 1863:    dup squared  ( n n^2 ) * ;
 1864: @end example
 1865: 
 1866: In this case the stack comment is pretty superfluous, because the word
 1867: is simple enough.  If you think it would be a good idea to add such a
 1868: comment to increase readability, you should also consider factoring the
 1869: word into several simpler words (@pxref{Factoring Tutorial,,
 1870: Factoring}), which typically eliminates the need for the stack comment;
 1871: however, if you decide not to refactor it, then having such a comment is
 1872: better than not having it.
 1873: 
 1874: The names of the stack items in stack-effect and stack comments in the
 1875: standard, in this manual, and in many programs specify the type through
 1876: a type prefix, similar to Fortran and Hungarian notation.  The most
 1877: frequent prefixes are:
 1878: 
 1879: @table @code
 1880: @item n
 1881: signed integer
 1882: @item u
 1883: unsigned integer
 1884: @item c
 1885: character
 1886: @item f
 1887: Boolean flags, i.e. @code{false} or @code{true}.
 1888: @item a-addr,a-
 1889: Cell-aligned address
 1890: @item c-addr,c-
 1891: Char-aligned address (note that a Char may have two bytes in Windows NT)
 1892: @item xt
 1893: Execution token, same size as Cell
 1894: @item w,x
 1895: Cell, can contain an integer or an address.  It usually takes 32, 64 or
 1896: 16 bits (depending on your platform and Forth system). A cell is more
 1897: commonly known as machine word, but the term @emph{word} already means
 1898: something different in Forth.
 1899: @item d
 1900: signed double-cell integer
 1901: @item ud
 1902: unsigned double-cell integer
 1903: @item r
 1904: Float (on the FP stack)
 1905: @end table
 1906: 
 1907: You can find a more complete list in @ref{Notation}.
 1908: 
 1909: @assignment
 1910: Write stack-effect comments for all definitions you have written up to
 1911: now.
 1912: @endassignment
 1913: 
 1914: 
 1915: @node Types Tutorial, Factoring Tutorial, Stack-Effect Comments Tutorial, Tutorial
 1916: @section Types
 1917: @cindex types tutorial
 1918: 
 1919: In Forth the names of the operations are not overloaded; so similar
 1920: operations on different types need different names; e.g., @code{+} adds
 1921: integers, and you have to use @code{f+} to add floating-point numbers.
 1922: The following prefixes are often used for related operations on
 1923: different types:
 1924: 
 1925: @table @code
 1926: @item (none)
 1927: signed integer
 1928: @item u
 1929: unsigned integer
 1930: @item c
 1931: character
 1932: @item d
 1933: signed double-cell integer
 1934: @item ud, du
 1935: unsigned double-cell integer
 1936: @item 2
 1937: two cells (not-necessarily double-cell numbers)
 1938: @item m, um
 1939: mixed single-cell and double-cell operations
 1940: @item f
 1941: floating-point (note that in stack comments @samp{f} represents flags,
 1942: and @samp{r} represents FP numbers).
 1943: @end table
 1944: 
 1945: If there are no differences between the signed and the unsigned variant
 1946: (e.g., for @code{+}), there is only the prefix-less variant.
 1947: 
 1948: Forth does not perform type checking, neither at compile time, nor at
 1949: run time.  If you use the wrong oeration, the data are interpreted
 1950: incorrectly:
 1951: 
 1952: @example
 1953: -1 u.
 1954: @end example
 1955: 
 1956: If you have only experience with type-checked languages until now, and
 1957: have heard how important type-checking is, don't panic!  In my
 1958: experience (and that of other Forthers), type errors in Forth code are
 1959: usually easy to find (once you get used to it), the increased vigilance
 1960: of the programmer tends to catch some harder errors in addition to most
 1961: type errors, and you never have to work around the type system, so in
 1962: most situations the lack of type-checking seems to be a win (projects to
 1963: add type checking to Forth have not caught on).
 1964: 
 1965: 
 1966: @node Factoring Tutorial, Designing the stack effect Tutorial, Types Tutorial, Tutorial
 1967: @section Factoring
 1968: @cindex factoring tutorial
 1969: 
 1970: If you try to write longer definitions, you will soon find it hard to
 1971: keep track of the stack contents.  Therefore, good Forth programmers
 1972: tend to write only short definitions (e.g., three lines).  The art of
 1973: finding meaningful short definitions is known as factoring (as in
 1974: factoring polynomials).
 1975: 
 1976: Well-factored programs offer additional advantages: smaller, more
 1977: general words, are easier to test and debug and can be reused more and
 1978: better than larger, specialized words.
 1979: 
 1980: So, if you run into difficulties with stack management, when writing
 1981: code, try to define meaningful factors for the word, and define the word
 1982: in terms of those.  Even if a factor contains only two words, it is
 1983: often helpful.
 1984: 
 1985: Good factoring is not easy, and it takes some practice to get the knack
 1986: for it; but even experienced Forth programmers often don't find the
 1987: right solution right away, but only when rewriting the program.  So, if
 1988: you don't come up with a good solution immediately, keep trying, don't
 1989: despair.
 1990: 
 1991: @c example !!
 1992: 
 1993: 
 1994: @node Designing the stack effect Tutorial, Local Variables Tutorial, Factoring Tutorial, Tutorial
 1995: @section Designing the stack effect
 1996: @cindex Stack effect design, tutorial
 1997: @cindex design of stack effects, tutorial
 1998: 
 1999: In other languages you can use an arbitrary order of parameters for a
 2000: function; and since there is only one result, you don't have to deal with
 2001: the order of results, either.
 2002: 
 2003: In Forth (and other stack-based languages, e.g., Postscript) the
 2004: parameter and result order of a definition is important and should be
 2005: designed well.  The general guideline is to design the stack effect such
 2006: that the word is simple to use in most cases, even if that complicates
 2007: the implementation of the word.  Some concrete rules are:
 2008: 
 2009: @itemize @bullet
 2010: 
 2011: @item
 2012: Words consume all of their parameters (e.g., @code{.}).
 2013: 
 2014: @item
 2015: If there is a convention on the order of parameters (e.g., from
 2016: mathematics or another programming language), stick with it (e.g.,
 2017: @code{-}).
 2018: 
 2019: @item
 2020: If one parameter usually requires only a short computation (e.g., it is
 2021: a constant), pass it on the top of the stack.  Conversely, parameters
 2022: that usually require a long sequence of code to compute should be passed
 2023: as the bottom (i.e., first) parameter.  This makes the code easier to
 2024: read, because reader does not need to keep track of the bottom item
 2025: through a long sequence of code (or, alternatively, through stack
 2026: manipulations). E.g., @code{!} (store, @pxref{Memory}) expects the
 2027: address on top of the stack because it is usually simpler to compute
 2028: than the stored value (often the address is just a variable).
 2029: 
 2030: @item
 2031: Similarly, results that are usually consumed quickly should be returned
 2032: on the top of stack, whereas a result that is often used in long
 2033: computations should be passed as bottom result.  E.g., the file words
 2034: like @code{open-file} return the error code on the top of stack, because
 2035: it is usually consumed quickly by @code{throw}; moreover, the error code
 2036: has to be checked before doing anything with the other results.
 2037: 
 2038: @end itemize
 2039: 
 2040: These rules are just general guidelines, don't lose sight of the overall
 2041: goal to make the words easy to use.  E.g., if the convention rule
 2042: conflicts with the computation-length rule, you might decide in favour
 2043: of the convention if the word will be used rarely, and in favour of the
 2044: computation-length rule if the word will be used frequently (because
 2045: with frequent use the cost of breaking the computation-length rule would
 2046: be quite high, and frequent use makes it easier to remember an
 2047: unconventional order).
 2048: 
 2049: @c example !! structure package
 2050: 
 2051: 
 2052: @node Local Variables Tutorial, Conditional execution Tutorial, Designing the stack effect Tutorial, Tutorial
 2053: @section Local Variables
 2054: @cindex local variables, tutorial
 2055: 
 2056: You can define local variables (@emph{locals}) in a colon definition:
 2057: 
 2058: @example
 2059: : swap @{ a b -- b a @}
 2060:   b a ;
 2061: 1 2 swap .s 2drop
 2062: @end example
 2063: 
 2064: (If your Forth system does not support this syntax, include
 2065: @file{compat/anslocals.fs} first).
 2066: 
 2067: In this example @code{@{ a b -- b a @}} is the locals definition; it
 2068: takes two cells from the stack, puts the top of stack in @code{b} and
 2069: the next stack element in @code{a}.  @code{--} starts a comment ending
 2070: with @code{@}}.  After the locals definition, using the name of the
 2071: local will push its value on the stack.  You can leave the comment
 2072: part (@code{-- b a}) away:
 2073: 
 2074: @example
 2075: : swap ( x1 x2 -- x2 x1 )
 2076:   @{ a b @} b a ;
 2077: @end example
 2078: 
 2079: In Gforth you can have several locals definitions, anywhere in a colon
 2080: definition; in contrast, in a standard program you can have only one
 2081: locals definition per colon definition, and that locals definition must
 2082: be outside any controll structure.
 2083: 
 2084: With locals you can write slightly longer definitions without running
 2085: into stack trouble.  However, I recommend trying to write colon
 2086: definitions without locals for exercise purposes to help you gain the
 2087: essential factoring skills.
 2088: 
 2089: @assignment
 2090: Rewrite your definitions until now with locals
 2091: @endassignment
 2092: 
 2093: Reference: @ref{Locals}.
 2094: 
 2095: 
 2096: @node Conditional execution Tutorial, Flags and Comparisons Tutorial, Local Variables Tutorial, Tutorial
 2097: @section Conditional execution
 2098: @cindex conditionals, tutorial
 2099: @cindex if, tutorial
 2100: 
 2101: In Forth you can use control structures only inside colon definitions.
 2102: An @code{if}-structure looks like this:
 2103: 
 2104: @example
 2105: : abs ( n1 -- +n2 )
 2106:     dup 0 < if
 2107:         negate
 2108:     endif ;
 2109: 5 abs .
 2110: -5 abs .
 2111: @end example
 2112: 
 2113: @code{if} takes a flag from the stack.  If the flag is non-zero (true),
 2114: the following code is performed, otherwise execution continues after the
 2115: @code{endif} (or @code{else}).  @code{<} compares the top two stack
 2116: elements and prioduces a flag:
 2117: 
 2118: @example
 2119: 1 2 < .
 2120: 2 1 < .
 2121: 1 1 < .
 2122: @end example
 2123: 
 2124: Actually the standard name for @code{endif} is @code{then}.  This
 2125: tutorial presents the examples using @code{endif}, because this is often
 2126: less confusing for people familiar with other programming languages
 2127: where @code{then} has a different meaning.  If your system does not have
 2128: @code{endif}, define it with
 2129: 
 2130: @example
 2131: : endif postpone then ; immediate
 2132: @end example
 2133: 
 2134: You can optionally use an @code{else}-part:
 2135: 
 2136: @example
 2137: : min ( n1 n2 -- n )
 2138:   2dup < if
 2139:     drop
 2140:   else
 2141:     nip
 2142:   endif ;
 2143: 2 3 min .
 2144: 3 2 min .
 2145: @end example
 2146: 
 2147: @assignment
 2148: Write @code{min} without @code{else}-part (hint: what's the definition
 2149: of @code{nip}?).
 2150: @endassignment
 2151: 
 2152: Reference: @ref{Selection}.
 2153: 
 2154: 
 2155: @node Flags and Comparisons Tutorial, General Loops Tutorial, Conditional execution Tutorial, Tutorial
 2156: @section Flags and Comparisons
 2157: @cindex flags tutorial
 2158: @cindex comparison tutorial
 2159: 
 2160: In a false-flag all bits are clear (0 when interpreted as integer).  In
 2161: a canonical true-flag all bits are set (-1 as a twos-complement signed
 2162: integer); in many contexts (e.g., @code{if}) any non-zero value is
 2163: treated as true flag.
 2164: 
 2165: @example
 2166: false .
 2167: true .
 2168: true hex u. decimal
 2169: @end example
 2170: 
 2171: Comparison words produce canonical flags:
 2172: 
 2173: @example
 2174: 1 1 = .
 2175: 1 0= .
 2176: 0 1 < .
 2177: 0 0 < .
 2178: -1 1 u< . \ type error, u< interprets -1 as large unsigned number
 2179: -1 1 < .
 2180: @end example
 2181: 
 2182: Gforth supports all combinations of the prefixes @code{0 u d d0 du f f0}
 2183: (or none) and the comparisons @code{= <> < > <= >=}.  Only a part of
 2184: these combinations are standard (for details see the standard,
 2185: @ref{Numeric comparison}, @ref{Floating Point} or @ref{Word Index}).
 2186: 
 2187: You can use @code{and or xor invert} can be used as operations on
 2188: canonical flags.  Actually they are bitwise operations:
 2189: 
 2190: @example
 2191: 1 2 and .
 2192: 1 2 or .
 2193: 1 3 xor .
 2194: 1 invert .
 2195: @end example
 2196: 
 2197: You can convert a zero/non-zero flag into a canonical flag with
 2198: @code{0<>} (and complement it on the way with @code{0=}).
 2199: 
 2200: @example
 2201: 1 0= .
 2202: 1 0<> .
 2203: @end example
 2204: 
 2205: You can use the all-bits-set feature of canonical flags and the bitwise
 2206: operation of the Boolean operations to avoid @code{if}s:
 2207: 
 2208: @example
 2209: : foo ( n1 -- n2 )
 2210:   0= if
 2211:     14
 2212:   else
 2213:     0
 2214:   endif ;
 2215: 0 foo .
 2216: 1 foo .
 2217: 
 2218: : foo ( n1 -- n2 )
 2219:   0= 14 and ;
 2220: 0 foo .
 2221: 1 foo .
 2222: @end example
 2223: 
 2224: @assignment
 2225: Write @code{min} without @code{if}.
 2226: @endassignment
 2227: 
 2228: For reference, see @ref{Boolean Flags}, @ref{Numeric comparison}, and
 2229: @ref{Bitwise operations}.
 2230: 
 2231: 
 2232: @node General Loops Tutorial, Counted loops Tutorial, Flags and Comparisons Tutorial, Tutorial
 2233: @section General Loops
 2234: @cindex loops, indefinite, tutorial
 2235: 
 2236: The endless loop is the most simple one:
 2237: 
 2238: @example
 2239: : endless ( -- )
 2240:   0 begin
 2241:     dup . 1+
 2242:   again ;
 2243: endless
 2244: @end example
 2245: 
 2246: Terminate this loop by pressing @kbd{Ctrl-C} (in Gforth).  @code{begin}
 2247: does nothing at run-time, @code{again} jumps back to @code{begin}.
 2248: 
 2249: A loop with one exit at any place looks like this:
 2250: 
 2251: @example
 2252: : log2 ( +n1 -- n2 )
 2253: \ logarithmus dualis of n1>0, rounded down to the next integer
 2254:   assert( dup 0> )
 2255:   2/ 0 begin
 2256:     over 0> while
 2257:       1+ swap 2/ swap
 2258:   repeat
 2259:   nip ;
 2260: 7 log2 .
 2261: 8 log2 .
 2262: @end example
 2263: 
 2264: At run-time @code{while} consumes a flag; if it is 0, execution
 2265: continues behind the @code{repeat}; if the flag is non-zero, execution
 2266: continues behind the @code{while}.  @code{Repeat} jumps back to
 2267: @code{begin}, just like @code{again}.
 2268: 
 2269: In Forth there are many combinations/abbreviations, like @code{1+}.
 2270: However, @code{2/} is not one of them; it shifts it's argument right by
 2271: one bit (arithmetic shift right):
 2272: 
 2273: @example
 2274: -5 2 / .
 2275: -5 2/ .
 2276: @end example
 2277: 
 2278: @code{assert(} is no standard word, but you can get it on systems other
 2279: then Gforth by including @file{compat/assert.fs}.  You can see what it
 2280: does by trying
 2281: 
 2282: @example
 2283: 0 log2 .
 2284: @end example
 2285: 
 2286: Here's a loop with an exit at the end:
 2287: 
 2288: @example
 2289: : log2 ( +n1 -- n2 )
 2290: \ logarithmus dualis of n1>0, rounded down to the next integer
 2291:   assert( dup 0 > )
 2292:   -1 begin
 2293:     1+ swap 2/ swap
 2294:     over 0 <=
 2295:   until
 2296:   nip ;
 2297: @end example
 2298: 
 2299: @code{Until} consumes a flag; if it is non-zero, execution continues at
 2300: the @code{begin}, otherwise after the @code{until}.
 2301: 
 2302: @assignment
 2303: Write a definition for computing the greatest common divisor.
 2304: @endassignment
 2305: 
 2306: Reference: @ref{Simple Loops}.
 2307: 
 2308: 
 2309: @node Counted loops Tutorial, Recursion Tutorial, General Loops Tutorial, Tutorial
 2310: @section Counted loops
 2311: @cindex loops, counted, tutorial
 2312: 
 2313: @example
 2314: : ^ ( n1 u -- n )
 2315: \ n = the uth power of u1
 2316:   1 swap 0 u+do
 2317:     over *
 2318:   loop
 2319:   nip ;
 2320: 3 2 ^ .
 2321: 4 3 ^ .
 2322: @end example
 2323: 
 2324: @code{U+do} (from @file{compat/loops.fs}, if your Forth system doesn't
 2325: have it) takes two numbers of the stack @code{( u3 u4 -- )}, and then
 2326: performs the code between @code{u+do} and @code{loop} for @code{u3-u4}
 2327: times (or not at all, if @code{u3-u4<0}).
 2328: 
 2329: You can see the stack effect design rules at work in the stack effect of
 2330: the loop start words: Since the start value of the loop is more
 2331: frequently constant than the end value, the start value is passed on
 2332: the top-of-stack.
 2333: 
 2334: You can access the counter of a counted loop with @code{i}:
 2335: 
 2336: @example
 2337: : fac ( u -- u! )
 2338:   1 swap 1+ 1 u+do
 2339:     i *
 2340:   loop ;
 2341: 5 fac .
 2342: 7 fac .
 2343: @end example
 2344: 
 2345: There is also @code{+do}, which expects signed numbers (important for
 2346: deciding whether to enter the loop).
 2347: 
 2348: @assignment
 2349: Write a definition for computing the nth Fibonacci number.
 2350: @endassignment
 2351: 
 2352: You can also use increments other than 1:
 2353: 
 2354: @example
 2355: : up2 ( n1 n2 -- )
 2356:   +do
 2357:     i .
 2358:   2 +loop ;
 2359: 10 0 up2
 2360: 
 2361: : down2 ( n1 n2 -- )
 2362:   -do
 2363:     i .
 2364:   2 -loop ;
 2365: 0 10 down2
 2366: @end example
 2367: 
 2368: Reference: @ref{Counted Loops}.
 2369: 
 2370: 
 2371: @node Recursion Tutorial, Leaving definitions or loops Tutorial, Counted loops Tutorial, Tutorial
 2372: @section Recursion
 2373: @cindex recursion tutorial
 2374: 
 2375: Usually the name of a definition is not visible in the definition; but
 2376: earlier definitions are usually visible:
 2377: 
 2378: @example
 2379: 1 0 / . \ "Floating-point unidentified fault" in Gforth on most platforms
 2380: : / ( n1 n2 -- n )
 2381:   dup 0= if
 2382:     -10 throw \ report division by zero
 2383:   endif
 2384:   /           \ old version
 2385: ;
 2386: 1 0 /
 2387: @end example
 2388: 
 2389: For recursive definitions you can use @code{recursive} (non-standard) or
 2390: @code{recurse}:
 2391: 
 2392: @example
 2393: : fac1 ( n -- n! ) recursive
 2394:  dup 0> if
 2395:    dup 1- fac1 *
 2396:  else
 2397:    drop 1
 2398:  endif ;
 2399: 7 fac1 .
 2400: 
 2401: : fac2 ( n -- n! )
 2402:  dup 0> if
 2403:    dup 1- recurse *
 2404:  else
 2405:    drop 1
 2406:  endif ;
 2407: 8 fac2 .
 2408: @end example
 2409: 
 2410: @assignment
 2411: Write a recursive definition for computing the nth Fibonacci number.
 2412: @endassignment
 2413: 
 2414: Reference (including indirect recursion): @xref{Calls and returns}.
 2415: 
 2416: 
 2417: @node Leaving definitions or loops Tutorial, Return Stack Tutorial, Recursion Tutorial, Tutorial
 2418: @section Leaving definitions or loops
 2419: @cindex leaving definitions, tutorial
 2420: @cindex leaving loops, tutorial
 2421: 
 2422: @code{EXIT} exits the current definition right away.  For every counted
 2423: loop that is left in this way, an @code{UNLOOP} has to be performed
 2424: before the @code{EXIT}:
 2425: 
 2426: @c !! real examples
 2427: @example
 2428: : ...
 2429:  ... u+do
 2430:    ... if
 2431:      ... unloop exit
 2432:    endif
 2433:    ...
 2434:  loop
 2435:  ... ;
 2436: @end example
 2437: 
 2438: @code{LEAVE} leaves the innermost counted loop right away:
 2439: 
 2440: @example
 2441: : ...
 2442:  ... u+do
 2443:    ... if
 2444:      ... leave
 2445:    endif
 2446:    ...
 2447:  loop
 2448:  ... ;
 2449: @end example
 2450: 
 2451: @c !! example
 2452: 
 2453: Reference: @ref{Calls and returns}, @ref{Counted Loops}.
 2454: 
 2455: 
 2456: @node Return Stack Tutorial, Memory Tutorial, Leaving definitions or loops Tutorial, Tutorial
 2457: @section Return Stack
 2458: @cindex return stack tutorial
 2459: 
 2460: In addition to the data stack Forth also has a second stack, the return
 2461: stack; most Forth systems store the return addresses of procedure calls
 2462: there (thus its name).  Programmers can also use this stack:
 2463: 
 2464: @example
 2465: : foo ( n1 n2 -- )
 2466:  .s
 2467:  >r .s
 2468:  r@@ .
 2469:  >r .s
 2470:  r@@ .
 2471:  r> .
 2472:  r@@ .
 2473:  r> . ;
 2474: 1 2 foo
 2475: @end example
 2476: 
 2477: @code{>r} takes an element from the data stack and pushes it onto the
 2478: return stack; conversely, @code{r>} moves an elementm from the return to
 2479: the data stack; @code{r@@} pushes a copy of the top of the return stack
 2480: on the return stack.
 2481: 
 2482: Forth programmers usually use the return stack for storing data
 2483: temporarily, if using the data stack alone would be too complex, and
 2484: factoring and locals are not an option:
 2485: 
 2486: @example
 2487: : 2swap ( x1 x2 x3 x4 -- x3 x4 x1 x2 )
 2488:  rot >r rot r> ;
 2489: @end example
 2490: 
 2491: The return address of the definition and the loop control parameters of
 2492: counted loops usually reside on the return stack, so you have to take
 2493: all items, that you have pushed on the return stack in a colon
 2494: definition or counted loop, from the return stack before the definition
 2495: or loop ends.  You cannot access items that you pushed on the return
 2496: stack outside some definition or loop within the definition of loop.
 2497: 
 2498: If you miscount the return stack items, this usually ends in a crash:
 2499: 
 2500: @example
 2501: : crash ( n -- )
 2502:   >r ;
 2503: 5 crash
 2504: @end example
 2505: 
 2506: You cannot mix using locals and using the return stack (according to the
 2507: standard; Gforth has no problem).  However, they solve the same
 2508: problems, so this shouldn't be an issue.
 2509: 
 2510: @assignment
 2511: Can you rewrite any of the definitions you wrote until now in a better
 2512: way using the return stack?
 2513: @endassignment
 2514: 
 2515: Reference: @ref{Return stack}.
 2516: 
 2517: 
 2518: @node Memory Tutorial, Characters and Strings Tutorial, Return Stack Tutorial, Tutorial
 2519: @section Memory
 2520: @cindex memory access/allocation tutorial
 2521: 
 2522: You can create a global variable @code{v} with
 2523: 
 2524: @example
 2525: variable v ( -- addr )
 2526: @end example
 2527: 
 2528: @code{v} pushes the address of a cell in memory on the stack.  This cell
 2529: was reserved by @code{variable}.  You can use @code{!} (store) to store
 2530: values into this cell and @code{@@} (fetch) to load the value from the
 2531: stack into memory:
 2532: 
 2533: @example
 2534: v .
 2535: 5 v ! .s
 2536: v @@ .
 2537: @end example
 2538: 
 2539: You can see a raw dump of memory with @code{dump}:
 2540: 
 2541: @example
 2542: v 1 cells .s dump
 2543: @end example
 2544: 
 2545: @code{Cells ( n1 -- n2 )} gives you the number of bytes (or, more
 2546: generally, address units (aus)) that @code{n1 cells} occupy.  You can
 2547: also reserve more memory:
 2548: 
 2549: @example
 2550: create v2 20 cells allot
 2551: v2 20 cells dump
 2552: @end example
 2553: 
 2554: creates a word @code{v2} and reserves 20 uninitialized cells; the
 2555: address pushed by @code{v2} points to the start of these 20 cells.  You
 2556: can use address arithmetic to access these cells:
 2557: 
 2558: @example
 2559: 3 v2 5 cells + !
 2560: v2 20 cells dump
 2561: @end example
 2562: 
 2563: You can reserve and initialize memory with @code{,}:
 2564: 
 2565: @example
 2566: create v3
 2567:   5 , 4 , 3 , 2 , 1 ,
 2568: v3 @@ .
 2569: v3 cell+ @@ .
 2570: v3 2 cells + @@ .
 2571: v3 5 cells dump
 2572: @end example
 2573: 
 2574: @assignment
 2575: Write a definition @code{vsum ( addr u -- n )} that computes the sum of
 2576: @code{u} cells, with the first of these cells at @code{addr}, the next
 2577: one at @code{addr cell+} etc.
 2578: @endassignment
 2579: 
 2580: You can also reserve memory without creating a new word:
 2581: 
 2582: @example
 2583: here 10 cells allot .
 2584: here .
 2585: @end example
 2586: 
 2587: @code{Here} pushes the start address of the memory area.  You should
 2588: store it somewhere, or you will have a hard time finding the memory area
 2589: again.
 2590: 
 2591: @code{Allot} manages dictionary memory.  The dictionary memory contains
 2592: the system's data structures for words etc. on Gforth and most other
 2593: Forth systems.  It is managed like a stack: You can free the memory that
 2594: you have just @code{allot}ed with
 2595: 
 2596: @example
 2597: -10 cells allot
 2598: here .
 2599: @end example
 2600: 
 2601: Note that you cannot do this if you have created a new word in the
 2602: meantime (because then your @code{allot}ed memory is no longer on the
 2603: top of the dictionary ``stack'').
 2604: 
 2605: Alternatively, you can use @code{allocate} and @code{free} which allow
 2606: freeing memory in any order:
 2607: 
 2608: @example
 2609: 10 cells allocate throw .s
 2610: 20 cells allocate throw .s
 2611: swap
 2612: free throw
 2613: free throw
 2614: @end example
 2615: 
 2616: The @code{throw}s deal with errors (e.g., out of memory).
 2617: 
 2618: And there is also a
 2619: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
 2620: garbage collector}, which eliminates the need to @code{free} memory
 2621: explicitly.
 2622: 
 2623: Reference: @ref{Memory}.
 2624: 
 2625: 
 2626: @node Characters and Strings Tutorial, Alignment Tutorial, Memory Tutorial, Tutorial
 2627: @section Characters and Strings
 2628: @cindex strings tutorial
 2629: @cindex characters tutorial
 2630: 
 2631: On the stack characters take up a cell, like numbers.  In memory they
 2632: have their own size (one 8-bit byte on most systems), and therefore
 2633: require their own words for memory access:
 2634: 
 2635: @example
 2636: create v4 
 2637:   104 c, 97 c, 108 c, 108 c, 111 c,
 2638: v4 4 chars + c@@ .
 2639: v4 5 chars dump
 2640: @end example
 2641: 
 2642: The preferred representation of strings on the stack is @code{addr
 2643: u-count}, where @code{addr} is the address of the first character and
 2644: @code{u-count} is the number of characters in the string.
 2645: 
 2646: @example
 2647: v4 5 type
 2648: @end example
 2649: 
 2650: You get a string constant with
 2651: 
 2652: @example
 2653: s" hello, world" .s
 2654: type
 2655: @end example
 2656: 
 2657: Make sure you have a space between @code{s"} and the string; @code{s"}
 2658: is a normal Forth word and must be delimited with white space (try what
 2659: happens when you remove the space).
 2660: 
 2661: However, this interpretive use of @code{s"} is quite restricted: the
 2662: string exists only until the next call of @code{s"} (some Forth systems
 2663: keep more than one of these strings, but usually they still have a
 2664: limited lifetime).
 2665: 
 2666: @example
 2667: s" hello," s" world" .s
 2668: type
 2669: type
 2670: @end example
 2671: 
 2672: You can also use @code{s"} in a definition, and the resulting
 2673: strings then live forever (well, for as long as the definition):
 2674: 
 2675: @example
 2676: : foo s" hello," s" world" ;
 2677: foo .s
 2678: type
 2679: type
 2680: @end example
 2681: 
 2682: @assignment
 2683: @code{Emit ( c -- )} types @code{c} as character (not a number).
 2684: Implement @code{type ( addr u -- )}.
 2685: @endassignment
 2686: 
 2687: Reference: @ref{Memory Blocks}.
 2688: 
 2689: 
 2690: @node Alignment Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Characters and Strings Tutorial, Tutorial
 2691: @section Alignment
 2692: @cindex alignment tutorial
 2693: @cindex memory alignment tutorial
 2694: 
 2695: On many processors cells have to be aligned in memory, if you want to
 2696: access them with @code{@@} and @code{!} (and even if the processor does
 2697: not require alignment, access to aligned cells is faster).
 2698: 
 2699: @code{Create} aligns @code{here} (i.e., the place where the next
 2700: allocation will occur, and that the @code{create}d word points to).
 2701: Likewise, the memory produced by @code{allocate} starts at an aligned
 2702: address.  Adding a number of @code{cells} to an aligned address produces
 2703: another aligned address.
 2704: 
 2705: However, address arithmetic involving @code{char+} and @code{chars} can
 2706: create an address that is not cell-aligned.  @code{Aligned ( addr --
 2707: a-addr )} produces the next aligned address:
 2708: 
 2709: @example
 2710: v3 char+ aligned .s @@ .
 2711: v3 char+ .s @@ .
 2712: @end example
 2713: 
 2714: Similarly, @code{align} advances @code{here} to the next aligned
 2715: address:
 2716: 
 2717: @example
 2718: create v5 97 c,
 2719: here .
 2720: align here .
 2721: 1000 ,
 2722: @end example
 2723: 
 2724: Note that you should use aligned addresses even if your processor does
 2725: not require them, if you want your program to be portable.
 2726: 
 2727: Reference: @ref{Address arithmetic}.
 2728: 
 2729: 
 2730: @node Interpretation and Compilation Semantics and Immediacy Tutorial, Execution Tokens Tutorial, Alignment Tutorial, Tutorial
 2731: @section Interpretation and Compilation Semantics and Immediacy
 2732: @cindex semantics tutorial
 2733: @cindex interpretation semantics tutorial
 2734: @cindex compilation semantics tutorial
 2735: @cindex immediate, tutorial
 2736: 
 2737: When a word is compiled, it behaves differently from being interpreted.
 2738: E.g., consider @code{+}:
 2739: 
 2740: @example
 2741: 1 2 + .
 2742: : foo + ;
 2743: @end example
 2744: 
 2745: These two behaviours are known as compilation and interpretation
 2746: semantics.  For normal words (e.g., @code{+}), the compilation semantics
 2747: is to append the interpretation semantics to the currently defined word
 2748: (@code{foo} in the example above).  I.e., when @code{foo} is executed
 2749: later, the interpretation semantics of @code{+} (i.e., adding two
 2750: numbers) will be performed.
 2751: 
 2752: However, there are words with non-default compilation semantics, e.g.,
 2753: the control-flow words like @code{if}.  You can use @code{immediate} to
 2754: change the compilation semantics of the last defined word to be equal to
 2755: the interpretation semantics:
 2756: 
 2757: @example
 2758: : [FOO] ( -- )
 2759:  5 . ; immediate
 2760: 
 2761: [FOO]
 2762: : bar ( -- )
 2763:   [FOO] ;
 2764: bar
 2765: see bar
 2766: @end example
 2767: 
 2768: Two conventions to mark words with non-default compilation semnatics are
 2769: names with brackets (more frequently used) and to write them all in
 2770: upper case (less frequently used).
 2771: 
 2772: In Gforth (and many other systems) you can also remove the
 2773: interpretation semantics with @code{compile-only} (the compilation
 2774: semantics is derived from the original interpretation semantics):
 2775: 
 2776: @example
 2777: : flip ( -- )
 2778:  6 . ; compile-only \ but not immediate
 2779: flip
 2780: 
 2781: : flop ( -- )
 2782:  flip ;
 2783: flop
 2784: @end example
 2785: 
 2786: In this example the interpretation semantics of @code{flop} is equal to
 2787: the original interpretation semantics of @code{flip}.
 2788: 
 2789: The text interpreter has two states: in interpret state, it performs the
 2790: interpretation semantics of words it encounters; in compile state, it
 2791: performs the compilation semantics of these words.
 2792: 
 2793: Among other things, @code{:} switches into compile state, and @code{;}
 2794: switches back to interpret state.  They contain the factors @code{]}
 2795: (switch to compile state) and @code{[} (switch to interpret state), that
 2796: do nothing but switch the state.
 2797: 
 2798: @example
 2799: : xxx ( -- )
 2800:   [ 5 . ]
 2801: ;
 2802: 
 2803: xxx
 2804: see xxx
 2805: @end example
 2806: 
 2807: These brackets are also the source of the naming convention mentioned
 2808: above.
 2809: 
 2810: Reference: @ref{Interpretation and Compilation Semantics}.
 2811: 
 2812: 
 2813: @node Execution Tokens Tutorial, Exceptions Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Tutorial
 2814: @section Execution Tokens
 2815: @cindex execution tokens tutorial
 2816: @cindex XT tutorial
 2817: 
 2818: @code{' word} gives you the execution token (XT) of a word.  The XT is a
 2819: cell representing the interpretation semantics of a word.  You can
 2820: execute this semantics with @code{execute}:
 2821: 
 2822: @example
 2823: ' + .s
 2824: 1 2 rot execute .
 2825: @end example
 2826: 
 2827: The XT is similar to a function pointer in C.  However, parameter
 2828: passing through the stack makes it a little more flexible:
 2829: 
 2830: @example
 2831: : map-array ( ... addr u xt -- ... )
 2832: \ executes xt ( ... x -- ... ) for every element of the array starting
 2833: \ at addr and containing u elements
 2834:   @{ xt @}
 2835:   cells over + swap ?do
 2836:     i @@ xt execute
 2837:   1 cells +loop ;
 2838: 
 2839: create a 3 , 4 , 2 , -1 , 4 ,
 2840: a 5 ' . map-array .s
 2841: 0 a 5 ' + map-array .
 2842: s" max-n" environment? drop .s
 2843: a 5 ' min map-array .
 2844: @end example
 2845: 
 2846: You can use map-array with the XTs of words that consume one element
 2847: more than they produce.  In theory you can also use it with other XTs,
 2848: but the stack effect then depends on the size of the array, which is
 2849: hard to understand.
 2850: 
 2851: Since XTs are cell-sized, you can store them in memory and manipulate
 2852: them on the stack like other cells.  You can also compile the XT into a
 2853: word with @code{compile,}:
 2854: 
 2855: @example
 2856: : foo1 ( n1 n2 -- n )
 2857:    [ ' + compile, ] ;
 2858: see foo
 2859: @end example
 2860: 
 2861: This is non-standard, because @code{compile,} has no compilation
 2862: semantics in the standard, but it works in good Forth systems.  For the
 2863: broken ones, use
 2864: 
 2865: @example
 2866: : [compile,] compile, ; immediate
 2867: 
 2868: : foo1 ( n1 n2 -- n )
 2869:    [ ' + ] [compile,] ;
 2870: see foo
 2871: @end example
 2872: 
 2873: @code{'} is a word with default compilation semantics; it parses the
 2874: next word when its interpretation semantics are executed, not during
 2875: compilation:
 2876: 
 2877: @example
 2878: : foo ( -- xt )
 2879:   ' ;
 2880: see foo
 2881: : bar ( ... "word" -- ... )
 2882:   ' execute ;
 2883: see bar
 2884: 1 2 bar + .
 2885: @end example
 2886: 
 2887: You often want to parse a word during compilation and compile its XT so
 2888: it will be pushed on the stack at run-time.  @code{[']} does this:
 2889: 
 2890: @example
 2891: : xt-+ ( -- xt )
 2892:   ['] + ;
 2893: see xt-+
 2894: 1 2 xt-+ execute .
 2895: @end example
 2896: 
 2897: Many programmers tend to see @code{'} and the word it parses as one
 2898: unit, and expect it to behave like @code{[']} when compiled, and are
 2899: confused by the actual behaviour.  If you are, just remember that the
 2900: Forth system just takes @code{'} as one unit and has no idea that it is
 2901: a parsing word (attempts to convenience programmers in this issue have
 2902: usually resulted in even worse pitfalls, see
 2903: @uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,
 2904: @code{State}-smartness---Why it is evil and How to Exorcise it}).
 2905: 
 2906: Note that the state of the interpreter does not come into play when
 2907: creating and executing XTs.  I.e., even when you execute @code{'} in
 2908: compile state, it still gives you the interpretation semantics.  And
 2909: whatever that state is, @code{execute} performs the semantics
 2910: represented by the XT (i.e., for XTs produced with @code{'} the
 2911: interpretation semantics).
 2912: 
 2913: Reference: @ref{Tokens for Words}.
 2914: 
 2915: 
 2916: @node Exceptions Tutorial, Defining Words Tutorial, Execution Tokens Tutorial, Tutorial
 2917: @section Exceptions
 2918: @cindex exceptions tutorial
 2919: 
 2920: @code{throw ( n -- )} causes an exception unless n is zero.
 2921: 
 2922: @example
 2923: 100 throw .s
 2924: 0 throw .s
 2925: @end example
 2926: 
 2927: @code{catch ( ... xt -- ... n )} behaves similar to @code{execute}, but
 2928: it catches exceptions and pushes the number of the exception on the
 2929: stack (or 0, if the xt executed without exception).  If there was an
 2930: exception, the stacks have the same depth as when entering @code{catch}:
 2931: 
 2932: @example
 2933: .s
 2934: 3 0 ' / catch .s
 2935: 3 2 ' / catch .s
 2936: @end example
 2937: 
 2938: @assignment
 2939: Try the same with @code{execute} instead of @code{catch}.
 2940: @endassignment
 2941: 
 2942: @code{Throw} always jumps to the dynamically next enclosing
 2943: @code{catch}, even if it has to leave several call levels to achieve
 2944: this:
 2945: 
 2946: @example
 2947: : foo 100 throw ;
 2948: : foo1 foo ." after foo" ;
 2949: : bar ['] foo1 catch ;
 2950: bar .
 2951: @end example
 2952: 
 2953: It is often important to restore a value upon leaving a definition, even
 2954: if the definition is left through an exception.  You can ensure this
 2955: like this:
 2956: 
 2957: @example
 2958: : ...
 2959:    save-x
 2960:    ['] word-changing-x catch ( ... n )
 2961:    restore-x
 2962:    ( ... n ) throw ;
 2963: @end example
 2964: 
 2965: Gforth provides an alternative syntax in addition to @code{catch}:
 2966: @code{try ... recover ... endtry}.  If the code between @code{try} and
 2967: @code{recover} has an exception, the stack depths are restored, the
 2968: exception number is pushed on the stack, and the code between
 2969: @code{recover} and @code{endtry} is performed.  E.g., the definition for
 2970: @code{catch} is
 2971: 
 2972: @example
 2973: : catch ( x1 .. xn xt -- y1 .. ym 0 / z1 .. zn error ) \ exception
 2974:   try
 2975:     execute 0
 2976:   recover
 2977:     nip
 2978:   endtry ;
 2979: @end example
 2980: 
 2981: The equivalent to the restoration code above is
 2982: 
 2983: @example
 2984: : ...
 2985:   save-x
 2986:   try
 2987:     word-changing-x
 2988:   end-try
 2989:   restore-x
 2990:   throw ;
 2991: @end example
 2992: 
 2993: As you can see, the @code{recover} part is optional.
 2994: 
 2995: Reference: @ref{Exception Handling}.
 2996: 
 2997: 
 2998: @node Defining Words Tutorial, Arrays and Records Tutorial, Exceptions Tutorial, Tutorial
 2999: @section Defining Words
 3000: @cindex defining words tutorial
 3001: @cindex does> tutorial
 3002: @cindex create...does> tutorial
 3003: 
 3004: @c before semantics?
 3005: 
 3006: @code{:}, @code{create}, and @code{variable} are definition words: They
 3007: define other words.  @code{Constant} is another definition word:
 3008: 
 3009: @example
 3010: 5 constant foo
 3011: foo .
 3012: @end example
 3013: 
 3014: You can also use the prefixes @code{2} (double-cell) and @code{f}
 3015: (floating point) with @code{variable} and @code{constant}.
 3016: 
 3017: You can also define your own defining words.  E.g.:
 3018: 
 3019: @example
 3020: : variable ( "name" -- )
 3021:   create 0 , ;
 3022: @end example
 3023: 
 3024: You can also define defining words that create words that do something
 3025: other than just producing their address:
 3026: 
 3027: @example
 3028: : constant ( n "name" -- )
 3029:   create ,
 3030: does> ( -- n )
 3031:   ( addr ) @@ ;
 3032: 
 3033: 5 constant foo
 3034: foo .
 3035: @end example
 3036: 
 3037: The definition of @code{constant} above ends at the @code{does>}; i.e.,
 3038: @code{does>} replaces @code{;}, but it also does something else: It
 3039: changes the last defined word such that it pushes the address of the
 3040: body of the word and then performs the code after the @code{does>}
 3041: whenever it is called.
 3042: 
 3043: In the example above, @code{constant} uses @code{,} to store 5 into the
 3044: body of @code{foo}.  When @code{foo} executes, it pushes the address of
 3045: the body onto the stack, then (in the code after the @code{does>})
 3046: fetches the 5 from there.
 3047: 
 3048: The stack comment near the @code{does>} reflects the stack effect of the
 3049: defined word, not the stack effect of the code after the @code{does>}
 3050: (the difference is that the code expects the address of the body that
 3051: the stack comment does not show).
 3052: 
 3053: You can use these definition words to do factoring in cases that involve
 3054: (other) definition words.  E.g., a field offset is always added to an
 3055: address.  Instead of defining
 3056: 
 3057: @example
 3058: 2 cells constant offset-field1
 3059: @end example
 3060: 
 3061: and using this like
 3062: 
 3063: @example
 3064: ( addr ) offset-field1 +
 3065: @end example
 3066: 
 3067: you can define a definition word
 3068: 
 3069: @example
 3070: : simple-field ( n "name" -- )
 3071:   create ,
 3072: does> ( n1 -- n1+n )
 3073:   ( addr ) @@ + ;
 3074: @end example
 3075: 
 3076: Definition and use of field offsets now look like this:
 3077: 
 3078: @example
 3079: 2 cells simple-field field1
 3080: create mystruct 4 cells allot
 3081: mystruct .s field1 .s drop
 3082: @end example
 3083: 
 3084: If you want to do something with the word without performing the code
 3085: after the @code{does>}, you can access the body of a @code{create}d word
 3086: with @code{>body ( xt -- addr )}:
 3087: 
 3088: @example
 3089: : value ( n "name" -- )
 3090:   create ,
 3091: does> ( -- n1 )
 3092:   @@ ;
 3093: : to ( n "name" -- )
 3094:   ' >body ! ;
 3095: 
 3096: 5 value foo
 3097: foo .
 3098: 7 to foo
 3099: foo .
 3100: @end example
 3101: 
 3102: @assignment
 3103: Define @code{defer ( "name" -- )}, which creates a word that stores an
 3104: XT (at the start the XT of @code{abort}), and upon execution
 3105: @code{execute}s the XT.  Define @code{is ( xt "name" -- )} that stores
 3106: @code{xt} into @code{name}, a word defined with @code{defer}.  Indirect
 3107: recursion is one application of @code{defer}.
 3108: @endassignment
 3109: 
 3110: Reference: @ref{User-defined Defining Words}.
 3111: 
 3112: 
 3113: @node Arrays and Records Tutorial, POSTPONE Tutorial, Defining Words Tutorial, Tutorial
 3114: @section Arrays and Records
 3115: @cindex arrays tutorial
 3116: @cindex records tutorial
 3117: @cindex structs tutorial
 3118: 
 3119: Forth has no standard words for defining data structures such as arrays
 3120: and records (structs in C terminology), but you can build them yourself
 3121: based on address arithmetic.  You can also define words for defining
 3122: arrays and records (@pxref{Defining Words Tutorial,, Defining Words}).
 3123: 
 3124: One of the first projects a Forth newcomer sets out upon when learning
 3125: about defining words is an array defining word (possibly for
 3126: n-dimensional arrays).  Go ahead and do it, I did it, too; you will
 3127: learn something from it.  However, don't be disappointed when you later
 3128: learn that you have little use for these words (inappropriate use would
 3129: be even worse).  I have not yet found a set of useful array words yet;
 3130: the needs are just too diverse, and named, global arrays (the result of
 3131: naive use of defining words) are often not flexible enough (e.g.,
 3132: consider how to pass them as parameters).  Another such project is a set
 3133: of words to help dealing with strings.
 3134: 
 3135: On the other hand, there is a useful set of record words, and it has
 3136: been defined in @file{compat/struct.fs}; these words are predefined in
 3137: Gforth.  They are explained in depth elsewhere in this manual (see
 3138: @pxref{Structures}).  The @code{simple-field} example above is
 3139: simplified variant of fields in this package.
 3140: 
 3141: 
 3142: @node POSTPONE Tutorial, Literal Tutorial, Arrays and Records Tutorial, Tutorial
 3143: @section @code{POSTPONE}
 3144: @cindex postpone tutorial
 3145: 
 3146: You can compile the compilation semantics (instead of compiling the
 3147: interpretation semantics) of a word with @code{POSTPONE}:
 3148: 
 3149: @example
 3150: : MY-+ ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
 3151:  POSTPONE + ; immediate
 3152: : foo ( n1 n2 -- n )
 3153:  MY-+ ;
 3154: 1 2 foo .
 3155: see foo
 3156: @end example
 3157: 
 3158: During the definition of @code{foo} the text interpreter performs the
 3159: compilation semantics of @code{MY-+}, which performs the compilation
 3160: semantics of @code{+}, i.e., it compiles @code{+} into @code{foo}.
 3161: 
 3162: This example also displays separate stack comments for the compilation
 3163: semantics and for the stack effect of the compiled code.  For words with
 3164: default compilation semantics these stack effects are usually not
 3165: displayed; the stack effect of the compilation semantics is always
 3166: @code{( -- )} for these words, the stack effect for the compiled code is
 3167: the stack effect of the interpretation semantics.
 3168: 
 3169: Note that the state of the interpreter does not come into play when
 3170: performing the compilation semantics in this way.  You can also perform
 3171: it interpretively, e.g.:
 3172: 
 3173: @example
 3174: : foo2 ( n1 n2 -- n )
 3175:  [ MY-+ ] ;
 3176: 1 2 foo .
 3177: see foo
 3178: @end example
 3179: 
 3180: However, there are some broken Forth systems where this does not always
 3181: work, and therefore this practice was been declared non-standard in
 3182: 1999.
 3183: @c !! repair.fs
 3184: 
 3185: Here is another example for using @code{POSTPONE}:
 3186: 
 3187: @example
 3188: : MY-- ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
 3189:  POSTPONE negate POSTPONE + ; immediate compile-only
 3190: : bar ( n1 n2 -- n )
 3191:   MY-- ;
 3192: 2 1 bar .
 3193: see bar
 3194: @end example
 3195: 
 3196: You can define @code{ENDIF} in this way:
 3197: 
 3198: @example
 3199: : ENDIF ( Compilation: orig -- )
 3200:   POSTPONE then ; immediate
 3201: @end example
 3202: 
 3203: @assignment
 3204: Write @code{MY-2DUP} that has compilation semantics equivalent to
 3205: @code{2dup}, but compiles @code{over over}.
 3206: @endassignment
 3207: 
 3208: @c !! @xref{Macros} for reference
 3209: 
 3210: 
 3211: @node Literal Tutorial, Advanced macros Tutorial, POSTPONE Tutorial, Tutorial
 3212: @section @code{Literal}
 3213: @cindex literal tutorial
 3214: 
 3215: You cannot @code{POSTPONE} numbers:
 3216: 
 3217: @example
 3218: : [FOO] POSTPONE 500 ; immediate
 3219: @end example
 3220: 
 3221: Instead, you can use @code{LITERAL (compilation: n --; run-time: -- n )}:
 3222: 
 3223: @example
 3224: : [FOO] ( compilation: --; run-time: -- n )
 3225:   500 POSTPONE literal ; immediate
 3226: 
 3227: : flip [FOO] ;
 3228: flip .
 3229: see flip
 3230: @end example
 3231: 
 3232: @code{LITERAL} consumes a number at compile-time (when it's compilation
 3233: semantics are executed) and pushes it at run-time (when the code it
 3234: compiled is executed).  A frequent use of @code{LITERAL} is to compile a
 3235: number computed at compile time into the current word:
 3236: 
 3237: @example
 3238: : bar ( -- n )
 3239:   [ 2 2 + ] literal ;
 3240: see bar
 3241: @end example
 3242: 
 3243: @assignment
 3244: Write @code{]L} which allows writing the example above as @code{: bar (
 3245: -- n ) [ 2 2 + ]L ;}
 3246: @endassignment
 3247: 
 3248: @c !! @xref{Macros} for reference
 3249: 
 3250: 
 3251: @node Advanced macros Tutorial, Compilation Tokens Tutorial, Literal Tutorial, Tutorial
 3252: @section Advanced macros
 3253: @cindex macros, advanced tutorial
 3254: @cindex run-time code generation, tutorial
 3255: 
 3256: Reconsider @code{map-array} from @ref{Execution Tokens Tutorial,,
 3257: Execution Tokens}.  It frequently performs @code{execute}, a relatively
 3258: expensive operation in some Forth implementations.  You can use
 3259: @code{compile,} and @code{POSTPONE} to eliminate these @code{execute}s
 3260: and produce a word that contains the word to be performed directly:
 3261: 
 3262: @c use ]] ... [[
 3263: @example
 3264: : compile-map-array ( compilation: xt -- ; run-time: ... addr u -- ... )
 3265: \ at run-time, execute xt ( ... x -- ... ) for each element of the
 3266: \ array beginning at addr and containing u elements
 3267:   @{ xt @}
 3268:   POSTPONE cells POSTPONE over POSTPONE + POSTPONE swap POSTPONE ?do
 3269:     POSTPONE i POSTPONE @@ xt compile,
 3270:   1 cells POSTPONE literal POSTPONE +loop ;
 3271: 
 3272: : sum-array ( addr u -- n )
 3273:  0 rot rot [ ' + compile-map-array ] ;
 3274: see sum-array
 3275: a 5 sum-array .
 3276: @end example
 3277: 
 3278: You can use the full power of Forth for generating the code; here's an
 3279: example where the code is generated in a loop:
 3280: 
 3281: @example
 3282: : compile-vmul-step ( compilation: n --; run-time: n1 addr1 -- n2 addr2 )
 3283: \ n2=n1+(addr1)*n, addr2=addr1+cell
 3284:   POSTPONE tuck POSTPONE @@
 3285:   POSTPONE literal POSTPONE * POSTPONE +
 3286:   POSTPONE swap POSTPONE cell+ ;
 3287: 
 3288: : compile-vmul ( compilation: addr1 u -- ; run-time: addr2 -- n )
 3289: \ n=v1*v2 (inner product), where the v_i are represented as addr_i u
 3290:   0 postpone literal postpone swap
 3291:   [ ' compile-vmul-step compile-map-array ]
 3292:   postpone drop ;
 3293: see compile-vmul
 3294: 
 3295: : a-vmul ( addr -- n )
 3296: \ n=a*v, where v is a vector that's as long as a and starts at addr
 3297:  [ a 5 compile-vmul ] ;
 3298: see a-vmul
 3299: a a-vmul .
 3300: @end example
 3301: 
 3302: This example uses @code{compile-map-array} to show off, but you could
 3303: also use @code{map-array} instead (try it now!).
 3304: 
 3305: You can use this technique for efficient multiplication of large
 3306: matrices.  In matrix multiplication, you multiply every line of one
 3307: matrix with every column of the other matrix.  You can generate the code
 3308: for one line once, and use it for every column.  The only downside of
 3309: this technique is that it is cumbersome to recover the memory consumed
 3310: by the generated code when you are done (and in more complicated cases
 3311: it is not possible portably).
 3312: 
 3313: @c !! @xref{Macros} for reference
 3314: 
 3315: 
 3316: @node Compilation Tokens Tutorial, Wordlists and Search Order Tutorial, Advanced macros Tutorial, Tutorial
 3317: @section Compilation Tokens
 3318: @cindex compilation tokens, tutorial
 3319: @cindex CT, tutorial
 3320: 
 3321: This section is Gforth-specific.  You can skip it.
 3322: 
 3323: @code{' word compile,} compiles the interpretation semantics.  For words
 3324: with default compilation semantics this is the same as performing the
 3325: compilation semantics.  To represent the compilation semantics of other
 3326: words (e.g., words like @code{if} that have no interpretation
 3327: semantics), Gforth has the concept of a compilation token (CT,
 3328: consisting of two cells), and words @code{comp'} and @code{[comp']}.
 3329: You can perform the compilation semantics represented by a CT with
 3330: @code{execute}:
 3331: 
 3332: @example
 3333: : foo2 ( n1 n2 -- n )
 3334:    [ comp' + execute ] ;
 3335: see foo
 3336: @end example
 3337: 
 3338: You can compile the compilation semantics represented by a CT with
 3339: @code{postpone,}:
 3340: 
 3341: @example
 3342: : foo3 ( -- )
 3343:   [ comp' + postpone, ] ;
 3344: see foo3
 3345: @end example
 3346: 
 3347: @code{[ comp' word postpone, ]} is equivalent to @code{POSTPONE word}.
 3348: @code{comp'} is particularly useful for words that have no
 3349: interpretation semantics:
 3350: 
 3351: @example
 3352: ' if
 3353: comp' if .s 2drop
 3354: @end example
 3355: 
 3356: Reference: @ref{Tokens for Words}.
 3357: 
 3358: 
 3359: @node Wordlists and Search Order Tutorial,  , Compilation Tokens Tutorial, Tutorial
 3360: @section Wordlists and Search Order
 3361: @cindex wordlists tutorial
 3362: @cindex search order, tutorial
 3363: 
 3364: The dictionary is not just a memory area that allows you to allocate
 3365: memory with @code{allot}, it also contains the Forth words, arranged in
 3366: several wordlists.  When searching for a word in a wordlist,
 3367: conceptually you start searching at the youngest and proceed towards
 3368: older words (in reality most systems nowadays use hash-tables); i.e., if
 3369: you define a word with the same name as an older word, the new word
 3370: shadows the older word.
 3371: 
 3372: Which wordlists are searched in which order is determined by the search
 3373: order.  You can display the search order with @code{order}.  It displays
 3374: first the search order, starting with the wordlist searched first, then
 3375: it displays the wordlist that will contain newly defined words.
 3376: 
 3377: You can create a new, empty wordlist with @code{wordlist ( -- wid )}:
 3378: 
 3379: @example
 3380: wordlist constant mywords
 3381: @end example
 3382: 
 3383: @code{Set-current ( wid -- )} sets the wordlist that will contain newly
 3384: defined words (the @emph{current} wordlist):
 3385: 
 3386: @example
 3387: mywords set-current
 3388: order
 3389: @end example
 3390: 
 3391: Gforth does not display a name for the wordlist in @code{mywords}
 3392: because this wordlist was created anonymously with @code{wordlist}.
 3393: 
 3394: You can get the current wordlist with @code{get-current ( -- wid)}.  If
 3395: you want to put something into a specific wordlist without overall
 3396: effect on the current wordlist, this typically looks like this:
 3397: 
 3398: @example
 3399: get-current mywords set-current ( wid )
 3400: create someword
 3401: ( wid ) set-current
 3402: @end example
 3403: 
 3404: You can write the search order with @code{set-order ( wid1 .. widn n --
 3405: )} and read it with @code{get-order ( -- wid1 .. widn n )}.  The first
 3406: searched wordlist is topmost.
 3407: 
 3408: @example
 3409: get-order mywords swap 1+ set-order
 3410: order
 3411: @end example
 3412: 
 3413: Yes, the order of wordlists in the output of @code{order} is reversed
 3414: from stack comments and the output of @code{.s} and thus unintuitive.
 3415: 
 3416: @assignment
 3417: Define @code{>order ( wid -- )} with adds @code{wid} as first searched
 3418: wordlist to the search order.  Define @code{previous ( -- )}, which
 3419: removes the first searched wordlist from the search order.  Experiment
 3420: with boundary conditions (you will see some crashes or situations that
 3421: are hard or impossible to leave).
 3422: @endassignment
 3423: 
 3424: The search order is a powerful foundation for providing features similar
 3425: to Modula-2 modules and C++ namespaces.  However, trying to modularize
 3426: programs in this way has disadvantages for debugging and reuse/factoring
 3427: that overcome the advantages in my experience (I don't do huge projects,
 3428: though).  These disadvantages are not so clear in other
 3429: languages/programming environments, because these langauges are not so
 3430: strong in debugging and reuse.
 3431: 
 3432: @c !! example
 3433: 
 3434: Reference: @ref{Word Lists}.
 3435: 
 3436: @c ******************************************************************
 3437: @node Introduction, Words, Tutorial, Top
 3438: @comment node-name,     next,           previous, up
 3439: @chapter An Introduction to ANS Forth
 3440: @cindex Forth - an introduction
 3441: 
 3442: The primary purpose of this manual is to document Gforth. However, since
 3443: Forth is not a widely-known language and there is a lack of up-to-date
 3444: teaching material, it seems worthwhile to provide some introductory
 3445: material.  For other sources of Forth-related
 3446: information, see @ref{Forth-related information}.
 3447: 
 3448: The examples in this section should work on any ANS Forth; the
 3449: output shown was produced using Gforth. Each example attempts to
 3450: reproduce the exact output that Gforth produces. If you try out the
 3451: examples (and you should), what you should type is shown @kbd{like this}
 3452: and Gforth's response is shown @code{like this}. The single exception is
 3453: that, where the example shows @key{RET} it means that you should
 3454: press the ``carriage return'' key. Unfortunately, some output formats for
 3455: this manual cannot show the difference between @kbd{this} and
 3456: @code{this} which will make trying out the examples harder (but not
 3457: impossible).
 3458: 
 3459: Forth is an unusual language. It provides an interactive development
 3460: environment which includes both an interpreter and compiler. Forth
 3461: programming style encourages you to break a problem down into many
 3462: @cindex factoring
 3463: small fragments (@dfn{factoring}), and then to develop and test each
 3464: fragment interactively. Forth advocates assert that breaking the
 3465: edit-compile-test cycle used by conventional programming languages can
 3466: lead to great productivity improvements.
 3467: 
 3468: @menu
 3469: * Introducing the Text Interpreter::  
 3470: * Stacks and Postfix notation::  
 3471: * Your first definition::       
 3472: * How does that work?::         
 3473: * Forth is written in Forth::   
 3474: * Review - elements of a Forth system::  
 3475: * Where to go next::            
 3476: * Exercises::                   
 3477: @end menu
 3478: 
 3479: @comment ----------------------------------------------
 3480: @node Introducing the Text Interpreter, Stacks and Postfix notation, Introduction, Introduction
 3481: @section Introducing the Text Interpreter
 3482: @cindex text interpreter
 3483: @cindex outer interpreter
 3484: 
 3485: @c IMO this is too detailed and the pace is too slow for
 3486: @c an introduction.  If you know German, take a look at
 3487: @c http://www.complang.tuwien.ac.at/anton/lvas/skriptum-stack.html 
 3488: @c to see how I do it - anton 
 3489: 
 3490: @c nac-> Where I have accepted your comments 100% and modified the text
 3491: @c accordingly, I have deleted your comments. Elsewhere I have added a
 3492: @c response like this to attempt to rationalise what I have done. Of
 3493: @c course, this is a very clumsy mechanism for something that would be
 3494: @c done far more efficiently over a beer. Please delete any dialogue
 3495: @c you consider closed.
 3496: 
 3497: When you invoke the Forth image, you will see a startup banner printed
 3498: and nothing else (if you have Gforth installed on your system, try
 3499: invoking it now, by typing @kbd{gforth@key{RET}}). Forth is now running
 3500: its command line interpreter, which is called the @dfn{Text Interpreter}
 3501: (also known as the @dfn{Outer Interpreter}).  (You will learn a lot
 3502: about the text interpreter as you read through this chapter, for more
 3503: detail @pxref{The Text Interpreter}).
 3504: 
 3505: Although it's not obvious, Forth is actually waiting for your
 3506: input. Type a number and press the @key{RET} key:
 3507: 
 3508: @example
 3509: @kbd{45@key{RET}}  ok
 3510: @end example
 3511: 
 3512: Rather than give you a prompt to invite you to input something, the text
 3513: interpreter prints a status message @i{after} it has processed a line
 3514: of input. The status message in this case (``@code{ ok}'' followed by
 3515: carriage-return) indicates that the text interpreter was able to process
 3516: all of your input successfully. Now type something illegal:
 3517: 
 3518: @example
 3519: @kbd{qwer341@key{RET}}
 3520: :1: Undefined word
 3521: qwer341
 3522: ^^^^^^^
 3523: $400D2BA8 Bounce
 3524: $400DBDA8 no.extensions
 3525: @end example
 3526: 
 3527: The exact text, other than the ``Undefined word'' may differ slightly on
 3528: your system, but the effect is the same; when the text interpreter
 3529: detects an error, it discards any remaining text on a line, resets
 3530: certain internal state and prints an error message. For a detailed description of error messages see @ref{Error
 3531: messages}.
 3532: 
 3533: The text interpreter waits for you to press carriage-return, and then
 3534: processes your input line. Starting at the beginning of the line, it
 3535: breaks the line into groups of characters separated by spaces. For each
 3536: group of characters in turn, it makes two attempts to do something:
 3537: 
 3538: @itemize @bullet
 3539: @item
 3540: @cindex name dictionary
 3541: It tries to treat it as a command. It does this by searching a @dfn{name
 3542: dictionary}. If the group of characters matches an entry in the name
 3543: dictionary, the name dictionary provides the text interpreter with
 3544: information that allows the text interpreter perform some actions. In
 3545: Forth jargon, we say that the group
 3546: @cindex word
 3547: @cindex definition
 3548: @cindex execution token
 3549: @cindex xt
 3550: of characters names a @dfn{word}, that the dictionary search returns an
 3551: @dfn{execution token (xt)} corresponding to the @dfn{definition} of the
 3552: word, and that the text interpreter executes the xt. Often, the terms
 3553: @dfn{word} and @dfn{definition} are used interchangeably.
 3554: @item
 3555: If the text interpreter fails to find a match in the name dictionary, it
 3556: tries to treat the group of characters as a number in the current number
 3557: base (when you start up Forth, the current number base is base 10). If
 3558: the group of characters legitimately represents a number, the text
 3559: interpreter pushes the number onto a stack (we'll learn more about that
 3560: in the next section).
 3561: @end itemize
 3562: 
 3563: If the text interpreter is unable to do either of these things with any
 3564: group of characters, it discards the group of characters and the rest of
 3565: the line, then prints an error message. If the text interpreter reaches
 3566: the end of the line without error, it prints the status message ``@code{ ok}''
 3567: followed by carriage-return.
 3568: 
 3569: This is the simplest command we can give to the text interpreter:
 3570: 
 3571: @example
 3572: @key{RET}  ok
 3573: @end example
 3574: 
 3575: The text interpreter did everything we asked it to do (nothing) without
 3576: an error, so it said that everything is ``@code{ ok}''. Try a slightly longer
 3577: command:
 3578: 
 3579: @example
 3580: @kbd{12 dup fred dup@key{RET}}
 3581: :1: Undefined word
 3582: 12 dup fred dup
 3583:        ^^^^
 3584: $400D2BA8 Bounce
 3585: $400DBDA8 no.extensions
 3586: @end example
 3587: 
 3588: When you press the carriage-return key, the text interpreter starts to
 3589: work its way along the line:
 3590: 
 3591: @itemize @bullet
 3592: @item
 3593: When it gets to the space after the @code{2}, it takes the group of
 3594: characters @code{12} and looks them up in the name
 3595: dictionary@footnote{We can't tell if it found them or not, but assume
 3596: for now that it did not}. There is no match for this group of characters
 3597: in the name dictionary, so it tries to treat them as a number. It is
 3598: able to do this successfully, so it puts the number, 12, ``on the stack''
 3599: (whatever that means).
 3600: @item
 3601: The text interpreter resumes scanning the line and gets the next group
 3602: of characters, @code{dup}. It looks it up in the name dictionary and
 3603: (you'll have to take my word for this) finds it, and executes the word
 3604: @code{dup} (whatever that means).
 3605: @item
 3606: Once again, the text interpreter resumes scanning the line and gets the
 3607: group of characters @code{fred}. It looks them up in the name
 3608: dictionary, but can't find them. It tries to treat them as a number, but
 3609: they don't represent any legal number.
 3610: @end itemize
 3611: 
 3612: At this point, the text interpreter gives up and prints an error
 3613: message. The error message shows exactly how far the text interpreter
 3614: got in processing the line. In particular, it shows that the text
 3615: interpreter made no attempt to do anything with the final character
 3616: group, @code{dup}, even though we have good reason to believe that the
 3617: text interpreter would have no problem looking that word up and
 3618: executing it a second time.
 3619: 
 3620: 
 3621: @comment ----------------------------------------------
 3622: @node Stacks and Postfix notation, Your first definition, Introducing the Text Interpreter, Introduction
 3623: @section Stacks, postfix notation and parameter passing
 3624: @cindex text interpreter
 3625: @cindex outer interpreter
 3626: 
 3627: In procedural programming languages (like C and Pascal), the
 3628: building-block of programs is the @dfn{function} or @dfn{procedure}. These
 3629: functions or procedures are called with @dfn{explicit parameters}. For
 3630: example, in C we might write:
 3631: 
 3632: @example
 3633: total = total + new_volume(length,height,depth);
 3634: @end example
 3635: 
 3636: @noindent
 3637: where new_volume is a function-call to another piece of code, and total,
 3638: length, height and depth are all variables. length, height and depth are
 3639: parameters to the function-call.
 3640: 
 3641: In Forth, the equivalent of the function or procedure is the
 3642: @dfn{definition} and parameters are implicitly passed between
 3643: definitions using a shared stack that is visible to the
 3644: programmer. Although Forth does support variables, the existence of the
 3645: stack means that they are used far less often than in most other
 3646: programming languages. When the text interpreter encounters a number, it
 3647: will place (@dfn{push}) it on the stack. There are several stacks (the
 3648: actual number is implementation-dependent ...) and the particular stack
 3649: used for any operation is implied unambiguously by the operation being
 3650: performed. The stack used for all integer operations is called the @dfn{data
 3651: stack} and, since this is the stack used most commonly, references to
 3652: ``the data stack'' are often abbreviated to ``the stack''.
 3653: 
 3654: The stacks have a last-in, first-out (LIFO) organisation. If you type:
 3655: 
 3656: @example
 3657: @kbd{1 2 3@key{RET}}  ok
 3658: @end example
 3659: 
 3660: Then this instructs the text interpreter to placed three numbers on the
 3661: (data) stack. An analogy for the behaviour of the stack is to take a
 3662: pack of playing cards and deal out the ace (1), 2 and 3 into a pile on
 3663: the table. The 3 was the last card onto the pile (``last-in'') and if
 3664: you take a card off the pile then, unless you're prepared to fiddle a
 3665: bit, the card that you take off will be the 3 (``first-out''). The
 3666: number that will be first-out of the stack is called the @dfn{top of
 3667: stack}, which
 3668: @cindex TOS definition
 3669: is often abbreviated to @dfn{TOS}.
 3670: 
 3671: To understand how parameters are passed in Forth, consider the
 3672: behaviour of the definition @code{+} (pronounced ``plus''). You will not
 3673: be surprised to learn that this definition performs addition. More
 3674: precisely, it adds two number together and produces a result. Where does
 3675: it get the two numbers from? It takes the top two numbers off the
 3676: stack. Where does it place the result? On the stack. You can act-out the
 3677: behaviour of @code{+} with your playing cards like this:
 3678: 
 3679: @itemize @bullet
 3680: @item
 3681: Pick up two cards from the stack on the table
 3682: @item
 3683: Stare at them intently and ask yourself ``what @i{is} the sum of these two
 3684: numbers''
 3685: @item
 3686: Decide that the answer is 5
 3687: @item
 3688: Shuffle the two cards back into the pack and find a 5
 3689: @item
 3690: Put a 5 on the remaining ace that's on the table.
 3691: @end itemize
 3692: 
 3693: If you don't have a pack of cards handy but you do have Forth running,
 3694: you can use the definition @code{.s} to show the current state of the stack,
 3695: without affecting the stack. Type:
 3696: 
 3697: @example
 3698: @kbd{clearstack 1 2 3@key{RET}} ok
 3699: @kbd{.s@key{RET}} <3> 1 2 3  ok
 3700: @end example
 3701: 
 3702: The text interpreter looks up the word @code{clearstack} and executes
 3703: it; it tidies up the stack and removes any entries that may have been
 3704: left on it by earlier examples. The text interpreter pushes each of the
 3705: three numbers in turn onto the stack. Finally, the text interpreter
 3706: looks up the word @code{.s} and executes it. The effect of executing
 3707: @code{.s} is to print the ``<3>'' (the total number of items on the stack)
 3708: followed by a list of all the items on the stack; the item on the far
 3709: right-hand side is the TOS.
 3710: 
 3711: You can now type:
 3712: 
 3713: @example
 3714: @kbd{+ .s@key{RET}} <2> 1 5  ok
 3715: @end example
 3716: 
 3717: @noindent
 3718: which is correct; there are now 2 items on the stack and the result of
 3719: the addition is 5.
 3720: 
 3721: If you're playing with cards, try doing a second addition: pick up the
 3722: two cards, work out that their sum is 6, shuffle them into the pack,
 3723: look for a 6 and place that on the table. You now have just one item on
 3724: the stack. What happens if you try to do a third addition? Pick up the
 3725: first card, pick up the second card -- ah! There is no second card. This
 3726: is called a @dfn{stack underflow} and consitutes an error. If you try to
 3727: do the same thing with Forth it will report an error (probably a Stack
 3728: Underflow or an Invalid Memory Address error).
 3729: 
 3730: The opposite situation to a stack underflow is a @dfn{stack overflow},
 3731: which simply accepts that there is a finite amount of storage space
 3732: reserved for the stack. To stretch the playing card analogy, if you had
 3733: enough packs of cards and you piled the cards up on the table, you would
 3734: eventually be unable to add another card; you'd hit the ceiling. Gforth
 3735: allows you to set the maximum size of the stacks. In general, the only
 3736: time that you will get a stack overflow is because a definition has a
 3737: bug in it and is generating data on the stack uncontrollably.
 3738: 
 3739: There's one final use for the playing card analogy. If you model your
 3740: stack using a pack of playing cards, the maximum number of items on
 3741: your stack will be 52 (I assume you didn't use the Joker). The maximum
 3742: @i{value} of any item on the stack is 13 (the King). In fact, the only
 3743: possible numbers are positive integer numbers 1 through 13; you can't
 3744: have (for example) 0 or 27 or 3.52 or -2. If you change the way you
 3745: think about some of the cards, you can accommodate different
 3746: numbers. For example, you could think of the Jack as representing 0,
 3747: the Queen as representing -1 and the King as representing -2. Your
 3748: @i{range} remains unchanged (you can still only represent a total of 13
 3749: numbers) but the numbers that you can represent are -2 through 10.
 3750: 
 3751: In that analogy, the limit was the amount of information that a single
 3752: stack entry could hold, and Forth has a similar limit. In Forth, the
 3753: size of a stack entry is called a @dfn{cell}. The actual size of a cell is
 3754: implementation dependent and affects the maximum value that a stack
 3755: entry can hold. A Standard Forth provides a cell size of at least
 3756: 16-bits, and most desktop systems use a cell size of 32-bits.
 3757: 
 3758: Forth does not do any type checking for you, so you are free to
 3759: manipulate and combine stack items in any way you wish. A convenient way
 3760: of treating stack items is as 2's complement signed integers, and that
 3761: is what Standard words like @code{+} do. Therefore you can type:
 3762: 
 3763: @example
 3764: @kbd{-5 12 + .s@key{RET}} <1> 7  ok
 3765: @end example
 3766: 
 3767: If you use numbers and definitions like @code{+} in order to turn Forth
 3768: into a great big pocket calculator, you will realise that it's rather
 3769: different from a normal calculator. Rather than typing 2 + 3 = you had
 3770: to type 2 3 + (ignore the fact that you had to use @code{.s} to see the
 3771: result). The terminology used to describe this difference is to say that
 3772: your calculator uses @dfn{Infix Notation} (parameters and operators are
 3773: mixed) whilst Forth uses @dfn{Postfix Notation} (parameters and
 3774: operators are separate), also called @dfn{Reverse Polish Notation}.
 3775: 
 3776: Whilst postfix notation might look confusing to begin with, it has
 3777: several important advantages:
 3778: 
 3779: @itemize @bullet
 3780: @item
 3781: it is unambiguous
 3782: @item
 3783: it is more concise
 3784: @item
 3785: it fits naturally with a stack-based system
 3786: @end itemize
 3787: 
 3788: To examine these claims in more detail, consider these sums:
 3789: 
 3790: @example
 3791: 6 + 5 * 4 =
 3792: 4 * 5 + 6 =
 3793: @end example
 3794: 
 3795: If you're just learning maths or your maths is very rusty, you will
 3796: probably come up with the answer 44 for the first and 26 for the
 3797: second. If you are a bit of a whizz at maths you will remember the
 3798: @i{convention} that multiplication takes precendence over addition, and
 3799: you'd come up with the answer 26 both times. To explain the answer 26
 3800: to someone who got the answer 44, you'd probably rewrite the first sum
 3801: like this:
 3802: 
 3803: @example
 3804: 6 + (5 * 4) =
 3805: @end example
 3806: 
 3807: If what you really wanted was to perform the addition before the
 3808: multiplication, you would have to use parentheses to force it.
 3809: 
 3810: If you did the first two sums on a pocket calculator you would probably
 3811: get the right answers, unless you were very cautious and entered them using
 3812: these keystroke sequences:
 3813: 
 3814: 6 + 5 = * 4 =
 3815: 4 * 5 = + 6 =
 3816: 
 3817: Postfix notation is unambiguous because the order that the operators
 3818: are applied is always explicit; that also means that parentheses are
 3819: never required. The operators are @i{active} (the act of quoting the
 3820: operator makes the operation occur) which removes the need for ``=''.
 3821: 
 3822: The sum 6 + 5 * 4 can be written (in postfix notation) in two
 3823: equivalent ways:
 3824: 
 3825: @example
 3826: 6 5 4 * +      or:
 3827: 5 4 * 6 +
 3828: @end example
 3829: 
 3830: An important thing that you should notice about this notation is that
 3831: the @i{order} of the numbers does not change; if you want to subtract
 3832: 2 from 10 you type @code{10 2 -}.
 3833: 
 3834: The reason that Forth uses postfix notation is very simple to explain: it
 3835: makes the implementation extremely simple, and it follows naturally from
 3836: using the stack as a mechanism for passing parameters. Another way of
 3837: thinking about this is to realise that all Forth definitions are
 3838: @i{active}; they execute as they are encountered by the text
 3839: interpreter. The result of this is that the syntax of Forth is trivially
 3840: simple.
 3841: 
 3842: 
 3843: 
 3844: @comment ----------------------------------------------
 3845: @node Your first definition, How does that work?, Stacks and Postfix notation, Introduction
 3846: @section Your first Forth definition
 3847: @cindex first definition
 3848: 
 3849: Until now, the examples we've seen have been trivial; we've just been
 3850: using Forth as a bigger-than-pocket calculator. Also, each calculation
 3851: we've shown has been a ``one-off'' -- to repeat it we'd need to type it in
 3852: again@footnote{That's not quite true. If you press the up-arrow key on
 3853: your keyboard you should be able to scroll back to any earlier command,
 3854: edit it and re-enter it.} In this section we'll see how to add new
 3855: words to Forth's vocabulary.
 3856: 
 3857: The easiest way to create a new word is to use a @dfn{colon
 3858: definition}. We'll define a few and try them out before worrying too
 3859: much about how they work. Try typing in these examples; be careful to
 3860: copy the spaces accurately:
 3861: 
 3862: @example
 3863: : add-two 2 + . ;
 3864: : greet ." Hello and welcome" ;
 3865: : demo 5 add-two ;
 3866: @end example
 3867: 
 3868: @noindent
 3869: Now try them out:
 3870: 
 3871: @example
 3872: @kbd{greet@key{RET}} Hello and welcome  ok
 3873: @kbd{greet greet@key{RET}} Hello and welcomeHello and welcome  ok
 3874: @kbd{4 add-two@key{RET}} 6  ok
 3875: @kbd{demo@key{RET}} 7  ok
 3876: @kbd{9 greet demo add-two@key{RET}} Hello and welcome7 11  ok
 3877: @end example
 3878: 
 3879: The first new thing that we've introduced here is the pair of words
 3880: @code{:} and @code{;}. These are used to start and terminate a new
 3881: definition, respectively. The first word after the @code{:} is the name
 3882: for the new definition.
 3883: 
 3884: As you can see from the examples, a definition is built up of words that
 3885: have already been defined; Forth makes no distinction between
 3886: definitions that existed when you started the system up, and those that
 3887: you define yourself.
 3888: 
 3889: The examples also introduce the words @code{.} (dot), @code{."}
 3890: (dot-quote) and @code{dup} (dewp). Dot takes the value from the top of
 3891: the stack and displays it. It's like @code{.s} except that it only
 3892: displays the top item of the stack and it is destructive; after it has
 3893: executed, the number is no longer on the stack. There is always one
 3894: space printed after the number, and no spaces before it. Dot-quote
 3895: defines a string (a sequence of characters) that will be printed when
 3896: the word is executed. The string can contain any printable characters
 3897: except @code{"}. A @code{"} has a special function; it is not a Forth
 3898: word but it acts as a delimiter (the way that delimiters work is
 3899: described in the next section). Finally, @code{dup} duplicates the value
 3900: at the top of the stack. Try typing @code{5 dup .s} to see what it does.
 3901: 
 3902: We already know that the text interpreter searches through the
 3903: dictionary to locate names. If you've followed the examples earlier, you
 3904: will already have a definition called @code{add-two}. Lets try modifying
 3905: it by typing in a new definition:
 3906: 
 3907: @example
 3908: @kbd{: add-two dup . ." + 2 =" 2 + . ;@key{RET}} redefined add-two  ok
 3909: @end example
 3910: 
 3911: Forth recognised that we were defining a word that already exists, and
 3912: printed a message to warn us of that fact. Let's try out the new
 3913: definition:
 3914: 
 3915: @example
 3916: @kbd{9 add-two@key{RET}} 9 + 2 =11  ok
 3917: @end example
 3918: 
 3919: @noindent
 3920: All that we've actually done here, though, is to create a new
 3921: definition, with a particular name. The fact that there was already a
 3922: definition with the same name did not make any difference to the way
 3923: that the new definition was created (except that Forth printed a warning
 3924: message). The old definition of add-two still exists (try @code{demo}
 3925: again to see that this is true). Any new definition will use the new
 3926: definition of @code{add-two}, but old definitions continue to use the
 3927: version that already existed at the time that they were @code{compiled}.
 3928: 
 3929: Before you go on to the next section, try defining and redefining some
 3930: words of your own.
 3931: 
 3932: @comment ----------------------------------------------
 3933: @node How does that work?, Forth is written in Forth, Your first definition, Introduction
 3934: @section How does that work?
 3935: @cindex parsing words
 3936: 
 3937: @c That's pretty deep (IMO way too deep) for an introduction. - anton
 3938: 
 3939: @c Is it a good idea to talk about the interpretation semantics of a
 3940: @c number? We don't have an xt to go along with it. - anton
 3941: 
 3942: @c Now that I have eliminated execution semantics, I wonder if it would not
 3943: @c be better to keep them (or add run-time semantics), to make it easier to
 3944: @c explain what compilation semantics usually does. - anton
 3945: 
 3946: @c nac-> I removed the term ``default compilation sematics'' from the
 3947: @c introductory chapter. Removing ``execution semantics'' was making
 3948: @c everything simpler to explain, then I think the use of this term made
 3949: @c everything more complex again. I replaced it with ``default
 3950: @c semantics'' (which is used elsewhere in the manual) by which I mean
 3951: @c ``a definition that has neither the immediate nor the compile-only
 3952: @c flag set''. I reworded big chunks of the ``how does that work''
 3953: @c section (and, unusually for me, I think I even made it shorter!).  See
 3954: @c what you think -- I know I have not addressed your primary concern
 3955: @c that it is too heavy-going for an introduction. From what I understood
 3956: @c of your course notes it looks as though they might be a good framework. 
 3957: @c Things that I've tried to capture here are some things that came as a
 3958: @c great revelation here when I first understood them. Also, I like the
 3959: @c fact that a very simple code example shows up almost all of the issues
 3960: @c that you need to understand to see how Forth works. That's unique and
 3961: @c worthwhile to emphasise.
 3962: 
 3963: Now we're going to take another look at the definition of @code{add-two}
 3964: from the previous section. From our knowledge of the way that the text
 3965: interpreter works, we would have expected this result when we tried to
 3966: define @code{add-two}:
 3967: 
 3968: @example
 3969: @kbd{: add-two 2 + . ;@key{RET}}
 3970:   ^^^^^^^
 3971: Error: Undefined word
 3972: @end example
 3973: 
 3974: The reason that this didn't happen is bound up in the way that @code{:}
 3975: works. The word @code{:} does two special things. The first special
 3976: thing that it does prevents the text interpreter from ever seeing the
 3977: characters @code{add-two}. The text interpreter uses a variable called
 3978: @cindex modifying >IN
 3979: @code{>IN} (pronounced ``to-in'') to keep track of where it is in the
 3980: input line. When it encounters the word @code{:} it behaves in exactly
 3981: the same way as it does for any other word; it looks it up in the name
 3982: dictionary, finds its xt and executes it. When @code{:} executes, it
 3983: looks at the input buffer, finds the word @code{add-two} and advances the
 3984: value of @code{>IN} to point past it. It then does some other stuff
 3985: associated with creating the new definition (including creating an entry
 3986: for @code{add-two} in the name dictionary). When the execution of @code{:}
 3987: completes, control returns to the text interpreter, which is oblivious
 3988: to the fact that it has been tricked into ignoring part of the input
 3989: line.
 3990: 
 3991: @cindex parsing words
 3992: Words like @code{:} -- words that advance the value of @code{>IN} and so
 3993: prevent the text interpreter from acting on the whole of the input line
 3994: -- are called @dfn{parsing words}.
 3995: 
 3996: @cindex @code{state} - effect on the text interpreter
 3997: @cindex text interpreter - effect of state
 3998: The second special thing that @code{:} does is change the value of a
 3999: variable called @code{state}, which affects the way that the text
 4000: interpreter behaves. When Gforth starts up, @code{state} has the value
 4001: 0, and the text interpreter is said to be @dfn{interpreting}. During a
 4002: colon definition (started with @code{:}), @code{state} is set to -1 and
 4003: the text interpreter is said to be @dfn{compiling}.
 4004: 
 4005: In this example, the text interpreter is compiling when it processes the
 4006: string ``@code{2 + . ;}''. It still breaks the string down into
 4007: character sequences in the same way. However, instead of pushing the
 4008: number @code{2} onto the stack, it lays down (@dfn{compiles}) some magic
 4009: into the definition of @code{add-two} that will make the number @code{2} get
 4010: pushed onto the stack when @code{add-two} is @dfn{executed}. Similarly,
 4011: the behaviours of @code{+} and @code{.} are also compiled into the
 4012: definition.
 4013: 
 4014: One category of words don't get compiled. These so-called @dfn{immediate
 4015: words} get executed (performed @i{now}) regardless of whether the text
 4016: interpreter is interpreting or compiling. The word @code{;} is an
 4017: immediate word. Rather than being compiled into the definition, it
 4018: executes. Its effect is to terminate the current definition, which
 4019: includes changing the value of @code{state} back to 0.
 4020: 
 4021: When you execute @code{add-two}, it has a @dfn{run-time effect} that is
 4022: exactly the same as if you had typed @code{2 + . @key{RET}} outside of a
 4023: definition.
 4024: 
 4025: In Forth, every word or number can be described in terms of two
 4026: properties:
 4027: 
 4028: @itemize @bullet
 4029: @item
 4030: @cindex interpretation semantics
 4031: Its @dfn{interpretation semantics} describe how it will behave when the
 4032: text interpreter encounters it in @dfn{interpret} state. The
 4033: interpretation semantics of a word are represented by an @dfn{execution
 4034: token}.
 4035: @item
 4036: @cindex compilation semantics
 4037: Its @dfn{compilation semantics} describe how it will behave when the
 4038: text interpreter encounters it in @dfn{compile} state. The compilation
 4039: semantics of a word are represented in an implementation-dependent way;
 4040: Gforth uses a @dfn{compilation token}.
 4041: @end itemize
 4042: 
 4043: @noindent
 4044: Numbers are always treated in a fixed way:
 4045: 
 4046: @itemize @bullet
 4047: @item
 4048: When the number is @dfn{interpreted}, its behaviour is to push the
 4049: number onto the stack.
 4050: @item
 4051: When the number is @dfn{compiled}, a piece of code is appended to the
 4052: current definition that pushes the number when it runs. (In other words,
 4053: the compilation semantics of a number are to postpone its interpretation
 4054: semantics until the run-time of the definition that it is being compiled
 4055: into.)
 4056: @end itemize
 4057: 
 4058: Words don't behave in such a regular way, but most have @i{default
 4059: semantics} which means that they behave like this:
 4060: 
 4061: @itemize @bullet
 4062: @item
 4063: The @dfn{interpretation semantics} of the word are to do something useful.
 4064: @item
 4065: The @dfn{compilation semantics} of the word are to append its
 4066: @dfn{interpretation semantics} to the current definition (so that its
 4067: run-time behaviour is to do something useful).
 4068: @end itemize
 4069: 
 4070: @cindex immediate words
 4071: The actual behaviour of any particular word can be controlled by using
 4072: the words @code{immediate} and @code{compile-only} when the word is
 4073: defined. These words set flags in the name dictionary entry of the most
 4074: recently defined word, and these flags are retrieved by the text
 4075: interpreter when it finds the word in the name dictionary.
 4076: 
 4077: A word that is marked as @dfn{immediate} has compilation semantics that
 4078: are identical to its interpretation semantics. In other words, it
 4079: behaves like this:
 4080: 
 4081: @itemize @bullet
 4082: @item
 4083: The @dfn{interpretation semantics} of the word are to do something useful.
 4084: @item
 4085: The @dfn{compilation semantics} of the word are to do something useful
 4086: (and actually the same thing); i.e., it is executed during compilation.
 4087: @end itemize
 4088: 
 4089: Marking a word as @dfn{compile-only} prohibits the text interpreter from
 4090: performing the interpretation semantics of the word directly; an attempt
 4091: to do so will generate an error. It is never necessary to use
 4092: @code{compile-only} (and it is not even part of ANS Forth, though it is
 4093: provided by many implementations) but it is good etiquette to apply it
 4094: to a word that will not behave correctly (and might have unexpected
 4095: side-effects) in interpret state. For example, it is only legal to use
 4096: the conditional word @code{IF} within a definition. If you forget this
 4097: and try to use it elsewhere, the fact that (in Gforth) it is marked as
 4098: @code{compile-only} allows the text interpreter to generate a helpful
 4099: error message rather than subjecting you to the consequences of your
 4100: folly.
 4101: 
 4102: This example shows the difference between an immediate and a
 4103: non-immediate word:
 4104: 
 4105: @example
 4106: : show-state state @@ . ;
 4107: : show-state-now show-state ; immediate
 4108: : word1 show-state ;
 4109: : word2 show-state-now ;
 4110: @end example
 4111: 
 4112: The word @code{immediate} after the definition of @code{show-state-now}
 4113: makes that word an immediate word. These definitions introduce a new
 4114: word: @code{@@} (pronounced ``fetch''). This word fetches the value of a
 4115: variable, and leaves it on the stack. Therefore, the behaviour of
 4116: @code{show-state} is to print a number that represents the current value
 4117: of @code{state}.
 4118: 
 4119: When you execute @code{word1}, it prints the number 0, indicating that
 4120: the system is interpreting. When the text interpreter compiled the
 4121: definition of @code{word1}, it encountered @code{show-state} whose
 4122: compilation semantics are to append its interpretation semantics to the
 4123: current definition. When you execute @code{word1}, it performs the
 4124: interpretation semantics of @code{show-state}.  At the time that @code{word1}
 4125: (and therefore @code{show-state}) are executed, the system is
 4126: interpreting.
 4127: 
 4128: When you pressed @key{RET} after entering the definition of @code{word2},
 4129: you should have seen the number -1 printed, followed by ``@code{
 4130: ok}''. When the text interpreter compiled the definition of
 4131: @code{word2}, it encountered @code{show-state-now}, an immediate word,
 4132: whose compilation semantics are therefore to perform its interpretation
 4133: semantics. It is executed straight away (even before the text
 4134: interpreter has moved on to process another group of characters; the
 4135: @code{;} in this example). The effect of executing it are to display the
 4136: value of @code{state} @i{at the time that the definition of}
 4137: @code{word2} @i{is being defined}. Printing -1 demonstrates that the
 4138: system is compiling at this time. If you execute @code{word2} it does
 4139: nothing at all.
 4140: 
 4141: @cindex @code{."}, how it works
 4142: Before leaving the subject of immediate words, consider the behaviour of
 4143: @code{."} in the definition of @code{greet}, in the previous
 4144: section. This word is both a parsing word and an immediate word. Notice
 4145: that there is a space between @code{."} and the start of the text
 4146: @code{Hello and welcome}, but that there is no space between the last
 4147: letter of @code{welcome} and the @code{"} character. The reason for this
 4148: is that @code{."} is a Forth word; it must have a space after it so that
 4149: the text interpreter can identify it. The @code{"} is not a Forth word;
 4150: it is a @dfn{delimiter}. The examples earlier show that, when the string
 4151: is displayed, there is neither a space before the @code{H} nor after the
 4152: @code{e}. Since @code{."} is an immediate word, it executes at the time
 4153: that @code{greet} is defined. When it executes, its behaviour is to
 4154: search forward in the input line looking for the delimiter. When it
 4155: finds the delimiter, it updates @code{>IN} to point past the
 4156: delimiter. It also compiles some magic code into the definition of
 4157: @code{greet}; the xt of a run-time routine that prints a text string. It
 4158: compiles the string @code{Hello and welcome} into memory so that it is
 4159: available to be printed later. When the text interpreter gains control,
 4160: the next word it finds in the input stream is @code{;} and so it
 4161: terminates the definition of @code{greet}.
 4162: 
 4163: 
 4164: @comment ----------------------------------------------
 4165: @node Forth is written in Forth, Review - elements of a Forth system, How does that work?, Introduction
 4166: @section Forth is written in Forth
 4167: @cindex structure of Forth programs
 4168: 
 4169: When you start up a Forth compiler, a large number of definitions
 4170: already exist. In Forth, you develop a new application using bottom-up
 4171: programming techniques to create new definitions that are defined in
 4172: terms of existing definitions. As you create each definition you can
 4173: test and debug it interactively.
 4174: 
 4175: If you have tried out the examples in this section, you will probably
 4176: have typed them in by hand; when you leave Gforth, your definitions will
 4177: be lost. You can avoid this by using a text editor to enter Forth source
 4178: code into a file, and then loading code from the file using
 4179: @code{include} (@pxref{Forth source files}). A Forth source file is
 4180: processed by the text interpreter, just as though you had typed it in by
 4181: hand@footnote{Actually, there are some subtle differences -- see
 4182: @ref{The Text Interpreter}.}.
 4183: 
 4184: Gforth also supports the traditional Forth alternative to using text
 4185: files for program entry (@pxref{Blocks}).
 4186: 
 4187: In common with many, if not most, Forth compilers, most of Gforth is
 4188: actually written in Forth. All of the @file{.fs} files in the
 4189: installation directory@footnote{For example,
 4190: @file{/usr/local/share/gforth...}} are Forth source files, which you can
 4191: study to see examples of Forth programming.
 4192: 
 4193: Gforth maintains a history file that records every line that you type to
 4194: the text interpreter. This file is preserved between sessions, and is
 4195: used to provide a command-line recall facility. If you enter long
 4196: definitions by hand, you can use a text editor to paste them out of the
 4197: history file into a Forth source file for reuse at a later time
 4198: (for more information @pxref{Command-line editing}).
 4199: 
 4200: 
 4201: @comment ----------------------------------------------
 4202: @node Review - elements of a Forth system, Where to go next, Forth is written in Forth, Introduction
 4203: @section Review - elements of a Forth system
 4204: @cindex elements of a Forth system
 4205: 
 4206: To summarise this chapter:
 4207: 
 4208: @itemize @bullet
 4209: @item
 4210: Forth programs use @dfn{factoring} to break a problem down into small
 4211: fragments called @dfn{words} or @dfn{definitions}.
 4212: @item
 4213: Forth program development is an interactive process.
 4214: @item
 4215: The main command loop that accepts input, and controls both
 4216: interpretation and compilation, is called the @dfn{text interpreter}
 4217: (also known as the @dfn{outer interpreter}).
 4218: @item
 4219: Forth has a very simple syntax, consisting of words and numbers
 4220: separated by spaces or carriage-return characters. Any additional syntax
 4221: is imposed by @dfn{parsing words}.
 4222: @item
 4223: Forth uses a stack to pass parameters between words. As a result, it
 4224: uses postfix notation.
 4225: @item
 4226: To use a word that has previously been defined, the text interpreter
 4227: searches for the word in the @dfn{name dictionary}.
 4228: @item
 4229: Words have @dfn{interpretation semantics} and @dfn{compilation semantics}.
 4230: @item
 4231: The text interpreter uses the value of @code{state} to select between
 4232: the use of the @dfn{interpretation semantics} and the  @dfn{compilation
 4233: semantics} of a word that it encounters.
 4234: @item
 4235: The relationship between the @dfn{interpretation semantics} and
 4236: @dfn{compilation semantics} for a word
 4237: depend upon the way in which the word was defined (for example, whether
 4238: it is an @dfn{immediate} word).
 4239: @item
 4240: Forth definitions can be implemented in Forth (called @dfn{high-level
 4241: definitions}) or in some other way (usually a lower-level language and
 4242: as a result often called @dfn{low-level definitions}, @dfn{code
 4243: definitions} or @dfn{primitives}).
 4244: @item
 4245: Many Forth systems are implemented mainly in Forth.
 4246: @end itemize
 4247: 
 4248: 
 4249: @comment ----------------------------------------------
 4250: @node Where to go next, Exercises, Review - elements of a Forth system, Introduction
 4251: @section Where To Go Next
 4252: @cindex where to go next
 4253: 
 4254: Amazing as it may seem, if you have read (and understood) this far, you
 4255: know almost all the fundamentals about the inner workings of a Forth
 4256: system. You certainly know enough to be able to read and understand the
 4257: rest of this manual and the ANS Forth document, to learn more about the
 4258: facilities that Forth in general and Gforth in particular provide. Even
 4259: scarier, you know almost enough to implement your own Forth system.
 4260: However, that's not a good idea just yet... better to try writing some
 4261: programs in Gforth.
 4262: 
 4263: Forth has such a rich vocabulary that it can be hard to know where to
 4264: start in learning it. This section suggests a few sets of words that are
 4265: enough to write small but useful programs. Use the word index in this
 4266: document to learn more about each word, then try it out and try to write
 4267: small definitions using it. Start by experimenting with these words:
 4268: 
 4269: @itemize @bullet
 4270: @item
 4271: Arithmetic: @code{+ - * / /MOD */ ABS INVERT}
 4272: @item
 4273: Comparison: @code{MIN MAX =}
 4274: @item
 4275: Logic: @code{AND OR XOR NOT}
 4276: @item
 4277: Stack manipulation: @code{DUP DROP SWAP OVER}
 4278: @item
 4279: Loops and decisions: @code{IF ELSE ENDIF ?DO I LOOP}
 4280: @item
 4281: Input/Output: @code{. ." EMIT CR KEY}
 4282: @item
 4283: Defining words: @code{: ; CREATE}
 4284: @item
 4285: Memory allocation words: @code{ALLOT ,}
 4286: @item
 4287: Tools: @code{SEE WORDS .S MARKER}
 4288: @end itemize
 4289: 
 4290: When you have mastered those, go on to:
 4291: 
 4292: @itemize @bullet
 4293: @item
 4294: More defining words: @code{VARIABLE CONSTANT VALUE TO CREATE DOES>}
 4295: @item
 4296: Memory access: @code{@@ !}
 4297: @end itemize
 4298: 
 4299: When you have mastered these, there's nothing for it but to read through
 4300: the whole of this manual and find out what you've missed.
 4301: 
 4302: @comment ----------------------------------------------
 4303: @node Exercises,  , Where to go next, Introduction
 4304: @section Exercises
 4305: @cindex exercises
 4306: 
 4307: TODO: provide a set of programming excercises linked into the stuff done
 4308: already and into other sections of the manual. Provide solutions to all
 4309: the exercises in a .fs file in the distribution.
 4310: 
 4311: @c Get some inspiration from Starting Forth and Kelly&Spies.
 4312: 
 4313: @c excercises:
 4314: @c 1. take inches and convert to feet and inches.
 4315: @c 2. take temperature and convert from fahrenheight to celcius;
 4316: @c    may need to care about symmetric vs floored??
 4317: @c 3. take input line and do character substitution
 4318: @c    to encipher or decipher
 4319: @c 4. as above but work on a file for in and out
 4320: @c 5. take input line and convert to pig-latin 
 4321: @c
 4322: @c thing of sets of things to exercise then come up with
 4323: @c problems that need those things.
 4324: 
 4325: 
 4326: @c ******************************************************************
 4327: @node Words, Error messages, Introduction, Top
 4328: @chapter Forth Words
 4329: @cindex words
 4330: 
 4331: @menu
 4332: * Notation::                    
 4333: * Case insensitivity::          
 4334: * Comments::                    
 4335: * Boolean Flags::               
 4336: * Arithmetic::                  
 4337: * Stack Manipulation::          
 4338: * Memory::                      
 4339: * Control Structures::          
 4340: * Defining Words::              
 4341: * Interpretation and Compilation Semantics::  
 4342: * Tokens for Words::            
 4343: * The Text Interpreter::        
 4344: * Word Lists::                  
 4345: * Environmental Queries::       
 4346: * Files::                       
 4347: * Blocks::                      
 4348: * Other I/O::                   
 4349: * Programming Tools::           
 4350: * Assembler and Code Words::    
 4351: * Threading Words::             
 4352: * Locals::                      
 4353: * Structures::                  
 4354: * Object-oriented Forth::       
 4355: * Passing Commands to the OS::  
 4356: * Keeping track of Time::       
 4357: * Miscellaneous Words::         
 4358: @end menu
 4359: 
 4360: @node Notation, Case insensitivity, Words, Words
 4361: @section Notation
 4362: @cindex notation of glossary entries
 4363: @cindex format of glossary entries
 4364: @cindex glossary notation format
 4365: @cindex word glossary entry format
 4366: 
 4367: The Forth words are described in this section in the glossary notation
 4368: that has become a de-facto standard for Forth texts:
 4369: 
 4370: @format
 4371: @i{word}     @i{Stack effect}   @i{wordset}   @i{pronunciation}
 4372: @end format
 4373: @i{Description}
 4374: 
 4375: @table @var
 4376: @item word
 4377: The name of the word.
 4378: 
 4379: @item Stack effect
 4380: @cindex stack effect
 4381: The stack effect is written in the notation @code{@i{before} --
 4382: @i{after}}, where @i{before} and @i{after} describe the top of
 4383: stack entries before and after the execution of the word. The rest of
 4384: the stack is not touched by the word. The top of stack is rightmost,
 4385: i.e., a stack sequence is written as it is typed in. Note that Gforth
 4386: uses a separate floating point stack, but a unified stack
 4387: notation. Also, return stack effects are not shown in @i{stack
 4388: effect}, but in @i{Description}. The name of a stack item describes
 4389: the type and/or the function of the item. See below for a discussion of
 4390: the types.
 4391: 
 4392: All words have two stack effects: A compile-time stack effect and a
 4393: run-time stack effect. The compile-time stack-effect of most words is
 4394: @i{ -- }. If the compile-time stack-effect of a word deviates from
 4395: this standard behaviour, or the word does other unusual things at
 4396: compile time, both stack effects are shown; otherwise only the run-time
 4397: stack effect is shown.
 4398: 
 4399: @cindex pronounciation of words
 4400: @item pronunciation
 4401: How the word is pronounced.
 4402: 
 4403: @cindex wordset
 4404: @cindex environment wordset
 4405: @item wordset
 4406: The ANS Forth standard is divided into several word sets. A standard
 4407: system need not support all of them. Therefore, in theory, the fewer
 4408: word sets your program uses the more portable it will be. However, we
 4409: suspect that most ANS Forth systems on personal machines will feature
 4410: all word sets. Words that are not defined in ANS Forth have
 4411: @code{gforth} or @code{gforth-internal} as word set. @code{gforth}
 4412: describes words that will work in future releases of Gforth;
 4413: @code{gforth-internal} words are more volatile. Environmental query
 4414: strings are also displayed like words; you can recognize them by the
 4415: @code{environment} in the word set field.
 4416: 
 4417: @item Description
 4418: A description of the behaviour of the word.
 4419: @end table
 4420: 
 4421: @cindex types of stack items
 4422: @cindex stack item types
 4423: The type of a stack item is specified by the character(s) the name
 4424: starts with:
 4425: 
 4426: @table @code
 4427: @item f
 4428: @cindex @code{f}, stack item type
 4429: Boolean flags, i.e. @code{false} or @code{true}.
 4430: @item c
 4431: @cindex @code{c}, stack item type
 4432: Char
 4433: @item w
 4434: @cindex @code{w}, stack item type
 4435: Cell, can contain an integer or an address
 4436: @item n
 4437: @cindex @code{n}, stack item type
 4438: signed integer
 4439: @item u
 4440: @cindex @code{u}, stack item type
 4441: unsigned integer
 4442: @item d
 4443: @cindex @code{d}, stack item type
 4444: double sized signed integer
 4445: @item ud
 4446: @cindex @code{ud}, stack item type
 4447: double sized unsigned integer
 4448: @item r
 4449: @cindex @code{r}, stack item type
 4450: Float (on the FP stack)
 4451: @item a-
 4452: @cindex @code{a_}, stack item type
 4453: Cell-aligned address
 4454: @item c-
 4455: @cindex @code{c_}, stack item type
 4456: Char-aligned address (note that a Char may have two bytes in Windows NT)
 4457: @item f-
 4458: @cindex @code{f_}, stack item type
 4459: Float-aligned address
 4460: @item df-
 4461: @cindex @code{df_}, stack item type
 4462: Address aligned for IEEE double precision float
 4463: @item sf-
 4464: @cindex @code{sf_}, stack item type
 4465: Address aligned for IEEE single precision float
 4466: @item xt
 4467: @cindex @code{xt}, stack item type
 4468: Execution token, same size as Cell
 4469: @item wid
 4470: @cindex @code{wid}, stack item type
 4471: Word list ID, same size as Cell
 4472: @item ior, wior
 4473: @cindex ior type description
 4474: @cindex wior type description
 4475: I/O result code, cell-sized.  In Gforth, you can @code{throw} iors.
 4476: @item f83name
 4477: @cindex @code{f83name}, stack item type
 4478: Pointer to a name structure
 4479: @item "
 4480: @cindex @code{"}, stack item type
 4481: string in the input stream (not on the stack). The terminating character
 4482: is a blank by default. If it is not a blank, it is shown in @code{<>}
 4483: quotes.
 4484: @end table
 4485: 
 4486: @comment ----------------------------------------------
 4487: @node Case insensitivity, Comments, Notation, Words
 4488: @section Case insensitivity
 4489: @cindex case sensitivity
 4490: @cindex upper and lower case
 4491: 
 4492: Gforth is case-insensitive; you can enter definitions and invoke
 4493: Standard words using upper, lower or mixed case (however,
 4494: @pxref{core-idef, Implementation-defined options, Implementation-defined
 4495: options}).
 4496: 
 4497: ANS Forth only @i{requires} implementations to recognise Standard words
 4498: when they are typed entirely in upper case. Therefore, a Standard
 4499: program must use upper case for all Standard words. You can use whatever
 4500: case you like for words that you define, but in a Standard program you
 4501: have to use the words in the same case that you defined them.
 4502: 
 4503: Gforth supports case sensitivity through @code{table}s (case-sensitive
 4504: wordlists, @pxref{Word Lists}).
 4505: 
 4506: Two people have asked how to convert Gforth to be case-sensitive; while
 4507: we think this is a bad idea, you can change all wordlists into tables
 4508: like this:
 4509: 
 4510: @example
 4511: ' table-find forth-wordlist wordlist-map @ !
 4512: @end example
 4513: 
 4514: Note that you now have to type the predefined words in the same case
 4515: that we defined them, which are varying.  You may want to convert them
 4516: to your favourite case before doing this operation (I won't explain how,
 4517: because if you are even contemplating doing this, you'd better have
 4518: enough knowledge of Forth systems to know this already).
 4519: 
 4520: @node Comments, Boolean Flags, Case insensitivity, Words
 4521: @section Comments
 4522: @cindex comments
 4523: 
 4524: Forth supports two styles of comment; the traditional @i{in-line} comment,
 4525: @code{(} and its modern cousin, the @i{comment to end of line}; @code{\}.
 4526: 
 4527: 
 4528: doc-(
 4529: doc-\
 4530: doc-\G
 4531: 
 4532: 
 4533: @node Boolean Flags, Arithmetic, Comments, Words
 4534: @section Boolean Flags
 4535: @cindex Boolean flags
 4536: 
 4537: A Boolean flag is cell-sized. A cell with all bits clear represents the
 4538: flag @code{false} and a flag with all bits set represents the flag
 4539: @code{true}. Words that check a flag (for example, @code{IF}) will treat
 4540: a cell that has @i{any} bit set as @code{true}.
 4541: @c on and off to Memory? 
 4542: @c true and false to "Bitwise operations" or "Numeric comparison"?
 4543: 
 4544: doc-true
 4545: doc-false
 4546: doc-on
 4547: doc-off
 4548: 
 4549: 
 4550: @node Arithmetic, Stack Manipulation, Boolean Flags, Words
 4551: @section Arithmetic
 4552: @cindex arithmetic words
 4553: 
 4554: @cindex division with potentially negative operands
 4555: Forth arithmetic is not checked, i.e., you will not hear about integer
 4556: overflow on addition or multiplication, you may hear about division by
 4557: zero if you are lucky. The operator is written after the operands, but
 4558: the operands are still in the original order. I.e., the infix @code{2-1}
 4559: corresponds to @code{2 1 -}. Forth offers a variety of division
 4560: operators. If you perform division with potentially negative operands,
 4561: you do not want to use @code{/} or @code{/mod} with its undefined
 4562: behaviour, but rather @code{fm/mod} or @code{sm/mod} (probably the
 4563: former, @pxref{Mixed precision}).
 4564: @comment TODO discuss the different division forms and the std approach
 4565: 
 4566: @menu
 4567: * Single precision::            
 4568: * Double precision::            Double-cell integer arithmetic
 4569: * Bitwise operations::          
 4570: * Numeric comparison::          
 4571: * Mixed precision::             Operations with single and double-cell integers
 4572: * Floating Point::              
 4573: @end menu
 4574: 
 4575: @node Single precision, Double precision, Arithmetic, Arithmetic
 4576: @subsection Single precision
 4577: @cindex single precision arithmetic words
 4578: 
 4579: @c !! cell undefined
 4580: 
 4581: By default, numbers in Forth are single-precision integers that are one
 4582: cell in size. They can be signed or unsigned, depending upon how you
 4583: treat them. For the rules used by the text interpreter for recognising
 4584: single-precision integers see @ref{Number Conversion}.
 4585: 
 4586: These words are all defined for signed operands, but some of them also
 4587: work for unsigned numbers: @code{+}, @code{1+}, @code{-}, @code{1-},
 4588: @code{*}.
 4589: 
 4590: doc-+
 4591: doc-1+
 4592: doc--
 4593: doc-1-
 4594: doc-*
 4595: doc-/
 4596: doc-mod
 4597: doc-/mod
 4598: doc-negate
 4599: doc-abs
 4600: doc-min
 4601: doc-max
 4602: doc-floored
 4603: 
 4604: 
 4605: @node Double precision, Bitwise operations, Single precision, Arithmetic
 4606: @subsection Double precision
 4607: @cindex double precision arithmetic words
 4608: 
 4609: For the rules used by the text interpreter for
 4610: recognising double-precision integers, see @ref{Number Conversion}.
 4611: 
 4612: A double precision number is represented by a cell pair, with the most
 4613: significant cell at the TOS. It is trivial to convert an unsigned single
 4614: to a double: simply push a @code{0} onto the TOS. Since numbers are
 4615: represented by Gforth using 2's complement arithmetic, converting a
 4616: signed single to a (signed) double requires sign-extension across the
 4617: most significant cell. This can be achieved using @code{s>d}. The moral
 4618: of the story is that you cannot convert a number without knowing whether
 4619: it represents an unsigned or a signed number.
 4620: 
 4621: These words are all defined for signed operands, but some of them also
 4622: work for unsigned numbers: @code{d+}, @code{d-}.
 4623: 
 4624: doc-s>d
 4625: doc-d>s
 4626: doc-d+
 4627: doc-d-
 4628: doc-dnegate
 4629: doc-dabs
 4630: doc-dmin
 4631: doc-dmax
 4632: 
 4633: 
 4634: @node Bitwise operations, Numeric comparison, Double precision, Arithmetic
 4635: @subsection Bitwise operations
 4636: @cindex bitwise operation words
 4637: 
 4638: 
 4639: doc-and
 4640: doc-or
 4641: doc-xor
 4642: doc-invert
 4643: doc-lshift
 4644: doc-rshift
 4645: doc-2*
 4646: doc-d2*
 4647: doc-2/
 4648: doc-d2/
 4649: 
 4650: 
 4651: @node Numeric comparison, Mixed precision, Bitwise operations, Arithmetic
 4652: @subsection Numeric comparison
 4653: @cindex numeric comparison words
 4654: 
 4655: Note that the words that compare for equality (@code{= <> 0= 0<> d= d<>
 4656: d0= d0<>}) work for for both signed and unsigned numbers.
 4657: 
 4658: doc-<
 4659: doc-<=
 4660: doc-<>
 4661: doc-=
 4662: doc->
 4663: doc->=
 4664: 
 4665: doc-0<
 4666: doc-0<=
 4667: doc-0<>
 4668: doc-0=
 4669: doc-0>
 4670: doc-0>=
 4671: 
 4672: doc-u<
 4673: doc-u<=
 4674: @c u<> and u= exist but are the same as <> and =
 4675: @c doc-u<>
 4676: @c doc-u=
 4677: doc-u>
 4678: doc-u>=
 4679: 
 4680: doc-within
 4681: 
 4682: doc-d<
 4683: doc-d<=
 4684: doc-d<>
 4685: doc-d=
 4686: doc-d>
 4687: doc-d>=
 4688: 
 4689: doc-d0<
 4690: doc-d0<=
 4691: doc-d0<>
 4692: doc-d0=
 4693: doc-d0>
 4694: doc-d0>=
 4695: 
 4696: doc-du<
 4697: doc-du<=
 4698: @c du<> and du= exist but are the same as d<> and d=
 4699: @c doc-du<>
 4700: @c doc-du=
 4701: doc-du>
 4702: doc-du>=
 4703: 
 4704: 
 4705: @node Mixed precision, Floating Point, Numeric comparison, Arithmetic
 4706: @subsection Mixed precision
 4707: @cindex mixed precision arithmetic words
 4708: 
 4709: 
 4710: doc-m+
 4711: doc-*/
 4712: doc-*/mod
 4713: doc-m*
 4714: doc-um*
 4715: doc-m*/
 4716: doc-um/mod
 4717: doc-fm/mod
 4718: doc-sm/rem
 4719: 
 4720: 
 4721: @node Floating Point,  , Mixed precision, Arithmetic
 4722: @subsection Floating Point
 4723: @cindex floating point arithmetic words
 4724: 
 4725: For the rules used by the text interpreter for
 4726: recognising floating-point numbers see @ref{Number Conversion}.
 4727: 
 4728: Gforth has a separate floating point stack, but the documentation uses
 4729: the unified notation.@footnote{It's easy to generate the separate
 4730: notation from that by just separating the floating-point numbers out:
 4731: e.g. @code{( n r1 u r2 -- r3 )} becomes @code{( n u -- ) ( F: r1 r2 --
 4732: r3 )}.}
 4733: 
 4734: @cindex floating-point arithmetic, pitfalls
 4735: Floating point numbers have a number of unpleasant surprises for the
 4736: unwary (e.g., floating point addition is not associative) and even a few
 4737: for the wary. You should not use them unless you know what you are doing
 4738: or you don't care that the results you get are totally bogus. If you
 4739: want to learn about the problems of floating point numbers (and how to
 4740: avoid them), you might start with @cite{David Goldberg,
 4741: @uref{http://www.validgh.com/goldberg/paper.ps,What Every Computer
 4742: Scientist Should Know About Floating-Point Arithmetic}, ACM Computing
 4743: Surveys 23(1):5@minus{}48, March 1991}.
 4744: 
 4745: 
 4746: doc-d>f
 4747: doc-f>d
 4748: doc-f+
 4749: doc-f-
 4750: doc-f*
 4751: doc-f/
 4752: doc-fnegate
 4753: doc-fabs
 4754: doc-fmax
 4755: doc-fmin
 4756: doc-floor
 4757: doc-fround
 4758: doc-f**
 4759: doc-fsqrt
 4760: doc-fexp
 4761: doc-fexpm1
 4762: doc-fln
 4763: doc-flnp1
 4764: doc-flog
 4765: doc-falog
 4766: doc-f2*
 4767: doc-f2/
 4768: doc-1/f
 4769: doc-precision
 4770: doc-set-precision
 4771: 
 4772: @cindex angles in trigonometric operations
 4773: @cindex trigonometric operations
 4774: Angles in floating point operations are given in radians (a full circle
 4775: has 2 pi radians).
 4776: 
 4777: doc-fsin
 4778: doc-fcos
 4779: doc-fsincos
 4780: doc-ftan
 4781: doc-fasin
 4782: doc-facos
 4783: doc-fatan
 4784: doc-fatan2
 4785: doc-fsinh
 4786: doc-fcosh
 4787: doc-ftanh
 4788: doc-fasinh
 4789: doc-facosh
 4790: doc-fatanh
 4791: doc-pi
 4792: 
 4793: @cindex equality of floats
 4794: @cindex floating-point comparisons
 4795: One particular problem with floating-point arithmetic is that comparison
 4796: for equality often fails when you would expect it to succeed.  For this
 4797: reason approximate equality is often preferred (but you still have to
 4798: know what you are doing).  Also note that IEEE NaNs may compare
 4799: differently from what you might expect.  The comparison words are:
 4800: 
 4801: doc-f~rel
 4802: doc-f~abs
 4803: doc-f~
 4804: doc-f=
 4805: doc-f<>
 4806: 
 4807: doc-f<
 4808: doc-f<=
 4809: doc-f>
 4810: doc-f>=
 4811: 
 4812: doc-f0<
 4813: doc-f0<=
 4814: doc-f0<>
 4815: doc-f0=
 4816: doc-f0>
 4817: doc-f0>=
 4818: 
 4819: 
 4820: @node Stack Manipulation, Memory, Arithmetic, Words
 4821: @section Stack Manipulation
 4822: @cindex stack manipulation words
 4823: 
 4824: @cindex floating-point stack in the standard
 4825: Gforth maintains a number of separate stacks:
 4826: 
 4827: @cindex data stack
 4828: @cindex parameter stack
 4829: @itemize @bullet
 4830: @item
 4831: A data stack (also known as the @dfn{parameter stack}) -- for
 4832: characters, cells, addresses, and double cells.
 4833: 
 4834: @cindex floating-point stack
 4835: @item
 4836: A floating point stack -- for holding floating point (FP) numbers.
 4837: 
 4838: @cindex return stack
 4839: @item
 4840: A return stack -- for holding the return addresses of colon
 4841: definitions and other (non-FP) data.
 4842: 
 4843: @cindex locals stack
 4844: @item
 4845: A locals stack -- for holding local variables.
 4846: @end itemize
 4847: 
 4848: @menu
 4849: * Data stack::                  
 4850: * Floating point stack::        
 4851: * Return stack::                
 4852: * Locals stack::                
 4853: * Stack pointer manipulation::  
 4854: @end menu
 4855: 
 4856: @node Data stack, Floating point stack, Stack Manipulation, Stack Manipulation
 4857: @subsection Data stack
 4858: @cindex data stack manipulation words
 4859: @cindex stack manipulations words, data stack
 4860: 
 4861: 
 4862: doc-drop
 4863: doc-nip
 4864: doc-dup
 4865: doc-over
 4866: doc-tuck
 4867: doc-swap
 4868: doc-pick
 4869: doc-rot
 4870: doc--rot
 4871: doc-?dup
 4872: doc-roll
 4873: doc-2drop
 4874: doc-2nip
 4875: doc-2dup
 4876: doc-2over
 4877: doc-2tuck
 4878: doc-2swap
 4879: doc-2rot
 4880: 
 4881: 
 4882: @node Floating point stack, Return stack, Data stack, Stack Manipulation
 4883: @subsection Floating point stack
 4884: @cindex floating-point stack manipulation words
 4885: @cindex stack manipulation words, floating-point stack
 4886: 
 4887: Whilst every sane Forth has a separate floating-point stack, it is not
 4888: strictly required; an ANS Forth system could theoretically keep
 4889: floating-point numbers on the data stack. As an additional difficulty,
 4890: you don't know how many cells a floating-point number takes. It is
 4891: reportedly possible to write words in a way that they work also for a
 4892: unified stack model, but we do not recommend trying it. Instead, just
 4893: say that your program has an environmental dependency on a separate
 4894: floating-point stack.
 4895: 
 4896: doc-floating-stack
 4897: 
 4898: doc-fdrop
 4899: doc-fnip
 4900: doc-fdup
 4901: doc-fover
 4902: doc-ftuck
 4903: doc-fswap
 4904: doc-fpick
 4905: doc-frot
 4906: 
 4907: 
 4908: @node Return stack, Locals stack, Floating point stack, Stack Manipulation
 4909: @subsection Return stack
 4910: @cindex return stack manipulation words
 4911: @cindex stack manipulation words, return stack
 4912: 
 4913: @cindex return stack and locals
 4914: @cindex locals and return stack
 4915: A Forth system is allowed to keep local variables on the
 4916: return stack. This is reasonable, as local variables usually eliminate
 4917: the need to use the return stack explicitly. So, if you want to produce
 4918: a standard compliant program and you are using local variables in a
 4919: word, forget about return stack manipulations in that word (refer to the
 4920: standard document for the exact rules).
 4921: 
 4922: doc->r
 4923: doc-r>
 4924: doc-r@
 4925: doc-rdrop
 4926: doc-2>r
 4927: doc-2r>
 4928: doc-2r@
 4929: doc-2rdrop
 4930: 
 4931: 
 4932: @node Locals stack, Stack pointer manipulation, Return stack, Stack Manipulation
 4933: @subsection Locals stack
 4934: 
 4935: Gforth uses an extra locals stack. It is described, along with the
 4936: reasons for its existence, in @ref{Implementation,Implementation of locals}.
 4937: 
 4938: @node Stack pointer manipulation,  , Locals stack, Stack Manipulation
 4939: @subsection Stack pointer manipulation
 4940: @cindex stack pointer manipulation words
 4941: 
 4942: @c removed s0 r0 l0 -- they are obsolete aliases for sp0 rp0 lp0
 4943: doc-sp0
 4944: doc-sp@
 4945: doc-sp!
 4946: doc-fp0
 4947: doc-fp@
 4948: doc-fp!
 4949: doc-rp0
 4950: doc-rp@
 4951: doc-rp!
 4952: doc-lp0
 4953: doc-lp@
 4954: doc-lp!
 4955: 
 4956: 
 4957: @node Memory, Control Structures, Stack Manipulation, Words
 4958: @section Memory
 4959: @cindex memory words
 4960: 
 4961: @menu
 4962: * Memory model::                
 4963: * Dictionary allocation::       
 4964: * Heap Allocation::             
 4965: * Memory Access::               
 4966: * Address arithmetic::          
 4967: * Memory Blocks::               
 4968: @end menu
 4969: 
 4970: In addition to the standard Forth memory allocation words, there is also
 4971: a @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
 4972: garbage collector}.
 4973: 
 4974: @node Memory model, Dictionary allocation, Memory, Memory
 4975: @subsection ANS Forth and Gforth memory models
 4976: 
 4977: @c The ANS Forth description is a mess (e.g., is the heap part of
 4978: @c the dictionary?), so let's not stick to closely with it.
 4979: 
 4980: ANS Forth considers a Forth system as consisting of several address
 4981: spaces, of which only @dfn{data space} is managed and accessible with
 4982: the memory words.  Memory not necessarily in data space includes the
 4983: stacks, the code (called code space) and the headers (called name
 4984: space). In Gforth everything is in data space, but the code for the
 4985: primitives is usually read-only.
 4986: 
 4987: Data space is divided into a number of areas: The (data space portion of
 4988: the) dictionary@footnote{Sometimes, the term @dfn{dictionary} is used to
 4989: refer to the search data structure embodied in word lists and headers,
 4990: because it is used for looking up names, just as you would in a
 4991: conventional dictionary.}, the heap, and a number of system-allocated
 4992: buffers.
 4993: 
 4994: @cindex address arithmetic restrictions, ANS vs. Gforth
 4995: @cindex contiguous regions, ANS vs. Gforth
 4996: In ANS Forth data space is also divided into contiguous regions.  You
 4997: can only use address arithmetic within a contiguous region, not between
 4998: them.  Usually each allocation gives you one contiguous region, but the
 4999: dictionary allocation words have additional rules (@pxref{Dictionary
 5000: allocation}).
 5001: 
 5002: Gforth provides one big address space, and address arithmetic can be
 5003: performed between any addresses. However, in the dictionary headers or
 5004: code are interleaved with data, so almost the only contiguous data space
 5005: regions there are those described by ANS Forth as contiguous; but you
 5006: can be sure that the dictionary is allocated towards increasing
 5007: addresses even between contiguous regions.  The memory order of
 5008: allocations in the heap is platform-dependent (and possibly different
 5009: from one run to the next).
 5010: 
 5011: 
 5012: @node Dictionary allocation, Heap Allocation, Memory model, Memory
 5013: @subsection Dictionary allocation
 5014: @cindex reserving data space
 5015: @cindex data space - reserving some
 5016: 
 5017: Dictionary allocation is a stack-oriented allocation scheme, i.e., if
 5018: you want to deallocate X, you also deallocate everything
 5019: allocated after X.
 5020: 
 5021: @cindex contiguous regions in dictionary allocation
 5022: The allocations using the words below are contiguous and grow the region
 5023: towards increasing addresses.  Other words that allocate dictionary
 5024: memory of any kind (i.e., defining words including @code{:noname}) end
 5025: the contiguous region and start a new one.
 5026: 
 5027: In ANS Forth only @code{create}d words are guaranteed to produce an
 5028: address that is the start of the following contiguous region.  In
 5029: particular, the cell allocated by @code{variable} is not guaranteed to
 5030: be contiguous with following @code{allot}ed memory.
 5031: 
 5032: You can deallocate memory by using @code{allot} with a negative argument
 5033: (with some restrictions, see @code{allot}). For larger deallocations use
 5034: @code{marker}.
 5035: 
 5036: 
 5037: doc-here
 5038: doc-unused
 5039: doc-allot
 5040: doc-c,
 5041: doc-f,
 5042: doc-,
 5043: doc-2,
 5044: 
 5045: Memory accesses have to be aligned (@pxref{Address arithmetic}). So of
 5046: course you should allocate memory in an aligned way, too. I.e., before
 5047: allocating allocating a cell, @code{here} must be cell-aligned, etc.
 5048: The words below align @code{here} if it is not already.  Basically it is
 5049: only already aligned for a type, if the last allocation was a multiple
 5050: of the size of this type and if @code{here} was aligned for this type
 5051: before.
 5052: 
 5053: After freshly @code{create}ing a word, @code{here} is @code{align}ed in
 5054: ANS Forth (@code{maxalign}ed in Gforth).
 5055: 
 5056: doc-align
 5057: doc-falign
 5058: doc-sfalign
 5059: doc-dfalign
 5060: doc-maxalign
 5061: doc-cfalign
 5062: 
 5063: 
 5064: @node Heap Allocation, Memory Access, Dictionary allocation, Memory
 5065: @subsection Heap allocation
 5066: @cindex heap allocation
 5067: @cindex dynamic allocation of memory
 5068: @cindex memory-allocation word set
 5069: 
 5070: @cindex contiguous regions and heap allocation
 5071: Heap allocation supports deallocation of allocated memory in any
 5072: order. Dictionary allocation is not affected by it (i.e., it does not
 5073: end a contiguous region). In Gforth, these words are implemented using
 5074: the standard C library calls malloc(), free() and resize().
 5075: 
 5076: The memory region produced by one invocation of @code{allocate} or
 5077: @code{resize} is internally contiguous.  There is no contiguity between
 5078: such a region and any other region (including others allocated from the
 5079: heap).
 5080: 
 5081: doc-allocate
 5082: doc-free
 5083: doc-resize
 5084: 
 5085: 
 5086: @node Memory Access, Address arithmetic, Heap Allocation, Memory
 5087: @subsection Memory Access
 5088: @cindex memory access words
 5089: 
 5090: doc-@
 5091: doc-!
 5092: doc-+!
 5093: doc-c@
 5094: doc-c!
 5095: doc-2@
 5096: doc-2!
 5097: doc-f@
 5098: doc-f!
 5099: doc-sf@
 5100: doc-sf!
 5101: doc-df@
 5102: doc-df!
 5103: 
 5104: 
 5105: @node Address arithmetic, Memory Blocks, Memory Access, Memory
 5106: @subsection Address arithmetic
 5107: @cindex address arithmetic words
 5108: 
 5109: Address arithmetic is the foundation on which you can build data
 5110: structures like arrays, records (@pxref{Structures}) and objects
 5111: (@pxref{Object-oriented Forth}).
 5112: 
 5113: @cindex address unit
 5114: @cindex au (address unit)
 5115: ANS Forth does not specify the sizes of the data types. Instead, it
 5116: offers a number of words for computing sizes and doing address
 5117: arithmetic. Address arithmetic is performed in terms of address units
 5118: (aus); on most systems the address unit is one byte. Note that a
 5119: character may have more than one au, so @code{chars} is no noop (on
 5120: platforms where it is a noop, it compiles to nothing).
 5121: 
 5122: The basic address arithmetic words are @code{+} and @code{-}.  E.g., if
 5123: you have the address of a cell, perform @code{1 cells +}, and you will
 5124: have the address of the next cell.
 5125: 
 5126: @cindex contiguous regions and address arithmetic
 5127: In ANS Forth you can perform address arithmetic only within a contiguous
 5128: region, i.e., if you have an address into one region, you can only add
 5129: and subtract such that the result is still within the region; you can
 5130: only subtract or compare addresses from within the same contiguous
 5131: region.  Reasons: several contiguous regions can be arranged in memory
 5132: in any way; on segmented systems addresses may have unusual
 5133: representations, such that address arithmetic only works within a
 5134: region.  Gforth provides a few more guarantees (linear address space,
 5135: dictionary grows upwards), but in general I have found it easy to stay
 5136: within contiguous regions (exception: computing and comparing to the
 5137: address just beyond the end of an array).
 5138: 
 5139: @cindex alignment of addresses for types
 5140: ANS Forth also defines words for aligning addresses for specific
 5141: types. Many computers require that accesses to specific data types
 5142: must only occur at specific addresses; e.g., that cells may only be
 5143: accessed at addresses divisible by 4. Even if a machine allows unaligned
 5144: accesses, it can usually perform aligned accesses faster. 
 5145: 
 5146: For the performance-conscious: alignment operations are usually only
 5147: necessary during the definition of a data structure, not during the
 5148: (more frequent) accesses to it.
 5149: 
 5150: ANS Forth defines no words for character-aligning addresses. This is not
 5151: an oversight, but reflects the fact that addresses that are not
 5152: char-aligned have no use in the standard and therefore will not be
 5153: created.
 5154: 
 5155: @cindex @code{CREATE} and alignment
 5156: ANS Forth guarantees that addresses returned by @code{CREATE}d words
 5157: are cell-aligned; in addition, Gforth guarantees that these addresses
 5158: are aligned for all purposes.
 5159: 
 5160: Note that the ANS Forth word @code{char} has nothing to do with address
 5161: arithmetic.
 5162: 
 5163: 
 5164: doc-chars
 5165: doc-char+
 5166: doc-cells
 5167: doc-cell+
 5168: doc-cell
 5169: doc-aligned
 5170: doc-floats
 5171: doc-float+
 5172: doc-float
 5173: doc-faligned
 5174: doc-sfloats
 5175: doc-sfloat+
 5176: doc-sfaligned
 5177: doc-dfloats
 5178: doc-dfloat+
 5179: doc-dfaligned
 5180: doc-maxaligned
 5181: doc-cfaligned
 5182: doc-address-unit-bits
 5183: 
 5184: 
 5185: @node Memory Blocks,  , Address arithmetic, Memory
 5186: @subsection Memory Blocks
 5187: @cindex memory block words
 5188: @cindex character strings - moving and copying
 5189: 
 5190: Memory blocks often represent character strings; For ways of storing
 5191: character strings in memory see @ref{String Formats}.  For other
 5192: string-processing words see @ref{Displaying characters and strings}.
 5193: 
 5194: A few of these words work on address unit blocks.  In that case, you
 5195: usually have to insert @code{CHARS} before the word when working on
 5196: character strings.  Most words work on character blocks, and expect a
 5197: char-aligned address.
 5198: 
 5199: When copying characters between overlapping memory regions, use
 5200: @code{chars move} or choose carefully between @code{cmove} and
 5201: @code{cmove>}.
 5202: 
 5203: doc-move
 5204: doc-erase
 5205: doc-cmove
 5206: doc-cmove>
 5207: doc-fill
 5208: doc-blank
 5209: doc-compare
 5210: doc-search
 5211: doc--trailing
 5212: doc-/string
 5213: 
 5214: 
 5215: @comment TODO examples
 5216: 
 5217: 
 5218: @node Control Structures, Defining Words, Memory, Words
 5219: @section Control Structures
 5220: @cindex control structures
 5221: 
 5222: Control structures in Forth cannot be used interpretively, only in a
 5223: colon definition@footnote{To be precise, they have no interpretation
 5224: semantics (@pxref{Interpretation and Compilation Semantics}).}. We do
 5225: not like this limitation, but have not seen a satisfying way around it
 5226: yet, although many schemes have been proposed.
 5227: 
 5228: @menu
 5229: * Selection::                   IF ... ELSE ... ENDIF
 5230: * Simple Loops::                BEGIN ...
 5231: * Counted Loops::               DO
 5232: * Arbitrary control structures::  
 5233: * Calls and returns::           
 5234: * Exception Handling::          
 5235: @end menu
 5236: 
 5237: @node Selection, Simple Loops, Control Structures, Control Structures
 5238: @subsection Selection
 5239: @cindex selection control structures
 5240: @cindex control structures for selection
 5241: 
 5242: @cindex @code{IF} control structure
 5243: @example
 5244: @i{flag}
 5245: IF
 5246:   @i{code}
 5247: ENDIF
 5248: @end example
 5249: @noindent
 5250: 
 5251: If @i{flag} is non-zero (as far as @code{IF} etc. are concerned, a cell
 5252: with any bit set represents truth) @i{code} is executed.
 5253: 
 5254: @example
 5255: @i{flag}
 5256: IF
 5257:   @i{code1}
 5258: ELSE
 5259:   @i{code2}
 5260: ENDIF
 5261: @end example
 5262: 
 5263: If @var{flag} is true, @i{code1} is executed, otherwise @i{code2} is
 5264: executed.
 5265: 
 5266: You can use @code{THEN} instead of @code{ENDIF}. Indeed, @code{THEN} is
 5267: standard, and @code{ENDIF} is not, although it is quite popular. We
 5268: recommend using @code{ENDIF}, because it is less confusing for people
 5269: who also know other languages (and is not prone to reinforcing negative
 5270: prejudices against Forth in these people). Adding @code{ENDIF} to a
 5271: system that only supplies @code{THEN} is simple:
 5272: @example
 5273: : ENDIF   POSTPONE THEN ; immediate
 5274: @end example
 5275: 
 5276: [According to @cite{Webster's New Encyclopedic Dictionary}, @dfn{then
 5277: (adv.)}  has the following meanings:
 5278: @quotation
 5279: ... 2b: following next after in order ... 3d: as a necessary consequence
 5280: (if you were there, then you saw them).
 5281: @end quotation
 5282: Forth's @code{THEN} has the meaning 2b, whereas @code{THEN} in Pascal
 5283: and many other programming languages has the meaning 3d.]
 5284: 
 5285: Gforth also provides the words @code{?DUP-IF} and @code{?DUP-0=-IF}, so
 5286: you can avoid using @code{?dup}. Using these alternatives is also more
 5287: efficient than using @code{?dup}. Definitions in ANS Forth
 5288: for @code{ENDIF}, @code{?DUP-IF} and @code{?DUP-0=-IF} are provided in
 5289: @file{compat/control.fs}.
 5290: 
 5291: @cindex @code{CASE} control structure
 5292: @example
 5293: @i{n}
 5294: CASE
 5295:   @i{n1} OF @i{code1} ENDOF
 5296:   @i{n2} OF @i{code2} ENDOF
 5297:   @dots{}
 5298:   ( n ) @i{default-code} ( n )
 5299: ENDCASE
 5300: @end example
 5301: 
 5302: Executes the first @i{codei}, where the @i{ni} is equal to @i{n}.  If no
 5303: @i{ni} matches, the optional @i{default-code} is executed. The optional
 5304: default case can be added by simply writing the code after the last
 5305: @code{ENDOF}. It may use @i{n}, which is on top of the stack, but must
 5306: not consume it.
 5307: 
 5308: @progstyle
 5309: To keep the code understandable, you should ensure that on all paths
 5310: through a selection construct the stack is changed in the same way
 5311: (wrt. number and types of stack items consumed and pushed).
 5312: 
 5313: @node Simple Loops, Counted Loops, Selection, Control Structures
 5314: @subsection Simple Loops
 5315: @cindex simple loops
 5316: @cindex loops without count 
 5317: 
 5318: @cindex @code{WHILE} loop
 5319: @example
 5320: BEGIN
 5321:   @i{code1}
 5322:   @i{flag}
 5323: WHILE
 5324:   @i{code2}
 5325: REPEAT
 5326: @end example
 5327: 
 5328: @i{code1} is executed and @i{flag} is computed. If it is true,
 5329: @i{code2} is executed and the loop is restarted; If @i{flag} is
 5330: false, execution continues after the @code{REPEAT}.
 5331: 
 5332: @cindex @code{UNTIL} loop
 5333: @example
 5334: BEGIN
 5335:   @i{code}
 5336:   @i{flag}
 5337: UNTIL
 5338: @end example
 5339: 
 5340: @i{code} is executed. The loop is restarted if @code{flag} is false.
 5341: 
 5342: @progstyle
 5343: To keep the code understandable, a complete iteration of the loop should
 5344: not change the number and types of the items on the stacks.
 5345: 
 5346: @cindex endless loop
 5347: @cindex loops, endless
 5348: @example
 5349: BEGIN
 5350:   @i{code}
 5351: AGAIN
 5352: @end example
 5353: 
 5354: This is an endless loop.
 5355: 
 5356: @node Counted Loops, Arbitrary control structures, Simple Loops, Control Structures
 5357: @subsection Counted Loops
 5358: @cindex counted loops
 5359: @cindex loops, counted
 5360: @cindex @code{DO} loops
 5361: 
 5362: The basic counted loop is:
 5363: @example
 5364: @i{limit} @i{start}
 5365: ?DO
 5366:   @i{body}
 5367: LOOP
 5368: @end example
 5369: 
 5370: This performs one iteration for every integer, starting from @i{start}
 5371: and up to, but excluding @i{limit}. The counter, or @i{index}, can be
 5372: accessed with @code{i}. For example, the loop:
 5373: @example
 5374: 10 0 ?DO
 5375:   i .
 5376: LOOP
 5377: @end example
 5378: @noindent
 5379: prints @code{0 1 2 3 4 5 6 7 8 9}
 5380: 
 5381: The index of the innermost loop can be accessed with @code{i}, the index
 5382: of the next loop with @code{j}, and the index of the third loop with
 5383: @code{k}.
 5384: 
 5385: 
 5386: doc-i
 5387: doc-j
 5388: doc-k
 5389: 
 5390: 
 5391: The loop control data are kept on the return stack, so there are some
 5392: restrictions on mixing return stack accesses and counted loop words. In
 5393: particuler, if you put values on the return stack outside the loop, you
 5394: cannot read them inside the loop@footnote{well, not in a way that is
 5395: portable.}. If you put values on the return stack within a loop, you
 5396: have to remove them before the end of the loop and before accessing the
 5397: index of the loop.
 5398: 
 5399: There are several variations on the counted loop:
 5400: 
 5401: @itemize @bullet
 5402: @item
 5403: @code{LEAVE} leaves the innermost counted loop immediately; execution
 5404: continues after the associated @code{LOOP} or @code{NEXT}. For example:
 5405: 
 5406: @example
 5407: 10 0 ?DO  i DUP . 3 = IF LEAVE THEN LOOP
 5408: @end example
 5409: prints @code{0 1 2 3}
 5410: 
 5411: 
 5412: @item
 5413: @code{UNLOOP} prepares for an abnormal loop exit, e.g., via
 5414: @code{EXIT}. @code{UNLOOP} removes the loop control parameters from the
 5415: return stack so @code{EXIT} can get to its return address. For example:
 5416: 
 5417: @example
 5418: : demo 10 0 ?DO i DUP . 3 = IF UNLOOP EXIT THEN LOOP ." Done" ;
 5419: @end example
 5420: prints @code{0 1 2 3}
 5421: 
 5422: 
 5423: @item
 5424: If @i{start} is greater than @i{limit}, a @code{?DO} loop is entered
 5425: (and @code{LOOP} iterates until they become equal by wrap-around
 5426: arithmetic). This behaviour is usually not what you want. Therefore,
 5427: Gforth offers @code{+DO} and @code{U+DO} (as replacements for
 5428: @code{?DO}), which do not enter the loop if @i{start} is greater than
 5429: @i{limit}; @code{+DO} is for signed loop parameters, @code{U+DO} for
 5430: unsigned loop parameters.
 5431: 
 5432: @item
 5433: @code{?DO} can be replaced by @code{DO}. @code{DO} always enters
 5434: the loop, independent of the loop parameters. Do not use @code{DO}, even
 5435: if you know that the loop is entered in any case. Such knowledge tends
 5436: to become invalid during maintenance of a program, and then the
 5437: @code{DO} will make trouble.
 5438: 
 5439: @item
 5440: @code{LOOP} can be replaced with @code{@i{n} +LOOP}; this updates the
 5441: index by @i{n} instead of by 1. The loop is terminated when the border
 5442: between @i{limit-1} and @i{limit} is crossed. E.g.:
 5443: 
 5444: @example
 5445: 4 0 +DO  i .  2 +LOOP
 5446: @end example
 5447: @noindent
 5448: prints @code{0 2}
 5449: 
 5450: @example
 5451: 4 1 +DO  i .  2 +LOOP
 5452: @end example
 5453: @noindent
 5454: prints @code{1 3}
 5455: 
 5456: @item
 5457: @cindex negative increment for counted loops
 5458: @cindex counted loops with negative increment
 5459: The behaviour of @code{@i{n} +LOOP} is peculiar when @i{n} is negative:
 5460: 
 5461: @example
 5462: -1 0 ?DO  i .  -1 +LOOP
 5463: @end example
 5464: @noindent
 5465: prints @code{0 -1}
 5466: 
 5467: @example
 5468: 0 0 ?DO  i .  -1 +LOOP
 5469: @end example
 5470: prints nothing.
 5471: 
 5472: Therefore we recommend avoiding @code{@i{n} +LOOP} with negative
 5473: @i{n}. One alternative is @code{@i{u} -LOOP}, which reduces the
 5474: index by @i{u} each iteration. The loop is terminated when the border
 5475: between @i{limit+1} and @i{limit} is crossed. Gforth also provides
 5476: @code{-DO} and @code{U-DO} for down-counting loops. E.g.:
 5477: 
 5478: @example
 5479: -2 0 -DO  i .  1 -LOOP
 5480: @end example
 5481: @noindent
 5482: prints @code{0 -1}
 5483: 
 5484: @example
 5485: -1 0 -DO  i .  1 -LOOP
 5486: @end example
 5487: @noindent
 5488: prints @code{0}
 5489: 
 5490: @example
 5491: 0 0 -DO  i .  1 -LOOP
 5492: @end example
 5493: @noindent
 5494: prints nothing.
 5495: 
 5496: @end itemize
 5497: 
 5498: Unfortunately, @code{+DO}, @code{U+DO}, @code{-DO}, @code{U-DO} and
 5499: @code{-LOOP} are not defined in ANS Forth. However, an implementation
 5500: for these words that uses only standard words is provided in
 5501: @file{compat/loops.fs}.
 5502: 
 5503: 
 5504: @cindex @code{FOR} loops
 5505: Another counted loop is:
 5506: @example
 5507: @i{n}
 5508: FOR
 5509:   @i{body}
 5510: NEXT
 5511: @end example
 5512: This is the preferred loop of native code compiler writers who are too
 5513: lazy to optimize @code{?DO} loops properly. This loop structure is not
 5514: defined in ANS Forth. In Gforth, this loop iterates @i{n+1} times;
 5515: @code{i} produces values starting with @i{n} and ending with 0. Other
 5516: Forth systems may behave differently, even if they support @code{FOR}
 5517: loops. To avoid problems, don't use @code{FOR} loops.
 5518: 
 5519: @node Arbitrary control structures, Calls and returns, Counted Loops, Control Structures
 5520: @subsection Arbitrary control structures
 5521: @cindex control structures, user-defined
 5522: 
 5523: @cindex control-flow stack
 5524: ANS Forth permits and supports using control structures in a non-nested
 5525: way. Information about incomplete control structures is stored on the
 5526: control-flow stack. This stack may be implemented on the Forth data
 5527: stack, and this is what we have done in Gforth.
 5528: 
 5529: @cindex @code{orig}, control-flow stack item
 5530: @cindex @code{dest}, control-flow stack item
 5531: An @i{orig} entry represents an unresolved forward branch, a @i{dest}
 5532: entry represents a backward branch target. A few words are the basis for
 5533: building any control structure possible (except control structures that
 5534: need storage, like calls, coroutines, and backtracking).
 5535: 
 5536: 
 5537: doc-if
 5538: doc-ahead
 5539: doc-then
 5540: doc-begin
 5541: doc-until
 5542: doc-again
 5543: doc-cs-pick
 5544: doc-cs-roll
 5545: 
 5546: 
 5547: The Standard words @code{CS-PICK} and @code{CS-ROLL} allow you to
 5548: manipulate the control-flow stack in a portable way. Without them, you
 5549: would need to know how many stack items are occupied by a control-flow
 5550: entry (many systems use one cell. In Gforth they currently take three,
 5551: but this may change in the future).
 5552: 
 5553: Some standard control structure words are built from these words:
 5554: 
 5555: 
 5556: doc-else
 5557: doc-while
 5558: doc-repeat
 5559: 
 5560: 
 5561: @noindent
 5562: Gforth adds some more control-structure words:
 5563: 
 5564: 
 5565: doc-endif
 5566: doc-?dup-if
 5567: doc-?dup-0=-if
 5568: 
 5569: 
 5570: @noindent
 5571: Counted loop words constitute a separate group of words:
 5572: 
 5573: 
 5574: doc-?do
 5575: doc-+do
 5576: doc-u+do
 5577: doc--do
 5578: doc-u-do
 5579: doc-do
 5580: doc-for
 5581: doc-loop
 5582: doc-+loop
 5583: doc--loop
 5584: doc-next
 5585: doc-leave
 5586: doc-?leave
 5587: doc-unloop
 5588: doc-done
 5589: 
 5590: 
 5591: The standard does not allow using @code{CS-PICK} and @code{CS-ROLL} on
 5592: @i{do-sys}. Gforth allows it, but it's your job to ensure that for
 5593: every @code{?DO} etc. there is exactly one @code{UNLOOP} on any path
 5594: through the definition (@code{LOOP} etc. compile an @code{UNLOOP} on the
 5595: fall-through path). Also, you have to ensure that all @code{LEAVE}s are
 5596: resolved (by using one of the loop-ending words or @code{DONE}).
 5597: 
 5598: @noindent
 5599: Another group of control structure words are:
 5600: 
 5601: 
 5602: doc-case
 5603: doc-endcase
 5604: doc-of
 5605: doc-endof
 5606: 
 5607: 
 5608: @i{case-sys} and @i{of-sys} cannot be processed using @code{CS-PICK} and
 5609: @code{CS-ROLL}.
 5610: 
 5611: @subsubsection Programming Style
 5612: @cindex control structures programming style
 5613: @cindex programming style, arbitrary control structures
 5614: 
 5615: In order to ensure readability we recommend that you do not create
 5616: arbitrary control structures directly, but define new control structure
 5617: words for the control structure you want and use these words in your
 5618: program. For example, instead of writing:
 5619: 
 5620: @example
 5621: BEGIN
 5622:   ...
 5623: IF [ 1 CS-ROLL ]
 5624:   ...
 5625: AGAIN THEN
 5626: @end example
 5627: 
 5628: @noindent
 5629: we recommend defining control structure words, e.g.,
 5630: 
 5631: @example
 5632: : WHILE ( DEST -- ORIG DEST )
 5633:  POSTPONE IF
 5634:  1 CS-ROLL ; immediate
 5635: 
 5636: : REPEAT ( orig dest -- )
 5637:  POSTPONE AGAIN
 5638:  POSTPONE THEN ; immediate
 5639: @end example
 5640: 
 5641: @noindent
 5642: and then using these to create the control structure:
 5643: 
 5644: @example
 5645: BEGIN
 5646:   ...
 5647: WHILE
 5648:   ...
 5649: REPEAT
 5650: @end example
 5651: 
 5652: That's much easier to read, isn't it? Of course, @code{REPEAT} and
 5653: @code{WHILE} are predefined, so in this example it would not be
 5654: necessary to define them.
 5655: 
 5656: @node Calls and returns, Exception Handling, Arbitrary control structures, Control Structures
 5657: @subsection Calls and returns
 5658: @cindex calling a definition
 5659: @cindex returning from a definition
 5660: 
 5661: @cindex recursive definitions
 5662: A definition can be called simply be writing the name of the definition
 5663: to be called. Normally a definition is invisible during its own
 5664: definition. If you want to write a directly recursive definition, you
 5665: can use @code{recursive} to make the current definition visible, or
 5666: @code{recurse} to call the current definition directly.
 5667: 
 5668: 
 5669: doc-recursive
 5670: doc-recurse
 5671: 
 5672: 
 5673: @comment TODO add example of the two recursion methods
 5674: @quotation
 5675: @progstyle
 5676: I prefer using @code{recursive} to @code{recurse}, because calling the
 5677: definition by name is more descriptive (if the name is well-chosen) than
 5678: the somewhat cryptic @code{recurse}.  E.g., in a quicksort
 5679: implementation, it is much better to read (and think) ``now sort the
 5680: partitions'' than to read ``now do a recursive call''.
 5681: @end quotation
 5682: 
 5683: For mutual recursion, use @code{Defer}red words, like this:
 5684: 
 5685: @example
 5686: Defer foo
 5687: 
 5688: : bar ( ... -- ... )
 5689:  ... foo ... ;
 5690: 
 5691: :noname ( ... -- ... )
 5692:  ... bar ... ;
 5693: IS foo
 5694: @end example
 5695: 
 5696: Deferred words are discussed in more detail in @ref{Deferred words}.
 5697: 
 5698: The current definition returns control to the calling definition when
 5699: the end of the definition is reached or @code{EXIT} is encountered.
 5700: 
 5701: doc-exit
 5702: doc-;s
 5703: 
 5704: 
 5705: @node Exception Handling,  , Calls and returns, Control Structures
 5706: @subsection Exception Handling
 5707: @cindex exceptions
 5708: 
 5709: @c quit is a very bad idea for error handling, 
 5710: @c because it does not translate into a THROW
 5711: @c it also does not belong into this chapter
 5712: 
 5713: If a word detects an error condition that it cannot handle, it can
 5714: @code{throw} an exception.  In the simplest case, this will terminate
 5715: your program, and report an appropriate error.
 5716: 
 5717: doc-throw
 5718: 
 5719: @code{Throw} consumes a cell-sized error number on the stack. There are
 5720: some predefined error numbers in ANS Forth (see @file{errors.fs}).  In
 5721: Gforth (and most other systems) you can use the iors produced by various
 5722: words as error numbers (e.g., a typical use of @code{allocate} is
 5723: @code{allocate throw}).  Gforth also provides the word @code{exception}
 5724: to define your own error numbers (with decent error reporting); an ANS
 5725: Forth version of this word (but without the error messages) is available
 5726: in @code{compat/except.fs}.  And finally, you can use your own error
 5727: numbers (anything outside the range -4095..0), but won't get nice error
 5728: messages, only numbers.  For example, try:
 5729: 
 5730: @example
 5731: -10 throw                    \ ANS defined
 5732: -267 throw                   \ system defined
 5733: s" my error" exception throw \ user defined
 5734: 7 throw                      \ arbitrary number
 5735: @end example
 5736: 
 5737: doc---exception-exception
 5738: 
 5739: A common idiom to @code{THROW} a specific error if a flag is true is
 5740: this:
 5741: 
 5742: @example
 5743: @code{( flag ) 0<> @i{errno} and throw}
 5744: @end example
 5745: 
 5746: Your program can provide exception handlers to catch exceptions.  An
 5747: exception handler can be used to correct the problem, or to clean up
 5748: some data structures and just throw the exception to the next exception
 5749: handler.  Note that @code{throw} jumps to the dynamically innermost
 5750: exception handler.  The system's exception handler is outermost, and just
 5751: prints an error and restarts command-line interpretation (or, in batch
 5752: mode (i.e., while processing the shell command line), leaves Gforth).
 5753: 
 5754: The ANS Forth way to catch exceptions is @code{catch}:
 5755: 
 5756: doc-catch
 5757: 
 5758: The most common use of exception handlers is to clean up the state when
 5759: an error happens.  E.g.,
 5760: 
 5761: @example
 5762: base @ >r hex \ actually the hex should be inside foo, or we h
 5763: ['] foo catch ( nerror|0 )
 5764: r> base !
 5765: ( nerror|0 ) throw \ pass it on
 5766: @end example
 5767: 
 5768: A use of @code{catch} for handling the error @code{myerror} might look
 5769: like this:
 5770: 
 5771: @example
 5772: ['] foo catch
 5773: CASE
 5774:   myerror OF ... ( do something about it ) ENDOF
 5775:   dup throw \ default: pass other errors on, do nothing on non-errors
 5776: ENDCASE
 5777: @end example
 5778: 
 5779: Having to wrap the code into a separate word is often cumbersome,
 5780: therefore Gforth provides an alternative syntax:
 5781: 
 5782: @example
 5783: TRY
 5784:   @i{code1}
 5785: RECOVER     \ optional
 5786:   @i{code2} \ optional
 5787: ENDTRY
 5788: @end example
 5789: 
 5790: This performs @i{Code1}.  If @i{code1} completes normally, execution
 5791: continues after the @code{endtry}.  If @i{Code1} throws, the stacks are
 5792: reset to the state during @code{try}, the throw value is pushed on the
 5793: data stack, and execution constinues at @i{code2}, and finally falls
 5794: through the @code{endtry} into the following code. If there is no
 5795: @code{recover} clause, this works like an empty recover clause.
 5796: 
 5797: doc-try
 5798: doc-recover
 5799: doc-endtry
 5800: 
 5801: The cleanup example from above in this syntax:
 5802: 
 5803: @example
 5804: base @ >r TRY
 5805:   hex foo \ now the hex is placed correctly
 5806:   0       \ value for throw
 5807: ENDTRY
 5808: r> base ! throw
 5809: @end example
 5810: 
 5811: And here's the error handling example:
 5812: 
 5813: @example
 5814: TRY
 5815:   foo
 5816: RECOVER
 5817:   CASE
 5818:     myerror OF ... ( do something about it ) ENDOF
 5819:     throw \ pass other errors on
 5820:   ENDCASE
 5821: ENDTRY
 5822: @end example
 5823: 
 5824: @progstyle
 5825: As usual, you should ensure that the stack depth is statically known at
 5826: the end: either after the @code{throw} for passing on errors, or after
 5827: the @code{ENDTRY} (or, if you use @code{catch}, after the end of the
 5828: selection construct for handling the error).
 5829: 
 5830: There are two alternatives to @code{throw}: @code{Abort"} is conditional
 5831: and you can provide an error message.  @code{Abort} just produces an
 5832: ``Aborted'' error.
 5833: 
 5834: The problem with these words is that exception handlers cannot
 5835: differentiate between different @code{abort"}s; they just look like
 5836: @code{-2 throw} to them (the error message cannot be accessed by
 5837: standard programs).  Similar @code{abort} looks like @code{-1 throw} to
 5838: exception handlers.
 5839: 
 5840: doc-abort"
 5841: doc-abort
 5842: 
 5843: 
 5844: 
 5845: @c -------------------------------------------------------------
 5846: @node Defining Words, Interpretation and Compilation Semantics, Control Structures, Words
 5847: @section Defining Words
 5848: @cindex defining words
 5849: 
 5850: Defining words are used to extend Forth by creating new entries in the dictionary.
 5851: 
 5852: @menu
 5853: * CREATE::                      
 5854: * Variables::                   Variables and user variables
 5855: * Constants::                   
 5856: * Values::                      Initialised variables
 5857: * Colon Definitions::           
 5858: * Anonymous Definitions::       Definitions without names
 5859: * Supplying names::             Passing definition names as strings
 5860: * User-defined Defining Words::  
 5861: * Deferred words::              Allow forward references
 5862: * Aliases::                     
 5863: @end menu
 5864: 
 5865: @node CREATE, Variables, Defining Words, Defining Words
 5866: @subsection @code{CREATE}
 5867: @cindex simple defining words
 5868: @cindex defining words, simple
 5869: 
 5870: Defining words are used to create new entries in the dictionary. The
 5871: simplest defining word is @code{CREATE}. @code{CREATE} is used like
 5872: this:
 5873: 
 5874: @example
 5875: CREATE new-word1
 5876: @end example
 5877: 
 5878: @code{CREATE} is a parsing word, i.e., it takes an argument from the
 5879: input stream (@code{new-word1} in our example).  It generates a
 5880: dictionary entry for @code{new-word1}. When @code{new-word1} is
 5881: executed, all that it does is leave an address on the stack. The address
 5882: represents the value of the data space pointer (@code{HERE}) at the time
 5883: that @code{new-word1} was defined. Therefore, @code{CREATE} is a way of
 5884: associating a name with the address of a region of memory.
 5885: 
 5886: doc-create
 5887: 
 5888: Note that in ANS Forth guarantees only for @code{create} that its body
 5889: is in dictionary data space (i.e., where @code{here}, @code{allot}
 5890: etc. work, @pxref{Dictionary allocation}).  Also, in ANS Forth only
 5891: @code{create}d words can be modified with @code{does>}
 5892: (@pxref{User-defined Defining Words}).  And in ANS Forth @code{>body}
 5893: can only be applied to @code{create}d words.
 5894: 
 5895: By extending this example to reserve some memory in data space, we end
 5896: up with something like a @i{variable}. Here are two different ways to do
 5897: it:
 5898: 
 5899: @example
 5900: CREATE new-word2 1 cells allot  \ reserve 1 cell - initial value undefined
 5901: CREATE new-word3 4 ,            \ reserve 1 cell and initialise it (to 4)
 5902: @end example
 5903: 
 5904: The variable can be examined and modified using @code{@@} (``fetch'') and
 5905: @code{!} (``store'') like this:
 5906: 
 5907: @example
 5908: new-word2 @@ .      \ get address, fetch from it and display
 5909: 1234 new-word2 !   \ new value, get address, store to it
 5910: @end example
 5911: 
 5912: @cindex arrays
 5913: A similar mechanism can be used to create arrays. For example, an
 5914: 80-character text input buffer:
 5915: 
 5916: @example
 5917: CREATE text-buf 80 chars allot
 5918: 
 5919: text-buf 0 chars c@@ \ the 1st character (offset 0)
 5920: text-buf 3 chars c@@ \ the 4th character (offset 3)
 5921: @end example
 5922: 
 5923: You can build arbitrarily complex data structures by allocating
 5924: appropriate areas of memory. For further discussions of this, and to
 5925: learn about some Gforth tools that make it easier,
 5926: @xref{Structures}.
 5927: 
 5928: 
 5929: @node Variables, Constants, CREATE, Defining Words
 5930: @subsection Variables
 5931: @cindex variables
 5932: 
 5933: The previous section showed how a sequence of commands could be used to
 5934: generate a variable.  As a final refinement, the whole code sequence can
 5935: be wrapped up in a defining word (pre-empting the subject of the next
 5936: section), making it easier to create new variables:
 5937: 
 5938: @example
 5939: : myvariableX ( "name" -- a-addr ) CREATE 1 cells allot ;
 5940: : myvariable0 ( "name" -- a-addr ) CREATE 0 , ;
 5941: 
 5942: myvariableX foo \ variable foo starts off with an unknown value
 5943: myvariable0 joe \ whilst joe is initialised to 0
 5944: 
 5945: 45 3 * foo !   \ set foo to 135
 5946: 1234 joe !     \ set joe to 1234
 5947: 3 joe +!       \ increment joe by 3.. to 1237
 5948: @end example
 5949: 
 5950: Not surprisingly, there is no need to define @code{myvariable}, since
 5951: Forth already has a definition @code{Variable}. ANS Forth does not
 5952: guarantee that a @code{Variable} is initialised when it is created
 5953: (i.e., it may behave like @code{myvariableX}). In contrast, Gforth's
 5954: @code{Variable} initialises the variable to 0 (i.e., it behaves exactly
 5955: like @code{myvariable0}). Forth also provides @code{2Variable} and
 5956: @code{fvariable} for double and floating-point variables, respectively
 5957: -- they are initialised to 0. and 0e in Gforth. If you use a @code{Variable} to
 5958: store a boolean, you can use @code{on} and @code{off} to toggle its
 5959: state.
 5960: 
 5961: doc-variable
 5962: doc-2variable
 5963: doc-fvariable
 5964: 
 5965: @cindex user variables
 5966: @cindex user space
 5967: The defining word @code{User} behaves in the same way as @code{Variable}.
 5968: The difference is that it reserves space in @i{user (data) space} rather
 5969: than normal data space. In a Forth system that has a multi-tasker, each
 5970: task has its own set of user variables.
 5971: 
 5972: doc-user
 5973: @c doc-udp
 5974: @c doc-uallot
 5975: 
 5976: @comment TODO is that stuff about user variables strictly correct? Is it
 5977: @comment just terminal tasks that have user variables?
 5978: @comment should document tasker.fs (with some examples) elsewhere
 5979: @comment in this manual, then expand on user space and user variables.
 5980: 
 5981: @node Constants, Values, Variables, Defining Words
 5982: @subsection Constants
 5983: @cindex constants
 5984: 
 5985: @code{Constant} allows you to declare a fixed value and refer to it by
 5986: name. For example:
 5987: 
 5988: @example
 5989: 12 Constant INCHES-PER-FOOT
 5990: 3E+08 fconstant SPEED-O-LIGHT
 5991: @end example
 5992: 
 5993: A @code{Variable} can be both read and written, so its run-time
 5994: behaviour is to supply an address through which its current value can be
 5995: manipulated. In contrast, the value of a @code{Constant} cannot be
 5996: changed once it has been declared@footnote{Well, often it can be -- but
 5997: not in a Standard, portable way. It's safer to use a @code{Value} (read
 5998: on).} so it's not necessary to supply the address -- it is more
 5999: efficient to return the value of the constant directly. That's exactly
 6000: what happens; the run-time effect of a constant is to put its value on
 6001: the top of the stack (You can find one
 6002: way of implementing @code{Constant} in @ref{User-defined Defining Words}).
 6003: 
 6004: Forth also provides @code{2Constant} and @code{fconstant} for defining
 6005: double and floating-point constants, respectively.
 6006: 
 6007: doc-constant
 6008: doc-2constant
 6009: doc-fconstant
 6010: 
 6011: @c that's too deep, and it's not necessarily true for all ANS Forths. - anton
 6012: @c nac-> How could that not be true in an ANS Forth? You can't define a
 6013: @c constant, use it and then delete the definition of the constant..
 6014: 
 6015: @c anton->An ANS Forth system can compile a constant to a literal; On
 6016: @c decompilation you would see only the number, just as if it had been used
 6017: @c in the first place.  The word will stay, of course, but it will only be
 6018: @c used by the text interpreter (no run-time duties, except when it is 
 6019: @c POSTPONEd or somesuch).
 6020: 
 6021: @c nac:
 6022: @c I agree that it's rather deep, but IMO it is an important difference
 6023: @c relative to other programming languages.. often it's annoying: it
 6024: @c certainly changes my programming style relative to C.
 6025: 
 6026: @c anton: In what way?
 6027: 
 6028: Constants in Forth behave differently from their equivalents in other
 6029: programming languages. In other languages, a constant (such as an EQU in
 6030: assembler or a #define in C) only exists at compile-time; in the
 6031: executable program the constant has been translated into an absolute
 6032: number and, unless you are using a symbolic debugger, it's impossible to
 6033: know what abstract thing that number represents. In Forth a constant has
 6034: an entry in the header space and remains there after the code that uses
 6035: it has been defined. In fact, it must remain in the dictionary since it
 6036: has run-time duties to perform. For example:
 6037: 
 6038: @example
 6039: 12 Constant INCHES-PER-FOOT
 6040: : FEET-TO-INCHES ( n1 -- n2 ) INCHES-PER-FOOT * ;
 6041: @end example
 6042: 
 6043: @cindex in-lining of constants
 6044: When @code{FEET-TO-INCHES} is executed, it will in turn execute the xt
 6045: associated with the constant @code{INCHES-PER-FOOT}. If you use
 6046: @code{see} to decompile the definition of @code{FEET-TO-INCHES}, you can
 6047: see that it makes a call to @code{INCHES-PER-FOOT}. Some Forth compilers
 6048: attempt to optimise constants by in-lining them where they are used. You
 6049: can force Gforth to in-line a constant like this:
 6050: 
 6051: @example
 6052: : FEET-TO-INCHES ( n1 -- n2 ) [ INCHES-PER-FOOT ] LITERAL * ;
 6053: @end example
 6054: 
 6055: If you use @code{see} to decompile @i{this} version of
 6056: @code{FEET-TO-INCHES}, you can see that @code{INCHES-PER-FOOT} is no
 6057: longer present. To understand how this works, read
 6058: @ref{Interpret/Compile states}, and @ref{Literals}.
 6059: 
 6060: In-lining constants in this way might improve execution time
 6061: fractionally, and can ensure that a constant is now only referenced at
 6062: compile-time. However, the definition of the constant still remains in
 6063: the dictionary. Some Forth compilers provide a mechanism for controlling
 6064: a second dictionary for holding transient words such that this second
 6065: dictionary can be deleted later in order to recover memory
 6066: space. However, there is no standard way of doing this.
 6067: 
 6068: 
 6069: @node Values, Colon Definitions, Constants, Defining Words
 6070: @subsection Values
 6071: @cindex values
 6072: 
 6073: A @code{Value} behaves like a @code{Constant}, but it can be changed.
 6074: @code{TO} is a parsing word that changes a @code{Values}.  In Gforth
 6075: (not in ANS Forth) you can access (and change) a @code{value} also with
 6076: @code{>body}.
 6077: 
 6078: Here are some
 6079: examples:
 6080: 
 6081: @example
 6082: 12 Value APPLES     \ Define APPLES with an initial value of 12
 6083: 34 TO APPLES        \ Change the value of APPLES. TO is a parsing word
 6084: 1 ' APPLES >body +! \ Increment APPLES.  Non-standard usage.
 6085: APPLES              \ puts 35 on the top of the stack.
 6086: @end example
 6087: 
 6088: doc-value
 6089: doc-to
 6090: 
 6091: 
 6092: 
 6093: @node Colon Definitions, Anonymous Definitions, Values, Defining Words
 6094: @subsection Colon Definitions
 6095: @cindex colon definitions
 6096: 
 6097: @example
 6098: : name ( ... -- ... )
 6099:     word1 word2 word3 ;
 6100: @end example
 6101: 
 6102: @noindent
 6103: Creates a word called @code{name} that, upon execution, executes
 6104: @code{word1 word2 word3}. @code{name} is a @dfn{(colon) definition}.
 6105: 
 6106: The explanation above is somewhat superficial. For simple examples of
 6107: colon definitions see @ref{Your first definition}.  For an in-depth
 6108: discussion of some of the issues involved, @xref{Interpretation and
 6109: Compilation Semantics}.
 6110: 
 6111: doc-:
 6112: doc-;
 6113: 
 6114: 
 6115: @node Anonymous Definitions, Supplying names, Colon Definitions, Defining Words
 6116: @subsection Anonymous Definitions
 6117: @cindex colon definitions
 6118: @cindex defining words without name
 6119: 
 6120: Sometimes you want to define an @dfn{anonymous word}; a word without a
 6121: name. You can do this with:
 6122: 
 6123: doc-:noname
 6124: 
 6125: This leaves the execution token for the word on the stack after the
 6126: closing @code{;}. Here's an example in which a deferred word is
 6127: initialised with an @code{xt} from an anonymous colon definition:
 6128: 
 6129: @example
 6130: Defer deferred
 6131: :noname ( ... -- ... )
 6132:   ... ;
 6133: IS deferred
 6134: @end example
 6135: 
 6136: @noindent
 6137: Gforth provides an alternative way of doing this, using two separate
 6138: words:
 6139: 
 6140: doc-noname
 6141: @cindex execution token of last defined word
 6142: doc-lastxt
 6143: 
 6144: @noindent
 6145: The previous example can be rewritten using @code{noname} and
 6146: @code{lastxt}:
 6147: 
 6148: @example
 6149: Defer deferred
 6150: noname : ( ... -- ... )
 6151:   ... ;
 6152: lastxt IS deferred
 6153: @end example
 6154: 
 6155: @noindent
 6156: @code{noname} works with any defining word, not just @code{:}.
 6157: 
 6158: @code{lastxt} also works when the last word was not defined as
 6159: @code{noname}.  It does not work for combined words, though.  It also has
 6160: the useful property that is is valid as soon as the header for a
 6161: definition has been built. Thus:
 6162: 
 6163: @example
 6164: lastxt . : foo [ lastxt . ] ; ' foo .
 6165: @end example
 6166: 
 6167: @noindent
 6168: prints 3 numbers; the last two are the same.
 6169: 
 6170: @node Supplying names, User-defined Defining Words, Anonymous Definitions, Defining Words
 6171: @subsection Supplying the name of a defined word
 6172: @cindex names for defined words
 6173: @cindex defining words, name given in a string
 6174: 
 6175: By default, a defining word takes the name for the defined word from the
 6176: input stream. Sometimes you want to supply the name from a string. You
 6177: can do this with:
 6178: 
 6179: doc-nextname
 6180: 
 6181: For example:
 6182: 
 6183: @example
 6184: s" foo" nextname create
 6185: @end example
 6186: 
 6187: @noindent
 6188: is equivalent to:
 6189: 
 6190: @example
 6191: create foo
 6192: @end example
 6193: 
 6194: @noindent
 6195: @code{nextname} works with any defining word.
 6196: 
 6197: 
 6198: @node User-defined Defining Words, Deferred words, Supplying names, Defining Words
 6199: @subsection User-defined Defining Words
 6200: @cindex user-defined defining words
 6201: @cindex defining words, user-defined
 6202: 
 6203: You can create a new defining word by wrapping defining-time code around
 6204: an existing defining word and putting the sequence in a colon
 6205: definition. 
 6206: 
 6207: @c anton: This example is very complex and leads in a quite different
 6208: @c direction from the CREATE-DOES> stuff that follows.  It should probably
 6209: @c be done elsewhere, or as a subsubsection of this subsection (or as a
 6210: @c subsection of Defining Words)
 6211: 
 6212: For example, suppose that you have a word @code{stats} that
 6213: gathers statistics about colon definitions given the @i{xt} of the
 6214: definition, and you want every colon definition in your application to
 6215: make a call to @code{stats}. You can define and use a new version of
 6216: @code{:} like this:
 6217: 
 6218: @example
 6219: : stats ( xt -- ) DUP ." (Gathering statistics for " . ." )"
 6220:   ... ;  \ other code
 6221: 
 6222: : my: : lastxt postpone literal ['] stats compile, ;
 6223: 
 6224: my: foo + - ;
 6225: @end example
 6226: 
 6227: When @code{foo} is defined using @code{my:} these steps occur:
 6228: 
 6229: @itemize @bullet
 6230: @item
 6231: @code{my:} is executed.
 6232: @item
 6233: The @code{:} within the definition (the one between @code{my:} and
 6234: @code{lastxt}) is executed, and does just what it always does; it parses
 6235: the input stream for a name, builds a dictionary header for the name
 6236: @code{foo} and switches @code{state} from interpret to compile.
 6237: @item
 6238: The word @code{lastxt} is executed. It puts the @i{xt} for the word that is
 6239: being defined -- @code{foo} -- onto the stack.
 6240: @item
 6241: The code that was produced by @code{postpone literal} is executed; this
 6242: causes the value on the stack to be compiled as a literal in the code
 6243: area of @code{foo}.
 6244: @item
 6245: The code @code{['] stats} compiles a literal into the definition of
 6246: @code{my:}. When @code{compile,} is executed, that literal -- the
 6247: execution token for @code{stats} -- is layed down in the code area of
 6248: @code{foo} , following the literal@footnote{Strictly speaking, the
 6249: mechanism that @code{compile,} uses to convert an @i{xt} into something
 6250: in the code area is implementation-dependent. A threaded implementation
 6251: might spit out the execution token directly whilst another
 6252: implementation might spit out a native code sequence.}.
 6253: @item
 6254: At this point, the execution of @code{my:} is complete, and control
 6255: returns to the text interpreter. The text interpreter is in compile
 6256: state, so subsequent text @code{+ -} is compiled into the definition of
 6257: @code{foo} and the @code{;} terminates the definition as always.
 6258: @end itemize
 6259: 
 6260: You can use @code{see} to decompile a word that was defined using
 6261: @code{my:} and see how it is different from a normal @code{:}
 6262: definition. For example:
 6263: 
 6264: @example
 6265: : bar + - ;  \ like foo but using : rather than my:
 6266: see bar
 6267: : bar
 6268:   + - ;
 6269: see foo
 6270: : foo
 6271:   107645672 stats + - ;
 6272: 
 6273: \ use ' stats . to show that 107645672 is the xt for stats
 6274: @end example
 6275: 
 6276: You can use techniques like this to make new defining words in terms of
 6277: @i{any} existing defining word.
 6278: 
 6279: 
 6280: @cindex defining defining words
 6281: @cindex @code{CREATE} ... @code{DOES>}
 6282: If you want the words defined with your defining words to behave
 6283: differently from words defined with standard defining words, you can
 6284: write your defining word like this:
 6285: 
 6286: @example
 6287: : def-word ( "name" -- )
 6288:     CREATE @i{code1}
 6289: DOES> ( ... -- ... )
 6290:     @i{code2} ;
 6291: 
 6292: def-word name
 6293: @end example
 6294: 
 6295: @cindex child words
 6296: This fragment defines a @dfn{defining word} @code{def-word} and then
 6297: executes it.  When @code{def-word} executes, it @code{CREATE}s a new
 6298: word, @code{name}, and executes the code @i{code1}. The code @i{code2}
 6299: is not executed at this time. The word @code{name} is sometimes called a
 6300: @dfn{child} of @code{def-word}.
 6301: 
 6302: When you execute @code{name}, the address of the body of @code{name} is
 6303: put on the data stack and @i{code2} is executed (the address of the body
 6304: of @code{name} is the address @code{HERE} returns immediately after the
 6305: @code{CREATE}, i.e., the address a @code{create}d word returns by
 6306: default).
 6307: 
 6308: @c anton:
 6309: @c www.dictionary.com says:
 6310: @c at·a·vism: 1.The reappearance of a characteristic in an organism after
 6311: @c several generations of absence, usually caused by the chance
 6312: @c recombination of genes.  2.An individual or a part that exhibits
 6313: @c atavism. Also called throwback.  3.The return of a trait or recurrence
 6314: @c of previous behavior after a period of absence.
 6315: @c
 6316: @c Doesn't seem to fit.
 6317: 
 6318: @c @cindex atavism in child words
 6319: You can use @code{def-word} to define a set of child words that behave
 6320: similarly; they all have a common run-time behaviour determined by
 6321: @i{code2}. Typically, the @i{code1} sequence builds a data area in the
 6322: body of the child word. The structure of the data is common to all
 6323: children of @code{def-word}, but the data values are specific -- and
 6324: private -- to each child word. When a child word is executed, the
 6325: address of its private data area is passed as a parameter on TOS to be
 6326: used and manipulated@footnote{It is legitimate both to read and write to
 6327: this data area.} by @i{code2}.
 6328: 
 6329: The two fragments of code that make up the defining words act (are
 6330: executed) at two completely separate times:
 6331: 
 6332: @itemize @bullet
 6333: @item
 6334: At @i{define time}, the defining word executes @i{code1} to generate a
 6335: child word
 6336: @item
 6337: At @i{child execution time}, when a child word is invoked, @i{code2}
 6338: is executed, using parameters (data) that are private and specific to
 6339: the child word.
 6340: @end itemize
 6341: 
 6342: Another way of understanding the behaviour of @code{def-word} and
 6343: @code{name} is to say that, if you make the following definitions:
 6344: @example
 6345: : def-word1 ( "name" -- )
 6346:     CREATE @i{code1} ;
 6347: 
 6348: : action1 ( ... -- ... )
 6349:     @i{code2} ;
 6350: 
 6351: def-word1 name1
 6352: @end example
 6353: 
 6354: @noindent
 6355: Then using @code{name1 action1} is equivalent to using @code{name}.
 6356: 
 6357: The classic example is that you can define @code{CONSTANT} in this way:
 6358: 
 6359: @example
 6360: : CONSTANT ( w "name" -- )
 6361:     CREATE ,
 6362: DOES> ( -- w )
 6363:     @@ ;
 6364: @end example
 6365: 
 6366: @comment There is a beautiful description of how this works and what
 6367: @comment it does in the Forthwrite 100th edition.. as well as an elegant
 6368: @comment commentary on the Counting Fruits problem.
 6369: 
 6370: When you create a constant with @code{5 CONSTANT five}, a set of
 6371: define-time actions take place; first a new word @code{five} is created,
 6372: then the value 5 is laid down in the body of @code{five} with
 6373: @code{,}. When @code{five} is executed, the address of the body is put on
 6374: the stack, and @code{@@} retrieves the value 5. The word @code{five} has
 6375: no code of its own; it simply contains a data field and a pointer to the
 6376: code that follows @code{DOES>} in its defining word. That makes words
 6377: created in this way very compact.
 6378: 
 6379: The final example in this section is intended to remind you that space
 6380: reserved in @code{CREATE}d words is @i{data} space and therefore can be
 6381: both read and written by a Standard program@footnote{Exercise: use this
 6382: example as a starting point for your own implementation of @code{Value}
 6383: and @code{TO} -- if you get stuck, investigate the behaviour of @code{'} and
 6384: @code{[']}.}:
 6385: 
 6386: @example
 6387: : foo ( "name" -- )
 6388:     CREATE -1 ,
 6389: DOES> ( -- )
 6390:     @@ . ;
 6391: 
 6392: foo first-word
 6393: foo second-word
 6394: 
 6395: 123 ' first-word >BODY !
 6396: @end example
 6397: 
 6398: If @code{first-word} had been a @code{CREATE}d word, we could simply
 6399: have executed it to get the address of its data field. However, since it
 6400: was defined to have @code{DOES>} actions, its execution semantics are to
 6401: perform those @code{DOES>} actions. To get the address of its data field
 6402: it's necessary to use @code{'} to get its xt, then @code{>BODY} to
 6403: translate the xt into the address of the data field.  When you execute
 6404: @code{first-word}, it will display @code{123}. When you execute
 6405: @code{second-word} it will display @code{-1}.
 6406: 
 6407: @cindex stack effect of @code{DOES>}-parts
 6408: @cindex @code{DOES>}-parts, stack effect
 6409: In the examples above the stack comment after the @code{DOES>} specifies
 6410: the stack effect of the defined words, not the stack effect of the
 6411: following code (the following code expects the address of the body on
 6412: the top of stack, which is not reflected in the stack comment). This is
 6413: the convention that I use and recommend (it clashes a bit with using
 6414: locals declarations for stack effect specification, though).
 6415: 
 6416: @menu
 6417: * CREATE..DOES> applications::  
 6418: * CREATE..DOES> details::       
 6419: * Advanced does> usage example::  
 6420: @end menu
 6421: 
 6422: @node CREATE..DOES> applications, CREATE..DOES> details, User-defined Defining Words, User-defined Defining Words
 6423: @subsubsection Applications of @code{CREATE..DOES>}
 6424: @cindex @code{CREATE} ... @code{DOES>}, applications
 6425: 
 6426: You may wonder how to use this feature. Here are some usage patterns:
 6427: 
 6428: @cindex factoring similar colon definitions
 6429: When you see a sequence of code occurring several times, and you can
 6430: identify a meaning, you will factor it out as a colon definition. When
 6431: you see similar colon definitions, you can factor them using
 6432: @code{CREATE..DOES>}. E.g., an assembler usually defines several words
 6433: that look very similar:
 6434: @example
 6435: : ori, ( reg-target reg-source n -- )
 6436:     0 asm-reg-reg-imm ;
 6437: : andi, ( reg-target reg-source n -- )
 6438:     1 asm-reg-reg-imm ;
 6439: @end example
 6440: 
 6441: @noindent
 6442: This could be factored with:
 6443: @example
 6444: : reg-reg-imm ( op-code -- )
 6445:     CREATE ,
 6446: DOES> ( reg-target reg-source n -- )
 6447:     @@ asm-reg-reg-imm ;
 6448: 
 6449: 0 reg-reg-imm ori,
 6450: 1 reg-reg-imm andi,
 6451: @end example
 6452: 
 6453: @cindex currying
 6454: Another view of @code{CREATE..DOES>} is to consider it as a crude way to
 6455: supply a part of the parameters for a word (known as @dfn{currying} in
 6456: the functional language community). E.g., @code{+} needs two
 6457: parameters. Creating versions of @code{+} with one parameter fixed can
 6458: be done like this:
 6459: @example
 6460: : curry+ ( n1 -- )
 6461:     CREATE ,
 6462: DOES> ( n2 -- n1+n2 )
 6463:     @@ + ;
 6464: 
 6465:  3 curry+ 3+
 6466: -2 curry+ 2-
 6467: @end example
 6468: 
 6469: @node CREATE..DOES> details, Advanced does> usage example, CREATE..DOES> applications, User-defined Defining Words
 6470: @subsubsection The gory details of @code{CREATE..DOES>}
 6471: @cindex @code{CREATE} ... @code{DOES>}, details
 6472: 
 6473: doc-does>
 6474: 
 6475: @cindex @code{DOES>} in a separate definition
 6476: This means that you need not use @code{CREATE} and @code{DOES>} in the
 6477: same definition; you can put the @code{DOES>}-part in a separate
 6478: definition. This allows us to, e.g., select among different @code{DOES>}-parts:
 6479: @example
 6480: : does1 
 6481: DOES> ( ... -- ... )
 6482:     ... ;
 6483: 
 6484: : does2
 6485: DOES> ( ... -- ... )
 6486:     ... ;
 6487: 
 6488: : def-word ( ... -- ... )
 6489:     create ...
 6490:     IF
 6491:        does1
 6492:     ELSE
 6493:        does2
 6494:     ENDIF ;
 6495: @end example
 6496: 
 6497: In this example, the selection of whether to use @code{does1} or
 6498: @code{does2} is made at definition-time; at the time that the child word is
 6499: @code{CREATE}d.
 6500: 
 6501: @cindex @code{DOES>} in interpretation state
 6502: In a standard program you can apply a @code{DOES>}-part only if the last
 6503: word was defined with @code{CREATE}. In Gforth, the @code{DOES>}-part
 6504: will override the behaviour of the last word defined in any case. In a
 6505: standard program, you can use @code{DOES>} only in a colon
 6506: definition. In Gforth, you can also use it in interpretation state, in a
 6507: kind of one-shot mode; for example:
 6508: @example
 6509: CREATE name ( ... -- ... )
 6510:   @i{initialization}
 6511: DOES>
 6512:   @i{code} ;
 6513: @end example
 6514: 
 6515: @noindent
 6516: is equivalent to the standard:
 6517: @example
 6518: :noname
 6519: DOES>
 6520:     @i{code} ;
 6521: CREATE name EXECUTE ( ... -- ... )
 6522:     @i{initialization}
 6523: @end example
 6524: 
 6525: doc->body
 6526: 
 6527: @node Advanced does> usage example,  , CREATE..DOES> details, User-defined Defining Words
 6528: @subsubsection Advanced does> usage example
 6529: 
 6530: The MIPS disassembler (@file{arch/mips/disasm.fs}) contains many words
 6531: for disassembling instructions, that follow a very repetetive scheme:
 6532: 
 6533: @example
 6534: :noname @var{disasm-operands} s" @var{inst-name}" type ;
 6535: @var{entry-num} cells @var{table} + !
 6536: @end example
 6537: 
 6538: Of course, this inspires the idea to factor out the commonalities to
 6539: allow a definition like
 6540: 
 6541: @example
 6542: @var{disasm-operands} @var{entry-num} @var{table} define-inst @var{inst-name}
 6543: @end example
 6544: 
 6545: The parameters @var{disasm-operands} and @var{table} are usually
 6546: correlated.  Moreover, before I wrote the disassembler, there already
 6547: existed code that defines instructions like this:
 6548: 
 6549: @example
 6550: @var{entry-num} @var{inst-format} @var{inst-name}
 6551: @end example
 6552: 
 6553: This code comes from the assembler and resides in
 6554: @file{arch/mips/insts.fs}.
 6555: 
 6556: So I had to define the @var{inst-format} words that performed the scheme
 6557: above when executed.  At first I chose to use run-time code-generation:
 6558: 
 6559: @example
 6560: : @var{inst-format} ( entry-num "name" -- ; compiled code: addr w -- )
 6561:   :noname Postpone @var{disasm-operands}
 6562:   name Postpone sliteral Postpone type Postpone ;
 6563:   swap cells @var{table} + ! ;
 6564: @end example
 6565: 
 6566: Note that this supplies the other two parameters of the scheme above.
 6567: 
 6568: An alternative would have been to write this using
 6569: @code{create}/@code{does>}:
 6570: 
 6571: @example
 6572: : @var{inst-format} ( entry-num "name" -- )
 6573:   here name string, ( entry-num c-addr ) \ parse and save "name"
 6574:   noname create , ( entry-num )
 6575:   lastxt swap cells @var{table} + !
 6576: does> ( addr w -- )
 6577:   \ disassemble instruction w at addr
 6578:   @@ >r 
 6579:   @var{disasm-operands}
 6580:   r> count type ;
 6581: @end example
 6582: 
 6583: Somehow the first solution is simpler, mainly because it's simpler to
 6584: shift a string from definition-time to use-time with @code{sliteral}
 6585: than with @code{string,} and friends.
 6586: 
 6587: I wrote a lot of words following this scheme and soon thought about
 6588: factoring out the commonalities among them.  Note that this uses a
 6589: two-level defining word, i.e., a word that defines ordinary defining
 6590: words.
 6591: 
 6592: This time a solution involving @code{postpone} and friends seemed more
 6593: difficult (try it as an exercise), so I decided to use a
 6594: @code{create}/@code{does>} word; since I was already at it, I also used
 6595: @code{create}/@code{does>} for the lower level (try using
 6596: @code{postpone} etc. as an exercise), resulting in the following
 6597: definition:
 6598: 
 6599: @example
 6600: : define-format ( disasm-xt table-xt -- )
 6601:     \ define an instruction format that uses disasm-xt for
 6602:     \ disassembling and enters the defined instructions into table
 6603:     \ table-xt
 6604:     create 2,
 6605: does> ( u "inst" -- )
 6606:     \ defines an anonymous word for disassembling instruction inst,
 6607:     \ and enters it as u-th entry into table-xt
 6608:     2@@ swap here name string, ( u table-xt disasm-xt c-addr ) \ remember string
 6609:     noname create 2,      \ define anonymous word
 6610:     execute lastxt swap ! \ enter xt of defined word into table-xt
 6611: does> ( addr w -- )
 6612:     \ disassemble instruction w at addr
 6613:     2@@ >r ( addr w disasm-xt R: c-addr )
 6614:     execute ( R: c-addr ) \ disassemble operands
 6615:     r> count type ; \ print name 
 6616: @end example
 6617: 
 6618: Note that the tables here (in contrast to above) do the @code{cells +}
 6619: by themselves (that's why you have to pass an xt).  This word is used in
 6620: the following way:
 6621: 
 6622: @example
 6623: ' @var{disasm-operands} ' @var{table} define-format @var{inst-format}
 6624: @end example
 6625: 
 6626: As shown above, the defined instruction format is then used like this:
 6627: 
 6628: @example
 6629: @var{entry-num} @var{inst-format} @var{inst-name}
 6630: @end example
 6631: 
 6632: In terms of currying, this kind of two-level defining word provides the
 6633: parameters in three stages: first @var{disasm-operands} and @var{table},
 6634: then @var{entry-num} and @var{inst-name}, finally @code{addr w}, i.e.,
 6635: the instruction to be disassembled.  
 6636: 
 6637: Of course this did not quite fit all the instruction format names used
 6638: in @file{insts.fs}, so I had to define a few wrappers that conditioned
 6639: the parameters into the right form.
 6640: 
 6641: If you have trouble following this section, don't worry.  First, this is
 6642: involved and takes time (and probably some playing around) to
 6643: understand; second, this is the first two-level
 6644: @code{create}/@code{does>} word I have written in seventeen years of
 6645: Forth; and if I did not have @file{insts.fs} to start with, I may well
 6646: have elected to use just a one-level defining word (with some repeating
 6647: of parameters when using the defining word). So it is not necessary to
 6648: understand this, but it may improve your understanding of Forth.
 6649: 
 6650: 
 6651: @node Deferred words, Aliases, User-defined Defining Words, Defining Words
 6652: @subsection Deferred words
 6653: @cindex deferred words
 6654: 
 6655: The defining word @code{Defer} allows you to define a word by name
 6656: without defining its behaviour; the definition of its behaviour is
 6657: deferred. Here are two situation where this can be useful:
 6658: 
 6659: @itemize @bullet
 6660: @item
 6661: Where you want to allow the behaviour of a word to be altered later, and
 6662: for all precompiled references to the word to change when its behaviour
 6663: is changed.
 6664: @item
 6665: For mutual recursion; @xref{Calls and returns}.
 6666: @end itemize
 6667: 
 6668: In the following example, @code{foo} always invokes the version of
 6669: @code{greet} that prints ``@code{Good morning}'' whilst @code{bar}
 6670: always invokes the version that prints ``@code{Hello}''. There is no way
 6671: of getting @code{foo} to use the later version without re-ordering the
 6672: source code and recompiling it.
 6673: 
 6674: @example
 6675: : greet ." Good morning" ;
 6676: : foo ... greet ... ;
 6677: : greet ." Hello" ;
 6678: : bar ... greet ... ;
 6679: @end example
 6680: 
 6681: This problem can be solved by defining @code{greet} as a @code{Defer}red
 6682: word. The behaviour of a @code{Defer}red word can be defined and
 6683: redefined at any time by using @code{IS} to associate the xt of a
 6684: previously-defined word with it. The previous example becomes:
 6685: 
 6686: @example
 6687: Defer greet ( -- )
 6688: : foo ... greet ... ;
 6689: : bar ... greet ... ;
 6690: : greet1 ( -- ) ." Good morning" ;
 6691: : greet2 ( -- ) ." Hello" ;
 6692: ' greet2 <IS> greet  \ make greet behave like greet2
 6693: @end example
 6694: 
 6695: @progstyle
 6696: You should write a stack comment for every deferred word, and put only
 6697: XTs into deferred words that conform to this stack effect.  Otherwise
 6698: it's too difficult to use the deferred word.
 6699: 
 6700: A deferred word can be used to improve the statistics-gathering example
 6701: from @ref{User-defined Defining Words}; rather than edit the
 6702: application's source code to change every @code{:} to a @code{my:}, do
 6703: this:
 6704: 
 6705: @example
 6706: : real: : ;     \ retain access to the original
 6707: defer :         \ redefine as a deferred word
 6708: ' my: <IS> :      \ use special version of :
 6709: \
 6710: \ load application here
 6711: \
 6712: ' real: <IS> :    \ go back to the original
 6713: @end example
 6714: 
 6715: 
 6716: One thing to note is that @code{<IS>} consumes its name when it is
 6717: executed.  If you want to specify the name at compile time, use
 6718: @code{[IS]}:
 6719: 
 6720: @example
 6721: : set-greet ( xt -- )
 6722:   [IS] greet ;
 6723: 
 6724: ' greet1 set-greet
 6725: @end example
 6726: 
 6727: A deferred word can only inherit execution semantics from the xt
 6728: (because that is all that an xt can represent -- for more discussion of
 6729: this @pxref{Tokens for Words}); by default it will have default
 6730: interpretation and compilation semantics deriving from this execution
 6731: semantics.  However, you can change the interpretation and compilation
 6732: semantics of the deferred word in the usual ways:
 6733: 
 6734: @example
 6735: : bar .... ; compile-only
 6736: Defer fred immediate
 6737: Defer jim
 6738: 
 6739: ' bar <IS> jim  \ jim has default semantics
 6740: ' bar <IS> fred \ fred is immediate
 6741: @end example
 6742: 
 6743: doc-defer
 6744: doc-<is>
 6745: doc-[is]
 6746: doc-is
 6747: @comment TODO document these: what's defers [is]
 6748: doc-what's
 6749: doc-defers
 6750: 
 6751: @c Use @code{words-deferred} to see a list of deferred words.
 6752: 
 6753: Definitions in ANS Forth for @code{defer}, @code{<is>} and @code{[is]}
 6754: are provided in @file{compat/defer.fs}.
 6755: 
 6756: 
 6757: @node Aliases,  , Deferred words, Defining Words
 6758: @subsection Aliases
 6759: @cindex aliases
 6760: 
 6761: The defining word @code{Alias} allows you to define a word by name that
 6762: has the same behaviour as some other word. Here are two situation where
 6763: this can be useful:
 6764: 
 6765: @itemize @bullet
 6766: @item
 6767: When you want access to a word's definition from a different word list
 6768: (for an example of this, see the definition of the @code{Root} word list
 6769: in the Gforth source).
 6770: @item
 6771: When you want to create a synonym; a definition that can be known by
 6772: either of two names (for example, @code{THEN} and @code{ENDIF} are
 6773: aliases).
 6774: @end itemize
 6775: 
 6776: Like deferred words, an alias has default compilation and interpretation
 6777: semantics at the beginning (not the modifications of the other word),
 6778: but you can change them in the usual ways (@code{immediate},
 6779: @code{compile-only}). For example:
 6780: 
 6781: @example
 6782: : foo ... ; immediate
 6783: 
 6784: ' foo Alias bar \ bar is not an immediate word
 6785: ' foo Alias fooby immediate \ fooby is an immediate word
 6786: @end example
 6787: 
 6788: Words that are aliases have the same xt, different headers in the
 6789: dictionary, and consequently different name tokens (@pxref{Tokens for
 6790: Words}) and possibly different immediate flags.  An alias can only have
 6791: default or immediate compilation semantics; you can define aliases for
 6792: combined words with @code{interpret/compile:} -- see @ref{Combined words}.
 6793: 
 6794: doc-alias
 6795: 
 6796: 
 6797: @node Interpretation and Compilation Semantics, Tokens for Words, Defining Words, Words
 6798: @section Interpretation and Compilation Semantics
 6799: @cindex semantics, interpretation and compilation
 6800: 
 6801: @c !! state and ' are used without explanation
 6802: @c example for immediate/compile-only? or is the tutorial enough
 6803: 
 6804: @cindex interpretation semantics
 6805: The @dfn{interpretation semantics} of a (named) word are what the text
 6806: interpreter does when it encounters the word in interpret state. It also
 6807: appears in some other contexts, e.g., the execution token returned by
 6808: @code{' @i{word}} identifies the interpretation semantics of @i{word}
 6809: (in other words, @code{' @i{word} execute} is equivalent to
 6810: interpret-state text interpretation of @code{@i{word}}).
 6811: 
 6812: @cindex compilation semantics
 6813: The @dfn{compilation semantics} of a (named) word are what the text
 6814: interpreter does when it encounters the word in compile state. It also
 6815: appears in other contexts, e.g, @code{POSTPONE @i{word}}
 6816: compiles@footnote{In standard terminology, ``appends to the current
 6817: definition''.} the compilation semantics of @i{word}.
 6818: 
 6819: @cindex execution semantics
 6820: The standard also talks about @dfn{execution semantics}. They are used
 6821: only for defining the interpretation and compilation semantics of many
 6822: words. By default, the interpretation semantics of a word are to
 6823: @code{execute} its execution semantics, and the compilation semantics of
 6824: a word are to @code{compile,} its execution semantics.@footnote{In
 6825: standard terminology: The default interpretation semantics are its
 6826: execution semantics; the default compilation semantics are to append its
 6827: execution semantics to the execution semantics of the current
 6828: definition.}
 6829: 
 6830: Unnamed words (@pxref{Anonymous Definitions}) cannot be encountered by
 6831: the text interpreter, ticked, or @code{postpone}d, so they have no
 6832: interpretation or compilation semantics.  Their behaviour is represented
 6833: by their XT (@pxref{Tokens for Words}), and we call it execution
 6834: semantics, too.
 6835: 
 6836: @comment TODO expand, make it co-operate with new sections on text interpreter.
 6837: 
 6838: @cindex immediate words
 6839: @cindex compile-only words
 6840: You can change the semantics of the most-recently defined word:
 6841: 
 6842: 
 6843: doc-immediate
 6844: doc-compile-only
 6845: doc-restrict
 6846: 
 6847: 
 6848: Note that ticking (@code{'}) a compile-only word gives an error
 6849: (``Interpreting a compile-only word'').
 6850: 
 6851: @menu
 6852: * Combined words::              
 6853: @end menu
 6854: 
 6855: 
 6856: @node Combined words,  , Interpretation and Compilation Semantics, Interpretation and Compilation Semantics
 6857: @subsection Combined Words
 6858: @cindex combined words
 6859: 
 6860: Gforth allows you to define @dfn{combined words} -- words that have an
 6861: arbitrary combination of interpretation and compilation semantics.
 6862: 
 6863: doc-interpret/compile:
 6864: 
 6865: This feature was introduced for implementing @code{TO} and @code{S"}. I
 6866: recommend that you do not define such words, as cute as they may be:
 6867: they make it hard to get at both parts of the word in some contexts.
 6868: E.g., assume you want to get an execution token for the compilation
 6869: part. Instead, define two words, one that embodies the interpretation
 6870: part, and one that embodies the compilation part.  Once you have done
 6871: that, you can define a combined word with @code{interpret/compile:} for
 6872: the convenience of your users.
 6873: 
 6874: You might try to use this feature to provide an optimizing
 6875: implementation of the default compilation semantics of a word. For
 6876: example, by defining:
 6877: @example
 6878: :noname
 6879:    foo bar ;
 6880: :noname
 6881:    POSTPONE foo POSTPONE bar ;
 6882: interpret/compile: opti-foobar
 6883: @end example
 6884: 
 6885: @noindent
 6886: as an optimizing version of:
 6887: 
 6888: @example
 6889: : foobar
 6890:     foo bar ;
 6891: @end example
 6892: 
 6893: Unfortunately, this does not work correctly with @code{[compile]},
 6894: because @code{[compile]} assumes that the compilation semantics of all
 6895: @code{interpret/compile:} words are non-default. I.e., @code{[compile]
 6896: opti-foobar} would compile compilation semantics, whereas
 6897: @code{[compile] foobar} would compile interpretation semantics.
 6898: 
 6899: @cindex state-smart words (are a bad idea)
 6900: Some people try to use @dfn{state-smart} words to emulate the feature provided
 6901: by @code{interpret/compile:} (words are state-smart if they check
 6902: @code{STATE} during execution). E.g., they would try to code
 6903: @code{foobar} like this:
 6904: 
 6905: @example
 6906: : foobar
 6907:   STATE @@
 6908:   IF ( compilation state )
 6909:     POSTPONE foo POSTPONE bar
 6910:   ELSE
 6911:     foo bar
 6912:   ENDIF ; immediate
 6913: @end example
 6914: 
 6915: Although this works if @code{foobar} is only processed by the text
 6916: interpreter, it does not work in other contexts (like @code{'} or
 6917: @code{POSTPONE}). E.g., @code{' foobar} will produce an execution token
 6918: for a state-smart word, not for the interpretation semantics of the
 6919: original @code{foobar}; when you execute this execution token (directly
 6920: with @code{EXECUTE} or indirectly through @code{COMPILE,}) in compile
 6921: state, the result will not be what you expected (i.e., it will not
 6922: perform @code{foo bar}). State-smart words are a bad idea. Simply don't
 6923: write them@footnote{For a more detailed discussion of this topic, see
 6924: M. Anton Ertl,
 6925: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,@code{State}-smartness---Why
 6926: it is Evil and How to Exorcise it}}, EuroForth '98.}!
 6927: 
 6928: @cindex defining words with arbitrary semantics combinations
 6929: It is also possible to write defining words that define words with
 6930: arbitrary combinations of interpretation and compilation semantics. In
 6931: general, they look like this:
 6932: 
 6933: @example
 6934: : def-word
 6935:     create-interpret/compile
 6936:     @i{code1}
 6937: interpretation>
 6938:     @i{code2}
 6939: <interpretation
 6940: compilation>
 6941:     @i{code3}
 6942: <compilation ;
 6943: @end example
 6944: 
 6945: For a @i{word} defined with @code{def-word}, the interpretation
 6946: semantics are to push the address of the body of @i{word} and perform
 6947: @i{code2}, and the compilation semantics are to push the address of
 6948: the body of @i{word} and perform @i{code3}. E.g., @code{constant}
 6949: can also be defined like this (except that the defined constants don't
 6950: behave correctly when @code{[compile]}d):
 6951: 
 6952: @example
 6953: : constant ( n "name" -- )
 6954:     create-interpret/compile
 6955:     ,
 6956: interpretation> ( -- n )
 6957:     @@
 6958: <interpretation
 6959: compilation> ( compilation. -- ; run-time. -- n )
 6960:     @@ postpone literal
 6961: <compilation ;
 6962: @end example
 6963: 
 6964: 
 6965: doc-create-interpret/compile
 6966: doc-interpretation>
 6967: doc-<interpretation
 6968: doc-compilation>
 6969: doc-<compilation
 6970: 
 6971: 
 6972: Words defined with @code{interpret/compile:} and
 6973: @code{create-interpret/compile} have an extended header structure that
 6974: differs from other words; however, unless you try to access them with
 6975: plain address arithmetic, you should not notice this. Words for
 6976: accessing the header structure usually know how to deal with this; e.g.,
 6977: @code{'} @i{word} @code{>body} also gives you the body of a word created
 6978: with @code{create-interpret/compile}.
 6979: 
 6980: 
 6981: doc-postpone
 6982: 
 6983: @comment TODO -- expand glossary text for POSTPONE
 6984: 
 6985: 
 6986: @c -------------------------------------------------------------
 6987: @node Tokens for Words, The Text Interpreter, Interpretation and Compilation Semantics, Words
 6988: @section Tokens for Words
 6989: @cindex tokens for words
 6990: 
 6991: This section describes the creation and use of tokens that represent
 6992: words.
 6993: 
 6994: @menu
 6995: * Execution token::             represents execution/interpretation semantics
 6996: * Compilation token::           represents compilation semantics
 6997: * Name token::                  represents named words
 6998: @end menu
 6999: 
 7000: @node Execution token, Compilation token, Tokens for Words, Tokens for Words
 7001: @subsection Execution token
 7002: 
 7003: @cindex xt
 7004: @cindex execution token
 7005: An @dfn{execution token} (@i{XT}) represents some behaviour of a word.
 7006: You can use @code{execute} to invoke this behaviour.
 7007: 
 7008: @cindex tick (')
 7009: You can use @code{'} to get an execution token that represents the
 7010: interpretation semantics of a named word:
 7011: 
 7012: @example
 7013: 5 ' .
 7014: execute
 7015: @end example
 7016: 
 7017: doc-'
 7018: 
 7019: @code{'} parses at run-time; there is also a word @code{[']} that parses
 7020: when it is compiled, and compiles the resulting XT:
 7021: 
 7022: @example
 7023: : foo ['] . execute ;
 7024: 5 foo
 7025: : bar ' execute ; \ by contrast,
 7026: 5 bar .           \ ' parses "." when bar executes
 7027: @end example
 7028: 
 7029: doc-[']
 7030: 
 7031: If you want the execution token of @i{word}, write @code{['] @i{word}}
 7032: in compiled code and @code{' @i{word}} in interpreted code.  Gforth's
 7033: @code{'} and @code{[']} behave somewhat unusually by complaining about
 7034: compile-only words (because these words have no interpretation
 7035: semantics).  You might get what you want by using @code{COMP' @i{word}
 7036: DROP} or @code{[COMP'] @i{word} DROP} (for details @pxref{Compilation
 7037: token}).
 7038: 
 7039: Another way to get an XT is @code{:noname} or @code{lastxt}
 7040: (@pxref{Anonymous Definitions}).  For anonymous words this gives an xt
 7041: for the only behaviour the word has (the execution semantics).  For
 7042: named words, @code{lastxt} produces an XT for the same behaviour it
 7043: would produce if the word was defined anonymously.
 7044: 
 7045: @example
 7046: :noname ." hello" ;
 7047: execute
 7048: @end example
 7049: 
 7050: An XT occupies one cell and can be manipulated like any other cell.
 7051: 
 7052: @cindex code field address
 7053: @cindex CFA
 7054: In ANS Forth the XT is just an abstract data type (i.e., defined by the
 7055: operations that produce or consume it).  For old hands: In Gforth, the
 7056: XT is implemented as a code field address (CFA).
 7057: 
 7058: @c !! discuss "compile," some more (or in Macros).
 7059: 
 7060: doc-execute
 7061: doc-perform
 7062: doc-compile,
 7063: 
 7064: @node Compilation token, Name token, Execution token, Tokens for Words
 7065: @subsection Compilation token
 7066: 
 7067: @cindex compilation token
 7068: @cindex CT (compilation token)
 7069: Gforth represents the compilation semantics of a named word by a
 7070: @dfn{compilation token} consisting of two cells: @i{w xt}. The top cell
 7071: @i{xt} is an execution token. The compilation semantics represented by
 7072: the compilation token can be performed with @code{execute}, which
 7073: consumes the whole compilation token, with an additional stack effect
 7074: determined by the represented compilation semantics.
 7075: 
 7076: At present, the @i{w} part of a compilation token is an execution token,
 7077: and the @i{xt} part represents either @code{execute} or
 7078: @code{compile,}@footnote{Depending upon the compilation semantics of the
 7079: word. If the word has default compilation semantics, the @i{xt} will
 7080: represent @code{compile,}. Otherwise (e.g., for immediate words), the
 7081: @i{xt} will represent @code{execute}.}. However, don't rely on that
 7082: knowledge, unless necessary; future versions of Gforth may introduce
 7083: unusual compilation tokens (e.g., a compilation token that represents
 7084: the compilation semantics of a literal).
 7085: 
 7086: You can perform the compilation semantics represented by the compilation
 7087: token with @code{execute}.  You can compile the compilation semantics
 7088: with @code{postpone,}. I.e., @code{COMP' @i{word} postpone,} is
 7089: equivalent to @code{postpone @i{word}}.
 7090: 
 7091: doc-[comp']
 7092: doc-comp'
 7093: doc-postpone,
 7094: 
 7095: @node Name token,  , Compilation token, Tokens for Words
 7096: @subsection Name token
 7097: 
 7098: @cindex name token
 7099: @cindex name field address
 7100: @cindex NFA
 7101: Gforth represents named words by the @dfn{name token}, (@i{nt}). In
 7102: Gforth, the abstract data type @emph{name token} is implemented as a
 7103: name field address (NFA).
 7104: 
 7105: doc-find-name
 7106: doc-name>int
 7107: doc-name?int
 7108: doc-name>comp
 7109: doc-name>string
 7110: 
 7111: 
 7112: @c ----------------------------------------------------------
 7113: @node The Text Interpreter, Word Lists, Tokens for Words, Words
 7114: @section  The Text Interpreter
 7115: @cindex interpreter - outer
 7116: @cindex text interpreter
 7117: @cindex outer interpreter
 7118: 
 7119: @c Should we really describe all these ugly details?  IMO the text
 7120: @c interpreter should be much cleaner, but that may not be possible within
 7121: @c ANS Forth. - anton
 7122: @c nac-> I wanted to explain how it works to show how you can exploit
 7123: @c it in your own programs. When I was writing a cross-compiler, figuring out
 7124: @c some of these gory details was very helpful to me. None of the textbooks
 7125: @c I've seen cover it, and the most modern Forth textbook -- Forth Inc's,
 7126: @c seems to positively avoid going into too much detail for some of
 7127: @c the internals.
 7128: 
 7129: @c anton: ok.  I wonder, though, if this is the right place; for some stuff
 7130: @c it is; for the ugly details, I would prefer another place.  I wonder
 7131: @c whether we should have a chapter before "Words" that describes some
 7132: @c basic concepts referred to in words, and a chapter after "Words" that
 7133: @c describes implementation details.
 7134: 
 7135: The text interpreter@footnote{This is an expanded version of the
 7136: material in @ref{Introducing the Text Interpreter}.} is an endless loop
 7137: that processes input from the current input device. It is also called
 7138: the outer interpreter, in contrast to the inner interpreter
 7139: (@pxref{Engine}) which executes the compiled Forth code on interpretive
 7140: implementations.
 7141: 
 7142: @cindex interpret state
 7143: @cindex compile state
 7144: The text interpreter operates in one of two states: @dfn{interpret
 7145: state} and @dfn{compile state}. The current state is defined by the
 7146: aptly-named variable @code{state}.
 7147: 
 7148: This section starts by describing how the text interpreter behaves when
 7149: it is in interpret state, processing input from the user input device --
 7150: the keyboard. This is the mode that a Forth system is in after it starts
 7151: up.
 7152: 
 7153: @cindex input buffer
 7154: @cindex terminal input buffer
 7155: The text interpreter works from an area of memory called the @dfn{input
 7156: buffer}@footnote{When the text interpreter is processing input from the
 7157: keyboard, this area of memory is called the @dfn{terminal input buffer}
 7158: (TIB) and is addressed by the (obsolescent) words @code{TIB} and
 7159: @code{#TIB}.}, which stores your keyboard input when you press the
 7160: @key{RET} key. Starting at the beginning of the input buffer, it skips
 7161: leading spaces (called @dfn{delimiters}) then parses a string (a
 7162: sequence of non-space characters) until it reaches either a space
 7163: character or the end of the buffer. Having parsed a string, it makes two
 7164: attempts to process it:
 7165: 
 7166: @cindex dictionary
 7167: @itemize @bullet
 7168: @item
 7169: It looks for the string in a @dfn{dictionary} of definitions. If the
 7170: string is found, the string names a @dfn{definition} (also known as a
 7171: @dfn{word}) and the dictionary search returns information that allows
 7172: the text interpreter to perform the word's @dfn{interpretation
 7173: semantics}. In most cases, this simply means that the word will be
 7174: executed.
 7175: @item
 7176: If the string is not found in the dictionary, the text interpreter
 7177: attempts to treat it as a number, using the rules described in
 7178: @ref{Number Conversion}. If the string represents a legal number in the
 7179: current radix, the number is pushed onto a parameter stack (the data
 7180: stack for integers, the floating-point stack for floating-point
 7181: numbers).
 7182: @end itemize
 7183: 
 7184: If both attempts fail, or if the word is found in the dictionary but has
 7185: no interpretation semantics@footnote{This happens if the word was
 7186: defined as @code{COMPILE-ONLY}.} the text interpreter discards the
 7187: remainder of the input buffer, issues an error message and waits for
 7188: more input. If one of the attempts succeeds, the text interpreter
 7189: repeats the parsing process until the whole of the input buffer has been
 7190: processed, at which point it prints the status message ``@code{ ok}''
 7191: and waits for more input.
 7192: 
 7193: @c anton: this should be in the input stream subsection (or below it)
 7194: 
 7195: @cindex parse area
 7196: The text interpreter keeps track of its position in the input buffer by
 7197: updating a variable called @code{>IN} (pronounced ``to-in''). The value
 7198: of @code{>IN} starts out as 0, indicating an offset of 0 from the start
 7199: of the input buffer. The region from offset @code{>IN @@} to the end of
 7200: the input buffer is called the @dfn{parse area}@footnote{In other words,
 7201: the text interpreter processes the contents of the input buffer by
 7202: parsing strings from the parse area until the parse area is empty.}.
 7203: This example shows how @code{>IN} changes as the text interpreter parses
 7204: the input buffer:
 7205: 
 7206: @example
 7207: : remaining >IN @@ SOURCE 2 PICK - -ROT + SWAP
 7208:   CR ." ->" TYPE ." <-" ; IMMEDIATE 
 7209: 
 7210: 1 2 3 remaining + remaining . 
 7211: 
 7212: : foo 1 2 3 remaining SWAP remaining ;
 7213: @end example
 7214: 
 7215: @noindent
 7216: The result is:
 7217: 
 7218: @example
 7219: ->+ remaining .<-
 7220: ->.<-5  ok
 7221: 
 7222: ->SWAP remaining ;-<
 7223: ->;<-  ok
 7224: @end example
 7225: 
 7226: @cindex parsing words
 7227: The value of @code{>IN} can also be modified by a word in the input
 7228: buffer that is executed by the text interpreter.  This means that a word
 7229: can ``trick'' the text interpreter into either skipping a section of the
 7230: input buffer@footnote{This is how parsing words work.} or into parsing a
 7231: section twice. For example:
 7232: 
 7233: @example
 7234: : lat ." <<foo>>" ;
 7235: : flat ." <<bar>>" >IN DUP @@ 3 - SWAP ! ;
 7236: @end example
 7237: 
 7238: @noindent
 7239: When @code{flat} is executed, this output is produced@footnote{Exercise
 7240: for the reader: what would happen if the @code{3} were replaced with
 7241: @code{4}?}:
 7242: 
 7243: @example
 7244: <<bar>><<foo>>
 7245: @end example
 7246: 
 7247: This technique can be used to work around some of the interoperability
 7248: problems of parsing words.  Of course, it's better to avoid parsing
 7249: words where possible.
 7250: 
 7251: @noindent
 7252: Two important notes about the behaviour of the text interpreter:
 7253: 
 7254: @itemize @bullet
 7255: @item
 7256: It processes each input string to completion before parsing additional
 7257: characters from the input buffer.
 7258: @item
 7259: It treats the input buffer as a read-only region (and so must your code).
 7260: @end itemize
 7261: 
 7262: @noindent
 7263: When the text interpreter is in compile state, its behaviour changes in
 7264: these ways:
 7265: 
 7266: @itemize @bullet
 7267: @item
 7268: If a parsed string is found in the dictionary, the text interpreter will
 7269: perform the word's @dfn{compilation semantics}. In most cases, this
 7270: simply means that the execution semantics of the word will be appended
 7271: to the current definition.
 7272: @item
 7273: When a number is encountered, it is compiled into the current definition
 7274: (as a literal) rather than being pushed onto a parameter stack.
 7275: @item
 7276: If an error occurs, @code{state} is modified to put the text interpreter
 7277: back into interpret state.
 7278: @item
 7279: Each time a line is entered from the keyboard, Gforth prints
 7280: ``@code{ compiled}'' rather than `` @code{ok}''.
 7281: @end itemize
 7282: 
 7283: @cindex text interpreter - input sources
 7284: When the text interpreter is using an input device other than the
 7285: keyboard, its behaviour changes in these ways:
 7286: 
 7287: @itemize @bullet
 7288: @item
 7289: When the parse area is empty, the text interpreter attempts to refill
 7290: the input buffer from the input source. When the input source is
 7291: exhausted, the input source is set back to the previous input source.
 7292: @item
 7293: It doesn't print out ``@code{ ok}'' or ``@code{ compiled}'' messages each
 7294: time the parse area is emptied.
 7295: @item
 7296: If an error occurs, the input source is set back to the user input
 7297: device.
 7298: @end itemize
 7299: 
 7300: You can read about this in more detail in @ref{Input Sources}.
 7301: 
 7302: doc->in
 7303: doc-source
 7304: 
 7305: doc-tib
 7306: doc-#tib
 7307: 
 7308: 
 7309: @menu
 7310: * Input Sources::               
 7311: * Number Conversion::           
 7312: * Interpret/Compile states::    
 7313: * Literals::                    
 7314: * Interpreter Directives::      
 7315: @end menu
 7316: 
 7317: @node Input Sources, Number Conversion, The Text Interpreter, The Text Interpreter
 7318: @subsection Input Sources
 7319: @cindex input sources
 7320: @cindex text interpreter - input sources
 7321: 
 7322: By default, the text interpreter processes input from the user input
 7323: device (the keyboard) when Forth starts up. The text interpreter can
 7324: process input from any of these sources:
 7325: 
 7326: @itemize @bullet
 7327: @item
 7328: The user input device -- the keyboard.
 7329: @item
 7330: A file, using the words described in @ref{Forth source files}.
 7331: @item
 7332: A block, using the words described in @ref{Blocks}.
 7333: @item
 7334: A text string, using @code{evaluate}.
 7335: @end itemize
 7336: 
 7337: A program can identify the current input device from the values of
 7338: @code{source-id} and @code{blk}.
 7339: 
 7340: 
 7341: doc-source-id
 7342: doc-blk
 7343: 
 7344: doc-save-input
 7345: doc-restore-input
 7346: 
 7347: doc-evaluate
 7348: 
 7349: 
 7350: 
 7351: @node Number Conversion, Interpret/Compile states, Input Sources, The Text Interpreter
 7352: @subsection Number Conversion
 7353: @cindex number conversion
 7354: @cindex double-cell numbers, input format
 7355: @cindex input format for double-cell numbers
 7356: @cindex single-cell numbers, input format
 7357: @cindex input format for single-cell numbers
 7358: @cindex floating-point numbers, input format
 7359: @cindex input format for floating-point numbers
 7360: 
 7361: This section describes the rules that the text interpreter uses when it
 7362: tries to convert a string into a number.
 7363: 
 7364: Let <digit> represent any character that is a legal digit in the current
 7365: number base@footnote{For example, 0-9 when the number base is decimal or
 7366: 0-9, A-F when the number base is hexadecimal.}.
 7367: 
 7368: Let <decimal digit> represent any character in the range 0-9.
 7369: 
 7370: Let @{@i{a b}@} represent the @i{optional} presence of any of the characters
 7371: in the braces (@i{a} or @i{b} or neither).
 7372: 
 7373: Let * represent any number of instances of the previous character
 7374: (including none).
 7375: 
 7376: Let any other character represent itself.
 7377: 
 7378: @noindent
 7379: Now, the conversion rules are:
 7380: 
 7381: @itemize @bullet
 7382: @item
 7383: A string of the form <digit><digit>* is treated as a single-precision
 7384: (cell-sized) positive integer. Examples are 0 123 6784532 32343212343456 42
 7385: @item
 7386: A string of the form -<digit><digit>* is treated as a single-precision
 7387: (cell-sized) negative integer, and is represented using 2's-complement
 7388: arithmetic. Examples are -45 -5681 -0
 7389: @item
 7390: A string of the form <digit><digit>*.<digit>* is treated as a double-precision
 7391: (double-cell-sized) positive integer. Examples are 3465. 3.465 34.65
 7392: (all three of these represent the same number).
 7393: @item
 7394: A string of the form -<digit><digit>*.<digit>* is treated as a
 7395: double-precision (double-cell-sized) negative integer, and is
 7396: represented using 2's-complement arithmetic. Examples are -3465. -3.465
 7397: -34.65 (all three of these represent the same number).
 7398: @item
 7399: A string of the form @{+ -@}<decimal digit>@{.@}<decimal digit>*@{e
 7400: E@}@{+ -@}<decimal digit><decimal digit>* is treated as a floating-point
 7401: number. Examples are 1e 1e0 1.e 1.e0 +1e+0 (which all represent the same
 7402: number) +12.E-4
 7403: @end itemize
 7404: 
 7405: By default, the number base used for integer number conversion is given
 7406: by the contents of the variable @code{base}.  Note that a lot of
 7407: confusion can result from unexpected values of @code{base}.  If you
 7408: change @code{base} anywhere, make sure to save the old value and restore
 7409: it afterwards.  In general I recommend keeping @code{base} decimal, and
 7410: using the prefixes described below for the popular non-decimal bases.
 7411: 
 7412: doc-dpl
 7413: doc-base
 7414: doc-hex
 7415: doc-decimal
 7416: 
 7417: 
 7418: @cindex '-prefix for character strings
 7419: @cindex &-prefix for decimal numbers
 7420: @cindex %-prefix for binary numbers
 7421: @cindex $-prefix for hexadecimal numbers
 7422: Gforth allows you to override the value of @code{base} by using a
 7423: prefix@footnote{Some Forth implementations provide a similar scheme by
 7424: implementing @code{$} etc. as parsing words that process the subsequent
 7425: number in the input stream and push it onto the stack. For example, see
 7426: @cite{Number Conversion and Literals}, by Wil Baden; Forth Dimensions
 7427: 20(3) pages 26--27. In such implementations, unlike in Gforth, a space
 7428: is required between the prefix and the number.} before the first digit
 7429: of an (integer) number. Four prefixes are supported:
 7430: 
 7431: @itemize @bullet
 7432: @item
 7433: @code{&} -- decimal
 7434: @item
 7435: @code{%} -- binary
 7436: @item
 7437: @code{$} -- hexadecimal
 7438: @item
 7439: @code{'} -- base @code{max-char+1}
 7440: @end itemize
 7441: 
 7442: Here are some examples, with the equivalent decimal number shown after
 7443: in braces:
 7444: 
 7445: -$41 (-65), %1001101 (205), %1001.0001 (145 - a double-precision number),
 7446: 'AB (16706; ascii A is 65, ascii B is 66, number is 65*256 + 66),
 7447: 'ab (24930; ascii a is 97, ascii B is 98, number is 97*256 + 98),
 7448: &905 (905), $abc (2478), $ABC (2478).
 7449: 
 7450: @cindex number conversion - traps for the unwary
 7451: @noindent
 7452: Number conversion has a number of traps for the unwary:
 7453: 
 7454: @itemize @bullet
 7455: @item
 7456: You cannot determine the current number base using the code sequence
 7457: @code{base @@ .} -- the number base is always 10 in the current number
 7458: base. Instead, use something like @code{base @@ dec.}
 7459: @item
 7460: If the number base is set to a value greater than 14 (for example,
 7461: hexadecimal), the number 123E4 is ambiguous; the conversion rules allow
 7462: it to be intepreted as either a single-precision integer or a
 7463: floating-point number (Gforth treats it as an integer). The ambiguity
 7464: can be resolved by explicitly stating the sign of the mantissa and/or
 7465: exponent: 123E+4 or +123E4 -- if the number base is decimal, no
 7466: ambiguity arises; either representation will be treated as a
 7467: floating-point number.
 7468: @item
 7469: There is a word @code{bin} but it does @i{not} set the number base!
 7470: It is used to specify file types.
 7471: @item
 7472: ANS Forth requires the @code{.} of a double-precision number to
 7473: be the final character in the string. Allowing the @code{.} to be
 7474: anywhere after the first digit is a Gforth extension.
 7475: @item
 7476: The number conversion process does not check for overflow.
 7477: @item
 7478: In Gforth, number conversion to floating-point numbers always use base
 7479: 10, irrespective of the value of @code{base}. In ANS Forth,
 7480: conversion to floating-point numbers whilst the value of
 7481: @code{base} is not 10 is an ambiguous condition.
 7482: @end itemize
 7483: 
 7484: You can read numbers into your programs with the words described in
 7485: @ref{Input}.
 7486: 
 7487: @node Interpret/Compile states, Literals, Number Conversion, The Text Interpreter
 7488: @subsection Interpret/Compile states
 7489: @cindex Interpret/Compile states
 7490: 
 7491: A standard program is not permitted to change @code{state}
 7492: explicitly. However, it can change @code{state} implicitly, using the
 7493: words @code{[} and @code{]}. When @code{[} is executed it switches
 7494: @code{state} to interpret state, and therefore the text interpreter
 7495: starts interpreting. When @code{]} is executed it switches @code{state}
 7496: to compile state and therefore the text interpreter starts
 7497: compiling. The most common usage for these words is for switching into
 7498: interpret state and back from within a colon definition; this technique
 7499: can be used to compile a literal (for an example, @pxref{Literals}) or
 7500: for conditional compilation (for an example, @pxref{Interpreter
 7501: Directives}).
 7502: 
 7503: 
 7504: @c This is a bad example: It's non-standard, and it's not necessary.
 7505: @c However, I can't think of a good example for switching into compile
 7506: @c state when there is no current word (@code{state}-smart words are not a
 7507: @c good reason).  So maybe we should use an example for switching into
 7508: @c interpret @code{state} in a colon def. - anton
 7509: @c nac-> I agree. I started out by putting in the example, then realised
 7510: @c that it was non-ANS, so wrote more words around it. I hope this
 7511: @c re-written version is acceptable to you. I do want to keep the example
 7512: @c as it is helpful for showing what is and what is not portable, particularly
 7513: @c where it outlaws a style in common use.
 7514: 
 7515: 
 7516: @code{[} and @code{]} also give you the ability to switch into compile
 7517: state and back, but we cannot think of any useful Standard application
 7518: for this ability. Pre-ANS Forth textbooks have examples like this:
 7519: 
 7520: @example
 7521: : AA ." this is A" ;
 7522: : BB ." this is B" ;
 7523: : CC ." this is C" ;
 7524: 
 7525: create table ] aa bb cc [
 7526: 
 7527: : go ( n -- ) \ n is offset into table.. 0 for 1st entry
 7528:   cells table + @ execute ;
 7529: @end example
 7530: 
 7531: This example builds a jump table; @code{0 go} will display ``@code{this
 7532: is A}''. Using @code{[} and @code{]} in this example is equivalent to
 7533: defining @code{table} like this:
 7534: 
 7535: @example
 7536: create table ' aa COMPILE, ' bb COMPILE, ' cc COMPILE,
 7537: @end example
 7538: 
 7539: The problem with this code is that the definition of @code{table} is not
 7540: portable -- it @i{compile}s execution tokens into code space. Whilst it
 7541: @i{may} work on systems where code space and data space co-incide, the
 7542: Standard only allows data space to be assigned for a @code{CREATE}d
 7543: word. In addition, the Standard only allows @code{@@} to access data
 7544: space, whilst this example is using it to access code space. The only
 7545: portable, Standard way to build this table is to build it in data space,
 7546: like this:
 7547: 
 7548: @example
 7549: create table ' aa , ' bb , ' cc ,
 7550: @end example
 7551: 
 7552: doc-state
 7553: doc-[
 7554: doc-]
 7555: 
 7556: 
 7557: @node Literals, Interpreter Directives, Interpret/Compile states, The Text Interpreter
 7558: @subsection Literals
 7559: @cindex Literals
 7560: 
 7561: Often, you want to use a number within a colon definition. When you do
 7562: this, the text interpreter automatically compiles the number as a
 7563: @i{literal}. A literal is a number whose run-time effect is to be pushed
 7564: onto the stack.  If you had to do some maths to generate the number, you
 7565: might write it like this:
 7566: 
 7567: @example
 7568: : HOUR-TO-SEC ( n1 -- n2 )
 7569:   60 *      \ to minutes
 7570:   60 * ;    \ to seconds
 7571: @end example
 7572: 
 7573: It is very clear what this definition is doing, but it's inefficient
 7574: since it is performing 2 multiples at run-time. An alternative would be
 7575: to write:
 7576: 
 7577: @example
 7578: : HOUR-TO-SEC ( n1 -- n2 )
 7579:   3600 * ;  \ to seconds
 7580: @end example
 7581: 
 7582: Which does the same thing, and has the advantage of using a single
 7583: multiply. Ideally, we'd like the efficiency of the second with the
 7584: readability of the first.
 7585: 
 7586: @code{Literal} allows us to achieve that. It takes a number from the
 7587: stack and lays it down in the current definition just as though the
 7588: number had been typed directly into the definition. Our first attempt
 7589: might look like this:
 7590: 
 7591: @example
 7592: 60          \ mins per hour
 7593: 60 *        \ seconds per minute
 7594: : HOUR-TO-SEC ( n1 -- n2 )
 7595:   Literal * ;  \ to seconds
 7596: @end example
 7597: 
 7598: But this produces the error message @code{unstructured}. What happened?
 7599: The stack notation for @code{:} is (@i{ -- colon-sys}) and the size of
 7600: @i{colon-sys} is implementation-defined. In other words, once we start a
 7601: colon definition we can't portably access anything that was on the stack
 7602: before the definition began@footnote{@cite{Two Problems in ANS Forth},
 7603: by Thomas Worthington; Forth Dimensions 20(2) pages 32--34 describes
 7604: some situations where you might want to access stack items above
 7605: colon-sys, and provides a solution to the problem.}. The correct way of
 7606: solving this problem in this instance is to use @code{[ ]} like this:
 7607: 
 7608: @example
 7609: : HOUR-TO-SEC ( n1 -- n2 )
 7610:   [ 60          \ minutes per hour
 7611:     60 * ]      \ seconds per minute
 7612:   LITERAL * ;   \ to seconds
 7613: @end example
 7614: 
 7615: 
 7616: doc-literal
 7617: doc-]L
 7618: doc-2literal
 7619: doc-fliteral
 7620: 
 7621: 
 7622: @node Interpreter Directives,  , Literals, The Text Interpreter
 7623: @subsection Interpreter Directives
 7624: @cindex interpreter directives
 7625: 
 7626: These words are usually used in interpret state; typically to control
 7627: which parts of a source file are processed by the text
 7628: interpreter. There are only a few ANS Forth Standard words, but Gforth
 7629: supplements these with a rich set of immediate control structure words
 7630: to compensate for the fact that the non-immediate versions can only be
 7631: used in compile state (@pxref{Control Structures}). Typical usages:
 7632: 
 7633: @example
 7634: FALSE Constant ASSEMBLER
 7635: .
 7636: .
 7637: ASSEMBLER [IF]
 7638: : ASSEMBLER-FEATURE
 7639:   ...
 7640: ;
 7641: [ENDIF]
 7642: .
 7643: .
 7644: : SEE
 7645:   ... \ general-purpose SEE code
 7646:   [ ASSEMBLER [IF] ]
 7647:   ... \ assembler-specific SEE code
 7648:   [ [ENDIF] ]
 7649: ;
 7650: @end example
 7651: 
 7652: 
 7653: doc-[IF]
 7654: doc-[ELSE]
 7655: doc-[THEN]
 7656: doc-[ENDIF]
 7657: 
 7658: doc-[IFDEF]
 7659: doc-[IFUNDEF]
 7660: 
 7661: doc-[?DO]
 7662: doc-[DO]
 7663: doc-[FOR]
 7664: doc-[LOOP]
 7665: doc-[+LOOP]
 7666: doc-[NEXT]
 7667: 
 7668: doc-[BEGIN]
 7669: doc-[UNTIL]
 7670: doc-[AGAIN]
 7671: doc-[WHILE]
 7672: doc-[REPEAT]
 7673: 
 7674: 
 7675: @c -------------------------------------------------------------
 7676: @node Word Lists, Environmental Queries, The Text Interpreter, Words
 7677: @section Word Lists
 7678: @cindex word lists
 7679: @cindex header space
 7680: 
 7681: A wordlist is a list of named words; you can add new words and look up
 7682: words by name (and you can remove words in a restricted way with
 7683: markers).  Every named (and @code{reveal}ed) word is in one wordlist.
 7684: 
 7685: @cindex search order stack
 7686: The text interpreter searches the wordlists present in the search order
 7687: (a stack of wordlists), from the top to the bottom.  Within each
 7688: wordlist, the search starts conceptually at the newest word; i.e., if
 7689: two words in a wordlist have the same name, the newer word is found.
 7690: 
 7691: @cindex compilation word list
 7692: New words are added to the @dfn{compilation wordlist} (aka current
 7693: wordlist).
 7694: 
 7695: @cindex wid
 7696: A word list is identified by a cell-sized word list identifier (@i{wid})
 7697: in much the same way as a file is identified by a file handle. The
 7698: numerical value of the wid has no (portable) meaning, and might change
 7699: from session to session.
 7700: 
 7701: The ANS Forth ``Search order'' word set is intended to provide a set of
 7702: low-level tools that allow various different schemes to be
 7703: implemented. Gforth provides @code{vocabulary}, a traditional Forth
 7704: word.  @file{compat/vocabulary.fs} provides an implementation in ANS
 7705: Forth.
 7706: 
 7707: @comment TODO: locals section refers to here, saying that every word list (aka
 7708: @comment vocabulary) has its own methods for searching etc. Need to document that.
 7709: 
 7710: @comment TODO: document markers, reveal, tables, mappedwordlist
 7711: 
 7712: @comment the gforthman- prefix is used to pick out the true definition of a
 7713: @comment word from the source files, rather than some alias.
 7714: 
 7715: doc-forth-wordlist
 7716: doc-definitions
 7717: doc-get-current
 7718: doc-set-current
 7719: doc-get-order
 7720: doc---gforthman-set-order
 7721: doc-wordlist
 7722: doc-table
 7723: doc-push-order
 7724: doc-previous
 7725: doc-also
 7726: doc---gforthman-forth
 7727: doc-only
 7728: doc---gforthman-order
 7729: 
 7730: doc-find
 7731: doc-search-wordlist
 7732: 
 7733: doc-words
 7734: doc-vlist
 7735: @c doc-words-deferred
 7736: 
 7737: doc-mappedwordlist
 7738: doc-root
 7739: doc-vocabulary
 7740: doc-seal
 7741: doc-vocs
 7742: doc-current
 7743: doc-context
 7744: 
 7745: 
 7746: @menu
 7747: * Why use word lists?::         
 7748: * Word list examples::          
 7749: @end menu
 7750: 
 7751: @node Why use word lists?, Word list examples, Word Lists, Word Lists
 7752: @subsection Why use word lists?
 7753: @cindex word lists - why use them?
 7754: 
 7755: Here are some reasons for using multiple word lists:
 7756: 
 7757: @itemize @bullet
 7758: @item
 7759: To improve compilation speed by reducing the number of header space
 7760: entries that must be searched. This is achieved by creating a new
 7761: word list that contains all of the definitions that are used in the
 7762: definition of a Forth system but which would not usually be used by
 7763: programs running on that system. That word list would be on the search
 7764: list when the Forth system was compiled but would be removed from the
 7765: search list for normal operation. This can be a useful technique for
 7766: low-performance systems (for example, 8-bit processors in embedded
 7767: systems) but is unlikely to be necessary in high-performance desktop
 7768: systems.
 7769: @item
 7770: To prevent a set of words from being used outside the context in which
 7771: they are valid. Two classic examples of this are an integrated editor
 7772: (all of the edit commands are defined in a separate word list; the
 7773: search order is set to the editor word list when the editor is invoked;
 7774: the old search order is restored when the editor is terminated) and an
 7775: integrated assembler (the op-codes for the machine are defined in a
 7776: separate word list which is used when a @code{CODE} word is defined).
 7777: @item
 7778: To prevent a name-space clash between multiple definitions with the same
 7779: name. For example, when building a cross-compiler you might have a word
 7780: @code{IF} that generates conditional code for your target system. By
 7781: placing this definition in a different word list you can control whether
 7782: the host system's @code{IF} or the target system's @code{IF} get used in
 7783: any particular context by controlling the order of the word lists on the
 7784: search order stack.
 7785: @end itemize
 7786: 
 7787: @node Word list examples,  , Why use word lists?, Word Lists
 7788: @subsection Word list examples
 7789: @cindex word lists - examples
 7790: 
 7791: Here is an example of creating and using a new wordlist using ANS
 7792: Forth Standard words:
 7793: 
 7794: @example
 7795: wordlist constant my-new-words-wordlist
 7796: : my-new-words get-order nip my-new-words-wordlist swap set-order ;
 7797: 
 7798: \ add it to the search order
 7799: also my-new-words
 7800: 
 7801: \ alternatively, add it to the search order and make it
 7802: \ the compilation word list
 7803: also my-new-words definitions
 7804: \ type "order" to see the problem
 7805: @end example
 7806: 
 7807: The problem with this example is that @code{order} has no way to
 7808: associate the name @code{my-new-words} with the wid of the word list (in
 7809: Gforth, @code{order} and @code{vocs} will display @code{???}  for a wid
 7810: that has no associated name). There is no Standard way of associating a
 7811: name with a wid.
 7812: 
 7813: In Gforth, this example can be re-coded using @code{vocabulary}, which
 7814: associates a name with a wid:
 7815: 
 7816: @example
 7817: vocabulary my-new-words
 7818: 
 7819: \ add it to the search order
 7820: also my-new-words
 7821: 
 7822: \ alternatively, add it to the search order and make it
 7823: \ the compilation word list
 7824: my-new-words definitions
 7825: \ type "order" to see that the problem is solved
 7826: @end example
 7827: 
 7828: @c -------------------------------------------------------------
 7829: @node Environmental Queries, Files, Word Lists, Words
 7830: @section Environmental Queries
 7831: @cindex environmental queries
 7832: 
 7833: ANS Forth introduced the idea of ``environmental queries'' as a way
 7834: for a program running on a system to determine certain characteristics of the system.
 7835: The Standard specifies a number of strings that might be recognised by a system.
 7836: 
 7837: The Standard requires that the header space used for environmental queries
 7838: be distinct from the header space used for definitions.
 7839: 
 7840: Typically, environmental queries are supported by creating a set of
 7841: definitions in a word list that is @i{only} used during environmental
 7842: queries; that is what Gforth does. There is no Standard way of adding
 7843: definitions to the set of recognised environmental queries, but any
 7844: implementation that supports the loading of optional word sets must have
 7845: some mechanism for doing this (after loading the word set, the
 7846: associated environmental query string must return @code{true}). In
 7847: Gforth, the word list used to honour environmental queries can be
 7848: manipulated just like any other word list.
 7849: 
 7850: 
 7851: doc-environment?
 7852: doc-environment-wordlist
 7853: 
 7854: doc-gforth
 7855: doc-os-class
 7856: 
 7857: 
 7858: Note that, whilst the documentation for (e.g.) @code{gforth} shows it
 7859: returning two items on the stack, querying it using @code{environment?}
 7860: will return an additional item; the @code{true} flag that shows that the
 7861: string was recognised.
 7862: 
 7863: @comment TODO Document the standard strings or note where they are documented herein
 7864: 
 7865: Here are some examples of using environmental queries:
 7866: 
 7867: @example
 7868: s" address-unit-bits" environment? 0=
 7869: [IF]
 7870:      cr .( environmental attribute address-units-bits unknown... ) cr
 7871: [THEN]
 7872: 
 7873: s" block" environment? [IF] DROP include block.fs [THEN]
 7874: 
 7875: s" gforth" environment? [IF] 2DROP include compat/vocabulary.fs [THEN]
 7876: 
 7877: s" gforth" environment? [IF] .( Gforth version ) TYPE
 7878:                         [ELSE] .( Not Gforth..) [THEN]
 7879: @end example
 7880: 
 7881: 
 7882: Here is an example of adding a definition to the environment word list:
 7883: 
 7884: @example
 7885: get-current environment-wordlist set-current
 7886: true constant block
 7887: true constant block-ext
 7888: set-current
 7889: @end example
 7890: 
 7891: You can see what definitions are in the environment word list like this:
 7892: 
 7893: @example
 7894: get-order 1+ environment-wordlist swap set-order words previous
 7895: @end example
 7896: 
 7897: 
 7898: @c -------------------------------------------------------------
 7899: @node Files, Blocks, Environmental Queries, Words
 7900: @section Files
 7901: @cindex files
 7902: @cindex I/O - file-handling
 7903: 
 7904: Gforth provides facilities for accessing files that are stored in the
 7905: host operating system's file-system. Files that are processed by Gforth
 7906: can be divided into two categories:
 7907: 
 7908: @itemize @bullet
 7909: @item
 7910: Files that are processed by the Text Interpreter (@dfn{Forth source files}).
 7911: @item
 7912: Files that are processed by some other program (@dfn{general files}).
 7913: @end itemize
 7914: 
 7915: doc-loadfilename
 7916: doc-sourcefilename
 7917: doc-sourceline#
 7918: 
 7919: @menu
 7920: * Forth source files::          
 7921: * General files::               
 7922: * Search Paths::                
 7923: @end menu
 7924: 
 7925: 
 7926: @c -------------------------------------------------------------
 7927: @node Forth source files, General files, Files, Files
 7928: @subsection Forth source files
 7929: @cindex including files
 7930: @cindex Forth source files
 7931: 
 7932: The simplest way to interpret the contents of a file is to use one of
 7933: these two formats:
 7934: 
 7935: @example
 7936: include mysource.fs
 7937: s" mysource.fs" included
 7938: @end example
 7939: 
 7940: Sometimes you want to include a file only if it is not included already
 7941: (by, say, another source file). In that case, you can use one of these
 7942: three formats:
 7943: 
 7944: @example
 7945: require mysource.fs
 7946: needs mysource.fs
 7947: s" mysource.fs" required
 7948: @end example
 7949: 
 7950: @cindex stack effect of included files
 7951: @cindex including files, stack effect
 7952: It is good practice to write your source files such that interpreting them
 7953: does not change the stack. Source files designed in this way can be used with
 7954: @code{required} and friends without complications. For example:
 7955: 
 7956: @example
 7957: 1 require foo.fs drop
 7958: @end example
 7959: 
 7960: 
 7961: doc-include-file
 7962: doc-included
 7963: doc-included?
 7964: doc-include
 7965: doc-required
 7966: doc-require
 7967: doc-needs
 7968: doc-init-included-files
 7969: 
 7970: 
 7971: A definition in ANS Forth for @code{required} is provided in
 7972: @file{compat/required.fs}.
 7973: 
 7974: @c -------------------------------------------------------------
 7975: @node General files, Search Paths, Forth source files, Files
 7976: @subsection General files
 7977: @cindex general files
 7978: @cindex file-handling
 7979: 
 7980: Files are opened/created by name and type. The following types are
 7981: recognised:
 7982: 
 7983: 
 7984: doc-r/o
 7985: doc-r/w
 7986: doc-w/o
 7987: doc-bin
 7988: 
 7989: 
 7990: When a file is opened/created, it returns a file identifier,
 7991: @i{wfileid} that is used for all other file commands. All file
 7992: commands also return a status value, @i{wior}, that is 0 for a
 7993: successful operation and an implementation-defined non-zero value in the
 7994: case of an error.
 7995: 
 7996: 
 7997: doc-open-file
 7998: doc-create-file
 7999: 
 8000: doc-close-file
 8001: doc-delete-file
 8002: doc-rename-file
 8003: doc-read-file
 8004: doc-read-line
 8005: doc-write-file
 8006: doc-write-line
 8007: doc-emit-file
 8008: doc-flush-file
 8009: 
 8010: doc-file-status
 8011: doc-file-position
 8012: doc-reposition-file
 8013: doc-file-size
 8014: doc-resize-file
 8015: 
 8016: 
 8017: @c ---------------------------------------------------------
 8018: @node Search Paths,  , General files, Files
 8019: @subsection Search Paths
 8020: @cindex path for @code{included}
 8021: @cindex file search path
 8022: @cindex @code{include} search path
 8023: @cindex search path for files
 8024: 
 8025: If you specify an absolute filename (i.e., a filename starting with
 8026: @file{/} or @file{~}, or with @file{:} in the second position (as in
 8027: @samp{C:...})) for @code{included} and friends, that file is included
 8028: just as you would expect.
 8029: 
 8030: For relative filenames, Gforth uses a search path similar to Forth's
 8031: search order (@pxref{Word Lists}). It tries to find the given filename
 8032: in the directories present in the path, and includes the first one it
 8033: finds. There are separate search paths for Forth source files and
 8034: general files.
 8035: 
 8036: If the search path contains the directory @file{.} (as it should), this
 8037: refers to the directory that the present file was @code{included}
 8038: from. This allows files to include other files relative to their own
 8039: position (irrespective of the current working directory or the absolute
 8040: position).  This feature is essential for libraries consisting of
 8041: several files, where a file may include other files from the library.
 8042: It corresponds to @code{#include "..."} in C. If the current input
 8043: source is not a file, @file{.} refers to the directory of the innermost
 8044: file being included, or, if there is no file being included, to the
 8045: current working directory.
 8046: 
 8047: Use @file{~+} to refer to the current working directory (as in the
 8048: @code{bash}).
 8049: 
 8050: If the filename starts with @file{./}, the search path is not searched
 8051: (just as with absolute filenames), and the @file{.} has the same meaning
 8052: as described above.
 8053: 
 8054: @menu
 8055: * Forth Search Paths::          
 8056: * General Search Paths::        
 8057: @end menu
 8058: 
 8059: @c ---------------------------------------------------------
 8060: @node Forth Search Paths, General Search Paths, Search Paths, Search Paths
 8061: @subsubsection Forth Search Paths
 8062: @cindex search path control - Forth
 8063: 
 8064: The search path is initialized when you start Gforth (@pxref{Invoking
 8065: Gforth}). You can display it and change it using these words:
 8066: 
 8067: 
 8068: doc-.fpath
 8069: doc-fpath+
 8070: doc-fpath=
 8071: doc-open-fpath-file
 8072: 
 8073: 
 8074: @noindent
 8075: Here is an example of using @code{fpath} and @code{require}:
 8076: 
 8077: @example
 8078: fpath= /usr/lib/forth/|./
 8079: require timer.fs
 8080: @end example
 8081: 
 8082: @c ---------------------------------------------------------
 8083: @node General Search Paths,  , Forth Search Paths, Search Paths
 8084: @subsubsection General Search Paths
 8085: @cindex search path control - for user applications
 8086: 
 8087: Your application may need to search files in several directories, like
 8088: @code{included} does. To facilitate this, Gforth allows you to define
 8089: and use your own search paths, by providing generic equivalents of the
 8090: Forth search path words:
 8091: 
 8092: 
 8093: doc-.path
 8094: doc-path+
 8095: doc-path=
 8096: doc-open-path-file
 8097: 
 8098: 
 8099: Here's an example of creating a search path:
 8100: 
 8101: @example
 8102: \ Make a buffer for the path:
 8103: create mypath   100 chars ,     \ maximum length (is checked)
 8104:                 0 ,             \ real len
 8105:                 100 chars allot \ space for path
 8106: @end example
 8107: 
 8108: @c -------------------------------------------------------------
 8109: @node Blocks, Other I/O, Files, Words
 8110: @section Blocks
 8111: @cindex I/O - blocks
 8112: @cindex blocks
 8113: 
 8114: When you run Gforth on a modern desk-top computer, it runs under the
 8115: control of an operating system which provides certain services.  One of
 8116: these services is @var{file services}, which allows Forth source code
 8117: and data to be stored in files and read into Gforth (@pxref{Files}).
 8118: 
 8119: Traditionally, Forth has been an important programming language on
 8120: systems where it has interfaced directly to the underlying hardware with
 8121: no intervening operating system. Forth provides a mechanism, called
 8122: @dfn{blocks}, for accessing mass storage on such systems.
 8123: 
 8124: A block is a 1024-byte data area, which can be used to hold data or
 8125: Forth source code. No structure is imposed on the contents of the
 8126: block. A block is identified by its number; blocks are numbered
 8127: contiguously from 1 to an implementation-defined maximum.
 8128: 
 8129: A typical system that used blocks but no operating system might use a
 8130: single floppy-disk drive for mass storage, with the disks formatted to
 8131: provide 256-byte sectors. Blocks would be implemented by assigning the
 8132: first four sectors of the disk to block 1, the second four sectors to
 8133: block 2 and so on, up to the limit of the capacity of the disk. The disk
 8134: would not contain any file system information, just the set of blocks.
 8135: 
 8136: @cindex blocks file
 8137: On systems that do provide file services, blocks are typically
 8138: implemented by storing a sequence of blocks within a single @dfn{blocks
 8139: file}.  The size of the blocks file will be an exact multiple of 1024
 8140: bytes, corresponding to the number of blocks it contains. This is the
 8141: mechanism that Gforth uses.
 8142: 
 8143: @cindex @file{blocks.fb}
 8144: Only 1 blocks file can be open at a time. If you use block words without
 8145: having specified a blocks file, Gforth defaults to the blocks file
 8146: @file{blocks.fb}. Gforth uses the Forth search path when attempting to
 8147: locate a blocks file (@pxref{Forth Search Paths}).
 8148: 
 8149: @cindex block buffers
 8150: When you read and write blocks under program control, Gforth uses a
 8151: number of @dfn{block buffers} as intermediate storage. These buffers are
 8152: not used when you use @code{load} to interpret the contents of a block.
 8153: 
 8154: The behaviour of the block buffers is directly analagous to that of a
 8155: cache. Each block buffer has three states:
 8156: 
 8157: @itemize @bullet
 8158: @item
 8159: Unassigned
 8160: @item
 8161: Assigned-clean
 8162: @item
 8163: Assigned-dirty
 8164: @end itemize
 8165: 
 8166: Initially, all block buffers are @i{unassigned}. In order to access a
 8167: block, the block (specified by its block number) must be assigned to a
 8168: block buffer.
 8169: 
 8170: The assignment of a block to a block buffer is performed by @code{block}
 8171: or @code{buffer}. Use @code{block} when you wish to modify the existing
 8172: contents of a block. Use @code{buffer} when you don't care about the
 8173: existing contents of the block@footnote{The ANS Forth definition of
 8174: @code{buffer} is intended not to cause disk I/O; if the data associated
 8175: with the particular block is already stored in a block buffer due to an
 8176: earlier @code{block} command, @code{buffer} will return that block
 8177: buffer and the existing contents of the block will be
 8178: available. Otherwise, @code{buffer} will simply assign a new, empty
 8179: block buffer for the block.}.
 8180: 
 8181: Once a block has been assigned to a block buffer using @code{block} or
 8182: @code{buffer}, that block buffer becomes the @i{current block buffer}
 8183: and its state changes to @i{assigned-clean}. Data may only be
 8184: manipulated (read or written) within the current block buffer.
 8185: 
 8186: When the contents of the current block buffer has been modified it is
 8187: necessary, @emph{before calling @code{block} or @code{buffer} again}, to
 8188: either abandon the changes (by doing nothing) or commit the changes,
 8189: using @code{update}. Using @code{update} does not change the blocks
 8190: file; it simply changes a block buffer's state to @i{assigned-dirty}.
 8191: 
 8192: The word @code{flush} causes all @i{assigned-dirty} blocks to be
 8193: written back to the blocks file on disk. Leaving Gforth using @code{bye}
 8194: also causes a @code{flush} to be performed.
 8195: 
 8196: In Gforth, @code{block} and @code{buffer} use a @i{direct-mapped}
 8197: algorithm to assign a block buffer to a block. That means that any
 8198: particular block can only be assigned to one specific block buffer,
 8199: called (for the particular operation) the @i{victim buffer}. If the
 8200: victim buffer is @i{unassigned} or @i{assigned-clean} it is allocated to
 8201: the new block immediately. If it is @i{assigned-dirty} its current
 8202: contents are written back to the blocks file on disk before it is
 8203: allocated to the new block.
 8204: 
 8205: Although no structure is imposed on the contents of a block, it is
 8206: traditional to display the contents as 16 lines each of 64 characters.  A
 8207: block provides a single, continuous stream of input (for example, it
 8208: acts as a single parse area) -- there are no end-of-line characters
 8209: within a block, and no end-of-file character at the end of a
 8210: block. There are two consequences of this:
 8211: 
 8212: @itemize @bullet
 8213: @item
 8214: The last character of one line wraps straight into the first character
 8215: of the following line
 8216: @item
 8217: The word @code{\} -- comment to end of line -- requires special
 8218: treatment; in the context of a block it causes all characters until the
 8219: end of the current 64-character ``line'' to be ignored.
 8220: @end itemize
 8221: 
 8222: In Gforth, when you use @code{block} with a non-existent block number,
 8223: the current blocks file will be extended to the appropriate size and the
 8224: block buffer will be initialised with spaces.
 8225: 
 8226: Gforth includes a simple block editor (type @code{use blocked.fb 0 list}
 8227: for details) but doesn't encourage the use of blocks; the mechanism is
 8228: only provided for backward compatibility -- ANS Forth requires blocks to
 8229: be available when files are.
 8230: 
 8231: Common techniques that are used when working with blocks include:
 8232: 
 8233: @itemize @bullet
 8234: @item
 8235: A screen editor that allows you to edit blocks without leaving the Forth
 8236: environment.
 8237: @item
 8238: Shadow screens; where every code block has an associated block
 8239: containing comments (for example: code in odd block numbers, comments in
 8240: even block numbers). Typically, the block editor provides a convenient
 8241: mechanism to toggle between code and comments.
 8242: @item
 8243: Load blocks; a single block (typically block 1) contains a number of
 8244: @code{thru} commands which @code{load} the whole of the application.
 8245: @end itemize
 8246: 
 8247: See Frank Sergeant's Pygmy Forth to see just how well blocks can be
 8248: integrated into a Forth programming environment.
 8249: 
 8250: @comment TODO what about errors on open-blocks?
 8251: 
 8252: doc-open-blocks
 8253: doc-use
 8254: doc-get-block-fid
 8255: doc-block-position
 8256: 
 8257: doc-scr
 8258: doc-list
 8259: 
 8260: doc---gforthman-block
 8261: doc-buffer
 8262: 
 8263: doc-update
 8264: doc-updated?
 8265: doc-save-buffers
 8266: doc-empty-buffers
 8267: doc-empty-buffer
 8268: doc-flush
 8269: 
 8270: doc-load
 8271: doc-thru
 8272: doc-+load
 8273: doc-+thru
 8274: doc---gforthman--->
 8275: doc-block-included
 8276: 
 8277: 
 8278: @c -------------------------------------------------------------
 8279: @node Other I/O, Programming Tools, Blocks, Words
 8280: @section Other I/O
 8281: @cindex I/O - keyboard and display
 8282: 
 8283: @menu
 8284: * Simple numeric output::       Predefined formats
 8285: * Formatted numeric output::    Formatted (pictured) output
 8286: * String Formats::              How Forth stores strings in memory
 8287: * Displaying characters and strings::  Other stuff
 8288: * Input::                       Input
 8289: @end menu
 8290: 
 8291: @node Simple numeric output, Formatted numeric output, Other I/O, Other I/O
 8292: @subsection Simple numeric output
 8293: @cindex numeric output - simple/free-format
 8294: 
 8295: The simplest output functions are those that display numbers from the
 8296: data or floating-point stacks. Floating-point output is always displayed
 8297: using base 10. Numbers displayed from the data stack use the value stored
 8298: in @code{base}.
 8299: 
 8300: 
 8301: doc-.
 8302: doc-dec.
 8303: doc-hex.
 8304: doc-u.
 8305: doc-.r
 8306: doc-u.r
 8307: doc-d.
 8308: doc-ud.
 8309: doc-d.r
 8310: doc-ud.r
 8311: doc-f.
 8312: doc-fe.
 8313: doc-fs.
 8314: 
 8315: 
 8316: Examples of printing the number 1234.5678E23 in the different floating-point output
 8317: formats are shown below:
 8318: 
 8319: @example
 8320: f. 123456779999999000000000000.
 8321: fe. 123.456779999999E24
 8322: fs. 1.23456779999999E26
 8323: @end example
 8324: 
 8325: 
 8326: @node Formatted numeric output, String Formats, Simple numeric output, Other I/O
 8327: @subsection Formatted numeric output
 8328: @cindex formatted numeric output
 8329: @cindex pictured numeric output
 8330: @cindex numeric output - formatted
 8331: 
 8332: Forth traditionally uses a technique called @dfn{pictured numeric
 8333: output} for formatted printing of integers.  In this technique, digits
 8334: are extracted from the number (using the current output radix defined by
 8335: @code{base}), converted to ASCII codes and appended to a string that is
 8336: built in a scratch-pad area of memory (@pxref{core-idef,
 8337: Implementation-defined options, Implementation-defined
 8338: options}). Arbitrary characters can be appended to the string during the
 8339: extraction process. The completed string is specified by an address
 8340: and length and can be manipulated (@code{TYPE}ed, copied, modified)
 8341: under program control.
 8342: 
 8343: All of the words described in the previous section for simple numeric
 8344: output are implemented in Gforth using pictured numeric output.
 8345: 
 8346: Three important things to remember about pictured numeric output:
 8347: 
 8348: @itemize @bullet
 8349: @item
 8350: It always operates on double-precision numbers; to display a
 8351: single-precision number, convert it first (for ways of doing this
 8352: @pxref{Double precision}).
 8353: @item
 8354: It always treats the double-precision number as though it were
 8355: unsigned. The examples below show ways of printing signed numbers.
 8356: @item
 8357: The string is built up from right to left; least significant digit first.
 8358: @end itemize
 8359: 
 8360: 
 8361: doc-<#
 8362: doc-<<#
 8363: doc-#
 8364: doc-#s
 8365: doc-hold
 8366: doc-sign
 8367: doc-#>
 8368: doc-#>>
 8369: 
 8370: doc-represent
 8371: 
 8372: 
 8373: @noindent
 8374: Here are some examples of using pictured numeric output:
 8375: 
 8376: @example
 8377: : my-u. ( u -- )
 8378:   \ Simplest use of pns.. behaves like Standard u. 
 8379:   0              \ convert to unsigned double
 8380:   <#             \ start conversion
 8381:   #s             \ convert all digits
 8382:   #>             \ complete conversion
 8383:   TYPE SPACE ;   \ display, with trailing space
 8384: 
 8385: : cents-only ( u -- )
 8386:   0              \ convert to unsigned double
 8387:   <#             \ start conversion
 8388:   # #            \ convert two least-significant digits
 8389:   #>             \ complete conversion, discard other digits
 8390:   TYPE SPACE ;   \ display, with trailing space
 8391: 
 8392: : dollars-and-cents ( u -- )
 8393:   0              \ convert to unsigned double
 8394:   <#             \ start conversion
 8395:   # #            \ convert two least-significant digits
 8396:   [char] . hold  \ insert decimal point
 8397:   #s             \ convert remaining digits
 8398:   [char] $ hold  \ append currency symbol
 8399:   #>             \ complete conversion
 8400:   TYPE SPACE ;   \ display, with trailing space
 8401: 
 8402: : my-. ( n -- )
 8403:   \ handling negatives.. behaves like Standard .
 8404:   s>d            \ convert to signed double
 8405:   swap over dabs \ leave sign byte followed by unsigned double
 8406:   <#             \ start conversion
 8407:   #s             \ convert all digits
 8408:   rot sign       \ get at sign byte, append "-" if needed
 8409:   #>             \ complete conversion
 8410:   TYPE SPACE ;   \ display, with trailing space
 8411: 
 8412: : account. ( n -- )
 8413:   \ accountants don't like minus signs, they use braces
 8414:   \ for negative numbers
 8415:   s>d            \ convert to signed double
 8416:   swap over dabs \ leave sign byte followed by unsigned double
 8417:   <#             \ start conversion
 8418:   2 pick         \ get copy of sign byte
 8419:   0< IF [char] ) hold THEN \ right-most character of output
 8420:   #s             \ convert all digits
 8421:   rot            \ get at sign byte
 8422:   0< IF [char] ( hold THEN
 8423:   #>             \ complete conversion
 8424:   TYPE SPACE ;   \ display, with trailing space
 8425: @end example
 8426: 
 8427: Here are some examples of using these words:
 8428: 
 8429: @example
 8430: 1 my-u. 1
 8431: hex -1 my-u. decimal FFFFFFFF
 8432: 1 cents-only 01
 8433: 1234 cents-only 34
 8434: 2 dollars-and-cents $0.02
 8435: 1234 dollars-and-cents $12.34
 8436: 123 my-. 123
 8437: -123 my. -123
 8438: 123 account. 123
 8439: -456 account. (456)
 8440: @end example
 8441: 
 8442: 
 8443: @node String Formats, Displaying characters and strings, Formatted numeric output, Other I/O
 8444: @subsection String Formats
 8445: @cindex strings - see character strings
 8446: @cindex character strings - formats
 8447: @cindex I/O - see character strings
 8448: 
 8449: Forth commonly uses two different methods for representing character
 8450: strings:
 8451: 
 8452: @itemize @bullet
 8453: @item
 8454: @cindex address of counted string
 8455: @cindex counted string
 8456: As a @dfn{counted string}, represented by a @i{c-addr}. The char
 8457: addressed by @i{c-addr} contains a character-count, @i{n}, of the
 8458: string and the string occupies the subsequent @i{n} char addresses in
 8459: memory.
 8460: @item
 8461: As cell pair on the stack; @i{c-addr u}, where @i{u} is the length
 8462: of the string in characters, and @i{c-addr} is the address of the
 8463: first byte of the string.
 8464: @end itemize
 8465: 
 8466: ANS Forth encourages the use of the second format when representing
 8467: strings on the stack, whilst conceeding that the counted string format
 8468: remains useful as a way of storing strings in memory.
 8469: 
 8470: 
 8471: doc-count
 8472: 
 8473: 
 8474: For words that move, copy and search for strings see @ref{Memory
 8475: Blocks}. For words that display characters and strings see
 8476: @ref{Displaying characters and strings}.
 8477: 
 8478: @node Displaying characters and strings, Input, String Formats, Other I/O
 8479: @subsection Displaying characters and strings
 8480: @cindex characters - compiling and displaying
 8481: @cindex character strings - compiling and displaying
 8482: 
 8483: This section starts with a glossary of Forth words and ends with a set
 8484: of examples.
 8485: 
 8486: 
 8487: doc-bl
 8488: doc-space
 8489: doc-spaces
 8490: doc-emit
 8491: doc-toupper
 8492: doc-."
 8493: doc-.(
 8494: doc-type
 8495: doc-typewhite
 8496: doc-cr
 8497: @cindex cursor control
 8498: doc-at-xy
 8499: doc-page
 8500: doc-s"
 8501: doc-c"
 8502: doc-char
 8503: doc-[char]
 8504: doc-sliteral
 8505: 
 8506: 
 8507: @noindent
 8508: As an example, consider the following text, stored in a file @file{test.fs}:
 8509: 
 8510: @example
 8511: .( text-1)
 8512: : my-word
 8513:   ." text-2" cr
 8514:   .( text-3)
 8515: ;
 8516: 
 8517: ." text-4"
 8518: 
 8519: : my-char
 8520:   [char] ALPHABET emit
 8521:   char emit
 8522: ;
 8523: @end example
 8524: 
 8525: When you load this code into Gforth, the following output is generated:
 8526: 
 8527: @example
 8528: @kbd{include test.fs @key{RET}} text-1text-3text-4 ok
 8529: @end example
 8530: 
 8531: @itemize @bullet
 8532: @item
 8533: Messages @code{text-1} and @code{text-3} are displayed because @code{.(} 
 8534: is an immediate word; it behaves in the same way whether it is used inside
 8535: or outside a colon definition.
 8536: @item
 8537: Message @code{text-4} is displayed because of Gforth's added interpretation
 8538: semantics for @code{."}.
 8539: @item
 8540: Message @code{text-2} is @i{not} displayed, because the text interpreter
 8541: performs the compilation semantics for @code{."} within the definition of
 8542: @code{my-word}.
 8543: @end itemize
 8544: 
 8545: Here are some examples of executing @code{my-word} and @code{my-char}:
 8546: 
 8547: @example
 8548: @kbd{my-word @key{RET}} text-2
 8549:  ok
 8550: @kbd{my-char fred @key{RET}} Af ok
 8551: @kbd{my-char jim @key{RET}} Aj ok
 8552: @end example
 8553: 
 8554: @itemize @bullet
 8555: @item
 8556: Message @code{text-2} is displayed because of the run-time behaviour of
 8557: @code{."}.
 8558: @item
 8559: @code{[char]} compiles the ``A'' from ``ALPHABET'' and puts its display code
 8560: on the stack at run-time. @code{emit} always displays the character
 8561: when @code{my-char} is executed.
 8562: @item
 8563: @code{char} parses a string at run-time and the second @code{emit} displays
 8564: the first character of the string.
 8565: @item
 8566: If you type @code{see my-char} you can see that @code{[char]} discarded
 8567: the text ``LPHABET'' and only compiled the display code for ``A'' into the
 8568: definition of @code{my-char}.
 8569: @end itemize
 8570: 
 8571: 
 8572: 
 8573: @node Input,  , Displaying characters and strings, Other I/O
 8574: @subsection Input
 8575: @cindex input
 8576: @cindex I/O - see input
 8577: @cindex parsing a string
 8578: 
 8579: For ways of storing character strings in memory see @ref{String Formats}.
 8580: 
 8581: @comment TODO examples for >number >float accept key key? pad parse word refill
 8582: @comment then index them
 8583: 
 8584: 
 8585: doc-key
 8586: doc-key?
 8587: doc-ekey
 8588: doc-ekey?
 8589: doc-ekey>char
 8590: doc->number
 8591: doc->float
 8592: doc-accept
 8593: doc-pad
 8594: doc-parse
 8595: doc-word
 8596: doc-sword
 8597: doc-(name)
 8598: doc-refill
 8599: @comment obsolescent words..
 8600: doc-convert
 8601: doc-query
 8602: doc-expect
 8603: doc-span
 8604: 
 8605: 
 8606: 
 8607: @c -------------------------------------------------------------
 8608: @node Programming Tools, Assembler and Code Words, Other I/O, Words
 8609: @section Programming Tools
 8610: @cindex programming tools
 8611: 
 8612: @menu
 8613: * Debugging::                   Simple and quick.
 8614: * Assertions::                  Making your programs self-checking.
 8615: * Singlestep Debugger::         Executing your program word by word.
 8616: @end menu
 8617: 
 8618: @node Debugging, Assertions, Programming Tools, Programming Tools
 8619: @subsection Debugging
 8620: @cindex debugging
 8621: 
 8622: Languages with a slow edit/compile/link/test development loop tend to
 8623: require sophisticated tracing/stepping debuggers to facilate
 8624: productive debugging.
 8625: 
 8626: A much better (faster) way in fast-compiling languages is to add
 8627: printing code at well-selected places, let the program run, look at
 8628: the output, see where things went wrong, add more printing code, etc.,
 8629: until the bug is found.
 8630: 
 8631: The simple debugging aids provided in @file{debugs.fs}
 8632: are meant to support this style of debugging. In addition, there are
 8633: words for non-destructively inspecting the stack and memory:
 8634: 
 8635: 
 8636: doc-.s
 8637: doc-f.s
 8638: 
 8639: 
 8640: There is a word @code{.r} but it does @i{not} display the return
 8641: stack! It is used for formatted numeric output.
 8642: 
 8643: 
 8644: doc-depth
 8645: doc-fdepth
 8646: doc-clearstack
 8647: doc-?
 8648: doc-dump
 8649: 
 8650: 
 8651: The word @code{~~} prints debugging information (by default the source
 8652: location and the stack contents). It is easy to insert. If you use Emacs
 8653: it is also easy to remove (@kbd{C-x ~} in the Emacs Forth mode to
 8654: query-replace them with nothing). The deferred words
 8655: @code{printdebugdata} and @code{printdebugline} control the output of
 8656: @code{~~}. The default source location output format works well with
 8657: Emacs' compilation mode, so you can step through the program at the
 8658: source level using @kbd{C-x `} (the advantage over a stepping debugger
 8659: is that you can step in any direction and you know where the crash has
 8660: happened or where the strange data has occurred).
 8661: 
 8662: The default actions of @code{~~} clobber the contents of the pictured
 8663: numeric output string, so you should not use @code{~~}, e.g., between
 8664: @code{<#} and @code{#>}.
 8665: 
 8666: 
 8667: doc-~~
 8668: doc-printdebugdata
 8669: doc-printdebugline
 8670: 
 8671: doc-see
 8672: doc-marker
 8673: 
 8674: 
 8675: Here's an example of using @code{marker} at the start of a source file
 8676: that you are debugging; it ensures that you only ever have one copy of
 8677: the file's definitions compiled at any time:
 8678: 
 8679: @example
 8680: [IFDEF] my-code
 8681:     my-code
 8682: [ENDIF]
 8683: 
 8684: marker my-code
 8685: init-included-files
 8686: 
 8687: \ .. definitions start here
 8688: \ .
 8689: \ .
 8690: \ end
 8691: @end example
 8692: 
 8693: 
 8694: 
 8695: @node Assertions, Singlestep Debugger, Debugging, Programming Tools
 8696: @subsection Assertions
 8697: @cindex assertions
 8698: 
 8699: It is a good idea to make your programs self-checking, especially if you
 8700: make an assumption that may become invalid during maintenance (for
 8701: example, that a certain field of a data structure is never zero). Gforth
 8702: supports @dfn{assertions} for this purpose. They are used like this:
 8703: 
 8704: @example
 8705: assert( @i{flag} )
 8706: @end example
 8707: 
 8708: The code between @code{assert(} and @code{)} should compute a flag, that
 8709: should be true if everything is alright and false otherwise. It should
 8710: not change anything else on the stack. The overall stack effect of the
 8711: assertion is @code{( -- )}. E.g.
 8712: 
 8713: @example
 8714: assert( 1 1 + 2 = ) \ what we learn in school
 8715: assert( dup 0<> ) \ assert that the top of stack is not zero
 8716: assert( false ) \ this code should not be reached
 8717: @end example
 8718: 
 8719: The need for assertions is different at different times. During
 8720: debugging, we want more checking, in production we sometimes care more
 8721: for speed. Therefore, assertions can be turned off, i.e., the assertion
 8722: becomes a comment. Depending on the importance of an assertion and the
 8723: time it takes to check it, you may want to turn off some assertions and
 8724: keep others turned on. Gforth provides several levels of assertions for
 8725: this purpose:
 8726: 
 8727: 
 8728: doc-assert0(
 8729: doc-assert1(
 8730: doc-assert2(
 8731: doc-assert3(
 8732: doc-assert(
 8733: doc-)
 8734: 
 8735: 
 8736: The variable @code{assert-level} specifies the highest assertions that
 8737: are turned on. I.e., at the default @code{assert-level} of one,
 8738: @code{assert0(} and @code{assert1(} assertions perform checking, while
 8739: @code{assert2(} and @code{assert3(} assertions are treated as comments.
 8740: 
 8741: The value of @code{assert-level} is evaluated at compile-time, not at
 8742: run-time. Therefore you cannot turn assertions on or off at run-time;
 8743: you have to set the @code{assert-level} appropriately before compiling a
 8744: piece of code. You can compile different pieces of code at different
 8745: @code{assert-level}s (e.g., a trusted library at level 1 and
 8746: newly-written code at level 3).
 8747: 
 8748: 
 8749: doc-assert-level
 8750: 
 8751: 
 8752: If an assertion fails, a message compatible with Emacs' compilation mode
 8753: is produced and the execution is aborted (currently with @code{ABORT"}.
 8754: If there is interest, we will introduce a special throw code. But if you
 8755: intend to @code{catch} a specific condition, using @code{throw} is
 8756: probably more appropriate than an assertion).
 8757: 
 8758: Definitions in ANS Forth for these assertion words are provided
 8759: in @file{compat/assert.fs}.
 8760: 
 8761: 
 8762: @node Singlestep Debugger,  , Assertions, Programming Tools
 8763: @subsection Singlestep Debugger
 8764: @cindex singlestep Debugger
 8765: @cindex debugging Singlestep
 8766: 
 8767: When you create a new word there's often the need to check whether it
 8768: behaves correctly or not. You can do this by typing @code{dbg
 8769: badword}. A debug session might look like this:
 8770: 
 8771: @example
 8772: : badword 0 DO i . LOOP ;  ok
 8773: 2 dbg badword 
 8774: : badword  
 8775: Scanning code...
 8776: 
 8777: Nesting debugger ready!
 8778: 
 8779: 400D4738  8049BC4 0              -> [ 2 ] 00002 00000 
 8780: 400D4740  8049F68 DO             -> [ 0 ] 
 8781: 400D4744  804A0C8 i              -> [ 1 ] 00000 
 8782: 400D4748 400C5E60 .              -> 0 [ 0 ] 
 8783: 400D474C  8049D0C LOOP           -> [ 0 ] 
 8784: 400D4744  804A0C8 i              -> [ 1 ] 00001 
 8785: 400D4748 400C5E60 .              -> 1 [ 0 ] 
 8786: 400D474C  8049D0C LOOP           -> [ 0 ] 
 8787: 400D4758  804B384 ;              ->  ok
 8788: @end example
 8789: 
 8790: Each line displayed is one step. You always have to hit return to
 8791: execute the next word that is displayed. If you don't want to execute
 8792: the next word in a whole, you have to type @kbd{n} for @code{nest}. Here is
 8793: an overview what keys are available:
 8794: 
 8795: @table @i
 8796: 
 8797: @item @key{RET}
 8798: Next; Execute the next word.
 8799: 
 8800: @item n
 8801: Nest; Single step through next word.
 8802: 
 8803: @item u
 8804: Unnest; Stop debugging and execute rest of word. If we got to this word
 8805: with nest, continue debugging with the calling word.
 8806: 
 8807: @item d
 8808: Done; Stop debugging and execute rest.
 8809: 
 8810: @item s
 8811: Stop; Abort immediately.
 8812: 
 8813: @end table
 8814: 
 8815: Debugging large application with this mechanism is very difficult, because
 8816: you have to nest very deeply into the program before the interesting part
 8817: begins. This takes a lot of time. 
 8818: 
 8819: To do it more directly put a @code{BREAK:} command into your source code.
 8820: When program execution reaches @code{BREAK:} the single step debugger is
 8821: invoked and you have all the features described above.
 8822: 
 8823: If you have more than one part to debug it is useful to know where the
 8824: program has stopped at the moment. You can do this by the 
 8825: @code{BREAK" string"} command. This behaves like @code{BREAK:} except that
 8826: string is typed out when the ``breakpoint'' is reached.
 8827: 
 8828: 
 8829: doc-dbg
 8830: doc-break:
 8831: doc-break"
 8832: 
 8833: 
 8834: 
 8835: @c -------------------------------------------------------------
 8836: @node Assembler and Code Words, Threading Words, Programming Tools, Words
 8837: @section Assembler and Code Words
 8838: @cindex assembler
 8839: @cindex code words
 8840: 
 8841: @menu
 8842: * Code and ;code::              
 8843: * Common Assembler::            Assembler Syntax
 8844: * Common Disassembler::         
 8845: * 386 Assembler::               Deviations and special cases
 8846: * Alpha Assembler::             Deviations and special cases
 8847: * MIPS assembler::              Deviations and special cases
 8848: * Other assemblers::            How to write them
 8849: @end menu
 8850: 
 8851: @node Code and ;code, Common Assembler, Assembler and Code Words, Assembler and Code Words
 8852: @subsection @code{Code} and @code{;code}
 8853: 
 8854: Gforth provides some words for defining primitives (words written in
 8855: machine code), and for defining the machine-code equivalent of
 8856: @code{DOES>}-based defining words. However, the machine-independent
 8857: nature of Gforth poses a few problems: First of all, Gforth runs on
 8858: several architectures, so it can provide no standard assembler. What's
 8859: worse is that the register allocation not only depends on the processor,
 8860: but also on the @code{gcc} version and options used.
 8861: 
 8862: The words that Gforth offers encapsulate some system dependences (e.g.,
 8863: the header structure), so a system-independent assembler may be used in
 8864: Gforth. If you do not have an assembler, you can compile machine code
 8865: directly with @code{,} and @code{c,}@footnote{This isn't portable,
 8866: because these words emit stuff in @i{data} space; it works because
 8867: Gforth has unified code/data spaces. Assembler isn't likely to be
 8868: portable anyway.}.
 8869: 
 8870: 
 8871: doc-assembler
 8872: doc-init-asm
 8873: doc-code
 8874: doc-end-code
 8875: doc-;code
 8876: doc-flush-icache
 8877: 
 8878: 
 8879: If @code{flush-icache} does not work correctly, @code{code} words
 8880: etc. will not work (reliably), either.
 8881: 
 8882: The typical usage of these @code{code} words can be shown most easily by
 8883: analogy to the equivalent high-level defining words:
 8884: 
 8885: @example
 8886: : foo                              code foo
 8887:    <high-level Forth words>              <assembler>
 8888: ;                                  end-code
 8889:                                 
 8890: : bar                              : bar
 8891:    <high-level Forth words>           <high-level Forth words>
 8892:    CREATE                             CREATE
 8893:       <high-level Forth words>           <high-level Forth words>
 8894:    DOES>                              ;code
 8895:       <high-level Forth words>           <assembler>
 8896: ;                                  end-code
 8897: @end example
 8898: 
 8899: @code{flush-icache} is always present. The other words are rarely used
 8900: and reside in @code{code.fs}, which is usually not loaded. You can load
 8901: it with @code{require code.fs}.
 8902: 
 8903: @cindex registers of the inner interpreter
 8904: In the assembly code you will want to refer to the inner interpreter's
 8905: registers (e.g., the data stack pointer) and you may want to use other
 8906: registers for temporary storage. Unfortunately, the register allocation
 8907: is installation-dependent.
 8908: 
 8909: The easiest solution is to use explicit register declarations
 8910: (@pxref{Explicit Reg Vars, , Variables in Specified Registers, gcc.info,
 8911: GNU C Manual}) for all of the inner interpreter's registers: You have to
 8912: compile Gforth with @code{-DFORCE_REG} (configure option
 8913: @code{--enable-force-reg}) and the appropriate declarations must be
 8914: present in the @code{machine.h} file (see @code{mips.h} for an example;
 8915: you can find a full list of all declarable register symbols with
 8916: @code{grep register engine.c}). If you give explicit registers to all
 8917: variables that are declared at the beginning of @code{engine()}, you
 8918: should be able to use the other caller-saved registers for temporary
 8919: storage. Alternatively, you can use the @code{gcc} option
 8920: @code{-ffixed-REG} (@pxref{Code Gen Options, , Options for Code
 8921: Generation Conventions, gcc.info, GNU C Manual}) to reserve a register
 8922: (however, this restriction on register allocation may slow Gforth
 8923: significantly).
 8924: 
 8925: If this solution is not viable (e.g., because @code{gcc} does not allow
 8926: you to explicitly declare all the registers you need), you have to find
 8927: out by looking at the code where the inner interpreter's registers
 8928: reside and which registers can be used for temporary storage. You can
 8929: get an assembly listing of the engine's code with @code{make engine.s}.
 8930: 
 8931: In any case, it is good practice to abstract your assembly code from the
 8932: actual register allocation. E.g., if the data stack pointer resides in
 8933: register @code{$17}, create an alias for this register called @code{sp},
 8934: and use that in your assembly code.
 8935: 
 8936: @cindex code words, portable
 8937: Another option for implementing normal and defining words efficiently
 8938: is to add the desired functionality to the source of Gforth. For normal
 8939: words you just have to edit @file{primitives} (@pxref{Automatic
 8940: Generation}). Defining words (equivalent to @code{;CODE} words, for fast
 8941: defined words) may require changes in @file{engine.c}, @file{kernel.fs},
 8942: @file{prims2x.fs}, and possibly @file{cross.fs}.
 8943: 
 8944: @node Common Assembler, Common Disassembler, Code and ;code, Assembler and Code Words
 8945: @subsection Common Assembler
 8946: 
 8947: The assemblers in Gforth generally use a postfix syntax, i.e., the
 8948: instruction name follows the operands.
 8949: 
 8950: The operands are passed in the usual order (the same that is used in the
 8951: manual of the architecture).  Since they all are Forth words, they have
 8952: to be separated by spaces; you can also use Forth words to compute the
 8953: operands.
 8954: 
 8955: The instruction names usually end with a @code{,}.  This makes it easier
 8956: to visually separate instructions if you put several of them on one
 8957: line; it also avoids shadowing other Forth words (e.g., @code{and}).
 8958: 
 8959: Registers are usually specified by number; e.g., (decimal) @code{11}
 8960: specifies registers R11 and F11 on the Alpha architecture (which one,
 8961: depends on the instruction).  The usual names are also available, e.g.,
 8962: @code{s2} for R11 on Alpha.
 8963: 
 8964: Control flow is specified similar to normal Forth code (@pxref{Arbitrary
 8965: control structures}), with @code{if,}, @code{ahead,}, @code{then,},
 8966: @code{begin,}, @code{until,}, @code{again,}, @code{cs-roll},
 8967: @code{cs-pick}, @code{else,}, @code{while,}, and @code{repeat,}.  The
 8968: conditions are specified in a way specific to each assembler.
 8969: 
 8970: Note that the register assignments of the Gforth engine can change
 8971: between Gforth versions, or even between different compilations of the
 8972: same Gforth version (e.g., if you use a different GCC version).  So if
 8973: you want to refer to Gforth's registers (e.g., the stack pointer or
 8974: TOS), I recommend defining your own words for refering to these
 8975: registers, and using them later on; then you can easily adapt to a
 8976: changed register assignment.  The stability of the register assignment
 8977: is usually better if you build Gforth with @code{--enable-force-reg}.
 8978: 
 8979: In particular, the resturn stack pointer and the instruction pointer are
 8980: in memory in @code{gforth}, and usually in registers in
 8981: @code{gforth-fast}.  The most common use of these registers is to
 8982: dispatch to the next word (the @code{next} routine).  A portable way to
 8983: do this is to jump to @code{' noop >code-address} (of course, this is
 8984: less efficient than integrating the @code{next} code and scheduling it
 8985: well).
 8986: 
 8987: @node  Common Disassembler, 386 Assembler, Common Assembler, Assembler and Code Words
 8988: @subsection Common Disassembler
 8989: 
 8990: You can disassemble a @code{code} word with @code{see}
 8991: (@pxref{Debugging}).  You can disassemble a section of memory with
 8992: 
 8993: doc-disasm
 8994: 
 8995: The disassembler generally produces output that can be fed into the
 8996: assembler (i.e., same syntax, etc.).  It also includes additional
 8997: information in comments.  In particular, the address of the instruction
 8998: is given in a comment before the instruction.
 8999: 
 9000: @code{See} may display more or less than the actual code of the word,
 9001: because the recognition of the end of the code is unreliable.  You can
 9002: use @code{disasm} if it did not display enough.  It may display more, if
 9003: the code word is not immediately followed by a named word.  If you have
 9004: something else there, you can follow the word with @code{align last @ ,}
 9005: to ensure that the end is recognized.
 9006: 
 9007: @node 386 Assembler, Alpha Assembler, Common Disassembler, Assembler and Code Words
 9008: @subsection 386 Assembler
 9009: 
 9010: The 386 assembler included in Gforth was written by Bernd Paysan, it's
 9011: available under GPL, and originally part of bigFORTH.
 9012: 
 9013: The 386 disassembler included in Gforth was written by Andrew McKewan
 9014: and is in the public domain.
 9015: 
 9016: The disassembler displays code in prefix Intel syntax.
 9017: 
 9018: The assembler uses a postfix syntax with reversed parameters.
 9019: 
 9020: The assembler includes all instruction of the Athlon, i.e. 486 core
 9021: instructions, Pentium and PPro extensions, floating point, MMX, 3Dnow!,
 9022: but not ISSE. It's an integrated 16- and 32-bit assembler. Default is 32
 9023: bit, you can switch to 16 bit with .86 and back to 32 bit with .386.
 9024: 
 9025: There are several prefixes to switch between different operation sizes,
 9026: @code{.b} for byte accesses, @code{.w} for word accesses, @code{.d} for
 9027: double-word accesses. Addressing modes can be switched with @code{.wa}
 9028: for 16 bit addresses, and @code{.da} for 32 bit addresses. You don't
 9029: need a prefix for byte register names (@code{AL} et al).
 9030: 
 9031: For floating point operations, the prefixes are @code{.fs} (IEEE
 9032: single), @code{.fl} (IEEE double), @code{.fx} (extended), @code{.fw}
 9033: (word), @code{.fd} (double-word), and @code{.fq} (quad-word).
 9034: 
 9035: The MMX opcodes don't have size prefixes, they are spelled out like in
 9036: the Intel assembler. Instead of move from and to memory, there are
 9037: PLDQ/PLDD and PSTQ/PSTD.
 9038: 
 9039: The registers lack the 'e' prefix; even in 32 bit mode, eax is called
 9040: ax.  Immediate values are indicated by postfixing them with @code{#},
 9041: e.g., @code{3 #}.  Here are some examples of addressing modes:
 9042: 
 9043: @example
 9044: 3 #          \ immediate
 9045: ax           \ register
 9046: 100 di d)    \ 100[edi]
 9047: 4 bx cx di)  \ 4[ebx][ecx]
 9048: di ax *4 i)  \ [edi][eax*4]
 9049: 20 ax *4 i#) \ 20[eax*4]
 9050: @end example
 9051: 
 9052: Some example of instructions are:
 9053: 
 9054: @example
 9055: ax bx mov             \ move ebx,eax
 9056: 3 # ax mov            \ mov eax,3
 9057: 100 di ) ax mov       \ mov eax,100[edi]
 9058: 4 bx cx di) ax mov    \ mov eax,4[ebx][ecx]
 9059: .w ax bx mov          \ mov bx,ax
 9060: @end example
 9061: 
 9062: The following forms are supported for binary instructions:
 9063: 
 9064: @example
 9065: <reg> <reg> <inst>
 9066: <n> # <reg> <inst>
 9067: <mem> <reg> <inst>
 9068: <reg> <mem> <inst>
 9069: @end example
 9070: 
 9071: Immediate to memory is not supported.  The shift/rotate syntax is:
 9072: 
 9073: @example
 9074: <reg/mem> 1 # shl \ shortens to shift without immediate
 9075: <reg/mem> 4 # shl
 9076: <reg/mem> cl shl
 9077: @end example
 9078: 
 9079: Precede string instructions (@code{movs} etc.) with @code{.b} to get
 9080: the byte version.
 9081: 
 9082: The control structure words @code{IF} @code{UNTIL} etc. must be preceded
 9083: by one of these conditions: @code{vs vc u< u>= 0= 0<> u<= u> 0< 0>= ps
 9084: pc < >= <= >}. (Note that most of these words shadow some Forth words
 9085: when @code{assembler} is in front of @code{forth} in the search path,
 9086: e.g., in @code{code} words).  Currently the control structure words use
 9087: one stack item, so you have to use @code{roll} instead of @code{cs-roll}
 9088: to shuffle them (you can also use @code{swap} etc.).
 9089: 
 9090: Here is an example of a @code{code} word (assumes that the stack pointer
 9091: is in esi and the TOS is in ebx):
 9092: 
 9093: @example
 9094: code my+ ( n1 n2 -- n )
 9095:     4 si D) bx add
 9096:     4 # si add
 9097:     Next
 9098: end-code
 9099: @end example
 9100: 
 9101: @node Alpha Assembler, MIPS assembler, 386 Assembler, Assembler and Code Words
 9102: @subsection Alpha Assembler
 9103: 
 9104: The Alpha assembler and disassembler were originally written by Bernd
 9105: Thallner.
 9106: 
 9107: The register names @code{a0}--@code{a5} are not available to avoid
 9108: shadowing hex numbers.
 9109: 
 9110: Immediate forms of arithmetic instructions are distinguished by a
 9111: @code{#} just before the @code{,}, e.g., @code{and#,} (note: @code{lda,}
 9112: does not count as arithmetic instruction).
 9113: 
 9114: You have to specify all operands to an instruction, even those that
 9115: other assemblers consider optional, e.g., the destination register for
 9116: @code{br,}, or the destination register and hint for @code{jmp,}.
 9117: 
 9118: You can specify conditions for @code{if,} by removing the first @code{b}
 9119: and the trailing @code{,} from a branch with a corresponding name; e.g.,
 9120: 
 9121: @example
 9122: 11 fgt if, \ if F11>0e
 9123:   ...
 9124: endif,
 9125: @end example
 9126: 
 9127: @code{fbgt,} gives @code{fgt}.  
 9128: 
 9129: @node MIPS assembler, Other assemblers, Alpha Assembler, Assembler and Code Words
 9130: @subsection MIPS assembler
 9131: 
 9132: The MIPS assembler was originally written by Christian Pirker.
 9133: 
 9134: Currently the assembler and disassembler only cover the MIPS-I
 9135: architecture (R3000), and don't support FP instructions.
 9136: 
 9137: The register names @code{$a0}--@code{$a3} are not available to avoid
 9138: shadowing hex numbers.
 9139: 
 9140: Because there is no way to distinguish registers from immediate values,
 9141: you have to explicitly use the immediate forms of instructions, i.e.,
 9142: @code{addiu,}, not just @code{addu,} (@command{as} does this
 9143: implicitly).
 9144: 
 9145: If the architecture manual specifies several formats for the instruction
 9146: (e.g., for @code{jalr,}), you usually have to use the one with more
 9147: arguments (i.e., two for @code{jalr,}).  When in doubt, see
 9148: @code{arch/mips/testasm.fs} for an example of correct use.
 9149: 
 9150: Branches and jumps in the MIPS architecture have a delay slot.  You have
 9151: to fill it yourself (the simplest way is to use @code{nop,}), the
 9152: assembler does not do it for you (unlike @command{as}).  Even
 9153: @code{if,}, @code{ahead,}, @code{until,}, @code{again,}, @code{while,},
 9154: @code{else,} and @code{repeat,} need a delay slot.  Since @code{begin,}
 9155: and @code{then,} just specify branch targets, they are not affected.
 9156: 
 9157: Note that you must not put branches, jumps, or @code{li,} into the delay
 9158: slot: @code{li,} may expand to several instructions, and control flow
 9159: instructions may not be put into the branch delay slot in any case.
 9160: 
 9161: For branches the argument specifying the target is a relative address;
 9162: You have to add the address of the delay slot to get the absolute
 9163: address.
 9164: 
 9165: The MIPS architecture also has load delay slots and restrictions on
 9166: using @code{mfhi,} and @code{mflo,}; you have to order the instructions
 9167: yourself to satisfy these restrictions, the assembler does not do it for
 9168: you.
 9169: 
 9170: You can specify the conditions for @code{if,} etc. by taking a
 9171: conditional branch and leaving away the @code{b} at the start and the
 9172: @code{,} at the end.  E.g.,
 9173: 
 9174: @example
 9175: 4 5 eq if,
 9176:   ... \ do something if $4 equals $5
 9177: then,
 9178: @end example
 9179: 
 9180: @node Other assemblers,  , MIPS assembler, Assembler and Code Words
 9181: @subsection Other assemblers
 9182: 
 9183: If you want to contribute another assembler/disassembler, please contact
 9184: us (@email{bug-gforth@@gnu.org}) to check if we have such an assembler
 9185: already.  If you are writing them from scratch, please use a similar
 9186: syntax style as the one we use (i.e., postfix, commas at the end of the
 9187: instruction names, @pxref{Common Assembler}); make the output of the
 9188: disassembler be valid input for the assembler, and keep the style
 9189: similar to the style we used.
 9190: 
 9191: Hints on implementation: The most important part is to have a good test
 9192: suite that contains all instructions.  Once you have that, the rest is
 9193: easy.  For actual coding you can take a look at
 9194: @file{arch/mips/disasm.fs} to get some ideas on how to use data for both
 9195: the assembler and disassembler, avoiding redundancy and some potential
 9196: bugs.  You can also look at that file (and @pxref{Advanced does> usage
 9197: example}) to get ideas how to factor a disassembler.
 9198: 
 9199: Start with the disassembler, because it's easier to reuse data from the
 9200: disassembler for the assembler than the other way round.
 9201: 
 9202: For the assembler, take a look at @file{arch/alpha/asm.fs}, which shows
 9203: how simple it can be.
 9204: 
 9205: @c -------------------------------------------------------------
 9206: @node Threading Words, Locals, Assembler and Code Words, Words
 9207: @section Threading Words
 9208: @cindex threading words
 9209: 
 9210: @cindex code address
 9211: These words provide access to code addresses and other threading stuff
 9212: in Gforth (and, possibly, other interpretive Forths). It more or less
 9213: abstracts away the differences between direct and indirect threading
 9214: (and, for direct threading, the machine dependences). However, at
 9215: present this wordset is still incomplete. It is also pretty low-level;
 9216: some day it will hopefully be made unnecessary by an internals wordset
 9217: that abstracts implementation details away completely.
 9218: 
 9219: 
 9220: doc-threading-method
 9221: doc->code-address
 9222: doc->does-code
 9223: doc-code-address!
 9224: doc-does-code!
 9225: doc-does-handler!
 9226: doc-/does-handler
 9227: 
 9228: 
 9229: The code addresses produced by various defining words are produced by
 9230: the following words:
 9231: 
 9232: 
 9233: doc-docol:
 9234: doc-docon:
 9235: doc-dovar:
 9236: doc-douser:
 9237: doc-dodefer:
 9238: doc-dofield:
 9239: 
 9240: 
 9241: You can recognize words defined by a @code{CREATE}...@code{DOES>} word
 9242: with @code{>does-code}. If the word was defined in that way, the value
 9243: returned is non-zero and identifies the @code{DOES>} used by the
 9244: defining word.
 9245: @comment TODO should that be ``identifies the xt of the DOES> ??''
 9246: 
 9247: @c -------------------------------------------------------------
 9248: @node Locals, Structures, Threading Words, Words
 9249: @section Locals
 9250: @cindex locals
 9251: 
 9252: Local variables can make Forth programming more enjoyable and Forth
 9253: programs easier to read. Unfortunately, the locals of ANS Forth are
 9254: laden with restrictions. Therefore, we provide not only the ANS Forth
 9255: locals wordset, but also our own, more powerful locals wordset (we
 9256: implemented the ANS Forth locals wordset through our locals wordset).
 9257: 
 9258: The ideas in this section have also been published in M. Anton Ertl,
 9259: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl94l.ps.gz,
 9260: Automatic Scoping of Local Variables}}, EuroForth '94.
 9261: 
 9262: @menu
 9263: * Gforth locals::               
 9264: * ANS Forth locals::            
 9265: @end menu
 9266: 
 9267: @node Gforth locals, ANS Forth locals, Locals, Locals
 9268: @subsection Gforth locals
 9269: @cindex Gforth locals
 9270: @cindex locals, Gforth style
 9271: 
 9272: Locals can be defined with
 9273: 
 9274: @example
 9275: @{ local1 local2 ... -- comment @}
 9276: @end example
 9277: or
 9278: @example
 9279: @{ local1 local2 ... @}
 9280: @end example
 9281: 
 9282: E.g.,
 9283: @example
 9284: : max @{ n1 n2 -- n3 @}
 9285:  n1 n2 > if
 9286:    n1
 9287:  else
 9288:    n2
 9289:  endif ;
 9290: @end example
 9291: 
 9292: The similarity of locals definitions with stack comments is intended. A
 9293: locals definition often replaces the stack comment of a word. The order
 9294: of the locals corresponds to the order in a stack comment and everything
 9295: after the @code{--} is really a comment.
 9296: 
 9297: This similarity has one disadvantage: It is too easy to confuse locals
 9298: declarations with stack comments, causing bugs and making them hard to
 9299: find. However, this problem can be avoided by appropriate coding
 9300: conventions: Do not use both notations in the same program. If you do,
 9301: they should be distinguished using additional means, e.g. by position.
 9302: 
 9303: @cindex types of locals
 9304: @cindex locals types
 9305: The name of the local may be preceded by a type specifier, e.g.,
 9306: @code{F:} for a floating point value:
 9307: 
 9308: @example
 9309: : CX* @{ F: Ar F: Ai F: Br F: Bi -- Cr Ci @}
 9310: \ complex multiplication
 9311:  Ar Br f* Ai Bi f* f-
 9312:  Ar Bi f* Ai Br f* f+ ;
 9313: @end example
 9314: 
 9315: @cindex flavours of locals
 9316: @cindex locals flavours
 9317: @cindex value-flavoured locals
 9318: @cindex variable-flavoured locals
 9319: Gforth currently supports cells (@code{W:}, @code{W^}), doubles
 9320: (@code{D:}, @code{D^}), floats (@code{F:}, @code{F^}) and characters
 9321: (@code{C:}, @code{C^}) in two flavours: a value-flavoured local (defined
 9322: with @code{W:}, @code{D:} etc.) produces its value and can be changed
 9323: with @code{TO}. A variable-flavoured local (defined with @code{W^} etc.)
 9324: produces its address (which becomes invalid when the variable's scope is
 9325: left). E.g., the standard word @code{emit} can be defined in terms of
 9326: @code{type} like this:
 9327: 
 9328: @example
 9329: : emit @{ C^ char* -- @}
 9330:     char* 1 type ;
 9331: @end example
 9332: 
 9333: @cindex default type of locals
 9334: @cindex locals, default type
 9335: A local without type specifier is a @code{W:} local. Both flavours of
 9336: locals are initialized with values from the data or FP stack.
 9337: 
 9338: Currently there is no way to define locals with user-defined data
 9339: structures, but we are working on it.
 9340: 
 9341: Gforth allows defining locals everywhere in a colon definition. This
 9342: poses the following questions:
 9343: 
 9344: @menu
 9345: * Where are locals visible by name?::  
 9346: * How long do locals live?::    
 9347: * Programming Style::           
 9348: * Implementation::              
 9349: @end menu
 9350: 
 9351: @node Where are locals visible by name?, How long do locals live?, Gforth locals, Gforth locals
 9352: @subsubsection Where are locals visible by name?
 9353: @cindex locals visibility
 9354: @cindex visibility of locals
 9355: @cindex scope of locals
 9356: 
 9357: Basically, the answer is that locals are visible where you would expect
 9358: it in block-structured languages, and sometimes a little longer. If you
 9359: want to restrict the scope of a local, enclose its definition in
 9360: @code{SCOPE}...@code{ENDSCOPE}.
 9361: 
 9362: 
 9363: doc-scope
 9364: doc-endscope
 9365: 
 9366: 
 9367: These words behave like control structure words, so you can use them
 9368: with @code{CS-PICK} and @code{CS-ROLL} to restrict the scope in
 9369: arbitrary ways.
 9370: 
 9371: If you want a more exact answer to the visibility question, here's the
 9372: basic principle: A local is visible in all places that can only be
 9373: reached through the definition of the local@footnote{In compiler
 9374: construction terminology, all places dominated by the definition of the
 9375: local.}. In other words, it is not visible in places that can be reached
 9376: without going through the definition of the local. E.g., locals defined
 9377: in @code{IF}...@code{ENDIF} are visible until the @code{ENDIF}, locals
 9378: defined in @code{BEGIN}...@code{UNTIL} are visible after the
 9379: @code{UNTIL} (until, e.g., a subsequent @code{ENDSCOPE}).
 9380: 
 9381: The reasoning behind this solution is: We want to have the locals
 9382: visible as long as it is meaningful. The user can always make the
 9383: visibility shorter by using explicit scoping. In a place that can
 9384: only be reached through the definition of a local, the meaning of a
 9385: local name is clear. In other places it is not: How is the local
 9386: initialized at the control flow path that does not contain the
 9387: definition? Which local is meant, if the same name is defined twice in
 9388: two independent control flow paths?
 9389: 
 9390: This should be enough detail for nearly all users, so you can skip the
 9391: rest of this section. If you really must know all the gory details and
 9392: options, read on.
 9393: 
 9394: In order to implement this rule, the compiler has to know which places
 9395: are unreachable. It knows this automatically after @code{AHEAD},
 9396: @code{AGAIN}, @code{EXIT} and @code{LEAVE}; in other cases (e.g., after
 9397: most @code{THROW}s), you can use the word @code{UNREACHABLE} to tell the
 9398: compiler that the control flow never reaches that place. If
 9399: @code{UNREACHABLE} is not used where it could, the only consequence is
 9400: that the visibility of some locals is more limited than the rule above
 9401: says. If @code{UNREACHABLE} is used where it should not (i.e., if you
 9402: lie to the compiler), buggy code will be produced.
 9403: 
 9404: 
 9405: doc-unreachable
 9406: 
 9407: 
 9408: Another problem with this rule is that at @code{BEGIN}, the compiler
 9409: does not know which locals will be visible on the incoming
 9410: back-edge. All problems discussed in the following are due to this
 9411: ignorance of the compiler (we discuss the problems using @code{BEGIN}
 9412: loops as examples; the discussion also applies to @code{?DO} and other
 9413: loops). Perhaps the most insidious example is:
 9414: @example
 9415: AHEAD
 9416: BEGIN
 9417:   x
 9418: [ 1 CS-ROLL ] THEN
 9419:   @{ x @}
 9420:   ...
 9421: UNTIL
 9422: @end example
 9423: 
 9424: This should be legal according to the visibility rule. The use of
 9425: @code{x} can only be reached through the definition; but that appears
 9426: textually below the use.
 9427: 
 9428: From this example it is clear that the visibility rules cannot be fully
 9429: implemented without major headaches. Our implementation treats common
 9430: cases as advertised and the exceptions are treated in a safe way: The
 9431: compiler makes a reasonable guess about the locals visible after a
 9432: @code{BEGIN}; if it is too pessimistic, the
 9433: user will get a spurious error about the local not being defined; if the
 9434: compiler is too optimistic, it will notice this later and issue a
 9435: warning. In the case above the compiler would complain about @code{x}
 9436: being undefined at its use. You can see from the obscure examples in
 9437: this section that it takes quite unusual control structures to get the
 9438: compiler into trouble, and even then it will often do fine.
 9439: 
 9440: If the @code{BEGIN} is reachable from above, the most optimistic guess
 9441: is that all locals visible before the @code{BEGIN} will also be
 9442: visible after the @code{BEGIN}. This guess is valid for all loops that
 9443: are entered only through the @code{BEGIN}, in particular, for normal
 9444: @code{BEGIN}...@code{WHILE}...@code{REPEAT} and
 9445: @code{BEGIN}...@code{UNTIL} loops and it is implemented in our
 9446: compiler. When the branch to the @code{BEGIN} is finally generated by
 9447: @code{AGAIN} or @code{UNTIL}, the compiler checks the guess and
 9448: warns the user if it was too optimistic:
 9449: @example
 9450: IF
 9451:   @{ x @}
 9452: BEGIN
 9453:   \ x ? 
 9454: [ 1 cs-roll ] THEN
 9455:   ...
 9456: UNTIL
 9457: @end example
 9458: 
 9459: Here, @code{x} lives only until the @code{BEGIN}, but the compiler
 9460: optimistically assumes that it lives until the @code{THEN}. It notices
 9461: this difference when it compiles the @code{UNTIL} and issues a
 9462: warning. The user can avoid the warning, and make sure that @code{x}
 9463: is not used in the wrong area by using explicit scoping:
 9464: @example
 9465: IF
 9466:   SCOPE
 9467:   @{ x @}
 9468:   ENDSCOPE
 9469: BEGIN
 9470: [ 1 cs-roll ] THEN
 9471:   ...
 9472: UNTIL
 9473: @end example
 9474: 
 9475: Since the guess is optimistic, there will be no spurious error messages
 9476: about undefined locals.
 9477: 
 9478: If the @code{BEGIN} is not reachable from above (e.g., after
 9479: @code{AHEAD} or @code{EXIT}), the compiler cannot even make an
 9480: optimistic guess, as the locals visible after the @code{BEGIN} may be
 9481: defined later. Therefore, the compiler assumes that no locals are
 9482: visible after the @code{BEGIN}. However, the user can use
 9483: @code{ASSUME-LIVE} to make the compiler assume that the same locals are
 9484: visible at the BEGIN as at the point where the top control-flow stack
 9485: item was created.
 9486: 
 9487: 
 9488: doc-assume-live
 9489: 
 9490: 
 9491: @noindent
 9492: E.g.,
 9493: @example
 9494: @{ x @}
 9495: AHEAD
 9496: ASSUME-LIVE
 9497: BEGIN
 9498:   x
 9499: [ 1 CS-ROLL ] THEN
 9500:   ...
 9501: UNTIL
 9502: @end example
 9503: 
 9504: Other cases where the locals are defined before the @code{BEGIN} can be
 9505: handled by inserting an appropriate @code{CS-ROLL} before the
 9506: @code{ASSUME-LIVE} (and changing the control-flow stack manipulation
 9507: behind the @code{ASSUME-LIVE}).
 9508: 
 9509: Cases where locals are defined after the @code{BEGIN} (but should be
 9510: visible immediately after the @code{BEGIN}) can only be handled by
 9511: rearranging the loop. E.g., the ``most insidious'' example above can be
 9512: arranged into:
 9513: @example
 9514: BEGIN
 9515:   @{ x @}
 9516:   ... 0=
 9517: WHILE
 9518:   x
 9519: REPEAT
 9520: @end example
 9521: 
 9522: @node How long do locals live?, Programming Style, Where are locals visible by name?, Gforth locals
 9523: @subsubsection How long do locals live?
 9524: @cindex locals lifetime
 9525: @cindex lifetime of locals
 9526: 
 9527: The right answer for the lifetime question would be: A local lives at
 9528: least as long as it can be accessed. For a value-flavoured local this
 9529: means: until the end of its visibility. However, a variable-flavoured
 9530: local could be accessed through its address far beyond its visibility
 9531: scope. Ultimately, this would mean that such locals would have to be
 9532: garbage collected. Since this entails un-Forth-like implementation
 9533: complexities, I adopted the same cowardly solution as some other
 9534: languages (e.g., C): The local lives only as long as it is visible;
 9535: afterwards its address is invalid (and programs that access it
 9536: afterwards are erroneous).
 9537: 
 9538: @node Programming Style, Implementation, How long do locals live?, Gforth locals
 9539: @subsubsection Programming Style
 9540: @cindex locals programming style
 9541: @cindex programming style, locals
 9542: 
 9543: The freedom to define locals anywhere has the potential to change
 9544: programming styles dramatically. In particular, the need to use the
 9545: return stack for intermediate storage vanishes. Moreover, all stack
 9546: manipulations (except @code{PICK}s and @code{ROLL}s with run-time
 9547: determined arguments) can be eliminated: If the stack items are in the
 9548: wrong order, just write a locals definition for all of them; then
 9549: write the items in the order you want.
 9550: 
 9551: This seems a little far-fetched and eliminating stack manipulations is
 9552: unlikely to become a conscious programming objective. Still, the number
 9553: of stack manipulations will be reduced dramatically if local variables
 9554: are used liberally (e.g., compare @code{max} (@pxref{Gforth locals}) with
 9555: a traditional implementation of @code{max}).
 9556: 
 9557: This shows one potential benefit of locals: making Forth programs more
 9558: readable. Of course, this benefit will only be realized if the
 9559: programmers continue to honour the principle of factoring instead of
 9560: using the added latitude to make the words longer.
 9561: 
 9562: @cindex single-assignment style for locals
 9563: Using @code{TO} can and should be avoided.  Without @code{TO},
 9564: every value-flavoured local has only a single assignment and many
 9565: advantages of functional languages apply to Forth. I.e., programs are
 9566: easier to analyse, to optimize and to read: It is clear from the
 9567: definition what the local stands for, it does not turn into something
 9568: different later.
 9569: 
 9570: E.g., a definition using @code{TO} might look like this:
 9571: @example
 9572: : strcmp @{ addr1 u1 addr2 u2 -- n @}
 9573:  u1 u2 min 0
 9574:  ?do
 9575:    addr1 c@@ addr2 c@@ -
 9576:    ?dup-if
 9577:      unloop exit
 9578:    then
 9579:    addr1 char+ TO addr1
 9580:    addr2 char+ TO addr2
 9581:  loop
 9582:  u1 u2 - ;
 9583: @end example
 9584: Here, @code{TO} is used to update @code{addr1} and @code{addr2} at
 9585: every loop iteration. @code{strcmp} is a typical example of the
 9586: readability problems of using @code{TO}. When you start reading
 9587: @code{strcmp}, you think that @code{addr1} refers to the start of the
 9588: string. Only near the end of the loop you realize that it is something
 9589: else.
 9590: 
 9591: This can be avoided by defining two locals at the start of the loop that
 9592: are initialized with the right value for the current iteration.
 9593: @example
 9594: : strcmp @{ addr1 u1 addr2 u2 -- n @}
 9595:  addr1 addr2
 9596:  u1 u2 min 0 
 9597:  ?do @{ s1 s2 @}
 9598:    s1 c@@ s2 c@@ -
 9599:    ?dup-if
 9600:      unloop exit
 9601:    then
 9602:    s1 char+ s2 char+
 9603:  loop
 9604:  2drop
 9605:  u1 u2 - ;
 9606: @end example
 9607: Here it is clear from the start that @code{s1} has a different value
 9608: in every loop iteration.
 9609: 
 9610: @node Implementation,  , Programming Style, Gforth locals
 9611: @subsubsection Implementation
 9612: @cindex locals implementation
 9613: @cindex implementation of locals
 9614: 
 9615: @cindex locals stack
 9616: Gforth uses an extra locals stack. The most compelling reason for
 9617: this is that the return stack is not float-aligned; using an extra stack
 9618: also eliminates the problems and restrictions of using the return stack
 9619: as locals stack. Like the other stacks, the locals stack grows toward
 9620: lower addresses. A few primitives allow an efficient implementation:
 9621: 
 9622: 
 9623: doc-@local#
 9624: doc-f@local#
 9625: doc-laddr#
 9626: doc-lp+!#
 9627: doc-lp!
 9628: doc->l
 9629: doc-f>l
 9630: 
 9631: 
 9632: In addition to these primitives, some specializations of these
 9633: primitives for commonly occurring inline arguments are provided for
 9634: efficiency reasons, e.g., @code{@@local0} as specialization of
 9635: @code{@@local#} for the inline argument 0. The following compiling words
 9636: compile the right specialized version, or the general version, as
 9637: appropriate:
 9638: 
 9639: 
 9640: doc-compile-@local
 9641: doc-compile-f@local
 9642: doc-compile-lp+!
 9643: 
 9644: 
 9645: Combinations of conditional branches and @code{lp+!#} like
 9646: @code{?branch-lp+!#} (the locals pointer is only changed if the branch
 9647: is taken) are provided for efficiency and correctness in loops.
 9648: 
 9649: A special area in the dictionary space is reserved for keeping the
 9650: local variable names. @code{@{} switches the dictionary pointer to this
 9651: area and @code{@}} switches it back and generates the locals
 9652: initializing code. @code{W:} etc.@ are normal defining words. This
 9653: special area is cleared at the start of every colon definition.
 9654: 
 9655: @cindex word list for defining locals
 9656: A special feature of Gforth's dictionary is used to implement the
 9657: definition of locals without type specifiers: every word list (aka
 9658: vocabulary) has its own methods for searching
 9659: etc. (@pxref{Word Lists}). For the present purpose we defined a word list
 9660: with a special search method: When it is searched for a word, it
 9661: actually creates that word using @code{W:}. @code{@{} changes the search
 9662: order to first search the word list containing @code{@}}, @code{W:} etc.,
 9663: and then the word list for defining locals without type specifiers.
 9664: 
 9665: The lifetime rules support a stack discipline within a colon
 9666: definition: The lifetime of a local is either nested with other locals
 9667: lifetimes or it does not overlap them.
 9668: 
 9669: At @code{BEGIN}, @code{IF}, and @code{AHEAD} no code for locals stack
 9670: pointer manipulation is generated. Between control structure words
 9671: locals definitions can push locals onto the locals stack. @code{AGAIN}
 9672: is the simplest of the other three control flow words. It has to
 9673: restore the locals stack depth of the corresponding @code{BEGIN}
 9674: before branching. The code looks like this:
 9675: @format
 9676: @code{lp+!#} current-locals-size @minus{} dest-locals-size
 9677: @code{branch} <begin>
 9678: @end format
 9679: 
 9680: @code{UNTIL} is a little more complicated: If it branches back, it
 9681: must adjust the stack just like @code{AGAIN}. But if it falls through,
 9682: the locals stack must not be changed. The compiler generates the
 9683: following code:
 9684: @format
 9685: @code{?branch-lp+!#} <begin> current-locals-size @minus{} dest-locals-size
 9686: @end format
 9687: The locals stack pointer is only adjusted if the branch is taken.
 9688: 
 9689: @code{THEN} can produce somewhat inefficient code:
 9690: @format
 9691: @code{lp+!#} current-locals-size @minus{} orig-locals-size
 9692: <orig target>:
 9693: @code{lp+!#} orig-locals-size @minus{} new-locals-size
 9694: @end format
 9695: The second @code{lp+!#} adjusts the locals stack pointer from the
 9696: level at the @i{orig} point to the level after the @code{THEN}. The
 9697: first @code{lp+!#} adjusts the locals stack pointer from the current
 9698: level to the level at the orig point, so the complete effect is an
 9699: adjustment from the current level to the right level after the
 9700: @code{THEN}.
 9701: 
 9702: @cindex locals information on the control-flow stack
 9703: @cindex control-flow stack items, locals information
 9704: In a conventional Forth implementation a dest control-flow stack entry
 9705: is just the target address and an orig entry is just the address to be
 9706: patched. Our locals implementation adds a word list to every orig or dest
 9707: item. It is the list of locals visible (or assumed visible) at the point
 9708: described by the entry. Our implementation also adds a tag to identify
 9709: the kind of entry, in particular to differentiate between live and dead
 9710: (reachable and unreachable) orig entries.
 9711: 
 9712: A few unusual operations have to be performed on locals word lists:
 9713: 
 9714: 
 9715: doc-common-list
 9716: doc-sub-list?
 9717: doc-list-size
 9718: 
 9719: 
 9720: Several features of our locals word list implementation make these
 9721: operations easy to implement: The locals word lists are organised as
 9722: linked lists; the tails of these lists are shared, if the lists
 9723: contain some of the same locals; and the address of a name is greater
 9724: than the address of the names behind it in the list.
 9725: 
 9726: Another important implementation detail is the variable
 9727: @code{dead-code}. It is used by @code{BEGIN} and @code{THEN} to
 9728: determine if they can be reached directly or only through the branch
 9729: that they resolve. @code{dead-code} is set by @code{UNREACHABLE},
 9730: @code{AHEAD}, @code{EXIT} etc., and cleared at the start of a colon
 9731: definition, by @code{BEGIN} and usually by @code{THEN}.
 9732: 
 9733: Counted loops are similar to other loops in most respects, but
 9734: @code{LEAVE} requires special attention: It performs basically the same
 9735: service as @code{AHEAD}, but it does not create a control-flow stack
 9736: entry. Therefore the information has to be stored elsewhere;
 9737: traditionally, the information was stored in the target fields of the
 9738: branches created by the @code{LEAVE}s, by organizing these fields into a
 9739: linked list. Unfortunately, this clever trick does not provide enough
 9740: space for storing our extended control flow information. Therefore, we
 9741: introduce another stack, the leave stack. It contains the control-flow
 9742: stack entries for all unresolved @code{LEAVE}s.
 9743: 
 9744: Local names are kept until the end of the colon definition, even if
 9745: they are no longer visible in any control-flow path. In a few cases
 9746: this may lead to increased space needs for the locals name area, but
 9747: usually less than reclaiming this space would cost in code size.
 9748: 
 9749: 
 9750: @node ANS Forth locals,  , Gforth locals, Locals
 9751: @subsection ANS Forth locals
 9752: @cindex locals, ANS Forth style
 9753: 
 9754: The ANS Forth locals wordset does not define a syntax for locals, but
 9755: words that make it possible to define various syntaxes. One of the
 9756: possible syntaxes is a subset of the syntax we used in the Gforth locals
 9757: wordset, i.e.:
 9758: 
 9759: @example
 9760: @{ local1 local2 ... -- comment @}
 9761: @end example
 9762: @noindent
 9763: or
 9764: @example
 9765: @{ local1 local2 ... @}
 9766: @end example
 9767: 
 9768: The order of the locals corresponds to the order in a stack comment. The
 9769: restrictions are:
 9770: 
 9771: @itemize @bullet
 9772: @item
 9773: Locals can only be cell-sized values (no type specifiers are allowed).
 9774: @item
 9775: Locals can be defined only outside control structures.
 9776: @item
 9777: Locals can interfere with explicit usage of the return stack. For the
 9778: exact (and long) rules, see the standard. If you don't use return stack
 9779: accessing words in a definition using locals, you will be all right. The
 9780: purpose of this rule is to make locals implementation on the return
 9781: stack easier.
 9782: @item
 9783: The whole definition must be in one line.
 9784: @end itemize
 9785: 
 9786: Locals defined in this way behave like @code{VALUE}s
 9787: (@pxref{Values}). I.e., they are initialized from the stack. Using their
 9788: name produces their value. Their value can be changed using @code{TO}.
 9789: 
 9790: Since this syntax is supported by Gforth directly, you need not do
 9791: anything to use it. If you want to port a program using this syntax to
 9792: another ANS Forth system, use @file{compat/anslocal.fs} to implement the
 9793: syntax on the other system.
 9794: 
 9795: Note that a syntax shown in the standard, section A.13 looks
 9796: similar, but is quite different in having the order of locals
 9797: reversed. Beware!
 9798: 
 9799: The ANS Forth locals wordset itself consists of a word:
 9800: 
 9801: 
 9802: doc-(local)
 9803: 
 9804: 
 9805: The ANS Forth locals extension wordset defines a syntax using @code{locals|}, but it is so
 9806: awful that we strongly recommend not to use it. We have implemented this
 9807: syntax to make porting to Gforth easy, but do not document it here. The
 9808: problem with this syntax is that the locals are defined in an order
 9809: reversed with respect to the standard stack comment notation, making
 9810: programs harder to read, and easier to misread and miswrite. The only
 9811: merit of this syntax is that it is easy to implement using the ANS Forth
 9812: locals wordset.
 9813: 
 9814: 
 9815: @c ----------------------------------------------------------
 9816: @node Structures, Object-oriented Forth, Locals, Words
 9817: @section  Structures
 9818: @cindex structures
 9819: @cindex records
 9820: 
 9821: This section presents the structure package that comes with Gforth. A
 9822: version of the package implemented in ANS Forth is available in
 9823: @file{compat/struct.fs}. This package was inspired by a posting on
 9824: comp.lang.forth in 1989 (unfortunately I don't remember, by whom;
 9825: possibly John Hayes). A version of this section has been published in
 9826: ???. Marcel Hendrix provided helpful comments.
 9827: 
 9828: @menu
 9829: * Why explicit structure support?::  
 9830: * Structure Usage::             
 9831: * Structure Naming Convention::  
 9832: * Structure Implementation::    
 9833: * Structure Glossary::          
 9834: @end menu
 9835: 
 9836: @node Why explicit structure support?, Structure Usage, Structures, Structures
 9837: @subsection Why explicit structure support?
 9838: 
 9839: @cindex address arithmetic for structures
 9840: @cindex structures using address arithmetic
 9841: If we want to use a structure containing several fields, we could simply
 9842: reserve memory for it, and access the fields using address arithmetic
 9843: (@pxref{Address arithmetic}). As an example, consider a structure with
 9844: the following fields
 9845: 
 9846: @table @code
 9847: @item a
 9848: is a float
 9849: @item b
 9850: is a cell
 9851: @item c
 9852: is a float
 9853: @end table
 9854: 
 9855: Given the (float-aligned) base address of the structure we get the
 9856: address of the field
 9857: 
 9858: @table @code
 9859: @item a
 9860: without doing anything further.
 9861: @item b
 9862: with @code{float+}
 9863: @item c
 9864: with @code{float+ cell+ faligned}
 9865: @end table
 9866: 
 9867: It is easy to see that this can become quite tiring. 
 9868: 
 9869: Moreover, it is not very readable, because seeing a
 9870: @code{cell+} tells us neither which kind of structure is
 9871: accessed nor what field is accessed; we have to somehow infer the kind
 9872: of structure, and then look up in the documentation, which field of
 9873: that structure corresponds to that offset.
 9874: 
 9875: Finally, this kind of address arithmetic also causes maintenance
 9876: troubles: If you add or delete a field somewhere in the middle of the
 9877: structure, you have to find and change all computations for the fields
 9878: afterwards.
 9879: 
 9880: So, instead of using @code{cell+} and friends directly, how
 9881: about storing the offsets in constants:
 9882: 
 9883: @example
 9884: 0 constant a-offset
 9885: 0 float+ constant b-offset
 9886: 0 float+ cell+ faligned c-offset
 9887: @end example
 9888: 
 9889: Now we can get the address of field @code{x} with @code{x-offset
 9890: +}. This is much better in all respects. Of course, you still
 9891: have to change all later offset definitions if you add a field. You can
 9892: fix this by declaring the offsets in the following way:
 9893: 
 9894: @example
 9895: 0 constant a-offset
 9896: a-offset float+ constant b-offset
 9897: b-offset cell+ faligned constant c-offset
 9898: @end example
 9899: 
 9900: Since we always use the offsets with @code{+}, we could use a defining
 9901: word @code{cfield} that includes the @code{+} in the action of the
 9902: defined word:
 9903: 
 9904: @example
 9905: : cfield ( n "name" -- )
 9906:     create ,
 9907: does> ( name execution: addr1 -- addr2 )
 9908:     @@ + ;
 9909: 
 9910: 0 cfield a
 9911: 0 a float+ cfield b
 9912: 0 b cell+ faligned cfield c
 9913: @end example
 9914: 
 9915: Instead of @code{x-offset +}, we now simply write @code{x}.
 9916: 
 9917: The structure field words now can be used quite nicely. However,
 9918: their definition is still a bit cumbersome: We have to repeat the
 9919: name, the information about size and alignment is distributed before
 9920: and after the field definitions etc.  The structure package presented
 9921: here addresses these problems.
 9922: 
 9923: @node Structure Usage, Structure Naming Convention, Why explicit structure support?, Structures
 9924: @subsection Structure Usage
 9925: @cindex structure usage
 9926: 
 9927: @cindex @code{field} usage
 9928: @cindex @code{struct} usage
 9929: @cindex @code{end-struct} usage
 9930: You can define a structure for a (data-less) linked list with:
 9931: @example
 9932: struct
 9933:     cell% field list-next
 9934: end-struct list%
 9935: @end example
 9936: 
 9937: With the address of the list node on the stack, you can compute the
 9938: address of the field that contains the address of the next node with
 9939: @code{list-next}. E.g., you can determine the length of a list
 9940: with:
 9941: 
 9942: @example
 9943: : list-length ( list -- n )
 9944: \ "list" is a pointer to the first element of a linked list
 9945: \ "n" is the length of the list
 9946:     0 BEGIN ( list1 n1 )
 9947:         over
 9948:     WHILE ( list1 n1 )
 9949:         1+ swap list-next @@ swap
 9950:     REPEAT
 9951:     nip ;
 9952: @end example
 9953: 
 9954: You can reserve memory for a list node in the dictionary with
 9955: @code{list% %allot}, which leaves the address of the list node on the
 9956: stack. For the equivalent allocation on the heap you can use @code{list%
 9957: %alloc} (or, for an @code{allocate}-like stack effect (i.e., with ior),
 9958: use @code{list% %allocate}). You can get the the size of a list
 9959: node with @code{list% %size} and its alignment with @code{list%
 9960: %alignment}.
 9961: 
 9962: Note that in ANS Forth the body of a @code{create}d word is
 9963: @code{aligned} but not necessarily @code{faligned};
 9964: therefore, if you do a:
 9965: @example
 9966: create @emph{name} foo% %allot
 9967: @end example
 9968: 
 9969: @noindent
 9970: then the memory alloted for @code{foo%} is
 9971: guaranteed to start at the body of @code{@emph{name}} only if
 9972: @code{foo%} contains only character, cell and double fields.
 9973: 
 9974: @cindex structures containing structures
 9975: You can include a structure @code{foo%} as a field of
 9976: another structure, like this:
 9977: @example
 9978: struct
 9979: ...
 9980:     foo% field ...
 9981: ...
 9982: end-struct ...
 9983: @end example
 9984: 
 9985: @cindex structure extension
 9986: @cindex extended records
 9987: Instead of starting with an empty structure, you can extend an
 9988: existing structure. E.g., a plain linked list without data, as defined
 9989: above, is hardly useful; You can extend it to a linked list of integers,
 9990: like this:@footnote{This feature is also known as @emph{extended
 9991: records}. It is the main innovation in the Oberon language; in other
 9992: words, adding this feature to Modula-2 led Wirth to create a new
 9993: language, write a new compiler etc.  Adding this feature to Forth just
 9994: required a few lines of code.}
 9995: 
 9996: @example
 9997: list%
 9998:     cell% field intlist-int
 9999: end-struct intlist%
10000: @end example
10001: 
10002: @code{intlist%} is a structure with two fields:
10003: @code{list-next} and @code{intlist-int}.
10004: 
10005: @cindex structures containing arrays
10006: You can specify an array type containing @emph{n} elements of
10007: type @code{foo%} like this:
10008: 
10009: @example
10010: foo% @emph{n} *
10011: @end example
10012: 
10013: You can use this array type in any place where you can use a normal
10014: type, e.g., when defining a @code{field}, or with
10015: @code{%allot}.
10016: 
10017: @cindex first field optimization
10018: The first field is at the base address of a structure and the word
10019: for this field (e.g., @code{list-next}) actually does not change
10020: the address on the stack. You may be tempted to leave it away in the
10021: interest of run-time and space efficiency. This is not necessary,
10022: because the structure package optimizes this case and compiling such
10023: words does not generate any code. So, in the interest of readability
10024: and maintainability you should include the word for the field when
10025: accessing the field.
10026: 
10027: @node Structure Naming Convention, Structure Implementation, Structure Usage, Structures
10028: @subsection Structure Naming Convention
10029: @cindex structure naming convention
10030: 
10031: The field names that come to (my) mind are often quite generic, and,
10032: if used, would cause frequent name clashes. E.g., many structures
10033: probably contain a @code{counter} field. The structure names
10034: that come to (my) mind are often also the logical choice for the names
10035: of words that create such a structure.
10036: 
10037: Therefore, I have adopted the following naming conventions: 
10038: 
10039: @itemize @bullet
10040: @cindex field naming convention
10041: @item
10042: The names of fields are of the form
10043: @code{@emph{struct}-@emph{field}}, where
10044: @code{@emph{struct}} is the basic name of the structure, and
10045: @code{@emph{field}} is the basic name of the field. You can
10046: think of field words as converting the (address of the)
10047: structure into the (address of the) field.
10048: 
10049: @cindex structure naming convention
10050: @item
10051: The names of structures are of the form
10052: @code{@emph{struct}%}, where
10053: @code{@emph{struct}} is the basic name of the structure.
10054: @end itemize
10055: 
10056: This naming convention does not work that well for fields of extended
10057: structures; e.g., the integer list structure has a field
10058: @code{intlist-int}, but has @code{list-next}, not
10059: @code{intlist-next}.
10060: 
10061: @node Structure Implementation, Structure Glossary, Structure Naming Convention, Structures
10062: @subsection Structure Implementation
10063: @cindex structure implementation
10064: @cindex implementation of structures
10065: 
10066: The central idea in the implementation is to pass the data about the
10067: structure being built on the stack, not in some global
10068: variable. Everything else falls into place naturally once this design
10069: decision is made.
10070: 
10071: The type description on the stack is of the form @emph{align
10072: size}. Keeping the size on the top-of-stack makes dealing with arrays
10073: very simple.
10074: 
10075: @code{field} is a defining word that uses @code{Create}
10076: and @code{DOES>}. The body of the field contains the offset
10077: of the field, and the normal @code{DOES>} action is simply:
10078: 
10079: @example
10080: @@ +
10081: @end example
10082: 
10083: @noindent
10084: i.e., add the offset to the address, giving the stack effect
10085: @i{addr1 -- addr2} for a field.
10086: 
10087: @cindex first field optimization, implementation
10088: This simple structure is slightly complicated by the optimization
10089: for fields with offset 0, which requires a different
10090: @code{DOES>}-part (because we cannot rely on there being
10091: something on the stack if such a field is invoked during
10092: compilation). Therefore, we put the different @code{DOES>}-parts
10093: in separate words, and decide which one to invoke based on the
10094: offset. For a zero offset, the field is basically a noop; it is
10095: immediate, and therefore no code is generated when it is compiled.
10096: 
10097: @node Structure Glossary,  , Structure Implementation, Structures
10098: @subsection Structure Glossary
10099: @cindex structure glossary
10100: 
10101: 
10102: doc-%align
10103: doc-%alignment
10104: doc-%alloc
10105: doc-%allocate
10106: doc-%allot
10107: doc-cell%
10108: doc-char%
10109: doc-dfloat%
10110: doc-double%
10111: doc-end-struct
10112: doc-field
10113: doc-float%
10114: doc-naligned
10115: doc-sfloat%
10116: doc-%size
10117: doc-struct
10118: 
10119: 
10120: @c -------------------------------------------------------------
10121: @node Object-oriented Forth, Passing Commands to the OS, Structures, Words
10122: @section Object-oriented Forth
10123: 
10124: Gforth comes with three packages for object-oriented programming:
10125: @file{objects.fs}, @file{oof.fs}, and @file{mini-oof.fs}; none of them
10126: is preloaded, so you have to @code{include} them before use. The most
10127: important differences between these packages (and others) are discussed
10128: in @ref{Comparison with other object models}. All packages are written
10129: in ANS Forth and can be used with any other ANS Forth.
10130: 
10131: @menu
10132: * Why object-oriented programming?::  
10133: * Object-Oriented Terminology::  
10134: * Objects::                     
10135: * OOF::                         
10136: * Mini-OOF::                    
10137: * Comparison with other object models::  
10138: @end menu
10139: 
10140: @c ----------------------------------------------------------------
10141: @node Why object-oriented programming?, Object-Oriented Terminology, Object-oriented Forth, Object-oriented Forth
10142: @subsection Why object-oriented programming?
10143: @cindex object-oriented programming motivation
10144: @cindex motivation for object-oriented programming
10145: 
10146: Often we have to deal with several data structures (@emph{objects}),
10147: that have to be treated similarly in some respects, but differently in
10148: others. Graphical objects are the textbook example: circles, triangles,
10149: dinosaurs, icons, and others, and we may want to add more during program
10150: development. We want to apply some operations to any graphical object,
10151: e.g., @code{draw} for displaying it on the screen. However, @code{draw}
10152: has to do something different for every kind of object.
10153: @comment TODO add some other operations eg perimeter, area
10154: @comment and tie in to concrete examples later..
10155: 
10156: We could implement @code{draw} as a big @code{CASE}
10157: control structure that executes the appropriate code depending on the
10158: kind of object to be drawn. This would be not be very elegant, and,
10159: moreover, we would have to change @code{draw} every time we add
10160: a new kind of graphical object (say, a spaceship).
10161: 
10162: What we would rather do is: When defining spaceships, we would tell
10163: the system: ``Here's how you @code{draw} a spaceship; you figure
10164: out the rest''.
10165: 
10166: This is the problem that all systems solve that (rightfully) call
10167: themselves object-oriented; the object-oriented packages presented here
10168: solve this problem (and not much else).
10169: @comment TODO ?list properties of oo systems.. oo vs o-based?
10170: 
10171: @c ------------------------------------------------------------------------
10172: @node Object-Oriented Terminology, Objects, Why object-oriented programming?, Object-oriented Forth
10173: @subsection Object-Oriented Terminology
10174: @cindex object-oriented terminology
10175: @cindex terminology for object-oriented programming
10176: 
10177: This section is mainly for reference, so you don't have to understand
10178: all of it right away.  The terminology is mainly Smalltalk-inspired.  In
10179: short:
10180: 
10181: @table @emph
10182: @cindex class
10183: @item class
10184: a data structure definition with some extras.
10185: 
10186: @cindex object
10187: @item object
10188: an instance of the data structure described by the class definition.
10189: 
10190: @cindex instance variables
10191: @item instance variables
10192: fields of the data structure.
10193: 
10194: @cindex selector
10195: @cindex method selector
10196: @cindex virtual function
10197: @item selector
10198: (or @emph{method selector}) a word (e.g.,
10199: @code{draw}) that performs an operation on a variety of data
10200: structures (classes). A selector describes @emph{what} operation to
10201: perform. In C++ terminology: a (pure) virtual function.
10202: 
10203: @cindex method
10204: @item method
10205: the concrete definition that performs the operation
10206: described by the selector for a specific class. A method specifies
10207: @emph{how} the operation is performed for a specific class.
10208: 
10209: @cindex selector invocation
10210: @cindex message send
10211: @cindex invoking a selector
10212: @item selector invocation
10213: a call of a selector. One argument of the call (the TOS (top-of-stack))
10214: is used for determining which method is used. In Smalltalk terminology:
10215: a message (consisting of the selector and the other arguments) is sent
10216: to the object.
10217: 
10218: @cindex receiving object
10219: @item receiving object
10220: the object used for determining the method executed by a selector
10221: invocation. In the @file{objects.fs} model, it is the object that is on
10222: the TOS when the selector is invoked. (@emph{Receiving} comes from
10223: the Smalltalk @emph{message} terminology.)
10224: 
10225: @cindex child class
10226: @cindex parent class
10227: @cindex inheritance
10228: @item child class
10229: a class that has (@emph{inherits}) all properties (instance variables,
10230: selectors, methods) from a @emph{parent class}. In Smalltalk
10231: terminology: The subclass inherits from the superclass. In C++
10232: terminology: The derived class inherits from the base class.
10233: 
10234: @end table
10235: 
10236: @c If you wonder about the message sending terminology, it comes from
10237: @c a time when each object had it's own task and objects communicated via
10238: @c message passing; eventually the Smalltalk developers realized that
10239: @c they can do most things through simple (indirect) calls. They kept the
10240: @c terminology.
10241: 
10242: @c --------------------------------------------------------------
10243: @node Objects, OOF, Object-Oriented Terminology, Object-oriented Forth
10244: @subsection The @file{objects.fs} model
10245: @cindex objects
10246: @cindex object-oriented programming
10247: 
10248: @cindex @file{objects.fs}
10249: @cindex @file{oof.fs}
10250: 
10251: This section describes the @file{objects.fs} package. This material also
10252: has been published in M. Anton Ertl,
10253: @cite{@uref{http://www.complang.tuwien.ac.at/forth/objects/objects.html,
10254: Yet Another Forth Objects Package}}, Forth Dimensions 19(2), pages
10255: 37--43.
10256: @c McKewan's and Zsoter's packages
10257: 
10258: This section assumes that you have read @ref{Structures}.
10259: 
10260: The techniques on which this model is based have been used to implement
10261: the parser generator, Gray, and have also been used in Gforth for
10262: implementing the various flavours of word lists (hashed or not,
10263: case-sensitive or not, special-purpose word lists for locals etc.).
10264: 
10265: 
10266: @menu
10267: * Properties of the Objects model::  
10268: * Basic Objects Usage::         
10269: * The Objects base class::      
10270: * Creating objects::            
10271: * Object-Oriented Programming Style::  
10272: * Class Binding::               
10273: * Method conveniences::         
10274: * Classes and Scoping::         
10275: * Dividing classes::            
10276: * Object Interfaces::           
10277: * Objects Implementation::      
10278: * Objects Glossary::            
10279: @end menu
10280: 
10281: Marcel Hendrix provided helpful comments on this section. Andras Zsoter
10282: and Bernd Paysan helped me with the related works section.
10283: 
10284: @node Properties of the Objects model, Basic Objects Usage, Objects, Objects
10285: @subsubsection Properties of the @file{objects.fs} model
10286: @cindex @file{objects.fs} properties
10287: 
10288: @itemize @bullet
10289: @item
10290: It is straightforward to pass objects on the stack. Passing
10291: selectors on the stack is a little less convenient, but possible.
10292: 
10293: @item
10294: Objects are just data structures in memory, and are referenced by their
10295: address. You can create words for objects with normal defining words
10296: like @code{constant}. Likewise, there is no difference between instance
10297: variables that contain objects and those that contain other data.
10298: 
10299: @item
10300: Late binding is efficient and easy to use.
10301: 
10302: @item
10303: It avoids parsing, and thus avoids problems with state-smartness
10304: and reduced extensibility; for convenience there are a few parsing
10305: words, but they have non-parsing counterparts. There are also a few
10306: defining words that parse. This is hard to avoid, because all standard
10307: defining words parse (except @code{:noname}); however, such
10308: words are not as bad as many other parsing words, because they are not
10309: state-smart.
10310: 
10311: @item
10312: It does not try to incorporate everything. It does a few things and does
10313: them well (IMO). In particular, this model was not designed to support
10314: information hiding (although it has features that may help); you can use
10315: a separate package for achieving this.
10316: 
10317: @item
10318: It is layered; you don't have to learn and use all features to use this
10319: model. Only a few features are necessary (@pxref{Basic Objects Usage},
10320: @pxref{The Objects base class}, @pxref{Creating objects}.), the others
10321: are optional and independent of each other.
10322: 
10323: @item
10324: An implementation in ANS Forth is available.
10325: 
10326: @end itemize
10327: 
10328: 
10329: @node Basic Objects Usage, The Objects base class, Properties of the Objects model, Objects
10330: @subsubsection Basic @file{objects.fs} Usage
10331: @cindex basic objects usage
10332: @cindex objects, basic usage
10333: 
10334: You can define a class for graphical objects like this:
10335: 
10336: @cindex @code{class} usage
10337: @cindex @code{end-class} usage
10338: @cindex @code{selector} usage
10339: @example
10340: object class \ "object" is the parent class
10341:   selector draw ( x y graphical -- )
10342: end-class graphical
10343: @end example
10344: 
10345: This code defines a class @code{graphical} with an
10346: operation @code{draw}.  We can perform the operation
10347: @code{draw} on any @code{graphical} object, e.g.:
10348: 
10349: @example
10350: 100 100 t-rex draw
10351: @end example
10352: 
10353: @noindent
10354: where @code{t-rex} is a word (say, a constant) that produces a
10355: graphical object.
10356: 
10357: @comment TODO add a 2nd operation eg perimeter.. and use for
10358: @comment a concrete example
10359: 
10360: @cindex abstract class
10361: How do we create a graphical object? With the present definitions,
10362: we cannot create a useful graphical object. The class
10363: @code{graphical} describes graphical objects in general, but not
10364: any concrete graphical object type (C++ users would call it an
10365: @emph{abstract class}); e.g., there is no method for the selector
10366: @code{draw} in the class @code{graphical}.
10367: 
10368: For concrete graphical objects, we define child classes of the
10369: class @code{graphical}, e.g.:
10370: 
10371: @cindex @code{overrides} usage
10372: @cindex @code{field} usage in class definition
10373: @example
10374: graphical class \ "graphical" is the parent class
10375:   cell% field circle-radius
10376: 
10377: :noname ( x y circle -- )
10378:   circle-radius @@ draw-circle ;
10379: overrides draw
10380: 
10381: :noname ( n-radius circle -- )
10382:   circle-radius ! ;
10383: overrides construct
10384: 
10385: end-class circle
10386: @end example
10387: 
10388: Here we define a class @code{circle} as a child of @code{graphical},
10389: with field @code{circle-radius} (which behaves just like a field
10390: (@pxref{Structures}); it defines (using @code{overrides}) new methods
10391: for the selectors @code{draw} and @code{construct} (@code{construct} is
10392: defined in @code{object}, the parent class of @code{graphical}).
10393: 
10394: Now we can create a circle on the heap (i.e.,
10395: @code{allocate}d memory) with:
10396: 
10397: @cindex @code{heap-new} usage
10398: @example
10399: 50 circle heap-new constant my-circle
10400: @end example
10401: 
10402: @noindent
10403: @code{heap-new} invokes @code{construct}, thus
10404: initializing the field @code{circle-radius} with 50. We can draw
10405: this new circle at (100,100) with:
10406: 
10407: @example
10408: 100 100 my-circle draw
10409: @end example
10410: 
10411: @cindex selector invocation, restrictions
10412: @cindex class definition, restrictions
10413: Note: You can only invoke a selector if the object on the TOS
10414: (the receiving object) belongs to the class where the selector was
10415: defined or one of its descendents; e.g., you can invoke
10416: @code{draw} only for objects belonging to @code{graphical}
10417: or its descendents (e.g., @code{circle}).  Immediately before
10418: @code{end-class}, the search order has to be the same as
10419: immediately after @code{class}.
10420: 
10421: @node The Objects base class, Creating objects, Basic Objects Usage, Objects
10422: @subsubsection The @file{object.fs} base class
10423: @cindex @code{object} class
10424: 
10425: When you define a class, you have to specify a parent class.  So how do
10426: you start defining classes? There is one class available from the start:
10427: @code{object}. It is ancestor for all classes and so is the
10428: only class that has no parent. It has two selectors: @code{construct}
10429: and @code{print}.
10430: 
10431: @node Creating objects, Object-Oriented Programming Style, The Objects base class, Objects
10432: @subsubsection Creating objects
10433: @cindex creating objects
10434: @cindex object creation
10435: @cindex object allocation options
10436: 
10437: @cindex @code{heap-new} discussion
10438: @cindex @code{dict-new} discussion
10439: @cindex @code{construct} discussion
10440: You can create and initialize an object of a class on the heap with
10441: @code{heap-new} ( ... class -- object ) and in the dictionary
10442: (allocation with @code{allot}) with @code{dict-new} (
10443: ... class -- object ). Both words invoke @code{construct}, which
10444: consumes the stack items indicated by "..." above.
10445: 
10446: @cindex @code{init-object} discussion
10447: @cindex @code{class-inst-size} discussion
10448: If you want to allocate memory for an object yourself, you can get its
10449: alignment and size with @code{class-inst-size 2@@} ( class --
10450: align size ). Once you have memory for an object, you can initialize
10451: it with @code{init-object} ( ... class object -- );
10452: @code{construct} does only a part of the necessary work.
10453: 
10454: @node Object-Oriented Programming Style, Class Binding, Creating objects, Objects
10455: @subsubsection Object-Oriented Programming Style
10456: @cindex object-oriented programming style
10457: @cindex programming style, object-oriented
10458: 
10459: This section is not exhaustive.
10460: 
10461: @cindex stack effects of selectors
10462: @cindex selectors and stack effects
10463: In general, it is a good idea to ensure that all methods for the
10464: same selector have the same stack effect: when you invoke a selector,
10465: you often have no idea which method will be invoked, so, unless all
10466: methods have the same stack effect, you will not know the stack effect
10467: of the selector invocation.
10468: 
10469: One exception to this rule is methods for the selector
10470: @code{construct}. We know which method is invoked, because we
10471: specify the class to be constructed at the same place. Actually, I
10472: defined @code{construct} as a selector only to give the users a
10473: convenient way to specify initialization. The way it is used, a
10474: mechanism different from selector invocation would be more natural
10475: (but probably would take more code and more space to explain).
10476: 
10477: @node Class Binding, Method conveniences, Object-Oriented Programming Style, Objects
10478: @subsubsection Class Binding
10479: @cindex class binding
10480: @cindex early binding
10481: 
10482: @cindex late binding
10483: Normal selector invocations determine the method at run-time depending
10484: on the class of the receiving object. This run-time selection is called
10485: @i{late binding}.
10486: 
10487: Sometimes it's preferable to invoke a different method. For example,
10488: you might want to use the simple method for @code{print}ing
10489: @code{object}s instead of the possibly long-winded @code{print} method
10490: of the receiver class. You can achieve this by replacing the invocation
10491: of @code{print} with:
10492: 
10493: @cindex @code{[bind]} usage
10494: @example
10495: [bind] object print
10496: @end example
10497: 
10498: @noindent
10499: in compiled code or:
10500: 
10501: @cindex @code{bind} usage
10502: @example
10503: bind object print
10504: @end example
10505: 
10506: @cindex class binding, alternative to
10507: @noindent
10508: in interpreted code. Alternatively, you can define the method with a
10509: name (e.g., @code{print-object}), and then invoke it through the
10510: name. Class binding is just a (often more convenient) way to achieve
10511: the same effect; it avoids name clutter and allows you to invoke
10512: methods directly without naming them first.
10513: 
10514: @cindex superclass binding
10515: @cindex parent class binding
10516: A frequent use of class binding is this: When we define a method
10517: for a selector, we often want the method to do what the selector does
10518: in the parent class, and a little more. There is a special word for
10519: this purpose: @code{[parent]}; @code{[parent]
10520: @emph{selector}} is equivalent to @code{[bind] @emph{parent
10521: selector}}, where @code{@emph{parent}} is the parent
10522: class of the current class. E.g., a method definition might look like:
10523: 
10524: @cindex @code{[parent]} usage
10525: @example
10526: :noname
10527:   dup [parent] foo \ do parent's foo on the receiving object
10528:   ... \ do some more
10529: ; overrides foo
10530: @end example
10531: 
10532: @cindex class binding as optimization
10533: In @cite{Object-oriented programming in ANS Forth} (Forth Dimensions,
10534: March 1997), Andrew McKewan presents class binding as an optimization
10535: technique. I recommend not using it for this purpose unless you are in
10536: an emergency. Late binding is pretty fast with this model anyway, so the
10537: benefit of using class binding is small; the cost of using class binding
10538: where it is not appropriate is reduced maintainability.
10539: 
10540: While we are at programming style questions: You should bind
10541: selectors only to ancestor classes of the receiving object. E.g., say,
10542: you know that the receiving object is of class @code{foo} or its
10543: descendents; then you should bind only to @code{foo} and its
10544: ancestors.
10545: 
10546: @node Method conveniences, Classes and Scoping, Class Binding, Objects
10547: @subsubsection Method conveniences
10548: @cindex method conveniences
10549: 
10550: In a method you usually access the receiving object pretty often.  If
10551: you define the method as a plain colon definition (e.g., with
10552: @code{:noname}), you may have to do a lot of stack
10553: gymnastics. To avoid this, you can define the method with @code{m:
10554: ... ;m}. E.g., you could define the method for
10555: @code{draw}ing a @code{circle} with
10556: 
10557: @cindex @code{this} usage
10558: @cindex @code{m:} usage
10559: @cindex @code{;m} usage
10560: @example
10561: m: ( x y circle -- )
10562:   ( x y ) this circle-radius @@ draw-circle ;m
10563: @end example
10564: 
10565: @cindex @code{exit} in @code{m: ... ;m}
10566: @cindex @code{exitm} discussion
10567: @cindex @code{catch} in @code{m: ... ;m}
10568: When this method is executed, the receiver object is removed from the
10569: stack; you can access it with @code{this} (admittedly, in this
10570: example the use of @code{m: ... ;m} offers no advantage). Note
10571: that I specify the stack effect for the whole method (i.e. including
10572: the receiver object), not just for the code between @code{m:}
10573: and @code{;m}. You cannot use @code{exit} in
10574: @code{m:...;m}; instead, use
10575: @code{exitm}.@footnote{Moreover, for any word that calls
10576: @code{catch} and was defined before loading
10577: @code{objects.fs}, you have to redefine it like I redefined
10578: @code{catch}: @code{: catch this >r catch r> to-this ;}}
10579: 
10580: @cindex @code{inst-var} usage
10581: You will frequently use sequences of the form @code{this
10582: @emph{field}} (in the example above: @code{this
10583: circle-radius}). If you use the field only in this way, you can
10584: define it with @code{inst-var} and eliminate the
10585: @code{this} before the field name. E.g., the @code{circle}
10586: class above could also be defined with:
10587: 
10588: @example
10589: graphical class
10590:   cell% inst-var radius
10591: 
10592: m: ( x y circle -- )
10593:   radius @@ draw-circle ;m
10594: overrides draw
10595: 
10596: m: ( n-radius circle -- )
10597:   radius ! ;m
10598: overrides construct
10599: 
10600: end-class circle
10601: @end example
10602: 
10603: @code{radius} can only be used in @code{circle} and its
10604: descendent classes and inside @code{m:...;m}.
10605: 
10606: @cindex @code{inst-value} usage
10607: You can also define fields with @code{inst-value}, which is
10608: to @code{inst-var} what @code{value} is to
10609: @code{variable}.  You can change the value of such a field with
10610: @code{[to-inst]}.  E.g., we could also define the class
10611: @code{circle} like this:
10612: 
10613: @example
10614: graphical class
10615:   inst-value radius
10616: 
10617: m: ( x y circle -- )
10618:   radius draw-circle ;m
10619: overrides draw
10620: 
10621: m: ( n-radius circle -- )
10622:   [to-inst] radius ;m
10623: overrides construct
10624: 
10625: end-class circle
10626: @end example
10627: 
10628: Finally, you can define named methods with @code{:m}.  One use of this
10629: feature is the definition of words that occur only in one class and are
10630: not intended to be overridden, but which still need method context
10631: (e.g., for accessing @code{inst-var}s).  Another use is for methods that
10632: would be bound frequently, if defined anonymously.
10633: 
10634: 
10635: @node Classes and Scoping, Dividing classes, Method conveniences, Objects
10636: @subsubsection Classes and Scoping
10637: @cindex classes and scoping
10638: @cindex scoping and classes
10639: 
10640: Inheritance is frequent, unlike structure extension. This exacerbates
10641: the problem with the field name convention (@pxref{Structure Naming
10642: Convention}): One always has to remember in which class the field was
10643: originally defined; changing a part of the class structure would require
10644: changes for renaming in otherwise unaffected code.
10645: 
10646: @cindex @code{inst-var} visibility
10647: @cindex @code{inst-value} visibility
10648: To solve this problem, I added a scoping mechanism (which was not in my
10649: original charter): A field defined with @code{inst-var} (or
10650: @code{inst-value}) is visible only in the class where it is defined and in
10651: the descendent classes of this class.  Using such fields only makes
10652: sense in @code{m:}-defined methods in these classes anyway.
10653: 
10654: This scoping mechanism allows us to use the unadorned field name,
10655: because name clashes with unrelated words become much less likely.
10656: 
10657: @cindex @code{protected} discussion
10658: @cindex @code{private} discussion
10659: Once we have this mechanism, we can also use it for controlling the
10660: visibility of other words: All words defined after
10661: @code{protected} are visible only in the current class and its
10662: descendents. @code{public} restores the compilation
10663: (i.e. @code{current}) word list that was in effect before. If you
10664: have several @code{protected}s without an intervening
10665: @code{public} or @code{set-current}, @code{public}
10666: will restore the compilation word list in effect before the first of
10667: these @code{protected}s.
10668: 
10669: @node Dividing classes, Object Interfaces, Classes and Scoping, Objects
10670: @subsubsection Dividing classes
10671: @cindex Dividing classes
10672: @cindex @code{methods}...@code{end-methods}
10673: 
10674: You may want to do the definition of methods separate from the
10675: definition of the class, its selectors, fields, and instance variables,
10676: i.e., separate the implementation from the definition.  You can do this
10677: in the following way:
10678: 
10679: @example
10680: graphical class
10681:   inst-value radius
10682: end-class circle
10683: 
10684: ... \ do some other stuff
10685: 
10686: circle methods \ now we are ready
10687: 
10688: m: ( x y circle -- )
10689:   radius draw-circle ;m
10690: overrides draw
10691: 
10692: m: ( n-radius circle -- )
10693:   [to-inst] radius ;m
10694: overrides construct
10695: 
10696: end-methods
10697: @end example
10698: 
10699: You can use several @code{methods}...@code{end-methods} sections.  The
10700: only things you can do to the class in these sections are: defining
10701: methods, and overriding the class's selectors.  You must not define new
10702: selectors or fields.
10703: 
10704: Note that you often have to override a selector before using it.  In
10705: particular, you usually have to override @code{construct} with a new
10706: method before you can invoke @code{heap-new} and friends.  E.g., you
10707: must not create a circle before the @code{overrides construct} sequence
10708: in the example above.
10709: 
10710: @node Object Interfaces, Objects Implementation, Dividing classes, Objects
10711: @subsubsection Object Interfaces
10712: @cindex object interfaces
10713: @cindex interfaces for objects
10714: 
10715: In this model you can only call selectors defined in the class of the
10716: receiving objects or in one of its ancestors. If you call a selector
10717: with a receiving object that is not in one of these classes, the
10718: result is undefined; if you are lucky, the program crashes
10719: immediately.
10720: 
10721: @cindex selectors common to hardly-related classes
10722: Now consider the case when you want to have a selector (or several)
10723: available in two classes: You would have to add the selector to a
10724: common ancestor class, in the worst case to @code{object}. You
10725: may not want to do this, e.g., because someone else is responsible for
10726: this ancestor class.
10727: 
10728: The solution for this problem is interfaces. An interface is a
10729: collection of selectors. If a class implements an interface, the
10730: selectors become available to the class and its descendents. A class
10731: can implement an unlimited number of interfaces. For the problem
10732: discussed above, we would define an interface for the selector(s), and
10733: both classes would implement the interface.
10734: 
10735: As an example, consider an interface @code{storage} for
10736: writing objects to disk and getting them back, and a class
10737: @code{foo} that implements it. The code would look like this:
10738: 
10739: @cindex @code{interface} usage
10740: @cindex @code{end-interface} usage
10741: @cindex @code{implementation} usage
10742: @example
10743: interface
10744:   selector write ( file object -- )
10745:   selector read1 ( file object -- )
10746: end-interface storage
10747: 
10748: bar class
10749:   storage implementation
10750: 
10751: ... overrides write
10752: ... overrides read1
10753: ...
10754: end-class foo
10755: @end example
10756: 
10757: @noindent
10758: (I would add a word @code{read} @i{( file -- object )} that uses
10759: @code{read1} internally, but that's beyond the point illustrated
10760: here.)
10761: 
10762: Note that you cannot use @code{protected} in an interface; and
10763: of course you cannot define fields.
10764: 
10765: In the Neon model, all selectors are available for all classes;
10766: therefore it does not need interfaces. The price you pay in this model
10767: is slower late binding, and therefore, added complexity to avoid late
10768: binding.
10769: 
10770: @node Objects Implementation, Objects Glossary, Object Interfaces, Objects
10771: @subsubsection @file{objects.fs} Implementation
10772: @cindex @file{objects.fs} implementation
10773: 
10774: @cindex @code{object-map} discussion
10775: An object is a piece of memory, like one of the data structures
10776: described with @code{struct...end-struct}. It has a field
10777: @code{object-map} that points to the method map for the object's
10778: class.
10779: 
10780: @cindex method map
10781: @cindex virtual function table
10782: The @emph{method map}@footnote{This is Self terminology; in C++
10783: terminology: virtual function table.} is an array that contains the
10784: execution tokens (@i{xt}s) of the methods for the object's class. Each
10785: selector contains an offset into a method map.
10786: 
10787: @cindex @code{selector} implementation, class
10788: @code{selector} is a defining word that uses
10789: @code{CREATE} and @code{DOES>}. The body of the
10790: selector contains the offset; the @code{DOES>} action for a
10791: class selector is, basically:
10792: 
10793: @example
10794: ( object addr ) @@ over object-map @@ + @@ execute
10795: @end example
10796: 
10797: Since @code{object-map} is the first field of the object, it
10798: does not generate any code. As you can see, calling a selector has a
10799: small, constant cost.
10800: 
10801: @cindex @code{current-interface} discussion
10802: @cindex class implementation and representation
10803: A class is basically a @code{struct} combined with a method
10804: map. During the class definition the alignment and size of the class
10805: are passed on the stack, just as with @code{struct}s, so
10806: @code{field} can also be used for defining class
10807: fields. However, passing more items on the stack would be
10808: inconvenient, so @code{class} builds a data structure in memory,
10809: which is accessed through the variable
10810: @code{current-interface}. After its definition is complete, the
10811: class is represented on the stack by a pointer (e.g., as parameter for
10812: a child class definition).
10813: 
10814: A new class starts off with the alignment and size of its parent,
10815: and a copy of the parent's method map. Defining new fields extends the
10816: size and alignment; likewise, defining new selectors extends the
10817: method map. @code{overrides} just stores a new @i{xt} in the method
10818: map at the offset given by the selector.
10819: 
10820: @cindex class binding, implementation
10821: Class binding just gets the @i{xt} at the offset given by the selector
10822: from the class's method map and @code{compile,}s (in the case of
10823: @code{[bind]}) it.
10824: 
10825: @cindex @code{this} implementation
10826: @cindex @code{catch} and @code{this}
10827: @cindex @code{this} and @code{catch}
10828: I implemented @code{this} as a @code{value}. At the
10829: start of an @code{m:...;m} method the old @code{this} is
10830: stored to the return stack and restored at the end; and the object on
10831: the TOS is stored @code{TO this}. This technique has one
10832: disadvantage: If the user does not leave the method via
10833: @code{;m}, but via @code{throw} or @code{exit},
10834: @code{this} is not restored (and @code{exit} may
10835: crash). To deal with the @code{throw} problem, I have redefined
10836: @code{catch} to save and restore @code{this}; the same
10837: should be done with any word that can catch an exception. As for
10838: @code{exit}, I simply forbid it (as a replacement, there is
10839: @code{exitm}).
10840: 
10841: @cindex @code{inst-var} implementation
10842: @code{inst-var} is just the same as @code{field}, with
10843: a different @code{DOES>} action:
10844: @example
10845: @@ this +
10846: @end example
10847: Similar for @code{inst-value}.
10848: 
10849: @cindex class scoping implementation
10850: Each class also has a word list that contains the words defined with
10851: @code{inst-var} and @code{inst-value}, and its protected
10852: words. It also has a pointer to its parent. @code{class} pushes
10853: the word lists of the class and all its ancestors onto the search order stack,
10854: and @code{end-class} drops them.
10855: 
10856: @cindex interface implementation
10857: An interface is like a class without fields, parent and protected
10858: words; i.e., it just has a method map. If a class implements an
10859: interface, its method map contains a pointer to the method map of the
10860: interface. The positive offsets in the map are reserved for class
10861: methods, therefore interface map pointers have negative
10862: offsets. Interfaces have offsets that are unique throughout the
10863: system, unlike class selectors, whose offsets are only unique for the
10864: classes where the selector is available (invokable).
10865: 
10866: This structure means that interface selectors have to perform one
10867: indirection more than class selectors to find their method. Their body
10868: contains the interface map pointer offset in the class method map, and
10869: the method offset in the interface method map. The
10870: @code{does>} action for an interface selector is, basically:
10871: 
10872: @example
10873: ( object selector-body )
10874: 2dup selector-interface @@ ( object selector-body object interface-offset )
10875: swap object-map @@ + @@ ( object selector-body map )
10876: swap selector-offset @@ + @@ execute
10877: @end example
10878: 
10879: where @code{object-map} and @code{selector-offset} are
10880: first fields and generate no code.
10881: 
10882: As a concrete example, consider the following code:
10883: 
10884: @example
10885: interface
10886:   selector if1sel1
10887:   selector if1sel2
10888: end-interface if1
10889: 
10890: object class
10891:   if1 implementation
10892:   selector cl1sel1
10893:   cell% inst-var cl1iv1
10894: 
10895: ' m1 overrides construct
10896: ' m2 overrides if1sel1
10897: ' m3 overrides if1sel2
10898: ' m4 overrides cl1sel2
10899: end-class cl1
10900: 
10901: create obj1 object dict-new drop
10902: create obj2 cl1    dict-new drop
10903: @end example
10904: 
10905: The data structure created by this code (including the data structure
10906: for @code{object}) is shown in the <a
10907: href="objects-implementation.eps">figure</a>, assuming a cell size of 4.
10908: @comment TODO add this diagram..
10909: 
10910: @node Objects Glossary,  , Objects Implementation, Objects
10911: @subsubsection @file{objects.fs} Glossary
10912: @cindex @file{objects.fs} Glossary
10913: 
10914: 
10915: doc---objects-bind
10916: doc---objects-<bind>
10917: doc---objects-bind'
10918: doc---objects-[bind]
10919: doc---objects-class
10920: doc---objects-class->map
10921: doc---objects-class-inst-size
10922: doc---objects-class-override!
10923: doc---objects-construct
10924: doc---objects-current'
10925: doc---objects-[current]
10926: doc---objects-current-interface
10927: doc---objects-dict-new
10928: doc---objects-drop-order
10929: doc---objects-end-class
10930: doc---objects-end-class-noname
10931: doc---objects-end-interface
10932: doc---objects-end-interface-noname
10933: doc---objects-end-methods
10934: doc---objects-exitm
10935: doc---objects-heap-new
10936: doc---objects-implementation
10937: doc---objects-init-object
10938: doc---objects-inst-value
10939: doc---objects-inst-var
10940: doc---objects-interface
10941: doc---objects-m:
10942: doc---objects-:m
10943: doc---objects-;m
10944: doc---objects-method
10945: doc---objects-methods
10946: doc---objects-object
10947: doc---objects-overrides
10948: doc---objects-[parent]
10949: doc---objects-print
10950: doc---objects-protected
10951: doc---objects-public
10952: doc---objects-push-order
10953: doc---objects-selector
10954: doc---objects-this
10955: doc---objects-<to-inst>
10956: doc---objects-[to-inst]
10957: doc---objects-to-this
10958: doc---objects-xt-new
10959: 
10960: 
10961: @c -------------------------------------------------------------
10962: @node OOF, Mini-OOF, Objects, Object-oriented Forth
10963: @subsection The @file{oof.fs} model
10964: @cindex oof
10965: @cindex object-oriented programming
10966: 
10967: @cindex @file{objects.fs}
10968: @cindex @file{oof.fs}
10969: 
10970: This section describes the @file{oof.fs} package.
10971: 
10972: The package described in this section has been used in bigFORTH since 1991, and
10973: used for two large applications: a chromatographic system used to
10974: create new medicaments, and a graphic user interface library (MINOS).
10975: 
10976: You can find a description (in German) of @file{oof.fs} in @cite{Object
10977: oriented bigFORTH} by Bernd Paysan, published in @cite{Vierte Dimension}
10978: 10(2), 1994.
10979: 
10980: @menu
10981: * Properties of the OOF model::  
10982: * Basic OOF Usage::             
10983: * The OOF base class::          
10984: * Class Declaration::           
10985: * Class Implementation::        
10986: @end menu
10987: 
10988: @node Properties of the OOF model, Basic OOF Usage, OOF, OOF
10989: @subsubsection Properties of the @file{oof.fs} model
10990: @cindex @file{oof.fs} properties
10991: 
10992: @itemize @bullet
10993: @item
10994: This model combines object oriented programming with information
10995: hiding. It helps you writing large application, where scoping is
10996: necessary, because it provides class-oriented scoping.
10997: 
10998: @item
10999: Named objects, object pointers, and object arrays can be created,
11000: selector invocation uses the ``object selector'' syntax. Selector invocation
11001: to objects and/or selectors on the stack is a bit less convenient, but
11002: possible.
11003: 
11004: @item
11005: Selector invocation and instance variable usage of the active object is
11006: straightforward, since both make use of the active object.
11007: 
11008: @item
11009: Late binding is efficient and easy to use.
11010: 
11011: @item
11012: State-smart objects parse selectors. However, extensibility is provided
11013: using a (parsing) selector @code{postpone} and a selector @code{'}.
11014: 
11015: @item
11016: An implementation in ANS Forth is available.
11017: 
11018: @end itemize
11019: 
11020: 
11021: @node Basic OOF Usage, The OOF base class, Properties of the OOF model, OOF
11022: @subsubsection Basic @file{oof.fs} Usage
11023: @cindex @file{oof.fs} usage
11024: 
11025: This section uses the same example as for @code{objects} (@pxref{Basic Objects Usage}).
11026: 
11027: You can define a class for graphical objects like this:
11028: 
11029: @cindex @code{class} usage
11030: @cindex @code{class;} usage
11031: @cindex @code{method} usage
11032: @example
11033: object class graphical \ "object" is the parent class
11034:   method draw ( x y graphical -- )
11035: class;
11036: @end example
11037: 
11038: This code defines a class @code{graphical} with an
11039: operation @code{draw}.  We can perform the operation
11040: @code{draw} on any @code{graphical} object, e.g.:
11041: 
11042: @example
11043: 100 100 t-rex draw
11044: @end example
11045: 
11046: @noindent
11047: where @code{t-rex} is an object or object pointer, created with e.g.
11048: @code{graphical : t-rex}.
11049: 
11050: @cindex abstract class
11051: How do we create a graphical object? With the present definitions,
11052: we cannot create a useful graphical object. The class
11053: @code{graphical} describes graphical objects in general, but not
11054: any concrete graphical object type (C++ users would call it an
11055: @emph{abstract class}); e.g., there is no method for the selector
11056: @code{draw} in the class @code{graphical}.
11057: 
11058: For concrete graphical objects, we define child classes of the
11059: class @code{graphical}, e.g.:
11060: 
11061: @example
11062: graphical class circle \ "graphical" is the parent class
11063:   cell var circle-radius
11064: how:
11065:   : draw ( x y -- )
11066:     circle-radius @@ draw-circle ;
11067: 
11068:   : init ( n-radius -- (
11069:     circle-radius ! ;
11070: class;
11071: @end example
11072: 
11073: Here we define a class @code{circle} as a child of @code{graphical},
11074: with a field @code{circle-radius}; it defines new methods for the
11075: selectors @code{draw} and @code{init} (@code{init} is defined in
11076: @code{object}, the parent class of @code{graphical}).
11077: 
11078: Now we can create a circle in the dictionary with:
11079: 
11080: @example
11081: 50 circle : my-circle
11082: @end example
11083: 
11084: @noindent
11085: @code{:} invokes @code{init}, thus initializing the field
11086: @code{circle-radius} with 50. We can draw this new circle at (100,100)
11087: with:
11088: 
11089: @example
11090: 100 100 my-circle draw
11091: @end example
11092: 
11093: @cindex selector invocation, restrictions
11094: @cindex class definition, restrictions
11095: Note: You can only invoke a selector if the receiving object belongs to
11096: the class where the selector was defined or one of its descendents;
11097: e.g., you can invoke @code{draw} only for objects belonging to
11098: @code{graphical} or its descendents (e.g., @code{circle}). The scoping
11099: mechanism will check if you try to invoke a selector that is not
11100: defined in this class hierarchy, so you'll get an error at compilation
11101: time.
11102: 
11103: 
11104: @node The OOF base class, Class Declaration, Basic OOF Usage, OOF
11105: @subsubsection The @file{oof.fs} base class
11106: @cindex @file{oof.fs} base class
11107: 
11108: When you define a class, you have to specify a parent class.  So how do
11109: you start defining classes? There is one class available from the start:
11110: @code{object}. You have to use it as ancestor for all classes. It is the
11111: only class that has no parent. Classes are also objects, except that
11112: they don't have instance variables; class manipulation such as
11113: inheritance or changing definitions of a class is handled through
11114: selectors of the class @code{object}.
11115: 
11116: @code{object} provides a number of selectors:
11117: 
11118: @itemize @bullet
11119: @item
11120: @code{class} for subclassing, @code{definitions} to add definitions
11121: later on, and @code{class?} to get type informations (is the class a
11122: subclass of the class passed on the stack?).
11123: 
11124: doc---object-class
11125: doc---object-definitions
11126: doc---object-class?
11127: 
11128: 
11129: @item
11130: @code{init} and @code{dispose} as constructor and destructor of the
11131: object. @code{init} is invocated after the object's memory is allocated,
11132: while @code{dispose} also handles deallocation. Thus if you redefine
11133: @code{dispose}, you have to call the parent's dispose with @code{super
11134: dispose}, too.
11135: 
11136: doc---object-init
11137: doc---object-dispose
11138: 
11139: 
11140: @item
11141: @code{new}, @code{new[]}, @code{:}, @code{ptr}, @code{asptr}, and
11142: @code{[]} to create named and unnamed objects and object arrays or
11143: object pointers.
11144: 
11145: doc---object-new
11146: doc---object-new[]
11147: doc---object-:
11148: doc---object-ptr
11149: doc---object-asptr
11150: doc---object-[]
11151: 
11152: 
11153: @item
11154: @code{::} and @code{super} for explicit scoping. You should use explicit
11155: scoping only for super classes or classes with the same set of instance
11156: variables. Explicitly-scoped selectors use early binding.
11157: 
11158: doc---object-::
11159: doc---object-super
11160: 
11161: 
11162: @item
11163: @code{self} to get the address of the object
11164: 
11165: doc---object-self
11166: 
11167: 
11168: @item
11169: @code{bind}, @code{bound}, @code{link}, and @code{is} to assign object
11170: pointers and instance defers.
11171: 
11172: doc---object-bind
11173: doc---object-bound
11174: doc---object-link
11175: doc---object-is
11176: 
11177: 
11178: @item
11179: @code{'} to obtain selector tokens, @code{send} to invocate selectors
11180: form the stack, and @code{postpone} to generate selector invocation code.
11181: 
11182: doc---object-'
11183: doc---object-postpone
11184: 
11185: 
11186: @item
11187: @code{with} and @code{endwith} to select the active object from the
11188: stack, and enable its scope. Using @code{with} and @code{endwith}
11189: also allows you to create code using selector @code{postpone} without being
11190: trapped by the state-smart objects.
11191: 
11192: doc---object-with
11193: doc---object-endwith
11194: 
11195: 
11196: @end itemize
11197: 
11198: @node Class Declaration, Class Implementation, The OOF base class, OOF
11199: @subsubsection Class Declaration
11200: @cindex class declaration
11201: 
11202: @itemize @bullet
11203: @item
11204: Instance variables
11205: 
11206: doc---oof-var
11207: 
11208: 
11209: @item
11210: Object pointers
11211: 
11212: doc---oof-ptr
11213: doc---oof-asptr
11214: 
11215: 
11216: @item
11217: Instance defers
11218: 
11219: doc---oof-defer
11220: 
11221: 
11222: @item
11223: Method selectors
11224: 
11225: doc---oof-early
11226: doc---oof-method
11227: 
11228: 
11229: @item
11230: Class-wide variables
11231: 
11232: doc---oof-static
11233: 
11234: 
11235: @item
11236: End declaration
11237: 
11238: doc---oof-how:
11239: doc---oof-class;
11240: 
11241: 
11242: @end itemize
11243: 
11244: @c -------------------------------------------------------------
11245: @node Class Implementation,  , Class Declaration, OOF
11246: @subsubsection Class Implementation
11247: @cindex class implementation
11248: 
11249: @c -------------------------------------------------------------
11250: @node Mini-OOF, Comparison with other object models, OOF, Object-oriented Forth
11251: @subsection The @file{mini-oof.fs} model
11252: @cindex mini-oof
11253: 
11254: Gforth's third object oriented Forth package is a 12-liner. It uses a
11255: mixture of the @file{object.fs} and the @file{oof.fs} syntax,
11256: and reduces to the bare minimum of features. This is based on a posting
11257: of Bernd Paysan in comp.lang.forth.
11258: 
11259: @menu
11260: * Basic Mini-OOF Usage::        
11261: * Mini-OOF Example::            
11262: * Mini-OOF Implementation::     
11263: @end menu
11264: 
11265: @c -------------------------------------------------------------
11266: @node Basic Mini-OOF Usage, Mini-OOF Example, Mini-OOF, Mini-OOF
11267: @subsubsection Basic @file{mini-oof.fs} Usage
11268: @cindex mini-oof usage
11269: 
11270: There is a base class (@code{class}, which allocates one cell for the
11271: object pointer) plus seven other words: to define a method, a variable,
11272: a class; to end a class, to resolve binding, to allocate an object and
11273: to compile a class method.
11274: @comment TODO better description of the last one
11275: 
11276: 
11277: doc-object
11278: doc-method
11279: doc-var
11280: doc-class
11281: doc-end-class
11282: doc-defines
11283: doc-new
11284: doc-::
11285: 
11286: 
11287: 
11288: @c -------------------------------------------------------------
11289: @node Mini-OOF Example, Mini-OOF Implementation, Basic Mini-OOF Usage, Mini-OOF
11290: @subsubsection Mini-OOF Example
11291: @cindex mini-oof example
11292: 
11293: A short example shows how to use this package. This example, in slightly
11294: extended form, is supplied as @file{moof-exm.fs}
11295: @comment TODO could flesh this out with some comments from the Forthwrite article
11296: 
11297: @example
11298: object class
11299:   method init
11300:   method draw
11301: end-class graphical
11302: @end example
11303: 
11304: This code defines a class @code{graphical} with an
11305: operation @code{draw}.  We can perform the operation
11306: @code{draw} on any @code{graphical} object, e.g.:
11307: 
11308: @example
11309: 100 100 t-rex draw
11310: @end example
11311: 
11312: where @code{t-rex} is an object or object pointer, created with e.g.
11313: @code{graphical new Constant t-rex}.
11314: 
11315: For concrete graphical objects, we define child classes of the
11316: class @code{graphical}, e.g.:
11317: 
11318: @example
11319: graphical class
11320:   cell var circle-radius
11321: end-class circle \ "graphical" is the parent class
11322: 
11323: :noname ( x y -- )
11324:   circle-radius @@ draw-circle ; circle defines draw
11325: :noname ( r -- )
11326:   circle-radius ! ; circle defines init
11327: @end example
11328: 
11329: There is no implicit init method, so we have to define one. The creation
11330: code of the object now has to call init explicitely.
11331: 
11332: @example
11333: circle new Constant my-circle
11334: 50 my-circle init
11335: @end example
11336: 
11337: It is also possible to add a function to create named objects with
11338: automatic call of @code{init}, given that all objects have @code{init}
11339: on the same place:
11340: 
11341: @example
11342: : new: ( .. o "name" -- )
11343:     new dup Constant init ;
11344: 80 circle new: large-circle
11345: @end example
11346: 
11347: We can draw this new circle at (100,100) with:
11348: 
11349: @example
11350: 100 100 my-circle draw
11351: @end example
11352: 
11353: @node Mini-OOF Implementation,  , Mini-OOF Example, Mini-OOF
11354: @subsubsection @file{mini-oof.fs} Implementation
11355: 
11356: Object-oriented systems with late binding typically use a
11357: ``vtable''-approach: the first variable in each object is a pointer to a
11358: table, which contains the methods as function pointers. The vtable
11359: may also contain other information.
11360: 
11361: So first, let's declare methods:
11362: 
11363: @example
11364: : method ( m v -- m' v ) Create  over , swap cell+ swap
11365:   DOES> ( ... o -- ... ) @ over @ + @ execute ;
11366: @end example
11367: 
11368: During method declaration, the number of methods and instance
11369: variables is on the stack (in address units). @code{method} creates
11370: one method and increments the method number. To execute a method, it
11371: takes the object, fetches the vtable pointer, adds the offset, and
11372: executes the @i{xt} stored there. Each method takes the object it is
11373: invoked from as top of stack parameter. The method itself should
11374: consume that object.
11375: 
11376: Now, we also have to declare instance variables
11377: 
11378: @example
11379: : var ( m v size -- m v' ) Create  over , +
11380:   DOES> ( o -- addr ) @ + ;
11381: @end example
11382: 
11383: As before, a word is created with the current offset. Instance
11384: variables can have different sizes (cells, floats, doubles, chars), so
11385: all we do is take the size and add it to the offset. If your machine
11386: has alignment restrictions, put the proper @code{aligned} or
11387: @code{faligned} before the variable, to adjust the variable
11388: offset. That's why it is on the top of stack.
11389: 
11390: We need a starting point (the base object) and some syntactic sugar:
11391: 
11392: @example
11393: Create object  1 cells , 2 cells ,
11394: : class ( class -- class methods vars ) dup 2@ ;
11395: @end example
11396: 
11397: For inheritance, the vtable of the parent object has to be
11398: copied when a new, derived class is declared. This gives all the
11399: methods of the parent class, which can be overridden, though.
11400: 
11401: @example
11402: : end-class  ( class methods vars -- )
11403:   Create  here >r , dup , 2 cells ?DO ['] noop , 1 cells +LOOP
11404:   cell+ dup cell+ r> rot @ 2 cells /string move ;
11405: @end example
11406: 
11407: The first line creates the vtable, initialized with
11408: @code{noop}s. The second line is the inheritance mechanism, it
11409: copies the xts from the parent vtable.
11410: 
11411: We still have no way to define new methods, let's do that now:
11412: 
11413: @example
11414: : defines ( xt class -- ) ' >body @ + ! ;
11415: @end example
11416: 
11417: To allocate a new object, we need a word, too:
11418: 
11419: @example
11420: : new ( class -- o )  here over @ allot swap over ! ;
11421: @end example
11422: 
11423: Sometimes derived classes want to access the method of the
11424: parent object. There are two ways to achieve this with Mini-OOF:
11425: first, you could use named words, and second, you could look up the
11426: vtable of the parent object.
11427: 
11428: @example
11429: : :: ( class "name" -- ) ' >body @ + @ compile, ;
11430: @end example
11431: 
11432: 
11433: Nothing can be more confusing than a good example, so here is
11434: one. First let's declare a text object (called
11435: @code{button}), that stores text and position:
11436: 
11437: @example
11438: object class
11439:   cell var text
11440:   cell var len
11441:   cell var x
11442:   cell var y
11443:   method init
11444:   method draw
11445: end-class button
11446: @end example
11447: 
11448: @noindent
11449: Now, implement the two methods, @code{draw} and @code{init}:
11450: 
11451: @example
11452: :noname ( o -- )
11453:  >r r@ x @ r@ y @ at-xy  r@ text @ r> len @ type ;
11454:  button defines draw
11455: :noname ( addr u o -- )
11456:  >r 0 r@ x ! 0 r@ y ! r@ len ! r> text ! ;
11457:  button defines init
11458: @end example
11459: 
11460: @noindent
11461: To demonstrate inheritance, we define a class @code{bold-button}, with no
11462: new data and no new methods:
11463: 
11464: @example
11465: button class
11466: end-class bold-button
11467: 
11468: : bold   27 emit ." [1m" ;
11469: : normal 27 emit ." [0m" ;
11470: @end example
11471: 
11472: @noindent
11473: The class @code{bold-button} has a different draw method to
11474: @code{button}, but the new method is defined in terms of the draw method
11475: for @code{button}:
11476: 
11477: @example
11478: :noname bold [ button :: draw ] normal ; bold-button defines draw
11479: @end example
11480: 
11481: @noindent
11482: Finally, create two objects and apply methods:
11483: 
11484: @example
11485: button new Constant foo
11486: s" thin foo" foo init
11487: page
11488: foo draw
11489: bold-button new Constant bar
11490: s" fat bar" bar init
11491: 1 bar y !
11492: bar draw
11493: @end example
11494: 
11495: 
11496: @node Comparison with other object models,  , Mini-OOF, Object-oriented Forth
11497: @subsection Comparison with other object models
11498: @cindex comparison of object models
11499: @cindex object models, comparison
11500: 
11501: Many object-oriented Forth extensions have been proposed (@cite{A survey
11502: of object-oriented Forths} (SIGPLAN Notices, April 1996) by Bradford
11503: J. Rodriguez and W. F. S. Poehlman lists 17). This section discusses the
11504: relation of the object models described here to two well-known and two
11505: closely-related (by the use of method maps) models.
11506: 
11507: @cindex Neon model
11508: The most popular model currently seems to be the Neon model (see
11509: @cite{Object-oriented programming in ANS Forth} (Forth Dimensions, March
11510: 1997) by Andrew McKewan) but this model has a number of limitations
11511: @footnote{A longer version of this critique can be
11512: found in @cite{On Standardizing Object-Oriented Forth Extensions} (Forth
11513: Dimensions, May 1997) by Anton Ertl.}:
11514: 
11515: @itemize @bullet
11516: @item
11517: It uses a @code{@emph{selector object}} syntax, which makes it unnatural
11518: to pass objects on the stack.
11519: 
11520: @item
11521: It requires that the selector parses the input stream (at
11522: compile time); this leads to reduced extensibility and to bugs that are+
11523: hard to find.
11524: 
11525: @item
11526: It allows using every selector to every object;
11527: this eliminates the need for classes, but makes it harder to create
11528: efficient implementations. 
11529: @end itemize
11530: 
11531: @cindex Pountain's object-oriented model
11532: Another well-known publication is @cite{Object-Oriented Forth} (Academic
11533: Press, London, 1987) by Dick Pountain. However, it is not really about
11534: object-oriented programming, because it hardly deals with late
11535: binding. Instead, it focuses on features like information hiding and
11536: overloading that are characteristic of modular languages like Ada (83).
11537: 
11538: @cindex Zsoter's object-oriented model
11539: In @cite{Does late binding have to be slow?} (Forth Dimensions 18(1)
11540: 1996, pages 31-35) Andras Zsoter describes a model that makes heavy use
11541: of an active object (like @code{this} in @file{objects.fs}): The active
11542: object is not only used for accessing all fields, but also specifies the
11543: receiving object of every selector invocation; you have to change the
11544: active object explicitly with @code{@{ ... @}}, whereas in
11545: @file{objects.fs} it changes more or less implicitly at @code{m:
11546: ... ;m}. Such a change at the method entry point is unnecessary with the
11547: Zsoter's model, because the receiving object is the active object
11548: already. On the other hand, the explicit change is absolutely necessary
11549: in that model, because otherwise no one could ever change the active
11550: object. An ANS Forth implementation of this model is available at
11551: @uref{http://www.forth.org/fig/oopf.html}.
11552: 
11553: @cindex @file{oof.fs}, differences to other models
11554: The @file{oof.fs} model combines information hiding and overloading
11555: resolution (by keeping names in various word lists) with object-oriented
11556: programming. It sets the active object implicitly on method entry, but
11557: also allows explicit changing (with @code{>o...o>} or with
11558: @code{with...endwith}). It uses parsing and state-smart objects and
11559: classes for resolving overloading and for early binding: the object or
11560: class parses the selector and determines the method from this. If the
11561: selector is not parsed by an object or class, it performs a call to the
11562: selector for the active object (late binding), like Zsoter's model.
11563: Fields are always accessed through the active object. The big
11564: disadvantage of this model is the parsing and the state-smartness, which
11565: reduces extensibility and increases the opportunities for subtle bugs;
11566: essentially, you are only safe if you never tick or @code{postpone} an
11567: object or class (Bernd disagrees, but I (Anton) am not convinced).
11568: 
11569: @cindex @file{mini-oof.fs}, differences to other models
11570: The @file{mini-oof.fs} model is quite similar to a very stripped-down
11571: version of the @file{objects.fs} model, but syntactically it is a
11572: mixture of the @file{objects.fs} and @file{oof.fs} models.
11573: 
11574: @c -------------------------------------------------------------
11575: @node Passing Commands to the OS, Keeping track of Time, Object-oriented Forth, Words
11576: @section Passing Commands to the Operating System
11577: @cindex operating system - passing commands
11578: @cindex shell commands
11579: 
11580: Gforth allows you to pass an arbitrary string to the host operating
11581: system shell (if such a thing exists) for execution.
11582: 
11583: 
11584: doc-sh
11585: doc-system
11586: doc-$?
11587: doc-getenv
11588: 
11589: 
11590: @c -------------------------------------------------------------
11591: @node Keeping track of Time, Miscellaneous Words, Passing Commands to the OS, Words
11592: @section Keeping track of Time
11593: @cindex time-related words
11594: 
11595: Gforth implements time-related operations by making calls to the C
11596: library function, @code{gettimeofday}.
11597: 
11598: doc-ms
11599: doc-time&date
11600: 
11601: 
11602: 
11603: @c -------------------------------------------------------------
11604: @node Miscellaneous Words,  , Keeping track of Time, Words
11605: @section Miscellaneous Words
11606: @cindex miscellaneous words
11607: 
11608: @comment TODO find homes for these
11609: 
11610: These section lists the ANS Forth words that are not documented
11611: elsewhere in this manual. Ultimately, they all need proper homes.
11612: 
11613: doc-[compile]
11614: doc-quit
11615: 
11616: The following ANS Forth words are not currently supported by Gforth 
11617: (@pxref{ANS conformance}):
11618: 
11619: @code{EDITOR} 
11620: @code{EMIT?} 
11621: @code{FORGET} 
11622: 
11623: @c ******************************************************************
11624: @node Error messages, Tools, Words, Top
11625: @chapter Error messages
11626: @cindex error messages
11627: @cindex backtrace
11628: 
11629: A typical Gforth error message looks like this:
11630: 
11631: @example
11632: in file included from :-1
11633: in file included from ./yyy.fs:1
11634: ./xxx.fs:4: Invalid memory address
11635: bar
11636: ^^^
11637: $400E664C @@
11638: $400E6664 foo
11639: @end example
11640: 
11641: The message identifying the error is @code{Invalid memory address}.  The
11642: error happened when text-interpreting line 4 of the file
11643: @file{./xxx.fs}. This line is given (it contains @code{bar}), and the
11644: word on the line where the error happened, is pointed out (with
11645: @code{^^^}).
11646: 
11647: The file containing the error was included in line 1 of @file{./yyy.fs},
11648: and @file{yyy.fs} was included from a non-file (in this case, by giving
11649: @file{yyy.fs} as command-line parameter to Gforth).
11650: 
11651: At the end of the error message you find a return stack dump that can be
11652: interpreted as a backtrace (possibly empty). On top you find the top of
11653: the return stack when the @code{throw} happened, and at the bottom you
11654: find the return stack entry just above the return stack of the topmost
11655: text interpreter.
11656: 
11657: To the right of most return stack entries you see a guess for the word
11658: that pushed that return stack entry as its return address. This gives a
11659: backtrace. In our case we see that @code{bar} called @code{foo}, and
11660: @code{foo} called @code{@@} (and @code{@@} had an @emph{Invalid memory
11661: address} exception).
11662: 
11663: Note that the backtrace is not perfect: We don't know which return stack
11664: entries are return addresses (so we may get false positives); and in
11665: some cases (e.g., for @code{abort"}) we cannot determine from the return
11666: address the word that pushed the return address, so for some return
11667: addresses you see no names in the return stack dump.
11668: 
11669: @cindex @code{catch} and backtraces
11670: The return stack dump represents the return stack at the time when a
11671: specific @code{throw} was executed.  In programs that make use of
11672: @code{catch}, it is not necessarily clear which @code{throw} should be
11673: used for the return stack dump (e.g., consider one @code{throw} that
11674: indicates an error, which is caught, and during recovery another error
11675: happens; which @code{throw} should be used for the stack dump?).  Gforth
11676: presents the return stack dump for the first @code{throw} after the last
11677: executed (not returned-to) @code{catch}; this works well in the usual
11678: case.
11679: 
11680: @cindex @code{gforth-fast} and backtraces
11681: @cindex @code{gforth-fast}, difference from @code{gforth}
11682: @cindex backtraces with @code{gforth-fast}
11683: @cindex return stack dump with @code{gforth-fast}
11684: @code{gforth} is able to do a return stack dump for throws generated
11685: from primitives (e.g., invalid memory address, stack empty etc.);
11686: @code{gforth-fast} is only able to do a return stack dump from a
11687: directly called @code{throw} (including @code{abort} etc.).  This is the
11688: only difference (apart from a speed factor of between 1.15 (K6-2) and
11689: 1.6 (21164A)) between @code{gforth} and @code{gforth-fast}.  Given an
11690: exception caused by a primitive in @code{gforth-fast}, you will
11691: typically see no return stack dump at all; however, if the exception is
11692: caught by @code{catch} (e.g., for restoring some state), and then
11693: @code{throw}n again, the return stack dump will be for the first such
11694: @code{throw}.
11695: 
11696: @c ******************************************************************
11697: @node Tools, ANS conformance, Error messages, Top
11698: @chapter Tools
11699: 
11700: @menu
11701: * ANS Report::                  Report the words used, sorted by wordset.
11702: @end menu
11703: 
11704: See also @ref{Emacs and Gforth}.
11705: 
11706: @node ANS Report,  , Tools, Tools
11707: @section @file{ans-report.fs}: Report the words used, sorted by wordset
11708: @cindex @file{ans-report.fs}
11709: @cindex report the words used in your program
11710: @cindex words used in your program
11711: 
11712: If you want to label a Forth program as ANS Forth Program, you must
11713: document which wordsets the program uses; for extension wordsets, it is
11714: helpful to list the words the program requires from these wordsets
11715: (because Forth systems are allowed to provide only some words of them).
11716: 
11717: The @file{ans-report.fs} tool makes it easy for you to determine which
11718: words from which wordset and which non-ANS words your application
11719: uses. You simply have to include @file{ans-report.fs} before loading the
11720: program you want to check. After loading your program, you can get the
11721: report with @code{print-ans-report}. A typical use is to run this as
11722: batch job like this:
11723: @example
11724: gforth ans-report.fs myprog.fs -e "print-ans-report bye"
11725: @end example
11726: 
11727: The output looks like this (for @file{compat/control.fs}):
11728: @example
11729: The program uses the following words
11730: from CORE :
11731: : POSTPONE THEN ; immediate ?dup IF 0= 
11732: from BLOCK-EXT :
11733: \ 
11734: from FILE :
11735: ( 
11736: @end example
11737: 
11738: @subsection Caveats
11739: 
11740: Note that @file{ans-report.fs} just checks which words are used, not whether
11741: they are used in an ANS Forth conforming way!
11742: 
11743: Some words are defined in several wordsets in the
11744: standard. @file{ans-report.fs} reports them for only one of the
11745: wordsets, and not necessarily the one you expect. It depends on usage
11746: which wordset is the right one to specify. E.g., if you only use the
11747: compilation semantics of @code{S"}, it is a Core word; if you also use
11748: its interpretation semantics, it is a File word.
11749: 
11750: @c ******************************************************************
11751: @node ANS conformance, Standard vs Extensions, Tools, Top
11752: @chapter ANS conformance
11753: @cindex ANS conformance of Gforth
11754: 
11755: To the best of our knowledge, Gforth is an
11756: 
11757: ANS Forth System
11758: @itemize @bullet
11759: @item providing the Core Extensions word set
11760: @item providing the Block word set
11761: @item providing the Block Extensions word set
11762: @item providing the Double-Number word set
11763: @item providing the Double-Number Extensions word set
11764: @item providing the Exception word set
11765: @item providing the Exception Extensions word set
11766: @item providing the Facility word set
11767: @item providing @code{EKEY}, @code{EKEY>CHAR}, @code{EKEY?}, @code{MS} and @code{TIME&DATE} from the Facility Extensions word set
11768: @item providing the File Access word set
11769: @item providing the File Access Extensions word set
11770: @item providing the Floating-Point word set
11771: @item providing the Floating-Point Extensions word set
11772: @item providing the Locals word set
11773: @item providing the Locals Extensions word set
11774: @item providing the Memory-Allocation word set
11775: @item providing the Memory-Allocation Extensions word set (that one's easy)
11776: @item providing the Programming-Tools word set
11777: @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
11778: @item providing the Search-Order word set
11779: @item providing the Search-Order Extensions word set
11780: @item providing the String word set
11781: @item providing the String Extensions word set (another easy one)
11782: @end itemize
11783: 
11784: @cindex system documentation
11785: In addition, ANS Forth systems are required to document certain
11786: implementation choices. This chapter tries to meet these
11787: requirements. In many cases it gives a way to ask the system for the
11788: information instead of providing the information directly, in
11789: particular, if the information depends on the processor, the operating
11790: system or the installation options chosen, or if they are likely to
11791: change during the maintenance of Gforth.
11792: 
11793: @comment The framework for the rest has been taken from pfe.
11794: 
11795: @menu
11796: * The Core Words::              
11797: * The optional Block word set::  
11798: * The optional Double Number word set::  
11799: * The optional Exception word set::  
11800: * The optional Facility word set::  
11801: * The optional File-Access word set::  
11802: * The optional Floating-Point word set::  
11803: * The optional Locals word set::  
11804: * The optional Memory-Allocation word set::  
11805: * The optional Programming-Tools word set::  
11806: * The optional Search-Order word set::  
11807: @end menu
11808: 
11809: 
11810: @c =====================================================================
11811: @node The Core Words, The optional Block word set, ANS conformance, ANS conformance
11812: @comment  node-name,  next,  previous,  up
11813: @section The Core Words
11814: @c =====================================================================
11815: @cindex core words, system documentation
11816: @cindex system documentation, core words
11817: 
11818: @menu
11819: * core-idef::                   Implementation Defined Options                   
11820: * core-ambcond::                Ambiguous Conditions                
11821: * core-other::                  Other System Documentation                  
11822: @end menu
11823: 
11824: @c ---------------------------------------------------------------------
11825: @node core-idef, core-ambcond, The Core Words, The Core Words
11826: @subsection Implementation Defined Options
11827: @c ---------------------------------------------------------------------
11828: @cindex core words, implementation-defined options
11829: @cindex implementation-defined options, core words
11830: 
11831: 
11832: @table @i
11833: @item (Cell) aligned addresses:
11834: @cindex cell-aligned addresses
11835: @cindex aligned addresses
11836: processor-dependent. Gforth's alignment words perform natural alignment
11837: (e.g., an address aligned for a datum of size 8 is divisible by
11838: 8). Unaligned accesses usually result in a @code{-23 THROW}.
11839: 
11840: @item @code{EMIT} and non-graphic characters:
11841: @cindex @code{EMIT} and non-graphic characters
11842: @cindex non-graphic characters and @code{EMIT}
11843: The character is output using the C library function (actually, macro)
11844: @code{putc}.
11845: 
11846: @item character editing of @code{ACCEPT} and @code{EXPECT}:
11847: @cindex character editing of @code{ACCEPT} and @code{EXPECT}
11848: @cindex editing in @code{ACCEPT} and @code{EXPECT}
11849: @cindex @code{ACCEPT}, editing
11850: @cindex @code{EXPECT}, editing
11851: This is modeled on the GNU readline library (@pxref{Readline
11852: Interaction, , Command Line Editing, readline, The GNU Readline
11853: Library}) with Emacs-like key bindings. @kbd{Tab} deviates a little by
11854: producing a full word completion every time you type it (instead of
11855: producing the common prefix of all completions). @xref{Command-line editing}.
11856: 
11857: @item character set:
11858: @cindex character set
11859: The character set of your computer and display device. Gforth is
11860: 8-bit-clean (but some other component in your system may make trouble).
11861: 
11862: @item Character-aligned address requirements:
11863: @cindex character-aligned address requirements
11864: installation-dependent. Currently a character is represented by a C
11865: @code{unsigned char}; in the future we might switch to @code{wchar_t}
11866: (Comments on that requested).
11867: 
11868: @item character-set extensions and matching of names:
11869: @cindex character-set extensions and matching of names
11870: @cindex case-sensitivity for name lookup
11871: @cindex name lookup, case-sensitivity
11872: @cindex locale and case-sensitivity
11873: Any character except the ASCII NUL character can be used in a
11874: name. Matching is case-insensitive (except in @code{TABLE}s). The
11875: matching is performed using the C library function @code{strncasecmp}, whose
11876: function is probably influenced by the locale. E.g., the @code{C} locale
11877: does not know about accents and umlauts, so they are matched
11878: case-sensitively in that locale. For portability reasons it is best to
11879: write programs such that they work in the @code{C} locale. Then one can
11880: use libraries written by a Polish programmer (who might use words
11881: containing ISO Latin-2 encoded characters) and by a French programmer
11882: (ISO Latin-1) in the same program (of course, @code{WORDS} will produce
11883: funny results for some of the words (which ones, depends on the font you
11884: are using)). Also, the locale you prefer may not be available in other
11885: operating systems. Hopefully, Unicode will solve these problems one day.
11886: 
11887: @item conditions under which control characters match a space delimiter:
11888: @cindex space delimiters
11889: @cindex control characters as delimiters
11890: If @code{WORD} is called with the space character as a delimiter, all
11891: white-space characters (as identified by the C macro @code{isspace()})
11892: are delimiters. @code{PARSE}, on the other hand, treats space like other
11893: delimiters. @code{SWORD} treats space like @code{WORD}, but behaves
11894: like @code{PARSE} otherwise. @code{(NAME)}, which is used by the outer
11895: interpreter (aka text interpreter) by default, treats all white-space
11896: characters as delimiters.
11897: 
11898: @item format of the control-flow stack:
11899: @cindex control-flow stack, format
11900: The data stack is used as control-flow stack. The size of a control-flow
11901: stack item in cells is given by the constant @code{cs-item-size}. At the
11902: time of this writing, an item consists of a (pointer to a) locals list
11903: (third), an address in the code (second), and a tag for identifying the
11904: item (TOS). The following tags are used: @code{defstart},
11905: @code{live-orig}, @code{dead-orig}, @code{dest}, @code{do-dest},
11906: @code{scopestart}.
11907: 
11908: @item conversion of digits > 35
11909: @cindex digits > 35
11910: The characters @code{[\]^_'} are the digits with the decimal value
11911: 36@minus{}41. There is no way to input many of the larger digits.
11912: 
11913: @item display after input terminates in @code{ACCEPT} and @code{EXPECT}:
11914: @cindex @code{EXPECT}, display after end of input
11915: @cindex @code{ACCEPT}, display after end of input
11916: The cursor is moved to the end of the entered string. If the input is
11917: terminated using the @kbd{Return} key, a space is typed.
11918: 
11919: @item exception abort sequence of @code{ABORT"}:
11920: @cindex exception abort sequence of @code{ABORT"}
11921: @cindex @code{ABORT"}, exception abort sequence
11922: The error string is stored into the variable @code{"error} and a
11923: @code{-2 throw} is performed.
11924: 
11925: @item input line terminator:
11926: @cindex input line terminator
11927: @cindex line terminator on input
11928: @cindex newline character on input
11929: For interactive input, @kbd{C-m} (CR) and @kbd{C-j} (LF) terminate
11930: lines. One of these characters is typically produced when you type the
11931: @kbd{Enter} or @kbd{Return} key.
11932: 
11933: @item maximum size of a counted string:
11934: @cindex maximum size of a counted string
11935: @cindex counted string, maximum size
11936: @code{s" /counted-string" environment? drop .}. Currently 255 characters
11937: on all ports, but this may change.
11938: 
11939: @item maximum size of a parsed string:
11940: @cindex maximum size of a parsed string
11941: @cindex parsed string, maximum size
11942: Given by the constant @code{/line}. Currently 255 characters.
11943: 
11944: @item maximum size of a definition name, in characters:
11945: @cindex maximum size of a definition name, in characters
11946: @cindex name, maximum length
11947: 31
11948: 
11949: @item maximum string length for @code{ENVIRONMENT?}, in characters:
11950: @cindex maximum string length for @code{ENVIRONMENT?}, in characters
11951: @cindex @code{ENVIRONMENT?} string length, maximum
11952: 31
11953: 
11954: @item method of selecting the user input device:
11955: @cindex user input device, method of selecting
11956: The user input device is the standard input. There is currently no way to
11957: change it from within Gforth. However, the input can typically be
11958: redirected in the command line that starts Gforth.
11959: 
11960: @item method of selecting the user output device:
11961: @cindex user output device, method of selecting
11962: @code{EMIT} and @code{TYPE} output to the file-id stored in the value
11963: @code{outfile-id} (@code{stdout} by default). Gforth uses unbuffered
11964: output when the user output device is a terminal, otherwise the output
11965: is buffered.
11966: 
11967: @item methods of dictionary compilation:
11968: What are we expected to document here?
11969: 
11970: @item number of bits in one address unit:
11971: @cindex number of bits in one address unit
11972: @cindex address unit, size in bits
11973: @code{s" address-units-bits" environment? drop .}. 8 in all current
11974: ports.
11975: 
11976: @item number representation and arithmetic:
11977: @cindex number representation and arithmetic
11978: Processor-dependent. Binary two's complement on all current ports.
11979: 
11980: @item ranges for integer types:
11981: @cindex ranges for integer types
11982: @cindex integer types, ranges
11983: Installation-dependent. Make environmental queries for @code{MAX-N},
11984: @code{MAX-U}, @code{MAX-D} and @code{MAX-UD}. The lower bounds for
11985: unsigned (and positive) types is 0. The lower bound for signed types on
11986: two's complement and one's complement machines machines can be computed
11987: by adding 1 to the upper bound.
11988: 
11989: @item read-only data space regions:
11990: @cindex read-only data space regions
11991: @cindex data-space, read-only regions
11992: The whole Forth data space is writable.
11993: 
11994: @item size of buffer at @code{WORD}:
11995: @cindex size of buffer at @code{WORD}
11996: @cindex @code{WORD} buffer size
11997: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
11998: shared with the pictured numeric output string. If overwriting
11999: @code{PAD} is acceptable, it is as large as the remaining dictionary
12000: space, although only as much can be sensibly used as fits in a counted
12001: string.
12002: 
12003: @item size of one cell in address units:
12004: @cindex cell size
12005: @code{1 cells .}.
12006: 
12007: @item size of one character in address units:
12008: @cindex char size
12009: @code{1 chars .}. 1 on all current ports.
12010: 
12011: @item size of the keyboard terminal buffer:
12012: @cindex size of the keyboard terminal buffer
12013: @cindex terminal buffer, size
12014: Varies. You can determine the size at a specific time using @code{lp@@
12015: tib - .}. It is shared with the locals stack and TIBs of files that
12016: include the current file. You can change the amount of space for TIBs
12017: and locals stack at Gforth startup with the command line option
12018: @code{-l}.
12019: 
12020: @item size of the pictured numeric output buffer:
12021: @cindex size of the pictured numeric output buffer
12022: @cindex pictured numeric output buffer, size
12023: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
12024: shared with @code{WORD}.
12025: 
12026: @item size of the scratch area returned by @code{PAD}:
12027: @cindex size of the scratch area returned by @code{PAD}
12028: @cindex @code{PAD} size
12029: The remainder of dictionary space. @code{unused pad here - - .}.
12030: 
12031: @item system case-sensitivity characteristics:
12032: @cindex case-sensitivity characteristics
12033: Dictionary searches are case-insensitive (except in
12034: @code{TABLE}s). However, as explained above under @i{character-set
12035: extensions}, the matching for non-ASCII characters is determined by the
12036: locale you are using. In the default @code{C} locale all non-ASCII
12037: characters are matched case-sensitively.
12038: 
12039: @item system prompt:
12040: @cindex system prompt
12041: @cindex prompt
12042: @code{ ok} in interpret state, @code{ compiled} in compile state.
12043: 
12044: @item division rounding:
12045: @cindex division rounding
12046: installation dependent. @code{s" floored" environment? drop .}. We leave
12047: the choice to @code{gcc} (what to use for @code{/}) and to you (whether
12048: to use @code{fm/mod}, @code{sm/rem} or simply @code{/}).
12049: 
12050: @item values of @code{STATE} when true:
12051: @cindex @code{STATE} values
12052: -1.
12053: 
12054: @item values returned after arithmetic overflow:
12055: On two's complement machines, arithmetic is performed modulo
12056: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
12057: arithmetic (with appropriate mapping for signed types). Division by zero
12058: typically results in a @code{-55 throw} (Floating-point unidentified
12059: fault), although a @code{-10 throw} (divide by zero) would be more
12060: appropriate.
12061: 
12062: @item whether the current definition can be found after @t{DOES>}:
12063: @cindex @t{DOES>}, visibility of current definition
12064: No.
12065: 
12066: @end table
12067: 
12068: @c ---------------------------------------------------------------------
12069: @node core-ambcond, core-other, core-idef, The Core Words
12070: @subsection Ambiguous conditions
12071: @c ---------------------------------------------------------------------
12072: @cindex core words, ambiguous conditions
12073: @cindex ambiguous conditions, core words
12074: 
12075: @table @i
12076: 
12077: @item a name is neither a word nor a number:
12078: @cindex name not found
12079: @cindex undefined word
12080: @code{-13 throw} (Undefined word). Actually, @code{-13 bounce}, which
12081: preserves the data and FP stack, so you don't lose more work than
12082: necessary.
12083: 
12084: @item a definition name exceeds the maximum length allowed:
12085: @cindex word name too long
12086: @code{-19 throw} (Word name too long)
12087: 
12088: @item addressing a region not inside the various data spaces of the forth system:
12089: @cindex Invalid memory address
12090: The stacks, code space and header space are accessible. Machine code space is
12091: typically readable. Accessing other addresses gives results dependent on
12092: the operating system. On decent systems: @code{-9 throw} (Invalid memory
12093: address).
12094: 
12095: @item argument type incompatible with parameter:
12096: @cindex argument type mismatch
12097: This is usually not caught. Some words perform checks, e.g., the control
12098: flow words, and issue a @code{ABORT"} or @code{-12 THROW} (Argument type
12099: mismatch).
12100: 
12101: @item attempting to obtain the execution token of a word with undefined execution semantics:
12102: @cindex Interpreting a compile-only word, for @code{'} etc.
12103: @cindex execution token of words with undefined execution semantics
12104: @code{-14 throw} (Interpreting a compile-only word). In some cases, you
12105: get an execution token for @code{compile-only-error} (which performs a
12106: @code{-14 throw} when executed).
12107: 
12108: @item dividing by zero:
12109: @cindex dividing by zero
12110: @cindex floating point unidentified fault, integer division
12111: On better platforms, this produces a @code{-10 throw} (Division by
12112: zero); on other systems, this typically results in a @code{-55 throw}
12113: (Floating-point unidentified fault).
12114: 
12115: @item insufficient data stack or return stack space:
12116: @cindex insufficient data stack or return stack space
12117: @cindex stack overflow
12118: @cindex address alignment exception, stack overflow
12119: @cindex Invalid memory address, stack overflow
12120: Depending on the operating system, the installation, and the invocation
12121: of Gforth, this is either checked by the memory management hardware, or
12122: it is not checked. If it is checked, you typically get a @code{-3 throw}
12123: (Stack overflow), @code{-5 throw} (Return stack overflow), or @code{-9
12124: throw} (Invalid memory address) (depending on the platform and how you
12125: achieved the overflow) as soon as the overflow happens. If it is not
12126: checked, overflows typically result in mysterious illegal memory
12127: accesses, producing @code{-9 throw} (Invalid memory address) or
12128: @code{-23 throw} (Address alignment exception); they might also destroy
12129: the internal data structure of @code{ALLOCATE} and friends, resulting in
12130: various errors in these words.
12131: 
12132: @item insufficient space for loop control parameters:
12133: @cindex insufficient space for loop control parameters
12134: like other return stack overflows.
12135: 
12136: @item insufficient space in the dictionary:
12137: @cindex insufficient space in the dictionary
12138: @cindex dictionary overflow
12139: If you try to allot (either directly with @code{allot}, or indirectly
12140: with @code{,}, @code{create} etc.) more memory than available in the
12141: dictionary, you get a @code{-8 throw} (Dictionary overflow). If you try
12142: to access memory beyond the end of the dictionary, the results are
12143: similar to stack overflows.
12144: 
12145: @item interpreting a word with undefined interpretation semantics:
12146: @cindex interpreting a word with undefined interpretation semantics
12147: @cindex Interpreting a compile-only word
12148: For some words, we have defined interpretation semantics. For the
12149: others: @code{-14 throw} (Interpreting a compile-only word).
12150: 
12151: @item modifying the contents of the input buffer or a string literal:
12152: @cindex modifying the contents of the input buffer or a string literal
12153: These are located in writable memory and can be modified.
12154: 
12155: @item overflow of the pictured numeric output string:
12156: @cindex overflow of the pictured numeric output string
12157: @cindex pictured numeric output string, overflow
12158: @code{-17 throw} (Pictured numeric ouput string overflow).
12159: 
12160: @item parsed string overflow:
12161: @cindex parsed string overflow
12162: @code{PARSE} cannot overflow. @code{WORD} does not check for overflow.
12163: 
12164: @item producing a result out of range:
12165: @cindex result out of range
12166: On two's complement machines, arithmetic is performed modulo
12167: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
12168: arithmetic (with appropriate mapping for signed types). Division by zero
12169: typically results in a @code{-10 throw} (divide by zero) or @code{-55
12170: throw} (floating point unidentified fault). @code{convert} and
12171: @code{>number} currently overflow silently.
12172: 
12173: @item reading from an empty data or return stack:
12174: @cindex stack empty
12175: @cindex stack underflow
12176: @cindex return stack underflow
12177: The data stack is checked by the outer (aka text) interpreter after
12178: every word executed. If it has underflowed, a @code{-4 throw} (Stack
12179: underflow) is performed. Apart from that, stacks may be checked or not,
12180: depending on operating system, installation, and invocation. If they are
12181: caught by a check, they typically result in @code{-4 throw} (Stack
12182: underflow), @code{-6 throw} (Return stack underflow) or @code{-9 throw}
12183: (Invalid memory address), depending on the platform and which stack
12184: underflows and by how much. Note that even if the system uses checking
12185: (through the MMU), your program may have to underflow by a significant
12186: number of stack items to trigger the reaction (the reason for this is
12187: that the MMU, and therefore the checking, works with a page-size
12188: granularity).  If there is no checking, the symptoms resulting from an
12189: underflow are similar to those from an overflow.  Unbalanced return
12190: stack errors result in a variaty of symptoms, including @code{-9 throw}
12191: (Invalid memory address) and Illegal Instruction (typically @code{-260
12192: throw}).
12193: 
12194: @item unexpected end of the input buffer, resulting in an attempt to use a zero-length string as a name:
12195: @cindex unexpected end of the input buffer
12196: @cindex zero-length string as a name
12197: @cindex Attempt to use zero-length string as a name
12198: @code{Create} and its descendants perform a @code{-16 throw} (Attempt to
12199: use zero-length string as a name). Words like @code{'} probably will not
12200: find what they search. Note that it is possible to create zero-length
12201: names with @code{nextname} (should it not?).
12202: 
12203: @item @code{>IN} greater than input buffer:
12204: @cindex @code{>IN} greater than input buffer
12205: The next invocation of a parsing word returns a string with length 0.
12206: 
12207: @item @code{RECURSE} appears after @code{DOES>}:
12208: @cindex @code{RECURSE} appears after @code{DOES>}
12209: Compiles a recursive call to the defining word, not to the defined word.
12210: 
12211: @item argument input source different than current input source for @code{RESTORE-INPUT}:
12212: @cindex argument input source different than current input source for @code{RESTORE-INPUT}
12213: @cindex argument type mismatch, @code{RESTORE-INPUT}
12214: @cindex @code{RESTORE-INPUT}, Argument type mismatch
12215: @code{-12 THROW}. Note that, once an input file is closed (e.g., because
12216: the end of the file was reached), its source-id may be
12217: reused. Therefore, restoring an input source specification referencing a
12218: closed file may lead to unpredictable results instead of a @code{-12
12219: THROW}.
12220: 
12221: In the future, Gforth may be able to restore input source specifications
12222: from other than the current input source.
12223: 
12224: @item data space containing definitions gets de-allocated:
12225: @cindex data space containing definitions gets de-allocated
12226: Deallocation with @code{allot} is not checked. This typically results in
12227: memory access faults or execution of illegal instructions.
12228: 
12229: @item data space read/write with incorrect alignment:
12230: @cindex data space read/write with incorrect alignment
12231: @cindex alignment faults
12232: @cindex address alignment exception
12233: Processor-dependent. Typically results in a @code{-23 throw} (Address
12234: alignment exception). Under Linux-Intel on a 486 or later processor with
12235: alignment turned on, incorrect alignment results in a @code{-9 throw}
12236: (Invalid memory address). There are reportedly some processors with
12237: alignment restrictions that do not report violations.
12238: 
12239: @item data space pointer not properly aligned, @code{,}, @code{C,}:
12240: @cindex data space pointer not properly aligned, @code{,}, @code{C,}
12241: Like other alignment errors.
12242: 
12243: @item less than u+2 stack items (@code{PICK} and @code{ROLL}):
12244: Like other stack underflows.
12245: 
12246: @item loop control parameters not available:
12247: @cindex loop control parameters not available
12248: Not checked. The counted loop words simply assume that the top of return
12249: stack items are loop control parameters and behave accordingly.
12250: 
12251: @item most recent definition does not have a name (@code{IMMEDIATE}):
12252: @cindex most recent definition does not have a name (@code{IMMEDIATE})
12253: @cindex last word was headerless
12254: @code{abort" last word was headerless"}.
12255: 
12256: @item name not defined by @code{VALUE} used by @code{TO}:
12257: @cindex name not defined by @code{VALUE} used by @code{TO}
12258: @cindex @code{TO} on non-@code{VALUE}s
12259: @cindex Invalid name argument, @code{TO}
12260: @code{-32 throw} (Invalid name argument) (unless name is a local or was
12261: defined by @code{CONSTANT}; in the latter case it just changes the constant).
12262: 
12263: @item name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}):
12264: @cindex name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]})
12265: @cindex undefined word, @code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}
12266: @code{-13 throw} (Undefined word)
12267: 
12268: @item parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN}):
12269: @cindex parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN})
12270: Gforth behaves as if they were of the same type. I.e., you can predict
12271: the behaviour by interpreting all parameters as, e.g., signed.
12272: 
12273: @item @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}:
12274: @cindex @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}
12275: Assume @code{: X POSTPONE TO ; IMMEDIATE}. @code{X} performs the
12276: compilation semantics of @code{TO}.
12277: 
12278: @item String longer than a counted string returned by @code{WORD}:
12279: @cindex string longer than a counted string returned by @code{WORD}
12280: @cindex @code{WORD}, string overflow
12281: Not checked. The string will be ok, but the count will, of course,
12282: contain only the least significant bits of the length.
12283: 
12284: @item u greater than or equal to the number of bits in a cell (@code{LSHIFT}, @code{RSHIFT}):
12285: @cindex @code{LSHIFT}, large shift counts
12286: @cindex @code{RSHIFT}, large shift counts
12287: Processor-dependent. Typical behaviours are returning 0 and using only
12288: the low bits of the shift count.
12289: 
12290: @item word not defined via @code{CREATE}:
12291: @cindex @code{>BODY} of non-@code{CREATE}d words
12292: @code{>BODY} produces the PFA of the word no matter how it was defined.
12293: 
12294: @cindex @code{DOES>} of non-@code{CREATE}d words
12295: @code{DOES>} changes the execution semantics of the last defined word no
12296: matter how it was defined. E.g., @code{CONSTANT DOES>} is equivalent to
12297: @code{CREATE , DOES>}.
12298: 
12299: @item words improperly used outside @code{<#} and @code{#>}:
12300: Not checked. As usual, you can expect memory faults.
12301: 
12302: @end table
12303: 
12304: 
12305: @c ---------------------------------------------------------------------
12306: @node core-other,  , core-ambcond, The Core Words
12307: @subsection Other system documentation
12308: @c ---------------------------------------------------------------------
12309: @cindex other system documentation, core words
12310: @cindex core words, other system documentation
12311: 
12312: @table @i
12313: @item nonstandard words using @code{PAD}:
12314: @cindex @code{PAD} use by nonstandard words
12315: None.
12316: 
12317: @item operator's terminal facilities available:
12318: @cindex operator's terminal facilities available
12319: After processing the command line, Gforth goes into interactive mode,
12320: and you can give commands to Gforth interactively. The actual facilities
12321: available depend on how you invoke Gforth.
12322: 
12323: @item program data space available:
12324: @cindex program data space available
12325: @cindex data space available
12326: @code{UNUSED .} gives the remaining dictionary space. The total
12327: dictionary space can be specified with the @code{-m} switch
12328: (@pxref{Invoking Gforth}) when Gforth starts up.
12329: 
12330: @item return stack space available:
12331: @cindex return stack space available
12332: You can compute the total return stack space in cells with
12333: @code{s" RETURN-STACK-CELLS" environment? drop .}. You can specify it at
12334: startup time with the @code{-r} switch (@pxref{Invoking Gforth}).
12335: 
12336: @item stack space available:
12337: @cindex stack space available
12338: You can compute the total data stack space in cells with
12339: @code{s" STACK-CELLS" environment? drop .}. You can specify it at
12340: startup time with the @code{-d} switch (@pxref{Invoking Gforth}).
12341: 
12342: @item system dictionary space required, in address units:
12343: @cindex system dictionary space required, in address units
12344: Type @code{here forthstart - .} after startup. At the time of this
12345: writing, this gives 80080 (bytes) on a 32-bit system.
12346: @end table
12347: 
12348: 
12349: @c =====================================================================
12350: @node The optional Block word set, The optional Double Number word set, The Core Words, ANS conformance
12351: @section The optional Block word set
12352: @c =====================================================================
12353: @cindex system documentation, block words
12354: @cindex block words, system documentation
12355: 
12356: @menu
12357: * block-idef::                  Implementation Defined Options
12358: * block-ambcond::               Ambiguous Conditions               
12359: * block-other::                 Other System Documentation                 
12360: @end menu
12361: 
12362: 
12363: @c ---------------------------------------------------------------------
12364: @node block-idef, block-ambcond, The optional Block word set, The optional Block word set
12365: @subsection Implementation Defined Options
12366: @c ---------------------------------------------------------------------
12367: @cindex implementation-defined options, block words
12368: @cindex block words, implementation-defined options
12369: 
12370: @table @i
12371: @item the format for display by @code{LIST}:
12372: @cindex @code{LIST} display format
12373: First the screen number is displayed, then 16 lines of 64 characters,
12374: each line preceded by the line number.
12375: 
12376: @item the length of a line affected by @code{\}:
12377: @cindex length of a line affected by @code{\}
12378: @cindex @code{\}, line length in blocks
12379: 64 characters.
12380: @end table
12381: 
12382: 
12383: @c ---------------------------------------------------------------------
12384: @node block-ambcond, block-other, block-idef, The optional Block word set
12385: @subsection Ambiguous conditions
12386: @c ---------------------------------------------------------------------
12387: @cindex block words, ambiguous conditions
12388: @cindex ambiguous conditions, block words
12389: 
12390: @table @i
12391: @item correct block read was not possible:
12392: @cindex block read not possible
12393: Typically results in a @code{throw} of some OS-derived value (between
12394: -512 and -2048). If the blocks file was just not long enough, blanks are
12395: supplied for the missing portion.
12396: 
12397: @item I/O exception in block transfer:
12398: @cindex I/O exception in block transfer
12399: @cindex block transfer, I/O exception
12400: Typically results in a @code{throw} of some OS-derived value (between
12401: -512 and -2048).
12402: 
12403: @item invalid block number:
12404: @cindex invalid block number
12405: @cindex block number invalid
12406: @code{-35 throw} (Invalid block number)
12407: 
12408: @item a program directly alters the contents of @code{BLK}:
12409: @cindex @code{BLK}, altering @code{BLK}
12410: The input stream is switched to that other block, at the same
12411: position. If the storing to @code{BLK} happens when interpreting
12412: non-block input, the system will get quite confused when the block ends.
12413: 
12414: @item no current block buffer for @code{UPDATE}:
12415: @cindex @code{UPDATE}, no current block buffer
12416: @code{UPDATE} has no effect.
12417: 
12418: @end table
12419: 
12420: @c ---------------------------------------------------------------------
12421: @node block-other,  , block-ambcond, The optional Block word set
12422: @subsection Other system documentation
12423: @c ---------------------------------------------------------------------
12424: @cindex other system documentation, block words
12425: @cindex block words, other system documentation
12426: 
12427: @table @i
12428: @item any restrictions a multiprogramming system places on the use of buffer addresses:
12429: No restrictions (yet).
12430: 
12431: @item the number of blocks available for source and data:
12432: depends on your disk space.
12433: 
12434: @end table
12435: 
12436: 
12437: @c =====================================================================
12438: @node The optional Double Number word set, The optional Exception word set, The optional Block word set, ANS conformance
12439: @section The optional Double Number word set
12440: @c =====================================================================
12441: @cindex system documentation, double words
12442: @cindex double words, system documentation
12443: 
12444: @menu
12445: * double-ambcond::              Ambiguous Conditions              
12446: @end menu
12447: 
12448: 
12449: @c ---------------------------------------------------------------------
12450: @node double-ambcond,  , The optional Double Number word set, The optional Double Number word set
12451: @subsection Ambiguous conditions
12452: @c ---------------------------------------------------------------------
12453: @cindex double words, ambiguous conditions
12454: @cindex ambiguous conditions, double words
12455: 
12456: @table @i
12457: @item @i{d} outside of range of @i{n} in @code{D>S}:
12458: @cindex @code{D>S}, @i{d} out of range of @i{n} 
12459: The least significant cell of @i{d} is produced.
12460: 
12461: @end table
12462: 
12463: 
12464: @c =====================================================================
12465: @node The optional Exception word set, The optional Facility word set, The optional Double Number word set, ANS conformance
12466: @section The optional Exception word set
12467: @c =====================================================================
12468: @cindex system documentation, exception words
12469: @cindex exception words, system documentation
12470: 
12471: @menu
12472: * exception-idef::              Implementation Defined Options              
12473: @end menu
12474: 
12475: 
12476: @c ---------------------------------------------------------------------
12477: @node exception-idef,  , The optional Exception word set, The optional Exception word set
12478: @subsection Implementation Defined Options
12479: @c ---------------------------------------------------------------------
12480: @cindex implementation-defined options, exception words
12481: @cindex exception words, implementation-defined options
12482: 
12483: @table @i
12484: @item @code{THROW}-codes used in the system:
12485: @cindex @code{THROW}-codes used in the system
12486: The codes -256@minus{}-511 are used for reporting signals. The mapping
12487: from OS signal numbers to throw codes is -256@minus{}@i{signal}. The
12488: codes -512@minus{}-2047 are used for OS errors (for file and memory
12489: allocation operations). The mapping from OS error numbers to throw codes
12490: is -512@minus{}@code{errno}. One side effect of this mapping is that
12491: undefined OS errors produce a message with a strange number; e.g.,
12492: @code{-1000 THROW} results in @code{Unknown error 488} on my system.
12493: @end table
12494: 
12495: @c =====================================================================
12496: @node The optional Facility word set, The optional File-Access word set, The optional Exception word set, ANS conformance
12497: @section The optional Facility word set
12498: @c =====================================================================
12499: @cindex system documentation, facility words
12500: @cindex facility words, system documentation
12501: 
12502: @menu
12503: * facility-idef::               Implementation Defined Options               
12504: * facility-ambcond::            Ambiguous Conditions            
12505: @end menu
12506: 
12507: 
12508: @c ---------------------------------------------------------------------
12509: @node facility-idef, facility-ambcond, The optional Facility word set, The optional Facility word set
12510: @subsection Implementation Defined Options
12511: @c ---------------------------------------------------------------------
12512: @cindex implementation-defined options, facility words
12513: @cindex facility words, implementation-defined options
12514: 
12515: @table @i
12516: @item encoding of keyboard events (@code{EKEY}):
12517: @cindex keyboard events, encoding in @code{EKEY}
12518: @cindex @code{EKEY}, encoding of keyboard events
12519: Keys corresponding to ASCII characters are encoded as ASCII characters.
12520: Other keys are encoded with the constants @code{k-left}, @code{k-right},
12521: @code{k-up}, @code{k-down}, @code{k-home}, @code{k-end}, @code{k1},
12522: @code{k2}, @code{k3}, @code{k4}, @code{k5}, @code{k6}, @code{k7},
12523: @code{k8}, @code{k9}, @code{k10}, @code{k11}, @code{k12}.
12524: 
12525: 
12526: @item duration of a system clock tick:
12527: @cindex duration of a system clock tick
12528: @cindex clock tick duration
12529: System dependent. With respect to @code{MS}, the time is specified in
12530: microseconds. How well the OS and the hardware implement this, is
12531: another question.
12532: 
12533: @item repeatability to be expected from the execution of @code{MS}:
12534: @cindex repeatability to be expected from the execution of @code{MS}
12535: @cindex @code{MS}, repeatability to be expected
12536: System dependent. On Unix, a lot depends on load. If the system is
12537: lightly loaded, and the delay is short enough that Gforth does not get
12538: swapped out, the performance should be acceptable. Under MS-DOS and
12539: other single-tasking systems, it should be good.
12540: 
12541: @end table
12542: 
12543: 
12544: @c ---------------------------------------------------------------------
12545: @node facility-ambcond,  , facility-idef, The optional Facility word set
12546: @subsection Ambiguous conditions
12547: @c ---------------------------------------------------------------------
12548: @cindex facility words, ambiguous conditions
12549: @cindex ambiguous conditions, facility words
12550: 
12551: @table @i
12552: @item @code{AT-XY} can't be performed on user output device:
12553: @cindex @code{AT-XY} can't be performed on user output device
12554: Largely terminal dependent. No range checks are done on the arguments.
12555: No errors are reported. You may see some garbage appearing, you may see
12556: simply nothing happen.
12557: 
12558: @end table
12559: 
12560: 
12561: @c =====================================================================
12562: @node The optional File-Access word set, The optional Floating-Point word set, The optional Facility word set, ANS conformance
12563: @section The optional File-Access word set
12564: @c =====================================================================
12565: @cindex system documentation, file words
12566: @cindex file words, system documentation
12567: 
12568: @menu
12569: * file-idef::                   Implementation Defined Options
12570: * file-ambcond::                Ambiguous Conditions                
12571: @end menu
12572: 
12573: @c ---------------------------------------------------------------------
12574: @node file-idef, file-ambcond, The optional File-Access word set, The optional File-Access word set
12575: @subsection Implementation Defined Options
12576: @c ---------------------------------------------------------------------
12577: @cindex implementation-defined options, file words
12578: @cindex file words, implementation-defined options
12579: 
12580: @table @i
12581: @item file access methods used:
12582: @cindex file access methods used
12583: @code{R/O}, @code{R/W} and @code{BIN} work as you would
12584: expect. @code{W/O} translates into the C file opening mode @code{w} (or
12585: @code{wb}): The file is cleared, if it exists, and created, if it does
12586: not (with both @code{open-file} and @code{create-file}).  Under Unix
12587: @code{create-file} creates a file with 666 permissions modified by your
12588: umask.
12589: 
12590: @item file exceptions:
12591: @cindex file exceptions
12592: The file words do not raise exceptions (except, perhaps, memory access
12593: faults when you pass illegal addresses or file-ids).
12594: 
12595: @item file line terminator:
12596: @cindex file line terminator
12597: System-dependent. Gforth uses C's newline character as line
12598: terminator. What the actual character code(s) of this are is
12599: system-dependent.
12600: 
12601: @item file name format:
12602: @cindex file name format
12603: System dependent. Gforth just uses the file name format of your OS.
12604: 
12605: @item information returned by @code{FILE-STATUS}:
12606: @cindex @code{FILE-STATUS}, returned information
12607: @code{FILE-STATUS} returns the most powerful file access mode allowed
12608: for the file: Either @code{R/O}, @code{W/O} or @code{R/W}. If the file
12609: cannot be accessed, @code{R/O BIN} is returned. @code{BIN} is applicable
12610: along with the returned mode.
12611: 
12612: @item input file state after an exception when including source:
12613: @cindex exception when including source
12614: All files that are left via the exception are closed.
12615: 
12616: @item @i{ior} values and meaning:
12617: @cindex @i{ior} values and meaning
12618: @cindex @i{wior} values and meaning
12619: The @i{ior}s returned by the file and memory allocation words are
12620: intended as throw codes. They typically are in the range
12621: -512@minus{}-2047 of OS errors.  The mapping from OS error numbers to
12622: @i{ior}s is -512@minus{}@i{errno}.
12623: 
12624: @item maximum depth of file input nesting:
12625: @cindex maximum depth of file input nesting
12626: @cindex file input nesting, maximum depth
12627: limited by the amount of return stack, locals/TIB stack, and the number
12628: of open files available. This should not give you troubles.
12629: 
12630: @item maximum size of input line:
12631: @cindex maximum size of input line
12632: @cindex input line size, maximum
12633: @code{/line}. Currently 255.
12634: 
12635: @item methods of mapping block ranges to files:
12636: @cindex mapping block ranges to files
12637: @cindex files containing blocks
12638: @cindex blocks in files
12639: By default, blocks are accessed in the file @file{blocks.fb} in the
12640: current working directory. The file can be switched with @code{USE}.
12641: 
12642: @item number of string buffers provided by @code{S"}:
12643: @cindex @code{S"}, number of string buffers
12644: 1
12645: 
12646: @item size of string buffer used by @code{S"}:
12647: @cindex @code{S"}, size of string buffer
12648: @code{/line}. currently 255.
12649: 
12650: @end table
12651: 
12652: @c ---------------------------------------------------------------------
12653: @node file-ambcond,  , file-idef, The optional File-Access word set
12654: @subsection Ambiguous conditions
12655: @c ---------------------------------------------------------------------
12656: @cindex file words, ambiguous conditions
12657: @cindex ambiguous conditions, file words
12658: 
12659: @table @i
12660: @item attempting to position a file outside its boundaries:
12661: @cindex @code{REPOSITION-FILE}, outside the file's boundaries
12662: @code{REPOSITION-FILE} is performed as usual: Afterwards,
12663: @code{FILE-POSITION} returns the value given to @code{REPOSITION-FILE}.
12664: 
12665: @item attempting to read from file positions not yet written:
12666: @cindex reading from file positions not yet written
12667: End-of-file, i.e., zero characters are read and no error is reported.
12668: 
12669: @item @i{file-id} is invalid (@code{INCLUDE-FILE}):
12670: @cindex @code{INCLUDE-FILE}, @i{file-id} is invalid 
12671: An appropriate exception may be thrown, but a memory fault or other
12672: problem is more probable.
12673: 
12674: @item I/O exception reading or closing @i{file-id} (@code{INCLUDE-FILE}, @code{INCLUDED}):
12675: @cindex @code{INCLUDE-FILE}, I/O exception reading or closing @i{file-id}
12676: @cindex @code{INCLUDED}, I/O exception reading or closing @i{file-id}
12677: The @i{ior} produced by the operation, that discovered the problem, is
12678: thrown.
12679: 
12680: @item named file cannot be opened (@code{INCLUDED}):
12681: @cindex @code{INCLUDED}, named file cannot be opened
12682: The @i{ior} produced by @code{open-file} is thrown.
12683: 
12684: @item requesting an unmapped block number:
12685: @cindex unmapped block numbers
12686: There are no unmapped legal block numbers. On some operating systems,
12687: writing a block with a large number may overflow the file system and
12688: have an error message as consequence.
12689: 
12690: @item using @code{source-id} when @code{blk} is non-zero:
12691: @cindex @code{SOURCE-ID}, behaviour when @code{BLK} is non-zero
12692: @code{source-id} performs its function. Typically it will give the id of
12693: the source which loaded the block. (Better ideas?)
12694: 
12695: @end table
12696: 
12697: 
12698: @c =====================================================================
12699: @node  The optional Floating-Point word set, The optional Locals word set, The optional File-Access word set, ANS conformance
12700: @section The optional Floating-Point word set
12701: @c =====================================================================
12702: @cindex system documentation, floating-point words
12703: @cindex floating-point words, system documentation
12704: 
12705: @menu
12706: * floating-idef::               Implementation Defined Options
12707: * floating-ambcond::            Ambiguous Conditions            
12708: @end menu
12709: 
12710: 
12711: @c ---------------------------------------------------------------------
12712: @node floating-idef, floating-ambcond, The optional Floating-Point word set, The optional Floating-Point word set
12713: @subsection Implementation Defined Options
12714: @c ---------------------------------------------------------------------
12715: @cindex implementation-defined options, floating-point words
12716: @cindex floating-point words, implementation-defined options
12717: 
12718: @table @i
12719: @item format and range of floating point numbers:
12720: @cindex format and range of floating point numbers
12721: @cindex floating point numbers, format and range
12722: System-dependent; the @code{double} type of C.
12723: 
12724: @item results of @code{REPRESENT} when @i{float} is out of range:
12725: @cindex  @code{REPRESENT}, results when @i{float} is out of range
12726: System dependent; @code{REPRESENT} is implemented using the C library
12727: function @code{ecvt()} and inherits its behaviour in this respect.
12728: 
12729: @item rounding or truncation of floating-point numbers:
12730: @cindex rounding of floating-point numbers
12731: @cindex truncation of floating-point numbers
12732: @cindex floating-point numbers, rounding or truncation
12733: System dependent; the rounding behaviour is inherited from the hosting C
12734: compiler. IEEE-FP-based (i.e., most) systems by default round to
12735: nearest, and break ties by rounding to even (i.e., such that the last
12736: bit of the mantissa is 0).
12737: 
12738: @item size of floating-point stack:
12739: @cindex floating-point stack size
12740: @code{s" FLOATING-STACK" environment? drop .} gives the total size of
12741: the floating-point stack (in floats). You can specify this on startup
12742: with the command-line option @code{-f} (@pxref{Invoking Gforth}).
12743: 
12744: @item width of floating-point stack:
12745: @cindex floating-point stack width 
12746: @code{1 floats}.
12747: 
12748: @end table
12749: 
12750: 
12751: @c ---------------------------------------------------------------------
12752: @node floating-ambcond,  , floating-idef, The optional Floating-Point word set
12753: @subsection Ambiguous conditions
12754: @c ---------------------------------------------------------------------
12755: @cindex floating-point words, ambiguous conditions
12756: @cindex ambiguous conditions, floating-point words
12757: 
12758: @table @i
12759: @item @code{df@@} or @code{df!} used with an address that is not double-float  aligned:
12760: @cindex @code{df@@} or @code{df!} used with an address that is not double-float  aligned
12761: System-dependent. Typically results in a @code{-23 THROW} like other
12762: alignment violations.
12763: 
12764: @item @code{f@@} or @code{f!} used with an address that is not float  aligned:
12765: @cindex @code{f@@} used with an address that is not float aligned
12766: @cindex @code{f!} used with an address that is not float aligned
12767: System-dependent. Typically results in a @code{-23 THROW} like other
12768: alignment violations.
12769: 
12770: @item floating-point result out of range:
12771: @cindex floating-point result out of range
12772: System-dependent. Can result in a @code{-55 THROW} (Floating-point
12773: unidentified fault), or can produce a special value representing, e.g.,
12774: Infinity.
12775: 
12776: @item @code{sf@@} or @code{sf!} used with an address that is not single-float  aligned:
12777: @cindex @code{sf@@} or @code{sf!} used with an address that is not single-float  aligned
12778: System-dependent. Typically results in an alignment fault like other
12779: alignment violations.
12780: 
12781: @item @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.}):
12782: @cindex @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.})
12783: The floating-point number is converted into decimal nonetheless.
12784: 
12785: @item Both arguments are equal to zero (@code{FATAN2}):
12786: @cindex @code{FATAN2}, both arguments are equal to zero
12787: System-dependent. @code{FATAN2} is implemented using the C library
12788: function @code{atan2()}.
12789: 
12790: @item Using @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero:
12791: @cindex @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero
12792: System-dependent. Anyway, typically the cos of @i{r1} will not be zero
12793: because of small errors and the tan will be a very large (or very small)
12794: but finite number.
12795: 
12796: @item @i{d} cannot be presented precisely as a float in @code{D>F}:
12797: @cindex @code{D>F}, @i{d} cannot be presented precisely as a float
12798: The result is rounded to the nearest float.
12799: 
12800: @item dividing by zero:
12801: @cindex dividing by zero, floating-point
12802: @cindex floating-point dividing by zero
12803: @cindex floating-point unidentified fault, FP divide-by-zero
12804: @code{-55 throw} (Floating-point unidentified fault)
12805: 
12806: @item exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@}):
12807: @cindex exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@})
12808: System dependent. On IEEE-FP based systems the number is converted into
12809: an infinity.
12810: 
12811: @item @i{float}<1 (@code{FACOSH}):
12812: @cindex @code{FACOSH}, @i{float}<1
12813: @cindex floating-point unidentified fault, @code{FACOSH}
12814: @code{-55 throw} (Floating-point unidentified fault)
12815: 
12816: @item @i{float}=<-1 (@code{FLNP1}):
12817: @cindex @code{FLNP1}, @i{float}=<-1
12818: @cindex floating-point unidentified fault, @code{FLNP1}
12819: @code{-55 throw} (Floating-point unidentified fault). On IEEE-FP systems
12820: negative infinity is typically produced for @i{float}=-1.
12821: 
12822: @item @i{float}=<0 (@code{FLN}, @code{FLOG}):
12823: @cindex @code{FLN}, @i{float}=<0
12824: @cindex @code{FLOG}, @i{float}=<0
12825: @cindex floating-point unidentified fault, @code{FLN} or @code{FLOG}
12826: @code{-55 throw} (Floating-point unidentified fault). On IEEE-FP systems
12827: negative infinity is typically produced for @i{float}=0.
12828: 
12829: @item @i{float}<0 (@code{FASINH}, @code{FSQRT}):
12830: @cindex @code{FASINH}, @i{float}<0
12831: @cindex @code{FSQRT}, @i{float}<0
12832: @cindex floating-point unidentified fault, @code{FASINH} or @code{FSQRT}
12833: @code{-55 throw} (Floating-point unidentified fault). @code{fasinh}
12834: produces values for these inputs on my Linux box (Bug in the C library?)
12835: 
12836: @item |@i{float}|>1 (@code{FACOS}, @code{FASIN}, @code{FATANH}):
12837: @cindex @code{FACOS}, |@i{float}|>1
12838: @cindex @code{FASIN}, |@i{float}|>1
12839: @cindex @code{FATANH}, |@i{float}|>1
12840: @cindex floating-point unidentified fault, @code{FACOS}, @code{FASIN} or @code{FATANH}
12841: @code{-55 throw} (Floating-point unidentified fault).
12842: 
12843: @item integer part of float cannot be represented by @i{d} in @code{F>D}:
12844: @cindex @code{F>D}, integer part of float cannot be represented by @i{d}
12845: @cindex floating-point unidentified fault, @code{F>D}
12846: @code{-55 throw} (Floating-point unidentified fault).
12847: 
12848: @item string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.}):
12849: @cindex string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.})
12850: This does not happen.
12851: @end table
12852: 
12853: @c =====================================================================
12854: @node  The optional Locals word set, The optional Memory-Allocation word set, The optional Floating-Point word set, ANS conformance
12855: @section The optional Locals word set
12856: @c =====================================================================
12857: @cindex system documentation, locals words
12858: @cindex locals words, system documentation
12859: 
12860: @menu
12861: * locals-idef::                 Implementation Defined Options                 
12862: * locals-ambcond::              Ambiguous Conditions              
12863: @end menu
12864: 
12865: 
12866: @c ---------------------------------------------------------------------
12867: @node locals-idef, locals-ambcond, The optional Locals word set, The optional Locals word set
12868: @subsection Implementation Defined Options
12869: @c ---------------------------------------------------------------------
12870: @cindex implementation-defined options, locals words
12871: @cindex locals words, implementation-defined options
12872: 
12873: @table @i
12874: @item maximum number of locals in a definition:
12875: @cindex maximum number of locals in a definition
12876: @cindex locals, maximum number in a definition
12877: @code{s" #locals" environment? drop .}. Currently 15. This is a lower
12878: bound, e.g., on a 32-bit machine there can be 41 locals of up to 8
12879: characters. The number of locals in a definition is bounded by the size
12880: of locals-buffer, which contains the names of the locals.
12881: 
12882: @end table
12883: 
12884: 
12885: @c ---------------------------------------------------------------------
12886: @node locals-ambcond,  , locals-idef, The optional Locals word set
12887: @subsection Ambiguous conditions
12888: @c ---------------------------------------------------------------------
12889: @cindex locals words, ambiguous conditions
12890: @cindex ambiguous conditions, locals words
12891: 
12892: @table @i
12893: @item executing a named local in interpretation state:
12894: @cindex local in interpretation state
12895: @cindex Interpreting a compile-only word, for a local
12896: Locals have no interpretation semantics. If you try to perform the
12897: interpretation semantics, you will get a @code{-14 throw} somewhere
12898: (Interpreting a compile-only word). If you perform the compilation
12899: semantics, the locals access will be compiled (irrespective of state).
12900: 
12901: @item @i{name} not defined by @code{VALUE} or @code{(LOCAL)} (@code{TO}):
12902: @cindex name not defined by @code{VALUE} or @code{(LOCAL)} used by @code{TO}
12903: @cindex @code{TO} on non-@code{VALUE}s and non-locals
12904: @cindex Invalid name argument, @code{TO}
12905: @code{-32 throw} (Invalid name argument)
12906: 
12907: @end table
12908: 
12909: 
12910: @c =====================================================================
12911: @node  The optional Memory-Allocation word set, The optional Programming-Tools word set, The optional Locals word set, ANS conformance
12912: @section The optional Memory-Allocation word set
12913: @c =====================================================================
12914: @cindex system documentation, memory-allocation words
12915: @cindex memory-allocation words, system documentation
12916: 
12917: @menu
12918: * memory-idef::                 Implementation Defined Options                 
12919: @end menu
12920: 
12921: 
12922: @c ---------------------------------------------------------------------
12923: @node memory-idef,  , The optional Memory-Allocation word set, The optional Memory-Allocation word set
12924: @subsection Implementation Defined Options
12925: @c ---------------------------------------------------------------------
12926: @cindex implementation-defined options, memory-allocation words
12927: @cindex memory-allocation words, implementation-defined options
12928: 
12929: @table @i
12930: @item values and meaning of @i{ior}:
12931: @cindex  @i{ior} values and meaning
12932: The @i{ior}s returned by the file and memory allocation words are
12933: intended as throw codes. They typically are in the range
12934: -512@minus{}-2047 of OS errors.  The mapping from OS error numbers to
12935: @i{ior}s is -512@minus{}@i{errno}.
12936: 
12937: @end table
12938: 
12939: @c =====================================================================
12940: @node  The optional Programming-Tools word set, The optional Search-Order word set, The optional Memory-Allocation word set, ANS conformance
12941: @section The optional Programming-Tools word set
12942: @c =====================================================================
12943: @cindex system documentation, programming-tools words
12944: @cindex programming-tools words, system documentation
12945: 
12946: @menu
12947: * programming-idef::            Implementation Defined Options            
12948: * programming-ambcond::         Ambiguous Conditions         
12949: @end menu
12950: 
12951: 
12952: @c ---------------------------------------------------------------------
12953: @node programming-idef, programming-ambcond, The optional Programming-Tools word set, The optional Programming-Tools word set
12954: @subsection Implementation Defined Options
12955: @c ---------------------------------------------------------------------
12956: @cindex implementation-defined options, programming-tools words
12957: @cindex programming-tools words, implementation-defined options
12958: 
12959: @table @i
12960: @item ending sequence for input following @code{;CODE} and @code{CODE}:
12961: @cindex @code{;CODE} ending sequence
12962: @cindex @code{CODE} ending sequence
12963: @code{END-CODE}
12964: 
12965: @item manner of processing input following @code{;CODE} and @code{CODE}:
12966: @cindex @code{;CODE}, processing input
12967: @cindex @code{CODE}, processing input
12968: The @code{ASSEMBLER} vocabulary is pushed on the search order stack, and
12969: the input is processed by the text interpreter, (starting) in interpret
12970: state.
12971: 
12972: @item search order capability for @code{EDITOR} and @code{ASSEMBLER}:
12973: @cindex @code{ASSEMBLER}, search order capability
12974: The ANS Forth search order word set.
12975: 
12976: @item source and format of display by @code{SEE}:
12977: @cindex @code{SEE}, source and format of output
12978: The source for @code{see} is the intermediate code used by the inner
12979: interpreter.  The current @code{see} tries to output Forth source code
12980: as well as possible.
12981: 
12982: @end table
12983: 
12984: @c ---------------------------------------------------------------------
12985: @node programming-ambcond,  , programming-idef, The optional Programming-Tools word set
12986: @subsection Ambiguous conditions
12987: @c ---------------------------------------------------------------------
12988: @cindex programming-tools words, ambiguous conditions
12989: @cindex ambiguous conditions, programming-tools words
12990: 
12991: @table @i
12992: 
12993: @item deleting the compilation word list (@code{FORGET}):
12994: @cindex @code{FORGET}, deleting the compilation word list
12995: Not implemented (yet).
12996: 
12997: @item fewer than @i{u}+1 items on the control-flow stack (@code{CS-PICK}, @code{CS-ROLL}):
12998: @cindex @code{CS-PICK}, fewer than @i{u}+1 items on the control flow-stack
12999: @cindex @code{CS-ROLL}, fewer than @i{u}+1 items on the control flow-stack
13000: @cindex control-flow stack underflow
13001: This typically results in an @code{abort"} with a descriptive error
13002: message (may change into a @code{-22 throw} (Control structure mismatch)
13003: in the future). You may also get a memory access error. If you are
13004: unlucky, this ambiguous condition is not caught.
13005: 
13006: @item @i{name} can't be found (@code{FORGET}):
13007: @cindex @code{FORGET}, @i{name} can't be found
13008: Not implemented (yet).
13009: 
13010: @item @i{name} not defined via @code{CREATE}:
13011: @cindex @code{;CODE}, @i{name} not defined via @code{CREATE}
13012: @code{;CODE} behaves like @code{DOES>} in this respect, i.e., it changes
13013: the execution semantics of the last defined word no matter how it was
13014: defined.
13015: 
13016: @item @code{POSTPONE} applied to @code{[IF]}:
13017: @cindex @code{POSTPONE} applied to @code{[IF]}
13018: @cindex @code{[IF]} and @code{POSTPONE}
13019: After defining @code{: X POSTPONE [IF] ; IMMEDIATE}. @code{X} is
13020: equivalent to @code{[IF]}.
13021: 
13022: @item reaching the end of the input source before matching @code{[ELSE]} or @code{[THEN]}:
13023: @cindex @code{[IF]}, end of the input source before matching @code{[ELSE]} or @code{[THEN]}
13024: Continue in the same state of conditional compilation in the next outer
13025: input source. Currently there is no warning to the user about this.
13026: 
13027: @item removing a needed definition (@code{FORGET}):
13028: @cindex @code{FORGET}, removing a needed definition
13029: Not implemented (yet).
13030: 
13031: @end table
13032: 
13033: 
13034: @c =====================================================================
13035: @node  The optional Search-Order word set,  , The optional Programming-Tools word set, ANS conformance
13036: @section The optional Search-Order word set
13037: @c =====================================================================
13038: @cindex system documentation, search-order words
13039: @cindex search-order words, system documentation
13040: 
13041: @menu
13042: * search-idef::                 Implementation Defined Options                 
13043: * search-ambcond::              Ambiguous Conditions              
13044: @end menu
13045: 
13046: 
13047: @c ---------------------------------------------------------------------
13048: @node search-idef, search-ambcond, The optional Search-Order word set, The optional Search-Order word set
13049: @subsection Implementation Defined Options
13050: @c ---------------------------------------------------------------------
13051: @cindex implementation-defined options, search-order words
13052: @cindex search-order words, implementation-defined options
13053: 
13054: @table @i
13055: @item maximum number of word lists in search order:
13056: @cindex maximum number of word lists in search order
13057: @cindex search order, maximum depth
13058: @code{s" wordlists" environment? drop .}. Currently 16.
13059: 
13060: @item minimum search order:
13061: @cindex minimum search order
13062: @cindex search order, minimum
13063: @code{root root}.
13064: 
13065: @end table
13066: 
13067: @c ---------------------------------------------------------------------
13068: @node search-ambcond,  , search-idef, The optional Search-Order word set
13069: @subsection Ambiguous conditions
13070: @c ---------------------------------------------------------------------
13071: @cindex search-order words, ambiguous conditions
13072: @cindex ambiguous conditions, search-order words
13073: 
13074: @table @i
13075: @item changing the compilation word list (during compilation):
13076: @cindex changing the compilation word list (during compilation)
13077: @cindex compilation word list, change before definition ends
13078: The word is entered into the word list that was the compilation word list
13079: at the start of the definition. Any changes to the name field (e.g.,
13080: @code{immediate}) or the code field (e.g., when executing @code{DOES>})
13081: are applied to the latest defined word (as reported by @code{last} or
13082: @code{lastxt}), if possible, irrespective of the compilation word list.
13083: 
13084: @item search order empty (@code{previous}):
13085: @cindex @code{previous}, search order empty
13086: @cindex vocstack empty, @code{previous}
13087: @code{abort" Vocstack empty"}.
13088: 
13089: @item too many word lists in search order (@code{also}):
13090: @cindex @code{also}, too many word lists in search order
13091: @cindex vocstack full, @code{also}
13092: @code{abort" Vocstack full"}.
13093: 
13094: @end table
13095: 
13096: @c ***************************************************************
13097: @node Standard vs Extensions, Model, ANS conformance, Top
13098: @chapter Should I use Gforth extensions?
13099: @cindex Gforth extensions
13100: 
13101: As you read through the rest of this manual, you will see documentation
13102: for @i{Standard} words, and documentation for some appealing Gforth
13103: @i{extensions}. You might ask yourself the question: @i{``Should I
13104: restrict myself to the standard, or should I use the extensions?''}
13105: 
13106: The answer depends on the goals you have for the program you are working
13107: on:
13108: 
13109: @itemize @bullet
13110: 
13111: @item Is it just for yourself or do you want to share it with others?
13112: 
13113: @item
13114: If you want to share it, do the others all use Gforth?
13115: 
13116: @item
13117: If it is just for yourself, do you want to restrict yourself to Gforth?
13118: 
13119: @end itemize
13120: 
13121: If restricting the program to Gforth is ok, then there is no reason not
13122: to use extensions.  It is still a good idea to keep to the standard
13123: where it is easy, in case you want to reuse these parts in another
13124: program that you want to be portable.
13125: 
13126: If you want to be able to port the program to other Forth systems, there
13127: are the following points to consider:
13128: 
13129: @itemize @bullet
13130: 
13131: @item
13132: Most Forth systems that are being maintained support the ANS Forth
13133: standard.  So if your program complies with the standard, it will be
13134: portable among many systems.
13135: 
13136: @item
13137: A number of the Gforth extensions can be implemented in ANS Forth using
13138: public-domain files provided in the @file{compat/} directory. These are
13139: mentioned in the text in passing.  There is no reason not to use these
13140: extensions, your program will still be ANS Forth compliant; just include
13141: the appropriate compat files with your program.
13142: 
13143: @item
13144: The tool @file{ans-report.fs} (@pxref{ANS Report}) makes it easy to
13145: analyse your program and determine what non-Standard words it relies
13146: upon.  However, it does not check whether you use standard words in a
13147: non-standard way.
13148: 
13149: @item
13150: Some techniques are not standardized by ANS Forth, and are hard or
13151: impossible to implement in a standard way, but can be implemented in
13152: most Forth systems easily, and usually in similar ways (e.g., accessing
13153: word headers).  Forth has a rich historical precedent for programmers
13154: taking advantage of implementation-dependent features of their tools
13155: (for example, relying on a knowledge of the dictionary
13156: structure). Sometimes these techniques are necessary to extract every
13157: last bit of performance from the hardware, sometimes they are just a
13158: programming shorthand.
13159: 
13160: @item
13161: Does using a Gforth extension save more work than the porting this part
13162: to other Forth systems (if any) will cost?
13163: 
13164: @item
13165: Is the additional functionality worth the reduction in portability and
13166: the additional porting problems?
13167: 
13168: @end itemize
13169: 
13170: In order to perform these consideratios, you need to know what's
13171: standard and what's not.  This manual generally states if something is
13172: non-standard, but the authoritative source is the standard document.
13173: Appendix A of the Standard (@var{Rationale}) provides a valuable insight
13174: into the thought processes of the technical committee.
13175: 
13176: Note also that portability between Forth systems is not the only
13177: portability issue; there is also the issue of portability between
13178: different platforms (processor/OS combinations).
13179: 
13180: @c ***************************************************************
13181: @node Model, Integrating Gforth, Standard vs Extensions, Top
13182: @chapter Model
13183: 
13184: This chapter has yet to be written. It will contain information, on
13185: which internal structures you can rely.
13186: 
13187: @c ***************************************************************
13188: @node Integrating Gforth, Emacs and Gforth, Model, Top
13189: @chapter Integrating Gforth into C programs
13190: 
13191: This is not yet implemented.
13192: 
13193: Several people like to use Forth as scripting language for applications
13194: that are otherwise written in C, C++, or some other language.
13195: 
13196: The Forth system ATLAST provides facilities for embedding it into
13197: applications; unfortunately it has several disadvantages: most
13198: importantly, it is not based on ANS Forth, and it is apparently dead
13199: (i.e., not developed further and not supported). The facilities
13200: provided by Gforth in this area are inspired by ATLAST's facilities, so
13201: making the switch should not be hard.
13202: 
13203: We also tried to design the interface such that it can easily be
13204: implemented by other Forth systems, so that we may one day arrive at a
13205: standardized interface. Such a standard interface would allow you to
13206: replace the Forth system without having to rewrite C code.
13207: 
13208: You embed the Gforth interpreter by linking with the library
13209: @code{libgforth.a} (give the compiler the option @code{-lgforth}).  All
13210: global symbols in this library that belong to the interface, have the
13211: prefix @code{forth_}. (Global symbols that are used internally have the
13212: prefix @code{gforth_}).
13213: 
13214: You can include the declarations of Forth types and the functions and
13215: variables of the interface with @code{#include <forth.h>}.
13216: 
13217: Types.
13218: 
13219: Variables.
13220: 
13221: Data and FP Stack pointer. Area sizes.
13222: 
13223: functions.
13224: 
13225: forth_init(imagefile)
13226: forth_evaluate(string) exceptions?
13227: forth_goto(address) (or forth_execute(xt)?)
13228: forth_continue() (a corountining mechanism)
13229: 
13230: Adding primitives.
13231: 
13232: No checking.
13233: 
13234: Signals?
13235: 
13236: Accessing the Stacks
13237: 
13238: @c ******************************************************************
13239: @node Emacs and Gforth, Image Files, Integrating Gforth, Top
13240: @chapter Emacs and Gforth
13241: @cindex Emacs and Gforth
13242: 
13243: @cindex @file{gforth.el}
13244: @cindex @file{forth.el}
13245: @cindex Rydqvist, Goran
13246: @cindex comment editing commands
13247: @cindex @code{\}, editing with Emacs
13248: @cindex debug tracer editing commands
13249: @cindex @code{~~}, removal with Emacs
13250: @cindex Forth mode in Emacs
13251: Gforth comes with @file{gforth.el}, an improved version of
13252: @file{forth.el} by Goran Rydqvist (included in the TILE package). The
13253: improvements are:
13254: 
13255: @itemize @bullet
13256: @item
13257: A better (but still not perfect) handling of indentation.
13258: @item
13259: Comment paragraph filling (@kbd{M-q})
13260: @item
13261: Commenting (@kbd{C-x \}) and uncommenting (@kbd{C-u C-x \}) of regions
13262: @item
13263: Removal of debugging tracers (@kbd{C-x ~}, @pxref{Debugging}).
13264: @item
13265: Support of the @code{info-lookup} feature for looking up the
13266: documentation of a word.
13267: @end itemize
13268: 
13269: I left the stuff I do not use alone, even though some of it only makes
13270: sense for TILE. To get a description of these features, enter Forth mode
13271: and type @kbd{C-h m}.
13272: 
13273: @cindex source location of error or debugging output in Emacs
13274: @cindex error output, finding the source location in Emacs
13275: @cindex debugging output, finding the source location in Emacs
13276: In addition, Gforth supports Emacs quite well: The source code locations
13277: given in error messages, debugging output (from @code{~~}) and failed
13278: assertion messages are in the right format for Emacs' compilation mode
13279: (@pxref{Compilation, , Running Compilations under Emacs, emacs, Emacs
13280: Manual}) so the source location corresponding to an error or other
13281: message is only a few keystrokes away (@kbd{C-x `} for the next error,
13282: @kbd{C-c C-c} for the error under the cursor).
13283: 
13284: @cindex @file{TAGS} file
13285: @cindex @file{etags.fs}
13286: @cindex viewing the source of a word in Emacs
13287: @cindex @code{require}, placement in files
13288: @cindex @code{include}, placement in files
13289: Also, if you @code{require} @file{etags.fs}, a new @file{TAGS} file will
13290: be produced (@pxref{Tags, , Tags Tables, emacs, Emacs Manual}) that
13291: contains the definitions of all words defined afterwards. You can then
13292: find the source for a word using @kbd{M-.}. Note that emacs can use
13293: several tags files at the same time (e.g., one for the Gforth sources
13294: and one for your program, @pxref{Select Tags Table,,Selecting a Tags
13295: Table,emacs, Emacs Manual}). The TAGS file for the preloaded words is
13296: @file{$(datadir)/gforth/$(VERSION)/TAGS} (e.g.,
13297: @file{/usr/local/share/gforth/0.2.0/TAGS}).  To get the best behaviour
13298: with @file{etags.fs}, you should avoid putting definitions both before
13299: and after @code{require} etc., otherwise you will see the same file
13300: visited several times by commands like @code{tags-search}.
13301: 
13302: @cindex viewing the documentation of a word in Emacs
13303: @cindex context-sensitive help
13304: Moreover, for words documented in this manual, you can look up the
13305: glossary entry quickly by using @kbd{C-h TAB}
13306: (@code{info-lookup-symbol}, see @pxref{Documentation, ,Documentation
13307: Commands, emacs, Emacs Manual}).  This feature requires Emacs 20.3 or
13308: later and does not work for words containing @code{:}.
13309: 
13310: 
13311: @cindex @file{.emacs}
13312: To get all these benefits, add the following lines to your @file{.emacs}
13313: file:
13314: 
13315: @example
13316: (autoload 'forth-mode "gforth.el")
13317: (setq auto-mode-alist (cons '("\\.fs\\'" . forth-mode) auto-mode-alist))
13318: @end example
13319: 
13320: @c ******************************************************************
13321: @node Image Files, Engine, Emacs and Gforth, Top
13322: @chapter Image Files
13323: @cindex image file
13324: @cindex @file{.fi} files
13325: @cindex precompiled Forth code
13326: @cindex dictionary in persistent form
13327: @cindex persistent form of dictionary
13328: 
13329: An image file is a file containing an image of the Forth dictionary,
13330: i.e., compiled Forth code and data residing in the dictionary.  By
13331: convention, we use the extension @code{.fi} for image files.
13332: 
13333: @menu
13334: * Image Licensing Issues::      Distribution terms for images.
13335: * Image File Background::       Why have image files?
13336: * Non-Relocatable Image Files::  don't always work.
13337: * Data-Relocatable Image Files::  are better.
13338: * Fully Relocatable Image Files::  better yet.
13339: * Stack and Dictionary Sizes::  Setting the default sizes for an image.
13340: * Running Image Files::         @code{gforth -i @i{file}} or @i{file}.
13341: * Modifying the Startup Sequence::  and turnkey applications.
13342: @end menu
13343: 
13344: @node Image Licensing Issues, Image File Background, Image Files, Image Files
13345: @section Image Licensing Issues
13346: @cindex license for images
13347: @cindex image license
13348: 
13349: An image created with @code{gforthmi} (@pxref{gforthmi}) or
13350: @code{savesystem} (@pxref{Non-Relocatable Image Files}) includes the
13351: original image; i.e., according to copyright law it is a derived work of
13352: the original image.
13353: 
13354: Since Gforth is distributed under the GNU GPL, the newly created image
13355: falls under the GNU GPL, too. In particular, this means that if you
13356: distribute the image, you have to make all of the sources for the image
13357: available, including those you wrote.  For details see @ref{License, ,
13358: GNU General Public License (Section 3)}.
13359: 
13360: If you create an image with @code{cross} (@pxref{cross.fs}), the image
13361: contains only code compiled from the sources you gave it; if none of
13362: these sources is under the GPL, the terms discussed above do not apply
13363: to the image. However, if your image needs an engine (a gforth binary)
13364: that is under the GPL, you should make sure that you distribute both in
13365: a way that is at most a @emph{mere aggregation}, if you don't want the
13366: terms of the GPL to apply to the image.
13367: 
13368: @node Image File Background, Non-Relocatable Image Files, Image Licensing Issues, Image Files
13369: @section Image File Background
13370: @cindex image file background
13371: 
13372: Our Forth system consists not only of primitives, but also of
13373: definitions written in Forth. Since the Forth compiler itself belongs to
13374: those definitions, it is not possible to start the system with the
13375: primitives and the Forth source alone. Therefore we provide the Forth
13376: code as an image file in nearly executable form. When Gforth starts up,
13377: a C routine loads the image file into memory, optionally relocates the
13378: addresses, then sets up the memory (stacks etc.) according to
13379: information in the image file, and (finally) starts executing Forth
13380: code.
13381: 
13382: The image file variants represent different compromises between the
13383: goals of making it easy to generate image files and making them
13384: portable.
13385: 
13386: @cindex relocation at run-time
13387: Win32Forth 3.4 and Mitch Bradley's @code{cforth} use relocation at
13388: run-time. This avoids many of the complications discussed below (image
13389: files are data relocatable without further ado), but costs performance
13390: (one addition per memory access).
13391: 
13392: @cindex relocation at load-time
13393: By contrast, the Gforth loader performs relocation at image load time. The
13394: loader also has to replace tokens that represent primitive calls with the
13395: appropriate code-field addresses (or code addresses in the case of
13396: direct threading).
13397: 
13398: There are three kinds of image files, with different degrees of
13399: relocatability: non-relocatable, data-relocatable, and fully relocatable
13400: image files.
13401: 
13402: @cindex image file loader
13403: @cindex relocating loader
13404: @cindex loader for image files
13405: These image file variants have several restrictions in common; they are
13406: caused by the design of the image file loader:
13407: 
13408: @itemize @bullet
13409: @item
13410: There is only one segment; in particular, this means, that an image file
13411: cannot represent @code{ALLOCATE}d memory chunks (and pointers to
13412: them). The contents of the stacks are not represented, either.
13413: 
13414: @item
13415: The only kinds of relocation supported are: adding the same offset to
13416: all cells that represent data addresses; and replacing special tokens
13417: with code addresses or with pieces of machine code.
13418: 
13419: If any complex computations involving addresses are performed, the
13420: results cannot be represented in the image file. Several applications that
13421: use such computations come to mind:
13422: @itemize @minus
13423: @item
13424: Hashing addresses (or data structures which contain addresses) for table
13425: lookup. If you use Gforth's @code{table}s or @code{wordlist}s for this
13426: purpose, you will have no problem, because the hash tables are
13427: recomputed automatically when the system is started. If you use your own
13428: hash tables, you will have to do something similar.
13429: 
13430: @item
13431: There's a cute implementation of doubly-linked lists that uses
13432: @code{XOR}ed addresses. You could represent such lists as singly-linked
13433: in the image file, and restore the doubly-linked representation on
13434: startup.@footnote{In my opinion, though, you should think thrice before
13435: using a doubly-linked list (whatever implementation).}
13436: 
13437: @item
13438: The code addresses of run-time routines like @code{docol:} cannot be
13439: represented in the image file (because their tokens would be replaced by
13440: machine code in direct threaded implementations). As a workaround,
13441: compute these addresses at run-time with @code{>code-address} from the
13442: executions tokens of appropriate words (see the definitions of
13443: @code{docol:} and friends in @file{kernel.fs}).
13444: 
13445: @item
13446: On many architectures addresses are represented in machine code in some
13447: shifted or mangled form. You cannot put @code{CODE} words that contain
13448: absolute addresses in this form in a relocatable image file. Workarounds
13449: are representing the address in some relative form (e.g., relative to
13450: the CFA, which is present in some register), or loading the address from
13451: a place where it is stored in a non-mangled form.
13452: @end itemize
13453: @end itemize
13454: 
13455: @node  Non-Relocatable Image Files, Data-Relocatable Image Files, Image File Background, Image Files
13456: @section Non-Relocatable Image Files
13457: @cindex non-relocatable image files
13458: @cindex image file, non-relocatable
13459: 
13460: These files are simple memory dumps of the dictionary. They are specific
13461: to the executable (i.e., @file{gforth} file) they were created
13462: with. What's worse, they are specific to the place on which the
13463: dictionary resided when the image was created. Now, there is no
13464: guarantee that the dictionary will reside at the same place the next
13465: time you start Gforth, so there's no guarantee that a non-relocatable
13466: image will work the next time (Gforth will complain instead of crashing,
13467: though).
13468: 
13469: You can create a non-relocatable image file with
13470: 
13471: 
13472: doc-savesystem
13473: 
13474: 
13475: @node Data-Relocatable Image Files, Fully Relocatable Image Files, Non-Relocatable Image Files, Image Files
13476: @section Data-Relocatable Image Files
13477: @cindex data-relocatable image files
13478: @cindex image file, data-relocatable
13479: 
13480: These files contain relocatable data addresses, but fixed code addresses
13481: (instead of tokens). They are specific to the executable (i.e.,
13482: @file{gforth} file) they were created with. For direct threading on some
13483: architectures (e.g., the i386), data-relocatable images do not work. You
13484: get a data-relocatable image, if you use @file{gforthmi} with a
13485: Gforth binary that is not doubly indirect threaded (@pxref{Fully
13486: Relocatable Image Files}).
13487: 
13488: @node Fully Relocatable Image Files, Stack and Dictionary Sizes, Data-Relocatable Image Files, Image Files
13489: @section Fully Relocatable Image Files
13490: @cindex fully relocatable image files
13491: @cindex image file, fully relocatable
13492: 
13493: @cindex @file{kern*.fi}, relocatability
13494: @cindex @file{gforth.fi}, relocatability
13495: These image files have relocatable data addresses, and tokens for code
13496: addresses. They can be used with different binaries (e.g., with and
13497: without debugging) on the same machine, and even across machines with
13498: the same data formats (byte order, cell size, floating point
13499: format). However, they are usually specific to the version of Gforth
13500: they were created with. The files @file{gforth.fi} and @file{kernl*.fi}
13501: are fully relocatable.
13502: 
13503: There are two ways to create a fully relocatable image file:
13504: 
13505: @menu
13506: * gforthmi::                    The normal way
13507: * cross.fs::                    The hard way
13508: @end menu
13509: 
13510: @node gforthmi, cross.fs, Fully Relocatable Image Files, Fully Relocatable Image Files
13511: @subsection @file{gforthmi}
13512: @cindex @file{comp-i.fs}
13513: @cindex @file{gforthmi}
13514: 
13515: You will usually use @file{gforthmi}. If you want to create an
13516: image @i{file} that contains everything you would load by invoking
13517: Gforth with @code{gforth @i{options}}, you simply say:
13518: @example
13519: gforthmi @i{file} @i{options}
13520: @end example
13521: 
13522: E.g., if you want to create an image @file{asm.fi} that has the file
13523: @file{asm.fs} loaded in addition to the usual stuff, you could do it
13524: like this:
13525: 
13526: @example
13527: gforthmi asm.fi asm.fs
13528: @end example
13529: 
13530: @file{gforthmi} is implemented as a sh script and works like this: It
13531: produces two non-relocatable images for different addresses and then
13532: compares them. Its output reflects this: first you see the output (if
13533: any) of the two Gforth invocations that produce the non-relocatable image
13534: files, then you see the output of the comparing program: It displays the
13535: offset used for data addresses and the offset used for code addresses;
13536: moreover, for each cell that cannot be represented correctly in the
13537: image files, it displays a line like this:
13538: 
13539: @example
13540:      78DC         BFFFFA50         BFFFFA40
13541: @end example
13542: 
13543: This means that at offset $78dc from @code{forthstart}, one input image
13544: contains $bffffa50, and the other contains $bffffa40. Since these cells
13545: cannot be represented correctly in the output image, you should examine
13546: these places in the dictionary and verify that these cells are dead
13547: (i.e., not read before they are written).
13548: 
13549: @cindex --application, @code{gforthmi} option
13550: If you insert the option @code{--application} in front of the image file
13551: name, you will get an image that uses the @code{--appl-image} option
13552: instead of the @code{--image-file} option (@pxref{Invoking
13553: Gforth}). When you execute such an image on Unix (by typing the image
13554: name as command), the Gforth engine will pass all options to the image
13555: instead of trying to interpret them as engine options.
13556: 
13557: If you type @file{gforthmi} with no arguments, it prints some usage
13558: instructions.
13559: 
13560: @cindex @code{savesystem} during @file{gforthmi}
13561: @cindex @code{bye} during @file{gforthmi}
13562: @cindex doubly indirect threaded code
13563: @cindex environment variables
13564: @cindex @code{GFORTHD} -- environment variable
13565: @cindex @code{GFORTH} -- environment variable
13566: @cindex @code{gforth-ditc}
13567: There are a few wrinkles: After processing the passed @i{options}, the
13568: words @code{savesystem} and @code{bye} must be visible. A special doubly
13569: indirect threaded version of the @file{gforth} executable is used for
13570: creating the non-relocatable images; you can pass the exact filename of
13571: this executable through the environment variable @code{GFORTHD}
13572: (default: @file{gforth-ditc}); if you pass a version that is not doubly
13573: indirect threaded, you will not get a fully relocatable image, but a
13574: data-relocatable image (because there is no code address offset). The
13575: normal @file{gforth} executable is used for creating the relocatable
13576: image; you can pass the exact filename of this executable through the
13577: environment variable @code{GFORTH}.
13578: 
13579: @node cross.fs,  , gforthmi, Fully Relocatable Image Files
13580: @subsection @file{cross.fs}
13581: @cindex @file{cross.fs}
13582: @cindex cross-compiler
13583: @cindex metacompiler
13584: @cindex target compiler
13585: 
13586: You can also use @code{cross}, a batch compiler that accepts a Forth-like
13587: programming language (@pxref{Cross Compiler}).
13588: 
13589: @code{cross} allows you to create image files for machines with
13590: different data sizes and data formats than the one used for generating
13591: the image file. You can also use it to create an application image that
13592: does not contain a Forth compiler. These features are bought with
13593: restrictions and inconveniences in programming. E.g., addresses have to
13594: be stored in memory with special words (@code{A!}, @code{A,}, etc.) in
13595: order to make the code relocatable.
13596: 
13597: 
13598: @node Stack and Dictionary Sizes, Running Image Files, Fully Relocatable Image Files, Image Files
13599: @section Stack and Dictionary Sizes
13600: @cindex image file, stack and dictionary sizes
13601: @cindex dictionary size default
13602: @cindex stack size default
13603: 
13604: If you invoke Gforth with a command line flag for the size
13605: (@pxref{Invoking Gforth}), the size you specify is stored in the
13606: dictionary. If you save the dictionary with @code{savesystem} or create
13607: an image with @file{gforthmi}, this size will become the default
13608: for the resulting image file. E.g., the following will create a
13609: fully relocatable version of @file{gforth.fi} with a 1MB dictionary:
13610: 
13611: @example
13612: gforthmi gforth.fi -m 1M
13613: @end example
13614: 
13615: In other words, if you want to set the default size for the dictionary
13616: and the stacks of an image, just invoke @file{gforthmi} with the
13617: appropriate options when creating the image.
13618: 
13619: @cindex stack size, cache-friendly
13620: Note: For cache-friendly behaviour (i.e., good performance), you should
13621: make the sizes of the stacks modulo, say, 2K, somewhat different. E.g.,
13622: the default stack sizes are: data: 16k (mod 2k=0); fp: 15.5k (mod
13623: 2k=1.5k); return: 15k(mod 2k=1k); locals: 14.5k (mod 2k=0.5k).
13624: 
13625: @node Running Image Files, Modifying the Startup Sequence, Stack and Dictionary Sizes, Image Files
13626: @section Running Image Files
13627: @cindex running image files
13628: @cindex invoking image files
13629: @cindex image file invocation
13630: 
13631: @cindex -i, invoke image file
13632: @cindex --image file, invoke image file
13633: You can invoke Gforth with an image file @i{image} instead of the
13634: default @file{gforth.fi} with the @code{-i} flag (@pxref{Invoking Gforth}):
13635: @example
13636: gforth -i @i{image}
13637: @end example
13638: 
13639: @cindex executable image file
13640: @cindex image file, executable
13641: If your operating system supports starting scripts with a line of the
13642: form @code{#! ...}, you just have to type the image file name to start
13643: Gforth with this image file (note that the file extension @code{.fi} is
13644: just a convention). I.e., to run Gforth with the image file @i{image},
13645: you can just type @i{image} instead of @code{gforth -i @i{image}}.
13646: This works because every @code{.fi} file starts with a line of this
13647: format:
13648: 
13649: @example
13650: #! /usr/local/bin/gforth-0.4.0 -i
13651: @end example
13652: 
13653: The file and pathname for the Gforth engine specified on this line is
13654: the specific Gforth executable that it was built against; i.e. the value
13655: of the environment variable @code{GFORTH} at the time that
13656: @file{gforthmi} was executed.
13657: 
13658: You can make use of the same shell capability to make a Forth source
13659: file into an executable. For example, if you place this text in a file:
13660: 
13661: @example
13662: #! /usr/local/bin/gforth
13663: 
13664: ." Hello, world" CR
13665: bye
13666: @end example
13667: 
13668: @noindent
13669: and then make the file executable (chmod +x in Unix), you can run it
13670: directly from the command line. The sequence @code{#!} is used in two
13671: ways; firstly, it is recognised as a ``magic sequence'' by the operating
13672: system@footnote{The Unix kernel actually recognises two types of files:
13673: executable files and files of data, where the data is processed by an
13674: interpreter that is specified on the ``interpreter line'' -- the first
13675: line of the file, starting with the sequence #!. There may be a small
13676: limit (e.g., 32) on the number of characters that may be specified on
13677: the interpreter line.} secondly it is treated as a comment character by
13678: Gforth. Because of the second usage, a space is required between
13679: @code{#!} and the path to the executable.
13680: 
13681: The disadvantage of this latter technique, compared with using
13682: @file{gforthmi}, is that it is slower; the Forth source code is compiled
13683: on-the-fly, each time the program is invoked.
13684: 
13685: 
13686: doc-#!
13687: 
13688: 
13689: @node Modifying the Startup Sequence,  , Running Image Files, Image Files
13690: @section Modifying the Startup Sequence
13691: @cindex startup sequence for image file
13692: @cindex image file initialization sequence
13693: @cindex initialization sequence of image file
13694: 
13695: You can add your own initialization to the startup sequence through the
13696: deferred word @code{'cold}. @code{'cold} is invoked just before the
13697: image-specific command line processing (by default, loading files and
13698: evaluating (@code{-e}) strings) starts.
13699: 
13700: A sequence for adding your initialization usually looks like this:
13701: 
13702: @example
13703: :noname
13704:     Defers 'cold \ do other initialization stuff (e.g., rehashing wordlists)
13705:     ... \ your stuff
13706: ; IS 'cold
13707: @end example
13708: 
13709: @cindex turnkey image files
13710: @cindex image file, turnkey applications
13711: You can make a turnkey image by letting @code{'cold} execute a word
13712: (your turnkey application) that never returns; instead, it exits Gforth
13713: via @code{bye} or @code{throw}.
13714: 
13715: @cindex command-line arguments, access
13716: @cindex arguments on the command line, access
13717: You can access the (image-specific) command-line arguments through the
13718: variables @code{argc} and @code{argv}. @code{arg} provides convenient
13719: access to @code{argv}.
13720: 
13721: If @code{'cold} exits normally, Gforth processes the command-line
13722: arguments as files to be loaded and strings to be evaluated.  Therefore,
13723: @code{'cold} should remove the arguments it has used in this case.
13724: 
13725: 
13726: 
13727: doc-'cold
13728: doc-argc
13729: doc-argv
13730: doc-arg
13731: 
13732: 
13733: 
13734: @c ******************************************************************
13735: @node Engine, Binding to System Library, Image Files, Top
13736: @chapter Engine
13737: @cindex engine
13738: @cindex virtual machine
13739: 
13740: Reading this chapter is not necessary for programming with Gforth. It
13741: may be helpful for finding your way in the Gforth sources.
13742: 
13743: The ideas in this section have also been published in Bernd Paysan,
13744: @cite{ANS fig/GNU/??? Forth} (in German), Forth-Tagung '93 and M. Anton
13745: Ertl, @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl93.ps.Z, A
13746: Portable Forth Engine}}, EuroForth '93.
13747: 
13748: @menu
13749: * Portability::                 
13750: * Threading::                   
13751: * Primitives::                  
13752: * Performance::                 
13753: @end menu
13754: 
13755: @node Portability, Threading, Engine, Engine
13756: @section Portability
13757: @cindex engine portability
13758: 
13759: An important goal of the Gforth Project is availability across a wide
13760: range of personal machines. fig-Forth, and, to a lesser extent, F83,
13761: achieved this goal by manually coding the engine in assembly language
13762: for several then-popular processors. This approach is very
13763: labor-intensive and the results are short-lived due to progress in
13764: computer architecture.
13765: 
13766: @cindex C, using C for the engine
13767: Others have avoided this problem by coding in C, e.g., Mitch Bradley
13768: (cforth), Mikael Patel (TILE) and Dirk Zoller (pfe). This approach is
13769: particularly popular for UNIX-based Forths due to the large variety of
13770: architectures of UNIX machines. Unfortunately an implementation in C
13771: does not mix well with the goals of efficiency and with using
13772: traditional techniques: Indirect or direct threading cannot be expressed
13773: in C, and switch threading, the fastest technique available in C, is
13774: significantly slower. Another problem with C is that it is very
13775: cumbersome to express double integer arithmetic.
13776: 
13777: @cindex GNU C for the engine
13778: @cindex long long
13779: Fortunately, there is a portable language that does not have these
13780: limitations: GNU C, the version of C processed by the GNU C compiler
13781: (@pxref{C Extensions, , Extensions to the C Language Family, gcc.info,
13782: GNU C Manual}). Its labels as values feature (@pxref{Labels as Values, ,
13783: Labels as Values, gcc.info, GNU C Manual}) makes direct and indirect
13784: threading possible, its @code{long long} type (@pxref{Long Long, ,
13785: Double-Word Integers, gcc.info, GNU C Manual}) corresponds to Forth's
13786: double numbers@footnote{Unfortunately, long longs are not implemented
13787: properly on all machines (e.g., on alpha-osf1, long longs are only 64
13788: bits, the same size as longs (and pointers), but they should be twice as
13789: long according to @pxref{Long Long, , Double-Word Integers, gcc.info, GNU
13790: C Manual}). So, we had to implement doubles in C after all. Still, on
13791: most machines we can use long longs and achieve better performance than
13792: with the emulation package.}. GNU C is available for free on all
13793: important (and many unimportant) UNIX machines, VMS, 80386s running
13794: MS-DOS, the Amiga, and the Atari ST, so a Forth written in GNU C can run
13795: on all these machines.
13796: 
13797: Writing in a portable language has the reputation of producing code that
13798: is slower than assembly. For our Forth engine we repeatedly looked at
13799: the code produced by the compiler and eliminated most compiler-induced
13800: inefficiencies by appropriate changes in the source code.
13801: 
13802: @cindex explicit register declarations
13803: @cindex --enable-force-reg, configuration flag
13804: @cindex -DFORCE_REG
13805: However, register allocation cannot be portably influenced by the
13806: programmer, leading to some inefficiencies on register-starved
13807: machines. We use explicit register declarations (@pxref{Explicit Reg
13808: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) to
13809: improve the speed on some machines. They are turned on by using the
13810: configuration flag @code{--enable-force-reg} (@code{gcc} switch
13811: @code{-DFORCE_REG}). Unfortunately, this feature not only depends on the
13812: machine, but also on the compiler version: On some machines some
13813: compiler versions produce incorrect code when certain explicit register
13814: declarations are used. So by default @code{-DFORCE_REG} is not used.
13815: 
13816: @node Threading, Primitives, Portability, Engine
13817: @section Threading
13818: @cindex inner interpreter implementation
13819: @cindex threaded code implementation
13820: 
13821: @cindex labels as values
13822: GNU C's labels as values extension (available since @code{gcc-2.0},
13823: @pxref{Labels as Values, , Labels as Values, gcc.info, GNU C Manual})
13824: makes it possible to take the address of @i{label} by writing
13825: @code{&&@i{label}}.  This address can then be used in a statement like
13826: @code{goto *@i{address}}. I.e., @code{goto *&&x} is the same as
13827: @code{goto x}.
13828: 
13829: @cindex @code{NEXT}, indirect threaded
13830: @cindex indirect threaded inner interpreter
13831: @cindex inner interpreter, indirect threaded
13832: With this feature an indirect threaded @code{NEXT} looks like:
13833: @example
13834: cfa = *ip++;
13835: ca = *cfa;
13836: goto *ca;
13837: @end example
13838: @cindex instruction pointer
13839: For those unfamiliar with the names: @code{ip} is the Forth instruction
13840: pointer; the @code{cfa} (code-field address) corresponds to ANS Forths
13841: execution token and points to the code field of the next word to be
13842: executed; The @code{ca} (code address) fetched from there points to some
13843: executable code, e.g., a primitive or the colon definition handler
13844: @code{docol}.
13845: 
13846: @cindex @code{NEXT}, direct threaded
13847: @cindex direct threaded inner interpreter
13848: @cindex inner interpreter, direct threaded
13849: Direct threading is even simpler:
13850: @example
13851: ca = *ip++;
13852: goto *ca;
13853: @end example
13854: 
13855: Of course we have packaged the whole thing neatly in macros called
13856: @code{NEXT} and @code{NEXT1} (the part of @code{NEXT} after fetching the cfa).
13857: 
13858: @menu
13859: * Scheduling::                  
13860: * Direct or Indirect Threaded?::  
13861: * DOES>::                       
13862: @end menu
13863: 
13864: @node Scheduling, Direct or Indirect Threaded?, Threading, Threading
13865: @subsection Scheduling
13866: @cindex inner interpreter optimization
13867: 
13868: There is a little complication: Pipelined and superscalar processors,
13869: i.e., RISC and some modern CISC machines can process independent
13870: instructions while waiting for the results of an instruction. The
13871: compiler usually reorders (schedules) the instructions in a way that
13872: achieves good usage of these delay slots. However, on our first tries
13873: the compiler did not do well on scheduling primitives. E.g., for
13874: @code{+} implemented as
13875: @example
13876: n=sp[0]+sp[1];
13877: sp++;
13878: sp[0]=n;
13879: NEXT;
13880: @end example
13881: the @code{NEXT} comes strictly after the other code, i.e., there is nearly no
13882: scheduling. After a little thought the problem becomes clear: The
13883: compiler cannot know that @code{sp} and @code{ip} point to different
13884: addresses (and the version of @code{gcc} we used would not know it even
13885: if it was possible), so it could not move the load of the cfa above the
13886: store to the TOS. Indeed the pointers could be the same, if code on or
13887: very near the top of stack were executed. In the interest of speed we
13888: chose to forbid this probably unused ``feature'' and helped the compiler
13889: in scheduling: @code{NEXT} is divided into the loading part (@code{NEXT_P1})
13890: and the goto part (@code{NEXT_P2}). @code{+} now looks like:
13891: @example
13892: n=sp[0]+sp[1];
13893: sp++;
13894: NEXT_P1;
13895: sp[0]=n;
13896: NEXT_P2;
13897: @end example
13898: This can be scheduled optimally by the compiler.
13899: 
13900: This division can be turned off with the switch @code{-DCISC_NEXT}. This
13901: switch is on by default on machines that do not profit from scheduling
13902: (e.g., the 80386), in order to preserve registers.
13903: 
13904: @node Direct or Indirect Threaded?, DOES>, Scheduling, Threading
13905: @subsection Direct or Indirect Threaded?
13906: @cindex threading, direct or indirect?
13907: 
13908: @cindex -DDIRECT_THREADED
13909: Both! After packaging the nasty details in macro definitions we
13910: realized that we could switch between direct and indirect threading by
13911: simply setting a compilation flag (@code{-DDIRECT_THREADED}) and
13912: defining a few machine-specific macros for the direct-threading case.
13913: On the Forth level we also offer access words that hide the
13914: differences between the threading methods (@pxref{Threading Words}).
13915: 
13916: Indirect threading is implemented completely machine-independently.
13917: Direct threading needs routines for creating jumps to the executable
13918: code (e.g. to @code{docol} or @code{dodoes}). These routines are inherently
13919: machine-dependent, but they do not amount to many source lines. Therefore,
13920: even porting direct threading to a new machine requires little effort.
13921: 
13922: @cindex --enable-indirect-threaded, configuration flag
13923: @cindex --enable-direct-threaded, configuration flag
13924: The default threading method is machine-dependent. You can enforce a
13925: specific threading method when building Gforth with the configuration
13926: flag @code{--enable-direct-threaded} or
13927: @code{--enable-indirect-threaded}. Note that direct threading is not
13928: supported on all machines.
13929: 
13930: @node DOES>,  , Direct or Indirect Threaded?, Threading
13931: @subsection DOES>
13932: @cindex @code{DOES>} implementation
13933: 
13934: @cindex @code{dodoes} routine
13935: @cindex @code{DOES>}-code
13936: One of the most complex parts of a Forth engine is @code{dodoes}, i.e.,
13937: the chunk of code executed by every word defined by a
13938: @code{CREATE}...@code{DOES>} pair. The main problem here is: How to find
13939: the Forth code to be executed, i.e. the code after the
13940: @code{DOES>} (the @code{DOES>}-code)? There are two solutions:
13941: 
13942: In fig-Forth the code field points directly to the @code{dodoes} and the
13943: @code{DOES>}-code address is stored in the cell after the code address (i.e. at
13944: @code{@i{CFA} cell+}). It may seem that this solution is illegal in
13945: the Forth-79 and all later standards, because in fig-Forth this address
13946: lies in the body (which is illegal in these standards). However, by
13947: making the code field larger for all words this solution becomes legal
13948: again. We use this approach for the indirect threaded version and for
13949: direct threading on some machines. Leaving a cell unused in most words
13950: is a bit wasteful, but on the machines we are targeting this is hardly a
13951: problem. The other reason for having a code field size of two cells is
13952: to avoid having different image files for direct and indirect threaded
13953: systems (direct threaded systems require two-cell code fields on many
13954: machines).
13955: 
13956: @cindex @code{DOES>}-handler
13957: The other approach is that the code field points or jumps to the cell
13958: after @code{DOES>}. In this variant there is a jump to @code{dodoes} at
13959: this address (the @code{DOES>}-handler). @code{dodoes} can then get the
13960: @code{DOES>}-code address by computing the code address, i.e., the address of
13961: the jump to @code{dodoes}, and add the length of that jump field. A variant of
13962: this is to have a call to @code{dodoes} after the @code{DOES>}; then the
13963: return address (which can be found in the return register on RISCs) is
13964: the @code{DOES>}-code address. Since the two cells available in the code field
13965: are used up by the jump to the code address in direct threading on many
13966: architectures, we use this approach for direct threading on these
13967: architectures. We did not want to add another cell to the code field.
13968: 
13969: @node Primitives, Performance, Threading, Engine
13970: @section Primitives
13971: @cindex primitives, implementation
13972: @cindex virtual machine instructions, implementation
13973: 
13974: @menu
13975: * Automatic Generation::        
13976: * TOS Optimization::            
13977: * Produced code::               
13978: @end menu
13979: 
13980: @node Automatic Generation, TOS Optimization, Primitives, Primitives
13981: @subsection Automatic Generation
13982: @cindex primitives, automatic generation
13983: 
13984: @cindex @file{prims2x.fs}
13985: Since the primitives are implemented in a portable language, there is no
13986: longer any need to minimize the number of primitives. On the contrary,
13987: having many primitives has an advantage: speed. In order to reduce the
13988: number of errors in primitives and to make programming them easier, we
13989: provide a tool, the primitive generator (@file{prims2x.fs}), that
13990: automatically generates most (and sometimes all) of the C code for a
13991: primitive from the stack effect notation.  The source for a primitive
13992: has the following form:
13993: 
13994: @cindex primitive source format
13995: @format
13996: @i{Forth-name}  ( @i{stack-effect} )        @i{category}    [@i{pronounc.}]
13997: [@code{""}@i{glossary entry}@code{""}]
13998: @i{C code}
13999: [@code{:}
14000: @i{Forth code}]
14001: @end format
14002: 
14003: The items in brackets are optional. The category and glossary fields
14004: are there for generating the documentation, the Forth code is there
14005: for manual implementations on machines without GNU C. E.g., the source
14006: for the primitive @code{+} is:
14007: @example
14008: +    ( n1 n2 -- n )   core    plus
14009: n = n1+n2;
14010: @end example
14011: 
14012: This looks like a specification, but in fact @code{n = n1+n2} is C
14013: code. Our primitive generation tool extracts a lot of information from
14014: the stack effect notations@footnote{We use a one-stack notation, even
14015: though we have separate data and floating-point stacks; The separate
14016: notation can be generated easily from the unified notation.}: The number
14017: of items popped from and pushed on the stack, their type, and by what
14018: name they are referred to in the C code. It then generates a C code
14019: prelude and postlude for each primitive. The final C code for @code{+}
14020: looks like this:
14021: 
14022: @example
14023: I_plus: /* + ( n1 n2 -- n ) */  /* label, stack effect */
14024: /*  */                          /* documentation */
14025: @{
14026: DEF_CA                          /* definition of variable ca (indirect threading) */
14027: Cell n1;                        /* definitions of variables */
14028: Cell n2;
14029: Cell n;
14030: n1 = (Cell) sp[1];              /* input */
14031: n2 = (Cell) TOS;
14032: sp += 1;                        /* stack adjustment */
14033: NAME("+")                       /* debugging output (with -DDEBUG) */
14034: @{
14035: n = n1+n2;                      /* C code taken from the source */
14036: @}
14037: NEXT_P1;                        /* NEXT part 1 */
14038: TOS = (Cell)n;                  /* output */
14039: NEXT_P2;                        /* NEXT part 2 */
14040: @}
14041: @end example
14042: 
14043: This looks long and inefficient, but the GNU C compiler optimizes quite
14044: well and produces optimal code for @code{+} on, e.g., the R3000 and the
14045: HP RISC machines: Defining the @code{n}s does not produce any code, and
14046: using them as intermediate storage also adds no cost.
14047: 
14048: There are also other optimizations that are not illustrated by this
14049: example: assignments between simple variables are usually for free (copy
14050: propagation). If one of the stack items is not used by the primitive
14051: (e.g.  in @code{drop}), the compiler eliminates the load from the stack
14052: (dead code elimination). On the other hand, there are some things that
14053: the compiler does not do, therefore they are performed by
14054: @file{prims2x.fs}: The compiler does not optimize code away that stores
14055: a stack item to the place where it just came from (e.g., @code{over}).
14056: 
14057: While programming a primitive is usually easy, there are a few cases
14058: where the programmer has to take the actions of the generator into
14059: account, most notably @code{?dup}, but also words that do not (always)
14060: fall through to @code{NEXT}.
14061: 
14062: @node TOS Optimization, Produced code, Automatic Generation, Primitives
14063: @subsection TOS Optimization
14064: @cindex TOS optimization for primitives
14065: @cindex primitives, keeping the TOS in a register
14066: 
14067: An important optimization for stack machine emulators, e.g., Forth
14068: engines, is keeping  one or more of the top stack items in
14069: registers.  If a word has the stack effect @i{in1}...@i{inx} @code{--}
14070: @i{out1}...@i{outy}, keeping the top @i{n} items in registers
14071: @itemize @bullet
14072: @item
14073: is better than keeping @i{n-1} items, if @i{x>=n} and @i{y>=n},
14074: due to fewer loads from and stores to the stack.
14075: @item is slower than keeping @i{n-1} items, if @i{x<>y} and @i{x<n} and
14076: @i{y<n}, due to additional moves between registers.
14077: @end itemize
14078: 
14079: @cindex -DUSE_TOS
14080: @cindex -DUSE_NO_TOS
14081: In particular, keeping one item in a register is never a disadvantage,
14082: if there are enough registers. Keeping two items in registers is a
14083: disadvantage for frequent words like @code{?branch}, constants,
14084: variables, literals and @code{i}. Therefore our generator only produces
14085: code that keeps zero or one items in registers. The generated C code
14086: covers both cases; the selection between these alternatives is made at
14087: C-compile time using the switch @code{-DUSE_TOS}. @code{TOS} in the C
14088: code for @code{+} is just a simple variable name in the one-item case,
14089: otherwise it is a macro that expands into @code{sp[0]}. Note that the
14090: GNU C compiler tries to keep simple variables like @code{TOS} in
14091: registers, and it usually succeeds, if there are enough registers.
14092: 
14093: @cindex -DUSE_FTOS
14094: @cindex -DUSE_NO_FTOS
14095: The primitive generator performs the TOS optimization for the
14096: floating-point stack, too (@code{-DUSE_FTOS}). For floating-point
14097: operations the benefit of this optimization is even larger:
14098: floating-point operations take quite long on most processors, but can be
14099: performed in parallel with other operations as long as their results are
14100: not used. If the FP-TOS is kept in a register, this works. If
14101: it is kept on the stack, i.e., in memory, the store into memory has to
14102: wait for the result of the floating-point operation, lengthening the
14103: execution time of the primitive considerably.
14104: 
14105: The TOS optimization makes the automatic generation of primitives a
14106: bit more complicated. Just replacing all occurrences of @code{sp[0]} by
14107: @code{TOS} is not sufficient. There are some special cases to
14108: consider:
14109: @itemize @bullet
14110: @item In the case of @code{dup ( w -- w w )} the generator must not
14111: eliminate the store to the original location of the item on the stack,
14112: if the TOS optimization is turned on.
14113: @item Primitives with stack effects of the form @code{--}
14114: @i{out1}...@i{outy} must store the TOS to the stack at the start.
14115: Likewise, primitives with the stack effect @i{in1}...@i{inx} @code{--}
14116: must load the TOS from the stack at the end. But for the null stack
14117: effect @code{--} no stores or loads should be generated.
14118: @end itemize
14119: 
14120: @node Produced code,  , TOS Optimization, Primitives
14121: @subsection Produced code
14122: @cindex primitives, assembly code listing
14123: 
14124: @cindex @file{engine.s}
14125: To see what assembly code is produced for the primitives on your machine
14126: with your compiler and your flag settings, type @code{make engine.s} and
14127: look at the resulting file @file{engine.s}.
14128: 
14129: @node  Performance,  , Primitives, Engine
14130: @section Performance
14131: @cindex performance of some Forth interpreters
14132: @cindex engine performance
14133: @cindex benchmarking Forth systems
14134: @cindex Gforth performance
14135: 
14136: On RISCs the Gforth engine is very close to optimal; i.e., it is usually
14137: impossible to write a significantly faster engine.
14138: 
14139: On register-starved machines like the 386 architecture processors
14140: improvements are possible, because @code{gcc} does not utilize the
14141: registers as well as a human, even with explicit register declarations;
14142: e.g., Bernd Beuster wrote a Forth system fragment in assembly language
14143: and hand-tuned it for the 486; this system is 1.19 times faster on the
14144: Sieve benchmark on a 486DX2/66 than Gforth compiled with
14145: @code{gcc-2.6.3} with @code{-DFORCE_REG}.  The situation has improved
14146: with gcc-2.95 and gforth-0.4.9; now the most important virtual machine
14147: registers fit in real registers (and we can even afford to use the TOS
14148: optimization), resulting in a speedup of 1.14 on the sieve over the
14149: earlier results.
14150: 
14151: @cindex Win32Forth performance
14152: @cindex NT Forth performance
14153: @cindex eforth performance
14154: @cindex ThisForth performance
14155: @cindex PFE performance
14156: @cindex TILE performance
14157: The potential advantage of assembly language implementations
14158: is not necessarily realized in complete Forth systems: We compared
14159: Gforth-0.4.9 (direct threaded, compiled with @code{gcc-2.95.1} and
14160: @code{-DFORCE_REG}) with Win32Forth 1.2093, LMI's NT Forth (Beta, May
14161: 1994) and Eforth (with and without peephole (aka pinhole) optimization
14162: of the threaded code); all these systems were written in assembly
14163: language. We also compared Gforth with three systems written in C:
14164: PFE-0.9.14 (compiled with @code{gcc-2.6.3} with the default
14165: configuration for Linux: @code{-O2 -fomit-frame-pointer -DUSE_REGS
14166: -DUNROLL_NEXT}), ThisForth Beta (compiled with @code{gcc-2.6.3 -O3
14167: -fomit-frame-pointer}; ThisForth employs peephole optimization of the
14168: threaded code) and TILE (compiled with @code{make opt}). We benchmarked
14169: Gforth, PFE, ThisForth and TILE on a 486DX2/66 under Linux. Kenneth
14170: O'Heskin kindly provided the results for Win32Forth and NT Forth on a
14171: 486DX2/66 with similar memory performance under Windows NT. Marcel
14172: Hendrix ported Eforth to Linux, then extended it to run the benchmarks,
14173: added the peephole optimizer, ran the benchmarks and reported the
14174: results.
14175: 
14176: We used four small benchmarks: the ubiquitous Sieve; bubble-sorting and
14177: matrix multiplication come from the Stanford integer benchmarks and have
14178: been translated into Forth by Martin Fraeman; we used the versions
14179: included in the TILE Forth package, but with bigger data set sizes; and
14180: a recursive Fibonacci number computation for benchmarking calling
14181: performance. The following table shows the time taken for the benchmarks
14182: scaled by the time taken by Gforth (in other words, it shows the speedup
14183: factor that Gforth achieved over the other systems).
14184: 
14185: @example
14186: relative      Win32-    NT       eforth       This-      
14187:   time  Gforth Forth Forth eforth  +opt   PFE Forth  TILE
14188: sieve     1.00  1.58  1.30   1.58  0.97  1.80  3.63  9.79
14189: bubble    1.00  1.55  1.67   1.75  1.04  1.78        4.59
14190: matmul    1.00  1.67  1.53   1.66  0.84  1.79        4.63
14191: fib       1.00  1.75  1.53   1.40  0.99  1.99  3.43  4.93
14192: @end example
14193: 
14194: You may be quite surprised by the good performance of Gforth when
14195: compared with systems written in assembly language. One important reason
14196: for the disappointing performance of these other systems is probably
14197: that they are not written optimally for the 486 (e.g., they use the
14198: @code{lods} instruction). In addition, Win32Forth uses a comfortable,
14199: but costly method for relocating the Forth image: like @code{cforth}, it
14200: computes the actual addresses at run time, resulting in two address
14201: computations per @code{NEXT} (@pxref{Image File Background}).
14202: 
14203: Only Eforth with the peephole optimizer performs comparable to
14204: Gforth. The speedups achieved with peephole optimization of threaded
14205: code are quite remarkable. Adding a peephole optimizer to Gforth should
14206: cause similar speedups.
14207: 
14208: The speedup of Gforth over PFE, ThisForth and TILE can be easily
14209: explained with the self-imposed restriction of the latter systems to
14210: standard C, which makes efficient threading impossible (however, the
14211: measured implementation of PFE uses a GNU C extension: @pxref{Global Reg
14212: Vars, , Defining Global Register Variables, gcc.info, GNU C Manual}).
14213: Moreover, current C compilers have a hard time optimizing other aspects
14214: of the ThisForth and the TILE source.
14215: 
14216: The performance of Gforth on 386 architecture processors varies widely
14217: with the version of @code{gcc} used. E.g., @code{gcc-2.5.8} failed to
14218: allocate any of the virtual machine registers into real machine
14219: registers by itself and would not work correctly with explicit register
14220: declarations, giving a 1.5 times slower engine (on a 486DX2/66 running
14221: the Sieve) than the one measured above.
14222: 
14223: Note that there have been several releases of Win32Forth since the
14224: release presented here, so the results presented above may have little
14225: predictive value for the performance of Win32Forth today (results for
14226: the current release on an i486DX2/66 are welcome).
14227: 
14228: @cindex @file{Benchres}
14229: In
14230: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl&maierhofer95.ps.gz,
14231: Translating Forth to Efficient C}} by M. Anton Ertl and Martin
14232: Maierhofer (presented at EuroForth '95), an indirect threaded version of
14233: Gforth is compared with Win32Forth, NT Forth, PFE, ThisForth, and
14234: several native code systems; that version of Gforth is slower on a 486
14235: than the direct threaded version used here. You can find a newer version
14236: of these measurements at
14237: @uref{http://www.complang.tuwien.ac.at/forth/performance.html}. You can
14238: find numbers for Gforth on various machines in @file{Benchres}.
14239: 
14240: @c ******************************************************************
14241: @node Binding to System Library, Cross Compiler, Engine, Top
14242: @chapter Binding to System Library
14243: 
14244: @node Cross Compiler, Bugs, Binding to System Library, Top
14245: @chapter Cross Compiler
14246: @cindex @file{cross.fs}
14247: @cindex cross-compiler
14248: @cindex metacompiler
14249: @cindex target compiler
14250: 
14251: The cross compiler is used to bootstrap a Forth kernel. Since Gforth is
14252: mostly written in Forth, including crucial parts like the outer
14253: interpreter and compiler, it needs compiled Forth code to get
14254: started. The cross compiler allows to create new images for other
14255: architectures, even running under another Forth system.
14256: 
14257: @menu
14258: * Using the Cross Compiler::    
14259: * How the Cross Compiler Works::  
14260: @end menu
14261: 
14262: @node Using the Cross Compiler, How the Cross Compiler Works, Cross Compiler, Cross Compiler
14263: @section Using the Cross Compiler
14264: 
14265: The cross compiler uses a language that resembles Forth, but isn't. The
14266: main difference is that you can execute Forth code after definition,
14267: while you usually can't execute the code compiled by cross, because the
14268: code you are compiling is typically for a different computer than the
14269: one you are compiling on.
14270: 
14271: The Makefile is already set up to allow you to create kernels for new
14272: architectures with a simple make command. The generic kernels using the
14273: GCC compiled virtual machine are created in the normal build process
14274: with @code{make}. To create a embedded Gforth executable for e.g. the
14275: 8086 processor (running on a DOS machine), type
14276: 
14277: @example
14278: make kernl-8086.fi
14279: @end example
14280: 
14281: This will use the machine description from the @file{arch/8086}
14282: directory to create a new kernel. A machine file may look like that:
14283: 
14284: @example
14285: \ Parameter for target systems                         06oct92py
14286: 
14287:     4 Constant cell             \ cell size in bytes
14288:     2 Constant cell<<           \ cell shift to bytes
14289:     5 Constant cell>bit         \ cell shift to bits
14290:     8 Constant bits/char        \ bits per character
14291:     8 Constant bits/byte        \ bits per byte [default: 8]
14292:     8 Constant float            \ bytes per float
14293:     8 Constant /maxalign        \ maximum alignment in bytes
14294: false Constant bigendian        \ byte order
14295: ( true=big, false=little )
14296: 
14297: include machpc.fs               \ feature list
14298: @end example
14299: 
14300: This part is obligatory for the cross compiler itself, the feature list
14301: is used by the kernel to conditionally compile some features in and out,
14302: depending on whether the target supports these features.
14303: 
14304: There are some optional features, if you define your own primitives,
14305: have an assembler, or need special, nonstandard preparation to make the
14306: boot process work. @code{asm-include} include an assembler,
14307: @code{prims-include} includes primitives, and @code{>boot} prepares for
14308: booting.
14309: 
14310: @example
14311: : asm-include    ." Include assembler" cr
14312:   s" arch/8086/asm.fs" included ;
14313: 
14314: : prims-include  ." Include primitives" cr
14315:   s" arch/8086/prim.fs" included ;
14316: 
14317: : >boot          ." Prepare booting" cr
14318:   s" ' boot >body into-forth 1+ !" evaluate ;
14319: @end example
14320: 
14321: These words are used as sort of macro during the cross compilation in
14322: the file @file{kernel/main.fs}. Instead of using this macros, it would
14323: be possible --- but more complicated --- to write a new kernel project
14324: file, too.
14325: 
14326: @file{kernel/main.fs} expects the machine description file name on the
14327: stack; the cross compiler itself (@file{cross.fs}) assumes that either
14328: @code{mach-file} leaves a counted string on the stack, or
14329: @code{machine-file} leaves an address, count pair of the filename on the
14330: stack.
14331: 
14332: The feature list is typically controlled using @code{SetValue}, generic
14333: files that are used by several projects can use @code{DefaultValue}
14334: instead. Both functions work like @code{Value}, when the value isn't
14335: defined, but @code{SetValue} works like @code{to} if the value is
14336: defined, and @code{DefaultValue} doesn't set anything, if the value is
14337: defined.
14338: 
14339: @example
14340: \ generic mach file for pc gforth                       03sep97jaw
14341: 
14342: true DefaultValue NIL  \ relocating
14343: 
14344: >ENVIRON
14345: 
14346: true DefaultValue file          \ controls the presence of the
14347:                                 \ file access wordset
14348: true DefaultValue OS            \ flag to indicate a operating system
14349: 
14350: true DefaultValue prims         \ true: primitives are c-code
14351: 
14352: true DefaultValue floating      \ floating point wordset is present
14353: 
14354: true DefaultValue glocals       \ gforth locals are present
14355:                                 \ will be loaded
14356: true DefaultValue dcomps        \ double number comparisons
14357: 
14358: true DefaultValue hash          \ hashing primitives are loaded/present
14359: 
14360: true DefaultValue xconds        \ used together with glocals,
14361:                                 \ special conditionals supporting gforths'
14362:                                 \ local variables
14363: true DefaultValue header        \ save a header information
14364: 
14365: true DefaultValue backtrace     \ enables backtrace code
14366: 
14367: false DefaultValue ec
14368: false DefaultValue crlf
14369: 
14370: cell 2 = [IF] &32 [ELSE] &256 [THEN] KB DefaultValue kernel-size
14371: 
14372: &16 KB          DefaultValue stack-size
14373: &15 KB &512 +   DefaultValue fstack-size
14374: &15 KB          DefaultValue rstack-size
14375: &14 KB &512 +   DefaultValue lstack-size
14376: @end example
14377: 
14378: @node How the Cross Compiler Works,  , Using the Cross Compiler, Cross Compiler
14379: @section How the Cross Compiler Works
14380: 
14381: @node Bugs, Origin, Cross Compiler, Top
14382: @appendix Bugs
14383: @cindex bug reporting
14384: 
14385: Known bugs are described in the file @file{BUGS} in the Gforth distribution.
14386: 
14387: If you find a bug, please send a bug report to
14388: @email{bug-gforth@@gnu.org}. A bug report should include this
14389: information:
14390: 
14391: @itemize @bullet
14392: @item
14393: The Gforth version used (it is announced at the start of an
14394: interactive Gforth session).
14395: @item
14396: The machine and operating system (on Unix
14397: systems @code{uname -a} will report this information).
14398: @item
14399: The installation options (send the file @file{config.status}).
14400: @item
14401: A complete list of changes (if any) you (or your installer) have made to the
14402: Gforth sources.
14403: @item
14404: A program (or a sequence of keyboard commands) that reproduces the bug.
14405: @item
14406: A description of what you think constitutes the buggy behaviour.
14407: @end itemize
14408: 
14409: For a thorough guide on reporting bugs read @ref{Bug Reporting, , How
14410: to Report Bugs, gcc.info, GNU C Manual}.
14411: 
14412: 
14413: @node Origin, Forth-related information, Bugs, Top
14414: @appendix Authors and Ancestors of Gforth
14415: 
14416: @section Authors and Contributors
14417: @cindex authors of Gforth
14418: @cindex contributors to Gforth
14419: 
14420: The Gforth project was started in mid-1992 by Bernd Paysan and Anton
14421: Ertl. The third major author was Jens Wilke.  Lennart Benschop (who was
14422: one of Gforth's first users, in mid-1993) and Stuart Ramsden inspired us
14423: with their continuous feedback. Lennart Benshop contributed
14424: @file{glosgen.fs}, while Stuart Ramsden has been working on automatic
14425: support for calling C libraries. Helpful comments also came from Paul
14426: Kleinrubatscher, Christian Pirker, Dirk Zoller, Marcel Hendrix, John
14427: Wavrik, Barrie Stott, Marc de Groot, Jorge Acerada, Bruce Hoyt, and
14428: Robert Epprecht. Since the release of Gforth-0.2.1 there were also
14429: helpful comments from many others; thank you all, sorry for not listing
14430: you here (but digging through my mailbox to extract your names is on my
14431: to-do list). Since the release of Gforth-0.4.0 Neal Crook worked on the
14432: manual.
14433: 
14434: Gforth also owes a lot to the authors of the tools we used (GCC, CVS,
14435: and autoconf, among others), and to the creators of the Internet: Gforth
14436: was developed across the Internet, and its authors did not meet
14437: physically for the first 4 years of development.
14438: 
14439: @section Pedigree
14440: @cindex pedigree of Gforth
14441: 
14442: Gforth descends from bigFORTH (1993) and fig-Forth. Gforth and PFE (by
14443: Dirk Zoller) will cross-fertilize each other. Of course, a significant
14444: part of the design of Gforth was prescribed by ANS Forth.
14445: 
14446: Bernd Paysan wrote bigFORTH, a descendent from TurboForth, an unreleased
14447: 32 bit native code version of VolksForth for the Atari ST, written
14448: mostly by Dietrich Weineck.
14449: 
14450: VolksForth descends from F83. It was written by Klaus Schleisiek, Bernd
14451: Pennemann, Georg Rehfeld and Dietrich Weineck for the C64 (called
14452: UltraForth there) in the mid-80s and ported to the Atari ST in 1986.
14453: 
14454: Henry Laxen and Mike Perry wrote F83 as a model implementation of the
14455: Forth-83 standard. !! Pedigree? When?
14456: 
14457: A team led by Bill Ragsdale implemented fig-Forth on many processors in
14458: 1979. Robert Selzer and Bill Ragsdale developed the original
14459: implementation of fig-Forth for the 6502 based on microForth.
14460: 
14461: The principal architect of microForth was Dean Sanderson. microForth was
14462: FORTH, Inc.'s first off-the-shelf product. It was developed in 1976 for
14463: the 1802, and subsequently implemented on the 8080, the 6800 and the
14464: Z80.
14465: 
14466: All earlier Forth systems were custom-made, usually by Charles Moore,
14467: who discovered (as he puts it) Forth during the late 60s. The first full
14468: Forth existed in 1971.
14469: 
14470: A part of the information in this section comes from @cite{The Evolution
14471: of Forth} by Elizabeth D. Rather, Donald R. Colburn and Charles
14472: H. Moore, presented at the HOPL-II conference and preprinted in SIGPLAN
14473: Notices 28(3), 1993.  You can find more historical and genealogical
14474: information about Forth there.
14475: 
14476: @node Forth-related information, Word Index, Origin, Top
14477: @appendix Other Forth-related information
14478: @cindex Forth-related information
14479: 
14480: @menu
14481: * Internet resources::          
14482: * Books::                       
14483: * The Forth Interest Group::    
14484: * Conferences::                 
14485: @end menu
14486: 
14487: 
14488: @node Internet resources, Books, Forth-related information, Forth-related information
14489: @section Internet resources
14490: @cindex internet resources
14491: 
14492: @cindex comp.lang.forth
14493: @cindex frequently asked questions
14494: There is an active news group (comp.lang.forth) discussing Forth and
14495: Forth-related issues. A frequently-asked-questions (FAQ) list
14496: is posted to the news group regularly, and archived at these sites:
14497: 
14498: @itemize @bullet
14499: @item
14500: @uref{ftp://rtfm.mit.edu/pub/usenet-by-group/comp.lang.forth/}
14501: @item
14502: @uref{ftp://ftp.forth.org/pub/Forth/FAQ/}
14503: @end itemize
14504: 
14505: The FAQ list should be considered mandatory reading before posting to
14506: the news group.
14507: 
14508: Here are some other web sites holding Forth-related material:
14509: 
14510: @itemize @bullet
14511: @item
14512: @uref{http://www.taygeta.com/forth.html} -- Skip Carter's Forth pages.
14513: @item
14514: @uref{http://www.jwdt.com/~paysan/gforth.html} -- the Gforth home page.
14515: @item
14516: @uref{http://www.minerva.com/uathena.htm} -- home of ANS Forth Standard.
14517: @item
14518: @uref{http://dec.bournemouth.ac.uk/forth/index.html} -- the Forth
14519: Research page, including links to the Journal of Forth Application and
14520: Research (JFAR) and a searchable Forth bibliography.
14521: @end itemize
14522: 
14523: 
14524: @node Books, The Forth Interest Group, Internet resources, Forth-related information
14525: @section Books
14526: @cindex books on Forth
14527: 
14528: As the Standard is relatively new, there are not many books out yet. It
14529: is not recommended to learn Forth by using Gforth and a book that is not
14530: written for ANS Forth, as you will not know your mistakes from the
14531: deviations of the book. However, books based on the Forth-83 standard
14532: should be ok, because ANS Forth is primarily an extension of Forth-83.
14533: Refer to the Forth FAQ for details of Forth-related books.
14534: 
14535: @cindex standard document for ANS Forth
14536: @cindex ANS Forth document
14537: The definite reference if you want to write ANS Forth programs is, of
14538: course, the ANS Forth document. It is available in printed form from the
14539: National Standards Institute Sales Department (Tel.: USA (212) 642-4900;
14540: Fax.: USA (212) 302-1286) as document @cite{X3.215-1994} for about
14541: $200. You can also get it from Global Engineering Documents (Tel.: USA
14542: (800) 854-7179; Fax.: (303) 843-9880) for about $300.
14543: 
14544: @cite{dpANS6}, the last draft of the standard, which was then submitted
14545: to ANSI for publication is available electronically and for free in some
14546: MS Word format, and it has been converted to HTML
14547: (@uref{http://www.taygeta.com/forth/dpans.html}; this HTML version also
14548: includes the answers to Requests for Interpretation (RFIs). Some
14549: pointers to these versions can be found through
14550: @*@uref{http://www.complang.tuwien.ac.at/projects/forth.html}.
14551: 
14552: 
14553: @node The Forth Interest Group, Conferences, Books, Forth-related information
14554: @section The Forth Interest Group
14555: @cindex Forth interest group (FIG)
14556: 
14557: The Forth Interest Group (FIG) is a world-wide, non-profit,
14558: member-supported organisation. It publishes a regular magazine,
14559: @var{FORTH Dimensions}, and offers other benefits of membership. You can
14560: contact the FIG through their office email address:
14561: @email{office@@forth.org} or by visiting their web site at
14562: @uref{http://www.forth.org/}. This web site also includes links to FIG
14563: chapters in other countries and American cities
14564: (@uref{http://www.forth.org/chapters.html}).
14565: 
14566: @node Conferences,  , The Forth Interest Group, Forth-related information
14567: @section Conferences
14568: @cindex Conferences
14569: 
14570: There are several regular conferences related to Forth. They are all
14571: well-publicised in @var{FORTH Dimensions} and on the comp.lang.forth
14572: news group:
14573: 
14574: @itemize @bullet
14575: @item
14576: FORML -- the Forth modification laboratory convenes every year near
14577: Monterey, California.
14578: @item
14579: The Rochester Forth Conference -- an annual conference traditionally
14580: held in Rochester, New York.
14581: @item
14582: EuroForth -- this European conference takes place annually.
14583: @end itemize
14584: 
14585: 
14586: @node Word Index, Name Index, Forth-related information, Top
14587: @unnumbered Word Index
14588: 
14589: This index is a list of Forth words that have ``glossary'' entries
14590: within this manual. Each word is listed with its stack effect and
14591: wordset.
14592: 
14593: @printindex fn
14594: 
14595: @node Name Index, Concept Index, Word Index, Top
14596: @unnumbered Name Index
14597: 
14598: This index is a list of Forth words that have ``glossary'' entries
14599: within this manual.
14600: 
14601: @printindex ky
14602: 
14603: @node Concept Index,  , Name Index, Top
14604: @unnumbered Concept and Word Index
14605: 
14606: Not all entries listed in this index are present verbatim in the
14607: text. This index also duplicates, in abbreviated form, all of the words
14608: listed in the Word Index (only the names are listed for the words here).
14609: 
14610: @printindex cp
14611: 
14612: @contents
14613: @bye
14614: 

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