File:  [gforth] / gforth / doc / gforth.ds
Revision 1.202: download - view: text, annotated - select for diffs
Thu Dec 25 21:20:31 2008 UTC (15 years, 3 months ago) by anton
Branches: MAIN
CVS tags: HEAD
improved documentation of C-LIBRARY

    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: @c
   15: @c Karl Berry writes:
   16: @c  If they don't like the all-caps for @var Info output, all I can say is
   17: @c  that it's always been that way, and the usage of all-caps for
   18: @c  metavariables has a long tradition.  I think it's best to just let it be
   19: @c  what it is, for the sake of consistency among manuals.
   20: @c
   21: @comment .. would be useful to have a word that identified all deferred words
   22: @comment should semantics stuff in intro be moved to another section
   23: 
   24: @c POSTPONE, COMPILE, [COMPILE], LITERAL should have their own section
   25: 
   26: @comment %**start of header (This is for running Texinfo on a region.)
   27: @setfilename gforth.info
   28: @include version.texi
   29: @settitle Gforth Manual
   30: @c @syncodeindex pg cp
   31: 
   32: @macro progstyle {}
   33: Programming style note:
   34: @end macro
   35: 
   36: @macro assignment {}
   37: @table @i
   38: @item Assignment:
   39: @end macro
   40: @macro endassignment {}
   41: @end table
   42: @end macro
   43: 
   44: @comment macros for beautifying glossary entries
   45: @macro GLOSS-START {}
   46: @iftex
   47: @ninerm
   48: @end iftex
   49: @end macro
   50: 
   51: @macro GLOSS-END {}
   52: @iftex
   53: @rm
   54: @end iftex
   55: @end macro
   56: 
   57: @comment %**end of header (This is for running Texinfo on a region.)
   58: @copying
   59: This manual is for Gforth (version @value{VERSION}, @value{UPDATED}),
   60: a fast and portable implementation of the ANS Forth language.  It
   61: serves as reference manual, but it also contains an introduction to
   62: Forth and a Forth tutorial.
   63: 
   64: Copyright @copyright{} 1995, 1996, 1997, 1998, 2000, 2003, 2004,2005,2006,2007,2008 Free Software Foundation, Inc.
   65: 
   66: @quotation
   67: Permission is granted to copy, distribute and/or modify this document
   68: under the terms of the GNU Free Documentation License, Version 1.1 or
   69: any later version published by the Free Software Foundation; with no
   70: Invariant Sections, with the Front-Cover texts being ``A GNU Manual,''
   71: and with the Back-Cover Texts as in (a) below.  A copy of the
   72: license is included in the section entitled ``GNU Free Documentation
   73: License.''
   74: 
   75: (a) The FSF's Back-Cover Text is: ``You have freedom to copy and modify
   76: this GNU Manual, like GNU software.  Copies published by the Free
   77: Software Foundation raise funds for GNU development.''
   78: @end quotation
   79: @end copying
   80: 
   81: @dircategory Software development
   82: @direntry
   83: * Gforth: (gforth).             A fast interpreter for the Forth language.
   84: @end direntry
   85: @c The Texinfo manual also recommends doing this, but for Gforth it may
   86: @c  not make much sense
   87: @c @dircategory Individual utilities
   88: @c @direntry
   89: @c * Gforth: (gforth)Invoking Gforth.      gforth, gforth-fast, gforthmi
   90: @c @end direntry
   91: 
   92: @titlepage
   93: @title Gforth
   94: @subtitle for version @value{VERSION}, @value{UPDATED}
   95: @author Neal Crook
   96: @author Anton Ertl
   97: @author David Kuehling
   98: @author Bernd Paysan
   99: @author Jens Wilke
  100: @page
  101: @vskip 0pt plus 1filll
  102: @insertcopying
  103: @end titlepage
  104: 
  105: @contents
  106: 
  107: @ifnottex
  108: @node Top, Goals, (dir), (dir)
  109: @top Gforth
  110: 
  111: @insertcopying
  112: @end ifnottex
  113: 
  114: @menu
  115: * Goals::                       About the Gforth Project
  116: * Gforth Environment::          Starting (and exiting) Gforth
  117: * Tutorial::                    Hands-on Forth Tutorial
  118: * Introduction::                An introduction to ANS Forth
  119: * Words::                       Forth words available in Gforth
  120: * Error messages::              How to interpret them
  121: * Tools::                       Programming tools
  122: * ANS conformance::             Implementation-defined options etc.
  123: * Standard vs Extensions::      Should I use extensions?
  124: * Model::                       The abstract machine of Gforth
  125: * Integrating Gforth::          Forth as scripting language for applications
  126: * Emacs and Gforth::            The Gforth Mode
  127: * Image Files::                 @code{.fi} files contain compiled code
  128: * Engine::                      The inner interpreter and the primitives
  129: * Cross Compiler::              The Cross Compiler
  130: * Bugs::                        How to report them
  131: * Origin::                      Authors and ancestors of Gforth
  132: * Forth-related information::   Books and places to look on the WWW
  133: * Licenses::                    
  134: * Word Index::                  An item for each Forth word
  135: * Concept Index::               A menu covering many topics
  136: 
  137: @detailmenu
  138:  --- The Detailed Node Listing ---
  139: 
  140: Gforth Environment
  141: 
  142: * Invoking Gforth::             Getting in
  143: * Leaving Gforth::              Getting out
  144: * Command-line editing::        
  145: * Environment variables::       that affect how Gforth starts up
  146: * Gforth Files::                What gets installed and where
  147: * Gforth in pipes::             
  148: * Startup speed::               When 35ms is not fast enough ...
  149: 
  150: Forth Tutorial
  151: 
  152: * Starting Gforth Tutorial::    
  153: * Syntax Tutorial::             
  154: * Crash Course Tutorial::       
  155: * Stack Tutorial::              
  156: * Arithmetics Tutorial::        
  157: * Stack Manipulation Tutorial::  
  158: * Using files for Forth code Tutorial::  
  159: * Comments Tutorial::           
  160: * Colon Definitions Tutorial::  
  161: * Decompilation Tutorial::      
  162: * Stack-Effect Comments Tutorial::  
  163: * Types Tutorial::              
  164: * Factoring Tutorial::          
  165: * Designing the stack effect Tutorial::  
  166: * Local Variables Tutorial::    
  167: * Conditional execution Tutorial::  
  168: * Flags and Comparisons Tutorial::  
  169: * General Loops Tutorial::      
  170: * Counted loops Tutorial::      
  171: * Recursion Tutorial::          
  172: * Leaving definitions or loops Tutorial::  
  173: * Return Stack Tutorial::       
  174: * Memory Tutorial::             
  175: * Characters and Strings Tutorial::  
  176: * Alignment Tutorial::          
  177: * Floating Point Tutorial::     
  178: * Files Tutorial::              
  179: * Interpretation and Compilation Semantics and Immediacy Tutorial::  
  180: * Execution Tokens Tutorial::   
  181: * Exceptions Tutorial::         
  182: * Defining Words Tutorial::     
  183: * Arrays and Records Tutorial::  
  184: * POSTPONE Tutorial::           
  185: * Literal Tutorial::            
  186: * Advanced macros Tutorial::    
  187: * Compilation Tokens Tutorial::  
  188: * Wordlists and Search Order Tutorial::  
  189: 
  190: An Introduction to ANS Forth
  191: 
  192: * Introducing the Text Interpreter::  
  193: * Stacks and Postfix notation::  
  194: * Your first definition::       
  195: * How does that work?::         
  196: * Forth is written in Forth::   
  197: * Review - elements of a Forth system::  
  198: * Where to go next::            
  199: * Exercises::                   
  200: 
  201: Forth Words
  202: 
  203: * Notation::                    
  204: * Case insensitivity::          
  205: * Comments::                    
  206: * Boolean Flags::               
  207: * Arithmetic::                  
  208: * Stack Manipulation::          
  209: * Memory::                      
  210: * Control Structures::          
  211: * Defining Words::              
  212: * Interpretation and Compilation Semantics::  
  213: * Tokens for Words::            
  214: * Compiling words::             
  215: * The Text Interpreter::        
  216: * The Input Stream::            
  217: * Word Lists::                  
  218: * Environmental Queries::       
  219: * Files::                       
  220: * Blocks::                      
  221: * Other I/O::                   
  222: * OS command line arguments::   
  223: * Locals::                      
  224: * Structures::                  
  225: * Object-oriented Forth::       
  226: * Programming Tools::           
  227: * C Interface::                 
  228: * Assembler and Code Words::    
  229: * Threading Words::             
  230: * Passing Commands to the OS::  
  231: * Keeping track of Time::       
  232: * Miscellaneous Words::         
  233: 
  234: Arithmetic
  235: 
  236: * Single precision::            
  237: * Double precision::            Double-cell integer arithmetic
  238: * Bitwise operations::          
  239: * Numeric comparison::          
  240: * Mixed precision::             Operations with single and double-cell integers
  241: * Floating Point::              
  242: 
  243: Stack Manipulation
  244: 
  245: * Data stack::                  
  246: * Floating point stack::        
  247: * Return stack::                
  248: * Locals stack::                
  249: * Stack pointer manipulation::  
  250: 
  251: Memory
  252: 
  253: * Memory model::                
  254: * Dictionary allocation::       
  255: * Heap Allocation::             
  256: * Memory Access::               
  257: * Address arithmetic::          
  258: * Memory Blocks::               
  259: 
  260: Control Structures
  261: 
  262: * Selection::                   IF ... ELSE ... ENDIF
  263: * Simple Loops::                BEGIN ...
  264: * Counted Loops::               DO
  265: * Arbitrary control structures::  
  266: * Calls and returns::           
  267: * Exception Handling::          
  268: 
  269: Defining Words
  270: 
  271: * CREATE::                      
  272: * Variables::                   Variables and user variables
  273: * Constants::                   
  274: * Values::                      Initialised variables
  275: * Colon Definitions::           
  276: * Anonymous Definitions::       Definitions without names
  277: * Supplying names::             Passing definition names as strings
  278: * User-defined Defining Words::  
  279: * Deferred Words::              Allow forward references
  280: * Aliases::                     
  281: 
  282: User-defined Defining Words
  283: 
  284: * CREATE..DOES> applications::  
  285: * CREATE..DOES> details::       
  286: * Advanced does> usage example::  
  287: * Const-does>::                 
  288: 
  289: Interpretation and Compilation Semantics
  290: 
  291: * Combined words::              
  292: 
  293: Tokens for Words
  294: 
  295: * Execution token::             represents execution/interpretation semantics
  296: * Compilation token::           represents compilation semantics
  297: * Name token::                  represents named words
  298: 
  299: Compiling words
  300: 
  301: * Literals::                    Compiling data values
  302: * Macros::                      Compiling words
  303: 
  304: The Text Interpreter
  305: 
  306: * Input Sources::               
  307: * Number Conversion::           
  308: * Interpret/Compile states::    
  309: * Interpreter Directives::      
  310: 
  311: Word Lists
  312: 
  313: * Vocabularies::                
  314: * Why use word lists?::         
  315: * Word list example::           
  316: 
  317: Files
  318: 
  319: * Forth source files::          
  320: * General files::               
  321: * Redirection::                 
  322: * Search Paths::                
  323: 
  324: Search Paths
  325: 
  326: * Source Search Paths::         
  327: * General Search Paths::        
  328: 
  329: Other I/O
  330: 
  331: * Simple numeric output::       Predefined formats
  332: * Formatted numeric output::    Formatted (pictured) output
  333: * String Formats::              How Forth stores strings in memory
  334: * Displaying characters and strings::  Other stuff
  335: * Terminal output::             Cursor positioning etc.
  336: * Single-key input::            
  337: * Line input and conversion::   
  338: * Pipes::                       How to create your own pipes
  339: * Xchars and Unicode::          Non-ASCII characters
  340: 
  341: Locals
  342: 
  343: * Gforth locals::               
  344: * ANS Forth locals::            
  345: 
  346: Gforth locals
  347: 
  348: * Where are locals visible by name?::  
  349: * How long do locals live?::    
  350: * Locals programming style::    
  351: * Locals implementation::       
  352: 
  353: Structures
  354: 
  355: * Why explicit structure support?::  
  356: * Structure Usage::             
  357: * Structure Naming Convention::  
  358: * Structure Implementation::    
  359: * Structure Glossary::          
  360: * Forth200x Structures::        
  361: 
  362: Object-oriented Forth
  363: 
  364: * Why object-oriented programming?::  
  365: * Object-Oriented Terminology::  
  366: * Objects::                     
  367: * OOF::                         
  368: * Mini-OOF::                    
  369: * Comparison with other object models::  
  370: 
  371: The @file{objects.fs} model
  372: 
  373: * Properties of the Objects model::  
  374: * Basic Objects Usage::         
  375: * The Objects base class::      
  376: * Creating objects::            
  377: * Object-Oriented Programming Style::  
  378: * Class Binding::               
  379: * Method conveniences::         
  380: * Classes and Scoping::         
  381: * Dividing classes::            
  382: * Object Interfaces::           
  383: * Objects Implementation::      
  384: * Objects Glossary::            
  385: 
  386: The @file{oof.fs} model
  387: 
  388: * Properties of the OOF model::  
  389: * Basic OOF Usage::             
  390: * The OOF base class::          
  391: * Class Declaration::           
  392: * Class Implementation::        
  393: 
  394: The @file{mini-oof.fs} model
  395: 
  396: * Basic Mini-OOF Usage::        
  397: * Mini-OOF Example::            
  398: * Mini-OOF Implementation::     
  399: 
  400: Programming Tools
  401: 
  402: * Examining::                   Data and Code.
  403: * Forgetting words::            Usually before reloading.
  404: * Debugging::                   Simple and quick.
  405: * Assertions::                  Making your programs self-checking.
  406: * Singlestep Debugger::         Executing your program word by word.
  407: 
  408: C Interface
  409: 
  410: * Calling C Functions::         
  411: * Declaring C Functions::       
  412: * Calling C function pointers::  
  413: * Defining library interfaces::  
  414: * Declaring OS-level libraries::  
  415: * Callbacks::                   
  416: * C interface internals::       
  417: * Low-Level C Interface Words::  
  418: 
  419: Assembler and Code Words
  420: 
  421: * Code and ;code::              
  422: * Common Assembler::            Assembler Syntax
  423: * Common Disassembler::         
  424: * 386 Assembler::               Deviations and special cases
  425: * Alpha Assembler::             Deviations and special cases
  426: * MIPS assembler::              Deviations and special cases
  427: * PowerPC assembler::           Deviations and special cases
  428: * ARM Assembler::               Deviations and special cases
  429: * Other assemblers::            How to write them
  430: 
  431: Tools
  432: 
  433: * ANS Report::                  Report the words used, sorted by wordset.
  434: * Stack depth changes::         Where does this stack item come from?
  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: Emacs and Gforth
  505: 
  506: * Installing gforth.el::        Making Emacs aware of Forth.
  507: * Emacs Tags::                  Viewing the source of a word in Emacs.
  508: * Hilighting::                  Making Forth code look prettier.
  509: * Auto-Indentation::            Customizing auto-indentation.
  510: * Blocks Files::                Reading and writing blocks files.
  511: 
  512: Image Files
  513: 
  514: * Image Licensing Issues::      Distribution terms for images.
  515: * Image File Background::       Why have image files?
  516: * Non-Relocatable Image Files::  don't always work.
  517: * Data-Relocatable Image Files::  are better.
  518: * Fully Relocatable Image Files::  better yet.
  519: * Stack and Dictionary Sizes::  Setting the default sizes for an image.
  520: * Running Image Files::         @code{gforth -i @i{file}} or @i{file}.
  521: * Modifying the Startup Sequence::  and turnkey applications.
  522: 
  523: Fully Relocatable Image Files
  524: 
  525: * gforthmi::                    The normal way
  526: * cross.fs::                    The hard way
  527: 
  528: Engine
  529: 
  530: * Portability::                 
  531: * Threading::                   
  532: * Primitives::                  
  533: * Performance::                 
  534: 
  535: Threading
  536: 
  537: * Scheduling::                  
  538: * Direct or Indirect Threaded?::  
  539: * Dynamic Superinstructions::   
  540: * DOES>::                       
  541: 
  542: Primitives
  543: 
  544: * Automatic Generation::        
  545: * TOS Optimization::            
  546: * Produced code::               
  547: 
  548: Cross Compiler
  549: 
  550: * Using the Cross Compiler::    
  551: * How the Cross Compiler Works::  
  552: 
  553: Licenses
  554: 
  555: * GNU Free Documentation License::  License for copying this manual.
  556: * Copying::                     GPL (for copying this software).
  557: 
  558: @end detailmenu
  559: @end menu
  560: 
  561: @c ----------------------------------------------------------
  562: @iftex
  563: @unnumbered Preface
  564: @cindex Preface
  565: This manual documents Gforth. Some introductory material is provided for
  566: readers who are unfamiliar with Forth or who are migrating to Gforth
  567: from other Forth compilers. However, this manual is primarily a
  568: reference manual.
  569: @end iftex
  570: 
  571: @comment TODO much more blurb here.
  572: 
  573: @c ******************************************************************
  574: @node Goals, Gforth Environment, Top, Top
  575: @comment node-name,     next,           previous, up
  576: @chapter Goals of Gforth
  577: @cindex goals of the Gforth project
  578: The goal of the Gforth Project is to develop a standard model for
  579: ANS Forth. This can be split into several subgoals:
  580: 
  581: @itemize @bullet
  582: @item
  583: Gforth should conform to the ANS Forth Standard.
  584: @item
  585: It should be a model, i.e. it should define all the
  586: implementation-dependent things.
  587: @item
  588: It should become standard, i.e. widely accepted and used. This goal
  589: is the most difficult one.
  590: @end itemize
  591: 
  592: To achieve these goals Gforth should be
  593: @itemize @bullet
  594: @item
  595: Similar to previous models (fig-Forth, F83)
  596: @item
  597: Powerful. It should provide for all the things that are considered
  598: necessary today and even some that are not yet considered necessary.
  599: @item
  600: Efficient. It should not get the reputation of being exceptionally
  601: slow.
  602: @item
  603: Free.
  604: @item
  605: Available on many machines/easy to port.
  606: @end itemize
  607: 
  608: Have we achieved these goals? Gforth conforms to the ANS Forth
  609: standard. It may be considered a model, but we have not yet documented
  610: which parts of the model are stable and which parts we are likely to
  611: change. It certainly has not yet become a de facto standard, but it
  612: appears to be quite popular. It has some similarities to and some
  613: differences from previous models. It has some powerful features, but not
  614: yet everything that we envisioned. We certainly have achieved our
  615: execution speed goals (@pxref{Performance})@footnote{However, in 1998
  616: the bar was raised when the major commercial Forth vendors switched to
  617: native code compilers.}.  It is free and available on many machines.
  618: 
  619: @c ******************************************************************
  620: @node Gforth Environment, Tutorial, Goals, Top
  621: @chapter Gforth Environment
  622: @cindex Gforth environment
  623: 
  624: Note: ultimately, the Gforth man page will be auto-generated from the
  625: material in this chapter.
  626: 
  627: @menu
  628: * Invoking Gforth::             Getting in
  629: * Leaving Gforth::              Getting out
  630: * Command-line editing::        
  631: * Environment variables::       that affect how Gforth starts up
  632: * Gforth Files::                What gets installed and where
  633: * Gforth in pipes::             
  634: * Startup speed::               When 35ms is not fast enough ...
  635: @end menu
  636: 
  637: For related information about the creation of images see @ref{Image Files}.
  638: 
  639: @comment ----------------------------------------------
  640: @node Invoking Gforth, Leaving Gforth, Gforth Environment, Gforth Environment
  641: @section Invoking Gforth
  642: @cindex invoking Gforth
  643: @cindex running Gforth
  644: @cindex command-line options
  645: @cindex options on the command line
  646: @cindex flags on the command line
  647: 
  648: Gforth is made up of two parts; an executable ``engine'' (named
  649: @command{gforth} or @command{gforth-fast}) and an image file. To start it, you
  650: will usually just say @code{gforth} -- this automatically loads the
  651: default image file @file{gforth.fi}. In many other cases the default
  652: Gforth image will be invoked like this:
  653: @example
  654: gforth [file | -e forth-code] ...
  655: @end example
  656: @noindent
  657: This interprets the contents of the files and the Forth code in the order they
  658: are given.
  659: 
  660: In addition to the @command{gforth} engine, there is also an engine
  661: called @command{gforth-fast}, which is faster, but gives less
  662: informative error messages (@pxref{Error messages}) and may catch some
  663: errors (in particular, stack underflows and integer division errors)
  664: later or not at all.  You should use it for debugged,
  665: performance-critical programs.
  666: 
  667: Moreover, there is an engine called @command{gforth-itc}, which is
  668: useful in some backwards-compatibility situations (@pxref{Direct or
  669: Indirect Threaded?}).
  670: 
  671: In general, the command line looks like this:
  672: 
  673: @example
  674: gforth[-fast] [engine options] [image options]
  675: @end example
  676: 
  677: The engine options must come before the rest of the command
  678: line. They are:
  679: 
  680: @table @code
  681: @cindex -i, command-line option
  682: @cindex --image-file, command-line option
  683: @item --image-file @i{file}
  684: @itemx -i @i{file}
  685: Loads the Forth image @i{file} instead of the default
  686: @file{gforth.fi} (@pxref{Image Files}).
  687: 
  688: @cindex --appl-image, command-line option
  689: @item --appl-image @i{file}
  690: Loads the image @i{file} and leaves all further command-line arguments
  691: to the image (instead of processing them as engine options).  This is
  692: useful for building executable application images on Unix, built with
  693: @code{gforthmi --application ...}.
  694: 
  695: @cindex --path, command-line option
  696: @cindex -p, command-line option
  697: @item --path @i{path}
  698: @itemx -p @i{path}
  699: Uses @i{path} for searching the image file and Forth source code files
  700: instead of the default in the environment variable @code{GFORTHPATH} or
  701: the path specified at installation time (e.g.,
  702: @file{/usr/local/share/gforth/0.2.0:.}). A path is given as a list of
  703: directories, separated by @samp{:} (on Unix) or @samp{;} (on other OSs).
  704: 
  705: @cindex --dictionary-size, command-line option
  706: @cindex -m, command-line option
  707: @cindex @i{size} parameters for command-line options
  708: @cindex size of the dictionary and the stacks
  709: @item --dictionary-size @i{size}
  710: @itemx -m @i{size}
  711: Allocate @i{size} space for the Forth dictionary space instead of
  712: using the default specified in the image (typically 256K). The
  713: @i{size} specification for this and subsequent options consists of
  714: an integer and a unit (e.g.,
  715: @code{4M}). The unit can be one of @code{b} (bytes), @code{e} (element
  716: size, in this case Cells), @code{k} (kilobytes), @code{M} (Megabytes),
  717: @code{G} (Gigabytes), and @code{T} (Terabytes). If no unit is specified,
  718: @code{e} is used.
  719: 
  720: @cindex --data-stack-size, command-line option
  721: @cindex -d, command-line option
  722: @item --data-stack-size @i{size}
  723: @itemx -d @i{size}
  724: Allocate @i{size} space for the data stack instead of using the
  725: default specified in the image (typically 16K).
  726: 
  727: @cindex --return-stack-size, command-line option
  728: @cindex -r, command-line option
  729: @item --return-stack-size @i{size}
  730: @itemx -r @i{size}
  731: Allocate @i{size} space for the return stack instead of using the
  732: default specified in the image (typically 15K).
  733: 
  734: @cindex --fp-stack-size, command-line option
  735: @cindex -f, command-line option
  736: @item --fp-stack-size @i{size}
  737: @itemx -f @i{size}
  738: Allocate @i{size} space for the floating point stack instead of
  739: using the default specified in the image (typically 15.5K). In this case
  740: the unit specifier @code{e} refers to floating point numbers.
  741: 
  742: @cindex --locals-stack-size, command-line option
  743: @cindex -l, command-line option
  744: @item --locals-stack-size @i{size}
  745: @itemx -l @i{size}
  746: Allocate @i{size} space for the locals stack instead of using the
  747: default specified in the image (typically 14.5K).
  748: 
  749: @cindex --vm-commit, command-line option
  750: @cindex overcommit memory for dictionary and stacks
  751: @cindex memory overcommit for dictionary and stacks
  752: @item --vm-commit
  753: Normally, Gforth tries to start up even if there is not enough virtual
  754: memory for the dictionary and the stacks (using @code{MAP_NORESERVE}
  755: on OSs that support it); so you can ask for a really big dictionary
  756: and/or stacks, and as long as you don't use more virtual memory than
  757: is available, everything will be fine (but if you use more, processes
  758: get killed).  With this option you just use the default allocation
  759: policy of the OS; for OSs that don't overcommit (e.g., Solaris), this
  760: means that you cannot and should not ask for as big dictionary and
  761: stacks, but once Gforth successfully starts up, out-of-memory won't
  762: kill it.
  763: 
  764: @cindex -h, command-line option
  765: @cindex --help, command-line option
  766: @item --help
  767: @itemx -h
  768: Print a message about the command-line options
  769: 
  770: @cindex -v, command-line option
  771: @cindex --version, command-line option
  772: @item --version
  773: @itemx -v
  774: Print version and exit
  775: 
  776: @cindex --debug, command-line option
  777: @item --debug
  778: Print some information useful for debugging on startup.
  779: 
  780: @cindex --offset-image, command-line option
  781: @item --offset-image
  782: Start the dictionary at a slightly different position than would be used
  783: otherwise (useful for creating data-relocatable images,
  784: @pxref{Data-Relocatable Image Files}).
  785: 
  786: @cindex --no-offset-im, command-line option
  787: @item --no-offset-im
  788: Start the dictionary at the normal position.
  789: 
  790: @cindex --clear-dictionary, command-line option
  791: @item --clear-dictionary
  792: Initialize all bytes in the dictionary to 0 before loading the image
  793: (@pxref{Data-Relocatable Image Files}).
  794: 
  795: @cindex --die-on-signal, command-line-option
  796: @item --die-on-signal
  797: Normally Gforth handles most signals (e.g., the user interrupt SIGINT,
  798: or the segmentation violation SIGSEGV) by translating it into a Forth
  799: @code{THROW}. With this option, Gforth exits if it receives such a
  800: signal. This option is useful when the engine and/or the image might be
  801: severely broken (such that it causes another signal before recovering
  802: from the first); this option avoids endless loops in such cases.
  803: 
  804: @cindex --no-dynamic, command-line option
  805: @cindex --dynamic, command-line option
  806: @item --no-dynamic
  807: @item --dynamic
  808: Disable or enable dynamic superinstructions with replication
  809: (@pxref{Dynamic Superinstructions}).
  810: 
  811: @cindex --no-super, command-line option
  812: @item --no-super
  813: Disable dynamic superinstructions, use just dynamic replication; this is
  814: useful if you want to patch threaded code (@pxref{Dynamic
  815: Superinstructions}).
  816: 
  817: @cindex --ss-number, command-line option
  818: @item --ss-number=@var{N}
  819: Use only the first @var{N} static superinstructions compiled into the
  820: engine (default: use them all; note that only @code{gforth-fast} has
  821: any).  This option is useful for measuring the performance impact of
  822: static superinstructions.
  823: 
  824: @cindex --ss-min-..., command-line options
  825: @item --ss-min-codesize
  826: @item --ss-min-ls
  827: @item --ss-min-lsu
  828: @item --ss-min-nexts
  829: Use specified metric for determining the cost of a primitive or static
  830: superinstruction for static superinstruction selection.  @code{Codesize}
  831: is the native code size of the primive or static superinstruction,
  832: @code{ls} is the number of loads and stores, @code{lsu} is the number of
  833: loads, stores, and updates, and @code{nexts} is the number of dispatches
  834: (not taking dynamic superinstructions into account), i.e. every
  835: primitive or static superinstruction has cost 1. Default:
  836: @code{codesize} if you use dynamic code generation, otherwise
  837: @code{nexts}.
  838: 
  839: @cindex --ss-greedy, command-line option
  840: @item --ss-greedy
  841: This option is useful for measuring the performance impact of static
  842: superinstructions.  By default, an optimal shortest-path algorithm is
  843: used for selecting static superinstructions.  With @option{--ss-greedy}
  844: this algorithm is modified to assume that anything after the static
  845: superinstruction currently under consideration is not combined into
  846: static superinstructions.  With @option{--ss-min-nexts} this produces
  847: the same result as a greedy algorithm that always selects the longest
  848: superinstruction available at the moment.  E.g., if there are
  849: superinstructions AB and BCD, then for the sequence A B C D the optimal
  850: algorithm will select A BCD and the greedy algorithm will select AB C D.
  851: 
  852: @cindex --print-metrics, command-line option
  853: @item --print-metrics
  854: Prints some metrics used during static superinstruction selection:
  855: @code{code size} is the actual size of the dynamically generated code.
  856: @code{Metric codesize} is the sum of the codesize metrics as seen by
  857: static superinstruction selection; there is a difference from @code{code
  858: size}, because not all primitives and static superinstructions are
  859: compiled into dynamically generated code, and because of markers.  The
  860: other metrics correspond to the @option{ss-min-...} options.  This
  861: option is useful for evaluating the effects of the @option{--ss-...}
  862: options.
  863: 
  864: @end table
  865: 
  866: @cindex loading files at startup
  867: @cindex executing code on startup
  868: @cindex batch processing with Gforth
  869: As explained above, the image-specific command-line arguments for the
  870: default image @file{gforth.fi} consist of a sequence of filenames and
  871: @code{-e @var{forth-code}} options that are interpreted in the sequence
  872: in which they are given. The @code{-e @var{forth-code}} or
  873: @code{--evaluate @var{forth-code}} option evaluates the Forth code. This
  874: option takes only one argument; if you want to evaluate more Forth
  875: words, you have to quote them or use @code{-e} several times. To exit
  876: after processing the command line (instead of entering interactive mode)
  877: append @code{-e bye} to the command line.  You can also process the
  878: command-line arguments with a Forth program (@pxref{OS command line
  879: arguments}).
  880: 
  881: @cindex versions, invoking other versions of Gforth
  882: If you have several versions of Gforth installed, @code{gforth} will
  883: invoke the version that was installed last. @code{gforth-@i{version}}
  884: invokes a specific version. If your environment contains the variable
  885: @code{GFORTHPATH}, you may want to override it by using the
  886: @code{--path} option.
  887: 
  888: Not yet implemented:
  889: On startup the system first executes the system initialization file
  890: (unless the option @code{--no-init-file} is given; note that the system
  891: resulting from using this option may not be ANS Forth conformant). Then
  892: the user initialization file @file{.gforth.fs} is executed, unless the
  893: option @code{--no-rc} is given; this file is searched for in @file{.},
  894: then in @file{~}, then in the normal path (see above).
  895: 
  896: 
  897: 
  898: @comment ----------------------------------------------
  899: @node Leaving Gforth, Command-line editing, Invoking Gforth, Gforth Environment
  900: @section Leaving Gforth
  901: @cindex Gforth - leaving
  902: @cindex leaving Gforth
  903: 
  904: You can leave Gforth by typing @code{bye} or @kbd{Ctrl-d} (at the start
  905: of a line) or (if you invoked Gforth with the @code{--die-on-signal}
  906: option) @kbd{Ctrl-c}. When you leave Gforth, all of your definitions and
  907: data are discarded.  For ways of saving the state of the system before
  908: leaving Gforth see @ref{Image Files}.
  909: 
  910: doc-bye
  911: 
  912: 
  913: @comment ----------------------------------------------
  914: @node Command-line editing, Environment variables, Leaving Gforth, Gforth Environment
  915: @section Command-line editing
  916: @cindex command-line editing
  917: 
  918: Gforth maintains a history file that records every line that you type to
  919: the text interpreter. This file is preserved between sessions, and is
  920: used to provide a command-line recall facility; if you type @kbd{Ctrl-P}
  921: repeatedly you can recall successively older commands from this (or
  922: previous) session(s). The full list of command-line editing facilities is:
  923: 
  924: @itemize @bullet
  925: @item
  926: @kbd{Ctrl-p} (``previous'') (or up-arrow) to recall successively older
  927: commands from the history buffer.
  928: @item
  929: @kbd{Ctrl-n} (``next'') (or down-arrow) to recall successively newer commands
  930: from the history buffer.
  931: @item
  932: @kbd{Ctrl-f} (or right-arrow) to move the cursor right, non-destructively.
  933: @item
  934: @kbd{Ctrl-b} (or left-arrow) to move the cursor left, non-destructively.
  935: @item
  936: @kbd{Ctrl-h} (backspace) to delete the character to the left of the cursor,
  937: closing up the line.
  938: @item
  939: @kbd{Ctrl-k} to delete (``kill'') from the cursor to the end of the line.
  940: @item
  941: @kbd{Ctrl-a} to move the cursor to the start of the line.
  942: @item
  943: @kbd{Ctrl-e} to move the cursor to the end of the line.
  944: @item
  945: @key{RET} (@kbd{Ctrl-m}) or @key{LFD} (@kbd{Ctrl-j}) to submit the current
  946: line.
  947: @item
  948: @key{TAB} to step through all possible full-word completions of the word
  949: currently being typed.
  950: @item
  951: @kbd{Ctrl-d} on an empty line line to terminate Gforth (gracefully,
  952: using @code{bye}). 
  953: @item
  954: @kbd{Ctrl-x} (or @code{Ctrl-d} on a non-empty line) to delete the
  955: character under the cursor.
  956: @end itemize
  957: 
  958: When editing, displayable characters are inserted to the left of the
  959: cursor position; the line is always in ``insert'' (as opposed to
  960: ``overstrike'') mode.
  961: 
  962: @cindex history file
  963: @cindex @file{.gforth-history}
  964: On Unix systems, the history file is @file{~/.gforth-history} by
  965: default@footnote{i.e. it is stored in the user's home directory.}. You
  966: can find out the name and location of your history file using:
  967: 
  968: @example 
  969: history-file type \ Unix-class systems
  970: 
  971: history-file type \ Other systems
  972: history-dir  type
  973: @end example
  974: 
  975: If you enter long definitions by hand, you can use a text editor to
  976: paste them out of the history file into a Forth source file for reuse at
  977: a later time.
  978: 
  979: Gforth never trims the size of the history file, so you should do this
  980: periodically, if necessary.
  981: 
  982: @comment this is all defined in history.fs
  983: @comment NAC TODO the ctrl-D behaviour can either do a bye or a beep.. how is that option
  984: @comment chosen?
  985: 
  986: 
  987: @comment ----------------------------------------------
  988: @node Environment variables, Gforth Files, Command-line editing, Gforth Environment
  989: @section Environment variables
  990: @cindex environment variables
  991: 
  992: Gforth uses these environment variables:
  993: 
  994: @itemize @bullet
  995: @item
  996: @cindex @code{GFORTHHIST} -- environment variable
  997: @code{GFORTHHIST} -- (Unix systems only) specifies the directory in which to
  998: open/create the history file, @file{.gforth-history}. Default:
  999: @code{$HOME}.
 1000: 
 1001: @item
 1002: @cindex @code{GFORTHPATH} -- environment variable
 1003: @code{GFORTHPATH} -- specifies the path used when searching for the gforth image file and
 1004: for Forth source-code files.
 1005: 
 1006: @item
 1007: @cindex @code{LANG} -- environment variable
 1008: @code{LANG} -- see @code{LC_CTYPE}
 1009: 
 1010: @item
 1011: @cindex @code{LC_ALL} -- environment variable
 1012: @code{LC_ALL} -- see @code{LC_CTYPE}
 1013: 
 1014: @item
 1015: @cindex @code{LC_CTYPE} -- environment variable
 1016: @code{LC_CTYPE} -- If this variable contains ``UTF-8'' on Gforth
 1017: startup, Gforth uses the UTF-8 encoding for strings internally and
 1018: expects its input and produces its output in UTF-8 encoding, otherwise
 1019: the encoding is 8bit (see @pxref{Xchars and Unicode}).  If this
 1020: environment variable is unset, Gforth looks in @code{LC_ALL}, and if
 1021: that is unset, in @code{LANG}.
 1022: 
 1023: @item
 1024: @cindex @code{GFORTHSYSTEMPREFIX} -- environment variable
 1025: 
 1026: @code{GFORTHSYSTEMPREFIX} -- specifies what to prepend to the argument
 1027: of @code{system} before passing it to C's @code{system()}.  Default:
 1028: @code{"./$COMSPEC /c "} on Windows, @code{""} on other OSs.  The prefix
 1029: and the command are directly concatenated, so if a space between them is
 1030: necessary, append it to the prefix.
 1031: 
 1032: @item
 1033: @cindex @code{GFORTH} -- environment variable
 1034: @code{GFORTH} -- used by @file{gforthmi}, @xref{gforthmi}.
 1035: 
 1036: @item
 1037: @cindex @code{GFORTHD} -- environment variable
 1038: @code{GFORTHD} -- used by @file{gforthmi}, @xref{gforthmi}.
 1039: 
 1040: @item
 1041: @cindex @code{TMP}, @code{TEMP} - environment variable
 1042: @code{TMP}, @code{TEMP} - (non-Unix systems only) used as a potential
 1043: location for the history file.
 1044: @end itemize
 1045: 
 1046: @comment also POSIXELY_CORRECT LINES COLUMNS HOME but no interest in
 1047: @comment mentioning these.
 1048: 
 1049: All the Gforth environment variables default to sensible values if they
 1050: are not set.
 1051: 
 1052: 
 1053: @comment ----------------------------------------------
 1054: @node Gforth Files, Gforth in pipes, Environment variables, Gforth Environment
 1055: @section Gforth files
 1056: @cindex Gforth files
 1057: 
 1058: When you install Gforth on a Unix system, it installs files in these
 1059: locations by default:
 1060: 
 1061: @itemize @bullet
 1062: @item
 1063: @file{/usr/local/bin/gforth}
 1064: @item
 1065: @file{/usr/local/bin/gforthmi}
 1066: @item
 1067: @file{/usr/local/man/man1/gforth.1} - man page.
 1068: @item
 1069: @file{/usr/local/info} - the Info version of this manual.
 1070: @item
 1071: @file{/usr/local/lib/gforth/<version>/...} - Gforth @file{.fi} files.
 1072: @item
 1073: @file{/usr/local/share/gforth/<version>/TAGS} - Emacs TAGS file.
 1074: @item
 1075: @file{/usr/local/share/gforth/<version>/...} - Gforth source files.
 1076: @item
 1077: @file{.../emacs/site-lisp/gforth.el} - Emacs gforth mode.
 1078: @end itemize
 1079: 
 1080: You can select different places for installation by using
 1081: @code{configure} options (listed with @code{configure --help}).
 1082: 
 1083: @comment ----------------------------------------------
 1084: @node Gforth in pipes, Startup speed, Gforth Files, Gforth Environment
 1085: @section Gforth in pipes
 1086: @cindex pipes, Gforth as part of
 1087: 
 1088: Gforth can be used in pipes created elsewhere (described here).  It can
 1089: also create pipes on its own (@pxref{Pipes}).
 1090: 
 1091: @cindex input from pipes
 1092: If you pipe into Gforth, your program should read with @code{read-file}
 1093: or @code{read-line} from @code{stdin} (@pxref{General files}).
 1094: @code{Key} does not recognize the end of input.  Words like
 1095: @code{accept} echo the input and are therefore usually not useful for
 1096: reading from a pipe.  You have to invoke the Forth program with an OS
 1097: command-line option, as you have no chance to use the Forth command line
 1098: (the text interpreter would try to interpret the pipe input).
 1099: 
 1100: @cindex output in pipes
 1101: You can output to a pipe with @code{type}, @code{emit}, @code{cr} etc.
 1102: 
 1103: @cindex silent exiting from Gforth
 1104: When you write to a pipe that has been closed at the other end, Gforth
 1105: receives a SIGPIPE signal (``pipe broken'').  Gforth translates this
 1106: into the exception @code{broken-pipe-error}.  If your application does
 1107: not catch that exception, the system catches it and exits, usually
 1108: silently (unless you were working on the Forth command line; then it
 1109: prints an error message and exits).  This is usually the desired
 1110: behaviour.
 1111: 
 1112: If you do not like this behaviour, you have to catch the exception
 1113: yourself, and react to it.
 1114: 
 1115: Here's an example of an invocation of Gforth that is usable in a pipe:
 1116: 
 1117: @example
 1118: gforth -e ": foo begin pad dup 10 stdin read-file throw dup while \
 1119:  type repeat ; foo bye"
 1120: @end example
 1121: 
 1122: This example just copies the input verbatim to the output.  A very
 1123: simple pipe containing this example looks like this:
 1124: 
 1125: @example
 1126: cat startup.fs |
 1127: gforth -e ": foo begin pad dup 80 stdin read-file throw dup while \
 1128:  type repeat ; foo bye"|
 1129: head
 1130: @end example
 1131: 
 1132: @cindex stderr and pipes
 1133: Pipes involving Gforth's @code{stderr} output do not work.
 1134: 
 1135: @comment ----------------------------------------------
 1136: @node Startup speed,  , Gforth in pipes, Gforth Environment
 1137: @section Startup speed
 1138: @cindex Startup speed
 1139: @cindex speed, startup
 1140: 
 1141: If Gforth is used for CGI scripts or in shell scripts, its startup
 1142: speed may become a problem.  On a 300MHz 21064a under Linux-2.2.13 with
 1143: glibc-2.0.7, @code{gforth -e bye} takes about 24.6ms user and 11.3ms
 1144: system time.
 1145: 
 1146: If startup speed is a problem, you may consider the following ways to
 1147: improve it; or you may consider ways to reduce the number of startups
 1148: (for example, by using Fast-CGI).
 1149: 
 1150: An easy step that influences Gforth startup speed is the use of the
 1151: @option{--no-dynamic} option; this decreases image loading speed, but
 1152: increases compile-time and run-time.
 1153: 
 1154: Another step to improve startup speed is to statically link Gforth, by
 1155: building it with @code{XLDFLAGS=-static}.  This requires more memory for
 1156: the code and will therefore slow down the first invocation, but
 1157: subsequent invocations avoid the dynamic linking overhead.  Another
 1158: disadvantage is that Gforth won't profit from library upgrades.  As a
 1159: result, @code{gforth-static -e bye} takes about 17.1ms user and
 1160: 8.2ms system time.
 1161: 
 1162: The next step to improve startup speed is to use a non-relocatable image
 1163: (@pxref{Non-Relocatable Image Files}).  You can create this image with
 1164: @code{gforth -e "savesystem gforthnr.fi bye"} and later use it with
 1165: @code{gforth -i gforthnr.fi ...}.  This avoids the relocation overhead
 1166: and a part of the copy-on-write overhead.  The disadvantage is that the
 1167: non-relocatable image does not work if the OS gives Gforth a different
 1168: address for the dictionary, for whatever reason; so you better provide a
 1169: fallback on a relocatable image.  @code{gforth-static -i gforthnr.fi -e
 1170: bye} takes about 15.3ms user and 7.5ms system time.
 1171: 
 1172: The final step is to disable dictionary hashing in Gforth.  Gforth
 1173: builds the hash table on startup, which takes much of the startup
 1174: overhead. You can do this by commenting out the @code{include hash.fs}
 1175: in @file{startup.fs} and everything that requires @file{hash.fs} (at the
 1176: moment @file{table.fs} and @file{ekey.fs}) and then doing @code{make}.
 1177: The disadvantages are that functionality like @code{table} and
 1178: @code{ekey} is missing and that text interpretation (e.g., compiling)
 1179: now takes much longer. So, you should only use this method if there is
 1180: no significant text interpretation to perform (the script should be
 1181: compiled into the image, amongst other things).  @code{gforth-static -i
 1182: gforthnrnh.fi -e bye} takes about 2.1ms user and 6.1ms system time.
 1183: 
 1184: @c ******************************************************************
 1185: @node Tutorial, Introduction, Gforth Environment, Top
 1186: @chapter Forth Tutorial
 1187: @cindex Tutorial
 1188: @cindex Forth Tutorial
 1189: 
 1190: @c Topics from nac's Introduction that could be mentioned:
 1191: @c press <ret> after each line
 1192: @c Prompt
 1193: @c numbers vs. words in dictionary on text interpretation
 1194: @c what happens on redefinition
 1195: @c parsing words (in particular, defining words)
 1196: 
 1197: The difference of this chapter from the Introduction
 1198: (@pxref{Introduction}) is that this tutorial is more fast-paced, should
 1199: be used while sitting in front of a computer, and covers much more
 1200: material, but does not explain how the Forth system works.
 1201: 
 1202: This tutorial can be used with any ANS-compliant Forth; any
 1203: Gforth-specific features are marked as such and you can skip them if you
 1204: work with another Forth.  This tutorial does not explain all features of
 1205: Forth, just enough to get you started and give you some ideas about the
 1206: facilities available in Forth.  Read the rest of the manual and the
 1207: standard when you are through this.
 1208: 
 1209: The intended way to use this tutorial is that you work through it while
 1210: sitting in front of the console, take a look at the examples and predict
 1211: what they will do, then try them out; if the outcome is not as expected,
 1212: find out why (e.g., by trying out variations of the example), so you
 1213: understand what's going on.  There are also some assignments that you
 1214: should solve.
 1215: 
 1216: This tutorial assumes that you have programmed before and know what,
 1217: e.g., a loop is.
 1218: 
 1219: @c !! explain compat library
 1220: 
 1221: @menu
 1222: * Starting Gforth Tutorial::    
 1223: * Syntax Tutorial::             
 1224: * Crash Course Tutorial::       
 1225: * Stack Tutorial::              
 1226: * Arithmetics Tutorial::        
 1227: * Stack Manipulation Tutorial::  
 1228: * Using files for Forth code Tutorial::  
 1229: * Comments Tutorial::           
 1230: * Colon Definitions Tutorial::  
 1231: * Decompilation Tutorial::      
 1232: * Stack-Effect Comments Tutorial::  
 1233: * Types Tutorial::              
 1234: * Factoring Tutorial::          
 1235: * Designing the stack effect Tutorial::  
 1236: * Local Variables Tutorial::    
 1237: * Conditional execution Tutorial::  
 1238: * Flags and Comparisons Tutorial::  
 1239: * General Loops Tutorial::      
 1240: * Counted loops Tutorial::      
 1241: * Recursion Tutorial::          
 1242: * Leaving definitions or loops Tutorial::  
 1243: * Return Stack Tutorial::       
 1244: * Memory Tutorial::             
 1245: * Characters and Strings Tutorial::  
 1246: * Alignment Tutorial::          
 1247: * Floating Point Tutorial::     
 1248: * Files Tutorial::              
 1249: * Interpretation and Compilation Semantics and Immediacy Tutorial::  
 1250: * Execution Tokens Tutorial::   
 1251: * Exceptions Tutorial::         
 1252: * Defining Words Tutorial::     
 1253: * Arrays and Records Tutorial::  
 1254: * POSTPONE Tutorial::           
 1255: * Literal Tutorial::            
 1256: * Advanced macros Tutorial::    
 1257: * Compilation Tokens Tutorial::  
 1258: * Wordlists and Search Order Tutorial::  
 1259: @end menu
 1260: 
 1261: @node Starting Gforth Tutorial, Syntax Tutorial, Tutorial, Tutorial
 1262: @section Starting Gforth
 1263: @cindex starting Gforth tutorial
 1264: You can start Gforth by typing its name:
 1265: 
 1266: @example
 1267: gforth
 1268: @end example
 1269: 
 1270: That puts you into interactive mode; you can leave Gforth by typing
 1271: @code{bye}.  While in Gforth, you can edit the command line and access
 1272: the command line history with cursor keys, similar to bash.
 1273: 
 1274: 
 1275: @node Syntax Tutorial, Crash Course Tutorial, Starting Gforth Tutorial, Tutorial
 1276: @section Syntax
 1277: @cindex syntax tutorial
 1278: 
 1279: A @dfn{word} is a sequence of arbitrary characters (except white
 1280: space).  Words are separated by white space.  E.g., each of the
 1281: following lines contains exactly one word:
 1282: 
 1283: @example
 1284: word
 1285: !@@#$%^&*()
 1286: 1234567890
 1287: 5!a
 1288: @end example
 1289: 
 1290: A frequent beginner's error is to leave away necessary white space,
 1291: resulting in an error like @samp{Undefined word}; so if you see such an
 1292: error, check if you have put spaces wherever necessary.
 1293: 
 1294: @example
 1295: ." hello, world" \ correct
 1296: ."hello, world"  \ gives an "Undefined word" error
 1297: @end example
 1298: 
 1299: Gforth and most other Forth systems ignore differences in case (they are
 1300: case-insensitive), i.e., @samp{word} is the same as @samp{Word}.  If
 1301: your system is case-sensitive, you may have to type all the examples
 1302: given here in upper case.
 1303: 
 1304: 
 1305: @node Crash Course Tutorial, Stack Tutorial, Syntax Tutorial, Tutorial
 1306: @section Crash Course
 1307: 
 1308: Type
 1309: 
 1310: @example
 1311: 0 0 !
 1312: here execute
 1313: ' catch >body 20 erase abort
 1314: ' (quit) >body 20 erase
 1315: @end example
 1316: 
 1317: The last two examples are guaranteed to destroy parts of Gforth (and
 1318: most other systems), so you better leave Gforth afterwards (if it has
 1319: not finished by itself).  On some systems you may have to kill gforth
 1320: from outside (e.g., in Unix with @code{kill}).
 1321: 
 1322: Now that you know how to produce crashes (and that there's not much to
 1323: them), let's learn how to produce meaningful programs.
 1324: 
 1325: 
 1326: @node Stack Tutorial, Arithmetics Tutorial, Crash Course Tutorial, Tutorial
 1327: @section Stack
 1328: @cindex stack tutorial
 1329: 
 1330: The most obvious feature of Forth is the stack.  When you type in a
 1331: number, it is pushed on the stack.  You can display the content of the
 1332: stack with @code{.s}.
 1333: 
 1334: @example
 1335: 1 2 .s
 1336: 3 .s
 1337: @end example
 1338: 
 1339: @code{.s} displays the top-of-stack to the right, i.e., the numbers
 1340: appear in @code{.s} output as they appeared in the input.
 1341: 
 1342: You can print the top of stack element with @code{.}.
 1343: 
 1344: @example
 1345: 1 2 3 . . .
 1346: @end example
 1347: 
 1348: In general, words consume their stack arguments (@code{.s} is an
 1349: exception).
 1350: 
 1351: @quotation Assignment
 1352: What does the stack contain after @code{5 6 7 .}?
 1353: @end quotation
 1354: 
 1355: 
 1356: @node Arithmetics Tutorial, Stack Manipulation Tutorial, Stack Tutorial, Tutorial
 1357: @section Arithmetics
 1358: @cindex arithmetics tutorial
 1359: 
 1360: The words @code{+}, @code{-}, @code{*}, @code{/}, and @code{mod} always
 1361: operate on the top two stack items:
 1362: 
 1363: @example
 1364: 2 2 .s
 1365: + .s
 1366: .
 1367: 2 1 - .
 1368: 7 3 mod .
 1369: @end example
 1370: 
 1371: The operands of @code{-}, @code{/}, and @code{mod} are in the same order
 1372: as in the corresponding infix expression (this is generally the case in
 1373: Forth).
 1374: 
 1375: Parentheses are superfluous (and not available), because the order of
 1376: the words unambiguously determines the order of evaluation and the
 1377: operands:
 1378: 
 1379: @example
 1380: 3 4 + 5 * .
 1381: 3 4 5 * + .
 1382: @end example
 1383: 
 1384: @quotation Assignment
 1385: What are the infix expressions corresponding to the Forth code above?
 1386: Write @code{6-7*8+9} in Forth notation@footnote{This notation is also
 1387: known as Postfix or RPN (Reverse Polish Notation).}.
 1388: @end quotation
 1389: 
 1390: To change the sign, use @code{negate}:
 1391: 
 1392: @example
 1393: 2 negate .
 1394: @end example
 1395: 
 1396: @quotation Assignment
 1397: Convert -(-3)*4-5 to Forth.
 1398: @end quotation
 1399: 
 1400: @code{/mod} performs both @code{/} and @code{mod}.
 1401: 
 1402: @example
 1403: 7 3 /mod . .
 1404: @end example
 1405: 
 1406: Reference: @ref{Arithmetic}.
 1407: 
 1408: 
 1409: @node Stack Manipulation Tutorial, Using files for Forth code Tutorial, Arithmetics Tutorial, Tutorial
 1410: @section Stack Manipulation
 1411: @cindex stack manipulation tutorial
 1412: 
 1413: Stack manipulation words rearrange the data on the stack.
 1414: 
 1415: @example
 1416: 1 .s drop .s
 1417: 1 .s dup .s drop drop .s
 1418: 1 2 .s over .s drop drop drop
 1419: 1 2 .s swap .s drop drop
 1420: 1 2 3 .s rot .s drop drop drop
 1421: @end example
 1422: 
 1423: These are the most important stack manipulation words.  There are also
 1424: variants that manipulate twice as many stack items:
 1425: 
 1426: @example
 1427: 1 2 3 4 .s 2swap .s 2drop 2drop
 1428: @end example
 1429: 
 1430: Two more stack manipulation words are:
 1431: 
 1432: @example
 1433: 1 2 .s nip .s drop
 1434: 1 2 .s tuck .s 2drop drop
 1435: @end example
 1436: 
 1437: @quotation Assignment
 1438: Replace @code{nip} and @code{tuck} with combinations of other stack
 1439: manipulation words.
 1440: 
 1441: @example
 1442: Given:          How do you get:
 1443: 1 2 3           3 2 1           
 1444: 1 2 3           1 2 3 2                 
 1445: 1 2 3           1 2 3 3                 
 1446: 1 2 3           1 3 3           
 1447: 1 2 3           2 1 3           
 1448: 1 2 3 4         4 3 2 1         
 1449: 1 2 3           1 2 3 1 2 3             
 1450: 1 2 3 4         1 2 3 4 1 2             
 1451: 1 2 3
 1452: 1 2 3           1 2 3 4                 
 1453: 1 2 3           1 3             
 1454: @end example
 1455: @end quotation
 1456: 
 1457: @example
 1458: 5 dup * .
 1459: @end example
 1460: 
 1461: @quotation Assignment
 1462: Write 17^3 and 17^4 in Forth, without writing @code{17} more than once.
 1463: Write a piece of Forth code that expects two numbers on the stack
 1464: (@var{a} and @var{b}, with @var{b} on top) and computes
 1465: @code{(a-b)(a+1)}.
 1466: @end quotation
 1467: 
 1468: Reference: @ref{Stack Manipulation}.
 1469: 
 1470: 
 1471: @node Using files for Forth code Tutorial, Comments Tutorial, Stack Manipulation Tutorial, Tutorial
 1472: @section Using files for Forth code
 1473: @cindex loading Forth code, tutorial
 1474: @cindex files containing Forth code, tutorial
 1475: 
 1476: While working at the Forth command line is convenient for one-line
 1477: examples and short one-off code, you probably want to store your source
 1478: code in files for convenient editing and persistence.  You can use your
 1479: favourite editor (Gforth includes Emacs support, @pxref{Emacs and
 1480: Gforth}) to create @var{file.fs} and use
 1481: 
 1482: @example
 1483: s" @var{file.fs}" included
 1484: @end example
 1485: 
 1486: to load it into your Forth system.  The file name extension I use for
 1487: Forth files is @samp{.fs}.
 1488: 
 1489: You can easily start Gforth with some files loaded like this:
 1490: 
 1491: @example
 1492: gforth @var{file1.fs} @var{file2.fs}
 1493: @end example
 1494: 
 1495: If an error occurs during loading these files, Gforth terminates,
 1496: whereas an error during @code{INCLUDED} within Gforth usually gives you
 1497: a Gforth command line.  Starting the Forth system every time gives you a
 1498: clean start every time, without interference from the results of earlier
 1499: tries.
 1500: 
 1501: I often put all the tests in a file, then load the code and run the
 1502: tests with
 1503: 
 1504: @example
 1505: gforth @var{code.fs} @var{tests.fs} -e bye
 1506: @end example
 1507: 
 1508: (often by performing this command with @kbd{C-x C-e} in Emacs).  The
 1509: @code{-e bye} ensures that Gforth terminates afterwards so that I can
 1510: restart this command without ado.
 1511: 
 1512: The advantage of this approach is that the tests can be repeated easily
 1513: every time the program ist changed, making it easy to catch bugs
 1514: introduced by the change.
 1515: 
 1516: Reference: @ref{Forth source files}.
 1517: 
 1518: 
 1519: @node Comments Tutorial, Colon Definitions Tutorial, Using files for Forth code Tutorial, Tutorial
 1520: @section Comments
 1521: @cindex comments tutorial
 1522: 
 1523: @example
 1524: \ That's a comment; it ends at the end of the line
 1525: ( Another comment; it ends here: )  .s
 1526: @end example
 1527: 
 1528: @code{\} and @code{(} are ordinary Forth words and therefore have to be
 1529: separated with white space from the following text.
 1530: 
 1531: @example
 1532: \This gives an "Undefined word" error
 1533: @end example
 1534: 
 1535: The first @code{)} ends a comment started with @code{(}, so you cannot
 1536: nest @code{(}-comments; and you cannot comment out text containing a
 1537: @code{)} with @code{( ... )}@footnote{therefore it's a good idea to
 1538: avoid @code{)} in word names.}.
 1539: 
 1540: I use @code{\}-comments for descriptive text and for commenting out code
 1541: of one or more line; I use @code{(}-comments for describing the stack
 1542: effect, the stack contents, or for commenting out sub-line pieces of
 1543: code.
 1544: 
 1545: The Emacs mode @file{gforth.el} (@pxref{Emacs and Gforth}) supports
 1546: these uses by commenting out a region with @kbd{C-x \}, uncommenting a
 1547: region with @kbd{C-u C-x \}, and filling a @code{\}-commented region
 1548: with @kbd{M-q}.
 1549: 
 1550: Reference: @ref{Comments}.
 1551: 
 1552: 
 1553: @node Colon Definitions Tutorial, Decompilation Tutorial, Comments Tutorial, Tutorial
 1554: @section Colon Definitions
 1555: @cindex colon definitions, tutorial
 1556: @cindex definitions, tutorial
 1557: @cindex procedures, tutorial
 1558: @cindex functions, tutorial
 1559: 
 1560: are similar to procedures and functions in other programming languages.
 1561: 
 1562: @example
 1563: : squared ( n -- n^2 )
 1564:    dup * ;
 1565: 5 squared .
 1566: 7 squared .
 1567: @end example
 1568: 
 1569: @code{:} starts the colon definition; its name is @code{squared}.  The
 1570: following comment describes its stack effect.  The words @code{dup *}
 1571: are not executed, but compiled into the definition.  @code{;} ends the
 1572: colon definition.
 1573: 
 1574: The newly-defined word can be used like any other word, including using
 1575: it in other definitions:
 1576: 
 1577: @example
 1578: : cubed ( n -- n^3 )
 1579:    dup squared * ;
 1580: -5 cubed .
 1581: : fourth-power ( n -- n^4 )
 1582:    squared squared ;
 1583: 3 fourth-power .
 1584: @end example
 1585: 
 1586: @quotation Assignment
 1587: Write colon definitions for @code{nip}, @code{tuck}, @code{negate}, and
 1588: @code{/mod} in terms of other Forth words, and check if they work (hint:
 1589: test your tests on the originals first).  Don't let the
 1590: @samp{redefined}-Messages spook you, they are just warnings.
 1591: @end quotation
 1592: 
 1593: Reference: @ref{Colon Definitions}.
 1594: 
 1595: 
 1596: @node Decompilation Tutorial, Stack-Effect Comments Tutorial, Colon Definitions Tutorial, Tutorial
 1597: @section Decompilation
 1598: @cindex decompilation tutorial
 1599: @cindex see tutorial
 1600: 
 1601: You can decompile colon definitions with @code{see}:
 1602: 
 1603: @example
 1604: see squared
 1605: see cubed
 1606: @end example
 1607: 
 1608: In Gforth @code{see} shows you a reconstruction of the source code from
 1609: the executable code.  Informations that were present in the source, but
 1610: not in the executable code, are lost (e.g., comments).
 1611: 
 1612: You can also decompile the predefined words:
 1613: 
 1614: @example
 1615: see .
 1616: see +
 1617: @end example
 1618: 
 1619: 
 1620: @node Stack-Effect Comments Tutorial, Types Tutorial, Decompilation Tutorial, Tutorial
 1621: @section Stack-Effect Comments
 1622: @cindex stack-effect comments, tutorial
 1623: @cindex --, tutorial
 1624: By convention the comment after the name of a definition describes the
 1625: stack effect: The part in front of the @samp{--} describes the state of
 1626: the stack before the execution of the definition, i.e., the parameters
 1627: that are passed into the colon definition; the part behind the @samp{--}
 1628: is the state of the stack after the execution of the definition, i.e.,
 1629: the results of the definition.  The stack comment only shows the top
 1630: stack items that the definition accesses and/or changes.
 1631: 
 1632: You should put a correct stack effect on every definition, even if it is
 1633: just @code{( -- )}.  You should also add some descriptive comment to
 1634: more complicated words (I usually do this in the lines following
 1635: @code{:}).  If you don't do this, your code becomes unreadable (because
 1636: you have to work through every definition before you can understand
 1637: any).
 1638: 
 1639: @quotation Assignment
 1640: The stack effect of @code{swap} can be written like this: @code{x1 x2 --
 1641: x2 x1}.  Describe the stack effect of @code{-}, @code{drop}, @code{dup},
 1642: @code{over}, @code{rot}, @code{nip}, and @code{tuck}.  Hint: When you
 1643: are done, you can compare your stack effects to those in this manual
 1644: (@pxref{Word Index}).
 1645: @end quotation
 1646: 
 1647: Sometimes programmers put comments at various places in colon
 1648: definitions that describe the contents of the stack at that place (stack
 1649: comments); i.e., they are like the first part of a stack-effect
 1650: comment. E.g.,
 1651: 
 1652: @example
 1653: : cubed ( n -- n^3 )
 1654:    dup squared  ( n n^2 ) * ;
 1655: @end example
 1656: 
 1657: In this case the stack comment is pretty superfluous, because the word
 1658: is simple enough.  If you think it would be a good idea to add such a
 1659: comment to increase readability, you should also consider factoring the
 1660: word into several simpler words (@pxref{Factoring Tutorial,,
 1661: Factoring}), which typically eliminates the need for the stack comment;
 1662: however, if you decide not to refactor it, then having such a comment is
 1663: better than not having it.
 1664: 
 1665: The names of the stack items in stack-effect and stack comments in the
 1666: standard, in this manual, and in many programs specify the type through
 1667: a type prefix, similar to Fortran and Hungarian notation.  The most
 1668: frequent prefixes are:
 1669: 
 1670: @table @code
 1671: @item n
 1672: signed integer
 1673: @item u
 1674: unsigned integer
 1675: @item c
 1676: character
 1677: @item f
 1678: Boolean flags, i.e. @code{false} or @code{true}.
 1679: @item a-addr,a-
 1680: Cell-aligned address
 1681: @item c-addr,c-
 1682: Char-aligned address (note that a Char may have two bytes in Windows NT)
 1683: @item xt
 1684: Execution token, same size as Cell
 1685: @item w,x
 1686: Cell, can contain an integer or an address.  It usually takes 32, 64 or
 1687: 16 bits (depending on your platform and Forth system). A cell is more
 1688: commonly known as machine word, but the term @emph{word} already means
 1689: something different in Forth.
 1690: @item d
 1691: signed double-cell integer
 1692: @item ud
 1693: unsigned double-cell integer
 1694: @item r
 1695: Float (on the FP stack)
 1696: @end table
 1697: 
 1698: You can find a more complete list in @ref{Notation}.
 1699: 
 1700: @quotation Assignment
 1701: Write stack-effect comments for all definitions you have written up to
 1702: now.
 1703: @end quotation
 1704: 
 1705: 
 1706: @node Types Tutorial, Factoring Tutorial, Stack-Effect Comments Tutorial, Tutorial
 1707: @section Types
 1708: @cindex types tutorial
 1709: 
 1710: In Forth the names of the operations are not overloaded; so similar
 1711: operations on different types need different names; e.g., @code{+} adds
 1712: integers, and you have to use @code{f+} to add floating-point numbers.
 1713: The following prefixes are often used for related operations on
 1714: different types:
 1715: 
 1716: @table @code
 1717: @item (none)
 1718: signed integer
 1719: @item u
 1720: unsigned integer
 1721: @item c
 1722: character
 1723: @item d
 1724: signed double-cell integer
 1725: @item ud, du
 1726: unsigned double-cell integer
 1727: @item 2
 1728: two cells (not-necessarily double-cell numbers)
 1729: @item m, um
 1730: mixed single-cell and double-cell operations
 1731: @item f
 1732: floating-point (note that in stack comments @samp{f} represents flags,
 1733: and @samp{r} represents FP numbers).
 1734: @end table
 1735: 
 1736: If there are no differences between the signed and the unsigned variant
 1737: (e.g., for @code{+}), there is only the prefix-less variant.
 1738: 
 1739: Forth does not perform type checking, neither at compile time, nor at
 1740: run time.  If you use the wrong oeration, the data are interpreted
 1741: incorrectly:
 1742: 
 1743: @example
 1744: -1 u.
 1745: @end example
 1746: 
 1747: If you have only experience with type-checked languages until now, and
 1748: have heard how important type-checking is, don't panic!  In my
 1749: experience (and that of other Forthers), type errors in Forth code are
 1750: usually easy to find (once you get used to it), the increased vigilance
 1751: of the programmer tends to catch some harder errors in addition to most
 1752: type errors, and you never have to work around the type system, so in
 1753: most situations the lack of type-checking seems to be a win (projects to
 1754: add type checking to Forth have not caught on).
 1755: 
 1756: 
 1757: @node Factoring Tutorial, Designing the stack effect Tutorial, Types Tutorial, Tutorial
 1758: @section Factoring
 1759: @cindex factoring tutorial
 1760: 
 1761: If you try to write longer definitions, you will soon find it hard to
 1762: keep track of the stack contents.  Therefore, good Forth programmers
 1763: tend to write only short definitions (e.g., three lines).  The art of
 1764: finding meaningful short definitions is known as factoring (as in
 1765: factoring polynomials).
 1766: 
 1767: Well-factored programs offer additional advantages: smaller, more
 1768: general words, are easier to test and debug and can be reused more and
 1769: better than larger, specialized words.
 1770: 
 1771: So, if you run into difficulties with stack management, when writing
 1772: code, try to define meaningful factors for the word, and define the word
 1773: in terms of those.  Even if a factor contains only two words, it is
 1774: often helpful.
 1775: 
 1776: Good factoring is not easy, and it takes some practice to get the knack
 1777: for it; but even experienced Forth programmers often don't find the
 1778: right solution right away, but only when rewriting the program.  So, if
 1779: you don't come up with a good solution immediately, keep trying, don't
 1780: despair.
 1781: 
 1782: @c example !!
 1783: 
 1784: 
 1785: @node Designing the stack effect Tutorial, Local Variables Tutorial, Factoring Tutorial, Tutorial
 1786: @section Designing the stack effect
 1787: @cindex Stack effect design, tutorial
 1788: @cindex design of stack effects, tutorial
 1789: 
 1790: In other languages you can use an arbitrary order of parameters for a
 1791: function; and since there is only one result, you don't have to deal with
 1792: the order of results, either.
 1793: 
 1794: In Forth (and other stack-based languages, e.g., PostScript) the
 1795: parameter and result order of a definition is important and should be
 1796: designed well.  The general guideline is to design the stack effect such
 1797: that the word is simple to use in most cases, even if that complicates
 1798: the implementation of the word.  Some concrete rules are:
 1799: 
 1800: @itemize @bullet
 1801: 
 1802: @item
 1803: Words consume all of their parameters (e.g., @code{.}).
 1804: 
 1805: @item
 1806: If there is a convention on the order of parameters (e.g., from
 1807: mathematics or another programming language), stick with it (e.g.,
 1808: @code{-}).
 1809: 
 1810: @item
 1811: If one parameter usually requires only a short computation (e.g., it is
 1812: a constant), pass it on the top of the stack.  Conversely, parameters
 1813: that usually require a long sequence of code to compute should be passed
 1814: as the bottom (i.e., first) parameter.  This makes the code easier to
 1815: read, because the reader does not need to keep track of the bottom item
 1816: through a long sequence of code (or, alternatively, through stack
 1817: manipulations). E.g., @code{!} (store, @pxref{Memory}) expects the
 1818: address on top of the stack because it is usually simpler to compute
 1819: than the stored value (often the address is just a variable).
 1820: 
 1821: @item
 1822: Similarly, results that are usually consumed quickly should be returned
 1823: on the top of stack, whereas a result that is often used in long
 1824: computations should be passed as bottom result.  E.g., the file words
 1825: like @code{open-file} return the error code on the top of stack, because
 1826: it is usually consumed quickly by @code{throw}; moreover, the error code
 1827: has to be checked before doing anything with the other results.
 1828: 
 1829: @end itemize
 1830: 
 1831: These rules are just general guidelines, don't lose sight of the overall
 1832: goal to make the words easy to use.  E.g., if the convention rule
 1833: conflicts with the computation-length rule, you might decide in favour
 1834: of the convention if the word will be used rarely, and in favour of the
 1835: computation-length rule if the word will be used frequently (because
 1836: with frequent use the cost of breaking the computation-length rule would
 1837: be quite high, and frequent use makes it easier to remember an
 1838: unconventional order).
 1839: 
 1840: @c example !! structure package
 1841: 
 1842: 
 1843: @node Local Variables Tutorial, Conditional execution Tutorial, Designing the stack effect Tutorial, Tutorial
 1844: @section Local Variables
 1845: @cindex local variables, tutorial
 1846: 
 1847: You can define local variables (@emph{locals}) in a colon definition:
 1848: 
 1849: @example
 1850: : swap @{ a b -- b a @}
 1851:   b a ;
 1852: 1 2 swap .s 2drop
 1853: @end example
 1854: 
 1855: (If your Forth system does not support this syntax, include
 1856: @file{compat/anslocal.fs} first).
 1857: 
 1858: In this example @code{@{ a b -- b a @}} is the locals definition; it
 1859: takes two cells from the stack, puts the top of stack in @code{b} and
 1860: the next stack element in @code{a}.  @code{--} starts a comment ending
 1861: with @code{@}}.  After the locals definition, using the name of the
 1862: local will push its value on the stack.  You can leave the comment
 1863: part (@code{-- b a}) away:
 1864: 
 1865: @example
 1866: : swap ( x1 x2 -- x2 x1 )
 1867:   @{ a b @} b a ;
 1868: @end example
 1869: 
 1870: In Gforth you can have several locals definitions, anywhere in a colon
 1871: definition; in contrast, in a standard program you can have only one
 1872: locals definition per colon definition, and that locals definition must
 1873: be outside any control structure.
 1874: 
 1875: With locals you can write slightly longer definitions without running
 1876: into stack trouble.  However, I recommend trying to write colon
 1877: definitions without locals for exercise purposes to help you gain the
 1878: essential factoring skills.
 1879: 
 1880: @quotation Assignment
 1881: Rewrite your definitions until now with locals
 1882: @end quotation
 1883: 
 1884: Reference: @ref{Locals}.
 1885: 
 1886: 
 1887: @node Conditional execution Tutorial, Flags and Comparisons Tutorial, Local Variables Tutorial, Tutorial
 1888: @section Conditional execution
 1889: @cindex conditionals, tutorial
 1890: @cindex if, tutorial
 1891: 
 1892: In Forth you can use control structures only inside colon definitions.
 1893: An @code{if}-structure looks like this:
 1894: 
 1895: @example
 1896: : abs ( n1 -- +n2 )
 1897:     dup 0 < if
 1898:         negate
 1899:     endif ;
 1900: 5 abs .
 1901: -5 abs .
 1902: @end example
 1903: 
 1904: @code{if} takes a flag from the stack.  If the flag is non-zero (true),
 1905: the following code is performed, otherwise execution continues after the
 1906: @code{endif} (or @code{else}).  @code{<} compares the top two stack
 1907: elements and produces a flag:
 1908: 
 1909: @example
 1910: 1 2 < .
 1911: 2 1 < .
 1912: 1 1 < .
 1913: @end example
 1914: 
 1915: Actually the standard name for @code{endif} is @code{then}.  This
 1916: tutorial presents the examples using @code{endif}, because this is often
 1917: less confusing for people familiar with other programming languages
 1918: where @code{then} has a different meaning.  If your system does not have
 1919: @code{endif}, define it with
 1920: 
 1921: @example
 1922: : endif postpone then ; immediate
 1923: @end example
 1924: 
 1925: You can optionally use an @code{else}-part:
 1926: 
 1927: @example
 1928: : min ( n1 n2 -- n )
 1929:   2dup < if
 1930:     drop
 1931:   else
 1932:     nip
 1933:   endif ;
 1934: 2 3 min .
 1935: 3 2 min .
 1936: @end example
 1937: 
 1938: @quotation Assignment
 1939: Write @code{min} without @code{else}-part (hint: what's the definition
 1940: of @code{nip}?).
 1941: @end quotation
 1942: 
 1943: Reference: @ref{Selection}.
 1944: 
 1945: 
 1946: @node Flags and Comparisons Tutorial, General Loops Tutorial, Conditional execution Tutorial, Tutorial
 1947: @section Flags and Comparisons
 1948: @cindex flags tutorial
 1949: @cindex comparison tutorial
 1950: 
 1951: In a false-flag all bits are clear (0 when interpreted as integer).  In
 1952: a canonical true-flag all bits are set (-1 as a twos-complement signed
 1953: integer); in many contexts (e.g., @code{if}) any non-zero value is
 1954: treated as true flag.
 1955: 
 1956: @example
 1957: false .
 1958: true .
 1959: true hex u. decimal
 1960: @end example
 1961: 
 1962: Comparison words produce canonical flags:
 1963: 
 1964: @example
 1965: 1 1 = .
 1966: 1 0= .
 1967: 0 1 < .
 1968: 0 0 < .
 1969: -1 1 u< . \ type error, u< interprets -1 as large unsigned number
 1970: -1 1 < .
 1971: @end example
 1972: 
 1973: Gforth supports all combinations of the prefixes @code{0 u d d0 du f f0}
 1974: (or none) and the comparisons @code{= <> < > <= >=}.  Only a part of
 1975: these combinations are standard (for details see the standard,
 1976: @ref{Numeric comparison}, @ref{Floating Point} or @ref{Word Index}).
 1977: 
 1978: You can use @code{and or xor invert} as operations on canonical flags.
 1979: Actually they are bitwise operations:
 1980: 
 1981: @example
 1982: 1 2 and .
 1983: 1 2 or .
 1984: 1 3 xor .
 1985: 1 invert .
 1986: @end example
 1987: 
 1988: You can convert a zero/non-zero flag into a canonical flag with
 1989: @code{0<>} (and complement it on the way with @code{0=}).
 1990: 
 1991: @example
 1992: 1 0= .
 1993: 1 0<> .
 1994: @end example
 1995: 
 1996: You can use the all-bits-set feature of canonical flags and the bitwise
 1997: operation of the Boolean operations to avoid @code{if}s:
 1998: 
 1999: @example
 2000: : foo ( n1 -- n2 )
 2001:   0= if
 2002:     14
 2003:   else
 2004:     0
 2005:   endif ;
 2006: 0 foo .
 2007: 1 foo .
 2008: 
 2009: : foo ( n1 -- n2 )
 2010:   0= 14 and ;
 2011: 0 foo .
 2012: 1 foo .
 2013: @end example
 2014: 
 2015: @quotation Assignment
 2016: Write @code{min} without @code{if}.
 2017: @end quotation
 2018: 
 2019: For reference, see @ref{Boolean Flags}, @ref{Numeric comparison}, and
 2020: @ref{Bitwise operations}.
 2021: 
 2022: 
 2023: @node General Loops Tutorial, Counted loops Tutorial, Flags and Comparisons Tutorial, Tutorial
 2024: @section General Loops
 2025: @cindex loops, indefinite, tutorial
 2026: 
 2027: The endless loop is the most simple one:
 2028: 
 2029: @example
 2030: : endless ( -- )
 2031:   0 begin
 2032:     dup . 1+
 2033:   again ;
 2034: endless
 2035: @end example
 2036: 
 2037: Terminate this loop by pressing @kbd{Ctrl-C} (in Gforth).  @code{begin}
 2038: does nothing at run-time, @code{again} jumps back to @code{begin}.
 2039: 
 2040: A loop with one exit at any place looks like this:
 2041: 
 2042: @example
 2043: : log2 ( +n1 -- n2 )
 2044: \ logarithmus dualis of n1>0, rounded down to the next integer
 2045:   assert( dup 0> )
 2046:   2/ 0 begin
 2047:     over 0> while
 2048:       1+ swap 2/ swap
 2049:   repeat
 2050:   nip ;
 2051: 7 log2 .
 2052: 8 log2 .
 2053: @end example
 2054: 
 2055: At run-time @code{while} consumes a flag; if it is 0, execution
 2056: continues behind the @code{repeat}; if the flag is non-zero, execution
 2057: continues behind the @code{while}.  @code{Repeat} jumps back to
 2058: @code{begin}, just like @code{again}.
 2059: 
 2060: In Forth there are many combinations/abbreviations, like @code{1+}.
 2061: However, @code{2/} is not one of them; it shifts its argument right by
 2062: one bit (arithmetic shift right):
 2063: 
 2064: @example
 2065: -5 2 / .
 2066: -5 2/ .
 2067: @end example
 2068: 
 2069: @code{assert(} is no standard word, but you can get it on systems other
 2070: than Gforth by including @file{compat/assert.fs}.  You can see what it
 2071: does by trying
 2072: 
 2073: @example
 2074: 0 log2 .
 2075: @end example
 2076: 
 2077: Here's a loop with an exit at the end:
 2078: 
 2079: @example
 2080: : log2 ( +n1 -- n2 )
 2081: \ logarithmus dualis of n1>0, rounded down to the next integer
 2082:   assert( dup 0 > )
 2083:   -1 begin
 2084:     1+ swap 2/ swap
 2085:     over 0 <=
 2086:   until
 2087:   nip ;
 2088: @end example
 2089: 
 2090: @code{Until} consumes a flag; if it is non-zero, execution continues at
 2091: the @code{begin}, otherwise after the @code{until}.
 2092: 
 2093: @quotation Assignment
 2094: Write a definition for computing the greatest common divisor.
 2095: @end quotation
 2096: 
 2097: Reference: @ref{Simple Loops}.
 2098: 
 2099: 
 2100: @node Counted loops Tutorial, Recursion Tutorial, General Loops Tutorial, Tutorial
 2101: @section Counted loops
 2102: @cindex loops, counted, tutorial
 2103: 
 2104: @example
 2105: : ^ ( n1 u -- n )
 2106: \ n = the uth power of n1
 2107:   1 swap 0 u+do
 2108:     over *
 2109:   loop
 2110:   nip ;
 2111: 3 2 ^ .
 2112: 4 3 ^ .
 2113: @end example
 2114: 
 2115: @code{U+do} (from @file{compat/loops.fs}, if your Forth system doesn't
 2116: have it) takes two numbers of the stack @code{( u3 u4 -- )}, and then
 2117: performs the code between @code{u+do} and @code{loop} for @code{u3-u4}
 2118: times (or not at all, if @code{u3-u4<0}).
 2119: 
 2120: You can see the stack effect design rules at work in the stack effect of
 2121: the loop start words: Since the start value of the loop is more
 2122: frequently constant than the end value, the start value is passed on
 2123: the top-of-stack.
 2124: 
 2125: You can access the counter of a counted loop with @code{i}:
 2126: 
 2127: @example
 2128: : fac ( u -- u! )
 2129:   1 swap 1+ 1 u+do
 2130:     i *
 2131:   loop ;
 2132: 5 fac .
 2133: 7 fac .
 2134: @end example
 2135: 
 2136: There is also @code{+do}, which expects signed numbers (important for
 2137: deciding whether to enter the loop).
 2138: 
 2139: @quotation Assignment
 2140: Write a definition for computing the nth Fibonacci number.
 2141: @end quotation
 2142: 
 2143: You can also use increments other than 1:
 2144: 
 2145: @example
 2146: : up2 ( n1 n2 -- )
 2147:   +do
 2148:     i .
 2149:   2 +loop ;
 2150: 10 0 up2
 2151: 
 2152: : down2 ( n1 n2 -- )
 2153:   -do
 2154:     i .
 2155:   2 -loop ;
 2156: 0 10 down2
 2157: @end example
 2158: 
 2159: Reference: @ref{Counted Loops}.
 2160: 
 2161: 
 2162: @node Recursion Tutorial, Leaving definitions or loops Tutorial, Counted loops Tutorial, Tutorial
 2163: @section Recursion
 2164: @cindex recursion tutorial
 2165: 
 2166: Usually the name of a definition is not visible in the definition; but
 2167: earlier definitions are usually visible:
 2168: 
 2169: @example
 2170: 1 0 / . \ "Floating-point unidentified fault" in Gforth on some platforms
 2171: : / ( n1 n2 -- n )
 2172:   dup 0= if
 2173:     -10 throw \ report division by zero
 2174:   endif
 2175:   /           \ old version
 2176: ;
 2177: 1 0 /
 2178: @end example
 2179: 
 2180: For recursive definitions you can use @code{recursive} (non-standard) or
 2181: @code{recurse}:
 2182: 
 2183: @example
 2184: : fac1 ( n -- n! ) recursive
 2185:  dup 0> if
 2186:    dup 1- fac1 *
 2187:  else
 2188:    drop 1
 2189:  endif ;
 2190: 7 fac1 .
 2191: 
 2192: : fac2 ( n -- n! )
 2193:  dup 0> if
 2194:    dup 1- recurse *
 2195:  else
 2196:    drop 1
 2197:  endif ;
 2198: 8 fac2 .
 2199: @end example
 2200: 
 2201: @quotation Assignment
 2202: Write a recursive definition for computing the nth Fibonacci number.
 2203: @end quotation
 2204: 
 2205: Reference (including indirect recursion): @xref{Calls and returns}.
 2206: 
 2207: 
 2208: @node Leaving definitions or loops Tutorial, Return Stack Tutorial, Recursion Tutorial, Tutorial
 2209: @section Leaving definitions or loops
 2210: @cindex leaving definitions, tutorial
 2211: @cindex leaving loops, tutorial
 2212: 
 2213: @code{EXIT} exits the current definition right away.  For every counted
 2214: loop that is left in this way, an @code{UNLOOP} has to be performed
 2215: before the @code{EXIT}:
 2216: 
 2217: @c !! real examples
 2218: @example
 2219: : ...
 2220:  ... u+do
 2221:    ... if
 2222:      ... unloop exit
 2223:    endif
 2224:    ...
 2225:  loop
 2226:  ... ;
 2227: @end example
 2228: 
 2229: @code{LEAVE} leaves the innermost counted loop right away:
 2230: 
 2231: @example
 2232: : ...
 2233:  ... u+do
 2234:    ... if
 2235:      ... leave
 2236:    endif
 2237:    ...
 2238:  loop
 2239:  ... ;
 2240: @end example
 2241: 
 2242: @c !! example
 2243: 
 2244: Reference: @ref{Calls and returns}, @ref{Counted Loops}.
 2245: 
 2246: 
 2247: @node Return Stack Tutorial, Memory Tutorial, Leaving definitions or loops Tutorial, Tutorial
 2248: @section Return Stack
 2249: @cindex return stack tutorial
 2250: 
 2251: In addition to the data stack Forth also has a second stack, the return
 2252: stack; most Forth systems store the return addresses of procedure calls
 2253: there (thus its name).  Programmers can also use this stack:
 2254: 
 2255: @example
 2256: : foo ( n1 n2 -- )
 2257:  .s
 2258:  >r .s
 2259:  r@@ .
 2260:  >r .s
 2261:  r@@ .
 2262:  r> .
 2263:  r@@ .
 2264:  r> . ;
 2265: 1 2 foo
 2266: @end example
 2267: 
 2268: @code{>r} takes an element from the data stack and pushes it onto the
 2269: return stack; conversely, @code{r>} moves an elementm from the return to
 2270: the data stack; @code{r@@} pushes a copy of the top of the return stack
 2271: on the data stack.
 2272: 
 2273: Forth programmers usually use the return stack for storing data
 2274: temporarily, if using the data stack alone would be too complex, and
 2275: factoring and locals are not an option:
 2276: 
 2277: @example
 2278: : 2swap ( x1 x2 x3 x4 -- x3 x4 x1 x2 )
 2279:  rot >r rot r> ;
 2280: @end example
 2281: 
 2282: The return address of the definition and the loop control parameters of
 2283: counted loops usually reside on the return stack, so you have to take
 2284: all items, that you have pushed on the return stack in a colon
 2285: definition or counted loop, from the return stack before the definition
 2286: or loop ends.  You cannot access items that you pushed on the return
 2287: stack outside some definition or loop within the definition of loop.
 2288: 
 2289: If you miscount the return stack items, this usually ends in a crash:
 2290: 
 2291: @example
 2292: : crash ( n -- )
 2293:   >r ;
 2294: 5 crash
 2295: @end example
 2296: 
 2297: You cannot mix using locals and using the return stack (according to the
 2298: standard; Gforth has no problem).  However, they solve the same
 2299: problems, so this shouldn't be an issue.
 2300: 
 2301: @quotation Assignment
 2302: Can you rewrite any of the definitions you wrote until now in a better
 2303: way using the return stack?
 2304: @end quotation
 2305: 
 2306: Reference: @ref{Return stack}.
 2307: 
 2308: 
 2309: @node Memory Tutorial, Characters and Strings Tutorial, Return Stack Tutorial, Tutorial
 2310: @section Memory
 2311: @cindex memory access/allocation tutorial
 2312: 
 2313: You can create a global variable @code{v} with
 2314: 
 2315: @example
 2316: variable v ( -- addr )
 2317: @end example
 2318: 
 2319: @code{v} pushes the address of a cell in memory on the stack.  This cell
 2320: was reserved by @code{variable}.  You can use @code{!} (store) to store
 2321: values into this cell and @code{@@} (fetch) to load the value from the
 2322: stack into memory:
 2323: 
 2324: @example
 2325: v .
 2326: 5 v ! .s
 2327: v @@ .
 2328: @end example
 2329: 
 2330: You can see a raw dump of memory with @code{dump}:
 2331: 
 2332: @example
 2333: v 1 cells .s dump
 2334: @end example
 2335: 
 2336: @code{Cells ( n1 -- n2 )} gives you the number of bytes (or, more
 2337: generally, address units (aus)) that @code{n1 cells} occupy.  You can
 2338: also reserve more memory:
 2339: 
 2340: @example
 2341: create v2 20 cells allot
 2342: v2 20 cells dump
 2343: @end example
 2344: 
 2345: creates a word @code{v2} and reserves 20 uninitialized cells; the
 2346: address pushed by @code{v2} points to the start of these 20 cells.  You
 2347: can use address arithmetic to access these cells:
 2348: 
 2349: @example
 2350: 3 v2 5 cells + !
 2351: v2 20 cells dump
 2352: @end example
 2353: 
 2354: You can reserve and initialize memory with @code{,}:
 2355: 
 2356: @example
 2357: create v3
 2358:   5 , 4 , 3 , 2 , 1 ,
 2359: v3 @@ .
 2360: v3 cell+ @@ .
 2361: v3 2 cells + @@ .
 2362: v3 5 cells dump
 2363: @end example
 2364: 
 2365: @quotation Assignment
 2366: Write a definition @code{vsum ( addr u -- n )} that computes the sum of
 2367: @code{u} cells, with the first of these cells at @code{addr}, the next
 2368: one at @code{addr cell+} etc.
 2369: @end quotation
 2370: 
 2371: You can also reserve memory without creating a new word:
 2372: 
 2373: @example
 2374: here 10 cells allot .
 2375: here .
 2376: @end example
 2377: 
 2378: @code{Here} pushes the start address of the memory area.  You should
 2379: store it somewhere, or you will have a hard time finding the memory area
 2380: again.
 2381: 
 2382: @code{Allot} manages dictionary memory.  The dictionary memory contains
 2383: the system's data structures for words etc. on Gforth and most other
 2384: Forth systems.  It is managed like a stack: You can free the memory that
 2385: you have just @code{allot}ed with
 2386: 
 2387: @example
 2388: -10 cells allot
 2389: here .
 2390: @end example
 2391: 
 2392: Note that you cannot do this if you have created a new word in the
 2393: meantime (because then your @code{allot}ed memory is no longer on the
 2394: top of the dictionary ``stack'').
 2395: 
 2396: Alternatively, you can use @code{allocate} and @code{free} which allow
 2397: freeing memory in any order:
 2398: 
 2399: @example
 2400: 10 cells allocate throw .s
 2401: 20 cells allocate throw .s
 2402: swap
 2403: free throw
 2404: free throw
 2405: @end example
 2406: 
 2407: The @code{throw}s deal with errors (e.g., out of memory).
 2408: 
 2409: And there is also a
 2410: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
 2411: garbage collector}, which eliminates the need to @code{free} memory
 2412: explicitly.
 2413: 
 2414: Reference: @ref{Memory}.
 2415: 
 2416: 
 2417: @node Characters and Strings Tutorial, Alignment Tutorial, Memory Tutorial, Tutorial
 2418: @section Characters and Strings
 2419: @cindex strings tutorial
 2420: @cindex characters tutorial
 2421: 
 2422: On the stack characters take up a cell, like numbers.  In memory they
 2423: have their own size (one 8-bit byte on most systems), and therefore
 2424: require their own words for memory access:
 2425: 
 2426: @example
 2427: create v4 
 2428:   104 c, 97 c, 108 c, 108 c, 111 c,
 2429: v4 4 chars + c@@ .
 2430: v4 5 chars dump
 2431: @end example
 2432: 
 2433: The preferred representation of strings on the stack is @code{addr
 2434: u-count}, where @code{addr} is the address of the first character and
 2435: @code{u-count} is the number of characters in the string.
 2436: 
 2437: @example
 2438: v4 5 type
 2439: @end example
 2440: 
 2441: You get a string constant with
 2442: 
 2443: @example
 2444: s" hello, world" .s
 2445: type
 2446: @end example
 2447: 
 2448: Make sure you have a space between @code{s"} and the string; @code{s"}
 2449: is a normal Forth word and must be delimited with white space (try what
 2450: happens when you remove the space).
 2451: 
 2452: However, this interpretive use of @code{s"} is quite restricted: the
 2453: string exists only until the next call of @code{s"} (some Forth systems
 2454: keep more than one of these strings, but usually they still have a
 2455: limited lifetime).
 2456: 
 2457: @example
 2458: s" hello," s" world" .s
 2459: type
 2460: type
 2461: @end example
 2462: 
 2463: You can also use @code{s"} in a definition, and the resulting
 2464: strings then live forever (well, for as long as the definition):
 2465: 
 2466: @example
 2467: : foo s" hello," s" world" ;
 2468: foo .s
 2469: type
 2470: type
 2471: @end example
 2472: 
 2473: @quotation Assignment
 2474: @code{Emit ( c -- )} types @code{c} as character (not a number).
 2475: Implement @code{type ( addr u -- )}.
 2476: @end quotation
 2477: 
 2478: Reference: @ref{Memory Blocks}.
 2479: 
 2480: 
 2481: @node Alignment Tutorial, Floating Point Tutorial, Characters and Strings Tutorial, Tutorial
 2482: @section Alignment
 2483: @cindex alignment tutorial
 2484: @cindex memory alignment tutorial
 2485: 
 2486: On many processors cells have to be aligned in memory, if you want to
 2487: access them with @code{@@} and @code{!} (and even if the processor does
 2488: not require alignment, access to aligned cells is faster).
 2489: 
 2490: @code{Create} aligns @code{here} (i.e., the place where the next
 2491: allocation will occur, and that the @code{create}d word points to).
 2492: Likewise, the memory produced by @code{allocate} starts at an aligned
 2493: address.  Adding a number of @code{cells} to an aligned address produces
 2494: another aligned address.
 2495: 
 2496: However, address arithmetic involving @code{char+} and @code{chars} can
 2497: create an address that is not cell-aligned.  @code{Aligned ( addr --
 2498: a-addr )} produces the next aligned address:
 2499: 
 2500: @example
 2501: v3 char+ aligned .s @@ .
 2502: v3 char+ .s @@ .
 2503: @end example
 2504: 
 2505: Similarly, @code{align} advances @code{here} to the next aligned
 2506: address:
 2507: 
 2508: @example
 2509: create v5 97 c,
 2510: here .
 2511: align here .
 2512: 1000 ,
 2513: @end example
 2514: 
 2515: Note that you should use aligned addresses even if your processor does
 2516: not require them, if you want your program to be portable.
 2517: 
 2518: Reference: @ref{Address arithmetic}.
 2519: 
 2520: @node Floating Point Tutorial, Files Tutorial, Alignment Tutorial, Tutorial
 2521: @section Floating Point
 2522: @cindex floating point tutorial
 2523: @cindex FP tutorial
 2524: 
 2525: Floating-point (FP) numbers and arithmetic in Forth works mostly as one
 2526: might expect, but there are a few things worth noting:
 2527: 
 2528: The first point is not specific to Forth, but so important and yet not
 2529: universally known that I mention it here: FP numbers are not reals.
 2530: Many properties (e.g., arithmetic laws) that reals have and that one
 2531: expects of all kinds of numbers do not hold for FP numbers.  If you
 2532: want to use FP computations, you should learn about their problems and
 2533: how to avoid them; a good starting point is @cite{David Goldberg,
 2534: @uref{http://docs.sun.com/source/806-3568/ncg_goldberg.html,What Every
 2535: Computer Scientist Should Know About Floating-Point Arithmetic}, ACM
 2536: Computing Surveys 23(1):5@minus{}48, March 1991}.
 2537: 
 2538: In Forth source code literal FP numbers need an exponent, e.g.,
 2539: @code{1e0}; this can also be written shorter as @code{1e},
 2540: @code{+1.0e+0}, and many variations in between.  The reason for this
 2541: is that, for historical reasons, Forth interprets a decimal point
 2542: alone (e.g., @code{1.}) as indicating a double-cell integer.  Another
 2543: requirement for literal FP numbers is that the current base is
 2544: decimal; with a hex base @code{1e} is interpreted as an integer.
 2545: 
 2546: Forth has a separate stack for FP numbers.@footnote{Theoretically, an
 2547: ANS Forth system may implement the FP stack on the data stack, but
 2548: virtually all systems implement a separate FP stack; and programming
 2549: in a way that accommodates all models is so cumbersome that nobody
 2550: does it.}  One advantage of this model is that cells are not in the
 2551: way when accessing FP values, and vice versa.  Forth has a set of
 2552: words for manipulating the FP stack: @code{fdup fswap fdrop fover
 2553: frot} and (non-standard) @code{fnip ftuck fpick}.
 2554: 
 2555: FP arithmetic words are prefixed with @code{F}.  There is the usual
 2556: set @code{f+ f- f* f/ f** fnegate} as well as a number of words for
 2557: other functions, e.g., @code{fsqrt fsin fln fmin}.  One word that you
 2558: might expect is @code{f=}; but @code{f=} is non-standard, because FP
 2559: computation results are usually inaccurate, so exact comparison is
 2560: usually a mistake, and one should use approximate comparison.
 2561: Unfortunately, @code{f~}, the standard word for that purpose, is not
 2562: well designed, so Gforth provides @code{f~abs} and @code{f~rel} as
 2563: well.
 2564: 
 2565: And of course there are words for accessing FP numbers in memory
 2566: (@code{f@@ f!}), and for address arithmetic (@code{floats float+
 2567: faligned}).  There are also variants of these words with an @code{sf}
 2568: and @code{df} prefix for accessing IEEE format single-precision and
 2569: double-precision numbers in memory; their main purpose is for
 2570: accessing external FP data (e.g., that has been read from or will be
 2571: written to a file).
 2572: 
 2573: Here is an example of a dot-product word and its use:
 2574: 
 2575: @example
 2576: : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
 2577:   >r swap 2swap swap 0e r> 0 ?DO
 2578:     dup f@@ over + 2swap dup f@@ f* f+ over + 2swap
 2579:   LOOP
 2580:   2drop 2drop ;
 2581: 
 2582: create v 1.23e f, 4.56e f, 7.89e f,
 2583: 
 2584: v 1 floats  v 1 floats  3  v* f.
 2585: @end example
 2586: 
 2587: @quotation Assignment
 2588: Write a program to solve a quadratic equation.  Then read @cite{Henry
 2589: G. Baker,
 2590: @uref{http://home.pipeline.com/~hbaker1/sigplannotices/sigcol05.ps.gz,You
 2591: Could Learn a Lot from a Quadratic}, ACM SIGPLAN Notices,
 2592: 33(1):30@minus{}39, January 1998}, and see if you can improve your
 2593: program.  Finally, find a test case where the original and the
 2594: improved version produce different results.
 2595: @end quotation
 2596: 
 2597: Reference: @ref{Floating Point}; @ref{Floating point stack};
 2598: @ref{Number Conversion}; @ref{Memory Access}; @ref{Address
 2599: arithmetic}.
 2600: 
 2601: @node Files Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Floating Point Tutorial, Tutorial
 2602: @section Files
 2603: @cindex files tutorial
 2604: 
 2605: This section gives a short introduction into how to use files inside
 2606: Forth. It's broken up into five easy steps:
 2607: 
 2608: @enumerate 1
 2609: @item Opened an ASCII text file for input
 2610: @item Opened a file for output
 2611: @item Read input file until string matched (or some other condition matched)
 2612: @item Wrote some lines from input ( modified or not) to output
 2613: @item Closed the files.
 2614: @end enumerate
 2615: 
 2616: Reference: @ref{General files}.
 2617: 
 2618: @subsection Open file for input
 2619: 
 2620: @example
 2621: s" foo.in"  r/o open-file throw Value fd-in
 2622: @end example
 2623: 
 2624: @subsection Create file for output
 2625: 
 2626: @example
 2627: s" foo.out" w/o create-file throw Value fd-out
 2628: @end example
 2629: 
 2630: The available file modes are r/o for read-only access, r/w for
 2631: read-write access, and w/o for write-only access. You could open both
 2632: files with r/w, too, if you like. All file words return error codes; for
 2633: most applications, it's best to pass there error codes with @code{throw}
 2634: to the outer error handler.
 2635: 
 2636: If you want words for opening and assigning, define them as follows:
 2637: 
 2638: @example
 2639: 0 Value fd-in
 2640: 0 Value fd-out
 2641: : open-input ( addr u -- )  r/o open-file throw to fd-in ;
 2642: : open-output ( addr u -- )  w/o create-file throw to fd-out ;
 2643: @end example
 2644: 
 2645: Usage example:
 2646: 
 2647: @example
 2648: s" foo.in" open-input
 2649: s" foo.out" open-output
 2650: @end example
 2651: 
 2652: @subsection Scan file for a particular line
 2653: 
 2654: @example
 2655: 256 Constant max-line
 2656: Create line-buffer  max-line 2 + allot
 2657: 
 2658: : scan-file ( addr u -- )
 2659:   begin
 2660:       line-buffer max-line fd-in read-line throw
 2661:   while
 2662:          >r 2dup line-buffer r> compare 0=
 2663:      until
 2664:   else
 2665:      drop
 2666:   then
 2667:   2drop ;
 2668: @end example
 2669: 
 2670: @code{read-line ( addr u1 fd -- u2 flag ior )} reads up to u1 bytes into
 2671: the buffer at addr, and returns the number of bytes read, a flag that is
 2672: false when the end of file is reached, and an error code.
 2673: 
 2674: @code{compare ( addr1 u1 addr2 u2 -- n )} compares two strings and
 2675: returns zero if both strings are equal. It returns a positive number if
 2676: the first string is lexically greater, a negative if the second string
 2677: is lexically greater.
 2678: 
 2679: We haven't seen this loop here; it has two exits. Since the @code{while}
 2680: exits with the number of bytes read on the stack, we have to clean up
 2681: that separately; that's after the @code{else}.
 2682: 
 2683: Usage example:
 2684: 
 2685: @example
 2686: s" The text I search is here" scan-file
 2687: @end example
 2688: 
 2689: @subsection Copy input to output
 2690: 
 2691: @example
 2692: : copy-file ( -- )
 2693:   begin
 2694:       line-buffer max-line fd-in read-line throw
 2695:   while
 2696:       line-buffer swap fd-out write-line throw
 2697:   repeat ;
 2698: @end example
 2699: @c !! does not handle long lines, no newline at end of file
 2700: 
 2701: @subsection Close files
 2702: 
 2703: @example
 2704: fd-in close-file throw
 2705: fd-out close-file throw
 2706: @end example
 2707: 
 2708: Likewise, you can put that into definitions, too:
 2709: 
 2710: @example
 2711: : close-input ( -- )  fd-in close-file throw ;
 2712: : close-output ( -- )  fd-out close-file throw ;
 2713: @end example
 2714: 
 2715: @quotation Assignment
 2716: How could you modify @code{copy-file} so that it copies until a second line is
 2717: matched? Can you write a program that extracts a section of a text file,
 2718: given the line that starts and the line that terminates that section?
 2719: @end quotation
 2720: 
 2721: @node Interpretation and Compilation Semantics and Immediacy Tutorial, Execution Tokens Tutorial, Files Tutorial, Tutorial
 2722: @section Interpretation and Compilation Semantics and Immediacy
 2723: @cindex semantics tutorial
 2724: @cindex interpretation semantics tutorial
 2725: @cindex compilation semantics tutorial
 2726: @cindex immediate, tutorial
 2727: 
 2728: When a word is compiled, it behaves differently from being interpreted.
 2729: E.g., consider @code{+}:
 2730: 
 2731: @example
 2732: 1 2 + .
 2733: : foo + ;
 2734: @end example
 2735: 
 2736: These two behaviours are known as compilation and interpretation
 2737: semantics.  For normal words (e.g., @code{+}), the compilation semantics
 2738: is to append the interpretation semantics to the currently defined word
 2739: (@code{foo} in the example above).  I.e., when @code{foo} is executed
 2740: later, the interpretation semantics of @code{+} (i.e., adding two
 2741: numbers) will be performed.
 2742: 
 2743: However, there are words with non-default compilation semantics, e.g.,
 2744: the control-flow words like @code{if}.  You can use @code{immediate} to
 2745: change the compilation semantics of the last defined word to be equal to
 2746: the interpretation semantics:
 2747: 
 2748: @example
 2749: : [FOO] ( -- )
 2750:  5 . ; immediate
 2751: 
 2752: [FOO]
 2753: : bar ( -- )
 2754:   [FOO] ;
 2755: bar
 2756: see bar
 2757: @end example
 2758: 
 2759: Two conventions to mark words with non-default compilation semantics are
 2760: names with brackets (more frequently used) and to write them all in
 2761: upper case (less frequently used).
 2762: 
 2763: In Gforth (and many other systems) you can also remove the
 2764: interpretation semantics with @code{compile-only} (the compilation
 2765: semantics is derived from the original interpretation semantics):
 2766: 
 2767: @example
 2768: : flip ( -- )
 2769:  6 . ; compile-only \ but not immediate
 2770: flip
 2771: 
 2772: : flop ( -- )
 2773:  flip ;
 2774: flop
 2775: @end example
 2776: 
 2777: In this example the interpretation semantics of @code{flop} is equal to
 2778: the original interpretation semantics of @code{flip}.
 2779: 
 2780: The text interpreter has two states: in interpret state, it performs the
 2781: interpretation semantics of words it encounters; in compile state, it
 2782: performs the compilation semantics of these words.
 2783: 
 2784: Among other things, @code{:} switches into compile state, and @code{;}
 2785: switches back to interpret state.  They contain the factors @code{]}
 2786: (switch to compile state) and @code{[} (switch to interpret state), that
 2787: do nothing but switch the state.
 2788: 
 2789: @example
 2790: : xxx ( -- )
 2791:   [ 5 . ]
 2792: ;
 2793: 
 2794: xxx
 2795: see xxx
 2796: @end example
 2797: 
 2798: These brackets are also the source of the naming convention mentioned
 2799: above.
 2800: 
 2801: Reference: @ref{Interpretation and Compilation Semantics}.
 2802: 
 2803: 
 2804: @node Execution Tokens Tutorial, Exceptions Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Tutorial
 2805: @section Execution Tokens
 2806: @cindex execution tokens tutorial
 2807: @cindex XT tutorial
 2808: 
 2809: @code{' word} gives you the execution token (XT) of a word.  The XT is a
 2810: cell representing the interpretation semantics of a word.  You can
 2811: execute this semantics with @code{execute}:
 2812: 
 2813: @example
 2814: ' + .s
 2815: 1 2 rot execute .
 2816: @end example
 2817: 
 2818: The XT is similar to a function pointer in C.  However, parameter
 2819: passing through the stack makes it a little more flexible:
 2820: 
 2821: @example
 2822: : map-array ( ... addr u xt -- ... )
 2823: \ executes xt ( ... x -- ... ) for every element of the array starting
 2824: \ at addr and containing u elements
 2825:   @{ xt @}
 2826:   cells over + swap ?do
 2827:     i @@ xt execute
 2828:   1 cells +loop ;
 2829: 
 2830: create a 3 , 4 , 2 , -1 , 4 ,
 2831: a 5 ' . map-array .s
 2832: 0 a 5 ' + map-array .
 2833: s" max-n" environment? drop .s
 2834: a 5 ' min map-array .
 2835: @end example
 2836: 
 2837: You can use map-array with the XTs of words that consume one element
 2838: more than they produce.  In theory you can also use it with other XTs,
 2839: but the stack effect then depends on the size of the array, which is
 2840: hard to understand.
 2841: 
 2842: Since XTs are cell-sized, you can store them in memory and manipulate
 2843: them on the stack like other cells.  You can also compile the XT into a
 2844: word with @code{compile,}:
 2845: 
 2846: @example
 2847: : foo1 ( n1 n2 -- n )
 2848:    [ ' + compile, ] ;
 2849: see foo
 2850: @end example
 2851: 
 2852: This is non-standard, because @code{compile,} has no compilation
 2853: semantics in the standard, but it works in good Forth systems.  For the
 2854: broken ones, use
 2855: 
 2856: @example
 2857: : [compile,] compile, ; immediate
 2858: 
 2859: : foo1 ( n1 n2 -- n )
 2860:    [ ' + ] [compile,] ;
 2861: see foo
 2862: @end example
 2863: 
 2864: @code{'} is a word with default compilation semantics; it parses the
 2865: next word when its interpretation semantics are executed, not during
 2866: compilation:
 2867: 
 2868: @example
 2869: : foo ( -- xt )
 2870:   ' ;
 2871: see foo
 2872: : bar ( ... "word" -- ... )
 2873:   ' execute ;
 2874: see bar
 2875: 1 2 bar + .
 2876: @end example
 2877: 
 2878: You often want to parse a word during compilation and compile its XT so
 2879: it will be pushed on the stack at run-time.  @code{[']} does this:
 2880: 
 2881: @example
 2882: : xt-+ ( -- xt )
 2883:   ['] + ;
 2884: see xt-+
 2885: 1 2 xt-+ execute .
 2886: @end example
 2887: 
 2888: Many programmers tend to see @code{'} and the word it parses as one
 2889: unit, and expect it to behave like @code{[']} when compiled, and are
 2890: confused by the actual behaviour.  If you are, just remember that the
 2891: Forth system just takes @code{'} as one unit and has no idea that it is
 2892: a parsing word (attempts to convenience programmers in this issue have
 2893: usually resulted in even worse pitfalls, see
 2894: @uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,
 2895: @code{State}-smartness---Why it is evil and How to Exorcise it}).
 2896: 
 2897: Note that the state of the interpreter does not come into play when
 2898: creating and executing XTs.  I.e., even when you execute @code{'} in
 2899: compile state, it still gives you the interpretation semantics.  And
 2900: whatever that state is, @code{execute} performs the semantics
 2901: represented by the XT (i.e., for XTs produced with @code{'} the
 2902: interpretation semantics).
 2903: 
 2904: Reference: @ref{Tokens for Words}.
 2905: 
 2906: 
 2907: @node Exceptions Tutorial, Defining Words Tutorial, Execution Tokens Tutorial, Tutorial
 2908: @section Exceptions
 2909: @cindex exceptions tutorial
 2910: 
 2911: @code{throw ( n -- )} causes an exception unless n is zero.
 2912: 
 2913: @example
 2914: 100 throw .s
 2915: 0 throw .s
 2916: @end example
 2917: 
 2918: @code{catch ( ... xt -- ... n )} behaves similar to @code{execute}, but
 2919: it catches exceptions and pushes the number of the exception on the
 2920: stack (or 0, if the xt executed without exception).  If there was an
 2921: exception, the stacks have the same depth as when entering @code{catch}:
 2922: 
 2923: @example
 2924: .s
 2925: 3 0 ' / catch .s
 2926: 3 2 ' / catch .s
 2927: @end example
 2928: 
 2929: @quotation Assignment
 2930: Try the same with @code{execute} instead of @code{catch}.
 2931: @end quotation
 2932: 
 2933: @code{Throw} always jumps to the dynamically next enclosing
 2934: @code{catch}, even if it has to leave several call levels to achieve
 2935: this:
 2936: 
 2937: @example
 2938: : foo 100 throw ;
 2939: : foo1 foo ." after foo" ;
 2940: : bar ['] foo1 catch ;
 2941: bar .
 2942: @end example
 2943: 
 2944: It is often important to restore a value upon leaving a definition, even
 2945: if the definition is left through an exception.  You can ensure this
 2946: like this:
 2947: 
 2948: @example
 2949: : ...
 2950:    save-x
 2951:    ['] word-changing-x catch ( ... n )
 2952:    restore-x
 2953:    ( ... n ) throw ;
 2954: @end example
 2955: 
 2956: However, this is still not safe against, e.g., the user pressing
 2957: @kbd{Ctrl-C} when execution is between the @code{catch} and
 2958: @code{restore-x}.
 2959: 
 2960: Gforth provides an alternative exception handling syntax that is safe
 2961: against such cases: @code{try ... restore ... endtry}.  If the code
 2962: between @code{try} and @code{endtry} has an exception, the stack
 2963: depths are restored, the exception number is pushed on the stack, and
 2964: the execution continues right after @code{restore}.
 2965: 
 2966: The safer equivalent to the restoration code above is
 2967: 
 2968: @example
 2969: : ...
 2970:   save-x
 2971:   try
 2972:     word-changing-x 0
 2973:   restore
 2974:     restore-x
 2975:   endtry
 2976:   throw ;
 2977: @end example
 2978: 
 2979: Reference: @ref{Exception Handling}.
 2980: 
 2981: 
 2982: @node Defining Words Tutorial, Arrays and Records Tutorial, Exceptions Tutorial, Tutorial
 2983: @section Defining Words
 2984: @cindex defining words tutorial
 2985: @cindex does> tutorial
 2986: @cindex create...does> tutorial
 2987: 
 2988: @c before semantics?
 2989: 
 2990: @code{:}, @code{create}, and @code{variable} are definition words: They
 2991: define other words.  @code{Constant} is another definition word:
 2992: 
 2993: @example
 2994: 5 constant foo
 2995: foo .
 2996: @end example
 2997: 
 2998: You can also use the prefixes @code{2} (double-cell) and @code{f}
 2999: (floating point) with @code{variable} and @code{constant}.
 3000: 
 3001: You can also define your own defining words.  E.g.:
 3002: 
 3003: @example
 3004: : variable ( "name" -- )
 3005:   create 0 , ;
 3006: @end example
 3007: 
 3008: You can also define defining words that create words that do something
 3009: other than just producing their address:
 3010: 
 3011: @example
 3012: : constant ( n "name" -- )
 3013:   create ,
 3014: does> ( -- n )
 3015:   ( addr ) @@ ;
 3016: 
 3017: 5 constant foo
 3018: foo .
 3019: @end example
 3020: 
 3021: The definition of @code{constant} above ends at the @code{does>}; i.e.,
 3022: @code{does>} replaces @code{;}, but it also does something else: It
 3023: changes the last defined word such that it pushes the address of the
 3024: body of the word and then performs the code after the @code{does>}
 3025: whenever it is called.
 3026: 
 3027: In the example above, @code{constant} uses @code{,} to store 5 into the
 3028: body of @code{foo}.  When @code{foo} executes, it pushes the address of
 3029: the body onto the stack, then (in the code after the @code{does>})
 3030: fetches the 5 from there.
 3031: 
 3032: The stack comment near the @code{does>} reflects the stack effect of the
 3033: defined word, not the stack effect of the code after the @code{does>}
 3034: (the difference is that the code expects the address of the body that
 3035: the stack comment does not show).
 3036: 
 3037: You can use these definition words to do factoring in cases that involve
 3038: (other) definition words.  E.g., a field offset is always added to an
 3039: address.  Instead of defining
 3040: 
 3041: @example
 3042: 2 cells constant offset-field1
 3043: @end example
 3044: 
 3045: and using this like
 3046: 
 3047: @example
 3048: ( addr ) offset-field1 +
 3049: @end example
 3050: 
 3051: you can define a definition word
 3052: 
 3053: @example
 3054: : simple-field ( n "name" -- )
 3055:   create ,
 3056: does> ( n1 -- n1+n )
 3057:   ( addr ) @@ + ;
 3058: @end example
 3059: 
 3060: Definition and use of field offsets now look like this:
 3061: 
 3062: @example
 3063: 2 cells simple-field field1
 3064: create mystruct 4 cells allot
 3065: mystruct .s field1 .s drop
 3066: @end example
 3067: 
 3068: If you want to do something with the word without performing the code
 3069: after the @code{does>}, you can access the body of a @code{create}d word
 3070: with @code{>body ( xt -- addr )}:
 3071: 
 3072: @example
 3073: : value ( n "name" -- )
 3074:   create ,
 3075: does> ( -- n1 )
 3076:   @@ ;
 3077: : to ( n "name" -- )
 3078:   ' >body ! ;
 3079: 
 3080: 5 value foo
 3081: foo .
 3082: 7 to foo
 3083: foo .
 3084: @end example
 3085: 
 3086: @quotation Assignment
 3087: Define @code{defer ( "name" -- )}, which creates a word that stores an
 3088: XT (at the start the XT of @code{abort}), and upon execution
 3089: @code{execute}s the XT.  Define @code{is ( xt "name" -- )} that stores
 3090: @code{xt} into @code{name}, a word defined with @code{defer}.  Indirect
 3091: recursion is one application of @code{defer}.
 3092: @end quotation
 3093: 
 3094: Reference: @ref{User-defined Defining Words}.
 3095: 
 3096: 
 3097: @node Arrays and Records Tutorial, POSTPONE Tutorial, Defining Words Tutorial, Tutorial
 3098: @section Arrays and Records
 3099: @cindex arrays tutorial
 3100: @cindex records tutorial
 3101: @cindex structs tutorial
 3102: 
 3103: Forth has no standard words for defining data structures such as arrays
 3104: and records (structs in C terminology), but you can build them yourself
 3105: based on address arithmetic.  You can also define words for defining
 3106: arrays and records (@pxref{Defining Words Tutorial,, Defining Words}).
 3107: 
 3108: One of the first projects a Forth newcomer sets out upon when learning
 3109: about defining words is an array defining word (possibly for
 3110: n-dimensional arrays).  Go ahead and do it, I did it, too; you will
 3111: learn something from it.  However, don't be disappointed when you later
 3112: learn that you have little use for these words (inappropriate use would
 3113: be even worse).  I have not found a set of useful array words yet;
 3114: the needs are just too diverse, and named, global arrays (the result of
 3115: naive use of defining words) are often not flexible enough (e.g.,
 3116: consider how to pass them as parameters).  Another such project is a set
 3117: of words to help dealing with strings.
 3118: 
 3119: On the other hand, there is a useful set of record words, and it has
 3120: been defined in @file{compat/struct.fs}; these words are predefined in
 3121: Gforth.  They are explained in depth elsewhere in this manual (see
 3122: @pxref{Structures}).  The @code{simple-field} example above is
 3123: simplified variant of fields in this package.
 3124: 
 3125: 
 3126: @node POSTPONE Tutorial, Literal Tutorial, Arrays and Records Tutorial, Tutorial
 3127: @section @code{POSTPONE}
 3128: @cindex postpone tutorial
 3129: 
 3130: You can compile the compilation semantics (instead of compiling the
 3131: interpretation semantics) of a word with @code{POSTPONE}:
 3132: 
 3133: @example
 3134: : MY-+ ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
 3135:  POSTPONE + ; immediate
 3136: : foo ( n1 n2 -- n )
 3137:  MY-+ ;
 3138: 1 2 foo .
 3139: see foo
 3140: @end example
 3141: 
 3142: During the definition of @code{foo} the text interpreter performs the
 3143: compilation semantics of @code{MY-+}, which performs the compilation
 3144: semantics of @code{+}, i.e., it compiles @code{+} into @code{foo}.
 3145: 
 3146: This example also displays separate stack comments for the compilation
 3147: semantics and for the stack effect of the compiled code.  For words with
 3148: default compilation semantics these stack effects are usually not
 3149: displayed; the stack effect of the compilation semantics is always
 3150: @code{( -- )} for these words, the stack effect for the compiled code is
 3151: the stack effect of the interpretation semantics.
 3152: 
 3153: Note that the state of the interpreter does not come into play when
 3154: performing the compilation semantics in this way.  You can also perform
 3155: it interpretively, e.g.:
 3156: 
 3157: @example
 3158: : foo2 ( n1 n2 -- n )
 3159:  [ MY-+ ] ;
 3160: 1 2 foo .
 3161: see foo
 3162: @end example
 3163: 
 3164: However, there are some broken Forth systems where this does not always
 3165: work, and therefore this practice was been declared non-standard in
 3166: 1999.
 3167: @c !! repair.fs
 3168: 
 3169: Here is another example for using @code{POSTPONE}:
 3170: 
 3171: @example
 3172: : MY-- ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
 3173:  POSTPONE negate POSTPONE + ; immediate compile-only
 3174: : bar ( n1 n2 -- n )
 3175:   MY-- ;
 3176: 2 1 bar .
 3177: see bar
 3178: @end example
 3179: 
 3180: You can define @code{ENDIF} in this way:
 3181: 
 3182: @example
 3183: : ENDIF ( Compilation: orig -- )
 3184:   POSTPONE then ; immediate
 3185: @end example
 3186: 
 3187: @quotation Assignment
 3188: Write @code{MY-2DUP} that has compilation semantics equivalent to
 3189: @code{2dup}, but compiles @code{over over}.
 3190: @end quotation
 3191: 
 3192: @c !! @xref{Macros} for reference
 3193: 
 3194: 
 3195: @node Literal Tutorial, Advanced macros Tutorial, POSTPONE Tutorial, Tutorial
 3196: @section @code{Literal}
 3197: @cindex literal tutorial
 3198: 
 3199: You cannot @code{POSTPONE} numbers:
 3200: 
 3201: @example
 3202: : [FOO] POSTPONE 500 ; immediate
 3203: @end example
 3204: 
 3205: Instead, you can use @code{LITERAL (compilation: n --; run-time: -- n )}:
 3206: 
 3207: @example
 3208: : [FOO] ( compilation: --; run-time: -- n )
 3209:   500 POSTPONE literal ; immediate
 3210: 
 3211: : flip [FOO] ;
 3212: flip .
 3213: see flip
 3214: @end example
 3215: 
 3216: @code{LITERAL} consumes a number at compile-time (when it's compilation
 3217: semantics are executed) and pushes it at run-time (when the code it
 3218: compiled is executed).  A frequent use of @code{LITERAL} is to compile a
 3219: number computed at compile time into the current word:
 3220: 
 3221: @example
 3222: : bar ( -- n )
 3223:   [ 2 2 + ] literal ;
 3224: see bar
 3225: @end example
 3226: 
 3227: @quotation Assignment
 3228: Write @code{]L} which allows writing the example above as @code{: bar (
 3229: -- n ) [ 2 2 + ]L ;}
 3230: @end quotation
 3231: 
 3232: @c !! @xref{Macros} for reference
 3233: 
 3234: 
 3235: @node Advanced macros Tutorial, Compilation Tokens Tutorial, Literal Tutorial, Tutorial
 3236: @section Advanced macros
 3237: @cindex macros, advanced tutorial
 3238: @cindex run-time code generation, tutorial
 3239: 
 3240: Reconsider @code{map-array} from @ref{Execution Tokens Tutorial,,
 3241: Execution Tokens}.  It frequently performs @code{execute}, a relatively
 3242: expensive operation in some Forth implementations.  You can use
 3243: @code{compile,} and @code{POSTPONE} to eliminate these @code{execute}s
 3244: and produce a word that contains the word to be performed directly:
 3245: 
 3246: @c use ]] ... [[
 3247: @example
 3248: : compile-map-array ( compilation: xt -- ; run-time: ... addr u -- ... )
 3249: \ at run-time, execute xt ( ... x -- ... ) for each element of the
 3250: \ array beginning at addr and containing u elements
 3251:   @{ xt @}
 3252:   POSTPONE cells POSTPONE over POSTPONE + POSTPONE swap POSTPONE ?do
 3253:     POSTPONE i POSTPONE @@ xt compile,
 3254:   1 cells POSTPONE literal POSTPONE +loop ;
 3255: 
 3256: : sum-array ( addr u -- n )
 3257:  0 rot rot [ ' + compile-map-array ] ;
 3258: see sum-array
 3259: a 5 sum-array .
 3260: @end example
 3261: 
 3262: You can use the full power of Forth for generating the code; here's an
 3263: example where the code is generated in a loop:
 3264: 
 3265: @example
 3266: : compile-vmul-step ( compilation: n --; run-time: n1 addr1 -- n2 addr2 )
 3267: \ n2=n1+(addr1)*n, addr2=addr1+cell
 3268:   POSTPONE tuck POSTPONE @@
 3269:   POSTPONE literal POSTPONE * POSTPONE +
 3270:   POSTPONE swap POSTPONE cell+ ;
 3271: 
 3272: : compile-vmul ( compilation: addr1 u -- ; run-time: addr2 -- n )
 3273: \ n=v1*v2 (inner product), where the v_i are represented as addr_i u
 3274:   0 postpone literal postpone swap
 3275:   [ ' compile-vmul-step compile-map-array ]
 3276:   postpone drop ;
 3277: see compile-vmul
 3278: 
 3279: : a-vmul ( addr -- n )
 3280: \ n=a*v, where v is a vector that's as long as a and starts at addr
 3281:  [ a 5 compile-vmul ] ;
 3282: see a-vmul
 3283: a a-vmul .
 3284: @end example
 3285: 
 3286: This example uses @code{compile-map-array} to show off, but you could
 3287: also use @code{map-array} instead (try it now!).
 3288: 
 3289: You can use this technique for efficient multiplication of large
 3290: matrices.  In matrix multiplication, you multiply every line of one
 3291: matrix with every column of the other matrix.  You can generate the code
 3292: for one line once, and use it for every column.  The only downside of
 3293: this technique is that it is cumbersome to recover the memory consumed
 3294: by the generated code when you are done (and in more complicated cases
 3295: it is not possible portably).
 3296: 
 3297: @c !! @xref{Macros} for reference
 3298: 
 3299: 
 3300: @node Compilation Tokens Tutorial, Wordlists and Search Order Tutorial, Advanced macros Tutorial, Tutorial
 3301: @section Compilation Tokens
 3302: @cindex compilation tokens, tutorial
 3303: @cindex CT, tutorial
 3304: 
 3305: This section is Gforth-specific.  You can skip it.
 3306: 
 3307: @code{' word compile,} compiles the interpretation semantics.  For words
 3308: with default compilation semantics this is the same as performing the
 3309: compilation semantics.  To represent the compilation semantics of other
 3310: words (e.g., words like @code{if} that have no interpretation
 3311: semantics), Gforth has the concept of a compilation token (CT,
 3312: consisting of two cells), and words @code{comp'} and @code{[comp']}.
 3313: You can perform the compilation semantics represented by a CT with
 3314: @code{execute}:
 3315: 
 3316: @example
 3317: : foo2 ( n1 n2 -- n )
 3318:    [ comp' + execute ] ;
 3319: see foo
 3320: @end example
 3321: 
 3322: You can compile the compilation semantics represented by a CT with
 3323: @code{postpone,}:
 3324: 
 3325: @example
 3326: : foo3 ( -- )
 3327:   [ comp' + postpone, ] ;
 3328: see foo3
 3329: @end example
 3330: 
 3331: @code{[ comp' word postpone, ]} is equivalent to @code{POSTPONE word}.
 3332: @code{comp'} is particularly useful for words that have no
 3333: interpretation semantics:
 3334: 
 3335: @example
 3336: ' if
 3337: comp' if .s 2drop
 3338: @end example
 3339: 
 3340: Reference: @ref{Tokens for Words}.
 3341: 
 3342: 
 3343: @node Wordlists and Search Order Tutorial,  , Compilation Tokens Tutorial, Tutorial
 3344: @section Wordlists and Search Order
 3345: @cindex wordlists tutorial
 3346: @cindex search order, tutorial
 3347: 
 3348: The dictionary is not just a memory area that allows you to allocate
 3349: memory with @code{allot}, it also contains the Forth words, arranged in
 3350: several wordlists.  When searching for a word in a wordlist,
 3351: conceptually you start searching at the youngest and proceed towards
 3352: older words (in reality most systems nowadays use hash-tables); i.e., if
 3353: you define a word with the same name as an older word, the new word
 3354: shadows the older word.
 3355: 
 3356: Which wordlists are searched in which order is determined by the search
 3357: order.  You can display the search order with @code{order}.  It displays
 3358: first the search order, starting with the wordlist searched first, then
 3359: it displays the wordlist that will contain newly defined words.
 3360: 
 3361: You can create a new, empty wordlist with @code{wordlist ( -- wid )}:
 3362: 
 3363: @example
 3364: wordlist constant mywords
 3365: @end example
 3366: 
 3367: @code{Set-current ( wid -- )} sets the wordlist that will contain newly
 3368: defined words (the @emph{current} wordlist):
 3369: 
 3370: @example
 3371: mywords set-current
 3372: order
 3373: @end example
 3374: 
 3375: Gforth does not display a name for the wordlist in @code{mywords}
 3376: because this wordlist was created anonymously with @code{wordlist}.
 3377: 
 3378: You can get the current wordlist with @code{get-current ( -- wid)}.  If
 3379: you want to put something into a specific wordlist without overall
 3380: effect on the current wordlist, this typically looks like this:
 3381: 
 3382: @example
 3383: get-current mywords set-current ( wid )
 3384: create someword
 3385: ( wid ) set-current
 3386: @end example
 3387: 
 3388: You can write the search order with @code{set-order ( wid1 .. widn n --
 3389: )} and read it with @code{get-order ( -- wid1 .. widn n )}.  The first
 3390: searched wordlist is topmost.
 3391: 
 3392: @example
 3393: get-order mywords swap 1+ set-order
 3394: order
 3395: @end example
 3396: 
 3397: Yes, the order of wordlists in the output of @code{order} is reversed
 3398: from stack comments and the output of @code{.s} and thus unintuitive.
 3399: 
 3400: @quotation Assignment
 3401: Define @code{>order ( wid -- )} with adds @code{wid} as first searched
 3402: wordlist to the search order.  Define @code{previous ( -- )}, which
 3403: removes the first searched wordlist from the search order.  Experiment
 3404: with boundary conditions (you will see some crashes or situations that
 3405: are hard or impossible to leave).
 3406: @end quotation
 3407: 
 3408: The search order is a powerful foundation for providing features similar
 3409: to Modula-2 modules and C++ namespaces.  However, trying to modularize
 3410: programs in this way has disadvantages for debugging and reuse/factoring
 3411: that overcome the advantages in my experience (I don't do huge projects,
 3412: though).  These disadvantages are not so clear in other
 3413: languages/programming environments, because these languages are not so
 3414: strong in debugging and reuse.
 3415: 
 3416: @c !! example
 3417: 
 3418: Reference: @ref{Word Lists}.
 3419: 
 3420: @c ******************************************************************
 3421: @node Introduction, Words, Tutorial, Top
 3422: @comment node-name,     next,           previous, up
 3423: @chapter An Introduction to ANS Forth
 3424: @cindex Forth - an introduction
 3425: 
 3426: The difference of this chapter from the Tutorial (@pxref{Tutorial}) is
 3427: that it is slower-paced in its examples, but uses them to dive deep into
 3428: explaining Forth internals (not covered by the Tutorial).  Apart from
 3429: that, this chapter covers far less material.  It is suitable for reading
 3430: without using a computer.
 3431: 
 3432: The primary purpose of this manual is to document Gforth. However, since
 3433: Forth is not a widely-known language and there is a lack of up-to-date
 3434: teaching material, it seems worthwhile to provide some introductory
 3435: material.  For other sources of Forth-related
 3436: information, see @ref{Forth-related information}.
 3437: 
 3438: The examples in this section should work on any ANS Forth; the
 3439: output shown was produced using Gforth. Each example attempts to
 3440: reproduce the exact output that Gforth produces. If you try out the
 3441: examples (and you should), what you should type is shown @kbd{like this}
 3442: and Gforth's response is shown @code{like this}. The single exception is
 3443: that, where the example shows @key{RET} it means that you should
 3444: press the ``carriage return'' key. Unfortunately, some output formats for
 3445: this manual cannot show the difference between @kbd{this} and
 3446: @code{this} which will make trying out the examples harder (but not
 3447: impossible).
 3448: 
 3449: Forth is an unusual language. It provides an interactive development
 3450: environment which includes both an interpreter and compiler. Forth
 3451: programming style encourages you to break a problem down into many
 3452: @cindex factoring
 3453: small fragments (@dfn{factoring}), and then to develop and test each
 3454: fragment interactively. Forth advocates assert that breaking the
 3455: edit-compile-test cycle used by conventional programming languages can
 3456: lead to great productivity improvements.
 3457: 
 3458: @menu
 3459: * Introducing the Text Interpreter::  
 3460: * Stacks and Postfix notation::  
 3461: * Your first definition::       
 3462: * How does that work?::         
 3463: * Forth is written in Forth::   
 3464: * Review - elements of a Forth system::  
 3465: * Where to go next::            
 3466: * Exercises::                   
 3467: @end menu
 3468: 
 3469: @comment ----------------------------------------------
 3470: @node Introducing the Text Interpreter, Stacks and Postfix notation, Introduction, Introduction
 3471: @section Introducing the Text Interpreter
 3472: @cindex text interpreter
 3473: @cindex outer interpreter
 3474: 
 3475: @c IMO this is too detailed and the pace is too slow for
 3476: @c an introduction.  If you know German, take a look at
 3477: @c http://www.complang.tuwien.ac.at/anton/lvas/skriptum-stack.html 
 3478: @c to see how I do it - anton 
 3479: 
 3480: @c nac-> Where I have accepted your comments 100% and modified the text
 3481: @c accordingly, I have deleted your comments. Elsewhere I have added a
 3482: @c response like this to attempt to rationalise what I have done. Of
 3483: @c course, this is a very clumsy mechanism for something that would be
 3484: @c done far more efficiently over a beer. Please delete any dialogue
 3485: @c you consider closed.
 3486: 
 3487: When you invoke the Forth image, you will see a startup banner printed
 3488: and nothing else (if you have Gforth installed on your system, try
 3489: invoking it now, by typing @kbd{gforth@key{RET}}). Forth is now running
 3490: its command line interpreter, which is called the @dfn{Text Interpreter}
 3491: (also known as the @dfn{Outer Interpreter}).  (You will learn a lot
 3492: about the text interpreter as you read through this chapter, for more
 3493: detail @pxref{The Text Interpreter}).
 3494: 
 3495: Although it's not obvious, Forth is actually waiting for your
 3496: input. Type a number and press the @key{RET} key:
 3497: 
 3498: @example
 3499: @kbd{45@key{RET}}  ok
 3500: @end example
 3501: 
 3502: Rather than give you a prompt to invite you to input something, the text
 3503: interpreter prints a status message @i{after} it has processed a line
 3504: of input. The status message in this case (``@code{ ok}'' followed by
 3505: carriage-return) indicates that the text interpreter was able to process
 3506: all of your input successfully. Now type something illegal:
 3507: 
 3508: @example
 3509: @kbd{qwer341@key{RET}}
 3510: *the terminal*:2: Undefined word
 3511: >>>qwer341<<<
 3512: Backtrace:
 3513: $2A95B42A20 throw 
 3514: $2A95B57FB8 no.extensions 
 3515: @end example
 3516: 
 3517: The exact text, other than the ``Undefined word'' may differ slightly
 3518: on your system, but the effect is the same; when the text interpreter
 3519: detects an error, it discards any remaining text on a line, resets
 3520: certain internal state and prints an error message. For a detailed
 3521: description of error messages see @ref{Error messages}.
 3522: 
 3523: The text interpreter waits for you to press carriage-return, and then
 3524: processes your input line. Starting at the beginning of the line, it
 3525: breaks the line into groups of characters separated by spaces. For each
 3526: group of characters in turn, it makes two attempts to do something:
 3527: 
 3528: @itemize @bullet
 3529: @item
 3530: @cindex name dictionary
 3531: It tries to treat it as a command. It does this by searching a @dfn{name
 3532: dictionary}. If the group of characters matches an entry in the name
 3533: dictionary, the name dictionary provides the text interpreter with
 3534: information that allows the text interpreter perform some actions. In
 3535: Forth jargon, we say that the group
 3536: @cindex word
 3537: @cindex definition
 3538: @cindex execution token
 3539: @cindex xt
 3540: of characters names a @dfn{word}, that the dictionary search returns an
 3541: @dfn{execution token (xt)} corresponding to the @dfn{definition} of the
 3542: word, and that the text interpreter executes the xt. Often, the terms
 3543: @dfn{word} and @dfn{definition} are used interchangeably.
 3544: @item
 3545: If the text interpreter fails to find a match in the name dictionary, it
 3546: tries to treat the group of characters as a number in the current number
 3547: base (when you start up Forth, the current number base is base 10). If
 3548: the group of characters legitimately represents a number, the text
 3549: interpreter pushes the number onto a stack (we'll learn more about that
 3550: in the next section).
 3551: @end itemize
 3552: 
 3553: If the text interpreter is unable to do either of these things with any
 3554: group of characters, it discards the group of characters and the rest of
 3555: the line, then prints an error message. If the text interpreter reaches
 3556: the end of the line without error, it prints the status message ``@code{ ok}''
 3557: followed by carriage-return.
 3558: 
 3559: This is the simplest command we can give to the text interpreter:
 3560: 
 3561: @example
 3562: @key{RET}  ok
 3563: @end example
 3564: 
 3565: The text interpreter did everything we asked it to do (nothing) without
 3566: an error, so it said that everything is ``@code{ ok}''. Try a slightly longer
 3567: command:
 3568: 
 3569: @example
 3570: @kbd{12 dup fred dup@key{RET}}
 3571: *the terminal*:3: Undefined word
 3572: 12 dup >>>fred<<< dup
 3573: Backtrace:
 3574: $2A95B42A20 throw 
 3575: $2A95B57FB8 no.extensions 
 3576: @end example
 3577: 
 3578: When you press the carriage-return key, the text interpreter starts to
 3579: work its way along the line:
 3580: 
 3581: @itemize @bullet
 3582: @item
 3583: When it gets to the space after the @code{2}, it takes the group of
 3584: characters @code{12} and looks them up in the name
 3585: dictionary@footnote{We can't tell if it found them or not, but assume
 3586: for now that it did not}. There is no match for this group of characters
 3587: in the name dictionary, so it tries to treat them as a number. It is
 3588: able to do this successfully, so it puts the number, 12, ``on the stack''
 3589: (whatever that means).
 3590: @item
 3591: The text interpreter resumes scanning the line and gets the next group
 3592: of characters, @code{dup}. It looks it up in the name dictionary and
 3593: (you'll have to take my word for this) finds it, and executes the word
 3594: @code{dup} (whatever that means).
 3595: @item
 3596: Once again, the text interpreter resumes scanning the line and gets the
 3597: group of characters @code{fred}. It looks them up in the name
 3598: dictionary, but can't find them. It tries to treat them as a number, but
 3599: they don't represent any legal number.
 3600: @end itemize
 3601: 
 3602: At this point, the text interpreter gives up and prints an error
 3603: message. The error message shows exactly how far the text interpreter
 3604: got in processing the line. In particular, it shows that the text
 3605: interpreter made no attempt to do anything with the final character
 3606: group, @code{dup}, even though we have good reason to believe that the
 3607: text interpreter would have no problem looking that word up and
 3608: executing it a second time.
 3609: 
 3610: 
 3611: @comment ----------------------------------------------
 3612: @node Stacks and Postfix notation, Your first definition, Introducing the Text Interpreter, Introduction
 3613: @section Stacks, postfix notation and parameter passing
 3614: @cindex text interpreter
 3615: @cindex outer interpreter
 3616: 
 3617: In procedural programming languages (like C and Pascal), the
 3618: building-block of programs is the @dfn{function} or @dfn{procedure}. These
 3619: functions or procedures are called with @dfn{explicit parameters}. For
 3620: example, in C we might write:
 3621: 
 3622: @example
 3623: total = total + new_volume(length,height,depth);
 3624: @end example
 3625: 
 3626: @noindent
 3627: where new_volume is a function-call to another piece of code, and total,
 3628: length, height and depth are all variables. length, height and depth are
 3629: parameters to the function-call.
 3630: 
 3631: In Forth, the equivalent of the function or procedure is the
 3632: @dfn{definition} and parameters are implicitly passed between
 3633: definitions using a shared stack that is visible to the
 3634: programmer. Although Forth does support variables, the existence of the
 3635: stack means that they are used far less often than in most other
 3636: programming languages. When the text interpreter encounters a number, it
 3637: will place (@dfn{push}) it on the stack. There are several stacks (the
 3638: actual number is implementation-dependent ...) and the particular stack
 3639: used for any operation is implied unambiguously by the operation being
 3640: performed. The stack used for all integer operations is called the @dfn{data
 3641: stack} and, since this is the stack used most commonly, references to
 3642: ``the data stack'' are often abbreviated to ``the stack''.
 3643: 
 3644: The stacks have a last-in, first-out (LIFO) organisation. If you type:
 3645: 
 3646: @example
 3647: @kbd{1 2 3@key{RET}}  ok
 3648: @end example
 3649: 
 3650: Then this instructs the text interpreter to placed three numbers on the
 3651: (data) stack. An analogy for the behaviour of the stack is to take a
 3652: pack of playing cards and deal out the ace (1), 2 and 3 into a pile on
 3653: the table. The 3 was the last card onto the pile (``last-in'') and if
 3654: you take a card off the pile then, unless you're prepared to fiddle a
 3655: bit, the card that you take off will be the 3 (``first-out''). The
 3656: number that will be first-out of the stack is called the @dfn{top of
 3657: stack}, which
 3658: @cindex TOS definition
 3659: is often abbreviated to @dfn{TOS}.
 3660: 
 3661: To understand how parameters are passed in Forth, consider the
 3662: behaviour of the definition @code{+} (pronounced ``plus''). You will not
 3663: be surprised to learn that this definition performs addition. More
 3664: precisely, it adds two number together and produces a result. Where does
 3665: it get the two numbers from? It takes the top two numbers off the
 3666: stack. Where does it place the result? On the stack. You can act-out the
 3667: behaviour of @code{+} with your playing cards like this:
 3668: 
 3669: @itemize @bullet
 3670: @item
 3671: Pick up two cards from the stack on the table
 3672: @item
 3673: Stare at them intently and ask yourself ``what @i{is} the sum of these two
 3674: numbers''
 3675: @item
 3676: Decide that the answer is 5
 3677: @item
 3678: Shuffle the two cards back into the pack and find a 5
 3679: @item
 3680: Put a 5 on the remaining ace that's on the table.
 3681: @end itemize
 3682: 
 3683: If you don't have a pack of cards handy but you do have Forth running,
 3684: you can use the definition @code{.s} to show the current state of the stack,
 3685: without affecting the stack. Type:
 3686: 
 3687: @example
 3688: @kbd{clearstacks 1 2 3@key{RET}} ok
 3689: @kbd{.s@key{RET}} <3> 1 2 3  ok
 3690: @end example
 3691: 
 3692: The text interpreter looks up the word @code{clearstacks} and executes
 3693: it; it tidies up the stacks and removes any entries that may have been
 3694: left on it by earlier examples. The text interpreter pushes each of the
 3695: three numbers in turn onto the stack. Finally, the text interpreter
 3696: looks up the word @code{.s} and executes it. The effect of executing
 3697: @code{.s} is to print the ``<3>'' (the total number of items on the stack)
 3698: followed by a list of all the items on the stack; the item on the far
 3699: right-hand side is the TOS.
 3700: 
 3701: You can now type:
 3702: 
 3703: @example
 3704: @kbd{+ .s@key{RET}} <2> 1 5  ok
 3705: @end example
 3706: 
 3707: @noindent
 3708: which is correct; there are now 2 items on the stack and the result of
 3709: the addition is 5.
 3710: 
 3711: If you're playing with cards, try doing a second addition: pick up the
 3712: two cards, work out that their sum is 6, shuffle them into the pack,
 3713: look for a 6 and place that on the table. You now have just one item on
 3714: the stack. What happens if you try to do a third addition? Pick up the
 3715: first card, pick up the second card -- ah! There is no second card. This
 3716: is called a @dfn{stack underflow} and consitutes an error. If you try to
 3717: do the same thing with Forth it often reports an error (probably a Stack
 3718: Underflow or an Invalid Memory Address error).
 3719: 
 3720: The opposite situation to a stack underflow is a @dfn{stack overflow},
 3721: which simply accepts that there is a finite amount of storage space
 3722: reserved for the stack. To stretch the playing card analogy, if you had
 3723: enough packs of cards and you piled the cards up on the table, you would
 3724: eventually be unable to add another card; you'd hit the ceiling. Gforth
 3725: allows you to set the maximum size of the stacks. In general, the only
 3726: time that you will get a stack overflow is because a definition has a
 3727: bug in it and is generating data on the stack uncontrollably.
 3728: 
 3729: There's one final use for the playing card analogy. If you model your
 3730: stack using a pack of playing cards, the maximum number of items on
 3731: your stack will be 52 (I assume you didn't use the Joker). The maximum
 3732: @i{value} of any item on the stack is 13 (the King). In fact, the only
 3733: possible numbers are positive integer numbers 1 through 13; you can't
 3734: have (for example) 0 or 27 or 3.52 or -2. If you change the way you
 3735: think about some of the cards, you can accommodate different
 3736: numbers. For example, you could think of the Jack as representing 0,
 3737: the Queen as representing -1 and the King as representing -2. Your
 3738: @i{range} remains unchanged (you can still only represent a total of 13
 3739: numbers) but the numbers that you can represent are -2 through 10.
 3740: 
 3741: In that analogy, the limit was the amount of information that a single
 3742: stack entry could hold, and Forth has a similar limit. In Forth, the
 3743: size of a stack entry is called a @dfn{cell}. The actual size of a cell is
 3744: implementation dependent and affects the maximum value that a stack
 3745: entry can hold. A Standard Forth provides a cell size of at least
 3746: 16-bits, and most desktop systems use a cell size of 32-bits.
 3747: 
 3748: Forth does not do any type checking for you, so you are free to
 3749: manipulate and combine stack items in any way you wish. A convenient way
 3750: of treating stack items is as 2's complement signed integers, and that
 3751: is what Standard words like @code{+} do. Therefore you can type:
 3752: 
 3753: @example
 3754: @kbd{-5 12 + .s@key{RET}} <1> 7  ok
 3755: @end example
 3756: 
 3757: If you use numbers and definitions like @code{+} in order to turn Forth
 3758: into a great big pocket calculator, you will realise that it's rather
 3759: different from a normal calculator. Rather than typing 2 + 3 = you had
 3760: to type 2 3 + (ignore the fact that you had to use @code{.s} to see the
 3761: result). The terminology used to describe this difference is to say that
 3762: your calculator uses @dfn{Infix Notation} (parameters and operators are
 3763: mixed) whilst Forth uses @dfn{Postfix Notation} (parameters and
 3764: operators are separate), also called @dfn{Reverse Polish Notation}.
 3765: 
 3766: Whilst postfix notation might look confusing to begin with, it has
 3767: several important advantages:
 3768: 
 3769: @itemize @bullet
 3770: @item
 3771: it is unambiguous
 3772: @item
 3773: it is more concise
 3774: @item
 3775: it fits naturally with a stack-based system
 3776: @end itemize
 3777: 
 3778: To examine these claims in more detail, consider these sums:
 3779: 
 3780: @example
 3781: 6 + 5 * 4 =
 3782: 4 * 5 + 6 =
 3783: @end example
 3784: 
 3785: If you're just learning maths or your maths is very rusty, you will
 3786: probably come up with the answer 44 for the first and 26 for the
 3787: second. If you are a bit of a whizz at maths you will remember the
 3788: @i{convention} that multiplication takes precendence over addition, and
 3789: you'd come up with the answer 26 both times. To explain the answer 26
 3790: to someone who got the answer 44, you'd probably rewrite the first sum
 3791: like this:
 3792: 
 3793: @example
 3794: 6 + (5 * 4) =
 3795: @end example
 3796: 
 3797: If what you really wanted was to perform the addition before the
 3798: multiplication, you would have to use parentheses to force it.
 3799: 
 3800: If you did the first two sums on a pocket calculator you would probably
 3801: get the right answers, unless you were very cautious and entered them using
 3802: these keystroke sequences:
 3803: 
 3804: 6 + 5 = * 4 =
 3805: 4 * 5 = + 6 =
 3806: 
 3807: Postfix notation is unambiguous because the order that the operators
 3808: are applied is always explicit; that also means that parentheses are
 3809: never required. The operators are @i{active} (the act of quoting the
 3810: operator makes the operation occur) which removes the need for ``=''.
 3811: 
 3812: The sum 6 + 5 * 4 can be written (in postfix notation) in two
 3813: equivalent ways:
 3814: 
 3815: @example
 3816: 6 5 4 * +      or:
 3817: 5 4 * 6 +
 3818: @end example
 3819: 
 3820: An important thing that you should notice about this notation is that
 3821: the @i{order} of the numbers does not change; if you want to subtract
 3822: 2 from 10 you type @code{10 2 -}.
 3823: 
 3824: The reason that Forth uses postfix notation is very simple to explain: it
 3825: makes the implementation extremely simple, and it follows naturally from
 3826: using the stack as a mechanism for passing parameters. Another way of
 3827: thinking about this is to realise that all Forth definitions are
 3828: @i{active}; they execute as they are encountered by the text
 3829: interpreter. The result of this is that the syntax of Forth is trivially
 3830: simple.
 3831: 
 3832: 
 3833: 
 3834: @comment ----------------------------------------------
 3835: @node Your first definition, How does that work?, Stacks and Postfix notation, Introduction
 3836: @section Your first Forth definition
 3837: @cindex first definition
 3838: 
 3839: Until now, the examples we've seen have been trivial; we've just been
 3840: using Forth as a bigger-than-pocket calculator. Also, each calculation
 3841: we've shown has been a ``one-off'' -- to repeat it we'd need to type it in
 3842: again@footnote{That's not quite true. If you press the up-arrow key on
 3843: your keyboard you should be able to scroll back to any earlier command,
 3844: edit it and re-enter it.} In this section we'll see how to add new
 3845: words to Forth's vocabulary.
 3846: 
 3847: The easiest way to create a new word is to use a @dfn{colon
 3848: definition}. We'll define a few and try them out before worrying too
 3849: much about how they work. Try typing in these examples; be careful to
 3850: copy the spaces accurately:
 3851: 
 3852: @example
 3853: : add-two 2 + . ;
 3854: : greet ." Hello and welcome" ;
 3855: : demo 5 add-two ;
 3856: @end example
 3857: 
 3858: @noindent
 3859: Now try them out:
 3860: 
 3861: @example
 3862: @kbd{greet@key{RET}} Hello and welcome  ok
 3863: @kbd{greet greet@key{RET}} Hello and welcomeHello and welcome  ok
 3864: @kbd{4 add-two@key{RET}} 6  ok
 3865: @kbd{demo@key{RET}} 7  ok
 3866: @kbd{9 greet demo add-two@key{RET}} Hello and welcome7 11  ok
 3867: @end example
 3868: 
 3869: The first new thing that we've introduced here is the pair of words
 3870: @code{:} and @code{;}. These are used to start and terminate a new
 3871: definition, respectively. The first word after the @code{:} is the name
 3872: for the new definition.
 3873: 
 3874: As you can see from the examples, a definition is built up of words that
 3875: have already been defined; Forth makes no distinction between
 3876: definitions that existed when you started the system up, and those that
 3877: you define yourself.
 3878: 
 3879: The examples also introduce the words @code{.} (dot), @code{."}
 3880: (dot-quote) and @code{dup} (dewp). Dot takes the value from the top of
 3881: the stack and displays it. It's like @code{.s} except that it only
 3882: displays the top item of the stack and it is destructive; after it has
 3883: executed, the number is no longer on the stack. There is always one
 3884: space printed after the number, and no spaces before it. Dot-quote
 3885: defines a string (a sequence of characters) that will be printed when
 3886: the word is executed. The string can contain any printable characters
 3887: except @code{"}. A @code{"} has a special function; it is not a Forth
 3888: word but it acts as a delimiter (the way that delimiters work is
 3889: described in the next section). Finally, @code{dup} duplicates the value
 3890: at the top of the stack. Try typing @code{5 dup .s} to see what it does.
 3891: 
 3892: We already know that the text interpreter searches through the
 3893: dictionary to locate names. If you've followed the examples earlier, you
 3894: will already have a definition called @code{add-two}. Lets try modifying
 3895: it by typing in a new definition:
 3896: 
 3897: @example
 3898: @kbd{: add-two dup . ." + 2 =" 2 + . ;@key{RET}} redefined add-two  ok
 3899: @end example
 3900: 
 3901: Forth recognised that we were defining a word that already exists, and
 3902: printed a message to warn us of that fact. Let's try out the new
 3903: definition:
 3904: 
 3905: @example
 3906: @kbd{9 add-two@key{RET}} 9 + 2 =11  ok
 3907: @end example
 3908: 
 3909: @noindent
 3910: All that we've actually done here, though, is to create a new
 3911: definition, with a particular name. The fact that there was already a
 3912: definition with the same name did not make any difference to the way
 3913: that the new definition was created (except that Forth printed a warning
 3914: message). The old definition of add-two still exists (try @code{demo}
 3915: again to see that this is true). Any new definition will use the new
 3916: definition of @code{add-two}, but old definitions continue to use the
 3917: version that already existed at the time that they were @code{compiled}.
 3918: 
 3919: Before you go on to the next section, try defining and redefining some
 3920: words of your own.
 3921: 
 3922: @comment ----------------------------------------------
 3923: @node How does that work?, Forth is written in Forth, Your first definition, Introduction
 3924: @section How does that work?
 3925: @cindex parsing words
 3926: 
 3927: @c That's pretty deep (IMO way too deep) for an introduction. - anton
 3928: 
 3929: @c Is it a good idea to talk about the interpretation semantics of a
 3930: @c number? We don't have an xt to go along with it. - anton
 3931: 
 3932: @c Now that I have eliminated execution semantics, I wonder if it would not
 3933: @c be better to keep them (or add run-time semantics), to make it easier to
 3934: @c explain what compilation semantics usually does. - anton
 3935: 
 3936: @c nac-> I removed the term ``default compilation sematics'' from the
 3937: @c introductory chapter. Removing ``execution semantics'' was making
 3938: @c everything simpler to explain, then I think the use of this term made
 3939: @c everything more complex again. I replaced it with ``default
 3940: @c semantics'' (which is used elsewhere in the manual) by which I mean
 3941: @c ``a definition that has neither the immediate nor the compile-only
 3942: @c flag set''.
 3943: 
 3944: @c anton: I have eliminated default semantics (except in one place where it
 3945: @c means "default interpretation and compilation semantics"), because it
 3946: @c makes no sense in the presence of combined words.  I reverted to
 3947: @c "execution semantics" where necessary.
 3948: 
 3949: @c nac-> I reworded big chunks of the ``how does that work''
 3950: @c section (and, unusually for me, I think I even made it shorter!).  See
 3951: @c what you think -- I know I have not addressed your primary concern
 3952: @c that it is too heavy-going for an introduction. From what I understood
 3953: @c of your course notes it looks as though they might be a good framework. 
 3954: @c Things that I've tried to capture here are some things that came as a
 3955: @c great revelation here when I first understood them. Also, I like the
 3956: @c fact that a very simple code example shows up almost all of the issues
 3957: @c that you need to understand to see how Forth works. That's unique and
 3958: @c worthwhile to emphasise.
 3959: 
 3960: @c anton: I think it's a good idea to present the details, especially those
 3961: @c that you found to be a revelation, and probably the tutorial tries to be
 3962: @c too superficial and does not get some of the things across that make
 3963: @c Forth special.  I do believe that most of the time these things should
 3964: @c be discussed at the end of a section or in separate sections instead of
 3965: @c in the middle of a section (e.g., the stuff you added in "User-defined
 3966: @c defining words" leads in a completely different direction from the rest
 3967: @c of the section).
 3968: 
 3969: Now we're going to take another look at the definition of @code{add-two}
 3970: from the previous section. From our knowledge of the way that the text
 3971: interpreter works, we would have expected this result when we tried to
 3972: define @code{add-two}:
 3973: 
 3974: @example
 3975: @kbd{: add-two 2 + . ;@key{RET}}
 3976: *the terminal*:4: Undefined word
 3977: : >>>add-two<<< 2 + . ;
 3978: @end example
 3979: 
 3980: The reason that this didn't happen is bound up in the way that @code{:}
 3981: works. The word @code{:} does two special things. The first special
 3982: thing that it does prevents the text interpreter from ever seeing the
 3983: characters @code{add-two}. The text interpreter uses a variable called
 3984: @cindex modifying >IN
 3985: @code{>IN} (pronounced ``to-in'') to keep track of where it is in the
 3986: input line. When it encounters the word @code{:} it behaves in exactly
 3987: the same way as it does for any other word; it looks it up in the name
 3988: dictionary, finds its xt and executes it. When @code{:} executes, it
 3989: looks at the input buffer, finds the word @code{add-two} and advances the
 3990: value of @code{>IN} to point past it. It then does some other stuff
 3991: associated with creating the new definition (including creating an entry
 3992: for @code{add-two} in the name dictionary). When the execution of @code{:}
 3993: completes, control returns to the text interpreter, which is oblivious
 3994: to the fact that it has been tricked into ignoring part of the input
 3995: line.
 3996: 
 3997: @cindex parsing words
 3998: Words like @code{:} -- words that advance the value of @code{>IN} and so
 3999: prevent the text interpreter from acting on the whole of the input line
 4000: -- are called @dfn{parsing words}.
 4001: 
 4002: @cindex @code{state} - effect on the text interpreter
 4003: @cindex text interpreter - effect of state
 4004: The second special thing that @code{:} does is change the value of a
 4005: variable called @code{state}, which affects the way that the text
 4006: interpreter behaves. When Gforth starts up, @code{state} has the value
 4007: 0, and the text interpreter is said to be @dfn{interpreting}. During a
 4008: colon definition (started with @code{:}), @code{state} is set to -1 and
 4009: the text interpreter is said to be @dfn{compiling}.
 4010: 
 4011: In this example, the text interpreter is compiling when it processes the
 4012: string ``@code{2 + . ;}''. It still breaks the string down into
 4013: character sequences in the same way. However, instead of pushing the
 4014: number @code{2} onto the stack, it lays down (@dfn{compiles}) some magic
 4015: into the definition of @code{add-two} that will make the number @code{2} get
 4016: pushed onto the stack when @code{add-two} is @dfn{executed}. Similarly,
 4017: the behaviours of @code{+} and @code{.} are also compiled into the
 4018: definition.
 4019: 
 4020: One category of words don't get compiled. These so-called @dfn{immediate
 4021: words} get executed (performed @i{now}) regardless of whether the text
 4022: interpreter is interpreting or compiling. The word @code{;} is an
 4023: immediate word. Rather than being compiled into the definition, it
 4024: executes. Its effect is to terminate the current definition, which
 4025: includes changing the value of @code{state} back to 0.
 4026: 
 4027: When you execute @code{add-two}, it has a @dfn{run-time effect} that is
 4028: exactly the same as if you had typed @code{2 + . @key{RET}} outside of a
 4029: definition.
 4030: 
 4031: In Forth, every word or number can be described in terms of two
 4032: properties:
 4033: 
 4034: @itemize @bullet
 4035: @item
 4036: @cindex interpretation semantics
 4037: Its @dfn{interpretation semantics} describe how it will behave when the
 4038: text interpreter encounters it in @dfn{interpret} state. The
 4039: interpretation semantics of a word are represented by an @dfn{execution
 4040: token}.
 4041: @item
 4042: @cindex compilation semantics
 4043: Its @dfn{compilation semantics} describe how it will behave when the
 4044: text interpreter encounters it in @dfn{compile} state. The compilation
 4045: semantics of a word are represented in an implementation-dependent way;
 4046: Gforth uses a @dfn{compilation token}.
 4047: @end itemize
 4048: 
 4049: @noindent
 4050: Numbers are always treated in a fixed way:
 4051: 
 4052: @itemize @bullet
 4053: @item
 4054: When the number is @dfn{interpreted}, its behaviour is to push the
 4055: number onto the stack.
 4056: @item
 4057: When the number is @dfn{compiled}, a piece of code is appended to the
 4058: current definition that pushes the number when it runs. (In other words,
 4059: the compilation semantics of a number are to postpone its interpretation
 4060: semantics until the run-time of the definition that it is being compiled
 4061: into.)
 4062: @end itemize
 4063: 
 4064: Words don't behave in such a regular way, but most have @i{default
 4065: semantics} which means that they behave like this:
 4066: 
 4067: @itemize @bullet
 4068: @item
 4069: The @dfn{interpretation semantics} of the word are to do something useful.
 4070: @item
 4071: The @dfn{compilation semantics} of the word are to append its
 4072: @dfn{interpretation semantics} to the current definition (so that its
 4073: run-time behaviour is to do something useful).
 4074: @end itemize
 4075: 
 4076: @cindex immediate words
 4077: The actual behaviour of any particular word can be controlled by using
 4078: the words @code{immediate} and @code{compile-only} when the word is
 4079: defined. These words set flags in the name dictionary entry of the most
 4080: recently defined word, and these flags are retrieved by the text
 4081: interpreter when it finds the word in the name dictionary.
 4082: 
 4083: A word that is marked as @dfn{immediate} has compilation semantics that
 4084: are identical to its interpretation semantics. In other words, it
 4085: behaves like this:
 4086: 
 4087: @itemize @bullet
 4088: @item
 4089: The @dfn{interpretation semantics} of the word are to do something useful.
 4090: @item
 4091: The @dfn{compilation semantics} of the word are to do something useful
 4092: (and actually the same thing); i.e., it is executed during compilation.
 4093: @end itemize
 4094: 
 4095: Marking a word as @dfn{compile-only} prohibits the text interpreter from
 4096: performing the interpretation semantics of the word directly; an attempt
 4097: to do so will generate an error. It is never necessary to use
 4098: @code{compile-only} (and it is not even part of ANS Forth, though it is
 4099: provided by many implementations) but it is good etiquette to apply it
 4100: to a word that will not behave correctly (and might have unexpected
 4101: side-effects) in interpret state. For example, it is only legal to use
 4102: the conditional word @code{IF} within a definition. If you forget this
 4103: and try to use it elsewhere, the fact that (in Gforth) it is marked as
 4104: @code{compile-only} allows the text interpreter to generate a helpful
 4105: error message rather than subjecting you to the consequences of your
 4106: folly.
 4107: 
 4108: This example shows the difference between an immediate and a
 4109: non-immediate word:
 4110: 
 4111: @example
 4112: : show-state state @@ . ;
 4113: : show-state-now show-state ; immediate
 4114: : word1 show-state ;
 4115: : word2 show-state-now ;
 4116: @end example
 4117: 
 4118: The word @code{immediate} after the definition of @code{show-state-now}
 4119: makes that word an immediate word. These definitions introduce a new
 4120: word: @code{@@} (pronounced ``fetch''). This word fetches the value of a
 4121: variable, and leaves it on the stack. Therefore, the behaviour of
 4122: @code{show-state} is to print a number that represents the current value
 4123: of @code{state}.
 4124: 
 4125: When you execute @code{word1}, it prints the number 0, indicating that
 4126: the system is interpreting. When the text interpreter compiled the
 4127: definition of @code{word1}, it encountered @code{show-state} whose
 4128: compilation semantics are to append its interpretation semantics to the
 4129: current definition. When you execute @code{word1}, it performs the
 4130: interpretation semantics of @code{show-state}.  At the time that @code{word1}
 4131: (and therefore @code{show-state}) are executed, the system is
 4132: interpreting.
 4133: 
 4134: When you pressed @key{RET} after entering the definition of @code{word2},
 4135: you should have seen the number -1 printed, followed by ``@code{
 4136: ok}''. When the text interpreter compiled the definition of
 4137: @code{word2}, it encountered @code{show-state-now}, an immediate word,
 4138: whose compilation semantics are therefore to perform its interpretation
 4139: semantics. It is executed straight away (even before the text
 4140: interpreter has moved on to process another group of characters; the
 4141: @code{;} in this example). The effect of executing it are to display the
 4142: value of @code{state} @i{at the time that the definition of}
 4143: @code{word2} @i{is being defined}. Printing -1 demonstrates that the
 4144: system is compiling at this time. If you execute @code{word2} it does
 4145: nothing at all.
 4146: 
 4147: @cindex @code{."}, how it works
 4148: Before leaving the subject of immediate words, consider the behaviour of
 4149: @code{."} in the definition of @code{greet}, in the previous
 4150: section. This word is both a parsing word and an immediate word. Notice
 4151: that there is a space between @code{."} and the start of the text
 4152: @code{Hello and welcome}, but that there is no space between the last
 4153: letter of @code{welcome} and the @code{"} character. The reason for this
 4154: is that @code{."} is a Forth word; it must have a space after it so that
 4155: the text interpreter can identify it. The @code{"} is not a Forth word;
 4156: it is a @dfn{delimiter}. The examples earlier show that, when the string
 4157: is displayed, there is neither a space before the @code{H} nor after the
 4158: @code{e}. Since @code{."} is an immediate word, it executes at the time
 4159: that @code{greet} is defined. When it executes, its behaviour is to
 4160: search forward in the input line looking for the delimiter. When it
 4161: finds the delimiter, it updates @code{>IN} to point past the
 4162: delimiter. It also compiles some magic code into the definition of
 4163: @code{greet}; the xt of a run-time routine that prints a text string. It
 4164: compiles the string @code{Hello and welcome} into memory so that it is
 4165: available to be printed later. When the text interpreter gains control,
 4166: the next word it finds in the input stream is @code{;} and so it
 4167: terminates the definition of @code{greet}.
 4168: 
 4169: 
 4170: @comment ----------------------------------------------
 4171: @node Forth is written in Forth, Review - elements of a Forth system, How does that work?, Introduction
 4172: @section Forth is written in Forth
 4173: @cindex structure of Forth programs
 4174: 
 4175: When you start up a Forth compiler, a large number of definitions
 4176: already exist. In Forth, you develop a new application using bottom-up
 4177: programming techniques to create new definitions that are defined in
 4178: terms of existing definitions. As you create each definition you can
 4179: test and debug it interactively.
 4180: 
 4181: If you have tried out the examples in this section, you will probably
 4182: have typed them in by hand; when you leave Gforth, your definitions will
 4183: be lost. You can avoid this by using a text editor to enter Forth source
 4184: code into a file, and then loading code from the file using
 4185: @code{include} (@pxref{Forth source files}). A Forth source file is
 4186: processed by the text interpreter, just as though you had typed it in by
 4187: hand@footnote{Actually, there are some subtle differences -- see
 4188: @ref{The Text Interpreter}.}.
 4189: 
 4190: Gforth also supports the traditional Forth alternative to using text
 4191: files for program entry (@pxref{Blocks}).
 4192: 
 4193: In common with many, if not most, Forth compilers, most of Gforth is
 4194: actually written in Forth. All of the @file{.fs} files in the
 4195: installation directory@footnote{For example,
 4196: @file{/usr/local/share/gforth...}} are Forth source files, which you can
 4197: study to see examples of Forth programming.
 4198: 
 4199: Gforth maintains a history file that records every line that you type to
 4200: the text interpreter. This file is preserved between sessions, and is
 4201: used to provide a command-line recall facility. If you enter long
 4202: definitions by hand, you can use a text editor to paste them out of the
 4203: history file into a Forth source file for reuse at a later time
 4204: (for more information @pxref{Command-line editing}).
 4205: 
 4206: 
 4207: @comment ----------------------------------------------
 4208: @node Review - elements of a Forth system, Where to go next, Forth is written in Forth, Introduction
 4209: @section Review - elements of a Forth system
 4210: @cindex elements of a Forth system
 4211: 
 4212: To summarise this chapter:
 4213: 
 4214: @itemize @bullet
 4215: @item
 4216: Forth programs use @dfn{factoring} to break a problem down into small
 4217: fragments called @dfn{words} or @dfn{definitions}.
 4218: @item
 4219: Forth program development is an interactive process.
 4220: @item
 4221: The main command loop that accepts input, and controls both
 4222: interpretation and compilation, is called the @dfn{text interpreter}
 4223: (also known as the @dfn{outer interpreter}).
 4224: @item
 4225: Forth has a very simple syntax, consisting of words and numbers
 4226: separated by spaces or carriage-return characters. Any additional syntax
 4227: is imposed by @dfn{parsing words}.
 4228: @item
 4229: Forth uses a stack to pass parameters between words. As a result, it
 4230: uses postfix notation.
 4231: @item
 4232: To use a word that has previously been defined, the text interpreter
 4233: searches for the word in the @dfn{name dictionary}.
 4234: @item
 4235: Words have @dfn{interpretation semantics} and @dfn{compilation semantics}.
 4236: @item
 4237: The text interpreter uses the value of @code{state} to select between
 4238: the use of the @dfn{interpretation semantics} and the  @dfn{compilation
 4239: semantics} of a word that it encounters.
 4240: @item
 4241: The relationship between the @dfn{interpretation semantics} and
 4242: @dfn{compilation semantics} for a word
 4243: depend upon the way in which the word was defined (for example, whether
 4244: it is an @dfn{immediate} word).
 4245: @item
 4246: Forth definitions can be implemented in Forth (called @dfn{high-level
 4247: definitions}) or in some other way (usually a lower-level language and
 4248: as a result often called @dfn{low-level definitions}, @dfn{code
 4249: definitions} or @dfn{primitives}).
 4250: @item
 4251: Many Forth systems are implemented mainly in Forth.
 4252: @end itemize
 4253: 
 4254: 
 4255: @comment ----------------------------------------------
 4256: @node Where to go next, Exercises, Review - elements of a Forth system, Introduction
 4257: @section Where To Go Next
 4258: @cindex where to go next
 4259: 
 4260: Amazing as it may seem, if you have read (and understood) this far, you
 4261: know almost all the fundamentals about the inner workings of a Forth
 4262: system. You certainly know enough to be able to read and understand the
 4263: rest of this manual and the ANS Forth document, to learn more about the
 4264: facilities that Forth in general and Gforth in particular provide. Even
 4265: scarier, you know almost enough to implement your own Forth system.
 4266: However, that's not a good idea just yet... better to try writing some
 4267: programs in Gforth.
 4268: 
 4269: Forth has such a rich vocabulary that it can be hard to know where to
 4270: start in learning it. This section suggests a few sets of words that are
 4271: enough to write small but useful programs. Use the word index in this
 4272: document to learn more about each word, then try it out and try to write
 4273: small definitions using it. Start by experimenting with these words:
 4274: 
 4275: @itemize @bullet
 4276: @item
 4277: Arithmetic: @code{+ - * / /MOD */ ABS INVERT}
 4278: @item
 4279: Comparison: @code{MIN MAX =}
 4280: @item
 4281: Logic: @code{AND OR XOR NOT}
 4282: @item
 4283: Stack manipulation: @code{DUP DROP SWAP OVER}
 4284: @item
 4285: Loops and decisions: @code{IF ELSE ENDIF ?DO I LOOP}
 4286: @item
 4287: Input/Output: @code{. ." EMIT CR KEY}
 4288: @item
 4289: Defining words: @code{: ; CREATE}
 4290: @item
 4291: Memory allocation words: @code{ALLOT ,}
 4292: @item
 4293: Tools: @code{SEE WORDS .S MARKER}
 4294: @end itemize
 4295: 
 4296: When you have mastered those, go on to:
 4297: 
 4298: @itemize @bullet
 4299: @item
 4300: More defining words: @code{VARIABLE CONSTANT VALUE TO CREATE DOES>}
 4301: @item
 4302: Memory access: @code{@@ !}
 4303: @end itemize
 4304: 
 4305: When you have mastered these, there's nothing for it but to read through
 4306: the whole of this manual and find out what you've missed.
 4307: 
 4308: @comment ----------------------------------------------
 4309: @node Exercises,  , Where to go next, Introduction
 4310: @section Exercises
 4311: @cindex exercises
 4312: 
 4313: TODO: provide a set of programming excercises linked into the stuff done
 4314: already and into other sections of the manual. Provide solutions to all
 4315: the exercises in a .fs file in the distribution.
 4316: 
 4317: @c Get some inspiration from Starting Forth and Kelly&Spies.
 4318: 
 4319: @c excercises:
 4320: @c 1. take inches and convert to feet and inches.
 4321: @c 2. take temperature and convert from fahrenheight to celcius;
 4322: @c    may need to care about symmetric vs floored??
 4323: @c 3. take input line and do character substitution
 4324: @c    to encipher or decipher
 4325: @c 4. as above but work on a file for in and out
 4326: @c 5. take input line and convert to pig-latin 
 4327: @c
 4328: @c thing of sets of things to exercise then come up with
 4329: @c problems that need those things.
 4330: 
 4331: 
 4332: @c ******************************************************************
 4333: @node Words, Error messages, Introduction, Top
 4334: @chapter Forth Words
 4335: @cindex words
 4336: 
 4337: @menu
 4338: * Notation::                    
 4339: * Case insensitivity::          
 4340: * Comments::                    
 4341: * Boolean Flags::               
 4342: * Arithmetic::                  
 4343: * Stack Manipulation::          
 4344: * Memory::                      
 4345: * Control Structures::          
 4346: * Defining Words::              
 4347: * Interpretation and Compilation Semantics::  
 4348: * Tokens for Words::            
 4349: * Compiling words::             
 4350: * The Text Interpreter::        
 4351: * The Input Stream::            
 4352: * Word Lists::                  
 4353: * Environmental Queries::       
 4354: * Files::                       
 4355: * Blocks::                      
 4356: * Other I/O::                   
 4357: * OS command line arguments::   
 4358: * Locals::                      
 4359: * Structures::                  
 4360: * Object-oriented Forth::       
 4361: * Programming Tools::           
 4362: * C Interface::                 
 4363: * Assembler and Code Words::    
 4364: * Threading Words::             
 4365: * Passing Commands to the OS::  
 4366: * Keeping track of Time::       
 4367: * Miscellaneous Words::         
 4368: @end menu
 4369: 
 4370: @node Notation, Case insensitivity, Words, Words
 4371: @section Notation
 4372: @cindex notation of glossary entries
 4373: @cindex format of glossary entries
 4374: @cindex glossary notation format
 4375: @cindex word glossary entry format
 4376: 
 4377: The Forth words are described in this section in the glossary notation
 4378: that has become a de-facto standard for Forth texts:
 4379: 
 4380: @format
 4381: @i{word}     @i{Stack effect}   @i{wordset}   @i{pronunciation}
 4382: @end format
 4383: @i{Description}
 4384: 
 4385: @table @var
 4386: @item word
 4387: The name of the word.
 4388: 
 4389: @item Stack effect
 4390: @cindex stack effect
 4391: The stack effect is written in the notation @code{@i{before} --
 4392: @i{after}}, where @i{before} and @i{after} describe the top of
 4393: stack entries before and after the execution of the word. The rest of
 4394: the stack is not touched by the word. The top of stack is rightmost,
 4395: i.e., a stack sequence is written as it is typed in. Note that Gforth
 4396: uses a separate floating point stack, but a unified stack
 4397: notation. Also, return stack effects are not shown in @i{stack
 4398: effect}, but in @i{Description}. The name of a stack item describes
 4399: the type and/or the function of the item. See below for a discussion of
 4400: the types.
 4401: 
 4402: All words have two stack effects: A compile-time stack effect and a
 4403: run-time stack effect. The compile-time stack-effect of most words is
 4404: @i{ -- }. If the compile-time stack-effect of a word deviates from
 4405: this standard behaviour, or the word does other unusual things at
 4406: compile time, both stack effects are shown; otherwise only the run-time
 4407: stack effect is shown.
 4408: 
 4409: @cindex pronounciation of words
 4410: @item pronunciation
 4411: How the word is pronounced.
 4412: 
 4413: @cindex wordset
 4414: @cindex environment wordset
 4415: @item wordset
 4416: The ANS Forth standard is divided into several word sets. A standard
 4417: system need not support all of them. Therefore, in theory, the fewer
 4418: word sets your program uses the more portable it will be. However, we
 4419: suspect that most ANS Forth systems on personal machines will feature
 4420: all word sets. Words that are not defined in ANS Forth have
 4421: @code{gforth} or @code{gforth-internal} as word set. @code{gforth}
 4422: describes words that will work in future releases of Gforth;
 4423: @code{gforth-internal} words are more volatile. Environmental query
 4424: strings are also displayed like words; you can recognize them by the
 4425: @code{environment} in the word set field.
 4426: 
 4427: @item Description
 4428: A description of the behaviour of the word.
 4429: @end table
 4430: 
 4431: @cindex types of stack items
 4432: @cindex stack item types
 4433: The type of a stack item is specified by the character(s) the name
 4434: starts with:
 4435: 
 4436: @table @code
 4437: @item f
 4438: @cindex @code{f}, stack item type
 4439: Boolean flags, i.e. @code{false} or @code{true}.
 4440: @item c
 4441: @cindex @code{c}, stack item type
 4442: Char
 4443: @item w
 4444: @cindex @code{w}, stack item type
 4445: Cell, can contain an integer or an address
 4446: @item n
 4447: @cindex @code{n}, stack item type
 4448: signed integer
 4449: @item u
 4450: @cindex @code{u}, stack item type
 4451: unsigned integer
 4452: @item d
 4453: @cindex @code{d}, stack item type
 4454: double sized signed integer
 4455: @item ud
 4456: @cindex @code{ud}, stack item type
 4457: double sized unsigned integer
 4458: @item r
 4459: @cindex @code{r}, stack item type
 4460: Float (on the FP stack)
 4461: @item a-
 4462: @cindex @code{a_}, stack item type
 4463: Cell-aligned address
 4464: @item c-
 4465: @cindex @code{c_}, stack item type
 4466: Char-aligned address (note that a Char may have two bytes in Windows NT)
 4467: @item f-
 4468: @cindex @code{f_}, stack item type
 4469: Float-aligned address
 4470: @item df-
 4471: @cindex @code{df_}, stack item type
 4472: Address aligned for IEEE double precision float
 4473: @item sf-
 4474: @cindex @code{sf_}, stack item type
 4475: Address aligned for IEEE single precision float
 4476: @item xt
 4477: @cindex @code{xt}, stack item type
 4478: Execution token, same size as Cell
 4479: @item wid
 4480: @cindex @code{wid}, stack item type
 4481: Word list ID, same size as Cell
 4482: @item ior, wior
 4483: @cindex ior type description
 4484: @cindex wior type description
 4485: I/O result code, cell-sized.  In Gforth, you can @code{throw} iors.
 4486: @item f83name
 4487: @cindex @code{f83name}, stack item type
 4488: Pointer to a name structure
 4489: @item "
 4490: @cindex @code{"}, stack item type
 4491: string in the input stream (not on the stack). The terminating character
 4492: is a blank by default. If it is not a blank, it is shown in @code{<>}
 4493: quotes.
 4494: @end table
 4495: 
 4496: @comment ----------------------------------------------
 4497: @node Case insensitivity, Comments, Notation, Words
 4498: @section Case insensitivity
 4499: @cindex case sensitivity
 4500: @cindex upper and lower case
 4501: 
 4502: Gforth is case-insensitive; you can enter definitions and invoke
 4503: Standard words using upper, lower or mixed case (however,
 4504: @pxref{core-idef, Implementation-defined options, Implementation-defined
 4505: options}).
 4506: 
 4507: ANS Forth only @i{requires} implementations to recognise Standard words
 4508: when they are typed entirely in upper case. Therefore, a Standard
 4509: program must use upper case for all Standard words. You can use whatever
 4510: case you like for words that you define, but in a Standard program you
 4511: have to use the words in the same case that you defined them.
 4512: 
 4513: Gforth supports case sensitivity through @code{table}s (case-sensitive
 4514: wordlists, @pxref{Word Lists}).
 4515: 
 4516: Two people have asked how to convert Gforth to be case-sensitive; while
 4517: we think this is a bad idea, you can change all wordlists into tables
 4518: like this:
 4519: 
 4520: @example
 4521: ' table-find forth-wordlist wordlist-map @ !
 4522: @end example
 4523: 
 4524: Note that you now have to type the predefined words in the same case
 4525: that we defined them, which are varying.  You may want to convert them
 4526: to your favourite case before doing this operation (I won't explain how,
 4527: because if you are even contemplating doing this, you'd better have
 4528: enough knowledge of Forth systems to know this already).
 4529: 
 4530: @node Comments, Boolean Flags, Case insensitivity, Words
 4531: @section Comments
 4532: @cindex comments
 4533: 
 4534: Forth supports two styles of comment; the traditional @i{in-line} comment,
 4535: @code{(} and its modern cousin, the @i{comment to end of line}; @code{\}.
 4536: 
 4537: 
 4538: doc-(
 4539: doc-\
 4540: doc-\G
 4541: 
 4542: 
 4543: @node Boolean Flags, Arithmetic, Comments, Words
 4544: @section Boolean Flags
 4545: @cindex Boolean flags
 4546: 
 4547: A Boolean flag is cell-sized. A cell with all bits clear represents the
 4548: flag @code{false} and a flag with all bits set represents the flag
 4549: @code{true}. Words that check a flag (for example, @code{IF}) will treat
 4550: a cell that has @i{any} bit set as @code{true}.
 4551: @c on and off to Memory? 
 4552: @c true and false to "Bitwise operations" or "Numeric comparison"?
 4553: 
 4554: doc-true
 4555: doc-false
 4556: doc-on
 4557: doc-off
 4558: 
 4559: 
 4560: @node Arithmetic, Stack Manipulation, Boolean Flags, Words
 4561: @section Arithmetic
 4562: @cindex arithmetic words
 4563: 
 4564: @cindex division with potentially negative operands
 4565: Forth arithmetic is not checked, i.e., you will not hear about integer
 4566: overflow on addition or multiplication, you may hear about division by
 4567: zero if you are lucky. The operator is written after the operands, but
 4568: the operands are still in the original order. I.e., the infix @code{2-1}
 4569: corresponds to @code{2 1 -}. Forth offers a variety of division
 4570: operators. If you perform division with potentially negative operands,
 4571: you do not want to use @code{/} or @code{/mod} with its undefined
 4572: behaviour, but rather @code{fm/mod} or @code{sm/mod} (probably the
 4573: former, @pxref{Mixed precision}).
 4574: @comment TODO discuss the different division forms and the std approach
 4575: 
 4576: @menu
 4577: * Single precision::            
 4578: * Double precision::            Double-cell integer arithmetic
 4579: * Bitwise operations::          
 4580: * Numeric comparison::          
 4581: * Mixed precision::             Operations with single and double-cell integers
 4582: * Floating Point::              
 4583: @end menu
 4584: 
 4585: @node Single precision, Double precision, Arithmetic, Arithmetic
 4586: @subsection Single precision
 4587: @cindex single precision arithmetic words
 4588: 
 4589: @c !! cell undefined
 4590: 
 4591: By default, numbers in Forth are single-precision integers that are one
 4592: cell in size. They can be signed or unsigned, depending upon how you
 4593: treat them. For the rules used by the text interpreter for recognising
 4594: single-precision integers see @ref{Number Conversion}.
 4595: 
 4596: These words are all defined for signed operands, but some of them also
 4597: work for unsigned numbers: @code{+}, @code{1+}, @code{-}, @code{1-},
 4598: @code{*}.
 4599: 
 4600: doc-+
 4601: doc-1+
 4602: doc-under+
 4603: doc--
 4604: doc-1-
 4605: doc-*
 4606: doc-/
 4607: doc-mod
 4608: doc-/mod
 4609: doc-negate
 4610: doc-abs
 4611: doc-min
 4612: doc-max
 4613: doc-floored
 4614: 
 4615: 
 4616: @node Double precision, Bitwise operations, Single precision, Arithmetic
 4617: @subsection Double precision
 4618: @cindex double precision arithmetic words
 4619: 
 4620: For the rules used by the text interpreter for
 4621: recognising double-precision integers, see @ref{Number Conversion}.
 4622: 
 4623: A double precision number is represented by a cell pair, with the most
 4624: significant cell at the TOS. It is trivial to convert an unsigned single
 4625: to a double: simply push a @code{0} onto the TOS. Since numbers are
 4626: represented by Gforth using 2's complement arithmetic, converting a
 4627: signed single to a (signed) double requires sign-extension across the
 4628: most significant cell. This can be achieved using @code{s>d}. The moral
 4629: of the story is that you cannot convert a number without knowing whether
 4630: it represents an unsigned or a signed number.
 4631: 
 4632: These words are all defined for signed operands, but some of them also
 4633: work for unsigned numbers: @code{d+}, @code{d-}.
 4634: 
 4635: doc-s>d
 4636: doc-d>s
 4637: doc-d+
 4638: doc-d-
 4639: doc-dnegate
 4640: doc-dabs
 4641: doc-dmin
 4642: doc-dmax
 4643: 
 4644: 
 4645: @node Bitwise operations, Numeric comparison, Double precision, Arithmetic
 4646: @subsection Bitwise operations
 4647: @cindex bitwise operation words
 4648: 
 4649: 
 4650: doc-and
 4651: doc-or
 4652: doc-xor
 4653: doc-invert
 4654: doc-lshift
 4655: doc-rshift
 4656: doc-2*
 4657: doc-d2*
 4658: doc-2/
 4659: doc-d2/
 4660: 
 4661: 
 4662: @node Numeric comparison, Mixed precision, Bitwise operations, Arithmetic
 4663: @subsection Numeric comparison
 4664: @cindex numeric comparison words
 4665: 
 4666: Note that the words that compare for equality (@code{= <> 0= 0<> d= d<>
 4667: d0= d0<>}) work for for both signed and unsigned numbers.
 4668: 
 4669: doc-<
 4670: doc-<=
 4671: doc-<>
 4672: doc-=
 4673: doc->
 4674: doc->=
 4675: 
 4676: doc-0<
 4677: doc-0<=
 4678: doc-0<>
 4679: doc-0=
 4680: doc-0>
 4681: doc-0>=
 4682: 
 4683: doc-u<
 4684: doc-u<=
 4685: @c u<> and u= exist but are the same as <> and =
 4686: @c doc-u<>
 4687: @c doc-u=
 4688: doc-u>
 4689: doc-u>=
 4690: 
 4691: doc-within
 4692: 
 4693: doc-d<
 4694: doc-d<=
 4695: doc-d<>
 4696: doc-d=
 4697: doc-d>
 4698: doc-d>=
 4699: 
 4700: doc-d0<
 4701: doc-d0<=
 4702: doc-d0<>
 4703: doc-d0=
 4704: doc-d0>
 4705: doc-d0>=
 4706: 
 4707: doc-du<
 4708: doc-du<=
 4709: @c du<> and du= exist but are the same as d<> and d=
 4710: @c doc-du<>
 4711: @c doc-du=
 4712: doc-du>
 4713: doc-du>=
 4714: 
 4715: 
 4716: @node Mixed precision, Floating Point, Numeric comparison, Arithmetic
 4717: @subsection Mixed precision
 4718: @cindex mixed precision arithmetic words
 4719: 
 4720: 
 4721: doc-m+
 4722: doc-*/
 4723: doc-*/mod
 4724: doc-m*
 4725: doc-um*
 4726: doc-m*/
 4727: doc-um/mod
 4728: doc-fm/mod
 4729: doc-sm/rem
 4730: 
 4731: 
 4732: @node Floating Point,  , Mixed precision, Arithmetic
 4733: @subsection Floating Point
 4734: @cindex floating point arithmetic words
 4735: 
 4736: For the rules used by the text interpreter for
 4737: recognising floating-point numbers see @ref{Number Conversion}.
 4738: 
 4739: Gforth has a separate floating point stack, but the documentation uses
 4740: the unified notation.@footnote{It's easy to generate the separate
 4741: notation from that by just separating the floating-point numbers out:
 4742: e.g. @code{( n r1 u r2 -- r3 )} becomes @code{( n u -- ) ( F: r1 r2 --
 4743: r3 )}.}
 4744: 
 4745: @cindex floating-point arithmetic, pitfalls
 4746: Floating point numbers have a number of unpleasant surprises for the
 4747: unwary (e.g., floating point addition is not associative) and even a
 4748: few for the wary. You should not use them unless you know what you are
 4749: doing or you don't care that the results you get are totally bogus. If
 4750: you want to learn about the problems of floating point numbers (and
 4751: how to avoid them), you might start with @cite{David Goldberg,
 4752: @uref{http://docs.sun.com/source/806-3568/ncg_goldberg.html,What Every
 4753: Computer Scientist Should Know About Floating-Point Arithmetic}, ACM
 4754: Computing Surveys 23(1):5@minus{}48, March 1991}.
 4755: 
 4756: 
 4757: doc-d>f
 4758: doc-f>d
 4759: doc-f+
 4760: doc-f-
 4761: doc-f*
 4762: doc-f/
 4763: doc-fnegate
 4764: doc-fabs
 4765: doc-fmax
 4766: doc-fmin
 4767: doc-floor
 4768: doc-fround
 4769: doc-f**
 4770: doc-fsqrt
 4771: doc-fexp
 4772: doc-fexpm1
 4773: doc-fln
 4774: doc-flnp1
 4775: doc-flog
 4776: doc-falog
 4777: doc-f2*
 4778: doc-f2/
 4779: doc-1/f
 4780: doc-precision
 4781: doc-set-precision
 4782: 
 4783: @cindex angles in trigonometric operations
 4784: @cindex trigonometric operations
 4785: Angles in floating point operations are given in radians (a full circle
 4786: has 2 pi radians).
 4787: 
 4788: doc-fsin
 4789: doc-fcos
 4790: doc-fsincos
 4791: doc-ftan
 4792: doc-fasin
 4793: doc-facos
 4794: doc-fatan
 4795: doc-fatan2
 4796: doc-fsinh
 4797: doc-fcosh
 4798: doc-ftanh
 4799: doc-fasinh
 4800: doc-facosh
 4801: doc-fatanh
 4802: doc-pi
 4803: 
 4804: @cindex equality of floats
 4805: @cindex floating-point comparisons
 4806: One particular problem with floating-point arithmetic is that comparison
 4807: for equality often fails when you would expect it to succeed.  For this
 4808: reason approximate equality is often preferred (but you still have to
 4809: know what you are doing).  Also note that IEEE NaNs may compare
 4810: differently from what you might expect.  The comparison words are:
 4811: 
 4812: doc-f~rel
 4813: doc-f~abs
 4814: doc-f~
 4815: doc-f=
 4816: doc-f<>
 4817: 
 4818: doc-f<
 4819: doc-f<=
 4820: doc-f>
 4821: doc-f>=
 4822: 
 4823: doc-f0<
 4824: doc-f0<=
 4825: doc-f0<>
 4826: doc-f0=
 4827: doc-f0>
 4828: doc-f0>=
 4829: 
 4830: 
 4831: @node Stack Manipulation, Memory, Arithmetic, Words
 4832: @section Stack Manipulation
 4833: @cindex stack manipulation words
 4834: 
 4835: @cindex floating-point stack in the standard
 4836: Gforth maintains a number of separate stacks:
 4837: 
 4838: @cindex data stack
 4839: @cindex parameter stack
 4840: @itemize @bullet
 4841: @item
 4842: A data stack (also known as the @dfn{parameter stack}) -- for
 4843: characters, cells, addresses, and double cells.
 4844: 
 4845: @cindex floating-point stack
 4846: @item
 4847: A floating point stack -- for holding floating point (FP) numbers.
 4848: 
 4849: @cindex return stack
 4850: @item
 4851: A return stack -- for holding the return addresses of colon
 4852: definitions and other (non-FP) data.
 4853: 
 4854: @cindex locals stack
 4855: @item
 4856: A locals stack -- for holding local variables.
 4857: @end itemize
 4858: 
 4859: @menu
 4860: * Data stack::                  
 4861: * Floating point stack::        
 4862: * Return stack::                
 4863: * Locals stack::                
 4864: * Stack pointer manipulation::  
 4865: @end menu
 4866: 
 4867: @node Data stack, Floating point stack, Stack Manipulation, Stack Manipulation
 4868: @subsection Data stack
 4869: @cindex data stack manipulation words
 4870: @cindex stack manipulations words, data stack
 4871: 
 4872: 
 4873: doc-drop
 4874: doc-nip
 4875: doc-dup
 4876: doc-over
 4877: doc-tuck
 4878: doc-swap
 4879: doc-pick
 4880: doc-rot
 4881: doc--rot
 4882: doc-?dup
 4883: doc-roll
 4884: doc-2drop
 4885: doc-2nip
 4886: doc-2dup
 4887: doc-2over
 4888: doc-2tuck
 4889: doc-2swap
 4890: doc-2rot
 4891: 
 4892: 
 4893: @node Floating point stack, Return stack, Data stack, Stack Manipulation
 4894: @subsection Floating point stack
 4895: @cindex floating-point stack manipulation words
 4896: @cindex stack manipulation words, floating-point stack
 4897: 
 4898: Whilst every sane Forth has a separate floating-point stack, it is not
 4899: strictly required; an ANS Forth system could theoretically keep
 4900: floating-point numbers on the data stack. As an additional difficulty,
 4901: you don't know how many cells a floating-point number takes. It is
 4902: reportedly possible to write words in a way that they work also for a
 4903: unified stack model, but we do not recommend trying it. Instead, just
 4904: say that your program has an environmental dependency on a separate
 4905: floating-point stack.
 4906: 
 4907: doc-floating-stack
 4908: 
 4909: doc-fdrop
 4910: doc-fnip
 4911: doc-fdup
 4912: doc-fover
 4913: doc-ftuck
 4914: doc-fswap
 4915: doc-fpick
 4916: doc-frot
 4917: 
 4918: 
 4919: @node Return stack, Locals stack, Floating point stack, Stack Manipulation
 4920: @subsection Return stack
 4921: @cindex return stack manipulation words
 4922: @cindex stack manipulation words, return stack
 4923: 
 4924: @cindex return stack and locals
 4925: @cindex locals and return stack
 4926: A Forth system is allowed to keep local variables on the
 4927: return stack. This is reasonable, as local variables usually eliminate
 4928: the need to use the return stack explicitly. So, if you want to produce
 4929: a standard compliant program and you are using local variables in a
 4930: word, forget about return stack manipulations in that word (refer to the
 4931: standard document for the exact rules).
 4932: 
 4933: doc->r
 4934: doc-r>
 4935: doc-r@
 4936: doc-rdrop
 4937: doc-2>r
 4938: doc-2r>
 4939: doc-2r@
 4940: doc-2rdrop
 4941: 
 4942: 
 4943: @node Locals stack, Stack pointer manipulation, Return stack, Stack Manipulation
 4944: @subsection Locals stack
 4945: 
 4946: Gforth uses an extra locals stack.  It is described, along with the
 4947: reasons for its existence, in @ref{Locals implementation}.
 4948: 
 4949: @node Stack pointer manipulation,  , Locals stack, Stack Manipulation
 4950: @subsection Stack pointer manipulation
 4951: @cindex stack pointer manipulation words
 4952: 
 4953: @c removed s0 r0 l0 -- they are obsolete aliases for sp0 rp0 lp0
 4954: doc-sp0
 4955: doc-sp@
 4956: doc-sp!
 4957: doc-fp0
 4958: doc-fp@
 4959: doc-fp!
 4960: doc-rp0
 4961: doc-rp@
 4962: doc-rp!
 4963: doc-lp0
 4964: doc-lp@
 4965: doc-lp!
 4966: 
 4967: 
 4968: @node Memory, Control Structures, Stack Manipulation, Words
 4969: @section Memory
 4970: @cindex memory words
 4971: 
 4972: @menu
 4973: * Memory model::                
 4974: * Dictionary allocation::       
 4975: * Heap Allocation::             
 4976: * Memory Access::               
 4977: * Address arithmetic::          
 4978: * Memory Blocks::               
 4979: @end menu
 4980: 
 4981: In addition to the standard Forth memory allocation words, there is also
 4982: a @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
 4983: garbage collector}.
 4984: 
 4985: @node Memory model, Dictionary allocation, Memory, Memory
 4986: @subsection ANS Forth and Gforth memory models
 4987: 
 4988: @c The ANS Forth description is a mess (e.g., is the heap part of
 4989: @c the dictionary?), so let's not stick to closely with it.
 4990: 
 4991: ANS Forth considers a Forth system as consisting of several address
 4992: spaces, of which only @dfn{data space} is managed and accessible with
 4993: the memory words.  Memory not necessarily in data space includes the
 4994: stacks, the code (called code space) and the headers (called name
 4995: space). In Gforth everything is in data space, but the code for the
 4996: primitives is usually read-only.
 4997: 
 4998: Data space is divided into a number of areas: The (data space portion of
 4999: the) dictionary@footnote{Sometimes, the term @dfn{dictionary} is used to
 5000: refer to the search data structure embodied in word lists and headers,
 5001: because it is used for looking up names, just as you would in a
 5002: conventional dictionary.}, the heap, and a number of system-allocated
 5003: buffers.
 5004: 
 5005: @cindex address arithmetic restrictions, ANS vs. Gforth
 5006: @cindex contiguous regions, ANS vs. Gforth
 5007: In ANS Forth data space is also divided into contiguous regions.  You
 5008: can only use address arithmetic within a contiguous region, not between
 5009: them.  Usually each allocation gives you one contiguous region, but the
 5010: dictionary allocation words have additional rules (@pxref{Dictionary
 5011: allocation}).
 5012: 
 5013: Gforth provides one big address space, and address arithmetic can be
 5014: performed between any addresses. However, in the dictionary headers or
 5015: code are interleaved with data, so almost the only contiguous data space
 5016: regions there are those described by ANS Forth as contiguous; but you
 5017: can be sure that the dictionary is allocated towards increasing
 5018: addresses even between contiguous regions.  The memory order of
 5019: allocations in the heap is platform-dependent (and possibly different
 5020: from one run to the next).
 5021: 
 5022: 
 5023: @node Dictionary allocation, Heap Allocation, Memory model, Memory
 5024: @subsection Dictionary allocation
 5025: @cindex reserving data space
 5026: @cindex data space - reserving some
 5027: 
 5028: Dictionary allocation is a stack-oriented allocation scheme, i.e., if
 5029: you want to deallocate X, you also deallocate everything
 5030: allocated after X.
 5031: 
 5032: @cindex contiguous regions in dictionary allocation
 5033: The allocations using the words below are contiguous and grow the region
 5034: towards increasing addresses.  Other words that allocate dictionary
 5035: memory of any kind (i.e., defining words including @code{:noname}) end
 5036: the contiguous region and start a new one.
 5037: 
 5038: In ANS Forth only @code{create}d words are guaranteed to produce an
 5039: address that is the start of the following contiguous region.  In
 5040: particular, the cell allocated by @code{variable} is not guaranteed to
 5041: be contiguous with following @code{allot}ed memory.
 5042: 
 5043: You can deallocate memory by using @code{allot} with a negative argument
 5044: (with some restrictions, see @code{allot}). For larger deallocations use
 5045: @code{marker}.
 5046: 
 5047: 
 5048: doc-here
 5049: doc-unused
 5050: doc-allot
 5051: doc-c,
 5052: doc-f,
 5053: doc-,
 5054: doc-2,
 5055: 
 5056: Memory accesses have to be aligned (@pxref{Address arithmetic}). So of
 5057: course you should allocate memory in an aligned way, too. I.e., before
 5058: allocating allocating a cell, @code{here} must be cell-aligned, etc.
 5059: The words below align @code{here} if it is not already.  Basically it is
 5060: only already aligned for a type, if the last allocation was a multiple
 5061: of the size of this type and if @code{here} was aligned for this type
 5062: before.
 5063: 
 5064: After freshly @code{create}ing a word, @code{here} is @code{align}ed in
 5065: ANS Forth (@code{maxalign}ed in Gforth).
 5066: 
 5067: doc-align
 5068: doc-falign
 5069: doc-sfalign
 5070: doc-dfalign
 5071: doc-maxalign
 5072: doc-cfalign
 5073: 
 5074: 
 5075: @node Heap Allocation, Memory Access, Dictionary allocation, Memory
 5076: @subsection Heap allocation
 5077: @cindex heap allocation
 5078: @cindex dynamic allocation of memory
 5079: @cindex memory-allocation word set
 5080: 
 5081: @cindex contiguous regions and heap allocation
 5082: Heap allocation supports deallocation of allocated memory in any
 5083: order. Dictionary allocation is not affected by it (i.e., it does not
 5084: end a contiguous region). In Gforth, these words are implemented using
 5085: the standard C library calls malloc(), free() and resize().
 5086: 
 5087: The memory region produced by one invocation of @code{allocate} or
 5088: @code{resize} is internally contiguous.  There is no contiguity between
 5089: such a region and any other region (including others allocated from the
 5090: heap).
 5091: 
 5092: doc-allocate
 5093: doc-free
 5094: doc-resize
 5095: 
 5096: 
 5097: @node Memory Access, Address arithmetic, Heap Allocation, Memory
 5098: @subsection Memory Access
 5099: @cindex memory access words
 5100: 
 5101: doc-@
 5102: doc-!
 5103: doc-+!
 5104: doc-c@
 5105: doc-c!
 5106: doc-2@
 5107: doc-2!
 5108: doc-f@
 5109: doc-f!
 5110: doc-sf@
 5111: doc-sf!
 5112: doc-df@
 5113: doc-df!
 5114: doc-sw@
 5115: doc-uw@
 5116: doc-w!
 5117: doc-sl@
 5118: doc-ul@
 5119: doc-l!
 5120: 
 5121: @node Address arithmetic, Memory Blocks, Memory Access, Memory
 5122: @subsection Address arithmetic
 5123: @cindex address arithmetic words
 5124: 
 5125: Address arithmetic is the foundation on which you can build data
 5126: structures like arrays, records (@pxref{Structures}) and objects
 5127: (@pxref{Object-oriented Forth}).
 5128: 
 5129: @cindex address unit
 5130: @cindex au (address unit)
 5131: ANS Forth does not specify the sizes of the data types. Instead, it
 5132: offers a number of words for computing sizes and doing address
 5133: arithmetic. Address arithmetic is performed in terms of address units
 5134: (aus); on most systems the address unit is one byte. Note that a
 5135: character may have more than one au, so @code{chars} is no noop (on
 5136: platforms where it is a noop, it compiles to nothing).
 5137: 
 5138: The basic address arithmetic words are @code{+} and @code{-}.  E.g., if
 5139: you have the address of a cell, perform @code{1 cells +}, and you will
 5140: have the address of the next cell.
 5141: 
 5142: @cindex contiguous regions and address arithmetic
 5143: In ANS Forth you can perform address arithmetic only within a contiguous
 5144: region, i.e., if you have an address into one region, you can only add
 5145: and subtract such that the result is still within the region; you can
 5146: only subtract or compare addresses from within the same contiguous
 5147: region.  Reasons: several contiguous regions can be arranged in memory
 5148: in any way; on segmented systems addresses may have unusual
 5149: representations, such that address arithmetic only works within a
 5150: region.  Gforth provides a few more guarantees (linear address space,
 5151: dictionary grows upwards), but in general I have found it easy to stay
 5152: within contiguous regions (exception: computing and comparing to the
 5153: address just beyond the end of an array).
 5154: 
 5155: @cindex alignment of addresses for types
 5156: ANS Forth also defines words for aligning addresses for specific
 5157: types. Many computers require that accesses to specific data types
 5158: must only occur at specific addresses; e.g., that cells may only be
 5159: accessed at addresses divisible by 4. Even if a machine allows unaligned
 5160: accesses, it can usually perform aligned accesses faster. 
 5161: 
 5162: For the performance-conscious: alignment operations are usually only
 5163: necessary during the definition of a data structure, not during the
 5164: (more frequent) accesses to it.
 5165: 
 5166: ANS Forth defines no words for character-aligning addresses. This is not
 5167: an oversight, but reflects the fact that addresses that are not
 5168: char-aligned have no use in the standard and therefore will not be
 5169: created.
 5170: 
 5171: @cindex @code{CREATE} and alignment
 5172: ANS Forth guarantees that addresses returned by @code{CREATE}d words
 5173: are cell-aligned; in addition, Gforth guarantees that these addresses
 5174: are aligned for all purposes.
 5175: 
 5176: Note that the ANS Forth word @code{char} has nothing to do with address
 5177: arithmetic.
 5178: 
 5179: 
 5180: doc-chars
 5181: doc-char+
 5182: doc-cells
 5183: doc-cell+
 5184: doc-cell
 5185: doc-aligned
 5186: doc-floats
 5187: doc-float+
 5188: doc-float
 5189: doc-faligned
 5190: doc-sfloats
 5191: doc-sfloat+
 5192: doc-sfaligned
 5193: doc-dfloats
 5194: doc-dfloat+
 5195: doc-dfaligned
 5196: doc-maxaligned
 5197: doc-cfaligned
 5198: doc-address-unit-bits
 5199: doc-/w
 5200: doc-/l
 5201: 
 5202: @node Memory Blocks,  , Address arithmetic, Memory
 5203: @subsection Memory Blocks
 5204: @cindex memory block words
 5205: @cindex character strings - moving and copying
 5206: 
 5207: Memory blocks often represent character strings; For ways of storing
 5208: character strings in memory see @ref{String Formats}.  For other
 5209: string-processing words see @ref{Displaying characters and strings}.
 5210: 
 5211: A few of these words work on address unit blocks.  In that case, you
 5212: usually have to insert @code{CHARS} before the word when working on
 5213: character strings.  Most words work on character blocks, and expect a
 5214: char-aligned address.
 5215: 
 5216: When copying characters between overlapping memory regions, use
 5217: @code{chars move} or choose carefully between @code{cmove} and
 5218: @code{cmove>}.
 5219: 
 5220: doc-move
 5221: doc-erase
 5222: doc-cmove
 5223: doc-cmove>
 5224: doc-fill
 5225: doc-blank
 5226: doc-compare
 5227: doc-str=
 5228: doc-str<
 5229: doc-string-prefix?
 5230: doc-search
 5231: doc--trailing
 5232: doc-/string
 5233: doc-bounds
 5234: doc-pad
 5235: 
 5236: @comment TODO examples
 5237: 
 5238: 
 5239: @node Control Structures, Defining Words, Memory, Words
 5240: @section Control Structures
 5241: @cindex control structures
 5242: 
 5243: Control structures in Forth cannot be used interpretively, only in a
 5244: colon definition@footnote{To be precise, they have no interpretation
 5245: semantics (@pxref{Interpretation and Compilation Semantics}).}. We do
 5246: not like this limitation, but have not seen a satisfying way around it
 5247: yet, although many schemes have been proposed.
 5248: 
 5249: @menu
 5250: * Selection::                   IF ... ELSE ... ENDIF
 5251: * Simple Loops::                BEGIN ...
 5252: * Counted Loops::               DO
 5253: * Arbitrary control structures::  
 5254: * Calls and returns::           
 5255: * Exception Handling::          
 5256: @end menu
 5257: 
 5258: @node Selection, Simple Loops, Control Structures, Control Structures
 5259: @subsection Selection
 5260: @cindex selection control structures
 5261: @cindex control structures for selection
 5262: 
 5263: @cindex @code{IF} control structure
 5264: @example
 5265: @i{flag}
 5266: IF
 5267:   @i{code}
 5268: ENDIF
 5269: @end example
 5270: @noindent
 5271: 
 5272: If @i{flag} is non-zero (as far as @code{IF} etc. are concerned, a cell
 5273: with any bit set represents truth) @i{code} is executed.
 5274: 
 5275: @example
 5276: @i{flag}
 5277: IF
 5278:   @i{code1}
 5279: ELSE
 5280:   @i{code2}
 5281: ENDIF
 5282: @end example
 5283: 
 5284: If @var{flag} is true, @i{code1} is executed, otherwise @i{code2} is
 5285: executed.
 5286: 
 5287: You can use @code{THEN} instead of @code{ENDIF}. Indeed, @code{THEN} is
 5288: standard, and @code{ENDIF} is not, although it is quite popular. We
 5289: recommend using @code{ENDIF}, because it is less confusing for people
 5290: who also know other languages (and is not prone to reinforcing negative
 5291: prejudices against Forth in these people). Adding @code{ENDIF} to a
 5292: system that only supplies @code{THEN} is simple:
 5293: @example
 5294: : ENDIF   POSTPONE then ; immediate
 5295: @end example
 5296: 
 5297: [According to @cite{Webster's New Encyclopedic Dictionary}, @dfn{then
 5298: (adv.)}  has the following meanings:
 5299: @quotation
 5300: ... 2b: following next after in order ... 3d: as a necessary consequence
 5301: (if you were there, then you saw them).
 5302: @end quotation
 5303: Forth's @code{THEN} has the meaning 2b, whereas @code{THEN} in Pascal
 5304: and many other programming languages has the meaning 3d.]
 5305: 
 5306: Gforth also provides the words @code{?DUP-IF} and @code{?DUP-0=-IF}, so
 5307: you can avoid using @code{?dup}. Using these alternatives is also more
 5308: efficient than using @code{?dup}. Definitions in ANS Forth
 5309: for @code{ENDIF}, @code{?DUP-IF} and @code{?DUP-0=-IF} are provided in
 5310: @file{compat/control.fs}.
 5311: 
 5312: @cindex @code{CASE} control structure
 5313: @example
 5314: @i{n}
 5315: CASE
 5316:   @i{n1} OF @i{code1} ENDOF
 5317:   @i{n2} OF @i{code2} ENDOF
 5318:   @dots{}
 5319:   ( n ) @i{default-code} ( n )
 5320: ENDCASE ( )
 5321: @end example
 5322: 
 5323: Executes the first @i{codei}, where the @i{ni} is equal to @i{n}.  If
 5324: no @i{ni} matches, the optional @i{default-code} is executed. The
 5325: optional default case can be added by simply writing the code after
 5326: the last @code{ENDOF}. It may use @i{n}, which is on top of the stack,
 5327: but must not consume it.  The value @i{n} is consumed by this
 5328: construction (either by a OF that matches, or by the ENDCASE, if no OF
 5329: matches).
 5330: 
 5331: @progstyle
 5332: To keep the code understandable, you should ensure that you change the
 5333: stack in the same way (wrt. number and types of stack items consumed
 5334: and pushed) on all paths through a selection construct.
 5335: 
 5336: @node Simple Loops, Counted Loops, Selection, Control Structures
 5337: @subsection Simple Loops
 5338: @cindex simple loops
 5339: @cindex loops without count 
 5340: 
 5341: @cindex @code{WHILE} loop
 5342: @example
 5343: BEGIN
 5344:   @i{code1}
 5345:   @i{flag}
 5346: WHILE
 5347:   @i{code2}
 5348: REPEAT
 5349: @end example
 5350: 
 5351: @i{code1} is executed and @i{flag} is computed. If it is true,
 5352: @i{code2} is executed and the loop is restarted; If @i{flag} is
 5353: false, execution continues after the @code{REPEAT}.
 5354: 
 5355: @cindex @code{UNTIL} loop
 5356: @example
 5357: BEGIN
 5358:   @i{code}
 5359:   @i{flag}
 5360: UNTIL
 5361: @end example
 5362: 
 5363: @i{code} is executed. The loop is restarted if @code{flag} is false.
 5364: 
 5365: @progstyle
 5366: To keep the code understandable, a complete iteration of the loop should
 5367: not change the number and types of the items on the stacks.
 5368: 
 5369: @cindex endless loop
 5370: @cindex loops, endless
 5371: @example
 5372: BEGIN
 5373:   @i{code}
 5374: AGAIN
 5375: @end example
 5376: 
 5377: This is an endless loop.
 5378: 
 5379: @node Counted Loops, Arbitrary control structures, Simple Loops, Control Structures
 5380: @subsection Counted Loops
 5381: @cindex counted loops
 5382: @cindex loops, counted
 5383: @cindex @code{DO} loops
 5384: 
 5385: The basic counted loop is:
 5386: @example
 5387: @i{limit} @i{start}
 5388: ?DO
 5389:   @i{body}
 5390: LOOP
 5391: @end example
 5392: 
 5393: This performs one iteration for every integer, starting from @i{start}
 5394: and up to, but excluding @i{limit}. The counter, or @i{index}, can be
 5395: accessed with @code{i}. For example, the loop:
 5396: @example
 5397: 10 0 ?DO
 5398:   i .
 5399: LOOP
 5400: @end example
 5401: @noindent
 5402: prints @code{0 1 2 3 4 5 6 7 8 9}
 5403: 
 5404: The index of the innermost loop can be accessed with @code{i}, the index
 5405: of the next loop with @code{j}, and the index of the third loop with
 5406: @code{k}.
 5407: 
 5408: 
 5409: doc-i
 5410: doc-j
 5411: doc-k
 5412: 
 5413: 
 5414: The loop control data are kept on the return stack, so there are some
 5415: restrictions on mixing return stack accesses and counted loop words. In
 5416: particuler, if you put values on the return stack outside the loop, you
 5417: cannot read them inside the loop@footnote{well, not in a way that is
 5418: portable.}. If you put values on the return stack within a loop, you
 5419: have to remove them before the end of the loop and before accessing the
 5420: index of the loop.
 5421: 
 5422: There are several variations on the counted loop:
 5423: 
 5424: @itemize @bullet
 5425: @item
 5426: @code{LEAVE} leaves the innermost counted loop immediately; execution
 5427: continues after the associated @code{LOOP} or @code{NEXT}. For example:
 5428: 
 5429: @example
 5430: 10 0 ?DO  i DUP . 3 = IF LEAVE THEN LOOP
 5431: @end example
 5432: prints @code{0 1 2 3}
 5433: 
 5434: 
 5435: @item
 5436: @code{UNLOOP} prepares for an abnormal loop exit, e.g., via
 5437: @code{EXIT}. @code{UNLOOP} removes the loop control parameters from the
 5438: return stack so @code{EXIT} can get to its return address. For example:
 5439: 
 5440: @example
 5441: : demo 10 0 ?DO i DUP . 3 = IF UNLOOP EXIT THEN LOOP ." Done" ;
 5442: @end example
 5443: prints @code{0 1 2 3}
 5444: 
 5445: 
 5446: @item
 5447: If @i{start} is greater than @i{limit}, a @code{?DO} loop is entered
 5448: (and @code{LOOP} iterates until they become equal by wrap-around
 5449: arithmetic). This behaviour is usually not what you want. Therefore,
 5450: Gforth offers @code{+DO} and @code{U+DO} (as replacements for
 5451: @code{?DO}), which do not enter the loop if @i{start} is greater than
 5452: @i{limit}; @code{+DO} is for signed loop parameters, @code{U+DO} for
 5453: unsigned loop parameters.
 5454: 
 5455: @item
 5456: @code{?DO} can be replaced by @code{DO}. @code{DO} always enters
 5457: the loop, independent of the loop parameters. Do not use @code{DO}, even
 5458: if you know that the loop is entered in any case. Such knowledge tends
 5459: to become invalid during maintenance of a program, and then the
 5460: @code{DO} will make trouble.
 5461: 
 5462: @item
 5463: @code{LOOP} can be replaced with @code{@i{n} +LOOP}; this updates the
 5464: index by @i{n} instead of by 1. The loop is terminated when the border
 5465: between @i{limit-1} and @i{limit} is crossed. E.g.:
 5466: 
 5467: @example
 5468: 4 0 +DO  i .  2 +LOOP
 5469: @end example
 5470: @noindent
 5471: prints @code{0 2}
 5472: 
 5473: @example
 5474: 4 1 +DO  i .  2 +LOOP
 5475: @end example
 5476: @noindent
 5477: prints @code{1 3}
 5478: 
 5479: @item
 5480: @cindex negative increment for counted loops
 5481: @cindex counted loops with negative increment
 5482: The behaviour of @code{@i{n} +LOOP} is peculiar when @i{n} is negative:
 5483: 
 5484: @example
 5485: -1 0 ?DO  i .  -1 +LOOP
 5486: @end example
 5487: @noindent
 5488: prints @code{0 -1}
 5489: 
 5490: @example
 5491: 0 0 ?DO  i .  -1 +LOOP
 5492: @end example
 5493: prints nothing.
 5494: 
 5495: Therefore we recommend avoiding @code{@i{n} +LOOP} with negative
 5496: @i{n}. One alternative is @code{@i{u} -LOOP}, which reduces the
 5497: index by @i{u} each iteration. The loop is terminated when the border
 5498: between @i{limit+1} and @i{limit} is crossed. Gforth also provides
 5499: @code{-DO} and @code{U-DO} for down-counting loops. E.g.:
 5500: 
 5501: @example
 5502: -2 0 -DO  i .  1 -LOOP
 5503: @end example
 5504: @noindent
 5505: prints @code{0 -1}
 5506: 
 5507: @example
 5508: -1 0 -DO  i .  1 -LOOP
 5509: @end example
 5510: @noindent
 5511: prints @code{0}
 5512: 
 5513: @example
 5514: 0 0 -DO  i .  1 -LOOP
 5515: @end example
 5516: @noindent
 5517: prints nothing.
 5518: 
 5519: @end itemize
 5520: 
 5521: Unfortunately, @code{+DO}, @code{U+DO}, @code{-DO}, @code{U-DO} and
 5522: @code{-LOOP} are not defined in ANS Forth. However, an implementation
 5523: for these words that uses only standard words is provided in
 5524: @file{compat/loops.fs}.
 5525: 
 5526: 
 5527: @cindex @code{FOR} loops
 5528: Another counted loop is:
 5529: @example
 5530: @i{n}
 5531: FOR
 5532:   @i{body}
 5533: NEXT
 5534: @end example
 5535: This is the preferred loop of native code compiler writers who are too
 5536: lazy to optimize @code{?DO} loops properly. This loop structure is not
 5537: defined in ANS Forth. In Gforth, this loop iterates @i{n+1} times;
 5538: @code{i} produces values starting with @i{n} and ending with 0. Other
 5539: Forth systems may behave differently, even if they support @code{FOR}
 5540: loops. To avoid problems, don't use @code{FOR} loops.
 5541: 
 5542: @node Arbitrary control structures, Calls and returns, Counted Loops, Control Structures
 5543: @subsection Arbitrary control structures
 5544: @cindex control structures, user-defined
 5545: 
 5546: @cindex control-flow stack
 5547: ANS Forth permits and supports using control structures in a non-nested
 5548: way. Information about incomplete control structures is stored on the
 5549: control-flow stack. This stack may be implemented on the Forth data
 5550: stack, and this is what we have done in Gforth.
 5551: 
 5552: @cindex @code{orig}, control-flow stack item
 5553: @cindex @code{dest}, control-flow stack item
 5554: An @i{orig} entry represents an unresolved forward branch, a @i{dest}
 5555: entry represents a backward branch target. A few words are the basis for
 5556: building any control structure possible (except control structures that
 5557: need storage, like calls, coroutines, and backtracking).
 5558: 
 5559: 
 5560: doc-if
 5561: doc-ahead
 5562: doc-then
 5563: doc-begin
 5564: doc-until
 5565: doc-again
 5566: doc-cs-pick
 5567: doc-cs-roll
 5568: 
 5569: 
 5570: The Standard words @code{CS-PICK} and @code{CS-ROLL} allow you to
 5571: manipulate the control-flow stack in a portable way. Without them, you
 5572: would need to know how many stack items are occupied by a control-flow
 5573: entry (many systems use one cell. In Gforth they currently take three,
 5574: but this may change in the future).
 5575: 
 5576: Some standard control structure words are built from these words:
 5577: 
 5578: 
 5579: doc-else
 5580: doc-while
 5581: doc-repeat
 5582: 
 5583: 
 5584: @noindent
 5585: Gforth adds some more control-structure words:
 5586: 
 5587: 
 5588: doc-endif
 5589: doc-?dup-if
 5590: doc-?dup-0=-if
 5591: 
 5592: 
 5593: @noindent
 5594: Counted loop words constitute a separate group of words:
 5595: 
 5596: 
 5597: doc-?do
 5598: doc-+do
 5599: doc-u+do
 5600: doc--do
 5601: doc-u-do
 5602: doc-do
 5603: doc-for
 5604: doc-loop
 5605: doc-+loop
 5606: doc--loop
 5607: doc-next
 5608: doc-leave
 5609: doc-?leave
 5610: doc-unloop
 5611: doc-done
 5612: 
 5613: 
 5614: The standard does not allow using @code{CS-PICK} and @code{CS-ROLL} on
 5615: @i{do-sys}. Gforth allows it, but it's your job to ensure that for
 5616: every @code{?DO} etc. there is exactly one @code{UNLOOP} on any path
 5617: through the definition (@code{LOOP} etc. compile an @code{UNLOOP} on the
 5618: fall-through path). Also, you have to ensure that all @code{LEAVE}s are
 5619: resolved (by using one of the loop-ending words or @code{DONE}).
 5620: 
 5621: @noindent
 5622: Another group of control structure words are:
 5623: 
 5624: 
 5625: doc-case
 5626: doc-endcase
 5627: doc-of
 5628: doc-endof
 5629: 
 5630: 
 5631: @i{case-sys} and @i{of-sys} cannot be processed using @code{CS-PICK} and
 5632: @code{CS-ROLL}.
 5633: 
 5634: @subsubsection Programming Style
 5635: @cindex control structures programming style
 5636: @cindex programming style, arbitrary control structures
 5637: 
 5638: In order to ensure readability we recommend that you do not create
 5639: arbitrary control structures directly, but define new control structure
 5640: words for the control structure you want and use these words in your
 5641: program. For example, instead of writing:
 5642: 
 5643: @example
 5644: BEGIN
 5645:   ...
 5646: IF [ 1 CS-ROLL ]
 5647:   ...
 5648: AGAIN THEN
 5649: @end example
 5650: 
 5651: @noindent
 5652: we recommend defining control structure words, e.g.,
 5653: 
 5654: @example
 5655: : WHILE ( DEST -- ORIG DEST )
 5656:  POSTPONE IF
 5657:  1 CS-ROLL ; immediate
 5658: 
 5659: : REPEAT ( orig dest -- )
 5660:  POSTPONE AGAIN
 5661:  POSTPONE THEN ; immediate
 5662: @end example
 5663: 
 5664: @noindent
 5665: and then using these to create the control structure:
 5666: 
 5667: @example
 5668: BEGIN
 5669:   ...
 5670: WHILE
 5671:   ...
 5672: REPEAT
 5673: @end example
 5674: 
 5675: That's much easier to read, isn't it? Of course, @code{REPEAT} and
 5676: @code{WHILE} are predefined, so in this example it would not be
 5677: necessary to define them.
 5678: 
 5679: @node Calls and returns, Exception Handling, Arbitrary control structures, Control Structures
 5680: @subsection Calls and returns
 5681: @cindex calling a definition
 5682: @cindex returning from a definition
 5683: 
 5684: @cindex recursive definitions
 5685: A definition can be called simply be writing the name of the definition
 5686: to be called. Normally a definition is invisible during its own
 5687: definition. If you want to write a directly recursive definition, you
 5688: can use @code{recursive} to make the current definition visible, or
 5689: @code{recurse} to call the current definition directly.
 5690: 
 5691: 
 5692: doc-recursive
 5693: doc-recurse
 5694: 
 5695: 
 5696: @comment TODO add example of the two recursion methods
 5697: @quotation
 5698: @progstyle
 5699: I prefer using @code{recursive} to @code{recurse}, because calling the
 5700: definition by name is more descriptive (if the name is well-chosen) than
 5701: the somewhat cryptic @code{recurse}.  E.g., in a quicksort
 5702: implementation, it is much better to read (and think) ``now sort the
 5703: partitions'' than to read ``now do a recursive call''.
 5704: @end quotation
 5705: 
 5706: For mutual recursion, use @code{Defer}red words, like this:
 5707: 
 5708: @example
 5709: Defer foo
 5710: 
 5711: : bar ( ... -- ... )
 5712:  ... foo ... ;
 5713: 
 5714: :noname ( ... -- ... )
 5715:  ... bar ... ;
 5716: IS foo
 5717: @end example
 5718: 
 5719: Deferred words are discussed in more detail in @ref{Deferred Words}.
 5720: 
 5721: The current definition returns control to the calling definition when
 5722: the end of the definition is reached or @code{EXIT} is encountered.
 5723: 
 5724: doc-exit
 5725: doc-;s
 5726: 
 5727: 
 5728: @node Exception Handling,  , Calls and returns, Control Structures
 5729: @subsection Exception Handling
 5730: @cindex exceptions
 5731: 
 5732: @c quit is a very bad idea for error handling, 
 5733: @c because it does not translate into a THROW
 5734: @c it also does not belong into this chapter
 5735: 
 5736: If a word detects an error condition that it cannot handle, it can
 5737: @code{throw} an exception.  In the simplest case, this will terminate
 5738: your program, and report an appropriate error.
 5739: 
 5740: doc-throw
 5741: 
 5742: @code{Throw} consumes a cell-sized error number on the stack. There are
 5743: some predefined error numbers in ANS Forth (see @file{errors.fs}).  In
 5744: Gforth (and most other systems) you can use the iors produced by various
 5745: words as error numbers (e.g., a typical use of @code{allocate} is
 5746: @code{allocate throw}).  Gforth also provides the word @code{exception}
 5747: to define your own error numbers (with decent error reporting); an ANS
 5748: Forth version of this word (but without the error messages) is available
 5749: in @code{compat/except.fs}.  And finally, you can use your own error
 5750: numbers (anything outside the range -4095..0), but won't get nice error
 5751: messages, only numbers.  For example, try:
 5752: 
 5753: @example
 5754: -10 throw                    \ ANS defined
 5755: -267 throw                   \ system defined
 5756: s" my error" exception throw \ user defined
 5757: 7 throw                      \ arbitrary number
 5758: @end example
 5759: 
 5760: doc---exception-exception
 5761: 
 5762: A common idiom to @code{THROW} a specific error if a flag is true is
 5763: this:
 5764: 
 5765: @example
 5766: @code{( flag ) 0<> @i{errno} and throw}
 5767: @end example
 5768: 
 5769: Your program can provide exception handlers to catch exceptions.  An
 5770: exception handler can be used to correct the problem, or to clean up
 5771: some data structures and just throw the exception to the next exception
 5772: handler.  Note that @code{throw} jumps to the dynamically innermost
 5773: exception handler.  The system's exception handler is outermost, and just
 5774: prints an error and restarts command-line interpretation (or, in batch
 5775: mode (i.e., while processing the shell command line), leaves Gforth).
 5776: 
 5777: The ANS Forth way to catch exceptions is @code{catch}:
 5778: 
 5779: doc-catch
 5780: doc-nothrow
 5781: 
 5782: The most common use of exception handlers is to clean up the state when
 5783: an error happens.  E.g.,
 5784: 
 5785: @example
 5786: base @ >r hex \ actually the hex should be inside foo, or we h
 5787: ['] foo catch ( nerror|0 )
 5788: r> base !
 5789: ( nerror|0 ) throw \ pass it on
 5790: @end example
 5791: 
 5792: A use of @code{catch} for handling the error @code{myerror} might look
 5793: like this:
 5794: 
 5795: @example
 5796: ['] foo catch
 5797: CASE
 5798:   myerror OF ... ( do something about it ) nothrow ENDOF
 5799:   dup throw \ default: pass other errors on, do nothing on non-errors
 5800: ENDCASE
 5801: @end example
 5802: 
 5803: Having to wrap the code into a separate word is often cumbersome,
 5804: therefore Gforth provides an alternative syntax:
 5805: 
 5806: @example
 5807: TRY
 5808:   @i{code1}
 5809:   IFERROR
 5810:     @i{code2}
 5811:   THEN
 5812:   @i{code3}
 5813: ENDTRY
 5814: @end example
 5815: 
 5816: This performs @i{code1}.  If @i{code1} completes normally, execution
 5817: continues with @i{code3}.  If there is an exception in @i{code1} or
 5818: before @code{endtry}, the stacks are reset to the depth during
 5819: @code{try}, the throw value is pushed on the data stack, and execution
 5820: constinues at @i{code2}, and finally falls through to @i{code3}.
 5821: 
 5822: doc-try
 5823: doc-endtry
 5824: doc-iferror
 5825: 
 5826: If you don't need @i{code2}, you can write @code{restore} instead of
 5827: @code{iferror then}:
 5828: 
 5829: @example
 5830: TRY
 5831:   @i{code1}
 5832: RESTORE
 5833:   @i{code3}
 5834: ENDTRY
 5835: @end example
 5836: 
 5837: @cindex unwind-protect
 5838: The cleanup example from above in this syntax:
 5839: 
 5840: @example
 5841: base @@ @{ oldbase @}
 5842: TRY
 5843:   hex foo \ now the hex is placed correctly
 5844:   0       \ value for throw
 5845: RESTORE
 5846:   oldbase base !
 5847: ENDTRY
 5848: throw
 5849: @end example
 5850: 
 5851: An additional advantage of this variant is that an exception between
 5852: @code{restore} and @code{endtry} (e.g., from the user pressing
 5853: @kbd{Ctrl-C}) restarts the execution of the code after @code{restore},
 5854: so the base will be restored under all circumstances.
 5855: 
 5856: However, you have to ensure that this code does not cause an exception
 5857: itself, otherwise the @code{iferror}/@code{restore} code will loop.
 5858: Moreover, you should also make sure that the stack contents needed by
 5859: the @code{iferror}/@code{restore} code exist everywhere between
 5860: @code{try} and @code{endtry}; in our example this is achived by
 5861: putting the data in a local before the @code{try} (you cannot use the
 5862: return stack because the exception frame (@i{sys1}) is in the way
 5863: there).
 5864: 
 5865: This kind of usage corresponds to Lisp's @code{unwind-protect}.
 5866: 
 5867: @cindex @code{recover} (old Gforth versions)
 5868: If you do not want this exception-restarting behaviour, you achieve
 5869: this as follows:
 5870: 
 5871: @example
 5872: TRY
 5873:   @i{code1}
 5874: ENDTRY-IFERROR
 5875:   @i{code2}
 5876: THEN
 5877: @end example
 5878: 
 5879: If there is an exception in @i{code1}, then @i{code2} is executed,
 5880: otherwise execution continues behind the @code{then} (or in a possible
 5881: @code{else} branch).  This corresponds to the construct
 5882: 
 5883: @example
 5884: TRY
 5885:   @i{code1}
 5886: RECOVER
 5887:   @i{code2}
 5888: ENDTRY
 5889: @end example
 5890: 
 5891: in Gforth before version 0.7.  So you can directly replace
 5892: @code{recover}-using code; however, we recommend that you check if it
 5893: would not be better to use one of the other @code{try} variants while
 5894: you are at it.
 5895: 
 5896: To ease the transition, Gforth provides two compatibility files:
 5897: @file{endtry-iferror.fs} provides the @code{try ... endtry-iferror
 5898: ... then} syntax (but not @code{iferror} or @code{restore}) for old
 5899: systems; @file{recover-endtry.fs} provides the @code{try ... recover
 5900: ... endtry} syntax on new systems, so you can use that file as a
 5901: stopgap to run old programs.  Both files work on any system (they just
 5902: do nothing if the system already has the syntax it implements), so you
 5903: can unconditionally @code{require} one of these files, even if you use
 5904: a mix old and new systems.
 5905: 
 5906: doc-restore
 5907: doc-endtry-iferror
 5908: 
 5909: Here's the error handling example:
 5910: 
 5911: @example
 5912: TRY
 5913:   foo
 5914: ENDTRY-IFERROR
 5915:   CASE
 5916:     myerror OF ... ( do something about it ) nothrow ENDOF
 5917:     throw \ pass other errors on
 5918:   ENDCASE
 5919: THEN
 5920: @end example
 5921: 
 5922: @progstyle
 5923: As usual, you should ensure that the stack depth is statically known at
 5924: the end: either after the @code{throw} for passing on errors, or after
 5925: the @code{ENDTRY} (or, if you use @code{catch}, after the end of the
 5926: selection construct for handling the error).
 5927: 
 5928: There are two alternatives to @code{throw}: @code{Abort"} is conditional
 5929: and you can provide an error message.  @code{Abort} just produces an
 5930: ``Aborted'' error.
 5931: 
 5932: The problem with these words is that exception handlers cannot
 5933: differentiate between different @code{abort"}s; they just look like
 5934: @code{-2 throw} to them (the error message cannot be accessed by
 5935: standard programs).  Similar @code{abort} looks like @code{-1 throw} to
 5936: exception handlers.
 5937: 
 5938: doc-abort"
 5939: doc-abort
 5940: 
 5941: 
 5942: 
 5943: @c -------------------------------------------------------------
 5944: @node Defining Words, Interpretation and Compilation Semantics, Control Structures, Words
 5945: @section Defining Words
 5946: @cindex defining words
 5947: 
 5948: Defining words are used to extend Forth by creating new entries in the dictionary.
 5949: 
 5950: @menu
 5951: * CREATE::                      
 5952: * Variables::                   Variables and user variables
 5953: * Constants::                   
 5954: * Values::                      Initialised variables
 5955: * Colon Definitions::           
 5956: * Anonymous Definitions::       Definitions without names
 5957: * Supplying names::             Passing definition names as strings
 5958: * User-defined Defining Words::  
 5959: * Deferred Words::              Allow forward references
 5960: * Aliases::                     
 5961: @end menu
 5962: 
 5963: @node CREATE, Variables, Defining Words, Defining Words
 5964: @subsection @code{CREATE}
 5965: @cindex simple defining words
 5966: @cindex defining words, simple
 5967: 
 5968: Defining words are used to create new entries in the dictionary. The
 5969: simplest defining word is @code{CREATE}. @code{CREATE} is used like
 5970: this:
 5971: 
 5972: @example
 5973: CREATE new-word1
 5974: @end example
 5975: 
 5976: @code{CREATE} is a parsing word, i.e., it takes an argument from the
 5977: input stream (@code{new-word1} in our example).  It generates a
 5978: dictionary entry for @code{new-word1}. When @code{new-word1} is
 5979: executed, all that it does is leave an address on the stack. The address
 5980: represents the value of the data space pointer (@code{HERE}) at the time
 5981: that @code{new-word1} was defined. Therefore, @code{CREATE} is a way of
 5982: associating a name with the address of a region of memory.
 5983: 
 5984: doc-create
 5985: 
 5986: Note that in ANS Forth guarantees only for @code{create} that its body
 5987: is in dictionary data space (i.e., where @code{here}, @code{allot}
 5988: etc. work, @pxref{Dictionary allocation}).  Also, in ANS Forth only
 5989: @code{create}d words can be modified with @code{does>}
 5990: (@pxref{User-defined Defining Words}).  And in ANS Forth @code{>body}
 5991: can only be applied to @code{create}d words.
 5992: 
 5993: By extending this example to reserve some memory in data space, we end
 5994: up with something like a @i{variable}. Here are two different ways to do
 5995: it:
 5996: 
 5997: @example
 5998: CREATE new-word2 1 cells allot  \ reserve 1 cell - initial value undefined
 5999: CREATE new-word3 4 ,            \ reserve 1 cell and initialise it (to 4)
 6000: @end example
 6001: 
 6002: The variable can be examined and modified using @code{@@} (``fetch'') and
 6003: @code{!} (``store'') like this:
 6004: 
 6005: @example
 6006: new-word2 @@ .      \ get address, fetch from it and display
 6007: 1234 new-word2 !   \ new value, get address, store to it
 6008: @end example
 6009: 
 6010: @cindex arrays
 6011: A similar mechanism can be used to create arrays. For example, an
 6012: 80-character text input buffer:
 6013: 
 6014: @example
 6015: CREATE text-buf 80 chars allot
 6016: 
 6017: text-buf 0 chars + c@@ \ the 1st character (offset 0)
 6018: text-buf 3 chars + c@@ \ the 4th character (offset 3)
 6019: @end example
 6020: 
 6021: You can build arbitrarily complex data structures by allocating
 6022: appropriate areas of memory. For further discussions of this, and to
 6023: learn about some Gforth tools that make it easier,
 6024: @xref{Structures}.
 6025: 
 6026: 
 6027: @node Variables, Constants, CREATE, Defining Words
 6028: @subsection Variables
 6029: @cindex variables
 6030: 
 6031: The previous section showed how a sequence of commands could be used to
 6032: generate a variable.  As a final refinement, the whole code sequence can
 6033: be wrapped up in a defining word (pre-empting the subject of the next
 6034: section), making it easier to create new variables:
 6035: 
 6036: @example
 6037: : myvariableX ( "name" -- a-addr ) CREATE 1 cells allot ;
 6038: : myvariable0 ( "name" -- a-addr ) CREATE 0 , ;
 6039: 
 6040: myvariableX foo \ variable foo starts off with an unknown value
 6041: myvariable0 joe \ whilst joe is initialised to 0
 6042: 
 6043: 45 3 * foo !   \ set foo to 135
 6044: 1234 joe !     \ set joe to 1234
 6045: 3 joe +!       \ increment joe by 3.. to 1237
 6046: @end example
 6047: 
 6048: Not surprisingly, there is no need to define @code{myvariable}, since
 6049: Forth already has a definition @code{Variable}. ANS Forth does not
 6050: guarantee that a @code{Variable} is initialised when it is created
 6051: (i.e., it may behave like @code{myvariableX}). In contrast, Gforth's
 6052: @code{Variable} initialises the variable to 0 (i.e., it behaves exactly
 6053: like @code{myvariable0}). Forth also provides @code{2Variable} and
 6054: @code{fvariable} for double and floating-point variables, respectively
 6055: -- they are initialised to 0. and 0e in Gforth. If you use a @code{Variable} to
 6056: store a boolean, you can use @code{on} and @code{off} to toggle its
 6057: state.
 6058: 
 6059: doc-variable
 6060: doc-2variable
 6061: doc-fvariable
 6062: 
 6063: @cindex user variables
 6064: @cindex user space
 6065: The defining word @code{User} behaves in the same way as @code{Variable}.
 6066: The difference is that it reserves space in @i{user (data) space} rather
 6067: than normal data space. In a Forth system that has a multi-tasker, each
 6068: task has its own set of user variables.
 6069: 
 6070: doc-user
 6071: @c doc-udp
 6072: @c doc-uallot
 6073: 
 6074: @comment TODO is that stuff about user variables strictly correct? Is it
 6075: @comment just terminal tasks that have user variables?
 6076: @comment should document tasker.fs (with some examples) elsewhere
 6077: @comment in this manual, then expand on user space and user variables.
 6078: 
 6079: @node Constants, Values, Variables, Defining Words
 6080: @subsection Constants
 6081: @cindex constants
 6082: 
 6083: @code{Constant} allows you to declare a fixed value and refer to it by
 6084: name. For example:
 6085: 
 6086: @example
 6087: 12 Constant INCHES-PER-FOOT
 6088: 3E+08 fconstant SPEED-O-LIGHT
 6089: @end example
 6090: 
 6091: A @code{Variable} can be both read and written, so its run-time
 6092: behaviour is to supply an address through which its current value can be
 6093: manipulated. In contrast, the value of a @code{Constant} cannot be
 6094: changed once it has been declared@footnote{Well, often it can be -- but
 6095: not in a Standard, portable way. It's safer to use a @code{Value} (read
 6096: on).} so it's not necessary to supply the address -- it is more
 6097: efficient to return the value of the constant directly. That's exactly
 6098: what happens; the run-time effect of a constant is to put its value on
 6099: the top of the stack (You can find one
 6100: way of implementing @code{Constant} in @ref{User-defined Defining Words}).
 6101: 
 6102: Forth also provides @code{2Constant} and @code{fconstant} for defining
 6103: double and floating-point constants, respectively.
 6104: 
 6105: doc-constant
 6106: doc-2constant
 6107: doc-fconstant
 6108: 
 6109: @c that's too deep, and it's not necessarily true for all ANS Forths. - anton
 6110: @c nac-> How could that not be true in an ANS Forth? You can't define a
 6111: @c constant, use it and then delete the definition of the constant..
 6112: 
 6113: @c anton->An ANS Forth system can compile a constant to a literal; On
 6114: @c decompilation you would see only the number, just as if it had been used
 6115: @c in the first place.  The word will stay, of course, but it will only be
 6116: @c used by the text interpreter (no run-time duties, except when it is 
 6117: @c POSTPONEd or somesuch).
 6118: 
 6119: @c nac:
 6120: @c I agree that it's rather deep, but IMO it is an important difference
 6121: @c relative to other programming languages.. often it's annoying: it
 6122: @c certainly changes my programming style relative to C.
 6123: 
 6124: @c anton: In what way?
 6125: 
 6126: Constants in Forth behave differently from their equivalents in other
 6127: programming languages. In other languages, a constant (such as an EQU in
 6128: assembler or a #define in C) only exists at compile-time; in the
 6129: executable program the constant has been translated into an absolute
 6130: number and, unless you are using a symbolic debugger, it's impossible to
 6131: know what abstract thing that number represents. In Forth a constant has
 6132: an entry in the header space and remains there after the code that uses
 6133: it has been defined. In fact, it must remain in the dictionary since it
 6134: has run-time duties to perform. For example:
 6135: 
 6136: @example
 6137: 12 Constant INCHES-PER-FOOT
 6138: : FEET-TO-INCHES ( n1 -- n2 ) INCHES-PER-FOOT * ;
 6139: @end example
 6140: 
 6141: @cindex in-lining of constants
 6142: When @code{FEET-TO-INCHES} is executed, it will in turn execute the xt
 6143: associated with the constant @code{INCHES-PER-FOOT}. If you use
 6144: @code{see} to decompile the definition of @code{FEET-TO-INCHES}, you can
 6145: see that it makes a call to @code{INCHES-PER-FOOT}. Some Forth compilers
 6146: attempt to optimise constants by in-lining them where they are used. You
 6147: can force Gforth to in-line a constant like this:
 6148: 
 6149: @example
 6150: : FEET-TO-INCHES ( n1 -- n2 ) [ INCHES-PER-FOOT ] LITERAL * ;
 6151: @end example
 6152: 
 6153: If you use @code{see} to decompile @i{this} version of
 6154: @code{FEET-TO-INCHES}, you can see that @code{INCHES-PER-FOOT} is no
 6155: longer present. To understand how this works, read
 6156: @ref{Interpret/Compile states}, and @ref{Literals}.
 6157: 
 6158: In-lining constants in this way might improve execution time
 6159: fractionally, and can ensure that a constant is now only referenced at
 6160: compile-time. However, the definition of the constant still remains in
 6161: the dictionary. Some Forth compilers provide a mechanism for controlling
 6162: a second dictionary for holding transient words such that this second
 6163: dictionary can be deleted later in order to recover memory
 6164: space. However, there is no standard way of doing this.
 6165: 
 6166: 
 6167: @node Values, Colon Definitions, Constants, Defining Words
 6168: @subsection Values
 6169: @cindex values
 6170: 
 6171: A @code{Value} behaves like a @code{Constant}, but it can be changed.
 6172: @code{TO} is a parsing word that changes a @code{Values}.  In Gforth
 6173: (not in ANS Forth) you can access (and change) a @code{value} also with
 6174: @code{>body}.
 6175: 
 6176: Here are some
 6177: examples:
 6178: 
 6179: @example
 6180: 12 Value APPLES     \ Define APPLES with an initial value of 12
 6181: 34 TO APPLES        \ Change the value of APPLES. TO is a parsing word
 6182: 1 ' APPLES >body +! \ Increment APPLES.  Non-standard usage.
 6183: APPLES              \ puts 35 on the top of the stack.
 6184: @end example
 6185: 
 6186: doc-value
 6187: doc-to
 6188: 
 6189: 
 6190: 
 6191: @node Colon Definitions, Anonymous Definitions, Values, Defining Words
 6192: @subsection Colon Definitions
 6193: @cindex colon definitions
 6194: 
 6195: @example
 6196: : name ( ... -- ... )
 6197:     word1 word2 word3 ;
 6198: @end example
 6199: 
 6200: @noindent
 6201: Creates a word called @code{name} that, upon execution, executes
 6202: @code{word1 word2 word3}. @code{name} is a @dfn{(colon) definition}.
 6203: 
 6204: The explanation above is somewhat superficial. For simple examples of
 6205: colon definitions see @ref{Your first definition}.  For an in-depth
 6206: discussion of some of the issues involved, @xref{Interpretation and
 6207: Compilation Semantics}.
 6208: 
 6209: doc-:
 6210: doc-;
 6211: 
 6212: 
 6213: @node Anonymous Definitions, Supplying names, Colon Definitions, Defining Words
 6214: @subsection Anonymous Definitions
 6215: @cindex colon definitions
 6216: @cindex defining words without name
 6217: 
 6218: Sometimes you want to define an @dfn{anonymous word}; a word without a
 6219: name. You can do this with:
 6220: 
 6221: doc-:noname
 6222: 
 6223: This leaves the execution token for the word on the stack after the
 6224: closing @code{;}. Here's an example in which a deferred word is
 6225: initialised with an @code{xt} from an anonymous colon definition:
 6226: 
 6227: @example
 6228: Defer deferred
 6229: :noname ( ... -- ... )
 6230:   ... ;
 6231: IS deferred
 6232: @end example
 6233: 
 6234: @noindent
 6235: Gforth provides an alternative way of doing this, using two separate
 6236: words:
 6237: 
 6238: doc-noname
 6239: @cindex execution token of last defined word
 6240: doc-latestxt
 6241: 
 6242: @noindent
 6243: The previous example can be rewritten using @code{noname} and
 6244: @code{latestxt}:
 6245: 
 6246: @example
 6247: Defer deferred
 6248: noname : ( ... -- ... )
 6249:   ... ;
 6250: latestxt IS deferred
 6251: @end example
 6252: 
 6253: @noindent
 6254: @code{noname} works with any defining word, not just @code{:}.
 6255: 
 6256: @code{latestxt} also works when the last word was not defined as
 6257: @code{noname}.  It does not work for combined words, though.  It also has
 6258: the useful property that is is valid as soon as the header for a
 6259: definition has been built. Thus:
 6260: 
 6261: @example
 6262: latestxt . : foo [ latestxt . ] ; ' foo .
 6263: @end example
 6264: 
 6265: @noindent
 6266: prints 3 numbers; the last two are the same.
 6267: 
 6268: @node Supplying names, User-defined Defining Words, Anonymous Definitions, Defining Words
 6269: @subsection Supplying the name of a defined word
 6270: @cindex names for defined words
 6271: @cindex defining words, name given in a string
 6272: 
 6273: By default, a defining word takes the name for the defined word from the
 6274: input stream. Sometimes you want to supply the name from a string. You
 6275: can do this with:
 6276: 
 6277: doc-nextname
 6278: 
 6279: For example:
 6280: 
 6281: @example
 6282: s" foo" nextname create
 6283: @end example
 6284: 
 6285: @noindent
 6286: is equivalent to:
 6287: 
 6288: @example
 6289: create foo
 6290: @end example
 6291: 
 6292: @noindent
 6293: @code{nextname} works with any defining word.
 6294: 
 6295: 
 6296: @node User-defined Defining Words, Deferred Words, Supplying names, Defining Words
 6297: @subsection User-defined Defining Words
 6298: @cindex user-defined defining words
 6299: @cindex defining words, user-defined
 6300: 
 6301: You can create a new defining word by wrapping defining-time code around
 6302: an existing defining word and putting the sequence in a colon
 6303: definition. 
 6304: 
 6305: @c anton: This example is very complex and leads in a quite different
 6306: @c direction from the CREATE-DOES> stuff that follows.  It should probably
 6307: @c be done elsewhere, or as a subsubsection of this subsection (or as a
 6308: @c subsection of Defining Words)
 6309: 
 6310: For example, suppose that you have a word @code{stats} that
 6311: gathers statistics about colon definitions given the @i{xt} of the
 6312: definition, and you want every colon definition in your application to
 6313: make a call to @code{stats}. You can define and use a new version of
 6314: @code{:} like this:
 6315: 
 6316: @example
 6317: : stats ( xt -- ) DUP ." (Gathering statistics for " . ." )"
 6318:   ... ;  \ other code
 6319: 
 6320: : my: : latestxt postpone literal ['] stats compile, ;
 6321: 
 6322: my: foo + - ;
 6323: @end example
 6324: 
 6325: When @code{foo} is defined using @code{my:} these steps occur:
 6326: 
 6327: @itemize @bullet
 6328: @item
 6329: @code{my:} is executed.
 6330: @item
 6331: The @code{:} within the definition (the one between @code{my:} and
 6332: @code{latestxt}) is executed, and does just what it always does; it parses
 6333: the input stream for a name, builds a dictionary header for the name
 6334: @code{foo} and switches @code{state} from interpret to compile.
 6335: @item
 6336: The word @code{latestxt} is executed. It puts the @i{xt} for the word that is
 6337: being defined -- @code{foo} -- onto the stack.
 6338: @item
 6339: The code that was produced by @code{postpone literal} is executed; this
 6340: causes the value on the stack to be compiled as a literal in the code
 6341: area of @code{foo}.
 6342: @item
 6343: The code @code{['] stats} compiles a literal into the definition of
 6344: @code{my:}. When @code{compile,} is executed, that literal -- the
 6345: execution token for @code{stats} -- is layed down in the code area of
 6346: @code{foo} , following the literal@footnote{Strictly speaking, the
 6347: mechanism that @code{compile,} uses to convert an @i{xt} into something
 6348: in the code area is implementation-dependent. A threaded implementation
 6349: might spit out the execution token directly whilst another
 6350: implementation might spit out a native code sequence.}.
 6351: @item
 6352: At this point, the execution of @code{my:} is complete, and control
 6353: returns to the text interpreter. The text interpreter is in compile
 6354: state, so subsequent text @code{+ -} is compiled into the definition of
 6355: @code{foo} and the @code{;} terminates the definition as always.
 6356: @end itemize
 6357: 
 6358: You can use @code{see} to decompile a word that was defined using
 6359: @code{my:} and see how it is different from a normal @code{:}
 6360: definition. For example:
 6361: 
 6362: @example
 6363: : bar + - ;  \ like foo but using : rather than my:
 6364: see bar
 6365: : bar
 6366:   + - ;
 6367: see foo
 6368: : foo
 6369:   107645672 stats + - ;
 6370: 
 6371: \ use ' foo . to show that 107645672 is the xt for foo
 6372: @end example
 6373: 
 6374: You can use techniques like this to make new defining words in terms of
 6375: @i{any} existing defining word.
 6376: 
 6377: 
 6378: @cindex defining defining words
 6379: @cindex @code{CREATE} ... @code{DOES>}
 6380: If you want the words defined with your defining words to behave
 6381: differently from words defined with standard defining words, you can
 6382: write your defining word like this:
 6383: 
 6384: @example
 6385: : def-word ( "name" -- )
 6386:     CREATE @i{code1}
 6387: DOES> ( ... -- ... )
 6388:     @i{code2} ;
 6389: 
 6390: def-word name
 6391: @end example
 6392: 
 6393: @cindex child words
 6394: This fragment defines a @dfn{defining word} @code{def-word} and then
 6395: executes it.  When @code{def-word} executes, it @code{CREATE}s a new
 6396: word, @code{name}, and executes the code @i{code1}. The code @i{code2}
 6397: is not executed at this time. The word @code{name} is sometimes called a
 6398: @dfn{child} of @code{def-word}.
 6399: 
 6400: When you execute @code{name}, the address of the body of @code{name} is
 6401: put on the data stack and @i{code2} is executed (the address of the body
 6402: of @code{name} is the address @code{HERE} returns immediately after the
 6403: @code{CREATE}, i.e., the address a @code{create}d word returns by
 6404: default).
 6405: 
 6406: @c anton:
 6407: @c www.dictionary.com says:
 6408: @c at·a·vism: 1.The reappearance of a characteristic in an organism after
 6409: @c several generations of absence, usually caused by the chance
 6410: @c recombination of genes.  2.An individual or a part that exhibits
 6411: @c atavism. Also called throwback.  3.The return of a trait or recurrence
 6412: @c of previous behavior after a period of absence.
 6413: @c
 6414: @c Doesn't seem to fit.
 6415: 
 6416: @c @cindex atavism in child words
 6417: You can use @code{def-word} to define a set of child words that behave
 6418: similarly; they all have a common run-time behaviour determined by
 6419: @i{code2}. Typically, the @i{code1} sequence builds a data area in the
 6420: body of the child word. The structure of the data is common to all
 6421: children of @code{def-word}, but the data values are specific -- and
 6422: private -- to each child word. When a child word is executed, the
 6423: address of its private data area is passed as a parameter on TOS to be
 6424: used and manipulated@footnote{It is legitimate both to read and write to
 6425: this data area.} by @i{code2}.
 6426: 
 6427: The two fragments of code that make up the defining words act (are
 6428: executed) at two completely separate times:
 6429: 
 6430: @itemize @bullet
 6431: @item
 6432: At @i{define time}, the defining word executes @i{code1} to generate a
 6433: child word
 6434: @item
 6435: At @i{child execution time}, when a child word is invoked, @i{code2}
 6436: is executed, using parameters (data) that are private and specific to
 6437: the child word.
 6438: @end itemize
 6439: 
 6440: Another way of understanding the behaviour of @code{def-word} and
 6441: @code{name} is to say that, if you make the following definitions:
 6442: @example
 6443: : def-word1 ( "name" -- )
 6444:     CREATE @i{code1} ;
 6445: 
 6446: : action1 ( ... -- ... )
 6447:     @i{code2} ;
 6448: 
 6449: def-word1 name1
 6450: @end example
 6451: 
 6452: @noindent
 6453: Then using @code{name1 action1} is equivalent to using @code{name}.
 6454: 
 6455: The classic example is that you can define @code{CONSTANT} in this way:
 6456: 
 6457: @example
 6458: : CONSTANT ( w "name" -- )
 6459:     CREATE ,
 6460: DOES> ( -- w )
 6461:     @@ ;
 6462: @end example
 6463: 
 6464: @comment There is a beautiful description of how this works and what
 6465: @comment it does in the Forthwrite 100th edition.. as well as an elegant
 6466: @comment commentary on the Counting Fruits problem.
 6467: 
 6468: When you create a constant with @code{5 CONSTANT five}, a set of
 6469: define-time actions take place; first a new word @code{five} is created,
 6470: then the value 5 is laid down in the body of @code{five} with
 6471: @code{,}. When @code{five} is executed, the address of the body is put on
 6472: the stack, and @code{@@} retrieves the value 5. The word @code{five} has
 6473: no code of its own; it simply contains a data field and a pointer to the
 6474: code that follows @code{DOES>} in its defining word. That makes words
 6475: created in this way very compact.
 6476: 
 6477: The final example in this section is intended to remind you that space
 6478: reserved in @code{CREATE}d words is @i{data} space and therefore can be
 6479: both read and written by a Standard program@footnote{Exercise: use this
 6480: example as a starting point for your own implementation of @code{Value}
 6481: and @code{TO} -- if you get stuck, investigate the behaviour of @code{'} and
 6482: @code{[']}.}:
 6483: 
 6484: @example
 6485: : foo ( "name" -- )
 6486:     CREATE -1 ,
 6487: DOES> ( -- )
 6488:     @@ . ;
 6489: 
 6490: foo first-word
 6491: foo second-word
 6492: 
 6493: 123 ' first-word >BODY !
 6494: @end example
 6495: 
 6496: If @code{first-word} had been a @code{CREATE}d word, we could simply
 6497: have executed it to get the address of its data field. However, since it
 6498: was defined to have @code{DOES>} actions, its execution semantics are to
 6499: perform those @code{DOES>} actions. To get the address of its data field
 6500: it's necessary to use @code{'} to get its xt, then @code{>BODY} to
 6501: translate the xt into the address of the data field.  When you execute
 6502: @code{first-word}, it will display @code{123}. When you execute
 6503: @code{second-word} it will display @code{-1}.
 6504: 
 6505: @cindex stack effect of @code{DOES>}-parts
 6506: @cindex @code{DOES>}-parts, stack effect
 6507: In the examples above the stack comment after the @code{DOES>} specifies
 6508: the stack effect of the defined words, not the stack effect of the
 6509: following code (the following code expects the address of the body on
 6510: the top of stack, which is not reflected in the stack comment). This is
 6511: the convention that I use and recommend (it clashes a bit with using
 6512: locals declarations for stack effect specification, though).
 6513: 
 6514: @menu
 6515: * CREATE..DOES> applications::  
 6516: * CREATE..DOES> details::       
 6517: * Advanced does> usage example::  
 6518: * Const-does>::                 
 6519: @end menu
 6520: 
 6521: @node CREATE..DOES> applications, CREATE..DOES> details, User-defined Defining Words, User-defined Defining Words
 6522: @subsubsection Applications of @code{CREATE..DOES>}
 6523: @cindex @code{CREATE} ... @code{DOES>}, applications
 6524: 
 6525: You may wonder how to use this feature. Here are some usage patterns:
 6526: 
 6527: @cindex factoring similar colon definitions
 6528: When you see a sequence of code occurring several times, and you can
 6529: identify a meaning, you will factor it out as a colon definition. When
 6530: you see similar colon definitions, you can factor them using
 6531: @code{CREATE..DOES>}. E.g., an assembler usually defines several words
 6532: that look very similar:
 6533: @example
 6534: : ori, ( reg-target reg-source n -- )
 6535:     0 asm-reg-reg-imm ;
 6536: : andi, ( reg-target reg-source n -- )
 6537:     1 asm-reg-reg-imm ;
 6538: @end example
 6539: 
 6540: @noindent
 6541: This could be factored with:
 6542: @example
 6543: : reg-reg-imm ( op-code -- )
 6544:     CREATE ,
 6545: DOES> ( reg-target reg-source n -- )
 6546:     @@ asm-reg-reg-imm ;
 6547: 
 6548: 0 reg-reg-imm ori,
 6549: 1 reg-reg-imm andi,
 6550: @end example
 6551: 
 6552: @cindex currying
 6553: Another view of @code{CREATE..DOES>} is to consider it as a crude way to
 6554: supply a part of the parameters for a word (known as @dfn{currying} in
 6555: the functional language community). E.g., @code{+} needs two
 6556: parameters. Creating versions of @code{+} with one parameter fixed can
 6557: be done like this:
 6558: 
 6559: @example
 6560: : curry+ ( n1 "name" -- )
 6561:     CREATE ,
 6562: DOES> ( n2 -- n1+n2 )
 6563:     @@ + ;
 6564: 
 6565:  3 curry+ 3+
 6566: -2 curry+ 2-
 6567: @end example
 6568: 
 6569: 
 6570: @node CREATE..DOES> details, Advanced does> usage example, CREATE..DOES> applications, User-defined Defining Words
 6571: @subsubsection The gory details of @code{CREATE..DOES>}
 6572: @cindex @code{CREATE} ... @code{DOES>}, details
 6573: 
 6574: doc-does>
 6575: 
 6576: @cindex @code{DOES>} in a separate definition
 6577: This means that you need not use @code{CREATE} and @code{DOES>} in the
 6578: same definition; you can put the @code{DOES>}-part in a separate
 6579: definition. This allows us to, e.g., select among different @code{DOES>}-parts:
 6580: @example
 6581: : does1 
 6582: DOES> ( ... -- ... )
 6583:     ... ;
 6584: 
 6585: : does2
 6586: DOES> ( ... -- ... )
 6587:     ... ;
 6588: 
 6589: : def-word ( ... -- ... )
 6590:     create ...
 6591:     IF
 6592:        does1
 6593:     ELSE
 6594:        does2
 6595:     ENDIF ;
 6596: @end example
 6597: 
 6598: In this example, the selection of whether to use @code{does1} or
 6599: @code{does2} is made at definition-time; at the time that the child word is
 6600: @code{CREATE}d.
 6601: 
 6602: @cindex @code{DOES>} in interpretation state
 6603: In a standard program you can apply a @code{DOES>}-part only if the last
 6604: word was defined with @code{CREATE}. In Gforth, the @code{DOES>}-part
 6605: will override the behaviour of the last word defined in any case. In a
 6606: standard program, you can use @code{DOES>} only in a colon
 6607: definition. In Gforth, you can also use it in interpretation state, in a
 6608: kind of one-shot mode; for example:
 6609: @example
 6610: CREATE name ( ... -- ... )
 6611:   @i{initialization}
 6612: DOES>
 6613:   @i{code} ;
 6614: @end example
 6615: 
 6616: @noindent
 6617: is equivalent to the standard:
 6618: @example
 6619: :noname
 6620: DOES>
 6621:     @i{code} ;
 6622: CREATE name EXECUTE ( ... -- ... )
 6623:     @i{initialization}
 6624: @end example
 6625: 
 6626: doc->body
 6627: 
 6628: @node Advanced does> usage example, Const-does>, CREATE..DOES> details, User-defined Defining Words
 6629: @subsubsection Advanced does> usage example
 6630: 
 6631: The MIPS disassembler (@file{arch/mips/disasm.fs}) contains many words
 6632: for disassembling instructions, that follow a very repetetive scheme:
 6633: 
 6634: @example
 6635: :noname @var{disasm-operands} s" @var{inst-name}" type ;
 6636: @var{entry-num} cells @var{table} + !
 6637: @end example
 6638: 
 6639: Of course, this inspires the idea to factor out the commonalities to
 6640: allow a definition like
 6641: 
 6642: @example
 6643: @var{disasm-operands} @var{entry-num} @var{table} define-inst @var{inst-name}
 6644: @end example
 6645: 
 6646: The parameters @var{disasm-operands} and @var{table} are usually
 6647: correlated.  Moreover, before I wrote the disassembler, there already
 6648: existed code that defines instructions like this:
 6649: 
 6650: @example
 6651: @var{entry-num} @var{inst-format} @var{inst-name}
 6652: @end example
 6653: 
 6654: This code comes from the assembler and resides in
 6655: @file{arch/mips/insts.fs}.
 6656: 
 6657: So I had to define the @var{inst-format} words that performed the scheme
 6658: above when executed.  At first I chose to use run-time code-generation:
 6659: 
 6660: @example
 6661: : @var{inst-format} ( entry-num "name" -- ; compiled code: addr w -- )
 6662:   :noname Postpone @var{disasm-operands}
 6663:   name Postpone sliteral Postpone type Postpone ;
 6664:   swap cells @var{table} + ! ;
 6665: @end example
 6666: 
 6667: Note that this supplies the other two parameters of the scheme above.
 6668: 
 6669: An alternative would have been to write this using
 6670: @code{create}/@code{does>}:
 6671: 
 6672: @example
 6673: : @var{inst-format} ( entry-num "name" -- )
 6674:   here name string, ( entry-num c-addr ) \ parse and save "name"
 6675:   noname create , ( entry-num )
 6676:   latestxt swap cells @var{table} + !
 6677: does> ( addr w -- )
 6678:   \ disassemble instruction w at addr
 6679:   @@ >r 
 6680:   @var{disasm-operands}
 6681:   r> count type ;
 6682: @end example
 6683: 
 6684: Somehow the first solution is simpler, mainly because it's simpler to
 6685: shift a string from definition-time to use-time with @code{sliteral}
 6686: than with @code{string,} and friends.
 6687: 
 6688: I wrote a lot of words following this scheme and soon thought about
 6689: factoring out the commonalities among them.  Note that this uses a
 6690: two-level defining word, i.e., a word that defines ordinary defining
 6691: words.
 6692: 
 6693: This time a solution involving @code{postpone} and friends seemed more
 6694: difficult (try it as an exercise), so I decided to use a
 6695: @code{create}/@code{does>} word; since I was already at it, I also used
 6696: @code{create}/@code{does>} for the lower level (try using
 6697: @code{postpone} etc. as an exercise), resulting in the following
 6698: definition:
 6699: 
 6700: @example
 6701: : define-format ( disasm-xt table-xt -- )
 6702:     \ define an instruction format that uses disasm-xt for
 6703:     \ disassembling and enters the defined instructions into table
 6704:     \ table-xt
 6705:     create 2,
 6706: does> ( u "inst" -- )
 6707:     \ defines an anonymous word for disassembling instruction inst,
 6708:     \ and enters it as u-th entry into table-xt
 6709:     2@@ swap here name string, ( u table-xt disasm-xt c-addr ) \ remember string
 6710:     noname create 2,      \ define anonymous word
 6711:     execute latestxt swap ! \ enter xt of defined word into table-xt
 6712: does> ( addr w -- )
 6713:     \ disassemble instruction w at addr
 6714:     2@@ >r ( addr w disasm-xt R: c-addr )
 6715:     execute ( R: c-addr ) \ disassemble operands
 6716:     r> count type ; \ print name 
 6717: @end example
 6718: 
 6719: Note that the tables here (in contrast to above) do the @code{cells +}
 6720: by themselves (that's why you have to pass an xt).  This word is used in
 6721: the following way:
 6722: 
 6723: @example
 6724: ' @var{disasm-operands} ' @var{table} define-format @var{inst-format}
 6725: @end example
 6726: 
 6727: As shown above, the defined instruction format is then used like this:
 6728: 
 6729: @example
 6730: @var{entry-num} @var{inst-format} @var{inst-name}
 6731: @end example
 6732: 
 6733: In terms of currying, this kind of two-level defining word provides the
 6734: parameters in three stages: first @var{disasm-operands} and @var{table},
 6735: then @var{entry-num} and @var{inst-name}, finally @code{addr w}, i.e.,
 6736: the instruction to be disassembled.  
 6737: 
 6738: Of course this did not quite fit all the instruction format names used
 6739: in @file{insts.fs}, so I had to define a few wrappers that conditioned
 6740: the parameters into the right form.
 6741: 
 6742: If you have trouble following this section, don't worry.  First, this is
 6743: involved and takes time (and probably some playing around) to
 6744: understand; second, this is the first two-level
 6745: @code{create}/@code{does>} word I have written in seventeen years of
 6746: Forth; and if I did not have @file{insts.fs} to start with, I may well
 6747: have elected to use just a one-level defining word (with some repeating
 6748: of parameters when using the defining word). So it is not necessary to
 6749: understand this, but it may improve your understanding of Forth.
 6750: 
 6751: 
 6752: @node Const-does>,  , Advanced does> usage example, User-defined Defining Words
 6753: @subsubsection @code{Const-does>}
 6754: 
 6755: A frequent use of @code{create}...@code{does>} is for transferring some
 6756: values from definition-time to run-time.  Gforth supports this use with
 6757: 
 6758: doc-const-does>
 6759: 
 6760: A typical use of this word is:
 6761: 
 6762: @example
 6763: : curry+ ( n1 "name" -- )
 6764: 1 0 CONST-DOES> ( n2 -- n1+n2 )
 6765:     + ;
 6766: 
 6767: 3 curry+ 3+
 6768: @end example
 6769: 
 6770: Here the @code{1 0} means that 1 cell and 0 floats are transferred from
 6771: definition to run-time.
 6772: 
 6773: The advantages of using @code{const-does>} are:
 6774: 
 6775: @itemize
 6776: 
 6777: @item
 6778: You don't have to deal with storing and retrieving the values, i.e.,
 6779: your program becomes more writable and readable.
 6780: 
 6781: @item
 6782: When using @code{does>}, you have to introduce a @code{@@} that cannot
 6783: be optimized away (because you could change the data using
 6784: @code{>body}...@code{!}); @code{const-does>} avoids this problem.
 6785: 
 6786: @end itemize
 6787: 
 6788: An ANS Forth implementation of @code{const-does>} is available in
 6789: @file{compat/const-does.fs}.
 6790: 
 6791: 
 6792: @node Deferred Words, Aliases, User-defined Defining Words, Defining Words
 6793: @subsection Deferred Words
 6794: @cindex deferred words
 6795: 
 6796: The defining word @code{Defer} allows you to define a word by name
 6797: without defining its behaviour; the definition of its behaviour is
 6798: deferred. Here are two situation where this can be useful:
 6799: 
 6800: @itemize @bullet
 6801: @item
 6802: Where you want to allow the behaviour of a word to be altered later, and
 6803: for all precompiled references to the word to change when its behaviour
 6804: is changed.
 6805: @item
 6806: For mutual recursion; @xref{Calls and returns}.
 6807: @end itemize
 6808: 
 6809: In the following example, @code{foo} always invokes the version of
 6810: @code{greet} that prints ``@code{Good morning}'' whilst @code{bar}
 6811: always invokes the version that prints ``@code{Hello}''. There is no way
 6812: of getting @code{foo} to use the later version without re-ordering the
 6813: source code and recompiling it.
 6814: 
 6815: @example
 6816: : greet ." Good morning" ;
 6817: : foo ... greet ... ;
 6818: : greet ." Hello" ;
 6819: : bar ... greet ... ;
 6820: @end example
 6821: 
 6822: This problem can be solved by defining @code{greet} as a @code{Defer}red
 6823: word. The behaviour of a @code{Defer}red word can be defined and
 6824: redefined at any time by using @code{IS} to associate the xt of a
 6825: previously-defined word with it. The previous example becomes:
 6826: 
 6827: @example
 6828: Defer greet ( -- )
 6829: : foo ... greet ... ;
 6830: : bar ... greet ... ;
 6831: : greet1 ( -- ) ." Good morning" ;
 6832: : greet2 ( -- ) ." Hello" ;
 6833: ' greet2 IS greet  \ make greet behave like greet2
 6834: @end example
 6835: 
 6836: @progstyle
 6837: You should write a stack comment for every deferred word, and put only
 6838: XTs into deferred words that conform to this stack effect.  Otherwise
 6839: it's too difficult to use the deferred word.
 6840: 
 6841: A deferred word can be used to improve the statistics-gathering example
 6842: from @ref{User-defined Defining Words}; rather than edit the
 6843: application's source code to change every @code{:} to a @code{my:}, do
 6844: this:
 6845: 
 6846: @example
 6847: : real: : ;     \ retain access to the original
 6848: defer :         \ redefine as a deferred word
 6849: ' my: IS :      \ use special version of :
 6850: \
 6851: \ load application here
 6852: \
 6853: ' real: IS :    \ go back to the original
 6854: @end example
 6855: 
 6856: 
 6857: One thing to note is that @code{IS} has special compilation semantics,
 6858: such that it parses the name at compile time (like @code{TO}):
 6859: 
 6860: @example
 6861: : set-greet ( xt -- )
 6862:   IS greet ;
 6863: 
 6864: ' greet1 set-greet
 6865: @end example
 6866: 
 6867: In situations where @code{IS} does not fit, use @code{defer!} instead.
 6868: 
 6869: A deferred word can only inherit execution semantics from the xt
 6870: (because that is all that an xt can represent -- for more discussion of
 6871: this @pxref{Tokens for Words}); by default it will have default
 6872: interpretation and compilation semantics deriving from this execution
 6873: semantics.  However, you can change the interpretation and compilation
 6874: semantics of the deferred word in the usual ways:
 6875: 
 6876: @example
 6877: : bar .... ; immediate
 6878: Defer fred immediate
 6879: Defer jim
 6880: 
 6881: ' bar IS jim  \ jim has default semantics
 6882: ' bar IS fred \ fred is immediate
 6883: @end example
 6884: 
 6885: doc-defer
 6886: doc-defer!
 6887: doc-is
 6888: doc-defer@
 6889: doc-action-of
 6890: @comment TODO document these: what's defers [is]
 6891: doc-defers
 6892: 
 6893: @c Use @code{words-deferred} to see a list of deferred words.
 6894: 
 6895: Definitions of these words (except @code{defers}) in ANS Forth are
 6896: provided in @file{compat/defer.fs}.
 6897: 
 6898: 
 6899: @node Aliases,  , Deferred Words, Defining Words
 6900: @subsection Aliases
 6901: @cindex aliases
 6902: 
 6903: The defining word @code{Alias} allows you to define a word by name that
 6904: has the same behaviour as some other word. Here are two situation where
 6905: this can be useful:
 6906: 
 6907: @itemize @bullet
 6908: @item
 6909: When you want access to a word's definition from a different word list
 6910: (for an example of this, see the definition of the @code{Root} word list
 6911: in the Gforth source).
 6912: @item
 6913: When you want to create a synonym; a definition that can be known by
 6914: either of two names (for example, @code{THEN} and @code{ENDIF} are
 6915: aliases).
 6916: @end itemize
 6917: 
 6918: Like deferred words, an alias has default compilation and interpretation
 6919: semantics at the beginning (not the modifications of the other word),
 6920: but you can change them in the usual ways (@code{immediate},
 6921: @code{compile-only}). For example:
 6922: 
 6923: @example
 6924: : foo ... ; immediate
 6925: 
 6926: ' foo Alias bar \ bar is not an immediate word
 6927: ' foo Alias fooby immediate \ fooby is an immediate word
 6928: @end example
 6929: 
 6930: Words that are aliases have the same xt, different headers in the
 6931: dictionary, and consequently different name tokens (@pxref{Tokens for
 6932: Words}) and possibly different immediate flags.  An alias can only have
 6933: default or immediate compilation semantics; you can define aliases for
 6934: combined words with @code{interpret/compile:} -- see @ref{Combined words}.
 6935: 
 6936: doc-alias
 6937: 
 6938: 
 6939: @node Interpretation and Compilation Semantics, Tokens for Words, Defining Words, Words
 6940: @section Interpretation and Compilation Semantics
 6941: @cindex semantics, interpretation and compilation
 6942: 
 6943: @c !! state and ' are used without explanation
 6944: @c example for immediate/compile-only? or is the tutorial enough
 6945: 
 6946: @cindex interpretation semantics
 6947: The @dfn{interpretation semantics} of a (named) word are what the text
 6948: interpreter does when it encounters the word in interpret state. It also
 6949: appears in some other contexts, e.g., the execution token returned by
 6950: @code{' @i{word}} identifies the interpretation semantics of @i{word}
 6951: (in other words, @code{' @i{word} execute} is equivalent to
 6952: interpret-state text interpretation of @code{@i{word}}).
 6953: 
 6954: @cindex compilation semantics
 6955: The @dfn{compilation semantics} of a (named) word are what the text
 6956: interpreter does when it encounters the word in compile state. It also
 6957: appears in other contexts, e.g, @code{POSTPONE @i{word}}
 6958: compiles@footnote{In standard terminology, ``appends to the current
 6959: definition''.} the compilation semantics of @i{word}.
 6960: 
 6961: @cindex execution semantics
 6962: The standard also talks about @dfn{execution semantics}. They are used
 6963: only for defining the interpretation and compilation semantics of many
 6964: words. By default, the interpretation semantics of a word are to
 6965: @code{execute} its execution semantics, and the compilation semantics of
 6966: a word are to @code{compile,} its execution semantics.@footnote{In
 6967: standard terminology: The default interpretation semantics are its
 6968: execution semantics; the default compilation semantics are to append its
 6969: execution semantics to the execution semantics of the current
 6970: definition.}
 6971: 
 6972: Unnamed words (@pxref{Anonymous Definitions}) cannot be encountered by
 6973: the text interpreter, ticked, or @code{postpone}d, so they have no
 6974: interpretation or compilation semantics.  Their behaviour is represented
 6975: by their XT (@pxref{Tokens for Words}), and we call it execution
 6976: semantics, too.
 6977: 
 6978: @comment TODO expand, make it co-operate with new sections on text interpreter.
 6979: 
 6980: @cindex immediate words
 6981: @cindex compile-only words
 6982: You can change the semantics of the most-recently defined word:
 6983: 
 6984: 
 6985: doc-immediate
 6986: doc-compile-only
 6987: doc-restrict
 6988: 
 6989: By convention, words with non-default compilation semantics (e.g.,
 6990: immediate words) often have names surrounded with brackets (e.g.,
 6991: @code{[']}, @pxref{Execution token}).
 6992: 
 6993: Note that ticking (@code{'}) a compile-only word gives an error
 6994: (``Interpreting a compile-only word'').
 6995: 
 6996: @menu
 6997: * Combined words::              
 6998: @end menu
 6999: 
 7000: 
 7001: @node Combined words,  , Interpretation and Compilation Semantics, Interpretation and Compilation Semantics
 7002: @subsection Combined Words
 7003: @cindex combined words
 7004: 
 7005: Gforth allows you to define @dfn{combined words} -- words that have an
 7006: arbitrary combination of interpretation and compilation semantics.
 7007: 
 7008: doc-interpret/compile:
 7009: 
 7010: This feature was introduced for implementing @code{TO} and @code{S"}. I
 7011: recommend that you do not define such words, as cute as they may be:
 7012: they make it hard to get at both parts of the word in some contexts.
 7013: E.g., assume you want to get an execution token for the compilation
 7014: part. Instead, define two words, one that embodies the interpretation
 7015: part, and one that embodies the compilation part.  Once you have done
 7016: that, you can define a combined word with @code{interpret/compile:} for
 7017: the convenience of your users.
 7018: 
 7019: You might try to use this feature to provide an optimizing
 7020: implementation of the default compilation semantics of a word. For
 7021: example, by defining:
 7022: @example
 7023: :noname
 7024:    foo bar ;
 7025: :noname
 7026:    POSTPONE foo POSTPONE bar ;
 7027: interpret/compile: opti-foobar
 7028: @end example
 7029: 
 7030: @noindent
 7031: as an optimizing version of:
 7032: 
 7033: @example
 7034: : foobar
 7035:     foo bar ;
 7036: @end example
 7037: 
 7038: Unfortunately, this does not work correctly with @code{[compile]},
 7039: because @code{[compile]} assumes that the compilation semantics of all
 7040: @code{interpret/compile:} words are non-default. I.e., @code{[compile]
 7041: opti-foobar} would compile compilation semantics, whereas
 7042: @code{[compile] foobar} would compile interpretation semantics.
 7043: 
 7044: @cindex state-smart words (are a bad idea)
 7045: @anchor{state-smartness}
 7046: Some people try to use @dfn{state-smart} words to emulate the feature provided
 7047: by @code{interpret/compile:} (words are state-smart if they check
 7048: @code{STATE} during execution). E.g., they would try to code
 7049: @code{foobar} like this:
 7050: 
 7051: @example
 7052: : foobar
 7053:   STATE @@
 7054:   IF ( compilation state )
 7055:     POSTPONE foo POSTPONE bar
 7056:   ELSE
 7057:     foo bar
 7058:   ENDIF ; immediate
 7059: @end example
 7060: 
 7061: Although this works if @code{foobar} is only processed by the text
 7062: interpreter, it does not work in other contexts (like @code{'} or
 7063: @code{POSTPONE}). E.g., @code{' foobar} will produce an execution token
 7064: for a state-smart word, not for the interpretation semantics of the
 7065: original @code{foobar}; when you execute this execution token (directly
 7066: with @code{EXECUTE} or indirectly through @code{COMPILE,}) in compile
 7067: state, the result will not be what you expected (i.e., it will not
 7068: perform @code{foo bar}). State-smart words are a bad idea. Simply don't
 7069: write them@footnote{For a more detailed discussion of this topic, see
 7070: M. Anton Ertl,
 7071: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,@code{State}-smartness---Why
 7072: it is Evil and How to Exorcise it}}, EuroForth '98.}!
 7073: 
 7074: @cindex defining words with arbitrary semantics combinations
 7075: It is also possible to write defining words that define words with
 7076: arbitrary combinations of interpretation and compilation semantics. In
 7077: general, they look like this:
 7078: 
 7079: @example
 7080: : def-word
 7081:     create-interpret/compile
 7082:     @i{code1}
 7083: interpretation>
 7084:     @i{code2}
 7085: <interpretation
 7086: compilation>
 7087:     @i{code3}
 7088: <compilation ;
 7089: @end example
 7090: 
 7091: For a @i{word} defined with @code{def-word}, the interpretation
 7092: semantics are to push the address of the body of @i{word} and perform
 7093: @i{code2}, and the compilation semantics are to push the address of
 7094: the body of @i{word} and perform @i{code3}. E.g., @code{constant}
 7095: can also be defined like this (except that the defined constants don't
 7096: behave correctly when @code{[compile]}d):
 7097: 
 7098: @example
 7099: : constant ( n "name" -- )
 7100:     create-interpret/compile
 7101:     ,
 7102: interpretation> ( -- n )
 7103:     @@
 7104: <interpretation
 7105: compilation> ( compilation. -- ; run-time. -- n )
 7106:     @@ postpone literal
 7107: <compilation ;
 7108: @end example
 7109: 
 7110: 
 7111: doc-create-interpret/compile
 7112: doc-interpretation>
 7113: doc-<interpretation
 7114: doc-compilation>
 7115: doc-<compilation
 7116: 
 7117: 
 7118: Words defined with @code{interpret/compile:} and
 7119: @code{create-interpret/compile} have an extended header structure that
 7120: differs from other words; however, unless you try to access them with
 7121: plain address arithmetic, you should not notice this. Words for
 7122: accessing the header structure usually know how to deal with this; e.g.,
 7123: @code{'} @i{word} @code{>body} also gives you the body of a word created
 7124: with @code{create-interpret/compile}.
 7125: 
 7126: 
 7127: @c -------------------------------------------------------------
 7128: @node Tokens for Words, Compiling words, Interpretation and Compilation Semantics, Words
 7129: @section Tokens for Words
 7130: @cindex tokens for words
 7131: 
 7132: This section describes the creation and use of tokens that represent
 7133: words.
 7134: 
 7135: @menu
 7136: * Execution token::             represents execution/interpretation semantics
 7137: * Compilation token::           represents compilation semantics
 7138: * Name token::                  represents named words
 7139: @end menu
 7140: 
 7141: @node Execution token, Compilation token, Tokens for Words, Tokens for Words
 7142: @subsection Execution token
 7143: 
 7144: @cindex xt
 7145: @cindex execution token
 7146: An @dfn{execution token} (@i{XT}) represents some behaviour of a word.
 7147: You can use @code{execute} to invoke this behaviour.
 7148: 
 7149: @cindex tick (')
 7150: You can use @code{'} to get an execution token that represents the
 7151: interpretation semantics of a named word:
 7152: 
 7153: @example
 7154: 5 ' .   ( n xt ) 
 7155: execute ( )      \ execute the xt (i.e., ".")
 7156: @end example
 7157: 
 7158: doc-'
 7159: 
 7160: @code{'} parses at run-time; there is also a word @code{[']} that parses
 7161: when it is compiled, and compiles the resulting XT:
 7162: 
 7163: @example
 7164: : foo ['] . execute ;
 7165: 5 foo
 7166: : bar ' execute ; \ by contrast,
 7167: 5 bar .           \ ' parses "." when bar executes
 7168: @end example
 7169: 
 7170: doc-[']
 7171: 
 7172: If you want the execution token of @i{word}, write @code{['] @i{word}}
 7173: in compiled code and @code{' @i{word}} in interpreted code.  Gforth's
 7174: @code{'} and @code{[']} behave somewhat unusually by complaining about
 7175: compile-only words (because these words have no interpretation
 7176: semantics).  You might get what you want by using @code{COMP' @i{word}
 7177: DROP} or @code{[COMP'] @i{word} DROP} (for details @pxref{Compilation
 7178: token}).
 7179: 
 7180: Another way to get an XT is @code{:noname} or @code{latestxt}
 7181: (@pxref{Anonymous Definitions}).  For anonymous words this gives an xt
 7182: for the only behaviour the word has (the execution semantics).  For
 7183: named words, @code{latestxt} produces an XT for the same behaviour it
 7184: would produce if the word was defined anonymously.
 7185: 
 7186: @example
 7187: :noname ." hello" ;
 7188: execute
 7189: @end example
 7190: 
 7191: An XT occupies one cell and can be manipulated like any other cell.
 7192: 
 7193: @cindex code field address
 7194: @cindex CFA
 7195: In ANS Forth the XT is just an abstract data type (i.e., defined by the
 7196: operations that produce or consume it).  For old hands: In Gforth, the
 7197: XT is implemented as a code field address (CFA).
 7198: 
 7199: doc-execute
 7200: doc-perform
 7201: 
 7202: @node Compilation token, Name token, Execution token, Tokens for Words
 7203: @subsection Compilation token
 7204: 
 7205: @cindex compilation token
 7206: @cindex CT (compilation token)
 7207: Gforth represents the compilation semantics of a named word by a
 7208: @dfn{compilation token} consisting of two cells: @i{w xt}. The top cell
 7209: @i{xt} is an execution token. The compilation semantics represented by
 7210: the compilation token can be performed with @code{execute}, which
 7211: consumes the whole compilation token, with an additional stack effect
 7212: determined by the represented compilation semantics.
 7213: 
 7214: At present, the @i{w} part of a compilation token is an execution token,
 7215: and the @i{xt} part represents either @code{execute} or
 7216: @code{compile,}@footnote{Depending upon the compilation semantics of the
 7217: word. If the word has default compilation semantics, the @i{xt} will
 7218: represent @code{compile,}. Otherwise (e.g., for immediate words), the
 7219: @i{xt} will represent @code{execute}.}. However, don't rely on that
 7220: knowledge, unless necessary; future versions of Gforth may introduce
 7221: unusual compilation tokens (e.g., a compilation token that represents
 7222: the compilation semantics of a literal).
 7223: 
 7224: You can perform the compilation semantics represented by the compilation
 7225: token with @code{execute}.  You can compile the compilation semantics
 7226: with @code{postpone,}. I.e., @code{COMP' @i{word} postpone,} is
 7227: equivalent to @code{postpone @i{word}}.
 7228: 
 7229: doc-[comp']
 7230: doc-comp'
 7231: doc-postpone,
 7232: 
 7233: @node Name token,  , Compilation token, Tokens for Words
 7234: @subsection Name token
 7235: 
 7236: @cindex name token
 7237: Gforth represents named words by the @dfn{name token}, (@i{nt}).  Name
 7238: token is an abstract data type that occurs as argument or result of the
 7239: words below.
 7240: 
 7241: @c !! put this elswhere?
 7242: @cindex name field address
 7243: @cindex NFA
 7244: The closest thing to the nt in older Forth systems is the name field
 7245: address (NFA), but there are significant differences: in older Forth
 7246: systems each word had a unique NFA, LFA, CFA and PFA (in this order, or
 7247: LFA, NFA, CFA, PFA) and there were words for getting from one to the
 7248: next.  In contrast, in Gforth 0@dots{}n nts correspond to one xt; there
 7249: is a link field in the structure identified by the name token, but
 7250: searching usually uses a hash table external to these structures; the
 7251: name in Gforth has a cell-wide count-and-flags field, and the nt is not
 7252: implemented as the address of that count field.
 7253: 
 7254: doc-find-name
 7255: doc-latest
 7256: doc->name
 7257: doc-name>int
 7258: doc-name?int
 7259: doc-name>comp
 7260: doc-name>string
 7261: doc-id.
 7262: doc-.name
 7263: doc-.id
 7264: 
 7265: @c ----------------------------------------------------------
 7266: @node Compiling words, The Text Interpreter, Tokens for Words, Words
 7267: @section Compiling words
 7268: @cindex compiling words
 7269: @cindex macros
 7270: 
 7271: In contrast to most other languages, Forth has no strict boundary
 7272: between compilation and run-time.  E.g., you can run arbitrary code
 7273: between defining words (or for computing data used by defining words
 7274: like @code{constant}). Moreover, @code{Immediate} (@pxref{Interpretation
 7275: and Compilation Semantics} and @code{[}...@code{]} (see below) allow
 7276: running arbitrary code while compiling a colon definition (exception:
 7277: you must not allot dictionary space).
 7278: 
 7279: @menu
 7280: * Literals::                    Compiling data values
 7281: * Macros::                      Compiling words
 7282: @end menu
 7283: 
 7284: @node Literals, Macros, Compiling words, Compiling words
 7285: @subsection Literals
 7286: @cindex Literals
 7287: 
 7288: The simplest and most frequent example is to compute a literal during
 7289: compilation.  E.g., the following definition prints an array of strings,
 7290: one string per line:
 7291: 
 7292: @example
 7293: : .strings ( addr u -- ) \ gforth
 7294:     2* cells bounds U+DO
 7295: 	cr i 2@@ type
 7296:     2 cells +LOOP ;  
 7297: @end example
 7298: 
 7299: With a simple-minded compiler like Gforth's, this computes @code{2
 7300: cells} on every loop iteration.  You can compute this value once and for
 7301: all at compile time and compile it into the definition like this:
 7302: 
 7303: @example
 7304: : .strings ( addr u -- ) \ gforth
 7305:     2* cells bounds U+DO
 7306: 	cr i 2@@ type
 7307:     [ 2 cells ] literal +LOOP ;  
 7308: @end example
 7309: 
 7310: @code{[} switches the text interpreter to interpret state (you will get
 7311: an @code{ok} prompt if you type this example interactively and insert a
 7312: newline between @code{[} and @code{]}), so it performs the
 7313: interpretation semantics of @code{2 cells}; this computes a number.
 7314: @code{]} switches the text interpreter back into compile state.  It then
 7315: performs @code{Literal}'s compilation semantics, which are to compile
 7316: this number into the current word.  You can decompile the word with
 7317: @code{see .strings} to see the effect on the compiled code.
 7318: 
 7319: You can also optimize the @code{2* cells} into @code{[ 2 cells ] literal
 7320: *} in this way.
 7321: 
 7322: doc-[
 7323: doc-]
 7324: doc-literal
 7325: doc-]L
 7326: 
 7327: There are also words for compiling other data types than single cells as
 7328: literals:
 7329: 
 7330: doc-2literal
 7331: doc-fliteral
 7332: doc-sliteral
 7333: 
 7334: @cindex colon-sys, passing data across @code{:}
 7335: @cindex @code{:}, passing data across
 7336: You might be tempted to pass data from outside a colon definition to the
 7337: inside on the data stack.  This does not work, because @code{:} puhes a
 7338: colon-sys, making stuff below unaccessible.  E.g., this does not work:
 7339: 
 7340: @example
 7341: 5 : foo literal ; \ error: "unstructured"
 7342: @end example
 7343: 
 7344: Instead, you have to pass the value in some other way, e.g., through a
 7345: variable:
 7346: 
 7347: @example
 7348: variable temp
 7349: 5 temp !
 7350: : foo [ temp @@ ] literal ;
 7351: @end example
 7352: 
 7353: 
 7354: @node Macros,  , Literals, Compiling words
 7355: @subsection Macros
 7356: @cindex Macros
 7357: @cindex compiling compilation semantics
 7358: 
 7359: @code{Literal} and friends compile data values into the current
 7360: definition.  You can also write words that compile other words into the
 7361: current definition.  E.g.,
 7362: 
 7363: @example
 7364: : compile-+ ( -- ) \ compiled code: ( n1 n2 -- n )
 7365:   POSTPONE + ;
 7366: 
 7367: : foo ( n1 n2 -- n )
 7368:   [ compile-+ ] ;
 7369: 1 2 foo .
 7370: @end example
 7371: 
 7372: This is equivalent to @code{: foo + ;} (@code{see foo} to check this).
 7373: What happens in this example?  @code{Postpone} compiles the compilation
 7374: semantics of @code{+} into @code{compile-+}; later the text interpreter
 7375: executes @code{compile-+} and thus the compilation semantics of +, which
 7376: compile (the execution semantics of) @code{+} into
 7377: @code{foo}.@footnote{A recent RFI answer requires that compiling words
 7378: should only be executed in compile state, so this example is not
 7379: guaranteed to work on all standard systems, but on any decent system it
 7380: will work.}
 7381: 
 7382: doc-postpone
 7383: doc-[compile]
 7384: 
 7385: Compiling words like @code{compile-+} are usually immediate (or similar)
 7386: so you do not have to switch to interpret state to execute them;
 7387: mopifying the last example accordingly produces:
 7388: 
 7389: @example
 7390: : [compile-+] ( compilation: --; interpretation: -- )
 7391:   \ compiled code: ( n1 n2 -- n )
 7392:   POSTPONE + ; immediate
 7393: 
 7394: : foo ( n1 n2 -- n )
 7395:   [compile-+] ;
 7396: 1 2 foo .
 7397: @end example
 7398: 
 7399: Immediate compiling words are similar to macros in other languages (in
 7400: particular, Lisp).  The important differences to macros in, e.g., C are:
 7401: 
 7402: @itemize @bullet
 7403: 
 7404: @item
 7405: You use the same language for defining and processing macros, not a
 7406: separate preprocessing language and processor.
 7407: 
 7408: @item
 7409: Consequently, the full power of Forth is available in macro definitions.
 7410: E.g., you can perform arbitrarily complex computations, or generate
 7411: different code conditionally or in a loop (e.g., @pxref{Advanced macros
 7412: Tutorial}).  This power is very useful when writing a parser generators
 7413: or other code-generating software.
 7414: 
 7415: @item
 7416: Macros defined using @code{postpone} etc. deal with the language at a
 7417: higher level than strings; name binding happens at macro definition
 7418: time, so you can avoid the pitfalls of name collisions that can happen
 7419: in C macros.  Of course, Forth is a liberal language and also allows to
 7420: shoot yourself in the foot with text-interpreted macros like
 7421: 
 7422: @example
 7423: : [compile-+] s" +" evaluate ; immediate
 7424: @end example
 7425: 
 7426: Apart from binding the name at macro use time, using @code{evaluate}
 7427: also makes your definition @code{state}-smart (@pxref{state-smartness}).
 7428: @end itemize
 7429: 
 7430: You may want the macro to compile a number into a word.  The word to do
 7431: it is @code{literal}, but you have to @code{postpone} it, so its
 7432: compilation semantics take effect when the macro is executed, not when
 7433: it is compiled:
 7434: 
 7435: @example
 7436: : [compile-5] ( -- ) \ compiled code: ( -- n )
 7437:   5 POSTPONE literal ; immediate
 7438: 
 7439: : foo [compile-5] ;
 7440: foo .
 7441: @end example
 7442: 
 7443: You may want to pass parameters to a macro, that the macro should
 7444: compile into the current definition.  If the parameter is a number, then
 7445: you can use @code{postpone literal} (similar for other values).
 7446: 
 7447: If you want to pass a word that is to be compiled, the usual way is to
 7448: pass an execution token and @code{compile,} it:
 7449: 
 7450: @example
 7451: : twice1 ( xt -- ) \ compiled code: ... -- ...
 7452:   dup compile, compile, ;
 7453: 
 7454: : 2+ ( n1 -- n2 )
 7455:   [ ' 1+ twice1 ] ;
 7456: @end example
 7457: 
 7458: doc-compile,
 7459: 
 7460: An alternative available in Gforth, that allows you to pass compile-only
 7461: words as parameters is to use the compilation token (@pxref{Compilation
 7462: token}).  The same example in this technique:
 7463: 
 7464: @example
 7465: : twice ( ... ct -- ... ) \ compiled code: ... -- ...
 7466:   2dup 2>r execute 2r> execute ;
 7467: 
 7468: : 2+ ( n1 -- n2 )
 7469:   [ comp' 1+ twice ] ;
 7470: @end example
 7471: 
 7472: In the example above @code{2>r} and @code{2r>} ensure that @code{twice}
 7473: works even if the executed compilation semantics has an effect on the
 7474: data stack.
 7475: 
 7476: You can also define complete definitions with these words; this provides
 7477: an alternative to using @code{does>} (@pxref{User-defined Defining
 7478: Words}).  E.g., instead of
 7479: 
 7480: @example
 7481: : curry+ ( n1 "name" -- )
 7482:     CREATE ,
 7483: DOES> ( n2 -- n1+n2 )
 7484:     @@ + ;
 7485: @end example
 7486: 
 7487: you could define
 7488: 
 7489: @example
 7490: : curry+ ( n1 "name" -- )
 7491:   \ name execution: ( n2 -- n1+n2 )
 7492:   >r : r> POSTPONE literal POSTPONE + POSTPONE ; ;
 7493: 
 7494: -3 curry+ 3-
 7495: see 3-
 7496: @end example
 7497: 
 7498: The sequence @code{>r : r>} is necessary, because @code{:} puts a
 7499: colon-sys on the data stack that makes everything below it unaccessible.
 7500: 
 7501: This way of writing defining words is sometimes more, sometimes less
 7502: convenient than using @code{does>} (@pxref{Advanced does> usage
 7503: example}).  One advantage of this method is that it can be optimized
 7504: better, because the compiler knows that the value compiled with
 7505: @code{literal} is fixed, whereas the data associated with a
 7506: @code{create}d word can be changed.
 7507: 
 7508: @c ----------------------------------------------------------
 7509: @node The Text Interpreter, The Input Stream, Compiling words, Words
 7510: @section  The Text Interpreter
 7511: @cindex interpreter - outer
 7512: @cindex text interpreter
 7513: @cindex outer interpreter
 7514: 
 7515: @c Should we really describe all these ugly details?  IMO the text
 7516: @c interpreter should be much cleaner, but that may not be possible within
 7517: @c ANS Forth. - anton
 7518: @c nac-> I wanted to explain how it works to show how you can exploit
 7519: @c it in your own programs. When I was writing a cross-compiler, figuring out
 7520: @c some of these gory details was very helpful to me. None of the textbooks
 7521: @c I've seen cover it, and the most modern Forth textbook -- Forth Inc's,
 7522: @c seems to positively avoid going into too much detail for some of
 7523: @c the internals.
 7524: 
 7525: @c anton: ok.  I wonder, though, if this is the right place; for some stuff
 7526: @c it is; for the ugly details, I would prefer another place.  I wonder
 7527: @c whether we should have a chapter before "Words" that describes some
 7528: @c basic concepts referred to in words, and a chapter after "Words" that
 7529: @c describes implementation details.
 7530: 
 7531: The text interpreter@footnote{This is an expanded version of the
 7532: material in @ref{Introducing the Text Interpreter}.} is an endless loop
 7533: that processes input from the current input device. It is also called
 7534: the outer interpreter, in contrast to the inner interpreter
 7535: (@pxref{Engine}) which executes the compiled Forth code on interpretive
 7536: implementations.
 7537: 
 7538: @cindex interpret state
 7539: @cindex compile state
 7540: The text interpreter operates in one of two states: @dfn{interpret
 7541: state} and @dfn{compile state}. The current state is defined by the
 7542: aptly-named variable @code{state}.
 7543: 
 7544: This section starts by describing how the text interpreter behaves when
 7545: it is in interpret state, processing input from the user input device --
 7546: the keyboard. This is the mode that a Forth system is in after it starts
 7547: up.
 7548: 
 7549: @cindex input buffer
 7550: @cindex terminal input buffer
 7551: The text interpreter works from an area of memory called the @dfn{input
 7552: buffer}@footnote{When the text interpreter is processing input from the
 7553: keyboard, this area of memory is called the @dfn{terminal input buffer}
 7554: (TIB) and is addressed by the (obsolescent) words @code{TIB} and
 7555: @code{#TIB}.}, which stores your keyboard input when you press the
 7556: @key{RET} key. Starting at the beginning of the input buffer, it skips
 7557: leading spaces (called @dfn{delimiters}) then parses a string (a
 7558: sequence of non-space characters) until it reaches either a space
 7559: character or the end of the buffer. Having parsed a string, it makes two
 7560: attempts to process it:
 7561: 
 7562: @cindex dictionary
 7563: @itemize @bullet
 7564: @item
 7565: It looks for the string in a @dfn{dictionary} of definitions. If the
 7566: string is found, the string names a @dfn{definition} (also known as a
 7567: @dfn{word}) and the dictionary search returns information that allows
 7568: the text interpreter to perform the word's @dfn{interpretation
 7569: semantics}. In most cases, this simply means that the word will be
 7570: executed.
 7571: @item
 7572: If the string is not found in the dictionary, the text interpreter
 7573: attempts to treat it as a number, using the rules described in
 7574: @ref{Number Conversion}. If the string represents a legal number in the
 7575: current radix, the number is pushed onto a parameter stack (the data
 7576: stack for integers, the floating-point stack for floating-point
 7577: numbers).
 7578: @end itemize
 7579: 
 7580: If both attempts fail, or if the word is found in the dictionary but has
 7581: no interpretation semantics@footnote{This happens if the word was
 7582: defined as @code{COMPILE-ONLY}.} the text interpreter discards the
 7583: remainder of the input buffer, issues an error message and waits for
 7584: more input. If one of the attempts succeeds, the text interpreter
 7585: repeats the parsing process until the whole of the input buffer has been
 7586: processed, at which point it prints the status message ``@code{ ok}''
 7587: and waits for more input.
 7588: 
 7589: @c anton: this should be in the input stream subsection (or below it)
 7590: 
 7591: @cindex parse area
 7592: The text interpreter keeps track of its position in the input buffer by
 7593: updating a variable called @code{>IN} (pronounced ``to-in''). The value
 7594: of @code{>IN} starts out as 0, indicating an offset of 0 from the start
 7595: of the input buffer. The region from offset @code{>IN @@} to the end of
 7596: the input buffer is called the @dfn{parse area}@footnote{In other words,
 7597: the text interpreter processes the contents of the input buffer by
 7598: parsing strings from the parse area until the parse area is empty.}.
 7599: This example shows how @code{>IN} changes as the text interpreter parses
 7600: the input buffer:
 7601: 
 7602: @example
 7603: : remaining >IN @@ SOURCE 2 PICK - -ROT + SWAP
 7604:   CR ." ->" TYPE ." <-" ; IMMEDIATE 
 7605: 
 7606: 1 2 3 remaining + remaining . 
 7607: 
 7608: : foo 1 2 3 remaining SWAP remaining ;
 7609: @end example
 7610: 
 7611: @noindent
 7612: The result is:
 7613: 
 7614: @example
 7615: ->+ remaining .<-
 7616: ->.<-5  ok
 7617: 
 7618: ->SWAP remaining ;-<
 7619: ->;<-  ok
 7620: @end example
 7621: 
 7622: @cindex parsing words
 7623: The value of @code{>IN} can also be modified by a word in the input
 7624: buffer that is executed by the text interpreter.  This means that a word
 7625: can ``trick'' the text interpreter into either skipping a section of the
 7626: input buffer@footnote{This is how parsing words work.} or into parsing a
 7627: section twice. For example:
 7628: 
 7629: @example
 7630: : lat ." <<foo>>" ;
 7631: : flat ." <<bar>>" >IN DUP @@ 3 - SWAP ! ;
 7632: @end example
 7633: 
 7634: @noindent
 7635: When @code{flat} is executed, this output is produced@footnote{Exercise
 7636: for the reader: what would happen if the @code{3} were replaced with
 7637: @code{4}?}:
 7638: 
 7639: @example
 7640: <<bar>><<foo>>
 7641: @end example
 7642: 
 7643: This technique can be used to work around some of the interoperability
 7644: problems of parsing words.  Of course, it's better to avoid parsing
 7645: words where possible.
 7646: 
 7647: @noindent
 7648: Two important notes about the behaviour of the text interpreter:
 7649: 
 7650: @itemize @bullet
 7651: @item
 7652: It processes each input string to completion before parsing additional
 7653: characters from the input buffer.
 7654: @item
 7655: It treats the input buffer as a read-only region (and so must your code).
 7656: @end itemize
 7657: 
 7658: @noindent
 7659: When the text interpreter is in compile state, its behaviour changes in
 7660: these ways:
 7661: 
 7662: @itemize @bullet
 7663: @item
 7664: If a parsed string is found in the dictionary, the text interpreter will
 7665: perform the word's @dfn{compilation semantics}. In most cases, this
 7666: simply means that the execution semantics of the word will be appended
 7667: to the current definition.
 7668: @item
 7669: When a number is encountered, it is compiled into the current definition
 7670: (as a literal) rather than being pushed onto a parameter stack.
 7671: @item
 7672: If an error occurs, @code{state} is modified to put the text interpreter
 7673: back into interpret state.
 7674: @item
 7675: Each time a line is entered from the keyboard, Gforth prints
 7676: ``@code{ compiled}'' rather than `` @code{ok}''.
 7677: @end itemize
 7678: 
 7679: @cindex text interpreter - input sources
 7680: When the text interpreter is using an input device other than the
 7681: keyboard, its behaviour changes in these ways:
 7682: 
 7683: @itemize @bullet
 7684: @item
 7685: When the parse area is empty, the text interpreter attempts to refill
 7686: the input buffer from the input source. When the input source is
 7687: exhausted, the input source is set back to the previous input source.
 7688: @item
 7689: It doesn't print out ``@code{ ok}'' or ``@code{ compiled}'' messages each
 7690: time the parse area is emptied.
 7691: @item
 7692: If an error occurs, the input source is set back to the user input
 7693: device.
 7694: @end itemize
 7695: 
 7696: You can read about this in more detail in @ref{Input Sources}.
 7697: 
 7698: doc->in
 7699: doc-source
 7700: 
 7701: doc-tib
 7702: doc-#tib
 7703: 
 7704: 
 7705: @menu
 7706: * Input Sources::               
 7707: * Number Conversion::           
 7708: * Interpret/Compile states::    
 7709: * Interpreter Directives::      
 7710: @end menu
 7711: 
 7712: @node Input Sources, Number Conversion, The Text Interpreter, The Text Interpreter
 7713: @subsection Input Sources
 7714: @cindex input sources
 7715: @cindex text interpreter - input sources
 7716: 
 7717: By default, the text interpreter processes input from the user input
 7718: device (the keyboard) when Forth starts up. The text interpreter can
 7719: process input from any of these sources:
 7720: 
 7721: @itemize @bullet
 7722: @item
 7723: The user input device -- the keyboard.
 7724: @item
 7725: A file, using the words described in @ref{Forth source files}.
 7726: @item
 7727: A block, using the words described in @ref{Blocks}.
 7728: @item
 7729: A text string, using @code{evaluate}.
 7730: @end itemize
 7731: 
 7732: A program can identify the current input device from the values of
 7733: @code{source-id} and @code{blk}.
 7734: 
 7735: 
 7736: doc-source-id
 7737: doc-blk
 7738: 
 7739: doc-save-input
 7740: doc-restore-input
 7741: 
 7742: doc-evaluate
 7743: doc-query
 7744: 
 7745: 
 7746: 
 7747: @node Number Conversion, Interpret/Compile states, Input Sources, The Text Interpreter
 7748: @subsection Number Conversion
 7749: @cindex number conversion
 7750: @cindex double-cell numbers, input format
 7751: @cindex input format for double-cell numbers
 7752: @cindex single-cell numbers, input format
 7753: @cindex input format for single-cell numbers
 7754: @cindex floating-point numbers, input format
 7755: @cindex input format for floating-point numbers
 7756: 
 7757: This section describes the rules that the text interpreter uses when it
 7758: tries to convert a string into a number.
 7759: 
 7760: Let <digit> represent any character that is a legal digit in the current
 7761: number base@footnote{For example, 0-9 when the number base is decimal or
 7762: 0-9, A-F when the number base is hexadecimal.}.
 7763: 
 7764: Let <decimal digit> represent any character in the range 0-9.
 7765: 
 7766: Let @{@i{a b}@} represent the @i{optional} presence of any of the characters
 7767: in the braces (@i{a} or @i{b} or neither).
 7768: 
 7769: Let * represent any number of instances of the previous character
 7770: (including none).
 7771: 
 7772: Let any other character represent itself.
 7773: 
 7774: @noindent
 7775: Now, the conversion rules are:
 7776: 
 7777: @itemize @bullet
 7778: @item
 7779: A string of the form <digit><digit>* is treated as a single-precision
 7780: (cell-sized) positive integer. Examples are 0 123 6784532 32343212343456 42
 7781: @item
 7782: A string of the form -<digit><digit>* is treated as a single-precision
 7783: (cell-sized) negative integer, and is represented using 2's-complement
 7784: arithmetic. Examples are -45 -5681 -0
 7785: @item
 7786: A string of the form <digit><digit>*.<digit>* is treated as a double-precision
 7787: (double-cell-sized) positive integer. Examples are 3465. 3.465 34.65
 7788: (all three of these represent the same number).
 7789: @item
 7790: A string of the form -<digit><digit>*.<digit>* is treated as a
 7791: double-precision (double-cell-sized) negative integer, and is
 7792: represented using 2's-complement arithmetic. Examples are -3465. -3.465
 7793: -34.65 (all three of these represent the same number).
 7794: @item
 7795: A string of the form @{+ -@}<decimal digit>@{.@}<decimal digit>*@{e
 7796: E@}@{+ -@}<decimal digit><decimal digit>* is treated as a floating-point
 7797: number. Examples are 1e 1e0 1.e 1.e0 +1e+0 (which all represent the same
 7798: number) +12.E-4
 7799: @end itemize
 7800: 
 7801: By default, the number base used for integer number conversion is
 7802: given by the contents of the variable @code{base}.  Note that a lot of
 7803: confusion can result from unexpected values of @code{base}.  If you
 7804: change @code{base} anywhere, make sure to save the old value and
 7805: restore it afterwards; better yet, use @code{base-execute}, which does
 7806: this for you.  In general I recommend keeping @code{base} decimal, and
 7807: using the prefixes described below for the popular non-decimal bases.
 7808: 
 7809: doc-dpl
 7810: doc-base-execute
 7811: doc-base
 7812: doc-hex
 7813: doc-decimal
 7814: 
 7815: @cindex '-prefix for character strings
 7816: @cindex &-prefix for decimal numbers
 7817: @cindex #-prefix for decimal numbers
 7818: @cindex %-prefix for binary numbers
 7819: @cindex $-prefix for hexadecimal numbers
 7820: @cindex 0x-prefix for hexadecimal numbers
 7821: Gforth allows you to override the value of @code{base} by using a
 7822: prefix@footnote{Some Forth implementations provide a similar scheme by
 7823: implementing @code{$} etc. as parsing words that process the subsequent
 7824: number in the input stream and push it onto the stack. For example, see
 7825: @cite{Number Conversion and Literals}, by Wil Baden; Forth Dimensions
 7826: 20(3) pages 26--27. In such implementations, unlike in Gforth, a space
 7827: is required between the prefix and the number.} before the first digit
 7828: of an (integer) number. The following prefixes are supported:
 7829: 
 7830: @itemize @bullet
 7831: @item
 7832: @code{&} -- decimal
 7833: @item
 7834: @code{#} -- decimal
 7835: @item
 7836: @code{%} -- binary
 7837: @item
 7838: @code{$} -- hexadecimal
 7839: @item
 7840: @code{0x} -- hexadecimal, if base<33.
 7841: @item
 7842: @code{'} -- numeric value (e.g., ASCII code) of next character; an
 7843: optional @code{'} may be present after the character.
 7844: @end itemize
 7845: 
 7846: Here are some examples, with the equivalent decimal number shown after
 7847: in braces:
 7848: 
 7849: -$41 (-65), %1001101 (205), %1001.0001 (145 - a double-precision number),
 7850: 'A (65),
 7851: -'a' (-97),
 7852: &905 (905), $abc (2478), $ABC (2478).
 7853: 
 7854: @cindex number conversion - traps for the unwary
 7855: @noindent
 7856: Number conversion has a number of traps for the unwary:
 7857: 
 7858: @itemize @bullet
 7859: @item
 7860: You cannot determine the current number base using the code sequence
 7861: @code{base @@ .} -- the number base is always 10 in the current number
 7862: base. Instead, use something like @code{base @@ dec.}
 7863: @item
 7864: If the number base is set to a value greater than 14 (for example,
 7865: hexadecimal), the number 123E4 is ambiguous; the conversion rules allow
 7866: it to be intepreted as either a single-precision integer or a
 7867: floating-point number (Gforth treats it as an integer). The ambiguity
 7868: can be resolved by explicitly stating the sign of the mantissa and/or
 7869: exponent: 123E+4 or +123E4 -- if the number base is decimal, no
 7870: ambiguity arises; either representation will be treated as a
 7871: floating-point number.
 7872: @item
 7873: There is a word @code{bin} but it does @i{not} set the number base!
 7874: It is used to specify file types.
 7875: @item
 7876: ANS Forth requires the @code{.} of a double-precision number to be the
 7877: final character in the string.  Gforth allows the @code{.} to be
 7878: anywhere after the first digit.
 7879: @item
 7880: The number conversion process does not check for overflow.
 7881: @item
 7882: In an ANS Forth program @code{base} is required to be decimal when
 7883: converting floating-point numbers.  In Gforth, number conversion to
 7884: floating-point numbers always uses base &10, irrespective of the value
 7885: of @code{base}.
 7886: @end itemize
 7887: 
 7888: You can read numbers into your programs with the words described in
 7889: @ref{Line input and conversion}.
 7890: 
 7891: @node Interpret/Compile states, Interpreter Directives, Number Conversion, The Text Interpreter
 7892: @subsection Interpret/Compile states
 7893: @cindex Interpret/Compile states
 7894: 
 7895: A standard program is not permitted to change @code{state}
 7896: explicitly. However, it can change @code{state} implicitly, using the
 7897: words @code{[} and @code{]}. When @code{[} is executed it switches
 7898: @code{state} to interpret state, and therefore the text interpreter
 7899: starts interpreting. When @code{]} is executed it switches @code{state}
 7900: to compile state and therefore the text interpreter starts
 7901: compiling. The most common usage for these words is for switching into
 7902: interpret state and back from within a colon definition; this technique
 7903: can be used to compile a literal (for an example, @pxref{Literals}) or
 7904: for conditional compilation (for an example, @pxref{Interpreter
 7905: Directives}).
 7906: 
 7907: 
 7908: @c This is a bad example: It's non-standard, and it's not necessary.
 7909: @c However, I can't think of a good example for switching into compile
 7910: @c state when there is no current word (@code{state}-smart words are not a
 7911: @c good reason).  So maybe we should use an example for switching into
 7912: @c interpret @code{state} in a colon def. - anton
 7913: @c nac-> I agree. I started out by putting in the example, then realised
 7914: @c that it was non-ANS, so wrote more words around it. I hope this
 7915: @c re-written version is acceptable to you. I do want to keep the example
 7916: @c as it is helpful for showing what is and what is not portable, particularly
 7917: @c where it outlaws a style in common use.
 7918: 
 7919: @c anton: it's more important to show what's portable.  After we have done
 7920: @c that, we can also show what's not.  In any case, I have written a
 7921: @c section Compiling Words which also deals with [ ].
 7922: 
 7923: @c  !! The following example does not work in Gforth 0.5.9 or later.
 7924: 
 7925: @c  @code{[} and @code{]} also give you the ability to switch into compile
 7926: @c  state and back, but we cannot think of any useful Standard application
 7927: @c  for this ability. Pre-ANS Forth textbooks have examples like this:
 7928: 
 7929: @c  @example
 7930: @c  : AA ." this is A" ;
 7931: @c  : BB ." this is B" ;
 7932: @c  : CC ." this is C" ;
 7933: 
 7934: @c  create table ] aa bb cc [
 7935: 
 7936: @c  : go ( n -- ) \ n is offset into table.. 0 for 1st entry
 7937: @c    cells table + @@ execute ;
 7938: @c  @end example
 7939: 
 7940: @c  This example builds a jump table; @code{0 go} will display ``@code{this
 7941: @c  is A}''. Using @code{[} and @code{]} in this example is equivalent to
 7942: @c  defining @code{table} like this:
 7943: 
 7944: @c  @example
 7945: @c  create table ' aa COMPILE, ' bb COMPILE, ' cc COMPILE,
 7946: @c  @end example
 7947: 
 7948: @c  The problem with this code is that the definition of @code{table} is not
 7949: @c  portable -- it @i{compile}s execution tokens into code space. Whilst it
 7950: @c  @i{may} work on systems where code space and data space co-incide, the
 7951: @c  Standard only allows data space to be assigned for a @code{CREATE}d
 7952: @c  word. In addition, the Standard only allows @code{@@} to access data
 7953: @c  space, whilst this example is using it to access code space. The only
 7954: @c  portable, Standard way to build this table is to build it in data space,
 7955: @c  like this:
 7956: 
 7957: @c  @example
 7958: @c  create table ' aa , ' bb , ' cc ,
 7959: @c  @end example
 7960: 
 7961: @c  doc-state
 7962: 
 7963: 
 7964: @node Interpreter Directives,  , Interpret/Compile states, The Text Interpreter
 7965: @subsection Interpreter Directives
 7966: @cindex interpreter directives
 7967: @cindex conditional compilation
 7968: 
 7969: These words are usually used in interpret state; typically to control
 7970: which parts of a source file are processed by the text
 7971: interpreter. There are only a few ANS Forth Standard words, but Gforth
 7972: supplements these with a rich set of immediate control structure words
 7973: to compensate for the fact that the non-immediate versions can only be
 7974: used in compile state (@pxref{Control Structures}). Typical usages:
 7975: 
 7976: @example
 7977: FALSE Constant HAVE-ASSEMBLER
 7978: .
 7979: .
 7980: HAVE-ASSEMBLER [IF]
 7981: : ASSEMBLER-FEATURE
 7982:   ...
 7983: ;
 7984: [ENDIF]
 7985: .
 7986: .
 7987: : SEE
 7988:   ... \ general-purpose SEE code
 7989:   [ HAVE-ASSEMBLER [IF] ]
 7990:   ... \ assembler-specific SEE code
 7991:   [ [ENDIF] ]
 7992: ;
 7993: @end example
 7994: 
 7995: 
 7996: doc-[IF]
 7997: doc-[ELSE]
 7998: doc-[THEN]
 7999: doc-[ENDIF]
 8000: 
 8001: doc-[IFDEF]
 8002: doc-[IFUNDEF]
 8003: 
 8004: doc-[?DO]
 8005: doc-[DO]
 8006: doc-[FOR]
 8007: doc-[LOOP]
 8008: doc-[+LOOP]
 8009: doc-[NEXT]
 8010: 
 8011: doc-[BEGIN]
 8012: doc-[UNTIL]
 8013: doc-[AGAIN]
 8014: doc-[WHILE]
 8015: doc-[REPEAT]
 8016: 
 8017: 
 8018: @c -------------------------------------------------------------
 8019: @node The Input Stream, Word Lists, The Text Interpreter, Words
 8020: @section The Input Stream
 8021: @cindex input stream
 8022: 
 8023: @c !! integrate this better with the "Text Interpreter" section
 8024: The text interpreter reads from the input stream, which can come from
 8025: several sources (@pxref{Input Sources}).  Some words, in particular
 8026: defining words, but also words like @code{'}, read parameters from the
 8027: input stream instead of from the stack.
 8028: 
 8029: Such words are called parsing words, because they parse the input
 8030: stream.  Parsing words are hard to use in other words, because it is
 8031: hard to pass program-generated parameters through the input stream.
 8032: They also usually have an unintuitive combination of interpretation and
 8033: compilation semantics when implemented naively, leading to various
 8034: approaches that try to produce a more intuitive behaviour
 8035: (@pxref{Combined words}).
 8036: 
 8037: It should be obvious by now that parsing words are a bad idea.  If you
 8038: want to implement a parsing word for convenience, also provide a factor
 8039: of the word that does not parse, but takes the parameters on the stack.
 8040: To implement the parsing word on top if it, you can use the following
 8041: words:
 8042: 
 8043: @c anton: these belong in the input stream section
 8044: doc-parse
 8045: doc-parse-name
 8046: doc-parse-word
 8047: doc-name
 8048: doc-word
 8049: doc-refill
 8050: 
 8051: Conversely, if you have the bad luck (or lack of foresight) to have to
 8052: deal with parsing words without having such factors, how do you pass a
 8053: string that is not in the input stream to it?
 8054: 
 8055: doc-execute-parsing
 8056: 
 8057: A definition of this word in ANS Forth is provided in
 8058: @file{compat/execute-parsing.fs}.
 8059: 
 8060: If you want to run a parsing word on a file, the following word should
 8061: help:
 8062: 
 8063: doc-execute-parsing-file
 8064: 
 8065: @c -------------------------------------------------------------
 8066: @node Word Lists, Environmental Queries, The Input Stream, Words
 8067: @section Word Lists
 8068: @cindex word lists
 8069: @cindex header space
 8070: 
 8071: A wordlist is a list of named words; you can add new words and look up
 8072: words by name (and you can remove words in a restricted way with
 8073: markers).  Every named (and @code{reveal}ed) word is in one wordlist.
 8074: 
 8075: @cindex search order stack
 8076: The text interpreter searches the wordlists present in the search order
 8077: (a stack of wordlists), from the top to the bottom.  Within each
 8078: wordlist, the search starts conceptually at the newest word; i.e., if
 8079: two words in a wordlist have the same name, the newer word is found.
 8080: 
 8081: @cindex compilation word list
 8082: New words are added to the @dfn{compilation wordlist} (aka current
 8083: wordlist).
 8084: 
 8085: @cindex wid
 8086: A word list is identified by a cell-sized word list identifier (@i{wid})
 8087: in much the same way as a file is identified by a file handle. The
 8088: numerical value of the wid has no (portable) meaning, and might change
 8089: from session to session.
 8090: 
 8091: The ANS Forth ``Search order'' word set is intended to provide a set of
 8092: low-level tools that allow various different schemes to be
 8093: implemented. Gforth also provides @code{vocabulary}, a traditional Forth
 8094: word.  @file{compat/vocabulary.fs} provides an implementation in ANS
 8095: Forth.
 8096: 
 8097: @comment TODO: locals section refers to here, saying that every word list (aka
 8098: @comment vocabulary) has its own methods for searching etc. Need to document that.
 8099: @c anton: but better in a separate subsection on wordlist internals
 8100: 
 8101: @comment TODO: document markers, reveal, tables, mappedwordlist
 8102: 
 8103: @comment the gforthman- prefix is used to pick out the true definition of a
 8104: @comment word from the source files, rather than some alias.
 8105: 
 8106: doc-forth-wordlist
 8107: doc-definitions
 8108: doc-get-current
 8109: doc-set-current
 8110: doc-get-order
 8111: doc-set-order
 8112: doc-wordlist
 8113: doc-table
 8114: doc->order
 8115: doc-previous
 8116: doc-also
 8117: doc-forth
 8118: doc-only
 8119: doc-order
 8120: 
 8121: doc-find
 8122: doc-search-wordlist
 8123: 
 8124: doc-words
 8125: doc-vlist
 8126: @c doc-words-deferred
 8127: 
 8128: @c doc-mappedwordlist @c map-structure undefined, implemantation-specific
 8129: doc-root
 8130: doc-vocabulary
 8131: doc-seal
 8132: doc-vocs
 8133: doc-current
 8134: doc-context
 8135: 
 8136: 
 8137: @menu
 8138: * Vocabularies::                
 8139: * Why use word lists?::         
 8140: * Word list example::           
 8141: @end menu
 8142: 
 8143: @node Vocabularies, Why use word lists?, Word Lists, Word Lists
 8144: @subsection Vocabularies
 8145: @cindex Vocabularies, detailed explanation
 8146: 
 8147: Here is an example of creating and using a new wordlist using ANS
 8148: Forth words:
 8149: 
 8150: @example
 8151: wordlist constant my-new-words-wordlist
 8152: : my-new-words get-order nip my-new-words-wordlist swap set-order ;
 8153: 
 8154: \ add it to the search order
 8155: also my-new-words
 8156: 
 8157: \ alternatively, add it to the search order and make it
 8158: \ the compilation word list
 8159: also my-new-words definitions
 8160: \ type "order" to see the problem
 8161: @end example
 8162: 
 8163: The problem with this example is that @code{order} has no way to
 8164: associate the name @code{my-new-words} with the wid of the word list (in
 8165: Gforth, @code{order} and @code{vocs} will display @code{???}  for a wid
 8166: that has no associated name). There is no Standard way of associating a
 8167: name with a wid.
 8168: 
 8169: In Gforth, this example can be re-coded using @code{vocabulary}, which
 8170: associates a name with a wid:
 8171: 
 8172: @example
 8173: vocabulary my-new-words
 8174: 
 8175: \ add it to the search order
 8176: also my-new-words
 8177: 
 8178: \ alternatively, add it to the search order and make it
 8179: \ the compilation word list
 8180: my-new-words definitions
 8181: \ type "order" to see that the problem is solved
 8182: @end example
 8183: 
 8184: 
 8185: @node Why use word lists?, Word list example, Vocabularies, Word Lists
 8186: @subsection Why use word lists?
 8187: @cindex word lists - why use them?
 8188: 
 8189: Here are some reasons why people use wordlists:
 8190: 
 8191: @itemize @bullet
 8192: 
 8193: @c anton: Gforth's hashing implementation makes the search speed
 8194: @c independent from the number of words.  But it is linear with the number
 8195: @c of wordlists that have to be searched, so in effect using more wordlists
 8196: @c actually slows down compilation.
 8197: 
 8198: @c @item
 8199: @c To improve compilation speed by reducing the number of header space
 8200: @c entries that must be searched. This is achieved by creating a new
 8201: @c word list that contains all of the definitions that are used in the
 8202: @c definition of a Forth system but which would not usually be used by
 8203: @c programs running on that system. That word list would be on the search
 8204: @c list when the Forth system was compiled but would be removed from the
 8205: @c search list for normal operation. This can be a useful technique for
 8206: @c low-performance systems (for example, 8-bit processors in embedded
 8207: @c systems) but is unlikely to be necessary in high-performance desktop
 8208: @c systems.
 8209: 
 8210: @item
 8211: To prevent a set of words from being used outside the context in which
 8212: they are valid. Two classic examples of this are an integrated editor
 8213: (all of the edit commands are defined in a separate word list; the
 8214: search order is set to the editor word list when the editor is invoked;
 8215: the old search order is restored when the editor is terminated) and an
 8216: integrated assembler (the op-codes for the machine are defined in a
 8217: separate word list which is used when a @code{CODE} word is defined).
 8218: 
 8219: @item
 8220: To organize the words of an application or library into a user-visible
 8221: set (in @code{forth-wordlist} or some other common wordlist) and a set
 8222: of helper words used just for the implementation (hidden in a separate
 8223: wordlist).  This keeps @code{words}' output smaller, separates
 8224: implementation and interface, and reduces the chance of name conflicts
 8225: within the common wordlist.
 8226: 
 8227: @item
 8228: To prevent a name-space clash between multiple definitions with the same
 8229: name. For example, when building a cross-compiler you might have a word
 8230: @code{IF} that generates conditional code for your target system. By
 8231: placing this definition in a different word list you can control whether
 8232: the host system's @code{IF} or the target system's @code{IF} get used in
 8233: any particular context by controlling the order of the word lists on the
 8234: search order stack.
 8235: 
 8236: @end itemize
 8237: 
 8238: The downsides of using wordlists are:
 8239: 
 8240: @itemize
 8241: 
 8242: @item
 8243: Debugging becomes more cumbersome.
 8244: 
 8245: @item
 8246: Name conflicts worked around with wordlists are still there, and you
 8247: have to arrange the search order carefully to get the desired results;
 8248: if you forget to do that, you get hard-to-find errors (as in any case
 8249: where you read the code differently from the compiler; @code{see} can
 8250: help seeing which of several possible words the name resolves to in such
 8251: cases).  @code{See} displays just the name of the words, not what
 8252: wordlist they belong to, so it might be misleading.  Using unique names
 8253: is a better approach to avoid name conflicts.
 8254: 
 8255: @item
 8256: You have to explicitly undo any changes to the search order.  In many
 8257: cases it would be more convenient if this happened implicitly.  Gforth
 8258: currently does not provide such a feature, but it may do so in the
 8259: future.
 8260: @end itemize
 8261: 
 8262: 
 8263: @node Word list example,  , Why use word lists?, Word Lists
 8264: @subsection Word list example
 8265: @cindex word lists - example
 8266: 
 8267: The following example is from the
 8268: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
 8269: garbage collector} and uses wordlists to separate public words from
 8270: helper words:
 8271: 
 8272: @example
 8273: get-current ( wid )
 8274: vocabulary garbage-collector also garbage-collector definitions
 8275: ... \ define helper words
 8276: ( wid ) set-current \ restore original (i.e., public) compilation wordlist
 8277: ... \ define the public (i.e., API) words
 8278:     \ they can refer to the helper words
 8279: previous \ restore original search order (helper words become invisible)
 8280: @end example
 8281: 
 8282: @c -------------------------------------------------------------
 8283: @node Environmental Queries, Files, Word Lists, Words
 8284: @section Environmental Queries
 8285: @cindex environmental queries
 8286: 
 8287: ANS Forth introduced the idea of ``environmental queries'' as a way
 8288: for a program running on a system to determine certain characteristics of the system.
 8289: The Standard specifies a number of strings that might be recognised by a system.
 8290: 
 8291: The Standard requires that the header space used for environmental queries
 8292: be distinct from the header space used for definitions.
 8293: 
 8294: Typically, environmental queries are supported by creating a set of
 8295: definitions in a word list that is @i{only} used during environmental
 8296: queries; that is what Gforth does. There is no Standard way of adding
 8297: definitions to the set of recognised environmental queries, but any
 8298: implementation that supports the loading of optional word sets must have
 8299: some mechanism for doing this (after loading the word set, the
 8300: associated environmental query string must return @code{true}). In
 8301: Gforth, the word list used to honour environmental queries can be
 8302: manipulated just like any other word list.
 8303: 
 8304: 
 8305: doc-environment?
 8306: doc-environment-wordlist
 8307: 
 8308: doc-gforth
 8309: doc-os-class
 8310: 
 8311: 
 8312: Note that, whilst the documentation for (e.g.) @code{gforth} shows it
 8313: returning two items on the stack, querying it using @code{environment?}
 8314: will return an additional item; the @code{true} flag that shows that the
 8315: string was recognised.
 8316: 
 8317: @comment TODO Document the standard strings or note where they are documented herein
 8318: 
 8319: Here are some examples of using environmental queries:
 8320: 
 8321: @example
 8322: s" address-unit-bits" environment? 0=
 8323: [IF]
 8324:      cr .( environmental attribute address-units-bits unknown... ) cr
 8325: [ELSE]
 8326:      drop \ ensure balanced stack effect
 8327: [THEN]
 8328: 
 8329: \ this might occur in the prelude of a standard program that uses THROW
 8330: s" exception" environment? [IF]
 8331:    0= [IF]
 8332:       : throw abort" exception thrown" ;
 8333:    [THEN]
 8334: [ELSE] \ we don't know, so make sure
 8335:    : throw abort" exception thrown" ;
 8336: [THEN]
 8337: 
 8338: s" gforth" environment? [IF] .( Gforth version ) TYPE
 8339:                         [ELSE] .( Not Gforth..) [THEN]
 8340: 
 8341: \ a program using v*
 8342: s" gforth" environment? [IF]
 8343:   s" 0.5.0" compare 0< [IF] \ v* is a primitive since 0.5.0
 8344:    : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
 8345:      >r swap 2swap swap 0e r> 0 ?DO
 8346:        dup f@@ over + 2swap dup f@@ f* f+ over + 2swap
 8347:      LOOP
 8348:      2drop 2drop ; 
 8349:   [THEN]
 8350: [ELSE] \ 
 8351:   : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
 8352:   ...
 8353: [THEN]
 8354: @end example
 8355: 
 8356: Here is an example of adding a definition to the environment word list:
 8357: 
 8358: @example
 8359: get-current environment-wordlist set-current
 8360: true constant block
 8361: true constant block-ext
 8362: set-current
 8363: @end example
 8364: 
 8365: You can see what definitions are in the environment word list like this:
 8366: 
 8367: @example
 8368: environment-wordlist >order words previous
 8369: @end example
 8370: 
 8371: 
 8372: @c -------------------------------------------------------------
 8373: @node Files, Blocks, Environmental Queries, Words
 8374: @section Files
 8375: @cindex files
 8376: @cindex I/O - file-handling
 8377: 
 8378: Gforth provides facilities for accessing files that are stored in the
 8379: host operating system's file-system. Files that are processed by Gforth
 8380: can be divided into two categories:
 8381: 
 8382: @itemize @bullet
 8383: @item
 8384: Files that are processed by the Text Interpreter (@dfn{Forth source files}).
 8385: @item
 8386: Files that are processed by some other program (@dfn{general files}).
 8387: @end itemize
 8388: 
 8389: @menu
 8390: * Forth source files::          
 8391: * General files::               
 8392: * Redirection::                 
 8393: * Search Paths::                
 8394: @end menu
 8395: 
 8396: @c -------------------------------------------------------------
 8397: @node Forth source files, General files, Files, Files
 8398: @subsection Forth source files
 8399: @cindex including files
 8400: @cindex Forth source files
 8401: 
 8402: The simplest way to interpret the contents of a file is to use one of
 8403: these two formats:
 8404: 
 8405: @example
 8406: include mysource.fs
 8407: s" mysource.fs" included
 8408: @end example
 8409: 
 8410: You usually want to include a file only if it is not included already
 8411: (by, say, another source file). In that case, you can use one of these
 8412: three formats:
 8413: 
 8414: @example
 8415: require mysource.fs
 8416: needs mysource.fs
 8417: s" mysource.fs" required
 8418: @end example
 8419: 
 8420: @cindex stack effect of included files
 8421: @cindex including files, stack effect
 8422: It is good practice to write your source files such that interpreting them
 8423: does not change the stack. Source files designed in this way can be used with
 8424: @code{required} and friends without complications. For example:
 8425: 
 8426: @example
 8427: 1024 require foo.fs drop
 8428: @end example
 8429: 
 8430: Here you want to pass the argument 1024 (e.g., a buffer size) to
 8431: @file{foo.fs}.  Interpreting @file{foo.fs} has the stack effect ( n -- n
 8432: ), which allows its use with @code{require}.  Of course with such
 8433: parameters to required files, you have to ensure that the first
 8434: @code{require} fits for all uses (i.e., @code{require} it early in the
 8435: master load file).
 8436: 
 8437: doc-include-file
 8438: doc-included
 8439: doc-included?
 8440: doc-include
 8441: doc-required
 8442: doc-require
 8443: doc-needs
 8444: @c doc-init-included-files @c internal
 8445: doc-sourcefilename
 8446: doc-sourceline#
 8447: 
 8448: A definition in ANS Forth for @code{required} is provided in
 8449: @file{compat/required.fs}.
 8450: 
 8451: @c -------------------------------------------------------------
 8452: @node General files, Redirection, Forth source files, Files
 8453: @subsection General files
 8454: @cindex general files
 8455: @cindex file-handling
 8456: 
 8457: Files are opened/created by name and type. The following file access
 8458: methods (FAMs) are recognised:
 8459: 
 8460: @cindex fam (file access method)
 8461: doc-r/o
 8462: doc-r/w
 8463: doc-w/o
 8464: doc-bin
 8465: 
 8466: 
 8467: When a file is opened/created, it returns a file identifier,
 8468: @i{wfileid} that is used for all other file commands. All file
 8469: commands also return a status value, @i{wior}, that is 0 for a
 8470: successful operation and an implementation-defined non-zero value in the
 8471: case of an error.
 8472: 
 8473: 
 8474: doc-open-file
 8475: doc-create-file
 8476: 
 8477: doc-close-file
 8478: doc-delete-file
 8479: doc-rename-file
 8480: doc-read-file
 8481: doc-read-line
 8482: doc-key-file
 8483: doc-key?-file
 8484: doc-write-file
 8485: doc-write-line
 8486: doc-emit-file
 8487: doc-flush-file
 8488: 
 8489: doc-file-status
 8490: doc-file-position
 8491: doc-reposition-file
 8492: doc-file-size
 8493: doc-resize-file
 8494: 
 8495: doc-slurp-file
 8496: doc-slurp-fid
 8497: doc-stdin
 8498: doc-stdout
 8499: doc-stderr
 8500: 
 8501: @c ---------------------------------------------------------
 8502: @node Redirection, Search Paths, General files, Files
 8503: @subsection Redirection
 8504: @cindex Redirection
 8505: @cindex Input Redirection
 8506: @cindex Output Redirection
 8507: 
 8508: You can redirect the output of @code{type} and @code{emit} and all the
 8509: words that use them (all output words that don't have an explicit
 8510: target file) to an arbitrary file with the @code{outfile-execute},
 8511: used like this:
 8512: 
 8513: @example
 8514: : some-warning ( n -- )
 8515:     cr ." warning# " . ;
 8516: 
 8517: : print-some-warning ( n -- )
 8518:     ['] some-warning stderr outfile-execute ;
 8519: @end example
 8520: 
 8521: After @code{some-warning} is executed, the original output direction
 8522: is restored; this construct is safe against exceptions.  Similarly,
 8523: there is @code{infile-execute} for redirecting the input of @code{key}
 8524: and its users (any input word that does not take a file explicitly).
 8525: 
 8526: doc-outfile-execute
 8527: doc-infile-execute
 8528: 
 8529: If you do not want to redirect the input or output to a file, you can
 8530: also make use of the fact that @code{key}, @code{emit} and @code{type}
 8531: are deferred words (@pxref{Deferred Words}).  However, in that case
 8532: you have to worry about the restoration and the protection against
 8533: exceptions yourself; also, note that for redirecting the output in
 8534: this way, you have to redirect both @code{emit} and @code{type}.
 8535: 
 8536: @c ---------------------------------------------------------
 8537: @node Search Paths,  , Redirection, Files
 8538: @subsection Search Paths
 8539: @cindex path for @code{included}
 8540: @cindex file search path
 8541: @cindex @code{include} search path
 8542: @cindex search path for files
 8543: 
 8544: If you specify an absolute filename (i.e., a filename starting with
 8545: @file{/} or @file{~}, or with @file{:} in the second position (as in
 8546: @samp{C:...})) for @code{included} and friends, that file is included
 8547: just as you would expect.
 8548: 
 8549: If the filename starts with @file{./}, this refers to the directory that
 8550: the present file was @code{included} from.  This allows files to include
 8551: other files relative to their own position (irrespective of the current
 8552: working directory or the absolute position).  This feature is essential
 8553: for libraries consisting of several files, where a file may include
 8554: other files from the library.  It corresponds to @code{#include "..."}
 8555: in C. If the current input source is not a file, @file{.} refers to the
 8556: directory of the innermost file being included, or, if there is no file
 8557: being included, to the current working directory.
 8558: 
 8559: For relative filenames (not starting with @file{./}), Gforth uses a
 8560: search path similar to Forth's search order (@pxref{Word Lists}). It
 8561: tries to find the given filename in the directories present in the path,
 8562: and includes the first one it finds. There are separate search paths for
 8563: Forth source files and general files.  If the search path contains the
 8564: directory @file{.}, this refers to the directory of the current file, or
 8565: the working directory, as if the file had been specified with @file{./}.
 8566: 
 8567: Use @file{~+} to refer to the current working directory (as in the
 8568: @code{bash}).
 8569: 
 8570: @c anton: fold the following subsubsections into this subsection?
 8571: 
 8572: @menu
 8573: * Source Search Paths::         
 8574: * General Search Paths::        
 8575: @end menu
 8576: 
 8577: @c ---------------------------------------------------------
 8578: @node Source Search Paths, General Search Paths, Search Paths, Search Paths
 8579: @subsubsection Source Search Paths
 8580: @cindex search path control, source files
 8581: 
 8582: The search path is initialized when you start Gforth (@pxref{Invoking
 8583: Gforth}). You can display it and change it using @code{fpath} in
 8584: combination with the general path handling words.
 8585: 
 8586: doc-fpath
 8587: @c the functionality of the following words is easily available through
 8588: @c   fpath and the general path words.  The may go away.
 8589: @c doc-.fpath
 8590: @c doc-fpath+
 8591: @c doc-fpath=
 8592: @c doc-open-fpath-file
 8593: 
 8594: @noindent
 8595: Here is an example of using @code{fpath} and @code{require}:
 8596: 
 8597: @example
 8598: fpath path= /usr/lib/forth/|./
 8599: require timer.fs
 8600: @end example
 8601: 
 8602: 
 8603: @c ---------------------------------------------------------
 8604: @node General Search Paths,  , Source Search Paths, Search Paths
 8605: @subsubsection General Search Paths
 8606: @cindex search path control, source files
 8607: 
 8608: Your application may need to search files in several directories, like
 8609: @code{included} does. To facilitate this, Gforth allows you to define
 8610: and use your own search paths, by providing generic equivalents of the
 8611: Forth search path words:
 8612: 
 8613: doc-open-path-file
 8614: doc-path-allot
 8615: doc-clear-path
 8616: doc-also-path
 8617: doc-.path
 8618: doc-path+
 8619: doc-path=
 8620: 
 8621: @c anton: better define a word for it, say "path-allot ( ucount -- path-addr )
 8622: 
 8623: Here's an example of creating an empty search path:
 8624: @c
 8625: @example
 8626: create mypath 500 path-allot \ maximum length 500 chars (is checked)
 8627: @end example
 8628: 
 8629: @c -------------------------------------------------------------
 8630: @node Blocks, Other I/O, Files, Words
 8631: @section Blocks
 8632: @cindex I/O - blocks
 8633: @cindex blocks
 8634: 
 8635: When you run Gforth on a modern desk-top computer, it runs under the
 8636: control of an operating system which provides certain services.  One of
 8637: these services is @var{file services}, which allows Forth source code
 8638: and data to be stored in files and read into Gforth (@pxref{Files}).
 8639: 
 8640: Traditionally, Forth has been an important programming language on
 8641: systems where it has interfaced directly to the underlying hardware with
 8642: no intervening operating system. Forth provides a mechanism, called
 8643: @dfn{blocks}, for accessing mass storage on such systems.
 8644: 
 8645: A block is a 1024-byte data area, which can be used to hold data or
 8646: Forth source code. No structure is imposed on the contents of the
 8647: block. A block is identified by its number; blocks are numbered
 8648: contiguously from 1 to an implementation-defined maximum.
 8649: 
 8650: A typical system that used blocks but no operating system might use a
 8651: single floppy-disk drive for mass storage, with the disks formatted to
 8652: provide 256-byte sectors. Blocks would be implemented by assigning the
 8653: first four sectors of the disk to block 1, the second four sectors to
 8654: block 2 and so on, up to the limit of the capacity of the disk. The disk
 8655: would not contain any file system information, just the set of blocks.
 8656: 
 8657: @cindex blocks file
 8658: On systems that do provide file services, blocks are typically
 8659: implemented by storing a sequence of blocks within a single @dfn{blocks
 8660: file}.  The size of the blocks file will be an exact multiple of 1024
 8661: bytes, corresponding to the number of blocks it contains. This is the
 8662: mechanism that Gforth uses.
 8663: 
 8664: @cindex @file{blocks.fb}
 8665: Only one blocks file can be open at a time. If you use block words without
 8666: having specified a blocks file, Gforth defaults to the blocks file
 8667: @file{blocks.fb}. Gforth uses the Forth search path when attempting to
 8668: locate a blocks file (@pxref{Source Search Paths}).
 8669: 
 8670: @cindex block buffers
 8671: When you read and write blocks under program control, Gforth uses a
 8672: number of @dfn{block buffers} as intermediate storage. These buffers are
 8673: not used when you use @code{load} to interpret the contents of a block.
 8674: 
 8675: The behaviour of the block buffers is analagous to that of a cache.
 8676: Each block buffer has three states:
 8677: 
 8678: @itemize @bullet
 8679: @item
 8680: Unassigned
 8681: @item
 8682: Assigned-clean
 8683: @item
 8684: Assigned-dirty
 8685: @end itemize
 8686: 
 8687: Initially, all block buffers are @i{unassigned}. In order to access a
 8688: block, the block (specified by its block number) must be assigned to a
 8689: block buffer.
 8690: 
 8691: The assignment of a block to a block buffer is performed by @code{block}
 8692: or @code{buffer}. Use @code{block} when you wish to modify the existing
 8693: contents of a block. Use @code{buffer} when you don't care about the
 8694: existing contents of the block@footnote{The ANS Forth definition of
 8695: @code{buffer} is intended not to cause disk I/O; if the data associated
 8696: with the particular block is already stored in a block buffer due to an
 8697: earlier @code{block} command, @code{buffer} will return that block
 8698: buffer and the existing contents of the block will be
 8699: available. Otherwise, @code{buffer} will simply assign a new, empty
 8700: block buffer for the block.}.
 8701: 
 8702: Once a block has been assigned to a block buffer using @code{block} or
 8703: @code{buffer}, that block buffer becomes the @i{current block
 8704: buffer}. Data may only be manipulated (read or written) within the
 8705: current block buffer.
 8706: 
 8707: When the contents of the current block buffer has been modified it is
 8708: necessary, @emph{before calling @code{block} or @code{buffer} again}, to
 8709: either abandon the changes (by doing nothing) or mark the block as
 8710: changed (assigned-dirty), using @code{update}. Using @code{update} does
 8711: not change the blocks file; it simply changes a block buffer's state to
 8712: @i{assigned-dirty}.  The block will be written implicitly when it's
 8713: buffer is needed for another block, or explicitly by @code{flush} or
 8714: @code{save-buffers}.
 8715: 
 8716: word @code{Flush} writes all @i{assigned-dirty} blocks back to the
 8717: blocks file on disk. Leaving Gforth with @code{bye} also performs a
 8718: @code{flush}.
 8719: 
 8720: In Gforth, @code{block} and @code{buffer} use a @i{direct-mapped}
 8721: algorithm to assign a block buffer to a block. That means that any
 8722: particular block can only be assigned to one specific block buffer,
 8723: called (for the particular operation) the @i{victim buffer}. If the
 8724: victim buffer is @i{unassigned} or @i{assigned-clean} it is allocated to
 8725: the new block immediately. If it is @i{assigned-dirty} its current
 8726: contents are written back to the blocks file on disk before it is
 8727: allocated to the new block.
 8728: 
 8729: Although no structure is imposed on the contents of a block, it is
 8730: traditional to display the contents as 16 lines each of 64 characters.  A
 8731: block provides a single, continuous stream of input (for example, it
 8732: acts as a single parse area) -- there are no end-of-line characters
 8733: within a block, and no end-of-file character at the end of a
 8734: block. There are two consequences of this:
 8735: 
 8736: @itemize @bullet
 8737: @item
 8738: The last character of one line wraps straight into the first character
 8739: of the following line
 8740: @item
 8741: The word @code{\} -- comment to end of line -- requires special
 8742: treatment; in the context of a block it causes all characters until the
 8743: end of the current 64-character ``line'' to be ignored.
 8744: @end itemize
 8745: 
 8746: In Gforth, when you use @code{block} with a non-existent block number,
 8747: the current blocks file will be extended to the appropriate size and the
 8748: block buffer will be initialised with spaces.
 8749: 
 8750: Gforth includes a simple block editor (type @code{use blocked.fb 0 list}
 8751: for details) but doesn't encourage the use of blocks; the mechanism is
 8752: only provided for backward compatibility -- ANS Forth requires blocks to
 8753: be available when files are.
 8754: 
 8755: Common techniques that are used when working with blocks include:
 8756: 
 8757: @itemize @bullet
 8758: @item
 8759: A screen editor that allows you to edit blocks without leaving the Forth
 8760: environment.
 8761: @item
 8762: Shadow screens; where every code block has an associated block
 8763: containing comments (for example: code in odd block numbers, comments in
 8764: even block numbers). Typically, the block editor provides a convenient
 8765: mechanism to toggle between code and comments.
 8766: @item
 8767: Load blocks; a single block (typically block 1) contains a number of
 8768: @code{thru} commands which @code{load} the whole of the application.
 8769: @end itemize
 8770: 
 8771: See Frank Sergeant's Pygmy Forth to see just how well blocks can be
 8772: integrated into a Forth programming environment.
 8773: 
 8774: @comment TODO what about errors on open-blocks?
 8775: 
 8776: doc-open-blocks
 8777: doc-use
 8778: doc-block-offset
 8779: doc-get-block-fid
 8780: doc-block-position
 8781: 
 8782: doc-list
 8783: doc-scr
 8784: 
 8785: doc-block
 8786: doc-buffer
 8787: 
 8788: doc-empty-buffers
 8789: doc-empty-buffer
 8790: doc-update
 8791: doc-updated?
 8792: doc-save-buffers
 8793: doc-save-buffer
 8794: doc-flush
 8795: 
 8796: doc-load
 8797: doc-thru
 8798: doc-+load
 8799: doc-+thru
 8800: doc---gforthman--->
 8801: doc-block-included
 8802: 
 8803: 
 8804: @c -------------------------------------------------------------
 8805: @node Other I/O, OS command line arguments, Blocks, Words
 8806: @section Other I/O
 8807: @cindex I/O - keyboard and display
 8808: 
 8809: @menu
 8810: * Simple numeric output::       Predefined formats
 8811: * Formatted numeric output::    Formatted (pictured) output
 8812: * String Formats::              How Forth stores strings in memory
 8813: * Displaying characters and strings::  Other stuff
 8814: * Terminal output::             Cursor positioning etc.
 8815: * Single-key input::            
 8816: * Line input and conversion::   
 8817: * Pipes::                       How to create your own pipes
 8818: * Xchars and Unicode::          Non-ASCII characters
 8819: @end menu
 8820: 
 8821: @node Simple numeric output, Formatted numeric output, Other I/O, Other I/O
 8822: @subsection Simple numeric output
 8823: @cindex numeric output - simple/free-format
 8824: 
 8825: The simplest output functions are those that display numbers from the
 8826: data or floating-point stacks. Floating-point output is always displayed
 8827: using base 10. Numbers displayed from the data stack use the value stored
 8828: in @code{base}.
 8829: 
 8830: 
 8831: doc-.
 8832: doc-dec.
 8833: doc-hex.
 8834: doc-u.
 8835: doc-.r
 8836: doc-u.r
 8837: doc-d.
 8838: doc-ud.
 8839: doc-d.r
 8840: doc-ud.r
 8841: doc-f.
 8842: doc-fe.
 8843: doc-fs.
 8844: doc-f.rdp
 8845: 
 8846: Examples of printing the number 1234.5678E23 in the different floating-point output
 8847: formats are shown below:
 8848: 
 8849: @example
 8850: f. 123456779999999000000000000.
 8851: fe. 123.456779999999E24
 8852: fs. 1.23456779999999E26
 8853: @end example
 8854: 
 8855: 
 8856: @node Formatted numeric output, String Formats, Simple numeric output, Other I/O
 8857: @subsection Formatted numeric output
 8858: @cindex formatted numeric output
 8859: @cindex pictured numeric output
 8860: @cindex numeric output - formatted
 8861: 
 8862: Forth traditionally uses a technique called @dfn{pictured numeric
 8863: output} for formatted printing of integers.  In this technique, digits
 8864: are extracted from the number (using the current output radix defined by
 8865: @code{base}), converted to ASCII codes and appended to a string that is
 8866: built in a scratch-pad area of memory (@pxref{core-idef,
 8867: Implementation-defined options, Implementation-defined
 8868: options}). Arbitrary characters can be appended to the string during the
 8869: extraction process. The completed string is specified by an address
 8870: and length and can be manipulated (@code{TYPE}ed, copied, modified)
 8871: under program control.
 8872: 
 8873: All of the integer output words described in the previous section
 8874: (@pxref{Simple numeric output}) are implemented in Gforth using pictured
 8875: numeric output.
 8876: 
 8877: Three important things to remember about pictured numeric output:
 8878: 
 8879: @itemize @bullet
 8880: @item
 8881: It always operates on double-precision numbers; to display a
 8882: single-precision number, convert it first (for ways of doing this
 8883: @pxref{Double precision}).
 8884: @item
 8885: It always treats the double-precision number as though it were
 8886: unsigned. The examples below show ways of printing signed numbers.
 8887: @item
 8888: The string is built up from right to left; least significant digit first.
 8889: @end itemize
 8890: 
 8891: 
 8892: doc-<#
 8893: doc-<<#
 8894: doc-#
 8895: doc-#s
 8896: doc-hold
 8897: doc-sign
 8898: doc-#>
 8899: doc-#>>
 8900: 
 8901: doc-represent
 8902: doc-f>str-rdp
 8903: doc-f>buf-rdp
 8904: 
 8905: 
 8906: @noindent
 8907: Here are some examples of using pictured numeric output:
 8908: 
 8909: @example
 8910: : my-u. ( u -- )
 8911:   \ Simplest use of pns.. behaves like Standard u. 
 8912:   0              \ convert to unsigned double
 8913:   <<#            \ start conversion
 8914:   #s             \ convert all digits
 8915:   #>             \ complete conversion
 8916:   TYPE SPACE     \ display, with trailing space
 8917:   #>> ;          \ release hold area
 8918: 
 8919: : cents-only ( u -- )
 8920:   0              \ convert to unsigned double
 8921:   <<#            \ start conversion
 8922:   # #            \ convert two least-significant digits
 8923:   #>             \ complete conversion, discard other digits
 8924:   TYPE SPACE     \ display, with trailing space
 8925:   #>> ;          \ release hold area
 8926: 
 8927: : dollars-and-cents ( u -- )
 8928:   0              \ convert to unsigned double
 8929:   <<#            \ start conversion
 8930:   # #            \ convert two least-significant digits
 8931:   [char] . hold  \ insert decimal point
 8932:   #s             \ convert remaining digits
 8933:   [char] $ hold  \ append currency symbol
 8934:   #>             \ complete conversion
 8935:   TYPE SPACE     \ display, with trailing space
 8936:   #>> ;          \ release hold area
 8937: 
 8938: : my-. ( n -- )
 8939:   \ handling negatives.. behaves like Standard .
 8940:   s>d            \ convert to signed double
 8941:   swap over dabs \ leave sign byte followed by unsigned double
 8942:   <<#            \ start conversion
 8943:   #s             \ convert all digits
 8944:   rot sign       \ get at sign byte, append "-" if needed
 8945:   #>             \ complete conversion
 8946:   TYPE SPACE     \ display, with trailing space
 8947:   #>> ;          \ release hold area
 8948: 
 8949: : account. ( n -- )
 8950:   \ accountants don't like minus signs, they use parentheses
 8951:   \ for negative numbers
 8952:   s>d            \ convert to signed double
 8953:   swap over dabs \ leave sign byte followed by unsigned double
 8954:   <<#            \ start conversion
 8955:   2 pick         \ get copy of sign byte
 8956:   0< IF [char] ) hold THEN \ right-most character of output
 8957:   #s             \ convert all digits
 8958:   rot            \ get at sign byte
 8959:   0< IF [char] ( hold THEN
 8960:   #>             \ complete conversion
 8961:   TYPE SPACE     \ display, with trailing space
 8962:   #>> ;          \ release hold area
 8963: 
 8964: @end example
 8965: 
 8966: Here are some examples of using these words:
 8967: 
 8968: @example
 8969: 1 my-u. 1
 8970: hex -1 my-u. decimal FFFFFFFF
 8971: 1 cents-only 01
 8972: 1234 cents-only 34
 8973: 2 dollars-and-cents $0.02
 8974: 1234 dollars-and-cents $12.34
 8975: 123 my-. 123
 8976: -123 my. -123
 8977: 123 account. 123
 8978: -456 account. (456)
 8979: @end example
 8980: 
 8981: 
 8982: @node String Formats, Displaying characters and strings, Formatted numeric output, Other I/O
 8983: @subsection String Formats
 8984: @cindex strings - see character strings
 8985: @cindex character strings - formats
 8986: @cindex I/O - see character strings
 8987: @cindex counted strings
 8988: 
 8989: @c anton: this does not really belong here; maybe the memory section,
 8990: @c  or the principles chapter
 8991: 
 8992: Forth commonly uses two different methods for representing character
 8993: strings:
 8994: 
 8995: @itemize @bullet
 8996: @item
 8997: @cindex address of counted string
 8998: @cindex counted string
 8999: As a @dfn{counted string}, represented by a @i{c-addr}. The char
 9000: addressed by @i{c-addr} contains a character-count, @i{n}, of the
 9001: string and the string occupies the subsequent @i{n} char addresses in
 9002: memory.
 9003: @item
 9004: As cell pair on the stack; @i{c-addr u}, where @i{u} is the length
 9005: of the string in characters, and @i{c-addr} is the address of the
 9006: first byte of the string.
 9007: @end itemize
 9008: 
 9009: ANS Forth encourages the use of the second format when representing
 9010: strings.
 9011: 
 9012: 
 9013: doc-count
 9014: 
 9015: 
 9016: For words that move, copy and search for strings see @ref{Memory
 9017: Blocks}. For words that display characters and strings see
 9018: @ref{Displaying characters and strings}.
 9019: 
 9020: @node Displaying characters and strings, Terminal output, String Formats, Other I/O
 9021: @subsection Displaying characters and strings
 9022: @cindex characters - compiling and displaying
 9023: @cindex character strings - compiling and displaying
 9024: 
 9025: This section starts with a glossary of Forth words and ends with a set
 9026: of examples.
 9027: 
 9028: doc-bl
 9029: doc-space
 9030: doc-spaces
 9031: doc-emit
 9032: doc-toupper
 9033: doc-."
 9034: doc-.(
 9035: doc-.\"
 9036: doc-type
 9037: doc-typewhite
 9038: doc-cr
 9039: @cindex cursor control
 9040: doc-s"
 9041: doc-s\"
 9042: doc-c"
 9043: doc-char
 9044: doc-[char]
 9045: 
 9046: 
 9047: @noindent
 9048: As an example, consider the following text, stored in a file @file{test.fs}:
 9049: 
 9050: @example
 9051: .( text-1)
 9052: : my-word
 9053:   ." text-2" cr
 9054:   .( text-3)
 9055: ;
 9056: 
 9057: ." text-4"
 9058: 
 9059: : my-char
 9060:   [char] ALPHABET emit
 9061:   char emit
 9062: ;
 9063: @end example
 9064: 
 9065: When you load this code into Gforth, the following output is generated:
 9066: 
 9067: @example
 9068: @kbd{include test.fs @key{RET}} text-1text-3text-4 ok
 9069: @end example
 9070: 
 9071: @itemize @bullet
 9072: @item
 9073: Messages @code{text-1} and @code{text-3} are displayed because @code{.(} 
 9074: is an immediate word; it behaves in the same way whether it is used inside
 9075: or outside a colon definition.
 9076: @item
 9077: Message @code{text-4} is displayed because of Gforth's added interpretation
 9078: semantics for @code{."}.
 9079: @item
 9080: Message @code{text-2} is @i{not} displayed, because the text interpreter
 9081: performs the compilation semantics for @code{."} within the definition of
 9082: @code{my-word}.
 9083: @end itemize
 9084: 
 9085: Here are some examples of executing @code{my-word} and @code{my-char}:
 9086: 
 9087: @example
 9088: @kbd{my-word @key{RET}} text-2
 9089:  ok
 9090: @kbd{my-char fred @key{RET}} Af ok
 9091: @kbd{my-char jim @key{RET}} Aj ok
 9092: @end example
 9093: 
 9094: @itemize @bullet
 9095: @item
 9096: Message @code{text-2} is displayed because of the run-time behaviour of
 9097: @code{."}.
 9098: @item
 9099: @code{[char]} compiles the ``A'' from ``ALPHABET'' and puts its display code
 9100: on the stack at run-time. @code{emit} always displays the character
 9101: when @code{my-char} is executed.
 9102: @item
 9103: @code{char} parses a string at run-time and the second @code{emit} displays
 9104: the first character of the string.
 9105: @item
 9106: If you type @code{see my-char} you can see that @code{[char]} discarded
 9107: the text ``LPHABET'' and only compiled the display code for ``A'' into the
 9108: definition of @code{my-char}.
 9109: @end itemize
 9110: 
 9111: 
 9112: @node Terminal output, Single-key input, Displaying characters and strings, Other I/O
 9113: @subsection Terminal output
 9114: @cindex output to terminal
 9115: @cindex terminal output
 9116: 
 9117: If you are outputting to a terminal, you may want to control the
 9118: positioning of the cursor:
 9119: @cindex cursor positioning
 9120: 
 9121: doc-at-xy
 9122: 
 9123: In order to know where to position the cursor, it is often helpful to
 9124: know the size of the screen:
 9125: @cindex terminal size 
 9126: 
 9127: doc-form
 9128: 
 9129: And sometimes you want to use:
 9130: @cindex clear screen
 9131: 
 9132: doc-page
 9133: 
 9134: Note that on non-terminals you should use @code{12 emit}, not
 9135: @code{page}, to get a form feed.
 9136: 
 9137: 
 9138: @node Single-key input, Line input and conversion, Terminal output, Other I/O
 9139: @subsection Single-key input
 9140: @cindex single-key input
 9141: @cindex input, single-key
 9142: 
 9143: If you want to get a single printable character, you can use
 9144: @code{key}; to check whether a character is available for @code{key},
 9145: you can use @code{key?}.
 9146: 
 9147: doc-key
 9148: doc-key?
 9149: 
 9150: If you want to process a mix of printable and non-printable
 9151: characters, you can do that with @code{ekey} and friends.  @code{Ekey}
 9152: produces a keyboard event that you have to convert into a character
 9153: with @code{ekey>char} or into a key identifier with @code{ekey>fkey}.
 9154: 
 9155: Typical code for using EKEY looks like this:
 9156: 
 9157: @example
 9158: ekey ekey>char if ( c )
 9159:   ... \ do something with the character
 9160: else ekey>fkey if ( key-id )
 9161:   case
 9162:     k-up                                  of ... endof
 9163:     k-f1                                  of ... endof
 9164:     k-left k-shift-mask or k-ctrl-mask or of ... endof
 9165:     ...
 9166:   endcase
 9167: else ( keyboard-event )
 9168:   drop \ just ignore an unknown keyboard event type
 9169: then then
 9170: @end example
 9171: 
 9172: doc-ekey
 9173: doc-ekey>char
 9174: doc-ekey>fkey
 9175: doc-ekey?
 9176: 
 9177: The key identifiers for cursor keys are:
 9178: 
 9179: doc-k-left
 9180: doc-k-right
 9181: doc-k-up
 9182: doc-k-down
 9183: doc-k-home
 9184: doc-k-end
 9185: doc-k-prior
 9186: doc-k-next
 9187: doc-k-insert
 9188: doc-k-delete
 9189: 
 9190: The key identifiers for function keys (aka keypad keys) are:
 9191: 
 9192: doc-k-f1
 9193: doc-k-f2
 9194: doc-k-f3
 9195: doc-k-f4
 9196: doc-k-f5
 9197: doc-k-f6
 9198: doc-k-f7
 9199: doc-k-f8
 9200: doc-k-f9
 9201: doc-k-f10
 9202: doc-k-f11
 9203: doc-k-f12
 9204: 
 9205: Note that @code{k-f11} and @code{k-f12} are not as widely available.
 9206: 
 9207: You can combine these key identifiers with masks for various shift keys:
 9208: 
 9209: doc-k-shift-mask
 9210: doc-k-ctrl-mask
 9211: doc-k-alt-mask
 9212: 
 9213: Note that, even if a Forth system has @code{ekey>fkey} and the key
 9214: identifier words, the keys are not necessarily available or it may not
 9215: necessarily be able to report all the keys and all the possible
 9216: combinations with shift masks.  Therefore, write your programs in such
 9217: a way that they are still useful even if the keys and key combinations
 9218: cannot be pressed or are not recognized.
 9219: 
 9220: Examples: Older keyboards often do not have an F11 and F12 key.  If
 9221: you run Gforth in an xterm, the xterm catches a number of combinations
 9222: (e.g., @key{Shift-Up}), and never passes it to Gforth.  Finally,
 9223: Gforth currently does not recognize and report combinations with
 9224: multiple shift keys (so the @key{shift-ctrl-left} case in the example
 9225: above would never be entered).
 9226: 
 9227: Gforth recognizes various keys available on ANSI terminals (in MS-DOS
 9228: you need the ANSI.SYS driver to get that behaviour); it works by
 9229: recognizing the escape sequences that ANSI terminals send when such a
 9230: key is pressed.  If you have a terminal that sends other escape
 9231: sequences, you will not get useful results on Gforth.  Other Forth
 9232: systems may work in a different way.
 9233: 
 9234: Gforth also provides a few words for outputting names of function
 9235: keys:
 9236: 
 9237: doc-fkey.
 9238: doc-simple-fkey-string
 9239: 
 9240: 
 9241: @node  Line input and conversion, Pipes, Single-key input, Other I/O
 9242: @subsection Line input and conversion
 9243: @cindex line input from terminal
 9244: @cindex input, linewise from terminal
 9245: @cindex convertin strings to numbers
 9246: @cindex I/O - see input
 9247: 
 9248: For ways of storing character strings in memory see @ref{String Formats}.
 9249: 
 9250: @comment TODO examples for >number >float accept key key? pad parse word refill
 9251: @comment then index them
 9252: 
 9253: Words for inputting one line from the keyboard:
 9254: 
 9255: doc-accept
 9256: doc-edit-line
 9257: 
 9258: Conversion words:
 9259: 
 9260: doc-s>number?
 9261: doc-s>unumber?
 9262: doc->number
 9263: doc->float
 9264: 
 9265: 
 9266: @comment obsolescent words..
 9267: Obsolescent input and conversion words:
 9268: 
 9269: doc-convert
 9270: doc-expect
 9271: doc-span
 9272: 
 9273: 
 9274: @node Pipes, Xchars and Unicode, Line input and conversion, Other I/O
 9275: @subsection Pipes
 9276: @cindex pipes, creating your own
 9277: 
 9278: In addition to using Gforth in pipes created by other processes
 9279: (@pxref{Gforth in pipes}), you can create your own pipe with
 9280: @code{open-pipe}, and read from or write to it.
 9281: 
 9282: doc-open-pipe
 9283: doc-close-pipe
 9284: 
 9285: If you write to a pipe, Gforth can throw a @code{broken-pipe-error}; if
 9286: you don't catch this exception, Gforth will catch it and exit, usually
 9287: silently (@pxref{Gforth in pipes}).  Since you probably do not want
 9288: this, you should wrap a @code{catch} or @code{try} block around the code
 9289: from @code{open-pipe} to @code{close-pipe}, so you can deal with the
 9290: problem yourself, and then return to regular processing.
 9291: 
 9292: doc-broken-pipe-error
 9293: 
 9294: @node Xchars and Unicode,  , Pipes, Other I/O
 9295: @subsection Xchars and Unicode
 9296: 
 9297: ASCII is only appropriate for the English language. Most western
 9298: languages however fit somewhat into the Forth frame, since a byte is
 9299: sufficient to encode the few special characters in each (though not
 9300: always the same encoding can be used; latin-1 is most widely used,
 9301: though). For other languages, different char-sets have to be used,
 9302: several of them variable-width. Most prominent representant is
 9303: UTF-8. Let's call these extended characters xchars. The primitive
 9304: fixed-size characters stored as bytes are called pchars in this
 9305: section.
 9306: 
 9307: The xchar words add a few data types:
 9308: 
 9309: @itemize
 9310: 
 9311: @item
 9312: @var{xc} is an extended char (xchar) on the stack. It occupies one cell,
 9313: and is a subset of unsigned cell. Note: UTF-8 can not store more that
 9314: 31 bits; on 16 bit systems, only the UCS16 subset of the UTF-8
 9315: character set can be used.
 9316: 
 9317: @item
 9318: @var{xc-addr} is the address of an xchar in memory. Alignment
 9319: requirements are the same as @var{c-addr}. The memory representation of an
 9320: xchar differs from the stack representation, and depends on the
 9321: encoding used. An xchar may use a variable number of pchars in memory.
 9322: 
 9323: @item
 9324: @var{xc-addr} @var{u} is a buffer of xchars in memory, starting at
 9325: @var{xc-addr}, @var{u} pchars long.
 9326: 
 9327: @end itemize
 9328: 
 9329: doc-xc-size
 9330: doc-x-size
 9331: doc-xc@+
 9332: doc-xc!+?
 9333: doc-xchar+
 9334: doc-xchar-
 9335: doc-+x/string
 9336: doc-x\string-
 9337: doc--trailing-garbage
 9338: doc-x-width
 9339: doc-xkey
 9340: doc-xemit
 9341: 
 9342: There's a new environment query
 9343: 
 9344: doc-xchar-encoding
 9345: 
 9346: @node OS command line arguments, Locals, Other I/O, Words
 9347: @section OS command line arguments
 9348: @cindex OS command line arguments
 9349: @cindex command line arguments, OS
 9350: @cindex arguments, OS command line
 9351: 
 9352: The usual way to pass arguments to Gforth programs on the command line
 9353: is via the @option{-e} option, e.g.
 9354: 
 9355: @example
 9356: gforth -e "123 456" foo.fs -e bye
 9357: @end example
 9358: 
 9359: However, you may want to interpret the command-line arguments directly.
 9360: In that case, you can access the (image-specific) command-line arguments
 9361: through @code{next-arg}:
 9362: 
 9363: doc-next-arg
 9364: 
 9365: Here's an example program @file{echo.fs} for @code{next-arg}:
 9366: 
 9367: @example
 9368: : echo ( -- )
 9369:     begin
 9370: 	next-arg 2dup 0 0 d<> while
 9371: 	    type space
 9372:     repeat
 9373:     2drop ;
 9374: 
 9375: echo cr bye
 9376: @end example
 9377: 
 9378: This can be invoked with
 9379: 
 9380: @example
 9381: gforth echo.fs hello world
 9382: @end example
 9383: 
 9384: and it will print
 9385: 
 9386: @example
 9387: hello world
 9388: @end example
 9389: 
 9390: The next lower level of dealing with the OS command line are the
 9391: following words:
 9392: 
 9393: doc-arg
 9394: doc-shift-args
 9395: 
 9396: Finally, at the lowest level Gforth provides the following words:
 9397: 
 9398: doc-argc
 9399: doc-argv
 9400: 
 9401: @c -------------------------------------------------------------
 9402: @node Locals, Structures, OS command line arguments, Words
 9403: @section Locals
 9404: @cindex locals
 9405: 
 9406: Local variables can make Forth programming more enjoyable and Forth
 9407: programs easier to read. Unfortunately, the locals of ANS Forth are
 9408: laden with restrictions. Therefore, we provide not only the ANS Forth
 9409: locals wordset, but also our own, more powerful locals wordset (we
 9410: implemented the ANS Forth locals wordset through our locals wordset).
 9411: 
 9412: The ideas in this section have also been published in M. Anton Ertl,
 9413: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl94l.ps.gz,
 9414: Automatic Scoping of Local Variables}}, EuroForth '94.
 9415: 
 9416: @menu
 9417: * Gforth locals::               
 9418: * ANS Forth locals::            
 9419: @end menu
 9420: 
 9421: @node Gforth locals, ANS Forth locals, Locals, Locals
 9422: @subsection Gforth locals
 9423: @cindex Gforth locals
 9424: @cindex locals, Gforth style
 9425: 
 9426: Locals can be defined with
 9427: 
 9428: @example
 9429: @{ local1 local2 ... -- comment @}
 9430: @end example
 9431: or
 9432: @example
 9433: @{ local1 local2 ... @}
 9434: @end example
 9435: 
 9436: E.g.,
 9437: @example
 9438: : max @{ n1 n2 -- n3 @}
 9439:  n1 n2 > if
 9440:    n1
 9441:  else
 9442:    n2
 9443:  endif ;
 9444: @end example
 9445: 
 9446: The similarity of locals definitions with stack comments is intended. A
 9447: locals definition often replaces the stack comment of a word. The order
 9448: of the locals corresponds to the order in a stack comment and everything
 9449: after the @code{--} is really a comment.
 9450: 
 9451: This similarity has one disadvantage: It is too easy to confuse locals
 9452: declarations with stack comments, causing bugs and making them hard to
 9453: find. However, this problem can be avoided by appropriate coding
 9454: conventions: Do not use both notations in the same program. If you do,
 9455: they should be distinguished using additional means, e.g. by position.
 9456: 
 9457: @cindex types of locals
 9458: @cindex locals types
 9459: The name of the local may be preceded by a type specifier, e.g.,
 9460: @code{F:} for a floating point value:
 9461: 
 9462: @example
 9463: : CX* @{ F: Ar F: Ai F: Br F: Bi -- Cr Ci @}
 9464: \ complex multiplication
 9465:  Ar Br f* Ai Bi f* f-
 9466:  Ar Bi f* Ai Br f* f+ ;
 9467: @end example
 9468: 
 9469: @cindex flavours of locals
 9470: @cindex locals flavours
 9471: @cindex value-flavoured locals
 9472: @cindex variable-flavoured locals
 9473: Gforth currently supports cells (@code{W:}, @code{W^}), doubles
 9474: (@code{D:}, @code{D^}), floats (@code{F:}, @code{F^}) and characters
 9475: (@code{C:}, @code{C^}) in two flavours: a value-flavoured local (defined
 9476: with @code{W:}, @code{D:} etc.) produces its value and can be changed
 9477: with @code{TO}. A variable-flavoured local (defined with @code{W^} etc.)
 9478: produces its address (which becomes invalid when the variable's scope is
 9479: left). E.g., the standard word @code{emit} can be defined in terms of
 9480: @code{type} like this:
 9481: 
 9482: @example
 9483: : emit @{ C^ char* -- @}
 9484:     char* 1 type ;
 9485: @end example
 9486: 
 9487: @cindex default type of locals
 9488: @cindex locals, default type
 9489: A local without type specifier is a @code{W:} local. Both flavours of
 9490: locals are initialized with values from the data or FP stack.
 9491: 
 9492: Currently there is no way to define locals with user-defined data
 9493: structures, but we are working on it.
 9494: 
 9495: Gforth allows defining locals everywhere in a colon definition. This
 9496: poses the following questions:
 9497: 
 9498: @menu
 9499: * Where are locals visible by name?::  
 9500: * How long do locals live?::    
 9501: * Locals programming style::    
 9502: * Locals implementation::       
 9503: @end menu
 9504: 
 9505: @node Where are locals visible by name?, How long do locals live?, Gforth locals, Gforth locals
 9506: @subsubsection Where are locals visible by name?
 9507: @cindex locals visibility
 9508: @cindex visibility of locals
 9509: @cindex scope of locals
 9510: 
 9511: Basically, the answer is that locals are visible where you would expect
 9512: it in block-structured languages, and sometimes a little longer. If you
 9513: want to restrict the scope of a local, enclose its definition in
 9514: @code{SCOPE}...@code{ENDSCOPE}.
 9515: 
 9516: 
 9517: doc-scope
 9518: doc-endscope
 9519: 
 9520: 
 9521: These words behave like control structure words, so you can use them
 9522: with @code{CS-PICK} and @code{CS-ROLL} to restrict the scope in
 9523: arbitrary ways.
 9524: 
 9525: If you want a more exact answer to the visibility question, here's the
 9526: basic principle: A local is visible in all places that can only be
 9527: reached through the definition of the local@footnote{In compiler
 9528: construction terminology, all places dominated by the definition of the
 9529: local.}. In other words, it is not visible in places that can be reached
 9530: without going through the definition of the local. E.g., locals defined
 9531: in @code{IF}...@code{ENDIF} are visible until the @code{ENDIF}, locals
 9532: defined in @code{BEGIN}...@code{UNTIL} are visible after the
 9533: @code{UNTIL} (until, e.g., a subsequent @code{ENDSCOPE}).
 9534: 
 9535: The reasoning behind this solution is: We want to have the locals
 9536: visible as long as it is meaningful. The user can always make the
 9537: visibility shorter by using explicit scoping. In a place that can
 9538: only be reached through the definition of a local, the meaning of a
 9539: local name is clear. In other places it is not: How is the local
 9540: initialized at the control flow path that does not contain the
 9541: definition? Which local is meant, if the same name is defined twice in
 9542: two independent control flow paths?
 9543: 
 9544: This should be enough detail for nearly all users, so you can skip the
 9545: rest of this section. If you really must know all the gory details and
 9546: options, read on.
 9547: 
 9548: In order to implement this rule, the compiler has to know which places
 9549: are unreachable. It knows this automatically after @code{AHEAD},
 9550: @code{AGAIN}, @code{EXIT} and @code{LEAVE}; in other cases (e.g., after
 9551: most @code{THROW}s), you can use the word @code{UNREACHABLE} to tell the
 9552: compiler that the control flow never reaches that place. If
 9553: @code{UNREACHABLE} is not used where it could, the only consequence is
 9554: that the visibility of some locals is more limited than the rule above
 9555: says. If @code{UNREACHABLE} is used where it should not (i.e., if you
 9556: lie to the compiler), buggy code will be produced.
 9557: 
 9558: 
 9559: doc-unreachable
 9560: 
 9561: 
 9562: Another problem with this rule is that at @code{BEGIN}, the compiler
 9563: does not know which locals will be visible on the incoming
 9564: back-edge. All problems discussed in the following are due to this
 9565: ignorance of the compiler (we discuss the problems using @code{BEGIN}
 9566: loops as examples; the discussion also applies to @code{?DO} and other
 9567: loops). Perhaps the most insidious example is:
 9568: @example
 9569: AHEAD
 9570: BEGIN
 9571:   x
 9572: [ 1 CS-ROLL ] THEN
 9573:   @{ x @}
 9574:   ...
 9575: UNTIL
 9576: @end example
 9577: 
 9578: This should be legal according to the visibility rule. The use of
 9579: @code{x} can only be reached through the definition; but that appears
 9580: textually below the use.
 9581: 
 9582: From this example it is clear that the visibility rules cannot be fully
 9583: implemented without major headaches. Our implementation treats common
 9584: cases as advertised and the exceptions are treated in a safe way: The
 9585: compiler makes a reasonable guess about the locals visible after a
 9586: @code{BEGIN}; if it is too pessimistic, the
 9587: user will get a spurious error about the local not being defined; if the
 9588: compiler is too optimistic, it will notice this later and issue a
 9589: warning. In the case above the compiler would complain about @code{x}
 9590: being undefined at its use. You can see from the obscure examples in
 9591: this section that it takes quite unusual control structures to get the
 9592: compiler into trouble, and even then it will often do fine.
 9593: 
 9594: If the @code{BEGIN} is reachable from above, the most optimistic guess
 9595: is that all locals visible before the @code{BEGIN} will also be
 9596: visible after the @code{BEGIN}. This guess is valid for all loops that
 9597: are entered only through the @code{BEGIN}, in particular, for normal
 9598: @code{BEGIN}...@code{WHILE}...@code{REPEAT} and
 9599: @code{BEGIN}...@code{UNTIL} loops and it is implemented in our
 9600: compiler. When the branch to the @code{BEGIN} is finally generated by
 9601: @code{AGAIN} or @code{UNTIL}, the compiler checks the guess and
 9602: warns the user if it was too optimistic:
 9603: @example
 9604: IF
 9605:   @{ x @}
 9606: BEGIN
 9607:   \ x ? 
 9608: [ 1 cs-roll ] THEN
 9609:   ...
 9610: UNTIL
 9611: @end example
 9612: 
 9613: Here, @code{x} lives only until the @code{BEGIN}, but the compiler
 9614: optimistically assumes that it lives until the @code{THEN}. It notices
 9615: this difference when it compiles the @code{UNTIL} and issues a
 9616: warning. The user can avoid the warning, and make sure that @code{x}
 9617: is not used in the wrong area by using explicit scoping:
 9618: @example
 9619: IF
 9620:   SCOPE
 9621:   @{ x @}
 9622:   ENDSCOPE
 9623: BEGIN
 9624: [ 1 cs-roll ] THEN
 9625:   ...
 9626: UNTIL
 9627: @end example
 9628: 
 9629: Since the guess is optimistic, there will be no spurious error messages
 9630: about undefined locals.
 9631: 
 9632: If the @code{BEGIN} is not reachable from above (e.g., after
 9633: @code{AHEAD} or @code{EXIT}), the compiler cannot even make an
 9634: optimistic guess, as the locals visible after the @code{BEGIN} may be
 9635: defined later. Therefore, the compiler assumes that no locals are
 9636: visible after the @code{BEGIN}. However, the user can use
 9637: @code{ASSUME-LIVE} to make the compiler assume that the same locals are
 9638: visible at the BEGIN as at the point where the top control-flow stack
 9639: item was created.
 9640: 
 9641: 
 9642: doc-assume-live
 9643: 
 9644: 
 9645: @noindent
 9646: E.g.,
 9647: @example
 9648: @{ x @}
 9649: AHEAD
 9650: ASSUME-LIVE
 9651: BEGIN
 9652:   x
 9653: [ 1 CS-ROLL ] THEN
 9654:   ...
 9655: UNTIL
 9656: @end example
 9657: 
 9658: Other cases where the locals are defined before the @code{BEGIN} can be
 9659: handled by inserting an appropriate @code{CS-ROLL} before the
 9660: @code{ASSUME-LIVE} (and changing the control-flow stack manipulation
 9661: behind the @code{ASSUME-LIVE}).
 9662: 
 9663: Cases where locals are defined after the @code{BEGIN} (but should be
 9664: visible immediately after the @code{BEGIN}) can only be handled by
 9665: rearranging the loop. E.g., the ``most insidious'' example above can be
 9666: arranged into:
 9667: @example
 9668: BEGIN
 9669:   @{ x @}
 9670:   ... 0=
 9671: WHILE
 9672:   x
 9673: REPEAT
 9674: @end example
 9675: 
 9676: @node How long do locals live?, Locals programming style, Where are locals visible by name?, Gforth locals
 9677: @subsubsection How long do locals live?
 9678: @cindex locals lifetime
 9679: @cindex lifetime of locals
 9680: 
 9681: The right answer for the lifetime question would be: A local lives at
 9682: least as long as it can be accessed. For a value-flavoured local this
 9683: means: until the end of its visibility. However, a variable-flavoured
 9684: local could be accessed through its address far beyond its visibility
 9685: scope. Ultimately, this would mean that such locals would have to be
 9686: garbage collected. Since this entails un-Forth-like implementation
 9687: complexities, I adopted the same cowardly solution as some other
 9688: languages (e.g., C): The local lives only as long as it is visible;
 9689: afterwards its address is invalid (and programs that access it
 9690: afterwards are erroneous).
 9691: 
 9692: @node Locals programming style, Locals implementation, How long do locals live?, Gforth locals
 9693: @subsubsection Locals programming style
 9694: @cindex locals programming style
 9695: @cindex programming style, locals
 9696: 
 9697: The freedom to define locals anywhere has the potential to change
 9698: programming styles dramatically. In particular, the need to use the
 9699: return stack for intermediate storage vanishes. Moreover, all stack
 9700: manipulations (except @code{PICK}s and @code{ROLL}s with run-time
 9701: determined arguments) can be eliminated: If the stack items are in the
 9702: wrong order, just write a locals definition for all of them; then
 9703: write the items in the order you want.
 9704: 
 9705: This seems a little far-fetched and eliminating stack manipulations is
 9706: unlikely to become a conscious programming objective. Still, the number
 9707: of stack manipulations will be reduced dramatically if local variables
 9708: are used liberally (e.g., compare @code{max} (@pxref{Gforth locals}) with
 9709: a traditional implementation of @code{max}).
 9710: 
 9711: This shows one potential benefit of locals: making Forth programs more
 9712: readable. Of course, this benefit will only be realized if the
 9713: programmers continue to honour the principle of factoring instead of
 9714: using the added latitude to make the words longer.
 9715: 
 9716: @cindex single-assignment style for locals
 9717: Using @code{TO} can and should be avoided.  Without @code{TO},
 9718: every value-flavoured local has only a single assignment and many
 9719: advantages of functional languages apply to Forth. I.e., programs are
 9720: easier to analyse, to optimize and to read: It is clear from the
 9721: definition what the local stands for, it does not turn into something
 9722: different later.
 9723: 
 9724: E.g., a definition using @code{TO} might look like this:
 9725: @example
 9726: : strcmp @{ addr1 u1 addr2 u2 -- n @}
 9727:  u1 u2 min 0
 9728:  ?do
 9729:    addr1 c@@ addr2 c@@ -
 9730:    ?dup-if
 9731:      unloop exit
 9732:    then
 9733:    addr1 char+ TO addr1
 9734:    addr2 char+ TO addr2
 9735:  loop
 9736:  u1 u2 - ;
 9737: @end example
 9738: Here, @code{TO} is used to update @code{addr1} and @code{addr2} at
 9739: every loop iteration. @code{strcmp} is a typical example of the
 9740: readability problems of using @code{TO}. When you start reading
 9741: @code{strcmp}, you think that @code{addr1} refers to the start of the
 9742: string. Only near the end of the loop you realize that it is something
 9743: else.
 9744: 
 9745: This can be avoided by defining two locals at the start of the loop that
 9746: are initialized with the right value for the current iteration.
 9747: @example
 9748: : strcmp @{ addr1 u1 addr2 u2 -- n @}
 9749:  addr1 addr2
 9750:  u1 u2 min 0 
 9751:  ?do @{ s1 s2 @}
 9752:    s1 c@@ s2 c@@ -
 9753:    ?dup-if
 9754:      unloop exit
 9755:    then
 9756:    s1 char+ s2 char+
 9757:  loop
 9758:  2drop
 9759:  u1 u2 - ;
 9760: @end example
 9761: Here it is clear from the start that @code{s1} has a different value
 9762: in every loop iteration.
 9763: 
 9764: @node Locals implementation,  , Locals programming style, Gforth locals
 9765: @subsubsection Locals implementation
 9766: @cindex locals implementation
 9767: @cindex implementation of locals
 9768: 
 9769: @cindex locals stack
 9770: Gforth uses an extra locals stack. The most compelling reason for
 9771: this is that the return stack is not float-aligned; using an extra stack
 9772: also eliminates the problems and restrictions of using the return stack
 9773: as locals stack. Like the other stacks, the locals stack grows toward
 9774: lower addresses. A few primitives allow an efficient implementation:
 9775: 
 9776: 
 9777: doc-@local#
 9778: doc-f@local#
 9779: doc-laddr#
 9780: doc-lp+!#
 9781: doc-lp!
 9782: doc->l
 9783: doc-f>l
 9784: 
 9785: 
 9786: In addition to these primitives, some specializations of these
 9787: primitives for commonly occurring inline arguments are provided for
 9788: efficiency reasons, e.g., @code{@@local0} as specialization of
 9789: @code{@@local#} for the inline argument 0. The following compiling words
 9790: compile the right specialized version, or the general version, as
 9791: appropriate:
 9792: 
 9793: 
 9794: @c doc-compile-@local
 9795: @c doc-compile-f@local
 9796: doc-compile-lp+!
 9797: 
 9798: 
 9799: Combinations of conditional branches and @code{lp+!#} like
 9800: @code{?branch-lp+!#} (the locals pointer is only changed if the branch
 9801: is taken) are provided for efficiency and correctness in loops.
 9802: 
 9803: A special area in the dictionary space is reserved for keeping the
 9804: local variable names. @code{@{} switches the dictionary pointer to this
 9805: area and @code{@}} switches it back and generates the locals
 9806: initializing code. @code{W:} etc.@ are normal defining words. This
 9807: special area is cleared at the start of every colon definition.
 9808: 
 9809: @cindex word list for defining locals
 9810: A special feature of Gforth's dictionary is used to implement the
 9811: definition of locals without type specifiers: every word list (aka
 9812: vocabulary) has its own methods for searching
 9813: etc. (@pxref{Word Lists}). For the present purpose we defined a word list
 9814: with a special search method: When it is searched for a word, it
 9815: actually creates that word using @code{W:}. @code{@{} changes the search
 9816: order to first search the word list containing @code{@}}, @code{W:} etc.,
 9817: and then the word list for defining locals without type specifiers.
 9818: 
 9819: The lifetime rules support a stack discipline within a colon
 9820: definition: The lifetime of a local is either nested with other locals
 9821: lifetimes or it does not overlap them.
 9822: 
 9823: At @code{BEGIN}, @code{IF}, and @code{AHEAD} no code for locals stack
 9824: pointer manipulation is generated. Between control structure words
 9825: locals definitions can push locals onto the locals stack. @code{AGAIN}
 9826: is the simplest of the other three control flow words. It has to
 9827: restore the locals stack depth of the corresponding @code{BEGIN}
 9828: before branching. The code looks like this:
 9829: @format
 9830: @code{lp+!#} current-locals-size @minus{} dest-locals-size
 9831: @code{branch} <begin>
 9832: @end format
 9833: 
 9834: @code{UNTIL} is a little more complicated: If it branches back, it
 9835: must adjust the stack just like @code{AGAIN}. But if it falls through,
 9836: the locals stack must not be changed. The compiler generates the
 9837: following code:
 9838: @format
 9839: @code{?branch-lp+!#} <begin> current-locals-size @minus{} dest-locals-size
 9840: @end format
 9841: The locals stack pointer is only adjusted if the branch is taken.
 9842: 
 9843: @code{THEN} can produce somewhat inefficient code:
 9844: @format
 9845: @code{lp+!#} current-locals-size @minus{} orig-locals-size
 9846: <orig target>:
 9847: @code{lp+!#} orig-locals-size @minus{} new-locals-size
 9848: @end format
 9849: The second @code{lp+!#} adjusts the locals stack pointer from the
 9850: level at the @i{orig} point to the level after the @code{THEN}. The
 9851: first @code{lp+!#} adjusts the locals stack pointer from the current
 9852: level to the level at the orig point, so the complete effect is an
 9853: adjustment from the current level to the right level after the
 9854: @code{THEN}.
 9855: 
 9856: @cindex locals information on the control-flow stack
 9857: @cindex control-flow stack items, locals information
 9858: In a conventional Forth implementation a dest control-flow stack entry
 9859: is just the target address and an orig entry is just the address to be
 9860: patched. Our locals implementation adds a word list to every orig or dest
 9861: item. It is the list of locals visible (or assumed visible) at the point
 9862: described by the entry. Our implementation also adds a tag to identify
 9863: the kind of entry, in particular to differentiate between live and dead
 9864: (reachable and unreachable) orig entries.
 9865: 
 9866: A few unusual operations have to be performed on locals word lists:
 9867: 
 9868: 
 9869: doc-common-list
 9870: doc-sub-list?
 9871: doc-list-size
 9872: 
 9873: 
 9874: Several features of our locals word list implementation make these
 9875: operations easy to implement: The locals word lists are organised as
 9876: linked lists; the tails of these lists are shared, if the lists
 9877: contain some of the same locals; and the address of a name is greater
 9878: than the address of the names behind it in the list.
 9879: 
 9880: Another important implementation detail is the variable
 9881: @code{dead-code}. It is used by @code{BEGIN} and @code{THEN} to
 9882: determine if they can be reached directly or only through the branch
 9883: that they resolve. @code{dead-code} is set by @code{UNREACHABLE},
 9884: @code{AHEAD}, @code{EXIT} etc., and cleared at the start of a colon
 9885: definition, by @code{BEGIN} and usually by @code{THEN}.
 9886: 
 9887: Counted loops are similar to other loops in most respects, but
 9888: @code{LEAVE} requires special attention: It performs basically the same
 9889: service as @code{AHEAD}, but it does not create a control-flow stack
 9890: entry. Therefore the information has to be stored elsewhere;
 9891: traditionally, the information was stored in the target fields of the
 9892: branches created by the @code{LEAVE}s, by organizing these fields into a
 9893: linked list. Unfortunately, this clever trick does not provide enough
 9894: space for storing our extended control flow information. Therefore, we
 9895: introduce another stack, the leave stack. It contains the control-flow
 9896: stack entries for all unresolved @code{LEAVE}s.
 9897: 
 9898: Local names are kept until the end of the colon definition, even if
 9899: they are no longer visible in any control-flow path. In a few cases
 9900: this may lead to increased space needs for the locals name area, but
 9901: usually less than reclaiming this space would cost in code size.
 9902: 
 9903: 
 9904: @node ANS Forth locals,  , Gforth locals, Locals
 9905: @subsection ANS Forth locals
 9906: @cindex locals, ANS Forth style
 9907: 
 9908: The ANS Forth locals wordset does not define a syntax for locals, but
 9909: words that make it possible to define various syntaxes. One of the
 9910: possible syntaxes is a subset of the syntax we used in the Gforth locals
 9911: wordset, i.e.:
 9912: 
 9913: @example
 9914: @{ local1 local2 ... -- comment @}
 9915: @end example
 9916: @noindent
 9917: or
 9918: @example
 9919: @{ local1 local2 ... @}
 9920: @end example
 9921: 
 9922: The order of the locals corresponds to the order in a stack comment. The
 9923: restrictions are:
 9924: 
 9925: @itemize @bullet
 9926: @item
 9927: Locals can only be cell-sized values (no type specifiers are allowed).
 9928: @item
 9929: Locals can be defined only outside control structures.
 9930: @item
 9931: Locals can interfere with explicit usage of the return stack. For the
 9932: exact (and long) rules, see the standard. If you don't use return stack
 9933: accessing words in a definition using locals, you will be all right. The
 9934: purpose of this rule is to make locals implementation on the return
 9935: stack easier.
 9936: @item
 9937: The whole definition must be in one line.
 9938: @end itemize
 9939: 
 9940: Locals defined in ANS Forth behave like @code{VALUE}s
 9941: (@pxref{Values}). I.e., they are initialized from the stack. Using their
 9942: name produces their value. Their value can be changed using @code{TO}.
 9943: 
 9944: Since the syntax above is supported by Gforth directly, you need not do
 9945: anything to use it. If you want to port a program using this syntax to
 9946: another ANS Forth system, use @file{compat/anslocal.fs} to implement the
 9947: syntax on the other system.
 9948: 
 9949: Note that a syntax shown in the standard, section A.13 looks
 9950: similar, but is quite different in having the order of locals
 9951: reversed. Beware!
 9952: 
 9953: The ANS Forth locals wordset itself consists of one word:
 9954: 
 9955: doc-(local)
 9956: 
 9957: The ANS Forth locals extension wordset defines a syntax using
 9958: @code{locals|}, but it is so awful that we strongly recommend not to use
 9959: it. We have implemented this syntax to make porting to Gforth easy, but
 9960: do not document it here. The problem with this syntax is that the locals
 9961: are defined in an order reversed with respect to the standard stack
 9962: comment notation, making programs harder to read, and easier to misread
 9963: and miswrite. The only merit of this syntax is that it is easy to
 9964: implement using the ANS Forth locals wordset.
 9965: 
 9966: 
 9967: @c ----------------------------------------------------------
 9968: @node Structures, Object-oriented Forth, Locals, Words
 9969: @section  Structures
 9970: @cindex structures
 9971: @cindex records
 9972: 
 9973: This section presents the structure package that comes with Gforth. A
 9974: version of the package implemented in ANS Forth is available in
 9975: @file{compat/struct.fs}. This package was inspired by a posting on
 9976: comp.lang.forth in 1989 (unfortunately I don't remember, by whom;
 9977: possibly John Hayes). A version of this section has been published in
 9978: M. Anton Ertl,
 9979: @uref{http://www.complang.tuwien.ac.at/forth/objects/structs.html, Yet
 9980: Another Forth Structures Package}, Forth Dimensions 19(3), pages
 9981: 13--16. Marcel Hendrix provided helpful comments.
 9982: 
 9983: @menu
 9984: * Why explicit structure support?::  
 9985: * Structure Usage::             
 9986: * Structure Naming Convention::  
 9987: * Structure Implementation::    
 9988: * Structure Glossary::          
 9989: * Forth200x Structures::        
 9990: @end menu
 9991: 
 9992: @node Why explicit structure support?, Structure Usage, Structures, Structures
 9993: @subsection Why explicit structure support?
 9994: 
 9995: @cindex address arithmetic for structures
 9996: @cindex structures using address arithmetic
 9997: If we want to use a structure containing several fields, we could simply
 9998: reserve memory for it, and access the fields using address arithmetic
 9999: (@pxref{Address arithmetic}). As an example, consider a structure with
10000: the following fields
10001: 
10002: @table @code
10003: @item a
10004: is a float
10005: @item b
10006: is a cell
10007: @item c
10008: is a float
10009: @end table
10010: 
10011: Given the (float-aligned) base address of the structure we get the
10012: address of the field
10013: 
10014: @table @code
10015: @item a
10016: without doing anything further.
10017: @item b
10018: with @code{float+}
10019: @item c
10020: with @code{float+ cell+ faligned}
10021: @end table
10022: 
10023: It is easy to see that this can become quite tiring. 
10024: 
10025: Moreover, it is not very readable, because seeing a
10026: @code{cell+} tells us neither which kind of structure is
10027: accessed nor what field is accessed; we have to somehow infer the kind
10028: of structure, and then look up in the documentation, which field of
10029: that structure corresponds to that offset.
10030: 
10031: Finally, this kind of address arithmetic also causes maintenance
10032: troubles: If you add or delete a field somewhere in the middle of the
10033: structure, you have to find and change all computations for the fields
10034: afterwards.
10035: 
10036: So, instead of using @code{cell+} and friends directly, how
10037: about storing the offsets in constants:
10038: 
10039: @example
10040: 0 constant a-offset
10041: 0 float+ constant b-offset
10042: 0 float+ cell+ faligned c-offset
10043: @end example
10044: 
10045: Now we can get the address of field @code{x} with @code{x-offset
10046: +}. This is much better in all respects. Of course, you still
10047: have to change all later offset definitions if you add a field. You can
10048: fix this by declaring the offsets in the following way:
10049: 
10050: @example
10051: 0 constant a-offset
10052: a-offset float+ constant b-offset
10053: b-offset cell+ faligned constant c-offset
10054: @end example
10055: 
10056: Since we always use the offsets with @code{+}, we could use a defining
10057: word @code{cfield} that includes the @code{+} in the action of the
10058: defined word:
10059: 
10060: @example
10061: : cfield ( n "name" -- )
10062:     create ,
10063: does> ( name execution: addr1 -- addr2 )
10064:     @@ + ;
10065: 
10066: 0 cfield a
10067: 0 a float+ cfield b
10068: 0 b cell+ faligned cfield c
10069: @end example
10070: 
10071: Instead of @code{x-offset +}, we now simply write @code{x}.
10072: 
10073: The structure field words now can be used quite nicely. However,
10074: their definition is still a bit cumbersome: We have to repeat the
10075: name, the information about size and alignment is distributed before
10076: and after the field definitions etc.  The structure package presented
10077: here addresses these problems.
10078: 
10079: @node Structure Usage, Structure Naming Convention, Why explicit structure support?, Structures
10080: @subsection Structure Usage
10081: @cindex structure usage
10082: 
10083: @cindex @code{field} usage
10084: @cindex @code{struct} usage
10085: @cindex @code{end-struct} usage
10086: You can define a structure for a (data-less) linked list with:
10087: @example
10088: struct
10089:     cell% field list-next
10090: end-struct list%
10091: @end example
10092: 
10093: With the address of the list node on the stack, you can compute the
10094: address of the field that contains the address of the next node with
10095: @code{list-next}. E.g., you can determine the length of a list
10096: with:
10097: 
10098: @example
10099: : list-length ( list -- n )
10100: \ "list" is a pointer to the first element of a linked list
10101: \ "n" is the length of the list
10102:     0 BEGIN ( list1 n1 )
10103:         over
10104:     WHILE ( list1 n1 )
10105:         1+ swap list-next @@ swap
10106:     REPEAT
10107:     nip ;
10108: @end example
10109: 
10110: You can reserve memory for a list node in the dictionary with
10111: @code{list% %allot}, which leaves the address of the list node on the
10112: stack. For the equivalent allocation on the heap you can use @code{list%
10113: %alloc} (or, for an @code{allocate}-like stack effect (i.e., with ior),
10114: use @code{list% %allocate}). You can get the the size of a list
10115: node with @code{list% %size} and its alignment with @code{list%
10116: %alignment}.
10117: 
10118: Note that in ANS Forth the body of a @code{create}d word is
10119: @code{aligned} but not necessarily @code{faligned};
10120: therefore, if you do a:
10121: 
10122: @example
10123: create @emph{name} foo% %allot drop
10124: @end example
10125: 
10126: @noindent
10127: then the memory alloted for @code{foo%} is guaranteed to start at the
10128: body of @code{@emph{name}} only if @code{foo%} contains only character,
10129: cell and double fields.  Therefore, if your structure contains floats,
10130: better use
10131: 
10132: @example
10133: foo% %allot constant @emph{name}
10134: @end example
10135: 
10136: @cindex structures containing structures
10137: You can include a structure @code{foo%} as a field of
10138: another structure, like this:
10139: @example
10140: struct
10141: ...
10142:     foo% field ...
10143: ...
10144: end-struct ...
10145: @end example
10146: 
10147: @cindex structure extension
10148: @cindex extended records
10149: Instead of starting with an empty structure, you can extend an
10150: existing structure. E.g., a plain linked list without data, as defined
10151: above, is hardly useful; You can extend it to a linked list of integers,
10152: like this:@footnote{This feature is also known as @emph{extended
10153: records}. It is the main innovation in the Oberon language; in other
10154: words, adding this feature to Modula-2 led Wirth to create a new
10155: language, write a new compiler etc.  Adding this feature to Forth just
10156: required a few lines of code.}
10157: 
10158: @example
10159: list%
10160:     cell% field intlist-int
10161: end-struct intlist%
10162: @end example
10163: 
10164: @code{intlist%} is a structure with two fields:
10165: @code{list-next} and @code{intlist-int}.
10166: 
10167: @cindex structures containing arrays
10168: You can specify an array type containing @emph{n} elements of
10169: type @code{foo%} like this:
10170: 
10171: @example
10172: foo% @emph{n} *
10173: @end example
10174: 
10175: You can use this array type in any place where you can use a normal
10176: type, e.g., when defining a @code{field}, or with
10177: @code{%allot}.
10178: 
10179: @cindex first field optimization
10180: The first field is at the base address of a structure and the word for
10181: this field (e.g., @code{list-next}) actually does not change the address
10182: on the stack. You may be tempted to leave it away in the interest of
10183: run-time and space efficiency. This is not necessary, because the
10184: structure package optimizes this case: If you compile a first-field
10185: words, no code is generated. So, in the interest of readability and
10186: maintainability you should include the word for the field when accessing
10187: the field.
10188: 
10189: 
10190: @node Structure Naming Convention, Structure Implementation, Structure Usage, Structures
10191: @subsection Structure Naming Convention
10192: @cindex structure naming convention
10193: 
10194: The field names that come to (my) mind are often quite generic, and,
10195: if used, would cause frequent name clashes. E.g., many structures
10196: probably contain a @code{counter} field. The structure names
10197: that come to (my) mind are often also the logical choice for the names
10198: of words that create such a structure.
10199: 
10200: Therefore, I have adopted the following naming conventions: 
10201: 
10202: @itemize @bullet
10203: @cindex field naming convention
10204: @item
10205: The names of fields are of the form
10206: @code{@emph{struct}-@emph{field}}, where
10207: @code{@emph{struct}} is the basic name of the structure, and
10208: @code{@emph{field}} is the basic name of the field. You can
10209: think of field words as converting the (address of the)
10210: structure into the (address of the) field.
10211: 
10212: @cindex structure naming convention
10213: @item
10214: The names of structures are of the form
10215: @code{@emph{struct}%}, where
10216: @code{@emph{struct}} is the basic name of the structure.
10217: @end itemize
10218: 
10219: This naming convention does not work that well for fields of extended
10220: structures; e.g., the integer list structure has a field
10221: @code{intlist-int}, but has @code{list-next}, not
10222: @code{intlist-next}.
10223: 
10224: @node Structure Implementation, Structure Glossary, Structure Naming Convention, Structures
10225: @subsection Structure Implementation
10226: @cindex structure implementation
10227: @cindex implementation of structures
10228: 
10229: The central idea in the implementation is to pass the data about the
10230: structure being built on the stack, not in some global
10231: variable. Everything else falls into place naturally once this design
10232: decision is made.
10233: 
10234: The type description on the stack is of the form @emph{align
10235: size}. Keeping the size on the top-of-stack makes dealing with arrays
10236: very simple.
10237: 
10238: @code{field} is a defining word that uses @code{Create}
10239: and @code{DOES>}. The body of the field contains the offset
10240: of the field, and the normal @code{DOES>} action is simply:
10241: 
10242: @example
10243: @@ +
10244: @end example
10245: 
10246: @noindent
10247: i.e., add the offset to the address, giving the stack effect
10248: @i{addr1 -- addr2} for a field.
10249: 
10250: @cindex first field optimization, implementation
10251: This simple structure is slightly complicated by the optimization
10252: for fields with offset 0, which requires a different
10253: @code{DOES>}-part (because we cannot rely on there being
10254: something on the stack if such a field is invoked during
10255: compilation). Therefore, we put the different @code{DOES>}-parts
10256: in separate words, and decide which one to invoke based on the
10257: offset. For a zero offset, the field is basically a noop; it is
10258: immediate, and therefore no code is generated when it is compiled.
10259: 
10260: @node Structure Glossary, Forth200x Structures, Structure Implementation, Structures
10261: @subsection Structure Glossary
10262: @cindex structure glossary
10263: 
10264: 
10265: doc-%align
10266: doc-%alignment
10267: doc-%alloc
10268: doc-%allocate
10269: doc-%allot
10270: doc-cell%
10271: doc-char%
10272: doc-dfloat%
10273: doc-double%
10274: doc-end-struct
10275: doc-field
10276: doc-float%
10277: doc-naligned
10278: doc-sfloat%
10279: doc-%size
10280: doc-struct
10281: 
10282: 
10283: @node Forth200x Structures,  , Structure Glossary, Structures
10284: @subsection Forth200x Structures
10285: @cindex Structures in Forth200x
10286: 
10287: The Forth 200x standard defines a slightly less convenient form of
10288: structures.  In general (when using @code{field+}, you have to perform
10289: the alignment yourself, but there are a number of convenience words
10290: (e.g., @code{field:} that perform the alignment for you.
10291: 
10292: A typical usage example is:
10293: 
10294: @example
10295: 0
10296:   field:                   s-a
10297:   faligned 2 floats +field s-b
10298: constant s-struct
10299: @end example
10300: 
10301: An alternative way of writing this structure is:
10302: 
10303: @example
10304: begin-structure s-struct
10305:   field:                   s-a
10306:   faligned 2 floats +field s-b
10307: end-structure
10308: @end example
10309: 
10310: doc-begin-structure
10311: doc-end-structure
10312: doc-+field
10313: doc-cfield:
10314: doc-field:
10315: doc-2field:
10316: doc-ffield:
10317: doc-sffield:
10318: doc-dffield:
10319: 
10320: @c -------------------------------------------------------------
10321: @node Object-oriented Forth, Programming Tools, Structures, Words
10322: @section Object-oriented Forth
10323: 
10324: Gforth comes with three packages for object-oriented programming:
10325: @file{objects.fs}, @file{oof.fs}, and @file{mini-oof.fs}; none of them
10326: is preloaded, so you have to @code{include} them before use. The most
10327: important differences between these packages (and others) are discussed
10328: in @ref{Comparison with other object models}. All packages are written
10329: in ANS Forth and can be used with any other ANS Forth.
10330: 
10331: @menu
10332: * Why object-oriented programming?::  
10333: * Object-Oriented Terminology::  
10334: * Objects::                     
10335: * OOF::                         
10336: * Mini-OOF::                    
10337: * Comparison with other object models::  
10338: @end menu
10339: 
10340: @c ----------------------------------------------------------------
10341: @node Why object-oriented programming?, Object-Oriented Terminology, Object-oriented Forth, Object-oriented Forth
10342: @subsection Why object-oriented programming?
10343: @cindex object-oriented programming motivation
10344: @cindex motivation for object-oriented programming
10345: 
10346: Often we have to deal with several data structures (@emph{objects}),
10347: that have to be treated similarly in some respects, but differently in
10348: others. Graphical objects are the textbook example: circles, triangles,
10349: dinosaurs, icons, and others, and we may want to add more during program
10350: development. We want to apply some operations to any graphical object,
10351: e.g., @code{draw} for displaying it on the screen. However, @code{draw}
10352: has to do something different for every kind of object.
10353: @comment TODO add some other operations eg perimeter, area
10354: @comment and tie in to concrete examples later..
10355: 
10356: We could implement @code{draw} as a big @code{CASE}
10357: control structure that executes the appropriate code depending on the
10358: kind of object to be drawn. This would be not be very elegant, and,
10359: moreover, we would have to change @code{draw} every time we add
10360: a new kind of graphical object (say, a spaceship).
10361: 
10362: What we would rather do is: When defining spaceships, we would tell
10363: the system: ``Here's how you @code{draw} a spaceship; you figure
10364: out the rest''.
10365: 
10366: This is the problem that all systems solve that (rightfully) call
10367: themselves object-oriented; the object-oriented packages presented here
10368: solve this problem (and not much else).
10369: @comment TODO ?list properties of oo systems.. oo vs o-based?
10370: 
10371: @c ------------------------------------------------------------------------
10372: @node Object-Oriented Terminology, Objects, Why object-oriented programming?, Object-oriented Forth
10373: @subsection Object-Oriented Terminology
10374: @cindex object-oriented terminology
10375: @cindex terminology for object-oriented programming
10376: 
10377: This section is mainly for reference, so you don't have to understand
10378: all of it right away.  The terminology is mainly Smalltalk-inspired.  In
10379: short:
10380: 
10381: @table @emph
10382: @cindex class
10383: @item class
10384: a data structure definition with some extras.
10385: 
10386: @cindex object
10387: @item object
10388: an instance of the data structure described by the class definition.
10389: 
10390: @cindex instance variables
10391: @item instance variables
10392: fields of the data structure.
10393: 
10394: @cindex selector
10395: @cindex method selector
10396: @cindex virtual function
10397: @item selector
10398: (or @emph{method selector}) a word (e.g.,
10399: @code{draw}) that performs an operation on a variety of data
10400: structures (classes). A selector describes @emph{what} operation to
10401: perform. In C++ terminology: a (pure) virtual function.
10402: 
10403: @cindex method
10404: @item method
10405: the concrete definition that performs the operation
10406: described by the selector for a specific class. A method specifies
10407: @emph{how} the operation is performed for a specific class.
10408: 
10409: @cindex selector invocation
10410: @cindex message send
10411: @cindex invoking a selector
10412: @item selector invocation
10413: a call of a selector. One argument of the call (the TOS (top-of-stack))
10414: is used for determining which method is used. In Smalltalk terminology:
10415: a message (consisting of the selector and the other arguments) is sent
10416: to the object.
10417: 
10418: @cindex receiving object
10419: @item receiving object
10420: the object used for determining the method executed by a selector
10421: invocation. In the @file{objects.fs} model, it is the object that is on
10422: the TOS when the selector is invoked. (@emph{Receiving} comes from
10423: the Smalltalk @emph{message} terminology.)
10424: 
10425: @cindex child class
10426: @cindex parent class
10427: @cindex inheritance
10428: @item child class
10429: a class that has (@emph{inherits}) all properties (instance variables,
10430: selectors, methods) from a @emph{parent class}. In Smalltalk
10431: terminology: The subclass inherits from the superclass. In C++
10432: terminology: The derived class inherits from the base class.
10433: 
10434: @end table
10435: 
10436: @c If you wonder about the message sending terminology, it comes from
10437: @c a time when each object had it's own task and objects communicated via
10438: @c message passing; eventually the Smalltalk developers realized that
10439: @c they can do most things through simple (indirect) calls. They kept the
10440: @c terminology.
10441: 
10442: @c --------------------------------------------------------------
10443: @node Objects, OOF, Object-Oriented Terminology, Object-oriented Forth
10444: @subsection The @file{objects.fs} model
10445: @cindex objects
10446: @cindex object-oriented programming
10447: 
10448: @cindex @file{objects.fs}
10449: @cindex @file{oof.fs}
10450: 
10451: This section describes the @file{objects.fs} package. This material also
10452: has been published in M. Anton Ertl,
10453: @cite{@uref{http://www.complang.tuwien.ac.at/forth/objects/objects.html,
10454: Yet Another Forth Objects Package}}, Forth Dimensions 19(2), pages
10455: 37--43.
10456: @c McKewan's and Zsoter's packages
10457: 
10458: This section assumes that you have read @ref{Structures}.
10459: 
10460: The techniques on which this model is based have been used to implement
10461: the parser generator, Gray, and have also been used in Gforth for
10462: implementing the various flavours of word lists (hashed or not,
10463: case-sensitive or not, special-purpose word lists for locals etc.).
10464: 
10465: 
10466: @menu
10467: * Properties of the Objects model::  
10468: * Basic Objects Usage::         
10469: * The Objects base class::      
10470: * Creating objects::            
10471: * Object-Oriented Programming Style::  
10472: * Class Binding::               
10473: * Method conveniences::         
10474: * Classes and Scoping::         
10475: * Dividing classes::            
10476: * Object Interfaces::           
10477: * Objects Implementation::      
10478: * Objects Glossary::            
10479: @end menu
10480: 
10481: Marcel Hendrix provided helpful comments on this section.
10482: 
10483: @node Properties of the Objects model, Basic Objects Usage, Objects, Objects
10484: @subsubsection Properties of the @file{objects.fs} model
10485: @cindex @file{objects.fs} properties
10486: 
10487: @itemize @bullet
10488: @item
10489: It is straightforward to pass objects on the stack. Passing
10490: selectors on the stack is a little less convenient, but possible.
10491: 
10492: @item
10493: Objects are just data structures in memory, and are referenced by their
10494: address. You can create words for objects with normal defining words
10495: like @code{constant}. Likewise, there is no difference between instance
10496: variables that contain objects and those that contain other data.
10497: 
10498: @item
10499: Late binding is efficient and easy to use.
10500: 
10501: @item
10502: It avoids parsing, and thus avoids problems with state-smartness
10503: and reduced extensibility; for convenience there are a few parsing
10504: words, but they have non-parsing counterparts. There are also a few
10505: defining words that parse. This is hard to avoid, because all standard
10506: defining words parse (except @code{:noname}); however, such
10507: words are not as bad as many other parsing words, because they are not
10508: state-smart.
10509: 
10510: @item
10511: It does not try to incorporate everything. It does a few things and does
10512: them well (IMO). In particular, this model was not designed to support
10513: information hiding (although it has features that may help); you can use
10514: a separate package for achieving this.
10515: 
10516: @item
10517: It is layered; you don't have to learn and use all features to use this
10518: model. Only a few features are necessary (@pxref{Basic Objects Usage},
10519: @pxref{The Objects base class}, @pxref{Creating objects}.), the others
10520: are optional and independent of each other.
10521: 
10522: @item
10523: An implementation in ANS Forth is available.
10524: 
10525: @end itemize
10526: 
10527: 
10528: @node Basic Objects Usage, The Objects base class, Properties of the Objects model, Objects
10529: @subsubsection Basic @file{objects.fs} Usage
10530: @cindex basic objects usage
10531: @cindex objects, basic usage
10532: 
10533: You can define a class for graphical objects like this:
10534: 
10535: @cindex @code{class} usage
10536: @cindex @code{end-class} usage
10537: @cindex @code{selector} usage
10538: @example
10539: object class \ "object" is the parent class
10540:   selector draw ( x y graphical -- )
10541: end-class graphical
10542: @end example
10543: 
10544: This code defines a class @code{graphical} with an
10545: operation @code{draw}.  We can perform the operation
10546: @code{draw} on any @code{graphical} object, e.g.:
10547: 
10548: @example
10549: 100 100 t-rex draw
10550: @end example
10551: 
10552: @noindent
10553: where @code{t-rex} is a word (say, a constant) that produces a
10554: graphical object.
10555: 
10556: @comment TODO add a 2nd operation eg perimeter.. and use for
10557: @comment a concrete example
10558: 
10559: @cindex abstract class
10560: How do we create a graphical object? With the present definitions,
10561: we cannot create a useful graphical object. The class
10562: @code{graphical} describes graphical objects in general, but not
10563: any concrete graphical object type (C++ users would call it an
10564: @emph{abstract class}); e.g., there is no method for the selector
10565: @code{draw} in the class @code{graphical}.
10566: 
10567: For concrete graphical objects, we define child classes of the
10568: class @code{graphical}, e.g.:
10569: 
10570: @cindex @code{overrides} usage
10571: @cindex @code{field} usage in class definition
10572: @example
10573: graphical class \ "graphical" is the parent class
10574:   cell% field circle-radius
10575: 
10576: :noname ( x y circle -- )
10577:   circle-radius @@ draw-circle ;
10578: overrides draw
10579: 
10580: :noname ( n-radius circle -- )
10581:   circle-radius ! ;
10582: overrides construct
10583: 
10584: end-class circle
10585: @end example
10586: 
10587: Here we define a class @code{circle} as a child of @code{graphical},
10588: with field @code{circle-radius} (which behaves just like a field
10589: (@pxref{Structures}); it defines (using @code{overrides}) new methods
10590: for the selectors @code{draw} and @code{construct} (@code{construct} is
10591: defined in @code{object}, the parent class of @code{graphical}).
10592: 
10593: Now we can create a circle on the heap (i.e.,
10594: @code{allocate}d memory) with:
10595: 
10596: @cindex @code{heap-new} usage
10597: @example
10598: 50 circle heap-new constant my-circle
10599: @end example
10600: 
10601: @noindent
10602: @code{heap-new} invokes @code{construct}, thus
10603: initializing the field @code{circle-radius} with 50. We can draw
10604: this new circle at (100,100) with:
10605: 
10606: @example
10607: 100 100 my-circle draw
10608: @end example
10609: 
10610: @cindex selector invocation, restrictions
10611: @cindex class definition, restrictions
10612: Note: You can only invoke a selector if the object on the TOS
10613: (the receiving object) belongs to the class where the selector was
10614: defined or one of its descendents; e.g., you can invoke
10615: @code{draw} only for objects belonging to @code{graphical}
10616: or its descendents (e.g., @code{circle}).  Immediately before
10617: @code{end-class}, the search order has to be the same as
10618: immediately after @code{class}.
10619: 
10620: @node The Objects base class, Creating objects, Basic Objects Usage, Objects
10621: @subsubsection The @file{object.fs} base class
10622: @cindex @code{object} class
10623: 
10624: When you define a class, you have to specify a parent class.  So how do
10625: you start defining classes? There is one class available from the start:
10626: @code{object}. It is ancestor for all classes and so is the
10627: only class that has no parent. It has two selectors: @code{construct}
10628: and @code{print}.
10629: 
10630: @node Creating objects, Object-Oriented Programming Style, The Objects base class, Objects
10631: @subsubsection Creating objects
10632: @cindex creating objects
10633: @cindex object creation
10634: @cindex object allocation options
10635: 
10636: @cindex @code{heap-new} discussion
10637: @cindex @code{dict-new} discussion
10638: @cindex @code{construct} discussion
10639: You can create and initialize an object of a class on the heap with
10640: @code{heap-new} ( ... class -- object ) and in the dictionary
10641: (allocation with @code{allot}) with @code{dict-new} (
10642: ... class -- object ). Both words invoke @code{construct}, which
10643: consumes the stack items indicated by "..." above.
10644: 
10645: @cindex @code{init-object} discussion
10646: @cindex @code{class-inst-size} discussion
10647: If you want to allocate memory for an object yourself, you can get its
10648: alignment and size with @code{class-inst-size 2@@} ( class --
10649: align size ). Once you have memory for an object, you can initialize
10650: it with @code{init-object} ( ... class object -- );
10651: @code{construct} does only a part of the necessary work.
10652: 
10653: @node Object-Oriented Programming Style, Class Binding, Creating objects, Objects
10654: @subsubsection Object-Oriented Programming Style
10655: @cindex object-oriented programming style
10656: @cindex programming style, object-oriented
10657: 
10658: This section is not exhaustive.
10659: 
10660: @cindex stack effects of selectors
10661: @cindex selectors and stack effects
10662: In general, it is a good idea to ensure that all methods for the
10663: same selector have the same stack effect: when you invoke a selector,
10664: you often have no idea which method will be invoked, so, unless all
10665: methods have the same stack effect, you will not know the stack effect
10666: of the selector invocation.
10667: 
10668: One exception to this rule is methods for the selector
10669: @code{construct}. We know which method is invoked, because we
10670: specify the class to be constructed at the same place. Actually, I
10671: defined @code{construct} as a selector only to give the users a
10672: convenient way to specify initialization. The way it is used, a
10673: mechanism different from selector invocation would be more natural
10674: (but probably would take more code and more space to explain).
10675: 
10676: @node Class Binding, Method conveniences, Object-Oriented Programming Style, Objects
10677: @subsubsection Class Binding
10678: @cindex class binding
10679: @cindex early binding
10680: 
10681: @cindex late binding
10682: Normal selector invocations determine the method at run-time depending
10683: on the class of the receiving object. This run-time selection is called
10684: @i{late binding}.
10685: 
10686: Sometimes it's preferable to invoke a different method. For example,
10687: you might want to use the simple method for @code{print}ing
10688: @code{object}s instead of the possibly long-winded @code{print} method
10689: of the receiver class. You can achieve this by replacing the invocation
10690: of @code{print} with:
10691: 
10692: @cindex @code{[bind]} usage
10693: @example
10694: [bind] object print
10695: @end example
10696: 
10697: @noindent
10698: in compiled code or:
10699: 
10700: @cindex @code{bind} usage
10701: @example
10702: bind object print
10703: @end example
10704: 
10705: @cindex class binding, alternative to
10706: @noindent
10707: in interpreted code. Alternatively, you can define the method with a
10708: name (e.g., @code{print-object}), and then invoke it through the
10709: name. Class binding is just a (often more convenient) way to achieve
10710: the same effect; it avoids name clutter and allows you to invoke
10711: methods directly without naming them first.
10712: 
10713: @cindex superclass binding
10714: @cindex parent class binding
10715: A frequent use of class binding is this: When we define a method
10716: for a selector, we often want the method to do what the selector does
10717: in the parent class, and a little more. There is a special word for
10718: this purpose: @code{[parent]}; @code{[parent]
10719: @emph{selector}} is equivalent to @code{[bind] @emph{parent
10720: selector}}, where @code{@emph{parent}} is the parent
10721: class of the current class. E.g., a method definition might look like:
10722: 
10723: @cindex @code{[parent]} usage
10724: @example
10725: :noname
10726:   dup [parent] foo \ do parent's foo on the receiving object
10727:   ... \ do some more
10728: ; overrides foo
10729: @end example
10730: 
10731: @cindex class binding as optimization
10732: In @cite{Object-oriented programming in ANS Forth} (Forth Dimensions,
10733: March 1997), Andrew McKewan presents class binding as an optimization
10734: technique. I recommend not using it for this purpose unless you are in
10735: an emergency. Late binding is pretty fast with this model anyway, so the
10736: benefit of using class binding is small; the cost of using class binding
10737: where it is not appropriate is reduced maintainability.
10738: 
10739: While we are at programming style questions: You should bind
10740: selectors only to ancestor classes of the receiving object. E.g., say,
10741: you know that the receiving object is of class @code{foo} or its
10742: descendents; then you should bind only to @code{foo} and its
10743: ancestors.
10744: 
10745: @node Method conveniences, Classes and Scoping, Class Binding, Objects
10746: @subsubsection Method conveniences
10747: @cindex method conveniences
10748: 
10749: In a method you usually access the receiving object pretty often.  If
10750: you define the method as a plain colon definition (e.g., with
10751: @code{:noname}), you may have to do a lot of stack
10752: gymnastics. To avoid this, you can define the method with @code{m:
10753: ... ;m}. E.g., you could define the method for
10754: @code{draw}ing a @code{circle} with
10755: 
10756: @cindex @code{this} usage
10757: @cindex @code{m:} usage
10758: @cindex @code{;m} usage
10759: @example
10760: m: ( x y circle -- )
10761:   ( x y ) this circle-radius @@ draw-circle ;m
10762: @end example
10763: 
10764: @cindex @code{exit} in @code{m: ... ;m}
10765: @cindex @code{exitm} discussion
10766: @cindex @code{catch} in @code{m: ... ;m}
10767: When this method is executed, the receiver object is removed from the
10768: stack; you can access it with @code{this} (admittedly, in this
10769: example the use of @code{m: ... ;m} offers no advantage). Note
10770: that I specify the stack effect for the whole method (i.e. including
10771: the receiver object), not just for the code between @code{m:}
10772: and @code{;m}. You cannot use @code{exit} in
10773: @code{m:...;m}; instead, use
10774: @code{exitm}.@footnote{Moreover, for any word that calls
10775: @code{catch} and was defined before loading
10776: @code{objects.fs}, you have to redefine it like I redefined
10777: @code{catch}: @code{: catch this >r catch r> to-this ;}}
10778: 
10779: @cindex @code{inst-var} usage
10780: You will frequently use sequences of the form @code{this
10781: @emph{field}} (in the example above: @code{this
10782: circle-radius}). If you use the field only in this way, you can
10783: define it with @code{inst-var} and eliminate the
10784: @code{this} before the field name. E.g., the @code{circle}
10785: class above could also be defined with:
10786: 
10787: @example
10788: graphical class
10789:   cell% inst-var radius
10790: 
10791: m: ( x y circle -- )
10792:   radius @@ draw-circle ;m
10793: overrides draw
10794: 
10795: m: ( n-radius circle -- )
10796:   radius ! ;m
10797: overrides construct
10798: 
10799: end-class circle
10800: @end example
10801: 
10802: @code{radius} can only be used in @code{circle} and its
10803: descendent classes and inside @code{m:...;m}.
10804: 
10805: @cindex @code{inst-value} usage
10806: You can also define fields with @code{inst-value}, which is
10807: to @code{inst-var} what @code{value} is to
10808: @code{variable}.  You can change the value of such a field with
10809: @code{[to-inst]}.  E.g., we could also define the class
10810: @code{circle} like this:
10811: 
10812: @example
10813: graphical class
10814:   inst-value radius
10815: 
10816: m: ( x y circle -- )
10817:   radius draw-circle ;m
10818: overrides draw
10819: 
10820: m: ( n-radius circle -- )
10821:   [to-inst] radius ;m
10822: overrides construct
10823: 
10824: end-class circle
10825: @end example
10826: 
10827: @c !! :m is easy to confuse with m:.  Another name would be better.
10828: 
10829: @c Finally, you can define named methods with @code{:m}.  One use of this
10830: @c feature is the definition of words that occur only in one class and are
10831: @c not intended to be overridden, but which still need method context
10832: @c (e.g., for accessing @code{inst-var}s).  Another use is for methods that
10833: @c would be bound frequently, if defined anonymously.
10834: 
10835: 
10836: @node Classes and Scoping, Dividing classes, Method conveniences, Objects
10837: @subsubsection Classes and Scoping
10838: @cindex classes and scoping
10839: @cindex scoping and classes
10840: 
10841: Inheritance is frequent, unlike structure extension. This exacerbates
10842: the problem with the field name convention (@pxref{Structure Naming
10843: Convention}): One always has to remember in which class the field was
10844: originally defined; changing a part of the class structure would require
10845: changes for renaming in otherwise unaffected code.
10846: 
10847: @cindex @code{inst-var} visibility
10848: @cindex @code{inst-value} visibility
10849: To solve this problem, I added a scoping mechanism (which was not in my
10850: original charter): A field defined with @code{inst-var} (or
10851: @code{inst-value}) is visible only in the class where it is defined and in
10852: the descendent classes of this class.  Using such fields only makes
10853: sense in @code{m:}-defined methods in these classes anyway.
10854: 
10855: This scoping mechanism allows us to use the unadorned field name,
10856: because name clashes with unrelated words become much less likely.
10857: 
10858: @cindex @code{protected} discussion
10859: @cindex @code{private} discussion
10860: Once we have this mechanism, we can also use it for controlling the
10861: visibility of other words: All words defined after
10862: @code{protected} are visible only in the current class and its
10863: descendents. @code{public} restores the compilation
10864: (i.e. @code{current}) word list that was in effect before. If you
10865: have several @code{protected}s without an intervening
10866: @code{public} or @code{set-current}, @code{public}
10867: will restore the compilation word list in effect before the first of
10868: these @code{protected}s.
10869: 
10870: @node Dividing classes, Object Interfaces, Classes and Scoping, Objects
10871: @subsubsection Dividing classes
10872: @cindex Dividing classes
10873: @cindex @code{methods}...@code{end-methods}
10874: 
10875: You may want to do the definition of methods separate from the
10876: definition of the class, its selectors, fields, and instance variables,
10877: i.e., separate the implementation from the definition.  You can do this
10878: in the following way:
10879: 
10880: @example
10881: graphical class
10882:   inst-value radius
10883: end-class circle
10884: 
10885: ... \ do some other stuff
10886: 
10887: circle methods \ now we are ready
10888: 
10889: m: ( x y circle -- )
10890:   radius draw-circle ;m
10891: overrides draw
10892: 
10893: m: ( n-radius circle -- )
10894:   [to-inst] radius ;m
10895: overrides construct
10896: 
10897: end-methods
10898: @end example
10899: 
10900: You can use several @code{methods}...@code{end-methods} sections.  The
10901: only things you can do to the class in these sections are: defining
10902: methods, and overriding the class's selectors.  You must not define new
10903: selectors or fields.
10904: 
10905: Note that you often have to override a selector before using it.  In
10906: particular, you usually have to override @code{construct} with a new
10907: method before you can invoke @code{heap-new} and friends.  E.g., you
10908: must not create a circle before the @code{overrides construct} sequence
10909: in the example above.
10910: 
10911: @node Object Interfaces, Objects Implementation, Dividing classes, Objects
10912: @subsubsection Object Interfaces
10913: @cindex object interfaces
10914: @cindex interfaces for objects
10915: 
10916: In this model you can only call selectors defined in the class of the
10917: receiving objects or in one of its ancestors. If you call a selector
10918: with a receiving object that is not in one of these classes, the
10919: result is undefined; if you are lucky, the program crashes
10920: immediately.
10921: 
10922: @cindex selectors common to hardly-related classes
10923: Now consider the case when you want to have a selector (or several)
10924: available in two classes: You would have to add the selector to a
10925: common ancestor class, in the worst case to @code{object}. You
10926: may not want to do this, e.g., because someone else is responsible for
10927: this ancestor class.
10928: 
10929: The solution for this problem is interfaces. An interface is a
10930: collection of selectors. If a class implements an interface, the
10931: selectors become available to the class and its descendents. A class
10932: can implement an unlimited number of interfaces. For the problem
10933: discussed above, we would define an interface for the selector(s), and
10934: both classes would implement the interface.
10935: 
10936: As an example, consider an interface @code{storage} for
10937: writing objects to disk and getting them back, and a class
10938: @code{foo} that implements it. The code would look like this:
10939: 
10940: @cindex @code{interface} usage
10941: @cindex @code{end-interface} usage
10942: @cindex @code{implementation} usage
10943: @example
10944: interface
10945:   selector write ( file object -- )
10946:   selector read1 ( file object -- )
10947: end-interface storage
10948: 
10949: bar class
10950:   storage implementation
10951: 
10952: ... overrides write
10953: ... overrides read1
10954: ...
10955: end-class foo
10956: @end example
10957: 
10958: @noindent
10959: (I would add a word @code{read} @i{( file -- object )} that uses
10960: @code{read1} internally, but that's beyond the point illustrated
10961: here.)
10962: 
10963: Note that you cannot use @code{protected} in an interface; and
10964: of course you cannot define fields.
10965: 
10966: In the Neon model, all selectors are available for all classes;
10967: therefore it does not need interfaces. The price you pay in this model
10968: is slower late binding, and therefore, added complexity to avoid late
10969: binding.
10970: 
10971: @node Objects Implementation, Objects Glossary, Object Interfaces, Objects
10972: @subsubsection @file{objects.fs} Implementation
10973: @cindex @file{objects.fs} implementation
10974: 
10975: @cindex @code{object-map} discussion
10976: An object is a piece of memory, like one of the data structures
10977: described with @code{struct...end-struct}. It has a field
10978: @code{object-map} that points to the method map for the object's
10979: class.
10980: 
10981: @cindex method map
10982: @cindex virtual function table
10983: The @emph{method map}@footnote{This is Self terminology; in C++
10984: terminology: virtual function table.} is an array that contains the
10985: execution tokens (@i{xt}s) of the methods for the object's class. Each
10986: selector contains an offset into a method map.
10987: 
10988: @cindex @code{selector} implementation, class
10989: @code{selector} is a defining word that uses
10990: @code{CREATE} and @code{DOES>}. The body of the
10991: selector contains the offset; the @code{DOES>} action for a
10992: class selector is, basically:
10993: 
10994: @example
10995: ( object addr ) @@ over object-map @@ + @@ execute
10996: @end example
10997: 
10998: Since @code{object-map} is the first field of the object, it
10999: does not generate any code. As you can see, calling a selector has a
11000: small, constant cost.
11001: 
11002: @cindex @code{current-interface} discussion
11003: @cindex class implementation and representation
11004: A class is basically a @code{struct} combined with a method
11005: map. During the class definition the alignment and size of the class
11006: are passed on the stack, just as with @code{struct}s, so
11007: @code{field} can also be used for defining class
11008: fields. However, passing more items on the stack would be
11009: inconvenient, so @code{class} builds a data structure in memory,
11010: which is accessed through the variable
11011: @code{current-interface}. After its definition is complete, the
11012: class is represented on the stack by a pointer (e.g., as parameter for
11013: a child class definition).
11014: 
11015: A new class starts off with the alignment and size of its parent,
11016: and a copy of the parent's method map. Defining new fields extends the
11017: size and alignment; likewise, defining new selectors extends the
11018: method map. @code{overrides} just stores a new @i{xt} in the method
11019: map at the offset given by the selector.
11020: 
11021: @cindex class binding, implementation
11022: Class binding just gets the @i{xt} at the offset given by the selector
11023: from the class's method map and @code{compile,}s (in the case of
11024: @code{[bind]}) it.
11025: 
11026: @cindex @code{this} implementation
11027: @cindex @code{catch} and @code{this}
11028: @cindex @code{this} and @code{catch}
11029: I implemented @code{this} as a @code{value}. At the
11030: start of an @code{m:...;m} method the old @code{this} is
11031: stored to the return stack and restored at the end; and the object on
11032: the TOS is stored @code{TO this}. This technique has one
11033: disadvantage: If the user does not leave the method via
11034: @code{;m}, but via @code{throw} or @code{exit},
11035: @code{this} is not restored (and @code{exit} may
11036: crash). To deal with the @code{throw} problem, I have redefined
11037: @code{catch} to save and restore @code{this}; the same
11038: should be done with any word that can catch an exception. As for
11039: @code{exit}, I simply forbid it (as a replacement, there is
11040: @code{exitm}).
11041: 
11042: @cindex @code{inst-var} implementation
11043: @code{inst-var} is just the same as @code{field}, with
11044: a different @code{DOES>} action:
11045: @example
11046: @@ this +
11047: @end example
11048: Similar for @code{inst-value}.
11049: 
11050: @cindex class scoping implementation
11051: Each class also has a word list that contains the words defined with
11052: @code{inst-var} and @code{inst-value}, and its protected
11053: words. It also has a pointer to its parent. @code{class} pushes
11054: the word lists of the class and all its ancestors onto the search order stack,
11055: and @code{end-class} drops them.
11056: 
11057: @cindex interface implementation
11058: An interface is like a class without fields, parent and protected
11059: words; i.e., it just has a method map. If a class implements an
11060: interface, its method map contains a pointer to the method map of the
11061: interface. The positive offsets in the map are reserved for class
11062: methods, therefore interface map pointers have negative
11063: offsets. Interfaces have offsets that are unique throughout the
11064: system, unlike class selectors, whose offsets are only unique for the
11065: classes where the selector is available (invokable).
11066: 
11067: This structure means that interface selectors have to perform one
11068: indirection more than class selectors to find their method. Their body
11069: contains the interface map pointer offset in the class method map, and
11070: the method offset in the interface method map. The
11071: @code{does>} action for an interface selector is, basically:
11072: 
11073: @example
11074: ( object selector-body )
11075: 2dup selector-interface @@ ( object selector-body object interface-offset )
11076: swap object-map @@ + @@ ( object selector-body map )
11077: swap selector-offset @@ + @@ execute
11078: @end example
11079: 
11080: where @code{object-map} and @code{selector-offset} are
11081: first fields and generate no code.
11082: 
11083: As a concrete example, consider the following code:
11084: 
11085: @example
11086: interface
11087:   selector if1sel1
11088:   selector if1sel2
11089: end-interface if1
11090: 
11091: object class
11092:   if1 implementation
11093:   selector cl1sel1
11094:   cell% inst-var cl1iv1
11095: 
11096: ' m1 overrides construct
11097: ' m2 overrides if1sel1
11098: ' m3 overrides if1sel2
11099: ' m4 overrides cl1sel2
11100: end-class cl1
11101: 
11102: create obj1 object dict-new drop
11103: create obj2 cl1    dict-new drop
11104: @end example
11105: 
11106: The data structure created by this code (including the data structure
11107: for @code{object}) is shown in the
11108: @uref{objects-implementation.eps,figure}, assuming a cell size of 4.
11109: @comment TODO add this diagram..
11110: 
11111: @node Objects Glossary,  , Objects Implementation, Objects
11112: @subsubsection @file{objects.fs} Glossary
11113: @cindex @file{objects.fs} Glossary
11114: 
11115: 
11116: doc---objects-bind
11117: doc---objects-<bind>
11118: doc---objects-bind'
11119: doc---objects-[bind]
11120: doc---objects-class
11121: doc---objects-class->map
11122: doc---objects-class-inst-size
11123: doc---objects-class-override!
11124: doc---objects-class-previous
11125: doc---objects-class>order
11126: doc---objects-construct
11127: doc---objects-current'
11128: doc---objects-[current]
11129: doc---objects-current-interface
11130: doc---objects-dict-new
11131: doc---objects-end-class
11132: doc---objects-end-class-noname
11133: doc---objects-end-interface
11134: doc---objects-end-interface-noname
11135: doc---objects-end-methods
11136: doc---objects-exitm
11137: doc---objects-heap-new
11138: doc---objects-implementation
11139: doc---objects-init-object
11140: doc---objects-inst-value
11141: doc---objects-inst-var
11142: doc---objects-interface
11143: doc---objects-m:
11144: doc---objects-:m
11145: doc---objects-;m
11146: doc---objects-method
11147: doc---objects-methods
11148: doc---objects-object
11149: doc---objects-overrides
11150: doc---objects-[parent]
11151: doc---objects-print
11152: doc---objects-protected
11153: doc---objects-public
11154: doc---objects-selector
11155: doc---objects-this
11156: doc---objects-<to-inst>
11157: doc---objects-[to-inst]
11158: doc---objects-to-this
11159: doc---objects-xt-new
11160: 
11161: 
11162: @c -------------------------------------------------------------
11163: @node OOF, Mini-OOF, Objects, Object-oriented Forth
11164: @subsection The @file{oof.fs} model
11165: @cindex oof
11166: @cindex object-oriented programming
11167: 
11168: @cindex @file{objects.fs}
11169: @cindex @file{oof.fs}
11170: 
11171: This section describes the @file{oof.fs} package.
11172: 
11173: The package described in this section has been used in bigFORTH since 1991, and
11174: used for two large applications: a chromatographic system used to
11175: create new medicaments, and a graphic user interface library (MINOS).
11176: 
11177: You can find a description (in German) of @file{oof.fs} in @cite{Object
11178: oriented bigFORTH} by Bernd Paysan, published in @cite{Vierte Dimension}
11179: 10(2), 1994.
11180: 
11181: @menu
11182: * Properties of the OOF model::  
11183: * Basic OOF Usage::             
11184: * The OOF base class::          
11185: * Class Declaration::           
11186: * Class Implementation::        
11187: @end menu
11188: 
11189: @node Properties of the OOF model, Basic OOF Usage, OOF, OOF
11190: @subsubsection Properties of the @file{oof.fs} model
11191: @cindex @file{oof.fs} properties
11192: 
11193: @itemize @bullet
11194: @item
11195: This model combines object oriented programming with information
11196: hiding. It helps you writing large application, where scoping is
11197: necessary, because it provides class-oriented scoping.
11198: 
11199: @item
11200: Named objects, object pointers, and object arrays can be created,
11201: selector invocation uses the ``object selector'' syntax. Selector invocation
11202: to objects and/or selectors on the stack is a bit less convenient, but
11203: possible.
11204: 
11205: @item
11206: Selector invocation and instance variable usage of the active object is
11207: straightforward, since both make use of the active object.
11208: 
11209: @item
11210: Late binding is efficient and easy to use.
11211: 
11212: @item
11213: State-smart objects parse selectors. However, extensibility is provided
11214: using a (parsing) selector @code{postpone} and a selector @code{'}.
11215: 
11216: @item
11217: An implementation in ANS Forth is available.
11218: 
11219: @end itemize
11220: 
11221: 
11222: @node Basic OOF Usage, The OOF base class, Properties of the OOF model, OOF
11223: @subsubsection Basic @file{oof.fs} Usage
11224: @cindex @file{oof.fs} usage
11225: 
11226: This section uses the same example as for @code{objects} (@pxref{Basic Objects Usage}).
11227: 
11228: You can define a class for graphical objects like this:
11229: 
11230: @cindex @code{class} usage
11231: @cindex @code{class;} usage
11232: @cindex @code{method} usage
11233: @example
11234: object class graphical \ "object" is the parent class
11235:   method draw ( x y -- )
11236: class;
11237: @end example
11238: 
11239: This code defines a class @code{graphical} with an
11240: operation @code{draw}.  We can perform the operation
11241: @code{draw} on any @code{graphical} object, e.g.:
11242: 
11243: @example
11244: 100 100 t-rex draw
11245: @end example
11246: 
11247: @noindent
11248: where @code{t-rex} is an object or object pointer, created with e.g.
11249: @code{graphical : t-rex}.
11250: 
11251: @cindex abstract class
11252: How do we create a graphical object? With the present definitions,
11253: we cannot create a useful graphical object. The class
11254: @code{graphical} describes graphical objects in general, but not
11255: any concrete graphical object type (C++ users would call it an
11256: @emph{abstract class}); e.g., there is no method for the selector
11257: @code{draw} in the class @code{graphical}.
11258: 
11259: For concrete graphical objects, we define child classes of the
11260: class @code{graphical}, e.g.:
11261: 
11262: @example
11263: graphical class circle \ "graphical" is the parent class
11264:   cell var circle-radius
11265: how:
11266:   : draw ( x y -- )
11267:     circle-radius @@ draw-circle ;
11268: 
11269:   : init ( n-radius -- )
11270:     circle-radius ! ;
11271: class;
11272: @end example
11273: 
11274: Here we define a class @code{circle} as a child of @code{graphical},
11275: with a field @code{circle-radius}; it defines new methods for the
11276: selectors @code{draw} and @code{init} (@code{init} is defined in
11277: @code{object}, the parent class of @code{graphical}).
11278: 
11279: Now we can create a circle in the dictionary with:
11280: 
11281: @example
11282: 50 circle : my-circle
11283: @end example
11284: 
11285: @noindent
11286: @code{:} invokes @code{init}, thus initializing the field
11287: @code{circle-radius} with 50. We can draw this new circle at (100,100)
11288: with:
11289: 
11290: @example
11291: 100 100 my-circle draw
11292: @end example
11293: 
11294: @cindex selector invocation, restrictions
11295: @cindex class definition, restrictions
11296: Note: You can only invoke a selector if the receiving object belongs to
11297: the class where the selector was defined or one of its descendents;
11298: e.g., you can invoke @code{draw} only for objects belonging to
11299: @code{graphical} or its descendents (e.g., @code{circle}). The scoping
11300: mechanism will check if you try to invoke a selector that is not
11301: defined in this class hierarchy, so you'll get an error at compilation
11302: time.
11303: 
11304: 
11305: @node The OOF base class, Class Declaration, Basic OOF Usage, OOF
11306: @subsubsection The @file{oof.fs} base class
11307: @cindex @file{oof.fs} base class
11308: 
11309: When you define a class, you have to specify a parent class.  So how do
11310: you start defining classes? There is one class available from the start:
11311: @code{object}. You have to use it as ancestor for all classes. It is the
11312: only class that has no parent. Classes are also objects, except that
11313: they don't have instance variables; class manipulation such as
11314: inheritance or changing definitions of a class is handled through
11315: selectors of the class @code{object}.
11316: 
11317: @code{object} provides a number of selectors:
11318: 
11319: @itemize @bullet
11320: @item
11321: @code{class} for subclassing, @code{definitions} to add definitions
11322: later on, and @code{class?} to get type informations (is the class a
11323: subclass of the class passed on the stack?).
11324: 
11325: doc---object-class
11326: doc---object-definitions
11327: doc---object-class?
11328: 
11329: 
11330: @item
11331: @code{init} and @code{dispose} as constructor and destructor of the
11332: object. @code{init} is invocated after the object's memory is allocated,
11333: while @code{dispose} also handles deallocation. Thus if you redefine
11334: @code{dispose}, you have to call the parent's dispose with @code{super
11335: dispose}, too.
11336: 
11337: doc---object-init
11338: doc---object-dispose
11339: 
11340: 
11341: @item
11342: @code{new}, @code{new[]}, @code{:}, @code{ptr}, @code{asptr}, and
11343: @code{[]} to create named and unnamed objects and object arrays or
11344: object pointers.
11345: 
11346: doc---object-new
11347: doc---object-new[]
11348: doc---object-:
11349: doc---object-ptr
11350: doc---object-asptr
11351: doc---object-[]
11352: 
11353: 
11354: @item
11355: @code{::} and @code{super} for explicit scoping. You should use explicit
11356: scoping only for super classes or classes with the same set of instance
11357: variables. Explicitly-scoped selectors use early binding.
11358: 
11359: doc---object-::
11360: doc---object-super
11361: 
11362: 
11363: @item
11364: @code{self} to get the address of the object
11365: 
11366: doc---object-self
11367: 
11368: 
11369: @item
11370: @code{bind}, @code{bound}, @code{link}, and @code{is} to assign object
11371: pointers and instance defers.
11372: 
11373: doc---object-bind
11374: doc---object-bound
11375: doc---object-link
11376: doc---object-is
11377: 
11378: 
11379: @item
11380: @code{'} to obtain selector tokens, @code{send} to invocate selectors
11381: form the stack, and @code{postpone} to generate selector invocation code.
11382: 
11383: doc---object-'
11384: doc---object-postpone
11385: 
11386: 
11387: @item
11388: @code{with} and @code{endwith} to select the active object from the
11389: stack, and enable its scope. Using @code{with} and @code{endwith}
11390: also allows you to create code using selector @code{postpone} without being
11391: trapped by the state-smart objects.
11392: 
11393: doc---object-with
11394: doc---object-endwith
11395: 
11396: 
11397: @end itemize
11398: 
11399: @node Class Declaration, Class Implementation, The OOF base class, OOF
11400: @subsubsection Class Declaration
11401: @cindex class declaration
11402: 
11403: @itemize @bullet
11404: @item
11405: Instance variables
11406: 
11407: doc---oof-var
11408: 
11409: 
11410: @item
11411: Object pointers
11412: 
11413: doc---oof-ptr
11414: doc---oof-asptr
11415: 
11416: 
11417: @item
11418: Instance defers
11419: 
11420: doc---oof-defer
11421: 
11422: 
11423: @item
11424: Method selectors
11425: 
11426: doc---oof-early
11427: doc---oof-method
11428: 
11429: 
11430: @item
11431: Class-wide variables
11432: 
11433: doc---oof-static
11434: 
11435: 
11436: @item
11437: End declaration
11438: 
11439: doc---oof-how:
11440: doc---oof-class;
11441: 
11442: 
11443: @end itemize
11444: 
11445: @c -------------------------------------------------------------
11446: @node Class Implementation,  , Class Declaration, OOF
11447: @subsubsection Class Implementation
11448: @cindex class implementation
11449: 
11450: @c -------------------------------------------------------------
11451: @node Mini-OOF, Comparison with other object models, OOF, Object-oriented Forth
11452: @subsection The @file{mini-oof.fs} model
11453: @cindex mini-oof
11454: 
11455: Gforth's third object oriented Forth package is a 12-liner. It uses a
11456: mixture of the @file{objects.fs} and the @file{oof.fs} syntax,
11457: and reduces to the bare minimum of features. This is based on a posting
11458: of Bernd Paysan in comp.lang.forth.
11459: 
11460: @menu
11461: * Basic Mini-OOF Usage::        
11462: * Mini-OOF Example::            
11463: * Mini-OOF Implementation::     
11464: @end menu
11465: 
11466: @c -------------------------------------------------------------
11467: @node Basic Mini-OOF Usage, Mini-OOF Example, Mini-OOF, Mini-OOF
11468: @subsubsection Basic @file{mini-oof.fs} Usage
11469: @cindex mini-oof usage
11470: 
11471: There is a base class (@code{class}, which allocates one cell for the
11472: object pointer) plus seven other words: to define a method, a variable,
11473: a class; to end a class, to resolve binding, to allocate an object and
11474: to compile a class method.
11475: @comment TODO better description of the last one
11476: 
11477: 
11478: doc-object
11479: doc-method
11480: doc-var
11481: doc-class
11482: doc-end-class
11483: doc-defines
11484: doc-new
11485: doc-::
11486: 
11487: 
11488: 
11489: @c -------------------------------------------------------------
11490: @node Mini-OOF Example, Mini-OOF Implementation, Basic Mini-OOF Usage, Mini-OOF
11491: @subsubsection Mini-OOF Example
11492: @cindex mini-oof example
11493: 
11494: A short example shows how to use this package. This example, in slightly
11495: extended form, is supplied as @file{moof-exm.fs}
11496: @comment TODO could flesh this out with some comments from the Forthwrite article
11497: 
11498: @example
11499: object class
11500:   method init
11501:   method draw
11502: end-class graphical
11503: @end example
11504: 
11505: This code defines a class @code{graphical} with an
11506: operation @code{draw}.  We can perform the operation
11507: @code{draw} on any @code{graphical} object, e.g.:
11508: 
11509: @example
11510: 100 100 t-rex draw
11511: @end example
11512: 
11513: where @code{t-rex} is an object or object pointer, created with e.g.
11514: @code{graphical new Constant t-rex}.
11515: 
11516: For concrete graphical objects, we define child classes of the
11517: class @code{graphical}, e.g.:
11518: 
11519: @example
11520: graphical class
11521:   cell var circle-radius
11522: end-class circle \ "graphical" is the parent class
11523: 
11524: :noname ( x y -- )
11525:   circle-radius @@ draw-circle ; circle defines draw
11526: :noname ( r -- )
11527:   circle-radius ! ; circle defines init
11528: @end example
11529: 
11530: There is no implicit init method, so we have to define one. The creation
11531: code of the object now has to call init explicitely.
11532: 
11533: @example
11534: circle new Constant my-circle
11535: 50 my-circle init
11536: @end example
11537: 
11538: It is also possible to add a function to create named objects with
11539: automatic call of @code{init}, given that all objects have @code{init}
11540: on the same place:
11541: 
11542: @example
11543: : new: ( .. o "name" -- )
11544:     new dup Constant init ;
11545: 80 circle new: large-circle
11546: @end example
11547: 
11548: We can draw this new circle at (100,100) with:
11549: 
11550: @example
11551: 100 100 my-circle draw
11552: @end example
11553: 
11554: @node Mini-OOF Implementation,  , Mini-OOF Example, Mini-OOF
11555: @subsubsection @file{mini-oof.fs} Implementation
11556: 
11557: Object-oriented systems with late binding typically use a
11558: ``vtable''-approach: the first variable in each object is a pointer to a
11559: table, which contains the methods as function pointers. The vtable
11560: may also contain other information.
11561: 
11562: So first, let's declare selectors:
11563: 
11564: @example
11565: : method ( m v "name" -- m' v ) Create  over , swap cell+ swap
11566:   DOES> ( ... o -- ... ) @@ over @@ + @@ execute ;
11567: @end example
11568: 
11569: During selector declaration, the number of selectors and instance
11570: variables is on the stack (in address units). @code{method} creates one
11571: selector and increments the selector number. To execute a selector, it
11572: takes the object, fetches the vtable pointer, adds the offset, and
11573: executes the method @i{xt} stored there. Each selector takes the object
11574: it is invoked with as top of stack parameter; it passes the parameters
11575: (including the object) unchanged to the appropriate method which should
11576: consume that object.
11577: 
11578: Now, we also have to declare instance variables
11579: 
11580: @example
11581: : var ( m v size "name" -- m v' ) Create  over , +
11582:   DOES> ( o -- addr ) @@ + ;
11583: @end example
11584: 
11585: As before, a word is created with the current offset. Instance
11586: variables can have different sizes (cells, floats, doubles, chars), so
11587: all we do is take the size and add it to the offset. If your machine
11588: has alignment restrictions, put the proper @code{aligned} or
11589: @code{faligned} before the variable, to adjust the variable
11590: offset. That's why it is on the top of stack.
11591: 
11592: We need a starting point (the base object) and some syntactic sugar:
11593: 
11594: @example
11595: Create object  1 cells , 2 cells ,
11596: : class ( class -- class selectors vars ) dup 2@@ ;
11597: @end example
11598: 
11599: For inheritance, the vtable of the parent object has to be
11600: copied when a new, derived class is declared. This gives all the
11601: methods of the parent class, which can be overridden, though.
11602: 
11603: @example
11604: : end-class  ( class selectors vars "name" -- )
11605:   Create  here >r , dup , 2 cells ?DO ['] noop , 1 cells +LOOP
11606:   cell+ dup cell+ r> rot @@ 2 cells /string move ;
11607: @end example
11608: 
11609: The first line creates the vtable, initialized with
11610: @code{noop}s. The second line is the inheritance mechanism, it
11611: copies the xts from the parent vtable.
11612: 
11613: We still have no way to define new methods, let's do that now:
11614: 
11615: @example
11616: : defines ( xt class "name" -- ) ' >body @@ + ! ;
11617: @end example
11618: 
11619: To allocate a new object, we need a word, too:
11620: 
11621: @example
11622: : new ( class -- o )  here over @@ allot swap over ! ;
11623: @end example
11624: 
11625: Sometimes derived classes want to access the method of the
11626: parent object. There are two ways to achieve this with Mini-OOF:
11627: first, you could use named words, and second, you could look up the
11628: vtable of the parent object.
11629: 
11630: @example
11631: : :: ( class "name" -- ) ' >body @@ + @@ compile, ;
11632: @end example
11633: 
11634: 
11635: Nothing can be more confusing than a good example, so here is
11636: one. First let's declare a text object (called
11637: @code{button}), that stores text and position:
11638: 
11639: @example
11640: object class
11641:   cell var text
11642:   cell var len
11643:   cell var x
11644:   cell var y
11645:   method init
11646:   method draw
11647: end-class button
11648: @end example
11649: 
11650: @noindent
11651: Now, implement the two methods, @code{draw} and @code{init}:
11652: 
11653: @example
11654: :noname ( o -- )
11655:  >r r@@ x @@ r@@ y @@ at-xy  r@@ text @@ r> len @@ type ;
11656:  button defines draw
11657: :noname ( addr u o -- )
11658:  >r 0 r@@ x ! 0 r@@ y ! r@@ len ! r> text ! ;
11659:  button defines init
11660: @end example
11661: 
11662: @noindent
11663: To demonstrate inheritance, we define a class @code{bold-button}, with no
11664: new data and no new selectors:
11665: 
11666: @example
11667: button class
11668: end-class bold-button
11669: 
11670: : bold   27 emit ." [1m" ;
11671: : normal 27 emit ." [0m" ;
11672: @end example
11673: 
11674: @noindent
11675: The class @code{bold-button} has a different draw method to
11676: @code{button}, but the new method is defined in terms of the draw method
11677: for @code{button}:
11678: 
11679: @example
11680: :noname bold [ button :: draw ] normal ; bold-button defines draw
11681: @end example
11682: 
11683: @noindent
11684: Finally, create two objects and apply selectors:
11685: 
11686: @example
11687: button new Constant foo
11688: s" thin foo" foo init
11689: page
11690: foo draw
11691: bold-button new Constant bar
11692: s" fat bar" bar init
11693: 1 bar y !
11694: bar draw
11695: @end example
11696: 
11697: 
11698: @node Comparison with other object models,  , Mini-OOF, Object-oriented Forth
11699: @subsection Comparison with other object models
11700: @cindex comparison of object models
11701: @cindex object models, comparison
11702: 
11703: Many object-oriented Forth extensions have been proposed (@cite{A survey
11704: of object-oriented Forths} (SIGPLAN Notices, April 1996) by Bradford
11705: J. Rodriguez and W. F. S. Poehlman lists 17). This section discusses the
11706: relation of the object models described here to two well-known and two
11707: closely-related (by the use of method maps) models.  Andras Zsoter
11708: helped us with this section.
11709: 
11710: @cindex Neon model
11711: The most popular model currently seems to be the Neon model (see
11712: @cite{Object-oriented programming in ANS Forth} (Forth Dimensions, March
11713: 1997) by Andrew McKewan) but this model has a number of limitations
11714: @footnote{A longer version of this critique can be
11715: found in @cite{On Standardizing Object-Oriented Forth Extensions} (Forth
11716: Dimensions, May 1997) by Anton Ertl.}:
11717: 
11718: @itemize @bullet
11719: @item
11720: It uses a @code{@emph{selector object}} syntax, which makes it unnatural
11721: to pass objects on the stack.
11722: 
11723: @item
11724: It requires that the selector parses the input stream (at
11725: compile time); this leads to reduced extensibility and to bugs that are
11726: hard to find.
11727: 
11728: @item
11729: It allows using every selector on every object; this eliminates the
11730: need for interfaces, but makes it harder to create efficient
11731: implementations.
11732: @end itemize
11733: 
11734: @cindex Pountain's object-oriented model
11735: Another well-known publication is @cite{Object-Oriented Forth} (Academic
11736: Press, London, 1987) by Dick Pountain. However, it is not really about
11737: object-oriented programming, because it hardly deals with late
11738: binding. Instead, it focuses on features like information hiding and
11739: overloading that are characteristic of modular languages like Ada (83).
11740: 
11741: @cindex Zsoter's object-oriented model
11742: In @uref{http://www.forth.org/oopf.html, Does late binding have to be
11743: slow?} (Forth Dimensions 18(1) 1996, pages 31-35) Andras Zsoter
11744: describes a model that makes heavy use of an active object (like
11745: @code{this} in @file{objects.fs}): The active object is not only used
11746: for accessing all fields, but also specifies the receiving object of
11747: every selector invocation; you have to change the active object
11748: explicitly with @code{@{ ... @}}, whereas in @file{objects.fs} it
11749: changes more or less implicitly at @code{m: ... ;m}. Such a change at
11750: the method entry point is unnecessary with Zsoter's model, because the
11751: receiving object is the active object already. On the other hand, the
11752: explicit change is absolutely necessary in that model, because otherwise
11753: no one could ever change the active object. An ANS Forth implementation
11754: of this model is available through
11755: @uref{http://www.forth.org/oopf.html}.
11756: 
11757: @cindex @file{oof.fs}, differences to other models
11758: The @file{oof.fs} model combines information hiding and overloading
11759: resolution (by keeping names in various word lists) with object-oriented
11760: programming. It sets the active object implicitly on method entry, but
11761: also allows explicit changing (with @code{>o...o>} or with
11762: @code{with...endwith}). It uses parsing and state-smart objects and
11763: classes for resolving overloading and for early binding: the object or
11764: class parses the selector and determines the method from this. If the
11765: selector is not parsed by an object or class, it performs a call to the
11766: selector for the active object (late binding), like Zsoter's model.
11767: Fields are always accessed through the active object. The big
11768: disadvantage of this model is the parsing and the state-smartness, which
11769: reduces extensibility and increases the opportunities for subtle bugs;
11770: essentially, you are only safe if you never tick or @code{postpone} an
11771: object or class (Bernd disagrees, but I (Anton) am not convinced).
11772: 
11773: @cindex @file{mini-oof.fs}, differences to other models
11774: The @file{mini-oof.fs} model is quite similar to a very stripped-down
11775: version of the @file{objects.fs} model, but syntactically it is a
11776: mixture of the @file{objects.fs} and @file{oof.fs} models.
11777: 
11778: 
11779: @c -------------------------------------------------------------
11780: @node Programming Tools, C Interface, Object-oriented Forth, Words
11781: @section Programming Tools
11782: @cindex programming tools
11783: 
11784: @c !! move this and assembler down below OO stuff.
11785: 
11786: @menu
11787: * Examining::                   Data and Code.
11788: * Forgetting words::            Usually before reloading.
11789: * Debugging::                   Simple and quick.
11790: * Assertions::                  Making your programs self-checking.
11791: * Singlestep Debugger::         Executing your program word by word.
11792: @end menu
11793: 
11794: @node Examining, Forgetting words, Programming Tools, Programming Tools
11795: @subsection Examining data and code
11796: @cindex examining data and code
11797: @cindex data examination
11798: @cindex code examination
11799: 
11800: The following words inspect the stack non-destructively:
11801: 
11802: doc-.s
11803: doc-f.s
11804: doc-maxdepth-.s
11805: 
11806: There is a word @code{.r} but it does @i{not} display the return stack!
11807: It is used for formatted numeric output (@pxref{Simple numeric output}).
11808: 
11809: doc-depth
11810: doc-fdepth
11811: doc-clearstack
11812: doc-clearstacks
11813: 
11814: The following words inspect memory.
11815: 
11816: doc-?
11817: doc-dump
11818: 
11819: And finally, @code{see} allows to inspect code:
11820: 
11821: doc-see
11822: doc-xt-see
11823: doc-simple-see
11824: doc-simple-see-range
11825: doc-see-code
11826: doc-see-code-range
11827: 
11828: @node Forgetting words, Debugging, Examining, Programming Tools
11829: @subsection Forgetting words
11830: @cindex words, forgetting
11831: @cindex forgeting words
11832: 
11833: @c  anton: other, maybe better places for this subsection: Defining Words;
11834: @c  Dictionary allocation.  At least a reference should be there.
11835: 
11836: Forth allows you to forget words (and everything that was alloted in the
11837: dictonary after them) in a LIFO manner.
11838: 
11839: doc-marker
11840: 
11841: The most common use of this feature is during progam development: when
11842: you change a source file, forget all the words it defined and load it
11843: again (since you also forget everything defined after the source file
11844: was loaded, you have to reload that, too).  Note that effects like
11845: storing to variables and destroyed system words are not undone when you
11846: forget words.  With a system like Gforth, that is fast enough at
11847: starting up and compiling, I find it more convenient to exit and restart
11848: Gforth, as this gives me a clean slate.
11849: 
11850: Here's an example of using @code{marker} at the start of a source file
11851: that you are debugging; it ensures that you only ever have one copy of
11852: the file's definitions compiled at any time:
11853: 
11854: @example
11855: [IFDEF] my-code
11856:     my-code
11857: [ENDIF]
11858: 
11859: marker my-code
11860: init-included-files
11861: 
11862: \ .. definitions start here
11863: \ .
11864: \ .
11865: \ end
11866: @end example
11867: 
11868: 
11869: @node Debugging, Assertions, Forgetting words, Programming Tools
11870: @subsection Debugging
11871: @cindex debugging
11872: 
11873: Languages with a slow edit/compile/link/test development loop tend to
11874: require sophisticated tracing/stepping debuggers to facilate debugging.
11875: 
11876: A much better (faster) way in fast-compiling languages is to add
11877: printing code at well-selected places, let the program run, look at
11878: the output, see where things went wrong, add more printing code, etc.,
11879: until the bug is found.
11880: 
11881: The simple debugging aids provided in @file{debugs.fs}
11882: are meant to support this style of debugging.
11883: 
11884: The word @code{~~} prints debugging information (by default the source
11885: location and the stack contents). It is easy to insert. If you use Emacs
11886: it is also easy to remove (@kbd{C-x ~} in the Emacs Forth mode to
11887: query-replace them with nothing). The deferred words
11888: @code{printdebugdata} and @code{.debugline} control the output of
11889: @code{~~}. The default source location output format works well with
11890: Emacs' compilation mode, so you can step through the program at the
11891: source level using @kbd{C-x `} (the advantage over a stepping debugger
11892: is that you can step in any direction and you know where the crash has
11893: happened or where the strange data has occurred).
11894: 
11895: doc-~~
11896: doc-printdebugdata
11897: doc-.debugline
11898: 
11899: @cindex filenames in @code{~~} output
11900: @code{~~} (and assertions) will usually print the wrong file name if a
11901: marker is executed in the same file after their occurance.  They will
11902: print @samp{*somewhere*} as file name if a marker is executed in the
11903: same file before their occurance.
11904: 
11905: 
11906: @node Assertions, Singlestep Debugger, Debugging, Programming Tools
11907: @subsection Assertions
11908: @cindex assertions
11909: 
11910: It is a good idea to make your programs self-checking, especially if you
11911: make an assumption that may become invalid during maintenance (for
11912: example, that a certain field of a data structure is never zero). Gforth
11913: supports @dfn{assertions} for this purpose. They are used like this:
11914: 
11915: @example
11916: assert( @i{flag} )
11917: @end example
11918: 
11919: The code between @code{assert(} and @code{)} should compute a flag, that
11920: should be true if everything is alright and false otherwise. It should
11921: not change anything else on the stack. The overall stack effect of the
11922: assertion is @code{( -- )}. E.g.
11923: 
11924: @example
11925: assert( 1 1 + 2 = ) \ what we learn in school
11926: assert( dup 0<> ) \ assert that the top of stack is not zero
11927: assert( false ) \ this code should not be reached
11928: @end example
11929: 
11930: The need for assertions is different at different times. During
11931: debugging, we want more checking, in production we sometimes care more
11932: for speed. Therefore, assertions can be turned off, i.e., the assertion
11933: becomes a comment. Depending on the importance of an assertion and the
11934: time it takes to check it, you may want to turn off some assertions and
11935: keep others turned on. Gforth provides several levels of assertions for
11936: this purpose:
11937: 
11938: 
11939: doc-assert0(
11940: doc-assert1(
11941: doc-assert2(
11942: doc-assert3(
11943: doc-assert(
11944: doc-)
11945: 
11946: 
11947: The variable @code{assert-level} specifies the highest assertions that
11948: are turned on. I.e., at the default @code{assert-level} of one,
11949: @code{assert0(} and @code{assert1(} assertions perform checking, while
11950: @code{assert2(} and @code{assert3(} assertions are treated as comments.
11951: 
11952: The value of @code{assert-level} is evaluated at compile-time, not at
11953: run-time. Therefore you cannot turn assertions on or off at run-time;
11954: you have to set the @code{assert-level} appropriately before compiling a
11955: piece of code. You can compile different pieces of code at different
11956: @code{assert-level}s (e.g., a trusted library at level 1 and
11957: newly-written code at level 3).
11958: 
11959: 
11960: doc-assert-level
11961: 
11962: 
11963: If an assertion fails, a message compatible with Emacs' compilation mode
11964: is produced and the execution is aborted (currently with @code{ABORT"}.
11965: If there is interest, we will introduce a special throw code. But if you
11966: intend to @code{catch} a specific condition, using @code{throw} is
11967: probably more appropriate than an assertion).
11968: 
11969: @cindex filenames in assertion output
11970: Assertions (and @code{~~}) will usually print the wrong file name if a
11971: marker is executed in the same file after their occurance.  They will
11972: print @samp{*somewhere*} as file name if a marker is executed in the
11973: same file before their occurance.
11974: 
11975: Definitions in ANS Forth for these assertion words are provided
11976: in @file{compat/assert.fs}.
11977: 
11978: 
11979: @node Singlestep Debugger,  , Assertions, Programming Tools
11980: @subsection Singlestep Debugger
11981: @cindex singlestep Debugger
11982: @cindex debugging Singlestep
11983: 
11984: The singlestep debugger works only with the engine @code{gforth-itc}.
11985: 
11986: When you create a new word there's often the need to check whether it
11987: behaves correctly or not. You can do this by typing @code{dbg
11988: badword}. A debug session might look like this:
11989: 
11990: @example
11991: : badword 0 DO i . LOOP ;  ok
11992: 2 dbg badword 
11993: : badword  
11994: Scanning code...
11995: 
11996: Nesting debugger ready!
11997: 
11998: 400D4738  8049BC4 0              -> [ 2 ] 00002 00000 
11999: 400D4740  8049F68 DO             -> [ 0 ] 
12000: 400D4744  804A0C8 i              -> [ 1 ] 00000 
12001: 400D4748 400C5E60 .              -> 0 [ 0 ] 
12002: 400D474C  8049D0C LOOP           -> [ 0 ] 
12003: 400D4744  804A0C8 i              -> [ 1 ] 00001 
12004: 400D4748 400C5E60 .              -> 1 [ 0 ] 
12005: 400D474C  8049D0C LOOP           -> [ 0 ] 
12006: 400D4758  804B384 ;              ->  ok
12007: @end example
12008: 
12009: Each line displayed is one step. You always have to hit return to
12010: execute the next word that is displayed. If you don't want to execute
12011: the next word in a whole, you have to type @kbd{n} for @code{nest}. Here is
12012: an overview what keys are available:
12013: 
12014: @table @i
12015: 
12016: @item @key{RET}
12017: Next; Execute the next word.
12018: 
12019: @item n
12020: Nest; Single step through next word.
12021: 
12022: @item u
12023: Unnest; Stop debugging and execute rest of word. If we got to this word
12024: with nest, continue debugging with the calling word.
12025: 
12026: @item d
12027: Done; Stop debugging and execute rest.
12028: 
12029: @item s
12030: Stop; Abort immediately.
12031: 
12032: @end table
12033: 
12034: Debugging large application with this mechanism is very difficult, because
12035: you have to nest very deeply into the program before the interesting part
12036: begins. This takes a lot of time. 
12037: 
12038: To do it more directly put a @code{BREAK:} command into your source code.
12039: When program execution reaches @code{BREAK:} the single step debugger is
12040: invoked and you have all the features described above.
12041: 
12042: If you have more than one part to debug it is useful to know where the
12043: program has stopped at the moment. You can do this by the 
12044: @code{BREAK" string"} command. This behaves like @code{BREAK:} except that
12045: string is typed out when the ``breakpoint'' is reached.
12046: 
12047: 
12048: doc-dbg
12049: doc-break:
12050: doc-break"
12051: 
12052: @c ------------------------------------------------------------
12053: @node C Interface, Assembler and Code Words, Programming Tools, Words
12054: @section C Interface
12055: @cindex C interface
12056: @cindex foreign language interface
12057: @cindex interface to C functions
12058: 
12059: Note that the C interface is not yet complete; callbacks are missing,
12060: as well as a way of declaring structs, unions, and their fields.
12061: 
12062: @menu
12063: * Calling C Functions::         
12064: * Declaring C Functions::       
12065: * Calling C function pointers::  
12066: * Defining library interfaces::  
12067: * Declaring OS-level libraries::  
12068: * Callbacks::                   
12069: * C interface internals::       
12070: * Low-Level C Interface Words::  
12071: @end menu
12072: 
12073: @node Calling C Functions, Declaring C Functions, C Interface, C Interface
12074: @subsection Calling C functions
12075: @cindex C functions, calls to
12076: @cindex calling C functions
12077: 
12078: Once a C function is declared (see @pxref{Declaring C Functions}), you
12079: can call it as follows: You push the arguments on the stack(s), and
12080: then call the word for the C function.  The arguments have to be
12081: pushed in the same order as the arguments appear in the C
12082: documentation (i.e., the first argument is deepest on the stack).
12083: Integer and pointer arguments have to be pushed on the data stack,
12084: floating-point arguments on the FP stack; these arguments are consumed
12085: by the called C function.
12086: 
12087: On returning from the C function, the return value, if any, resides on
12088: the appropriate stack: an integer return value is pushed on the data
12089: stack, an FP return value on the FP stack, and a void return value
12090: results in not pushing anything.  Note that most C functions have a
12091: return value, even if that is often not used in C; in Forth, you have
12092: to @code{drop} this return value explicitly if you do not use it.
12093: 
12094: The C interface automatically converts between the C type and the
12095: Forth type as necessary, on a best-effort basis (in some cases, there
12096: may be some loss).
12097: 
12098: As an example, consider the POSIX function @code{lseek()}:
12099: 
12100: @example
12101: off_t lseek(int fd, off_t offset, int whence);
12102: @end example
12103: 
12104: This function takes three integer arguments, and returns an integer
12105: argument, so a Forth call for setting the current file offset to the
12106: start of the file could look like this:
12107: 
12108: @example
12109: fd @@ 0 SEEK_SET lseek -1 = if
12110:   ... \ error handling
12111: then
12112: @end example
12113: 
12114: You might be worried that an @code{off_t} does not fit into a cell, so
12115: you could not pass larger offsets to lseek, and might get only a part
12116: of the return values.  In that case, in your declaration of the
12117: function (@pxref{Declaring C Functions}) you should declare it to use
12118: double-cells for the off_t argument and return value, and maybe give
12119: the resulting Forth word a different name, like @code{dlseek}; the
12120: result could be called like this:
12121: 
12122: @example
12123: fd @@ 0. SEEK_SET dlseek -1. d= if
12124:   ... \ error handling
12125: then
12126: @end example
12127: 
12128: Passing and returning structs or unions is currently not supported by
12129: our interface@footnote{If you know the calling convention of your C
12130: compiler, you usually can call such functions in some way, but that
12131: way is usually not portable between platforms, and sometimes not even
12132: between C compilers.}.
12133: 
12134: Calling functions with a variable number of arguments (@emph{variadic}
12135: functions, e.g., @code{printf()}) is only supported by having you
12136: declare one function-calling word for each argument pattern, and
12137: calling the appropriate word for the desired pattern.
12138: 
12139: 
12140: 
12141: @node Declaring C Functions, Calling C function pointers, Calling C Functions, C Interface
12142: @subsection Declaring C Functions
12143: @cindex C functions, declarations
12144: @cindex declaring C functions
12145: 
12146: Before you can call @code{lseek} or @code{dlseek}, you have to declare
12147: it.  The declaration consists of two parts: 
12148: 
12149: @table @b
12150: 
12151: @item The C part
12152: is the C declaration of the function, or more typically and portably,
12153: a C-style @code{#include} of a file that contains the declaration of
12154: the C function.
12155: 
12156: @item The Forth part
12157: declares the Forth types of the parameters and the Forth word name
12158: corresponding to the C function.
12159: 
12160: @end table
12161: 
12162: For the words @code{lseek} and @code{dlseek} mentioned earlier, the
12163: declarations are:
12164: 
12165: @example
12166: \c #define _FILE_OFFSET_BITS 64
12167: \c #include <sys/types.h>
12168: \c #include <unistd.h>
12169: c-function lseek lseek n n n -- n
12170: c-function dlseek lseek n d n -- d
12171: @end example
12172: 
12173: The C part of the declarations is prefixed by @code{\c}, and the rest
12174: of the line is ordinary C code.  You can use as many lines of C
12175: declarations as you like, and they are visible for all further
12176: function declarations.
12177: 
12178: The Forth part declares each interface word with @code{c-function},
12179: followed by the Forth name of the word, the C name of the called
12180: function, and the stack effect of the word.  The stack effect contains
12181: an arbitrary number of types of parameters, then @code{--}, and then
12182: exactly one type for the return value.  The possible types are:
12183: 
12184: @table @code
12185: 
12186: @item n
12187: single-cell integer
12188: 
12189: @item a
12190: address (single-cell)
12191: 
12192: @item d
12193: double-cell integer
12194: 
12195: @item r
12196: floating-point value
12197: 
12198: @item func
12199: C function pointer
12200: 
12201: @item void
12202: no value (used as return type for void functions)
12203: 
12204: @end table
12205: 
12206: @cindex variadic C functions
12207: 
12208: To deal with variadic C functions, you can declare one Forth word for
12209: every pattern you want to use, e.g.:
12210: 
12211: @example
12212: \c #include <stdio.h>
12213: c-function printf-nr printf a n r -- n
12214: c-function printf-rn printf a r n -- n
12215: @end example
12216: 
12217: Note that with C functions declared as variadic (or if you don't
12218: provide a prototype), the C interface has no C type to convert to, so
12219: no automatic conversion happens, which may lead to portability
12220: problems in some cases.  In such cases you can perform the conversion
12221: explicitly on the C level, e.g., as follows:
12222: 
12223: @example
12224: \c #define printfll(s,ll) printf(s,(long long)ll)
12225: c-function printfll printfll a n -- n
12226: @end example
12227: 
12228: Here, instead of calling @code{printf()} directly, we define a macro
12229: that casts (converts) the Forth single-cell integer into a
12230: C @code{long long} before calling @code{printf()}.
12231: 
12232: doc-\c
12233: doc-c-function
12234: 
12235: In order to work, this C interface invokes GCC at run-time and uses
12236: dynamic linking.  If these features are not available, there are
12237: other, less convenient and less portable C interfaces in @file{lib.fs}
12238: and @file{oldlib.fs}.  These interfaces are mostly undocumented and
12239: mostly incompatible with each other and with the documented C
12240: interface; you can find some examples for the @file{lib.fs} interface
12241: in @file{lib.fs}.
12242: 
12243: 
12244: @node Calling C function pointers, Defining library interfaces, Declaring C Functions, C Interface
12245: @subsection Calling C function pointers from Forth
12246: @cindex C function pointers, calling from Forth
12247: 
12248: If you come across a C function pointer (e.g., in some C-constructed
12249: structure) and want to call it from your Forth program, you can also
12250: use the features explained until now to achieve that, as follows:
12251: 
12252: Let us assume that there is a C function pointer type @code{func1}
12253: defined in some header file @file{func1.h}, and you know that these
12254: functions take one integer argument and return an integer result; and
12255: you want to call functions through such pointers.  Just define
12256: 
12257: @example
12258: \c #include <func1.h>
12259: \c #define call_func1(par1,fptr) ((func1)fptr)(par1)
12260: c-function call-func1 call_func1 n func -- n
12261: @end example
12262: 
12263: and then you can call a function pointed to by, say @code{func1a} as
12264: follows:
12265: 
12266: @example
12267: -5 func1a call-func1 .
12268: @end example
12269: 
12270: In the C part, @code{call_func} is defined as a macro to avoid having
12271: to declare the exact parameter and return types, so the C compiler
12272: knows them from the declaration of @code{func1}.
12273: 
12274: The Forth word @code{call-func1} is similar to @code{execute}, except
12275: that it takes a C @code{func1} pointer instead of a Forth execution
12276: token, and it is specific to @code{func1} pointers.  For each type of
12277: function pointer you want to call from Forth, you have to define
12278: a separate calling word.
12279: 
12280: 
12281: @node Defining library interfaces, Declaring OS-level libraries, Calling C function pointers, C Interface
12282: @subsection Defining library interfaces
12283: @cindex giving a name to a library interface
12284: @cindex library interface names
12285: 
12286: You can give a name to a bunch of C function declarations (a library
12287: interface), as follows:
12288: 
12289: @example
12290: c-library lseek-lib
12291: \c #define _FILE_OFFSET_BITS 64
12292: ...
12293: end-c-library
12294: @end example
12295: 
12296: The effect of giving such a name to the interface is that the names of
12297: the generated files will contain that name, and when you use the
12298: interface a second time, it will use the existing files instead of
12299: generating and compiling them again, saving you time.  Note that even
12300: if you change the declarations, the old (stale) files will be used,
12301: probably leading to errors.  So, during development of the
12302: declarations we recommend not using @code{c-library}.  Normally these
12303: files are cached in @file{$HOME/.gforth/libcc-named}, so by deleting
12304: that directory you can get rid of stale files.
12305: 
12306: Note that you should use @code{c-library} before everything else
12307: having anything to do with that library, as it resets some setup
12308: stuff.  The idea is that the typical use is to put each
12309: @code{c-library}...@code{end-library} unit in its own file, and to be
12310: able to include these files in any order.
12311: 
12312: Note that the library name is not allocated in the dictionary and
12313: therefore does not shadow dictionary names.  It is used in the file
12314: system, so you have to use naming conventions appropriate for file
12315: systems.  Also, you must not call a function you declare after
12316: @code{c-library} before you perform @code{end-c-library}.
12317: 
12318: A major benefit of these named library interfaces is that, once they
12319: are generated, the tools used to generated them (in particular, the C
12320: compiler and libtool) are no longer needed, so the interface can be
12321: used even on machines that do not have the tools installed.
12322: 
12323: doc-c-library-name
12324: doc-c-library
12325: doc-end-c-library
12326: 
12327: 
12328: @node Declaring OS-level libraries, Callbacks, Defining library interfaces, C Interface
12329: @subsection Declaring OS-level libraries
12330: @cindex Shared libraries in C interface
12331: @cindex Dynamically linked libraries in C interface
12332: @cindex Libraries in C interface
12333: 
12334: For calling some C functions, you need to link with a specific
12335: OS-level library that contains that function.  E.g., the @code{sin}
12336: function requires linking a special library by using the command line
12337: switch @code{-lm}.  In our C iterface you do the equivalent thing by
12338: calling @code{add-lib} as follows:
12339: 
12340: @example
12341: clear-libs
12342: s" m" add-lib
12343: \c #include <math.h>
12344: c-function sin sin r -- r
12345: @end example
12346: 
12347: First, you clear any libraries that may have been declared earlier
12348: (you don't need them for @code{sin}); then you add the @code{m}
12349: library (actually @code{libm.so} or somesuch) to the currently
12350: declared libraries; you can add as many as you need.  Finally you
12351: declare the function as shown above.  Typically you will use the same
12352: set of library declarations for many function declarations; you need
12353: to write only one set for that, right at the beginning.
12354: 
12355: Note that you must not call @code{clear-libs} inside
12356: @code{c-library...end-c-library}; however, @code{c-library} performs
12357: the function of @code{clear-libs}, so @code{clear-libs} is not
12358: necessary, and you usually want to put @code{add-lib} calls inside
12359: @code{c-library...end-c-library}.
12360: 
12361: doc-clear-libs
12362: doc-add-lib
12363: 
12364: 
12365: @node Callbacks, C interface internals, Declaring OS-level libraries, C Interface
12366: @subsection Callbacks
12367: @cindex Callback functions written in Forth
12368: @cindex C function pointers to Forth words
12369: 
12370: Callbacks are not yet supported by the documented C interface.  You
12371: can use the undocumented @file{lib.fs} interface for callbacks.
12372: 
12373: In some cases you have to pass a function pointer to a C function,
12374: i.e., the library wants to call back to your application (and the
12375: pointed-to function is called a callback function).  You can pass the
12376: address of an existing C function (that you get with @code{lib-sym},
12377: @pxref{Low-Level C Interface Words}), but if there is no appropriate C
12378: function, you probably want to define the function as a Forth word.
12379: 
12380: @c I don't understand the existing callback interface from the example - anton
12381: 
12382: 
12383: @c > > Und dann gibt's noch die fptr-Deklaration, die einem
12384: @c > > C-Funktionspointer entspricht (Deklaration gleich wie bei
12385: @c > > Library-Funktionen, nur ohne den C-Namen, Aufruf mit der
12386: @c > > C-Funktionsadresse auf dem TOS).
12387: @c >
12388: @c > Ja, da bin ich dann ausgestiegen, weil ich aus dem Beispiel nicht
12389: @c > gesehen habe, wozu das gut ist.
12390: @c 
12391: @c Irgendwie muss ich den Callback ja testen. Und es soll ja auch 
12392: @c vorkommen, dass man von irgendwelchen kranken Interfaces einen 
12393: @c Funktionspointer übergeben bekommt, den man dann bei Gelegenheit 
12394: @c aufrufen muss. Also kann man den deklarieren, und das damit deklarierte 
12395: @c Wort verhält sich dann wie ein EXECUTE für alle C-Funktionen mit 
12396: @c demselben Prototyp.
12397: 
12398: 
12399: @node C interface internals, Low-Level C Interface Words, Callbacks, C Interface
12400: @subsection How the C interface works
12401: 
12402: The documented C interface works by generating a C code out of the
12403: declarations.
12404: 
12405: In particular, for every Forth word declared with @code{c-function},
12406: it generates a wrapper function in C that takes the Forth data from
12407: the Forth stacks, and calls the target C function with these data as
12408: arguments.  The C compiler then performs an implicit conversion
12409: between the Forth type from the stack, and the C type for the
12410: parameter, which is given by the C function prototype.  After the C
12411: function returns, the return value is likewise implicitly converted to
12412: a Forth type and written back on the stack.
12413: 
12414: The @code{\c} lines are literally included in the C code (but without
12415: the @code{\c}), and provide the necessary declarations so that the C
12416: compiler knows the C types and has enough information to perform the
12417: conversion.
12418: 
12419: These wrapper functions are eventually compiled and dynamically linked
12420: into Gforth, and then they can be called.
12421: 
12422: The libraries added with @code{add-lib} are used in the compile
12423: command line to specify dependent libraries with @code{-l@var{lib}},
12424: causing these libraries to be dynamically linked when the wrapper
12425: function is linked.
12426: 
12427: 
12428: @node Low-Level C Interface Words,  , C interface internals, C Interface
12429: @subsection Low-Level C Interface Words
12430: 
12431: doc-open-lib
12432: doc-lib-sym
12433: doc-lib-error
12434: doc-call-c
12435: 
12436: @c -------------------------------------------------------------
12437: @node Assembler and Code Words, Threading Words, C Interface, Words
12438: @section Assembler and Code Words
12439: @cindex assembler
12440: @cindex code words
12441: 
12442: @menu
12443: * Code and ;code::              
12444: * Common Assembler::            Assembler Syntax
12445: * Common Disassembler::         
12446: * 386 Assembler::               Deviations and special cases
12447: * Alpha Assembler::             Deviations and special cases
12448: * MIPS assembler::              Deviations and special cases
12449: * PowerPC assembler::           Deviations and special cases
12450: * ARM Assembler::               Deviations and special cases
12451: * Other assemblers::            How to write them
12452: @end menu
12453: 
12454: @node Code and ;code, Common Assembler, Assembler and Code Words, Assembler and Code Words
12455: @subsection @code{Code} and @code{;code}
12456: 
12457: Gforth provides some words for defining primitives (words written in
12458: machine code), and for defining the machine-code equivalent of
12459: @code{DOES>}-based defining words. However, the machine-independent
12460: nature of Gforth poses a few problems: First of all, Gforth runs on
12461: several architectures, so it can provide no standard assembler. What's
12462: worse is that the register allocation not only depends on the processor,
12463: but also on the @code{gcc} version and options used.
12464: 
12465: The words that Gforth offers encapsulate some system dependences (e.g.,
12466: the header structure), so a system-independent assembler may be used in
12467: Gforth. If you do not have an assembler, you can compile machine code
12468: directly with @code{,} and @code{c,}@footnote{This isn't portable,
12469: because these words emit stuff in @i{data} space; it works because
12470: Gforth has unified code/data spaces. Assembler isn't likely to be
12471: portable anyway.}.
12472: 
12473: 
12474: doc-assembler
12475: doc-init-asm
12476: doc-code
12477: doc-end-code
12478: doc-;code
12479: doc-flush-icache
12480: 
12481: 
12482: If @code{flush-icache} does not work correctly, @code{code} words
12483: etc. will not work (reliably), either.
12484: 
12485: The typical usage of these @code{code} words can be shown most easily by
12486: analogy to the equivalent high-level defining words:
12487: 
12488: @example
12489: : foo                              code foo
12490:    <high-level Forth words>              <assembler>
12491: ;                                  end-code
12492:                                 
12493: : bar                              : bar
12494:    <high-level Forth words>           <high-level Forth words>
12495:    CREATE                             CREATE
12496:       <high-level Forth words>           <high-level Forth words>
12497:    DOES>                              ;code
12498:       <high-level Forth words>           <assembler>
12499: ;                                  end-code
12500: @end example
12501: 
12502: @c anton: the following stuff is also in "Common Assembler", in less detail.
12503: 
12504: @cindex registers of the inner interpreter
12505: In the assembly code you will want to refer to the inner interpreter's
12506: registers (e.g., the data stack pointer) and you may want to use other
12507: registers for temporary storage. Unfortunately, the register allocation
12508: is installation-dependent.
12509: 
12510: In particular, @code{ip} (Forth instruction pointer) and @code{rp}
12511: (return stack pointer) may be in different places in @code{gforth} and
12512: @code{gforth-fast}, or different installations.  This means that you
12513: cannot write a @code{NEXT} routine that works reliably on both versions
12514: or different installations; so for doing @code{NEXT}, I recommend
12515: jumping to @code{' noop >code-address}, which contains nothing but a
12516: @code{NEXT}.
12517: 
12518: For general accesses to the inner interpreter's registers, the easiest
12519: solution is to use explicit register declarations (@pxref{Explicit Reg
12520: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) for
12521: all of the inner interpreter's registers: You have to compile Gforth
12522: with @code{-DFORCE_REG} (configure option @code{--enable-force-reg}) and
12523: the appropriate declarations must be present in the @code{machine.h}
12524: file (see @code{mips.h} for an example; you can find a full list of all
12525: declarable register symbols with @code{grep register engine.c}). If you
12526: give explicit registers to all variables that are declared at the
12527: beginning of @code{engine()}, you should be able to use the other
12528: caller-saved registers for temporary storage. Alternatively, you can use
12529: the @code{gcc} option @code{-ffixed-REG} (@pxref{Code Gen Options, ,
12530: Options for Code Generation Conventions, gcc.info, GNU C Manual}) to
12531: reserve a register (however, this restriction on register allocation may
12532: slow Gforth significantly).
12533: 
12534: If this solution is not viable (e.g., because @code{gcc} does not allow
12535: you to explicitly declare all the registers you need), you have to find
12536: out by looking at the code where the inner interpreter's registers
12537: reside and which registers can be used for temporary storage. You can
12538: get an assembly listing of the engine's code with @code{make engine.s}.
12539: 
12540: In any case, it is good practice to abstract your assembly code from the
12541: actual register allocation. E.g., if the data stack pointer resides in
12542: register @code{$17}, create an alias for this register called @code{sp},
12543: and use that in your assembly code.
12544: 
12545: @cindex code words, portable
12546: Another option for implementing normal and defining words efficiently
12547: is to add the desired functionality to the source of Gforth. For normal
12548: words you just have to edit @file{primitives} (@pxref{Automatic
12549: Generation}). Defining words (equivalent to @code{;CODE} words, for fast
12550: defined words) may require changes in @file{engine.c}, @file{kernel.fs},
12551: @file{prims2x.fs}, and possibly @file{cross.fs}.
12552: 
12553: @node Common Assembler, Common Disassembler, Code and ;code, Assembler and Code Words
12554: @subsection Common Assembler
12555: 
12556: The assemblers in Gforth generally use a postfix syntax, i.e., the
12557: instruction name follows the operands.
12558: 
12559: The operands are passed in the usual order (the same that is used in the
12560: manual of the architecture).  Since they all are Forth words, they have
12561: to be separated by spaces; you can also use Forth words to compute the
12562: operands.
12563: 
12564: The instruction names usually end with a @code{,}.  This makes it easier
12565: to visually separate instructions if you put several of them on one
12566: line; it also avoids shadowing other Forth words (e.g., @code{and}).
12567: 
12568: Registers are usually specified by number; e.g., (decimal) @code{11}
12569: specifies registers R11 and F11 on the Alpha architecture (which one,
12570: depends on the instruction).  The usual names are also available, e.g.,
12571: @code{s2} for R11 on Alpha.
12572: 
12573: Control flow is specified similar to normal Forth code (@pxref{Arbitrary
12574: control structures}), with @code{if,}, @code{ahead,}, @code{then,},
12575: @code{begin,}, @code{until,}, @code{again,}, @code{cs-roll},
12576: @code{cs-pick}, @code{else,}, @code{while,}, and @code{repeat,}.  The
12577: conditions are specified in a way specific to each assembler.
12578: 
12579: Note that the register assignments of the Gforth engine can change
12580: between Gforth versions, or even between different compilations of the
12581: same Gforth version (e.g., if you use a different GCC version).  So if
12582: you want to refer to Gforth's registers (e.g., the stack pointer or
12583: TOS), I recommend defining your own words for refering to these
12584: registers, and using them later on; then you can easily adapt to a
12585: changed register assignment.  The stability of the register assignment
12586: is usually better if you build Gforth with @code{--enable-force-reg}.
12587: 
12588: The most common use of these registers is to dispatch to the next word
12589: (the @code{next} routine).  A portable way to do this is to jump to
12590: @code{' noop >code-address} (of course, this is less efficient than
12591: integrating the @code{next} code and scheduling it well).
12592: 
12593: Another difference between Gforth version is that the top of stack is
12594: kept in memory in @code{gforth} and, on most platforms, in a register in
12595: @code{gforth-fast}.
12596: 
12597: @node  Common Disassembler, 386 Assembler, Common Assembler, Assembler and Code Words
12598: @subsection Common Disassembler
12599: @cindex disassembler, general
12600: @cindex gdb disassembler
12601: 
12602: You can disassemble a @code{code} word with @code{see}
12603: (@pxref{Debugging}).  You can disassemble a section of memory with
12604: 
12605: doc-discode
12606: 
12607: There are two kinds of disassembler for Gforth: The Forth disassembler
12608: (available on some CPUs) and the gdb disassembler (available on
12609: platforms with @command{gdb} and @command{mktemp}).  If both are
12610: available, the Forth disassembler is used by default.  If you prefer
12611: the gdb disassembler, say
12612: 
12613: @example
12614: ' disasm-gdb is discode
12615: @end example
12616: 
12617: If neither is available, @code{discode} performs @code{dump}.
12618: 
12619: The Forth disassembler generally produces output that can be fed into the
12620: assembler (i.e., same syntax, etc.).  It also includes additional
12621: information in comments.  In particular, the address of the instruction
12622: is given in a comment before the instruction.
12623: 
12624: The gdb disassembler produces output in the same format as the gdb
12625: @code{disassemble} command (@pxref{Machine Code,,Source and machine
12626: code,gdb,Debugging with GDB}), in the default flavour (AT&T syntax for
12627: the 386 and AMD64 architectures).
12628: 
12629: @code{See} may display more or less than the actual code of the word,
12630: because the recognition of the end of the code is unreliable.  You can
12631: use @code{discode} if it did not display enough.  It may display more, if
12632: the code word is not immediately followed by a named word.  If you have
12633: something else there, you can follow the word with @code{align latest ,}
12634: to ensure that the end is recognized.
12635: 
12636: @node 386 Assembler, Alpha Assembler, Common Disassembler, Assembler and Code Words
12637: @subsection 386 Assembler
12638: 
12639: The 386 assembler included in Gforth was written by Bernd Paysan, it's
12640: available under GPL, and originally part of bigFORTH.
12641: 
12642: The 386 disassembler included in Gforth was written by Andrew McKewan
12643: and is in the public domain.
12644: 
12645: The disassembler displays code in an Intel-like prefix syntax.
12646: 
12647: The assembler uses a postfix syntax with reversed parameters.
12648: 
12649: The assembler includes all instruction of the Athlon, i.e. 486 core
12650: instructions, Pentium and PPro extensions, floating point, MMX, 3Dnow!,
12651: but not ISSE. It's an integrated 16- and 32-bit assembler. Default is 32
12652: bit, you can switch to 16 bit with .86 and back to 32 bit with .386.
12653: 
12654: There are several prefixes to switch between different operation sizes,
12655: @code{.b} for byte accesses, @code{.w} for word accesses, @code{.d} for
12656: double-word accesses. Addressing modes can be switched with @code{.wa}
12657: for 16 bit addresses, and @code{.da} for 32 bit addresses. You don't
12658: need a prefix for byte register names (@code{AL} et al).
12659: 
12660: For floating point operations, the prefixes are @code{.fs} (IEEE
12661: single), @code{.fl} (IEEE double), @code{.fx} (extended), @code{.fw}
12662: (word), @code{.fd} (double-word), and @code{.fq} (quad-word).
12663: 
12664: The MMX opcodes don't have size prefixes, they are spelled out like in
12665: the Intel assembler. Instead of move from and to memory, there are
12666: PLDQ/PLDD and PSTQ/PSTD.
12667: 
12668: The registers lack the 'e' prefix; even in 32 bit mode, eax is called
12669: ax.  Immediate values are indicated by postfixing them with @code{#},
12670: e.g., @code{3 #}.  Here are some examples of addressing modes in various
12671: syntaxes:
12672: 
12673: @example
12674: Gforth          Intel (NASM)   AT&T (gas)      Name
12675: .w ax           ax             %ax             register (16 bit)
12676: ax              eax            %eax            register (32 bit)
12677: 3 #             offset 3       $3              immediate
12678: 1000 #)         byte ptr 1000  1000            displacement
12679: bx )            [ebx]          (%ebx)          base
12680: 100 di d)       100[edi]       100(%edi)       base+displacement
12681: 20 ax *4 i#)    20[eax*4]      20(,%eax,4)     (index*scale)+displacement
12682: di ax *4 i)     [edi][eax*4]   (%edi,%eax,4)   base+(index*scale)
12683: 4 bx cx di)     4[ebx][ecx]    4(%ebx,%ecx)    base+index+displacement
12684: 12 sp ax *2 di) 12[esp][eax*2] 12(%esp,%eax,2) base+(index*scale)+displacement
12685: @end example
12686: 
12687: You can use @code{L)} and @code{LI)} instead of @code{D)} and
12688: @code{DI)} to enforce 32-bit displacement fields (useful for
12689: later patching).
12690: 
12691: Some example of instructions are:
12692: 
12693: @example
12694: ax bx mov             \ move ebx,eax
12695: 3 # ax mov            \ mov eax,3
12696: 100 di d) ax mov      \ mov eax,100[edi]
12697: 4 bx cx di) ax mov    \ mov eax,4[ebx][ecx]
12698: .w ax bx mov          \ mov bx,ax
12699: @end example
12700: 
12701: The following forms are supported for binary instructions:
12702: 
12703: @example
12704: <reg> <reg> <inst>
12705: <n> # <reg> <inst>
12706: <mem> <reg> <inst>
12707: <reg> <mem> <inst>
12708: <n> # <mem> <inst>
12709: @end example
12710: 
12711: The shift/rotate syntax is:
12712: 
12713: @example
12714: <reg/mem> 1 # shl \ shortens to shift without immediate
12715: <reg/mem> 4 # shl
12716: <reg/mem> cl shl
12717: @end example
12718: 
12719: Precede string instructions (@code{movs} etc.) with @code{.b} to get
12720: the byte version.
12721: 
12722: The control structure words @code{IF} @code{UNTIL} etc. must be preceded
12723: by one of these conditions: @code{vs vc u< u>= 0= 0<> u<= u> 0< 0>= ps
12724: pc < >= <= >}. (Note that most of these words shadow some Forth words
12725: when @code{assembler} is in front of @code{forth} in the search path,
12726: e.g., in @code{code} words).  Currently the control structure words use
12727: one stack item, so you have to use @code{roll} instead of @code{cs-roll}
12728: to shuffle them (you can also use @code{swap} etc.).
12729: 
12730: Here is an example of a @code{code} word (assumes that the stack pointer
12731: is in esi and the TOS is in ebx):
12732: 
12733: @example
12734: code my+ ( n1 n2 -- n )
12735:     4 si D) bx add
12736:     4 # si add
12737:     Next
12738: end-code
12739: @end example
12740: 
12741: 
12742: @node Alpha Assembler, MIPS assembler, 386 Assembler, Assembler and Code Words
12743: @subsection Alpha Assembler
12744: 
12745: The Alpha assembler and disassembler were originally written by Bernd
12746: Thallner.
12747: 
12748: The register names @code{a0}--@code{a5} are not available to avoid
12749: shadowing hex numbers.
12750: 
12751: Immediate forms of arithmetic instructions are distinguished by a
12752: @code{#} just before the @code{,}, e.g., @code{and#,} (note: @code{lda,}
12753: does not count as arithmetic instruction).
12754: 
12755: You have to specify all operands to an instruction, even those that
12756: other assemblers consider optional, e.g., the destination register for
12757: @code{br,}, or the destination register and hint for @code{jmp,}.
12758: 
12759: You can specify conditions for @code{if,} by removing the first @code{b}
12760: and the trailing @code{,} from a branch with a corresponding name; e.g.,
12761: 
12762: @example
12763: 11 fgt if, \ if F11>0e
12764:   ...
12765: endif,
12766: @end example
12767: 
12768: @code{fbgt,} gives @code{fgt}.  
12769: 
12770: @node MIPS assembler, PowerPC assembler, Alpha Assembler, Assembler and Code Words
12771: @subsection MIPS assembler
12772: 
12773: The MIPS assembler was originally written by Christian Pirker.
12774: 
12775: Currently the assembler and disassembler only cover the MIPS-I
12776: architecture (R3000), and don't support FP instructions.
12777: 
12778: The register names @code{$a0}--@code{$a3} are not available to avoid
12779: shadowing hex numbers.
12780: 
12781: Because there is no way to distinguish registers from immediate values,
12782: you have to explicitly use the immediate forms of instructions, i.e.,
12783: @code{addiu,}, not just @code{addu,} (@command{as} does this
12784: implicitly).
12785: 
12786: If the architecture manual specifies several formats for the instruction
12787: (e.g., for @code{jalr,}), you usually have to use the one with more
12788: arguments (i.e., two for @code{jalr,}).  When in doubt, see
12789: @code{arch/mips/testasm.fs} for an example of correct use.
12790: 
12791: Branches and jumps in the MIPS architecture have a delay slot.  You have
12792: to fill it yourself (the simplest way is to use @code{nop,}), the
12793: assembler does not do it for you (unlike @command{as}).  Even
12794: @code{if,}, @code{ahead,}, @code{until,}, @code{again,}, @code{while,},
12795: @code{else,} and @code{repeat,} need a delay slot.  Since @code{begin,}
12796: and @code{then,} just specify branch targets, they are not affected.
12797: 
12798: Note that you must not put branches, jumps, or @code{li,} into the delay
12799: slot: @code{li,} may expand to several instructions, and control flow
12800: instructions may not be put into the branch delay slot in any case.
12801: 
12802: For branches the argument specifying the target is a relative address;
12803: You have to add the address of the delay slot to get the absolute
12804: address.
12805: 
12806: The MIPS architecture also has load delay slots and restrictions on
12807: using @code{mfhi,} and @code{mflo,}; you have to order the instructions
12808: yourself to satisfy these restrictions, the assembler does not do it for
12809: you.
12810: 
12811: You can specify the conditions for @code{if,} etc. by taking a
12812: conditional branch and leaving away the @code{b} at the start and the
12813: @code{,} at the end.  E.g.,
12814: 
12815: @example
12816: 4 5 eq if,
12817:   ... \ do something if $4 equals $5
12818: then,
12819: @end example
12820: 
12821: 
12822: @node PowerPC assembler, ARM Assembler, MIPS assembler, Assembler and Code Words
12823: @subsection PowerPC assembler
12824: 
12825: The PowerPC assembler and disassembler were contributed by Michal
12826: Revucky.
12827: 
12828: This assembler does not follow the convention of ending mnemonic names
12829: with a ``,'', so some mnemonic names shadow regular Forth words (in
12830: particular: @code{and or xor fabs}); so if you want to use the Forth
12831: words, you have to make them visible first, e.g., with @code{also
12832: forth}.
12833: 
12834: Registers are referred to by their number, e.g., @code{9} means the
12835: integer register 9 or the FP register 9 (depending on the
12836: instruction).
12837: 
12838: Because there is no way to distinguish registers from immediate values,
12839: you have to explicitly use the immediate forms of instructions, i.e.,
12840: @code{addi,}, not just @code{add,}.
12841: 
12842: The assembler and disassembler usually support the most general form
12843: of an instruction, but usually not the shorter forms (especially for
12844: branches).
12845: 
12846: 
12847: @node ARM Assembler, Other assemblers, PowerPC assembler, Assembler and Code Words
12848: @subsection ARM Assembler
12849: 
12850: The ARM assembler included in Gforth was written from scratch by David
12851: Kuehling.
12852: 
12853: The assembler includes all instruction of ARM architecture version 4,
12854: but does not (yet) have support for Thumb instructions.  It also lacks
12855: support for any co-processors.
12856: 
12857: The assembler uses a postfix syntax with the target operand specified
12858: last.  For load/store instructions the last operand will be the
12859: register(s) to be loaded from/stored to.
12860: 
12861: Registers are specified by their names @code{r0} through @code{r15},
12862: with the aliases @code{pc}, @code{lr}, @code{sp}, @code{ip} and
12863: @code{fp} provided for convenience.  Note that @code{ip} means intra
12864: procedure call scratch register (@code{r12}) and does not refer to the
12865: instruction pointer.
12866: 
12867: Condition codes can be specified anywhere in the instruction, but will
12868: be most readable if specified just in front of the mnemonic.  The 'S'
12869: flag is not a separate word, but encoded into instruction mnemonics,
12870: ie. just use @code{adds,} instead of @code{add,} if you want the
12871: status register to be updated.
12872: 
12873: The following table lists the syntax of operands for general
12874: instructions:
12875: 
12876: @example
12877: Gforth          normal assembler      description
12878: 123 #           #123                  immediate
12879: r12             r12                   register
12880: r12 4 #LSL      r12, LSL #4           shift left by immediate
12881: r12 r1 #LSL     r12, LSL r1           shift left by register
12882: r12 4 #LSR      r12, LSR #4           shift right by immediate
12883: r12 r1 #LSR     r12, LSR r1           shift right by register
12884: r12 4 #ASR      r12, ASR #4           arithmetic shift right
12885: r12 r1 #ASR     r12, ASR r1           ... by register
12886: r12 4 #ROR      r12, ROR #4           rotate right by immediate
12887: r12 r1 #ROR     r12, ROR r1           ... by register
12888: r12 RRX         r12, RRX              rotate right with extend by 1
12889: @end example
12890: 
12891: Memory operand syntax is listed in this table:
12892: 
12893: @example
12894: Gforth            normal assembler      description
12895: r4 ]              [r4]                  register
12896: r4 4 #]           [r4, #+4]             register with immediate offset
12897: r4 -4 #]          [r4, #-4]             with negative offset
12898: r4 r1 +]          [r4, +r1]             register with register offset
12899: r4 r1 -]          [r4, -r1]             with negated register offset
12900: r4 r1 2 #LSL -]   [r4, -r1, LSL #2]     with negated and shifted offset
12901: r4 4 #]!          [r4, #+4]!            immediate preincrement
12902: r4 r1 +]!         [r4, +r1]!            register preincrement
12903: r4 r1 -]!         [r4, +r1]!            register predecrement
12904: r4 r1 2 #LSL +]!  [r4, +r1, LSL #2]!    shifted preincrement
12905: r4 -4 ]#          [r4], #-4             immediate postdecrement
12906: r4 r1 ]+          [r4], r1              register postincrement
12907: r4 r1 ]-          [r4], -r1             register postdecrement
12908: r4 r1 2 #LSL ]-   [r4], -r1, LSL #2     shifted postdecrement
12909: ' xyz >body [#]   xyz                   PC-relative addressing
12910: @end example
12911: 
12912: Register lists for load/store multiple instructions are started and
12913: terminated by using the words @code{@{} and @code{@}}
12914: respectivly.  Between braces, register names can be listed one by one,
12915: or register ranges can be formed by using the postfix operator
12916: @code{r-r}.  The @code{^} flag is not encoded in the register list
12917: operand, but instead directly encoded into the instruction mnemonic,
12918: ie. use @code{^ldm,} and @code{^stm,}.
12919: 
12920: Addressing modes for load/store multiple are not encoded as
12921: instruction suffixes, but instead specified after the register that
12922: supplies the address.  Use one of @code{DA}, @code{IA}, @code{DB},
12923: @code{IB}, @code{DA!}, @code{IA!}, @code{DB!} or @code{IB!}.
12924: 
12925: The following table gives some examples:
12926: 
12927: @example
12928: Gforth                           normal assembler
12929: @{ r0 r7 r8 @}  r4 ia  stm,        stmia    @{r0,r7,r8@}, r4
12930: @{ r0 r7 r8 @}  r4 db!  ldm,       ldmdb    @{r0,r7,r8@}, r4!
12931: @{ r0 r15 r-r @}  sp ia!  ^ldm,    ldmfd    @{r0-r15@}^, sp!
12932: @end example
12933: 
12934: Conditions for control structure words are specified in front of a
12935: word:
12936: 
12937: @example
12938: r1 r2 cmp,    \ compare r1 and r2
12939: eq if,        \ equal?
12940:    ...          \ code executed if r1 == r2
12941: then,
12942: @end example
12943: 
12944: Here is an example of a @code{code} word (assumes that the stack
12945: pointer is in @code{r9}, and that @code{r2} and @code{r3} can be
12946: clobbered):
12947: 
12948: @example
12949: code my+ ( n1 n2 --  n3 )
12950:    r9 IA!       @{ r2 r3 @} ldm,  \ pop r2 = n2, r3 = n1
12951:    r2   r3      r3        add,  \ r3 = n2+n1
12952:    r9 -4 #]!    r3        str,  \ push r3
12953:    next,
12954: end-code
12955: @end example
12956: 
12957: Look at @file{arch/arm/asm-example.fs} for more examples.
12958: 
12959: @node Other assemblers,  , ARM Assembler, Assembler and Code Words
12960: @subsection Other assemblers
12961: 
12962: If you want to contribute another assembler/disassembler, please contact
12963: us (@email{anton@@mips.complang.tuwien.ac.at}) to check if we have such
12964: an assembler already.  If you are writing them from scratch, please use
12965: a similar syntax style as the one we use (i.e., postfix, commas at the
12966: end of the instruction names, @pxref{Common Assembler}); make the output
12967: of the disassembler be valid input for the assembler, and keep the style
12968: similar to the style we used.
12969: 
12970: Hints on implementation: The most important part is to have a good test
12971: suite that contains all instructions.  Once you have that, the rest is
12972: easy.  For actual coding you can take a look at
12973: @file{arch/mips/disasm.fs} to get some ideas on how to use data for both
12974: the assembler and disassembler, avoiding redundancy and some potential
12975: bugs.  You can also look at that file (and @pxref{Advanced does> usage
12976: example}) to get ideas how to factor a disassembler.
12977: 
12978: Start with the disassembler, because it's easier to reuse data from the
12979: disassembler for the assembler than the other way round.
12980: 
12981: For the assembler, take a look at @file{arch/alpha/asm.fs}, which shows
12982: how simple it can be.
12983: 
12984: 
12985: 
12986: 
12987: @c -------------------------------------------------------------
12988: @node Threading Words, Passing Commands to the OS, Assembler and Code Words, Words
12989: @section Threading Words
12990: @cindex threading words
12991: 
12992: @cindex code address
12993: These words provide access to code addresses and other threading stuff
12994: in Gforth (and, possibly, other interpretive Forths). It more or less
12995: abstracts away the differences between direct and indirect threading
12996: (and, for direct threading, the machine dependences). However, at
12997: present this wordset is still incomplete. It is also pretty low-level;
12998: some day it will hopefully be made unnecessary by an internals wordset
12999: that abstracts implementation details away completely.
13000: 
13001: The terminology used here stems from indirect threaded Forth systems; in
13002: such a system, the XT of a word is represented by the CFA (code field
13003: address) of a word; the CFA points to a cell that contains the code
13004: address.  The code address is the address of some machine code that
13005: performs the run-time action of invoking the word (e.g., the
13006: @code{dovar:} routine pushes the address of the body of the word (a
13007: variable) on the stack
13008: ).
13009: 
13010: @cindex code address
13011: @cindex code field address
13012: In an indirect threaded Forth, you can get the code address of @i{name}
13013: with @code{' @i{name} @@}; in Gforth you can get it with @code{' @i{name}
13014: >code-address}, independent of the threading method.
13015: 
13016: doc-threading-method
13017: doc->code-address
13018: doc-code-address!
13019: 
13020: @cindex @code{does>}-handler
13021: @cindex @code{does>}-code
13022: For a word defined with @code{DOES>}, the code address usually points to
13023: a jump instruction (the @dfn{does-handler}) that jumps to the dodoes
13024: routine (in Gforth on some platforms, it can also point to the dodoes
13025: routine itself).  What you are typically interested in, though, is
13026: whether a word is a @code{DOES>}-defined word, and what Forth code it
13027: executes; @code{>does-code} tells you that.
13028: 
13029: doc->does-code
13030: 
13031: To create a @code{DOES>}-defined word with the following basic words,
13032: you have to set up a @code{DOES>}-handler with @code{does-handler!};
13033: @code{/does-handler} aus behind you have to place your executable Forth
13034: code.  Finally you have to create a word and modify its behaviour with
13035: @code{does-handler!}.
13036: 
13037: doc-does-code!
13038: doc-does-handler!
13039: doc-/does-handler
13040: 
13041: The code addresses produced by various defining words are produced by
13042: the following words:
13043: 
13044: doc-docol:
13045: doc-docon:
13046: doc-dovar:
13047: doc-douser:
13048: doc-dodefer:
13049: doc-dofield:
13050: 
13051: @cindex definer
13052: The following two words generalize @code{>code-address},
13053: @code{>does-code}, @code{code-address!}, and @code{does-code!}:
13054: 
13055: doc->definer
13056: doc-definer!
13057: 
13058: @c -------------------------------------------------------------
13059: @node Passing Commands to the OS, Keeping track of Time, Threading Words, Words
13060: @section Passing Commands to the Operating System
13061: @cindex operating system - passing commands
13062: @cindex shell commands
13063: 
13064: Gforth allows you to pass an arbitrary string to the host operating
13065: system shell (if such a thing exists) for execution.
13066: 
13067: doc-sh
13068: doc-system
13069: doc-$?
13070: doc-getenv
13071: 
13072: @c -------------------------------------------------------------
13073: @node Keeping track of Time, Miscellaneous Words, Passing Commands to the OS, Words
13074: @section Keeping track of Time
13075: @cindex time-related words
13076: 
13077: doc-ms
13078: doc-time&date
13079: doc-utime
13080: doc-cputime
13081: 
13082: 
13083: @c -------------------------------------------------------------
13084: @node Miscellaneous Words,  , Keeping track of Time, Words
13085: @section Miscellaneous Words
13086: @cindex miscellaneous words
13087: 
13088: @comment TODO find homes for these
13089: 
13090: These section lists the ANS Forth words that are not documented
13091: elsewhere in this manual. Ultimately, they all need proper homes.
13092: 
13093: doc-quit
13094: 
13095: The following ANS Forth words are not currently supported by Gforth 
13096: (@pxref{ANS conformance}):
13097: 
13098: @code{EDITOR} 
13099: @code{EMIT?} 
13100: @code{FORGET} 
13101: 
13102: @c ******************************************************************
13103: @node Error messages, Tools, Words, Top
13104: @chapter Error messages
13105: @cindex error messages
13106: @cindex backtrace
13107: 
13108: A typical Gforth error message looks like this:
13109: 
13110: @example
13111: in file included from \evaluated string/:-1
13112: in file included from ./yyy.fs:1
13113: ./xxx.fs:4: Invalid memory address
13114: >>>bar<<<
13115: Backtrace:
13116: $400E664C @@
13117: $400E6664 foo
13118: @end example
13119: 
13120: The message identifying the error is @code{Invalid memory address}.  The
13121: error happened when text-interpreting line 4 of the file
13122: @file{./xxx.fs}. This line is given (it contains @code{bar}), and the
13123: word on the line where the error happened, is pointed out (with
13124: @code{>>>} and @code{<<<}).
13125: 
13126: The file containing the error was included in line 1 of @file{./yyy.fs},
13127: and @file{yyy.fs} was included from a non-file (in this case, by giving
13128: @file{yyy.fs} as command-line parameter to Gforth).
13129: 
13130: At the end of the error message you find a return stack dump that can be
13131: interpreted as a backtrace (possibly empty). On top you find the top of
13132: the return stack when the @code{throw} happened, and at the bottom you
13133: find the return stack entry just above the return stack of the topmost
13134: text interpreter.
13135: 
13136: To the right of most return stack entries you see a guess for the word
13137: that pushed that return stack entry as its return address. This gives a
13138: backtrace. In our case we see that @code{bar} called @code{foo}, and
13139: @code{foo} called @code{@@} (and @code{@@} had an @emph{Invalid memory
13140: address} exception).
13141: 
13142: Note that the backtrace is not perfect: We don't know which return stack
13143: entries are return addresses (so we may get false positives); and in
13144: some cases (e.g., for @code{abort"}) we cannot determine from the return
13145: address the word that pushed the return address, so for some return
13146: addresses you see no names in the return stack dump.
13147: 
13148: @cindex @code{catch} and backtraces
13149: The return stack dump represents the return stack at the time when a
13150: specific @code{throw} was executed.  In programs that make use of
13151: @code{catch}, it is not necessarily clear which @code{throw} should be
13152: used for the return stack dump (e.g., consider one @code{throw} that
13153: indicates an error, which is caught, and during recovery another error
13154: happens; which @code{throw} should be used for the stack dump?).
13155: Gforth presents the return stack dump for the first @code{throw} after
13156: the last executed (not returned-to) @code{catch} or @code{nothrow};
13157: this works well in the usual case. To get the right backtrace, you
13158: usually want to insert @code{nothrow} or @code{['] false catch drop}
13159: after a @code{catch} if the error is not rethrown.
13160: 
13161: @cindex @code{gforth-fast} and backtraces
13162: @cindex @code{gforth-fast}, difference from @code{gforth}
13163: @cindex backtraces with @code{gforth-fast}
13164: @cindex return stack dump with @code{gforth-fast}
13165: @code{Gforth} is able to do a return stack dump for throws generated
13166: from primitives (e.g., invalid memory address, stack empty etc.);
13167: @code{gforth-fast} is only able to do a return stack dump from a
13168: directly called @code{throw} (including @code{abort} etc.).  Given an
13169: exception caused by a primitive in @code{gforth-fast}, you will
13170: typically see no return stack dump at all; however, if the exception is
13171: caught by @code{catch} (e.g., for restoring some state), and then
13172: @code{throw}n again, the return stack dump will be for the first such
13173: @code{throw}.
13174: 
13175: @c ******************************************************************
13176: @node Tools, ANS conformance, Error messages, Top
13177: @chapter Tools
13178: 
13179: @menu
13180: * ANS Report::                  Report the words used, sorted by wordset.
13181: * Stack depth changes::         Where does this stack item come from?
13182: @end menu
13183: 
13184: See also @ref{Emacs and Gforth}.
13185: 
13186: @node ANS Report, Stack depth changes, Tools, Tools
13187: @section @file{ans-report.fs}: Report the words used, sorted by wordset
13188: @cindex @file{ans-report.fs}
13189: @cindex report the words used in your program
13190: @cindex words used in your program
13191: 
13192: If you want to label a Forth program as ANS Forth Program, you must
13193: document which wordsets the program uses; for extension wordsets, it is
13194: helpful to list the words the program requires from these wordsets
13195: (because Forth systems are allowed to provide only some words of them).
13196: 
13197: The @file{ans-report.fs} tool makes it easy for you to determine which
13198: words from which wordset and which non-ANS words your application
13199: uses. You simply have to include @file{ans-report.fs} before loading the
13200: program you want to check. After loading your program, you can get the
13201: report with @code{print-ans-report}. A typical use is to run this as
13202: batch job like this:
13203: @example
13204: gforth ans-report.fs myprog.fs -e "print-ans-report bye"
13205: @end example
13206: 
13207: The output looks like this (for @file{compat/control.fs}):
13208: @example
13209: The program uses the following words
13210: from CORE :
13211: : POSTPONE THEN ; immediate ?dup IF 0= 
13212: from BLOCK-EXT :
13213: \ 
13214: from FILE :
13215: ( 
13216: @end example
13217: 
13218: @subsection Caveats
13219: 
13220: Note that @file{ans-report.fs} just checks which words are used, not whether
13221: they are used in an ANS Forth conforming way!
13222: 
13223: Some words are defined in several wordsets in the
13224: standard. @file{ans-report.fs} reports them for only one of the
13225: wordsets, and not necessarily the one you expect. It depends on usage
13226: which wordset is the right one to specify. E.g., if you only use the
13227: compilation semantics of @code{S"}, it is a Core word; if you also use
13228: its interpretation semantics, it is a File word.
13229: 
13230: 
13231: @node Stack depth changes,  , ANS Report, Tools
13232: @section Stack depth changes during interpretation
13233: @cindex @file{depth-changes.fs}
13234: @cindex depth changes during interpretation
13235: @cindex stack depth changes during interpretation
13236: @cindex items on the stack after interpretation
13237: 
13238: Sometimes you notice that, after loading a file, there are items left
13239: on the stack.  The tool @file{depth-changes.fs} helps you find out
13240: quickly where in the file these stack items are coming from.
13241: 
13242: The simplest way of using @file{depth-changes.fs} is to include it
13243: before the file(s) you want to check, e.g.:
13244: 
13245: @example
13246: gforth depth-changes.fs my-file.fs
13247: @end example
13248: 
13249: This will compare the stack depths of the data and FP stack at every
13250: empty line (in interpretation state) against these depths at the last
13251: empty line (in interpretation state).  If the depths are not equal,
13252: the position in the file and the stack contents are printed with
13253: @code{~~} (@pxref{Debugging}).  This indicates that a stack depth
13254: change has occured in the paragraph of non-empty lines before the
13255: indicated line.  It is a good idea to leave an empty line at the end
13256: of the file, so the last paragraph is checked, too.
13257: 
13258: Checking only at empty lines usually works well, but sometimes you
13259: have big blocks of non-empty lines (e.g., when building a big table),
13260: and you want to know where in this block the stack depth changed.  You
13261: can check all interpreted lines with
13262: 
13263: @example
13264: gforth depth-changes.fs -e "' all-lines is depth-changes-filter" my-file.fs
13265: @end example
13266: 
13267: This checks the stack depth at every end-of-line.  So the depth change
13268: occured in the line reported by the @code{~~} (not in the line
13269: before).
13270: 
13271: Note that, while this offers better accuracy in indicating where the
13272: stack depth changes, it will often report many intentional stack depth
13273: changes (e.g., when an interpreted computation stretches across
13274: several lines).  You can suppress the checking of some lines by
13275: putting backslashes at the end of these lines (not followed by white
13276: space), and using
13277: 
13278: @example
13279: gforth depth-changes.fs -e "' most-lines is depth-changes-filter" my-file.fs
13280: @end example
13281: 
13282: @c ******************************************************************
13283: @node ANS conformance, Standard vs Extensions, Tools, Top
13284: @chapter ANS conformance
13285: @cindex ANS conformance of Gforth
13286: 
13287: To the best of our knowledge, Gforth is an
13288: 
13289: ANS Forth System
13290: @itemize @bullet
13291: @item providing the Core Extensions word set
13292: @item providing the Block word set
13293: @item providing the Block Extensions word set
13294: @item providing the Double-Number word set
13295: @item providing the Double-Number Extensions word set
13296: @item providing the Exception word set
13297: @item providing the Exception Extensions word set
13298: @item providing the Facility word set
13299: @item providing @code{EKEY}, @code{EKEY>CHAR}, @code{EKEY?}, @code{MS} and @code{TIME&DATE} from the Facility Extensions word set
13300: @item providing the File Access word set
13301: @item providing the File Access Extensions word set
13302: @item providing the Floating-Point word set
13303: @item providing the Floating-Point Extensions word set
13304: @item providing the Locals word set
13305: @item providing the Locals Extensions word set
13306: @item providing the Memory-Allocation word set
13307: @item providing the Memory-Allocation Extensions word set (that one's easy)
13308: @item providing the Programming-Tools word set
13309: @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
13310: @item providing the Search-Order word set
13311: @item providing the Search-Order Extensions word set
13312: @item providing the String word set
13313: @item providing the String Extensions word set (another easy one)
13314: @end itemize
13315: 
13316: Gforth has the following environmental restrictions:
13317: 
13318: @cindex environmental restrictions
13319: @itemize @bullet
13320: @item
13321: While processing the OS command line, if an exception is not caught,
13322: Gforth exits with a non-zero exit code instyead of performing QUIT.
13323: 
13324: @item
13325: When an @code{throw} is performed after a @code{query}, Gforth does not
13326: allways restore the input source specification in effect at the
13327: corresponding catch.
13328: 
13329: @end itemize
13330: 
13331: 
13332: @cindex system documentation
13333: In addition, ANS Forth systems are required to document certain
13334: implementation choices. This chapter tries to meet these
13335: requirements. In many cases it gives a way to ask the system for the
13336: information instead of providing the information directly, in
13337: particular, if the information depends on the processor, the operating
13338: system or the installation options chosen, or if they are likely to
13339: change during the maintenance of Gforth.
13340: 
13341: @comment The framework for the rest has been taken from pfe.
13342: 
13343: @menu
13344: * The Core Words::              
13345: * The optional Block word set::  
13346: * The optional Double Number word set::  
13347: * The optional Exception word set::  
13348: * The optional Facility word set::  
13349: * The optional File-Access word set::  
13350: * The optional Floating-Point word set::  
13351: * The optional Locals word set::  
13352: * The optional Memory-Allocation word set::  
13353: * The optional Programming-Tools word set::  
13354: * The optional Search-Order word set::  
13355: @end menu
13356: 
13357: 
13358: @c =====================================================================
13359: @node The Core Words, The optional Block word set, ANS conformance, ANS conformance
13360: @comment  node-name,  next,  previous,  up
13361: @section The Core Words
13362: @c =====================================================================
13363: @cindex core words, system documentation
13364: @cindex system documentation, core words
13365: 
13366: @menu
13367: * core-idef::                   Implementation Defined Options                   
13368: * core-ambcond::                Ambiguous Conditions                
13369: * core-other::                  Other System Documentation                  
13370: @end menu
13371: 
13372: @c ---------------------------------------------------------------------
13373: @node core-idef, core-ambcond, The Core Words, The Core Words
13374: @subsection Implementation Defined Options
13375: @c ---------------------------------------------------------------------
13376: @cindex core words, implementation-defined options
13377: @cindex implementation-defined options, core words
13378: 
13379: 
13380: @table @i
13381: @item (Cell) aligned addresses:
13382: @cindex cell-aligned addresses
13383: @cindex aligned addresses
13384: processor-dependent. Gforth's alignment words perform natural alignment
13385: (e.g., an address aligned for a datum of size 8 is divisible by
13386: 8). Unaligned accesses usually result in a @code{-23 THROW}.
13387: 
13388: @item @code{EMIT} and non-graphic characters:
13389: @cindex @code{EMIT} and non-graphic characters
13390: @cindex non-graphic characters and @code{EMIT}
13391: The character is output using the C library function (actually, macro)
13392: @code{putc}.
13393: 
13394: @item character editing of @code{ACCEPT} and @code{EXPECT}:
13395: @cindex character editing of @code{ACCEPT} and @code{EXPECT}
13396: @cindex editing in @code{ACCEPT} and @code{EXPECT}
13397: @cindex @code{ACCEPT}, editing
13398: @cindex @code{EXPECT}, editing
13399: This is modeled on the GNU readline library (@pxref{Readline
13400: Interaction, , Command Line Editing, readline, The GNU Readline
13401: Library}) with Emacs-like key bindings. @kbd{Tab} deviates a little by
13402: producing a full word completion every time you type it (instead of
13403: producing the common prefix of all completions). @xref{Command-line editing}.
13404: 
13405: @item character set:
13406: @cindex character set
13407: The character set of your computer and display device. Gforth is
13408: 8-bit-clean (but some other component in your system may make trouble).
13409: 
13410: @item Character-aligned address requirements:
13411: @cindex character-aligned address requirements
13412: installation-dependent. Currently a character is represented by a C
13413: @code{unsigned char}; in the future we might switch to @code{wchar_t}
13414: (Comments on that requested).
13415: 
13416: @item character-set extensions and matching of names:
13417: @cindex character-set extensions and matching of names
13418: @cindex case-sensitivity for name lookup
13419: @cindex name lookup, case-sensitivity
13420: @cindex locale and case-sensitivity
13421: Any character except the ASCII NUL character can be used in a
13422: name. Matching is case-insensitive (except in @code{TABLE}s). The
13423: matching is performed using the C library function @code{strncasecmp}, whose
13424: function is probably influenced by the locale. E.g., the @code{C} locale
13425: does not know about accents and umlauts, so they are matched
13426: case-sensitively in that locale. For portability reasons it is best to
13427: write programs such that they work in the @code{C} locale. Then one can
13428: use libraries written by a Polish programmer (who might use words
13429: containing ISO Latin-2 encoded characters) and by a French programmer
13430: (ISO Latin-1) in the same program (of course, @code{WORDS} will produce
13431: funny results for some of the words (which ones, depends on the font you
13432: are using)). Also, the locale you prefer may not be available in other
13433: operating systems. Hopefully, Unicode will solve these problems one day.
13434: 
13435: @item conditions under which control characters match a space delimiter:
13436: @cindex space delimiters
13437: @cindex control characters as delimiters
13438: If @code{word} is called with the space character as a delimiter, all
13439: white-space characters (as identified by the C macro @code{isspace()})
13440: are delimiters. @code{Parse}, on the other hand, treats space like other
13441: delimiters.  @code{Parse-name}, which is used by the outer
13442: interpreter (aka text interpreter) by default, treats all white-space
13443: characters as delimiters.
13444: 
13445: @item format of the control-flow stack:
13446: @cindex control-flow stack, format
13447: The data stack is used as control-flow stack. The size of a control-flow
13448: stack item in cells is given by the constant @code{cs-item-size}. At the
13449: time of this writing, an item consists of a (pointer to a) locals list
13450: (third), an address in the code (second), and a tag for identifying the
13451: item (TOS). The following tags are used: @code{defstart},
13452: @code{live-orig}, @code{dead-orig}, @code{dest}, @code{do-dest},
13453: @code{scopestart}.
13454: 
13455: @item conversion of digits > 35
13456: @cindex digits > 35
13457: The characters @code{[\]^_'} are the digits with the decimal value
13458: 36@minus{}41. There is no way to input many of the larger digits.
13459: 
13460: @item display after input terminates in @code{ACCEPT} and @code{EXPECT}:
13461: @cindex @code{EXPECT}, display after end of input
13462: @cindex @code{ACCEPT}, display after end of input
13463: The cursor is moved to the end of the entered string. If the input is
13464: terminated using the @kbd{Return} key, a space is typed.
13465: 
13466: @item exception abort sequence of @code{ABORT"}:
13467: @cindex exception abort sequence of @code{ABORT"}
13468: @cindex @code{ABORT"}, exception abort sequence
13469: The error string is stored into the variable @code{"error} and a
13470: @code{-2 throw} is performed.
13471: 
13472: @item input line terminator:
13473: @cindex input line terminator
13474: @cindex line terminator on input
13475: @cindex newline character on input
13476: For interactive input, @kbd{C-m} (CR) and @kbd{C-j} (LF) terminate
13477: lines. One of these characters is typically produced when you type the
13478: @kbd{Enter} or @kbd{Return} key.
13479: 
13480: @item maximum size of a counted string:
13481: @cindex maximum size of a counted string
13482: @cindex counted string, maximum size
13483: @code{s" /counted-string" environment? drop .}. Currently 255 characters
13484: on all platforms, but this may change.
13485: 
13486: @item maximum size of a parsed string:
13487: @cindex maximum size of a parsed string
13488: @cindex parsed string, maximum size
13489: Given by the constant @code{/line}. Currently 255 characters.
13490: 
13491: @item maximum size of a definition name, in characters:
13492: @cindex maximum size of a definition name, in characters
13493: @cindex name, maximum length
13494: MAXU/8
13495: 
13496: @item maximum string length for @code{ENVIRONMENT?}, in characters:
13497: @cindex maximum string length for @code{ENVIRONMENT?}, in characters
13498: @cindex @code{ENVIRONMENT?} string length, maximum
13499: MAXU/8
13500: 
13501: @item method of selecting the user input device:
13502: @cindex user input device, method of selecting
13503: The user input device is the standard input. There is currently no way to
13504: change it from within Gforth. However, the input can typically be
13505: redirected in the command line that starts Gforth.
13506: 
13507: @item method of selecting the user output device:
13508: @cindex user output device, method of selecting
13509: @code{EMIT} and @code{TYPE} output to the file-id stored in the value
13510: @code{outfile-id} (@code{stdout} by default). Gforth uses unbuffered
13511: output when the user output device is a terminal, otherwise the output
13512: is buffered.
13513: 
13514: @item methods of dictionary compilation:
13515: What are we expected to document here?
13516: 
13517: @item number of bits in one address unit:
13518: @cindex number of bits in one address unit
13519: @cindex address unit, size in bits
13520: @code{s" address-units-bits" environment? drop .}. 8 in all current
13521: platforms.
13522: 
13523: @item number representation and arithmetic:
13524: @cindex number representation and arithmetic
13525: Processor-dependent. Binary two's complement on all current platforms.
13526: 
13527: @item ranges for integer types:
13528: @cindex ranges for integer types
13529: @cindex integer types, ranges
13530: Installation-dependent. Make environmental queries for @code{MAX-N},
13531: @code{MAX-U}, @code{MAX-D} and @code{MAX-UD}. The lower bounds for
13532: unsigned (and positive) types is 0. The lower bound for signed types on
13533: two's complement and one's complement machines machines can be computed
13534: by adding 1 to the upper bound.
13535: 
13536: @item read-only data space regions:
13537: @cindex read-only data space regions
13538: @cindex data-space, read-only regions
13539: The whole Forth data space is writable.
13540: 
13541: @item size of buffer at @code{WORD}:
13542: @cindex size of buffer at @code{WORD}
13543: @cindex @code{WORD} buffer size
13544: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
13545: shared with the pictured numeric output string. If overwriting
13546: @code{PAD} is acceptable, it is as large as the remaining dictionary
13547: space, although only as much can be sensibly used as fits in a counted
13548: string.
13549: 
13550: @item size of one cell in address units:
13551: @cindex cell size
13552: @code{1 cells .}.
13553: 
13554: @item size of one character in address units:
13555: @cindex char size
13556: @code{1 chars .}. 1 on all current platforms.
13557: 
13558: @item size of the keyboard terminal buffer:
13559: @cindex size of the keyboard terminal buffer
13560: @cindex terminal buffer, size
13561: Varies. You can determine the size at a specific time using @code{lp@@
13562: tib - .}. It is shared with the locals stack and TIBs of files that
13563: include the current file. You can change the amount of space for TIBs
13564: and locals stack at Gforth startup with the command line option
13565: @code{-l}.
13566: 
13567: @item size of the pictured numeric output buffer:
13568: @cindex size of the pictured numeric output buffer
13569: @cindex pictured numeric output buffer, size
13570: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
13571: shared with @code{WORD}.
13572: 
13573: @item size of the scratch area returned by @code{PAD}:
13574: @cindex size of the scratch area returned by @code{PAD}
13575: @cindex @code{PAD} size
13576: The remainder of dictionary space. @code{unused pad here - - .}.
13577: 
13578: @item system case-sensitivity characteristics:
13579: @cindex case-sensitivity characteristics
13580: Dictionary searches are case-insensitive (except in
13581: @code{TABLE}s). However, as explained above under @i{character-set
13582: extensions}, the matching for non-ASCII characters is determined by the
13583: locale you are using. In the default @code{C} locale all non-ASCII
13584: characters are matched case-sensitively.
13585: 
13586: @item system prompt:
13587: @cindex system prompt
13588: @cindex prompt
13589: @code{ ok} in interpret state, @code{ compiled} in compile state.
13590: 
13591: @item division rounding:
13592: @cindex division rounding
13593: The ordinary division words @code{/ mod /mod */ */mod} perform floored
13594: division (with the default installation of Gforth).  You can check
13595: this with @code{s" floored" environment? drop .}.  If you write
13596: programs that need a specific division rounding, best use
13597: @code{fm/mod} or @code{sm/rem} for portability.
13598: 
13599: @item values of @code{STATE} when true:
13600: @cindex @code{STATE} values
13601: -1.
13602: 
13603: @item values returned after arithmetic overflow:
13604: On two's complement machines, arithmetic is performed modulo
13605: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
13606: arithmetic (with appropriate mapping for signed types). Division by
13607: zero typically results in a @code{-55 throw} (Floating-point
13608: unidentified fault) or @code{-10 throw} (divide by zero).  Integer
13609: division overflow can result in these throws, or in @code{-11 throw};
13610: in @code{gforth-fast} division overflow and divide by zero may also
13611: result in returning bogus results without producing an exception.
13612: 
13613: @item whether the current definition can be found after @t{DOES>}:
13614: @cindex @t{DOES>}, visibility of current definition
13615: No.
13616: 
13617: @end table
13618: 
13619: @c ---------------------------------------------------------------------
13620: @node core-ambcond, core-other, core-idef, The Core Words
13621: @subsection Ambiguous conditions
13622: @c ---------------------------------------------------------------------
13623: @cindex core words, ambiguous conditions
13624: @cindex ambiguous conditions, core words
13625: 
13626: @table @i
13627: 
13628: @item a name is neither a word nor a number:
13629: @cindex name not found
13630: @cindex undefined word
13631: @code{-13 throw} (Undefined word).
13632: 
13633: @item a definition name exceeds the maximum length allowed:
13634: @cindex word name too long
13635: @code{-19 throw} (Word name too long)
13636: 
13637: @item addressing a region not inside the various data spaces of the forth system:
13638: @cindex Invalid memory address
13639: The stacks, code space and header space are accessible. Machine code space is
13640: typically readable. Accessing other addresses gives results dependent on
13641: the operating system. On decent systems: @code{-9 throw} (Invalid memory
13642: address).
13643: 
13644: @item argument type incompatible with parameter:
13645: @cindex argument type mismatch
13646: This is usually not caught. Some words perform checks, e.g., the control
13647: flow words, and issue a @code{ABORT"} or @code{-12 THROW} (Argument type
13648: mismatch).
13649: 
13650: @item attempting to obtain the execution token of a word with undefined execution semantics:
13651: @cindex Interpreting a compile-only word, for @code{'} etc.
13652: @cindex execution token of words with undefined execution semantics
13653: @code{-14 throw} (Interpreting a compile-only word). In some cases, you
13654: get an execution token for @code{compile-only-error} (which performs a
13655: @code{-14 throw} when executed).
13656: 
13657: @item dividing by zero:
13658: @cindex dividing by zero
13659: @cindex floating point unidentified fault, integer division
13660: On some platforms, this produces a @code{-10 throw} (Division by
13661: zero); on other systems, this typically results in a @code{-55 throw}
13662: (Floating-point unidentified fault).
13663: 
13664: @item insufficient data stack or return stack space:
13665: @cindex insufficient data stack or return stack space
13666: @cindex stack overflow
13667: @cindex address alignment exception, stack overflow
13668: @cindex Invalid memory address, stack overflow
13669: Depending on the operating system, the installation, and the invocation
13670: of Gforth, this is either checked by the memory management hardware, or
13671: it is not checked. If it is checked, you typically get a @code{-3 throw}
13672: (Stack overflow), @code{-5 throw} (Return stack overflow), or @code{-9
13673: throw} (Invalid memory address) (depending on the platform and how you
13674: achieved the overflow) as soon as the overflow happens. If it is not
13675: checked, overflows typically result in mysterious illegal memory
13676: accesses, producing @code{-9 throw} (Invalid memory address) or
13677: @code{-23 throw} (Address alignment exception); they might also destroy
13678: the internal data structure of @code{ALLOCATE} and friends, resulting in
13679: various errors in these words.
13680: 
13681: @item insufficient space for loop control parameters:
13682: @cindex insufficient space for loop control parameters
13683: Like other return stack overflows.
13684: 
13685: @item insufficient space in the dictionary:
13686: @cindex insufficient space in the dictionary
13687: @cindex dictionary overflow
13688: If you try to allot (either directly with @code{allot}, or indirectly
13689: with @code{,}, @code{create} etc.) more memory than available in the
13690: dictionary, you get a @code{-8 throw} (Dictionary overflow). If you try
13691: to access memory beyond the end of the dictionary, the results are
13692: similar to stack overflows.
13693: 
13694: @item interpreting a word with undefined interpretation semantics:
13695: @cindex interpreting a word with undefined interpretation semantics
13696: @cindex Interpreting a compile-only word
13697: For some words, we have defined interpretation semantics. For the
13698: others: @code{-14 throw} (Interpreting a compile-only word).
13699: 
13700: @item modifying the contents of the input buffer or a string literal:
13701: @cindex modifying the contents of the input buffer or a string literal
13702: These are located in writable memory and can be modified.
13703: 
13704: @item overflow of the pictured numeric output string:
13705: @cindex overflow of the pictured numeric output string
13706: @cindex pictured numeric output string, overflow
13707: @code{-17 throw} (Pictured numeric ouput string overflow).
13708: 
13709: @item parsed string overflow:
13710: @cindex parsed string overflow
13711: @code{PARSE} cannot overflow. @code{WORD} does not check for overflow.
13712: 
13713: @item producing a result out of range:
13714: @cindex result out of range
13715: On two's complement machines, arithmetic is performed modulo
13716: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
13717: arithmetic (with appropriate mapping for signed types). Division by
13718: zero typically results in a @code{-10 throw} (divide by zero) or
13719: @code{-55 throw} (floating point unidentified fault). Overflow on
13720: division may result in these errors or in @code{-11 throw} (result out
13721: of range).  @code{Gforth-fast} may silently produce bogus results on
13722: division overflow or division by zero.  @code{Convert} and
13723: @code{>number} currently overflow silently.
13724: 
13725: @item reading from an empty data or return stack:
13726: @cindex stack empty
13727: @cindex stack underflow
13728: @cindex return stack underflow
13729: The data stack is checked by the outer (aka text) interpreter after
13730: every word executed. If it has underflowed, a @code{-4 throw} (Stack
13731: underflow) is performed. Apart from that, stacks may be checked or not,
13732: depending on operating system, installation, and invocation. If they are
13733: caught by a check, they typically result in @code{-4 throw} (Stack
13734: underflow), @code{-6 throw} (Return stack underflow) or @code{-9 throw}
13735: (Invalid memory address), depending on the platform and which stack
13736: underflows and by how much. Note that even if the system uses checking
13737: (through the MMU), your program may have to underflow by a significant
13738: number of stack items to trigger the reaction (the reason for this is
13739: that the MMU, and therefore the checking, works with a page-size
13740: granularity).  If there is no checking, the symptoms resulting from an
13741: underflow are similar to those from an overflow.  Unbalanced return
13742: stack errors can result in a variety of symptoms, including @code{-9 throw}
13743: (Invalid memory address) and Illegal Instruction (typically @code{-260
13744: throw}).
13745: 
13746: @item unexpected end of the input buffer, resulting in an attempt to use a zero-length string as a name:
13747: @cindex unexpected end of the input buffer
13748: @cindex zero-length string as a name
13749: @cindex Attempt to use zero-length string as a name
13750: @code{Create} and its descendants perform a @code{-16 throw} (Attempt to
13751: use zero-length string as a name). Words like @code{'} probably will not
13752: find what they search. Note that it is possible to create zero-length
13753: names with @code{nextname} (should it not?).
13754: 
13755: @item @code{>IN} greater than input buffer:
13756: @cindex @code{>IN} greater than input buffer
13757: The next invocation of a parsing word returns a string with length 0.
13758: 
13759: @item @code{RECURSE} appears after @code{DOES>}:
13760: @cindex @code{RECURSE} appears after @code{DOES>}
13761: Compiles a recursive call to the defining word, not to the defined word.
13762: 
13763: @item argument input source different than current input source for @code{RESTORE-INPUT}:
13764: @cindex argument input source different than current input source for @code{RESTORE-INPUT}
13765: @cindex argument type mismatch, @code{RESTORE-INPUT}
13766: @cindex @code{RESTORE-INPUT}, Argument type mismatch
13767: @code{-12 THROW}. Note that, once an input file is closed (e.g., because
13768: the end of the file was reached), its source-id may be
13769: reused. Therefore, restoring an input source specification referencing a
13770: closed file may lead to unpredictable results instead of a @code{-12
13771: THROW}.
13772: 
13773: In the future, Gforth may be able to restore input source specifications
13774: from other than the current input source.
13775: 
13776: @item data space containing definitions gets de-allocated:
13777: @cindex data space containing definitions gets de-allocated
13778: Deallocation with @code{allot} is not checked. This typically results in
13779: memory access faults or execution of illegal instructions.
13780: 
13781: @item data space read/write with incorrect alignment:
13782: @cindex data space read/write with incorrect alignment
13783: @cindex alignment faults
13784: @cindex address alignment exception
13785: Processor-dependent. Typically results in a @code{-23 throw} (Address
13786: alignment exception). Under Linux-Intel on a 486 or later processor with
13787: alignment turned on, incorrect alignment results in a @code{-9 throw}
13788: (Invalid memory address). There are reportedly some processors with
13789: alignment restrictions that do not report violations.
13790: 
13791: @item data space pointer not properly aligned, @code{,}, @code{C,}:
13792: @cindex data space pointer not properly aligned, @code{,}, @code{C,}
13793: Like other alignment errors.
13794: 
13795: @item less than u+2 stack items (@code{PICK} and @code{ROLL}):
13796: Like other stack underflows.
13797: 
13798: @item loop control parameters not available:
13799: @cindex loop control parameters not available
13800: Not checked. The counted loop words simply assume that the top of return
13801: stack items are loop control parameters and behave accordingly.
13802: 
13803: @item most recent definition does not have a name (@code{IMMEDIATE}):
13804: @cindex most recent definition does not have a name (@code{IMMEDIATE})
13805: @cindex last word was headerless
13806: @code{abort" last word was headerless"}.
13807: 
13808: @item name not defined by @code{VALUE} used by @code{TO}:
13809: @cindex name not defined by @code{VALUE} used by @code{TO}
13810: @cindex @code{TO} on non-@code{VALUE}s
13811: @cindex Invalid name argument, @code{TO}
13812: @code{-32 throw} (Invalid name argument) (unless name is a local or was
13813: defined by @code{CONSTANT}; in the latter case it just changes the constant).
13814: 
13815: @item name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}):
13816: @cindex name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]})
13817: @cindex undefined word, @code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}
13818: @code{-13 throw} (Undefined word)
13819: 
13820: @item parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN}):
13821: @cindex parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN})
13822: Gforth behaves as if they were of the same type. I.e., you can predict
13823: the behaviour by interpreting all parameters as, e.g., signed.
13824: 
13825: @item @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}:
13826: @cindex @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}
13827: Assume @code{: X POSTPONE TO ; IMMEDIATE}. @code{X} performs the
13828: compilation semantics of @code{TO}.
13829: 
13830: @item String longer than a counted string returned by @code{WORD}:
13831: @cindex string longer than a counted string returned by @code{WORD}
13832: @cindex @code{WORD}, string overflow
13833: Not checked. The string will be ok, but the count will, of course,
13834: contain only the least significant bits of the length.
13835: 
13836: @item u greater than or equal to the number of bits in a cell (@code{LSHIFT}, @code{RSHIFT}):
13837: @cindex @code{LSHIFT}, large shift counts
13838: @cindex @code{RSHIFT}, large shift counts
13839: Processor-dependent. Typical behaviours are returning 0 and using only
13840: the low bits of the shift count.
13841: 
13842: @item word not defined via @code{CREATE}:
13843: @cindex @code{>BODY} of non-@code{CREATE}d words
13844: @code{>BODY} produces the PFA of the word no matter how it was defined.
13845: 
13846: @cindex @code{DOES>} of non-@code{CREATE}d words
13847: @code{DOES>} changes the execution semantics of the last defined word no
13848: matter how it was defined. E.g., @code{CONSTANT DOES>} is equivalent to
13849: @code{CREATE , DOES>}.
13850: 
13851: @item words improperly used outside @code{<#} and @code{#>}:
13852: Not checked. As usual, you can expect memory faults.
13853: 
13854: @end table
13855: 
13856: 
13857: @c ---------------------------------------------------------------------
13858: @node core-other,  , core-ambcond, The Core Words
13859: @subsection Other system documentation
13860: @c ---------------------------------------------------------------------
13861: @cindex other system documentation, core words
13862: @cindex core words, other system documentation
13863: 
13864: @table @i
13865: @item nonstandard words using @code{PAD}:
13866: @cindex @code{PAD} use by nonstandard words
13867: None.
13868: 
13869: @item operator's terminal facilities available:
13870: @cindex operator's terminal facilities available
13871: After processing the OS's command line, Gforth goes into interactive mode,
13872: and you can give commands to Gforth interactively. The actual facilities
13873: available depend on how you invoke Gforth.
13874: 
13875: @item program data space available:
13876: @cindex program data space available
13877: @cindex data space available
13878: @code{UNUSED .} gives the remaining dictionary space. The total
13879: dictionary space can be specified with the @code{-m} switch
13880: (@pxref{Invoking Gforth}) when Gforth starts up.
13881: 
13882: @item return stack space available:
13883: @cindex return stack space available
13884: You can compute the total return stack space in cells with
13885: @code{s" RETURN-STACK-CELLS" environment? drop .}. You can specify it at
13886: startup time with the @code{-r} switch (@pxref{Invoking Gforth}).
13887: 
13888: @item stack space available:
13889: @cindex stack space available
13890: You can compute the total data stack space in cells with
13891: @code{s" STACK-CELLS" environment? drop .}. You can specify it at
13892: startup time with the @code{-d} switch (@pxref{Invoking Gforth}).
13893: 
13894: @item system dictionary space required, in address units:
13895: @cindex system dictionary space required, in address units
13896: Type @code{here forthstart - .} after startup. At the time of this
13897: writing, this gives 80080 (bytes) on a 32-bit system.
13898: @end table
13899: 
13900: 
13901: @c =====================================================================
13902: @node The optional Block word set, The optional Double Number word set, The Core Words, ANS conformance
13903: @section The optional Block word set
13904: @c =====================================================================
13905: @cindex system documentation, block words
13906: @cindex block words, system documentation
13907: 
13908: @menu
13909: * block-idef::                  Implementation Defined Options
13910: * block-ambcond::               Ambiguous Conditions               
13911: * block-other::                 Other System Documentation                 
13912: @end menu
13913: 
13914: 
13915: @c ---------------------------------------------------------------------
13916: @node block-idef, block-ambcond, The optional Block word set, The optional Block word set
13917: @subsection Implementation Defined Options
13918: @c ---------------------------------------------------------------------
13919: @cindex implementation-defined options, block words
13920: @cindex block words, implementation-defined options
13921: 
13922: @table @i
13923: @item the format for display by @code{LIST}:
13924: @cindex @code{LIST} display format
13925: First the screen number is displayed, then 16 lines of 64 characters,
13926: each line preceded by the line number.
13927: 
13928: @item the length of a line affected by @code{\}:
13929: @cindex length of a line affected by @code{\}
13930: @cindex @code{\}, line length in blocks
13931: 64 characters.
13932: @end table
13933: 
13934: 
13935: @c ---------------------------------------------------------------------
13936: @node block-ambcond, block-other, block-idef, The optional Block word set
13937: @subsection Ambiguous conditions
13938: @c ---------------------------------------------------------------------
13939: @cindex block words, ambiguous conditions
13940: @cindex ambiguous conditions, block words
13941: 
13942: @table @i
13943: @item correct block read was not possible:
13944: @cindex block read not possible
13945: Typically results in a @code{throw} of some OS-derived value (between
13946: -512 and -2048). If the blocks file was just not long enough, blanks are
13947: supplied for the missing portion.
13948: 
13949: @item I/O exception in block transfer:
13950: @cindex I/O exception in block transfer
13951: @cindex block transfer, I/O exception
13952: Typically results in a @code{throw} of some OS-derived value (between
13953: -512 and -2048).
13954: 
13955: @item invalid block number:
13956: @cindex invalid block number
13957: @cindex block number invalid
13958: @code{-35 throw} (Invalid block number)
13959: 
13960: @item a program directly alters the contents of @code{BLK}:
13961: @cindex @code{BLK}, altering @code{BLK}
13962: The input stream is switched to that other block, at the same
13963: position. If the storing to @code{BLK} happens when interpreting
13964: non-block input, the system will get quite confused when the block ends.
13965: 
13966: @item no current block buffer for @code{UPDATE}:
13967: @cindex @code{UPDATE}, no current block buffer
13968: @code{UPDATE} has no effect.
13969: 
13970: @end table
13971: 
13972: @c ---------------------------------------------------------------------
13973: @node block-other,  , block-ambcond, The optional Block word set
13974: @subsection Other system documentation
13975: @c ---------------------------------------------------------------------
13976: @cindex other system documentation, block words
13977: @cindex block words, other system documentation
13978: 
13979: @table @i
13980: @item any restrictions a multiprogramming system places on the use of buffer addresses:
13981: No restrictions (yet).
13982: 
13983: @item the number of blocks available for source and data:
13984: depends on your disk space.
13985: 
13986: @end table
13987: 
13988: 
13989: @c =====================================================================
13990: @node The optional Double Number word set, The optional Exception word set, The optional Block word set, ANS conformance
13991: @section The optional Double Number word set
13992: @c =====================================================================
13993: @cindex system documentation, double words
13994: @cindex double words, system documentation
13995: 
13996: @menu
13997: * double-ambcond::              Ambiguous Conditions              
13998: @end menu
13999: 
14000: 
14001: @c ---------------------------------------------------------------------
14002: @node double-ambcond,  , The optional Double Number word set, The optional Double Number word set
14003: @subsection Ambiguous conditions
14004: @c ---------------------------------------------------------------------
14005: @cindex double words, ambiguous conditions
14006: @cindex ambiguous conditions, double words
14007: 
14008: @table @i
14009: @item @i{d} outside of range of @i{n} in @code{D>S}:
14010: @cindex @code{D>S}, @i{d} out of range of @i{n} 
14011: The least significant cell of @i{d} is produced.
14012: 
14013: @end table
14014: 
14015: 
14016: @c =====================================================================
14017: @node The optional Exception word set, The optional Facility word set, The optional Double Number word set, ANS conformance
14018: @section The optional Exception word set
14019: @c =====================================================================
14020: @cindex system documentation, exception words
14021: @cindex exception words, system documentation
14022: 
14023: @menu
14024: * exception-idef::              Implementation Defined Options              
14025: @end menu
14026: 
14027: 
14028: @c ---------------------------------------------------------------------
14029: @node exception-idef,  , The optional Exception word set, The optional Exception word set
14030: @subsection Implementation Defined Options
14031: @c ---------------------------------------------------------------------
14032: @cindex implementation-defined options, exception words
14033: @cindex exception words, implementation-defined options
14034: 
14035: @table @i
14036: @item @code{THROW}-codes used in the system:
14037: @cindex @code{THROW}-codes used in the system
14038: The codes -256@minus{}-511 are used for reporting signals. The mapping
14039: from OS signal numbers to throw codes is -256@minus{}@i{signal}. The
14040: codes -512@minus{}-2047 are used for OS errors (for file and memory
14041: allocation operations). The mapping from OS error numbers to throw codes
14042: is -512@minus{}@code{errno}. One side effect of this mapping is that
14043: undefined OS errors produce a message with a strange number; e.g.,
14044: @code{-1000 THROW} results in @code{Unknown error 488} on my system.
14045: @end table
14046: 
14047: @c =====================================================================
14048: @node The optional Facility word set, The optional File-Access word set, The optional Exception word set, ANS conformance
14049: @section The optional Facility word set
14050: @c =====================================================================
14051: @cindex system documentation, facility words
14052: @cindex facility words, system documentation
14053: 
14054: @menu
14055: * facility-idef::               Implementation Defined Options               
14056: * facility-ambcond::            Ambiguous Conditions            
14057: @end menu
14058: 
14059: 
14060: @c ---------------------------------------------------------------------
14061: @node facility-idef, facility-ambcond, The optional Facility word set, The optional Facility word set
14062: @subsection Implementation Defined Options
14063: @c ---------------------------------------------------------------------
14064: @cindex implementation-defined options, facility words
14065: @cindex facility words, implementation-defined options
14066: 
14067: @table @i
14068: @item encoding of keyboard events (@code{EKEY}):
14069: @cindex keyboard events, encoding in @code{EKEY}
14070: @cindex @code{EKEY}, encoding of keyboard events
14071: Keys corresponding to ASCII characters are encoded as ASCII characters.
14072: Other keys are encoded with the constants @code{k-left}, @code{k-right},
14073: @code{k-up}, @code{k-down}, @code{k-home}, @code{k-end}, @code{k1},
14074: @code{k2}, @code{k3}, @code{k4}, @code{k5}, @code{k6}, @code{k7},
14075: @code{k8}, @code{k9}, @code{k10}, @code{k11}, @code{k12}.
14076: 
14077: 
14078: @item duration of a system clock tick:
14079: @cindex duration of a system clock tick
14080: @cindex clock tick duration
14081: System dependent. With respect to @code{MS}, the time is specified in
14082: microseconds. How well the OS and the hardware implement this, is
14083: another question.
14084: 
14085: @item repeatability to be expected from the execution of @code{MS}:
14086: @cindex repeatability to be expected from the execution of @code{MS}
14087: @cindex @code{MS}, repeatability to be expected
14088: System dependent. On Unix, a lot depends on load. If the system is
14089: lightly loaded, and the delay is short enough that Gforth does not get
14090: swapped out, the performance should be acceptable. Under MS-DOS and
14091: other single-tasking systems, it should be good.
14092: 
14093: @end table
14094: 
14095: 
14096: @c ---------------------------------------------------------------------
14097: @node facility-ambcond,  , facility-idef, The optional Facility word set
14098: @subsection Ambiguous conditions
14099: @c ---------------------------------------------------------------------
14100: @cindex facility words, ambiguous conditions
14101: @cindex ambiguous conditions, facility words
14102: 
14103: @table @i
14104: @item @code{AT-XY} can't be performed on user output device:
14105: @cindex @code{AT-XY} can't be performed on user output device
14106: Largely terminal dependent. No range checks are done on the arguments.
14107: No errors are reported. You may see some garbage appearing, you may see
14108: simply nothing happen.
14109: 
14110: @end table
14111: 
14112: 
14113: @c =====================================================================
14114: @node The optional File-Access word set, The optional Floating-Point word set, The optional Facility word set, ANS conformance
14115: @section The optional File-Access word set
14116: @c =====================================================================
14117: @cindex system documentation, file words
14118: @cindex file words, system documentation
14119: 
14120: @menu
14121: * file-idef::                   Implementation Defined Options
14122: * file-ambcond::                Ambiguous Conditions                
14123: @end menu
14124: 
14125: @c ---------------------------------------------------------------------
14126: @node file-idef, file-ambcond, The optional File-Access word set, The optional File-Access word set
14127: @subsection Implementation Defined Options
14128: @c ---------------------------------------------------------------------
14129: @cindex implementation-defined options, file words
14130: @cindex file words, implementation-defined options
14131: 
14132: @table @i
14133: @item file access methods used:
14134: @cindex file access methods used
14135: @code{R/O}, @code{R/W} and @code{BIN} work as you would
14136: expect. @code{W/O} translates into the C file opening mode @code{w} (or
14137: @code{wb}): The file is cleared, if it exists, and created, if it does
14138: not (with both @code{open-file} and @code{create-file}).  Under Unix
14139: @code{create-file} creates a file with 666 permissions modified by your
14140: umask.
14141: 
14142: @item file exceptions:
14143: @cindex file exceptions
14144: The file words do not raise exceptions (except, perhaps, memory access
14145: faults when you pass illegal addresses or file-ids).
14146: 
14147: @item file line terminator:
14148: @cindex file line terminator
14149: System-dependent. Gforth uses C's newline character as line
14150: terminator. What the actual character code(s) of this are is
14151: system-dependent.
14152: 
14153: @item file name format:
14154: @cindex file name format
14155: System dependent. Gforth just uses the file name format of your OS.
14156: 
14157: @item information returned by @code{FILE-STATUS}:
14158: @cindex @code{FILE-STATUS}, returned information
14159: @code{FILE-STATUS} returns the most powerful file access mode allowed
14160: for the file: Either @code{R/O}, @code{W/O} or @code{R/W}. If the file
14161: cannot be accessed, @code{R/O BIN} is returned. @code{BIN} is applicable
14162: along with the returned mode.
14163: 
14164: @item input file state after an exception when including source:
14165: @cindex exception when including source
14166: All files that are left via the exception are closed.
14167: 
14168: @item @i{ior} values and meaning:
14169: @cindex @i{ior} values and meaning
14170: @cindex @i{wior} values and meaning
14171: The @i{ior}s returned by the file and memory allocation words are
14172: intended as throw codes. They typically are in the range
14173: -512@minus{}-2047 of OS errors.  The mapping from OS error numbers to
14174: @i{ior}s is -512@minus{}@i{errno}.
14175: 
14176: @item maximum depth of file input nesting:
14177: @cindex maximum depth of file input nesting
14178: @cindex file input nesting, maximum depth
14179: limited by the amount of return stack, locals/TIB stack, and the number
14180: of open files available. This should not give you troubles.
14181: 
14182: @item maximum size of input line:
14183: @cindex maximum size of input line
14184: @cindex input line size, maximum
14185: @code{/line}. Currently 255.
14186: 
14187: @item methods of mapping block ranges to files:
14188: @cindex mapping block ranges to files
14189: @cindex files containing blocks
14190: @cindex blocks in files
14191: By default, blocks are accessed in the file @file{blocks.fb} in the
14192: current working directory. The file can be switched with @code{USE}.
14193: 
14194: @item number of string buffers provided by @code{S"}:
14195: @cindex @code{S"}, number of string buffers
14196: 1
14197: 
14198: @item size of string buffer used by @code{S"}:
14199: @cindex @code{S"}, size of string buffer
14200: @code{/line}. currently 255.
14201: 
14202: @end table
14203: 
14204: @c ---------------------------------------------------------------------
14205: @node file-ambcond,  , file-idef, The optional File-Access word set
14206: @subsection Ambiguous conditions
14207: @c ---------------------------------------------------------------------
14208: @cindex file words, ambiguous conditions
14209: @cindex ambiguous conditions, file words
14210: 
14211: @table @i
14212: @item attempting to position a file outside its boundaries:
14213: @cindex @code{REPOSITION-FILE}, outside the file's boundaries
14214: @code{REPOSITION-FILE} is performed as usual: Afterwards,
14215: @code{FILE-POSITION} returns the value given to @code{REPOSITION-FILE}.
14216: 
14217: @item attempting to read from file positions not yet written:
14218: @cindex reading from file positions not yet written
14219: End-of-file, i.e., zero characters are read and no error is reported.
14220: 
14221: @item @i{file-id} is invalid (@code{INCLUDE-FILE}):
14222: @cindex @code{INCLUDE-FILE}, @i{file-id} is invalid 
14223: An appropriate exception may be thrown, but a memory fault or other
14224: problem is more probable.
14225: 
14226: @item I/O exception reading or closing @i{file-id} (@code{INCLUDE-FILE}, @code{INCLUDED}):
14227: @cindex @code{INCLUDE-FILE}, I/O exception reading or closing @i{file-id}
14228: @cindex @code{INCLUDED}, I/O exception reading or closing @i{file-id}
14229: The @i{ior} produced by the operation, that discovered the problem, is
14230: thrown.
14231: 
14232: @item named file cannot be opened (@code{INCLUDED}):
14233: @cindex @code{INCLUDED}, named file cannot be opened
14234: The @i{ior} produced by @code{open-file} is thrown.
14235: 
14236: @item requesting an unmapped block number:
14237: @cindex unmapped block numbers
14238: There are no unmapped legal block numbers. On some operating systems,
14239: writing a block with a large number may overflow the file system and
14240: have an error message as consequence.
14241: 
14242: @item using @code{source-id} when @code{blk} is non-zero:
14243: @cindex @code{SOURCE-ID}, behaviour when @code{BLK} is non-zero
14244: @code{source-id} performs its function. Typically it will give the id of
14245: the source which loaded the block. (Better ideas?)
14246: 
14247: @end table
14248: 
14249: 
14250: @c =====================================================================
14251: @node  The optional Floating-Point word set, The optional Locals word set, The optional File-Access word set, ANS conformance
14252: @section The optional Floating-Point word set
14253: @c =====================================================================
14254: @cindex system documentation, floating-point words
14255: @cindex floating-point words, system documentation
14256: 
14257: @menu
14258: * floating-idef::               Implementation Defined Options
14259: * floating-ambcond::            Ambiguous Conditions            
14260: @end menu
14261: 
14262: 
14263: @c ---------------------------------------------------------------------
14264: @node floating-idef, floating-ambcond, The optional Floating-Point word set, The optional Floating-Point word set
14265: @subsection Implementation Defined Options
14266: @c ---------------------------------------------------------------------
14267: @cindex implementation-defined options, floating-point words
14268: @cindex floating-point words, implementation-defined options
14269: 
14270: @table @i
14271: @item format and range of floating point numbers:
14272: @cindex format and range of floating point numbers
14273: @cindex floating point numbers, format and range
14274: System-dependent; the @code{double} type of C.
14275: 
14276: @item results of @code{REPRESENT} when @i{float} is out of range:
14277: @cindex  @code{REPRESENT}, results when @i{float} is out of range
14278: System dependent; @code{REPRESENT} is implemented using the C library
14279: function @code{ecvt()} and inherits its behaviour in this respect.
14280: 
14281: @item rounding or truncation of floating-point numbers:
14282: @cindex rounding of floating-point numbers
14283: @cindex truncation of floating-point numbers
14284: @cindex floating-point numbers, rounding or truncation
14285: System dependent; the rounding behaviour is inherited from the hosting C
14286: compiler. IEEE-FP-based (i.e., most) systems by default round to
14287: nearest, and break ties by rounding to even (i.e., such that the last
14288: bit of the mantissa is 0).
14289: 
14290: @item size of floating-point stack:
14291: @cindex floating-point stack size
14292: @code{s" FLOATING-STACK" environment? drop .} gives the total size of
14293: the floating-point stack (in floats). You can specify this on startup
14294: with the command-line option @code{-f} (@pxref{Invoking Gforth}).
14295: 
14296: @item width of floating-point stack:
14297: @cindex floating-point stack width 
14298: @code{1 floats}.
14299: 
14300: @end table
14301: 
14302: 
14303: @c ---------------------------------------------------------------------
14304: @node floating-ambcond,  , floating-idef, The optional Floating-Point word set
14305: @subsection Ambiguous conditions
14306: @c ---------------------------------------------------------------------
14307: @cindex floating-point words, ambiguous conditions
14308: @cindex ambiguous conditions, floating-point words
14309: 
14310: @table @i
14311: @item @code{df@@} or @code{df!} used with an address that is not double-float  aligned:
14312: @cindex @code{df@@} or @code{df!} used with an address that is not double-float  aligned
14313: System-dependent. Typically results in a @code{-23 THROW} like other
14314: alignment violations.
14315: 
14316: @item @code{f@@} or @code{f!} used with an address that is not float  aligned:
14317: @cindex @code{f@@} used with an address that is not float aligned
14318: @cindex @code{f!} used with an address that is not float aligned
14319: System-dependent. Typically results in a @code{-23 THROW} like other
14320: alignment violations.
14321: 
14322: @item floating-point result out of range:
14323: @cindex floating-point result out of range
14324: System-dependent. Can result in a @code{-43 throw} (floating point
14325: overflow), @code{-54 throw} (floating point underflow), @code{-41 throw}
14326: (floating point inexact result), @code{-55 THROW} (Floating-point
14327: unidentified fault), or can produce a special value representing, e.g.,
14328: Infinity.
14329: 
14330: @item @code{sf@@} or @code{sf!} used with an address that is not single-float  aligned:
14331: @cindex @code{sf@@} or @code{sf!} used with an address that is not single-float  aligned
14332: System-dependent. Typically results in an alignment fault like other
14333: alignment violations.
14334: 
14335: @item @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.}):
14336: @cindex @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.})
14337: The floating-point number is converted into decimal nonetheless.
14338: 
14339: @item Both arguments are equal to zero (@code{FATAN2}):
14340: @cindex @code{FATAN2}, both arguments are equal to zero
14341: System-dependent. @code{FATAN2} is implemented using the C library
14342: function @code{atan2()}.
14343: 
14344: @item Using @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero:
14345: @cindex @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero
14346: System-dependent. Anyway, typically the cos of @i{r1} will not be zero
14347: because of small errors and the tan will be a very large (or very small)
14348: but finite number.
14349: 
14350: @item @i{d} cannot be presented precisely as a float in @code{D>F}:
14351: @cindex @code{D>F}, @i{d} cannot be presented precisely as a float
14352: The result is rounded to the nearest float.
14353: 
14354: @item dividing by zero:
14355: @cindex dividing by zero, floating-point
14356: @cindex floating-point dividing by zero
14357: @cindex floating-point unidentified fault, FP divide-by-zero
14358: Platform-dependent; can produce an Infinity, NaN, @code{-42 throw}
14359: (floating point divide by zero) or @code{-55 throw} (Floating-point
14360: unidentified fault).
14361: 
14362: @item exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@}):
14363: @cindex exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@})
14364: System dependent. On IEEE-FP based systems the number is converted into
14365: an infinity.
14366: 
14367: @item @i{float}<1 (@code{FACOSH}):
14368: @cindex @code{FACOSH}, @i{float}<1
14369: @cindex floating-point unidentified fault, @code{FACOSH}
14370: Platform-dependent; on IEEE-FP systems typically produces a NaN.
14371: 
14372: @item @i{float}=<-1 (@code{FLNP1}):
14373: @cindex @code{FLNP1}, @i{float}=<-1
14374: @cindex floating-point unidentified fault, @code{FLNP1}
14375: Platform-dependent; on IEEE-FP systems typically produces a NaN (or a
14376: negative infinity for @i{float}=-1).
14377: 
14378: @item @i{float}=<0 (@code{FLN}, @code{FLOG}):
14379: @cindex @code{FLN}, @i{float}=<0
14380: @cindex @code{FLOG}, @i{float}=<0
14381: @cindex floating-point unidentified fault, @code{FLN} or @code{FLOG}
14382: Platform-dependent; on IEEE-FP systems typically produces a NaN (or a
14383: negative infinity for @i{float}=0).
14384: 
14385: @item @i{float}<0 (@code{FASINH}, @code{FSQRT}):
14386: @cindex @code{FASINH}, @i{float}<0
14387: @cindex @code{FSQRT}, @i{float}<0
14388: @cindex floating-point unidentified fault, @code{FASINH} or @code{FSQRT}
14389: Platform-dependent; for @code{fsqrt} this typically gives a NaN, for
14390: @code{fasinh} some platforms produce a NaN, others a number (bug in the
14391: C library?).
14392: 
14393: @item |@i{float}|>1 (@code{FACOS}, @code{FASIN}, @code{FATANH}):
14394: @cindex @code{FACOS}, |@i{float}|>1
14395: @cindex @code{FASIN}, |@i{float}|>1
14396: @cindex @code{FATANH}, |@i{float}|>1
14397: @cindex floating-point unidentified fault, @code{FACOS}, @code{FASIN} or @code{FATANH}
14398: Platform-dependent; IEEE-FP systems typically produce a NaN.
14399: 
14400: @item integer part of float cannot be represented by @i{d} in @code{F>D}:
14401: @cindex @code{F>D}, integer part of float cannot be represented by @i{d}
14402: @cindex floating-point unidentified fault, @code{F>D}
14403: Platform-dependent; typically, some double number is produced and no
14404: error is reported.
14405: 
14406: @item string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.}):
14407: @cindex string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.})
14408: @code{Precision} characters of the numeric output area are used.  If
14409: @code{precision} is too high, these words will smash the data or code
14410: close to @code{here}.
14411: @end table
14412: 
14413: @c =====================================================================
14414: @node  The optional Locals word set, The optional Memory-Allocation word set, The optional Floating-Point word set, ANS conformance
14415: @section The optional Locals word set
14416: @c =====================================================================
14417: @cindex system documentation, locals words
14418: @cindex locals words, system documentation
14419: 
14420: @menu
14421: * locals-idef::                 Implementation Defined Options                 
14422: * locals-ambcond::              Ambiguous Conditions              
14423: @end menu
14424: 
14425: 
14426: @c ---------------------------------------------------------------------
14427: @node locals-idef, locals-ambcond, The optional Locals word set, The optional Locals word set
14428: @subsection Implementation Defined Options
14429: @c ---------------------------------------------------------------------
14430: @cindex implementation-defined options, locals words
14431: @cindex locals words, implementation-defined options
14432: 
14433: @table @i
14434: @item maximum number of locals in a definition:
14435: @cindex maximum number of locals in a definition
14436: @cindex locals, maximum number in a definition
14437: @code{s" #locals" environment? drop .}. Currently 15. This is a lower
14438: bound, e.g., on a 32-bit machine there can be 41 locals of up to 8
14439: characters. The number of locals in a definition is bounded by the size
14440: of locals-buffer, which contains the names of the locals.
14441: 
14442: @end table
14443: 
14444: 
14445: @c ---------------------------------------------------------------------
14446: @node locals-ambcond,  , locals-idef, The optional Locals word set
14447: @subsection Ambiguous conditions
14448: @c ---------------------------------------------------------------------
14449: @cindex locals words, ambiguous conditions
14450: @cindex ambiguous conditions, locals words
14451: 
14452: @table @i
14453: @item executing a named local in interpretation state:
14454: @cindex local in interpretation state
14455: @cindex Interpreting a compile-only word, for a local
14456: Locals have no interpretation semantics. If you try to perform the
14457: interpretation semantics, you will get a @code{-14 throw} somewhere
14458: (Interpreting a compile-only word). If you perform the compilation
14459: semantics, the locals access will be compiled (irrespective of state).
14460: 
14461: @item @i{name} not defined by @code{VALUE} or @code{(LOCAL)} (@code{TO}):
14462: @cindex name not defined by @code{VALUE} or @code{(LOCAL)} used by @code{TO}
14463: @cindex @code{TO} on non-@code{VALUE}s and non-locals
14464: @cindex Invalid name argument, @code{TO}
14465: @code{-32 throw} (Invalid name argument)
14466: 
14467: @end table
14468: 
14469: 
14470: @c =====================================================================
14471: @node  The optional Memory-Allocation word set, The optional Programming-Tools word set, The optional Locals word set, ANS conformance
14472: @section The optional Memory-Allocation word set
14473: @c =====================================================================
14474: @cindex system documentation, memory-allocation words
14475: @cindex memory-allocation words, system documentation
14476: 
14477: @menu
14478: * memory-idef::                 Implementation Defined Options                 
14479: @end menu
14480: 
14481: 
14482: @c ---------------------------------------------------------------------
14483: @node memory-idef,  , The optional Memory-Allocation word set, The optional Memory-Allocation word set
14484: @subsection Implementation Defined Options
14485: @c ---------------------------------------------------------------------
14486: @cindex implementation-defined options, memory-allocation words
14487: @cindex memory-allocation words, implementation-defined options
14488: 
14489: @table @i
14490: @item values and meaning of @i{ior}:
14491: @cindex  @i{ior} values and meaning
14492: The @i{ior}s returned by the file and memory allocation words are
14493: intended as throw codes. They typically are in the range
14494: -512@minus{}-2047 of OS errors.  The mapping from OS error numbers to
14495: @i{ior}s is -512@minus{}@i{errno}.
14496: 
14497: @end table
14498: 
14499: @c =====================================================================
14500: @node  The optional Programming-Tools word set, The optional Search-Order word set, The optional Memory-Allocation word set, ANS conformance
14501: @section The optional Programming-Tools word set
14502: @c =====================================================================
14503: @cindex system documentation, programming-tools words
14504: @cindex programming-tools words, system documentation
14505: 
14506: @menu
14507: * programming-idef::            Implementation Defined Options            
14508: * programming-ambcond::         Ambiguous Conditions         
14509: @end menu
14510: 
14511: 
14512: @c ---------------------------------------------------------------------
14513: @node programming-idef, programming-ambcond, The optional Programming-Tools word set, The optional Programming-Tools word set
14514: @subsection Implementation Defined Options
14515: @c ---------------------------------------------------------------------
14516: @cindex implementation-defined options, programming-tools words
14517: @cindex programming-tools words, implementation-defined options
14518: 
14519: @table @i
14520: @item ending sequence for input following @code{;CODE} and @code{CODE}:
14521: @cindex @code{;CODE} ending sequence
14522: @cindex @code{CODE} ending sequence
14523: @code{END-CODE}
14524: 
14525: @item manner of processing input following @code{;CODE} and @code{CODE}:
14526: @cindex @code{;CODE}, processing input
14527: @cindex @code{CODE}, processing input
14528: The @code{ASSEMBLER} vocabulary is pushed on the search order stack, and
14529: the input is processed by the text interpreter, (starting) in interpret
14530: state.
14531: 
14532: @item search order capability for @code{EDITOR} and @code{ASSEMBLER}:
14533: @cindex @code{ASSEMBLER}, search order capability
14534: The ANS Forth search order word set.
14535: 
14536: @item source and format of display by @code{SEE}:
14537: @cindex @code{SEE}, source and format of output
14538: The source for @code{see} is the executable code used by the inner
14539: interpreter.  The current @code{see} tries to output Forth source code
14540: (and on some platforms, assembly code for primitives) as well as
14541: possible.
14542: 
14543: @end table
14544: 
14545: @c ---------------------------------------------------------------------
14546: @node programming-ambcond,  , programming-idef, The optional Programming-Tools word set
14547: @subsection Ambiguous conditions
14548: @c ---------------------------------------------------------------------
14549: @cindex programming-tools words, ambiguous conditions
14550: @cindex ambiguous conditions, programming-tools words
14551: 
14552: @table @i
14553: 
14554: @item deleting the compilation word list (@code{FORGET}):
14555: @cindex @code{FORGET}, deleting the compilation word list
14556: Not implemented (yet).
14557: 
14558: @item fewer than @i{u}+1 items on the control-flow stack (@code{CS-PICK}, @code{CS-ROLL}):
14559: @cindex @code{CS-PICK}, fewer than @i{u}+1 items on the control flow-stack
14560: @cindex @code{CS-ROLL}, fewer than @i{u}+1 items on the control flow-stack
14561: @cindex control-flow stack underflow
14562: This typically results in an @code{abort"} with a descriptive error
14563: message (may change into a @code{-22 throw} (Control structure mismatch)
14564: in the future). You may also get a memory access error. If you are
14565: unlucky, this ambiguous condition is not caught.
14566: 
14567: @item @i{name} can't be found (@code{FORGET}):
14568: @cindex @code{FORGET}, @i{name} can't be found
14569: Not implemented (yet).
14570: 
14571: @item @i{name} not defined via @code{CREATE}:
14572: @cindex @code{;CODE}, @i{name} not defined via @code{CREATE}
14573: @code{;CODE} behaves like @code{DOES>} in this respect, i.e., it changes
14574: the execution semantics of the last defined word no matter how it was
14575: defined.
14576: 
14577: @item @code{POSTPONE} applied to @code{[IF]}:
14578: @cindex @code{POSTPONE} applied to @code{[IF]}
14579: @cindex @code{[IF]} and @code{POSTPONE}
14580: After defining @code{: X POSTPONE [IF] ; IMMEDIATE}. @code{X} is
14581: equivalent to @code{[IF]}.
14582: 
14583: @item reaching the end of the input source before matching @code{[ELSE]} or @code{[THEN]}:
14584: @cindex @code{[IF]}, end of the input source before matching @code{[ELSE]} or @code{[THEN]}
14585: Continue in the same state of conditional compilation in the next outer
14586: input source. Currently there is no warning to the user about this.
14587: 
14588: @item removing a needed definition (@code{FORGET}):
14589: @cindex @code{FORGET}, removing a needed definition
14590: Not implemented (yet).
14591: 
14592: @end table
14593: 
14594: 
14595: @c =====================================================================
14596: @node  The optional Search-Order word set,  , The optional Programming-Tools word set, ANS conformance
14597: @section The optional Search-Order word set
14598: @c =====================================================================
14599: @cindex system documentation, search-order words
14600: @cindex search-order words, system documentation
14601: 
14602: @menu
14603: * search-idef::                 Implementation Defined Options                 
14604: * search-ambcond::              Ambiguous Conditions              
14605: @end menu
14606: 
14607: 
14608: @c ---------------------------------------------------------------------
14609: @node search-idef, search-ambcond, The optional Search-Order word set, The optional Search-Order word set
14610: @subsection Implementation Defined Options
14611: @c ---------------------------------------------------------------------
14612: @cindex implementation-defined options, search-order words
14613: @cindex search-order words, implementation-defined options
14614: 
14615: @table @i
14616: @item maximum number of word lists in search order:
14617: @cindex maximum number of word lists in search order
14618: @cindex search order, maximum depth
14619: @code{s" wordlists" environment? drop .}. Currently 16.
14620: 
14621: @item minimum search order:
14622: @cindex minimum search order
14623: @cindex search order, minimum
14624: @code{root root}.
14625: 
14626: @end table
14627: 
14628: @c ---------------------------------------------------------------------
14629: @node search-ambcond,  , search-idef, The optional Search-Order word set
14630: @subsection Ambiguous conditions
14631: @c ---------------------------------------------------------------------
14632: @cindex search-order words, ambiguous conditions
14633: @cindex ambiguous conditions, search-order words
14634: 
14635: @table @i
14636: @item changing the compilation word list (during compilation):
14637: @cindex changing the compilation word list (during compilation)
14638: @cindex compilation word list, change before definition ends
14639: The word is entered into the word list that was the compilation word list
14640: at the start of the definition. Any changes to the name field (e.g.,
14641: @code{immediate}) or the code field (e.g., when executing @code{DOES>})
14642: are applied to the latest defined word (as reported by @code{latest} or
14643: @code{latestxt}), if possible, irrespective of the compilation word list.
14644: 
14645: @item search order empty (@code{previous}):
14646: @cindex @code{previous}, search order empty
14647: @cindex vocstack empty, @code{previous}
14648: @code{abort" Vocstack empty"}.
14649: 
14650: @item too many word lists in search order (@code{also}):
14651: @cindex @code{also}, too many word lists in search order
14652: @cindex vocstack full, @code{also}
14653: @code{abort" Vocstack full"}.
14654: 
14655: @end table
14656: 
14657: @c ***************************************************************
14658: @node Standard vs Extensions, Model, ANS conformance, Top
14659: @chapter Should I use Gforth extensions?
14660: @cindex Gforth extensions
14661: 
14662: As you read through the rest of this manual, you will see documentation
14663: for @i{Standard} words, and documentation for some appealing Gforth
14664: @i{extensions}. You might ask yourself the question: @i{``Should I
14665: restrict myself to the standard, or should I use the extensions?''}
14666: 
14667: The answer depends on the goals you have for the program you are working
14668: on:
14669: 
14670: @itemize @bullet
14671: 
14672: @item Is it just for yourself or do you want to share it with others?
14673: 
14674: @item
14675: If you want to share it, do the others all use Gforth?
14676: 
14677: @item
14678: If it is just for yourself, do you want to restrict yourself to Gforth?
14679: 
14680: @end itemize
14681: 
14682: If restricting the program to Gforth is ok, then there is no reason not
14683: to use extensions.  It is still a good idea to keep to the standard
14684: where it is easy, in case you want to reuse these parts in another
14685: program that you want to be portable.
14686: 
14687: If you want to be able to port the program to other Forth systems, there
14688: are the following points to consider:
14689: 
14690: @itemize @bullet
14691: 
14692: @item
14693: Most Forth systems that are being maintained support the ANS Forth
14694: standard.  So if your program complies with the standard, it will be
14695: portable among many systems.
14696: 
14697: @item
14698: A number of the Gforth extensions can be implemented in ANS Forth using
14699: public-domain files provided in the @file{compat/} directory. These are
14700: mentioned in the text in passing.  There is no reason not to use these
14701: extensions, your program will still be ANS Forth compliant; just include
14702: the appropriate compat files with your program.
14703: 
14704: @item
14705: The tool @file{ans-report.fs} (@pxref{ANS Report}) makes it easy to
14706: analyse your program and determine what non-Standard words it relies
14707: upon.  However, it does not check whether you use standard words in a
14708: non-standard way.
14709: 
14710: @item
14711: Some techniques are not standardized by ANS Forth, and are hard or
14712: impossible to implement in a standard way, but can be implemented in
14713: most Forth systems easily, and usually in similar ways (e.g., accessing
14714: word headers).  Forth has a rich historical precedent for programmers
14715: taking advantage of implementation-dependent features of their tools
14716: (for example, relying on a knowledge of the dictionary
14717: structure). Sometimes these techniques are necessary to extract every
14718: last bit of performance from the hardware, sometimes they are just a
14719: programming shorthand.
14720: 
14721: @item
14722: Does using a Gforth extension save more work than the porting this part
14723: to other Forth systems (if any) will cost?
14724: 
14725: @item
14726: Is the additional functionality worth the reduction in portability and
14727: the additional porting problems?
14728: 
14729: @end itemize
14730: 
14731: In order to perform these consideratios, you need to know what's
14732: standard and what's not.  This manual generally states if something is
14733: non-standard, but the authoritative source is the
14734: @uref{http://www.taygeta.com/forth/dpans.html,standard document}.
14735: Appendix A of the Standard (@var{Rationale}) provides a valuable insight
14736: into the thought processes of the technical committee.
14737: 
14738: Note also that portability between Forth systems is not the only
14739: portability issue; there is also the issue of portability between
14740: different platforms (processor/OS combinations).
14741: 
14742: @c ***************************************************************
14743: @node Model, Integrating Gforth, Standard vs Extensions, Top
14744: @chapter Model
14745: 
14746: This chapter has yet to be written. It will contain information, on
14747: which internal structures you can rely.
14748: 
14749: @c ***************************************************************
14750: @node Integrating Gforth, Emacs and Gforth, Model, Top
14751: @chapter Integrating Gforth into C programs
14752: 
14753: This is not yet implemented.
14754: 
14755: Several people like to use Forth as scripting language for applications
14756: that are otherwise written in C, C++, or some other language.
14757: 
14758: The Forth system ATLAST provides facilities for embedding it into
14759: applications; unfortunately it has several disadvantages: most
14760: importantly, it is not based on ANS Forth, and it is apparently dead
14761: (i.e., not developed further and not supported). The facilities
14762: provided by Gforth in this area are inspired by ATLAST's facilities, so
14763: making the switch should not be hard.
14764: 
14765: We also tried to design the interface such that it can easily be
14766: implemented by other Forth systems, so that we may one day arrive at a
14767: standardized interface. Such a standard interface would allow you to
14768: replace the Forth system without having to rewrite C code.
14769: 
14770: You embed the Gforth interpreter by linking with the library
14771: @code{libgforth.a} (give the compiler the option @code{-lgforth}).  All
14772: global symbols in this library that belong to the interface, have the
14773: prefix @code{forth_}. (Global symbols that are used internally have the
14774: prefix @code{gforth_}).
14775: 
14776: You can include the declarations of Forth types and the functions and
14777: variables of the interface with @code{#include <forth.h>}.
14778: 
14779: Types.
14780: 
14781: Variables.
14782: 
14783: Data and FP Stack pointer. Area sizes.
14784: 
14785: functions.
14786: 
14787: forth_init(imagefile)
14788: forth_evaluate(string) exceptions?
14789: forth_goto(address) (or forth_execute(xt)?)
14790: forth_continue() (a corountining mechanism)
14791: 
14792: Adding primitives.
14793: 
14794: No checking.
14795: 
14796: Signals?
14797: 
14798: Accessing the Stacks
14799: 
14800: @c ******************************************************************
14801: @node Emacs and Gforth, Image Files, Integrating Gforth, Top
14802: @chapter Emacs and Gforth
14803: @cindex Emacs and Gforth
14804: 
14805: @cindex @file{gforth.el}
14806: @cindex @file{forth.el}
14807: @cindex Rydqvist, Goran
14808: @cindex Kuehling, David
14809: @cindex comment editing commands
14810: @cindex @code{\}, editing with Emacs
14811: @cindex debug tracer editing commands
14812: @cindex @code{~~}, removal with Emacs
14813: @cindex Forth mode in Emacs
14814: 
14815: Gforth comes with @file{gforth.el}, an improved version of
14816: @file{forth.el} by Goran Rydqvist (included in the TILE package). The
14817: improvements are:
14818: 
14819: @itemize @bullet
14820: @item
14821: A better handling of indentation.
14822: @item
14823: A custom hilighting engine for Forth-code.
14824: @item
14825: Comment paragraph filling (@kbd{M-q})
14826: @item
14827: Commenting (@kbd{C-x \}) and uncommenting (@kbd{C-u C-x \}) of regions
14828: @item
14829: Removal of debugging tracers (@kbd{C-x ~}, @pxref{Debugging}).
14830: @item
14831: Support of the @code{info-lookup} feature for looking up the
14832: documentation of a word.
14833: @item
14834: Support for reading and writing blocks files.
14835: @end itemize
14836: 
14837: To get a basic description of these features, enter Forth mode and
14838: type @kbd{C-h m}.
14839: 
14840: @cindex source location of error or debugging output in Emacs
14841: @cindex error output, finding the source location in Emacs
14842: @cindex debugging output, finding the source location in Emacs
14843: In addition, Gforth supports Emacs quite well: The source code locations
14844: given in error messages, debugging output (from @code{~~}) and failed
14845: assertion messages are in the right format for Emacs' compilation mode
14846: (@pxref{Compilation, , Running Compilations under Emacs, emacs, Emacs
14847: Manual}) so the source location corresponding to an error or other
14848: message is only a few keystrokes away (@kbd{C-x `} for the next error,
14849: @kbd{C-c C-c} for the error under the cursor).
14850: 
14851: @cindex viewing the documentation of a word in Emacs
14852: @cindex context-sensitive help
14853: Moreover, for words documented in this manual, you can look up the
14854: glossary entry quickly by using @kbd{C-h TAB}
14855: (@code{info-lookup-symbol}, @pxref{Documentation, ,Documentation
14856: Commands, emacs, Emacs Manual}).  This feature requires Emacs 20.3 or
14857: later and does not work for words containing @code{:}.
14858: 
14859: @menu
14860: * Installing gforth.el::        Making Emacs aware of Forth.
14861: * Emacs Tags::                  Viewing the source of a word in Emacs.
14862: * Hilighting::                  Making Forth code look prettier.
14863: * Auto-Indentation::            Customizing auto-indentation.
14864: * Blocks Files::                Reading and writing blocks files.
14865: @end menu
14866: 
14867: @c ----------------------------------
14868: @node Installing gforth.el, Emacs Tags, Emacs and Gforth, Emacs and Gforth
14869: @section Installing gforth.el
14870: @cindex @file{.emacs}
14871: @cindex @file{gforth.el}, installation
14872: To make the features from @file{gforth.el} available in Emacs, add
14873: the following lines to your @file{.emacs} file:
14874: 
14875: @example
14876: (autoload 'forth-mode "gforth.el")
14877: (setq auto-mode-alist (cons '("\\.fs\\'" . forth-mode) 
14878: 			    auto-mode-alist))
14879: (autoload 'forth-block-mode "gforth.el")
14880: (setq auto-mode-alist (cons '("\\.fb\\'" . forth-block-mode) 
14881: 			    auto-mode-alist))
14882: (add-hook 'forth-mode-hook (function (lambda ()
14883:    ;; customize variables here:
14884:    (setq forth-indent-level 4)
14885:    (setq forth-minor-indent-level 2)
14886:    (setq forth-hilight-level 3)
14887:    ;;; ...
14888: )))
14889: @end example
14890: 
14891: @c ----------------------------------
14892: @node Emacs Tags, Hilighting, Installing gforth.el, Emacs and Gforth
14893: @section Emacs Tags
14894: @cindex @file{TAGS} file
14895: @cindex @file{etags.fs}
14896: @cindex viewing the source of a word in Emacs
14897: @cindex @code{require}, placement in files
14898: @cindex @code{include}, placement in files
14899: If you @code{require} @file{etags.fs}, a new @file{TAGS} file will be
14900: produced (@pxref{Tags, , Tags Tables, emacs, Emacs Manual}) that
14901: contains the definitions of all words defined afterwards. You can then
14902: find the source for a word using @kbd{M-.}. Note that Emacs can use
14903: several tags files at the same time (e.g., one for the Gforth sources
14904: and one for your program, @pxref{Select Tags Table,,Selecting a Tags
14905: Table,emacs, Emacs Manual}). The TAGS file for the preloaded words is
14906: @file{$(datadir)/gforth/$(VERSION)/TAGS} (e.g.,
14907: @file{/usr/local/share/gforth/0.2.0/TAGS}).  To get the best behaviour
14908: with @file{etags.fs}, you should avoid putting definitions both before
14909: and after @code{require} etc., otherwise you will see the same file
14910: visited several times by commands like @code{tags-search}.
14911: 
14912: @c ----------------------------------
14913: @node Hilighting, Auto-Indentation, Emacs Tags, Emacs and Gforth
14914: @section Hilighting
14915: @cindex hilighting Forth code in Emacs
14916: @cindex highlighting Forth code in Emacs
14917: @file{gforth.el} comes with a custom source hilighting engine.  When
14918: you open a file in @code{forth-mode}, it will be completely parsed,
14919: assigning faces to keywords, comments, strings etc.  While you edit
14920: the file, modified regions get parsed and updated on-the-fly. 
14921: 
14922: Use the variable `forth-hilight-level' to change the level of
14923: decoration from 0 (no hilighting at all) to 3 (the default).  Even if
14924: you set the hilighting level to 0, the parser will still work in the
14925: background, collecting information about whether regions of text are
14926: ``compiled'' or ``interpreted''.  Those information are required for
14927: auto-indentation to work properly.  Set `forth-disable-parser' to
14928: non-nil if your computer is too slow to handle parsing.  This will
14929: have an impact on the smartness of the auto-indentation engine,
14930: though.
14931: 
14932: Sometimes Forth sources define new features that should be hilighted,
14933: new control structures, defining-words etc.  You can use the variable
14934: `forth-custom-words' to make @code{forth-mode} hilight additional
14935: words and constructs.  See the docstring of `forth-words' for details
14936: (in Emacs, type @kbd{C-h v forth-words}).
14937: 
14938: `forth-custom-words' is meant to be customized in your
14939: @file{.emacs} file.  To customize hilighing in a file-specific manner,
14940: set `forth-local-words' in a local-variables section at the end of
14941: your source file (@pxref{Local Variables in Files,, Variables, emacs, Emacs Manual}).
14942: 
14943: Example:
14944: @example
14945: 0 [IF]
14946:    Local Variables:
14947:    forth-local-words:
14948:       ((("t:") definition-starter (font-lock-keyword-face . 1)
14949:         "[ \t\n]" t name (font-lock-function-name-face . 3))
14950:        ((";t") definition-ender (font-lock-keyword-face . 1)))
14951:    End:
14952: [THEN]
14953: @end example
14954: 
14955: @c ----------------------------------
14956: @node Auto-Indentation, Blocks Files, Hilighting, Emacs and Gforth
14957: @section Auto-Indentation
14958: @cindex auto-indentation of Forth code in Emacs
14959: @cindex indentation of Forth code in Emacs
14960: @code{forth-mode} automatically tries to indent lines in a smart way,
14961: whenever you type @key{TAB} or break a line with @kbd{C-m}.
14962: 
14963: Simple customization can be achieved by setting
14964: `forth-indent-level' and `forth-minor-indent-level' in your
14965: @file{.emacs} file. For historical reasons @file{gforth.el} indents
14966: per default by multiples of 4 columns.  To use the more traditional
14967: 3-column indentation, add the following lines to your @file{.emacs}:
14968: 
14969: @example
14970: (add-hook 'forth-mode-hook (function (lambda ()
14971:    ;; customize variables here:
14972:    (setq forth-indent-level 3)
14973:    (setq forth-minor-indent-level 1)
14974: )))
14975: @end example
14976: 
14977: If you want indentation to recognize non-default words, customize it
14978: by setting `forth-custom-indent-words' in your @file{.emacs}.  See the
14979: docstring of `forth-indent-words' for details (in Emacs, type @kbd{C-h
14980: v forth-indent-words}).
14981: 
14982: To customize indentation in a file-specific manner, set
14983: `forth-local-indent-words' in a local-variables section at the end of
14984: your source file (@pxref{Local Variables in Files, Variables,,emacs,
14985: Emacs Manual}).
14986: 
14987: Example:
14988: @example
14989: 0 [IF]
14990:    Local Variables:
14991:    forth-local-indent-words:
14992:       ((("t:") (0 . 2) (0 . 2))
14993:        ((";t") (-2 . 0) (0 . -2)))
14994:    End:
14995: [THEN]
14996: @end example
14997: 
14998: @c ----------------------------------
14999: @node Blocks Files,  , Auto-Indentation, Emacs and Gforth
15000: @section Blocks Files
15001: @cindex blocks files, use with Emacs
15002: @code{forth-mode} Autodetects blocks files by checking whether the
15003: length of the first line exceeds 1023 characters.  It then tries to
15004: convert the file into normal text format.  When you save the file, it
15005: will be written to disk as normal stream-source file.
15006: 
15007: If you want to write blocks files, use @code{forth-blocks-mode}.  It
15008: inherits all the features from @code{forth-mode}, plus some additions:
15009: 
15010: @itemize @bullet
15011: @item
15012: Files are written to disk in blocks file format.
15013: @item
15014: Screen numbers are displayed in the mode line (enumerated beginning
15015: with the value of `forth-block-base')
15016: @item
15017: Warnings are displayed when lines exceed 64 characters.
15018: @item
15019: The beginning of the currently edited block is marked with an
15020: overlay-arrow. 
15021: @end itemize
15022: 
15023: There are some restrictions you should be aware of.  When you open a
15024: blocks file that contains tabulator or newline characters, these
15025: characters will be translated into spaces when the file is written
15026: back to disk.  If tabs or newlines are encountered during blocks file
15027: reading, an error is output to the echo area. So have a look at the
15028: `*Messages*' buffer, when Emacs' bell rings during reading.
15029: 
15030: Please consult the docstring of @code{forth-blocks-mode} for more
15031: information by typing @kbd{C-h v forth-blocks-mode}).
15032: 
15033: @c ******************************************************************
15034: @node Image Files, Engine, Emacs and Gforth, Top
15035: @chapter Image Files
15036: @cindex image file
15037: @cindex @file{.fi} files
15038: @cindex precompiled Forth code
15039: @cindex dictionary in persistent form
15040: @cindex persistent form of dictionary
15041: 
15042: An image file is a file containing an image of the Forth dictionary,
15043: i.e., compiled Forth code and data residing in the dictionary.  By
15044: convention, we use the extension @code{.fi} for image files.
15045: 
15046: @menu
15047: * Image Licensing Issues::      Distribution terms for images.
15048: * Image File Background::       Why have image files?
15049: * Non-Relocatable Image Files::  don't always work.
15050: * Data-Relocatable Image Files::  are better.
15051: * Fully Relocatable Image Files::  better yet.
15052: * Stack and Dictionary Sizes::  Setting the default sizes for an image.
15053: * Running Image Files::         @code{gforth -i @i{file}} or @i{file}.
15054: * Modifying the Startup Sequence::  and turnkey applications.
15055: @end menu
15056: 
15057: @node Image Licensing Issues, Image File Background, Image Files, Image Files
15058: @section Image Licensing Issues
15059: @cindex license for images
15060: @cindex image license
15061: 
15062: An image created with @code{gforthmi} (@pxref{gforthmi}) or
15063: @code{savesystem} (@pxref{Non-Relocatable Image Files}) includes the
15064: original image; i.e., according to copyright law it is a derived work of
15065: the original image.
15066: 
15067: Since Gforth is distributed under the GNU GPL, the newly created image
15068: falls under the GNU GPL, too. In particular, this means that if you
15069: distribute the image, you have to make all of the sources for the image
15070: available, including those you wrote.  For details see @ref{Copying, ,
15071: GNU General Public License (Section 3)}.
15072: 
15073: If you create an image with @code{cross} (@pxref{cross.fs}), the image
15074: contains only code compiled from the sources you gave it; if none of
15075: these sources is under the GPL, the terms discussed above do not apply
15076: to the image. However, if your image needs an engine (a gforth binary)
15077: that is under the GPL, you should make sure that you distribute both in
15078: a way that is at most a @emph{mere aggregation}, if you don't want the
15079: terms of the GPL to apply to the image.
15080: 
15081: @node Image File Background, Non-Relocatable Image Files, Image Licensing Issues, Image Files
15082: @section Image File Background
15083: @cindex image file background
15084: 
15085: Gforth consists not only of primitives (in the engine), but also of
15086: definitions written in Forth. Since the Forth compiler itself belongs to
15087: those definitions, it is not possible to start the system with the
15088: engine and the Forth source alone. Therefore we provide the Forth
15089: code as an image file in nearly executable form. When Gforth starts up,
15090: a C routine loads the image file into memory, optionally relocates the
15091: addresses, then sets up the memory (stacks etc.) according to
15092: information in the image file, and (finally) starts executing Forth
15093: code.
15094: 
15095: The image file variants represent different compromises between the
15096: goals of making it easy to generate image files and making them
15097: portable.
15098: 
15099: @cindex relocation at run-time
15100: Win32Forth 3.4 and Mitch Bradley's @code{cforth} use relocation at
15101: run-time. This avoids many of the complications discussed below (image
15102: files are data relocatable without further ado), but costs performance
15103: (one addition per memory access).
15104: 
15105: @cindex relocation at load-time
15106: By contrast, the Gforth loader performs relocation at image load time. The
15107: loader also has to replace tokens that represent primitive calls with the
15108: appropriate code-field addresses (or code addresses in the case of
15109: direct threading).
15110: 
15111: There are three kinds of image files, with different degrees of
15112: relocatability: non-relocatable, data-relocatable, and fully relocatable
15113: image files.
15114: 
15115: @cindex image file loader
15116: @cindex relocating loader
15117: @cindex loader for image files
15118: These image file variants have several restrictions in common; they are
15119: caused by the design of the image file loader:
15120: 
15121: @itemize @bullet
15122: @item
15123: There is only one segment; in particular, this means, that an image file
15124: cannot represent @code{ALLOCATE}d memory chunks (and pointers to
15125: them). The contents of the stacks are not represented, either.
15126: 
15127: @item
15128: The only kinds of relocation supported are: adding the same offset to
15129: all cells that represent data addresses; and replacing special tokens
15130: with code addresses or with pieces of machine code.
15131: 
15132: If any complex computations involving addresses are performed, the
15133: results cannot be represented in the image file. Several applications that
15134: use such computations come to mind:
15135: @itemize @minus
15136: @item
15137: Hashing addresses (or data structures which contain addresses) for table
15138: lookup. If you use Gforth's @code{table}s or @code{wordlist}s for this
15139: purpose, you will have no problem, because the hash tables are
15140: recomputed automatically when the system is started. If you use your own
15141: hash tables, you will have to do something similar.
15142: 
15143: @item
15144: There's a cute implementation of doubly-linked lists that uses
15145: @code{XOR}ed addresses. You could represent such lists as singly-linked
15146: in the image file, and restore the doubly-linked representation on
15147: startup.@footnote{In my opinion, though, you should think thrice before
15148: using a doubly-linked list (whatever implementation).}
15149: 
15150: @item
15151: The code addresses of run-time routines like @code{docol:} cannot be
15152: represented in the image file (because their tokens would be replaced by
15153: machine code in direct threaded implementations). As a workaround,
15154: compute these addresses at run-time with @code{>code-address} from the
15155: executions tokens of appropriate words (see the definitions of
15156: @code{docol:} and friends in @file{kernel/getdoers.fs}).
15157: 
15158: @item
15159: On many architectures addresses are represented in machine code in some
15160: shifted or mangled form. You cannot put @code{CODE} words that contain
15161: absolute addresses in this form in a relocatable image file. Workarounds
15162: are representing the address in some relative form (e.g., relative to
15163: the CFA, which is present in some register), or loading the address from
15164: a place where it is stored in a non-mangled form.
15165: @end itemize
15166: @end itemize
15167: 
15168: @node  Non-Relocatable Image Files, Data-Relocatable Image Files, Image File Background, Image Files
15169: @section Non-Relocatable Image Files
15170: @cindex non-relocatable image files
15171: @cindex image file, non-relocatable
15172: 
15173: These files are simple memory dumps of the dictionary. They are specific
15174: to the executable (i.e., @file{gforth} file) they were created
15175: with. What's worse, they are specific to the place on which the
15176: dictionary resided when the image was created. Now, there is no
15177: guarantee that the dictionary will reside at the same place the next
15178: time you start Gforth, so there's no guarantee that a non-relocatable
15179: image will work the next time (Gforth will complain instead of crashing,
15180: though).
15181: 
15182: You can create a non-relocatable image file with
15183: 
15184: 
15185: doc-savesystem
15186: 
15187: 
15188: @node Data-Relocatable Image Files, Fully Relocatable Image Files, Non-Relocatable Image Files, Image Files
15189: @section Data-Relocatable Image Files
15190: @cindex data-relocatable image files
15191: @cindex image file, data-relocatable
15192: 
15193: These files contain relocatable data addresses, but fixed code addresses
15194: (instead of tokens). They are specific to the executable (i.e.,
15195: @file{gforth} file) they were created with. For direct threading on some
15196: architectures (e.g., the i386), data-relocatable images do not work. You
15197: get a data-relocatable image, if you use @file{gforthmi} with a
15198: Gforth binary that is not doubly indirect threaded (@pxref{Fully
15199: Relocatable Image Files}).
15200: 
15201: @node Fully Relocatable Image Files, Stack and Dictionary Sizes, Data-Relocatable Image Files, Image Files
15202: @section Fully Relocatable Image Files
15203: @cindex fully relocatable image files
15204: @cindex image file, fully relocatable
15205: 
15206: @cindex @file{kern*.fi}, relocatability
15207: @cindex @file{gforth.fi}, relocatability
15208: These image files have relocatable data addresses, and tokens for code
15209: addresses. They can be used with different binaries (e.g., with and
15210: without debugging) on the same machine, and even across machines with
15211: the same data formats (byte order, cell size, floating point
15212: format). However, they are usually specific to the version of Gforth
15213: they were created with. The files @file{gforth.fi} and @file{kernl*.fi}
15214: are fully relocatable.
15215: 
15216: There are two ways to create a fully relocatable image file:
15217: 
15218: @menu
15219: * gforthmi::                    The normal way
15220: * cross.fs::                    The hard way
15221: @end menu
15222: 
15223: @node gforthmi, cross.fs, Fully Relocatable Image Files, Fully Relocatable Image Files
15224: @subsection @file{gforthmi}
15225: @cindex @file{comp-i.fs}
15226: @cindex @file{gforthmi}
15227: 
15228: You will usually use @file{gforthmi}. If you want to create an
15229: image @i{file} that contains everything you would load by invoking
15230: Gforth with @code{gforth @i{options}}, you simply say:
15231: @example
15232: gforthmi @i{file} @i{options}
15233: @end example
15234: 
15235: E.g., if you want to create an image @file{asm.fi} that has the file
15236: @file{asm.fs} loaded in addition to the usual stuff, you could do it
15237: like this:
15238: 
15239: @example
15240: gforthmi asm.fi asm.fs
15241: @end example
15242: 
15243: @file{gforthmi} is implemented as a sh script and works like this: It
15244: produces two non-relocatable images for different addresses and then
15245: compares them. Its output reflects this: first you see the output (if
15246: any) of the two Gforth invocations that produce the non-relocatable image
15247: files, then you see the output of the comparing program: It displays the
15248: offset used for data addresses and the offset used for code addresses;
15249: moreover, for each cell that cannot be represented correctly in the
15250: image files, it displays a line like this:
15251: 
15252: @example
15253:      78DC         BFFFFA50         BFFFFA40
15254: @end example
15255: 
15256: This means that at offset $78dc from @code{forthstart}, one input image
15257: contains $bffffa50, and the other contains $bffffa40. Since these cells
15258: cannot be represented correctly in the output image, you should examine
15259: these places in the dictionary and verify that these cells are dead
15260: (i.e., not read before they are written).
15261: 
15262: @cindex --application, @code{gforthmi} option
15263: If you insert the option @code{--application} in front of the image file
15264: name, you will get an image that uses the @code{--appl-image} option
15265: instead of the @code{--image-file} option (@pxref{Invoking
15266: Gforth}). When you execute such an image on Unix (by typing the image
15267: name as command), the Gforth engine will pass all options to the image
15268: instead of trying to interpret them as engine options.
15269: 
15270: If you type @file{gforthmi} with no arguments, it prints some usage
15271: instructions.
15272: 
15273: @cindex @code{savesystem} during @file{gforthmi}
15274: @cindex @code{bye} during @file{gforthmi}
15275: @cindex doubly indirect threaded code
15276: @cindex environment variables
15277: @cindex @code{GFORTHD} -- environment variable
15278: @cindex @code{GFORTH} -- environment variable
15279: @cindex @code{gforth-ditc}
15280: There are a few wrinkles: After processing the passed @i{options}, the
15281: words @code{savesystem} and @code{bye} must be visible. A special doubly
15282: indirect threaded version of the @file{gforth} executable is used for
15283: creating the non-relocatable images; you can pass the exact filename of
15284: this executable through the environment variable @code{GFORTHD}
15285: (default: @file{gforth-ditc}); if you pass a version that is not doubly
15286: indirect threaded, you will not get a fully relocatable image, but a
15287: data-relocatable image (because there is no code address offset). The
15288: normal @file{gforth} executable is used for creating the relocatable
15289: image; you can pass the exact filename of this executable through the
15290: environment variable @code{GFORTH}.
15291: 
15292: @node cross.fs,  , gforthmi, Fully Relocatable Image Files
15293: @subsection @file{cross.fs}
15294: @cindex @file{cross.fs}
15295: @cindex cross-compiler
15296: @cindex metacompiler
15297: @cindex target compiler
15298: 
15299: You can also use @code{cross}, a batch compiler that accepts a Forth-like
15300: programming language (@pxref{Cross Compiler}).
15301: 
15302: @code{cross} allows you to create image files for machines with
15303: different data sizes and data formats than the one used for generating
15304: the image file. You can also use it to create an application image that
15305: does not contain a Forth compiler. These features are bought with
15306: restrictions and inconveniences in programming. E.g., addresses have to
15307: be stored in memory with special words (@code{A!}, @code{A,}, etc.) in
15308: order to make the code relocatable.
15309: 
15310: 
15311: @node Stack and Dictionary Sizes, Running Image Files, Fully Relocatable Image Files, Image Files
15312: @section Stack and Dictionary Sizes
15313: @cindex image file, stack and dictionary sizes
15314: @cindex dictionary size default
15315: @cindex stack size default
15316: 
15317: If you invoke Gforth with a command line flag for the size
15318: (@pxref{Invoking Gforth}), the size you specify is stored in the
15319: dictionary. If you save the dictionary with @code{savesystem} or create
15320: an image with @file{gforthmi}, this size will become the default
15321: for the resulting image file. E.g., the following will create a
15322: fully relocatable version of @file{gforth.fi} with a 1MB dictionary:
15323: 
15324: @example
15325: gforthmi gforth.fi -m 1M
15326: @end example
15327: 
15328: In other words, if you want to set the default size for the dictionary
15329: and the stacks of an image, just invoke @file{gforthmi} with the
15330: appropriate options when creating the image.
15331: 
15332: @cindex stack size, cache-friendly
15333: Note: For cache-friendly behaviour (i.e., good performance), you should
15334: make the sizes of the stacks modulo, say, 2K, somewhat different. E.g.,
15335: the default stack sizes are: data: 16k (mod 2k=0); fp: 15.5k (mod
15336: 2k=1.5k); return: 15k(mod 2k=1k); locals: 14.5k (mod 2k=0.5k).
15337: 
15338: @node Running Image Files, Modifying the Startup Sequence, Stack and Dictionary Sizes, Image Files
15339: @section Running Image Files
15340: @cindex running image files
15341: @cindex invoking image files
15342: @cindex image file invocation
15343: 
15344: @cindex -i, invoke image file
15345: @cindex --image file, invoke image file
15346: You can invoke Gforth with an image file @i{image} instead of the
15347: default @file{gforth.fi} with the @code{-i} flag (@pxref{Invoking Gforth}):
15348: @example
15349: gforth -i @i{image}
15350: @end example
15351: 
15352: @cindex executable image file
15353: @cindex image file, executable
15354: If your operating system supports starting scripts with a line of the
15355: form @code{#! ...}, you just have to type the image file name to start
15356: Gforth with this image file (note that the file extension @code{.fi} is
15357: just a convention). I.e., to run Gforth with the image file @i{image},
15358: you can just type @i{image} instead of @code{gforth -i @i{image}}.
15359: This works because every @code{.fi} file starts with a line of this
15360: format:
15361: 
15362: @example
15363: #! /usr/local/bin/gforth-0.4.0 -i
15364: @end example
15365: 
15366: The file and pathname for the Gforth engine specified on this line is
15367: the specific Gforth executable that it was built against; i.e. the value
15368: of the environment variable @code{GFORTH} at the time that
15369: @file{gforthmi} was executed.
15370: 
15371: You can make use of the same shell capability to make a Forth source
15372: file into an executable. For example, if you place this text in a file:
15373: 
15374: @example
15375: #! /usr/local/bin/gforth
15376: 
15377: ." Hello, world" CR
15378: bye
15379: @end example
15380: 
15381: @noindent
15382: and then make the file executable (chmod +x in Unix), you can run it
15383: directly from the command line. The sequence @code{#!} is used in two
15384: ways; firstly, it is recognised as a ``magic sequence'' by the operating
15385: system@footnote{The Unix kernel actually recognises two types of files:
15386: executable files and files of data, where the data is processed by an
15387: interpreter that is specified on the ``interpreter line'' -- the first
15388: line of the file, starting with the sequence #!. There may be a small
15389: limit (e.g., 32) on the number of characters that may be specified on
15390: the interpreter line.} secondly it is treated as a comment character by
15391: Gforth. Because of the second usage, a space is required between
15392: @code{#!} and the path to the executable (moreover, some Unixes
15393: require the sequence @code{#! /}).
15394: 
15395: The disadvantage of this latter technique, compared with using
15396: @file{gforthmi}, is that it is slightly slower; the Forth source code is
15397: compiled on-the-fly, each time the program is invoked.
15398: 
15399: doc-#!
15400: 
15401: 
15402: @node Modifying the Startup Sequence,  , Running Image Files, Image Files
15403: @section Modifying the Startup Sequence
15404: @cindex startup sequence for image file
15405: @cindex image file initialization sequence
15406: @cindex initialization sequence of image file
15407: 
15408: You can add your own initialization to the startup sequence of an image
15409: through the deferred word @code{'cold}. @code{'cold} is invoked just
15410: before the image-specific command line processing (i.e., loading files
15411: and evaluating (@code{-e}) strings) starts.
15412: 
15413: A sequence for adding your initialization usually looks like this:
15414: 
15415: @example
15416: :noname
15417:     Defers 'cold \ do other initialization stuff (e.g., rehashing wordlists)
15418:     ... \ your stuff
15419: ; IS 'cold
15420: @end example
15421: 
15422: After @code{'cold}, Gforth processes the image options
15423: (@pxref{Invoking Gforth}), and then it performs @code{bootmessage},
15424: another deferred word.  This normally prints Gforth's startup message
15425: and does nothing else.
15426: 
15427: @cindex turnkey image files
15428: @cindex image file, turnkey applications
15429: So, if you want to make a turnkey image (i.e., an image for an
15430: application instead of an extended Forth system), you can do this in
15431: two ways:
15432: 
15433: @itemize @bullet
15434: 
15435: @item
15436: If you want to do your interpretation of the OS command-line
15437: arguments, hook into @code{'cold}.  In that case you probably also
15438: want to build the image with @code{gforthmi --application}
15439: (@pxref{gforthmi}) to keep the engine from processing OS command line
15440: options.  You can then do your own command-line processing with
15441: @code{next-arg} 
15442: 
15443: @item
15444: If you want to have the normal Gforth processing of OS command-line
15445: arguments, hook into @code{bootmessage}.
15446: 
15447: @end itemize
15448: 
15449: In either case, you probably do not want the word that you execute in
15450: these hooks to exit normally, but use @code{bye} or @code{throw}.
15451: Otherwise the Gforth startup process would continue and eventually
15452: present the Forth command line to the user.
15453: 
15454: doc-'cold
15455: doc-bootmessage
15456: 
15457: @c ******************************************************************
15458: @node Engine, Cross Compiler, Image Files, Top
15459: @chapter Engine
15460: @cindex engine
15461: @cindex virtual machine
15462: 
15463: Reading this chapter is not necessary for programming with Gforth. It
15464: may be helpful for finding your way in the Gforth sources.
15465: 
15466: The ideas in this section have also been published in the following
15467: papers: Bernd Paysan, @cite{ANS fig/GNU/??? Forth} (in German),
15468: Forth-Tagung '93; M. Anton Ertl,
15469: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl93.ps.Z, A
15470: Portable Forth Engine}}, EuroForth '93; M. Anton Ertl,
15471: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl02.ps.gz,
15472: Threaded code variations and optimizations (extended version)}},
15473: Forth-Tagung '02.
15474: 
15475: @menu
15476: * Portability::                 
15477: * Threading::                   
15478: * Primitives::                  
15479: * Performance::                 
15480: @end menu
15481: 
15482: @node Portability, Threading, Engine, Engine
15483: @section Portability
15484: @cindex engine portability
15485: 
15486: An important goal of the Gforth Project is availability across a wide
15487: range of personal machines. fig-Forth, and, to a lesser extent, F83,
15488: achieved this goal by manually coding the engine in assembly language
15489: for several then-popular processors. This approach is very
15490: labor-intensive and the results are short-lived due to progress in
15491: computer architecture.
15492: 
15493: @cindex C, using C for the engine
15494: Others have avoided this problem by coding in C, e.g., Mitch Bradley
15495: (cforth), Mikael Patel (TILE) and Dirk Zoller (pfe). This approach is
15496: particularly popular for UNIX-based Forths due to the large variety of
15497: architectures of UNIX machines. Unfortunately an implementation in C
15498: does not mix well with the goals of efficiency and with using
15499: traditional techniques: Indirect or direct threading cannot be expressed
15500: in C, and switch threading, the fastest technique available in C, is
15501: significantly slower. Another problem with C is that it is very
15502: cumbersome to express double integer arithmetic.
15503: 
15504: @cindex GNU C for the engine
15505: @cindex long long
15506: Fortunately, there is a portable language that does not have these
15507: limitations: GNU C, the version of C processed by the GNU C compiler
15508: (@pxref{C Extensions, , Extensions to the C Language Family, gcc.info,
15509: GNU C Manual}). Its labels as values feature (@pxref{Labels as Values, ,
15510: Labels as Values, gcc.info, GNU C Manual}) makes direct and indirect
15511: threading possible, its @code{long long} type (@pxref{Long Long, ,
15512: Double-Word Integers, gcc.info, GNU C Manual}) corresponds to Forth's
15513: double numbers on many systems.  GNU C is freely available on all
15514: important (and many unimportant) UNIX machines, VMS, 80386s running
15515: MS-DOS, the Amiga, and the Atari ST, so a Forth written in GNU C can run
15516: on all these machines.
15517: 
15518: Writing in a portable language has the reputation of producing code that
15519: is slower than assembly. For our Forth engine we repeatedly looked at
15520: the code produced by the compiler and eliminated most compiler-induced
15521: inefficiencies by appropriate changes in the source code.
15522: 
15523: @cindex explicit register declarations
15524: @cindex --enable-force-reg, configuration flag
15525: @cindex -DFORCE_REG
15526: However, register allocation cannot be portably influenced by the
15527: programmer, leading to some inefficiencies on register-starved
15528: machines. We use explicit register declarations (@pxref{Explicit Reg
15529: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) to
15530: improve the speed on some machines. They are turned on by using the
15531: configuration flag @code{--enable-force-reg} (@code{gcc} switch
15532: @code{-DFORCE_REG}). Unfortunately, this feature not only depends on the
15533: machine, but also on the compiler version: On some machines some
15534: compiler versions produce incorrect code when certain explicit register
15535: declarations are used. So by default @code{-DFORCE_REG} is not used.
15536: 
15537: @node Threading, Primitives, Portability, Engine
15538: @section Threading
15539: @cindex inner interpreter implementation
15540: @cindex threaded code implementation
15541: 
15542: @cindex labels as values
15543: GNU C's labels as values extension (available since @code{gcc-2.0},
15544: @pxref{Labels as Values, , Labels as Values, gcc.info, GNU C Manual})
15545: makes it possible to take the address of @i{label} by writing
15546: @code{&&@i{label}}.  This address can then be used in a statement like
15547: @code{goto *@i{address}}. I.e., @code{goto *&&x} is the same as
15548: @code{goto x}.
15549: 
15550: @cindex @code{NEXT}, indirect threaded
15551: @cindex indirect threaded inner interpreter
15552: @cindex inner interpreter, indirect threaded
15553: With this feature an indirect threaded @code{NEXT} looks like:
15554: @example
15555: cfa = *ip++;
15556: ca = *cfa;
15557: goto *ca;
15558: @end example
15559: @cindex instruction pointer
15560: For those unfamiliar with the names: @code{ip} is the Forth instruction
15561: pointer; the @code{cfa} (code-field address) corresponds to ANS Forths
15562: execution token and points to the code field of the next word to be
15563: executed; The @code{ca} (code address) fetched from there points to some
15564: executable code, e.g., a primitive or the colon definition handler
15565: @code{docol}.
15566: 
15567: @cindex @code{NEXT}, direct threaded
15568: @cindex direct threaded inner interpreter
15569: @cindex inner interpreter, direct threaded
15570: Direct threading is even simpler:
15571: @example
15572: ca = *ip++;
15573: goto *ca;
15574: @end example
15575: 
15576: Of course we have packaged the whole thing neatly in macros called
15577: @code{NEXT} and @code{NEXT1} (the part of @code{NEXT} after fetching the cfa).
15578: 
15579: @menu
15580: * Scheduling::                  
15581: * Direct or Indirect Threaded?::  
15582: * Dynamic Superinstructions::   
15583: * DOES>::                       
15584: @end menu
15585: 
15586: @node Scheduling, Direct or Indirect Threaded?, Threading, Threading
15587: @subsection Scheduling
15588: @cindex inner interpreter optimization
15589: 
15590: There is a little complication: Pipelined and superscalar processors,
15591: i.e., RISC and some modern CISC machines can process independent
15592: instructions while waiting for the results of an instruction. The
15593: compiler usually reorders (schedules) the instructions in a way that
15594: achieves good usage of these delay slots. However, on our first tries
15595: the compiler did not do well on scheduling primitives. E.g., for
15596: @code{+} implemented as
15597: @example
15598: n=sp[0]+sp[1];
15599: sp++;
15600: sp[0]=n;
15601: NEXT;
15602: @end example
15603: the @code{NEXT} comes strictly after the other code, i.e., there is
15604: nearly no scheduling. After a little thought the problem becomes clear:
15605: The compiler cannot know that @code{sp} and @code{ip} point to different
15606: addresses (and the version of @code{gcc} we used would not know it even
15607: if it was possible), so it could not move the load of the cfa above the
15608: store to the TOS. Indeed the pointers could be the same, if code on or
15609: very near the top of stack were executed. In the interest of speed we
15610: chose to forbid this probably unused ``feature'' and helped the compiler
15611: in scheduling: @code{NEXT} is divided into several parts:
15612: @code{NEXT_P0}, @code{NEXT_P1} and @code{NEXT_P2}). @code{+} now looks
15613: like:
15614: @example
15615: NEXT_P0;
15616: n=sp[0]+sp[1];
15617: sp++;
15618: NEXT_P1;
15619: sp[0]=n;
15620: NEXT_P2;
15621: @end example
15622: 
15623: There are various schemes that distribute the different operations of
15624: NEXT between these parts in several ways; in general, different schemes
15625: perform best on different processors.  We use a scheme for most
15626: architectures that performs well for most processors of this
15627: architecture; in the future we may switch to benchmarking and chosing
15628: the scheme on installation time.
15629: 
15630: 
15631: @node Direct or Indirect Threaded?, Dynamic Superinstructions, Scheduling, Threading
15632: @subsection Direct or Indirect Threaded?
15633: @cindex threading, direct or indirect?
15634: 
15635: Threaded forth code consists of references to primitives (simple machine
15636: code routines like @code{+}) and to non-primitives (e.g., colon
15637: definitions, variables, constants); for a specific class of
15638: non-primitives (e.g., variables) there is one code routine (e.g.,
15639: @code{dovar}), but each variable needs a separate reference to its data.
15640: 
15641: Traditionally Forth has been implemented as indirect threaded code,
15642: because this allows to use only one cell to reference a non-primitive
15643: (basically you point to the data, and find the code address there).
15644: 
15645: @cindex primitive-centric threaded code
15646: However, threaded code in Gforth (since 0.6.0) uses two cells for
15647: non-primitives, one for the code address, and one for the data address;
15648: the data pointer is an immediate argument for the virtual machine
15649: instruction represented by the code address.  We call this
15650: @emph{primitive-centric} threaded code, because all code addresses point
15651: to simple primitives.  E.g., for a variable, the code address is for
15652: @code{lit} (also used for integer literals like @code{99}).
15653: 
15654: Primitive-centric threaded code allows us to use (faster) direct
15655: threading as dispatch method, completely portably (direct threaded code
15656: in Gforth before 0.6.0 required architecture-specific code).  It also
15657: eliminates the performance problems related to I-cache consistency that
15658: 386 implementations have with direct threaded code, and allows
15659: additional optimizations.
15660: 
15661: @cindex hybrid direct/indirect threaded code
15662: There is a catch, however: the @var{xt} parameter of @code{execute} can
15663: occupy only one cell, so how do we pass non-primitives with their code
15664: @emph{and} data addresses to them?  Our answer is to use indirect
15665: threaded dispatch for @code{execute} and other words that use a
15666: single-cell xt.  So, normal threaded code in colon definitions uses
15667: direct threading, and @code{execute} and similar words, which dispatch
15668: to xts on the data stack, use indirect threaded code.  We call this
15669: @emph{hybrid direct/indirect} threaded code.
15670: 
15671: @cindex engines, gforth vs. gforth-fast vs. gforth-itc
15672: @cindex gforth engine
15673: @cindex gforth-fast engine
15674: The engines @command{gforth} and @command{gforth-fast} use hybrid
15675: direct/indirect threaded code.  This means that with these engines you
15676: cannot use @code{,} to compile an xt.  Instead, you have to use
15677: @code{compile,}.
15678: 
15679: @cindex gforth-itc engine
15680: If you want to compile xts with @code{,}, use @command{gforth-itc}.
15681: This engine uses plain old indirect threaded code.  It still compiles in
15682: a primitive-centric style, so you cannot use @code{compile,} instead of
15683: @code{,} (e.g., for producing tables of xts with @code{] word1 word2
15684: ... [}).  If you want to do that, you have to use @command{gforth-itc}
15685: and execute @code{' , is compile,}.  Your program can check if it is
15686: running on a hybrid direct/indirect threaded engine or a pure indirect
15687: threaded engine with @code{threading-method} (@pxref{Threading Words}).
15688: 
15689: 
15690: @node Dynamic Superinstructions, DOES>, Direct or Indirect Threaded?, Threading
15691: @subsection Dynamic Superinstructions
15692: @cindex Dynamic superinstructions with replication
15693: @cindex Superinstructions
15694: @cindex Replication
15695: 
15696: The engines @command{gforth} and @command{gforth-fast} use another
15697: optimization: Dynamic superinstructions with replication.  As an
15698: example, consider the following colon definition:
15699: 
15700: @example
15701: : squared ( n1 -- n2 )
15702:   dup * ;
15703: @end example
15704: 
15705: Gforth compiles this into the threaded code sequence
15706: 
15707: @example
15708: dup
15709: *
15710: ;s
15711: @end example
15712: 
15713: In normal direct threaded code there is a code address occupying one
15714: cell for each of these primitives.  Each code address points to a
15715: machine code routine, and the interpreter jumps to this machine code in
15716: order to execute the primitive.  The routines for these three
15717: primitives are (in @command{gforth-fast} on the 386):
15718: 
15719: @example
15720: Code dup  
15721: ( $804B950 )  add     esi , # -4  \ $83 $C6 $FC 
15722: ( $804B953 )  add     ebx , # 4  \ $83 $C3 $4 
15723: ( $804B956 )  mov     dword ptr 4 [esi] , ecx  \ $89 $4E $4 
15724: ( $804B959 )  jmp     dword ptr FC [ebx]  \ $FF $63 $FC 
15725: end-code
15726: Code *  
15727: ( $804ACC4 )  mov     eax , dword ptr 4 [esi]  \ $8B $46 $4 
15728: ( $804ACC7 )  add     esi , # 4  \ $83 $C6 $4 
15729: ( $804ACCA )  add     ebx , # 4  \ $83 $C3 $4 
15730: ( $804ACCD )  imul    ecx , eax  \ $F $AF $C8 
15731: ( $804ACD0 )  jmp     dword ptr FC [ebx]  \ $FF $63 $FC 
15732: end-code
15733: Code ;s  
15734: ( $804A693 )  mov     eax , dword ptr [edi]  \ $8B $7 
15735: ( $804A695 )  add     edi , # 4  \ $83 $C7 $4 
15736: ( $804A698 )  lea     ebx , dword ptr 4 [eax]  \ $8D $58 $4 
15737: ( $804A69B )  jmp     dword ptr FC [ebx]  \ $FF $63 $FC 
15738: end-code
15739: @end example
15740: 
15741: With dynamic superinstructions and replication the compiler does not
15742: just lay down the threaded code, but also copies the machine code
15743: fragments, usually without the jump at the end.
15744: 
15745: @example
15746: ( $4057D27D )  add     esi , # -4  \ $83 $C6 $FC 
15747: ( $4057D280 )  add     ebx , # 4  \ $83 $C3 $4 
15748: ( $4057D283 )  mov     dword ptr 4 [esi] , ecx  \ $89 $4E $4 
15749: ( $4057D286 )  mov     eax , dword ptr 4 [esi]  \ $8B $46 $4 
15750: ( $4057D289 )  add     esi , # 4  \ $83 $C6 $4 
15751: ( $4057D28C )  add     ebx , # 4  \ $83 $C3 $4 
15752: ( $4057D28F )  imul    ecx , eax  \ $F $AF $C8 
15753: ( $4057D292 )  mov     eax , dword ptr [edi]  \ $8B $7 
15754: ( $4057D294 )  add     edi , # 4  \ $83 $C7 $4 
15755: ( $4057D297 )  lea     ebx , dword ptr 4 [eax]  \ $8D $58 $4 
15756: ( $4057D29A )  jmp     dword ptr FC [ebx]  \ $FF $63 $FC 
15757: @end example
15758: 
15759: Only when a threaded-code control-flow change happens (e.g., in
15760: @code{;s}), the jump is appended.  This optimization eliminates many of
15761: these jumps and makes the rest much more predictable.  The speedup
15762: depends on the processor and the application; on the Athlon and Pentium
15763: III this optimization typically produces a speedup by a factor of 2.
15764: 
15765: The code addresses in the direct-threaded code are set to point to the
15766: appropriate points in the copied machine code, in this example like
15767: this:
15768: 
15769: @example
15770: primitive  code address
15771:    dup       $4057D27D
15772:    *         $4057D286
15773:    ;s        $4057D292
15774: @end example
15775: 
15776: Thus there can be threaded-code jumps to any place in this piece of
15777: code.  This also simplifies decompilation quite a bit.
15778: 
15779: @cindex --no-dynamic command-line option
15780: @cindex --no-super command-line option
15781: You can disable this optimization with @option{--no-dynamic}.  You can
15782: use the copying without eliminating the jumps (i.e., dynamic
15783: replication, but without superinstructions) with @option{--no-super};
15784: this gives the branch prediction benefit alone; the effect on
15785: performance depends on the CPU; on the Athlon and Pentium III the
15786: speedup is a little less than for dynamic superinstructions with
15787: replication.
15788: 
15789: @cindex patching threaded code
15790: One use of these options is if you want to patch the threaded code.
15791: With superinstructions, many of the dispatch jumps are eliminated, so
15792: patching often has no effect.  These options preserve all the dispatch
15793: jumps.
15794: 
15795: @cindex --dynamic command-line option
15796: On some machines dynamic superinstructions are disabled by default,
15797: because it is unsafe on these machines.  However, if you feel
15798: adventurous, you can enable it with @option{--dynamic}.
15799: 
15800: @node DOES>,  , Dynamic Superinstructions, Threading
15801: @subsection DOES>
15802: @cindex @code{DOES>} implementation
15803: 
15804: @cindex @code{dodoes} routine
15805: @cindex @code{DOES>}-code
15806: One of the most complex parts of a Forth engine is @code{dodoes}, i.e.,
15807: the chunk of code executed by every word defined by a
15808: @code{CREATE}...@code{DOES>} pair; actually with primitive-centric code,
15809: this is only needed if the xt of the word is @code{execute}d. The main
15810: problem here is: How to find the Forth code to be executed, i.e. the
15811: code after the @code{DOES>} (the @code{DOES>}-code)? There are two
15812: solutions:
15813: 
15814: In fig-Forth the code field points directly to the @code{dodoes} and the
15815: @code{DOES>}-code address is stored in the cell after the code address
15816: (i.e. at @code{@i{CFA} cell+}). It may seem that this solution is
15817: illegal in the Forth-79 and all later standards, because in fig-Forth
15818: this address lies in the body (which is illegal in these
15819: standards). However, by making the code field larger for all words this
15820: solution becomes legal again.  We use this approach.  Leaving a cell
15821: unused in most words is a bit wasteful, but on the machines we are
15822: targeting this is hardly a problem.
15823: 
15824: 
15825: @node Primitives, Performance, Threading, Engine
15826: @section Primitives
15827: @cindex primitives, implementation
15828: @cindex virtual machine instructions, implementation
15829: 
15830: @menu
15831: * Automatic Generation::        
15832: * TOS Optimization::            
15833: * Produced code::               
15834: @end menu
15835: 
15836: @node Automatic Generation, TOS Optimization, Primitives, Primitives
15837: @subsection Automatic Generation
15838: @cindex primitives, automatic generation
15839: 
15840: @cindex @file{prims2x.fs}
15841: 
15842: Since the primitives are implemented in a portable language, there is no
15843: longer any need to minimize the number of primitives. On the contrary,
15844: having many primitives has an advantage: speed. In order to reduce the
15845: number of errors in primitives and to make programming them easier, we
15846: provide a tool, the primitive generator (@file{prims2x.fs} aka Vmgen,
15847: @pxref{Top, Vmgen, Introduction, vmgen, Vmgen}), that automatically
15848: generates most (and sometimes all) of the C code for a primitive from
15849: the stack effect notation.  The source for a primitive has the following
15850: form:
15851: 
15852: @cindex primitive source format
15853: @format
15854: @i{Forth-name}  ( @i{stack-effect} )        @i{category}    [@i{pronounc.}]
15855: [@code{""}@i{glossary entry}@code{""}]
15856: @i{C code}
15857: [@code{:}
15858: @i{Forth code}]
15859: @end format
15860: 
15861: The items in brackets are optional. The category and glossary fields
15862: are there for generating the documentation, the Forth code is there
15863: for manual implementations on machines without GNU C. E.g., the source
15864: for the primitive @code{+} is:
15865: @example
15866: +    ( n1 n2 -- n )   core    plus
15867: n = n1+n2;
15868: @end example
15869: 
15870: This looks like a specification, but in fact @code{n = n1+n2} is C
15871: code. Our primitive generation tool extracts a lot of information from
15872: the stack effect notations@footnote{We use a one-stack notation, even
15873: though we have separate data and floating-point stacks; The separate
15874: notation can be generated easily from the unified notation.}: The number
15875: of items popped from and pushed on the stack, their type, and by what
15876: name they are referred to in the C code. It then generates a C code
15877: prelude and postlude for each primitive. The final C code for @code{+}
15878: looks like this:
15879: 
15880: @example
15881: I_plus: /* + ( n1 n2 -- n ) */  /* label, stack effect */
15882: /*  */                          /* documentation */
15883: NAME("+")                       /* debugging output (with -DDEBUG) */
15884: @{
15885: DEF_CA                          /* definition of variable ca (indirect threading) */
15886: Cell n1;                        /* definitions of variables */
15887: Cell n2;
15888: Cell n;
15889: NEXT_P0;                        /* NEXT part 0 */
15890: n1 = (Cell) sp[1];              /* input */
15891: n2 = (Cell) TOS;
15892: sp += 1;                        /* stack adjustment */
15893: @{
15894: n = n1+n2;                      /* C code taken from the source */
15895: @}
15896: NEXT_P1;                        /* NEXT part 1 */
15897: TOS = (Cell)n;                  /* output */
15898: NEXT_P2;                        /* NEXT part 2 */
15899: @}
15900: @end example
15901: 
15902: This looks long and inefficient, but the GNU C compiler optimizes quite
15903: well and produces optimal code for @code{+} on, e.g., the R3000 and the
15904: HP RISC machines: Defining the @code{n}s does not produce any code, and
15905: using them as intermediate storage also adds no cost.
15906: 
15907: There are also other optimizations that are not illustrated by this
15908: example: assignments between simple variables are usually for free (copy
15909: propagation). If one of the stack items is not used by the primitive
15910: (e.g.  in @code{drop}), the compiler eliminates the load from the stack
15911: (dead code elimination). On the other hand, there are some things that
15912: the compiler does not do, therefore they are performed by
15913: @file{prims2x.fs}: The compiler does not optimize code away that stores
15914: a stack item to the place where it just came from (e.g., @code{over}).
15915: 
15916: While programming a primitive is usually easy, there are a few cases
15917: where the programmer has to take the actions of the generator into
15918: account, most notably @code{?dup}, but also words that do not (always)
15919: fall through to @code{NEXT}.
15920: 
15921: For more information
15922: 
15923: @node TOS Optimization, Produced code, Automatic Generation, Primitives
15924: @subsection TOS Optimization
15925: @cindex TOS optimization for primitives
15926: @cindex primitives, keeping the TOS in a register
15927: 
15928: An important optimization for stack machine emulators, e.g., Forth
15929: engines, is keeping  one or more of the top stack items in
15930: registers.  If a word has the stack effect @i{in1}...@i{inx} @code{--}
15931: @i{out1}...@i{outy}, keeping the top @i{n} items in registers
15932: @itemize @bullet
15933: @item
15934: is better than keeping @i{n-1} items, if @i{x>=n} and @i{y>=n},
15935: due to fewer loads from and stores to the stack.
15936: @item is slower than keeping @i{n-1} items, if @i{x<>y} and @i{x<n} and
15937: @i{y<n}, due to additional moves between registers.
15938: @end itemize
15939: 
15940: @cindex -DUSE_TOS
15941: @cindex -DUSE_NO_TOS
15942: In particular, keeping one item in a register is never a disadvantage,
15943: if there are enough registers. Keeping two items in registers is a
15944: disadvantage for frequent words like @code{?branch}, constants,
15945: variables, literals and @code{i}. Therefore our generator only produces
15946: code that keeps zero or one items in registers. The generated C code
15947: covers both cases; the selection between these alternatives is made at
15948: C-compile time using the switch @code{-DUSE_TOS}. @code{TOS} in the C
15949: code for @code{+} is just a simple variable name in the one-item case,
15950: otherwise it is a macro that expands into @code{sp[0]}. Note that the
15951: GNU C compiler tries to keep simple variables like @code{TOS} in
15952: registers, and it usually succeeds, if there are enough registers.
15953: 
15954: @cindex -DUSE_FTOS
15955: @cindex -DUSE_NO_FTOS
15956: The primitive generator performs the TOS optimization for the
15957: floating-point stack, too (@code{-DUSE_FTOS}). For floating-point
15958: operations the benefit of this optimization is even larger:
15959: floating-point operations take quite long on most processors, but can be
15960: performed in parallel with other operations as long as their results are
15961: not used. If the FP-TOS is kept in a register, this works. If
15962: it is kept on the stack, i.e., in memory, the store into memory has to
15963: wait for the result of the floating-point operation, lengthening the
15964: execution time of the primitive considerably.
15965: 
15966: The TOS optimization makes the automatic generation of primitives a
15967: bit more complicated. Just replacing all occurrences of @code{sp[0]} by
15968: @code{TOS} is not sufficient. There are some special cases to
15969: consider:
15970: @itemize @bullet
15971: @item In the case of @code{dup ( w -- w w )} the generator must not
15972: eliminate the store to the original location of the item on the stack,
15973: if the TOS optimization is turned on.
15974: @item Primitives with stack effects of the form @code{--}
15975: @i{out1}...@i{outy} must store the TOS to the stack at the start.
15976: Likewise, primitives with the stack effect @i{in1}...@i{inx} @code{--}
15977: must load the TOS from the stack at the end. But for the null stack
15978: effect @code{--} no stores or loads should be generated.
15979: @end itemize
15980: 
15981: @node Produced code,  , TOS Optimization, Primitives
15982: @subsection Produced code
15983: @cindex primitives, assembly code listing
15984: 
15985: @cindex @file{engine.s}
15986: To see what assembly code is produced for the primitives on your machine
15987: with your compiler and your flag settings, type @code{make engine.s} and
15988: look at the resulting file @file{engine.s}.  Alternatively, you can also
15989: disassemble the code of primitives with @code{see} on some architectures.
15990: 
15991: @node  Performance,  , Primitives, Engine
15992: @section Performance
15993: @cindex performance of some Forth interpreters
15994: @cindex engine performance
15995: @cindex benchmarking Forth systems
15996: @cindex Gforth performance
15997: 
15998: On RISCs the Gforth engine is very close to optimal; i.e., it is usually
15999: impossible to write a significantly faster threaded-code engine.
16000: 
16001: On register-starved machines like the 386 architecture processors
16002: improvements are possible, because @code{gcc} does not utilize the
16003: registers as well as a human, even with explicit register declarations;
16004: e.g., Bernd Beuster wrote a Forth system fragment in assembly language
16005: and hand-tuned it for the 486; this system is 1.19 times faster on the
16006: Sieve benchmark on a 486DX2/66 than Gforth compiled with
16007: @code{gcc-2.6.3} with @code{-DFORCE_REG}.  The situation has improved
16008: with gcc-2.95 and gforth-0.4.9; now the most important virtual machine
16009: registers fit in real registers (and we can even afford to use the TOS
16010: optimization), resulting in a speedup of 1.14 on the sieve over the
16011: earlier results.  And dynamic superinstructions provide another speedup
16012: (but only around a factor 1.2 on the 486).
16013: 
16014: @cindex Win32Forth performance
16015: @cindex NT Forth performance
16016: @cindex eforth performance
16017: @cindex ThisForth performance
16018: @cindex PFE performance
16019: @cindex TILE performance
16020: The potential advantage of assembly language implementations is not
16021: necessarily realized in complete Forth systems: We compared Gforth-0.5.9
16022: (direct threaded, compiled with @code{gcc-2.95.1} and
16023: @code{-DFORCE_REG}) with Win32Forth 1.2093 (newer versions are
16024: reportedly much faster), LMI's NT Forth (Beta, May 1994) and Eforth
16025: (with and without peephole (aka pinhole) optimization of the threaded
16026: code); all these systems were written in assembly language. We also
16027: compared Gforth with three systems written in C: PFE-0.9.14 (compiled
16028: with @code{gcc-2.6.3} with the default configuration for Linux:
16029: @code{-O2 -fomit-frame-pointer -DUSE_REGS -DUNROLL_NEXT}), ThisForth
16030: Beta (compiled with @code{gcc-2.6.3 -O3 -fomit-frame-pointer}; ThisForth
16031: employs peephole optimization of the threaded code) and TILE (compiled
16032: with @code{make opt}). We benchmarked Gforth, PFE, ThisForth and TILE on
16033: a 486DX2/66 under Linux. Kenneth O'Heskin kindly provided the results
16034: for Win32Forth and NT Forth on a 486DX2/66 with similar memory
16035: performance under Windows NT. Marcel Hendrix ported Eforth to Linux,
16036: then extended it to run the benchmarks, added the peephole optimizer,
16037: ran the benchmarks and reported the results.
16038: 
16039: We used four small benchmarks: the ubiquitous Sieve; bubble-sorting and
16040: matrix multiplication come from the Stanford integer benchmarks and have
16041: been translated into Forth by Martin Fraeman; we used the versions
16042: included in the TILE Forth package, but with bigger data set sizes; and
16043: a recursive Fibonacci number computation for benchmarking calling
16044: performance. The following table shows the time taken for the benchmarks
16045: scaled by the time taken by Gforth (in other words, it shows the speedup
16046: factor that Gforth achieved over the other systems).
16047: 
16048: @example
16049: relative       Win32-    NT       eforth       This-      
16050: time     Gforth Forth Forth eforth  +opt   PFE Forth  TILE
16051: sieve      1.00  2.16  1.78   2.16  1.32  2.46  4.96 13.37
16052: bubble     1.00  1.93  2.07   2.18  1.29  2.21        5.70
16053: matmul     1.00  1.92  1.76   1.90  0.96  2.06        5.32
16054: fib        1.00  2.32  2.03   1.86  1.31  2.64  4.55  6.54
16055: @end example
16056: 
16057: You may be quite surprised by the good performance of Gforth when
16058: compared with systems written in assembly language. One important reason
16059: for the disappointing performance of these other systems is probably
16060: that they are not written optimally for the 486 (e.g., they use the
16061: @code{lods} instruction). In addition, Win32Forth uses a comfortable,
16062: but costly method for relocating the Forth image: like @code{cforth}, it
16063: computes the actual addresses at run time, resulting in two address
16064: computations per @code{NEXT} (@pxref{Image File Background}).
16065: 
16066: The speedup of Gforth over PFE, ThisForth and TILE can be easily
16067: explained with the self-imposed restriction of the latter systems to
16068: standard C, which makes efficient threading impossible (however, the
16069: measured implementation of PFE uses a GNU C extension: @pxref{Global Reg
16070: Vars, , Defining Global Register Variables, gcc.info, GNU C Manual}).
16071: Moreover, current C compilers have a hard time optimizing other aspects
16072: of the ThisForth and the TILE source.
16073: 
16074: The performance of Gforth on 386 architecture processors varies widely
16075: with the version of @code{gcc} used. E.g., @code{gcc-2.5.8} failed to
16076: allocate any of the virtual machine registers into real machine
16077: registers by itself and would not work correctly with explicit register
16078: declarations, giving a significantly slower engine (on a 486DX2/66
16079: running the Sieve) than the one measured above.
16080: 
16081: Note that there have been several releases of Win32Forth since the
16082: release presented here, so the results presented above may have little
16083: predictive value for the performance of Win32Forth today (results for
16084: the current release on an i486DX2/66 are welcome).
16085: 
16086: @cindex @file{Benchres}
16087: In
16088: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl&maierhofer95.ps.gz,
16089: Translating Forth to Efficient C}} by M. Anton Ertl and Martin
16090: Maierhofer (presented at EuroForth '95), an indirect threaded version of
16091: Gforth is compared with Win32Forth, NT Forth, PFE, ThisForth, and
16092: several native code systems; that version of Gforth is slower on a 486
16093: than the version used here. You can find a newer version of these
16094: measurements at
16095: @uref{http://www.complang.tuwien.ac.at/forth/performance.html}. You can
16096: find numbers for Gforth on various machines in @file{Benchres}.
16097: 
16098: @c ******************************************************************
16099: @c @node Binding to System Library, Cross Compiler, Engine, Top
16100: @c @chapter Binding to System Library
16101: 
16102: @c ****************************************************************
16103: @node Cross Compiler, Bugs, Engine, Top
16104: @chapter Cross Compiler
16105: @cindex @file{cross.fs}
16106: @cindex cross-compiler
16107: @cindex metacompiler
16108: @cindex target compiler
16109: 
16110: The cross compiler is used to bootstrap a Forth kernel. Since Gforth is
16111: mostly written in Forth, including crucial parts like the outer
16112: interpreter and compiler, it needs compiled Forth code to get
16113: started. The cross compiler allows to create new images for other
16114: architectures, even running under another Forth system.
16115: 
16116: @menu
16117: * Using the Cross Compiler::    
16118: * How the Cross Compiler Works::  
16119: @end menu
16120: 
16121: @node Using the Cross Compiler, How the Cross Compiler Works, Cross Compiler, Cross Compiler
16122: @section Using the Cross Compiler
16123: 
16124: The cross compiler uses a language that resembles Forth, but isn't. The
16125: main difference is that you can execute Forth code after definition,
16126: while you usually can't execute the code compiled by cross, because the
16127: code you are compiling is typically for a different computer than the
16128: one you are compiling on.
16129: 
16130: @c anton: This chapter is somewhat different from waht I would expect: I
16131: @c would expect an explanation of the cross language and how to create an
16132: @c application image with it.  The section explains some aspects of
16133: @c creating a Gforth kernel.
16134: 
16135: The Makefile is already set up to allow you to create kernels for new
16136: architectures with a simple make command. The generic kernels using the
16137: GCC compiled virtual machine are created in the normal build process
16138: with @code{make}. To create a embedded Gforth executable for e.g. the
16139: 8086 processor (running on a DOS machine), type
16140: 
16141: @example
16142: make kernl-8086.fi
16143: @end example
16144: 
16145: This will use the machine description from the @file{arch/8086}
16146: directory to create a new kernel. A machine file may look like that:
16147: 
16148: @example
16149: \ Parameter for target systems                         06oct92py
16150: 
16151:     4 Constant cell             \ cell size in bytes
16152:     2 Constant cell<<           \ cell shift to bytes
16153:     5 Constant cell>bit         \ cell shift to bits
16154:     8 Constant bits/char        \ bits per character
16155:     8 Constant bits/byte        \ bits per byte [default: 8]
16156:     8 Constant float            \ bytes per float
16157:     8 Constant /maxalign        \ maximum alignment in bytes
16158: false Constant bigendian        \ byte order
16159: ( true=big, false=little )
16160: 
16161: include machpc.fs               \ feature list
16162: @end example
16163: 
16164: This part is obligatory for the cross compiler itself, the feature list
16165: is used by the kernel to conditionally compile some features in and out,
16166: depending on whether the target supports these features.
16167: 
16168: There are some optional features, if you define your own primitives,
16169: have an assembler, or need special, nonstandard preparation to make the
16170: boot process work. @code{asm-include} includes an assembler,
16171: @code{prims-include} includes primitives, and @code{>boot} prepares for
16172: booting.
16173: 
16174: @example
16175: : asm-include    ." Include assembler" cr
16176:   s" arch/8086/asm.fs" included ;
16177: 
16178: : prims-include  ." Include primitives" cr
16179:   s" arch/8086/prim.fs" included ;
16180: 
16181: : >boot          ." Prepare booting" cr
16182:   s" ' boot >body into-forth 1+ !" evaluate ;
16183: @end example
16184: 
16185: These words are used as sort of macro during the cross compilation in
16186: the file @file{kernel/main.fs}. Instead of using these macros, it would
16187: be possible --- but more complicated --- to write a new kernel project
16188: file, too.
16189: 
16190: @file{kernel/main.fs} expects the machine description file name on the
16191: stack; the cross compiler itself (@file{cross.fs}) assumes that either
16192: @code{mach-file} leaves a counted string on the stack, or
16193: @code{machine-file} leaves an address, count pair of the filename on the
16194: stack.
16195: 
16196: The feature list is typically controlled using @code{SetValue}, generic
16197: files that are used by several projects can use @code{DefaultValue}
16198: instead. Both functions work like @code{Value}, when the value isn't
16199: defined, but @code{SetValue} works like @code{to} if the value is
16200: defined, and @code{DefaultValue} doesn't set anything, if the value is
16201: defined.
16202: 
16203: @example
16204: \ generic mach file for pc gforth                       03sep97jaw
16205: 
16206: true DefaultValue NIL  \ relocating
16207: 
16208: >ENVIRON
16209: 
16210: true DefaultValue file          \ controls the presence of the
16211:                                 \ file access wordset
16212: true DefaultValue OS            \ flag to indicate a operating system
16213: 
16214: true DefaultValue prims         \ true: primitives are c-code
16215: 
16216: true DefaultValue floating      \ floating point wordset is present
16217: 
16218: true DefaultValue glocals       \ gforth locals are present
16219:                                 \ will be loaded
16220: true DefaultValue dcomps        \ double number comparisons
16221: 
16222: true DefaultValue hash          \ hashing primitives are loaded/present
16223: 
16224: true DefaultValue xconds        \ used together with glocals,
16225:                                 \ special conditionals supporting gforths'
16226:                                 \ local variables
16227: true DefaultValue header        \ save a header information
16228: 
16229: true DefaultValue backtrace     \ enables backtrace code
16230: 
16231: false DefaultValue ec
16232: false DefaultValue crlf
16233: 
16234: cell 2 = [IF] &32 [ELSE] &256 [THEN] KB DefaultValue kernel-size
16235: 
16236: &16 KB          DefaultValue stack-size
16237: &15 KB &512 +   DefaultValue fstack-size
16238: &15 KB          DefaultValue rstack-size
16239: &14 KB &512 +   DefaultValue lstack-size
16240: @end example
16241: 
16242: @node How the Cross Compiler Works,  , Using the Cross Compiler, Cross Compiler
16243: @section How the Cross Compiler Works
16244: 
16245: @node Bugs, Origin, Cross Compiler, Top
16246: @appendix Bugs
16247: @cindex bug reporting
16248: 
16249: Known bugs are described in the file @file{BUGS} in the Gforth distribution.
16250: 
16251: If you find a bug, please submit a bug report through
16252: @uref{https://savannah.gnu.org/bugs/?func=addbug&group=gforth}.
16253: 
16254: @itemize @bullet
16255: @item
16256: A program (or a sequence of keyboard commands) that reproduces the bug.
16257: @item
16258: A description of what you think constitutes the buggy behaviour.
16259: @item
16260: The Gforth version used (it is announced at the start of an
16261: interactive Gforth session).
16262: @item
16263: The machine and operating system (on Unix
16264: systems @code{uname -a} will report this information).
16265: @item
16266: The installation options (you can find the configure options at the
16267: start of @file{config.status}) and configuration (@code{configure}
16268: output or @file{config.cache}).
16269: @item
16270: A complete list of changes (if any) you (or your installer) have made to the
16271: Gforth sources.
16272: @end itemize
16273: 
16274: For a thorough guide on reporting bugs read @ref{Bug Reporting, , How
16275: to Report Bugs, gcc.info, GNU C Manual}.
16276: 
16277: 
16278: @node Origin, Forth-related information, Bugs, Top
16279: @appendix Authors and Ancestors of Gforth
16280: 
16281: @section Authors and Contributors
16282: @cindex authors of Gforth
16283: @cindex contributors to Gforth
16284: 
16285: The Gforth project was started in mid-1992 by Bernd Paysan and Anton
16286: Ertl. The third major author was Jens Wilke.  Neal Crook contributed a
16287: lot to the manual.  Assemblers and disassemblers were contributed by
16288: Andrew McKewan, Christian Pirker, Bernd Thallner, and Michal Revucky.
16289: Lennart Benschop (who was one of Gforth's first users, in mid-1993)
16290: and Stuart Ramsden inspired us with their continuous feedback. Lennart
16291: Benshop contributed @file{glosgen.fs}, while Stuart Ramsden has been
16292: working on automatic support for calling C libraries. Helpful comments
16293: also came from Paul Kleinrubatscher, Christian Pirker, Dirk Zoller,
16294: Marcel Hendrix, John Wavrik, Barrie Stott, Marc de Groot, Jorge
16295: Acerada, Bruce Hoyt, Robert Epprecht, Dennis Ruffer and David
16296: N. Williams. Since the release of Gforth-0.2.1 there were also helpful
16297: comments from many others; thank you all, sorry for not listing you
16298: here (but digging through my mailbox to extract your names is on my
16299: to-do list).
16300: 
16301: Gforth also owes a lot to the authors of the tools we used (GCC, CVS,
16302: and autoconf, among others), and to the creators of the Internet: Gforth
16303: was developed across the Internet, and its authors did not meet
16304: physically for the first 4 years of development.
16305: 
16306: @section Pedigree
16307: @cindex pedigree of Gforth
16308: 
16309: Gforth descends from bigFORTH (1993) and fig-Forth.  Of course, a
16310: significant part of the design of Gforth was prescribed by ANS Forth.
16311: 
16312: Bernd Paysan wrote bigFORTH, a descendent from TurboForth, an unreleased
16313: 32 bit native code version of VolksForth for the Atari ST, written
16314: mostly by Dietrich Weineck.
16315: 
16316: VolksForth was written by Klaus Schleisiek, Bernd Pennemann, Georg
16317: Rehfeld and Dietrich Weineck for the C64 (called UltraForth there) in
16318: the mid-80s and ported to the Atari ST in 1986.  It descends from fig-Forth.
16319: 
16320: @c Henry Laxen and Mike Perry wrote F83 as a model implementation of the
16321: @c Forth-83 standard. !! Pedigree? When?
16322: 
16323: A team led by Bill Ragsdale implemented fig-Forth on many processors in
16324: 1979. Robert Selzer and Bill Ragsdale developed the original
16325: implementation of fig-Forth for the 6502 based on microForth.
16326: 
16327: The principal architect of microForth was Dean Sanderson. microForth was
16328: FORTH, Inc.'s first off-the-shelf product. It was developed in 1976 for
16329: the 1802, and subsequently implemented on the 8080, the 6800 and the
16330: Z80.
16331: 
16332: All earlier Forth systems were custom-made, usually by Charles Moore,
16333: who discovered (as he puts it) Forth during the late 60s. The first full
16334: Forth existed in 1971.
16335: 
16336: A part of the information in this section comes from
16337: @cite{@uref{http://www.forth.com/Content/History/History1.htm,The
16338: Evolution of Forth}} by Elizabeth D. Rather, Donald R. Colburn and
16339: Charles H. Moore, presented at the HOPL-II conference and preprinted
16340: in SIGPLAN Notices 28(3), 1993.  You can find more historical and
16341: genealogical information about Forth there.  For a more general (and
16342: graphical) Forth family tree look see
16343: @cite{@uref{http://www.complang.tuwien.ac.at/forth/family-tree/},
16344: Forth Family Tree and Timeline}.
16345: 
16346: @c ------------------------------------------------------------------
16347: @node Forth-related information, Licenses, Origin, Top
16348: @appendix Other Forth-related information
16349: @cindex Forth-related information
16350: 
16351: @c anton: I threw most of this stuff out, because it can be found through
16352: @c the FAQ and the FAQ is more likely to be up-to-date.
16353: 
16354: @cindex comp.lang.forth
16355: @cindex frequently asked questions
16356: There is an active news group (comp.lang.forth) discussing Forth
16357: (including Gforth) and Forth-related issues. Its
16358: @uref{http://www.complang.tuwien.ac.at/forth/faq/faq-general-2.html,FAQs}
16359: (frequently asked questions and their answers) contains a lot of
16360: information on Forth.  You should read it before posting to
16361: comp.lang.forth.
16362: 
16363: The ANS Forth standard is most usable in its
16364: @uref{http://www.taygeta.com/forth/dpans.html, HTML form}.
16365: 
16366: @c ---------------------------------------------------
16367: @node  Licenses, Word Index, Forth-related information, Top
16368: @appendix Licenses
16369: 
16370: @menu
16371: * GNU Free Documentation License::  License for copying this manual.
16372: * Copying::                     GPL (for copying this software).
16373: @end menu
16374: 
16375: @node GNU Free Documentation License, Copying, Licenses, Licenses
16376: @appendixsec GNU Free Documentation License
16377: @include fdl.texi
16378: 
16379: @node Copying,  , GNU Free Documentation License, Licenses
16380: @appendixsec GNU GENERAL PUBLIC LICENSE
16381: @include gpl.texi
16382: 
16383: 
16384: 
16385: @c ------------------------------------------------------------------
16386: @node Word Index, Concept Index, Licenses, Top
16387: @unnumbered Word Index
16388: 
16389: This index is a list of Forth words that have ``glossary'' entries
16390: within this manual. Each word is listed with its stack effect and
16391: wordset.
16392: 
16393: @printindex fn
16394: 
16395: @c anton: the name index seems superfluous given the word and concept indices.
16396: 
16397: @c @node Name Index, Concept Index, Word Index, Top
16398: @c @unnumbered Name Index
16399: 
16400: @c This index is a list of Forth words that have ``glossary'' entries
16401: @c within this manual.
16402: 
16403: @c @printindex ky
16404: 
16405: @c -------------------------------------------------------
16406: @node Concept Index,  , Word Index, Top
16407: @unnumbered Concept and Word Index
16408: 
16409: Not all entries listed in this index are present verbatim in the
16410: text. This index also duplicates, in abbreviated form, all of the words
16411: listed in the Word Index (only the names are listed for the words here).
16412: 
16413: @printindex cp
16414: 
16415: @bye
16416: 
16417: 
16418: 

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